Advertisement
Guest User

serialProcess.py

a guest
Sep 29th, 2014
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. from array import *
  2. import serial
  3. import time
  4. import multiprocessing
  5. import sqlite3
  6.  
  7. conn=sqlite3.connect('rover.db')
  8. curs=conn.cursor()
  9.  
  10. class SerialProcess(multiprocessing.Process):
  11.  
  12.     def __init__(self, taskQ, resultQ):
  13.         multiprocessing.Process.__init__(self)
  14.         self.taskQ = taskQ
  15.         self.resultQ = resultQ
  16.         self.usbPort = '/dev/ttyAMA0'
  17.         self.sp = serial.Serial(self.usbPort, 2400, timeout=1)
  18.  
  19.     def close(self):
  20.         self.sp.close()
  21.  
  22.     def sendData(self, data):
  23.         print "sendData start..."
  24.         self.sp.write(data)
  25.         time.sleep(3)
  26.         print "sendData done: " + data
  27.  
  28.     def run(self):
  29.  
  30.         self.sp.flushInput()
  31.  
  32.         while True:
  33.             # look for incoming tornado request
  34.             if not self.taskQ.empty():
  35.                 task = self.taskQ.get()
  36.  
  37.                 # send it to the arduino
  38.         self.sp.write(task)
  39.         print "received from client, sending to radio:  JOYSTICK_X  " + str(ord(task[1])) + "    JOYSTICK_Y:  " + str(ord(task[2]))
  40.  
  41.             # look for incoming serial data
  42.             if (self.sp.inWaiting() > 0):
  43.         receivedArray = bytes()
  44.         while (self.sp.inWaiting()):
  45.             receivedArray = receivedArray + self.sp.read(1)
  46.  
  47.         # encode string to two utf-8 characters (A through P) per byte      
  48.         encoded = bytes()
  49.         index = 0
  50.         while (index < len(receivedArray)):
  51.             encoded += chr(ord(receivedArray[index]) / 16 + 65)
  52.             encoded += chr(ord(receivedArray[index]) % 16 + 65)
  53.             index += 1
  54.         if (len(receivedArray) == 2):
  55.             curs.execute("INSERT INTO pings values((?), (?))", (ord(receivedArray[0]), ord(receivedArray[1])))
  56.             conn.commit()
  57.  
  58.         # send it to tornado
  59.         self.resultQ.put(encoded)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement