Ejemplo n.º 1
0
    def get_screen(self, id):
        """
        Get single screen by ID
        :param id: screen ID (primary INT key not optional attribute screen_name)
        :return: single DAO object Display
        """
        con = self._get_connection()
        try:
            cur = con.cursor()
            cur.row_factory = sql.Row
            cur.execute("SELECT * FROM Displays WHERE Id=:id", {
                'id': id,
            })
            row = cur.fetchone()

            return DAO.Display(id=row['Id'],
                               device_id=row['Device_id'],
                               display_name=row['Display_name'],
                               screen_name=row['Screen_name'],
                               params=row['Params'])
        except sql.Error as e:
            print(e.args[0])
            return None
        except IndexError:
            print("No item found")
            return None
        finally:
            con.close()
Ejemplo n.º 2
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')
Ejemplo n.º 3
0
    def new_device_callback(self, client, userdata, msg):
        """
        Handle Hello msg from devices
        Topic: esp_hub/device/hello
        """
        data = self.extract_payload(msg)
        print(data["name"], data["id"])

        # device is in database
        if self.db.get_device(data['id']):
            reply = {"ip": conf.get('mqtt', 'ip'), "port": conf.getint('mqtt', 'port')}
            self.mqtt.publish(str.format("esp_hub/device/{}/accept", data['id']), json.dumps(reply))
            # TODO load MQTT strings from config file
        else:
            provided_func = data['ability']
            provided_func = provided_func.replace('[', '')
            provided_func = provided_func.replace(']', '')
            provided_func = provided_func.replace(';', ',')
            provided_func = provided_func.replace(' ', '')
            provided_func = provided_func.replace('"', '')
            provided_func = provided_func.replace("'", '')
            provided_func = provided_func.split(',')
            # add device to waiting device list
            self.db.add_waiting_device(DAO.Device(data['id'], data['name'], provided_func))
            print(self.db)
Ejemplo n.º 4
0
    def get_display(self, device_id, display_name):
        """
        Get all screen for single display
        :param device_id: ID of device
        :param display_name: ability name
        :return: list of DAO objects Display
        """
        con = self._get_connection()
        try:
            cur = con.cursor()
            cur.row_factory = sql.Row
            cur.execute(
                "SELECT * FROM Displays WHERE Device_id=:Device_id AND Display_name=:Display_name",
                {
                    "Device_id": device_id,
                    "Display_name": display_name
                })
            rows = cur.fetchall()
            return [
                DAO.Display(id=row['Id'],
                            device_id=row['Device_id'],
                            display_name=row['Display_name'],
                            screen_name=row['Screen_name'],
                            params=row['Params']) for row in rows
            ]

        except sql.Error as e:
            print(e.args[0])
            return None
        except IndexError:
            print("No item found")
            return None
        finally:
            con.close()
Ejemplo n.º 5
0
    def get_record_from_device(self,
                               device_id,
                               value_type=None,
                               order='desc',
                               limit=600):
        con = self._get_connection()
        if value_type:
            type_selector = str.format("AND Type='{}'", value_type)
        else:
            type_selector = ""

        try:
            cur = con.cursor()
            cur.row_factory = sql.Row  # return data from cursor as dictionary
            cur.execute(
                str.format(
                    "SELECT * FROM Records WHERE Device_id=:Device_id {} ORDER BY TIME {} LIMIT {}",
                    type_selector, order, limit), {"Device_id": device_id})

            rows = cur.fetchall()
            return [
                DAO.Record(x['Device_id'], x['Time'], x['Type'], x['Value'])
                for x in rows
            ]
        except sql.Error as e:
            print(e.args[0])
            return []
        finally:
            con.close()
Ejemplo n.º 6
0
    def data_callback(self, client, userdata, msg):
        """
        Handle messages from device witch contain measured data
        Topic: esp_hub/device/+/data
        """
        data = self.extract_payload(msg)
        client_id = self.extract_device_id(msg)

        if 'type' in data and 'value' in data:
            record = DAO.Record(client_id, datetime.now(), data["type"], data["value"])
            self.db.insert_record(record)
            print(">>> ", data['type'], data['value'])
Ejemplo n.º 7
0
    def telemetry_callback(self, client, userdata, msg):
        """
        Handle telemetry messages from devices
        Topic: esp_hub/device/+/telemetry
        """
        data = self.extract_payload(msg)
        device_id = self.extract_device_id(msg)

        print(data)
        telemetry = DAO.Telemetry(device_id, datetime.now(), rssi=data.get('rssi', '0'), heap=data.get('heap', '0'),
                                  cycles=data.get('cycles', '0'), ip=data.get('local_ip', '0'), mac=data.get('mac', '0'),
                                  voltage=data.get('voltage', '0'), ssid=data.get('ssid', '0'))
        self.db.insert_telemetry(telemetry)
Ejemplo n.º 8
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'))
Ejemplo n.º 9
0
 def get_device(self, device_id):
     con = self._get_connection()
     try:
         cur = con.cursor()
         cur.row_factory = sql.Row
         cur.execute("SELECT * FROM Devices WHERE Id=:Id",
                     {'Id': device_id})
         row = (cur.fetchall())[0]  # get first record
         return DAO.Device(row['Id'], row['Name'], row['Provided_func'])
     except sql.Error as e:
         print(e.args[0])
         return None
     except IndexError:  # when does not exist any record with given id
         return None
     finally:
         con.close()
Ejemplo n.º 10
0
 def get_devices(self):
     con = self._get_connection()
     try:
         cur = con.cursor()
         cur.row_factory = sql.Row  # return data from cursor as dictionary
         cur.execute("SELECT * FROM Devices")
         rows = cur.fetchall()
         return [
             DAO.Device(x['Id'], x['Name'], x['Provided_func'])
             for x in rows
         ]
     except sql.Error as e:
         print(e.args[0])
         return []
     finally:
         con.close()
Ejemplo n.º 11
0
 def get_waiting_devices(self):
     """
     :return: list of DAO device objects - waiting devices
     """
     con = self._get_connection()
     try:
         cur = con.cursor()
         cur.row_factory = sql.Row  # return data from cursor as dictionary
         cur.execute("SELECT * FROM WaitingDevices")
         rows = cur.fetchall()
         return [
             DAO.Device(x['Device_id'], x['Name'],
                        x['Provided_func'].split(',')) for x in rows
         ]
     except sql.Error as e:
         print(e.args[0])
         return []
     finally:
         con.close()
Ejemplo n.º 12
0
 def get_waiting_device(self, device_id):
     """
     get specific waiting device
     :param device_id: id of device
     :return: single DAO device object
     """
     con = self._get_connection()
     try:
         cur = con.cursor()
         cur.row_factory = sql.Row
         cur.execute(
             "SELECT * FROM WaitingDevices WHERE Device_id=:Device_id",
             {'Device_id': device_id})
         row = (cur.fetchall())[0]  # get first record
         return DAO.Device(row['Device_id'], row['Name'],
                           row['Provided_func'].split(','))
     except sql.Error as e:
         print(e.args[0])
         return None
     except IndexError:  # when does not exist any record with given id
         return None
     finally:
         con.close()
Ejemplo n.º 13
0
 def get_telemetry(self, device_id):
     """
     Get single telemetry record by device_id
     :param device_id
     :return: DAO telemetry record
     """
     con = self._get_connection()
     try:
         cur = con.cursor()
         cur.row_factory = sql.Row  # return data from cursor as dictionary
         cur.execute("SELECT * FROM Telemetry WHERE Device_id=:Device_id",
                     {'Device_id': device_id})
         row = (cur.fetchall())[0]
         return DAO.Telemetry(row['Device_id'], row['Time'], row['Rssi'],
                              row['Heap'], row['Cycles'], row['Voltage'],
                              row['Ip'], row['Mac'], row['Ssid'])
     except sql.Error as e:
         print(e.args[0])
         return None
     except IndexError:
         print("No item found")
         return None
     finally:
         con.close()