Usable but ugly!
[zanchey/dispense2.git] / sql-edition / servers / VendingMachine.py
1 import re, pg
2 from CRC import do_crc
3 from select import select
4
5 asynchronous_responses = [      '400', '401', # door open/closed
6                                 '610',        # switches changed
7                                 '200', '201', '202', '203', '204', '205', '206',
8                                 '207', '208', '209', '211', # key presses
9                          ]
10 DOOR = 1
11 SWITCH = 2
12 KEY = 3
13
14 class VendingMachine:
15         def __init__(self, rfh, wfh):
16                 self.events = []
17                 self.secret = 'AAAAAAAAAAAAAAAA'
18                 self.rfh = rfh
19                 self.wfh = wfh
20                 self.challenge = None
21                 # Initialise ourselves into a known state
22                 self.wfh.write('\n')
23                 self.await_prompt()
24                 self.wfh.write('echo off\n')
25                 self.await_prompt()
26                 self.wfh.write('PING\n')
27                 code = ''
28                 while code != '000':
29                         (code, _) = self.get_response()
30                 self.get_switches()
31
32         def await_prompt(self):
33                 self.wfh.flush()
34                 state = 1
35                 prefix = ''
36                 s = ''
37                 while True:
38                         s = self.rfh.read(1)
39                         if s == '': raise Exception('nothing read!')
40                         if s == '\n' or s == '\r':
41                                 state = 1
42                                 prefix = ''
43                         if (s == '#' or s == '%') and state == 1: state = 2
44                         if s == ' ' and state == 2:
45                                 if prefix == '':
46                                         self.challenge = None
47                                         return
48                                 if re.search('^[0-9a-fA-F]{4}$', prefix):
49                                         self.challenge = int(prefix, 16)
50                                         return
51
52         def get_response(self, async = False):
53                 self.wfh.flush()
54                 while True:
55                         s = ''
56                         while s == '':
57                                 s = self.rfh.readline()
58                                 if s == '': return None
59                                 s = s.strip('\r\n')
60                         code = s[0:3]
61                         text = s[4:]
62                         if code in asynchronous_responses:
63                                 self.handle_event(code, text)
64                                 if async: return None
65                         else:
66                                 self.await_prompt()
67                                 return (code, text)
68
69         def get_switches(self):
70                 self.wfh.write('S\n')
71                 (code, text) = self.get_response()
72                 if code != '600':
73                         return (False, code, text)
74                 self.interpret_switches(text)
75                 return (True, code, text)
76
77         def interpret_switches(self, text):
78                 self.switches = (int(text[0:2], 16) << 8) | int(text[3:5], 16)
79
80         def handle_event(self, code, text):
81                 if code == '400':
82                         self.events.append((DOOR, 0))
83                 elif code == '401':
84                         self.events.append((DOOR, 1))
85                 elif code == '610':
86                         self.events_append((SWITCH, None))
87                         self.interpret_switches(text)
88                 elif code[0] == '2':
89                         self.events.append((KEY, int(code[1:3])))
90                 else:
91                         sys.stderr.write('WARNING: Unhandled event! (%s %s)\n'%(code,text))
92
93         def authed_message(self, message):
94                 if self.challenge == None:
95                         return message
96                 crc = do_crc('%c%c'%(self.challenge >> 8, self.challenge & 0xff))
97                 crc = do_crc(self.secret, crc)
98                 crc = do_crc(message, crc)
99                 return message+'|'+('%04x'%crc)
100
101         def ping(self):
102                 self.wfh.write('PING\n')
103                 (code, string) = self.get_response()
104                 return (code == '000', code, string)
105
106         def vend(self, item):
107                 if not re.search('^[0-9][0-9]$', item):
108                         return (False, 'Invalid item requested (%s)'%item)
109                 self.wfh.write(self.authed_message(('V%s\n'%item)+'\n'))
110                 (code, string) = self.get_response()
111                 return (code == '100', code, string)
112
113         def beep(self, duration = None, synchronous = True):
114                 msg = 'B'
115                 if synchronous: msg += 'S'
116                 if duration != None:
117                         if duration > 255: duration = 255
118                         if duration < 1: duration = 1
119                         msg += '%02x'%duration
120                 self.wfh.write(msg+'\n')
121                 (code, string) = self.get_response()
122                 return (code == '500', code, string)
123
124         def silence(self, duration = None, synchronous = True):
125                 msg = 'C'
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                 # FIXME: workaround a bug in rom W. should be just: return (code == '500', code, string)
134                 return (code == '500' or code == '501', code, string)
135
136         def display(self, string):
137                 if len(string) > 10:
138                         string = string[0:10]
139                 self.wfh.write('D'+string+'\n')
140                 (code, string) = self.get_response()
141                 return (code == '300', code, string)
142
143         def next_event(self):
144                 if len(self.events) > 0:
145                         ret = self.events[0]
146                         del self.events[0]
147                         return ret
148                 return None
149
150         def wait_for_events(self, timeout = None):
151                 if self.events: return True
152                 (r, _, _) = select([self.rfh], [], [], timeout)
153                 if not r: return False
154                 event_added = False
155                 while True:
156                     self.get_response(async = True)
157                     (r, _, _) = select([self.rfh], [], [], 0)
158                     if not r: return event_added

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