Beispiel #1
0
func setupSerial(device string, baud int) {
	// open the serial
	log.Println("open", device, "at", baud)
	port, err := serial.Open(device, baud)
	if err != nil {
		fmt.Println("open failed:", err)
	}
	defer port.Close()
	log.Println("ready")

	// open the databases
	db, err := sql.Open("mysql", dbconn)
	if err != nil {
		log.Println("can not open databases: ", err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		log.Println("can not connect databbases: ", err)
	}

	// Prepare statement for inserting data
	stmtIns, err := db.Prepare("INSERT INTO tbl_id set id=?")
	if err != nil {
		log.Println("db prepare error:", err)
	}

	stmtUpdate, err := db.Prepare("UPDATE tbl_serial set id=?")
	if err != nil {
		log.Println("db prepare error:", err)
	}

	buf := make([]byte, 512)

	for {
		n, err := port.Read(buf)
		if err != nil {
			log.Println("serial read error:", err)
		}
		// n = the read length
		if n > 0 {
			log.Println(n, ">", string(buf[:n]))
			_, err = stmtIns.Exec(string(buf[:n]))
			if err != nil {
				log.Println("stmtIns exec error:", err)
			}
			_, err = stmtUpdate.Exec(string(buf[:n]))
			if err != nil {
				log.Println("stmtUpdate exec error:", err)
			}
			log.Println("update the db")
		}
	}
}
Beispiel #2
0
func main() {
	device := "COM9"
	baud := 9600

	fmt.Println("open", device, "at", baud)

	port, err := serial.Open(device, baud)

	if err != nil {
		fmt.Println("open failed:", err)
		return
	}

	defer port.Close()

	fmt.Println("ready")

	// display data from serial
	//
	go func() {
		buf := make([]byte, 32)

		for {
			n, err := port.Read(buf)

			if err != nil {
				fmt.Println("serial read error:", err)
				return
			}

			if n > 0 {
				fmt.Println(n, ">", string(buf[:n]))
			}
		}
	}()

	// send user input (by line) to serial
	//
	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		_, err := port.Write([]byte(scanner.Text() + "\n"))

		if err != nil {
			fmt.Println("serial write error:", err)
		}
	}

}
Beispiel #3
0
func setupSerial(device string, baud int) {
	// open the serial
	log.Println("open", device, "at", baud)
	port, err := serial.Open(device, baud)
	if err != nil {
		fmt.Println("open failed:", err)
	}
	defer port.Close()
	log.Println("ready")

	buf := make([]byte, 512)
	var buffer bytes.Buffer
	i := 0

	for {
		i = 0
		buffer.Truncate(0)
		for i != 10 && i < 10 {
			// n = the read length
			n, err := port.Read(buf)
			if err != nil {
				log.Println("serial read error:", err)
			}
			time.Sleep(time.Second)
			log.Println(n, "接收到刷卡信息--> ", string(buf[:n]))
			buffer.Write(buf[:n])
			i += n
		}
		if i != 10 {
			continue
		}
		buffer.Truncate(8)
		buffer.Write([]byte("  "))
		num = buffer.String()
	}
}