Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
302 lines (254 loc) · 6.87 KB
/
Copy pathmain.go
File metadata and controls
302 lines (254 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main
import (
"flag"
"net"
"io"
"strings"
"log"
"time"
sc "strconv"
"os"
"encoding/json"
)
// Valid contents of a given container
var contTypes []string = []string{"corn", "salt", "soybeans", "grain", "ducks"}
// Global variables
var (
port string // port to listen on
width uint64 // width to read from connection
silo Silo // our silo
tractor Tractor // our tractor
combine Combine // our combine
mode string // "silo", "tractor", or "combine"
busy bool = false // lock for busy signal
auth bool // auth mode y/n
pin int // pin
status string // current status
reqChan chan string // status request channel, unbuffered
statChan chan string // status channel, unbuffered
dumpChan chan map[string]string // dump trigger channel
stopChan chan bool // Stops the spin
)
var path = os.Getenv("HOME") + "/farmstate.json"
// Spins for a period of time in minutes
func spin(n int, during, after string) {
for busy {
time.Sleep(15 * time.Millisecond)
}
end := time.Now().Add(time.Duration(n) * time.Minute)
// Might be bad
busy = true
reqChan <- during
for run := true; run; {
if(time.Now().After(end)) {
break
}
select {
case <- stopChan:
run = false
default:
time.Sleep(5 * time.Millisecond)
}
}
reqChan <- after
busy = false
}
// Handshakes for current status
func stat() string {
reqChan <- ""
return <-statChan
}
// Manages status get/set
func statuser() {
for {
select {
case req := <- reqChan:
switch req {
case "":
// Ordinary request
statChan <- status
default:
status = req
}
default:
time.Sleep(5 * time.Millisecond)
}
}
}
// Manages state writing to file
func dumper() {
for {
select {
case cfg := <- dumpChan:
f, err := os.Create(path)
if err != nil {
log.Println("Error: unable to create file --", err)
break
}
enc := json.NewEncoder(f)
enc.Encode(cfg)
default:
time.Sleep(5 * time.Millisecond)
}
}
}
// Handles incoming connections
func handler(conn net.Conn) {
connected := true
msgChan := make(chan string)
defer conn.Close()
defer log.Println("Handler ended:", conn.RemoteAddr())
// Handles basic writing to interface
write := func(msg string) {
_, err := conn.Write([]byte(msg + "\n"))
if err != nil {
log.Println("Failed to write, disconnecting: ", err)
conn.Close()
connected = false
}
}
// Handles basic reading to interface
read := func(buf []byte) {
_, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
// Connection ended
conn.Close()
connected = false
} else {
log.Println("Unexpected disconnect: ", err)
conn.Close()
connected = false
}
}
}
// "Do it with flare" Clockwerk
write(banner)
// PIN Authentication
if auth {
// Verify auth
buf := make([]byte, width)
write("Enter PIN: ")
read(buf)
pinstr := strings.Fields(string(buf))[0]
p, err := sc.Atoi(pinstr)
// Debug flag stuff
if pinstr == "F" {
switch mode {
case "silo":
write(silo.flag)
case "tractor":
write(tractor.flag)
case "combine":
// TODO
;
}
}
if !(p == 0 || p < 0 || p == pin) || err != nil {
write("Access denied.")
conn.Close()
return
} else {
write("Access granted.\n")
}
}
switch mode {
case "silo":
go silo.DoCmd(msgChan)
case "tractor":
go tractor.DoCmd(msgChan)
case "combine":
write("Vendor must add Combine support for 2.0 control schema")
os.Exit(1337)
}
// Empty strings are indicative of desiring teardown
for connected {
// Errors can be dealt with later
conn.Write([]byte("> "))
buf := make([]byte, width)
n, err := conn.Read(buf)
if err != nil || n <= 0 {
close(msgChan)
break
}
msgChan <- string(buf)
msg, more := <- msgChan
// If quit or similar command to end connection
if !more {
connected = false
msg = "ok."
}
write(msg)
}
if _, more := <- msgChan; more {
close(msgChan)
}
}
// Simulates a smart device, listens on tcp/1337
func main() {
flag.StringVar(&port, "p", ":1337", "Port to listen on")
flag.Uint64Var(&width, "w", 1024, "Max width of communications")
flag.StringVar(&mode, "m", "combine", "Which mode to start in: tractor, silo, combine")
flag.IntVar(&pin, "c", 1234, "Pin for auth (if any)")
flag.BoolVar(&auth, "a", true, "Auth t/f")
flag.Parse()
if mode != "silo" && mode != "tractor" && mode != "combine" {
log.Fatal("Error: mode must be one of tractor, silo, or combine.")
}
// Set up status management
status = "idle"
reqChan = make(chan string)
statChan = make(chan string)
stopChan = make(chan bool)
go statuser()
// Load config file
var cfg map[string]string
f, err := os.Open(path)
if err != nil {
log.Println("Warning: failed to open config file --", err.Error())
} else {
dec := json.NewDecoder(f)
err := dec.Decode(&cfg)
if err != nil {
log.Println("Warning: config file decoding failed --", err.Error())
}
}
dumpChan = make(chan map[string]string, 5)
go dumper()
switch mode {
case "silo":
silo = NewSilo()
silo.LoadCfg(cfg)
case "tractor":
tractor = NewTractor()
tractor.LoadCfg(cfg)
case "combine":
combine = NewCombine()
// TODO -- loadcfg
default:
log.Fatal("Error: Invalid mode --", mode)
}
// Start listener
ln, err := net.Listen("tcp", port)
efatal(err, "couldn't start listener")
for {
conn, err := ln.Accept()
efatal(err, "could not accept connection")
go handler(conn)
}
}
// Style: ANSI Shadow
var banner string = `
TRAC CORP INDUSTRIES UNIFIED OPERATING SYSTEM
GEN 2.3.4
COPYRIGHT 2075-2077 TRAC CORP INDUSTRIES
───────────────────────────────────────────────────────────────────────────
DIAL SUCCEEDED
***************************************************************************
████████╗██████╗ █████╗ ██████╗ ██████╗ ██████╗ ██████╗ ██████╗
╚══██╔══╝██╔══██╗██╔══██╗██╔════╝ ██╔════╝██╔═══██╗██╔══██╗██╔══██╗
██║ ██████╔╝███████║██║ ██║ ██║ ██║██████╔╝██████╔╝
██║ ██╔══██╗██╔══██║██║ ██║ ██║ ██║██╔══██╗██╔═══╝
██║ ██║ ██║██║ ██║╚██████╗ ╚██████╗╚██████╔╝██║ ██║██║
╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝
`