2020-07-07 19:04:52 +02:00

80 lines
3.2 KiB
Python

import datetime
import echo_serial.serial_controller as EchoSerial
import echo_db.database as EchoDB
class Switch:
@staticmethod
def handle_action(device, action, data):
actionData = device['actions'][action]
collection = EchoDB.EchoDB.database['Devices']
if action == "automatic_movement":
if data == "on":
# Update Database
now_time = datetime.datetime.now()
auto_shutdown = now_time + datetime.timedelta(minutes= 2)
collection.update_one({'uuid': device['uuid']}, {"$set": { 'last_used': datetime.datetime.now(), 'automatic_movement': True, 'automatic_shutdown': auto_shutdown }})
return {'status': 'success', 'message': actionData['message']}, 200
if data == "off":
# Update Database
collection.update_one({'uuid': device['uuid']}, {"$set": { 'last_used': datetime.datetime.now(), 'automatic_movement': False }})
return {'status': 'success', 'message': actionData['message']}, 200
return {'status': 'failed', 'message': 'Setting not found!'}, 200
#Check if status is already the action
if device['status'] == action:
message = "Device is already in the requested state!"
return {'status': 'failed', 'message': message}, 200
# Send Serial Command
EchoSerial.EchoSerial.send_commmand(device, action)
# Update Database
collection.update_one({'uuid': device['uuid']}, {"$set": { 'last_used': datetime.datetime.now(), 'status': action }})
return {'status': 'success', 'message': actionData['message']}, 200
@staticmethod
def handle_movement_switch():
mainLightUUID = '9472-4f60'
collection = EchoDB.EchoDB.database['Devices']
# Get Device (Main Light)
mainLightDevice = collection.find_one({'uuid': mainLightUUID})
# Check if automatic movement mode of main light is enabled, else do nothing
if mainLightDevice['automatic_movement'] == False:
return
# Check if light levels are low enough to turn on light
collectionLight = EchoDB.EchoDB.database['LightLogs']
data = collectionLight.find().sort([('timestamp', -1)]).limit(1)
if data[0]['light_amount'] > 20:
return;
# Light is already on, update automatic shutdown.
if mainLightDevice['status'] == "on":
now_time = datetime.datetime.now()
auto_shutdown = now_time + datetime.timedelta(minutes= 2)
collection.update_one({'uuid': mainLightUUID}, {"$set": { 'automatic_shutdown': auto_shutdown }})
return
# Light is off, turn it on
# Send Serial Command
EchoSerial.EchoSerial.send_commmand(mainLightDevice, "on")
# Auto shutdown time
now_time = datetime.datetime.now()
auto_shutdown = now_time + datetime.timedelta(minutes= 2)
# Update Database
collection.update_one({'uuid': mainLightUUID}, {"$set": { 'last_used': datetime.datetime.now(), 'status': "on", 'automatic_shutdown': auto_shutdown }})