-
Notifications
You must be signed in to change notification settings - Fork 9
/
pipuck_server.py
executable file
·61 lines (48 loc) · 1.89 KB
/
pipuck_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python3
import asyncio
import websockets
import json
from pipuck.pipuck import PiPuck
pipuck = PiPuck(epuck_version=1)
pipuck.epuck.enable_ir_sensors(True)
async def handler(websocket):
async for packet in websocket:
message = json.loads(packet)
# Process any requests received
reply = {}
send_reply = False
if "check_awake" in message:
reply["awake"] = True
send_reply = True
if "get_ir" in message:
reply["ir"] = pipuck.epuck.ir_reflected
send_reply = True
if "get_battery" in message:
charging, voltage, percentage = pipuck.get_battery_state("epuck")
reply["battery"] = {}
reply["battery"]["voltage"] = voltage
reply["battery"]["percentage"] = int(percentage * 100)
send_reply = True
# Send reply, if requested
if send_reply:
await websocket.send(json.dumps(reply))
if "set_leds_colour" in message:
try:
pipuck.set_leds_colour(message["set_leds_colour"])
except (KeyError, ValueError):
pass
if "set_motor_speeds" in message:
try:
left_in = int(message["set_motor_speeds"]["left"])
right_in = int(message["set_motor_speeds"]["right"])
left_clamped = max(min(left_in, 100), -100)
right_clamped = max(min(right_in, 100), -100)
left_scaled = left_clamped * 5
right_scaled = right_clamped * 5
pipuck.epuck.set_motor_speeds(left_scaled, right_scaled)
except (KeyError, ValueError):
pass
if __name__ == "__main__":
start_server = websockets.serve(ws_handler=handler, host=None, port=80)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()