Example #1
0
// Connects to the ARM on the given serial port
func ConnectSerial(port string, baud int) common.Protocol {
	c := &serial.Config{Name: port, Baud: baud}
	if s, err := serial.OpenPort(c); err != nil {
		panic(err)
	} else {
		return SerialProtocol{s}
	}
}
Example #2
0
File: air.go Project: kf8a/airflow
// Send a couple of returns to wake up the controller
func (air AIR) wake() {
	c := serial.Config{Name: air.device, Baud: 9600}
	port, err := serial.OpenPort(&c)
	if err != nil {
		log.Fatal(err)
	}
	defer port.Close()

	for i := 0; i < 5; i++ {
		query := air.address + "\r"
		_, err = port.Write([]byte(query))
		if err != nil {
			log.Fatal(err)
		}
	}
}
Example #3
0
func (ser *SerialChannel) Start() error {
	log.Println("[INFO] Starting Serial")

	cfg := ser.GetConfiguration()
	port := cfg.Port
	baud := cfg.Baud

	c := &serial.Config{Name: port, Baud: int(baud)}
	s, err := serial.OpenPort(c)
	ser.serial = s
	if err == nil {
		buf := ""

		for {
			serialContent := make([]byte, 256)
			_, err := s.Read(serialContent)
			if err != nil {
				log.Fatal(err)
			}

			c := string(serialContent)
			if strings.Index(c, "\n") != -1 {
				str := strings.Split(c, "\n")
				buf += str[0]
				buf = strings.Replace(buf, "\x00", "", -1)

				// Iterate all protocols and call Handle for Buf
				payload := api.NewReadRequest(buf)
				for _, prot := range ser.GetProtocols() {
					go prot.OnRead(payload)
				}

				buf = str[1]
			} else {
				buf += c
			}
		}
	} else {
		log.Print("[ERROR] Unable to start Serial -- ", err)
	}
	return nil
}
Example #4
0
func (noxbox NOXBOX) Sample() (string, error) {
	c := serial.Config{Name: noxbox.device, Baud: 9600}
	port, err := serial.OpenPort(&c)
	if err != nil {
		log.Fatal(err)
	}
	defer port.Close()
	data := noxbox.read(port)
	for data == "" {
		data = noxbox.read(port)
	}
	nox, err := noxbox.parse(data)
	if err != nil {
		return "", err
	}

	message := Message{nox, noxbox.site, time.Now()}
	json_message, err := json.Marshal(message)
	return string(json_message), err
}
Example #5
0
File: air.go Project: kf8a/airflow
func (air AIR) read() string {
	c := serial.Config{Name: air.device, Baud: 9600}
	port, err := serial.OpenPort(&c)
	if err != nil {
		log.Fatal(err)
	}
	defer port.Close()

	query := air.address + "\r"
	_, err = port.Write([]byte(query))
	if err != nil {
		log.Fatal(err)
	}

	reader := bufio.NewReader(port)
	reply, err := reader.ReadBytes('\x0d')
	if err != nil {
		log.Fatal(err)
	}

	return string(reply)
}
Example #6
0
func (s *SerialPort) Open() (err error) {
	if s.opened {
		return nil
	}

	s.port, err = serial.OpenPort(&s.Config)
	if err != nil {
		return err
	}

	if s.ChanPubSub == nil {
		s.ChanPubSub = chanpubsub.New()
	}

	go s.reader()

	if s.Write == nil {
		s.Write = s.writer()
	}

	s.opened = true
	return nil
}
Example #7
0
// Com 接口
func Com(dev string, data string) ([]string, error) {

	c := &serial.Config{Name: dev, Baud: 115200}
	s, e := serial.OpenPort(c)
	if e != nil {
		return make([]string, 0), e
	}
	defer s.Close()

	wd := bufio.NewWriter(s)
	wd.Write([]byte(data + "\r"))
	wd.Flush()

	time.Sleep(1 * time.Second)

	content := make([]string, 0)

	rd := bufio.NewReader(s)
	for {

		line, err := rd.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			break
		}
		content = append(content, Trim(line))
		if strings.Contains(line, "OK") || strings.Contains(line, "ERROR") {
			break
		}

	}

	return content, nil

}
Example #8
0
// Do mouse tracking, must open up serial port directly in order to send steps in realtime as requested
func PerformMouseTracking() {

	fmt.Println("Opening mouse reader")
	mouse := CreateAndStartMouseReader()
	defer mouse.Close()

	fmt.Println("Opening com port")
	c := &serial.Config{Name: "/dev/ttyAMA0", Baud: 57600}
	s, err := serial.OpenPort(c)
	if err != nil {
		panic(err)
	}
	defer s.Close()

	fmt.Println("Left click to exit, Right click to exit and enter X Y location of pen")

	// buffers to use during serial communication
	writeData := make([]byte, 128)
	readData := make([]byte, 1)

	polarSystem := PolarSystemFromSettings()
	previousPolarPos := PolarCoordinate{LeftDist: Settings.StartingLeftDist_MM, RightDist: Settings.StartingRightDist_MM}
	startingPos := previousPolarPos.ToCoord(polarSystem)
	polarSystem.XOffset = startingPos.X
	polarSystem.YOffset = startingPos.Y

	currentPos := Coordinate{X: 0, Y: 0}

	// max distance that can be travelled in one batch
	maxDistance := 64 * (Settings.MaxSpeed_MM_S * TimeSlice_US / 1000000.0)

	// send a -128 to force the arduino to restart and rerequest data
	s.Write([]byte{ResetCommand})
	for stepDataOpen := true; stepDataOpen; {
		// wait for next data request
		n, err := s.Read(readData)
		if err != nil {
			panic(err)
		}
		if n != 1 {
			panic(err)
		}

		if mouse.GetLeftButton() {
			updateSettingsPosition(currentPos, polarSystem)
			return
		} else if mouse.GetRightButton() {
			promptForSettingsPosition(polarSystem)
			return
		}

		mouseX, mouseY := mouse.GetPos()
		mousePos := Coordinate{X: float64(mouseX) / 20.0, Y: float64(mouseY) / 20.0}
		direction := mousePos.Minus(currentPos)
		distance := direction.Len()
		if distance == 0.0 {
			direction = Coordinate{X: 1, Y: 0}
		} else {
			direction = direction.Normalized()
		}
		if distance > maxDistance {
			distance = maxDistance
		}
		//fmt.Println("Got mouse pos", mousePos)

		dataToWrite := int(readData[0])
		for i := 0; i < dataToWrite; i += 2 {

			sliceTarget := currentPos.Add(direction.Scaled(float64(i) * distance / 128.0))
			polarSliceTarget := sliceTarget.ToPolar(polarSystem)

			//fmt.Println("i", i, "pos", currentPos, "target", sliceTarget);

			sliceSteps := polarSliceTarget.
				Minus(previousPolarPos).
				Scaled(StepsFixedPointFactor/Settings.StepSize_MM).
				Ceil().
				Clamp(StepsMaxValue, -StepsMaxValue)
			previousPolarPos = previousPolarPos.
				Add(sliceSteps.Scaled(Settings.StepSize_MM / StepsFixedPointFactor))

			writeData[i] = byte(int8(-sliceSteps.LeftDist))
			writeData[i+1] = byte(int8(sliceSteps.RightDist))
		}
		currentPos = previousPolarPos.ToCoord(polarSystem)

		s.Write(writeData)
	}
}
Example #9
0
// Sends the given stepData to the stepper driver
func WriteStepsToSerial(stepData <-chan int8, pauseOnPenUp bool) {
	if pauseOnPenUp {
		fmt.Println("Pause on PenUp enabled!")
	}

	fmt.Println("Opening com port")
	c := &serial.Config{Name: "/dev/ttyAMA0", Baud: 57600}
	s, err := serial.OpenPort(c)
	if err != nil {
		panic(err)
	}
	defer s.Close()

	// buffers to use during serial communication
	writeData := make([]byte, 128)
	readData := make([]byte, 1)

	previousSend := time.Now()
	var totalSends int = 0
	var byteData int8 = 0

	// send a -128 to force the arduino to restart and rerequest data
	s.Write([]byte{ResetCommand})

	var pauseAfterWrite = false

	for stepDataOpen := true; stepDataOpen; {
		// wait for next data request
		n, err := s.Read(readData)
		if err != nil {
			panic(err)
		}
		if n != 1 {
			panic(err)
		}

		dataToWrite := int(readData[0])
		for i := 0; i < dataToWrite; i += 2 {

			if pauseAfterWrite {
				// want to fill remainder of buffer with 0s before writing it to serial
				writeData[i] = byte(0)
				writeData[i+1] = byte(0)
			} else {
				// even if stepData is closed and empty, receiving from it will return default value 0 for byteData and false for stepDataOpen
				byteData, stepDataOpen = <-stepData
				writeData[i] = byte(byteData)
				byteData, stepDataOpen = <-stepData
				writeData[i+1] = byte(byteData)

				// pause on pen up
				if byteData == PenUpCommand {
					fmt.Println("PenUp...")
					pauseAfterWrite = pauseOnPenUp
				} else if byteData == PenDownCommand {
					fmt.Println("PenDown...")
				}
			}
		}

		totalSends++
		if totalSends >= 100 {
			curTime := time.Now()

			fmt.Println("Sent 100 messages after", curTime.Sub(previousSend))
			totalSends = 0

			previousSend = curTime
		}

		s.Write(writeData)

		if pauseAfterWrite {
			pauseAfterWrite = false

			fmt.Println("Press any key to continue...")
			reader := bufio.NewReader(os.Stdin)
			reader.ReadString('\n')
		}
	}
}
Example #10
0
func main() {
	// common.Init()
	ardupilotmega.Init()

	flag.StringVar(&port, "port", "", "Serial port to connect to")
	flag.IntVar(&baud, "baud", 115200, "Speed of the connection")
	flag.IntVar(&maxPackets, "max", 10, "Quit program after this number of packets")
	flag.DurationVar(&quitAfter, "quitafter", time.Second*3, "Quit program after this duration")
	flag.DurationVar(&timeout, "timeout", time.Second, "Read timeout per packet")
	flag.BoolVar(&debug, "debug", false, "Log everything for debugging")
	flag.Parse()

	if debug {
		mavlink.LogEverything(log.New(os.Stderr, "", log.LstdFlags))
	}

	if port == "" {
		if flag.NArg() > 0 {
			port = flag.Arg(0)
		} else {
			ports := serial.ListPorts()
			if len(ports) == 1 {
				port = ports[0]
			} else {
				fmt.Fprintln(os.Stderr, "Call with -port=PORT")
				flag.PrintDefaults()
				fmt.Fprintln(os.Stderr, "\nAvailable as PORT are:")
				for _, p := range ports {
					fmt.Fprintln(os.Stderr, "  ", p)
				}
				return
			}
		}
	}

	// serialConn, err := serial.OpenDefault(port, serial.Baud(baud), timeout)
	serialConn, err := tarm.OpenPort(&tarm.Config{Name: port, Baud: baud})
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Opened serial port", port)
	defer func() {
		log.Println("Closed serial port", port, "with error", serialConn.Close())
	}()

	//conn := mavlink.NewConnection(serialConn, 99)

	// err = mavlink.Send(serialConn, 0, 0, 0, common.NewHeartbeat())
	// if err != nil {
	// 	log.Println(err)
	// }

	// err = mavlink.Send(serialConn, 0, 0, 0, &common.Ping{})
	// if err != nil {
	// 	log.Println(err)
	// }

	// err = mavlink.Send(serialConn, 0, 0, 0, &common.ParamRequestList{})
	// if err != nil {
	// 	log.Println(err)
	// }

	go func() {
		dry.WaitForStdin("Press any key to quit")
		stop = true
	}()

	time.AfterFunc(quitAfter, func() { stop = true })

	for i := 0; i < maxPackets && !stop; i++ {
		packet, err := mavlink.Receive(serialConn)
		if err == nil {
			log.Println(packet)
		} else {
			log.Println(err)
		}
	}
}