virtualsnack.py 10.2 KB
Newer Older
1 2
#!/usr/bin/env python
import npyscreen
Mark Tearle's avatar
Mark Tearle committed
3
from datetime import datetime
4

5 6 7 8 9
# Incorporates code
# from http://www.binarytides.com/python-socket-server-code-example/
# Socket server in python using select function
import socket, select

Mark Tearle's avatar
Mark Tearle committed
10 11 12 13
# for emulator code
import sys
import string

Mark Tearle's avatar
Mark Tearle committed
14 15 16
class ContainedMultiSelect(npyscreen.BoxTitle):
    _contained_widget = npyscreen.TitleMultiSelect

17 18 19 20 21 22 23 24 25
class SnackButtonPress(npyscreen.MiniButtonPress):
    def __init__(self, screen, when_pressed_function=None, when_pressed_callback=None, *args, **keywords):
	super(SnackButtonPress, self).__init__(screen, *args, **keywords)
	self.when_pressed_callback = when_pressed_callback

    def whenPressed(self,key=None):
	if self.when_pressed_callback:
		self.when_pressed_callback(widget=self)

Mark Tearle's avatar
Mark Tearle committed
26 27 28 29 30 31 32 33 34 35 36 37 38
class Switches:
    def __init__(self):
        self.misc_input = 0xff
        self.switch_input = 0x3f
    def door_open(self):
        return self.switch_input & 0x20
    def set_door_open(self, open = True):
        if open:
            self.switch_input |= 0x20
        else:
            self.switch_input &= ~0x20


Mark Tearle's avatar
Mark Tearle committed
39
class VirtualSnack(npyscreen.Form):
40

Mark Tearle's avatar
Mark Tearle committed
41
    def while_waiting(self):
Mark Tearle's avatar
Mark Tearle committed
42
        self.date_widget.value = datetime.now().ctime()
43 44
	self.sentfield.value = self.parentApp.sent
	self.receivedfield.value = self.parentApp.received
Mark Tearle's avatar
Mark Tearle committed
45
	self.textdisplay.value = self.parentApp.textdisplay
Mark Tearle's avatar
Mark Tearle committed
46 47 48 49 50
        self.display()

    def create(self, *args, **keywords):
        super(VirtualSnack, self).create(*args, **keywords)

Mark Tearle's avatar
Mark Tearle committed
51
        self.textdisplay = self.add(npyscreen.FixedText, value=self.parentApp.textdisplay, editable=False, relx=9)
Mark Tearle's avatar
Mark Tearle committed
52 53 54 55 56 57 58 59
        self.textdisplay.important = True
	
	self.kpbuttons = []
	kpx = 1
	kpy = 1
	for keypad in range(0,10):
		kpx = ((keypad % 4) * 6 ) + 3
		kpy = int(keypad / 4) + 4
60 61 62
		widget = self.add(SnackButtonPress,name="%d"%keypad, relx = kpx, rely = kpy, when_pressed_callback=self.parentApp.when_keypad_pressed)
		self.kpbuttons.append(widget)
		self.add_handlers({"%d"%keypad: widget.whenPressed})
Mark Tearle's avatar
Mark Tearle committed
63
		
64 65 66
	self.reset=self.add(SnackButtonPress,name="RESET",  relx = kpx + 7, rely = kpy, when_pressed_callback=self.parentApp.when_reset_pressed)
	self.add_handlers({"R": self.reset.whenPressed})
	self.add_handlers({"r": self.reset.whenPressed})
Mark Tearle's avatar
Mark Tearle committed
67

Mark Tearle's avatar
Mark Tearle committed
68
	self.dip = self.add(npyscreen.MultiSelect, name = "Door", max_width=15, relx = 4, rely = 12, max_height=4, value = [], values = ["DOOR"], scroll_exit=True, value_changed_callback=self.parentApp.when_door_toggled)
Mark Tearle's avatar
Mark Tearle committed
69

Mark Tearle's avatar
Mark Tearle committed
70
	self.dip = self.add(npyscreen.MultiSelect, name = "DIP Switch", max_width=10, rely =3, relx = 35, max_height=10, value = [], values = ["DIP1", "DIP2", "DIP3","DIP4","DIP5","DIP6","DIP7","DIP8"], scroll_exit=True)
71

72 73 74 75
	self.nickel=self.add(SnackButtonPress,name="0.05", rely= 3, relx=50)
	self.dime=self.add(SnackButtonPress,name="0.10", relx=50)
	self.quarter=self.add(SnackButtonPress,name="0.25", relx=50)
	self.dollar=self.add(SnackButtonPress,name="1.00", relx=50)
Mark Tearle's avatar
Mark Tearle committed
76

77
	self.mode=self.add(SnackButtonPress,name="MODE", relx=50)
Mark Tearle's avatar
Mark Tearle committed
78

Mark Tearle's avatar
Mark Tearle committed
79
	
Mark Tearle's avatar
Mark Tearle committed
80
	self.date_widget = self.add(npyscreen.FixedText, value=datetime.now().ctime(), editable=False, rely=18)
Mark Tearle's avatar
Mark Tearle committed
81
        self.date_widget.value = "Hello"
Mark Tearle's avatar
Mark Tearle committed
82
	self.add_handlers({"^Q": self.exit_application})
83
        
Mark Tearle's avatar
Mark Tearle committed
84
	self.sentfield = self.add(npyscreen.TitleText, name = "Sent:", value="", editable=False, rely=20 )
85
        self.receivedfield = self.add(npyscreen.TitleText, name = "Received:", value="", editable=False )
86 87 88 89

    def exit_application(self,name):
        self.parentApp.setNextForm(None)
        self.editing = False
Mark Tearle's avatar
Mark Tearle committed
90 91 92


class VirtualSnackApp(npyscreen.NPSAppManaged):
93
    keypress_timeout_default = 1
Mark Tearle's avatar
Mark Tearle committed
94 95

    def onStart(self):
Mark Tearle's avatar
Mark Tearle committed
96 97 98 99 100 101
	# initialise virtual vending machine
        # vending machine password set here
        self.vendpw = "AAAAAAAAAAAAAAAA"
        self.switches = Switches()
	self.textdisplay = "*5N4CK0RZ*"

Mark Tearle's avatar
Mark Tearle committed
102
	self.F = self.addForm("MAIN", VirtualSnack, name="Virtual Snack")
103 104 105 106
	
	# socket code
    	self.CONNECTION_LIST = []    # list of socket clients
    	self.RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2
107
    	PORT = 5150
108 109 110 111 112 113 114 115 116 117 118 119

        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # this has no effect, why ?
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind(("0.0.0.0", PORT))
        self.server_socket.listen(10)
     
        # Add server socket to the list of readable connections
        self.CONNECTION_LIST.append(self.server_socket)

	self.sent=""
	self.received="Chat server started on port " + str(PORT)
120

121 122 123 124 125 126 127 128 129 130 131 132
    def while_waiting(self):
        # Get the list sockets which are ready to be read through select
        read_sockets,write_sockets,error_sockets = select.select(self.CONNECTION_LIST,[],[],0.01)
 
        for sock in read_sockets:
             
            #New connection
            if sock == self.server_socket:
                # Handle the case in which there is a new connection recieved through self.server_socket
                sockfd, addr = self.server_socket.accept()
                self.CONNECTION_LIST.append(sockfd)
                self.received = "Client (%s, %s) connected" % addr
Mark Tearle's avatar
Mark Tearle committed
133

134
		self.do_send("000 Virtual Snack is alive \n")
Mark Tearle's avatar
Mark Tearle committed
135
		self.do_prompt()
136 137 138 139 140 141 142 143 144 145
                 
                #Some incoming message from a client
            else:
                # Data recieved from client, process it
                try:
                    #In Windows, sometimes when a TCP program closes abruptly,
                    # a "Connection reset by peer" exception will be thrown
                    data = sock.recv(self.RECV_BUFFER)
                    # echo back the client message
                    if data:
Mark Tearle's avatar
Mark Tearle committed
146 147 148 149
			self.handle_command(data)
			#response = 'OK ... ' + data
                        #sock.send(response)
			#self.sent = response
150 151 152 153 154 155 156 157 158 159 160 161 162
			self.received = data
                 
                 
                # client disconnected, so remove from socket list
                except:
                    #print "Client (%s, %s) is offline" % addr
                    sock.close()
                    self.CONNECTION_LIST.remove(sock)
                    continue
             

    def onCleanExit(self):
        self.server_socket.close()
Mark Tearle's avatar
Mark Tearle committed
163 164 165 166 167 168 169 170 171 172 173 174
    
    # Snack Emulator comms below
    
    def do_send(self, data):
        # Get the list sockets which are ready to be written through select
        read_sockets,write_sockets,error_sockets = select.select([],self.CONNECTION_LIST,[],0.01)
 
        for sock in write_sockets:
		sock.send(data)

	self.sent = data

Mark Tearle's avatar
Mark Tearle committed
175 176 177 178 179 180 181 182 183 184 185

    # Callbacks
    def when_door_toggled(self, *args, **keywords):
# See 
#  https://code.google.com/p/npyscreen/source/detail?r=9768a97fd80ed1e7b3e670f312564c19b1adfef8#
# for callback info
        if keywords['widget'].get_selected_objects():
            self.do_send('401 door closed\n')
        else:
            self.do_send('400 door open\n')

Mark Tearle's avatar
Mark Tearle committed
186 187 188
    def when_reset_pressed(self, *args, **keywords):
        self.do_send('211 keypress\n')
        keywords['widget'].value = False
Mark Tearle's avatar
Mark Tearle committed
189 190 191 192 193 194 195
	self.F.display()

    def when_keypad_pressed(self, *args, **keywords):
	key = '0'+ keywords['widget'].name
        self.do_send('2'+key+' keypress\n')
        keywords['widget'].value = False
	self.F.display()
Mark Tearle's avatar
Mark Tearle committed
196

Mark Tearle's avatar
Mark Tearle committed
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    # Snack Emulator code below

    def do_prompt(self):
        self.do_send("# ")

    def do_help(self):
        help = """

Valid commands are:
ABOUT         ROM information
B[S][nn]      beep [synchronously] for a duration nn (optional)
C[S][nn]      silence [synchronously] for a duration nn (optional)
Dxxxxxxxxxx   show a message on the display
ECHO {ON|OFF} turn echo on or off
GETROM        download the ROM source code using xmodem
H[...]        this help screen
*JUMPxxxx      jumps to a subroutine at location xxxx
*PEEKxxxx      returns the value of the byte at location xxxx
*POKExxxxyy    sets the value of location xxxx to yy
PING          pongs
S[...]        query all internal switch states
+Vnn           vend an item
+VALL          vend all items
*Wxxxxxxxxxxxx set a new password for authenticated vends. xxx=16 chars
                   password will be converted to uppercase

Very few functions are available when the machine is in standalone
mode (DIP SW 1 is set)
+ denotes that this item requires authentication if DIP SW 2 is set
* denotes that DIP SW 3 must be set to use these
Commands starting with # are ignored (comments)
"""
        self.do_send(help)

    def do_about(self):
        about = """

The Virtual Vending^WSnack Machine Company

Mark Tearle, October 2014
"""
        self.do_send(about)

    def do_vend_all(self):
        for i in range(11,99):
            self.do_send("101 Vending "+str(i)+"\n")
            self.do_send("153 Home sensors failing\n")
        self.do_send("102 Vend all motors complete\n")

    def do_vend(self,command):
        fail = None
        if fail:
            self.do_send("153 Home sensors failing\n")
        else:
	# FIXME
        #     self.insert("Vending "+command)
            self.do_send("100 Vend successful\n")

    def do_display(self,string):
Mark Tearle's avatar
Mark Tearle committed
256
        self.textdisplay = "%-10.10s" % (string)
Mark Tearle's avatar
Mark Tearle committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        self.do_send('300 Written\n')

    def do_beep(self,command):
        sys.stdout.write("\a")
        self.do_send('500 Beeped\n')

    def do_silence(self,command):
        pass

    def do_switches(self):
        self.do_send("600 3F 3F\n")

    def do_pong(self):
        self.do_send("000 PONG!\n")

272 273 274
    def do_echo(self):
        self.do_send("000 Not implemented\n")

Mark Tearle's avatar
Mark Tearle committed
275 276 277 278
    def handle_command(self, command):
        command = string.upper(command)
        if string.find(command, "HELP",0) == 0:
            self.do_help()
279 280
        elif string.find(command, "ECHO",0) == 0:
            self.do_echo()
Mark Tearle's avatar
Mark Tearle committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        elif string.find(command, "ABOUT",0) == 0:
            self.do_about()
        elif string.find(command, "PING",0) == 0:
            self.do_pong()
        elif string.find(command, "VALL",0) == 0:
            self.do_vend_all()
        elif string.find(command, "V",0) == 0:
            self.do_vend(command)
        elif string.find(command, "B",0) == 0:
            self.do_beep(command)
        elif string.find(command, "C",0) == 0:
            self.do_silence(command)
        elif string.find(command, "S",0) == 0:
            self.do_switches()
        elif string.find(command, "D",0) == 0:
            self.do_display(command[1:])
        self.do_prompt()
298 299 300 301

if __name__ == "__main__":
    App = VirtualSnackApp()
    App.run()