예제 #1
0
def mqtt_benchmark(N, is_server, broker, user, pwd):
    received = 0

    def mqtt_callback(topic, msg):
        nonlocal received
        received += 1

    print("Connecting to MQTT broker", broker, "...")
    mqtt = MQTTClient(broker, user=user, password=pwd)
    mqtt.set_callback(mqtt_callback)
    mqtt.subscribe("iot49/{}".format(is_server))
    topic = "iot49/{}".format(not is_server)
    print("Starting test ...")
    gc.collect()
    try:
        t_start = time.ticks_ms()
        for i in range(N):
            if is_server:
                mqtt.publish(topic, "msg {}".format(i))
                mqtt.wait_msg()
            else:
                mqtt.wait_msg()
                mqtt.publish(topic, "ok {}".format(i))
        t_stop = time.ticks_ms()
        dt = time.ticks_diff(t_stop, t_start)
        if N != received:
            print("***** sent {} messages, received {}".format(N, received))
        print(">>> MQTT throughput, broker {}: {:8.4f} msg/s (N={})".format(
            broker, 1000 * received / dt, N))
    finally:
        mqtt.disconnect()
예제 #2
0
 def test_publishOne(self):
     #connect
     #publishone
     #disconnect
     #connect
     #publishone
     #...
     #publishone
     #disconnect
     topic = "test_topic"
     message = "test_message"
     mqtt_client = MQTTClient()
     
     mqtt_client.connect()
     mqtt_client.publish_one(topic, message)
     mqtt_client.publish_one(topic, message)
     #raw_input("Wait for restart push server and return.")
     mqtt_client.publish_one(topic, message)
     mqtt_client.publish_one(topic, message)
     mqtt_client.publish_one(topic, message)
     mqtt_client.start_send()
     mqtt_client.disconnect()
예제 #3
0
    def test_publishOne(self):
        #connect
        #publishone
        #disconnect
        #connect
        #publishone
        #...
        #publishone
        #disconnect
        topic = "test_topic"
        message = "test_message"
        mqtt_client = MQTTClient()

        mqtt_client.connect()
        mqtt_client.publish_one(topic, message)
        mqtt_client.publish_one(topic, message)
        #raw_input("Wait for restart push server and return.")
        mqtt_client.publish_one(topic, message)
        mqtt_client.publish_one(topic, message)
        mqtt_client.publish_one(topic, message)
        mqtt_client.start_send()
        mqtt_client.disconnect()
예제 #4
0
파일: 01_mqtt_demo.py 프로젝트: iot49/iot49
from mqttclient import MQTTClient
import time


def mqtt_callback(topic, msg):
    print("MQTT received topic={}, msg='{}'".format(topic, msg))


SERVER = "iot.eclipse.org"

mqtt = MQTTClient(SERVER)
mqtt.set_callback(mqtt_callback)
mqtt.subscribe("y")

# publish
for i in range(20):
    mqtt.check_msg()
    msg = "value=" + str(i)
    topic = "x"
    print("publish topic={} msg={}".format(topic, msg))
    mqtt.publish(topic, msg)
    time.sleep(1)

mqtt.disconnect()
예제 #5
0
        break
    #print("Waiting for Wifi connection...")
    sleep(1)

#print('Wifi connected at', wlan.ifconfig()[0])

#MQTT
tSpeak = 'mqtt.thingspeak.com'  #broker

channelID = '480665'  #SIP Channel
writeKey = '7PZPPOGEBEHAPKH3'
topic = "channels/" + channelID + "/publish/" + writeKey

#print("Connecting to broker ", tSpeak, "...")
mqtt = MQTTClient(tSpeak)
#print("Connected!")

message = "field1={}&field2={}&field3={}&field4={}&field5={}".format(\
          plant1, plant2, watered1, watered2, reservoir)

#print("Publish TOPIC = {}, MSG = {}".format(topic, message))
mqtt.publish(topic, message)  #publish the message

#print("All done")

mqtt.disconnect()  #close the socket

################################################################################
#Reset
deepsleep(2 * 60 * 60 * 1000)  #to take measurements every 2 hours
예제 #6
0
class Subscribe(base_calvinsys_object.BaseCalvinsysObject):
    """
    Subscribe to data on given MQTT broker
    """
    def init(self,
             topics,
             hostname,
             port=1883,
             qos=0,
             client_id='calvinconstrained',
             will=None,
             auth=None,
             tls=None,
             transport='tcp',
             payload_only=False,
             **kwargs):
        def sub_cb(topic, msg):
            self.data.append({"topic": topic.decode('utf-8'), "payload": msg})

        self.data = []
        self.payload_only = payload_only
        self.topics = topics
        self.user = None
        self.password = None
        self.ssl = False
        self.ssl_params = None

        if auth:
            user = auth.get("username")
            password = auth.get("password")

        if tls:
            print("Using TLS")
            self.ssl = True
            key_file = open(tls.get("keyfile"), "r")
            key = key_file.read()
            cert_file = open(tls.get("certfile"), "r")
            cert = cert_file.read()
            self.ssl_params = {"key": key, "cert": cert}

        self.c = MQTTClient(client_id,
                            hostname,
                            port=port,
                            user=self.user,
                            password=self.password,
                            ssl=self.ssl,
                            ssl_params=self.ssl_params)
        self.c.set_callback(sub_cb)
        self.c.connect()
        for topic in self.topics:
            self.c.subscribe(topic.encode("ascii"))

    def can_write(self):
        return True

    def write(self, data=None):
        pass

    def can_read(self):
        try:
            data = self.c.check_msg()
        except:
            return False
        return bool(self.data)

    def read(self):
        data = self.data.pop(0)
        if self.payload_only:
            return data.get("payload")
        else:
            return data

    def close(self):
        self.c.disconnect()
예제 #7
0
파일: mqtt.py 프로젝트: arduino-org/Ciao
	shd["requests"] = {}

	ciaoclient = MQTTCiao(shd, mqtt_queue, ciao_queue)
	ciaoclient.start()

	# endless loop until SIGHUP/SIGTERM
	while shd["loop"] :
		if not mqtt_queue.empty():
			entry = mqtt_queue.get()
			logger.debug("Entry %s" % entry)

			# if entry received from ciao is an "out" message
			if entry['type'] == "out":
				topic = str(entry['data'][0])
				message = str(entry['data'][1])
			else:
				continue

			mqttclient.publish(topic, message)

		# the sleep is really useful to prevent ciao to cap all CPU
		# this could be increased/decreased (keep an eye on CPU usage)
		# time.sleep is MANDATORY to make signal handlers work (they are synchronous in python)
		time.sleep(0.01)

	mqttclient.disconnect()
	logger.info("MQTT connector is closing")
	sys.exit(0)

else:
	logger.critical("Unable to connect to %s" % shd["conf"]["params"]["host"])
예제 #8
0
파일: mqtt.py 프로젝트: siwaphol/Ciao
    shd["requests"] = {}

    ciaoclient = MQTTCiao(shd, mqtt_queue, ciao_queue)
    ciaoclient.start()

    # endless loop until SIGHUP/SIGTERM
    while shd["loop"]:
        if not mqtt_queue.empty():
            entry = mqtt_queue.get()
            logger.debug("Entry %s" % entry)

            # if entry received from ciao is an "out" message
            if entry['type'] == "out":
                topic = str(entry['data'][0])
                message = str(entry['data'][1])
            else:
                continue

            mqttclient.publish(topic, message)

        # the sleep is really useful to prevent ciao to cap all CPU
        # this could be increased/decreased (keep an eye on CPU usage)
        # time.sleep is MANDATORY to make signal handlers work (they are synchronous in python)
        time.sleep(0.01)

    mqttclient.disconnect()
    logger.info("MQTT connector is closing")
    sys.exit(0)

else:
    logger.critical("Unable to connect to %s" % shd["conf"]["params"]["host"])