如何通过编程从ThingsBoard获取Device Token并发送设备属性
Got it, let's work through this problem step by step. You're right that the /api/tenant/devices endpoint only returns basic device metadata (like ID, name, type) but not the device token needed for the attributes API. Here's how to bridge that gap:
1. Use a Device Credentials API to Fetch the Token
Most IoT platforms with REST API setups provide a dedicated endpoint to retrieve device credentials—including the access token. Typically, this endpoint requires the device ID you already get from the /api/tenant/devices response.
Example Workflow:
- From your existing device list response, extract the device's unique ID:
66c2f980-4568-11e9-a10d-9be803b14c20(from theid.idfield) - Call a credentials endpoint like this (adjust the path if your platform uses a slightly different route):
GET /api/tenant/devices/66c2f980-4568-11e9-a10d-9be803b14c20/credentials - A successful response will usually include the device token in a field like
credentialsValue(the exact key might vary, but it's often labeled clearly):{
"credentialsId": "77d3a091-4569-11e9-b20e-9cf804c25d31",
"deviceId": {
"entityType": "DEVICE",
"id": "66c2f980-4568-11e9-a10d-9be803b14c20"
},
"credentialsType": "ACCESS_TOKEN",
"credentialsValue": "your-unique-device-token-12345"
}
2. Verify Permissions and API Documentation
Make sure your API key has the necessary permissions to access device credentials—you might get a 403 Forbidden error if you don't have the right roles (like "DEVICE_ADMIN" or similar). If you're unsure about the exact credentials endpoint, check your platform's internal API docs (since this is tenant-specific, the docs should be available for your organization).
3. Automate the Process for All Devices
Once you confirm the credentials endpoint works, you can loop through all devices from the /api/tenant/devices response:
- For each device, extract its
id.id - Fetch its token via the credentials API
- Use the token to call
/api/v1/[device token]/attributesand send your target attributes
Quick Notes:
- If the credentials endpoint doesn't exist, double-check if the device token is stored in any other field from the initial device list (you mentioned
additionalInfois null, so that's out, but sometimes platforms hide tokens under fields likesecurityInfo—worth a quick check) - If you're managing the devices directly, you might also retrieve the token from the device's local configuration (but using the API is the most scalable way for tenant-managed devices)
内容的提问来源于stack exchange,提问作者sungyong




