scadora 0.1.0__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.
- scadora/__init__.py +12 -0
- scadora/client.py +194 -0
- scadora-0.1.0.dist-info/METADATA +51 -0
- scadora-0.1.0.dist-info/RECORD +7 -0
- scadora-0.1.0.dist-info/WHEEL +5 -0
- scadora-0.1.0.dist-info/licenses/LICENSE +21 -0
- scadora-0.1.0.dist-info/top_level.txt +1 -0
scadora/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Scadora REST API client: read and write tags, query history and alarms.
|
|
2
|
+
|
|
3
|
+
from scadora import Scadora
|
|
4
|
+
scada = Scadora("https://scada-server:5101", token="sct_...", verify="scadora-server.cer")
|
|
5
|
+
print(scada.read("Tank1.Level"))
|
|
6
|
+
scada.write("Tank1.Setpoint", 42.5)
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .client import Scadora, ScadoraError, Tag, Sample
|
|
10
|
+
|
|
11
|
+
__all__ = ["Scadora", "ScadoraError", "Tag", "Sample"]
|
|
12
|
+
__version__ = "0.1.0"
|
scadora/client.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Scadora REST API client. Standard library only: works on any Python 3.8+ without extra packages."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import ssl
|
|
7
|
+
import urllib.error
|
|
8
|
+
import urllib.parse
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
12
|
+
from typing import Any, Dict, Iterable, List, Optional, Union
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ScadoraError(Exception):
|
|
16
|
+
"""Error returned by the server: no permission, unknown tag, device refused the write and so on."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, status: int, message: str):
|
|
19
|
+
super().__init__(f"{status}: {message}")
|
|
20
|
+
self.status = status
|
|
21
|
+
self.message = message
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Tag:
|
|
26
|
+
name: str
|
|
27
|
+
value: Any
|
|
28
|
+
quality: Optional[str]
|
|
29
|
+
timestamp: Optional[datetime]
|
|
30
|
+
table: Optional[str] = None
|
|
31
|
+
connection: Optional[str] = None
|
|
32
|
+
type: Optional[str] = None
|
|
33
|
+
unit: Optional[str] = None
|
|
34
|
+
comment: Optional[str] = None
|
|
35
|
+
writable: bool = False
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def good(self) -> bool:
|
|
39
|
+
"""The value is valid (quality Good)."""
|
|
40
|
+
return self.quality == "Good"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Sample:
|
|
45
|
+
time: datetime
|
|
46
|
+
value: Optional[float]
|
|
47
|
+
quality: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _time(text: Optional[str]) -> Optional[datetime]:
|
|
51
|
+
if not text:
|
|
52
|
+
return None
|
|
53
|
+
# .NET writes 7 fractional digits; Python before 3.11 accepts at most 6.
|
|
54
|
+
text = text.replace("Z", "+00:00")
|
|
55
|
+
if "." in text:
|
|
56
|
+
head, rest = text.split(".", 1)
|
|
57
|
+
digits = "".join(c for c in rest if c.isdigit())
|
|
58
|
+
tail = rest[len(digits):]
|
|
59
|
+
text = f"{head}.{digits[:6]}{tail}"
|
|
60
|
+
return datetime.fromisoformat(text)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _iso(value: datetime) -> str:
|
|
64
|
+
if value.tzinfo is None:
|
|
65
|
+
value = value.astimezone()
|
|
66
|
+
return value.isoformat()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Scadora:
|
|
70
|
+
"""Connection to a Scadora server's REST API (the web port, 5101 by default).
|
|
71
|
+
|
|
72
|
+
url -- server address, e.g. "https://scada-server:5101"
|
|
73
|
+
token -- API token (an administrator issues it in the editor: Project → Users and roles → API tokens)
|
|
74
|
+
verify -- TLS check: True (system trust store), False (no check — test benches only) or a path to the
|
|
75
|
+
server certificate (download it from https://scada-server:5101/scadora-server.cer)
|
|
76
|
+
check_hostname -- set False when you connect by an address that is not in the certificate
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, url: str, token: str, verify: Union[bool, str] = True, check_hostname: bool = True, timeout: float = 15):
|
|
80
|
+
self.url = url.rstrip("/")
|
|
81
|
+
self.token = token
|
|
82
|
+
self.timeout = timeout
|
|
83
|
+
self._context: Optional[ssl.SSLContext] = None
|
|
84
|
+
if self.url.startswith("https://"):
|
|
85
|
+
if verify is False:
|
|
86
|
+
context = ssl.create_default_context()
|
|
87
|
+
context.check_hostname = False
|
|
88
|
+
context.verify_mode = ssl.CERT_NONE
|
|
89
|
+
elif isinstance(verify, str):
|
|
90
|
+
context = ssl.create_default_context()
|
|
91
|
+
with open(verify, "rb") as f:
|
|
92
|
+
data = f.read()
|
|
93
|
+
# The server offers its certificate as .cer (DER); PEM works too.
|
|
94
|
+
if data.lstrip().startswith(b"-----BEGIN"):
|
|
95
|
+
context.load_verify_locations(cadata=data.decode("ascii"))
|
|
96
|
+
else:
|
|
97
|
+
context.load_verify_locations(cadata=data)
|
|
98
|
+
context.check_hostname = check_hostname
|
|
99
|
+
else:
|
|
100
|
+
context = ssl.create_default_context()
|
|
101
|
+
context.check_hostname = check_hostname
|
|
102
|
+
self._context = context
|
|
103
|
+
|
|
104
|
+
# --- requests ---------------------------------------------------------------------------------------------
|
|
105
|
+
|
|
106
|
+
def _request(self, method: str, path: str, body: Any = None, query: Optional[Dict[str, Any]] = None) -> Any:
|
|
107
|
+
url = self.url + path
|
|
108
|
+
if query:
|
|
109
|
+
clean = {k: v for k, v in query.items() if v is not None}
|
|
110
|
+
if clean:
|
|
111
|
+
url += "?" + urllib.parse.urlencode(clean)
|
|
112
|
+
data = None
|
|
113
|
+
headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/json"}
|
|
114
|
+
if body is not None:
|
|
115
|
+
data = json.dumps(body).encode("utf-8")
|
|
116
|
+
headers["Content-Type"] = "application/json"
|
|
117
|
+
request = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
118
|
+
try:
|
|
119
|
+
with urllib.request.urlopen(request, timeout=self.timeout, context=self._context) as response:
|
|
120
|
+
payload = response.read()
|
|
121
|
+
return json.loads(payload) if payload else None
|
|
122
|
+
except urllib.error.HTTPError as e:
|
|
123
|
+
message = e.reason
|
|
124
|
+
try:
|
|
125
|
+
problem = json.loads(e.read() or b"{}")
|
|
126
|
+
message = problem.get("detail") or problem.get("title") or message
|
|
127
|
+
except ValueError:
|
|
128
|
+
pass
|
|
129
|
+
if e.code == 401 and message == e.reason:
|
|
130
|
+
message = "No token, or the token is invalid, revoked or expired"
|
|
131
|
+
raise ScadoraError(e.code, str(message)) from None
|
|
132
|
+
|
|
133
|
+
@staticmethod
|
|
134
|
+
def _quote(name: str) -> str:
|
|
135
|
+
return urllib.parse.quote(name, safe="")
|
|
136
|
+
|
|
137
|
+
# --- API ----------------------------------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
def me(self) -> Dict[str, Any]:
|
|
140
|
+
"""Who the token belongs to and its permissions."""
|
|
141
|
+
return self._request("GET", "/api/v1/me")
|
|
142
|
+
|
|
143
|
+
def tags(self, filter: str = "*") -> List[Tag]:
|
|
144
|
+
"""Tags visible to the user, with current values. filter is a name mask: "Tank*", "Pump?.Run"."""
|
|
145
|
+
return [self._tag(t) for t in self._request("GET", "/api/v1/tags", query={"filter": filter})]
|
|
146
|
+
|
|
147
|
+
def tag(self, name: str) -> Tag:
|
|
148
|
+
"""One tag with its current value, quality and timestamp."""
|
|
149
|
+
return self._tag(self._request("GET", "/api/v1/tags/" + self._quote(name)))
|
|
150
|
+
|
|
151
|
+
def read(self, name: str) -> Any:
|
|
152
|
+
"""Current value of a tag."""
|
|
153
|
+
return self.tag(name).value
|
|
154
|
+
|
|
155
|
+
def read_many(self, names: Iterable[str]) -> Dict[str, Any]:
|
|
156
|
+
"""Current values of several tags in one request: {name: value}."""
|
|
157
|
+
names = list(names)
|
|
158
|
+
result = self._request("POST", "/api/v1/tags/read", {"names": names})
|
|
159
|
+
return {item["name"]: item["value"] for item in result}
|
|
160
|
+
|
|
161
|
+
def write(self, name: str, value: Union[bool, int, float, str]) -> None:
|
|
162
|
+
"""Write a value. Needs the Operate permission (parameters: Write parameters); goes to the audit log."""
|
|
163
|
+
self._request("PUT", "/api/v1/tags/" + self._quote(name), {"value": value})
|
|
164
|
+
|
|
165
|
+
def history(self, name: str, start: Optional[datetime] = None, end: Optional[datetime] = None,
|
|
166
|
+
hours: Optional[float] = None, max_points: int = 0) -> List[Sample]:
|
|
167
|
+
"""Archived values. Either start/end or hours back from now; max_points thins out long intervals."""
|
|
168
|
+
if hours is not None:
|
|
169
|
+
end = end or datetime.now(timezone.utc)
|
|
170
|
+
start = end - timedelta(hours=hours)
|
|
171
|
+
query = {
|
|
172
|
+
"from": _iso(start) if start else None,
|
|
173
|
+
"to": _iso(end) if end else None,
|
|
174
|
+
"maxPoints": max_points or None,
|
|
175
|
+
}
|
|
176
|
+
result = self._request("GET", "/api/v1/history/" + self._quote(name), query=query)
|
|
177
|
+
return [Sample(_time(s["time"]), s["value"], s["quality"]) for s in result]
|
|
178
|
+
|
|
179
|
+
def alarms(self, area: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
180
|
+
"""Active and unacknowledged alarms (optionally of one area)."""
|
|
181
|
+
return self._request("GET", "/api/v1/alarms", query={"area": area})
|
|
182
|
+
|
|
183
|
+
def acknowledge(self, names: Optional[Iterable[str]] = None, all: bool = False) -> int:
|
|
184
|
+
"""Acknowledge alarms by name, or all visible ones. Returns how many were acknowledged."""
|
|
185
|
+
body = {"names": list(names or []), "all": all}
|
|
186
|
+
return self._request("POST", "/api/v1/alarms/ack", body)["acknowledged"]
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def _tag(t: Dict[str, Any]) -> Tag:
|
|
190
|
+
return Tag(
|
|
191
|
+
name=t["name"], value=t.get("value"), quality=t.get("quality"), timestamp=_time(t.get("timestamp")),
|
|
192
|
+
table=t.get("table"), connection=t.get("connection"), type=t.get("type"), unit=t.get("unit"), comment=t.get("comment"),
|
|
193
|
+
writable=bool(t.get("writable", False)),
|
|
194
|
+
)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: scadora
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client for the Scadora SCADA REST API: read and write tags, query history and alarms
|
|
5
|
+
Author: Scadora
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://scadora.app
|
|
8
|
+
Project-URL: Documentation, https://scadora.app/docs/rest-api/
|
|
9
|
+
Project-URL: Issues, https://github.com/AnatoliiRavkov/scadora-releases/issues
|
|
10
|
+
Keywords: scada,hmi,industrial,automation,plc,opc,modbus,historian
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Intended Audience :: Manufacturing
|
|
14
|
+
Classifier: Topic :: System :: Monitoring
|
|
15
|
+
Requires-Python: >=3.8
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# scadora
|
|
21
|
+
|
|
22
|
+
Python client for the [Scadora](https://scadora.app) SCADA REST API: read and write tags, query history and alarms. Standard library only, Python 3.8+.
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
pip install scadora
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from scadora import Scadora
|
|
30
|
+
|
|
31
|
+
scada = Scadora("https://scada-server:5101", token="sct_...", verify="scadora-server.cer")
|
|
32
|
+
|
|
33
|
+
print(scada.read("Tank1.Level")) # current value
|
|
34
|
+
print(scada.read_many(["Tank1.Level", "Pump1.Run"]))
|
|
35
|
+
for tag in scada.tags("Tank*"): # values with quality and time
|
|
36
|
+
print(tag.name, tag.value, tag.unit, tag.good)
|
|
37
|
+
|
|
38
|
+
scada.write("Tank1.Setpoint", 42.5) # needs the Operate permission
|
|
39
|
+
|
|
40
|
+
for s in scada.history("Tank1.Level", hours=24, max_points=500):
|
|
41
|
+
print(s.time, s.value)
|
|
42
|
+
|
|
43
|
+
print(scada.alarms())
|
|
44
|
+
scada.acknowledge(["Tank1_High"])
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**Token.** An administrator issues API tokens in the Scadora editor: *Project → Users and roles → select a user → API tokens…*. A token has the permissions of its user, every write goes to the audit log, and a revoked token stops working at once.
|
|
48
|
+
|
|
49
|
+
**Certificate.** The server uses its own TLS certificate. Download it from `https://<server>:5101/scadora-server.cer` and pass the path as `verify`. If you connect by an address that is not in the certificate, add `check_hostname=False`. `verify=False` turns the check off — for test benches only.
|
|
50
|
+
|
|
51
|
+
API reference: `https://<server>:5101/api/v1/docs` on your server and [scadora.app/docs/rest-api](https://scadora.app/docs/rest-api/).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
scadora/__init__.py,sha256=0F-d216Oljxk9-XX4eAb8UTeEwcEmXCDfmkWI-DR5FI,418
|
|
2
|
+
scadora/client.py,sha256=PKT7a-Lon5T9MGlnb-uDFecSQA-6jDlBMlpx1viKVP0,8268
|
|
3
|
+
scadora-0.1.0.dist-info/licenses/LICENSE,sha256=gIWn9uv7_SNMGo0dRIZOM5UKpZ7khnpnAFAz_lK16xQ,1064
|
|
4
|
+
scadora-0.1.0.dist-info/METADATA,sha256=k0w-f8eZECAnIQ_ByShmLkNJo4MTcZYSusBK_-dPKB4,2281
|
|
5
|
+
scadora-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
scadora-0.1.0.dist-info/top_level.txt,sha256=0-zl8Soi6DQ6hiDi1DudbfJEg7BAP8llnSi5l6khcsM,8
|
|
7
|
+
scadora-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Scadora
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
scadora
|