3 import sys, os, string, socket, time, re
4 from popen2 import popen2
5 from pyPgSQL import PgSQL
6 from LATClient import LATClient
8 from binascii import unhexlify
10 asynchronous_responses = [ '400', '401', # door open/closed
11 '610', # switches changed
15 def __init__(self, rfh, wfh):
16 self.secret = 'AAAAAAAAAAAAAAAA'
20 # Initialise ourselves into a known state
23 self.wfh.write('echo off\n')
25 self.wfh.write('PING\n')
28 (code, _) = self.get_response()
30 def await_prompt(self):
37 if s == '': raise Exception
38 if s == '\n' or s == '\r':
41 if (s == '#' or s == '%') and state == 1: state = 2
42 if s == ' ' and state == 2:
46 if re.search('^[0-9a-fA-F]{4}$', prefix):
47 self.challenge = unhexlify(prefix)
50 def get_response(self):
55 s = self.rfh.readline()
56 if s == '': return None
60 if code in asynchronous_responses:
61 self.handle_event(code, text)
66 def handle_event(self, code, text):
69 def authed_message(self, message):
70 if self.challenge == None:
72 crc = do_crc('%c%c'%(self.challenge >> 8, self.challenge & 0xff))
73 crc = do_crc(self.secret, crc)
74 crc = do_crc(message, crc)
75 return message+'|'+('%04x'%crc)
78 self.wfh.write('PING\n')
79 (code, string) = self.get_response()
80 return (code == '000', code, string)
83 if not re.search('^[0-9][0-9]$', item):
84 return (False, 'Invalid item requested (%s)'%item)
85 self.wfh.write(self.authed_message(('V%s\n'%item)+'\n'))
86 (code, string) = self.get_response()
89 def beep(self, duration = None, synchronous = True):
91 if synchronous: msg += 'S'
93 if duration > 255: duration = 255
94 if duration < 1: duration = 1
95 msg += '%02x'%duration
96 self.wfh.write(msg+'\n')
97 (code, string) = self.get_response()
98 return (code == '500', code, string)
100 def silence(self, duration = None, synchronous = True):
102 if synchronous: msg += 'S'
104 if duration > 255: duration = 255
105 if duration < 1: duration = 1
106 msg += '%02x'%duration
107 self.wfh.write(msg+'\n')
108 (code, string) = self.get_response()
109 # FIXME: workaround a bug in rom W. should be just: return (code == '500', code, string)
110 return (code == '500' or code == '501', code, string)
112 def display(self, string):
114 string = string[0:10]
115 self.wfh.write('D'+string+'\n')
116 (code, string) = self.get_response()
117 return (code == '300', code, string)
119 if __name__ == '__main__':
120 # Open vending machine via LAT
121 latclient = LATClient(service = 'VEND', password = 'dmscptd')
122 (rfh, wfh) = latclient.get_fh()
123 v = VendingMachine(rfh, wfh)
124 print 'PING is', v.ping()
125 print 'BEEP is', v.beep()
126 print 'VEND 11 is', v.vend('11')
127 print 'SILENCE is', v.silence()
128 print 'DISPLAY is', v.display('GOOD NIGHT')