/[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.20 - (hide annotations) (download) (as text)
Sun Jan 6 06:11:33 2008 UTC (13 years, 5 months ago) by root
Branch: MAIN
Changes since 1.19: +5 -0 lines
File MIME type: text/x-python
note vis pyserial

change of timeout

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.19 # Secret
24     self.secret = 'SN4CKZ0RZZZZZZZZ'
25 dagobah 1.1 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 cameron 1.8 code = self.get_response()[0]
37 dagobah 1.2 self.get_switches()
38 dagobah 1.1
39     def await_prompt(self):
40     self.wfh.flush()
41     state = 1
42 root 1.20 timeout = 0.5
43 dagobah 1.1 prefix = ''
44     s = ''
45 root 1.20 # mtearle - vending machine was dying wait for a response from
46     # the hardware, suspect it was missing characters
47     #
48     # fixed by migration to pyserial - but future good place to start
49 dagobah 1.1 while True:
50 cameron 1.8 try:
51     s = self.rfh.read(1)
52     except socket.error:
53     raise VendingException('failed to read input from vending machine')
54     if s == '': raise VendingException('nothing read!')
55 dagobah 1.13 if (s != '#' and s != '%') and state == 1: prefix += s
56 dagobah 1.1 if s == '\n' or s == '\r':
57     state = 1
58     prefix = ''
59     if (s == '#' or s == '%') and state == 1: state = 2
60     if s == ' ' and state == 2:
61     if prefix == '':
62     self.challenge = None
63     return
64     if re.search('^[0-9a-fA-F]{4}$', prefix):
65 dagobah 1.2 self.challenge = int(prefix, 16)
66 dagobah 1.1 return
67    
68 dagobah 1.3 def get_response(self, async = False):
69 dagobah 1.1 self.wfh.flush()
70     while True:
71     s = ''
72     while s == '':
73     s = self.rfh.readline()
74 dagobah 1.9 if s == '':
75 cameron 1.10 raise VendingException('Input socket has closed!')
76 dagobah 1.1 s = s.strip('\r\n')
77     code = s[0:3]
78     text = s[4:]
79     if code in asynchronous_responses:
80     self.handle_event(code, text)
81 dagobah 1.3 if async: return None
82 dagobah 1.1 else:
83     self.await_prompt()
84     return (code, text)
85    
86 dagobah 1.2 def get_switches(self):
87     self.wfh.write('S\n')
88     (code, text) = self.get_response()
89     if code != '600':
90     return (False, code, text)
91     self.interpret_switches(text)
92     return (True, code, text)
93    
94     def interpret_switches(self, text):
95     self.switches = (int(text[0:2], 16) << 8) | int(text[3:5], 16)
96    
97 dagobah 1.1 def handle_event(self, code, text):
98 dagobah 1.2 if code == '400':
99 mtearle 1.14 self.events.append((DOOR, 1))
100     elif code == '401':
101 dagobah 1.2 self.events.append((DOOR, 0))
102     elif code == '610':
103 dagobah 1.18 # NOP this. Nothing handles this yet.
104     #self.events.append((SWITCH, None))
105 dagobah 1.2 self.interpret_switches(text)
106     elif code[0] == '2':
107     self.events.append((KEY, int(code[1:3])))
108     else:
109 cameron 1.12 logging.warning('Unhandled event! (%s %s)\n'%(code,text))
110 dagobah 1.1
111     def authed_message(self, message):
112     if self.challenge == None:
113     return message
114     crc = do_crc('%c%c'%(self.challenge >> 8, self.challenge & 0xff))
115     crc = do_crc(self.secret, crc)
116     crc = do_crc(message, crc)
117     return message+'|'+('%04x'%crc)
118    
119     def ping(self):
120     self.wfh.write('PING\n')
121     (code, string) = self.get_response()
122     return (code == '000', code, string)
123    
124     def vend(self, item):
125     if not re.search('^[0-9][0-9]$', item):
126     return (False, 'Invalid item requested (%s)'%item)
127 dagobah 1.13 self.wfh.write(self.authed_message(('V%s'%item))+'\n')
128 dagobah 1.1 (code, string) = self.get_response()
129 dagobah 1.2 return (code == '100', code, string)
130 dagobah 1.1
131     def beep(self, duration = None, synchronous = True):
132     msg = 'B'
133     if synchronous: msg += 'S'
134     if duration != None:
135     if duration > 255: duration = 255
136     if duration < 1: duration = 1
137     msg += '%02x'%duration
138     self.wfh.write(msg+'\n')
139     (code, string) = self.get_response()
140     return (code == '500', code, string)
141    
142     def silence(self, duration = None, synchronous = True):
143     msg = 'C'
144     if synchronous: msg += 'S'
145     if duration != None:
146     if duration > 255: duration = 255
147     if duration < 1: duration = 1
148     msg += '%02x'%duration
149     self.wfh.write(msg+'\n')
150     (code, string) = self.get_response()
151 dagobah 1.6 return (code == '501', code, string)
152 dagobah 1.1
153     def display(self, string):
154     if len(string) > 10:
155     string = string[0:10]
156 dagobah 1.15 string = re.sub('(.)\.', lambda match: '.'+match.group(1), string)
157 dagobah 1.1 self.wfh.write('D'+string+'\n')
158     (code, string) = self.get_response()
159     return (code == '300', code, string)
160    
161 dagobah 1.4 def next_event(self, timeout = None):
162     # we don't want to buffer in the serial port, so we get all the events
163     # we can ASAP.
164 dagobah 1.17 if timeout < 0: timeout = 0
165 dagobah 1.4 if len(self.events) > 0: timeout = 0
166 dagobah 1.2 while True:
167 dagobah 1.4 (r, _, _) = select([self.rfh], [], [], timeout)
168     if r:
169     self.get_response(async = True)
170 dagobah 1.5 timeout = 0
171 dagobah 1.4 else:
172     break
173 mtearle 1.16 if len(self.events) == 0: return (TICK, time())
174 dagobah 1.4 ret = self.events[0]
175     del self.events[0]
176     return ret

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26