python-eigen-ingenuity 0.4.37b6__tar.gz → 0.4.38b1__tar.gz
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.
- {python_eigen_ingenuity-0.4.37b6/python_eigen_ingenuity.egg-info → python_eigen_ingenuity-0.4.38b1}/PKG-INFO +2 -1
- python_eigen_ingenuity-0.4.38b1/eigeningenuity/historianmulti.py +361 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/util.py +89 -18
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1/python_eigen_ingenuity.egg-info}/PKG-INFO +2 -1
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/python_eigen_ingenuity.egg-info/requires.txt +1 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/requirements.txt +1 -0
- python_eigen_ingenuity-0.4.37b6/eigeningenuity/historianmulti.py +0 -672
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/MANIFEST.in +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/README.md +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/assetmodel.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/auth.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/core/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/elastic.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/events.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/historian.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/settings.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/smartdash.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/eigeningenuity/sql.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/assetmodelbuilder.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/assetmodelcsvwriter.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/assetmodelutilities.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/configmanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/connectors/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/connectors/boltconnector.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/connectors/dbconnectors.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/connectors/genericconnector.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/connectors/httpsconnector.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/csvcontentsmanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/csvwriter.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/fileanalyser.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/filemanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/messages.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/cypherfileprocessor.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/labelmanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/nodefileprocessor.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/propertymanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/relationshipfileprocessor.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/processors/relationshipmanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/queries/__init__.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/queries/cypherbuilder.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/queries/query.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/queries/typedefs.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/modelbuilder/src/versionmanager.py +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/pyproject.toml +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/python_eigen_ingenuity.egg-info/SOURCES.txt +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/python_eigen_ingenuity.egg-info/dependency_links.txt +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/python_eigen_ingenuity.egg-info/entry_points.txt +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/python_eigen_ingenuity.egg-info/top_level.txt +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/setup.cfg +0 -0
- {python_eigen_ingenuity-0.4.37b6 → python_eigen_ingenuity-0.4.38b1}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: python-eigen-ingenuity
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.38b1
|
|
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
|
|
@@ -18,6 +18,7 @@ Requires-Dist: keyring
|
|
|
18
18
|
Requires-Dist: pyarrow
|
|
19
19
|
Requires-Dist: neo4j>=5.17.0
|
|
20
20
|
Requires-Dist: requests>=2.31.0
|
|
21
|
+
Requires-Dist: dateparser
|
|
21
22
|
|
|
22
23
|
CONTENTS <!-- omit in toc -->
|
|
23
24
|
============
|
|
@@ -0,0 +1,361 @@
|
|
|
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.auth = auth
|
|
49
|
+
self.historian = ""
|
|
50
|
+
if historian:
|
|
51
|
+
self.historian = historian + "/"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _testConnection(self):
|
|
55
|
+
try:
|
|
56
|
+
status = requests.get(self.serverurl, verify=False).status_code
|
|
57
|
+
if status != 200:
|
|
58
|
+
raise ConnectionError(
|
|
59
|
+
"Invalid API Response from " + self.serverurl + ". Please check the url is correct and the instance is up.")
|
|
60
|
+
except (URLError, ConnectionError):
|
|
61
|
+
raise ConnectionError ("Failed to connect to ingenuity instance at " + self.serverurl + ". Please check the url is correct and the instance is up.")
|
|
62
|
+
|
|
63
|
+
def getCurrentDataPoints(self,tags: Union[str, list], output: str = "json"):
|
|
64
|
+
tags = force_list(tags)
|
|
65
|
+
body = {
|
|
66
|
+
"requests": {}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
for tag in tags:
|
|
70
|
+
if "/" not in tag:
|
|
71
|
+
tag = self.historian + tag
|
|
72
|
+
request = {
|
|
73
|
+
"type": "CURRENT_POINT",
|
|
74
|
+
"tag": tag,
|
|
75
|
+
"details": {}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
body["requests"][tag] = request
|
|
79
|
+
|
|
80
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
if output == "raw":
|
|
84
|
+
return response
|
|
85
|
+
elif output == "json":
|
|
86
|
+
if len(tags) == 1:
|
|
87
|
+
return items[tags[0]]
|
|
88
|
+
else:
|
|
89
|
+
return items
|
|
90
|
+
elif output == "string":
|
|
91
|
+
return json.dumps(items)
|
|
92
|
+
elif output == "df":
|
|
93
|
+
return multi_response_to_df(items)
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def getInterpolatedPoints(self, tags: Union[str, list], timestamps: Union[list, int, float, str, datetime],
|
|
98
|
+
output: str = "json"):
|
|
99
|
+
"""
|
|
100
|
+
Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
tags: A datatag (string), or list of datatags
|
|
104
|
+
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
|
|
105
|
+
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".
|
|
106
|
+
|
|
107
|
+
Returns:
|
|
108
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
109
|
+
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: When invalid Output Type is given
|
|
112
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
113
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
114
|
+
RunTimeError/HTTPError: No response from the API
|
|
115
|
+
"""
|
|
116
|
+
body = {
|
|
117
|
+
"requests": {}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
tags = force_list(tags)
|
|
121
|
+
timestamps = force_list(timestamps)
|
|
122
|
+
timestamps = [time_to_epoch_millis(timestamp) for timestamp in timestamps]
|
|
123
|
+
|
|
124
|
+
for tag in tags:
|
|
125
|
+
if "/" not in tag:
|
|
126
|
+
tag = self.historian + tag
|
|
127
|
+
for index, timestamp in enumerate(timestamps):
|
|
128
|
+
request = {
|
|
129
|
+
"type": "HISTORICAL_POINT",
|
|
130
|
+
"tag": tag,
|
|
131
|
+
"details": {
|
|
132
|
+
"at": timestamp
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
body["requests"][tag.split("/")[1] + "-" + str(index)] = request
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
140
|
+
items = merge_tags_from_response(response["results"])
|
|
141
|
+
|
|
142
|
+
return format_output(output,items,tags,timestamps)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def getInterpolatedRange(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
146
|
+
end: Union[int, float, str, datetime], count: int = 1000, output: str = "json"):
|
|
147
|
+
"""Return a specified number of interpolated datapoints between a start and end timestamp for one or more datatags
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
tags: A datatag, or list of datatags
|
|
151
|
+
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
152
|
+
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
153
|
+
count (Optional): Number of points to return, evenly spaced across the given time range. Defaults to 1000
|
|
154
|
+
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".
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
ValueError: When invalid Output Type is given
|
|
161
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
162
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
163
|
+
RunTimeError/HTTPError: No response from the API
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
body = {
|
|
167
|
+
"requests": {}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
tags = force_list(tags)
|
|
171
|
+
|
|
172
|
+
for tag in tags:
|
|
173
|
+
if "/" not in tag:
|
|
174
|
+
tag = self.historian + tag
|
|
175
|
+
request = {
|
|
176
|
+
"type": "INTERPOLATED_POINTS",
|
|
177
|
+
"tag": tag,
|
|
178
|
+
"details": {
|
|
179
|
+
"from": time_to_epoch_millis(start),
|
|
180
|
+
"to": time_to_epoch_millis(end),
|
|
181
|
+
"count": count
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
body["requests"][tag.split("/")[1]] = request
|
|
186
|
+
|
|
187
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
188
|
+
|
|
189
|
+
return format_output(output,response,tags)
|
|
190
|
+
|
|
191
|
+
def getRawDatapoints(self, tags: Union[str, list], start: Union[int, float, str, datetime],
|
|
192
|
+
end: Union[int, float, str, datetime], maxpoints: int = 1000, output: str = "json"):
|
|
193
|
+
"""Return up to a specified number of raw datapoints between a start and end timestamp for one or more datatags
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
tags: A datatag, or list of datatags
|
|
197
|
+
start: Start of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
198
|
+
end: End of the time range. Accepts epoch milliseconds, python datetime objects, or strings of format dd-mm-YYYYTHH:MM:DD
|
|
199
|
+
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
|
|
200
|
+
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".
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
Timestamps, values and statuses for each datapoint returned, the format is dependent on the output parameter
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
ValueError: When invalid Output Type is given
|
|
207
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
208
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
209
|
+
RunTimeError/HTTPError: No response from the API
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
body = {
|
|
213
|
+
"requests": {}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
tags = force_list(tags)
|
|
217
|
+
|
|
218
|
+
for tag in tags:
|
|
219
|
+
if "/" not in tag:
|
|
220
|
+
tag = self.historian + tag
|
|
221
|
+
request = {
|
|
222
|
+
"type": "RAW_POINTS",
|
|
223
|
+
"tag": tag,
|
|
224
|
+
"details": {
|
|
225
|
+
"from": time_to_epoch_millis(start),
|
|
226
|
+
"to": time_to_epoch_millis(end),
|
|
227
|
+
"maxPoints": maxpoints
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
body["requests"][tag.split("/")[1]] = request
|
|
232
|
+
|
|
233
|
+
response = _do_historian_multi_request(self.serverurl,body,self.auth)
|
|
234
|
+
|
|
235
|
+
return format_output(output,response,tags)
|
|
236
|
+
|
|
237
|
+
def writeToTag(self, tag:str, points: Union[dict, list]):
|
|
238
|
+
"""Write one or more points to a single tag
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
tag: A datatag
|
|
242
|
+
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
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
A dict with keys: success (bool) representing the success of the request. message (str) forwarded from the api.
|
|
246
|
+
|
|
247
|
+
Raises:
|
|
248
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
249
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
250
|
+
RunTimeError/HTTPError: No response from the API
|
|
251
|
+
"""
|
|
252
|
+
points = force_list(points)
|
|
253
|
+
if "/" not in tag:
|
|
254
|
+
tag = self.historian + tag
|
|
255
|
+
|
|
256
|
+
for point in points:
|
|
257
|
+
if "status" not in point.keys():
|
|
258
|
+
point['status'] = "OK"
|
|
259
|
+
point['timestamp'] = time_to_epoch_millis(point['timestamp'])
|
|
260
|
+
|
|
261
|
+
body = {
|
|
262
|
+
"points": {
|
|
263
|
+
tag: points
|
|
264
|
+
},
|
|
265
|
+
"createTags": True
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
269
|
+
|
|
270
|
+
if message == 'All points written!':
|
|
271
|
+
ret = {"success": True, "message": message}
|
|
272
|
+
else:
|
|
273
|
+
ret = {"success": False, "message": message}
|
|
274
|
+
|
|
275
|
+
return ret
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def writeToMultipleTags(self, data:Union[dict,list]):
|
|
279
|
+
"""Write one or more points to multiple tags
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
payloads: A dict (or list of dicts) of the form {tag1: [{"value": x, "timestamp": y}, ...], tag2: [...], ...}
|
|
283
|
+
|
|
284
|
+
Returns:
|
|
285
|
+
None
|
|
286
|
+
|
|
287
|
+
Raises:
|
|
288
|
+
URLError: When no Ingenuity instance could be found at given EigenServer, or no internet connection is available
|
|
289
|
+
RemoteServerException: When the provided historian could not be found, or the API response contains an error
|
|
290
|
+
RunTimeError/HTTPError: No response from the API
|
|
291
|
+
"""
|
|
292
|
+
data = force_list(data)
|
|
293
|
+
|
|
294
|
+
payload = {}
|
|
295
|
+
tags = []
|
|
296
|
+
|
|
297
|
+
for item in data:
|
|
298
|
+
if set(item.keys()).intersection(set(tags)):
|
|
299
|
+
for tag in set(item.keys()).intersection(set(tags)):
|
|
300
|
+
payload[tag] += item[tag]
|
|
301
|
+
item.pop(tag)
|
|
302
|
+
payload = payload | item
|
|
303
|
+
tags += item.keys()
|
|
304
|
+
|
|
305
|
+
for key in payload.keys():
|
|
306
|
+
for datapoint in payload[key]:
|
|
307
|
+
if "status" not in datapoint.keys():
|
|
308
|
+
datapoint['status'] = "OK"
|
|
309
|
+
datapoint['timestamp'] = time_to_epoch_millis(datapoint['timestamp'])
|
|
310
|
+
|
|
311
|
+
payload = update_keys(payload, self.historian)
|
|
312
|
+
|
|
313
|
+
body = {
|
|
314
|
+
"points": payload,
|
|
315
|
+
"createTags": True
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
message = _do_historian_multi_request(self.writeurl,body,self.auth,True)
|
|
319
|
+
|
|
320
|
+
if message == 'All points written!':
|
|
321
|
+
ret = {"success": True, "message": message}
|
|
322
|
+
else:
|
|
323
|
+
ret = {"success": False, "message": message}
|
|
324
|
+
|
|
325
|
+
return ret
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def createPoint(value:Union[int,float],timestamp:Union[int,str,datetime],status:str="OK"):
|
|
329
|
+
"""Quickly Create a dict of the format required to push data to historians
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
value: The value to be pushed
|
|
333
|
+
timestamp: The timestamp to assign the value to. Accepts formats of epoch milliseconds, python datetimes, and iso format datetime strings
|
|
334
|
+
status: (Optional) Indicates the quality of the data, accepts "OK" or "BAD". Defaults to "OK"
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
A structured dict for use in the WriteToTag method
|
|
338
|
+
"""
|
|
339
|
+
if status not in ["OK","BAD"]:
|
|
340
|
+
raise EigenException("Bad Status Parameter, must be 'OK' or 'BAD'")
|
|
341
|
+
return {"value": value, "timestamp": timestamp, "status": status}
|
|
342
|
+
|
|
343
|
+
def get_historian_multi(eigenserver: EigenServer = None, default_historian = None) -> HistorianMulti:
|
|
344
|
+
"""Instantiate a historian object for the given instance.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
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
|
|
348
|
+
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.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
An Object that can be used to query historian data.
|
|
352
|
+
|
|
353
|
+
"""
|
|
354
|
+
if eigenserver is None:
|
|
355
|
+
eigenserver = get_default_server()
|
|
356
|
+
elif type(eigenserver) == str:
|
|
357
|
+
eigenserver = EigenServer(eigenserver)
|
|
358
|
+
|
|
359
|
+
return HistorianMulti(eigenserver.getEigenServerUrl() + "historian" + "/", eigenserver.auth, default_historian)
|
|
360
|
+
|
|
361
|
+
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
|
|
2
2
|
import sys, os, json, time, requests, csv, logging
|
|
3
3
|
from datetime import datetime
|
|
4
|
+
from dateparser import parse
|
|
4
5
|
import pandas as pd
|
|
5
6
|
from collections import ChainMap
|
|
6
7
|
from urllib.parse import urlsplit, quote as urlquote
|
|
@@ -135,7 +136,7 @@ def time_to_epoch_millis(t):
|
|
|
135
136
|
if "ago" in t or "now" in t:
|
|
136
137
|
return t
|
|
137
138
|
else:
|
|
138
|
-
epochmillis =
|
|
139
|
+
epochmillis = parse(t)
|
|
139
140
|
else:
|
|
140
141
|
raise EigenException("Unknown time format " + str(type(t)))
|
|
141
142
|
return int(round(epochmillis))
|
|
@@ -152,25 +153,28 @@ def get_timestamp_string(t):
|
|
|
152
153
|
def get_timestamp(t):
|
|
153
154
|
if type(t) == str:
|
|
154
155
|
try:
|
|
155
|
-
|
|
156
|
-
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
156
|
+
epochmillis = parse(t)
|
|
157
157
|
except ValueError:
|
|
158
158
|
try:
|
|
159
|
-
pattern = '%Y-%m-%
|
|
159
|
+
pattern = '%Y-%m-%d %H:%M:%S.%f'
|
|
160
160
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
161
161
|
except ValueError:
|
|
162
162
|
try:
|
|
163
|
-
pattern = '%Y-%m-%
|
|
163
|
+
pattern = '%Y-%m-%dT%H:%M:%S.%f%z'
|
|
164
164
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
165
165
|
except ValueError:
|
|
166
166
|
try:
|
|
167
|
-
pattern = '%Y-%m-%d'
|
|
167
|
+
pattern = '%Y-%m-%d %H:%M:%S'
|
|
168
168
|
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
169
169
|
except ValueError:
|
|
170
170
|
try:
|
|
171
|
-
|
|
171
|
+
pattern = '%Y-%m-%d'
|
|
172
|
+
epochmillis = int(time.mktime(time.strptime(t, pattern)))
|
|
172
173
|
except ValueError:
|
|
173
|
-
|
|
174
|
+
try:
|
|
175
|
+
epochmillis = int(t)
|
|
176
|
+
except ValueError:
|
|
177
|
+
raise EigenException("Unknown time format " + str(type(t)))
|
|
174
178
|
|
|
175
179
|
else:
|
|
176
180
|
return(time_to_epoch_millis(t))
|
|
@@ -424,31 +428,98 @@ def csvWriter(data,historian,filepath,multi_csv,functionName,order=None,headers=
|
|
|
424
428
|
dict_writer.writerows(sortedList)
|
|
425
429
|
return True
|
|
426
430
|
|
|
431
|
+
def process_datapoint(data_dict,key,datapoint):
|
|
432
|
+
tag_name = key
|
|
433
|
+
timestamp = datapoint['timestamp']
|
|
434
|
+
value_data = datapoint['value']
|
|
435
|
+
|
|
436
|
+
# Check if timestamp is already a key in the dictionary
|
|
437
|
+
if timestamp not in data_dict:
|
|
438
|
+
data_dict[timestamp] = {}
|
|
439
|
+
|
|
440
|
+
# Add data to the dictionary
|
|
441
|
+
data_dict[timestamp][tag_name] = value_data
|
|
442
|
+
|
|
443
|
+
return data_dict
|
|
444
|
+
|
|
427
445
|
def multi_response_to_df(api_response):
|
|
428
446
|
data_dict = {}
|
|
429
447
|
|
|
430
448
|
# Iterate through the response
|
|
431
449
|
for key, value in api_response.items():
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
450
|
+
if "dataPoints" in value.keys():
|
|
451
|
+
for datapoint in value["dataPoints"]:
|
|
452
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
435
453
|
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
data_dict
|
|
439
|
-
|
|
440
|
-
# Add data to the dictionary
|
|
441
|
-
data_dict[timestamp][tag_name] = value_data
|
|
454
|
+
elif "dataPoint" in value.keys():
|
|
455
|
+
datapoint = value["dataPoint"]
|
|
456
|
+
data_dict = process_datapoint(data_dict,key,datapoint)
|
|
442
457
|
|
|
443
458
|
# Create DataFrame
|
|
444
|
-
df = pd.DataFrame(data_dict).T # Transpose the DataFrame
|
|
459
|
+
df = pd.DataFrame(data_dict,format="ISO8601").T # Transpose the DataFrame
|
|
445
460
|
|
|
446
461
|
# Convert timestamp index to datetime format
|
|
447
462
|
df.index = pd.to_datetime(df.index)
|
|
448
463
|
|
|
449
464
|
return df
|
|
450
465
|
|
|
466
|
+
def merge_tags_from_response(response):
|
|
467
|
+
merged_response = {}
|
|
468
|
+
|
|
469
|
+
for key, value in response.items():
|
|
470
|
+
# Extract the header by removing the suffix (e.g., '-0' or '-1')
|
|
471
|
+
header = key.rsplit('-', 1)[0]
|
|
472
|
+
|
|
473
|
+
# If the header is not already in the merged_response, initialize it
|
|
474
|
+
if header not in merged_response:
|
|
475
|
+
merged_response[header] = {'dataPoints': []}
|
|
451
476
|
|
|
477
|
+
# Append the dataPoint to the list of dataPoints under the header
|
|
478
|
+
merged_response[header]['dataPoints'].append(value['dataPoint'])
|
|
479
|
+
|
|
480
|
+
return merged_response
|
|
481
|
+
|
|
482
|
+
def update_keys(my_dict, historian):
|
|
483
|
+
# Use dictionary comprehension to update keys
|
|
484
|
+
return {
|
|
485
|
+
(historian + key if "/" not in key else key): value
|
|
486
|
+
for key, value in my_dict.items()
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
def _do_historian_multi_request(url,body,auth,write_request=False):
|
|
490
|
+
|
|
491
|
+
headers = {}
|
|
492
|
+
|
|
493
|
+
if settings._azure_tenant_id_ and settings._azure_client_id_ and settings._azure_auth_enabled_ and auth:
|
|
494
|
+
headers = _authenticate_azure_user('/'.join(url.split("/")[0:3]))
|
|
495
|
+
|
|
496
|
+
if settings._api_token_value_:
|
|
497
|
+
headers['X-Api-Key'] = settings._api_token_value_
|
|
498
|
+
|
|
499
|
+
resp = requests.post(url, json=body, verify=False, headers=headers).json()
|
|
500
|
+
|
|
501
|
+
if write_request:
|
|
502
|
+
return resp['message']
|
|
503
|
+
|
|
504
|
+
return resp
|
|
505
|
+
|
|
506
|
+
def format_output(output,response,tags,timestamps=False):
|
|
507
|
+
if not timestamps:
|
|
508
|
+
items = response['results']
|
|
509
|
+
|
|
510
|
+
if output == "raw":
|
|
511
|
+
return response
|
|
512
|
+
elif output == "json":
|
|
513
|
+
if len(tags) == 1 and (not timestamps or len(timestamps) == 1):
|
|
514
|
+
return items[tags[0]]
|
|
515
|
+
else:
|
|
516
|
+
return items
|
|
517
|
+
elif output == "string":
|
|
518
|
+
return json.dumps(items,indent=4)
|
|
519
|
+
elif output == "df":
|
|
520
|
+
return multi_response_to_df(items)
|
|
521
|
+
|
|
522
|
+
raise EigenException("Unrecognised Output Type. Must be one of ['raw','json','string','df']")
|
|
452
523
|
|
|
453
524
|
|
|
454
525
|
class EigenException (Exception): pass
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: python-eigen-ingenuity
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.38b1
|
|
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
|
|
@@ -18,6 +18,7 @@ Requires-Dist: keyring
|
|
|
18
18
|
Requires-Dist: pyarrow
|
|
19
19
|
Requires-Dist: neo4j>=5.17.0
|
|
20
20
|
Requires-Dist: requests>=2.31.0
|
|
21
|
+
Requires-Dist: dateparser
|
|
21
22
|
|
|
22
23
|
CONTENTS <!-- omit in toc -->
|
|
23
24
|
============
|