python-eigen-ingenuity-nocli 0.5.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- eigeningenuity/__init__.py +29 -0
- eigeningenuity/assetmodel.py +433 -0
- eigeningenuity/auth.py +178 -0
- eigeningenuity/core/__init__.py +236 -0
- eigeningenuity/elastic.py +171 -0
- eigeningenuity/events.py +88 -0
- eigeningenuity/historian.py +786 -0
- eigeningenuity/historianmulti.py +481 -0
- eigeningenuity/settings.py +87 -0
- eigeningenuity/smartdash.py +103 -0
- eigeningenuity/sql.py +132 -0
- eigeningenuity/util.py +548 -0
- modelbuilder/__init__.py +7 -0
- modelbuilder/src/__init__.py +0 -0
- modelbuilder/src/assetmodelbuilder.py +164 -0
- modelbuilder/src/assetmodelcsvwriter.py +31 -0
- modelbuilder/src/assetmodelutilities.py +51 -0
- modelbuilder/src/configmanager.py +500 -0
- modelbuilder/src/connectors/__init__.py +0 -0
- modelbuilder/src/connectors/boltconnector.py +108 -0
- modelbuilder/src/connectors/dbconnectors.py +40 -0
- modelbuilder/src/connectors/genericconnector.py +30 -0
- modelbuilder/src/connectors/httpsconnector.py +132 -0
- modelbuilder/src/csvcontentsmanager.py +135 -0
- modelbuilder/src/csvwriter.py +305 -0
- modelbuilder/src/fileanalyser.py +91 -0
- modelbuilder/src/filemanager.py +400 -0
- modelbuilder/src/messages.py +61 -0
- modelbuilder/src/processors/__init__.py +0 -0
- modelbuilder/src/processors/cypherfileprocessor.py +73 -0
- modelbuilder/src/processors/labelmanager.py +133 -0
- modelbuilder/src/processors/nodefileprocessor.py +282 -0
- modelbuilder/src/processors/propertymanager.py +129 -0
- modelbuilder/src/processors/relationshipfileprocessor.py +285 -0
- modelbuilder/src/processors/relationshipmanager.py +31 -0
- modelbuilder/src/queries/__init__.py +0 -0
- modelbuilder/src/queries/cypherbuilder.py +323 -0
- modelbuilder/src/queries/query.py +82 -0
- modelbuilder/src/queries/typedefs.py +180 -0
- modelbuilder/src/versionmanager.py +356 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/METADATA +30 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/RECORD +44 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/WHEEL +5 -0
- python_eigen_ingenuity_nocli-0.5.6.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Eigen Ingenuity - Historian
|
|
2
|
+
|
|
3
|
+
This package deals with the Eigen Ingenuity Historian API, mostly by means
|
|
4
|
+
of the JSON Bridge Historian.
|
|
5
|
+
|
|
6
|
+
To get a historian object to work with, use get_historian(xxx) with either
|
|
7
|
+
an instance name (which will be resolved via the the usual methods in
|
|
8
|
+
eigeningenuity.core) or a full URL to a JSON Bridge Historian instance.
|
|
9
|
+
|
|
10
|
+
from eigeningenuity.historian import get_historian
|
|
11
|
+
from time import gmtime, asctime
|
|
12
|
+
|
|
13
|
+
h = get_historian("pi-opc")
|
|
14
|
+
tags = h.listDataTags()
|
|
15
|
+
for tag in tags:
|
|
16
|
+
dp = h.getCurrentDataPoint(tag)
|
|
17
|
+
print(asctime(time.gmtime(dp['timestamp'])), dp['value'])
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import math
|
|
22
|
+
import logging
|
|
23
|
+
import csv
|
|
24
|
+
import requests
|
|
25
|
+
from urllib.parse import quote as urlquote
|
|
26
|
+
from typing import Union
|
|
27
|
+
from datetime import datetime
|
|
28
|
+
|
|
29
|
+
from requests.exceptions import ConnectionError
|
|
30
|
+
from urllib.error import URLError
|
|
31
|
+
from eigeningenuity.core import get_default_server, EigenServer
|
|
32
|
+
from eigeningenuity.util import force_list, time_to_epoch_millis, EigenException, \
|
|
33
|
+
multi_response_to_df, merge_tags_from_response, update_keys, _do_historian_multi_request, format_output
|
|
34
|
+
|
|
35
|
+
from urllib3.exceptions import InsecureRequestWarning
|
|
36
|
+
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class HistorianMulti (object):
|
|
40
|
+
"""A Historian which talks the Eigen Historian Json Bridge protocol.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, baseurl, auth, historian):
|
|
44
|
+
"""This is a constructor. It takes in a URL like http://infra:8080/historian-servlet/jsonbridge/Demo-influxdb"""
|
|
45
|
+
self.baseurl = baseurl
|
|
46
|
+
self.serverurl = baseurl + "multi/"
|
|
47
|
+
self.writeurl = baseurl + "write/points"
|
|
48
|
+
self.listurl = baseurl + "list"
|
|
49
|
+
self.searchurl = baseurl + "search"
|
|
50
|
+
|
|
51
|
+
self.auth = auth
|
|
52
|
+
self.historian = ""
|
|
53
|
+
if historian:
|
|
54
|
+
self.historian = historian + "/"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _testConnection(self):
|
|
58
|
+
try:
|
|
59
|
+
status = requests.get(self.serverurl, verify=False).status_code
|
|
60
|
+
if status != 200:
|
|
61
|
+
raise ConnectionError(
|
|
62
|
+
"Invalid API Response from " + self.serverurl + ". Please check the url is correct and the instance is up.")
|
|
63
|
+
except (URLError, ConnectionError):
|
|
64
|
+
raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
|
|
65
|
+
|
|
66
|
+
def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json"):
|
|
67
|
+
tags = force_list(tags)
|
|
68
|
+
body = {
|
|
69
|
+
"requests": {}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
for tag in tags:
|
|
73
|
+
fulltag = tag
|
|
74
|
+
if "/" not in tag:
|
|
75
|
+
fulltag = self.historian + tag
|
|
76
|
+
request = {
|
|
77
|
+
"type": "CURRENT_POINT",
|
|
78
|
+
"tag": fulltag,
|
|
79
|
+
"details": {}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
body["requests"][tag] = request
|
|
83
|
+
|
|
84
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
85
|
+
|
|
86
|
+
return format_output(output,response,tags)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def getInterpolatedPoints(self, tags: Union[str, list], timestamps: Union[list, int, float, str, datetime],
|
|
91
|
+
output: str = "json"):
|
|
92
|
+
"""
|
|
93
|
+
Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
tags: A datatag (string), or list of datatags
|
|
97
|
+
timestamps: One (string) or more (list) timestamps for which to return a datapoint. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
98
|
+
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
102
|
+
|
|
103
|
+
Raises:
|
|
104
|
+
ValueError: When invalid Output Type is given
|
|
105
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
106
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
107
|
+
RunTimeError/HTTPError: No response from the API
|
|
108
|
+
"""
|
|
109
|
+
body = {
|
|
110
|
+
"requests": {}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
tags = force_list(tags)
|
|
114
|
+
timestamps = force_list(timestamps)
|
|
115
|
+
timestamps = [time_to_epoch_millis(timestamp) for timestamp in timestamps]
|
|
116
|
+
|
|
117
|
+
for tag in tags:
|
|
118
|
+
fulltag = tag
|
|
119
|
+
if "/" not in tag:
|
|
120
|
+
fulltag = self.historian + tag
|
|
121
|
+
for index, timestamp in enumerate(timestamps):
|
|
122
|
+
request = {
|
|
123
|
+
"type": "HISTORICAL_POINT",
|
|
124
|
+
"tag": fulltag,
|
|
125
|
+
"details": {
|
|
126
|
+
"at": timestamp
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
body["requests"][tag + "-" + str(index)] = request
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
134
|
+
items = merge_tags_from_response(response["results"])
|
|
135
|
+
|
|
136
|
+
return format_output(output,items,tags,timestamps)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def getInterpolatedRange(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
140
|
+
end: Union[int, float, str, datetime], count: int = 1000, output: str = "json"):
|
|
141
|
+
"""Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
tags: A datatag, or list of datatags
|
|
145
|
+
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
146
|
+
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
147
|
+
count (Optional): Number of points to return, evenly spaced across the given time range. Defaults to 1000
|
|
148
|
+
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
ValueError: When invalid Output Type is given
|
|
155
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
156
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
157
|
+
RunTimeError/HTTPError: No response from the API
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
body = {
|
|
161
|
+
"requests": {}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
tags = force_list(tags)
|
|
165
|
+
|
|
166
|
+
for tag in tags:
|
|
167
|
+
fulltag = tag
|
|
168
|
+
if "/" not in tag:
|
|
169
|
+
fulltag = self.historian + tag
|
|
170
|
+
request = {
|
|
171
|
+
"type": "INTERPOLATED_POINTS",
|
|
172
|
+
"tag": fulltag,
|
|
173
|
+
"details": {
|
|
174
|
+
"from": time_to_epoch_millis(start),
|
|
175
|
+
"to": time_to_epoch_millis(end),
|
|
176
|
+
"count": count
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
body["requests"][tag] = request
|
|
181
|
+
|
|
182
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
183
|
+
|
|
184
|
+
return format_output(output,response,tags)
|
|
185
|
+
|
|
186
|
+
def getRawDatapoints(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
187
|
+
end: Union[int, float, str, datetime], maxpoints: int = 1000, output: str = "json"):
|
|
188
|
+
"""Return up to a specified number of raw datapoints between a start and end timestamp for one or more datatags
|
|
189
|
+
|
|
190
|
+
Args:
|
|
191
|
+
tags: A datatag, or list of datatags
|
|
192
|
+
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
193
|
+
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
194
|
+
maxPoints (Optional): Max number of points to return. The query will return raw points in sequence from the first raw point in the timespan, until the end, or the point limit is reached. Defaults to 1000
|
|
195
|
+
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
196
|
+
|
|
197
|
+
Returns:
|
|
198
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
199
|
+
|
|
200
|
+
Raises:
|
|
201
|
+
ValueError: When invalid Output Type is given
|
|
202
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
203
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
204
|
+
RunTimeError/HTTPError: No response from the API
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
body = {
|
|
208
|
+
"requests": {}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
tags = force_list(tags)
|
|
212
|
+
|
|
213
|
+
for tag in tags:
|
|
214
|
+
fulltag = tag
|
|
215
|
+
if "/" not in tag:
|
|
216
|
+
fulltag = self.historian + tag
|
|
217
|
+
request = {
|
|
218
|
+
"type": "RAW_POINTS",
|
|
219
|
+
"tag": fulltag,
|
|
220
|
+
"details": {
|
|
221
|
+
"from": time_to_epoch_millis(start),
|
|
222
|
+
"to": time_to_epoch_millis(end),
|
|
223
|
+
"maxPoints": maxpoints
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
body["requests"][tag] = request
|
|
228
|
+
|
|
229
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
230
|
+
|
|
231
|
+
return format_output(output,response,tags)
|
|
232
|
+
|
|
233
|
+
def getClosestRawPoint(self, tags: Union[str, list], timestamps: Union[int, float, str, datetime, list],
|
|
234
|
+
before_or_after:str="AFTER_OR_AT", output: str = "json"):
|
|
235
|
+
"""Return up to a specified number of raw datapoints between a start and end timestamp for one or more datatags
|
|
236
|
+
|
|
237
|
+
Args:
|
|
238
|
+
tags: A datatag, or list of datatags
|
|
239
|
+
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
240
|
+
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
241
|
+
maxPoints (Optional): Max number of points to return. The query will return raw points in sequence from the first raw point in the timespan, until the end, or the point limit is reached. Defaults to 1000
|
|
242
|
+
output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
ValueError: When invalid Output Type is given
|
|
249
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
250
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
251
|
+
RunTimeError/HTTPError: No response from the API
|
|
252
|
+
"""
|
|
253
|
+
before_or_after = before_or_after.upper()
|
|
254
|
+
|
|
255
|
+
if before_or_after.upper() not in ["BEFORE", "BEFORE_OR_AT", "AFTER", "AFTER_OR_AT"]:
|
|
256
|
+
raise EigenException('before_or_after must be one of ["BEFORE", "BEFORE_OR_AT", "AFTER", "AFTER_OR_AT"]')
|
|
257
|
+
|
|
258
|
+
body = {
|
|
259
|
+
"requests": {}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
tags = force_list(tags)
|
|
263
|
+
timestamps = force_list(timestamps)
|
|
264
|
+
timestamps = [time_to_epoch_millis(timestamp) for timestamp in timestamps]
|
|
265
|
+
|
|
266
|
+
for tag in tags:
|
|
267
|
+
fulltag = tag
|
|
268
|
+
if "/" not in tag:
|
|
269
|
+
fulltag = self.historian + tag
|
|
270
|
+
for index, timestamp in enumerate(timestamps):
|
|
271
|
+
request = {
|
|
272
|
+
"type": f"POINT_{before_or_after.upper()}",
|
|
273
|
+
"tag": fulltag,
|
|
274
|
+
"details": {
|
|
275
|
+
"at": time_to_epoch_millis(timestamp),
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
body["requests"][tag + "-" + str(index)] = request
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
283
|
+
items = merge_tags_from_response(response["results"])
|
|
284
|
+
|
|
285
|
+
return format_output(output,items,tags,timestamps)
|
|
286
|
+
|
|
287
|
+
def listDataTags(self, historian:str=None, limit:int=100, match:str=""):
|
|
288
|
+
"""List all tags in a historian, or those matching a wildcard
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
historian: Name of the historian containing tags of interest
|
|
292
|
+
limit: Max number of records to return
|
|
293
|
+
match: A string that tags must match to be returned (Accepts * as wildcard character)
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
A list of tag names
|
|
297
|
+
|
|
298
|
+
Raises:
|
|
299
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
300
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
301
|
+
RunTimeError/HTTPError: No response from the API
|
|
302
|
+
"""
|
|
303
|
+
metadata = self.getMetaData(historian, limit, match)
|
|
304
|
+
|
|
305
|
+
tags = [tag["tagName"] for tag in metadata]
|
|
306
|
+
|
|
307
|
+
return tags
|
|
308
|
+
|
|
309
|
+
def getMetaData(self, historian:str=None, limit:int=100, match:str=""):
|
|
310
|
+
"""Get Metadata for all tags in a historian, or those matching a wildcard
|
|
311
|
+
|
|
312
|
+
Args:
|
|
313
|
+
historian: Name of the historian containing tags of interest
|
|
314
|
+
limit: Max number of records to return
|
|
315
|
+
match: A string that tags must match to be returned (Accepts * as wildcard character)
|
|
316
|
+
|
|
317
|
+
Returns:
|
|
318
|
+
A list of dicts with metadata fields for each tag
|
|
319
|
+
|
|
320
|
+
Raises:
|
|
321
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
322
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
323
|
+
RunTimeError/HTTPError: No response from the API
|
|
324
|
+
"""
|
|
325
|
+
if historian is None:
|
|
326
|
+
historian = self.historian
|
|
327
|
+
|
|
328
|
+
resp = _do_historian_multi_request(self.searchurl + f'?historian={historian}&limit={limit}&search={match}',{},self.auth,get_request=True)
|
|
329
|
+
metadata = resp["tags"]
|
|
330
|
+
|
|
331
|
+
return metadata
|
|
332
|
+
|
|
333
|
+
def listHistorians(self, historian:str=None, limit:int=100, match:str=""):
|
|
334
|
+
"""Get Metadata for all tags in a historian, or those matching a wildcard
|
|
335
|
+
|
|
336
|
+
Args:
|
|
337
|
+
historian: Name of the historian containing tags of interest
|
|
338
|
+
limit: Max number of records to return
|
|
339
|
+
match: A string that tags must match to be returned (Accepts * as wildcard character)
|
|
340
|
+
|
|
341
|
+
Returns:
|
|
342
|
+
A list of dicts with metadata fields for each tag
|
|
343
|
+
|
|
344
|
+
Raises:
|
|
345
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
346
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
347
|
+
RunTimeError/HTTPError: No response from the API
|
|
348
|
+
"""
|
|
349
|
+
if historian is None:
|
|
350
|
+
historian = self.historian
|
|
351
|
+
|
|
352
|
+
resp = _do_historian_multi_request(self.searchurl + f'?historian={historian}&limit={limit}&search={match}',{},self.auth,get_request=True)
|
|
353
|
+
metadata = resp["tags"]
|
|
354
|
+
|
|
355
|
+
return metadata
|
|
356
|
+
|
|
357
|
+
def writePoints(self, tag:str, points: Union[dict, list]):
|
|
358
|
+
"""Write one or more points to a single tag
|
|
359
|
+
|
|
360
|
+
Args:
|
|
361
|
+
tag: A datatag
|
|
362
|
+
points: A dict, or list of dicts of the form {"value": x, "timestamp": y}. Where x is an int/double and y is a python datetime, iso datetime string, or epoch timestamp
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
A dict with keys: success (bool) representing the success of the request. message (str) forwarded from the api.
|
|
366
|
+
|
|
367
|
+
Raises:
|
|
368
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
369
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
370
|
+
RunTimeError/HTTPError: No response from the API
|
|
371
|
+
"""
|
|
372
|
+
points = force_list(points)
|
|
373
|
+
if "/" not in tag:
|
|
374
|
+
tag = self.historian + tag
|
|
375
|
+
|
|
376
|
+
for point in points:
|
|
377
|
+
if "status" not in point.keys():
|
|
378
|
+
point['status'] = "OK"
|
|
379
|
+
point['timestamp'] = time_to_epoch_millis(point['timestamp'])
|
|
380
|
+
|
|
381
|
+
body = {
|
|
382
|
+
"points": {
|
|
383
|
+
tag: points
|
|
384
|
+
},
|
|
385
|
+
"createTags": True
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
389
|
+
|
|
390
|
+
if message == 'All points written!':
|
|
391
|
+
ret = {"success": True, "message": message}
|
|
392
|
+
else:
|
|
393
|
+
ret = {"success": False, "message": message}
|
|
394
|
+
|
|
395
|
+
return ret
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def writePointsBatch(self, data:Union[dict,list]):
|
|
399
|
+
"""Write one or more points to multiple tags
|
|
400
|
+
|
|
401
|
+
Args:
|
|
402
|
+
payloads: A dict (or list of dicts) of the form {tag1: [{"value": x, "timestamp": y}, ...], tag2: [...], ...}
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
None
|
|
406
|
+
|
|
407
|
+
Raises:
|
|
408
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
409
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
410
|
+
RunTimeError/HTTPError: No response from the API
|
|
411
|
+
"""
|
|
412
|
+
data = force_list(data)
|
|
413
|
+
|
|
414
|
+
payload = {}
|
|
415
|
+
tags = []
|
|
416
|
+
|
|
417
|
+
for item in data:
|
|
418
|
+
if set(item.keys()).intersection(set(tags)):
|
|
419
|
+
for tag in set(item.keys()).intersection(set(tags)):
|
|
420
|
+
payload[tag] += item[tag]
|
|
421
|
+
item.pop(tag)
|
|
422
|
+
payload = payload | item
|
|
423
|
+
tags += item.keys()
|
|
424
|
+
|
|
425
|
+
for key in payload.keys():
|
|
426
|
+
for datapoint in payload[key]:
|
|
427
|
+
if "status" not in datapoint.keys():
|
|
428
|
+
datapoint['status'] = "OK"
|
|
429
|
+
datapoint['timestamp'] = time_to_epoch_millis(datapoint['timestamp'])
|
|
430
|
+
|
|
431
|
+
payload = update_keys(payload, self.historian)
|
|
432
|
+
|
|
433
|
+
body = {
|
|
434
|
+
"points": payload,
|
|
435
|
+
"createTags": True
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
439
|
+
|
|
440
|
+
if message == 'All points written!':
|
|
441
|
+
ret = {"success": True, "message": message}
|
|
442
|
+
else:
|
|
443
|
+
ret = {"success": False, "message": message}
|
|
444
|
+
|
|
445
|
+
return ret
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def createPoint(value:Union[int,float],timestamp:Union[int,str,datetime],status:str="OK"):
|
|
449
|
+
"""Quickly Create a dict of the format required to push data to historians
|
|
450
|
+
|
|
451
|
+
Args:
|
|
452
|
+
value: The value to be pushed
|
|
453
|
+
timestamp: The timestamp to assign the value to. Accepts formats of epoch milliseconds, python datetimes, and iso format datetime strings
|
|
454
|
+
status: (Optional) Indicates the quality of the data, accepts "OK" or "BAD". Defaults to "OK"
|
|
455
|
+
|
|
456
|
+
Returns:
|
|
457
|
+
A structured dict for use in the WriteToTag method
|
|
458
|
+
"""
|
|
459
|
+
if status not in ["OK","BAD"]:
|
|
460
|
+
raise EigenException("Bad Status Parameter, must be 'OK' or 'BAD'")
|
|
461
|
+
return {"value": value, "timestamp": timestamp, "status": status}
|
|
462
|
+
|
|
463
|
+
def get_historian_multi(eigenserver: EigenServer = None, default_historian = None) -> HistorianMulti:
|
|
464
|
+
"""Instantiate a historian object for the given instance.
|
|
465
|
+
|
|
466
|
+
Args:
|
|
467
|
+
eigenserver (Optional): An EigenServer Object linked to the ingenuity url containing the historian. Can be omitted if environmental variable "EIGENSERVER" exists and is equal to the Ingenuity base url
|
|
468
|
+
default_historian (Optional): The name of the historian to be used if none is passed with a tag. Defaults to None, and will not hanbdle tags without historians.
|
|
469
|
+
|
|
470
|
+
Returns:
|
|
471
|
+
An Object that can be used to query historian data.
|
|
472
|
+
|
|
473
|
+
"""
|
|
474
|
+
if eigenserver is None:
|
|
475
|
+
eigenserver = get_default_server()
|
|
476
|
+
elif type(eigenserver) == str:
|
|
477
|
+
eigenserver = EigenServer(eigenserver)
|
|
478
|
+
|
|
479
|
+
return HistorianMulti(eigenserver.getEigenServerUrl() + "historian" + "/", eigenserver.auth, default_historian)
|
|
480
|
+
|
|
481
|
+
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from getpass import getuser
|
|
3
|
+
|
|
4
|
+
_token_cache_enabled_ = True
|
|
5
|
+
_azure_auth_enabled_ = True
|
|
6
|
+
_azure_tenant_id_ = os.getenv("EIGEN_INGENUITY_TENANT_ID", "74efa022-e6d6-42ad-bc15-edc76c525bde")
|
|
7
|
+
_azure_client_id_ = os.getenv("EIGEN_INGENUITY_CLIENT_ID", "c2b9aa13-e178-4dde-bc2c-b6cc4c8391d2")
|
|
8
|
+
_api_token_value_ = os.getenv("EIGEN_INGENUITY_API_TOKEN", False)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def clear_auth_token_cache():
|
|
12
|
+
"""
|
|
13
|
+
Delete any cached tokens for the current signed in user
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
None
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
None
|
|
20
|
+
"""
|
|
21
|
+
if os.path.exists(os.path.dirname(__file__) + f'/.azure/{getuser()}_cache.bin'):
|
|
22
|
+
os.remove(os.path.dirname(__file__) + f'/.azure/{getuser()}_cache.bin')
|
|
23
|
+
|
|
24
|
+
def disable_auth_token_cache(state=True):
|
|
25
|
+
"""
|
|
26
|
+
Prevent the program from creating/using/updating the token cache when authenticating with Azure. Note that this will not delete any existing tokens, for this see clear_auth_token_cache()
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
None
|
|
30
|
+
|
|
31
|
+
Returns:
|
|
32
|
+
None
|
|
33
|
+
"""
|
|
34
|
+
global _token_cache_enabled_
|
|
35
|
+
_token_cache_enabled_ = not state
|
|
36
|
+
|
|
37
|
+
def disable_azure_auth(state=True):
|
|
38
|
+
"""
|
|
39
|
+
Skip all azure authentication steps, note that this will cause an error if querying a protected resource (Disabling this is not necessarily necessary, it will not cause errors).
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
None
|
|
43
|
+
|
|
44
|
+
Returns:
|
|
45
|
+
None
|
|
46
|
+
"""
|
|
47
|
+
global _azure_auth_enabled_
|
|
48
|
+
_azure_auth_enabled_ = not state
|
|
49
|
+
|
|
50
|
+
def set_azure_tenant_id(id):
|
|
51
|
+
"""
|
|
52
|
+
Set the ID of the Azure tenant of the eigenserver. This value is required for Azure authentication, but the use of the TENANTID environmental variable can be used as an alternative way of setting it.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
id: The ID of your tenant in Azure. This can be found at portal.azure.com.(Default points to our DEMO Instance)
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
None
|
|
59
|
+
"""
|
|
60
|
+
global _azure_tenant_id_
|
|
61
|
+
_azure_tenant_id_ = id
|
|
62
|
+
|
|
63
|
+
def set_azure_client_id(id):
|
|
64
|
+
"""
|
|
65
|
+
Set the Client ID of the App registration for the eigenserver. This value required for Azure authentication, but the use of the EIGEN_INGENUITY_TENANT_ID environmental variable can be used as an alternative way of setting it.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
id: The ID of your tenant in Azure. This can be found at portal.azure.com. (Default points to our DEMO Instance)
|
|
69
|
+
|
|
70
|
+
Returns:
|
|
71
|
+
None
|
|
72
|
+
"""
|
|
73
|
+
global _azure_client_id_
|
|
74
|
+
_azure_client_id_ = id
|
|
75
|
+
|
|
76
|
+
def set_api_token(token):
|
|
77
|
+
"""
|
|
78
|
+
Set the API token for the eigenserver. This value is required to access our secured endpoints, but the use of the EIGEN_INGENUITY_API_TOKEN environmental variable can be used as an alternative way of setting it.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
token: The value of your api token. This can be found at {TBA}.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
None
|
|
85
|
+
"""
|
|
86
|
+
global _api_token_value_
|
|
87
|
+
_api_token_value_ = token
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Eigen Ingenuity - Smart Dash
|
|
2
|
+
|
|
3
|
+
This package deals with the Eigen Ingenuity Smart Dash API.
|
|
4
|
+
|
|
5
|
+
To get a smart object to work with, use get_historian(xxx) with either
|
|
6
|
+
an instance name (which will be resolved via the the usual methods in
|
|
7
|
+
eigeningenuity.core) or a full URL to a JSON Bridge Historian instance.
|
|
8
|
+
|
|
9
|
+
from eigeningenuity.smartdash import get_smartdash
|
|
10
|
+
|
|
11
|
+
sd = get_smartdash()
|
|
12
|
+
sd.addItem("foobar", "HistorianTagTotaliser", "pi-af/testsim00001", "year")
|
|
13
|
+
vals = sd.getValues()
|
|
14
|
+
|
|
15
|
+
print vals['foobar']
|
|
16
|
+
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import (absolute_import, division, print_function, unicode_literals)
|
|
20
|
+
|
|
21
|
+
import requests
|
|
22
|
+
|
|
23
|
+
from eigeningenuity.core import get_default_server, EigenServer
|
|
24
|
+
from eigeningenuity.util import _do_eigen_json_request, force_list, time_to_epoch_millis, is_list, get_datetime, number_to_string, EigenException, get_timestamp_string, pythonTimeToFloatingSecs, serverTimeToPythonTime, pythonTimeToServerTime, get_time_tuple
|
|
25
|
+
from urllib.parse import quote_plus as urlquote_plus
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class SmartDashSet (object):
|
|
30
|
+
def __init__(self, baseurl, auth):
|
|
31
|
+
self.__items = {}
|
|
32
|
+
self.__key = None
|
|
33
|
+
self.__baseurl = baseurl
|
|
34
|
+
self.__itemcount = 0
|
|
35
|
+
self.auth = auth
|
|
36
|
+
|
|
37
|
+
def addAutoItem(self, itype, *args):
|
|
38
|
+
self.__itemcount += 1
|
|
39
|
+
id = "item%04d" % self.__itemcount
|
|
40
|
+
self.addItem(id, itype, *args)
|
|
41
|
+
|
|
42
|
+
return id
|
|
43
|
+
|
|
44
|
+
def clear(self):
|
|
45
|
+
self.__key = None
|
|
46
|
+
self.__items = {}
|
|
47
|
+
|
|
48
|
+
def removeItem(self, kname):
|
|
49
|
+
self.__key = None
|
|
50
|
+
del self.__items[kname]
|
|
51
|
+
|
|
52
|
+
def addItem(self, kname, itype, *args):
|
|
53
|
+
self.__key = None
|
|
54
|
+
encodedargs = []
|
|
55
|
+
for i in ((itype,) + args):
|
|
56
|
+
encodedargs.append(urlquote_plus(str(i)))
|
|
57
|
+
|
|
58
|
+
itemSpec = ":".join(encodedargs)
|
|
59
|
+
self.__items[urlquote_plus(kname)] = itemSpec
|
|
60
|
+
|
|
61
|
+
def getKey(self):
|
|
62
|
+
if self.__key is None:
|
|
63
|
+
self.getValues()
|
|
64
|
+
return self.__key
|
|
65
|
+
|
|
66
|
+
def getValues(self):
|
|
67
|
+
res = None
|
|
68
|
+
|
|
69
|
+
if self.__key is not None:
|
|
70
|
+
try:
|
|
71
|
+
res = _do_eigen_json_request(self.__baseurl, self.auth, key = self.__key)
|
|
72
|
+
except EigenException:
|
|
73
|
+
res = None
|
|
74
|
+
|
|
75
|
+
if res is None:
|
|
76
|
+
items = []
|
|
77
|
+
for k,spec in self.__items.items():
|
|
78
|
+
items.append(k + "=" + spec)
|
|
79
|
+
|
|
80
|
+
res = _do_eigen_json_request(self.__baseurl, self.auth, item = items)
|
|
81
|
+
|
|
82
|
+
self.__key = res['key']
|
|
83
|
+
return res['data']
|
|
84
|
+
|
|
85
|
+
def get_smartdash(eigenserver = None):
|
|
86
|
+
if eigenserver is None:
|
|
87
|
+
eigenserver = get_default_server()
|
|
88
|
+
elif type(eigenserver) == str:
|
|
89
|
+
eigenserver = EigenServer(eigenserver)
|
|
90
|
+
|
|
91
|
+
url = eigenserver.getEigenServerUrl() + "smartdash-servlet"
|
|
92
|
+
|
|
93
|
+
x = requests.get(url, verify=False).status_code
|
|
94
|
+
|
|
95
|
+
if x != 200:
|
|
96
|
+
url = eigenserver.getAppUrl("dashboards-applet")
|
|
97
|
+
|
|
98
|
+
if url is None:
|
|
99
|
+
raise EigenException("No smartdash found")
|
|
100
|
+
|
|
101
|
+
return SmartDashSet(url + "/smartdash", eigenserver.auth)
|
|
102
|
+
|
|
103
|
+
|