-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
109 lines (79 loc) · 2.88 KB
/
client.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import socket, machine, time
# Bytes meanings
flag_up_lights_on = b"u" # u - Flag up and lights on
flag_down_lights_off = b"d" # d - Flag down and lights off
flag_up = b"f" # f - Flag up
flag_down = b"c" # c - Flag down
lights_on = b"l" # l - lights on
lights_off = b"m" # m - lights off
class Client():
server_socket = socket.socket()
def __init__(self):
# Servo setup
self.servo_pin = machine.PWM(machine.Pin(12))
self.servo_pin.freq(50)
self.servo_pin.duty(60)
# Button setup
self.button_pin = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
# Led pin setup
self.led_pin = machine.Pin(2, machine.Pin.OUT)
self.led_pin.value(1)
def start(self, ip, port):
if not self.connect(ip, port):
print("Unable to connect...")
print("Exiting game!")
return
print("Connected")
self.gameLoop()
def connect(self, ip, port):
# Returns true, if connected properly
try:
self.server_socket.connect((ip, port))
except:
return False
return True
def gameLoop(self):
print("Starting game")
self.server_socket.setblocking(0)
last_button_value = self.button_pin.value()
try:
while True:
recieve = None
# Recieve instructions from server
try:
recieve = self.server_socket.recv(1)
except:
# Nothing was received
pass
if recieve:
print(recieve)
if recieve == flag_up_lights_on:
self.showFlag()
self.switch_lights_on()
elif recieve == flag_down_lights_off:
self.hideFlag()
self.switch_lights_off()
elif recieve == flag_up:
self.showFlag()
elif recieve == flag_down:
self.hideFlag()
elif recieve == lights_on:
self.switch_lights_on()
elif recieve == lights_off:
self.switch_lights_off()
# If button state has changed, sent info to server
new_button_value = self.button_pin.value()
if last_button_value != new_button_value:
last_button_value = new_button_value
self.server_socket.send(b"p")
print("Button pressed")
except KeyboardInterrupt:
print("Terminating")
def showFlag(self):
self.servo_pin.duty(105)
def hideFlag(self):
self.servo_pin.duty(60)
def switch_lights_on(self):
self.led_pin.value(0)
def switch_lights_off(self):
self.led_pin.value(1)