skip to Main Content

I am trying to publish some sensor data from an IoT device which, I have set up in Azure IoT hub, to a MQTT topic. I have found this but I haven’t had any success following it.

I have also found read some places that I should be using the /{deviceID}/messages/events/ topic while using event broker http://{IoTHubName}.azure-devices.net/ but I also haven’t had any success using this.

I am just using the Raspberry Pi online simulator as the sensor and this is working as I can see the messages using the command ‘az iot hub monitor-events –hub-name {IoTHubName}’.

My end goal is to read data into a platform called Vantiq, whcih you can do by subscribing to MQTT topics, so all I really need is to publish the data from IoT Hub, preferably in JSON.

Sorry if I am not using the correct terminology, I am new to all IoT, Azure and MQTT.

Any help would be gratefully appreciated, thanks!

2

Answers


  1. The link that you mentioned is related to Azure IoT Edge and not IoT Hub. If not using the SDKs and just MQTT client you will need to refer to following –

    https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-mqtt-support#using-the-mqtt-protocol-directly-as-a-device

    For token based authentication you will need to generate token for your mqtt client to authenticate with IoTHub, other option is to use X509 certificate. The connection also needs to be TLS which requires your client device to trust IoTHub certificate (Windows or Linux already have the certs trusted).

    Once the token is generated, you can configure your mqtt client with ClientId as deviceId, Username as {iotHub-hostname}/{device-id}/?api-version=2021-04-12 and Password set to the SAS token e.g. SharedAccessSignature sig={signature-string}&se={expiry}&sr={URL-encoded-resourceURI

    The mqtt client then can publish messages to topic devices/{device-id}/messages/events/ and update its reported properties to devices/{device-id}/messages/events/{property-bag}

    The above link has a Python sample using Paho MQTT library.

    Login or Signup to reply.
  2. Loading the default certs (in a debian:buster-slim docker container) into an ssl context and using that context for the mqtt connection works for me:

    def __init__(self):
        self._mqttUsername = "%s/%s/%s/?api-version=2020-09-30&model-id=%s" %(self._hubname, self._deviceId, self._moduleId, dtmi)
    
        token = AzureIoTDevice.generate_sas_token("%s/devices/%s" %(self._hubname, self._deviceId), self._key)
    
        self._mqttClient = mqtt.Client(client_id="%s/%s" %(self._deviceId, self._moduleId), clean_session=False, protocol=mqtt.MQTTv311)
        self._mqttClient.user_data_set(serialNumber)
        self._mqttClient.username_pw_set(username=self._mqttUsername, password=token)
        ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLSv1_2)
        ssl_context.load_default_certs()
        self._mqttClient.tls_set_context(context=ssl_context)
    
    def sendTelemetry(self, telemetry):
        """ Sends a telemetry dict to the default event endpoint.
            Arguments:
                telemetry: a dictionary of sensorname, sensorvalue
        """
        self.logger.debug("{%s} Reporting telemetry '%s'." %(self._deviceId, telemetry))
        res, mid = self._mqttClient.publish(topic="devices/%s/modules/%s/messages/events/" %(self._deviceId, self._moduleId), payload=json.dumps(telemetry), qos=1, retain=False)
        if res != 0:
            self.logger.error("{%s} Reporting telemetry failed with status %s." %(self._deviceId, str(res)))
            return False
        return True
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search