# -*- coding: utf-8 -*-
from gpiozero import LED, MotionSensor, Buzzer
from time import sleep, strftime, gmtime
from datetime import datetime
import MySQLdb
from threading import Thread
import sys
import RPi.GPIO as GPIO
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import logging

logging.basicConfig()

host = "a2be3h2y6o06rl.iot.us-west-2.amazonaws.com"
rootCAPath = "rootca.pem"
certificatePath = "certificate.pem.crt"
privateKeyPath = "private.pem.key"

my_rpi = AWSIoTMQTTClient("basjcPubSub")
my_rpi.configureEndpoint(host, 8883)
my_rpi.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

my_rpi.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
my_rpi.configureDrainingFrequency(2)  # Draining: 2 Hz
my_rpi.configureConnectDisconnectTimeout(10)  # 10 sec
my_rpi.configureMQTTOperationTimeout(30)  # 30 sec

my_rpi.connect()

pir = MotionSensor(26, threshold=0.8)
bz = Buzzer(5)
led = LED(18)
led_off = False

def led_check(client, userdata, message):
	global led_off
	print("[LEDController] Status from AWS: " + message.payload)	
	if message.payload == "1":
		led.on()
		led_off = False
	else:
		led.off()
		led_off = True
try:
	print("Running LEDController")
	db = MySQLdb.connect("localhost", "root", "dmitiot", "iotCAone")
	curs = db.cursor()
	print("Successfully connected to database!")
	while True:
		my_rpi.subscribe("sensors/rfid", 1,led_check)
		if led_off:
			if pir.motion_detected:
				print("Motion Detected. Recorded into Database")
				motion_detected = strftime("%Y-%m-%dT%H:%M:%S", gmtime())
                		sql = 'INSERT INTO motion(datetime_value) VALUES(%s)'
				args = (motion_detected)
				cursor=db.cursor()
				cursor.execute(sql,args)
                		db.commit()
				bz.on()
				sleep(1)
				bz.off()
except KeyboardInterrupt, SystemExit:
	sys.exit()
except MySQLdb.Error:
	print("Error connection to mySQL database")
finally:
	curs.close()
	db.close()