Skip to content

Commit 8106c84

Browse files
committed
feat: move serial port into new file
1 parent fc51194 commit 8106c84

File tree

3 files changed

+200
-200
lines changed

3 files changed

+200
-200
lines changed

serial.go

-187
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package main
1919

2020
import (
2121
"encoding/json"
22-
"fmt"
2322
"slices"
2423
"strings"
2524
"sync"
@@ -45,34 +44,6 @@ func newSerialHub() *serialhub {
4544
}
4645
}
4746

48-
type serialPortList struct {
49-
tools *tools.Tools
50-
51-
Ports []*SpPortItem
52-
portsLock sync.Mutex
53-
54-
OnList func([]byte) `json:"-"`
55-
OnErr func(string) `json:"-"`
56-
}
57-
58-
func newSerialPortList(tools *tools.Tools) *serialPortList {
59-
return &serialPortList{tools: tools}
60-
}
61-
62-
// SpPortItem is the serial port item
63-
type SpPortItem struct {
64-
Name string
65-
SerialNumber string
66-
DeviceClass string
67-
IsOpen bool
68-
IsPrimary bool
69-
Baud int
70-
BufferAlgorithm string
71-
Ver string
72-
VendorID string
73-
ProductID string
74-
}
75-
7647
// Register serial ports from the connections.
7748
func (sh *serialhub) Register(port *serport) {
7849
sh.mu.Lock()
@@ -107,164 +78,6 @@ func (sh *serialhub) FindPortByName(portname string) (*serport, bool) {
10778
return nil, false
10879
}
10980

110-
// List broadcasts a Json representation of the ports found
111-
func (sp *serialPortList) List() {
112-
sp.portsLock.Lock()
113-
ls, err := json.MarshalIndent(sp, "", "\t")
114-
sp.portsLock.Unlock()
115-
116-
if err != nil {
117-
sp.OnErr("Error creating json on port list " + err.Error())
118-
} else {
119-
sp.OnList(ls)
120-
}
121-
}
122-
123-
// Run is the main loop for port discovery and management
124-
func (sp *serialPortList) Run() {
125-
for retries := 0; retries < 10; retries++ {
126-
sp.runSerialDiscovery()
127-
128-
logrus.Errorf("Serial discovery stopped working, restarting it in 10 seconds...")
129-
time.Sleep(10 * time.Second)
130-
}
131-
logrus.Errorf("Failed restarting serial discovery. Giving up...")
132-
}
133-
134-
func (sp *serialPortList) runSerialDiscovery() {
135-
// First ensure that all the discoveries are available
136-
noOpProgress := func(msg string) {}
137-
if err := sp.tools.Download("builtin", "serial-discovery", "latest", "keep", noOpProgress); err != nil {
138-
logrus.Errorf("Error downloading serial-discovery: %s", err)
139-
panic(err)
140-
}
141-
sd, err := sp.tools.GetLocation("serial-discovery")
142-
if err != nil {
143-
logrus.Errorf("Error downloading serial-discovery: %s", err)
144-
panic(err)
145-
}
146-
d := discovery.NewClient("serial", sd+"/serial-discovery")
147-
dLogger := logrus.WithField("discovery", "serial")
148-
if *verbose {
149-
d.SetLogger(dLogger)
150-
}
151-
d.SetUserAgent("arduino-create-agent/" + version)
152-
if err := d.Run(); err != nil {
153-
logrus.Errorf("Error running serial-discovery: %s", err)
154-
panic(err)
155-
}
156-
defer d.Quit()
157-
158-
events, err := d.StartSync(10)
159-
if err != nil {
160-
logrus.Errorf("Error starting event watcher on serial-discovery: %s", err)
161-
panic(err)
162-
}
163-
164-
logrus.Infof("Serial discovery started, watching for events")
165-
for ev := range events {
166-
logrus.WithField("event", ev).Debugf("Serial discovery event")
167-
switch ev.Type {
168-
case "add":
169-
sp.add(ev.Port)
170-
case "remove":
171-
sp.remove(ev.Port)
172-
}
173-
}
174-
175-
sp.reset()
176-
logrus.Errorf("Serial discovery stopped.")
177-
}
178-
179-
func (sp *serialPortList) reset() {
180-
sp.portsLock.Lock()
181-
defer sp.portsLock.Unlock()
182-
sp.Ports = []*SpPortItem{}
183-
}
184-
185-
func (sp *serialPortList) add(addedPort *discovery.Port) {
186-
if addedPort.Protocol != "serial" {
187-
return
188-
}
189-
props := addedPort.Properties
190-
if !props.ContainsKey("vid") {
191-
return
192-
}
193-
vid, pid := props.Get("vid"), props.Get("pid")
194-
if vid == "0x0000" || pid == "0x0000" {
195-
return
196-
}
197-
if portsFilter != nil && !portsFilter.MatchString(addedPort.Address) {
198-
logrus.Debugf("ignoring port not matching filter. port: %v\n", addedPort.Address)
199-
return
200-
}
201-
202-
sp.portsLock.Lock()
203-
defer sp.portsLock.Unlock()
204-
205-
// If the port is already in the list, just update the metadata...
206-
for _, oldPort := range sp.Ports {
207-
fmt.Println("oldPort.Name: ", oldPort.Name)
208-
if oldPort.Name == addedPort.Address {
209-
oldPort.SerialNumber = props.Get("serialNumber")
210-
oldPort.VendorID = vid
211-
oldPort.ProductID = pid
212-
return
213-
}
214-
}
215-
// ...otherwise, add it to the list
216-
sp.Ports = append(sp.Ports, &SpPortItem{
217-
Name: addedPort.Address,
218-
SerialNumber: props.Get("serialNumber"),
219-
VendorID: vid,
220-
ProductID: pid,
221-
Ver: version,
222-
IsOpen: false,
223-
IsPrimary: false,
224-
Baud: 0,
225-
BufferAlgorithm: "",
226-
})
227-
}
228-
229-
func (sp *serialPortList) remove(removedPort *discovery.Port) {
230-
sp.portsLock.Lock()
231-
defer sp.portsLock.Unlock()
232-
233-
// Remove the port from the list
234-
sp.Ports = slices.DeleteFunc(sp.Ports, func(oldPort *SpPortItem) bool {
235-
return oldPort.Name == removedPort.Address
236-
})
237-
}
238-
239-
// MarkPortAsOpened marks a port as opened by the user
240-
func (sp *serialPortList) MarkPortAsOpened(portname string) {
241-
sp.portsLock.Lock()
242-
defer sp.portsLock.Unlock()
243-
port := sp.getPortByName(portname)
244-
if port != nil {
245-
port.IsOpen = true
246-
}
247-
}
248-
249-
// MarkPortAsClosed marks a port as no more opened by the user
250-
func (sp *serialPortList) MarkPortAsClosed(portname string) {
251-
sp.portsLock.Lock()
252-
defer sp.portsLock.Unlock()
253-
port := sp.getPortByName(portname)
254-
if port != nil {
255-
port.IsOpen = false
256-
}
257-
}
258-
259-
func (sp *serialPortList) getPortByName(portname string) *SpPortItem {
260-
for _, port := range sp.Ports {
261-
if port.Name == portname {
262-
return port
263-
}
264-
}
265-
return nil
266-
}
267-
26881
func (h *hub) spErr(err string) {
26982
//log.Println("Sending err back: ", err)
27083
//sh.hub.broadcastSys <- []byte(err)

serialport.go

+3-13
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@ type serport struct {
6262
//bufferwatcher *BufferflowDummypause
6363
bufferwatcher Bufferflow
6464

65-
// TODO: to remove global
6665
OnMessage func([]byte)
6766
OnClose func(*serport)
6867
}
@@ -93,7 +92,6 @@ func (p *serport) reader(buftype string) {
9392
if p.isClosing.Load() {
9493
strmsg := "Shutting down reader on " + p.portConf.Name
9594
log.Println(strmsg)
96-
// h.broadcastSys <- ([]byte(strmsg)
9795
p.OnMessage([]byte(strmsg))
9896
break
9997
}
@@ -148,18 +146,13 @@ func (p *serport) reader(buftype string) {
148146
if err == io.EOF || err == io.ErrUnexpectedEOF {
149147
// hit end of file
150148
log.Println("Hit end of file on serial port")
151-
// h.broadcastSys <- []byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Got EOF (End of File) on port which usually means another app other than Serial Port JSON Server is locking your port. " + err.Error() + "\",\"Port\":\"" + p.portConf.Name + "\",\"Baud\":" + strconv.Itoa(p.portConf.Baud) + "}")
152149
p.OnMessage([]byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Got EOF (End of File) on port which usually means another app other than Serial Port JSON Server is locking your port. " + err.Error() + "\",\"Port\":\"" + p.portConf.Name + "\",\"Baud\":" + strconv.Itoa(p.portConf.Baud) + "}"))
153150

154151
}
155152

156153
if err != nil {
157154
log.Println(err)
158-
// h.broadcastSys <- []byte("Error reading on " + p.portConf.Name + " " +
159-
// err.Error() + " Closing port.")
160155
p.OnMessage([]byte("Error reading on " + p.portConf.Name + " " + err.Error() + " Closing port."))
161-
162-
// h.broadcastSys <- []byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Got error reading on port. " + err.Error() + "\",\"Port\":\"" + p.portConf.Name + "\",\"Baud\":" + strconv.Itoa(p.portConf.Baud) + "}")
163156
p.OnMessage([]byte("{\"Cmd\":\"OpenFail\",\"Desc\":\"Got error reading on port. " + err.Error() + "\",\"Port\":\"" + p.portConf.Name + "\",\"Baud\":" + strconv.Itoa(p.portConf.Baud) + "}"))
164157
p.isClosingDueToError = true
165158
break
@@ -218,7 +211,6 @@ func (p *serport) writerBuffered() {
218211
}
219212
msgstr := "writerBuffered just got closed. make sure you make a new one. port:" + p.portConf.Name
220213
log.Println(msgstr)
221-
// h.broadcastSys <- []byte(msgstr)
222214
p.OnMessage([]byte(msgstr))
223215
}
224216

@@ -240,18 +232,17 @@ func (p *serport) writerNoBuf() {
240232
if err != nil {
241233
errstr := "Error writing to " + p.portConf.Name + " " + err.Error() + " Closing port."
242234
log.Print(errstr)
243-
// h.broadcastSys <- []byte(errstr)
244235
p.OnMessage([]byte(errstr))
245236
break
246237
}
247238
}
248239
msgstr := "Shutting down writer on " + p.portConf.Name
249240
log.Println(msgstr)
250-
// h.broadcastSys <- []byte(msgstr)
251241
p.OnMessage([]byte(msgstr))
242+
252243
p.portIo.Close()
253-
// TODO: is this needed ?
254-
// serialPorts.List()
244+
// serialPorts.List(
245+
255246
}
256247

257248
// this method runs as its own thread because it's instantiated
@@ -283,7 +274,6 @@ func (p *serport) writerRaw() {
283274
}
284275
msgstr := "writerRaw just got closed. make sure you make a new one. port:" + p.portConf.Name
285276
log.Println(msgstr)
286-
// h.broadcastSys <- []byte(msgstr)
287277
p.OnMessage([]byte(msgstr))
288278
}
289279

0 commit comments

Comments
 (0)