Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. import argparse
  2. import asyncio
  3. import colored
  4. import serial
  5. from serial.tools import list_ports
  6. import sys
  7. import uuid
  8. import websockets
  9.  
  10.  
  11. parser = argparse.ArgumentParser(
  12. description='Listen for finger game players and control hardware.',
  13. )
  14. parser.add_argument(
  15. '--server',
  16. dest='server_address',
  17. action='store',
  18. default='localhost:9000',
  19. help='The URL and port of the coordinating server to connect to.',
  20. )
  21. parser.add_argument(
  22. '--debug',
  23. dest='debug',
  24. action='store_true',
  25. default=False,
  26. help='Whether to print debugging information or not.',
  27. )
  28. args = parser.parse_args()
  29.  
  30.  
  31. VALID_COMMANDS = [
  32. 'BEGIN_TOUCHING_CUP',
  33. 'STOPPED_TOUCHING_CUP',
  34. 'HEALTH_CHECK',
  35. ]
  36. BAUD_RATE = 9600
  37.  
  38.  
  39. def log(message, color):
  40. color_code = {
  41. 'danger': 13,
  42. 'good': 40,
  43. 'info': 6,
  44. }.get(color, 9)
  45. print(colored.stylize(message, colored.bg(color_code)))
  46.  
  47. def find_device():
  48. arduino_devices = []
  49. for device in list_ports.comports():
  50. if 'arduino' in device.description.lower() or (device.manufacturer and 'arduino' in device.manufacturer.lower()):
  51. arduino_devices.append(device)
  52.  
  53. if len(arduino_devices) > 1:
  54. log(
  55. ' - more than one arduino found: {}'.format(','.join([device.product for device in arduino_devices])),
  56. 'danger',
  57. )
  58.  
  59. if not arduino_devices:
  60. log(
  61. ' - no arduino like devices found.',
  62. 'danger',
  63. )
  64. return
  65.  
  66. return arduino_devices[0]
  67.  
  68. async def client(identifier, arduino):
  69. async with websockets.connect('wss://{}'.format(args.server_address)) as websocket:
  70. await websocket.send('REGISTER:{}'.format(identifier))
  71. while True:
  72. command = await websocket.recv()
  73.  
  74. if command not in VALID_COMMANDS:
  75. if args.debug:
  76. log('Unknown command: {}'.format(command), 'danger')
  77. else:
  78. if command == 'HEALTH_CHECK':
  79. await websocket.send('HEALTHY:{}'.format(identifier))
  80. else:
  81. log(command, 'good')
  82. arduino.write('{}\n'.format(command).encode('utf-8'))
  83.  
  84.  
  85. if __name__ == '__main__':
  86. identifier = str(uuid.uuid4())
  87. arduino = find_device()
  88. if not arduino:
  89. sys.exit(1)
  90.  
  91. try:
  92. arduino = serial.Serial(arduino.device, BAUD_RATE)
  93. log(' - arduino found and connected', 'info')
  94. log(' - connecting client to server as: {}'.format(identifier), 'info')
  95. asyncio.get_event_loop().run_until_complete(client(identifier, arduino))
  96. except websockets.exceptions.ConnectionClosed:
  97. log(' - connection closed by remote', 'danger')
  98. except OSError as error:
  99. log(' - cannot connect to remote server: {}'.format(error), 'danger')
  100. except KeyboardInterrupt:
  101. log(' - disconnecting', 'info')
  102. except serial.serialutil.SerialException:
  103. log(' - cannot connect to arduino, it is in use', 'danger')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement