-
Notifications
You must be signed in to change notification settings - Fork 0
/
virtualsnack.py
executable file
·461 lines (379 loc) · 16.7 KB
/
virtualsnack.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#!/usr/bin/env python
# coding: latin-1
import npyscreen
from datetime import datetime
# Incorporates code
# from http://www.binarytides.com/python-socket-server-code-example/
# Socket server in python using select function
import socket, select, errno
# for box characters
import curses
# for emulator code
import os
import sys
import string
import time
class VerticalLine(npyscreen.FixedText):
def __init__(self, screen, line_height=1, *args, **keywords):
self.line_height = line_height
super(VerticalLine, self).__init__(screen, *args, **keywords)
def update(self, clear=True):
self.parent.curses_pad.vline(self.rely, self.relx, curses.ACS_VLINE, self.line_height)
class HorizontalLine(npyscreen.FixedText):
def __init__(self, screen, line_width=1, *args, **keywords):
self.line_width = line_width
super(HorizontalLine, self).__init__(screen, *args, **keywords)
def update(self, clear=True):
self.parent.curses_pad.hline(self.rely, self.relx, curses.ACS_HLINE, self.line_width)
class Corner(npyscreen.FixedText):
def __init__(self, screen, corner_type=None, *args, **keywords):
self.corner_type = corner_type
super(Corner, self).__init__(screen, *args, **keywords)
def update(self, clear=True):
corners = {}
corners["ULCORNER"] = curses.ACS_ULCORNER
corners["URCORNER"] = curses.ACS_URCORNER
corners["LLCORNER"] = curses.ACS_LLCORNER
corners["LRCORNER"] = curses.ACS_LRCORNER
corners["LTEE"] = curses.ACS_LTEE
corners["RTEE"] = curses.ACS_RTEE
corners["BTEE"] = curses.ACS_BTEE
corners["TTEE"] = curses.ACS_TTEE
corners["HLINE"] = curses.ACS_HLINE
corner = corners.get(self.corner_type,curses.ACS_BULLET)
self.parent.curses_pad.addch(self.rely, self.relx, corner)
class ContainedMultiSelect(npyscreen.BoxTitle):
_contained_widget = npyscreen.TitleMultiSelect
class SnackButtonPress(npyscreen.MiniButtonPress):
def __init__(self, screen, when_pressed_function=None, when_pressed_callback=None, *args, **keywords):
super(SnackButtonPress, self).__init__(screen, *args, **keywords)
self.when_pressed_callback = when_pressed_callback
def whenPressed(self,key=None):
if self.when_pressed_callback:
self.when_pressed_callback(widget=self)
class Switches:
def __init__(self):
self.misc_input = 0xff
self.switch_input = 0x3f
def door_open(self):
return self.switch_input & 0x20
def set_door_open(self, open = True):
if open:
self.switch_input |= 0x20
else:
self.switch_input &= ~0x20
class VirtualSnack(npyscreen.Form):
def while_waiting(self):
self.date_widget.value = datetime.now().ctime()
self.sentfield.value = self.parentApp.sent
self.receivedfield.value = self.parentApp.received
self.textdisplay.value = self.parentApp.textdisplay
self.display()
def create(self, *args, **keywords):
super(VirtualSnack, self).create(*args, **keywords)
# The display
self.textdisplay = self.add(npyscreen.FixedText, value=self.parentApp.textdisplay, editable=False, relx=9)
self.textdisplay.important = True
# The keypad
self.kpbuttons = []
kpx = 1
kpy = 1
for keypad in range(0,10):
kpx = ((keypad % 4) * 6 ) + 3
kpy = int(keypad / 4) + 4
widget = self.add(SnackButtonPress,name="%d"%keypad, relx = kpx, rely = kpy, when_pressed_callback=self.parentApp.when_keypad_pressed)
self.kpbuttons.append(widget)
self.add_handlers({"%d"%keypad: widget.whenPressed})
self.reset=self.add(SnackButtonPress,name="RESET", relx = kpx + 7, rely = kpy, when_pressed_callback=self.parentApp.when_reset_pressed)
self.add_handlers({"R": self.reset.whenPressed})
self.add_handlers({"r": self.reset.whenPressed})
# The door switch
self.door = self.add(npyscreen.MultiSelect, name = "Door", max_width=15, relx = 4, rely = 12, max_height=4, value = [], values = ["DOOR"], scroll_exit=True, value_changed_callback=self.parentApp.when_door_toggled)
# The DIP switches
self.dip = self.add(npyscreen.MultiSelect, name = "DIP Switch", max_width=10, rely =3, relx = 30, max_height=8, value = [], values = ["DIP1", "DIP2", "DIP3","DIP4","DIP5","DIP6","DIP7","DIP8"], scroll_exit=True)
# The coin buttons
self.nickel=self.add(SnackButtonPress,name="0.05", rely= 12, relx=33)
self.dime=self.add(SnackButtonPress,name="0.10", relx=33)
self.quarter=self.add(SnackButtonPress,name="0.25", relx=33)
self.dollar=self.add(SnackButtonPress,name="1.00", relx=33)
# The mode button
self.mode=self.add(SnackButtonPress,name="MODE", relx=33)
# Space for the current time
self.date_widget = self.add(npyscreen.FixedText, value=datetime.now().ctime(), editable=False, rely=18)
self.date_widget.value = "Hello"
self.slots = []
slotx = 0
sloty = 0
# The Virtual Vending Machine
for i in range(1,9):
self.add(npyscreen.FixedText, value=str(i), editable=False, relx=47, rely=4+i)
for slx in range(0,10):
self.slots.append([])
xpos = 49 + (slx * 2)
self.add(npyscreen.FixedText, value=str(slx), editable=False, relx=xpos, rely=3)
for sly in range(1,9):
ypos = 4 + sly
if sly == 5:
self.slots[slx].append(None)
else:
self.slots[slx].append(self.add(npyscreen.FixedText, value="/", editable=False, relx=xpos, rely=ypos))
self.collectionslot = self.add(npyscreen.FixedText, value=" PUSH", editable=False, relx=54, rely=15)
# Draw some fancy things to make it look fancy
# All the big things that can be done in bulk
# If you ever need to modify this, see http://en.wikipedia.org/wiki/Box-drawing_character
# See also
# http://www.melvilletheatre.com/articles/ncurses-extended-characters/index.html
# https://stackoverflow.com/questions/1279341/how-do-i-use-extended-characters-in-pythons-curses-library
#
self.add(HorizontalLine, line_width=28, value="-"*28, relx=46, rely=2)
self.add(HorizontalLine, line_width=24, value="-"*24, relx=46, rely=14)
self.add(HorizontalLine, line_width=24, value="-"*24, relx=46, rely=16)
self.add(HorizontalLine, line_width=28, value="-"*28, relx=46, rely=18)
for j in [45, 74]:
self.add(VerticalLine, line_height=16, value="|", relx=j, rely=3)
self.add(VerticalLine, line_height=15, value="|", relx=69, rely=3)
self.add(Corner, corner_type="ULCORNER", relx=45, rely=2)
self.add(Corner, corner_type="URCORNER", relx=74, rely=2)
self.add(Corner, corner_type="TTEE", relx=69, rely=2)
self.add(Corner, corner_type="BTEE", relx=69, rely=18)
self.add(Corner, corner_type="LTEE", relx=45, rely=14)
self.add(Corner, corner_type="LTEE", relx=45, rely=16)
self.add(Corner, corner_type="LTEE", relx=45, rely=18)
self.add(Corner, corner_type="RTEE", relx=69, rely=14)
self.add(Corner, corner_type="RTEE", relx=69, rely=16)
self.add(Corner, corner_type="RTEE", relx=74, rely=18)
# feet
self.add(Corner, corner_type="LLCORNER", relx=45, rely=19)
self.add(Corner, corner_type="HLINE", relx=46, rely=19)
self.add(Corner, corner_type="LRCORNER", relx=47, rely=19)
self.add(Corner, corner_type="LLCORNER", relx=72, rely=19)
self.add(Corner, corner_type="HLINE", relx=73, rely=19)
self.add(Corner, corner_type="LRCORNER", relx=74, rely=19)
self.add(Corner, corner_type="TTEE", relx=47, rely=18)
self.add(Corner, corner_type="TTEE", relx=72, rely=18)
self.textdisplaymini = self.add(npyscreen.FixedText, value="====", editable=False, relx=70, rely=5)
self.textdisplaymini.important = True
# Ctrl + Q exits the application
self.add_handlers({"^Q": self.exit_application})
self.add_handlers({"^C": self.exit_application})
# Display info about what has been comminucated to and by the vending machine
self.sentfield = self.add(npyscreen.TitleText, name = "Sent:", value="", editable=False, rely=20 )
self.receivedfield = self.add(npyscreen.TitleText, name = "Received:", value="", editable=False )
def exit_application(self,name):
self.parentApp.setNextForm(None)
self.editing = False
class VirtualSnackApp(npyscreen.NPSAppManaged):
keypress_timeout_default = 1
def start_listening(self):
self.PORT = 5150
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this has no effect, why ?
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind(("0.0.0.0", self.PORT))
self.server_socket.listen(10)
# Add server socket to the list of readable connections
self.CONNECTION_LIST.append(self.server_socket)
self.received="Chat server started on port " + str(self.PORT)
def onStart(self):
# initialise virtual vending machine
# vending machine password set here
self.vendpw = "AAAAAAAAAAAAAAAA"
self.switches = Switches()
self.textdisplay = "*5N4CK0RZ*"
self.F = self.addForm("MAIN", VirtualSnack, name="Virtual Snack", columns=80, lines=24)
# socket code
self.CONNECTION_LIST = [] # list of socket clients
self.RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
self.start_listening()
self.sent=""
def while_waiting(self):
# Get the list sockets which are ready to be read through select
try:
read_sockets,write_sockets,error_sockets = select.select(self.CONNECTION_LIST,[],[],0.1)
except socket.error as e:
self.CONNECTION_LIST = []
self.start_listening()
return
for sock in read_sockets:
#New connection
if sock == self.server_socket:
# Handle the case in which there is a new connection recieved through self.server_socket
sockfd, addr = self.server_socket.accept()
self.CONNECTION_LIST.append(sockfd)
self.received = "Client (%s, %s) connected" % addr
self.do_send("000 Virtual Snack is alive \n")
self.do_prompt()
#Some incoming message from a client
else:
# Data recieved from client, process it
try:
#In Windows, sometimes when a TCP program closes abruptly,
# a "Connection reset by peer" exception will be thrown
data = sock.recv(self.RECV_BUFFER)
# echo back the client message
if data:
self.handle_command(data)
#response = 'OK ... ' + data
#sock.send(response)
#self.sent = response
self.received = data
# client disconnected, so remove from socket list
except socket.error as e:
#print "Client (%s, %s) is offline" % addr
sock.close()
#self.CONNECTION_LIST.remove(sock)
continue
def onCleanExit(self):
self.server_socket.close()
# Snack Emulator comms below
def do_send(self, data):
# Get the list sockets which are ready to be written through select
read_sockets,write_sockets,error_sockets = select.select([],self.CONNECTION_LIST,[],0.1)
for sock in write_sockets:
try:
sock.send(data)
except socket.error as e:
if isinstance(e.args, tuple):
self.sent = "errno is %d" % e[0]
if e[0] == errno.EPIPE:
# remote peer disconnected
self.sent = "Detected remote disconnect"
else:
# determine and handle different error
pass
else:
self.sent = "socket error ", e
self.CONNECTION_LIST.remove(sock)
sock.close()
return
except IOError as e:
# Hmmm, Can IOError actually be raised by the socket module?
self.sent = "Got IOError: ", e
return
self.sent = data
# Callbacks
def when_door_toggled(self, *args, **keywords):
# See
# https://code.google.com/p/npyscreen/source/detail?r=9768a97fd80ed1e7b3e670f312564c19b1adfef8#
# for callback info
if keywords['widget'].get_selected_objects():
self.do_send('401 door closed\n')
else:
self.do_send('400 door open\n')
def when_reset_pressed(self, *args, **keywords):
self.do_send('211 keypress\n')
keywords['widget'].value = False
self.F.display()
def when_keypad_pressed(self, *args, **keywords):
key = '0'+ keywords['widget'].name
self.do_send('2'+key+' keypress\n')
keywords['widget'].value = False
self.F.display()
# Snack Emulator code below
def do_prompt(self):
self.do_send("# ")
def do_help(self):
help = """
Valid commands are:
ABOUT ROM information
B[S][nn] beep [synchronously] for a duration nn (optional)
C[S][nn] silence [synchronously] for a duration nn (optional)
Dxxxxxxxxxx show a message on the display
ECHO {ON|OFF} turn echo on or off
GETROM download the ROM source code using xmodem
H[...] this help screen
IDENTIFY report ROM version
*JUMPxxxx jumps to a subroutine at location xxxx
*PEEKxxxx returns the value of the byte at location xxxx
*POKExxxxyy sets the value of location xxxx to yy
PING pongs
S[...] query all internal switch states
+Vnn vend an item
+VALL vend all items
*Wxxxxxxxxxxxx set a new password for authenticated vends. xxx=16 chars
password will be converted to uppercase
Very few functions are available when the machine is in standalone
mode (DIP SW 1 is set)
+ denotes that this item requires authentication if DIP SW 2 is set
* denotes that DIP SW 3 must be set to use these
Commands starting with # are ignored (comments)
"""
self.do_send(help)
def do_identify(self):
mtime = datetime.fromtimestamp(os.path.getmtime(__file__))
time = mtime.strftime("%Y%m%d")
host = socket.gethostname()
identify = "086 VIRTUAL %s %s\n" % (host,time,)
self.do_send(identify)
def do_about(self):
about = """
The Virtual Vending^WSnack Machine Company
Mark Tearle, October 2014
"""
self.do_send(about)
def do_vend_all(self):
for i in range(11,99):
self.do_send("101 Vending "+str(i)+"\n")
self.do_send("153 Home sensors failing\n")
self.do_send("102 Vend all motors complete\n")
def do_vend(self,command):
if self.F.slots[int(command[2])][int(command[1])] == None:
self.do_send("153 Home sensors failing\n")
else:
for pos in "-\|/-\|/":
self.F.slots[int(command[2])][int(command[1])].value = pos
self.F.display()
time.sleep(0.4)
self.F.collectionslot.value = "*THUNK*"
self.F.display()
time.sleep(2)
self.F.collectionslot.value = " PUSH"
self.F.display()
self.do_send("100 Vend successful\n")
def do_display(self,string):
self.textdisplay = "%-10.10s" % (string)
self.do_send('300 Written\n')
def do_beep(self,command):
sys.stdout.write("\a")
self.do_send('500 Beeped\n')
def do_silence(self,command):
pass
def do_switches(self):
self.do_send("600 3F 3F\n")
def do_pong(self):
self.do_send("000 PONG!\n")
def do_echo(self):
self.do_send("000 Not implemented\n")
def handle_command(self, command):
command = string.upper(command)
if string.find(command, "HELP",0) == 0:
self.do_help()
elif string.find(command, "ID",0) == 0:
self.do_identify()
elif string.find(command, "ECHO",0) == 0:
self.do_echo()
elif string.find(command, "ABOUT",0) == 0:
self.do_about()
elif string.find(command, "PING",0) == 0:
self.do_pong()
elif string.find(command, "VALL",0) == 0:
self.do_vend_all()
elif string.find(command, "V",0) == 0:
self.do_vend(command)
elif string.find(command, "B",0) == 0:
self.do_beep(command)
elif string.find(command, "C",0) == 0:
self.do_silence(command)
elif string.find(command, "S",0) == 0:
self.do_switches()
elif string.find(command, "D",0) == 0:
self.do_display(command[1:])
elif string.find(command, "#", 0) == 0:
self.do_send("\n")
self.do_prompt()
if __name__ == "__main__":
App = VirtualSnackApp()
try:
App.run()
except (KeyboardInterrupt):
print("Application Closed")