Skip to content

Commit

Permalink
readme updates
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanwinter committed Dec 16, 2022
1 parent 8626cce commit 4695b17
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 77 deletions.
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ For more information, refer to the [Overview of Azure IoT Device SDKs](https://d

This repository contains the following samples:

* [Mosquitto](mosquitto)
* [Mosquitto_pub](mosquitto_pub)
* [Mosquitto client library](mosquitto)
* [Mosquitto_pub CLI](mosquitto_pub)
* [Python](python)

## Root certificates
Expand All @@ -44,17 +44,25 @@ The following root certificates are provided in the repository root:

| Certificate | Path | Description |
|-|-|-|
| [Baltimore CyberTrust Root](https://www.digicert.com/kb/digicert-root-certificates.htm) | BaltimoreCyberTrustRoot.crt.pem | Current Root CA set to **expire in 2025** |
| [Baltimore CyberTrust Root](https://www.digicert.com/kb/digicert-root-certificates.htm) | BaltimoreCyberTrustRoot.crt.pem | **NOT recommended for use** since [IoT Hub migration out of Baltimore](https://techcommunity.microsoft.com/t5/internet-of-things-blog/azure-iot-tls-critical-changes-are-almost-here-and-why-you/ba-p/2393169) is set to start on Feb 2023.
| [DigiCert Global Root G2](https://www.digicert.com/kb/digicert-root-certificates.htm) | DigiCertGlobalRootG2.crt.pem | Future Root CA which will become active in Feb 2023 |

## General Prerequisites

To be able to run these samples the following general prerequisites are needed:
1. Clone this repository

1. Clone this repository (Install [Git](https://git-scm.com/downloads))
1. Change into the cloned directory:

```
cd IoTMQTTSample
```

1. Install the [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli)
1. [Provision an IoT Hub](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal) in your Azure subscription
1. [Register a device](https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-create-through-portal#register-a-new-device-in-the-iot-hub) within your IoT Hub
1. [Generate a SAS token](https://docs.microsoft.com/cli/azure/iot/hub?view=azure-cli-latest#az-iot-hub-generate-sas-token) for the device using the Azure CLI
1. [Generate a SAS token](https://learn.microsoft.com/cli/azure/iot/hub?view=azure-cli-latest#az-iot-hub-generate-sas-token) for the device using the Azure CLI

> **Note**
> By default the **SAS Token is valid for 60 minutes**. Use the --du parameter to increase if needed.
Expand Down
25 changes: 20 additions & 5 deletions mosquitto/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,24 @@ This samples uses the Mosquitto (MQTT) library to send a message to an Azure IoT
sudo apt install libmosquitto-dev
```

## Variable substitions

The following variables will need to be expanded in the samples:

| Variable | Description | Example |
|-|-|-|
| iothub_name | The name of the created IoT Hub (**NOT FQDN/HostName**) | *iothub*
| device_id | The name of the device created in the IoT Hub | *mosquitto_pub*
| sas_token | The SAS token [generated](https://learn.microsoft.com/cli/azure/iot/hub?view=azure-cli-latest#az-iot-hub-generate-sas-token) for the device | *SharedAccessSignature sr=\*.azure-devices.net%2Fdevices%2F\*&sig=\**

## Build

1. Change to the `mosquitto` directory in the cloned repository

```Shell
cd mosquitto
```

1. Edit the `config.h` file and expand the required connection information:

```c
Expand Down Expand Up @@ -77,7 +92,7 @@ This sample will send a single telemetry message, which can be viewed by monitor
```json
{
"event": {
"origin": "pubsub",
"origin": "*",
"module": "",
"interface": "",
"component": "",
Expand Down Expand Up @@ -106,10 +121,10 @@ This sample will subscribe to all available MQTT topics, and then display an clo

```Shell
Waiting for C2D messages...
C2D message 'hello world' for topic 'devices/pubsub/messages/devicebound/...`
Got message for devices/pubsub/messages/# topic
C2D message 'hello world' for topic 'devices/*/messages/devicebound/...`
Got message for devices/*/messages/# topic
```
### Device twin sample
This sample will add a temperature reported property to the device twin, and then read the property back.
Expand All @@ -130,4 +145,4 @@ This sample will add a temperature reported property to the device twin, and the
Getting device twin properties....
Device twin message '{"desired":{"$version":1},"reported":{"temperature":32,"$version":2}}' for topic '$iothub/twin/res/200/?$rid=123'
Getting device twin properties SUCCEEDED.
```
```
24 changes: 13 additions & 11 deletions mosquitto_pub/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,25 @@ The following steps must be complete before running the samples below:

1. Follow the [general prerequisites](/README.md#general-rerequisites)
1. Install [Mosquitto](https://mosquitto.org/download) to your target machine

> **NOTE**
> On Windows, you will need to add the Mosquitto directory to your environment PATH
1. Confirm that `mosquitto_pub` is in your system path

## Variable substitution

The following variables will need to be expanded in the following samples:
The following variables will need to be expanded in the samples:

| Variable | Description |
|-|-|
| iothub_name | The name of the created IoT Hub |
| device_id | The name of the device created in the IoT Hub |
| sas_token | The SAS token generated for the device |
| certificate_pem | The [Root CA](/README.md#root-certificates) used to validate the IoT Hub |
| Variable | Description | Example |
|-|-|-|
| iothub_name | The name of the created IoT Hub (**NOT FQDN/HostName**) | *iothub*
| device_id | The name of the device created in the IoT Hub | *mosquitto_pub*
| sas_token | The SAS token [generated](https://learn.microsoft.com/cli/azure/iot/hub?view=azure-cli-latest#az-iot-hub-generate-sas-token) for the device | *SharedAccessSignature sr=\*.azure-devices.net%2Fdevices%2F\*&sig=\**
| certificate_pem | The [Root CA](/README.md#root-certificates) used to validate the IoT Hub | *DigiCertGlobalRootG2.crt.pem*

## Send a message

1. Change to the `src` directory in the cloned repository directory for easier access to the root certificates

1. Start monitoring incoming messages on your Hub:

```Shell
Expand All @@ -37,7 +39,7 @@ The following variables will need to be expanded in the following samples:
1. From a second terminal, send a message from the device:

```Shell
mosquitto_pub -d -h {iothub_name}.azure-devices.net -p 8883 -i {device_id} -u "{iothub_name}.azure-devices.net/{device_id}/?api-version=2018-06-30" -P "{sas_token}>" -t "devices/{device_id}/messages/events/" -m "hello world" -V mqttv311 --cafile {certificate_pem} -q 1
mosquitto_pub -d -h {iothub_name}.azure-devices.net -p 8883 -i {device_id} -u "{iothub_name}.azure-devices.net/{device_id}/?api-version=2018-06-30" -P "{sas_token}" -t "devices/{device_id}/messages/events/" -m "hello world" -V mqttv311 --cafile {certificate_pem} -q 1
```

3. Confirm the following output is seen from the monitor-events command:
Expand Down Expand Up @@ -65,7 +67,7 @@ The following variables will need to be expanded in the following samples:
2. Send a message from the Hub to the device:

```Shell
az iot device c2d-message send --hub-name {iothub_name} --device-id {device_id} --data "hello world"
az iot device c2d-message send -n {iothub_name} -d {device_id} --data "hello world"
```

3. Confirm the following output from the mosquitto_sub command:
Expand Down
31 changes: 9 additions & 22 deletions python/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,33 @@
# Licensed under the MIT License.

import paho.mqtt.client as mqtt
from base64 import b64encode, b64decode
from time import time, sleep
from urllib import parse
from hmac import HMAC
from hashlib import sha256
from time import sleep
from ssl import SSLContext, PROTOCOL_TLS_CLIENT, CERT_REQUIRED

IOT_HUB_HOSTNAME = ""
IOT_HUB_DEVICE_ID = ""
IOT_HUB_SAS_KEY = ""
IOT_HUB_NAME = "{iothub_name}"
IOT_HUB_DEVICE_ID = "{device_id}"
IOT_HUB_SAS_TOKEN = "{sas_token}"

def on_connect(mqtt_client, obj, flags, rc):
print("connect: " + str(rc))

def on_publish(mqtt_client, obj, mid):
print("publish: " + str(mid))

def generate_sas_token():
ttl = int(time()) + 300
uri = IOT_HUB_HOSTNAME + "/devices/" + IOT_HUB_DEVICE_ID
sign_key = uri + "\n" + str(ttl)

signature = b64encode(HMAC(b64decode(IOT_HUB_SAS_KEY), sign_key.encode('utf-8'), sha256).digest())

return "SharedAccessSignature sr=" + uri + "&sig=" + parse.quote(signature, safe="") + "&se=" + str(ttl)

mqtt_client = mqtt.Client(client_id=IOT_HUB_DEVICE_ID, protocol=mqtt.MQTTv311)
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish
mqtt_client.on_connect = on_connect
mqtt_client.on_publish = on_publish

mqtt_client.username_pw_set(username=IOT_HUB_HOSTNAME + "/" + IOT_HUB_DEVICE_ID + "/?api-version=2021-04-12",
password=generate_sas_token())
mqtt_client.username_pw_set(username=IOT_HUB_NAME + ".azure-devices.net/" + IOT_HUB_DEVICE_ID + "/?api-version=2021-04-12",
password=IOT_HUB_SAS_TOKEN)

ssl_context = SSLContext(protocol=PROTOCOL_TLS_CLIENT)
ssl_context.load_default_certs()
ssl_context.verify_mode = CERT_REQUIRED
ssl_context.check_hostname = True
mqtt_client.tls_set_context(context=ssl_context)

mqtt_client.connect(host=IOT_HUB_HOSTNAME, port=8883, keepalive=120)
mqtt_client.connect(host=IOT_HUB_NAME + ".azure-devices.net", port=8883, keepalive=120)

# start the MQTT processing loop
mqtt_client.loop_start()
Expand Down
86 changes: 52 additions & 34 deletions python/readme.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,59 @@

# Using MQTT to connect an IoT Hub with Python

## Assumptions
1. Python is [installed](https://www.python.org/downloads)
1. Pip is [installed](https://pip.pypa.io/en/stable/installation)
1. An IoT Hub has been [created](https://docs.microsoft.com/azure/iot-hub/iot-hub-create-through-portal)
1. A device has been [registered](https://docs.microsoft.com/azure/iot-hub/iot-hub-create-through-portal#register-a-new-device-in-the-iot-hub) using Symmetric key authentication
## Prerequisites

1. Follow the [general prerequisites](/README.md#general-rerequisites)
1. Install [Python](https://www.python.org/downloads)
1. Install [Pip](https://pip.pypa.io/en/stable/installation)

## Variable substitution

The following variables will need to be expanded in the sample:

| Variable | Description | Example |
|-|-|-|
| iothub_name | The name of the created IoT Hub (**NOT FQDN/HostName**) | *iothub*
| device_id | The name of the device created in the IoT Hub | *mosquitto_pub*
| sas_token | The SAS token [generated](https://learn.microsoft.com/cli/azure/iot/hub?view=azure-cli-latest#az-iot-hub-generate-sas-token) for the device | *SharedAccessSignature sr=\*.azure-devices.net%2Fdevices%2F\*&sig=\**

## Setup

1. Open main.py and edit the following fields with the correct IoT Hub and device information
* IOT_HUB_HOSTNAME
* IOT_HUB_NAME
* IOT_HUB_DEVICE_ID
* IOT_HUB_SAS_KEY

2. Install Paho MQTT

```
pip install paho-mqtt
```

3. Run the script

```
python main.py
```

4. Observe the telemetry being sent
```
sending message[0]: Accio
connect: 0
publish: 1
sending message[1]: Aguamenti
publish: 2
sending message[2]: Alarte Ascendare
publish: 3
sending message[3]: Expecto Patronum
publish: 4
sending message[4]: Homenum Revelio
publish: 5
```
* IOT_HUB_SAS_TOKEN

1. Install Paho MQTT

```Shell
pip install paho-mqtt
```

1. Change into the `python` directory in the cloned repository:

```Shell
cd python
```

1. Run the script

```Shell
python main.py
```

1. Observe the telemetry being sent

```Shell
sending message[0]: Accio
connect: 0
publish: 1
sending message[1]: Aguamenti
publish: 2
sending message[2]: Alarte Ascendare
publish: 3
sending message[3]: Expecto Patronum
publish: 4
sending message[4]: Homenum Revelio
publish: 5
```

0 comments on commit 4695b17

Please sign in to comment.