-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth_server.py
70 lines (61 loc) · 1.81 KB
/
bluetooth_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
62
63
64
65
66
67
68
69
70
import bluetooth
import picar_4wd as fc
from gpiozero import CPUTemperature
class CarTelemetry:
def __init__(self, speed, distance_traveled, direction, temp):
self.speed = speed
self.distance_traveled = distance_traveled
self.direction = direction
self.temp = temp
def __rep__(self):
return str(self.__dict__)
hostMACAddress = "E4:5F:01:78:14:3C"
backlog = 1
size = 1024
port = 0
power_val = 50
def move(direction):
cpu_temp = CPUTemperature()
temp = cpu_temp.temperature
car_telemetry = CarTelemetry(
speed=power_val,
distance_traveled=0,
direction="Not a valid direction",
temp=temp,
)
if direction == "f":
fc.forward(power_val)
car_telemetry.direction = "Moving forward"
elif direction == "b":
fc.backward(power_val)
car_telemetry.direction = "Moving backward"
elif direction == "l":
fc.turn_left(power_val)
car_telemetry.direction = "Turning left"
elif direction == "r":
fc.turn_right(power_val)
car_telemetry.direction = "Turning right"
elif direction == "s":
fc.stop()
car_telemetry.direction = "stopping the car"
else:
fc.stop()
car_telemetry.direction = "Not a valid direction"
return car_telemetry
print("***starting bluetooth server waiting for command from client***")
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.bind((hostMACAddress, port))
s.listen(backlog)
try:
client, clientInfo = s.accept()
while True:
data = client.recv(size)
print(f"server recv from: {clientInfo} -> {data}")
if data:
res = move(data.decode())
client.send(res.__rep__())
except Exception as Error:
print(Error)
print("Closing socket")
client.close()
s.close()