Advertisement
zoroastre74

server.py

Dec 5th, 2011
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.40 KB | None | 0 0
  1. #! /usr/bin/python
  2. #
  3. #       Fortement inspiré de bitty.py: serial-to-network multiplexer for Arduino
  4. #
  5. #
  6. #   __copyright__ = 'Copyright 2010 by Bill Roy'
  7. #   - Ameliorer le gestion des logs, tar, os.mkdir
  8. ##############################################################
  9.  
  10. import serial, time, socket, commands, traceback, os, sys, glob
  11.  
  12. # serial port config
  13. usbdevice = None
  14. baud = 57600
  15.  
  16. # network config
  17. port = 32800
  18.  
  19. # change below here at your own risk
  20. serialport = None
  21. netsocket = None
  22. netclient = None
  23. clientaddress = None
  24.  
  25. # Net pump thread, and queued interface
  26. import Queue
  27. netq = Queue.Queue()
  28. serialq = Queue.Queue()
  29.  
  30. def closeSerialPort():
  31.         global serialport
  32.         if serialport and serialport.isOpen():
  33.                 print "Closing: ", serialport.portstr
  34.                 try:
  35.                         if netclient:
  36.                                 netclient.send("Closing ")
  37.                                 netclient.send(serialport.portstr)
  38.                                 netclient.send("\r\n");
  39.                 except: pass
  40.                 serialport.close()
  41.  
  42. def openSerialPort():
  43.         global serialport, device
  44.         #closeSerialPort()
  45.  
  46.         # serial port autoconfig
  47.         device = usbdevice                                       # command line overrides auto select
  48.         if not device:
  49.                 #devicelist = commands.getoutput("ls /dev/tty.usbserial*")
  50.                 devicelist = commands.getoutput("ls /dev/ttyUSB*")              # this works on the XO/Fedora
  51.        
  52.         if devicelist[0] == '/':
  53.                 device = devicelist
  54. #                status,output = commands.getstatusoutput("stty --file=%s crtscts -hupcl" %device)
  55.         if not device:
  56.                 print "Waiting for device..."
  57.                 return False
  58.  
  59.         print "Connecting to", device, baud, "..."
  60.         if netclient:
  61.                 netclient.send('Connecting to ');
  62.                 netclient.send(device);
  63.                 netclient.send('... ');
  64.  
  65.         try:
  66.                 # two stop bits helps paste-to-terminal not lose characters
  67.                 serialport = serial.Serial(device, baud, timeout=0.3, stopbits=serial.STOPBITS_TWO)
  68.                 print 'Opened port: ', serialport.portstr
  69.                 if netclient:
  70.                         netclient.send("connected.\r\n")
  71.                         serialq.put("connected.\r\n")
  72.         except:
  73.                 print 'Failed to open port'
  74.                 if netclient:
  75.                         netclient.send("failed.\r\n")
  76.                 return False
  77.         return True
  78.  
  79. def scan():
  80.     """scan for available ports. return a list of device names."""
  81.     f = glob.glob('/dev/ttyUSB*')
  82.     if len(f) == 0:
  83.         return None
  84.     else:
  85.         return f[0]
  86.  
  87.  
  88.  
  89. # thread to read and queue serial input
  90. # assumes opening the serial port is handled elsewhere
  91. def serialPumpTask(usbdevice, baud):
  92.         while True:
  93.                 if serialport and serialport.isOpen():
  94.                         try:
  95.                                 data = serialport.readline(2048);
  96.                                 #data = filter(lambda x : x != '\r', serialport.read(2048))
  97.                                 if data: print data
  98.                                 if data[0:1] == '@':
  99.                                         serialq.put(data[1:])
  100.                                         # enable for debug
  101.                                         # print data
  102.                                 if data[0:1] == '\7' :
  103.                                         update_time()
  104.                                         time.sleep(0.05)
  105.                                 if data[0:3] == 'LOG' :
  106.                                         write_logs(data[3:])
  107.                                 else:
  108.                                         time.sleep(0.05)
  109.                         except:
  110.                                 print "Exception reading serial port"
  111.                                 traceback.print_exc()
  112.                                 closeSerialPort()
  113.                 else:
  114.                         time.sleep(0.1)
  115.  
  116. # send network data to the serial port
  117. def handleNetworkInput(data):
  118.         global serialport
  119.         try:
  120.                 if serialport and serialport.isOpen():
  121.                         #serialport.write(data);
  122.                         for i in range(len(data)):
  123.                                 serialport.write(data[i])
  124.                                 time.sleep(0.05)
  125.         except:
  126.                 print "Exception writing serial port"
  127.                 traceback.print_exc()
  128.                 closeSerialPort()
  129.  
  130. # send serial port data to the network socket
  131. def handleSerialInput(data):
  132.         global netclient
  133.         try:
  134.                 if netclient:
  135.                     netclient.send(data)
  136.                
  137.         except:
  138.                 print "Exception writing network port"
  139.                 traceback.print_exc()
  140.                 closeSerialPort()
  141.  
  142. # thread to read and queue network input
  143. def netPumpTask(port, dummy):
  144.  
  145.         global netsocket, netclient, clientaddress
  146.         netsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  147.         netsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  148.         #socket.setblocking(0)
  149.         netsocket.bind(('', port))
  150.         netsocket.listen(1)     # allow no waiting connections
  151.  
  152.         while True:
  153.                 try:
  154.                         print "Listening for network connection on", socket.getfqdn(), ':', port, '/', socket.gethostname()
  155.                         netclient, clientaddress = netsocket.accept()
  156.                         print "Connection from", clientaddress
  157.                         netclient.send("g'day from bitty ")
  158.                         netclient.send(__version__)
  159.                         netclient.send(" -- type 'logout' to disconnect")
  160.                         netclient.send("\r\n");
  161.                         if netclient:
  162.                                 netq.put("*START_CLI!")
  163.                                 serialq.put("connected.\r\n")
  164.  
  165.                         while True:
  166.                                 if not netclient: break         # client went away: go get another one
  167.  
  168.                                 while not serialport.isOpen():
  169.                                 #while not openSerialPort():
  170.                                         netclient.send("Waiting for device...\r\n");
  171.                                         time.sleep(0.2);
  172.  
  173.                                 while serialport.isOpen():
  174.                                         if netclient:
  175.                                                 data = netclient.recv(10240)
  176.                                                 if data:
  177.                                                         if data[0:6].find('logout') == 0:
  178.                                                                 netclient.send("Disconnected.\r\n");
  179.                                                                 netclient.close()
  180.                                                                 netclient = None
  181.                                                                 #serialport.write("*STOP_CLI!")
  182.                                                                 netq.put("*STOP_CLI!")
  183.                                                                 #closeSerialPort()
  184.                                                                 time.sleep(1.0)         # pause to allow disconnect
  185.                                                                 break
  186.                                                         else:
  187.                                                                 netq.put(data)
  188.                                                 else: time.sleep(0.05)
  189.                                         else : time.sleep(0.2)
  190.                 except:
  191.                         print "Exception in net pump"
  192.                         traceback.print_exc()
  193.                         closeSerialPort()
  194.  
  195. def update_time():
  196.     try:
  197. #            tic = time.time() - time.timezone + time.daylight*3600
  198.             tic = time.time() + 3600
  199. #            tic = time.mktime(time.localtime())
  200. #            tics = '*T' + str(tic)[0:10] + ';M1;F17.5;!'
  201.             tics = '*CLOCK;' + str(tic)[0:10] + '!'
  202.             #serialport.write(tics)
  203.             netq.put(tics)
  204.     except: pass
  205.    
  206. def write_logs(_data):
  207.     try:
  208.             today = time.strftime("%d.%m.%Y.log", time.localtime())
  209.             timestamp = time.strftime("%H:%M:%S", time.localtime())
  210.             f = open('/home/philippe/domoserver/logs/%s' %today, 'a')
  211.             print >> f, timestamp, _data.strip()
  212.             f.close()
  213.     except: pass
  214.  
  215. if __name__ == '__main__':
  216.  
  217.         import thread
  218.         openSerialPort()
  219.         net_pump_thread = thread.start_new_thread(netPumpTask, (port, 0))
  220.         serial_pump_thread = thread.start_new_thread(serialPumpTask, (usbdevice, baud))
  221.            
  222.         while True:
  223.                 while not netq.empty():
  224.                         handleNetworkInput(netq.get())
  225.                         netq.task_done()
  226.  
  227.                 while not serialq.empty():
  228.                         handleSerialInput(serialq.get())
  229.                         serialq.task_done()
  230.                        
  231.                 if scan() != device:
  232.                         closeSerialPort()
  233.                         time.sleep(2)
  234.                         openSerialPort()
  235.  
  236.                 time.sleep(0.05)
  237.  
  238.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement