Created
June 2, 2020 07:55
-
-
Save chrishannam/2de1f44177c68d24d7e93ed07f5d3010 to your computer and use it in GitHub Desktop.
Read from a serial port and extract JSON.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"encoding/json" | |
"fmt" | |
"log" | |
"github.com/tarm/serial" | |
) | |
func main() { | |
c := &serial.Config{Name: "/dev/cu.usbserial-14120", Baud: 9600} | |
ser, err := serial.OpenPort(c) | |
if err != nil { | |
log.Fatal(err) | |
} | |
scanner := bufio.NewScanner(ser) | |
for scanner.Scan() { | |
output := scanner.Bytes() | |
var f interface{} | |
err := json.Unmarshal(output, &f) | |
if err != nil { | |
fmt.Println("Trying again") | |
} else { | |
m := f.(map[string]interface{}) | |
fmt.Println(m["light"]) | |
fmt.Println(m["temperature"]) | |
fmt.Println(m["humidity"]) | |
for k, v := range m { | |
switch vv := v.(type) { | |
case string: | |
fmt.Println(k, "is string", vv) | |
case float64: | |
fmt.Println(k, "is float64", vv) | |
case []interface{}: | |
fmt.Println(k, "is an array:") | |
for i, u := range vv { | |
fmt.Println(i, u) | |
} | |
default: | |
fmt.Println(k, "is of a type I don't know how to handle") | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment