@@ -284,6 +284,8 @@ func (p *serport) writerRaw() {
284284
285285// FIXME: move this into the `hub.go` file
286286func (h * hub ) spHandlerOpen (portname string , baud int , buftype string ) {
287+ h .spHandlerOpenLock .Lock ()
288+ defer h .spHandlerOpenLock .Unlock ()
287289
288290 log .Print ("Inside spHandler" )
289291
@@ -305,11 +307,14 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
305307 sp , err := serial .Open (portname , mode )
306308 log .Print ("Just tried to open port" )
307309 if err != nil {
308- //log.Fatal(err)
309- log .Print ("Error opening port " + err .Error ())
310- //h.broadcastSys <- []byte("Error opening port. " + err.Error())
311- h .broadcastSys <- []byte ("{\" Cmd\" :\" OpenFail\" ,\" Desc\" :\" Error opening port. " + err .Error () + "\" ,\" Port\" :\" " + conf .Name + "\" ,\" Baud\" :" + strconv .Itoa (conf .Baud ) + "}" )
312-
310+ existingPort , ok := h .serialHub .FindPortByName (portname )
311+ if ok && existingPort .portConf .Baud == baud && existingPort .BufferType == buftype {
312+ log .Print ("Port already opened" )
313+ h .broadcastSys <- []byte ("{\" Cmd\" :\" Open\" ,\" Desc\" :\" Port already opened.\" ,\" Port\" :\" " + existingPort .portConf .Name + "\" ,\" Baud\" :" + strconv .Itoa (existingPort .portConf .Baud ) + ",\" BufferType\" :\" " + existingPort .BufferType + "\" }" )
314+ } else {
315+ log .Print ("Error opening port " + err .Error ())
316+ h .broadcastSys <- []byte ("{\" Cmd\" :\" OpenFail\" ,\" Desc\" :\" Error opening port. " + err .Error () + "\" ,\" Port\" :\" " + conf .Name + "\" ,\" Baud\" :" + strconv .Itoa (conf .Baud ) + "}" )
317+ }
313318 return
314319 }
315320 log .Print ("Opened port successfully" )
@@ -348,7 +353,6 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
348353 p .bufferwatcher = bw
349354
350355 h .serialHub .Register (p )
351- defer h .serialHub .Unregister (p )
352356
353357 h .serialPortList .MarkPortAsOpened (portname )
354358 h .serialPortList .List ()
@@ -359,10 +363,12 @@ func (h *hub) spHandlerOpen(portname string, baud int, buftype string) {
359363 go p .writerNoBuf ()
360364 // this is thread to send to serial port but with base64 decoding
361365 go p .writerRaw ()
362-
363- p .reader (buftype )
364-
365- h .serialPortList .List ()
366+ // this is the thread that reads from the serial port
367+ go func () {
368+ p .reader (buftype )
369+ h .serialPortList .List ()
370+ h .serialHub .Unregister (p )
371+ }()
366372}
367373
368374func (p * serport ) Close () {
0 commit comments