2 import time, socket, os, stat, atexit, errno
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
31 # only ignore error if it was "file didn't exist"
32 if e.errno != errno.ENOENT:
35 # commands: on a pin do a series of timed on/off switches
37 # name is for logging and also used for mapping command names to instances of this class
38 # actionsanddelays is a list of pairs: (bool to set on pin, delay in seconds to wait afterwards)
39 def __init__ (self, name, pinnumber, actionsanddelays):
42 self.todo = actionsanddelays
43 GPIO.setup(pinnumber, GPIO.OUT)
44 log ("Pin %d set to be an output pin for %s." % (pinnumber,name))
45 # actually send the signal to the pins
46 def __call__ (self, conn):
47 for (value,delay) in self.todo:
48 GPIO.output(self.pin, value)
49 log ("%s: Pin %d set to %s." % (self.name,self.pin,str(value)))
54 # ******** configuration *********
57 socketname = "/run/tuer.sock"
58 pinlist = [Pinoutput("open", 12, [(True, 0.3), (False, 5.0)]),
59 Pinoutput("close", 16, [(True, 0.3), (False, 5.0)]),
60 Pinoutput("buzz", 22, [(True, 2.0), (False, 0.1)])]
63 # ******** main *********
64 # at the end do a cleanup
65 atexit.register(GPIO.cleanup);
67 # convert list of pin objects to dictionary for command lookup
70 pindict[pin.name.encode()] = pin
73 sock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
74 # delete old socket file and don't bitch around if it's not there
76 # bind socket to file name
77 sock.bind (socketname)
78 # ensure we close and delete the socket when we quit (atexit.register is LIFO!)
79 atexit.register(forcerm, socketname)
80 atexit.register(sock.close)
81 # allow only users in the tuergroup to write to the socket
82 os.chown (socketname, 0, tuergroupid)
83 os.chmod (socketname, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP)
84 # listen to the people, but not too many at once
88 # FIXME: DoS by opening socket but not sending data, because this loop is single threaded; maybe settimeout helps a bit.
91 conn, addr = sock.accept()
92 # TODO: use addr to determine the client for logging
93 # get some data from the client (enough to hold any valid command)
96 log("received command: %s" % str(data))
97 # lookup the command, if it's not in the dict, use the doNothing function instead
98 # and execute the looked up command or doNothing with the connection, so it can respond to the client
99 pindict.get(data,doNothing)(conn)
100 # close connection cleanly