forked from chilipeppr/serial-port-json-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcayenn.go
More file actions
463 lines (380 loc) · 11.4 KB
/
Copy pathcayenn.go
File metadata and controls
463 lines (380 loc) · 11.4 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package main
import (
"bufio"
"encoding/json"
"log"
"net"
"regexp"
"strings"
)
type Addr struct {
IP string
Port int
Network string
TcpOrUdp string
}
type DataAnnounce struct {
Addr Addr
Announce string
Widget string
JsonTag string
DeviceId string
}
type ClientAnnounceMsg struct {
Announce string
Widget string
MyDeviceId string
JsonTag string
}
// This is the UDP packet sent back from the server (us)
// to the client saying "hey we got your announce, this is
// who we are and our IP in case you want to create a TCP
// socket conn back to us for reliable conn"
type ServerAnnounceResponseMsg struct {
Announce string
Widget string
YourDeviceId string
ServerIp string
JsonTag string
}
func udpServerRun() {
/* Lets prepare a address at any address at port 8988*/
ServerAddr, err := net.ResolveUDPAddr("udp", ":8988")
if err != nil {
log.Println("Error: ", err)
return
}
/* Now listen at selected port */
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil {
log.Println("Error: ", err)
return
}
defer ServerConn.Close()
log.Println("UDP server running on port 8988 to listen for incoming device announcements and unguaranteed data.")
buf := make([]byte, 1024)
for {
n, addr, err := ServerConn.ReadFromUDP(buf)
if err != nil {
log.Println("Error: ", err)
} else {
log.Println("Received ", string(buf[0:n]), " from ", addr)
m := DataAnnounce{}
m.Addr.IP = addr.IP.String()
m.Addr.Network = addr.Network()
m.Addr.Port = addr.Port
m.Addr.TcpOrUdp = "udp"
// if the udp message was from us, i.e. we sent out a broadcast so
// we got a copy back, just ignore
MyIp := ServerConn.LocalAddr().String()
// drop port, cuz we don't care about it. we have known ports
re := regexp.MustCompile(":\\d+$")
MyIp = re.ReplaceAllString(MyIp, "")
externIP, _ := externalIP()
// print("Checking if from me ", addr.IP.String(), "<>", externIP)
if addr.IP.String() == externIP {
log.Println("Got msg back from ourself, so dropping.")
continue
}
var am ClientAnnounceMsg
err := json.Unmarshal([]byte(buf[0:n]), &am)
if err != nil {
log.Println("Err unmarshalling UDP inbound message from device. err:", err)
continue
}
m.Announce = am.Announce
m.Widget = am.Widget
m.JsonTag = am.JsonTag
m.DeviceId = am.MyDeviceId
// send message to websocket clients, i.e. ChiliPeppr
bm, err := json.Marshal(m)
if err == nil {
h.broadcastSys <- bm
}
// send back our own AnnounceRecv
// but only if the incoming message was an "Announce":"i-am-a-client"
//re2 := regexp.MustCompile('"Announce":"i-am-a-client"')
//if re2.MatchString()
if am.Announce == "i-am-a-client" {
var arm ServerAnnounceResponseMsg
arm.Announce = "i-am-your-server"
arm.YourDeviceId = am.MyDeviceId
arm.ServerIp = ServerConn.LocalAddr().String()
arm.Widget = am.Widget
//arm.JsonTag = am.JsonTag
// we send back reverse acknowledgement on both UDP and TCP
// but long term we should likely just send a TCP response back
// because Cayenn devices will likely long term need to store what
// server they are interacting with, however, the debate is i have
// Cayenn devices mostly just sending back broadcast messages to entire
// network and it's working well
sendUdp(arm, m.Addr.IP, ":8988")
go sendTcp(arm, m.Addr.IP, ":8988")
// cayennSendTcpMsg(m.Addr.IP, ":8988", bmsg)
// go makeTcpConnBackToDevice(m.Addr.IP)
} else {
log.Println("The incoming msg was not an i-am-client announce so not sending back response")
}
}
}
}
// Called from hub.go as entry point
func cayennSendUdp(s string) {
// we get here if a client sent into spjs the command
// cayenn-sendudp 192.168.1.12 any-msg-to-end-of-line
args := strings.SplitN(s, " ", 3)
// make sure we got 3 args
if len(args) < 3 {
spErr("Error parsing cayenn-sendudp. Returning. msg:" + s)
return
}
ip := args[1]
if len(ip) < 7 {
spErr("Error parsing IP address for cayenn-sendudp. Returning. msg:" + s)
return
}
msg := args[2]
log.Println("cayenn-sendudp ip:", ip, "msg:", msg)
cayennSendUdpMsg(ip, ":8988", msg)
}
func cayennSendUdpMsg(ipaddr string, port string, msg string) {
// This method sends a message to a specific IP address / port over UDP
var service = ipaddr + port
conn, err := net.Dial("udp", service)
if err != nil {
log.Println("Could not resolve udp address or connect to it on ", service)
log.Println(err)
return
}
defer conn.Close()
log.Println("Connected to udp server at ", service)
n, err := conn.Write([]byte(msg))
if err != nil {
log.Println("error writing data to server", service)
log.Println(err)
return
}
if n > 0 {
log.Println("Wrote ", n, " bytes to server at ", service)
} else {
log.Println("Wrote 0 bytes to server. Huh?")
}
}
// This method is similar to cayennSendUdp but it takes in a struct and json
// serializes it
func sendUdp(sarm ServerAnnounceResponseMsg, ipaddr string, port string) {
var service = ipaddr + port
conn, err := net.Dial("udp", service)
if err != nil {
log.Println("Could not resolve udp address or connect to it on ", service)
log.Println(err)
return
}
defer conn.Close()
log.Println("Connected to udp server at ", service)
// add our server ip to packet because esp8266 and Lua make it near impossible
// to determine the ip the udp packet came from, so we'll include it in the payload
sarm.ServerIp = conn.LocalAddr().String()
// drop port, cuz we don't care about it. we have known ports
re := regexp.MustCompile(":\\d+$")
sarm.ServerIp = re.ReplaceAllString(sarm.ServerIp, "")
bmsg, err := json.Marshal(sarm)
if err != nil {
log.Println("Error marshalling json for sarm:", sarm, "err:", err)
return
}
n, err := conn.Write([]byte(bmsg))
if err != nil {
log.Println("error writing data to server", service)
log.Println(err)
return
}
if n > 0 {
log.Println("Wrote ", n, " bytes to server at ", service)
} else {
log.Println("Wrote 0 bytes to server. Huh?")
}
}
func makeTcpConnBackToDevice(ipaddr string) {
var ip = ipaddr + ":8988"
conn, err := net.Dial("tcp", ip)
log.Println("Making TCP connection to:", ip)
if err != nil {
log.Println("Error trying to make TCP conn. err:", err)
return
}
defer func() {
log.Println("Closing TCP conn to:", ip)
conn.Close()
}()
n, err := conn.Write([]byte("hello"))
if err != nil {
log.Println("Write to server failed:", err.Error())
return
}
log.Println("Wrote n:", n, "bytes to server")
connbuf := bufio.NewReader(conn)
for {
str, err := connbuf.ReadString('\n')
if len(str) > 0 {
log.Println("Got msg on TCP client from ip:", ip)
log.Println(str)
h.broadcastSys <- []byte(str)
}
if err != nil {
break
}
}
}
// Called from hub.go as entry point
func cayennSendTcp(s string) {
// we get here if a client sent into spjs the command
// cayenn-sendtcp 192.168.1.12 any-msg-to-end-of-line
args := strings.SplitN(s, " ", 3)
// make sure we got 3 args
if len(args) < 3 {
spErr("Error parsing cayenn-sendtcp. Returning. msg:" + s)
return
}
ip := args[1]
if len(ip) < 7 {
spErr("Error parsing IP address for cayenn-sendtcp. Returning. msg:" + s)
return
}
msg := args[2]
log.Println("cayenn-sendtcp ip:", ip, "msg:", msg)
cayennSendTcpMsg(ip, ":8988", msg)
}
// For now just connect, send, and then disconnect. This keeps stuff simple
// but it does create overhead. However, it is similar to RESTful web calls
func cayennSendTcpMsg(ipaddr string, port string, msg string) {
// This method sends a message to a specific IP address / port over TCP
var service = ipaddr + port
conn, err := net.Dial("tcp", service)
log.Println("Making TCP connection to:", service)
if err != nil {
log.Println("Error trying to make TCP conn. err:", err)
return
}
defer func() {
log.Println("Closing TCP conn to:", service)
conn.Close()
}()
n, err := conn.Write([]byte(msg))
if err != nil {
log.Println("Write to server failed:", err.Error())
return
}
log.Println("Wrote n:", n, "bytes to server")
// close connection immediately
conn.Close()
// connbuf := bufio.NewReader(conn)
// for {
// str, err := connbuf.ReadString('\n')
// if len(str) > 0 {
// log.Println("Got msg on TCP client from ip:", service)
// log.Println(str)
// h.broadcastSys <- []byte(str)
// }
// if err != nil {
// break
// }
// }
}
// This method is similar to cayennSendTcp but it takes in a struct and json
// serializes it
func sendTcp(sarm ServerAnnounceResponseMsg, ipaddr string, port string) {
// This method sends a message to a specific IP address / port over TCP
var service = ipaddr + port
conn, err := net.Dial("tcp", service)
log.Println("Making TCP connection to:", service)
if err != nil {
log.Println("Error trying to make TCP conn. err:", err)
return
}
defer func() {
log.Println("Closing TCP conn to:", service)
conn.Close()
}()
// add our server ip to packet because esp8266 and Lua make it near impossible
// to determine the ip the udp packet came from, so we'll include it in the payload
sarm.ServerIp = conn.LocalAddr().String()
// drop port, cuz we don't care about it. we have known ports
re := regexp.MustCompile(":\\d+$")
sarm.ServerIp = re.ReplaceAllString(sarm.ServerIp, "")
bmsg, err := json.Marshal(sarm)
if err != nil {
log.Println("Error marshalling json for sarm:", sarm, "err:", err)
return
}
n, err := conn.Write(bmsg)
if err != nil {
log.Println("Write to server failed:", err.Error())
return
}
log.Println("Wrote n:", n, "bytes to server")
// close connection immediately
conn.Close()
}
func tcpServerRun() {
ServerAddr, err := net.ResolveTCPAddr("tcp", ":8988")
if err != nil {
log.Println("Error: ", err)
return
}
// Listen for incoming connections on all/any IP addresses
// on port 8988
l, err := net.ListenTCP("tcp", ServerAddr)
if err != nil {
log.Println("Error listening:", err.Error())
}
// Close the listener when the application closes.
defer l.Close()
log.Println("TCP server running on port 8988 to listen for incoming guaranteed device messages.")
for {
// Listen for an incoming connection.
ServerConn, err := l.Accept()
if err != nil {
log.Println("Error accepting: ", err.Error())
}
// Handle connections in a new goroutine.
go handleTcpRequest(ServerConn)
}
}
// Handles incoming requests.
func handleTcpRequest(conn net.Conn) {
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
reqLen, err := conn.Read(buf)
if err != nil {
log.Println("Error reading incoming TCP data:", err.Error(), reqLen)
return
}
// Send a response back to person contacting us.
// conn.Write([]byte("Message received."))
addr := conn.RemoteAddr()
log.Println("TCP Received ", string(buf[0:reqLen]), " from ", addr)
m := DataAnnounce{}
m.Addr.IP = addr.String()
m.Addr.Network = addr.Network()
// m.Addr.Port = addr.Port
m.Addr.TcpOrUdp = "tcp"
var am ClientAnnounceMsg
err2 := json.Unmarshal([]byte(buf[0:reqLen]), &am)
if err2 != nil {
log.Println("Err unmarshalling TCP inbound message from device. err:", err2)
return
}
m.Announce = am.Announce
m.Widget = am.Widget
m.JsonTag = am.JsonTag
m.DeviceId = am.MyDeviceId
// send message to websocket clients, i.e. ChiliPeppr
bm, err := json.Marshal(m)
if err == nil {
h.broadcastSys <- bm
}
// Close the connection when you're done with it.
conn.Close()
}