How can I send telemetry message to Azure IOT hub using swift. I have python code, I am very new to swift.
I am trying to use code from here
from paho.mqtt import client as mqtt
import ssl
path_to_root_cert = "<local path to digicert.cer file>"
device_id = "<device id from device registry>"
sas_token = "<generated SAS token>"
iot_hub_name = "<iot hub name>"
def on_connect(client, userdata, flags, rc):
print("Device connected with result code: " + str(rc))
def on_disconnect(client, userdata, rc):
print("Device disconnected with result code: " + str(rc))
def on_publish(client, userdata, mid):
print("Device sent message")
client = mqtt.Client(client_id=device_id, protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
client.username_pw_set(username=iot_hub_name+".azure-devices.net/" +
device_id + "/?api-version=2021-04-12", password=sas_token)
client.tls_set(ca_certs=path_to_root_cert, certfile=None, keyfile=None,
cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)
client.tls_insecure_set(False)
client.connect(iot_hub_name+".azure-devices.net", port=8883)
client.publish("devices/" + device_id + "/messages/events/", '{"id":123}', qos=1)
client.loop_forever()
2
Answers
you have to install third party library named
CocoaMQTT
and setup the server same as you did in python
then in app delegate file you have to call this delegate method
CocoaMQTT5Delegate
setup socket when app become active
for more information you can check example of the library on GitHub
or you can comment your email I can share the full code personally
The Swift code below is for using MQTT to send telemetry messages to Azure IoT Hub.
I referred to this Microsoft documentation, and I would like to thank @Kelly Gremban for the GitHub link from which I referred to the code.
The code below uses the MQTT protocol for communication with Azure IoT Hub.
Output: