####### camera_mov_zero.py ######################## import json from datetime import datetime import cv2, time import pymssql import os.path import os import base64 from datetime import datetime, timedelta import threading first_frame=None last_sent_time=None SENSOR_INTERVAL=timedelta(minutes=2) def api_add_log(devid,filename,image): conn = False try: sqlite_insert = "INSERT INTO bh_img_device(id_dev_id,id_file_name,id_fecha_aud,id_image) VALUES (" + str(devid) + ",'" + filename + "',REPLACE(convert(char(10),DATEADD(hh,(SELECT TOP 1 fi_hora_local FROM bh_filiales INNER JOIN bh_devices ON bh_devices.dv_filial = bh_filiales.fi_id WHERE dv_id = " + str(devid) + "),GETDATE()),102),'.','-') + ' ' + convert(char(8),DATEADD(hh,(SELECT TOP 1 fi_hora_local FROM bh_filiales INNER JOIN bh_devices.dv_filial = bh_filiales.fi_id WHERE dv_id = " + str(devid) + "),GETDATE()),108),'" + image + "')" conn = pymssql.connect(server='hunterpr.database.windows.net',user='guillermo@hunterpr.database.windows.net',password='Jkzcg1l4%33ae83e122',database='tl_bh') cur = conn.cursor() count = cur.execute(sqlite_insert) conn.commit() lastact = cur.lastrowid cur.close() except pymssql.Error as error: conn = False return 0 finally: if (conn): conn.close() return 1 def get_frame(): global first_frame global mov global last_sent_time cap = cv2.VideoCapture(0) out = None i=0 j=0 while True: ret, frame = cap.read() timestamp = datetime.now() text = "No hay movimiento!" frame = cv2.resize(frame, None, fx=0.6, fy=0.6, interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray,(21,21),0) if first_frame is None: first_frame = gray continue delta_frame = cv2.absdiff(first_frame,gray) thresh_delta = cv2.threshold(delta_frame,30,255,cv2.THRESH_BINARY)[1] thresh_delta = cv2.dilate(thresh_delta, None, iterations=3) (cnts,_) = cv2.findContours(thresh_delta.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in cnts: if cv2.contourArea(contour) > 500: text = "Movimiento Detectado!" print(text) break ts = datetime.today() + timedelta(hours=6) ts = ts.strftime("%A %d %B %Y %I:%M:%S%p") cv2.putText(frame, "Status: {}".format(text), (10,20),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,255),2) cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0,0,255), 1) if text == "Movimiento Detectado!": if not last_sent_time or (datetime.now() - last_sent_time) > SENSOR_INTERVAL: last_sent_time = datetime.now() print("[Info] Movimiento Detectado!") pathname = "/home/pi/projects/images/movimiento/" filename = "2~" + str(last_sent_time).replace(" ","~") filename = filename[0:21] + ".jpg" savefilename = pathname + filename cv2.imwrite(savefilename,frame) with open(savefilename,"rb") as img_file: img_string = base64.b64encode(img_file.read()) img64 = img_string.decode('utf-8') api_add_log(2,filename,img64) if len(savefilename) > 0: if os.path.exists(savefilename): os.remove(savefilename) if i == 240: i=0 text="No hay Movimiento!" cnts = [] contour = [] cap.release() cv2.destroyAllWindows() break get_frame() if __name__ == '__main__': get_frame() ############### restart_cammov.py ############################################# from subprocess import call import subprocess import time def killProcess(procname): lpro = subprocess.Popen(['ps', '-fA'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = lpro.communicate() dat = output.decode('utf-8') offsetini = 47 offsetfin = 40 if procname == "camera_mov_zero.py": offsetini = 47 offsetfin = 40 while 1: try: ltotal = len(dat) x = dat.index(procname) idx_ini_PID = x-offsetini idx_fin_PID = x-offsetfin idx_ini_NPID = x idx_fin_NPID = x + len(procname) PID = dat[idx_ini_PID:idx_fin_PID].strip() NPROC = dat[idx_ini_NPID:idx_fin_NPID].strip() dat = dat[idx_fin_NPID:ltotal] killpro = subprocess.Popen(['kill',PID.strip()], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output1, err1 = killpro.communicate() except ValueError as ve: break def runProcess(procname): runpro = subprocess.Popen(['/usr/bin/python3', procname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = runpro.communicate() if __name__=='__main__': killProcess("camera_mov_zero.py") time.sleep(10) runProcess("camera_mov_zero.py") ################### wd_cammov.py ################################### from subprocess import call import subprocess import time def CheckProcess(procname): lpro = subprocess.Popen(['ps', '-fA'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = lpro.communicate() dat = output.decode('utf-8') while 1: try: x=dat.index(procname) return True except ValueError as ve: return False def runProcess(procname): runpro = subprocess.Popen(['/usr/bin/python3', procname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = runpro.communicate() if __name__=='__main__': if CheckProcess("camera_mov_zero.py") == False: runProcess("camera_mov_zero.py")