监听消息。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
Python
global minimum_backoff_time
jwt_iat = datetime.datetime.now(tz=datetime.timezone.utc)
jwt_exp_mins = jwt_expires_minutes
# Use gateway to connect to server
client = get_client(
project_id,
cloud_region,
registry_id,
gateway_id,
private_key_file,
algorithm,
ca_certs,
mqtt_bridge_hostname,
mqtt_bridge_port,
)
attach_device(client, device_id, "")
print("Waiting for device to attach.")
time.sleep(5)
# The topic devices receive configuration updates on.
device_config_topic = "/devices/{}/config".format(device_id)
client.subscribe(device_config_topic, qos=1)
# The topic gateways receive configuration updates on.
gateway_config_topic = "/devices/{}/config".format(gateway_id)
client.subscribe(gateway_config_topic, qos=1)
# The topic gateways receive error updates on. QoS must be 0.
error_topic = "/devices/{}/errors".format(gateway_id)
client.subscribe(error_topic, qos=0)
# Wait for about a minute for config messages.
for i in range(1, duration):
client.loop()
if cb is not None:
cb(client)
if should_backoff:
# If backoff time is too large, give up.
if minimum_backoff_time > MAXIMUM_BACKOFF_TIME:
print("Exceeded maximum backoff time. Giving up.")
break
delay = minimum_backoff_time + random.randint(0, 1000) / 1000.0
time.sleep(delay)
minimum_backoff_time *= 2
client.connect(mqtt_bridge_hostname, mqtt_bridge_port)
seconds_since_issue = (datetime.datetime.now(tz=datetime.timezone.utc) - jwt_iat).seconds
if seconds_since_issue > 60 * jwt_exp_mins:
print("Refreshing token after {}s".format(seconds_since_issue))
jwt_iat = datetime.datetime.now(tz=datetime.timezone.utc)
client.loop()
client.disconnect()
client = get_client(
project_id,
cloud_region,
registry_id,
gateway_id,
private_key_file,
algorithm,
ca_certs,
mqtt_bridge_hostname,
mqtt_bridge_port,
)
time.sleep(1)
detach_device(client, device_id)
print("Finished.")
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。