/[anoncvs]/projects/dispense2/sql-edition/servers/VendingMachine.py


UCC Code Repository

Contents of /projects/dispense2/sql-edition/servers/VendingMachine.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.18 - (hide annotations) (download) (as text)
Fri Mar 2 12:33:13 2007 UTC (14 years, 3 months ago) by dagobah
Branch: MAIN
Changes since 1.17: +2 -1 lines
File MIME type: text/x-python
fix bugs and solve world poverty.

1 dagobah 1.4 # vim:ts=4
2 dagobah 1.7 import re
3 dagobah 1.1 from CRC import do_crc
4 dagobah 1.2 from select import select
5 cameron 1.12 import socket, logging
6 mtearle 1.16 from time import time, sleep
7 dagobah 1.1
8     asynchronous_responses = [ '400', '401', # door open/closed
9     '610', # switches changed
10 dagobah 1.2 '200', '201', '202', '203', '204', '205', '206',
11     '207', '208', '209', '211', # key presses
12 dagobah 1.1 ]
13 dagobah 1.2 DOOR = 1
14     SWITCH = 2
15     KEY = 3
16 mtearle 1.16 TICK = 4
17 dagobah 1.1
18 cameron 1.8 class VendingException(Exception): pass
19    
20 dagobah 1.1 class VendingMachine:
21     def __init__(self, rfh, wfh):
22 dagobah 1.2 self.events = []
23 dagobah 1.1 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 cameron 1.8 code = self.get_response()[0]
36 dagobah 1.2 self.get_switches()
37 dagobah 1.1
38     def await_prompt(self):
39     self.wfh.flush()
40     state = 1
41     prefix = ''
42     s = ''
43     while True:
44 cameron 1.8 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 dagobah 1.13 if (s != '#' and s != '%') and state == 1: prefix += s
50 dagobah 1.1 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 dagobah 1.2 self.challenge = int(prefix, 16)
60 dagobah 1.1 return
61    
62 dagobah 1.3 def get_response(self, async = False):
63 dagobah 1.1 self.wfh.flush()
64     while True:
65     s = ''
66     while s == '':
67     s = self.rfh.readline()
68 dagobah 1.9 if s == '':
69 cameron 1.10 raise VendingException('Input socket has closed!')
70 dagobah 1.1 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 dagobah 1.3 if async: return None
76 dagobah 1.1 else:
77     self.await_prompt()
78     return (code, text)
79    
80 dagobah 1.2 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 dagobah 1.1 def handle_event(self, code, text):
92 dagobah 1.2 if code == '400':
93 mtearle 1.14 self.events.append((DOOR, 1))
94     elif code == '401':
95 dagobah 1.2 self.events.append((DOOR, 0))
96     elif code == '610':
97 dagobah 1.18 # NOP this. Nothing handles this yet.
98     #self.events.append((SWITCH, None))
99 dagobah 1.2 self.interpret_switches(text)
100     elif code[0] == '2':
101     self.events.append((KEY, int(code[1:3])))
102     else:
103 cameron 1.12 logging.warning('Unhandled event! (%s %s)\n'%(code,text))
104 dagobah 1.1
105     def authed_message(self, message):
106     if self.challenge == None:
107     return message
108     crc = do_crc('%c%c'%(self.challenge >> 8, self.challenge & 0xff))
109     crc = do_crc(self.secret, crc)
110     crc = do_crc(message, crc)
111     return message+'|'+('%04x'%crc)
112    
113     def ping(self):
114     self.wfh.write('PING\n')
115     (code, string) = self.get_response()
116     return (code == '000', code, string)
117    
118     def vend(self, item):
119     if not re.search('^[0-9][0-9]$', item):
120     return (False, 'Invalid item requested (%s)'%item)
121 dagobah 1.13 self.wfh.write(self.authed_message(('V%s'%item))+'\n')
122 dagobah 1.1 (code, string) = self.get_response()
123 dagobah 1.2 return (code == '100', code, string)
124 dagobah 1.1
125     def beep(self, duration = None, synchronous = True):
126     msg = 'B'
127     if synchronous: msg += 'S'
128     if duration != None:
129     if duration > 255: duration = 255
130     if duration < 1: duration = 1
131     msg += '%02x'%duration
132     self.wfh.write(msg+'\n')
133     (code, string) = self.get_response()
134     return (code == '500', code, string)
135    
136     def silence(self, duration = None, synchronous = True):
137     msg = 'C'
138     if synchronous: msg += 'S'
139     if duration != None:
140     if duration > 255: duration = 255
141     if duration < 1: duration = 1
142     msg += '%02x'%duration
143     self.wfh.write(msg+'\n')
144     (code, string) = self.get_response()
145 dagobah 1.6 return (code == '501', code, string)
146 dagobah 1.1
147     def display(self, string):
148     if len(string) > 10:
149     string = string[0:10]
150 dagobah 1.15 string = re.sub('(.)\.', lambda match: '.'+match.group(1), string)
151 dagobah 1.1 self.wfh.write('D'+string+'\n')
152     (code, string) = self.get_response()
153     return (code == '300', code, string)
154    
155 dagobah 1.4 def next_event(self, timeout = None):
156     # we don't want to buffer in the serial port, so we get all the events
157     # we can ASAP.
158 dagobah 1.17 if timeout < 0: timeout = 0
159 dagobah 1.4 if len(self.events) > 0: timeout = 0
160 dagobah 1.2 while True:
161 dagobah 1.4 (r, _, _) = select([self.rfh], [], [], timeout)
162     if r:
163     self.get_response(async = True)
164 dagobah 1.5 timeout = 0
165 dagobah 1.4 else:
166     break
167 mtearle 1.16 if len(self.events) == 0: return (TICK, time())
168 dagobah 1.4 ret = self.events[0]
169     del self.events[0]
170     return ret

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26