# Mochad monitor # # Script is used to gather and control Mochad socket data # Security and sensor data is stored in database # Depends security database and mochad import socket import sys import time import os import signal import sqlite3 # handle Ctrl-C to not leave a dangling connection around def signal_handler(signal, frame): s.close() print 'Mochadmon.py: kill signal received, terminating...' sys.exit(0) # receive loop def receive(sock): sock.setblocking(0) total_data = [] while 1: try: data = sock.recv(1) if data != '': total_data.append(data) if data == '\n': return ''.join(total_data) else: time.sleep(0.01) except: pass return ''.join(total_data) # Database function def databaseexec(q): conn = sqlite3.connect('/run/shm/security') c = conn.cursor() # Execute Query returnedRows = c.execute(q) # Save the changes conn.commit() # Close Connection conn.close() return returnedRows # Process data def process(r): global activeunit d = resp.replace('\n', ' ').replace('\r', ' ').split(' ') # RFSEC Handling if len(d) > 5: datetime = d[0] + " " + d[1] direction = d[2] method = d[3] if direction == 'Rx' and ( method == 'RFSEC' or method == 'HTTP' or method== 'CAMSEC' ): # this is a command for RF SECURITY if d[4] == 'Addr:': SensorID = d[5].upper() if len(d) > 6 and d[6] == 'Func:': SensorData = d[7].replace('_', ' ').split(' ') SensorName = SensorData[-1] SensorFunc = SensorData[0] # Arm and Disarm Functions if "arm" in SensorFunc.lower() or SensorFunc == "Panic": print ("debug: %s %s set %s Alarm \n" % (datetime, SensorName, SensorFunc)) # Prepare Query query = "update currentalarmstatus set alarm_mode='%s,' sensor_name='$s', sensor_id='%s', last_update='%s' where rowid=1;" % (SensorFunc, SensorName, SensorID, datetime) processedsuccessfully = 1 # Add Functionality for Control of lights, outlets..etc elif SensorFunc == "Lights": LightStatus = SensorData[1] print ("debug: %s %s set Lights %s" % (datetime, SensorName, LightStatus)) processedsuccessfully = 1 # Window and Motion Sensors elif SensorFunc == "Contact" or SensorFunc == "Motion": SensorStatus = SensorData[1] if SensorData[-2] == "low": LowBatt = 1 print ("debug: %s %s Status %s, Battery Low!" % (datetime, SensorID, SensorStatus)) else lowBatt = 0 print ("debug: %s %s Status %s" % (datetime, SensorID, SensorStatus)) # Prepare Query query = "insert or ignore into sensors (sensor_id, sensor_locationid, sensor_type, sensor_status, sensor_last_update, battery_status) values('%s', 0, '%s', '%s', '%s', '%d');" % (SensorID, SensorName, SensorStatus, datetime, lowBatt) query2 = "update sensors set sensor_status='%s', sensor_last_update='%s', battery_status=1 where changes()=0 and sensor_id='%s';" % (SensorStatus, datetime, SensorID) # Execute query(s) if (databaseexec(query)) == 0 if(databaseexec(query2)) == 0 print ("debug: update %s Status failed!" % (SensorID)) processedsuccessfully = 0 else print ("debug: updated %s Status successfully" % (SensorID)) processedsuccessfully = 1 elif (databaseexec(query)) == 1 print ("debug: added %s Status successfully" % (SensorID)) processedsuccessfully = 1 # Add Functionality for PL and IR here # if processedsuccessfully == 1 return 0 else return 1 # hook up SIGINT handler signal.signal(signal.SIGINT, signal_handler) # create socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print 'Mochadmon.py: failed to create socket' sys.exit() print 'Mochadmon.py: socket created' # replace this with your IP, port is 1099 host = '127.0.0.1' port = 1099 s.connect((host, port)) print 'Mochadmon.py: socket connected to ' + host message = "st\n" try: # make sure we actually have a valid mochad connection s.sendall(message) reply = s.recv(4096) if reply == '': print 'Mochadmon.py: cannot receive reply from mochad' sys.exit() except socket.error: print 'Mochadmon.py: cannot establish successful connection' sys.exit() print 'Mochadmon.py: connection established successfully' # loop forever while True: resp = receive(s) if resp != '': print 'debug: ' + resp processRet = process(resp) if processRet != 0: print "Error occurred during processing" # just for debugging... os.system("pause")