Esempio n. 1
0
func configureWifi() {

	options := serial.OpenOptions{
		PortName:        serialPort,
		BaudRate:        115200,
		DataBits:        8,
		StopBits:        1,
		MinimumReadSize: 1,
	}

	s, err := serial.Open(options)
	if err != nil {
		log.Println("No device connected at", serialPort)
		os.Exit(0)
	}
	// Clean up
	defer s.Close()

	// Send script
	var configScript string = `
var wifi = require("Wifi");	
wifi.stopAP();
wifi.connect("%s", {password: "******"}, function(){
	console.log("Connected");
	console.log(wifi.getIP().ip);
});
wifi.save();
`
	send := fmt.Sprintf(configScript, username, password)
	_, err = s.Write([]byte(send))
	if err != nil {
		log.Println("Unable to write to connected device")
		os.Exit(0)
	}

	// Handle terminal output
	reader := bufio.NewReader(s)
	readCount := 0
	go func() {
		// Read buffer to terminal
		for {
			response, _ := reader.ReadBytes('\n')
			responseString := stripBytes(response)
			if readCount == 1 {
				log.Println("IP address:", responseString)
				os.Exit(0)
			}
			if responseString == "Connected" {
				log.Println("Successfully connected to Wifi")
				readCount++
			}
		}
	}()
	select {}
}
Esempio n. 2
0
func main() {
	options := serial.OpenOptions{
		PortName:        "/dev/ttyUSB0",
		BaudRate:        9600,
		DataBits:        8,
		StopBits:        1,
		ParityMode:      serial.PARITY_NONE,
		MinimumReadSize: 4,
	}

	port, err := serial.Open(options)
	if err != nil {
		log.Fatalf("serial.Open: %v", err.Error())
	}

	buffer := make([]byte, 12)
	_, err = io.ReadAtLeast(port, buffer, 12)
	if err != nil {
		log.Fatalf("io.ReadAtLeast: %v", err.Error())
	}

	log.Infof("Data read: %+v", buffer)
}
Esempio n. 3
0
func openSerial(b []byte) ([]byte, bool, error) {
	options := serial.OpenOptions{
		PortName:        "/dev/ttyACM0",
		BaudRate:        9600,
		DataBits:        8,
		StopBits:        1,
		MinimumReadSize: 4,
	}
	port, err := serial.Open(options)
	if err != nil {
		panic(err)
	}
	defer port.Close()

	port.Write(b)
	if err != nil {
		panic(err)
	}

	time.Sleep(1000000)

	reader := bufio.NewReaderSize(port, 4096)
	return reader.ReadLine()
}
Esempio n. 4
0
func main() {
	fmt.Println("Go serial test")
	port := flag.String("port", "", "serial port to test (/dev/ttyUSB0, etc)")
	baud := flag.Uint("baud", 115200, "Baud rate")
	txData := flag.String("txdata", "", "data to send in hex format (01ab238b)")
	even := flag.Bool("even", false, "enable even parity")
	odd := flag.Bool("odd", false, "enable odd parity")
	rs485 := flag.Bool("rs485", false, "enable RS485 RTS for direction control")
	rs485HighDuringSend := flag.Bool("rs485_high_during_send", false, "RTS signal should be high during send")
	rs485HighAfterSend := flag.Bool("rs485_high_after_send", false, "RTS signal should be high after send")
	stopbits := flag.Uint("stopbits", 1, "Stop bits")
	databits := flag.Uint("databits", 8, "Data bits")
	chartimeout := flag.Uint("chartimeout", 100, "Inter Character timeout (ms)")
	minread := flag.Uint("minread", 0, "Minimum read count")
	rx := flag.Bool("rx", false, "Read data received")

	flag.Parse()

	if *port == "" {
		fmt.Println("Must specify port")
		usage()
	}

	if *even && *odd {
		fmt.Println("can't specify both even and odd parity")
		usage()
	}

	parity := serial.PARITY_NONE

	if *even {
		parity = serial.PARITY_EVEN
	} else if *odd {
		parity = serial.PARITY_ODD
	}

	options := serial.OpenOptions{
		PortName:               *port,
		BaudRate:               *baud,
		DataBits:               *databits,
		StopBits:               *stopbits,
		MinimumReadSize:        *minread,
		InterCharacterTimeout:  *chartimeout,
		ParityMode:             parity,
		Rs485Enable:            *rs485,
		Rs485RtsHighDuringSend: *rs485HighDuringSend,
		Rs485RtsHighAfterSend:  *rs485HighAfterSend,
	}

	f, err := serial.Open(options)

	if err != nil {
		fmt.Println("Error opening serial port: ", err)
		os.Exit(-1)
	} else {
		defer f.Close()
	}

	if *txData != "" {
		txData_, err := hex.DecodeString(*txData)

		if err != nil {
			fmt.Println("Error decoding hex data: ", err)
			os.Exit(-1)
		}

		fmt.Println("Sending: ", hex.EncodeToString(txData_))

		count, err := f.Write(txData_)

		if err != nil {
			fmt.Println("Error writing to serial port: ", err)
		} else {
			fmt.Printf("Wrote %v bytes\n", count)
		}

	}

	if *rx {
		for {
			buf := make([]byte, 32)
			n, err := f.Read(buf)
			if err != nil {
				if err != io.EOF {
					fmt.Println("Error reading from serial port: ", err)
				}
			} else {
				buf = buf[:n]
				fmt.Println("Rx: ", hex.EncodeToString(buf))
			}
		}
	}
}
Esempio n. 5
0
func main() {
	var targetFile, device string

	//Banner
	colorLog("! Espruingo v"+appVersion, "blue")

	// Handle arguments
	flag.Parse()
	if len(flag.Args()) < 1 {
		colorLog("! Usage: espruingo <target file> <port name>", "red")
		os.Exit(0)
	}
	if len(flag.Args()) < 2 {
		colorLog("! Please provide the <port name> argument", "red")
		os.Exit(0)
	} else {
		device = flag.Args()[1]
	}
	targetFile = flag.Args()[0]

	// Set up connection
	options := serial.OpenOptions{
		PortName:        device,
		BaudRate:        115200,
		DataBits:        8,
		StopBits:        1,
		MinimumReadSize: 1,
	}

	s, err := serial.Open(options)
	if err != nil {
		colorLog("! No Espruino connected at "+device+"..", "red")
		os.Exit(0)
	}
	// Clean up
	defer s.Close()

	// Connected, so say so
	colorLog("! Espruino connected..", "green")
	ct.Foreground(ct.Blue, false)

	// Initialise watcher for targetFile
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	done := make(chan bool)

	// Clean up
	defer watcher.Close()

	// Monitor target file for changes
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					// File has changed, read it, send a reset() to Espurino and send the file line by line
					_, err = s.Write([]byte("\x03reset();\n"))
					colorLog("< Writing to board", "blue")

					// Open and scan file
					fContents := bytes.NewBuffer(nil)
					f, err := os.Open(targetFile)
					if err != nil {
						colorLog("! Target file could not be opened for reading..", "red")
						os.Exit(0)
						log.Fatal(err)
					}
					io.Copy(fContents, f)
					f.Close()

					// This is our script
					script := string(fContents.Bytes())

					// Load modules
					script = loadModules(script)

					// Minify script
					script = minifyScript(script)

					// Write to board
					script = "echo(0)\n" + script + "echo(1)\n"
					_, err = s.Write([]byte(script))
					if err != nil {
						colorLog("! Unable to write to Esrpuino..", "red")
						os.Exit(0)
						log.Fatal(err)
					}

				}
			case err = <-watcher.Errors:
				colorLog("! Unexpected error..", "red")
				os.Exit(0)
				log.Fatal(err)
			}
		}
	}()

	// Handle terminal output
	reader := bufio.NewReader(s)
	go func() {
		// Read buffer to terminal
		for {
			time.Sleep(time.Second / 100)
			reply, err := reader.ReadBytes('\n')

			n := len(reply)
			limit := n - 1
			if err != nil {
				colorLog("! Espruino disconnected..", "red")
				os.Exit(0)
			}

			output := cleanConsoleOutput(string(reply[:limit]))
			if !strings.Contains(output, "Console Moved") { // Adds nothing, remove it
				if output != "." && output != "" && output != "echo(0)" {
					colorLog("> "+output, "black")
				}
			}
		}
	}()

	// Add targetFile to watcher
	err = watcher.Add(targetFile)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}
Esempio n. 6
0
File: main.go Progetto: nocd5/serial
func main() {
	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.ListComPorts {
		listComPorts()
		os.Exit(0)
	}

	if opts.PortName == "" || opts.BaudRate == 0 {
		fmt.Fprintln(os.Stderr, "the required flags `/b, /baud' and `/p, /port' were not specified")
		os.Exit(1)
	}

	var parityMode serial.ParityMode
	switch opts.ParityMode {
	case "none":
		parityMode = serial.PARITY_NONE
	case "odd":
		parityMode = serial.PARITY_ODD
	case "even":
		parityMode = serial.PARITY_EVEN
	default:
		fmt.Fprintf(os.Stderr, "Invalid ParityMode: %s\n", opts.ParityMode)
		fmt.Fprintf(os.Stderr, "`--parity` should be any one of none/odd/even\n")
		os.Exit(1)
	}

	options := serial.OpenOptions{
		PortName:   opts.PortName,
		BaudRate:   opts.BaudRate,
		DataBits:   opts.DataBits,
		ParityMode: parityMode,
		StopBits:   opts.StopBits,
	}

	port, err := serial.Open(options)
	defer port.Close()
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		buf := make([]byte, 128)
		for {
			n, err := port.Read(buf)
			if err != nil {
				log.Fatal(err)
			}
			if opts.RxBin {
				for i := 0; i < n; i++ {
					fmt.Fprintf(os.Stdout, "0x%02X ", buf[i])
				}
			} else {
				if n > 0 {
					fmt.Fprintf(os.Stdout, "%s", buf[:n])
				}
			}
		}
	}()

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		var bytes []byte
		if opts.TxBin {
			if bytes, err = getBytes(scanner.Text()); err != nil {
				log.Println(err)
			}
		} else {
			bytes = []byte(scanner.Text())
		}
		if _, err := port.Write(bytes); err != nil {
			log.Fatal(err)
		}
	}
}