Example #1
0
func connect() (io.ReadWriter, error) {
	if *baud == 0 {
		return net.Dial("tcp", *dst)
	}
	c := &serial.Config{Name: *dst, Baud: *baud}
	return serial.OpenPort(c)
}
func main() {
	config := &serial.Config{Name: "/dev/tty.usbmodem1411", Baud: 57600}
	s, err := serial.OpenPort(config)
	if err != nil {
		panic(err)
	}

	opts := MQTT.NewClientOptions().AddBroker("tcp://46.101.145.61:1883")
	opts.SetClientID("meteo-studio")

	// Connect MQTT client
	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}

	// Loop over serial port lines
	scanner := bufio.NewScanner(s)
	for scanner.Scan() {
		parts := strings.Split(scanner.Text(), "|")
		if parts[0] == "6" {
			// if command is "6" (meteo data payload), push it to the broker
			token := c.Publish("studio/meteo", 0, false, parts[1])
			token.Wait()
		}
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}
Example #3
0
func main() {
	sp, err := serial.OpenPort(&serial.Config{Name: "/dev/ttyACM0", Baud: 57600})
	if err != nil {
		panic(err)
	}

	board := client.New()

	fmt.Println("connecting.....")
	err = board.Connect(sp)
	defer board.Disconnect()

	if err != nil {
		panic(err)
	}

	fmt.Println("firmware name:", board.FirmwareName)
	fmt.Println("firmata version:", board.ProtocolVersion)

	pin := 13
	if err = board.SetPinMode(pin, client.Output); err != nil {
		panic(err)
	}

	level := 0

	for {
		level ^= 1
		if err := board.DigitalWrite(pin, level); err != nil {
			panic(err)
		}
		fmt.Println("level:", level)
		time.Sleep(500 * time.Millisecond)
	}
}
Example #4
0
// Connect starts a connection to the board
func (megaPi *MegaPiAdaptor) Connect() (errs []error) {
	if megaPi.connection == nil {
		sp, err := serial.OpenPort(megaPi.serialConfig)
		if err != nil {
			return []error{err}
		}

		// sleeping is required to give the board a chance to reset
		time.Sleep(2 * time.Second)
		megaPi.connection = sp
	}

	// kick off thread to send bytes to the board
	go func() {
		for {
			select {
			case bytes := <-megaPi.writeBytesChannel:
				megaPi.connection.Write(bytes)
				time.Sleep(10 * time.Millisecond)
			case <-megaPi.finalizeChannel:
				megaPi.finalizeChannel <- struct{}{}
				return
			default:
				time.Sleep(10 * time.Millisecond)
			}
		}
	}()
	return
}
Example #5
0
func (l *leds) OnClick(button string) {
	totalClicks := l.btns.Clicks()[button]

	l.hub.Broadcast <- fmt.Sprintf(`{"event":"processing","data":{"button":%s}}`, button)

	c := &serial.Config{Name: "/dev/ttyAMA0", Baud: 9600}
	s, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}

	btnNum, err := strconv.Atoi(button)
	n, err := s.Write([]byte{byte(btnNum), byte(totalClicks)})
	if err != nil {
		log.Fatal(err)
	}

	buf := make([]byte, 128)
	n, err = s.Read(buf)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Response from arduino: %q", buf[:n])

	l.hub.Broadcast <- fmt.Sprintf(`{"event":"click","data":{"button":%s,"count":%d}}`, button, totalClicks)
}
//------------------------------------------------------------------------------
// Purpose: Uploads the firmware to the devices via xmodem.
//
// Param dev_path: The device path to commmunicate on.
// Param firmware_path: The location on disk of the firmware that is to be
//                      installed.
// Param wg : The waitgroup that is needed to sync the goroutines together with
//            all the other instances of this function.
//------------------------------------------------------------------------------
func uploadFirmware(devPath, firmwarePath string, wg *sync.WaitGroup) {
	logDebug("Reading binary file")
	data, err := ioutil.ReadFile(firmwarePath)

	check(err)
	infoLog.Println("Opening", devPath)

	config := &serial.Config{Name: devPath, Baud: 115200, ReadTimeout: time.Second * 5}

	logDebug("Opening serial port")
	port, err := serial.OpenPort(config)
	check(err)

	logDebug("Sending xmodem request to serial")
	_, err = port.Write([]byte("U"))
	check(err)
	verifyWrite(port)

	_, err = port.Write([]byte("u"))
	check(err)
	verifyWrite(port)

	logDebug("Done sending xmodem request to serial")

	startTime := time.Now()
	infoLog.Println("Starting XMODEM transfer for", devPath)
	check(xmodem.ModemSend(port, data))
	infoLog.Println("Finished XMODEM transfer for", devPath, "in", time.Since(startTime))
	wg.Done()
}
Example #7
0
func changeGPSBaudRate(config *serial.Config, newRate int) error {
	if config.Baud == newRate {
		return nil
	}

	p, err := serial.OpenPort(config)
	if err != nil {
		return err
	}
	defer p.Close()

	baud_cfg := createChecksummedNMEASentence([]byte(fmt.Sprintf("PMTK251,%d", newRate)))

	_, err = p.Write(baud_cfg)
	if err != nil {
		return err
	}

	config.Baud = newRate

	valid, err := detectGPS(config)
	if !valid {
		err = fmt.Errorf("Set GPS to new rate, but unable to detect it at that new rate!")
	}
	return err
}
Example #8
0
func main() {
	serialPort := flag.String("port", "", "Port to use for serial communication (COM4, COM5, /path/to/serial/file, etc)")
	baudRate := flag.Int("baud", 115200, "Baud rate for serial port")

	httpHost := flag.String("httpHost", "", "HTTP host")
	httpPort := flag.Int("httpPort", 8752, "HTTP port")
	websocketUrl := flag.String("webUrl", "/scary", "Url for websocket communication")

	flag.Parse()
	if *serialPort == "" {
		log.Fatalln("Serial port is required! Use --help for more info")
	}

	c := &serial.Config{Name: *serialPort, Baud: *baudRate}
	fmt.Println(c)

	p, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}
	// pr, pw := io.Pipe()
	server := &Server{From: p}
	server.init()

	go server.keepAlive()
	go server.proxy()
	// go testCommands(pw)

	log.Printf("Proxying from serial port %s to websocket url %s:%d%s \n", *serialPort, *httpHost, *httpPort, *websocketUrl)
	http.HandleFunc(*websocketUrl, server.handleClientConnection)
	err = http.ListenAndServe(fmt.Sprintf("%s:%d", *httpHost, *httpPort), nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
Example #9
0
func (acq *Acquisition) connectArduinoSerialBT() {
	// config the comm port for serial via BT
	commPort := &serial.Config{Name: commDevName, Baud: bauds}
	// open the serial comm with the arduino via BT
	acq.serialPort, _ = serial.OpenPort(commPort)
	//defer acq.serialPort.Close()
	log.Printf("Open serial device %s", commDevName)
}
Example #10
0
// Open is used to open serial ports of the device. This should be used first.
// The method returns error if open was not succeed, i.e. if device is absent.
func (d *Device) Open() (err error) {
	cmdPortCfg := serial.Config{
		Name: d.CommandPort,
		Baud: BaudRate,
	}
	notifyPortCfg := serial.Config{
		Name: d.NotifyPort,
		Baud: BaudRate,
	}
	if d.cmdPort, err = serial.OpenPort(&cmdPortCfg); err != nil {
		return
	}
	if d.notifyPort, err = serial.OpenPort(&notifyPortCfg); err != nil {
		return
	}
	return
}
Example #11
0
// Open attempts to detect and run a numato device at the provided location.
func Open(serialName string) (*Numato, error) {
	c := &serial.Config{Name: serialName, Baud: 9600, ReadTimeout: time.Millisecond * 10}
	s, err := serial.OpenPort(c)
	if err != nil {
		return nil, err
	}
	return &Numato{s}, nil
}
Example #12
0
//Setup allows to configure the sensor conexion
func (s *Sensor) Init(c *serial.Config) {
	s.Address = 0xFFFFFFFF
	var err error
	s.port, err = serial.OpenPort(c)
	if err != nil {
		panic(err)
	}
}
func main() {
	log.Printf("Establishing the serial connection...")
	c := &serial.Config{Name: "/dev/ttyACM0", Baud: 9600}
	s, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}

	time.Sleep(2 * time.Second) // needed to give Arduino some time to initialise as it is reset when the port is opened

	cloud, err := NewdbusWrapper("/com/devicehive/cloud", "com.devicehive.cloud")
	if err != nil {
		log.Panic(err)
	}

	cloudHandlers := make(map[string]cloudCommandHandler)

	cloudHandlers["led/on"] = func(p map[string]interface{}) (map[string]interface{}, error) {
		log.Printf("Turning the LED on...")
		_, err := s.Write([]byte("1"))
		return map[string]interface{}{"led": "on"}, err
	}

	cloudHandlers["led/off"] = func(p map[string]interface{}) (map[string]interface{}, error) {
		log.Printf("Turning the LED off...")
		_, err := s.Write([]byte("0"))
		return map[string]interface{}{"led": "off"}, err
	}

	cloud.RegisterHandler("CommandReceived", func(args ...interface{}) {
		id := args[0].(uint32)
		command := args[1].(string)
		params := args[2].(string)

		log.Printf("Got command %d with name \"%s\" and parameters %s", id, command, params)
		var param_data map[string]interface{}
		b := []byte(params)
		json.Unmarshal(b, &param_data)

		//log.Printf("param_data %s", param_data)

		if h, ok := cloudHandlers[command]; ok {
			//At this point the client notifies the cloud about the success/failure of the command
			res, err := h(param_data)

			if err != nil {
				cloud.CloudUpdateCommand(id, fmt.Sprintf("ERROR: %s", err.Error()), nil)
			} else {
				cloud.CloudUpdateCommand(id, "success", res)
			}

		} else {
			log.Printf("Unhandled command: %s", command)
		}
	})

	select {}
}
Example #14
0
// Open opens a serial port to the undelying device
func (c *Conn) Open() error {
	p, err := serial.OpenPort(&c.device)
	if err != nil {
		return err
	}
	c.port = p
	c.isOpen = true
	return nil
}
Example #15
0
// NewAdaptor creates a neurosky adaptor with specified port
func NewAdaptor(port string) *Adaptor {
	return &Adaptor{
		name: "Neurosky",
		port: port,
		connect: func(n *Adaptor) (io.ReadWriteCloser, error) {
			return serial.OpenPort(&serial.Config{Name: n.Port(), Baud: 57600})
		},
	}
}
func NewComClient(ComName string, ComBaudRate int) (*comClient, error) {
	c := comClient{}
	var err error
	c.com, err = serial.OpenPort(&serial.Config{Name: ComName, Baud: ComBaudRate})
	if err != nil {
		return nil, err
	}
	return &c, nil
}
Example #17
0
func (s SerialReader) newSerialConnection() io.ReadWriteCloser {
	serialConfig := &serial.Config{Name: s.Device, Baud: int(s.BaudRate)}
	serialPort, err := serial.OpenPort(serialConfig)
	if err != nil {
		log.Fatalf("FATAL newSerialConnection(): %s", err)
	}

	return serialPort
}
Example #18
0
// NewAdaptor creates a new mavlink adaptor with specified port
func NewAdaptor(port string) *Adaptor {
	return &Adaptor{
		name: "Mavlink",
		port: port,
		connect: func(port string) (io.ReadWriteCloser, error) {
			return serial.OpenPort(&serial.Config{Name: port, Baud: 57600})
		},
	}
}
Example #19
0
func InitModem(ComPort string, BaudRate int) (err error) {
	m = &modem{ComPort: ComPort, BaudRate: BaudRate}
	config := &serial.Config{Name: m.ComPort, Baud: m.BaudRate, ReadTimeout: time.Second}
	m.Port, err = serial.OpenPort(config)
	if err != nil {
		return fmt.Errorf("InitModem: Failed to open port. %s", err.Error())
	}
	return nil
}
Example #20
0
// New returns an SMSClient
func New(name string, baud int, routes []byte) (*SMSClient, error) {
	var err error
	sc := new(SMSClient)
	sc.Port, err = serial.OpenPort(&serial.Config{Name: name, Baud: baud, ReadTimeout: 3})
	if err != nil {
		return nil, err
	}
	sc.Routing = LoadRouter(routes)
	return sc, nil
}
Example #21
0
func Open(c *Config) (*IM920, error) {
	t := (1000 * 200 * 8 / defaultBps) * time.Millisecond
	sc := &serial.Config{Name: c.Name, Baud: defaultBps, ReadTimeout: t}
	s, err := serial.OpenPort(sc)
	if err != nil {
		return &IM920{}, fmt.Errorf("error: OpenPort failed: %s", err)
	}

	return &IM920{s: s, m: new(sync.Mutex), readTimeout: c.ReadTimeout, rcvedData: list.New()}, nil
}
// Start Gateway on a COM port interface to service single protocol Client.
func (com *comGateway) ServeCOM() error {
	comPort, err := serial.OpenPort(com.comConfig)
	if err != nil {
		return err
	}

	log.Println("Listening on", com.comConfig.Name)
	com.Listen(comPort)
	return errors.New("COM Port Lost")
}
Example #23
0
// Watersensor starts listening for data from Arduino on Serial port.
func Watersensor(serialPort string, baud int, timeout time.Duration) {
	c := &serial.Config{Name: serialPort, Baud: baud, ReadTimeout: time.Second * timeout}
	s, err := serial.OpenPort(c)
	check(err)
	for {
		data, err := prettifyData(s)
		check(err)
		check(write(dataFile, data))
	}
}
Example #24
0
func OpenSerial() error {
	c = new(serial.Config)
	c.Baud = 115200
	c.Name = "COM1"
	c.ReadTimeout = time.Millisecond * 200
	var err error
	s = new(serial.Port)
	s, err = serial.OpenPort(c)
	return err
}
Example #25
0
func initGPSSerial() bool {
	serialConfig = &serial.Config{Name: "/dev/ttyACM0", Baud: 9600}
	p, err := serial.OpenPort(serialConfig)
	if err != nil {
		log.Printf("serial port err: %s\n", err.Error())
		return false
	}
	serialPort = p
	return true
}
Example #26
0
// Monitor serial output channel, send to serial port.
func serialOutWatcher() {
	// Check every 30 seconds for a serial output device.
	serialTicker := time.NewTicker(30 * time.Second)

	serialDev := "/dev/serialout0" //FIXME: This is temporary. Only one serial output device for now.

	for {
		select {
		case <-serialTicker.C:
			if _, err := os.Stat(serialDev); !os.IsNotExist(err) { // Check if the device file exists.
				var thisSerialConn serialConnection
				// Check if we need to start handling a new device.
				if val, ok := globalSettings.SerialOutputs[serialDev]; !ok {
					newSerialOut := serialConnection{DeviceString: serialDev, Baud: 38400}
					log.Printf("detected new serial output, setting up now: %s. Default baudrate 38400.\n", serialDev)
					if globalSettings.SerialOutputs == nil {
						globalSettings.SerialOutputs = make(map[string]serialConnection)
					}
					globalSettings.SerialOutputs[serialDev] = newSerialOut
					saveSettings()
					thisSerialConn = newSerialOut
				} else {
					thisSerialConn = val
				}
				// Check if we need to open the connection now.
				if thisSerialConn.serialPort == nil {
					cfg := &serial.Config{Name: thisSerialConn.DeviceString, Baud: thisSerialConn.Baud}
					p, err := serial.OpenPort(cfg)
					if err != nil {
						log.Printf("serialout port (%s) err: %s\n", thisSerialConn.DeviceString, err.Error())
						break // We'll attempt again in 30 seconds.
					} else {
						log.Printf("opened serialout: Name: %s, Baud: %d\n", thisSerialConn.DeviceString, thisSerialConn.Baud)
					}
					// Save the serial port connection.
					thisSerialConn.serialPort = p
					globalSettings.SerialOutputs[serialDev] = thisSerialConn
				}
			}

		case b := <-serialOutputChan:
			if val, ok := globalSettings.SerialOutputs[serialDev]; ok {
				if val.serialPort != nil {
					_, err := val.serialPort.Write(b)
					if err != nil { // Encountered an error in writing to the serial port. Close it and set Serial_out_enabled.
						log.Printf("serialout (%s) port err: %s. Closing port.\n", val.DeviceString, err.Error())
						val.serialPort.Close()
						val.serialPort = nil
						globalSettings.SerialOutputs[serialDev] = val
					}
				}
			}
		}
	}
}
Example #27
0
// connect to either a net port for telnet use, or to a serial device
func connect(name string) (io.ReadWriter, error) {
	if isNetPort(name) {
		return net.Dial("tcp", name)
	}

	config := serial.Config{Name: *port, Baud: *baud}
	if *upload != "" {
		config.Parity = serial.ParityEven
	}
	return serial.OpenPort(&config)
}
Example #28
0
func InitComms() (s *serial.Port) {
	c := &serial.Config{Name: "/dev/cu.usbserial-AH01NGJJ", Baud: 19200}
	s, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Serial port initialized")

	return
}
Example #29
0
func (device *Device) Connect() {
	conf := &serial.Config{Name: device.config.Path, Baud: device.config.Baud}
	s, err := serial.OpenPort(conf)
	if err != nil {
		log.Fatal(err)
	}
	device.serialPort = s
	err = device.Reset()
	if err != nil {
		log.Fatal(err)
	}
}
Example #30
0
File: wmc.go Project: Deadroad/wmc
func openSerial() *serial.Port {
	//c := &serial.Config{Name: "/dev/ttyUSB0", Baud: 115200}
	c := &serial.Config{Name: viper.GetString("serial"), Baud: 115200, ReadTimeout: time.Second * 1}
	s, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}

	flushSerial(*s)

	return s
}