def do_write_path_DB(cam_params, filepath): head, tail = os.path.split(filepath) logger.info('>>>do_write_path_DB: CAM= %s File= %s', cam_params, tail) #mariadb_connection = mariadb.connect(user=DBUSER, password=DBPASSWD, database=DB) #cursor = mariadb_connection.cursor() db_cursor = DB_mngt(HcDB.config()) if db_cursor.echec: sys.exit(1) # Mage 31/12 : MySql DATETIME values in 'YYYY-MM-DD HH:MM:SS' and MUST be UTC (django applies timez zone afterwards) # now = time.strftime("%Y-%m-%d %H:%M:%S") now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") #cursor.execute("INSERT INTO camera_history (timestamp,description,sensor_type,sensor_id) VALUES (%s,%s,%s,%s)", (now, tail[0:-4],"3",camera_id)) #mariadb_connection.commit() #mariadb_connection.close() # write into history req = "INSERT INTO {} (timestamp, userWEB_id, type, cameraID_id, event_code, event_description, video_file) VALUES ( %s, %s, %s, %s, %s, %s, %s )".format( "history_events") value = ( now, cam_params[1], "CA", cam_params[0], "800", EventCode.value("800")[0], tail[0:-4], ) db_cursor.executerReq(req, value) db_cursor.commit() #Mage record_id=cursor.lastrowid # write into camera.file_list # db_cursor.executerReq("""INSERT INTO camera_file_list (hist_id, filename) VALUES (%s,%s)""", (record_id, tail[0:-4]) ) # db_cursor.commit() # db_cursor.close() logger.info('<<<do_write_path_DB')
def do_write_path_DB(cam_params, filepath): head, tail = os.path.split(filepath) hclog.info('>>>do_write_path_DB: CAM= %s File= {}'.format( cam_params, tail)) db_cursor = DB_mngt(HcDB.config()) if db_cursor.echec: sys.exit(1) # Mage 31/12 : MySql DATETIME values in 'YYYY-MM-DD HH:MM:SS' and MUST be UTC (django applies timez zone afterwards) now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") # write into history req = "INSERT INTO {} (timestamp, userWEB_id, type, cameraID_id, event_code, event_description, video_file) VALUES ( %s, %s, %s, %s, %s, %s, %s )".format( "history_events") value = ( now, cam_params[1], "CA", cam_params[0], "800", EventCode.value("800")[0] + " on " + cam_params[3], tail[0:-4], ) db_cursor.executerReq(req, value) db_cursor.commit() #Mage record_id=cursor.lastrowid # write into camera.file_list hclog.info('<<<do_write_path_DB')
def translate(contactID, snsr_list, usr_list): hclog = logging.getLogger(__name__) alarmMsg = "" #[0730#74 18_1_751_00_003_2CA2] #[0730#119 18 3 401 00 015 C0CF] # MT Q EEE GG ZZZ Q = contactID[ -14:-13] # Q: Event qualifier 1: new event & disarm 3: restore & arm evt = contactID[-13:-10] # EEE: event code GG = contactID[ -10:-8] # GG: partition number (always 00 for non partitioned panels) sensor_id = contactID[ -7: -5] # ZZZ: representing zone number C 1 = 0 (fixed) , C 2 C 3 = Zone number sensor_id = sensor_id.lstrip( '0') or '0' # remove leading zeros in text string sensor_ref_id = None try: if evt == "401" or evt == "407": # GW has been armed/disarmed via Keyfob or Keypad user_name = "WEB" # if user is not found then user is type 14, meaning WEB but redundant with message type "401" for u in usr_list: # search for sensor name based on sensor ID if sensor_id == u[0]: user_name = u[1] break if Q == '1': alarmMsg = "Disarmed with " else: alarmMsg = "Armed with " alarmMsg += EventCode.value(evt)[0] alarmMsg += " by user " alarmMsg += user_name elif evt == "400": sensor_name = "" # keyfob searched based on device name for s in snsr_list: # search for sensor name based on sensor ID if sensor_id == s[1]: sensor_name = s[2] sensor_type = s[3] sensor_ref_id = s[0] break if Q == '1': alarmMsg = "Disarmed with " else: alarmMsg = "Armed with " alarmMsg += EventCode.value(evt)[0] alarmMsg += ": " alarmMsg += sensor_name elif evt == "602": alarmMsg += EventCode.value(evt)[0] alarmMsg += " = OK" sensor_id = None # the GW is not a sensor, will give a NULL in the history DB else: sensor_name = "" for s in snsr_list: # search for sensor name based on sensor ID if sensor_id == s[1]: sensor_name = s[2] sensor_type = s[3] sensor_ref_id = s[0] break if Q == '1': # new event alarmMsg += "Event: " alarmMsg += EventCode.value(evt)[ 0] # add event name on the message alarmMsg += " Sensor " alarmMsg += sensor_name else: evt = '000' # Q = 3 : Restore event : no need to process that message alarmMsg = "Event: Restore" except: hclog.info("ERROR ContactID: {}, evt:{}, GG:{}, sensorid:{}".format( contactID, evt, GG, sensor_id)) return ("") else: hclog.debug("Event: {}".format(alarmMsg)) return (evt, alarmMsg, EventCode.value(evt)[1], sensor_ref_id)
def translate(contactID, snsr_list): alarmMsg="" #[0730#74 18_1_751_00_003_2CA2] # MT Q XYZ GG CCC Q = contactID[-14:-13] evt= contactID[-13:-10] GG = contactID[-10:-8] sensor_id= contactID[-7:-5] sensor="" sensor_id = sensor_id.lstrip('0') or '0' # remove leading zeros in text string for s in snsr_list: # search for sensor name based on sensor ID if sensor_id == s[0]: sensor_name=s[1] sensor_type=s[2] break # print("Event={}".format(evt)) try: if GG == "01": GG="01" elif GG == "10": GG="02" elif GG == "11": GG="03" else : GG="00" # alarmMsg += ArmingRequest.value(GG) # alarmMsg += ": " if Q== '1': if sensor_type == '0' or sensor_type == '14' or sensor_type == '15' : alarmMsg += "Disarm: " else: alarmMsg += "New event: " elif Q == '3': if sensor_type == '0' or sensor_type == '14' or sensor_type == '15' : alarmMsg += "Armed: " else: alarmMsg += "Restore: " else: alarmMsg += "" # arm vie RC if evt == '400': alarmMsg += EventCode.value(evt)[0] alarmMsg += " User " alarmMsg += sensor_name # arm via WEB elif evt =='401' and (sensor_type == '14' or sensor_type == '15'): alarmMsg += EventCode.value(evt)[0] # arm via Keypad elif evt == '407': alarmMsg += EventCode.value(evt)[0] alarmMsg += " User " alarmMsg += sensor_name else: alarmMsg += EventCode.value(evt)[0] # add event name on the message alarmMsg += " Sensor " alarmMsg += sensor_name except: logging.info("Error ContactID: {}".format(contactID)) return( "" ) else: # print("Event= {}".format(alarmMsg), end='') logging.debug("Event: {}".format(alarmMsg)) return( evt, alarmMsg, EventCode.value(evt)[1] )
def Main(): opts = getopts() logPath= HcLog.config("logPath") retentionTime = int(HcLog.config("retentionTime")) moduleName = "care_svr" hclog = logging.getLogger() # must be the rotlogger, otherwise sub-modules will not benefit from the config. handler = TimedRotatingFileHandler(logPath + moduleName + '.log', when='midnight', backupCount=retentionTime) if opts.level == 'debug': hclog.setLevel(logging.DEBUG) handler.setLevel(logging.DEBUG) else: hclog.setLevel(logging.INFO) handler.setLevel(logging.INFO) formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s',datefmt='%b %d %H:%M:%S') handler.setFormatter(formatter) hclog.addHandler(handler) print('Care Server starting up') hclog.info('Care Server starting up' ) db_cur= DB_mngt( HcDB.config() ) if db_cur.echec: hclog.info("Cannot open DB") exit() else : # get naive date current_tz = pytz.timezone('Europe/Brussels') date = datetime.now().date() gwDB=DB_gw(db_cur) gw_list = gwDB.search_gw_with_Care_flag( "1" ) for gw in gw_list: hclog.info("Scan rules of Gw= {}, current time= {}".format(gw[0], datetime.today().strftime("%Y-%m-%d %H:%M:%S") ) ) rules= gwDB.search_rules_from_gwID( gw[0] ) for rule in rules: hclog.info("Rule: sensor_id {}, start_time {}, end_time {}".format(rule[1],rule[2],rule[3]) ) dt= datetime.combine(date, time(0, 0) ) + rule[2] start = current_tz.localize(dt).astimezone(pytz.utc) # convert to UTC time dt = datetime.combine(date, time(0, 0) ) + rule[3] end = current_tz.localize(dt).astimezone(pytz.utc) # convert to UTC time if start <= datetime.now(timezone.utc) <= end: # we are between the start and the end of the rule if rule[4] != "1": # rule was not valid during the last script run gwDB.upd_in_rule_flag(rule[0], "1") # update flag of rule id hclog.debug("Rule is applicable") break else: if rule[4] == "1": # the rule was valid during the last script run gwDB.upd_in_rule_flag(rule[0], "0") # deactivate flag of rule id evt_list = gwDB.apply_rule(rule[1], start.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%Y-%m-%d %H:%M:%S")) # check if there was sensor messages between start and end time hclog.debug( "Event List= {}".format(evt_list) ) if len(evt_list) == 0: hclog.debug( "No event found during rule validity period" ) snsr_list = gwDB.search_sensors_name_from_gwID( gw[0]) # get sensors from gateways sensor_name="" for s in snsr_list: # search for sensor name based on sensor ID if rule[1] == s[0]: sensor_name=s[2] break no_event= ("900", "Event: No motion detected on sensor {}".format(sensor_name), EventCode.value("900")[1], None) usr_profile = gwDB.search_usrprofile_from_gwID( gw[0] ) # get usr_profile from gateway = username, propertyaddr, SN_SMS, SN_Voice, prof.email, language now=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") req="INSERT INTO {} (timestamp, userWEB_id, type, gwID_id, sensorID_id, event_code, event_description) VALUES ( %s, %s, %s, %s, %s, %s, %s )".format("history_events") value= (now, usr_profile[0][0], "CR", gw[0],no_event[3], no_event[0], no_event[1]) db_cur.executerReq(req, value) db_cur.commit() send_notification(usr_profile[0], no_event) db_cur.close() hclog.info('Finished' )
def main(argv): level = "debug" logPath = HcLog.config("logPath") retentionTime = int(HcLog.config("retentionTime")) moduleName = "cameraFTP_svr" global hclog hclog = logging.getLogger( ) # must be the rotlogger, otherwise sub-modules will not benefit from the config. handler = TimedRotatingFileHandler(logPath + moduleName + '.log', when='midnight', backupCount=retentionTime) if level == 'debug': hclog.setLevel(logging.DEBUG) handler.setLevel(logging.DEBUG) else: hclog.setLevel(logging.INFO) handler.setLevel(logging.INFO) formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%b %d %H:%M:%S') handler.setFormatter(formatter) hclog.addHandler(handler) print("Starting {} with user {}".format(__name__, getpass.getuser())) for arg in sys.argv: print(arg) hclog.info("++++ {0} started with UID {1}, GID {2} ++++".format( argv[0], os.getuid(), os.getgid())) hclog.info(("Argument List: {}").format(str(sys.argv))) #000E8F88C2F1 201209031438030001.avi #000E8F9AF368 123456 201605181528390001.avi global FTP_file_path FTP_file_path = argv[1] # MAC_hex=argv[1][len(argv[1])-40:len(argv[1])-28] head, tail = os.path.split(argv[1]) MAC_hex = tail[0:12] MAC_str = do_MAC_formatting(MAC_hex) timestamp = argv[1][len(argv[1]) - 22:len(argv[1]) - 4] head, tail = os.path.split(argv[1]) hclog.info(("Camera MAC= {}, Timestamp= {}").format(MAC_str, timestamp)) res = do_search_DB(MAC_str) if res: do_clean_up_files(res) if do_movevideo(FTP_file_path, VIDEO_STORAGE + tail): do_write_path_DB(res, VIDEO_STORAGE + tail) do_create_vignette(VIDEO_STORAGE + tail) do_create_mp4(VIDEO_STORAGE + tail) os.remove(VIDEO_STORAGE + tail) camID = res[0] camName = res[3] notificationEnabled = res[4] if notificationEnabled == 1: # ( evt, alarmMsg, EventCode.value(evt)[1], sensor_ref_id ) notif_flag = EventCode.value("800")[ 1] # '800':("Camera motion detected", ("1", "1", "0")), event = [ "800", "Motion detected on camera: " + camName, notif_flag, camID ] profile = search_usrprofile_from_CamID( camID) # get user profile of the camera owner send_notification(profile, event) hclog.info("{0} successfully terminated".format(argv[0])) else: hclog.info("Issue with video file of camera {0}".format(MAC_str)) try: os.remove(FTP_file_path) except OSError as e: hclog.info("ERROR: Cannot delete: {0}, OS error: {1}".format( FTP_file_path, os.strerror(e.errno))) else: hclog.info("File deleted: {0}".format(FTP_file_path)) hclog.info("{0} successfully terminated".format(argv[0]))
def translate(contactID): alarmMsg="" sensor_id="" # to be sure it will be processed as a string sensor_name = "" #[0730#74 18_1_751_00_003_2CA2] # MT Q XYZ GG CCC Q = contactID[-14:-13] # 1: new event & disarm 3: restore & arm evt= contactID[-13:-10] GG = contactID[-10:-8] # sensor_id= contactID[-7:-5].lstrip("0") # representing zone number C 1 = 0 (fixed) , C 2 C 3 = Zone number #sensor = sensors.objects.filter(gwID = Glob.current_GW.id, no = sensor_id) sensor = sensors.objects.filter(gwID__id = Glob.current_GW.id, no=sensor_id) if sensor.exists() : sensor_name = sensor[0].name # print("Event={}".format(evt)) try: # alarmMsg += ArmingRequest[GG] # alarmMsg += ": " if Q == '1': if sensor_id == '14' or sensor_id == '15' : alarmMsg += "Disarm: " else: alarmMsg += "New event: " elif Q == '3': if sensor_id == '14' or sensor_id == '15' : alarmMsg += "Armed: " else: alarmMsg += "Restore: " else: alarmMsg += "" # arm vie RC if evt == '400': alarmMsg += EventCode.value(evt)[0] alarmMsg += " User " alarmMsg += sensor_name # arm via WEB elif evt == '401' and (sensor == '14' or sensor == '15'): alarmMsg += EventCode.value(evt)[0] # arm via Keypad elif evt == '407': alarmMsg += EventCode.value(evt)[0] alarmMsg += " User " alarmMsg += sensor_name else: alarmMsg += EventCode.value(evt)[0] alarmMsg += " Sensor " alarmMsg += sensor_name except: return("Error ContactID {}".format(contactID)) else: return( alarmMsg )