Created
April 9, 2014 21:54
-
-
Save lachlan/10321939 to your computer and use it in GitHub Desktop.
Revisions
-
lachlan created this gist
Apr 9, 2014 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,83 @@ package main import ( "encoding/base64" "encoding/hex" "github.com/docopt/docopt.go" "github.com/tarm/goserial" "log" "strconv" ) var version string = "0.0.1" var usage string = `cereal -- writes data to a serial port Usage: cereal write [--device=<device>] [--baud=<baud>] [--base64 | --hex] <data> cereal -h | --help cereal --version Options: -h --help Show this screen. --version Show version. --device=<device> The serial port to write the specified data to [default: COM1]. --baud=<baud> The baud rate used when transmitting the specified data [default: 9600]. --base64 Data is provided as a base64-encoded string, for example "aGVsbG8=". --hex Data is provided as a hex-encoded string, for example "00fffa08". ` func main() { // parse the command line arguments arguments, err := docopt.Parse(usage, nil, true, version, false) if err != nil { log.Fatal("Error: command line arguments could not be parsed: ", err) } // extract the command line arguments data, _ := arguments["<data>"].(string) base64Encoded, _ := arguments["--base64"].(bool) hexEncoded, _ := arguments["--hex"].(bool) device, _ := arguments["--device"].(string) baud, _ := strconv.Atoi(arguments["--baud"].(string)) write, _ := arguments["write"].(bool) if (write) { // encode the data as a byte array using the specified encoding var bytes []byte; if (base64Encoded) { bytes, err = base64.StdEncoding.DecodeString(data) if err != nil { log.Fatal("Error: base64-encoded data is malformed: ", err) } } else if (hexEncoded) { bytes, err = hex.DecodeString(data) if err != nil { log.Fatal("Error: hex-encoded data is malformed: ", err) } } else { bytes = []byte(data) } // open the serial port c := &serial.Config{Name: device, Baud: baud} handle, err := serial.OpenPort(c) if err != nil { log.Fatal("Error: device ", device, " could not be opened: ", err) } // close the serial port when done defer handle.Close() // write the data to the serial port n, err := handle.Write(bytes) if err != nil { log.Fatal("Error: device ", device, " could not be written to: ", err) } // log the number of bytes written to the console if (n == 1) { log.Printf("%v byte written to device %v", n, device) } else { log.Printf("%v bytes written to device %v", n, device) } } }