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.
Files changed (44) hide show
  1. eigeningenuity/__init__.py +29 -0
  2. eigeningenuity/assetmodel.py +433 -0
  3. eigeningenuity/auth.py +178 -0
  4. eigeningenuity/core/__init__.py +236 -0
  5. eigeningenuity/elastic.py +171 -0
  6. eigeningenuity/events.py +88 -0
  7. eigeningenuity/historian.py +786 -0
  8. eigeningenuity/historianmulti.py +481 -0
  9. eigeningenuity/settings.py +87 -0
  10. eigeningenuity/smartdash.py +103 -0
  11. eigeningenuity/sql.py +132 -0
  12. eigeningenuity/util.py +548 -0
  13. modelbuilder/__init__.py +7 -0
  14. modelbuilder/src/__init__.py +0 -0
  15. modelbuilder/src/assetmodelbuilder.py +164 -0
  16. modelbuilder/src/assetmodelcsvwriter.py +31 -0
  17. modelbuilder/src/assetmodelutilities.py +51 -0
  18. modelbuilder/src/configmanager.py +500 -0
  19. modelbuilder/src/connectors/__init__.py +0 -0
  20. modelbuilder/src/connectors/boltconnector.py +108 -0
  21. modelbuilder/src/connectors/dbconnectors.py +40 -0
  22. modelbuilder/src/connectors/genericconnector.py +30 -0
  23. modelbuilder/src/connectors/httpsconnector.py +132 -0
  24. modelbuilder/src/csvcontentsmanager.py +135 -0
  25. modelbuilder/src/csvwriter.py +305 -0
  26. modelbuilder/src/fileanalyser.py +91 -0
  27. modelbuilder/src/filemanager.py +400 -0
  28. modelbuilder/src/messages.py +61 -0
  29. modelbuilder/src/processors/__init__.py +0 -0
  30. modelbuilder/src/processors/cypherfileprocessor.py +73 -0
  31. modelbuilder/src/processors/labelmanager.py +133 -0
  32. modelbuilder/src/processors/nodefileprocessor.py +282 -0
  33. modelbuilder/src/processors/propertymanager.py +129 -0
  34. modelbuilder/src/processors/relationshipfileprocessor.py +285 -0
  35. modelbuilder/src/processors/relationshipmanager.py +31 -0
  36. modelbuilder/src/queries/__init__.py +0 -0
  37. modelbuilder/src/queries/cypherbuilder.py +323 -0
  38. modelbuilder/src/queries/query.py +82 -0
  39. modelbuilder/src/queries/typedefs.py +180 -0
  40. modelbuilder/src/versionmanager.py +356 -0
  41. python_eigen_ingenuity_nocli-0.5.6.dist-info/METADATA +30 -0
  42. python_eigen_ingenuity_nocli-0.5.6.dist-info/RECORD +44 -0
  43. python_eigen_ingenuity_nocli-0.5.6.dist-info/WHEEL +5 -0
  44. python_eigen_ingenuity_nocli-0.5.6.dist-info/top_level.txt +2 -0
@@ -0,0 +1,786 @@
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 _do_eigen_json_request, force_list, time_to_epoch_millis, is_list, \
33
+ get_datetime, number_to_string, EigenException, get_timestamp_string, pythonTimeToFloatingSecs, \
34
+ serverTimeToPythonTime, pythonTimeToServerTime, get_time_tuple, parse_duration, jsonToDf, \
35
+ aggToDf, divide_chunks, flattenDict, csvWriter
36
+
37
+ from urllib3.exceptions import InsecureRequestWarning
38
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
39
+
40
+
41
+ class JsonBridgeHistorian (object):
42
+ """A Historian which talks the Eigen Historian Json Bridge protocol.
43
+ """
44
+
45
+ def __init__(self, serverurl, auth):
46
+ """This is a constructor. It takes in a URL like http://infra:8080/historian-servlet/jsonbridge/Demo-influxdb"""
47
+ self.serverurl = serverurl
48
+ self.historian = serverurl.split("/")[-1]
49
+ self.baseurl = serverurl.rsplit("/",1)[0]
50
+ self.auth = auth
51
+
52
+ def _testConnection(self):
53
+ try:
54
+ status = requests.get(self.serverurl, verify=False).status_code
55
+ if status != 200:
56
+ raise ConnectionError(
57
+ "Invalid API Response from " + self.serverurl + ". Please check the url is correct and the instance is up.")
58
+ except (URLError, ConnectionError):
59
+ raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
60
+
61
+ def listDataTags(self, wildcard):
62
+ """Return a list of all tags that match a given wildcard, or all tags in the historian
63
+
64
+ Args:
65
+ wildcard (Optional): Return all tags that contain this value in their name. Defaults to All Tags in historian.
66
+
67
+ Returns:
68
+ A list of all tags containing wildcard
69
+
70
+ Raises:
71
+ ValueError: When invalid Output Type is given
72
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
73
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
74
+ RunTimeError/HTTPError: No response from the API
75
+ """
76
+ # self._testConnection()
77
+ args = {}
78
+ if wildcard is not None:
79
+ args['match'] = force_list(wildcard)
80
+
81
+ return self._doJsonRequest("list", args)
82
+
83
+ def getMetaData(self, tags: Union[str, list], output: str = "json", filepath:str=None, multi_csv:bool=False):
84
+ """
85
+ Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
86
+
87
+ Args:
88
+ tags: A datatag, or list of datatags
89
+ 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".
90
+
91
+ Returns:
92
+ Units, unit multiplier, and description for each datatag, the format is dependent on the output parameter
93
+
94
+ Raises:
95
+ ValueError: When invalid Output Type is given
96
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
97
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
98
+ RunTimeError/HTTPError: No response from the API
99
+ """
100
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
101
+ if output not in validOutputTypes:
102
+ raise ValueError("output must be one of %r." % validOutputTypes)
103
+ response = {}
104
+
105
+ for tag in force_list(tags):
106
+ args = {}
107
+ args['tag'] = tag
108
+ response[tag] = (self._doJsonRequest("getmeta", args))
109
+
110
+
111
+ if output == "raw":
112
+ return response
113
+ elif output == "json":
114
+ if len(force_list(tags)) == 1:
115
+ return response[tags]
116
+ else:
117
+ return response
118
+ elif output == "string":
119
+ return json.dumps(response)
120
+ elif output == "df":
121
+ return jsonToDf(response, True)
122
+ elif output == "csv":
123
+ return csvWriter(response,self.historian,filepath,multi_csv,"GetMetaData")
124
+ return None
125
+
126
+
127
+ def getCurrentDataPoints(self, tags: Union[str, list], output: str = "json", filepath:str=None, multi_csv:bool=False):
128
+ """
129
+ Return most recent raw value for one or more datatags
130
+
131
+ Args:
132
+ tags: A datatag, or list of datatags
133
+ 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".
134
+
135
+ Returns:
136
+ A timestamps, values and statuses for each tag, the format is dependent on the output parameter
137
+
138
+ Raises:
139
+ ValueError: When invalid Output Type is given
140
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
141
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
142
+ RunTimeError/HTTPError: No response from the API
143
+ """
144
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
145
+ if output not in validOutputTypes:
146
+ raise ValueError("output must be one of %r." % validOutputTypes)
147
+ args = {}
148
+ args['tag'] = force_list(tags)
149
+ response = self._doJsonRequest("getmulticurrent", args)
150
+ items = response["items"]
151
+
152
+ if response['unknown'] != []:
153
+ if items == {}:
154
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
155
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
156
+
157
+ if output == "raw":
158
+ return response
159
+ elif output == "json":
160
+ if len(force_list(tags)) == 1:
161
+ return items[tags]
162
+ else:
163
+ return items
164
+ elif output == "string":
165
+ return json.dumps(items)
166
+ elif output == "df":
167
+ return jsonToDf(items)
168
+ elif output == "csv":
169
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetCurrent")
170
+ return None
171
+
172
+
173
+ def getInterpolatedPoints(self, tags: Union[str, list], timestamps: Union[list, int, float, str, datetime],
174
+ output: str = "json", filepath:str=None, multi_csv:bool=False):
175
+ """
176
+ Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
177
+
178
+ Args:
179
+ tags: A datatag, or list of datatags
180
+ timestamps: One or more timestamps for which to return a datapoint. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
181
+ 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".
182
+
183
+ Returns:
184
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
185
+
186
+ Raises:
187
+ ValueError: When invalid Output Type is given
188
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
189
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
190
+ RunTimeError/HTTPError: No response from the API
191
+ """
192
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
193
+ if output not in validOutputTypes:
194
+ raise ValueError("output must be one of %r." % validOutputTypes)
195
+ args = {}
196
+ args['tag'] = force_list(tags)
197
+ args['timestamp'] = force_list(timestamps)
198
+ response = self._doJsonRequest("getmulti", args)
199
+ items = response['items']
200
+
201
+ if response['unknown'] != []:
202
+ if items == {}:
203
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
204
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
205
+
206
+ if output == "raw":
207
+ return response
208
+ elif output == "json":
209
+ if len(force_list(tags)) == 1:
210
+ return items[tags]
211
+ else:
212
+ return items
213
+ elif output == "string":
214
+ return json.dumps(items)
215
+ elif output == "df":
216
+ return jsonToDf(items)
217
+ elif output == "csv":
218
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetInterpolatedPoints")
219
+ return None
220
+
221
+
222
+ def getRawDataPoints(self, tags: Union[str, list], start: Union[int, float, str, datetime],
223
+ end: Union[int, float, str, datetime], maxpoints: int = 1000, output: str = "json", filepath:str=None, multi_csv:bool=False) -> object:
224
+ """Return the first [maxpoints] raw datapoints between a start and end timestamp for one or more datatags, if maxpoints is greater than the total number of raw points, return all raw points within the time window
225
+
226
+ Args:
227
+ tags: A datatag, or list of datatags
228
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
229
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
230
+ maxpoints (Optional): The maximum number of points to return. Defaults to 1000
231
+ 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".
232
+
233
+ Returns:
234
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
235
+
236
+ Raises:
237
+ ValueError: When invalid Output Type is given
238
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
239
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
240
+ RunTimeError/HTTPError: No response from the API
241
+ """
242
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
243
+ if output not in validOutputTypes:
244
+ raise ValueError("output must be one of %r." % validOutputTypes)
245
+ args = {}
246
+ args['tag'] = force_list(tags)
247
+ args['start'] = time_to_epoch_millis(start)
248
+ args['end'] = time_to_epoch_millis(end)
249
+ args['maxpoints'] = maxpoints
250
+ response = self._doJsonRequest("getraw", args)
251
+ items = response["items"]
252
+
253
+ if response['unknown'] != []:
254
+ if items == {}:
255
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
256
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
257
+
258
+ if output == "raw":
259
+ return response
260
+ elif output == "json":
261
+ if len(force_list(tags)) == 1:
262
+ return items[tags]
263
+ else:
264
+ return items
265
+ elif output == "string":
266
+ return json.dumps(items)
267
+ elif output == "df":
268
+ return jsonToDf(items)
269
+ elif output == "csv":
270
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetRaw")
271
+ return None
272
+
273
+
274
+
275
+ def getInterpolatedRange(self, tags: Union[str, list], start: Union[int, float, str, datetime],
276
+ end: Union[int, float, str, datetime], count: int = 1000, output: str = "json", filepath:str=None, multi_csv:bool=False):
277
+ """Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
278
+
279
+ Args:
280
+ tags: A datatag, or list of datatags
281
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
282
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
283
+ count (Optional): Number of points to return, evenly spaced across the given time range. Defaults to 1000
284
+ 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".
285
+
286
+ Returns:
287
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
288
+
289
+ Raises:
290
+ ValueError: When invalid Output Type is given
291
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
292
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
293
+ RunTimeError/HTTPError: No response from the API
294
+ """
295
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
296
+ if output not in validOutputTypes:
297
+ raise ValueError("output must be one of %r." % validOutputTypes)
298
+ args = {}
299
+ args['tag'] = force_list(tags)
300
+ args['start'] = time_to_epoch_millis(start)
301
+ args['end'] = time_to_epoch_millis(end)
302
+ args['count'] = count
303
+ response = self._doJsonRequest("getrange", args)
304
+ items = response["items"]
305
+
306
+ if response['unknown'] != []:
307
+ if items == {}:
308
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
309
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
310
+
311
+ if output == "raw":
312
+ return response
313
+ elif output == "json":
314
+ if len(force_list(tags)) == 1:
315
+ return items[tags]
316
+ else:
317
+ return items
318
+ elif output == "string":
319
+ return json.dumps(items)
320
+ elif output == "df":
321
+ return jsonToDf(items)
322
+ elif output == "csv":
323
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetInterpolatedRange")
324
+ return None
325
+
326
+ def getAggregates(self, tags: Union[str, list], start: Union[int, float, str, datetime],
327
+ end: Union[int, float, str, datetime], fields: Union[str, list] = None, count: int = 1,
328
+ output: str = "json", filepath:str=None, multi_csv:bool=False):
329
+ """
330
+ Return specified aggregates of tags over a given time window, optionally divided into equal parts
331
+
332
+ Args:
333
+ tags: A datatag, or list of datatags
334
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
335
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
336
+ fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
337
+ count (Optional): Number of intervals to split the time window into, returning aggregates over each interval. Defaults to 1
338
+ 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".
339
+
340
+ Returns:
341
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
342
+
343
+ Raises:
344
+ ValueError: When invalid Output Type is given
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
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
350
+ if output not in validOutputTypes:
351
+ raise ValueError("output must be one of %r." % validOutputTypes)
352
+ args = {}
353
+ args['tag'] = force_list(tags)
354
+ args['start'] = time_to_epoch_millis(start)
355
+ args['end'] = time_to_epoch_millis(end)
356
+ args['count'] = count
357
+ args['aggfields'] = fields
358
+
359
+ response = self._doJsonRequest("getagg", args)
360
+
361
+ keys = set(response.keys())
362
+ missing = [x for x in args['tag'] if x not in keys]
363
+
364
+ if missing != []:
365
+ if response == {}:
366
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
367
+ logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
368
+
369
+ if output == "raw":
370
+ return response
371
+ elif output == "json":
372
+ if len(force_list(tags)) == 1:
373
+ return response[tags]
374
+ else:
375
+ return response
376
+ elif output == "string":
377
+ return json.dumps(response)
378
+ elif output == "df":
379
+ return aggToDf(response,fields)
380
+ elif output == "csv":
381
+ order = ["tag","start","end","min","max","avg","var","stddev","count","numgood","numbad"]
382
+ return csvWriter(response,self.historian,filepath,multi_csv,"GetAggregates",order,True)
383
+ return None
384
+
385
+
386
+ def getAggregateIntervals(self, tags, start: Union[int, float, str, datetime],
387
+ end: Union[int, float, str, datetime], window: str = None,
388
+ fields: Union[str, list] = None, output: str = "json", filepath:str=None, multi_csv:bool=False):
389
+ """
390
+ Return specified aggregates of tags over a given time window, optionally divided into equal parts
391
+
392
+ Args:
393
+ tags: A datatag, or list of datatags
394
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
395
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
396
+ window (Optional): Sub-interval of time to divide the timeframe into as a multiple of seconds,minutes,hours,days or years. (e.g. "1d" for 1 day or "2h" for 2 hours etc). Defaults to the entire timeframe.
397
+ fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
398
+ 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".
399
+
400
+ Returns:
401
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
402
+
403
+ Raises:
404
+ ValueError: When invalid Output Type is given
405
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
406
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
407
+ RunTimeError/HTTPError: No response from the API
408
+ """
409
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
410
+ if output not in validOutputTypes:
411
+ raise ValueError("output must be one of %r." % validOutputTypes)
412
+
413
+ epoch_ms_start = time_to_epoch_millis(start)
414
+ epoch_ms_end = time_to_epoch_millis(end)
415
+
416
+ if window is not None:
417
+ windowDuration = parse_duration(window)
418
+ totalDuration = epoch_ms_end - epoch_ms_start
419
+ count = math.floor(totalDuration / windowDuration)
420
+ epoch_ms_end = epoch_ms_end - totalDuration % windowDuration
421
+ else:
422
+ count = 1
423
+ if count > 1000:
424
+ logging.warning(
425
+ "getAggregateIntervals is only designed to return up to 1000 aggregate sets, currently returning " + str(
426
+ count) + " sets. This may return overlapping intervals")
427
+
428
+ args = {}
429
+ args['tag'] = force_list(tags)
430
+ args['start'] = epoch_ms_start
431
+ args['end'] = epoch_ms_end
432
+ args['count'] = count
433
+ args['aggfields'] = fields
434
+ response = self._doJsonRequest("getagg", args)
435
+
436
+ keys = set(response.keys())
437
+ missing = [x for x in args['tag'] if x not in keys]
438
+
439
+ if missing != []:
440
+ if response == {}:
441
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
442
+ logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
443
+
444
+ if output == "raw":
445
+ return response
446
+ elif output == "json":
447
+ if len(force_list(tags)) == 1:
448
+ return response[tags]
449
+ else:
450
+ return response
451
+ elif output == "string":
452
+ return json.dumps(response)
453
+ elif output == "df":
454
+ return aggToDf(response,fields)
455
+ elif output == "csv":
456
+ order = ["tag","start","end","min","max","avg","var","stddev","count","numgood","numbad"]
457
+ return csvWriter(response,self.historian,filepath,multi_csv,"GetAggregateIntervals",order,True)
458
+
459
+
460
+ def countPoints(self, tags, start, end, output="json"):
461
+ """
462
+ Return the number of raw points of tags over a given time window
463
+
464
+ Args:
465
+ tags: A datatag, or list of datatags
466
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
467
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
468
+ 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".
469
+
470
+ Returns:
471
+ The number of raw datapoints in the interval, per tag.
472
+
473
+ Raises:
474
+ ValueError: When invalid Output Type is given
475
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
476
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
477
+ RunTimeError/HTTPError: No response from the API
478
+ """
479
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
480
+ if output not in validOutputTypes:
481
+ raise ValueError("output must be one of %r." % validOutputTypes)
482
+ ret = {}
483
+ aggs = self.getAggregates(force_list(tags), start, end, "COUNT", 1, "raw")
484
+ for tag in aggs.keys():
485
+ ret[tag] = aggs[tag][0]["count"]
486
+
487
+ response = self._matchArgumentCardinality(tags, ret)
488
+
489
+ if output == "raw" or output == "json":
490
+ return response
491
+ elif output == "string":
492
+ return json.dumps(response)
493
+ elif output == "df":
494
+ df = jsonToDf({"No. of Points": response})
495
+ return df
496
+ return None
497
+
498
+
499
+ def _writeDataPoints(self, data) -> bool:
500
+ rawdata = {}
501
+ for tag in list(data.keys()):
502
+ rawdps = []
503
+ for dp in force_list(data[tag]):
504
+ rawdps.append([int(dp.getTimestamp() * 1000), dp.getValue(), dp.getStatus()])
505
+ rawdata[tag] = rawdps
506
+
507
+ return self._doJsonRequest("write", {'write': json.dumps(rawdata)})
508
+
509
+ def createDataTag(self, tag:str, units:str, description:str) -> bool:
510
+ """
511
+ Create a new tag, or update the metadata of an existing tag
512
+
513
+ Args:
514
+ tag: The unique identifier of the tag
515
+ units: The unit of the values stored in the tag
516
+ description: A short explanation of the tags purpose or content
517
+
518
+ Returns:
519
+ A boolean representing the success of the creation. True means tag was created, False means the operation failed.
520
+ """
521
+ args = {}
522
+ args['tag'] = tag
523
+ args['units'] = units
524
+ args['description'] = description
525
+ return self._doJsonRequest("create", args)
526
+
527
+ def _doJsonRequest(self, cmd, params):
528
+ # self._testConnection()
529
+ url = self.serverurl + "?cmd=" + urlquote(cmd)
530
+ return _do_eigen_json_request(url, self.auth, **params)
531
+
532
+ def _matchArgumentCardinality(self, proto, ret):
533
+ """Takes in ret (a dict) and proto. If proto is a list, it returns
534
+ ret. If proto is a single value, it extracts that key from ret and
535
+ returns that instead.
536
+ The intention is that:
537
+ getTagThing("myTag") returns Thing for myTag
538
+ getTagThing(["myTag", "myOtherTag"]) returns {'myTag': Thing, 'myOtherTag': OtherThing}
539
+ and for clarification:
540
+ getTagThing(["myTag"]) returns {'myTag': Thing}
541
+ """
542
+ try:
543
+ badTags = []
544
+ if is_list(proto):
545
+ if ret != {}:
546
+ if len(ret) < len(proto):
547
+ for i in proto:
548
+ if i not in ret:
549
+ badTags.append(i)
550
+ return ret
551
+ else:
552
+ raise KeyError
553
+ return ret[proto]
554
+ except KeyError:
555
+ raise KeyError("Could not find tag(s): " + str(proto))
556
+
557
+ def writePoints(self, tag:str, points:list) -> bool:
558
+ """
559
+ Writes point data to a single existing tag.
560
+
561
+ Args:
562
+ tag: Id of tag to write to
563
+ points: The points to add to the tag (takes form [{value: ... , timestamp: ... , status: ...}, { ... }, ... ])
564
+
565
+ Returns:
566
+ Success: A boolean representing the successful push of data.
567
+ """
568
+ points = force_list(points)
569
+
570
+ datapoints = {tag : []}
571
+ for point in points:
572
+ if type(point["timestamp"]) is datetime:
573
+ point["timestamp"] = point["timestamp"].timestamp()
574
+ datapoints[tag].append(DataPoint(point["value"],point["timestamp"],point["status"]))
575
+
576
+ return self._writeDataPoints(datapoints)
577
+
578
+
579
+ def batchCSVImport(self, filepaths: Union[str,list]) -> bool:
580
+ """
581
+ Writes tag data from one or more csv file to Ingenuity. Will create a tag if it does not exist.
582
+
583
+ Args:
584
+ filepaths: The paths to one or more csv files. CSV Layouts must be as follows, with one point per line: tag,value,timestamp,status,units,description
585
+
586
+ Returns:
587
+ Success: A boolean representing the successful push of data. True means all csvs were successfully imported, False means at least one csv failed.
588
+ """
589
+ success = []
590
+ for filepath in force_list(filepaths):
591
+ with open(filepath, "r") as file:
592
+ csv_reader = csv.reader(file, delimiter=',')
593
+ data = list(csv_reader)
594
+ # Upload in batches of 500 to avoid API timeouts/throttling
595
+ chunks = divide_chunks(data, 500)
596
+ for chunk in chunks:
597
+ datapoints = {}
598
+ for item in chunk:
599
+
600
+ self.createDataTag(item[0], item[4], item[5])
601
+ try:
602
+ datapoints[item[0]].append(DataPoint(item[1], int(item[2]), item[3]))
603
+ except KeyError:
604
+ datapoints[item[0]] = [DataPoint(item[1], int(item[2]), item[3])]
605
+ success.append(self._writeDataPoints(datapoints))
606
+ file.close()
607
+ return all(success)
608
+
609
+
610
+ def batchJsonImport(self, data:Union[dict,list]) -> bool:
611
+ """
612
+ Writes datapoints from dict objects to tags in the Ingenuity historian.
613
+
614
+ Args:
615
+ data: a dict (or list of dicts) with format {"tag1": [{value,timestamp,status},{value,..},...], "tag2": {{value,..},...],...}
616
+
617
+ Returns:
618
+ A boolean indicating whether the push of data was successful. True means all data was successfully pushed, False means at least one batch failed to push.
619
+ """
620
+ success = []
621
+ data = force_list(data)
622
+ for datum in data:
623
+ datapoints = {}
624
+ totalPoints = 0
625
+ tags = datum.keys()
626
+ for tag in tags:
627
+ # Upload in batches of 500 to avoid API timeouts/throttling
628
+ if totalPoints >= 500:
629
+ self._writeDataPoints(datapoints)
630
+ datapoints = {}
631
+ totalPoints = 0
632
+
633
+ for item in datum[tag]:
634
+ try:
635
+ datapoints[tag].append(DataPoint(item["value"],item["timestamp"],item["status"]))
636
+ except:
637
+ datapoints[tag] = [DataPoint(item["value"], item["timestamp"], item["status"])]
638
+ totalPoints += len(datapoints[tag])
639
+
640
+ success.append(self._writeDataPoints(datapoints))
641
+ return all(success)
642
+
643
+
644
+ class DataPoint(object): # LEGACY OBJECT
645
+ """This class represents a data point which has a value and a python timestamp, and optionally a status of 'OK' or 'BAD'.
646
+ Timestamp is stored in epochseconds. The constructor will convert datetime and tuples into floating point epoch seconds.
647
+ """
648
+
649
+ def __init__(self, value, timestamp, status = 'OK'):
650
+ """This constructor takes in a value, a python timestamp (epoch floating point seconds or datetime or tuple)
651
+ and an optional status. Status is either "OK" or "BAD" and will default to "OK"
652
+ """
653
+
654
+ self.value = value
655
+
656
+ if status is None:
657
+ self.status = "OK"
658
+ elif status == "OK" or status == "BAD":
659
+ self.status = status
660
+ else:
661
+ raise EigenException("Unrecognised Status")
662
+
663
+ # Convert timestamp from python datetime or tuple into python floating point epoch seconds
664
+ self.datetime = datetime.fromtimestamp(time_to_epoch_millis(timestamp)/1000)
665
+ self.timestamp = pythonTimeToFloatingSecs(time_to_epoch_millis(timestamp)/1000)
666
+
667
+
668
+ def __str__(self):
669
+ """Return a nicely formatted version of the datapoint"""
670
+ val = self.value
671
+ if type(val) != str:
672
+ val = str(number_to_string(val))
673
+ else:
674
+ val = val.ljust(12)
675
+ return val + " @ " + get_timestamp_string(self.timestamp) + " - " + self.status
676
+
677
+ def __repr__(self):
678
+ return "DataPoint[" + str(self) + "]"
679
+
680
+ def getValue(self):
681
+ """Return the value of the datapoint"""
682
+ return self.value
683
+
684
+ def getTimestamp(self):
685
+ """Return the timestamp of the datapoint in python floating point epoch seconds"""
686
+ return self.timestamp
687
+
688
+ def getTimestampMillis(self):
689
+ """Return the timestamp of the datapoint in epochmillis"""
690
+ return pythonTimeToServerTime(self.timestamp)
691
+
692
+ def getTimestampAsDatetime(self):
693
+ """Return the timestamp of the datapoint as Datetime"""
694
+ return get_datetime(self.timestamp)
695
+
696
+ def getTimestampAsTuple(self):
697
+ """Return the timestamp of the datapoint as Tuple"""
698
+ return get_time_tuple(self.timestamp)
699
+
700
+ def getStatus(self):
701
+ """Return the status of the datapoint - either 'OK' or 'BAD'"""
702
+ return self.status
703
+
704
+ def isBad(self):
705
+ """Returns either True if status = "BAD" or false if status = "OK" """
706
+ return self.status != "OK"
707
+
708
+ def __eq__(self, other):
709
+ if isinstance(other, self.__class__):
710
+ return self.__dict__ == other.__dict__
711
+ else:
712
+ return False
713
+
714
+ def getAsJson(self):
715
+ """Return as a json map with the timestamp in milliseconds"""
716
+ return "{" + "\"value\":" + str(self.value) + ",\"timestamp\":" + self.getTimestampMillis(
717
+ self) + ",\"status\":\"" + self.status + "\"}"
718
+
719
+
720
+ def get_datapoint(dp):
721
+ tag = dp["tag"]
722
+ value = dp["value"]
723
+ timestamp = dp["timestamp"]
724
+ timestampinmillis = dp["timestamp"]
725
+ timestamp = serverTimeToPythonTime(timestampinmillis)
726
+ status = dp["status"]
727
+ return DataPoint(tag, value, timestamp, status)
728
+
729
+
730
+ def get_historian(instance: str = None, eigenserver: EigenServer = None) -> JsonBridgeHistorian:
731
+ """Instantiate a historian object for the given instance.
732
+
733
+ Args:
734
+ instance (Optional): The name of the historian to connect to. Defaults to the default historian of the EigenServer.
735
+ 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
736
+
737
+ Returns:
738
+ An Object that can be used to query historian data.
739
+
740
+ """
741
+ if eigenserver is None:
742
+ eigenserver = get_default_server()
743
+ elif type(eigenserver) == str:
744
+ eigenserver = EigenServer(eigenserver)
745
+
746
+ if instance is not None and (instance.startswith("http:") or instance.startswith("https:")):
747
+ return JsonBridgeHistorian(instance)
748
+
749
+ if instance is None:
750
+ instance = get_default_historian_name(eigenserver=eigenserver)
751
+ if instance is None:
752
+ raise EigenException("No default historian instance found")
753
+ return JsonBridgeHistorian(eigenserver.getEigenServerUrl() + "historian-servlet" + "/jsonbridge/" + instance, eigenserver.auth)
754
+
755
+
756
+ def list_historians(eigenserver=None) -> list:
757
+ """List all historian instances in EigenServer.
758
+
759
+ Args:
760
+ 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
761
+
762
+ Returns:
763
+ A list of all historians on the server
764
+ """
765
+ if eigenserver is None:
766
+ eigenserver = get_default_server()
767
+
768
+ return eigenserver._listDataSources_legacy("historian")
769
+
770
+
771
+ def get_default_historian_name(eigenserver=None) -> str:
772
+ """Get the default historian of an EigenServer.
773
+
774
+ Args:
775
+ 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
776
+
777
+ Returns:
778
+ The name of the default historian
779
+ """
780
+ if eigenserver is None:
781
+ eigenserver = get_default_server()
782
+
783
+ return eigenserver.getDefaultDataSource("historian")
784
+
785
+ def createPoint(value:Union[str,int,float],timestamp:int,status:str):
786
+ return {"value": value, "timestamp": timestamp, "status": status}