def scan_for_humans(frame): current = datetime.datetime.now() """ Scan the frame for any humans (pedestrians). """ frame = imutils.resize(frame, width=min(400, frame.shape[1])) (rects, weights) = people_hog.detectMultiScale(frame, winStride=(4, 4), padding=(8, 8), scale=1.05) rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects]) pick = non_max_suppression(rects, probs=None, overlapThresh=0.65) for (xA, yA, xB, yB) in pick: if elapsed_frames == 0: cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2) elapsed_frames += 1 name = "Events/%d-%d-%d %d-%d-%d.jpg"\ % (current.day, current.month, current.year,\ current.hour, current.minute, current.second) cv2.imwrite(name, frame) notifier.send_notification( "Pedestrian detected while armed", "Detected in X: " + str(xA) + ", Y: " + str(yA) + " at " + str(current), [name]) return
def check_for_update(): # get date and time as string now = datetime.now() filename = '/root/campbell/{}.pdf'.format(now.strftime("%Y%d%m%H%M%S")) # download file url = 'https://tonyteaches.tech/test.pdf' urllib.request.urlretrieve(url, filename) # get hashes try: hash_latest = sha1('/root/campbell/latest.pdf') except: move_files(filename) print('First file saved') return hash_new = sha1(filename) # compare hashes if hash_latest != hash_new: print('Found update') move_files(filename) send_notification(url) else: print('No update') os.remove(filename)
def __init__(self, id=None, create=None, db_config=("127.0.0.1", "my_database", "my_user"), related_task_id=None, mustExit=None): assert id or create, "Bad arguments, no id nor create" assert id == None or isinstance( id, int), "Bad arguments id, must be an int" assert mustExit, "Bad arguments, mustExit not provided" assert create == None or ( isinstance(create, tuple) and 3 <= len(create) <= 4 ), "Bad argument create, must be (user_id,type,request in json[,is_visible_to_user true/false])" self.db = DBHandler(db_config) if create: self.status, self.progress_percent, self.user_id, self.type, self.request, self.result = "created", 0, create[ 0], create[1], create[2], [] if isinstance(self.request, str): self.request = json.loads(self.request) r = self.db.execute( "INSERT INTO tasks (status, progress_percent, type, request, user_id) VALUES (%s, %s, %s, %s::jsonb, %s) RETURNING id, start_date, end_date ;", [ self.status, self.progress_percent, self.type, json.dumps(self.request), self.user_id ]) r = self.db.fetchall(r) self.id, self.start_date, self.end_date = r[0] if related_task_id: self.db.execute( "UPDATE tasks SET related_task_id = %s WHERE id = %s", [related_task_id, self.id]) self.related_task_id = related_task_id with Notifier() as notifier: notifier.send_notification( "task", "id={},status=created".format(self.id)) else: r = self.db.execute( "SELECT status, progress_percent, type, request, result, user_id, start_date, end_date, related_task_id FROM tasks WHERE id = %s;", [id]) r = self.db.fetchall(r) self.id = id self.status, self.progress_percent, self.type, self.request, self.result, self.user_id, self.start_date, self.end_date, self.related_task_id = r[ 0] if self.result == None: self.result = []
def scan_for_motion(frame): current = datetime.datetime.now() frame = imutils.resize(frame, width=500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) if first_frame is None: first_frame = gray frameDelta = cv2.absdiff(first_frame, gray) thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1] # dilate the thresholded image to fill in holes, then find contours # on thresholded image thresh = cv2.dilate(thresh, None, iterations=2) cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\ cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) for c in cnts: # if the contour is too small or too large, or we # are out of bounds, ignore it (x, y, w, h) = cv2.boundingRect(c) if cv2.contourArea(c) < json_obj["motion_detection"]["min_area_px"]\ or cv2.contourArea(c) > json_obj["motion_detection"]["max_area_sq_px"]: elapsed_frames = max(0, elapsed_frames - 1) return for zone in json_obj["motion_detection"]["exclusion_zones"]: for attr, val in zone.items(): if (x > val[0] - val[2] and x < val[0] + val[2])\ or (y > val[1] - val[2] and y < val[1] + val[2]): elapsed_frames = max(0, elapsed_frames - 1) return if elapsed_frames == 0: elapsed_frames += 1 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) name = "Events/%d-%d-%d %d-%d-%d.jpg"\ % (current.day, current.month, current.year,\ current.hour, current.minute, current.second) cv2.imwrite(name, frame) notifier.send_notification("Motion detected while armed",\ "Detected in X: " + str(x) + ", Y: " + str(y)\ + " at " + str(current), [name]) return elapsed_frames = max(0, elapsed_frames - 1)
def send_alert(self,item,handler_obj): alert_receivers = item["receivers"] notification_items = handler_obj.notification_items() alert_notification_item = item["notification_item"] notification_info = notification_items[alert_notification_item] rootlogger.info("Sending alert to receivers:"+str(notification_info)) for alert_receiver in alert_receivers: receiver = notifications.receivers[alert_receiver] notifier.send_notification(receiver,item["description"],str(notification_info)) rootlogger.debug("Alert sent to receiver: "+str(receiver))
def send_notifications_thread(pincode, pincode_info): by_pincode = user_requests_by_pincode.get(pincode, set()) if len(by_pincode) > 0: for user_id, age in by_pincode: # user_info dic is updated every 5 minutes by another thread user_info = user_info_by_user_id.get(user_id, None) if user_info is None: logger.log( DEBUG, '******** Impossible event, debug immediately. ********') continue # check if it is already being processed notification_critical_section_key = f'{user_id}_{pincode}_{age}' if notification_critical_section_key in notification_critical_section: continue notification_critical_section.add( notification_critical_section_key) # -------------- this code is part of critical section notification_type, send_time = send_notification( user_id, pincode, age, pincode_info, user_info) if send_time is not None: # update cached object set_key(user_info, ['notificationState', f'{pincode}_{age}'], { 'timestamp': send_time, 'type': notification_type }) # ----------------------------------------------------- notification_critical_section.remove( notification_critical_section_key) if send_time is not None: # wait if message was sent, to ease on telegram api # notifications are sent in short bursts (experimental) time.sleep(0.5)
def handle(self): Contact_ID_filter = re.compile( r'^\[[0-9A-Fa-f]{4}#[0-9A-Fa-f\s]{4}18[0-9A-Fa-f\s]{13}\]$' ) # contact ID self.request.settimeout(10) self.IPaddr = self.client_address[0] try: self.data = self.request.recv(32) except socket.timeout: # fail after x seconds of no activity, connection automatically closed now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") hclog.info( "ERROR: session opened without content UTC {} [client {}] {}". format(now, self.IPaddr, threading.current_thread())) else: now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") hclog.info("Contact ID: UTC {} {} [client {}]:{} {}".format( now, self.data, self.client_address[0], self.client_address[1], threading.current_thread())) try: data = self.data.decode() if Contact_ID_filter.match(data): self.request.sendall( b'\x06') # respond only if Contact ID is correct hclog.debug("Contact ID format OK, acknowledge sent") rptipid = data[1:5] tmp = data[6:].split(' ') acct2 = tmp[0] db_cur = DB_mngt(HcDB.config()) if db_cur.echec: hclog.info("Cannot open DB") else: gw = DB_gw(db_cur) # returns the_id of the gateway gw_id = gw.search_gw_from_acct(rptipid, acct2) if gw_id == []: hclog.info( " No Gw found with acct2= {}".format(acct2)) else: hclog.debug(" on Gw_id {}".format(gw_id[0][0])) snsr_list = gw.search_sensors_name_from_gwID( gw_id[0][0]) # get sensors from gateways usr_list = gw.search_users_name_from_gwID( gw_id[0][0]) # get users from gateways) event = [ ] # data [0730#74 181751000032CA2] event = translate( data, snsr_list, usr_list ) # returns event code, formated alarm message, event action (send SMS, email , call) if event[0] != '000': #get info about user #user_id, propertyaddr, SN_SMS, SN_Voice, prof.email, language " usr_profile = gw.search_usrprofile_from_gwID( gw_id[0][0] ) # get usr_profile from gateway = username, propertyaddr, SN_SMS, SN_Voice, prof.email, language 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], "GW", gw_id[0][0], event[3], event[0], event[1]) db_cur.executerReq(req, value) db_cur.commit() send_notification(usr_profile[0], event) if event[0] == "400" or event[ 0] == "407": # check if Horus has been armed via keyfob / keypad, then arm camera if relevant if event[ 1][: 5] == "Armed": # dirty implementation ;-) , should pass the alarm status instead securityStatus = 1 elif event[ 1][: 8] == "Disarmed": # dirty implementation ;-) , should pass the alarm status instead securityStatus = 0 else: securityStatus = 9 if securityStatus == 0 or securityStatus == 1: cam_cursor = DB_camera(db_cur) cam_list = cam_cursor.search_cam_list_from_user( usr_profile[0][0]) # returns : id, securityStatus (char), activateWithAlarm (Bolean) for cam in cam_list: if cam[2] == 1: #send "Arm/Disarm command to the camera" #add_camera_cmd( self, cam_id, cmd): cam_cursor.add_camera_cmd( cam[0], 'GET /adm/set_group.cgi?group=SYSTEM&pir_mode={} HTTP/1.1\r\n' .format(securityStatus)) cam_cursor.add_camera_cmd( cam[0], 'GET /adm/set_group.cgi?group=EVENT&event_trigger=1&event_interval=0&event_pir=ftpu:1&event_attach=avi,1,10,20 HTTP/1.1\r\n' ) #change the camera security status #update_camera_status(self, cam_id, status) cam_cursor.update_camera_security_flag( cam[0], securityStatus) db_cur.commit() hclog.info( "Camera {} Armed/disarmed ( {} ) on Gw {} request" .format( cam[0], securityStatus, gw_id[0][0])) # "if..." close the opened DB db_cur.close() # data not matching the Contact ID format else: hclog.info( "ERROR: Bad Contact ID: UTC {} {} [client {}]".format( now, self.data, self.client_address[0])) except: if 'db_cur' in locals(): db_cur.close() hclog.info( "ERROR: bad Contact ID translation or user error in DB or issue sending notification: UTC {} {} [client {}]" .format(now, self.data, self.client_address[0])) finally: self.request.close() finally: pass
def Main(): opts = getopts() logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=get_logging_level(opts)) # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_ip = Rpt_svr.config("ip") server_port = Rpt_svr.config("port") server = (server_ip, int(server_port)) logging.info('starting up on %s port %s' % server) sock.bind(server) # Listen for incoming connections sock.listen(1) Contact_ID_filter = re.compile(r'^\[[0-9A-Fa-f]{4}#[0-9A-Fa-f\s]{4}18[0-9A-Fa-f\s]{13}\]$') # contact ID while True: # Wait for a connection # print ('waiting for a connection') try: connection, client_address = sock.accept() # print ('connection from {}'.format(client_address)) # Receive the data in small chunks and retransmit it while True: try: data = connection.recv(32) except SocketError as e: errno, strerror = e.args logging.info("Socket errorI/O error({0}): {1}".format(errno,strerror)) else: if data: now=datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") # now = time.strftime("%Y-%m-%d %H:%M:%S") logging.info("Contact ID: {} {} ".format(now, data)) try: data = data.decode() if Contact_ID_filter.match(data): connection.sendall( b'\x06' ) # respond only if Contact ID is correct logging.debug("Contact ID format OK, acknowledge sent") rptipid = data[1:5] tmp = data[6:].split(' ') acct2 = tmp[0] db_cur= DB_mngt( HcDB.config() ) if db_cur.echec: logging.info("Cannot open DB") else : gw=DB_gw(db_cur) gw_id = gw.search_gw_from_acct( rptipid, acct2 ) # returns gateways_id if gw_id == []: logging.info( " No Gw found with acct2= {}".format(acct2)) else: logging.debug( " on Gw_id {}".format(gw_id[0][0])) snsr_list = gw.search_sensors_name_from_gwID( gw_id[0][0] ) # get sensors from gateways event=[] # data [0730#74 181751000032CA2] event = translate(data, snsr_list) # returns event code, formated alarm message, event action (send SMS, email , call) usr_profile = gw.search_usrprofile_from_gwID( gw_id[0][0] ) # get usr_profile from gateway = username, propertyaddr, SN_SMS, SN_Voice, prof.email, language req="INSERT INTO {} (timestamp, userWEB_id, type, gwID_id, event_code, event_description) VALUES ( %s, %s, %s, %s, %s, %s )".format("history_events") value= (now, usr_profile[0][0], "GW", gw_id[0][0],event[0], event[1], ) db_cur.executerReq(req, value) db_cur.commit() db_cur.close() send_notification(usr_profile[0], event) else: logging.info("Error: bad contact id format") except: db_cur.close() logging.info("Error: bad Contact ID translation or user error in DB or issue sending notification") else: # print ('no more data from {}'.format(client_address)) break finally: # Clean up the connection connection.close() db_cur.close()
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]))
(data['name'], data['serious_old'], data['serious_new'])) if "rec_old" in data: message.append( "- Total number of recovered patients in %s has risen from %s to %s" % (data['name'], data['rec_old'], data['rec_new'])) for data in insertions: new_message = "- New data for %s added: " % (data['name']) cases = [] if data['total'] > 0: cases.append("%d total cases" % (data['total'])) if data['active'] > 0: cases.append("%d active cases" % (data['active'])) if data['serious'] > 0: cases.append("%d serious cases" % (data['serious'])) if data['recovered'] > 0: cases.append("%d patients recovered" % (data['recovered'])) if data['death'] > 0: cases.append("%d patients died" % (data['death'])) new_message += ', '.join(cases) message.append(new_message) if message: message = '\n'.join(message) logger.info("\n" + message) print(message) send_notification(message) else: logger.info("No new updates from the world") except Exception as e: logger.error(e) # Error in parsing
def cli(os, processor, arch, host, python, uptime, bt, temp, load): if os: r = os_details() notifier.send_notification("Operating System", r) elif processor: p = processor_details() notifier.send_notification("Processor", p) elif arch: a = architecture() notifier.send_notification("Architecture", a) elif host: h = hostname() notifier.send_notification("Host Name", h) elif python: v = python_version() notifier.send_notification("Python Version", v) elif uptime: ut = up_time() notifier.send_notification("Uptime", ut) elif bt: b = boottime() notifier.send_notification("Boot time", b) elif temp: t = gettemp() notifier.send_notification("Temperature in Celcius", t) elif load: l = getload() notifier.send_notification("CPU load in %", l)