Skip to content

Commit f07103e

Browse files
committed
WIP: remove hub and sh globals
1 parent 55ca9e5 commit f07103e

File tree

5 files changed

+135
-122
lines changed

5 files changed

+135
-122
lines changed

conn.go

+83-80
Original file line numberDiff line numberDiff line change
@@ -79,116 +79,119 @@ type Upload struct {
7979

8080
var uploadStatusStr = "ProgrammerStatus"
8181

82-
func uploadHandler(c *gin.Context) {
83-
data := new(Upload)
84-
if err := c.BindJSON(data); err != nil {
85-
c.String(http.StatusBadRequest, fmt.Sprintf("err with the payload. %v", err.Error()))
86-
return
87-
}
88-
89-
log.Printf("%+v %+v %+v %+v %+v %+v", data.Port, data.Board, data.Rewrite, data.Commandline, data.Extra, data.Filename)
90-
91-
if data.Port == "" {
92-
c.String(http.StatusBadRequest, "port is required")
93-
return
94-
}
95-
96-
if data.Board == "" {
97-
c.String(http.StatusBadRequest, "board is required")
98-
log.Error("board is required")
99-
return
100-
}
101-
102-
if !data.Extra.Network {
103-
if data.Signature == "" {
104-
c.String(http.StatusBadRequest, "signature is required")
82+
func UploadHandler(h *hub) func(c *gin.Context) {
83+
return func(c *gin.Context) {
84+
data := new(Upload)
85+
if err := c.BindJSON(data); err != nil {
86+
c.String(http.StatusBadRequest, fmt.Sprintf("err with the payload. %v", err.Error()))
10587
return
10688
}
10789

108-
if data.Commandline == "" {
109-
c.String(http.StatusBadRequest, "commandline is required for local board")
90+
log.Printf("%+v %+v %+v %+v %+v %+v", data.Port, data.Board, data.Rewrite, data.Commandline, data.Extra, data.Filename)
91+
92+
if data.Port == "" {
93+
c.String(http.StatusBadRequest, "port is required")
11094
return
11195
}
11296

113-
err := utilities.VerifyInput(data.Commandline, data.Signature)
114-
115-
if err != nil {
116-
c.String(http.StatusBadRequest, "signature is invalid")
97+
if data.Board == "" {
98+
c.String(http.StatusBadRequest, "board is required")
99+
log.Error("board is required")
117100
return
118101
}
119-
}
120102

121-
buffer := bytes.NewBuffer(data.Hex)
103+
if !data.Extra.Network {
104+
if data.Signature == "" {
105+
c.String(http.StatusBadRequest, "signature is required")
106+
return
107+
}
122108

123-
filePath, err := utilities.SaveFileonTempDir(data.Filename, buffer)
124-
if err != nil {
125-
c.String(http.StatusBadRequest, err.Error())
126-
return
127-
}
109+
if data.Commandline == "" {
110+
c.String(http.StatusBadRequest, "commandline is required for local board")
111+
return
112+
}
128113

129-
tmpdir, err := os.MkdirTemp("", "extrafiles")
130-
if err != nil {
131-
c.String(http.StatusBadRequest, err.Error())
132-
return
133-
}
114+
err := utilities.VerifyInput(data.Commandline, data.Signature)
134115

135-
for _, extraFile := range data.ExtraFiles {
136-
path, err := utilities.SafeJoin(tmpdir, extraFile.Filename)
137-
if err != nil {
138-
c.String(http.StatusBadRequest, err.Error())
139-
return
116+
if err != nil {
117+
c.String(http.StatusBadRequest, "signature is invalid")
118+
return
119+
}
140120
}
141-
log.Printf("Saving %s on %s", extraFile.Filename, path)
142121

143-
err = os.MkdirAll(filepath.Dir(path), 0744)
144-
if err != nil {
145-
c.String(http.StatusBadRequest, err.Error())
146-
return
147-
}
122+
buffer := bytes.NewBuffer(data.Hex)
148123

149-
err = os.WriteFile(path, extraFile.Hex, 0644)
124+
filePath, err := utilities.SaveFileonTempDir(data.Filename, buffer)
150125
if err != nil {
151126
c.String(http.StatusBadRequest, err.Error())
152127
return
153128
}
154-
}
155129

156-
if data.Rewrite != "" {
157-
data.Board = data.Rewrite
158-
}
159-
160-
go func() {
161-
// Resolve commandline
162-
commandline, err := upload.PartiallyResolve(data.Board, filePath, tmpdir, data.Commandline, data.Extra, Tools)
130+
tmpdir, err := os.MkdirTemp("", "extrafiles")
163131
if err != nil {
164-
send(map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
132+
c.String(http.StatusBadRequest, err.Error())
165133
return
166134
}
167135

168-
l := PLogger{Verbose: true}
169-
170-
// Upload
171-
if data.Extra.Network {
172-
err = errors.New("network upload is not supported anymore, pease use OTA instead")
173-
} else {
174-
send(map[string]string{uploadStatusStr: "Starting", "Cmd": "Serial"})
175-
err = upload.Serial(data.Port, commandline, data.Extra, l)
136+
for _, extraFile := range data.ExtraFiles {
137+
path, err := utilities.SafeJoin(tmpdir, extraFile.Filename)
138+
if err != nil {
139+
c.String(http.StatusBadRequest, err.Error())
140+
return
141+
}
142+
log.Printf("Saving %s on %s", extraFile.Filename, path)
143+
144+
err = os.MkdirAll(filepath.Dir(path), 0744)
145+
if err != nil {
146+
c.String(http.StatusBadRequest, err.Error())
147+
return
148+
}
149+
150+
err = os.WriteFile(path, extraFile.Hex, 0644)
151+
if err != nil {
152+
c.String(http.StatusBadRequest, err.Error())
153+
return
154+
}
176155
}
177156

178-
// Handle result
179-
if err != nil {
180-
send(map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
181-
return
157+
if data.Rewrite != "" {
158+
data.Board = data.Rewrite
182159
}
183-
send(map[string]string{uploadStatusStr: "Done", "Flash": "Ok"})
184-
}()
185160

186-
c.String(http.StatusAccepted, "")
161+
go func() {
162+
// Resolve commandline
163+
commandline, err := upload.PartiallyResolve(data.Board, filePath, tmpdir, data.Commandline, data.Extra, Tools)
164+
if err != nil {
165+
send(h, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
166+
return
167+
}
168+
169+
l := PLogger{Verbose: true}
170+
171+
// Upload
172+
if data.Extra.Network {
173+
err = errors.New("network upload is not supported anymore, pease use OTA instead")
174+
} else {
175+
send(h, map[string]string{uploadStatusStr: "Starting", "Cmd": "Serial"})
176+
err = upload.Serial(data.Port, commandline, data.Extra, l)
177+
}
178+
179+
// Handle result
180+
if err != nil {
181+
send(h, map[string]string{uploadStatusStr: "Error", "Msg": err.Error()})
182+
return
183+
}
184+
send(h, map[string]string{uploadStatusStr: "Done", "Flash": "Ok"})
185+
}()
186+
187+
c.String(http.StatusAccepted, "")
188+
}
187189
}
188190

189191
// PLogger sends the info from the upload to the websocket
190192
type PLogger struct {
191193
Verbose bool
194+
h *hub
192195
}
193196

194197
// Debug only sends messages if verbose is true (always true for now)
@@ -202,15 +205,15 @@ func (l PLogger) Debug(args ...interface{}) {
202205
func (l PLogger) Info(args ...interface{}) {
203206
output := fmt.Sprint(args...)
204207
log.Println(output)
205-
send(map[string]string{uploadStatusStr: "Busy", "Msg": output})
208+
send(l.h, map[string]string{uploadStatusStr: "Busy", "Msg": output})
206209
}
207210

208-
func send(args map[string]string) {
211+
func send(h *hub, args map[string]string) {
209212
mapB, _ := json.Marshal(args)
210213
h.broadcastSys <- mapB
211214
}
212215

213-
func wsHandler() *WsServer {
216+
func wsHandler(h *hub) *WsServer {
214217
server, err := socketio.NewServer(nil)
215218
if err != nil {
216219
log.Fatal(err)

hub.go

+25-19
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,20 @@ type hub struct {
4545

4646
// Unregister requests from connections.
4747
unregister chan *connection
48+
49+
// Serial hub to communicate with serial ports
50+
serialHub *serialhub
4851
}
4952

50-
var h = hub{
51-
broadcast: make(chan []byte, 1000),
52-
broadcastSys: make(chan []byte, 1000),
53-
register: make(chan *connection),
54-
unregister: make(chan *connection),
55-
connections: make(map[*connection]bool),
53+
func NewHub() *hub {
54+
return &hub{
55+
broadcast: make(chan []byte, 1000),
56+
broadcastSys: make(chan []byte, 1000),
57+
register: make(chan *connection),
58+
unregister: make(chan *connection),
59+
connections: make(map[*connection]bool),
60+
serialHub: NewSerialHub(),
61+
}
5662
}
5763

5864
const commands = `{
@@ -108,7 +114,7 @@ func (h *hub) run() {
108114
h.unregisterConnection(c)
109115
case m := <-h.broadcast:
110116
if len(m) > 0 {
111-
checkCmd(m)
117+
h.checkCmd(m)
112118
h.sendToRegisteredConnections(m)
113119
}
114120
case m := <-h.broadcastSys:
@@ -117,7 +123,7 @@ func (h *hub) run() {
117123
}
118124
}
119125

120-
func checkCmd(m []byte) {
126+
func (h *hub) checkCmd(m []byte) {
121127
//log.Print("Inside checkCmd")
122128
s := string(m[:])
123129

@@ -154,7 +160,7 @@ func checkCmd(m []byte) {
154160
buftype := strings.Replace(args[3], "\n", "", -1)
155161
bufferAlgorithm = buftype
156162
}
157-
go spHandlerOpen(args[1], baud, bufferAlgorithm)
163+
go h.spHandlerOpen(args[1], baud, bufferAlgorithm)
158164

159165
} else if strings.HasPrefix(sl, "close") {
160166

@@ -228,13 +234,13 @@ func checkCmd(m []byte) {
228234
} else if strings.HasPrefix(sl, "exit") {
229235
// Systray.Quit()
230236
} else if strings.HasPrefix(sl, "memstats") {
231-
memoryStats()
237+
h.memoryStats()
232238
} else if strings.HasPrefix(sl, "gc") {
233-
garbageCollection()
239+
h.garbageCollection()
234240
} else if strings.HasPrefix(sl, "hostname") {
235-
getHostname()
241+
h.getHostname()
236242
} else if strings.HasPrefix(sl, "version") {
237-
getVersion()
243+
h.getVersion()
238244
} else {
239245
go spErr("Could not understand command.")
240246
}
@@ -254,30 +260,30 @@ func logAction(sl string) {
254260
}
255261
}
256262

257-
func memoryStats() {
263+
func (h *hub) memoryStats() {
258264
var memStats runtime.MemStats
259265
runtime.ReadMemStats(&memStats)
260266
json, _ := json.Marshal(memStats)
261267
log.Printf("memStats:%v\n", string(json))
262268
h.broadcastSys <- json
263269
}
264270

265-
func getHostname() {
271+
func (h *hub) getHostname() {
266272
h.broadcastSys <- []byte("{\"Hostname\" : \"" + *hostname + "\"}")
267273
}
268274

269-
func getVersion() {
275+
func (h *hub) getVersion() {
270276
h.broadcastSys <- []byte("{\"Version\" : \"" + version + "\"}")
271277
}
272278

273-
func garbageCollection() {
279+
func (h *hub) garbageCollection() {
274280
log.Printf("Starting garbageCollection()\n")
275281
h.broadcastSys <- []byte("{\"gc\":\"starting\"}")
276-
memoryStats()
282+
h.memoryStats()
277283
debug.SetGCPercent(100)
278284
debug.FreeOSMemory()
279285
debug.SetGCPercent(-1)
280286
log.Printf("Done with garbageCollection()\n")
281287
h.broadcastSys <- []byte("{\"gc\":\"done\"}")
282-
memoryStats()
288+
h.memoryStats()
283289
}

main.go

+11-8
Original file line numberDiff line numberDiff line change
@@ -107,14 +107,15 @@ var (
107107
Index *index.Resource
108108
)
109109

110-
type logWriter struct{}
110+
// TODO: enable it
111+
// type logWriter struct{}
111112

112-
func (u *logWriter) Write(p []byte) (n int, err error) {
113-
h.broadcastSys <- p
114-
return len(p), nil
115-
}
113+
// func (u *logWriter) Write(p []byte) (n int, err error) {
114+
// h.broadcastSys <- p
115+
// return len(p), nil
116+
// }
116117

117-
var loggerWs logWriter
118+
// var loggerWs logWriter
118119

119120
func homeHandler(c *gin.Context) {
120121
homeTemplate.Execute(c.Writer, c.Request.Host)
@@ -191,6 +192,8 @@ func loop(stray *systray.Systray, configPath *paths.Path) {
191192
os.Exit(0)
192193
}
193194

195+
h := NewHub()
196+
194197
logger := func(msg string) {
195198
mapD := map[string]string{"DownloadStatus": "Pending", "Msg": msg}
196199
mapB, _ := json.Marshal(mapD)
@@ -390,7 +393,7 @@ func loop(stray *systray.Systray, configPath *paths.Path) {
390393

391394
r := gin.New()
392395

393-
socketHandler := wsHandler().ServeHTTP
396+
socketHandler := wsHandler(h).ServeHTTP
394397

395398
extraOrigins := []string{
396399
"https://create.arduino.cc",
@@ -429,7 +432,7 @@ func loop(stray *systray.Systray, configPath *paths.Path) {
429432
r.LoadHTMLFiles("templates/nofirefox.html")
430433

431434
r.GET("/", homeHandler)
432-
r.POST("/upload", uploadHandler)
435+
r.POST("/upload", UpdateHandler(stray))
433436
r.GET("/socket.io/", socketHandler)
434437
r.POST("/socket.io/", socketHandler)
435438
r.Handle("WS", "/socket.io/", socketHandler)

0 commit comments

Comments
 (0)