adafruit / circuitpython

CircuitPython - a Python implementation for teaching coding with microcontrollers
https://circuitpython.org
Other
4.09k stars 1.21k forks source link

picow unable to connect to Microsoft Azure IoT Hub or IoT Central #7038

Closed BlitzCityDIY closed 2 years ago

BlitzCityDIY commented 2 years ago

CircuitPython version

Adafruit CircuitPython 8.0.0-beta.1-24-g14c9028c1 on 2022-10-10; Raspberry Pi Pico W with rp2040

Code/REPL

#IoT Central Test Code

# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import os
import busio
import json
import supervisor
import board
import terminalio
import rtc
import socketpool
import wifi
import adafruit_ntp
from adafruit_azureiot import IoTCentralDevice

print("Connecting to WiFi...")
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))

print("Connected to WiFi!")

#  ntp clock - update tz_offset to your timezone
pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool)
rtc.RTC().datetime = ntp.datetime

if time.localtime().tm_year < 2022:
    print("Setting System Time in UTC")
    rtc.RTC().datetime = ntp.datetime

else:
    print("Year seems good, skipping set time.")

# Create an IoT Hub device client and connect
esp = None
pool = socketpool.SocketPool(wifi.radio)
device = IoTCentralDevice(
    pool, esp, os.getenv('id_scope'), os.getenv('device_id'), os.getenv('device_primary_key')
)
try:
    print("Connecting to Azure IoT Central...")
    device.connect()
except Exception:
    time.sleep(2)
    print("trying to connect again...")
    device.connect()

print("Connected to Azure IoT Central!")

#  clock to count down to sending data to Azure
azure_clock = 500

while True:
    try:
        #  when the azure clock runs out
        if azure_clock > 500:
            #  pack message
            message = {"Temperature": 75}
            print("sending json")
            device.send_telemetry(json.dumps(message))
            print("data sent")
            #  reset azure clock
            azure_clock = 0
        else:
            azure_clock += 1
        #  ping azure
        device.loop()
    #  if something disrupts the loop, reconnect
    # pylint: disable=broad-except
    except (ValueError, RuntimeError, OSError, ConnectionError) as e:
        print("Network error, reconnecting\n", str(e))
        supervisor.reload()
        continue
    #  delay
    time.sleep(1)
    print(azure_clock)

# ----------

#  IoT Hub Test Code

# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import os
import json
import digitalio
import supervisor
import board
import rtc
import socketpool
import wifi
import adafruit_ntp
from adafruit_azureiot import IoTHubDevice

print("Connecting to WiFi...")
wifi.radio.connect(os.getenv('WIFI_SSID'), os.getenv('WIFI_PASSWORD'))

print("Connected to WiFi!")

#  ntp clock - update tz_offset to your timezone
pool = socketpool.SocketPool(wifi.radio)
ntp = adafruit_ntp.NTP(pool, tz_offset=0)
rtc.RTC().datetime = ntp.datetime

if time.localtime().tm_year < 2022:
    print("Setting System Time in UTC")
    rtc.RTC().datetime = ntp.datetime

else:
    print("Year seems good, skipping set time.")

esp = None
pool = socketpool.SocketPool(wifi.radio)
# Create an IoT Hub device client and connect
#  the IoTHubDevice() does not seem to like os.getenv() for loading device string
#  was passing it directly as a string to workaround
device = IoTHubDevice(pool, esp, " ")

print("Connecting to Azure IoT Hub...")

# Connect to IoT Hub
device.connect()

print("Connected to Azure IoT Hub!")

#  clock to count down to sending data to Azure
azure_clock = 500

while True:
    try:
        if azure_clock > 500:
            print("getting msg")
            #  pack message
            message = {"CO2": 500}
            print("sending json")
            device.send_device_to_cloud_message(json.dumps(message))
            print("data sent")
            #  reset azure clock
            azure_clock = 0
        #  if no clocks are running out
        #  increase counts by 1
        else:
            azure_clock += 1
        #  ping azure
        device.loop()
    #  if something disrupts the loop, reconnect
    # pylint: disable=broad-except
    except (ValueError, RuntimeError, OSError, ConnectionError) as e:
        print("Network error, reconnecting\n", str(e))
        time.sleep(10)
        supervisor.reload()
        continue
    #  delay
    time.sleep(1)

Behavior

The REPL from running the IoT Central test code:

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
]0;🐍code.py | 8.0.0-beta.1-24-g14c9028c1\Connecting to WiFi...
Connected to WiFi!
Year seems good, skipping set time.
Connecting to Azure IoT Central...
989.607: DEBUG - Attempting to establish MQTT connection...
989.613: INFO - Establishing a SECURE SSL connection to global.azure-devices-provisioning.net:8883
992.453: DEBUG - Sending CONNECT to broker...
992.458: DEBUG - Fixed Header: bytearray(b'\x10\xf1\x01\x00')
Variable Header: bytearray(b'\x04MQTT\x04\xc2\x00x')
992.472: DEBUG - Receiving CONNACK packet from broker
992.739: INFO - - device_registration :: _on_connect :: rc = 0, userdata = None
992.743: INFO -  - device_registration :: connect :: created mqtt client. connecting..
992.748: INFO -  - device_registration :: connect :: on_connect must be fired. Connected ? True
992.755: DEBUG - SUBSCRIBING to topic $dps/registrations/res/# with QoS 0
trying to connect again...
995.331: DEBUG - Attempting to establish MQTT connection...
995.336: INFO - Establishing a SECURE SSL connection to global.azure-devices-provisioning.net:8883
999.175: DEBUG - Sending CONNECT to broker...
999.180: DEBUG - Fixed Header: bytearray(b'\x10\xed\x01\x00')
Variable Header: bytearray(b'\x04MQTT\x04\xc2\x00x')
999.194: DEBUG - Receiving CONNACK packet from broker
999.419: INFO - - device_registration :: _on_connect :: rc = 0, userdata = None
999.423: INFO -  - device_registration :: connect :: created mqtt client. connecting..
999.428: INFO -  - device_registration :: connect :: on_connect must be fired. Connected ? True
999.435: DEBUG - SUBSCRIBING to topic $dps/registrations/res/# with QoS 0
Traceback (most recent call last):
  File "code.py", line 46, in <module>
  File "adafruit_azureiot/iotcentral_device.py", line 159, in connect
  File "adafruit_azureiot/device_registration.py", line 204, in register_device
  File "adafruit_azureiot/device_registration.py", line 128, in _start_registration
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 741, in subscribe
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 876, in _wait_for_msg
MMQTTException: 
]0;🐍876@/lib/adafruit_minimqtt/adafruit_ MMQTTException | 8.0.0-beta.1-24-g14c9028c1\
Code done running.

Press any key to enter the REPL. Use CTRL-D to reload.```

The REPL from running the IoT Hub test code (some info blocked out for security)

```Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
]0;🐍code.py | 8.0.0-beta.1-24-g14c9028c1\Connecting to WiFi...
Connected to WiFi!
Year seems good, skipping set time.
1376.192: DEBUG - Hostname: BlitzCityHub.azure-devices.net
1376.197: DEBUG - Device Id: ####
1376.201: DEBUG - Shared Access Key: #####
Connecting to Azure IoT Hub...
1376.759: INFO - - iot_mqtt :: connect :: BlitzCityHub.azure-devices.net
1376.766: DEBUG - - iot_mqtt :: _on_connect :: username = ###/?api-version=2019-10-01, password = SharedAccessSignature sr=####
1376.772: DEBUG - Attempting to establish MQTT connection...
1376.778: INFO - Establishing a SECURE SSL connection to BlitzCityHub.azure-devices.net:8883
1379.336: DEBUG - Sending CONNECT to broker...
1379.342: DEBUG - Fixed Header: bytearray(b'\x10\xf8\x01\x00')
Variable Header: bytearray(b'\x04MQTT\x04\xc2\x00x')
1379.354: DEBUG - Receiving CONNACK packet from broker
1379.823: INFO - - iot_mqtt :: _on_connect :: rc = 0, userdata = None
1379.827: INFO -  - iot_mqtt :: connect :: created mqtt client. connecting..
1379.832: INFO -  - iot_mqtt :: connect :: on_connect must be fired. Connected ? True
1379.840: DEBUG - SUBSCRIBING to topic devices/#####/messages/devicebound/# with QoS 0
Traceback (most recent call last):
  File "code.py", line 41, in <module>
  File "adafruit_azureiot/iothub_device.py", line 312, in connect
  File "adafruit_azureiot/iot_mqtt.py", line 409, in connect
  File "adafruit_azureiot/iot_mqtt.py", line 368, in _subscribe_to_core_topics
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 741, in subscribe
  File "/lib/adafruit_minimqtt/adafruit_minimqtt.py", line 876, in _wait_for_msg
MMQTTException: 
]0;🐍876@/lib/adafruit_minimqtt/adafruit_ MMQTTException | 8.0.0-beta.1-24-g14c9028c1\
Code done running.

Press any key to enter the REPL. Use CTRL-D to reload.```

Description

Hello,

I've been testing out the picow beta and have not be able to successfully connect with Microsoft Azure IoT Central or IoT Hub. It seems to be erroring out during device registration with a MMQTT exception.

Additional information

No response

jepler commented 2 years ago

@BlitzCityDIY I think this may have been the same cause as https://github.com/adafruit/circuitpython/issues/6988 which we now think is fixed by #7048. Can you re-test in a few hours / tomorrow when the fix is in the very latest builds?

BlitzCityDIY commented 2 years ago

hi @jepler ! just tested iot central and iot hub and happy to report they are both working now. thanks!