基于Python与Boto3的AWS IoT Jobs创建及订阅响应技术问询
Hey there! Let's walk through your AWS IoT Jobs setup, refine your existing code, and cover essential guidance and common issue fixes you might run into:
1. Job Creation with Boto3: Refinements & Best Practices
Your existing job creation code is solid, but here are some key tweaks and checks to make it more reliable:
- Use unique Job IDs: Hardcoding
job_idwill cause conflicts if you run the script multiple times. Instead, generate a unique ID (e.g., include a timestamp or random string):import time job_id = f"restart_job_{int(time.time())}" - Avoid raw JSON strings: Convert a Python dictionary to JSON using
json.dumps()—it’s more readable and reduces syntax errors:import json job_document = {"operation": "restart"} response = client.create_job( jobId=job_id, targets=["arn:aws:iot:<your-region>:<your-account-id>:thing/<your-thing-name>"], document=json.dumps(job_document), description="Restart device via Boto3", targetSelection="SNAPSHOT" ) - Validate target ARNs: Ensure your thing ARN follows the exact format
arn:aws:iot:<region>:<account-id>:thing/<thing-name>—a typo here will prevent the job from reaching your device. - Verify job status: After creation, use
client.describe_job(jobId=job_id)to confirm the job is inQUEUEDorIN_PROGRESSstatus.
2. Completing the Subscription Listener
Your variable setup is a great start—let’s build out a full, functional listener using the AWS IoT Device SDK for Python (v2) (it’s more robust than the older v1 SDK). Here’s a complete example:
from awsiot import mqtt_connection_builder import time # Your existing configuration endpoint = "your-account-specific-endpoint-ats.iot.<region>.amazonaws.com" root_ca_path = "./AmazonRootCA1.pem" certificate_path = "./device-cert.pem.crt" private_key_path = "./device-private.pem.key" client_id = "myClientID" thing_name = "your-thing-name" # Topic to subscribe for new job notifications job_notification_topic = f"$aws/things/{thing_name}/jobs/+/notify-next" def handle_job_update(topic, payload, **kwargs): print(f"New job received:") job_details = payload.decode("utf-8") print(job_details) # Add your logic here to execute the restart operation # After execution, send a status update back to AWS IoT Core # Example: publish to "$aws/things/{thing_name}/jobs/{job_id}/update" # Build MQTT connection mqtt_connection = mqtt_connection_builder.mtls_from_path( endpoint=endpoint, cert_filepath=certificate_path, pri_key_filepath=private_key_path, root_ca_filepath=root_ca_path, client_id=client_id, clean_session=False, keep_alive_secs=30 ) # Connect to AWS IoT Core print("Connecting to AWS IoT Core...") connect_future = mqtt_connection.connect() connect_future.result() print("Connected successfully!") # Subscribe to job notifications print(f"Subscribing to topic: {job_notification_topic}") subscribe_future, packet_id = mqtt_connection.subscribe( topic=job_notification_topic, qos=1, callback=handle_job_update ) subscribe_result = subscribe_future.result() print(f"Subscribed with QoS level: {subscribe_result['qos']}") # Keep the listener running try: while True: time.sleep(1) except KeyboardInterrupt: print("\nDisconnecting...") disconnect_future = mqtt_connection.disconnect() disconnect_future.result() print("Disconnected!")
Key listener notes:
- Job topic options: Use
notify-nextto get alerts for new pending jobs. For status updates on in-progress jobs, subscribe to$aws/things/{thing_name}/jobs/+/update. - QoS setting: Use QoS 1 for job messages to guarantee at-least-once delivery.
- Status updates: After executing the job, publish a payload like
{"status": "SUCCEEDED"}to the job’s update topic to notify AWS IoT Core of completion.
3. Common Troubleshooting Scenarios
- Job not reaching the device:
- Confirm your device’s certificate is active and attached to the thing in AWS IoT Core.
- Check your IoT policy allows
iot:Subscribe,iot:Receiveon job topics, andiot:Publishfor status updates. - Ensure the device has internet access and can resolve the IoT endpoint.
- Boto3 creation errors:
ResourceNotFoundException: Your target thing ARN is invalid or doesn’t exist in your region/account.InvalidRequestException: Likely a duplicate job ID or malformed JSON document—use unique IDs and validate your job document.
- No messages in subscription:
- Double-check the topic format (it’s case-sensitive, and the thing name must match exactly).
- Use the AWS IoT Core Test Console to publish a test message to the job topic and confirm your device receives it.
内容的提问来源于stack exchange,提问作者tamil arasan
相关产品推荐
相关产品推荐

