def on_message(mqttc, userdata, msg):
    print(msg.topic + "  " + str(msg.payload))

    # Get the response properties, abort if they're not given
    props = msg.properties
    if not hasattr(props, 'ResponseTopic') or not hasattr(
            props, 'CorrelationData'):
        print("No reply requested")
        return

    corr_id = props.CorrelationData
    reply_to = props.ResponseTopic

    # The command parameters are in the payload
    nums = json.loads(msg.payload)

    # The requested command is at the end of the topic
    res = 0
    if msg.topic.endswith("add"):
        res = add(nums)
    elif msg.topic.endswith("mult"):
        res = mult(nums)

    # Now we have the result, res, so send it back on the 'reply_to'
    # topic using the same correlation ID as the request.
    print("Sending response " + str(res) + " on '" + reply_to + "': " +
          str(corr_id))
    props = mqtt.Properties(PacketTypes.PUBLISH)
    props.CorrelationData = corr_id

    payload = json.dumps(res)
    mqttc.publish(reply_to, payload, qos=1, properties=props)
    def submit_cbor(self):
        """ publish the data
        read the topic from screen
        read the message, convert it to cbor
        add qos level & retain info
        if command, then add return topic and corrolation id.
        publish the data
        """
        my_data = self.message_entry.get('1.0', tk.END)
        cbor_data = None
        if my_data is not None and len(my_data) > 2:
            try:
                json_data = json.loads(my_data)
            except JSONDecodeError as e:
                # do whatever you want
                logger.log(logging.ERROR, e)
                return
            except TypeError as e:
                # do whatever you want in this case
                logger.log(logging.ERROR, e)
                return
            cbor_data = cbor.dumps(json_data)
        my_topic = self.topic.get()
        my_qos = self.level.get()
        my_qos_int = int(my_qos)
        my_retain = self.btn_var.get()
        print(" ====> RETAIN", my_retain)
        retain_flag = False
        if my_retain == "1":
            print("retain is true")
            retain_flag = True

        additional_data = " "
        props = None
        last_topic = my_topic.split("/")[-1]
        if last_topic in ["C", "R", "U", "D", "N"]:
            return_topic = self.app.client.my_udn
            props = mqtt.Properties(PacketTypes.PUBLISH)
            random_number = randrange(100000)
            random_string = str(random_number)
            props.CorrelationData = random_string.encode("utf-8")
            props.ResponseTopic = return_topic
            additional_data = "\ncorr Id: " + \
                str(props.CorrelationData) + \
                " Response Topic: " + props.ResponseTopic

        my_string = "publish: " + str(self.topic.get()) + " QOS: " + my_qos + \
            " Retain: " + my_retain + " " + my_data + additional_data
        logger.log(logging.INFO, my_string)
        topic_queue.append([props.CorrelationData, my_topic, None, None])
        ret = self.app.client.publish(my_topic,
                                      cbor_data,
                                      my_qos_int,
                                      retain_flag,
                                      properties=props)
    def submit_disc(self):
        """ publish the oic/res discovery

        publish the data
        """
        my_data = ""  # no input for discovery
        cbor_data = None
        if my_data is not None and len(my_data) > 2:
            try:
                json_data = json.loads(my_data)
            except JSONDecodeError as e:
                # do whatever you want
                logger.log(logging.ERROR, e)
                return
            except TypeError as e:
                # do whatever you want in this case
                logger.log(logging.ERROR, e)
                return
            cbor_data = cbor.dumps(json_data)
        my_topic = "OCF/*/oic%2Fres/R"
        my_qos = self.level.get()
        my_qos_int = int(my_qos)
        my_retain = self.btn_var.get()
        print(" ====> RETAIN", my_retain)
        retain_flag = False
        if my_retain == "1":
            print("retain is true")
            retain_flag = True

        additional_data = " "
        props = None
        last_topic = my_topic.split("/")[-1]
        if last_topic in ["C", "R", "U", "D", "N"]:
            return_topic = self.app.client.my_udn
            props = mqtt.Properties(PacketTypes.PUBLISH)
            random_number = randrange(100000)
            random_string = str(random_number)
            props.CorrelationData = random_string.encode("utf-8")
            props.ResponseTopic = return_topic
            additional_data = "\ncorr Id: " + str(
                props.CorrelationData
            ) + " Response Topic: " + props.ResponseTopic

        my_string = "publish: " + str(
            self.topic.get()
        ) + " QOS: " + my_qos + " Retain: " + my_retain + " " + my_data + additional_data
        logger.log(logging.INFO, my_string)
        topic_queue.append([props.CorrelationData, my_topic, None, None])
        print(my_string)
        ret = self.app.client.publish(my_topic,
                                      cbor_data,
                                      my_qos_int,
                                      retain_flag,
                                      properties=props)
def publish_url(client,
                return_topic,
                udn,
                url,
                command=None,
                cb=None,
                message=None):
    """publish the message
       udn + url as topic with optional command
    Args:
        client (mqtt): mqtt client
        return_topic (string): return topic
        udn (string): udn of the target device
        url (string): url of the target
        command (string, optional): command e.g. CRUDN. Defaults to None.
        cb (function name, optional): callback function. Defaults to None.
        message (any, optional): message to be published . Defaults to None.
    """
    my_url = url
    my_qos_int = 0
    retain_flag = False
    cbor_data = message
    if my_url[0] == "/":
        my_url = my_url[1:]
    my_url = my_url.replace("/", "%2F")
    my_topic = "OCF/" + udn + "/" + my_url
    if command is not None:
        if command in ["C", "R", "U", "D", "N"]:
            my_topic += "/" + command
        else:
            logger.log(logging.ERROR, "command not in CRUDN:" + command)
    props = mqtt.Properties(PacketTypes.PUBLISH)
    random_number = randrange(100000)
    random_string = str(random_number)
    props.CorrelationData = random_string.encode("utf-8")
    props.ResponseTopic = return_topic
    print(" publish_url publish request:", my_topic, random_string)
    topic_queue.append([props.CorrelationData, my_topic, cb, udn])
    ret = client.publish(my_topic,
                         cbor_data,
                         my_qos_int,
                         retain_flag,
                         properties=props)
Ejemplo n.º 5
0
def on_message(mqttc, userdata, msg):
    print(msg.topic + "  " + str(msg.payload))

    #获取响应属性,如果没有给出则中止
    props = msg.properties
    if not hasattr(props, 'ResponseTopic') or not hasattr(
            props, 'CorrelationData'):
        print("No reply requested")
        return

    corr_id = props.CorrelationData
    reply_to = props.ResponseTopic

    #现在我们有了结果res,所以将其发送回'reply_to'
    #个主题,使用与请求相同的相关性ID。
    props = mqtt.Properties(PacketTypes.PUBLISH)
    props.CorrelationData = corr_id

    mqttc.publish(reply_to, msg.payload, qos=1, properties=props)
Ejemplo n.º 6
0
    done = True


# Init MQTT client
client = mqtt.Client("Python test client", protocol=mqtt.MQTTv5)
# optional login data: client.username_pw_set("username","password")
client.on_message = on_message
client.on_connect = on_connect
# optional configure transport level security: client.tls_set(cert_reqs=mqtt.ssl.CERT_NONE,tls_version=mqtt.ssl.PROTOCOL_TLSv1_2)
client.connect("localhost",
               1883)  # or 8883 when in transport level security mode
client.loop_start()
client.subscribe("Python/response", qos=2)

# Send model
properties = mqtt.Properties(mqttpackettypes.PacketTypes.PUBLISH)
properties.ResponseTopic = "Python/response"
properties.UserProperty = (
    "a", "2"
)  # User properties can be used to identify response (Warteschlangensimulator will echo them in response message)
properties.UserProperty = ("c", "3")
client.publish("Warteschlangensimulator/task",
               payload=model,
               qos=2,
               properties=properties)
print(
    "Submitted work request together with response topic name and user properties"
)

# Wait
while not done:
    print("USAGE: client_rpc_math.py [add|mult] n1 n2 ...")
    sys.exit(1)

mqttc = mqtt.Client(client_id="", protocol=mqtt.MQTTv5)
mqttc.on_message = on_message
mqttc.on_connect = on_connect

mqttc.connect(host='localhost', clean_start=True)
mqttc.loop_start()

# Wait for connection to set `client_id`, etc.
while not mqttc.is_connected():
    time.sleep(0.1)

# Properties for the request specify the ResponseTopic and CorrelationData
props = mqtt.Properties(PacketTypes.PUBLISH)
props.CorrelationData = corr_id
props.ResponseTopic = reply_to

# Uncomment to see what got set
#print("Client ID: "+client_id)
#print("Reply To: "+reply_to)
#print(props)

# The requested operation, 'add' or 'mult'
func = sys.argv[1]

# Gather the numeric parameters as an array of numbers
# These can be int's or float's
args = []
for s in sys.argv[2:]: