skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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.

        
        private let connectionString = "<Your IoT Hub Connection String>"
        
        private let iotProtocol: IOTHUB_CLIENT_TRANSPORT_PROVIDER = MQTT_Protocol
    
        private var iotHubClientHandle: IOTHUB_CLIENT_LL_HANDLE!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, iotProtocol)
            if (iotHubClientHandle == nil) {
                print("Failed to create IoT handle")
                return
            }
         
            Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(sendTelemetry), userInfo: nil, repeats: true)
        }
        
        @objc func sendTelemetry() {
            let temperature = String(format: "%.2f", drand48() * 15 + 20)
            let humidity = String(format: "%.2f", drand48() * 20 + 60)
            
            let telemetryData: [String: String] = ["temperature": temperature, "humidity": humidity]
            let messageString = telemetryData.description
     
            let messageHandle: IOTHUB_MESSAGE_HANDLE = IoTHubMessage_CreateFromByteArray(messageString, messageString.utf8.count)
            
            if messageHandle != OpaquePointer.init(bitPattern: 0) {
     IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, { result, userContext in
                    if result == IOTHUB_CLIENT_CONFIRMATION_OK {
                        print("Message sent successfully")
                    } else {
                        print("Failed to send message")
                    }
                }, nil)
            }
        }
        
        deinit {
      
            if let clientHandle = iotHubClientHandle {
                IoTHubClient_LL_Destroy(clientHandle)
            }
        }
    
    
    
    

    Output:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search