09bfe669ae1897a7df246c55ebe32ce3e5f1443d
[zanchey/dispense2.git] / sql-edition / servers / VendServer.py
1 #!/usr/bin/python
2 # vim:ts=4
3
4 import sys, os, string, re, pwd
5 import pg
6 from time import time, sleep
7 from popen2 import popen2
8 from LATClient import LATClient
9 from VendingMachine import VendingMachine
10 from ConfigParser import ConfigParser
11
12 GREETING = 'UCC SNACKS'
13 PIN_LENGTH = 4
14
15 DOOR = 1
16 SWITCH = 2
17 KEY = 3
18
19 class DispenseDatabase:
20         def __init__(self, vending_machine, host, name, user, password):
21                 self.vending_machine = vending_machine
22                 self.db = pg.DB(dbname = name, host = host, user = user, passwd = password)
23                 self.db.query('LISTEN vend_requests')
24
25         def process_requests(self):
26                 print 'processing'
27                 query = 'SELECT request_id, request_slot FROM vend_requests WHERE request_handled = false'
28                 try:
29                         outstanding = self.db.query(query).getresult()
30                 except (pg.error,), db_err:
31                         sys.stderr.write('Failed to query database: %s\n'%(db_err.strip()))
32                         return
33                 for (id, slot) in outstanding:
34                         (worked, code, string) = self.vending_machine.vend(slot)
35                         print (worked, code, string)
36                         if worked:
37                                 query = 'SELECT vend_success(%s)'%id
38                                 self.db.query(query).getresult()
39                         else:
40                                 query = 'SELECT vend_failed(%s)'%id
41                                 self.db.query(query).getresult()
42
43         def handle_events(self):
44                 notifier = self.db.getnotify()
45                 while notifier is not None:
46                         self.process_requests()
47                         notify = self.db.getnotify()
48
49 def get_pin(uid):
50         try:
51                 info = pwd.getpwuid(uid)
52         except KeyError:
53                 return None
54         if info.pw_dir == None: return False
55         pinfile = os.path.join(info.pw_dir, '.pin')
56         try:
57                 s = os.stat(pinfile)
58         except OSError:
59                 return None
60         if s.st_mode & 077:
61                 return None
62         try:
63                 f = file(pinfile)
64         except IOError:
65                 return None
66         pinstr = f.readline()
67         f.close()
68         if not re.search('^'+'[0-9]'*PIN_LENGTH+'$', pinstr):
69                 return None
70         return int(pinstr)
71
72 def has_good_pin(uid):
73         return get_pin(uid) != None
74
75 def verify_user_pin(uid, pin):
76         if get_pin(uid) == pin:
77                 info = pwd.getpwuid(uid)
78                 return info.pw_name
79         else:
80                 return None
81
82 def door_open_mode(vending_machine):
83         print "Entering open door mode"
84         v.display("DOOR  OPEN")
85         while True:
86                 e = v.next_event()
87                 if e == None: break
88                 (event, params) = e
89                 if event == DOOR:
90                         if params == 1: # door closed
91                                 v.display("BYE BYE!")
92                                 sleep(1)
93                                 return
94
95 def center(str):
96         LEN = 10
97         return ' '*((LEN-len(str))/2)+str
98
99 class MessageKeeper:
100         def __init__(self, vendie):
101                 self.scrolling_message = []
102                 self.v = vendie
103                 self.next_update = None
104
105         def set_message(self, string):
106                 self.scrolling_message = [(string, False, None)]
107                 self.update_display(True)
108
109         def set_messages(self, strings):
110                 self.scrolling_message = strings
111                 self.update_display(True)
112
113         def update_display(self, forced = False):
114                 if not forced and self.next_update != None and time() < self.next_update:
115                         return
116                 if len(self.scrolling_message) > 0:
117                         newmsg = self.scrolling_message[0]
118                         if newmsg[2] != None:
119                                 self.next_update = time() + newmsg[2]
120                         else:
121                                 self.next_update = None
122                         self.v.display(self.scrolling_message[0][0])
123                         if self.scrolling_message[0][1]:
124                                 self.scrolling_message.append(self.scrolling_message[0])
125                         del self.scrolling_message[0]
126
127 if __name__ == '__main__':
128         cp = ConfigParser()
129         cp.read('/etc/dispense/servers.conf')
130         DBServer = cp.get('Database', 'Server')
131         DBName = cp.get('Database', 'Name')
132         DBUser = cp.get('VendingMachine', 'DBUser')
133         DBPassword = cp.get('VendingMachine', 'DBPassword')
134
135         ServiceName = cp.get('VendingMachine', 'ServiceName')
136         ServicePassword = cp.get('VendingMachine', 'Password')
137         # Open vending machine via LAT
138         if 0:
139                 latclient = LATClient(service = ServiceName, password = ServicePassword)
140                 (rfh, wfh) = latclient.get_fh()
141         else:
142                 #(rfh, wfh) = popen2('../../virtualvend/vvend.py')
143                 import socket
144                 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
145                 sock.connect(('localhost', 5150))
146                 rfh = sock.makefile('r')
147                 wfh = sock.makefile('w')
148         v = VendingMachine(rfh, wfh)
149         print 'PING is', v.ping()
150
151         db = DispenseDatabase(v, DBServer, DBName, DBUser, DBPassword)
152         cur_user = ''
153         cur_pin = ''
154         cur_selection = ''
155
156         mk = MessageKeeper(v)
157         mk.set_message(GREETING)
158         logout_timeout = None
159         last_timeout_refresh = None
160
161         while True:
162                 db.handle_events()
163
164                 if logout_timeout != None:
165                         time_left = logout_timeout - time()
166                         if time_left < 10 and last_timeout_refresh > time_left:
167                                 mk.set_message('LOGOUT: '+str(int(time_left)))
168                                 last_timeout_refresh = int(time_left)
169
170                 if logout_timeout != None and logout_timeout - time() <= 0:
171                         logout_timeout = None
172                         cur_user = ''
173                         cur_pin = ''
174                         cur_selection = ''
175                         mk.set_message(GREETING)
176
177                 mk.update_display()
178
179                 e = v.next_event(0)
180                 if e == None:
181                         e = v.next_event(0.1)
182                         if e == None:
183                                 continue
184                 (event, params) = e
185                 print e
186                 if event == DOOR:
187                         if params == 0:
188                                 door_open_mode(v);
189                                 cur_user = ''
190                                 cur_pin = ''
191                                 mk.set_message(GREETING)
192                 elif event == SWITCH:
193                         # don't care right now.
194                         pass
195                 elif event == KEY:
196                         key = params
197                         # complicated key handling here:
198                         if len(cur_user) < 5:
199                                 if key == 11:
200                                         cur_user = ''
201                                         mk.set_message(GREETING)
202                                         continue
203                                 cur_user += chr(key + ord('0'))
204                                 mk.set_message('UID: '+cur_user)
205                                 if len(cur_user) == 5:
206                                         uid = int(cur_user)
207                                         if not has_good_pin(uid):
208                                                 mk.set_messages(
209                                                         [(center('INVALID'), False, 0.7),
210                                                          (center('PIN'), False, 0.7),
211                                                          (center('SETUP'), False, 1.0),
212                                                          (GREETING, False, None)])
213                                                 cur_user = ''
214                                                 cur_pin = ''
215                                                 continue
216                                         cur_pin = ''
217                                         mk.set_message('PIN: ')
218                                         continue
219                         elif len(cur_pin) < PIN_LENGTH:
220                                 if key == 11:
221                                         if cur_pin == '':
222                                                 cur_user = ''
223                                                 mk.set_message(GREETING)
224                                                 continue
225                                         cur_pin = ''
226                                         mk.set_message('PIN: ')
227                                         continue
228                                 cur_pin += chr(key + ord('0'))
229                                 mk.set_message('PIN: '+'X'*len(cur_pin))
230                                 if len(cur_pin) == PIN_LENGTH:
231                                         username = verify_user_pin(int(cur_user), int(cur_pin))
232                                         if username:
233                                                 v.beep(0, False)
234                                                 cur_selection = ''
235
236                                                 msg = [(center('WELCOME'), False, 0.8),
237                                                            (center(username), False, 0.9)]
238                                                 msg.append(('CHOICES :', True, 1))
239                                                 msg.append(('55 - DOOR', True, 1))
240                                                 msg.append(('OR A SNACK', True, 1))
241                                                 mk.set_messages(msg)
242                                                 continue
243                                         else:
244                                                 v.beep(40, False)
245                                                 mk.set_messages(
246                                                         [(center('BAD PIN'), False, 1.0),
247                                                          (center('SORRY'), False, 0.5),
248                                                          (GREETING, False, None)])
249                                                 cur_user = ''
250                                                 cur_pin = ''
251                                                 continue
252                         elif len(cur_selection) == 0:
253                                 if key == 11:
254                                         cur_pin = ''
255                                         cur_user = ''
256                                         cur_selection = ''
257                                         v.display('BYE!')
258                                         sleep(0.5)
259                                         mk.set_message(GREETING)
260                                         continue
261                                 cur_selection += chr(key + ord('0'))
262                                 mk.set_message('SELECT: '+cur_selection)
263                         elif len(cur_selection) == 1:
264                                 if key == 11:
265                                         cur_selection = ''
266                                         mk.set_message('SELECT: ')
267                                         continue
268                                 else:
269                                         cur_selection += chr(key + ord('0'))
270                                         #make_selection(cur_selection)
271                                         # XXX this should move somewhere else:
272                                         if cur_selection == '55':
273                                                 v.display('GOT DOOR?')
274                                                 os.system('su - "%s" -c "dispense door"'%username)
275                                         elif cur_selection[1] == '8':
276                                                 v.display('GOT COKE?')
277                                                 os.system('su - "%s" -c "dispense %s"'%(username, cur_selection[0]))
278                                         else:
279                                                 v.display('HERES A '+cur_selection)
280                                                 v.vend(cur_selection)
281                                         sleep(0.5)
282                                         v.display('THANK YOU')
283                                         sleep(0.5)
284                                         cur_selection = ''
285                                         logout_timeout = time() + 10

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