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

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