-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkrp.py
301 lines (233 loc) · 8.47 KB
/
krp.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
import Adafruit_CharLCD as LCD
import RPi.GPIO as GPIO
from time import sleep
import commands
from threading import Thread, Timer
import requests
from socket import *
import sys, termios, tty, os, logging
handler = logging.FileHandler('errors.log')
handler.setLevel(logging.INFO)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info('\n------------------------------------')
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
lcd_rs = 25
lcd_en = 24
lcd_d4 = 23
lcd_d5 = 17
lcd_d6 = 18
lcd_d7 = 22
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows, lcd_backlight)
lcd.home()
lcd.clear()
lcd.message(commands.getoutput('hostname -I'))
sleep(5)
lcd.home()
lcd.clear()
lcd.message("HelloWorld!\nFoo")
led_pin = 20
GPIO.setup(led_pin, GPIO.OUT)
left_button_pin = 13
GPIO.setup(left_button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
ok_button_pin = 19
GPIO.setup(ok_button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
right_button_pin = 26
GPIO.setup(right_button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# while True:
# GPIO.output(led_pin, GPIO.HIGH)
# print("hello")
# time.sleep(2)
# GPIO.output(led_pin, GPIO.LOW)
# time.sleep(2)
# GPIO.output(led_pin, GPIO.HIGH)
#while True:
# input_state = GPIO.input(ok_button_pin)
# if input_state == False:
# print('OK Button Pressed')
# time.sleep(0.2)
class KrpController:
baseUrl = "http://azfn-linqpad-web-app-e5opllzphjvwc.azurewebsites.net/api/krp"
minimumMinutesBetweenLogs = 0
users = []
latestLogByUserId = None #todo: get this from the server
selectedUserIndex = 0
returnTimer = None
def __init__(self, client):
self.client = client
self.client.controller = self
def init(self):
self.state = "LOADING"
self.client.init()
self.client.turnLed(True)
self.client.write(self.client.getIp(),"Loading...")
url = self.baseUrl + "/config"
try:
response = requests.get(url=url)
data = response.json()
# print(str(data))
self.minimumMinutesBetweenLogs = data['MinimumMinutesBetweenLogs']
for jUser in data['Users']:
self.users.append(KrpPlayer(jUser['Id'], jUser['FirstName'], jUser['LastName']))
self.latestLogByUserId = data['LatestLogByUserId']
self.client.clear()
self.__writeLastCleanedBy()
except:
logger.info(sys.exc_info()[0])
def onButtonPress(self, button): # handler for button press
if self.state == "MENU":
self.__selectPlayer()
elif self.state == "SELECT_PLAYER":
if button == "LEFT":
self.selectedUserIndex -= 1
if self.selectedUserIndex == -1: self.selectedUserIndex = len(self.users) - 1
self.__selectPlayer()
elif button == "RIGHT":
self.selectedUserIndex += 1
if self.selectedUserIndex == len(self.users): self.selectedUserIndex = 0
self.__selectPlayer()
elif button == "OK":
self.__registerPlayer(self.users[self.selectedUserIndex].id)
elif self.state == "ERROR":
self.__writeLastCleanedBy()
elif self.state == "REGISTERED":
self.__writeLastCleanedBy()
def __writeLastCleanedBy(self): # Show main menu
self.state = "MENU"
user = self.__findUserById(self.latestLogByUserId)
self.client.write("Last cleaned by:", user.firstName if user is not None else "<NONE>")
self.__cancelReturningTimer()
def __selectPlayer(self): # Show select player on led
self.state = "SELECT_PLAYER"
user = self.users[self.selectedUserIndex]
self.__startReturningTimer()
userString = str(user).ljust(14)
self.client.write("SELECT", "<" + userString + ">")
def __registerPlayer(self, userId): # Show registing player on led
self.state = "REGISTERING"
self.client.write("Registering...", "")
self.__cancelReturningTimer()
self.client.turnLed(True)
try:
url = self.baseUrl + "/log?playerId=" + str(userId)
response = requests.get(url=url)
if response.status_code == 200:
data = response.json()
if data['Status'] == 1: # Register Success
self.latestLogByUserId = userId
self.__writeRegisteredMessage(data['Message'])
elif data['Status'] == 2: # Log_To_Soon Error
self.__writeError("Log To Soon")
else:
self.__writeError("")
else:
self.__writeError("")
except Exception as error:
self.__writeError("")
self.client.turnLed(False)
def __writeError(self, error): # Show Error on Lcd when register failed
self.state = "ERROR"
self.client.write("Oops!", error)
self.__startReturningTimer()
def __writeRegisteredMessage(self, msg): # Show Register Message on Lcd when register successed
self.state = "REGISTERED"
self.client.write("REGISTERED", msg)
self.__startReturningTimer()
def __findUserById(self, userId): # Find user by userId
if userId is None:
return None
for user in self.users:
if user.id == userId:
return user
return None
def __startReturningTimer(self): # Timer for returning to main menu when no signal in 5 seconds.
self.__cancelReturningTimer()
self.returnTimer = Timer(5, self.__writeLastCleanedBy)
self.returnTimer.start()
def __cancelReturningTimer(self): # Cancel returing timer
if self.returnTimer != None and self.returnTimer.is_alive():
self.returnTimer.cancel()
#################################################################
class KrpPlayer:
def __init__(self, id, firstName, lastName):
self.id = id
self.firstName = firstName
self.lastName = lastName
def __str__(self):
return self.firstName
#################################################################
class KrpClient:
controller = None
def init(self):
pass
def write(self,top16,bottom16):
pass
def clear(self):
self.write("","")
def loop(self):
pass
def getIp(self):
return gethostbyname(getfqdn())
class KrpConsoleClient(KrpClient):
lcd = None
def __init__(self, lcd):
self.lcd = lcd
def write(self, top16, bottom16):
top16 = '{0: <16}'.format(top16[:16])
bottom16 = '{0: <16}'.format(bottom16[:16])
self.lcd.clear()
self.lcd.message(top16 + "\n" + bottom16)
print("+----------------+")
print("|"+top16+"|")
print("+----------------+")
print("|"+bottom16+"|")
print("+----------------+")
def turnLed(self, on):
if on:
GPIO.output(led_pin, GPIO.HIGH)
else:
GPIO.output(led_pin, GPIO.LOW)
def clear(self):
self.lcd.clear()
GPIO.output(led_pin, GPIO.LOW)
#################################################################
controller = KrpController(KrpConsoleClient(lcd))
controller.init()
def buttonPressed(button):
controller.onButtonPress(button)
print(button)
GPIO.add_event_detect(left_button_pin, GPIO.FALLING, callback=lambda x: buttonPressed("LEFT"), bouncetime=200)
GPIO.add_event_detect(ok_button_pin, GPIO.FALLING, callback=lambda x: buttonPressed("OK"), bouncetime=200)
GPIO.add_event_detect(right_button_pin, GPIO.FALLING, callback=lambda x: buttonPressed("RIGHT"), bouncetime=200)
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
while True:
pass
# def run(*args):
# while True:
# char = getch()
# if (char == "p"):
# print("Stop!")
# exit(0)
# Thread(target=run).start()
# try:
# while True:
# sleep(1)
# except KeyboardInterrupt:
# GPIO.cleanup()