@@ -53,6 +53,13 @@ def __init__(
5353 self .device_resolver = SdkResolver (target = self .target , device_id = device_id )
5454 self .device_sdk = self .device_resolver .get_sdk (SdkType .device_sdk )
5555
56+ @property
57+ def _device_hostname (self ) -> str :
58+ # Device-facing MQTT connect must target the device hostname. On GWv2 hubs
59+ # target['entity'] is the SERVICE hostname, which rejects device credentials
60+ # ("not authorised"); deviceHostName is the correct device-facing endpoint.
61+ return self .target .get ("deviceHostName" ) or self .target ["entity" ]
62+
5663 def device_send_message (
5764 self ,
5865 data : str = "Ping from Az CLI IoT Extension" ,
@@ -76,9 +83,11 @@ def device_send_message(
7683 if properties :
7784 properties = validate_key_value_pairs (properties )
7885
79- device_connection_string = _build_device_or_module_connection_string (device , KeyType .primary .value )
86+ device_connection_string = _build_device_or_module_connection_string (
87+ device , KeyType .primary .value , hostname_override = self ._device_hostname
88+ )
8089 client_mqtt = MQTTProvider (
81- hub_hostname = self .target [ "entity" ] ,
90+ hub_hostname = self ._device_hostname ,
8291 device_conn_string = device_connection_string ,
8392 x509_files = device ["authentication" ].get ("x509_files" ),
8493 device_id = self .device_id ,
@@ -399,10 +408,12 @@ def http_wrap(generator, msg_interval, msg_count):
399408 passphrase = passphrase
400409 )
401410 if protocol_type == ProtocolType .mqtt .name :
402- device_connection_string = _build_device_or_module_connection_string (device , KeyType .primary .value )
411+ device_connection_string = _build_device_or_module_connection_string (
412+ device , KeyType .primary .value , hostname_override = self ._device_hostname
413+ )
403414
404415 client_mqtt = MQTTProvider (
405- hub_hostname = self .target [ "entity" ] ,
416+ hub_hostname = self ._device_hostname ,
406417 device_conn_string = device_connection_string ,
407418 x509_files = device ["authentication" ].get ("x509_files" ),
408419 device_id = self .device_id ,
0 commit comments