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

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