2018-04-26 14:45:28 +00:00
|
|
|
import atexit
|
|
|
|
from flask import Blueprint
|
2018-05-03 20:30:34 +00:00
|
|
|
from .mqtt_client import MqttClient
|
2018-05-08 14:45:09 +00:00
|
|
|
from .models import Device, Recording
|
2018-04-26 12:12:20 +00:00
|
|
|
|
2018-05-06 19:42:21 +00:00
|
|
|
devices_bp = Blueprint('devices', __name__)
|
2018-04-26 12:12:20 +00:00
|
|
|
|
2018-05-03 07:48:24 +00:00
|
|
|
|
2018-04-27 09:15:44 +00:00
|
|
|
# When app dies, stop mqtt connection
|
2018-04-26 14:45:28 +00:00
|
|
|
def on_stop():
|
2018-05-08 14:45:09 +00:00
|
|
|
MqttClient.tear_down()
|
2018-04-26 13:03:38 +00:00
|
|
|
|
2018-05-03 07:48:24 +00:00
|
|
|
|
2018-04-26 14:45:28 +00:00
|
|
|
atexit.register(on_stop)
|
|
|
|
|
2018-05-03 07:48:24 +00:00
|
|
|
|
2018-05-08 14:45:09 +00:00
|
|
|
# Setup
|
2018-05-06 19:42:21 +00:00
|
|
|
@devices_bp.record
|
2018-05-08 14:45:09 +00:00
|
|
|
def __on_blueprint_setup(setup_state):
|
2018-05-04 06:35:26 +00:00
|
|
|
print('Blueprint setup')
|
2018-05-08 14:45:09 +00:00
|
|
|
MqttClient.setup(setup_state.app)
|
|
|
|
|
|
|
|
|
|
|
|
# Public interface
|
|
|
|
def create_device(name, device_type=1):
|
|
|
|
"""
|
|
|
|
Tries to create device with given parameters
|
|
|
|
|
|
|
|
:param name: Desired device name
|
|
|
|
:param device_type: Id of desired device type.
|
|
|
|
By default it is 1 (STANDARD)
|
|
|
|
:type name: string
|
|
|
|
:type device_type: int
|
|
|
|
:returns: True if device is successfully created
|
|
|
|
:rtype: Boolean
|
|
|
|
"""
|
|
|
|
device = Device(name, None, device_type)
|
|
|
|
device.save()
|
|
|
|
|
|
|
|
|
|
|
|
def get_device_recordings(device_id):
|
|
|
|
"""
|
|
|
|
Tries to get device recording for device with given parameters. Raises
|
|
|
|
error on failure
|
|
|
|
|
|
|
|
:param device_id: Id of device
|
|
|
|
:type device_id: int
|
|
|
|
:returns: List of Recordings for given device
|
|
|
|
:rtype: List of Recording
|
|
|
|
:raises: ValueError if device does not exist
|
|
|
|
"""
|
|
|
|
if not Device.exists(id=device_id):
|
|
|
|
raise ValueError("Device with id %s does not exist" % device_id)
|
|
|
|
|
|
|
|
return Recording.get_many(device_id=device_id)
|
|
|
|
|
|
|
|
|
|
|
|
def get_device(device_id):
|
|
|
|
"""
|
|
|
|
Tries to get device with given parameters. Raises error on failure
|
|
|
|
|
|
|
|
:param device_id: Id of device
|
|
|
|
:type device_id: int
|
|
|
|
:returns: Requested device
|
|
|
|
:rtype: Device
|
|
|
|
:raises: ValueError if device does not exist
|
|
|
|
"""
|
|
|
|
if not Device.exists(id=device_id):
|
|
|
|
raise ValueError("Device with id %s does not exist" % device_id)
|
2018-05-04 06:35:26 +00:00
|
|
|
|
2018-05-08 14:45:09 +00:00
|
|
|
return Device.get(id=device_id)
|