python-eigen-ingenuity 0.4.29__py3-none-any.whl → 0.4.30__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.
@@ -19,6 +19,7 @@ from __future__ import (absolute_import, division, print_function, unicode_liter
19
19
  import pkg_resources
20
20
  from eigeningenuity.core import EigenServer
21
21
  from eigeningenuity.historian import get_historian, list_historians, get_default_historian_name
22
+ from eigeningenuity.historianmulti import get_historian_multi
22
23
  from eigeningenuity.elastic import get_elastic
23
24
  from eigeningenuity.events import get_eventlog
24
25
  from eigeningenuity.assetmodel import get_assetmodel
@@ -26,5 +27,5 @@ from eigeningenuity.smartdash import get_smartdash
26
27
  from eigeningenuity.sql import get_sql
27
28
  from eigeningenuity.settings import set_azure_client_id, set_azure_tenant_id, disable_azure_auth, disable_token_cache, clear_token_cache
28
29
 
29
- __all__ = ["get_historian", "get_assetmodel", "get_elastic", "get_sql", "get_eventlog", "get_smartdash", "list_historians", "get_default_historian_name", "EigenServer", "set_azure_client_id", "set_azure_tenant_id", "disable_azure_auth", "disable_token_cache", "clear_token_cache"]
30
+ __all__ = ["get_historian", "get_historian_multi", "get_assetmodel", "get_elastic", "get_sql", "get_eventlog", "get_smartdash", "list_historians", "get_default_historian_name", "EigenServer", "set_azure_client_id", "set_azure_tenant_id", "disable_azure_auth", "disable_token_cache", "clear_token_cache"]
30
31
  __version__ = pkg_resources.require("python-eigen-ingenuity")[0].version
@@ -375,7 +375,7 @@ class AssetModel (object):
375
375
  KeyError: Raises an exception
376
376
  """
377
377
 
378
- args = []
378
+ args = {}
379
379
  if exact:
380
380
  matchStatement = "n.%s = '%s'" % (prop,node)
381
381
  else:
@@ -0,0 +1,668 @@
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, multi_response_to_df
36
+
37
+ from urllib3.exceptions import InsecureRequestWarning
38
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
39
+
40
+
41
+ class HistorianMulti (object):
42
+ """A Historian which talks the Eigen Historian Json Bridge protocol.
43
+ """
44
+
45
+ def __init__(self, serverurl):
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.baseurl = serverurl.rsplit("/",1)[0]
49
+
50
+ def _testConnection(self):
51
+ try:
52
+ status = requests.get(self.serverurl, verify=False).status_code
53
+ if status != 200:
54
+ raise ConnectionError(
55
+ "Invalid API Response from " + self.serverurl + ". Please check the url is correct and the instance is up.")
56
+ except (URLError, ConnectionError):
57
+ raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
58
+
59
+ def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json", filepath:str=None, multi_csv:bool=False):
60
+ body = {
61
+ "requests": {}
62
+ }
63
+
64
+ for tag in tags:
65
+ request = {
66
+ "type": "CURRENT_POINT",
67
+ "tag": tag,
68
+ "details": {}
69
+ }
70
+
71
+ body["requests"][tag] = request
72
+
73
+ response = requests.post(self.serverurl,json=body).json()
74
+ items = response["results"]
75
+
76
+ if output == "raw":
77
+ return response
78
+ elif output == "json":
79
+ if len(force_list(tags)) == 1:
80
+ return items[tags]
81
+ else:
82
+ return items
83
+ elif output == "string":
84
+ return json.dumps(items)
85
+ elif output == "df":
86
+ return multi_response_to_df(items)
87
+ return None
88
+
89
+
90
+ def getInterpolatedPoints(self, tags: Union[str, list], timestamps: Union[list, int, float, str, datetime],
91
+ output: str = "json", filepath:str=None, multi_csv:bool=False):
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, or list of datatags
97
+ 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
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
+ for tag in tags:
114
+ for timestamp in timestamps:
115
+ request = {
116
+ "type": "HISTORIC_POINT",
117
+ "tag": tag,
118
+ "details": {
119
+ "at": timestamp
120
+ }
121
+ }
122
+
123
+ body[tag +"-"+ timestamp] = request
124
+
125
+
126
+ response = requests.post(self.serverurl,json=body)
127
+ items = response["results"]
128
+
129
+ if output == "raw":
130
+ return response
131
+ elif output == "json":
132
+ if len(force_list(tags)) == 1:
133
+ return items[tags]
134
+ else:
135
+ return items
136
+ elif output == "string":
137
+ return json.dumps(items)
138
+ elif output == "df":
139
+ return multi_response_to_df(items)
140
+ return None
141
+
142
+
143
+ def getRawDataPoints(self, tags: Union[str, list], start: Union[int, float, str, datetime],
144
+ end: Union[int, float, str, datetime], maxpoints: int = 1000, output: str = "json", filepath:str=None, multi_csv:bool=False) -> object:
145
+ """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
146
+
147
+ Args:
148
+ tags: A datatag, or list of datatags
149
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
150
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
151
+ maxpoints (Optional): The maximum number of points to return. Defaults to 1000
152
+ 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".
153
+
154
+ Returns:
155
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
156
+
157
+ Raises:
158
+ ValueError: When invalid Output Type is given
159
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
160
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
161
+ RunTimeError/HTTPError: No response from the API
162
+ """
163
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
164
+ if output not in validOutputTypes:
165
+ raise ValueError("output must be one of %r." % validOutputTypes)
166
+ args = {}
167
+ args['tag'] = force_list(tags)
168
+ args['start'] = time_to_epoch_millis(start)
169
+ args['end'] = time_to_epoch_millis(end)
170
+ args['maxpoints'] = maxpoints
171
+ response = self._doJsonRequest("getraw", args)
172
+ items = response["items"]
173
+
174
+ if response['unknown'] != []:
175
+ if items == {}:
176
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
177
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
178
+
179
+ if output == "raw":
180
+ return response
181
+ elif output == "json":
182
+ if len(force_list(tags)) == 1:
183
+ return items[tags]
184
+ else:
185
+ return items
186
+ elif output == "string":
187
+ return json.dumps(items)
188
+ elif output == "df":
189
+ return jsonToDf(items)
190
+ elif output == "csv":
191
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetRaw")
192
+ return None
193
+
194
+
195
+
196
+ def getInterpolatedRange(self, tags: Union[str, list], start: Union[int, float, str, datetime],
197
+ end: Union[int, float, str, datetime], count: int = 1000, output: str = "json", filepath:str=None, multi_csv:bool=False):
198
+ """Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
199
+
200
+ Args:
201
+ tags: A datatag, or list of datatags
202
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
203
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
204
+ count (Optional): Number of points to return, evenly spaced across the given time range. Defaults to 1000
205
+ 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".
206
+
207
+ Returns:
208
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
209
+
210
+ Raises:
211
+ ValueError: When invalid Output Type is given
212
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
213
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
214
+ RunTimeError/HTTPError: No response from the API
215
+ """
216
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
217
+ if output not in validOutputTypes:
218
+ raise ValueError("output must be one of %r." % validOutputTypes)
219
+ args = {}
220
+ args['tag'] = force_list(tags)
221
+ args['start'] = time_to_epoch_millis(start)
222
+ args['end'] = time_to_epoch_millis(end)
223
+ args['count'] = count
224
+ response = self._doJsonRequest("getrange", args)
225
+ items = response["items"]
226
+
227
+ if response['unknown'] != []:
228
+ if items == {}:
229
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
230
+ logging.warning("Could not find tags: " + str(response["unknown"]) + " in historian " + self.historian)
231
+
232
+ if output == "raw":
233
+ return response
234
+ elif output == "json":
235
+ if len(force_list(tags)) == 1:
236
+ return items[tags]
237
+ else:
238
+ return items
239
+ elif output == "string":
240
+ return json.dumps(items)
241
+ elif output == "df":
242
+ return jsonToDf(items)
243
+ elif output == "csv":
244
+ return csvWriter(items,self.historian,filepath,multi_csv,"GetInterpolatedRange")
245
+ return None
246
+
247
+ def getAggregates(self, tags: Union[str, list], start: Union[int, float, str, datetime],
248
+ end: Union[int, float, str, datetime], fields: Union[str, list] = None, count: int = 1,
249
+ output: str = "json", filepath:str=None, multi_csv:bool=False):
250
+ """
251
+ Return specified aggregates of tags over a given time window, optionally divided into equal parts
252
+
253
+ Args:
254
+ tags: A datatag, or list of datatags
255
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
256
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
257
+ fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
258
+ count (Optional): Number of intervals to split the time window into, returning aggregates over each interval. Defaults to 1
259
+ 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".
260
+
261
+ Returns:
262
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
263
+
264
+ Raises:
265
+ ValueError: When invalid Output Type is given
266
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
267
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
268
+ RunTimeError/HTTPError: No response from the API
269
+ """
270
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
271
+ if output not in validOutputTypes:
272
+ raise ValueError("output must be one of %r." % validOutputTypes)
273
+ args = {}
274
+ args['tag'] = force_list(tags)
275
+ args['start'] = time_to_epoch_millis(start)
276
+ args['end'] = time_to_epoch_millis(end)
277
+ args['count'] = count
278
+ args['aggfields'] = fields
279
+
280
+ response = self._doJsonRequest("getagg", args)
281
+
282
+ keys = set(response.keys())
283
+ missing = [x for x in args['tag'] if x not in keys]
284
+
285
+ if missing != []:
286
+ if response == {}:
287
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
288
+ logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
289
+
290
+ if output == "raw":
291
+ return response
292
+ elif output == "json":
293
+ if len(force_list(tags)) == 1:
294
+ return response[tags]
295
+ else:
296
+ return response
297
+ elif output == "string":
298
+ return json.dumps(response)
299
+ elif output == "df":
300
+ return aggToDf(response,fields)
301
+ elif output == "csv":
302
+ order = ["tag","start","end","min","max","avg","var","stddev","count","numgood","numbad"]
303
+ return csvWriter(response,self.historian,filepath,multi_csv,"GetAggregates",order,True)
304
+ return None
305
+
306
+
307
+ def getAggregateIntervals(self, tags, start: Union[int, float, str, datetime],
308
+ end: Union[int, float, str, datetime], window: str = None,
309
+ fields: Union[str, list] = None, output: str = "json", filepath:str=None, multi_csv:bool=False):
310
+ """
311
+ Return specified aggregates of tags over a given time window, optionally divided into equal parts
312
+
313
+ Args:
314
+ tags: A datatag, or list of datatags
315
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
316
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
317
+ 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.
318
+ fields (Optional): The aggregates to be calculated, accepts any subset of ["min","max","mean","stddev","var","numgood","numbad"]. Defaults to all aggregates.
319
+ 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".
320
+
321
+ Returns:
322
+ Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
323
+
324
+ Raises:
325
+ ValueError: When invalid Output Type is given
326
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
327
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
328
+ RunTimeError/HTTPError: No response from the API
329
+ """
330
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
331
+ if output not in validOutputTypes:
332
+ raise ValueError("output must be one of %r." % validOutputTypes)
333
+
334
+ epoch_ms_start = time_to_epoch_millis(start)
335
+ epoch_ms_end = time_to_epoch_millis(end)
336
+
337
+ if window is not None:
338
+ windowDuration = parse_duration(window)
339
+ totalDuration = epoch_ms_end - epoch_ms_start
340
+ count = math.floor(totalDuration / windowDuration)
341
+ epoch_ms_end = epoch_ms_end - totalDuration % windowDuration
342
+ else:
343
+ count = 1
344
+ if count > 1000:
345
+ logging.warning(
346
+ "getAggregateIntervals is only designed to return up to 1000 aggregate sets, currently returning " + str(
347
+ count) + " sets. This may return overlapping intervals")
348
+
349
+ args = {}
350
+ args['tag'] = force_list(tags)
351
+ args['start'] = epoch_ms_start
352
+ args['end'] = epoch_ms_end
353
+ args['count'] = count
354
+ args['aggfields'] = fields
355
+ response = self._doJsonRequest("getagg", args)
356
+
357
+ keys = set(response.keys())
358
+ missing = [x for x in args['tag'] if x not in keys]
359
+
360
+ if missing != []:
361
+ if response == {}:
362
+ raise EigenException("None of the provided tags could be found in historian " + self.historian)
363
+ logging.warning("Could not find tags: " + str(missing) + " in historian " + self.historian)
364
+
365
+ if output == "raw":
366
+ return response
367
+ elif output == "json":
368
+ if len(force_list(tags)) == 1:
369
+ return response[tags]
370
+ else:
371
+ return response
372
+ elif output == "string":
373
+ return json.dumps(response)
374
+ elif output == "df":
375
+ return aggToDf(response,fields)
376
+ elif output == "csv":
377
+ order = ["tag","start","end","min","max","avg","var","stddev","count","numgood","numbad"]
378
+ return csvWriter(response,self.historian,filepath,multi_csv,"GetAggregateIntervals",order,True)
379
+
380
+
381
+ def countPoints(self, tags, start, end, output="json"):
382
+ """
383
+ Return the number of raw points of tags over a given time window
384
+
385
+ Args:
386
+ tags: A datatag, or list of datatags
387
+ start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
388
+ end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
389
+ 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".
390
+
391
+ Returns:
392
+ The number of raw datapoints in the interval, per tag.
393
+
394
+ Raises:
395
+ ValueError: When invalid Output Type is given
396
+ URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
397
+ RemoteServerException: When the provided historian could not be found, or the API response contains an error
398
+ RunTimeError/HTTPError: No response from the API
399
+ """
400
+ validOutputTypes = ["raw", "json", "df", "csv", "string"]
401
+ if output not in validOutputTypes:
402
+ raise ValueError("output must be one of %r." % validOutputTypes)
403
+ ret = {}
404
+ aggs = self.getAggregates(force_list(tags), start, end, "COUNT", 1, "raw")
405
+ for tag in aggs.keys():
406
+ ret[tag] = aggs[tag][0]["count"]
407
+
408
+ response = self._matchArgumentCardinality(tags, ret)
409
+
410
+ if output == "raw" or output == "json":
411
+ return response
412
+ elif output == "string":
413
+ return json.dumps(response)
414
+ elif output == "df":
415
+ df = jsonToDf({"No. of Points": response})
416
+ return df
417
+ return None
418
+
419
+
420
+ def _writeDataPoints(self, data) -> bool:
421
+ rawdata = {}
422
+ for tag in list(data.keys()):
423
+ rawdps = []
424
+ for dp in force_list(data[tag]):
425
+ rawdps.append([int(dp.getTimestamp() * 1000), dp.getValue(), dp.getStatus()])
426
+ rawdata[tag] = rawdps
427
+
428
+ return self._doJsonRequest("write", {'write': json.dumps(rawdata)})
429
+
430
+ def createDataTag(self, tag:str, units:str, description:str) -> bool:
431
+ """
432
+ Create a new tag, or update the metadata of an existing tag
433
+
434
+ Args:
435
+ tag: The unique identifier of the tag
436
+ units: The unit of the values stored in the tag
437
+ description: A short explanation of the tags purpose or content
438
+
439
+ Returns:
440
+ A boolean representing the success of the creation. True means tag was created, False means the operation failed.
441
+ """
442
+ args = {}
443
+ args['tag'] = tag
444
+ args['units'] = units
445
+ args['description'] = description
446
+ return self._doJsonRequest("create", args)
447
+
448
+ def _doJsonRequest(self, cmd, params):
449
+ self._testConnection()
450
+ url = self.serverurl + "?cmd=" + urlquote(cmd)
451
+ return _do_eigen_json_request(url, **params)
452
+
453
+ def _matchArgumentCardinality(self, proto, ret):
454
+ """Takes in ret (a dict) and proto. If proto is a list, it returns
455
+ ret. If proto is a single value, it extracts that key from ret and
456
+ returns that instead.
457
+ The intention is that:
458
+ getTagThing("myTag") returns Thing for myTag
459
+ getTagThing(["myTag", "myOtherTag"]) returns {'myTag': Thing, 'myOtherTag': OtherThing}
460
+ and for clarification:
461
+ getTagThing(["myTag"]) returns {'myTag': Thing}
462
+ """
463
+ try:
464
+ badTags = []
465
+ if is_list(proto):
466
+ if ret != {}:
467
+ if len(ret) < len(proto):
468
+ for i in proto:
469
+ if i not in ret:
470
+ badTags.append(i)
471
+ return ret
472
+ else:
473
+ raise KeyError
474
+ return ret[proto]
475
+ except KeyError:
476
+ raise KeyError("Could not find tag(s): " + str(proto))
477
+
478
+ def writePoints(self, tag:str, points:Union[dict,list]) -> bool:
479
+ """
480
+ Writes point data to a single existing tag.
481
+
482
+ Args:
483
+ tag: Id of tag to write to
484
+ points: The points to add to the tag (takes form [{value: ... , timestamp: ... , status: ...}, { ... }, ... ])
485
+
486
+ Returns:
487
+ Success: A boolean representing the successful push of data.
488
+ """
489
+ points = force_list(points)
490
+
491
+ datapoints = {tag : []}
492
+ for point in points:
493
+ if type(point["timestamp"]) is datetime:
494
+ point["timestamp"] = point["timestamp"].timestamp()
495
+ datapoints[tag].append(DataPoint(point["value"],point["timestamp"],point["status"]))
496
+
497
+ return self._writeDataPoints(datapoints)
498
+
499
+
500
+ def batchCSVImport(self, filepaths: Union[str,list]) -> bool:
501
+ """
502
+ Writes tag data from one or more csv file to Ingenuity. Will create a tag if it does not exist.
503
+
504
+ Args:
505
+ 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
506
+
507
+ Returns:
508
+ Success: A boolean representing the successful push of data. True means all csvs were successfully imported, False means at least one csv failed.
509
+ """
510
+ success = []
511
+ for filepath in force_list(filepaths):
512
+ with open(filepath, "r") as file:
513
+ csv_reader = csv.reader(file, delimiter=',')
514
+ data = list(csv_reader)
515
+ # Upload in batches of 500 to avoid API timeouts/throttling
516
+ chunks = divide_chunks(data, 500)
517
+ for chunk in chunks:
518
+ datapoints = {}
519
+ for item in chunk:
520
+
521
+ self.createDataTag(item[0], item[4], item[5])
522
+ try:
523
+ datapoints[item[0]].append(DataPoint(item[1], int(item[2]), item[3]))
524
+ except KeyError:
525
+ datapoints[item[0]] = [DataPoint(item[1], int(item[2]), item[3])]
526
+ success.append(self._writeDataPoints(datapoints))
527
+ file.close()
528
+ return all(success)
529
+
530
+
531
+ def batchJsonImport(self, data:Union[dict,list]) -> bool:
532
+ """
533
+ Writes datapoints from dict objects to tags in the Ingenuity historian.
534
+
535
+ Args:
536
+ data: a dict (or list of dicts) with format {"tag1": [{value,timestamp,status},{value,..},...], "tag2": {{value,..},...],...}
537
+
538
+ Returns:
539
+ 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.
540
+ """
541
+ success = []
542
+ data = force_list(data)
543
+ for datum in data:
544
+ datapoints = {}
545
+ totalPoints = 0
546
+ tags = datum.keys()
547
+ for tag in tags:
548
+ # Upload in batches of 500 to avoid API timeouts/throttling
549
+ if totalPoints >= 500:
550
+ self._writeDataPoints(datapoints)
551
+ datapoints = {}
552
+ totalPoints = 0
553
+
554
+ for item in datum[tag]:
555
+ try:
556
+ datapoints[tag].append(DataPoint(item["value"],item["timestamp"],item["status"]))
557
+ except:
558
+ datapoints[tag] = [DataPoint(item["value"], item["timestamp"], item["status"])]
559
+ totalPoints += len(datapoints[tag])
560
+
561
+ success.append(self._writeDataPoints(datapoints))
562
+ return all(success)
563
+
564
+
565
+ class DataPoint(object): # LEGACY OBJECT
566
+ """This class represents a data point which has a value and a python timestamp, and optionally a status of 'OK' or 'BAD'.
567
+ Timestamp is stored in epochseconds. The constructor will convert datetime and tuples into floating point epoch seconds.
568
+ """
569
+
570
+ def __init__(self, value, timestamp, status = 'OK'):
571
+ """This constructor takes in a value, a python timestamp (epoch floating point seconds or datetime or tuple)
572
+ and an optional status. Status is either "OK" or "BAD" and will default to "OK"
573
+ """
574
+
575
+ self.value = value
576
+
577
+ if status is None:
578
+ self.status = "OK"
579
+ elif status == "OK" or status == "BAD":
580
+ self.status = status
581
+ else:
582
+ raise EigenException("Unrecognised Status")
583
+
584
+ # Convert timestamp from python datetime or tuple into python floating point epoch seconds
585
+ self.datetime = datetime.fromtimestamp(time_to_epoch_millis(timestamp)/1000)
586
+ self.timestamp = pythonTimeToFloatingSecs(time_to_epoch_millis(timestamp)/1000)
587
+
588
+
589
+ def __str__(self):
590
+ """Return a nicely formatted version of the datapoint"""
591
+ val = self.value
592
+ if type(val) != str:
593
+ val = str(number_to_string(val))
594
+ else:
595
+ val = val.ljust(12)
596
+ return val + " @ " + get_timestamp_string(self.timestamp) + " - " + self.status
597
+
598
+ def __repr__(self):
599
+ return "DataPoint[" + str(self) + "]"
600
+
601
+ def getValue(self):
602
+ """Return the value of the datapoint"""
603
+ return self.value
604
+
605
+ def getTimestamp(self):
606
+ """Return the timestamp of the datapoint in python floating point epoch seconds"""
607
+ return self.timestamp
608
+
609
+ def getTimestampMillis(self):
610
+ """Return the timestamp of the datapoint in epochmillis"""
611
+ return pythonTimeToServerTime(self.timestamp)
612
+
613
+ def getTimestampAsDatetime(self):
614
+ """Return the timestamp of the datapoint as Datetime"""
615
+ return get_datetime(self.timestamp)
616
+
617
+ def getTimestampAsTuple(self):
618
+ """Return the timestamp of the datapoint as Tuple"""
619
+ return get_time_tuple(self.timestamp)
620
+
621
+ def getStatus(self):
622
+ """Return the status of the datapoint - either 'OK' or 'BAD'"""
623
+ return self.status
624
+
625
+ def isBad(self):
626
+ """Returns either True if status = "BAD" or false if status = "OK" """
627
+ return self.status != "OK"
628
+
629
+ def __eq__(self, other):
630
+ if isinstance(other, self.__class__):
631
+ return self.__dict__ == other.__dict__
632
+ else:
633
+ return False
634
+
635
+ def getAsJson(self):
636
+ """Return as a json map with the timestamp in milliseconds"""
637
+ return "{" + "\"value\":" + str(self.value) + ",\"timestamp\":" + self.getTimestampMillis(
638
+ self) + ",\"status\":\"" + self.status + "\"}"
639
+
640
+
641
+ def get_datapoint(dp):
642
+ tag = dp["tag"]
643
+ value = dp["value"]
644
+ timestamp = dp["timestamp"]
645
+ timestampinmillis = dp["timestamp"]
646
+ timestamp = serverTimeToPythonTime(timestampinmillis)
647
+ status = dp["status"]
648
+ return DataPoint(tag, value, timestamp, status)
649
+
650
+
651
+ def get_historian_multi(eigenserver: EigenServer = None) -> HistorianMulti:
652
+ """Instantiate a historian object for the given instance.
653
+
654
+ Args:
655
+ instance (Optional): The name of the historian to connect to. Defaults to the default historian of the EigenServer.
656
+ 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
657
+
658
+ Returns:
659
+ An Object that can be used to query historian data.
660
+
661
+ """
662
+ if eigenserver is None:
663
+ eigenserver = get_default_server()
664
+
665
+ return HistorianMulti(eigenserver.getEigenServerUrl() + "historian-servlet" + "/multi/")
666
+
667
+ def createPoint(value:Union[str,int,float],timestamp:int,status:str):
668
+ return {"value": value, "timestamp": timestamp, "status": status}
eigeningenuity/util.py CHANGED
@@ -10,6 +10,11 @@ from requests.exceptions import ConnectionError
10
10
  from eigeningenuity.auth import _authenticate_azure_user
11
11
  import eigeningenuity.settings as settings
12
12
 
13
+ from urllib3.exceptions import InsecureRequestWarning
14
+ import urllib3
15
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
16
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
17
+
13
18
  def _do_eigen_json_request(requesturl,**params):
14
19
 
15
20
  headers = {}
@@ -270,7 +275,10 @@ def jsonToDf(json,transpose:bool=False):
270
275
 
271
276
  def dataMap(j):
272
277
  try:
273
- h = {datetime.fromtimestamp(j["timestamp"] / 1000): j["value"]}
278
+ if type(j["timestamp"]) == int:
279
+ h = {datetime.fromtimestamp(j["timestamp"] / 1000): j["value"]}
280
+ else:
281
+ h = {datetime.fromisoformat(j["timestamp"]): j["value"]}
274
282
  except:
275
283
  h = j
276
284
  return h
@@ -343,6 +351,30 @@ def parseEvents(events):
343
351
  def parse_properties(x):
344
352
  return x["graphapi"]["properties"]
345
353
 
354
+ def multi_response_to_df(api_response):
355
+ data_dict = {}
356
+
357
+ # Iterate through the response
358
+ for key, value in api_response.items():
359
+ tag_name = key
360
+ timestamp = value['dataPoint']['timestamp']
361
+ value_data = value['dataPoint']['value']
362
+
363
+ # Check if timestamp is already a key in the dictionary
364
+ if timestamp not in data_dict:
365
+ data_dict[timestamp] = {}
366
+
367
+ # Add data to the dictionary
368
+ data_dict[timestamp][tag_name] = value_data
369
+
370
+ # Create DataFrame
371
+ df = pd.DataFrame(data_dict).T # Transpose the DataFrame
372
+
373
+ # Convert timestamp index to datetime format
374
+ df.index = pd.to_datetime(df.index)
375
+
376
+ return df
377
+
346
378
  def csvWriter(data,historian,filepath,multi_csv,functionName,order=None,headers=False):
347
379
  if "Agg" in functionName:
348
380
  timeField = 'start'
@@ -1,22 +1,22 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: python-eigen-ingenuity
3
- Version: 0.4.29
3
+ Version: 0.4.30
4
4
  Summary: A python library used to query data from the Eigen Ingenuity system
5
5
  Home-page: https://www.eigen.co/
6
6
  Author: Murray Callander
7
7
  Author-email: info@eigen.co
8
8
  License: Apache License 2.0
9
9
  Description-Content-Type: text/markdown
10
- Requires-Dist: numpy >=1.24.2
11
- Requires-Dist: paho-mqtt >=1.6.1
12
- Requires-Dist: pandas >=1.5.3
13
- Requires-Dist: pyserial >=3.5
14
- Requires-Dist: requests >=2.28.2
15
- Requires-Dist: setuptools >=57.0.0
16
- Requires-Dist: urllib3 >=1.26.14
10
+ Requires-Dist: numpy
11
+ Requires-Dist: pandas
12
+ Requires-Dist: pyserial
13
+ Requires-Dist: requests
14
+ Requires-Dist: setuptools
15
+ Requires-Dist: urllib3
17
16
  Requires-Dist: msal
18
17
  Requires-Dist: cryptography
19
18
  Requires-Dist: keyring
19
+ Requires-Dist: pyarrow
20
20
 
21
21
  CONTENTS
22
22
  ============
@@ -1,15 +1,16 @@
1
- eigeningenuity/__init__.py,sha256=rBwqY37xmQKCHyRf0rUaLI4_yztd2ueQTUoo1nGOJH4,1417
2
- eigeningenuity/assetmodel.py,sha256=Ly26iD_t-cyhaSNHRvbhHo_eulVUDXmNRAbgsfSeaqM,16619
1
+ eigeningenuity/__init__.py,sha256=oCrilopumT7tGVXOp4TO0qWQ2m-DqDpr3oex-W5guoU,1502
2
+ eigeningenuity/assetmodel.py,sha256=p95F0aGy9Q--dLjT2QuJMWR8rNZFqqqbsY-GQbgueJU,16619
3
3
  eigeningenuity/auth.py,sha256=3efTRyiKoKXCYt3F2lZ9KVF82Gw-BfFLC8y9lo8690I,6560
4
4
  eigeningenuity/elastic.py,sha256=FYwjnIjDimDS4XWVnhPWVWJ4yLPUsTNr12S-YCYmM04,6250
5
5
  eigeningenuity/events.py,sha256=gU6Q3VLpk4lgVjZPtCchjJI7CVWehEGijSEfmrFEgkY,3054
6
6
  eigeningenuity/historian.py,sha256=G0bd7wC_1Zw9az4vWRtQFGoh4NYrxGVtu7A7VBFG5O4,36195
7
+ eigeningenuity/historianmulti.py,sha256=WtSEzow1lPNjvM52_JI7mv75YIAe989GvD0NKisbOcs,30295
7
8
  eigeningenuity/settings.py,sha256=q9hiuD9E8Bcpl8NI2kr-DQK1U8wNqZDNKSQ8Xy_Dpx4,2085
8
9
  eigeningenuity/smartdash.py,sha256=pkqx_hSZLJUKT1xJtu2TmQgk4pZCTiPoaCjrbgcD86I,2843
9
10
  eigeningenuity/sql.py,sha256=bWZpCPTKgX_MF-xlNb0qPEZv09to4_SIUAvTjZXWkDc,4081
10
- eigeningenuity/util.py,sha256=ewNDMk4n1PZm2nRW1_5RlQgUWF_fQ9l2oW76WHysU7o,12839
11
+ eigeningenuity/util.py,sha256=33A7L71vhgBusUUfnRkwesuT5VS6pbqCNdZjH9RoZ2E,13867
11
12
  eigeningenuity/core/__init__.py,sha256=QVMU9bEoZTjPzg_-oNWXHzQB0HPlt95tKGXdlBS_eP0,7741
12
- python_eigen_ingenuity-0.4.29.dist-info/METADATA,sha256=zL8dYHyfz27oRL5mb4BjKpOJgLabO3CdVVbq7yhTAnc,14288
13
- python_eigen_ingenuity-0.4.29.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
14
- python_eigen_ingenuity-0.4.29.dist-info/top_level.txt,sha256=N3esHxXM41zWhi8-bvfUn84i2Vl1Ry6RJtrrzEwpLcM,15
15
- python_eigen_ingenuity-0.4.29.dist-info/RECORD,,
13
+ python_eigen_ingenuity-0.4.30.dist-info/METADATA,sha256=pVrLcerfiRg839rO0eyL6XkxYn1E61PP_7XqA4z3DY8,14227
14
+ python_eigen_ingenuity-0.4.30.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
15
+ python_eigen_ingenuity-0.4.30.dist-info/top_level.txt,sha256=N3esHxXM41zWhi8-bvfUn84i2Vl1Ry6RJtrrzEwpLcM,15
16
+ python_eigen_ingenuity-0.4.30.dist-info/RECORD,,