/[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.24 - (hide annotations) (download) (as text)
Sat Jan 12 14:43:49 2013 UTC (8 years, 5 months ago) by tpg
Branch: MAIN
CVS Tags: HEAD
Changes since 1.23: +2 -0 lines
File MIME type: text/x-python
Updated pin code to work off dispense server's copies

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

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26