main.go (2508B)
1 // Example: States and branching to check a PIN for access. 2 package main 3 4 import ( 5 "bytes" 6 "context" 7 "flag" 8 "fmt" 9 "os" 10 "path" 11 12 testdataloader "github.com/peteole/testdata-loader" 13 14 "git.defalsify.org/vise.git/cache" 15 "git.defalsify.org/vise.git/engine" 16 "git.defalsify.org/vise.git/resource" 17 "git.defalsify.org/vise.git/state" 18 "git.defalsify.org/vise.git/logging" 19 fsdb "git.defalsify.org/vise.git/db/fs" 20 ) 21 22 const ( 23 USERFLAG_VALIDPIN = iota + state.FLAG_USERSTART 24 USERFLAG_QUERYPIN 25 ) 26 27 var ( 28 logg = logging.NewVanilla() 29 baseDir = testdataloader.GetBasePath() 30 scriptDir = path.Join(baseDir, "examples", "pincheck") 31 pin = []byte("1234") 32 ) 33 34 type pinResource struct{ 35 resource.Resource 36 st *state.State 37 } 38 39 func newPinResource(resource resource.Resource, state *state.State) *pinResource { 40 return &pinResource{ 41 resource, 42 state, 43 } 44 } 45 46 func(rs *pinResource) pinCheck(ctx context.Context, sym string, input []byte) (resource.Result, error) { 47 var r resource.Result 48 49 if rs.st.MatchFlag(USERFLAG_QUERYPIN, false) { 50 r.Content = "Please enter PIN" 51 r.FlagReset = []uint32{USERFLAG_VALIDPIN} 52 r.FlagSet = []uint32{USERFLAG_QUERYPIN} 53 return r, nil 54 } 55 if bytes.Equal(input, pin) { 56 r.FlagSet = []uint32{USERFLAG_VALIDPIN} 57 logg.DebugCtxf(ctx, "pin match", "state", rs.st, "rs", r.FlagSet, "rr", r.FlagReset) 58 } else { 59 r.Content = "Wrong PIN please try again" 60 } 61 return r, nil 62 } 63 64 func(rs *pinResource) pinClear(ctx context.Context, sym string, input []byte) (resource.Result, error) { 65 var r resource.Result 66 r.FlagReset = []uint32{USERFLAG_VALIDPIN, USERFLAG_QUERYPIN} 67 return r, nil 68 } 69 70 func main() { 71 root := "root" 72 flag.Parse() 73 fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, scriptDir) 74 75 ctx := context.Background() 76 st := state.NewState(3) 77 st.UseDebug() 78 state.FlagDebugger.Register(USERFLAG_VALIDPIN, "VALIDPIN") 79 state.FlagDebugger.Register(USERFLAG_QUERYPIN, "QUERYPIN") 80 store := fsdb.NewFsDb() 81 err := store.Connect(ctx, scriptDir) 82 if err != nil { 83 panic(err) 84 } 85 rsf := resource.NewDbResource(store) 86 rs := newPinResource(rsf, st) 87 rsf.AddLocalFunc("pincheck", rs.pinCheck) 88 rsf.AddLocalFunc("pinclear", rs.pinClear) 89 ca := cache.NewCache() 90 cfg := engine.Config{ 91 Root: "root", 92 StateDebug: true, 93 } 94 en := engine.NewEngine(cfg, rs) 95 en = en.WithState(st) 96 en = en.WithMemory(ca) 97 98 err = engine.Loop(ctx, en, os.Stdin, os.Stdout, nil) 99 if err != nil { 100 fmt.Fprintf(os.Stderr, "loop exited with error: %v\n", err) 101 os.Exit(1) 102 } 103 }