Advertisement
Guest User

Untitled

a guest
Jul 1st, 2024
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import aiohttp
  2. import asyncio
  3. import logging
  4. from gpiozero import Button
  5.  
  6. # Configure logging
  7. logging.basicConfig(level=logging.INFO)
  8.  
  9. # Define buttons
  10. button1 = Button(17) # Use the correct GPIO pin numbers
  11. button2 = Button(18)
  12.  
  13. async def keep_alive(ws):
  14. while True:
  15. await asyncio.sleep(20)
  16. await ws.ping()
  17. logging.info("Sent keep-alive ping")
  18.  
  19. async def buzzer(ws):
  20. while True:
  21. try:
  22. player = ''
  23. if button1.is_pressed:
  24. logging.info('button1 is pressed')
  25. player = {'id': 'buzzer', 'data': 'player1'}
  26. if ws.closed:
  27. logging.error('WebSocket is closed')
  28. break
  29. await ws.send_json(player)
  30. await asyncio.sleep(1)
  31. elif button2.is_pressed:
  32. logging.info('button2 is pressed')
  33. player = {'id': 'buzzer', 'data': 'player2'}
  34. if ws.closed:
  35. logging.error('WebSocket is closed')
  36. break
  37. await ws.send_json(player)
  38. await asyncio.sleep(1)
  39. else:
  40. await asyncio.sleep(0.1)
  41. except Exception as e:
  42. logging.error(f"Error in buzzer function: {e}")
  43. break
  44.  
  45. async def main():
  46. async with aiohttp.ClientSession() as session:
  47. try:
  48. async with session.ws_connect('ws://rasp-wanexa:8001') as ws:
  49. logging.info('Connected to WebSocket')
  50.  
  51. # Start keep_alive task
  52. asyncio.create_task(keep_alive(ws))
  53.  
  54. # Start buzzer task
  55. asyncio.create_task(buzzer(ws))
  56.  
  57. async for msg in ws:
  58. logging.info(f"Received message: {msg.data}")
  59. except aiohttp.ClientError as e:
  60. logging.error(f"WebSocket connection error: {e}")
  61. except Exception as e:
  62. logging.error(f"Unexpected error: {e}")
  63.  
  64. if __name__ == "__main__":
  65. try:
  66. asyncio.run(main())
  67. except Exception as e:
  68. logging.error(f"Error running main: {e}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement