start of minimal functionality
[uccvend-vendserver.git] / virtualvend / vvend.py
1 #!/usr/bin/env python
2
3 import sys
4 import socket
5 import string
6
7 try:
8   import pygtk
9   #tell pyGTK, if possible, that we want GTKv2
10   pygtk.require("2.0")
11 except:
12   #Some distributions come with GTK2, but not pyGTK
13   pass
14
15 try:
16   import gtk
17   import gtk.glade
18 except:
19   print "You need to install pyGTK or GTKv2 ",
20   print "or set your PYTHONPATH correctly."
21   print "try: export PYTHONPATH=",
22   print "/usr/local/lib/python2.2/site-packages/"
23   sys.exit(1)
24
25 #now we have both gtk and gtk.glade imported
26 #Also, we know we are running GTK v2
27
28 class appgui:
29   def __init__(self):
30     """
31     In this init we are going to display the main
32     serverinfo window
33     """
34     gladefile="vvend.glade"
35     windowname="vvend"
36     self.wTree=gtk.glade.XML (gladefile,windowname)
37     # we only have two callbacks to register, but
38     # you could register any number, or use a
39     # special class that automatically
40     # registers all callbacks. If you wanted to pass
41     # an argument, you would use a tuple like this:
42     # dic = { "on button1_clicked" : 
43     #         (self.button1_clicked, arg1,arg2) , ...
44     
45     dic = { 
46         "on_button1_clicked" : self.keypad_clicked,
47         "on_button2_clicked" : self.keypad_clicked,
48         "on_button3_clicked" : self.keypad_clicked,
49         "on_button4_clicked" : self.keypad_clicked,
50         "on_button5_clicked" : self.keypad_clicked,
51         "on_button6_clicked" : self.keypad_clicked,
52         "on_button7_clicked" : self.keypad_clicked,
53         "on_button8_clicked" : self.keypad_clicked,
54         "on_button9_clicked" : self.keypad_clicked,
55         "on_button10_clicked" : self.keypad_clicked,
56         "on_button11_clicked" : self.keypad_clicked,
57         "on_vvend_destroy_event" : self.quit,
58         "on_vvend_delete_event" : self.quit }
59     self.wTree.signal_autoconnect (dic)
60     display = self.wTree.get_widget("label1")
61     display.set_text("*5N4CK0RZ*")
62
63     # vending machine password set here
64     self.vendpw = "AAAAAAAAAAAAAAAA"
65
66     self.messageid = None
67
68     #s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
69     #s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
70 #
71 #    listenhost=""
72 #    listenport=5150
73 #    s.bind((listenhost, listenport))
74 #    # only one connection
75 #    s.listen(1)
76 #    s.setblocking(1)
77 #    #GDK->gtk.gdk in GTK V 2.0
78 #    id=gtk.input_add(s, gtk.gdk.INPUT_READ, self.handleNewConnection)
79
80     self.server()
81
82
83     return
84   
85 #####CALLBACKS
86   def keypad_clicked(self,widget):
87     print "button clicked"
88     print widget.get_label()
89     self.do_send(widget.get_label())
90     sys.stdout.write("\a")
91
92   def handleNewConnection(self,source,condition):
93     #source is a socket in GTK v 1 and a fd in version 2
94     conn, addr = source.accept()
95     sys.stdout.write(conn.recv(1))
96     conn.send("bing\n")
97     return gtk.TRUE
98
99 # from http://www.pythonbrasil.com.br/moin.cgi/MonitorandoSocketsComPygtk
100
101
102   def send(self, data=None, widget=None):
103      text = self.entry.get_text()
104      self.do_send(text)
105      self.entry.set_text('')
106
107      #
108
109   def do_send(self, data):
110
111      # envia ''data'' para todos os clientes conectados
112
113      for addr, (conn, tag) in self.clients.iteritems():
114             conn.send(data)
115
116   def server(self):
117
118      # inicializa o servidor
119      port = 5150
120
121      self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
122      self.sock.bind(('localhost', port))
123      self.sock.listen(0)
124      print "listening on ", port
125
126      # 
127      #
128
129      self.server_tag = gtk.input_add(self.sock, gtk.gdk.INPUT_READ, self.accept)
130
131      # mantemos uma lista dos clientes conectados
132
133      self.clients = {}
134
135   def accept(self, source, condition):
136
137      #
138      # esperando para ser aceito
139
140      conn, addr = source.accept()
141      self.insert("%s:%s conectado\n" % addr)
142
143      # insere o cliente na lista e registra o método self.write como 
144      # callback para quando existirem dados esperando para serem lidos
145
146      self.do_prompt()
147      self.clients[addr] = (conn, gtk.input_add(conn, gtk.gdk.INPUT_READ, self.write))
148
149   def write(self, source, condition):
150
151      # método chamado quando um cliente envia dados 
152
153      data = source.recv(1024)
154      if data.strip() == 'bye' or not len(data):
155
156             # se o cliente enviar um ''bye'', desconecte-o :)
157
158             source.close()
159             for addr, (conn, tag) in self.clients.iteritems():
160                 if source is conn:
161                     gtk.input_remove(tag)
162                     self.insert('%s:%s desconectado\n' % addr)
163                     del self.clients[addr]
164                     
165                     self.server_tag = gtk.input_add(self.sock, gtk.gdk.INPUT_READ, self.accept)
166                     break
167      elif data.strip() == 'quit':
168         self.quit()
169      else:
170             for (addr, port), (conn, tag) in self.clients.iteritems():
171                 if source is conn:
172                     self.insert('%s:%s >>> %s\n'%(addr, port, data.strip()))
173                     self.handle_command(data.strip())
174                     break
175      
176      return gtk.TRUE
177
178   def insert(self, data):
179      statusbar = self.wTree.get_widget("statusbar1")
180      if self.messageid:
181         statusbar.remove(1, self.messageid)
182      self.messageid=statusbar.push(1,data)
183
184   def quit(self, *args):
185      sys.stdout.write("quiting...\n")
186      gtk.input_remove(self.server_tag)
187      for addr, (conn, tag) in self.clients.iteritems():
188             gtk.input_remove(tag)
189             conn.close()
190      self.sock.close()
191
192      gtk.mainquit()
193      sys.stdout.write("quit!\n")
194
195   def do_prompt(self):
196     self.do_send("# ")
197
198   def do_help(self):
199     help = """
200
201 Valid commands are:
202  ABOUT         ROM information
203  B[S][nn]      beep [synchronously] for a duration nn (optional)
204  C[S][nn]      silence [synchronously] for a duration nn (optional)
205  Dxxxxxxxxxx   show a message on the display
206  ECHO {ON|OFF} turn echo on or off
207  GETROM        download the ROM source code using xmodem
208  H[...]        this help screen
209 *JUMPxxxx      jumps to a subroutine at location xxxx
210 *PEEKxxxx      returns the value of the byte at location xxxx
211 *POKExxxxyy    sets the value of location xxxx to yy
212  PING          pongs
213  S[...]        query all internal switch states
214 +Vnn           vend an item
215 +VALL          vend all items
216 *Wxxxxxxxxxxxx set a new password for authenticated vends. xxx=16 chars
217                password will be converted to uppercase
218
219 Very few functions are available when the machine is in standalone 
220 mode (DIP SW 1 is set)
221 + denotes that this item requires authentication if DIP SW 2 is set
222 * denotes that DIP SW 3 must be set to use these
223 Commands starting with # are ignored (comments)
224 """
225     self.do_send(help)
226   
227   def do_about(self):
228     about = """
229
230 The Virtual Vending Machine Company
231
232 Mark Tearle, June 2004
233 """
234     self.do_send(about)
235
236   def do_vend_all(self):
237      for i in range(11,99):
238         self.do_send("101 Vending ",i)
239         self.do_send("153 Home sensors failing")
240      self.do_send("102 Vend all motors complete")
241   
242   def do_vend(self,command):
243      self.do_send("153 Home sensors failing")
244     
245   def do_display(self,string):
246      display = self.wTree.get_widget("label1")
247      display.set_text("%10.10s" % (string))
248
249   def do_beep(self,command):
250      sys.stdout.write("\a")
251
252   def do_silence(self,command):
253      pass
254
255
256   def handle_command(self, command):
257      command = string.upper(command)
258      print command
259      if string.find(command, "HELP",0) == 0:
260         self.do_help()
261      elif string.find(command, "ABOUT",0) == 0:
262         self.do_about()
263      elif string.find(command, "VALL",0) == 0:
264         self.do_vend_all()
265      elif string.find(command, "V",0) == 0:
266         self.do_vend(command)
267      elif string.find(command, "B",0) == 0:
268         self.do_beep(command)
269      elif string.find(command, "S",0) == 0:
270         self.do_silence(command)
271      elif string.find(command, "D",0) == 0:
272         self.do_display(command[1:-1])
273      self.do_prompt()
274         
275
276 # we start the app like this...
277 app=appgui()
278 gtk.mainloop()
279
280
281 # notes
282 # http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq20.011.htp

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