Skip to content

Instantly share code, notes, and snippets.

@ivan4th
Last active October 30, 2019 15:17
Show Gist options
  • Save ivan4th/118c0189d75cb3b9d92849549b143613 to your computer and use it in GitHub Desktop.
Save ivan4th/118c0189d75cb3b9d92849549b143613 to your computer and use it in GitHub Desktop.
modem signal check

Build:

GOOS=linux GOARCH=mipsle CGO_ENABLED=0 GOMIPS=softfloat go build
package main
import (
"fmt"
"io"
"log"
"strconv"
"strings"
"github.com/jacobsa/go-serial/serial"
)
const (
respPrefix = "^HCSQ: "
numParts = 5
)
// ^HCSQ: "LTE",41,36,141,28
func processResponse(s string) {
if !strings.HasPrefix(s, respPrefix) {
return
}
parts := strings.Split(s[len(respPrefix):], ",")
if parts[0] != `"LTE"` || len(parts) != numParts {
fmt.Printf("RAW RESPONSE: %s\n", s)
return
}
nums := make([]float64, len(parts)-1)
for n := range nums {
v, err := strconv.Atoi(parts[n+1])
if err != nil {
fmt.Printf("RAW RESPONSE: %s\n", s)
return
}
nums[n] = float64(v)
}
// FIXME: handle 255="unknown or undetectable"
// FIXME: these are actually ranges
rssi := nums[0] - 120.0
rsrp := nums[1] - 140.0
sinr := nums[2]*0.2 - 20.0 + 0.1
rsrq := nums[3]*0.5 - 19.5
fmt.Printf("LTE: RSSI=%f RSRP=%f SINR=%f RSRQ=%f\n", rssi, rsrp, sinr, rsrq)
}
func main() {
options := serial.OpenOptions{
PortName: "/dev/ttyUSB2",
BaudRate: 115200,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 0,
InterCharacterTimeout: 500,
}
port, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open(): %v", err)
}
defer port.Close()
for {
if _, err = port.Write([]byte("AT^HCSQ?\r\n")); err != nil {
log.Fatalf("port.Write(): %v", err)
}
b := make([]byte, 1)
s := ""
INNERLOOP:
for {
n, err := port.Read(b)
switch {
case err == io.EOF:
processResponse(s)
break INNERLOOP
case err != nil:
processResponse(s)
log.Fatalf("port.Read(): %v", err)
case n == 0:
processResponse(s)
log.Fatalf("port.Read(): no data")
case b[0] == 13:
// NOOP
case b[0] == 10:
processResponse(s)
s = ""
default:
s += string(b)
}
}
}
}
@ivan4th
Copy link
Author

ivan4th commented Oct 30, 2019

go-serial needs a patch (better use another fork, didn't bother to find it):

diff --git a/serial/open_linux.go b/serial/open_linux.go
index ccce12c..a27fa73 100644
--- a/serial/open_linux.go
+++ b/serial/open_linux.go
@@ -25,9 +25,10 @@ import (
 // }
 //
 const (
-	kTCSETS2 = 0x402C542B
-	kBOTHER  = 0x1000
-	kNCCS    = 19
+	// https://github.com/jacobsa/go-serial/issues/37#issuecomment-379078372
+	kTCSETS2 = 0x8030542B
+	kBOTHER  = 0x00001000
+	kNCCS    = 23
 )
 
 //

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment