python for Raspberry 0W surveillance camera write to NAS - python

I have made a raspi0 PIR cam and am trying to get it to write to my network storage device. The .py writes to the drive but just keeps re-saving over the same file unless I ctrl C and manually restart.
from picamera import PiCamera
import time
from time import sleep
import os
import sys
from datetime import datetime
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pir_sensor = 17 #GPIO physical pin 11
GPIO.setup(pir_sensor, GPIO.IN, GPIO.PUD_DOWN)
current_state = 0
filename_part1="surv"
file_ext=".mp4"
now = datetime.now()
current_datetime = now.strftime("%d-%m-%Y_%H:%M:%S")
filename=filename_part1+"_"+current_datetime+file_ext
filepath="/mnt/local_share/Surveillance_Captures/"
def capture_video():
camera.start_preview()
camera.start_recording('/home/pi/python_code/capture/newvideo.h264')
camera.wait_recording(10)
camera.stop_recording()
camera.stop_preview()
def remove_file():
if os.path.exists("/home/pi/python_code/capture/newvideo.h264"):
os.remove("/home/pi/python_code/capture/newvideo.h264")
else:
print("file does not exist")
camera=PiCamera()
while True:
i = GPIO.input(17)
if i==1:
print("Motion Detected")
capture_video()
sleep(2)
res=os.system("MP4Box -add /home/pi/python_code/capture/newvideo.h264 /home/pi/python_code/capture/newvideo.mp4")
os.system("mv /home/pi/python_code/capture/newvideo.mp4 "+filepath+filename)
print("File Moved")
print("Scanning Sector")
sleep(2)
remove_file()

Because you put filename=filename_part1+"_"+current_datetime+file_ext out of while loop, so the filename never change.
while True:
now = datetime.now()
current_datetime = now.strftime("%d-%m-%Y_%H:%M:%S")
filename=filename_part1+"_"+current_datetime+file_ext

Related

Error while Working with US-100 on Raspberry pi 3

I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image

python program stops after wifi connection discontinuity

I started learning Python two months ago and I have written a code for a Raspberry pi project. My problem is that the program stucks after some hours of operation. I think that in all cases, it stopped after some wifi connection drops. But I don't understand why the whole program stops if there something wrong with the wifi connection. It stops uploading values and renew the lcd screen messages it prints (I removed this and other stuff from the code in order to be more easy to read.)
The code starts at the startup (sudo python /home/pi/test.py &) and contains two Threads:
The "Control" thread reads temperature and humidity by using an i2c bus and a sensor am2315 and according to a temperature threshold, controls a relay through GPIO.
The "Thingspeak" thread reads the temperature threshold from a 'Thingspeak' channel and then uploads the measurements from the previous thread to 'Thingspeak'.
I really don't know what to do and how to search for any solutions.
Any help will be much appreciated.
#! /usr/bin/env python
from time import sleep
import datetime
import urllib2
import RPi.GPIO as GPIO
import threading
import smbus
from tentacle_pi.AM2315 import AM2315
import smtplib
import contextlib
sleep(120)
# Lock
tLock = threading.Lock()
# Global variables
tem_global = 0; hum_global = 0
tem_hi = 35; relay = 21
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay, GPIO.OUT)
GPIO.output(relay, False)
sleep(1)
def Control():
global temg, humg, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
tLock.acquire()
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
tLock.release()
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
t.Lock.release()
sleep(30)
# Uploading values to thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
tLock.release()
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
file.close()
sleep(60)
continue
def Main():
t1 = threading.Thread(target=Thingspeak)
t2 = threading.Thread(target=Control)
t1.start()
t2.start()
t1.join()
t2.join()
GPIO.cleanup()
if __name__ == '__main__':
Main()
Problem solved. As James K Polk indicated, there was an error after the tLock.acquire(), every time the internet connection went off, causing deadlock of the program. Below is a corrected part of the code for anyone would be interested.
def Control():
global tem_global, hum_global, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
with tLock:
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
sleep(30)
# Uploading values to thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
sleep(60)
continue

Running multiple programs on Raspberr Pi

I just finished all of the prototyping of this project:, and I encountered 2 problems: https://www.pubnub.com/blog/2015-03-17-building-a-model-smart-home-with-raspberry-pi/
I cant run all of the programs at once(Humidity and Temperature, LEDs, Micro Servo motors, etc...)
I can't have more than three LED's (technically two)
What can I do to run everything at once, so it is all displayed in the WEB UI? How can I have more LED's, since the limit is 50mah which is about 2 LED's? (they can be three per 'room', so three per GPIO pin or just per GPIO). I dont see hoe it could work with such a power limit. Also, they need to be controlled with PWM. There simply isn't enough power on the Raspberry Pi!
the code for the DHT22 sensor is:
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def callback(message):
print(message)
#published in this fashion to comply with Eon
while True:
h,t = dht.read_retry(dht.DHT22, 4)
temp='{0:0.1f}'.format(t)
hum='{0:0.1f}'.format(h)
message = {'temperature': temp, 'humidity': hum}
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
pubnub.publish(channel=channel, message=message, callback=callback, error=callback)
the code for the led's is:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
Thanks!

Python and gpio raspberry

I have a problem with my project, I have a little python script to read my gas meter.
Every revolution of digits a small magnet inside the gas meter close to the reed switch makes an input for my raspberry. The problem is when the magnet stops close to the sensor circuit leaving on a high level, which cause false inputs, here my script.
Any suggestion? thanks to all
#!/usr/bin/env python
import time
import datetime
import os.path
import pycurl
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(10, GPIO.RISING, bouncetime = 5000)
def GetGas(arg):
time.sleep(0.01) # need to filter out the false positive of some power fluctuation
if GPIO.input(10) != GPIO.HIGH:
return
gastotale=0
if os.path.isfile('/var/www/myscripts/gas/gastotale.txt'):
file = open("/var/www/myscripts/gas/gastotale.txt","r")
gastotale = float(file.read())
file.close()
gastotale = gastotale+0.01
file = open("/var/www/myscripts/gas/gastotale.txt","w")
file.write(str(gastotale))
file.close()
now = datetime.datetime.now()
fileday = '/var/www/myscripts/gas/'+now.strftime("%Y-%m-%d")+'.txt'
gasday = 0
if os.path.isfile(fileday):
file = open(fileday,"r")
gasday = float(file.read())
file.close()
gasday = gasday+0.01
file = open(fileday,"w")
file.write(str(gasday))
file.close()
oem = pycurl.Curl()
oem.setopt(oem.URL, 'http://emoncms.org/input/post.json?node=0
csv=0,'+str(gasday)+',0,0,'+str(gastotale)+'&apikey=dfb6ccf')
oem.perform()
laststate = 0
while True:
if (GPIO.input(10) == 1 ):
if (laststate == 0):
gastotale = gastotale+0.01
laststate=1
else:
laststate=0
time.sleep(30)

Python clean keyboard interupt

I have a python script in which I'm using threading to wait for inputs on my raspberry pi. This is the first time I've ever used threading before and I'm having some difficulties handling the KeyboardInterrupt. Its not really an issue, but if the user presses control-c to early, like right as soon as the program starts, python freaks out and spews a console full of import errors. Ive tried wrapping the imports in try - excepts, but that doesn't seem to work. I have a feeling its something with the threading as I've never had this issue before.
Besides wrapping everything in try-excepts i also tried:
from threading import Thread
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)
which I hear was suppose to not allow the keyboard interrupt until its been loaded?
Is there anyway just to not have python do anything on keyboardinterrupts?
Any help would be appreciated. Thanks!
My Code:
import RPi.GPIO as GPIO
import pymysql as mysql
import time
import urllib.request
from threading import Thread
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
class table():
__slots__ = ['pin','num','time']
def __init__(self, pin, num, time=0):
self.pin = pin
self.num = num
self.time = time
# Room ID
room = 6
# time (minutes)
thetime = 38
# table Setup
tableList = [ \
table(11,6), \
table(13,2), \
table(15,4), \
table(19,5), \
table(21,3), \
table(23,1), \
]
def settable(table):
with urllib.request.urlopen("http://time.zyphox.com") as url:
curtime = int(url.read())+(thetime*60)
con = mysql.connect(host="345", user="435", passwd="345435", db="34534543")
cur = con.cursor()
cur.execute("UPDATE tables SET time='"+str(curtime)+"' WHERE number='"+str(table)+"' AND id_room='"+str(room)+"'")
cur.close()
con.close()
print("Setting table " + str(table) + " to " + str(thetime) + " minutes...")
def watchtable(table):
GPIO.setup(table.pin, GPIO.IN)
while True:
if(GPIO.input(table.pin)!=1 and table.time <= time.time()):
settable(table.num)
table.time = time.time() + 10
def main():
print("Loading kitchen System...")
for table in tableList:
t = Thread(target=watchtable,args=(table,))
t.daemon=True
t.start()
time.sleep(1)
print("Successful!")
while True:
time.sleep(300)
print("- Pinging MYSQL database.")
main()

Categories

Resources