2 import time, socket, os, stat, atexit
3 from datetime import datetime
4 import RPi.GPIO as GPIO
5 GPIO.setmode(GPIO.BOARD)
7 # ******** definitions *********
9 # TODO: loglevel, log like a real daemon
11 print (datetime.now(),what)
13 # send to client for information but don't care if it arrives
14 def waynesend (conn, what):
18 log("Couldn't send %s" % str(what))
20 # for command not found: do nothing with the pins and send a "0" to the client
26 # delete a file, don't care if it did not exist in the first place
28 if os.path.exists(name):
31 # commands: on a pin do a series of timed on/off switches
33 # name is for logging and also used for mapping command names to instances of this class
34 # actionsanddelays is a list of pairs: (bool to set on pin, delay in seconds to wait afterwards)
35 def __init__ (self, name, pinnumber, actionsanddelays):
38 self.todo = actionsanddelays
39 GPIO.setup(pinnumber, GPIO.OUT)
40 log ("Pin %d set to be an output pin for %s." % (pinnumber,name))
41 # actually send the signal to the pins
42 def __call__ (self, conn):
43 for (value,delay) in self.todo:
44 GPIO.output(self.pin, value)
45 log ("%s: Pin %d set to %s." % (self.name,self.pin,str(value)))
50 # ******** configuration *********
53 socketname = "/run/tuer.sock"
54 pinlist = [Pinoutput("open", 12, [(True, 0.3), (False, 5.0)]),
55 Pinoutput("close", 16, [(True, 0.3), (False, 5.0)]),
56 Pinoutput("buzz", 22, [(True, 2.0), (False, 0.1)])]
59 # ******** main *********
60 # at the end do a cleanup
61 atexit.register(GPIO.cleanup);
63 # convert list of pin objects to dictionary for command lookup
66 pindict[pin.name.encode()] = pin
69 sock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
70 # delete old socket file and don't bitch around if it's not there
72 # bind socket to file name
73 sock.bind (socketname)
74 # ensure we close and delete the socket when we quit (atexit.register is LIFO!)
75 atexit.register(forcerm, socketname)
76 atexit.register(sock.close)
77 # allow only users in the tuergroup to write to the socket
78 os.chown (socketname, 0, tuergroupid)
79 os.chmod (socketname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP)
80 # listen to the people, but not too many at once
84 # FIXME: DoS by opening socket but not sending data, because this loop is single threaded; maybe settimeout helps a bit.
87 conn, addr = sock.accept()
88 # TODO: use addr to determine the client for logging
89 # get some data from the client (enough to hold any valid command)
92 log("received command: %s" % str(data))
93 # lookup the command, if it's not in the dict, use the doNothing function instead
94 # and execute the looked up command or doNothing with the connection, so it can respond to the client
95 pindict.get(data,doNothing)(conn)
96 # close connection cleanly