class PIR: def __init__(self, ledmatrix, pirpin, nomovementforseconds): logging.info('init motion') self.__Matrix = ledmatrix self.__delay = nomovementforseconds self.__pin = pirpin logging.info('set up sensor') self.__PIR = MotionSensor(self.__pin) logging.info('starting motion') # ------------------------------------------------------------------------- # wait_for_no_movement # Waits to see if there is movement within self.__delay seconds # If there is none, fades the matrix to black and stops it from being # updated. # Once movement is seen, fades the screen back on. # ------------------------------------------------------------------------- def wait_for_no_movement(self): logging.info('motionsensor') t = time.time() while True: nomovement = self.__PIR.wait_for_no_motion(10) if nomovement: logging.info('No movement') if (time.time() - t) >= self.__delay: logging.info('Turning off screen') self.__Matrix.set_draw_on_matrix(False) if self.__PIR.wait_for_motion(): t = time.time() logging.info('Turning on screen') self.__Matrix.set_draw_on_matrix(True) else: if self.__PIR.wait_for_motion(10): logging.info('Motion detected') t = time.time() else: logging.info('Motion detected') t = time.time()
from gpiozero import MotionSensor from time import sleep from picamera import PiCamera pir = MotionSensor(4) camera = PiCamera() while True: pir.wait_for_motion() camera.start_preview() pir.wait_for_no_motion() camera.stop_preview()
from gpiozero import MotionSensor from picamera import PiCamera from datetime import datetime import time import os if os.path.isfile('./authenticated')!=1: os.system("sudo grive --dry-run -a") f = open('authenticated','w') motion_timeout = 6; next_video_timeout = 0; camera = PiCamera() pir = MotionSensor(4) while True: pir.wait_for_motion() print 'motion detected' filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264") camfilename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.jpg") camera.capture(camfilename) camera.start_recording(filename) pir.wait_for_no_motion(motion_timeout) camera.stop_recording() print 'motion ended' os.system("sudo grive -u -f") os.system("sudo rm *.jpg *.h264") time.sleep(next_video_timeout)
#Denver Riggleman Detector (give me that squatch) #Jack Riggleman and James Riggleman from gpiozero import MotionSensor from picamera import PiCamera from datetime import datetime camera = PiCamera() pir = MotionSensor(17) while True: pir.wait_for_motion() print("We got one!") camera.start_recording("/home/pi/Documents/Engineering_4_Notebook/Python/Camera/Videos/DadGetOutOfMyRoom.h264") pir.wait_for_no_motion() print("no motion") camera.stop_recording() print("done")
from gpiozero import MotionSensor from picamera import PiCamera import datetime pir = MotionSensor(4) # creates motion sensor on gpio 4 camera = PiCamera() now = datetime.datetime.now() # gets current date and time filename = "intruder_" + str(now).replace(" ", "_") + ".mp4" # creates filename that changes based on date and time while True: pir.wait_for_motion() # waits for motion sensor to be triggered print("Motion detected") camera.start_recording(filename) # starts new recording with filename pir.wait_for_no_motion() # waits for motion to stop camera.stop_preview() # stops recording
class SecurityCamera: def __init__(self): self.my_stream = BytesIO() self.pir = MotionSensor(4) self.camera = PiCamera(resolution=(1920, 1080)) self.images_directory = self.current_images_directory( ) + os.sep + 'camera images' + os.sep self.on = False self.threads = [] if not os.path.exists(self.images_directory): os.makedirs(self.images_directory) def start(self): if self.pir.motion_detected: print(self.time_stamp() + ' - Initializing motion sensor... Please wait') self.pir.wait_for_no_motion() print(self.time_stamp() + ' - Initialized') time.sleep(30) self.on = True self.main_loop() def stop(self): self.on = False def main_loop(self): while self.on: if True: images_captured = [] old_stamp = self.time_stamp() while self.pir.motion_detected: stamp = old_stamp self.camera.annotate_text = stamp self.camera.capture(self.images_directory + stamp + '.jpg') # Draw the time stamp on the image # Save the image images_captured.append(self.images_directory + stamp + '.jpg') print(self.images_directory + stamp + '.jpg') while old_stamp == stamp: time.sleep(0.1) old_stamp = self.time_stamp() if len(images_captured) == 15: t = threading.Thread( target=Email, args=(images_captured, 'Dear Kyle,\n\nIntruder detected.', False)) t.start() self.threads.append(t) t = threading.Thread(target=self.__email, args=((), 'Intruder left: ' + self.time_stamp(), False)) t.start() self.on = False time.sleep(0.5) def time_stamp(self): return datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') def current_images_directory(self): return os.path.dirname((os.path.realpath(__file__)))
#****************Setup******************* pir_1 = MotionSensor(4) camera = PiCamera() #****************Heart of the Code*********** while True: # WAIT FOR MOTION AND THEN RECORD VIDEO pir_1.wait_for_motion() now = datetime.now() filename = "{0:%d}-{0:%m}-{0:%Y}.h264".format(now) print("Intruder Alert!") camera.start_recording(filename) pir_1.wait_for_no_motion() print("Deactivated!") camera.stop_recording() # EMAIL SETUP print("PREPARTING EMAIL") stamp = "{0:%d}-{0:%m}-{0:%Y}.h264".format(now) msg = MIMEMultipart() msg["subject"] = stamp msg["from"] = "*****@*****.**" msg["to"] = "*****@*****.**" text = MIMEText("Intruder Alert!") text = MIMEText("WARNING! Motion Detected!") msg.attach(text) print("EMAIL PREPARED")
class Motion(): ERROR = -1 LISTEN = 1 CONNECTED = 2 STOP = 3 SIG_NORMAL = 0 SIG_STOP = 1 SIG_DISCONNECT = 2 def __init__(self, config): self.camera_port = config['camera']['listen_port'] self.bot_port = config['bot']['listen_port'] self.ip = '127.0.0.1' self.port = config['motion']['listen_port'] self.udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.motion_pin = config['motion']['pir_pin'] self.interval = config['motion']['interval'] self.timestamp = None self.time_start = datetime.time( hour=config['motion']['time_start'][0], minute=config['motion']['time_start'][1]) self.time_end = datetime.time(hour=config['motion']['time_end'][0], minute=config['motion']['time_end'][1]) self.pir = MotionSensor(self.motion_pin) def send_udp(self, msg, port): payload = json.dumps(msg) self.udp_socket.sendto(payload.encode(), ('127.0.0.1', port)) def run(self): logging.info('Motion thread started') while True: self.pir.wait_for_motion() current_time = time.time() if self.timestamp is not None: if current_time - self.timestamp < self.interval: continue now_time = datetime.datetime.now().time() if self.time_start < self.time_end: if now_time < self.time_start: continue if now_time > self.time_end: continue else: if now_time < self.time_start and now_time > self.time_end: continue print('motion detected') self.timestamp = current_time date_str = datetime.datetime.now().strftime('%Y-%m-%d') time_str = datetime.datetime.now().strftime('%H-%M-%S') self.send_udp({'cmd': 'take_photo', 'count': 1}, self.camera_port) self.send_udp( { 'cmd': 'send_msg', 'date': date_str, 'time': time_str }, self.bot_port) logging.info('motion detected') self.pir.wait_for_no_motion()
class Detector(object): def __init__(self): # 4 = the pin on the Rasberry pi that the MotionSensor is connected to self.pir = MotionSensor(4, threshold=0.5) self.camera = PiCamera() self.source_photo = 'test.jpg' with open('new_user_credentials.csv', 'r') as input: csvreader = csv.DictReader(input) for row in csvreader: self.access_key_id = row['Access key ID'] self.secret_key = row['Secret access key'] def start(self): self.wait_for_motion() self.take_picture() self.wait_for_no_motion() photo = self.covert_img_to_bytes() results = self.aws_rekognition_image(photo) self.print_results(results) def wait_for_motion(self): self.pir.wait_for_no_motion() self.pir.wait_for_motion() print("Motion detect!") def wait_for_no_motion(self): self.pir.wait_for_no_motion() print("No Motion") def take_picture(self): self.camera.resolution = (1920, 1080) self.camera.rotation = 180 self.camera.start_preview() sleep(2) self.camera.capture(self.source_photo) self.camera.stop_preview() def stop_camera(self): self.camera.stop_recording() def start_camera(self): datename = "{0:%Y}-{0:%m}-{0:%d}:{0:%H}:{0:%M}:{0:%S}".format(datetime.now()) filename = str(datename) + "video.h264" self.camera.resolution = (640, 480) self.camera.rotation = 180 self.camera.start_recording(filename) def aws_rekognition_image(self, photo): client = boto3.client('rekognition', aws_access_key_id=self.access_key_id, aws_secret_access_key=self.secret_key, region_name='us-west-2') return client.detect_labels(Image={'Bytes': photo}) def covert_img_to_bytes(self): with open(self.source_photo, 'rb') as photo: return photo.read() def print_results(self, results): for each in results['Labels']: print(each['Name'] + ": " + str(each['Confidence']))
print((dt.utcnow() - td(hours=5)).strftime("%Y-%m-%d %H:%M:%S"), 'nm') if len(collect) >= min_element: print("sending data in", threshold_seconds, "if no more movement") if len(collect) > min_element: try: scheduler.remove_job('send_dompeux') except: print("Something went wrong when removing job 'send_dompeux'") scheduler.add_job(send_data, 'date', id='send_dompeux', next_run_time=dt.utcnow() + td(seconds=threshold_seconds)) else: print("need", min_element - len(collect), "more movement to interprete this movement as dompeux") print('* Setting up...') print('* Do not move, setting up the PIR sensor...') sensor.wait_for_no_motion() print('* Device ready! ', end='', flush=True) sensor.when_motion = on_motion sensor.when_no_motion = no_motion scheduler.start() print('Press Ctrl+C to exit\n\n') sleep(60 * 60 * 24 * 200)
print("number of pixels for apple: ") print(x1) if x > 5: print("") print("Orange") show = cv2.cvtColor(I, cv2.COLOR_BGR2RGB) plt.imshow(show, cmap='gray') plt.show() pwm.start(7) DC = 1. / 15. * (desiredPosition1) + 2 pwm.ChangeDutyCycle(DC) time.sleep(2) DC = 1. / 15. * (desiredPosition3) + 2 pwm.ChangeDutyCycle(DC) elif x1 > 5: print("") print("Apple") plt.imshow(I, cmap='gray') plt.show() pwm_1.start(7) DC_1 = 1. / 15. * (desired_1) + 2 pwm_1.ChangeDutyCycle(DC_1) time.sleep(2) DC_1 = 1. / 15. * (desired_3) + 2 pwm_1.ChangeDutyCycle(DC_1) else: print('Unclassified fruit') if pir.wait_for_no_motion(): #object is far away print("") print('Place the fruit')
from datetime import datetime from gpiozero import Buzzer, LED, MotionSensor from signal import pause from text_me import texter buzzer = Buzzer(4) led = LED(14) motion_sensor = MotionSensor(18) def start_motion(): detection = datetime.now() led.blink(0.5, 0.5) buzzer.beep(0.5, 0.5) print(f"Motion detected at {detection}") texter(detection) def end_motion(): led.off() # Method to turn off the LED light buzzer.off() # Method to turn off the buzzer print("Starting up the sensor...") motion_sensor.wait_for_no_motion() print("Sensor ready") motion_sensor.when_motion = start_motion motion_sensor.when_no_motion = end_motion pause()
#print("Motion Detected") # Print a notice to the console for debugging # Turn on IR array here # Create date timestamps for files timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") # method calls date/time cast str$ timestamp_jpg = tempFolder + "/" + timestamp + ".jpg" timestamp_mp4 = tempFolder + "/" + timestamp + ".mp4" # Capture image print("Capturing image...") subprocess.call(["raspistill", "-t", "1", "-n", "-o", timestamp_jpg]) # Move image to 'images' folder os.rename(timestamp_jpg, timestamp_jpg.replace("temp", "images")) # Capture video print("Capturing video...") # subprocess.call(["raspivid ", "-t", "10000", "-o", timestamp_mp4]) subprocess.call(["raspivid", "-t", "15000", "-n", "-o", timestamp_mp4]) # Move video to 'videos' folder os.rename(timestamp_mp4, timestamp_mp4.replace("temp", "videos")) # Turn off IR array here pir.wait_for_no_motion() # Wait until the PIR sensor no longer detects motion before continuing #print("Motion no longer detected") # Print a notice to the console for debugging