Created
October 6, 2017 15:13
-
-
Save tkan/ab04665fbc7e26d3363e41c31a87fcf6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RPi.GPIO as GPIO | |
import time | |
import datetime | |
import sqlite3 | |
from sqlite3 import Error | |
import os | |
import logging | |
text_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "last_move.txt") | |
log_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "sensor.log") | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger() | |
handler = logging.FileHandler(log_file) | |
handler.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
GPIO.setmode(GPIO.BCM) | |
GPIO.setup(23, GPIO.IN) #PIR | |
db_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "punchclock.db") | |
sql_create_table = """ CREATE TABLE IF NOT EXISTS entries ( | |
id integer PRIMARY KEY, | |
date text NOT NULL, | |
timestamp text, | |
delta text); """ | |
try: | |
conn = sqlite3.connect(db_file) | |
try: | |
c = conn.cursor() | |
c.execute(sql_create_table) | |
except Error as e: | |
print(e) | |
except Error as e: | |
logger.debug(e) | |
finally: | |
conn.close() | |
time.sleep(3) # to stabilize sensor | |
a = datetime.datetime.now() | |
with open(text_file, "r+") as f: | |
f.seek(0) | |
timestamp = f.readline().strip("\n") | |
timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f") | |
date = timestamp.strftime('%d-%m-%Y') | |
delta = (a - timestamp).total_seconds() | |
f.close() | |
i = 0 | |
j = 0.0 | |
while i < 50: | |
j += GPIO.input(23) | |
time.sleep(0.4) | |
i += 1 | |
movement = j / i | |
logger.info('movement calculated: %s', movement) | |
if delta > 300 and movement < 0.05: | |
logger.info('Insert on DB has been triggered.') | |
data = [date, datetime.datetime.now(), delta] | |
sql_new_entry = """INSERT INTO entries(date, timestamp, delta) | |
VALUES (?,?,?); """ | |
conn = sqlite3.connect(db_file) | |
try: | |
c = conn.cursor() | |
c.execute(sql_new_entry, data) | |
conn.commit() | |
except Error as e: | |
logger.debug(e) | |
finally: | |
conn.close() | |
with open(text_file, "w+") as g: | |
g.write(str(a)) | |
logger.info('Write new timestamp to last_move.txt') | |
g.close() | |
else: | |
logger.info('No update on DB.') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment