-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice-reader.py
More file actions
71 lines (60 loc) · 1.89 KB
/
Copy pathdevice-reader.py
File metadata and controls
71 lines (60 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Datacake Python GraphQL API example on how to read devices from workspace
"""
import requests
# Replace with your API token
headers = {"Authorization": "Token YOURTOKENHERE"}
# GraphQL Query helper function
def run_query(query):
request = requests.post('https://api.datacake.co/graphql/', json={'query': query}, headers=headers)
if request.status_code == 200:
return request.json()
else:
raise Exception("Query failed to run by returning code of {}. {}".format(request.status_code, query))
# Helper class to convert dictionary parsed from JSON to Python Object
class DictObj:
def __init__(self, in_dict:dict):
for key, val in in_dict.items():
if isinstance(val, (list, tuple)):
setattr(self, key, [DictObj(x) if isinstance(x, dict) else x for x in val])
else:
setattr(self, key, DictObj(val) if isinstance(val, dict) else val)
# Actual Datacake Query
query = """
query {
allDevices(inWorkspace:"YOURWORKSPACEUUIDHERE") {
online
verboseName
id
serialNumber
roleFields {
field {
fieldName
verboseFieldName
}
value
chartData
role
}
}
}
"""
# Run query
result = run_query(query) # Execute the query
my_obj = DictObj(result)
print(my_obj)
averageLevel = 0
for device in my_obj.data.allDevices:
print("")
print(f"Device: {device.verboseName}, Serial: {device.serialNumber}")
for field in device.roleFields:
print("Field: " +str(field.field.fieldName) + ", Value: " + str(field.value) + ", Chart: " + str(field.chartData))
if field.role == "PRIMARY":
averageLevel = averageLevel + float(field.value)
print("")
print("")
print("Number of Sensors Total: " + str(len(my_obj.data.allDevices)))
print("")
averageLevel = averageLevel / len(my_obj.data.allDevices)
print("Average Level: " + str(averageLevel))
print("")