From 0837d376f7865382175495e6abf4803bfbc40162 Mon Sep 17 00:00:00 2001 From: yotia Date: Tue, 6 Aug 2024 21:10:24 +0300 Subject: [PATCH] Added sync. --- api/modem/modem.go | 19 +++++++++++++++++++ api/modem/sms/sms.go | 8 ++++++++ 2 files changed, 27 insertions(+) diff --git a/api/modem/modem.go b/api/modem/modem.go index 0fbc05a..d7d3302 100644 --- a/api/modem/modem.go +++ b/api/modem/modem.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "strings" + "sync" "time" "github.com/CGSG-2021-AE4/modem-test/api/modem/at" @@ -24,6 +25,7 @@ type ModemData struct { type modem struct { // Internal values logger *log.Logger + mutex sync.Mutex // Serial values baudrate int @@ -71,6 +73,9 @@ func New(logger *log.Logger) Modem { } func (m *modem) Init() error { + m.mutex.Lock() + defer m.mutex.Unlock() + // Turn module on m.logger.Println("=============================== Turn on module") if err := m.onOffPin.Init(); err != nil { @@ -138,6 +143,9 @@ func (m *modem) Init() error { } func (m *modem) Update() error { + m.mutex.Lock() + defer m.mutex.Unlock() + if !m.IsConnected() { m.logger.Println("No connection to module") return nil @@ -152,6 +160,9 @@ func (m *modem) Update() error { } func (m *modem) GetData() ModemData { + m.mutex.Lock() + defer m.mutex.Unlock() + return ModemData{ Port: m.port.GetName(), Data: m.gps.GetData(), @@ -171,6 +182,9 @@ func (m *modem) At() at.Port { } func (m *modem) Close() error { // I can't return error so I log it + m.mutex.Lock() + defer m.mutex.Unlock() + if err := m.sms.Close(); err != nil { m.logger.Printf("\x1b[38;2;255;0;0mclose sms error: %s\x1b[38;2;255;255;255m\n", err.Error()) } @@ -290,6 +304,11 @@ func (m *modem) checkPort(portName string) (outErr error) { } defer m.port.Disconnect() // Do not bother about errors... + // To filter dead ports + if _, err := m.port.Send("AT"); err != nil { + return fmt.Errorf("ping error: %w", err) + } + if err := m.setupPort(); err != nil { return fmt.Errorf("setup port: %w", err) } diff --git a/api/modem/sms/sms.go b/api/modem/sms/sms.go index 3806516..7ca39a7 100644 --- a/api/modem/sms/sms.go +++ b/api/modem/sms/sms.go @@ -35,6 +35,14 @@ func (d *dialer) Init() error { return fmt.Errorf("serial port is not connected") } + // Check SIM an PIN + if resp, err := d.port.Send("AT+CPIN?"); err != nil || !resp.Check() { + if err != nil { + return fmt.Errorf("check pin: %w", err) + } + return fmt.Errorf("check pin: error response: %s", resp) + } + // Ensure text format if resp, err := d.port.Send("AT+CMGF=1"); err != nil || !resp.Check() { if err != nil {