25d375b0d1855bb5cb0ff2c726b2fecdd654ff02
[zanchey/dispense2.git] / sql-edition / servers / VendingMachine.py
1 # vim:ts=4
2 import re
3 from CRC import do_crc
4 from select import select
5 import socket, logging
6 from time import time, sleep
7
8 asynchronous_responses = [      '400', '401', # door open/closed
9                                 '610',        # switches changed
10                                 '200', '201', '202', '203', '204', '205', '206',
11                                 '207', '208', '209', '211', # key presses
12                          ]
13 DOOR = 1
14 SWITCH = 2
15 KEY = 3
16 TICK = 4
17
18 class VendingException(Exception): pass
19
20 class VendingMachine:
21         def __init__(self, rfh, wfh):
22                 self.events = []
23                 # Secret
24                 self.secret = 'SN4CKZ0RZZZZZZZZ'
25                 self.rfh = rfh
26                 self.wfh = wfh
27                 self.challenge = None
28                 # Initialise ourselves into a known state
29                 self.wfh.write('\n')
30                 self.await_prompt()
31                 self.wfh.write('echo off\n')
32                 self.await_prompt()
33                 self.wfh.write('PING\n')
34                 code = ''
35                 while code != '000':
36                         code = self.get_response()[0]
37                 self.get_switches()
38
39         def await_prompt(self):
40                 self.wfh.flush()
41                 state = 1
42                 prefix = ''
43                 s = ''
44                 while True:
45                         try:
46                                 s = self.rfh.read(1)
47                         except socket.error:
48                                 raise VendingException('failed to read input from vending machine')
49                         if s == '': raise VendingException('nothing read!')
50                         if (s != '#' and s != '%') and state == 1: prefix += s
51                         if s == '\n' or s == '\r':
52                                 state = 1
53                                 prefix = ''
54                         if (s == '#' or s == '%') and state == 1: state = 2
55                         if s == ' ' and state == 2:
56                                 if prefix == '':
57                                         self.challenge = None
58                                         return
59                                 if re.search('^[0-9a-fA-F]{4}$', prefix):
60                                         self.challenge = int(prefix, 16)
61                                         return
62
63         def get_response(self, async = False):
64                 self.wfh.flush()
65                 while True:
66                         s = ''
67                         while s == '':
68                                 s = self.rfh.readline()
69                                 if s == '':
70                                         raise VendingException('Input socket has closed!')
71                                 s = s.strip('\r\n')
72                         code = s[0:3]
73                         text = s[4:]
74                         if code in asynchronous_responses:
75                                 self.handle_event(code, text)
76                                 if async: return None
77                         else:
78                                 self.await_prompt()
79                                 return (code, text)
80
81         def get_switches(self):
82                 self.wfh.write('S\n')
83                 (code, text) = self.get_response()
84                 if code != '600':
85                         return (False, code, text)
86                 self.interpret_switches(text)
87                 return (True, code, text)
88
89         def interpret_switches(self, text):
90                 self.switches = (int(text[0:2], 16) << 8) | int(text[3:5], 16)
91
92         def handle_event(self, code, text):
93                 if code == '400':
94                         self.events.append((DOOR, 1))
95                 elif code == '401':
96                         self.events.append((DOOR, 0))
97                 elif code == '610':
98                         # NOP this. Nothing handles this yet.
99                         #self.events.append((SWITCH, None))
100                         self.interpret_switches(text)
101                 elif code[0] == '2':
102                         self.events.append((KEY, int(code[1:3])))
103                 else:
104                         logging.warning('Unhandled event! (%s %s)\n'%(code,text))
105
106         def authed_message(self, message):
107                 if self.challenge == None:
108                         return message
109                 crc = do_crc('%c%c'%(self.challenge >> 8, self.challenge & 0xff))
110                 crc = do_crc(self.secret, crc)
111                 crc = do_crc(message, crc)
112                 return message+'|'+('%04x'%crc)
113
114         def ping(self):
115                 self.wfh.write('PING\n')
116                 (code, string) = self.get_response()
117                 return (code == '000', code, string)
118
119         def vend(self, item):
120                 if not re.search('^[0-9][0-9]$', item):
121                         return (False, 'Invalid item requested (%s)'%item)
122                 self.wfh.write(self.authed_message(('V%s'%item))+'\n')
123                 (code, string) = self.get_response()
124                 return (code == '100', code, string)
125
126         def beep(self, duration = None, synchronous = True):
127                 msg = 'B'
128                 if synchronous: msg += 'S'
129                 if duration != None:
130                         if duration > 255: duration = 255
131                         if duration < 1: duration = 1
132                         msg += '%02x'%duration
133                 self.wfh.write(msg+'\n')
134                 (code, string) = self.get_response()
135                 return (code == '500', code, string)
136
137         def silence(self, duration = None, synchronous = True):
138                 msg = 'C'
139                 if synchronous: msg += 'S'
140                 if duration != None:
141                         if duration > 255: duration = 255
142                         if duration < 1: duration = 1
143                         msg += '%02x'%duration
144                 self.wfh.write(msg+'\n')
145                 (code, string) = self.get_response()
146                 return (code == '501', code, string)
147
148         def display(self, string):
149                 if len(string) > 10:
150                         string = string[0:10]
151                 string = re.sub('(.)\.', lambda match: '.'+match.group(1), string)
152                 self.wfh.write('D'+string+'\n')
153                 (code, string) = self.get_response()
154                 return (code == '300', code, string)
155
156         def next_event(self, timeout = None):
157                 # we don't want to buffer in the serial port, so we get all the events
158                 # we can ASAP.
159                 if timeout < 0: timeout = 0
160                 if len(self.events) > 0: timeout = 0
161                 while True:
162                         (r, _, _) = select([self.rfh], [], [], timeout)
163                         if r:
164                                 self.get_response(async = True)
165                                 timeout = 0
166                         else:
167                                 break
168                 if len(self.events) == 0: return (TICK, time())
169                 ret = self.events[0]
170                 del self.events[0]
171                 return ret

UCC git Repository :: git.ucc.asn.au