示例#1
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)
示例#2
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()
示例#3
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()
示例#4
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()
示例#5
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()
示例#6
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'))