Advertisement
Guest User

touchmy.py

a guest
Jan 8th, 2011
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.05 KB | None | 0 0
  1. import serial
  2. import sys
  3. import Xlib
  4. import Xlib.display
  5. import time
  6.  
  7. #requirements:
  8. # linux (or manually remove xlib and put in win32 equivalent
  9. # load extmod in your xorg.conf modules
  10. # python-serial
  11. # python-xlib
  12.  
  13. #MODIFY THE NEXT LINE TO REFLECT THE CORRECT SERIAL PORT NUMBER!
  14. port=3
  15.  
  16. #set this variable to [] and the calibration will run
  17. calibration=[32591, 32638, 32603, 32639, 8196, 8009]
  18.  
  19. s = serial.Serial(port)
  20. s.timeout=1
  21.  
  22. MOUSE_DOWN = 0x80
  23. MOUSE_HELD = 0x81
  24. MOUSE_UP = 0x82
  25.  
  26. display = Xlib.display.Display()
  27. screen = display.screen()
  28.  
  29. def mouse_down():
  30.         Xlib.ext.xtest.fake_input(display,Xlib.X.ButtonPress,1)
  31.         display.sync()
  32.  
  33. def mouse_up():
  34.         Xlib.ext.xtest.fake_input(display,Xlib.X.ButtonRelease,1)
  35.         display.sync()
  36.  
  37. def mouse_move(x,y):
  38.         screen.root.warp_pointer(x,y)
  39.         display.sync()
  40.  
  41. def wait_for_quiet():
  42.         '''Waits for the touchscreen to stop sending data'''
  43.         f = ''
  44.         while True:
  45.                 f = s.read(1)
  46.                 if f == None or f == '':
  47.                         sys.stdout.write('\n')
  48.                         break
  49.  
  50. def get_touched():
  51.         '''Get a valid touch from the touchscreen'''
  52.         touch = []
  53.         while touch == []:
  54.                 try:
  55.                         e = ord(s.read(1))
  56.                         if (e & 0x80) == 0:
  57.                                 print "out of sync..."
  58.                                 continue
  59.                         u1 = ord(s.read(1))
  60.                         x = ord(s.read(1))
  61.                         touch_x = (x<<8 | u1)
  62.                         u2 = ord(s.read(1))
  63.                         y = ord(s.read(1))
  64.                         touch_y = (y<<8 | u2)
  65.                         touch = (e,touch_x,touch_y)
  66.                 except KeyboardInterrupt:
  67.                         raise
  68.                 except:
  69.                         pass
  70.         return touch
  71.  
  72. def do_init():
  73.         '''Wait for the touchscreen to become quiet and let the user know they can start using it'''
  74.         print("Initializing touchscreen... (Don't touch it!)")
  75.         wait_for_quiet()
  76.         print("Touchscreen initialized.  (Go ahead and touch it!)")
  77.  
  78. def do_fancy_callibration():
  79.         smallX = None
  80.         bigX = None
  81.         smallY = None
  82.         bigY = None
  83.         sBigX = None
  84.         sBigY = None
  85.         biggest_possible_x = 9000
  86.         biggest_possible_y = 9000
  87.         print("Drag the stylus from the center of the screen into each corner.  You will 30 seconds (from the time the first touch is registered) to get some initial values, if this is successful, then a new timer will start and when the values have stabillized for 10 seconds, calibration will end.  (You may need to tap the screen again to finish calibration)")
  88.         initial_time = time.time()
  89.         good_values = False
  90.         last_change = time.time()
  91.         o = get_touched()
  92.         while time.time() - initial_time < 30:
  93.                 if good_values and time.time() - last_change > 10:
  94.                         break
  95.  
  96.                 e = get_touched()
  97.                 if e[2]!=o[2] or e[1] !=o[1]:
  98.                         if e[2] < biggest_possible_y:
  99.                                 if sBigY == None:
  100.                                         sBigY = e[2]
  101.                                         last_change = time.time()
  102.                                 if e[2] > sBigY:
  103.                                         sBigY = e[2]
  104.                                         last_change = time.time()
  105.  
  106.                         if e[1] < biggest_possible_x:
  107.                                 if sBigX == None:
  108.                                         sBigX = e[1]
  109.                                         last_change = time.time()
  110.                                 if e[1] > sBigX:
  111.                                         sBigX = e[1]
  112.                                         last_change = time.time()
  113.  
  114.                         if e[2] > biggest_possible_y:
  115.                                 if bigY == None:
  116.                                         bigY = e[2]
  117.                                         last_change = time.time()
  118.                                 if smallY == None:
  119.                                         smallY = e[2]
  120.                                         last_change = time.time()
  121.                                 if e[2] < smallY:
  122.                                         smallY = e[2]
  123.                                         last_change = time.time()
  124.                                 elif e[2] > bigY:
  125.                                         bigY = e[2]
  126.                                         last_change = time.time()
  127.  
  128.                         if e[1] > biggest_possible_x:
  129.                                 if bigX == None:
  130.                                         bigX=e[1]
  131.                                         last_change = time.time()
  132.                                 if smallX == None:
  133.                                         smallX = e[1]
  134.                                         last_change = time.time()
  135.  
  136.                                 if e[1] < smallX:
  137.                                         smallX = e[1]
  138.                                         last_change = time.time()
  139.                                 elif e[1] > bigX:
  140.                                         bigX = e[1]
  141.                                         last_change = time.time()
  142.  
  143.                         if smallX != None and smallY != None and sBigX != None and sBigY != None and bigX != None and bigY != None:
  144.                                 print("Good values acquired, stop once you've visited the corners.  Then wait 10 seconds and tap the screen.")
  145.                                 good_values = True
  146.                 o = e
  147.  
  148.         if not good_values: print("Calibraion failed!")
  149.         else: print("Calibration complete!")
  150.  
  151.         print [ smallX, bigX, smallY, bigY, sBigX, sBigY ]
  152.         return [ smallX, bigX, smallY, bigY, sBigX, sBigY ]
  153.  
  154. def touch_to_screen(touch,calibration):
  155.         #not sure if the resolution changes then it will be reflected in the screen object, might have to keep fetching a new screen or something...
  156.         res_x = float(screen['width_in_pixels'])
  157.         res_y = float(screen['height_in_pixels'])
  158.         return [ touch[0], float(touch[1]) / float(calibration[4]) * res_x, float(touch[2]) / float(calibration[5]) * res_y ]
  159.  
  160. def get_good_touch(calibration):
  161.         '''Returns a touch event within the calibrated area'''
  162.  
  163.         while True:
  164.                 event = get_touched()
  165.                 if event[1] >= calibration[0] and event[1] <= calibration[1]:
  166.                         event = [ event[0], event[1] - calibration[0] , event[2] ]
  167.                 elif event[1] >= 0 and event[1] <= calibration[4]:
  168.                         event = [ event[0], event[1] + calibration[1] - calibration[0], event[2] ]
  169.                 else:
  170.                         #bad X value
  171.                         print("Bad X value for calibration range: %d" % event[1])
  172.                         continue
  173.  
  174.                 if event[2] >= calibration[2] and event[2] <= calibration[3]:
  175.                         event = [ event[0], event[1], event[2] - calibration[2] ]
  176.                 elif event[2] >= 0 and event[2] <= calibration[5]:
  177.                         event = [ event[0], event[1], event[2] + calibration[3] - calibration[2] ]
  178.                 else:
  179.                         #bad Y value
  180.                         print("Bad Y value for calibration range: %d" % event[2])
  181.                         continue
  182.                 break
  183.         return event
  184.  
  185. def save_calibration(calibration):
  186.         '''Modifies this script to include saved calibration data'''
  187.         file = open(sys.argv[0],'r+w')
  188.         lines = file.readlines()
  189.         replace_line = -1
  190.         for i in range(0,len(lines)):
  191.                 if lines[i].startswith('calibration='):
  192.                    replace_line = i
  193.  
  194.         file.seek(0)
  195.         if replace_line == -1:
  196.                 print("Calibration line not found in script!  Unable to save calibration data!")
  197.         else:
  198.                 for i in range(0, len(lines)):
  199.                         if i != replace_line:
  200.                                 file.write(lines[i])
  201.                         else:
  202.                                 file.write('calibration = %s' % calibration)
  203.                 print("Calibration data saved to script.")
  204.         file.close()
  205.  
  206. if __name__ == "__main__":
  207.         do_init()
  208.         if calibration == []:
  209.                 calibration = do_fancy_callibration()
  210.                 save_calibration(calibration)
  211.         while True:
  212.                 touch = get_good_touch(calibration)
  213.                 touch = touch_to_screen(touch,calibration)
  214.                 if touch[0] == MOUSE_DOWN:
  215.                         mouse_move(touch[1], touch[2])
  216.                         mouse_down()
  217.                 elif touch[0] == MOUSE_HELD:
  218.                         mouse_move(touch[1], touch[2])
  219.                 elif touch[0] == MOUSE_UP:
  220.                         mouse_move(touch[1], touch[2])
  221.                         mouse_up()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement