Skip to content

Commit 14ddd43

Browse files
committedApr 2, 2025·
renamed h into hub
1 parent 47213d1 commit 14ddd43

File tree

3 files changed

+138
-138
lines changed

3 files changed

+138
-138
lines changed
 

‎conn.go

+13-13
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ type Upload struct {
8181

8282
var uploadStatusStr = "ProgrammerStatus"
8383

84-
func uploadHandler(h *hub, pubKey *rsa.PublicKey, tools *tools.Tools) func(*gin.Context) {
84+
func uploadHandler(hub *hub, pubKey *rsa.PublicKey, tools *tools.Tools) func(*gin.Context) {
8585
return func(c *gin.Context) {
8686
data := new(Upload)
8787
if err := c.BindJSON(data); err != nil {
@@ -165,7 +165,7 @@ func uploadHandler(h *hub, pubKey *rsa.PublicKey, tools *tools.Tools) func(*gin.
165165
// Resolve commandline
166166
commandline, err := upload.PartiallyResolve(data.Board, filePath, tmpdir, data.Commandline, data.Extra, tools)
167167
if err != nil {
168-
send(h, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
168+
send(hub, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
169169
return
170170
}
171171

@@ -175,16 +175,16 @@ func uploadHandler(h *hub, pubKey *rsa.PublicKey, tools *tools.Tools) func(*gin.
175175
if data.Extra.Network {
176176
err = errors.New("network upload is not supported anymore, pease use OTA instead")
177177
} else {
178-
send(h, map[string]string{uploadStatusStr: "Starting", "Cmd": "Serial"})
178+
send(hub, map[string]string{uploadStatusStr: "Starting", "Cmd": "Serial"})
179179
err = upload.Serial(data.Port, commandline, data.Extra, l)
180180
}
181181

182182
// Handle result
183183
if err != nil {
184-
send(h, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
184+
send(hub, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
185185
return
186186
}
187-
send(h, map[string]string{uploadStatusStr: "Done", "Flash": "Ok"})
187+
send(hub, map[string]string{uploadStatusStr: "Done", "Flash": "Ok"})
188188
}()
189189

190190
c.String(http.StatusAccepted, "")
@@ -194,7 +194,7 @@ func uploadHandler(h *hub, pubKey *rsa.PublicKey, tools *tools.Tools) func(*gin.
194194
// PLogger sends the info from the upload to the websocket
195195
type PLogger struct {
196196
Verbose bool
197-
h *hub
197+
hub *hub
198198
}
199199

200200
// Debug only sends messages if verbose is true (always true for now)
@@ -208,29 +208,29 @@ func (l PLogger) Debug(args ...interface{}) {
208208
func (l PLogger) Info(args ...interface{}) {
209209
output := fmt.Sprint(args...)
210210
log.Println(output)
211-
send(l.h, map[string]string{uploadStatusStr: "Busy", "Msg": output})
211+
send(l.hub, map[string]string{uploadStatusStr: "Busy", "Msg": output})
212212
}
213213

214-
func send(h *hub, args map[string]string) {
214+
func send(hub *hub, args map[string]string) {
215215
mapB, _ := json.Marshal(args)
216-
h.broadcastSys <- mapB
216+
hub.broadcastSys <- mapB
217217
}
218218

219-
func wsHandler(h *hub) *WsServer {
219+
func wsHandler(hub *hub) *WsServer {
220220
server, err := socketio.NewServer(nil)
221221
if err != nil {
222222
log.Fatal(err)
223223
}
224224

225225
server.On("connection", func(so socketio.Socket) {
226226
c := &connection{send: make(chan []byte, 256*10), ws: so}
227-
h.register <- c
227+
hub.register <- c
228228
so.On("command", func(message string) {
229-
h.broadcast <- []byte(message)
229+
hub.broadcast <- []byte(message)
230230
})
231231

232232
so.On("disconnection", func() {
233-
h.unregister <- c
233+
hub.unregister <- c
234234
})
235235
go c.writer()
236236
})

‎hub.go

+123-123
Original file line numberDiff line numberDiff line change
@@ -110,51 +110,51 @@ const commands = `{
110110
]
111111
}`
112112

113-
func (h *hub) unregisterConnection(c *connection) {
114-
if _, contains := h.connections[c]; !contains {
113+
func (hub *hub) unregisterConnection(c *connection) {
114+
if _, contains := hub.connections[c]; !contains {
115115
return
116116
}
117-
delete(h.connections, c)
117+
delete(hub.connections, c)
118118
close(c.send)
119119
}
120120

121-
func (h *hub) sendToRegisteredConnections(data []byte) {
122-
for c := range h.connections {
121+
func (hub *hub) sendToRegisteredConnections(data []byte) {
122+
for c := range hub.connections {
123123
select {
124124
case c.send <- data:
125125
//log.Print("did broadcast to ")
126126
//log.Print(c.ws.RemoteAddr())
127127
//c.send <- []byte("hello world")
128128
default:
129-
h.unregisterConnection(c)
129+
hub.unregisterConnection(c)
130130
}
131131
}
132132
}
133133

134-
func (h *hub) run() {
134+
func (hub *hub) run() {
135135
for {
136136
select {
137-
case c := <-h.register:
138-
h.connections[c] = true
137+
case c := <-hub.register:
138+
hub.connections[c] = true
139139
// send supported commands
140140
c.send <- []byte(fmt.Sprintf(`{"Version" : "%s"} `, version))
141141
c.send <- []byte(html.EscapeString(commands))
142142
c.send <- []byte(fmt.Sprintf(`{"Hostname" : "%s"} `, *hostname))
143143
c.send <- []byte(fmt.Sprintf(`{"OS" : "%s"} `, runtime.GOOS))
144-
case c := <-h.unregister:
145-
h.unregisterConnection(c)
146-
case m := <-h.broadcast:
144+
case c := <-hub.unregister:
145+
hub.unregisterConnection(c)
146+
case m := <-hub.broadcast:
147147
if len(m) > 0 {
148-
h.checkCmd(m)
149-
h.sendToRegisteredConnections(m)
148+
hub.checkCmd(m)
149+
hub.sendToRegisteredConnections(m)
150150
}
151-
case m := <-h.broadcastSys:
152-
h.sendToRegisteredConnections(m)
151+
case m := <-hub.broadcastSys:
152+
hub.sendToRegisteredConnections(m)
153153
}
154154
}
155155
}
156156

157-
func (h *hub) checkCmd(m []byte) {
157+
func (hub *hub) checkCmd(m []byte) {
158158
//log.Print("Inside checkCmd")
159159
s := string(m[:])
160160

@@ -169,18 +169,18 @@ func (h *hub) checkCmd(m []byte) {
169169

170170
args := strings.Split(s, " ")
171171
if len(args) < 3 {
172-
go h.spErr("You did not specify a port and baud rate in your open cmd")
172+
go hub.spErr("You did not specify a port and baud rate in your open cmd")
173173
return
174174
}
175175
if len(args[1]) < 1 {
176-
go h.spErr("You did not specify a serial port")
176+
go hub.spErr("You did not specify a serial port")
177177
return
178178
}
179179

180180
baudStr := strings.Replace(args[2], "\n", "", -1)
181181
baud, err := strconv.Atoi(baudStr)
182182
if err != nil {
183-
go h.spErr("Problem converting baud rate " + args[2])
183+
go hub.spErr("Problem converting baud rate " + args[2])
184184
return
185185
}
186186
// pass in buffer type now as string. if user does not
@@ -191,30 +191,30 @@ func (h *hub) checkCmd(m []byte) {
191191
buftype := strings.Replace(args[3], "\n", "", -1)
192192
bufferAlgorithm = buftype
193193
}
194-
go h.spHandlerOpen(args[1], baud, bufferAlgorithm)
194+
go hub.spHandlerOpen(args[1], baud, bufferAlgorithm)
195195

196196
} else if strings.HasPrefix(sl, "close") {
197197

198198
args := strings.Split(s, " ")
199199
if len(args) > 1 {
200-
go h.spClose(args[1])
200+
go hub.spClose(args[1])
201201
} else {
202-
go h.spErr("You did not specify a port to close")
202+
go hub.spErr("You did not specify a port to close")
203203
}
204204

205205
} else if strings.HasPrefix(sl, "killupload") {
206206
// kill the running process (assumes singleton for now)
207207
go func() {
208208
upload.Kill()
209-
h.broadcastSys <- []byte("{\"uploadStatus\": \"Killed\"}")
209+
hub.broadcastSys <- []byte("{\"uploadStatus\": \"Killed\"}")
210210
log.Println("{\"uploadStatus\": \"Killed\"}")
211211
}()
212212

213213
} else if strings.HasPrefix(sl, "send") {
214214
// will catch send and sendnobuf and sendraw
215-
go h.spWrite(s)
215+
go hub.spWrite(s)
216216
} else if strings.HasPrefix(sl, "list") {
217-
go h.serialPortList.List()
217+
go hub.serialPortList.List()
218218
} else if strings.HasPrefix(sl, "downloadtool") {
219219
go func() {
220220
args := strings.Split(s, " ")
@@ -225,7 +225,7 @@ func (h *hub) checkCmd(m []byte) {
225225
if len(args) <= 1 {
226226
mapD := map[string]string{"DownloadStatus": "Error", "Msg": "Not enough arguments"}
227227
mapB, _ := json.Marshal(mapD)
228-
h.broadcastSys <- mapB
228+
hub.broadcastSys <- mapB
229229
return
230230
}
231231
if len(args) > 1 {
@@ -248,41 +248,41 @@ func (h *hub) checkCmd(m []byte) {
248248
reportPendingProgress := func(msg string) {
249249
mapD := map[string]string{"DownloadStatus": "Pending", "Msg": msg}
250250
mapB, _ := json.Marshal(mapD)
251-
h.broadcastSys <- mapB
251+
hub.broadcastSys <- mapB
252252
}
253-
err := h.tools.Download(pack, tool, toolVersion, behaviour, reportPendingProgress)
253+
err := hub.tools.Download(pack, tool, toolVersion, behaviour, reportPendingProgress)
254254
if err != nil {
255255
mapD := map[string]string{"DownloadStatus": "Error", "Msg": err.Error()}
256256
mapB, _ := json.Marshal(mapD)
257-
h.broadcastSys <- mapB
257+
hub.broadcastSys <- mapB
258258
} else {
259259
mapD := map[string]string{"DownloadStatus": "Success", "Msg": "Map Updated"}
260260
mapB, _ := json.Marshal(mapD)
261-
h.broadcastSys <- mapB
261+
hub.broadcastSys <- mapB
262262
}
263263
}()
264264
} else if strings.HasPrefix(sl, "log") {
265-
go h.logAction(sl)
265+
go hub.logAction(sl)
266266
} else if strings.HasPrefix(sl, "restart") {
267267
// potentially, the sysStray dependencies can be removed https://github.com/arduino/arduino-create-agent/issues/1013
268268
log.Println("Received restart from the daemon. Why? Boh")
269-
h.systray.Restart()
269+
hub.systray.Restart()
270270
} else if strings.HasPrefix(sl, "exit") {
271-
h.systray.Quit()
271+
hub.systray.Quit()
272272
} else if strings.HasPrefix(sl, "memstats") {
273-
h.memoryStats()
273+
hub.memoryStats()
274274
} else if strings.HasPrefix(sl, "gc") {
275-
h.garbageCollection()
275+
hub.garbageCollection()
276276
} else if strings.HasPrefix(sl, "hostname") {
277-
h.getHostname()
277+
hub.getHostname()
278278
} else if strings.HasPrefix(sl, "version") {
279-
h.getVersion()
279+
hub.getVersion()
280280
} else {
281-
go h.spErr("Could not understand command.")
281+
go hub.spErr("Could not understand command.")
282282
}
283283
}
284284

285-
func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
285+
func (hub *hub) spHandlerOpen(portname string, baud int, buftype string) {
286286

287287
log.Print("Inside spHandler")
288288

@@ -306,8 +306,8 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
306306
if err != nil {
307307
//log.Fatal(err)
308308
log.Print("Error opening port " + err.Error())
309-
//h.broadcastSys <- []byte("Error opening port. " + err.Error())
310-
h.broadcastSys <- []byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Error opening port. " + err.Error() + "\",\"Port\":\"" + conf.Name + "\",\"Baud\":" + strconv.Itoa(conf.Baud) + "}")
309+
//hub.broadcastSys <- []byte("Error opening port. " + err.Error())
310+
hub.broadcastSys <- []byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Error opening port. " + err.Error() + "\",\"Port\":\"" + conf.Name + "\",\"Baud\":" + strconv.Itoa(conf.Baud) + "}")
311311

312312
return
313313
}
@@ -325,34 +325,34 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
325325
}
326326

327327
p.OnMessage = func(msg []byte) {
328-
h.broadcastSys <- msg
328+
hub.broadcastSys <- msg
329329
}
330330
p.OnClose = func(port *serport) {
331-
h.serialPortList.MarkPortAsClosed(p.portName)
332-
h.serialPortList.List()
331+
hub.serialPortList.MarkPortAsClosed(p.portName)
332+
hub.serialPortList.List()
333333
}
334334

335335
var bw Bufferflow
336336

337337
switch buftype {
338338
case "timed":
339-
bw = NewBufferflowTimed(portname, h.broadcastSys)
339+
bw = NewBufferflowTimed(portname, hub.broadcastSys)
340340
case "timedraw":
341-
bw = NewBufferflowTimedRaw(portname, h.broadcastSys)
341+
bw = NewBufferflowTimedRaw(portname, hub.broadcastSys)
342342
case "default":
343-
bw = NewBufferflowDefault(portname, h.broadcastSys)
343+
bw = NewBufferflowDefault(portname, hub.broadcastSys)
344344
default:
345345
log.Panicf("unknown buffer type: %s", buftype)
346346
}
347347

348348
bw.Init()
349349
p.bufferwatcher = bw
350350

351-
h.serialHub.Register(p)
352-
defer h.serialHub.Unregister(p)
351+
hub.serialHub.Register(p)
352+
defer hub.serialHub.Unregister(p)
353353

354-
h.serialPortList.MarkPortAsOpened(portname)
355-
h.serialPortList.List()
354+
hub.serialPortList.MarkPortAsOpened(portname)
355+
hub.serialPortList.List()
356356

357357
// this is internally buffered thread to not send to serial port if blocked
358358
go p.writerBuffered()
@@ -363,25 +363,69 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
363363

364364
p.reader(buftype)
365365

366-
h.serialPortList.List()
366+
hub.serialPortList.List()
367367
}
368368

369-
type logWriter struct {
370-
onWrite func([]byte)
369+
func (hub *hub) spClose(portname string) {
370+
if myport, ok := hub.serialHub.FindPortByName(portname); ok {
371+
hub.broadcastSys <- []byte("Closing serial port " + portname)
372+
myport.Close()
373+
} else {
374+
hub.spErr("We could not find the serial port " + portname + " that you were trying to close.")
375+
}
371376
}
372377

373-
func (u *logWriter) Write(p []byte) (n int, err error) {
374-
u.onWrite(p)
375-
return len(p), nil
378+
func (hub *hub) spWrite(arg string) {
379+
// we will get a string of comXX asdf asdf asdf
380+
//log.Println("Inside spWrite arg: " + arg)
381+
arg = strings.TrimPrefix(arg, " ")
382+
//log.Println("arg after trim: " + arg)
383+
args := strings.SplitN(arg, " ", 3)
384+
if len(args) != 3 {
385+
errstr := "Could not parse send command: " + arg
386+
//log.Println(errstr)
387+
hub.spErr(errstr)
388+
return
389+
}
390+
bufferingMode := args[0]
391+
portname := strings.Trim(args[1], " ")
392+
data := args[2]
393+
394+
//log.Println("The port to write to is:" + portname + "---")
395+
//log.Println("The data is:" + data + "---")
396+
397+
// See if we have this port open
398+
port, ok := hub.serialHub.FindPortByName(portname)
399+
if !ok {
400+
// we couldn't find the port, so send err
401+
hub.spErr("We could not find the serial port " + portname + " that you were trying to write to.")
402+
return
403+
}
404+
405+
// see if bufferingMode is valid
406+
switch bufferingMode {
407+
case "send", "sendnobuf", "sendraw":
408+
// valid buffering mode, go ahead
409+
default:
410+
hub.spErr("Unsupported send command:" + args[0] + ". Please specify a valid one")
411+
return
412+
}
413+
414+
// send it to the write channel
415+
port.Write(data, bufferingMode)
416+
}
417+
418+
type logWriter struct {
419+
onWrite func([]byte)
376420
}
377421

378-
func (h *hub) logAction(sl string) {
422+
func (hub *hub) logAction(sl string) {
379423
if strings.HasPrefix(sl, "log on") {
380424
*logDump = "on"
381425

382426
logWriter := logWriter{}
383427
logWriter.onWrite = func(p []byte) {
384-
h.broadcastSys <- p
428+
hub.broadcastSys <- p
385429
}
386430

387431
multiWriter := io.MultiWriter(&logWriter, os.Stderr)
@@ -391,88 +435,44 @@ func (h *hub) logAction(sl string) {
391435
log.SetOutput(os.Stderr)
392436
// } else if strings.HasPrefix(sl, "log show") {
393437
// TODO: send all the saved log to websocket
394-
//h.broadcastSys <- []byte("{\"BufFlowDebug\" : \"" + *logDump + "\"}")
438+
//hub.broadcastSys <- []byte("{\"BufFlowDebug\" : \"" + *logDump + "\"}")
395439
}
396440
}
397441

398-
func (h *hub) memoryStats() {
442+
func (u *logWriter) Write(p []byte) (n int, err error) {
443+
u.onWrite(p)
444+
return len(p), nil
445+
}
446+
447+
func (hub *hub) memoryStats() {
399448
var memStats runtime.MemStats
400449
runtime.ReadMemStats(&memStats)
401450
json, _ := json.Marshal(memStats)
402451
log.Printf("memStats:%v\n", string(json))
403-
h.broadcastSys <- json
452+
hub.broadcastSys <- json
404453
}
405454

406-
func (h *hub) getHostname() {
407-
h.broadcastSys <- []byte("{\"Hostname\" : \"" + *hostname + "\"}")
455+
func (hub *hub) getHostname() {
456+
hub.broadcastSys <- []byte("{\"Hostname\" : \"" + *hostname + "\"}")
408457
}
409458

410-
func (h *hub) getVersion() {
411-
h.broadcastSys <- []byte("{\"Version\" : \"" + version + "\"}")
459+
func (hub *hub) getVersion() {
460+
hub.broadcastSys <- []byte("{\"Version\" : \"" + version + "\"}")
412461
}
413462

414-
func (h *hub) garbageCollection() {
463+
func (hub *hub) garbageCollection() {
415464
log.Printf("Starting garbageCollection()\n")
416-
h.broadcastSys <- []byte("{\"gc\":\"starting\"}")
417-
h.memoryStats()
465+
hub.broadcastSys <- []byte("{\"gc\":\"starting\"}")
466+
hub.memoryStats()
418467
debug.SetGCPercent(100)
419468
debug.FreeOSMemory()
420469
debug.SetGCPercent(-1)
421470
log.Printf("Done with garbageCollection()\n")
422-
h.broadcastSys <- []byte("{\"gc\":\"done\"}")
423-
h.memoryStats()
471+
hub.broadcastSys <- []byte("{\"gc\":\"done\"}")
472+
hub.memoryStats()
424473
}
425474

426-
func (h *hub) spErr(err string) {
475+
func (hub *hub) spErr(err string) {
427476
//log.Println("Sending err back: ", err)
428-
h.broadcastSys <- []byte("{\"Error\" : \"" + err + "\"}")
429-
}
430-
431-
func (h *hub) spClose(portname string) {
432-
if myport, ok := h.serialHub.FindPortByName(portname); ok {
433-
h.broadcastSys <- []byte("Closing serial port " + portname)
434-
myport.Close()
435-
} else {
436-
h.spErr("We could not find the serial port " + portname + " that you were trying to close.")
437-
}
438-
}
439-
440-
func (h *hub) spWrite(arg string) {
441-
// we will get a string of comXX asdf asdf asdf
442-
//log.Println("Inside spWrite arg: " + arg)
443-
arg = strings.TrimPrefix(arg, " ")
444-
//log.Println("arg after trim: " + arg)
445-
args := strings.SplitN(arg, " ", 3)
446-
if len(args) != 3 {
447-
errstr := "Could not parse send command: " + arg
448-
//log.Println(errstr)
449-
h.spErr(errstr)
450-
return
451-
}
452-
bufferingMode := args[0]
453-
portname := strings.Trim(args[1], " ")
454-
data := args[2]
455-
456-
//log.Println("The port to write to is:" + portname + "---")
457-
//log.Println("The data is:" + data + "---")
458-
459-
// See if we have this port open
460-
port, ok := h.serialHub.FindPortByName(portname)
461-
if !ok {
462-
// we couldn't find the port, so send err
463-
h.spErr("We could not find the serial port " + portname + " that you were trying to write to.")
464-
return
465-
}
466-
467-
// see if bufferingMode is valid
468-
switch bufferingMode {
469-
case "send", "sendnobuf", "sendraw":
470-
// valid buffering mode, go ahead
471-
default:
472-
h.spErr("Unsupported send command:" + args[0] + ". Please specify a valid one")
473-
return
474-
}
475-
476-
// send it to the write channel
477-
port.Write(data, bufferingMode)
477+
hub.broadcastSys <- []byte("{\"Error\" : \"" + err + "\"}")
478478
}

‎info.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,12 @@ func infoHandler(c *gin.Context) {
4141
})
4242
}
4343

44-
func pauseHandler(h *hub, s *systray.Systray) func(c *gin.Context) {
44+
func pauseHandler(hub *hub, s *systray.Systray) func(c *gin.Context) {
4545
return func(c *gin.Context) {
4646
go func() {
4747
ports, _ := serial.GetPortsList()
4848
for _, element := range ports {
49-
h.spClose(element)
49+
hub.spClose(element)
5050
}
5151
*hibernate = true
5252
s.Pause()

0 commit comments

Comments
 (0)
Please sign in to comment.