Ejemplo n.º 1
0
class FlaskMQTTTestCase(unittest.TestCase):
    def setUp(self):

        self.app = Flask(__name__)

    def test_simple_connect(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt.disconnect()

    def test_connect_with_username(self):
        self.app.config['MQTT_USERNAME'] = '******'
        self.app.config['MQTT_PASSWORD'] = '******'
        self.mqtt = Mqtt(self.app)
        self.mqtt.disconnect()

    def test_subscribe(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt.subscribe('test')
        self.assertEqual('test', self.mqtt.topics[0])
        self.assertEqual(1, len(self.mqtt.topics))
        self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))
        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt.unsubscribe('test')

        self.mqtt.subscribe('test1')
        self.mqtt.subscribe('test2')
        self.assertEqual(2, len(self.mqtt.topics))
        self.mqtt.unsubscribe_all()
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt.disconnect()

    def test_publish(self):

        self.mqtt = Mqtt(self.app)

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            print(message)

        @self.mqtt.on_topic('test')
        def handle_on_topic(*args, **kwargs):
            pass

        self.mqtt.subscribe('test')
        self.mqtt.publish('test', 'hello world')
        time.sleep(2)
Ejemplo n.º 2
0
class FlaskMQTTTestCase(unittest.TestCase):
    def setUp(self):

        self.app = Flask(__name__)

    def test_simple_connect(self):
        self.mqtt = Mqtt(self.app)
        self.mqtt._disconnect()

    def test_connect_with_username(self):
        self.app.config['MQTT_USERNAME'] = '******'
        self.app.config['MQTT_PASSWORD'] = '******'
        self.mqtt = Mqtt(self.app)
        self.mqtt._disconnect()

    def test_subscribe(self):
        self.mqtt = Mqtt(self.app)
        self.subscribe_handled = False
        self.unsubscribe_handled = False

        @self.mqtt.on_subscribe()
        def handle_subscribe(client, userdata, mid_, granted_qos):
            self.subscribe_handled = True

        @self.mqtt.on_unsubscribe()
        def handle_unsubscribe(client, userdata, mid_):
            self.unsubscribe_handled = True

        ret, mid = self.mqtt.subscribe('home/test')
        self.assertEqual(ret, MQTT_ERR_SUCCESS)
        wait()

        ret, mid = self.mqtt.unsubscribe('home/test')
        self.assertEqual(ret, MQTT_ERR_SUCCESS)
        wait()

        self.assertTrue(self.subscribe_handled)
        self.assertTrue(self.unsubscribe_handled)

    def test_topic_count(self):
        self.mqtt = Mqtt(self.app)

        ret, mid = self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))

        ret, mid = self.mqtt.subscribe('test')
        self.assertEqual(1, len(self.mqtt.topics))

        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))

        self.mqtt.unsubscribe('test')
        self.assertEqual(0, len(self.mqtt.topics))

        ret, mid = self.mqtt.subscribe('test1')
        ret, mid = self.mqtt.subscribe('test2')
        self.assertEqual(2, len(self.mqtt.topics))
        self.mqtt.unsubscribe_all()
        self.assertEqual(0, len(self.mqtt.topics))
        self.mqtt._disconnect()

    def test_publish(self):

        self.mqtt = Mqtt(self.app)
        self.handled_message = False
        self.handled_topic = False
        self.handled_publish = False

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            self.handled_message = True

        @self.mqtt.on_publish()
        def handle_publish(client, userdata, mid):
            self.handled_publish = True

        self.mqtt.subscribe('home/test')
        wait()
        self.mqtt.publish('home/test', 'hello world')
        wait()

        self.assertTrue(self.handled_message)
        # self.assertTrue(self.handled_topic)
        self.assertTrue(self.handled_publish)

    def test_on_topic(self):

        self.mqtt = Mqtt(self.app)
        self.handled_message = False
        self.handled_topic = False

        @self.mqtt.on_message()
        def handle_message(client, userdata, message):
            self.handled_message = True

        @self.mqtt.on_topic('home/test')
        def handle_on_topic(*args, **kwargs):
            self.handled_topic = True

        self.mqtt.subscribe('home/test')
        wait()
        self.mqtt.publish('home/test', 'hello world')
        wait()

        self.assertFalse(self.handled_message)
        self.assertTrue(self.handled_topic)

    def test_logging(self):
        self.mqtt = Mqtt(self.app)

        @self.mqtt.on_log()
        def handle_logging(client, userdata, level, buf):
            self.assertIsNotNone(client)
            self.assertIsNotNone(level)
            self.assertIsNotNone(buf)

        self.mqtt.publish('test', 'hello world')
Ejemplo n.º 3
0
mqtt = Mqtt(app)
socketio = SocketIO(app)

users_online_controller_id = {}


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


# Send initial MQTT message in order to simulate some devices
devices_id_list = ['1', '2']
mqtt.publish(
    topic=f'{PUBLISH_MQTT_TOPIC}/{random.choice(devices_id_list)}/boiler_temp',
    payload=random.randrange(0, 100),
    retain=True
)


@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    mqtt.subscribe(SUBSCRIBE_MQTT_TOPIC)
    # Generate random data messages

@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    payload = message.payload
    topic = message.topic

    split_topic = topic.split('/')
#                answer+= ' ' + retVal[keys]
#        return answer

    # use the found information to call the device hub -> invoke the functions on the device(& return the value)
=======
    def buildMQTTMessage(retVal):
        for keys in retVal:
            if (keys == 'text' or keys == 'light-value'):
                answer = "Light-Value: " + str(retVal[keys])
            if(keys == 'resistance-value'):
                answer+= ' Resistance: ' + str(retVal[keys])
            if keys == 'unit':
                answer+= ' ' + str(retVal[keys])
        return answer

    mqtt.publish('light', buildMQTTMessage(light_sensor.get_light_intensity(1)))
    mqtt.publish('temperature', buildMQTTMessage(temperature_humidity_sensor.get_temperature(1)))
    mqtt.publish('humidity', buildMQTTMessage(temperature_humidity_sensor.get_humidity(1)))

   # use the found information to call the device hub -> invoke the functions on the device(& return the value)
>>>>>>> Stashed changes
#    tSensorValue = buildMQTTMessage(hub.invoke_implementation(tFunction, parameter_registery['temperature'],
#                                                              defaultArgs(qos), tSensor))
#    hSensorValue = buildMQTTMessage(hub.invoke_implementation(hFunction, parameter_registery['humidity'],
#                                                              defaultArgs(qos), hSensor))
#    lSensorValue = buildMQTTMessage(hub.invoke_implementation(lFunction, parameter_registery['light'],
#                                                              defaultArgs(qos), lSensor))

    # send the measured values to the broker endpoint other clients can access
#    mqtt.publish('temperature', tSensorValue)
#    mqtt.publish('humidity', hSensorValue)
Ejemplo n.º 5
0
        ConManager.conman.cond.update(connection)

    def on_log(client, userdata, level, buf):
        print("log: ", buf)

    connection_status_topic = mq_connections[:-2] + '/' + mq_client_name
    print('Publishing to', connection_status_topic)
    mqtt_client.subscribe(mq_connections)
    print('Mqtt client Connected to', mq_connections)
    mqtt_client.subscribe(mq_expdict)
    mqtt_client.subscribe(mq_status)
    mqtt_client.subscribe(mq_gpsdos)

    temp = {
        mq_client_name: {
            mq_client_name: {
                "name": mq_client_name,
                "connection": True,
                "ip": "192.168.100"
            }
        }
    }
    mqtt_client.publish(connection_status_topic, str(temp), 0, True)
    for node, v in mq_runners.items():
        mqtt_client.publish(mq_runners[node],
                            str({node: {
                                "Status": {
                                    "run": 0
                                }
                            }}), 0, False)
Ejemplo n.º 6
0
#api_key= 'waD6G64LINl7ieNoERaJ'
#@mqtt.on_log()
#def handle_logging(client, userdata, level, buf):
#   if level == MQTT_LOG_ERR:
#        print('Error: {}'.format(buf))
@mqtt.on_connect()
def handle_connect(client, userdata, flags, rc):
    mqtt.subscribe('iot')


#	if rc==0:
#		print("connected OK Returned code=",rc)
#	else:
#		print("Bad connection Returned code=",rc)
#	print('Connected and waiting for msgs')
mqtt.publish('home/mytopic', 'hello world')


@mqtt.on_message()
def handle_mqtt_messages(client, userdata, msg):
    #	print("Msg "+msg)
    global lat, lng
    data = eval(msg.payload.decode())
    lat = data['latitude']
    lng = data['longitude']
    print("received from aws  Lat=" + str(lat) + " Long" + str(lng))


print("MQTT Setup done " + "initial value -Lat=" + str(lat) + " long=" +
      str(lng))
Ejemplo n.º 7
0
class MqttClient:
    def __init__(self):
        self.mqtt = Mqtt()
        self.mqttclient_pub_topic_list = []
        self.mqttclient_sub_topic_list = []
        self.recv_msg_buffer = RingBuf(15)
        self.is_mqtt_client_connected = False

    def add_publish_topic(self, topic):
        # check for duplicate topics
        for item in self.mqttclient_pub_topic_list:
            if topic in item:
                return False

        # add topic to the list
        new_item = (topic, topic)
        self.mqttclient_pub_topic_list.append(new_item)
        return True

    def add_subscription_topic(self, topic):
        # check for duplicate topics
        for item in self.mqttclient_sub_topic_list:
            if topic in item:
                return False

        # add topic to the list
        new_item = (topic, topic)
        self.mqttclient_sub_topic_list.append(new_item)
        # Subscribe this topic
        self.mqtt.subscribe(topic)
        return True

    def rm_publish_topic(self, topic):
        # check for duplicate topics
        for item in self.mqttclient_pub_topic_list:
            if topic in item:
                # add topic to the list
                self.mqttclient_pub_topic_list.remove(item)
                return True
        return False

    def rm_subscription_topic(self, topic):
        # check for duplicate topics
        for item in self.mqttclient_sub_topic_list:
            if topic in item:
                # add topic to the list
                self.mqttclient_sub_topic_list.remove(item)

                # unsubscribe this topic
                self.mqtt.unsubscribe(topic)
                return True
        return False

    def get_status(self):
        return self.is_mqtt_client_connected

    def on_message_send(self, topic, message, qos):
        if topic != "" and message != "":
            [result, b] = self.mqtt.publish(topic, message, int(qos))
            if result == MQTT_ERR_SUCCESS:
                return True
        return False

    def on_message_receive(self, topic, data):
        message = topic + " : " + data
        self.recv_msg_buffer.append(message)
        print("added")

    def update(self):
        if self.recv_msg_buffer.item_list:
            output = ""
            for item in self.recv_msg_buffer.item_list:
                output = output + item + "\n"
            return output
        return None