python serial_to_network.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python serial_to_network.py相关的知识,希望对你有一定的参考价值。

import serial
import socket
import argparse
import sys

from time import sleep

NEWLINE = "\r\n"

def connect_tcp(sock, target):
	connected = False
	while not connected:
		try:
			sock.connect(target)
			connected = True
		except Exception, e:
			sys.stderr.write("Unable to connect to target host %s:%s: %s\n" % (
				target[0], target[1], e))
			sleep(5)

if __name__ == "__main__":
	p = argparse.ArgumentParser()
	p.add_argument("com_port")
	p.add_argument("target_host")
	p.add_argument("target_port", type=int)
	p.add_argument("--baud", default=9600, type=int)
	p.add_argument("--strip_newlines", action="store_true")
	p.add_argument("--tcp", action="store_true")

	args = p.parse_args()

	ser = serial.Serial()
	ser.port = args.com_port
	ser.baudrate = args.baud

	sock_type = socket.SOCK_STREAM if args.tcp else socket.SOCK_DGRAM
	sock = socket.socket(socket.AF_INET, sock_type)

	while not ser.isOpen():
		try:
			ser.open()
		except (serial.SerialException, OSError), e:
			sys.stderr.write("Could not open serial port: %s\n" % e)
			sleep(1)

	if args.tcp:
		connect_tcp(sock, (args.target_host, args.target_port))
		sock.setblocking(False)

	while True:
		try:
			data = ""
			while NEWLINE not in data:
				data = data + ser.read(1)

			if args.strip_newlines:
				data = data.strip(NEWLINE)

			sys.stderr.write(".")
			if args.tcp:
				try:
					sock.send(data)
				except socket.error, e:
					print "Error sending packet to target via TCP: %s" % e.strerror
					sleep(1)
					print "Reconnecting.."
					sock.close()
					connect_tcp(sock, (args.target_host, args.target_port))
			else:
				try:
					sock.sendto(data, (args.target_host, args.target_port))
				except socket.error, e:
					print "Error sending packet to target via UDP: %s" % e.strerror
					sleep(1)
		except Exception, e:
			print "Unhandled error: %s" % e
			sleep(5)

以上是关于python serial_to_network.py的主要内容,如果未能解决你的问题,请参考以下文章

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python