/[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.21 - (hide annotations) (download) (as text)
Fri Feb 29 13:25:50 2008 UTC (13 years, 3 months ago) by dagobah
Branch: MAIN
Changes since 1.20: +25 -6 lines
File MIME type: text/x-python
Work from tonight:
MIFARE integration.
Old DAA patches for balance showing.
Eat easter eggs.

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

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26