I’m trying to get the last telemetry of one device by grpc, but I can’t get it. I verified that the dev_eui is the correct and the time too.
I have the following code:
import os
import sys
import csv
import grpc
from chirpstack_api import api
from datetime import datetime
from google.protobuf.timestamp_pb2 import Timestamp
# Configuration.
# This must point to the API interface.
server = "XX"
# This must point to the API interface.
tenant_id = "XX"
# The API token (retrieved using the web-interface).
api_token = "XXX"
start_datetime = datetime(2024, 4, 1, 0, 0, 0) # 1 de abril de 2024, 00:00:00 UTC
end_datetime = datetime(2024, 4, 29, 0, 0, 0) # 30 de abril de 2024, 23:59:59 UTC
start_timestamp = start_datetime.timestamp()
end_timestamp = end_datetime.timestamp()
if __name__ == "__main__":
# Connect without using TLS.
channel = grpc.secure_channel(server, grpc.ssl_channel_credentials())
# Device-queue API client.
client = api.DeviceServiceStub(channel)
# Define the API key meta-data.
auth_token = [("authorization", "Bearer %s" % api_token)]
request = api.GetDeviceMetricsRequest(dev_eui="78d800b524002088", start=Timestamp(seconds=int(start_timestamp)),end=Timestamp(seconds=int(end_timestamp)))
try:
devices = client.GetMetrics(request, metadata=auth_token)
for device in devices.result:
print(device)
except grpc.RpcError as e:
print(f"Error: {e}")
except Exception as ex:
print(f"Unexpected error: {ex}")
Although it’s important to know by default Chirpstack doesn’t store device metrics for long and the preferred way to pull sensor data is by using an integration.
I fixed my code with your response and now I don’t have an error but the response is empty and the device exists and it has metrics.
I only want the last metrics.
My code now is:
try:
devices = client.GetMetrics(request, metadata=auth_token)
for device in devices.metrics:
print(device)
except grpc.RpcError as e:
print(f"Error: {e}")
except Exception as ex:
print(f"Unexpected error: {ex}")
And the console output is empty, do you know the error is the Timestamp format?
Are you sure the timeframe you are setting is recent and has data? As chirpstack promptly deletes data and its possible you are trying to pull data thats not there anymore. For reference here is my getMetrics() call that works fine:
def getMetrics(client,token,dev_eui,start,end):
print("Retrieving metrics from device with EUI: " + dev_eui)
# Define the API key meta-data.
auth_token = [("authorization", "Bearer %s" % token)]
try:
# Construct request.
req = api.GetDeviceMetricsRequest()
req.dev_eui = dev_eui
req.start.FromDatetime(start)
req.end.FromDatetime(end)
resp = client.GetMetrics(req, metadata=auth_token)
print(resp.metrics)
return resp
except grpc.RpcError as e:
print('error:',type(e))
print('Ensure server URL is correct, API token is valid, devEUI is correct,