Exemplo n.º 1
0
def save_screen(request, device_id):
    """
    Receive screen parameters from display setting. Insert or update existing screen from DB. Action for 'add screen' and 'save' btn. 
    :param request: 
    :param device_id: parent device ID
    :return: 
    """
    if request.is_ajax() and request.POST.get(
            'destination-device') == device_id and request.POST.get(
                'destination-display-name'):

        screen_id = request.POST.get('destination-screen-id')
        screen_params = {
            'source_device': request.POST.get('data-source-device'),
            'source_ability': request.POST.get('data-source-ability')
        }

        db = DBA.Dba(conf.get('db', 'path'))
        if screen_id:
            # update display setting (already have screen_id)
            old_display = db.get_screen(screen_id)
            old_display.params = json.dumps(screen_params)
            db.update_display(old_display)

        else:
            # insert new display settings (dont have screen_id)
            new_display = DAO.Display(
                device_id=request.POST.get('destination-device'),
                display_name=request.POST.get('destination-display-name'),
                params=json.dumps(screen_params))
            db.insert_display(new_display)

    return HttpResponse('ok')
Exemplo n.º 2
0
def device_detail(request, device_id):
    """
    Device detail page
    :param request:
    :param device_id: device ID
    :return: device detail page
    """
    db = DBA.Dba(conf.get('db', 'path'))
    device = db.get_device(device_id)
    # device = Device.get(device_id)
    records = db.get_record_from_device(device_id, limit=10)
    # records = Record.get_all(device_id, limit=10)

    actual_in_values = get_actual_device_values(device_id, io_type='in')
    actual_out_values = get_actual_device_values(device_id, io_type='out')
    print(actual_out_values)

    response = {
        'device': device,
        'values': records,
        'actual_values': actual_in_values,
        'actual_out_values': actual_out_values,
        'device_status_interval': 30000,  # status refresh interval in seconds
        'device_values_interval': 3000,  # values refresh interval in seconds
    }
    return render(request, 'main/device_detail.html', response)
Exemplo n.º 3
0
    def __init__(self, database_path, config_file=None):
        self.db = DBA.Dba(conf.get('db', 'path'))
        self.topics = {"esp_hub/device/hello": self.new_device_callback,
                       "esp_hub/device/+/telemetry": self.telemetry_callback,
                       "esp_hub/device/+/data": self.data_callback}
        # TODO replace with config

        self.mqtt = MessageHandler(conf.get('mqtt', 'ip'), conf.getint('mqtt', 'port'))
        self.mqtt.register_topics(self.topics)
Exemplo n.º 4
0
def waiting_devices_api(request):
    """
    Provide data about waiting devices
    :param request:
    :return: JSON list of all waiting devices
    """
    db = DBA.Dba(conf.get('db', 'path'))
    devices = db.get_waiting_devices()

    response = json.dumps([device.__dict__ for device in devices])
    return HttpResponse(response)
Exemplo n.º 5
0
def remove_device(request, device_id):
    """
    Remove device from database
    :param request: 
    :param device_id: device ID
    :return: redirect to home page
    """
    db = DBA.Dba(conf.get('db', 'path'))
    if request.POST['remove-device'] == 'true':
        print('true')
        db.remove_device(device_id)

    return HttpResponseRedirect(reverse('main:index'))
Exemplo n.º 6
0
def telemetry_api(request, device_id):
    """
    Provide actual telemetry data
    :param request:
    :param device_id: device ID
    :return: JSON last telemetry record from DB
    """
    db = DBA.Dba(conf.get('db', 'path'))
    telemetry = db.get_telemetry(device_id)

    if telemetry:
        response = json.dumps(telemetry.__dict__)
        return HttpResponse(response)
    else:
        return HttpResponse('{}')
Exemplo n.º 7
0
 def __init__(self):
     """
     Display event scheduler - periodically read tasks from task file (JSON) and schedule events
     Read data from DB >> render plot >> convert plot to standard format (display size ong or byte array) >> 
         >> obtain MQTT connection from MessageHandler >> pass data to Display controller >> 
         >> [DisplayController] convert image to line format >> [DisplayController] transmit via MQTT
     """
     threading.Thread.__init__(self)
     self.conf = Config.Config().get_config()
     self.schedule_file_name = self.conf.get('scheduler', 'task_file')
     self.interval = self.conf.getint('scheduler', 'schedule_interval')
     self.screen_index = {}  # help with screen rotation
     self.last_time_index = {}  # help with event scheduling
     self.last_time = time.time()
     self.db = DBA.Dba(self.conf.get('db', 'path'))
Exemplo n.º 8
0
def waiting_devices(request):
    """
    List of all waiting device
    :param request:
    :return: waiting device page
    """
    db = DBA.Dba(conf.get('db', 'path'))
    devices = db.get_waiting_devices()

    response = {
        'title': 'Waiting devices',
        'devices': devices,
        'input_abilities': input_abilities,
        'output_abilities': output_abilities,
    }
    return render(request, 'main/waiting_devices.html', response)
Exemplo n.º 9
0
def get_screen_list(device_id, ability_name):
    db = DBA.Dba(conf.get('db', 'path'))
    screens = db.get_display(device_id, ability_name)

    for screen in screens:
        screen.params = json.loads(screen.params)  # parse screen setting like source device and ability
        source_device = db.get_device(
            screen.params.get('source_device'))  # load device to determine user names of device and ability

        screen.params['source_device_name'] = source_device.name

        # extract ability user name from provided_function JSON
        source_device_abilities = json.loads(source_device.provided_func)
        for ability in source_device_abilities:
            if ability.get('name') == screen.params.get('source_ability'):
                screen.params['source_ability_name'] = ability.get('user_name')

        screen.params['base64_plot'] = render_plot_64base_preview(screen.params.get('source_device'),
                                                                  screen.params.get('source_ability'))
    return screens
Exemplo n.º 10
0
def get_actual_device_values(device_id, io_type='all'):
    """
    Get actual values of device (newest record from database) and prepare for device detail card
    :param device_id: device ID
    :param io_type: select in/out type of ability, default 'all' select both 'in' and 'out'
    :return: JSON object with actual values, description, unit, ...
    """
    db = DBA.Dba(conf.get('db', 'path'))
    device = db.get_device(device_id)

    device_values = []
    if device:
        try:
            abilities = json.loads(device.provided_func)
        except json.JSONDecodeError as e:
            print(conf.get('msg', 'decode_error'))
            abilities = []

        for ability in abilities:
            # get newest record from db
            records = db.get_record_from_device(device_id, value_type=ability['name'], limit=1)

            # select type of ability
            if ability['io'] == io_type or io_type == 'all':
                # select first item from record list or create empty dictionary if record list is empty
                if len(records) > 0:
                    record_dict = records[0].__dict__
                    record_dict['time'] = records[0].time
                else:
                    record_dict = {}

                record_dict['value_type'] = ability['user_name']
                record_dict['unit'] = ability['unit']
                record_dict['category'] = ability['category']
                record_dict['io'] = ability['io']
                record_dict['desc'] = ability['desc']
                record_dict['user_name'] = ability['user_name']
                record_dict['name'] = ability['name']
                device_values.append(record_dict)

    return device_values
Exemplo n.º 11
0
def get_all_input_abilities():
    """
    Prepare input abilities for display setting
    :return: JSON list of devices witch provide input abilities and input abilities
    """
    db = DBA.Dba(conf.get('db', 'path'))
    records = db.get_devices()
    output = []
    for record in records:
        abilities = json.loads(record.provided_func)
        output_record = {'name': record.name, 'id': record.id}
        abilities_list = []
        for ability in abilities:
            if ability['io'] == 'in':
                abilities_list.append(ability)

        if len(abilities_list) != 0:
            output_record['abilities'] = abilities_list
            output.append(output_record)

    return output
Exemplo n.º 12
0
def get_records_for_charts(device_id, value_type, from_date, to_date):
    """
    Get record from database for plot and charts
    :param device_id: device ID
    :param value_type: name of ability
    :param from_date: start of time interval
    :param to_date: end of time interval
    :return: JSON object of time labels and values
    """
    # TODO move this logic to DB layer
    db = DBA.Dba(conf.get('db', 'path'))
    records = db.get_record_from_device(device_id, value_type, limit=conf.getint('db', 'default_records_limit'))
    # TODO implement time interval from date - to date
    values = [float(record.value) for record in records]
    values.reverse()

    response = {
        # convert datetime objects to isoformat strings in reverse order
        'labels': list(reversed([record.time.isoformat() for record in records])),
        'values': values,
    }

    return response
Exemplo n.º 13
0
def verify_device(request, device_id):
    db = DBA.Dba(conf.get('db', 'path'))
    device = db.get_waiting_device(
        device_id
    )  # get waiting device for transfer to permanent devices table
    db.remove_waiting_device(
        device_id)  # remove device from waiting devices table

    # if hidden remove input is set to false -> save new device to db
    if request.POST['remove-device'] == 'false':
        # sending MQTT message to device
        sender = DataSender.DataSender()
        sender.verify_device(device_id)

        abilities = []
        # get modified abilities from user form
        for ability in device.provided_func:
            io_type = 'in' if request.POST[
                'category-' + ability] in input_abilities else 'out'
            abilities.append(
                DAO.Ability(
                    name=ability,
                    io=io_type,
                    user_name=request.POST['user-name-' + ability],
                    category=request.POST['category-' + ability],
                    unit=request.POST['unit-' + ability],
                    desc=request.POST['desc-' + ability],
                ))

        abilities_json = json.dumps([a.__dict__ for a in abilities
                                     ])  # create json from abilities
        new_device = DAO.Device(device.id, request.POST['device-name'],
                                abilities_json)

        db.insert_device(new_device)  # add new device to database

    return HttpResponseRedirect(reverse('main:waiting_devices'))
Exemplo n.º 14
0
 def get_all():
     db = DBA.Dba("test.db")
     return db.get_devices()
Exemplo n.º 15
0
 def get_all(device_id, limit=20):
     db = DBA.Dba("test.db")
     return db.get_record_from_device(device_id, limit=limit)
Exemplo n.º 16
0
 def get(device_id):
     db = DBA.Dba("test.db")
     return db.get_device(device_id)