def arm_system(self, mode): cur.execute("SELECT * FROM security_zones") self.zonedata = cur.fetchall() self.parent_conn, self.child_conn = Pipe() self.keep_piping = True self.send_disarm = False self.mode = mode n = 5 while n != 0: gui.console("Security system will be armed in "+str(n)+" seconds") n = n - 1 time.sleep(1) for i in self.zonedata: if inputs[int(i['pin'])].idling: inputs[int(i['pin'])].stop_input_idle() else: events[inputs[int(i['pin'])].event_id].stop_event() inputs[int(i['pin'])].stop_input_idle() self.pipe_threads[i['pin']] = Thread(target=self.pipe_listener, args=()) self.pipe_threads[i['pin']].start() self.watchdog_process[i['pin']] = Process(target=self.watchdog, args=(self.child_conn, i['pin'], i['name'])) self.watchdog_process[i['pin']].start() gui.console("System armed!") self.armed_status = True
def output_toggle_on_input_timeout(self, conn): while True: alreadyon = [] GPIO.wait_for_edge(int(self.trigger), GPIO.BOTH) conn.send("inputchange:"+str(self.trigger)+":on") gui.change_input_state(int(self.trigger), 1, "reg") for i in self.who: if outputs[i].input() == 0: alreadyon.append(i) gui.console("Pin already on") else: outputs[i].output(1) gui.change_output_state(int(i), 1) conn.send("pinchange:"+i+":on") targettime = int(time.time()) + int(self.timeout) changed = False while not targettime == int(time.time()): if GPIO.input(int(self.trigger)): if changed: conn.send("inputchange:"+str(self.trigger)+":on") gui.change_input_state(int(self.trigger), 1, "reg") changed = False targettime = int(time.time()) + self.timeout - 3 else: changed = True conn.send("inputchange:"+str(self.trigger)+":off") gui.change_input_state(int(self.trigger), 0, "reg") time.sleep(0.2) for i in self.who: if not i in alreadyon: outputs[i].output(1) conn.send("pinchange:"+i+":off") gui.change_output_state(int(i), 0)
def start_sockets(): ADDR = (HOST, PORT) serversock = socket(AF_INET, SOCK_STREAM) serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) serversock.bind(ADDR) serversock.listen(5) gui.console("Started socket server on port ", str(PORT)) while 1: clientsock, addr = serversock.accept() gui.console('...connected from:', addr) thread.start_new_thread(handler, (clientsock, addr))
def start_input_idle(self): if self.direction == "in": self.idling = True self.keep_piping = True self.parent_conn, self.child_conn = Pipe() self.pipe_thread = Thread(target=self.pipe_listener, args=()) self.pipe_thread.start() self.idle_process = Process(target=self.input_idle, args=(self.child_conn,)) self.idle_process.start() else: gui.console("Tried to start idle process on an output!")
def refresh_gui_sensors(self): gui.console("Started sensor gui refresh process") while self.run_sensor_refresh: for i in temp_sensors: temp = self.get_temperature(sensor_name = i, return_cache = False) self.temp[i] = temp gui.change_input_state(temp_sensors[i], temp, "temp") for i in light_sensors: light = self.get_light_level(sensor_name = i) gui.change_input_state(light_sensors[i], light, "light") time.sleep(5)
def record_temp_to_database(self): gui.console("Started temperature recording process") cur.execute("SELECT value FROM settings WHERE field = 'temp_interval'") interval = cur.fetchone() count = 0 while True: if int(count) == int(interval['value']): gui.console("Recording current temperatures to database") temp = self.temp[sensors_index['temp'][0]] cur.execute("""INSERT INTO temperature_records VALUES (NULL,%s,%s,now())""",(temp_sensors[sensors_index['temp'][0]],temp)) con.commit() count = 0 time.sleep(60) count = count + 1
def signal_handler(signal, frame): # Run all clean-up functions to indicate a safe shutdown gui.console('Closing server') for i in clients: i.close() for i in events: events[i].stop_event() for i in inputs: if inputs[i].idling: inputs[i].stop_input_idle() sensors.temp_process.terminate() sensors.run_sensor_refresh = False GPIO.cleanup() gui.end() os.remove('lock.pid') sys.exit(0)
def signal_handler(signal, frame): # Run all clean-up functions to indicate a safe shutdown gui.console('Closing server') for i in globals.clients: i.close() for i in globals.events: globals.events[i].stop_event() for i in globals.inputs: if globals.inputs[i].idling: globals.inputs[i].stop_input_idle() try: sensors.temp_process.terminate() except AttributeError: pass sensors.run_sensor_refresh = False GPIO.cleanup() if not globals.nogui: gui.end() os.remove('/etc/homeremote/lock.pid') sys.exit(0)
def addcamera(self, name, camera_type, camera_address, camera_username, camera_password): cur.execute("""INSERT INTO security_cameras VALUES (NULL,%s,NULL,%s,%s,%s,%s)""",(name, camera_type, camera_address, camera_username, camera_password)) con.commit() cur.execute("SELECT id FROM security_cameras WHERE name = '"+name+"'") camera_id = cur.fetchone() address = 8080 + int(camera_id['id']) gui.console(str(address)) with open("/etc/motion/motion.conf", "a") as motionconf: motionconf.write("\nthread /etc/motion/thread"+str(camera_id['id'])+".conf") with open("/etc/motion/thread"+str(camera_id['id'])+".conf", "a") as cameraconf: if camera_type == "usb": cameraconf.write("videodevice /dev/video1\ntext_left "+name+"\ntarget_dir /usr/share/nginx/www/cams/"+name+"\nwebcam_port "+str(address)) os.makedirs("/usr/share/nginx/www/cams/"+name) cur.execute("SELECT value FROM settings WHERE field = 'motion_server'") server = cur.fetchone() cur.execute("UPDATE security_cameras SET server_address = '"+server['value']+":"+str(address)+"' WHERE id = '"+str(camera_id['id'])+"'") con.commit() os.system("service motion restart") for i in clients: i.write_message("refreshpage:") gui.gb.screen.refresh()
def __init__(self, pin, name, in_type, direction): self.name = name self.direction = direction if direction == "out": if "mcp" in pin: if not globals.mcp_loaded: globals.mcp = extender.Adafruit_MCP230XX(busnum=1, address=0x20, num_gpios=16) globals.mcp_loaded = True gui.console("Setting up MCP23017 pin") self.mcp = True self.pin = int(pin[3:]) globals.mcp.config(self.pin, globals.mcp.OUTPUT) else: self.pin = int(pin) GPIO.setup(int(pin), GPIO.OUT) gui.add_output(name, pin) # thread.start_new_thread(self.identify, ()) elif direction == "in": self.pin = int(pin) self.in_type = in_type if in_type == "switch": GPIO.setup(int(pin), GPIO.IN, pull_up_down=GPIO.PUD_UP) self.start_input_idle() gui.add_input(name, pin, "reg") elif in_type == "motion": GPIO.setup(int(pin), GPIO.IN) self.start_input_idle() gui.add_input(name, pin, "reg") elif in_type == "temp": globals.sensors_index["temp"].append(str(self.name)) globals.temp_sensors[self.name] = str(self.pin) gui.add_input(name, pin, "temp") elif in_type == "light": globals.sensors_index["light"].append(str(self.name)) globals.light_sensors[self.name] = str(self.pin) gui.add_input(name, pin, "light") else: gui.console("Failed to setup GPIO: Unknown input type for pin " + str(self.pin)) return else: gui.console("Failed to setup GPIO: Unrecognized direction!") return gui.console("Setup new GPIO. Pin: " + str(pin) + ", Name: " + name + ", Direction: " + direction)
def __init__(self, pin, name, in_type, direction): self.name = name self.direction = direction if(direction == "out"): if "mcp" in pin: gui.console("Setting up MCP23017 pin") self.mcp = True self.pin = int(pin[3:]) mcp.config(self.pin, mcp.OUTPUT) else: self.pin = int(pin) GPIO.setup(int(pin), GPIO.OUT) gui.add_output(name, pin) #thread.start_new_thread(self.identify, ()) elif direction == "in": self.pin = int(pin) self.in_type = in_type if in_type == "switch": GPIO.setup(int(pin), GPIO.IN, pull_up_down=GPIO.PUD_UP) self.start_input_idle() gui.add_input(name, pin, "reg") elif in_type == "motion": GPIO.setup(int(pin), GPIO.IN) self.start_input_idle() gui.add_input(name, pin, "reg") elif in_type == "temp": sensors_index['temp'].append(str(self.name)) temp_sensors[self.name] = str(self.pin) gui.add_input(name, pin, "temp") elif in_type == "light": sensors_index['light'].append(str(self.name)) light_sensors[self.name] = str(self.pin) gui.add_input(name, pin, "light") else: gui.console("Failed to setup GPIO: Unknown input type for pin "+str(self.pin)) return else: gui.console("Failed to setup GPIO: Unrecognized direction!") return gui.console("Setup new GPIO. Pin: " + str(pin) + ", Name: " + name + ", Direction: " + direction)
def alarm_trip(self): self.trip_running = True cur.execute("SELECT value FROM settings WHERE field = 'alarm timeout'") timeout = cur.fetchone() n = int(timeout['value']) while n != 0: gui.console("Zone violation at "+",".join(self.trip_zones)+". Alarm will sound in "+str(n)) if not self.tripped: gui.console("System disarmed. Alarm countdown cancelled") self.keep_piping = False self.trip_zones = [] return n = n - 1 time.sleep(1) gui.console("Bang") for i in outputs: self.alarm_process[str(outputs[i].pin)] = Process(target=outputs[i].flash(), args=()) self.alarm_process[str(outputs[i].pin)].start()
def on_message(self, message): gui.console(message) args = message.split(":") # Create a new output (pin, name) if args[0] == "newoutput": if args[1] in outputs: self.write_message("error:GPIO already setup on pin " + args[1]) else: outputs[args[1]] = gpio(args[1], args[2], None, 'out') cur.execute("""INSERT INTO outputs VALUES (NULL,%s,%s)""",(args[2],args[1])) con.commit() for i in clients: i.write_message("addlight:"+args[1]+":"+args[2]) # Get all outputs that are currently on elif args[0] == "getoutputson": total = 0 on = 0 for i in outputs: if outputs[i].get_state() == 1: on = on + 1 else: total = total + 1 self.write_message("lightoverview:"+str(on)+":"+str(total)) # Set the state of an output (pin, state) elif args[0] == "setoutputstate": if args[1] in outputs: res = outputs[args[1]].output(args[2]) if res is True: self.write_message("ok:") else: self.write_message("error:" + str(res)) else: self.write_message("error:Output does not exist on pin " + args[1]) # Toggle a pin to the opposite state (pin) elif args[0] == "togglepin": if args[1] in outputs: res = outputs[args[1]].toggle() else: self.write_message("error:Output does not exist on pin " + args[1]) # Report back the state of pins as if they changed state elif args[0] == "declarepins": for i in outputs: gui.console(str(i)+" "+str(outputs[i].input())) if outputs[i].input() == 0: if outputs[i].mcp: self.write_message("pinchange:mcp"+str(outputs[i].pin)+":on") else: self.write_message("pinchange:"+str(outputs[i].pin)+":on") elif outputs[i].input() == 1: if outputs[i].mcp: self.write_message("pinchange:mcp"+str(outputs[i].pin)+":off") else: self.write_message("pinchange:"+str(outputs[i].pin)+":off") # Report back the state of all events as if they changed state elif args[0] == "declareevents": for i in events: if events[i].event_process != None: self.write_message("eventchange:"+str(events[i].id)+":on") else: self.write_message("eventchange:"+str(events[i].id)+":off") # Toggle the state of an event elif args[0] == "toggleevent": args[1] = int(args[1]) if events[args[1]].event_process != None: events[args[1]].stop_event() for i in clients: i.write_message("eventchange:"+str(args[1])+":off") else: events[args[1]].start_event() for i in clients: i.write_message("eventchange:"+str(args[1])+":on") # Remove a light from the system elif args[0] == "deletelight": cur.execute("""DELETE FROM outputs WHERE pin = %s""",(args[1])) con.commit() del outputs[args[1]] for i in clients: i.write_message("deletelight:"+args[1]) gui.remove_output(args[1]) # Create a new event (name, elif args[0] == "newevent": args[5] = args[5].replace("-", ":") cur.execute("""INSERT INTO events VALUES (NULL,%s,%s,%s,%s,%s,%s)""",(args[1],args[2], args[3], args[4], args[5], args[6])) con.commit() cur.execute("SELECT `id`, `trigger` FROM events WHERE name = '"+args[1]+"'") eventdat = cur.fetchone() events[eventdat['id']] = event(eventdat['id'], cur) # Remove an event from the system elif args[0] == "deleteevent": events[int(args[1])].stop_event() del events[int(args[1])] cur.execute("""DELETE FROM events WHERE id = '%s'""",(int(args[1]))) con.commit() for i in clients: i.write_message("deleteevent:"+args[1]) gui.remove_event(args[1]) # Create a new input (name, pin, type, ) elif args[0] == "newinput": if args[1] in inputs: self.write_message("error:Input already exists on pin "+args[2]) else: cur.execute("""INSERT INTO inputs VALUES (NULL,%s,%s,%s,%s)""",(args[1],args[2],args[3],args[4])) con.commit() inputs[args[2]] = gpio(args[2], args[1], args[3], "in") #events[int(args[2])] = event(0, True, args[2]) # Remove an input from the system elif args[0] == "deleteinput": cur.execute("SELECT name FROM events WHERE `trigger` = "+args[1]) if cur.fetchone(): self.write_message("error:Please delete the associated event for this input first!") else: cur.execute("""DELETE FROM inputs WHERE pin = %s""",(int(args[1]))) con.commit() if inputs[int(args[1])].in_type == "temp": del temp_sensors[inputs[int(args[1])].name] sensors_index['temp'].remove(inputs[int(args[1])].name) del sensors.temp[inputs[int(args[1])].name] elif inputs[int(args[1])].in_type == "light": del light_sensors[inputs[int(args[1])].name] sensors_index['light'].remove(inputs[int(args[1])].name) elif inputs[int(args[1])].in_type == "switch" or inputs[int(args[1])].in_type == "motion": inputs[int(args[1])].stop_input_idle() del inputs[int(args[1])] for i in clients: i.write_message("deleteinput:"+args[1]) gui.remove_input(args[1]) # Report back the current state of the security system elif args[0] == "securitystatus": if security.armed_status: self.write_message("securitystatus:armed:"+security.mode) else: self.write_message("securitystatus:disarmed") # Arm the security system in mode (mode) elif args[0] == "armalarm": thread.start_new_thread(security.arm_system, (args[1],)) for i in clients: i.write_message("securitystatus:armed:"+args[1]) elif args[0] == "disarmalarm": security.disarm_system() for i in clients: i.write_message("securitystatus:disarmed") elif args[0] == "addcamera": security.addcamera(args[1],args[2], args[3], args[4], args[5]) elif args[0] == "removecamera": security.removecamera(args[1]) elif args[0] == "gettemp": self.write_message("temperature:"+sensors.get_temperature()) elif args[0] == "gethumid": self.write_message("humidity:"+sensors.get_humidity()) elif args[0] == "getlightlevel": self.write_message("lightlevel:"+sensors.get_light_level())
def open(self): clients.append(self) gui.console("Websocket Opened")
def on_close(self): gui.console("Websocket closed") clients.remove(self)
elif args[0] == "getlightlevel": self.write_message("lightlevel:"+sensors.get_light_level()) def on_close(self): gui.console("Websocket closed") clients.remove(self) application = tornado.web.Application([(r"/", WebSocket),]) def signal_handler(signal, frame): # Run all clean-up functions to indicate a safe shutdown gui.console('Closing server') for i in clients: i.close() for i in events: events[i].stop_event() for i in inputs: if inputs[i].idling: inputs[i].stop_input_idle() sensors.temp_process.terminate() sensors.run_sensor_refresh = False GPIO.cleanup() gui.end() os.remove('lock.pid') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) if __name__ == "__main__": application.listen(9000, '0.0.0.0') gui.console("Server started. Waiting for clients") tornado.ioloop.IOLoop.instance().start()
def handle_client(self): message = self.message args = message.split(":") if args[0] == "newoutput": if globals.blockspi: if args[1] == "9" or args[1] == "10" or args[1] == "11": self.send("error:Cannot use these GPIO's while wireless sensors are in use!") return if globals.blocki2c: if args[1] == "2" or args[1] == "3": self.send("error:Cannot use these GPIO's while I2C GPIO expander is in use!") return if args[1] in globals.outputs: self.send("error:GPIO already setup on pin " + args[1]) else: globals.outputs[args[1]] = gpio(args[1], args[2], None, 'out') globals.cur.execute("INSERT INTO outputs VALUES (NULL,'%s','%s')" % (args[2],args[1])) globals.con.commit() for i in globals.clients: self.send("addlight:"+args[1]+":"+args[2]) # Get all outputs that are globals.currently on elif args[0] == "getoutputson": total = 0 on = 0 for i in globals.outputs: if globals.outputs[i].get_state() == 1: on = on + 1 else: total = total + 1 self.send("lightoverview:"+str(on)+":"+str(total)) # Set the state of an output (pin, state) elif args[0] == "setoutputstate": if args[1] in globals.outputs: res = globals.outputs[args[1]].output(args[2]) if res is True: self.send("ok:") else: self.send("error:" + str(res)) else: self.send("error:Output does not exist on pin " + args[1]) # Toggle a pin to the opposite state (pin) elif args[0] == "togglepin": if args[1] in globals.outputs: res = globals.outputs[args[1]].toggle() else: self.send("error:Output does not exist on pin " + args[1]) # Report back the state of pins as if they changed state elif args[0] == "declarepins": for i in globals.outputs: gui.console(str(i)+" "+str(globals.outputs[i].input())) if globals.outputs[i].input() == 0: if globals.outputs[i].mcp: self.send("pinchange:mcp"+str(globals.outputs[i].pin)+":off") else: self.send("pinchange:"+str(globals.outputs[i].pin)+":off") elif globals.outputs[i].input() == 1: if globals.outputs[i].mcp: self.send("pinchange:mcp"+str(globals.outputs[i].pin)+":on") else: self.send("pinchange:"+str(globals.outputs[i].pin)+":on") # Report back the state of all events as if they changed state elif args[0] == "declareevents": for i in globals.events: if globals.events[i].event_process != None: self.send("eventchange:"+str(globals.events[i].id)+":on") else: self.send("eventchange:"+str(globals.events[i].id)+":off") # Toggle the state of an event elif args[0] == "toggleevent": args[1] = int(args[1]) if globals.events[args[1]].event_process != None: globals.events[args[1]].stop_event() for i in globals.clients: self.send("eventchange:"+str(args[1])+":off") else: globals.events[args[1]].start_event() for i in globals.clients: self.send("eventchange:"+str(args[1])+":on") # Remove a light from the system elif args[0] == "deletelight": globals.cur.execute("DELETE FROM outputs WHERE pin = '%s'" % (args[1])) globals.con.commit() del globals.outputs[args[1]] for i in globals.clients: self.send("deletelight:"+args[1]) gui.remove_output(args[1]) # Create a new event (name, elif args[0] == "newevent": args[5] = args[5].replace("-", ":") globals.cur.execute("INSERT INTO events VALUES (NULL,'%s','%s','%s','%s','%s','%s')" % (args[1],args[2], args[3], args[4], args[5], args[6])) globals.con.commit() globals.cur.execute("SELECT `id`, `trigger` FROM events WHERE name = '"+args[1]+"'") eventdat = globals.cur.fetchone() globals.events[eventdat['id']] = event(eventdat['id']) # Remove an event from the system elif args[0] == "deleteevent": globals.events[int(args[1])].stop_event() del globals.events[int(args[1])] globals.cur.execute("DELETE FROM events WHERE id = '%s'" % (int(args[1]))) globals.con.commit() for i in globals.clients: self.send("deleteevent:"+args[1]) gui.remove_event(args[1]) # Create a new input (name, pin, type, ) elif args[0] == "newinput": if globals.blockspi: if args[1] == "9" or args[1] == "10" or args[1] == "11": self.send("error:Cannot use these GPIO's while wireless sensors are in use!") return if globals.blocki2c: if args[1] == "2" or args[1] == "3": self.send("error:Cannot use these GPIO's while I2C GPIO expander is in use!") return if args[1] in globals.inputs: self.send("error:Input already exists on pin "+args[2]) else: globals.cur.execute('INSERT INTO inputs VALUES (NULL,%s,%s,%s,%s)' % (args[1],args[2],args[3],args[4])) globals.con.commit() globals.inputs[args[2]] = gpio(args[2], args[1], args[3], "in") #events[int(args[2])] = event(0, True, args[2]) # Remove an input from the system elif args[0] == "deleteinput": globals.cur.execute("SELECT name FROM events WHERE `trigger` = "+args[1]) if globals.cur.fetchone(): self.send("error:Please delete the associated event for this input first!") else: globals.cur.execute("""DELETE FROM inputs WHERE pin = %s""",(int(args[1]))) globals.con.commit() if globals.inputs[int(args[1])].in_type == "temp": del globals.temp_sensors[globals.inputs[int(args[1])].name] globals.sensors_index['temp'].remove(globals.inputs[int(args[1])].name) del sensors.temp[globals.inputs[int(args[1])].name] elif globals.inputs[int(args[1])].in_type == "light": del globals.light_sensors[globals.inputs[int(args[1])].name] globals.sensors_index['light'].remove(globals.inputs[int(args[1])].name) elif globals.inputs[int(args[1])].in_type == "switch" or globals.inputs[int(args[1])].in_type == "motion": globals.inputs[int(args[1])].stop_input_idle() del globals.inputs[int(args[1])] for i in globals.clients: self.send("deleteinput:"+args[1]) gui.remove_input(args[1]) # Report back the current state of the security system elif args[0] == "securitystatus": if globals.security.armed_status: self.send("securitystatus:armed:"+globals.security.mode) else: self.send("securitystatus:disarmed") # Arm the security system in mode (mode) elif args[0] == "armalarm": thread.start_new_thread(globals.security.arm_system, (args[1],)) for i in globals.clients: self.send("securitystatus:armed:"+args[1]) elif args[0] == "disarmalarm": globals.security.disarm_system() for i in globals.clients: self.send("securitystatus:disarmed") elif args[0] == "addcamera": globals.security.addcamera(args[1],args[2], args[3], args[4], args[5]) elif args[0] == "removecamera": globals.security.removecamera(args[1]) elif args[0] == "gettemp": self.send("temperature:"+globals.sensors.get_temperature()) elif args[0] == "gethumid": self.send("humidity:"+globals.sensors.get_humidity()) elif args[0] == "getlightlevel": self.send("lightlevel:"+globals.sensors.get_light_level())
def start_websocket_server(): application = tornado.web.Application([(r"/", WebSocket),]) application.listen(9000, '0.0.0.0') gui.console("Server started. Waiting for clients") tornado.ioloop.IOLoop.instance().start()
def on_message(self, message): gui.console(message) h = serverhandler.handle(message, Server_type="web", Conn=self) h.handle_client()