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

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