Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/python
- #
- # Fortement inspiré de bitty.py: serial-to-network multiplexer for Arduino
- #
- #
- # __copyright__ = 'Copyright 2010 by Bill Roy'
- # - Ameliorer le gestion des logs, tar, os.mkdir
- ##############################################################
- import serial, time, socket, commands, traceback, os, sys, glob
- # serial port config
- usbdevice = None
- baud = 57600
- # network config
- port = 32800
- # change below here at your own risk
- serialport = None
- netsocket = None
- netclient = None
- clientaddress = None
- # Net pump thread, and queued interface
- import Queue
- netq = Queue.Queue()
- serialq = Queue.Queue()
- def closeSerialPort():
- global serialport
- if serialport and serialport.isOpen():
- print "Closing: ", serialport.portstr
- try:
- if netclient:
- netclient.send("Closing ")
- netclient.send(serialport.portstr)
- netclient.send("\r\n");
- except: pass
- serialport.close()
- def openSerialPort():
- global serialport, device
- #closeSerialPort()
- # serial port autoconfig
- device = usbdevice # command line overrides auto select
- if not device:
- #devicelist = commands.getoutput("ls /dev/tty.usbserial*")
- devicelist = commands.getoutput("ls /dev/ttyUSB*") # this works on the XO/Fedora
- if devicelist[0] == '/':
- device = devicelist
- # status,output = commands.getstatusoutput("stty --file=%s crtscts -hupcl" %device)
- if not device:
- print "Waiting for device..."
- return False
- print "Connecting to", device, baud, "..."
- if netclient:
- netclient.send('Connecting to ');
- netclient.send(device);
- netclient.send('... ');
- try:
- # two stop bits helps paste-to-terminal not lose characters
- serialport = serial.Serial(device, baud, timeout=0.3, stopbits=serial.STOPBITS_TWO)
- print 'Opened port: ', serialport.portstr
- if netclient:
- netclient.send("connected.\r\n")
- serialq.put("connected.\r\n")
- except:
- print 'Failed to open port'
- if netclient:
- netclient.send("failed.\r\n")
- return False
- return True
- def scan():
- """scan for available ports. return a list of device names."""
- f = glob.glob('/dev/ttyUSB*')
- if len(f) == 0:
- return None
- else:
- return f[0]
- # thread to read and queue serial input
- # assumes opening the serial port is handled elsewhere
- def serialPumpTask(usbdevice, baud):
- while True:
- if serialport and serialport.isOpen():
- try:
- data = serialport.readline(2048);
- #data = filter(lambda x : x != '\r', serialport.read(2048))
- if data: print data
- if data[0:1] == '@':
- serialq.put(data[1:])
- # enable for debug
- # print data
- if data[0:1] == '\7' :
- update_time()
- time.sleep(0.05)
- if data[0:3] == 'LOG' :
- write_logs(data[3:])
- else:
- time.sleep(0.05)
- except:
- print "Exception reading serial port"
- traceback.print_exc()
- closeSerialPort()
- else:
- time.sleep(0.1)
- # send network data to the serial port
- def handleNetworkInput(data):
- global serialport
- try:
- if serialport and serialport.isOpen():
- #serialport.write(data);
- for i in range(len(data)):
- serialport.write(data[i])
- time.sleep(0.05)
- except:
- print "Exception writing serial port"
- traceback.print_exc()
- closeSerialPort()
- # send serial port data to the network socket
- def handleSerialInput(data):
- global netclient
- try:
- if netclient:
- netclient.send(data)
- except:
- print "Exception writing network port"
- traceback.print_exc()
- closeSerialPort()
- # thread to read and queue network input
- def netPumpTask(port, dummy):
- global netsocket, netclient, clientaddress
- netsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- netsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- #socket.setblocking(0)
- netsocket.bind(('', port))
- netsocket.listen(1) # allow no waiting connections
- while True:
- try:
- print "Listening for network connection on", socket.getfqdn(), ':', port, '/', socket.gethostname()
- netclient, clientaddress = netsocket.accept()
- print "Connection from", clientaddress
- netclient.send("g'day from bitty ")
- netclient.send(__version__)
- netclient.send(" -- type 'logout' to disconnect")
- netclient.send("\r\n");
- if netclient:
- netq.put("*START_CLI!")
- serialq.put("connected.\r\n")
- while True:
- if not netclient: break # client went away: go get another one
- while not serialport.isOpen():
- #while not openSerialPort():
- netclient.send("Waiting for device...\r\n");
- time.sleep(0.2);
- while serialport.isOpen():
- if netclient:
- data = netclient.recv(10240)
- if data:
- if data[0:6].find('logout') == 0:
- netclient.send("Disconnected.\r\n");
- netclient.close()
- netclient = None
- #serialport.write("*STOP_CLI!")
- netq.put("*STOP_CLI!")
- #closeSerialPort()
- time.sleep(1.0) # pause to allow disconnect
- break
- else:
- netq.put(data)
- else: time.sleep(0.05)
- else : time.sleep(0.2)
- except:
- print "Exception in net pump"
- traceback.print_exc()
- closeSerialPort()
- def update_time():
- try:
- # tic = time.time() - time.timezone + time.daylight*3600
- tic = time.time() + 3600
- # tic = time.mktime(time.localtime())
- # tics = '*T' + str(tic)[0:10] + ';M1;F17.5;!'
- tics = '*CLOCK;' + str(tic)[0:10] + '!'
- #serialport.write(tics)
- netq.put(tics)
- except: pass
- def write_logs(_data):
- try:
- today = time.strftime("%d.%m.%Y.log", time.localtime())
- timestamp = time.strftime("%H:%M:%S", time.localtime())
- f = open('/home/philippe/domoserver/logs/%s' %today, 'a')
- print >> f, timestamp, _data.strip()
- f.close()
- except: pass
- if __name__ == '__main__':
- import thread
- openSerialPort()
- net_pump_thread = thread.start_new_thread(netPumpTask, (port, 0))
- serial_pump_thread = thread.start_new_thread(serialPumpTask, (usbdevice, baud))
- while True:
- while not netq.empty():
- handleNetworkInput(netq.get())
- netq.task_done()
- while not serialq.empty():
- handleSerialInput(serialq.get())
- serialq.task_done()
- if scan() != device:
- closeSerialPort()
- time.sleep(2)
- openSerialPort()
- time.sleep(0.05)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement