pymscada 0.1.11__py3-none-any.whl → 0.1.11b2__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.
- pymscada/bus_client.py +23 -22
- pymscada/bus_server.py +28 -25
- pymscada/console.py +11 -14
- pymscada/demo/openweather.yaml +25 -0
- pymscada/demo/tags.yaml +3 -0
- pymscada/demo/wwwserver.yaml +0 -263
- pymscada/iodrivers/openweather.py +126 -0
- pymscada/main.py +41 -295
- pymscada/module_config.py +208 -0
- pymscada/protocol_constants.py +29 -39
- pymscada/validate.py +29 -26
- pymscada/www_server.py +4 -4
- {pymscada-0.1.11.dist-info → pymscada-0.1.11b2.dist-info}/METADATA +3 -3
- {pymscada-0.1.11.dist-info → pymscada-0.1.11b2.dist-info}/RECORD +17 -14
- {pymscada-0.1.11.dist-info → pymscada-0.1.11b2.dist-info}/WHEEL +1 -1
- {pymscada-0.1.11.dist-info → pymscada-0.1.11b2.dist-info}/entry_points.txt +0 -0
- {pymscada-0.1.11.dist-info → pymscada-0.1.11b2.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Poll OpenWeather current and forecast APIs."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import aiohttp
|
|
4
|
+
import logging
|
|
5
|
+
from time import time
|
|
6
|
+
from pymscada.bus_client import BusClient
|
|
7
|
+
from pymscada.periodic import Periodic
|
|
8
|
+
from pymscada.tag import Tag
|
|
9
|
+
|
|
10
|
+
class OpenWeatherClient:
|
|
11
|
+
"""Get weather data from OpenWeather Current and Forecast APIs."""
|
|
12
|
+
|
|
13
|
+
def __init__(self, bus_ip: str = '127.0.0.1', bus_port: int = 1324,
|
|
14
|
+
proxy: str = None, api: dict = {}, tags: dict = {}) -> None:
|
|
15
|
+
"""
|
|
16
|
+
Connect to bus on bus_ip:bus_port.
|
|
17
|
+
|
|
18
|
+
api dict should contain:
|
|
19
|
+
- api_key: OpenWeatherMap API key
|
|
20
|
+
- locations: dict of location names and coordinates
|
|
21
|
+
- times: list of hours ahead to fetch forecast data for
|
|
22
|
+
- units: optional units (standard, metric, imperial)
|
|
23
|
+
"""
|
|
24
|
+
self.busclient = None
|
|
25
|
+
if bus_ip is not None:
|
|
26
|
+
self.busclient = BusClient(bus_ip, bus_port, module='OpenWeather')
|
|
27
|
+
self.proxy = proxy
|
|
28
|
+
self.map_bus = id(self)
|
|
29
|
+
self.tags = {tagname: Tag(tagname, float) for tagname in tags}
|
|
30
|
+
self.api_key = api['api_key']
|
|
31
|
+
self.units = api.get('units', 'standard')
|
|
32
|
+
self.locations = api.get('locations', {})
|
|
33
|
+
self.parameters = api.get('parameters', {})
|
|
34
|
+
self.times = api.get('times', [3, 6, 12, 24, 48])
|
|
35
|
+
self.current_url = "https://api.openweathermap.org/data/2.5/weather"
|
|
36
|
+
self.forecast_url = "https://api.openweathermap.org/data/2.5/forecast"
|
|
37
|
+
self.queue = asyncio.Queue()
|
|
38
|
+
self.session = None
|
|
39
|
+
self.handle = None
|
|
40
|
+
self.periodic = None
|
|
41
|
+
|
|
42
|
+
def update_tags(self, location, data, suffix):
|
|
43
|
+
"""Update tags for forecast weather."""
|
|
44
|
+
for parameter in self.parameters:
|
|
45
|
+
tagname = f"{location}_{parameter}{suffix}"
|
|
46
|
+
if parameter == 'Temp':
|
|
47
|
+
value = data['main']['temp']
|
|
48
|
+
elif parameter == 'WindSpeed':
|
|
49
|
+
value = data['wind']['speed']
|
|
50
|
+
elif parameter == 'WindDir':
|
|
51
|
+
value = data['wind'].get('deg', 0)
|
|
52
|
+
elif parameter == 'Rain':
|
|
53
|
+
value = data.get('rain', {}).get('1h', 0)
|
|
54
|
+
try:
|
|
55
|
+
self.tags[tagname].value = value
|
|
56
|
+
except KeyError:
|
|
57
|
+
logging.warning(f'{tagname} not found setting weather value')
|
|
58
|
+
|
|
59
|
+
async def handle_response(self):
|
|
60
|
+
"""Handle responses from the API."""
|
|
61
|
+
while True:
|
|
62
|
+
location, data = await self.queue.get()
|
|
63
|
+
now = int(time())
|
|
64
|
+
if 'dt' in data:
|
|
65
|
+
self.update_tags(location, data, '')
|
|
66
|
+
elif 'list' in data:
|
|
67
|
+
for forecast in data['list']:
|
|
68
|
+
hours_ahead = int((forecast['dt'] - now) / 3600)
|
|
69
|
+
if hours_ahead not in self.times:
|
|
70
|
+
continue
|
|
71
|
+
suffix = f'_{hours_ahead:02d}'
|
|
72
|
+
self.update_tags(location, forecast, suffix)
|
|
73
|
+
|
|
74
|
+
async def fetch_current_data(self):
|
|
75
|
+
"""Fetch current weather data for all locations."""
|
|
76
|
+
if self.session is None:
|
|
77
|
+
self.session = aiohttp.ClientSession()
|
|
78
|
+
for location, coords in self.locations.items():
|
|
79
|
+
base_params = {'lat': coords['lat'], 'lon': coords['lon'],
|
|
80
|
+
'appid': self.api_key, 'units': self.units }
|
|
81
|
+
try:
|
|
82
|
+
async with self.session.get(self.current_url,
|
|
83
|
+
params=base_params, proxy=self.proxy) as resp:
|
|
84
|
+
if resp.status == 200:
|
|
85
|
+
self.queue.put_nowait((location, await resp.json()))
|
|
86
|
+
else:
|
|
87
|
+
logging.warning('OpenWeather current API error for '
|
|
88
|
+
f'{location}: {resp.status}')
|
|
89
|
+
except Exception as e:
|
|
90
|
+
logging.warning('OpenWeather current API error for '
|
|
91
|
+
f'{location}: {e}')
|
|
92
|
+
|
|
93
|
+
async def fetch_forecast_data(self):
|
|
94
|
+
"""Fetch forecast weather data for all locations."""
|
|
95
|
+
if self.session is None:
|
|
96
|
+
self.session = aiohttp.ClientSession()
|
|
97
|
+
for location, coords in self.locations.items():
|
|
98
|
+
base_params = {'lat': coords['lat'], 'lon': coords['lon'],
|
|
99
|
+
'appid': self.api_key, 'units': self.units }
|
|
100
|
+
try:
|
|
101
|
+
async with self.session.get(self.forecast_url,
|
|
102
|
+
params=base_params, proxy=self.proxy) as resp:
|
|
103
|
+
if resp.status == 200:
|
|
104
|
+
self.queue.put_nowait((location, await resp.json()))
|
|
105
|
+
else:
|
|
106
|
+
logging.warning('OpenWeather forecast API error '
|
|
107
|
+
f'for {location}: {resp.status}')
|
|
108
|
+
except Exception as e:
|
|
109
|
+
logging.warning('OpenWeather forecast API error for '
|
|
110
|
+
f'{location}: {e}')
|
|
111
|
+
|
|
112
|
+
async def poll(self):
|
|
113
|
+
"""Poll OpenWeather APIs every 10 minutes."""
|
|
114
|
+
now = int(time())
|
|
115
|
+
if now % 600 == 0: # Every 10 minutes
|
|
116
|
+
await self.fetch_current_data()
|
|
117
|
+
if now % 10800 == 60: # Every 3 hours, offset by 1 minute
|
|
118
|
+
await self.fetch_forecast_data()
|
|
119
|
+
|
|
120
|
+
async def start(self):
|
|
121
|
+
"""Start bus connection and API polling."""
|
|
122
|
+
if self.busclient is not None:
|
|
123
|
+
await self.busclient.start()
|
|
124
|
+
self.handle = asyncio.create_task(self.handle_response())
|
|
125
|
+
self.periodic = Periodic(self.poll, 1.0)
|
|
126
|
+
await self.periodic.start()
|
pymscada/main.py
CHANGED
|
@@ -1,311 +1,57 @@
|
|
|
1
1
|
"""Main server entry point."""
|
|
2
2
|
import argparse
|
|
3
3
|
import asyncio
|
|
4
|
-
from importlib.metadata import version
|
|
5
4
|
import logging
|
|
6
5
|
import sys
|
|
7
|
-
from
|
|
8
|
-
from pymscada.
|
|
9
|
-
from pymscada.config import Config
|
|
10
|
-
from pymscada.console import Console
|
|
11
|
-
from pymscada.files import Files
|
|
12
|
-
from pymscada.history import History
|
|
13
|
-
from pymscada.opnotes import OpNotes
|
|
14
|
-
from pymscada.www_server import WwwServer
|
|
15
|
-
from pymscada.iodrivers.accuweather import AccuWeatherClient
|
|
16
|
-
from pymscada.iodrivers.logix_client import LogixClient
|
|
17
|
-
from pymscada.iodrivers.modbus_client import ModbusClient
|
|
18
|
-
from pymscada.iodrivers.modbus_server import ModbusServer
|
|
19
|
-
from pymscada.iodrivers.ping_client import PingClient
|
|
20
|
-
from pymscada.iodrivers.snmp_client import SnmpClient
|
|
21
|
-
from pymscada.validate import validate
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
class Module():
|
|
25
|
-
"""Default Module."""
|
|
26
|
-
|
|
27
|
-
name = None
|
|
28
|
-
help = None
|
|
29
|
-
epilog = None
|
|
30
|
-
module = None
|
|
31
|
-
config = True
|
|
32
|
-
tags = True
|
|
33
|
-
sub = None
|
|
34
|
-
await_future = True
|
|
35
|
-
|
|
36
|
-
def __init__(self, subparser: argparse._SubParsersAction):
|
|
37
|
-
"""Add arguments common to all subparsers."""
|
|
38
|
-
self.sub = subparser.add_parser(
|
|
39
|
-
self.name, help=self.help, epilog=self.epilog)
|
|
40
|
-
self.sub.set_defaults(app=self)
|
|
41
|
-
if self.config:
|
|
42
|
-
self.sub.add_argument(
|
|
43
|
-
'--config', metavar='file', default=f'{self.name}.yaml',
|
|
44
|
-
help=f"Config file, default is '{self.name}.yaml'")
|
|
45
|
-
if self.tags:
|
|
46
|
-
self.sub.add_argument(
|
|
47
|
-
'--tags', metavar='file', default='tags.yaml',
|
|
48
|
-
help="Tags file, default is 'tags.yaml'")
|
|
49
|
-
self.sub.add_argument('--verbose', action='store_true',
|
|
50
|
-
help="Set level to logging.INFO")
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
class _Bus(Module):
|
|
54
|
-
"""Bus Server."""
|
|
55
|
-
|
|
56
|
-
name = 'bus'
|
|
57
|
-
help = 'run the message bus'
|
|
58
|
-
tags = False
|
|
59
|
-
|
|
60
|
-
def run_once(self, options):
|
|
61
|
-
"""Create the module."""
|
|
62
|
-
config = Config(options.config)
|
|
63
|
-
self.module = BusServer(**config)
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
class _WwwServer(Module):
|
|
67
|
-
"""WWW Server Module."""
|
|
68
|
-
|
|
69
|
-
name = 'wwwserver'
|
|
70
|
-
help = 'serve web pages'
|
|
71
|
-
|
|
72
|
-
def run_once(self, options):
|
|
73
|
-
"""Create the module."""
|
|
74
|
-
config = Config(options.config)
|
|
75
|
-
tag_info = dict(Config(options.tags))
|
|
76
|
-
self.module = WwwServer(tag_info=tag_info, **config)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
class _History(Module):
|
|
80
|
-
"""History Module."""
|
|
81
|
-
|
|
82
|
-
name = 'history'
|
|
83
|
-
help = 'collect and serve history'
|
|
84
|
-
|
|
85
|
-
def run_once(self, options):
|
|
86
|
-
"""Create the module."""
|
|
87
|
-
config = Config(options.config)
|
|
88
|
-
tag_info = dict(Config(options.tags))
|
|
89
|
-
self.module = History(tag_info=tag_info, **config)
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
class _Files(Module):
|
|
93
|
-
"""Files Module."""
|
|
94
|
-
|
|
95
|
-
name = 'files'
|
|
96
|
-
help = 'receive and send files'
|
|
97
|
-
tags = False
|
|
98
|
-
|
|
99
|
-
def run_once(self, options):
|
|
100
|
-
"""Create the module."""
|
|
101
|
-
config = Config(options.config)
|
|
102
|
-
self.module = Files(**config)
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
class _OpNotes(Module):
|
|
106
|
-
"""Operator Notes Module."""
|
|
107
|
-
|
|
108
|
-
name = 'opnotes'
|
|
109
|
-
help = 'present and manage operator notes'
|
|
110
|
-
tags = False
|
|
111
|
-
|
|
112
|
-
def run_once(self, options):
|
|
113
|
-
"""Create the module."""
|
|
114
|
-
config = Config(options.config)
|
|
115
|
-
self.module = OpNotes(**config)
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
class _Console(Module):
|
|
119
|
-
"""Bus Module."""
|
|
120
|
-
|
|
121
|
-
name = 'console'
|
|
122
|
-
help = 'interactive bus console'
|
|
123
|
-
config = False
|
|
124
|
-
await_future = False
|
|
125
|
-
|
|
126
|
-
def __init__(self, subparser: argparse._SubParsersAction):
|
|
127
|
-
super().__init__(subparser)
|
|
128
|
-
self.sub.add_argument(
|
|
129
|
-
'-p', '--port', action='store', type=int, default=1324,
|
|
130
|
-
help='connect to port (default: 1324)')
|
|
131
|
-
self.sub.add_argument(
|
|
132
|
-
'-i', '--ip', action='store', default='localhost',
|
|
133
|
-
help='connect to ip address (default: locahost)')
|
|
134
|
-
|
|
135
|
-
def run_once(self, options):
|
|
136
|
-
"""Create the module."""
|
|
137
|
-
tag_info = dict(Config(options.tags))
|
|
138
|
-
self.module = Console(options.ip, options.port, tag_info)
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
class _checkout(Module):
|
|
142
|
-
"""Bus Module."""
|
|
143
|
-
|
|
144
|
-
name = 'checkout'
|
|
145
|
-
help = 'create example config files'
|
|
146
|
-
epilog = """
|
|
147
|
-
To add to systemd `f="pymscada-bus" && cp config/$f.service
|
|
148
|
-
/lib/systemd/system && systemctl enable $f && systemctl start
|
|
149
|
-
$f`"""
|
|
150
|
-
config = False
|
|
151
|
-
tags = False
|
|
152
|
-
|
|
153
|
-
def __init__(self, subparser: argparse._SubParsersAction):
|
|
154
|
-
super().__init__(subparser)
|
|
155
|
-
self.sub.add_argument(
|
|
156
|
-
'--overwrite', action='store_true', default=False,
|
|
157
|
-
help='checkout may overwrite files, CARE!')
|
|
158
|
-
self.sub.add_argument(
|
|
159
|
-
'--diff', action='store_true', default=False,
|
|
160
|
-
help='compare default with existing')
|
|
161
|
-
|
|
162
|
-
def run_once(self, options):
|
|
163
|
-
"""Create the module."""
|
|
164
|
-
checkout(overwrite=options.overwrite, diff=options.diff)
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
class _validate(Module):
|
|
168
|
-
"""Bus Module."""
|
|
169
|
-
|
|
170
|
-
name = 'validate'
|
|
171
|
-
help = 'validate config files'
|
|
172
|
-
config = False
|
|
173
|
-
tags = False
|
|
174
|
-
|
|
175
|
-
def __init__(self, subparser: argparse._SubParsersAction):
|
|
176
|
-
super().__init__(subparser)
|
|
177
|
-
self.sub.add_argument(
|
|
178
|
-
'--path', metavar='file',
|
|
179
|
-
help='default is current working directory')
|
|
180
|
-
|
|
181
|
-
def run_once(self, options):
|
|
182
|
-
"""Create the module."""
|
|
183
|
-
r, e, p = validate(options.path)
|
|
184
|
-
if r:
|
|
185
|
-
print(f'Config files in {p} valid.')
|
|
186
|
-
else:
|
|
187
|
-
print(e)
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
class _AccuWeatherClient(Module):
|
|
191
|
-
"""Bus Module."""
|
|
192
|
-
|
|
193
|
-
name = 'accuweatherclient'
|
|
194
|
-
help = 'poll weather information'
|
|
195
|
-
|
|
196
|
-
def run_once(self, options):
|
|
197
|
-
"""Create the module."""
|
|
198
|
-
config = Config(options.config)
|
|
199
|
-
self.module = AccuWeatherClient(**config)
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
class _LogixClient(Module):
|
|
203
|
-
"""Bus Module."""
|
|
204
|
-
|
|
205
|
-
name = 'logixclient'
|
|
206
|
-
help = 'poll/write to logix devices'
|
|
207
|
-
|
|
208
|
-
def run_once(self, options):
|
|
209
|
-
"""Create the module."""
|
|
210
|
-
config = Config(options.config)
|
|
211
|
-
self.module = LogixClient(**config)
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
class _ModbusServer(Module):
|
|
215
|
-
"""Bus Module."""
|
|
216
|
-
|
|
217
|
-
name = 'modbusserver'
|
|
218
|
-
help = 'receive modbus messages'
|
|
219
|
-
epilog = """
|
|
220
|
-
Needs `setcap CAP_NET_BIND_SERVICE=+eip /usr/bin/python3.nn` to
|
|
221
|
-
bind to port 502."""
|
|
222
|
-
tags = False
|
|
223
|
-
|
|
224
|
-
def run_once(self, options):
|
|
225
|
-
"""Create the module."""
|
|
226
|
-
config = Config(options.config)
|
|
227
|
-
self.module = ModbusServer(**config)
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
class _ModbusClient(Module):
|
|
231
|
-
"""Bus Module."""
|
|
232
|
-
|
|
233
|
-
name = 'modbusclient'
|
|
234
|
-
help = 'poll/write to modbus devices'
|
|
235
|
-
tags = False
|
|
236
|
-
|
|
237
|
-
def run_once(self, options):
|
|
238
|
-
"""Create the module."""
|
|
239
|
-
config = Config(options.config)
|
|
240
|
-
self.module = ModbusClient(**config)
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
class _PingClient(Module):
|
|
244
|
-
"""Bus Module."""
|
|
245
|
-
|
|
246
|
-
name = 'ping'
|
|
247
|
-
help = 'ping a list of addresses, return time'
|
|
248
|
-
epilog = """
|
|
249
|
-
Needs `setcap CAP_NET_RAW+ep /usr/bin/python3.nn` to open SOCK_RAW
|
|
250
|
-
"""
|
|
251
|
-
tags = False
|
|
252
|
-
|
|
253
|
-
def run_once(self, options):
|
|
254
|
-
"""Create the module."""
|
|
255
|
-
if sys.platform.startswith("win"):
|
|
256
|
-
asyncio.set_event_loop_policy(
|
|
257
|
-
asyncio.WindowsSelectorEventLoopPolicy())
|
|
258
|
-
config = Config(options.config)
|
|
259
|
-
self.module = PingClient(**config)
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
class _SnmpClient(Module):
|
|
263
|
-
"""Bus Module."""
|
|
264
|
-
|
|
265
|
-
name = 'snmpclient'
|
|
266
|
-
help = 'poll snmp oids'
|
|
267
|
-
tags = False
|
|
268
|
-
|
|
269
|
-
def run_once(self, options):
|
|
270
|
-
"""Create the module."""
|
|
271
|
-
config = Config(options.config)
|
|
272
|
-
self.module = SnmpClient(**config)
|
|
6
|
+
from importlib.metadata import version
|
|
7
|
+
from pymscada.module_config import ModuleFactory
|
|
273
8
|
|
|
274
9
|
|
|
275
|
-
def args(
|
|
10
|
+
def args():
|
|
276
11
|
"""Read commandline arguments."""
|
|
277
12
|
parser = argparse.ArgumentParser(
|
|
278
13
|
prog='pymscada',
|
|
279
14
|
description='Connect IO, logic, applications, and webpage UI',
|
|
280
|
-
epilog=f'Python Mobile SCADA {
|
|
15
|
+
epilog=f'Python Mobile SCADA {version("pymscada")}'
|
|
281
16
|
)
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
_Files(s)
|
|
287
|
-
_OpNotes(s)
|
|
288
|
-
_Console(s)
|
|
289
|
-
_checkout(s)
|
|
290
|
-
_validate(s)
|
|
291
|
-
_AccuWeatherClient(s)
|
|
292
|
-
_LogixClient(s)
|
|
293
|
-
_ModbusServer(s)
|
|
294
|
-
_ModbusClient(s)
|
|
295
|
-
_PingClient(s)
|
|
296
|
-
_SnmpClient(s)
|
|
17
|
+
factory = ModuleFactory()
|
|
18
|
+
subparsers = parser.add_subparsers(title='module', dest='module_name')
|
|
19
|
+
for _, module_def in factory.modules.items():
|
|
20
|
+
factory.add_module_parser(subparsers, module_def)
|
|
297
21
|
return parser.parse_args()
|
|
298
22
|
|
|
299
23
|
|
|
300
24
|
async def run():
|
|
301
|
-
"""Run
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
25
|
+
"""Run the selected module."""
|
|
26
|
+
options = args()
|
|
27
|
+
if not options.module_name:
|
|
28
|
+
print("Error: Please specify a module to run")
|
|
29
|
+
sys.exit(1)
|
|
30
|
+
root_logger = logging.getLogger()
|
|
31
|
+
handler = logging.StreamHandler()
|
|
32
|
+
formatter = logging.Formatter('%(levelname)s:pymscada: %(message)s')
|
|
33
|
+
handler.setFormatter(formatter)
|
|
34
|
+
root_logger.handlers.clear() # Remove any existing handlers
|
|
35
|
+
root_logger.addHandler(handler)
|
|
36
|
+
root_logger.setLevel(logging.INFO)
|
|
37
|
+
logging.info(f'Python Mobile SCADA {version("pymscada")} starting '
|
|
38
|
+
f'{options.module_name}')
|
|
39
|
+
if not options.verbose:
|
|
40
|
+
root_logger.setLevel(logging.WARNING)
|
|
41
|
+
factory = ModuleFactory()
|
|
42
|
+
module = factory.create_module(options.module_name, options)
|
|
43
|
+
if module is not None:
|
|
44
|
+
if hasattr(module, 'start'):
|
|
45
|
+
await module.start()
|
|
46
|
+
if options.module_name in factory.modules:
|
|
47
|
+
module_def = factory.modules[options.module_name]
|
|
48
|
+
if module_def.await_future:
|
|
49
|
+
await asyncio.get_event_loop().create_future()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main():
|
|
53
|
+
"""Entry point."""
|
|
54
|
+
asyncio.run(run())
|
|
55
|
+
|
|
56
|
+
if __name__ == '__main__':
|
|
57
|
+
main()
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Module configuration and factory system."""
|
|
2
|
+
from typing import Any, Optional, Type
|
|
3
|
+
import argparse
|
|
4
|
+
from importlib.metadata import version
|
|
5
|
+
import logging
|
|
6
|
+
from pymscada.config import Config
|
|
7
|
+
from pymscada.console import Console
|
|
8
|
+
|
|
9
|
+
class ModuleArgument:
|
|
10
|
+
def __init__(self, args: tuple[str, ...], kwargs: dict[str, Any]):
|
|
11
|
+
self.args = args
|
|
12
|
+
self.kwargs = kwargs
|
|
13
|
+
|
|
14
|
+
class ModuleDefinition:
|
|
15
|
+
"""Defines a module's configuration and behavior."""
|
|
16
|
+
def __init__(self, name: str, help: str, module_class: Type[Any], *,
|
|
17
|
+
config: bool = True, tags: bool = True,
|
|
18
|
+
epilog: Optional[str] = None,
|
|
19
|
+
extra_args: list[ModuleArgument] = None,
|
|
20
|
+
await_future: bool = True):
|
|
21
|
+
self.name = name
|
|
22
|
+
self.help = help
|
|
23
|
+
self.module_class = module_class
|
|
24
|
+
self.config = config
|
|
25
|
+
self.tags = tags
|
|
26
|
+
self.epilog = epilog
|
|
27
|
+
self.extra_args = extra_args
|
|
28
|
+
self.await_future = await_future
|
|
29
|
+
|
|
30
|
+
def create_module_registry():
|
|
31
|
+
"""Create the central module registry with lazy imports."""
|
|
32
|
+
return [
|
|
33
|
+
ModuleDefinition(
|
|
34
|
+
name='bus',
|
|
35
|
+
help='run the message bus',
|
|
36
|
+
module_class='pymscada.bus_server:BusServer',
|
|
37
|
+
tags=False
|
|
38
|
+
),
|
|
39
|
+
ModuleDefinition(
|
|
40
|
+
name='wwwserver',
|
|
41
|
+
help='serve web pages',
|
|
42
|
+
module_class='pymscada.www_server:WwwServer'
|
|
43
|
+
),
|
|
44
|
+
ModuleDefinition(
|
|
45
|
+
name='history',
|
|
46
|
+
help='save tag changes to database',
|
|
47
|
+
module_class='pymscada.history:History'
|
|
48
|
+
),
|
|
49
|
+
ModuleDefinition(
|
|
50
|
+
name='files',
|
|
51
|
+
help='serve files',
|
|
52
|
+
module_class='pymscada.files:Files'
|
|
53
|
+
),
|
|
54
|
+
ModuleDefinition(
|
|
55
|
+
name='opnotes',
|
|
56
|
+
help='operator notes',
|
|
57
|
+
module_class='pymscada.opnotes:OpNotes'
|
|
58
|
+
),
|
|
59
|
+
ModuleDefinition(
|
|
60
|
+
name='validate',
|
|
61
|
+
help='validate config files',
|
|
62
|
+
module_class='pymscada.validate:validate',
|
|
63
|
+
config=False,
|
|
64
|
+
tags=False,
|
|
65
|
+
extra_args=[
|
|
66
|
+
ModuleArgument(
|
|
67
|
+
('--path',),
|
|
68
|
+
{'metavar': 'file', 'help': 'default is current working directory'}
|
|
69
|
+
)
|
|
70
|
+
]
|
|
71
|
+
),
|
|
72
|
+
ModuleDefinition(
|
|
73
|
+
name='checkout',
|
|
74
|
+
help='create example config files',
|
|
75
|
+
module_class='pymscada.checkout:checkout',
|
|
76
|
+
config=False,
|
|
77
|
+
tags=False,
|
|
78
|
+
epilog="""To add to systemd `f="pymscada-bus" && cp config/$f.service
|
|
79
|
+
/lib/systemd/system && systemctl enable $f && systemctl start $f`""",
|
|
80
|
+
extra_args=[
|
|
81
|
+
ModuleArgument(
|
|
82
|
+
('--overwrite',),
|
|
83
|
+
{'action': 'store_true', 'default': False,
|
|
84
|
+
'help': 'checkout may overwrite files, CARE!'}
|
|
85
|
+
),
|
|
86
|
+
ModuleArgument(
|
|
87
|
+
('--diff',),
|
|
88
|
+
{'action': 'store_true', 'default': False,
|
|
89
|
+
'help': 'compare default with existing'}
|
|
90
|
+
)
|
|
91
|
+
]
|
|
92
|
+
),
|
|
93
|
+
ModuleDefinition(
|
|
94
|
+
name='accuweatherclient',
|
|
95
|
+
help='poll weather information',
|
|
96
|
+
module_class='pymscada.iodrivers.accuweather:AccuWeatherClient'
|
|
97
|
+
),
|
|
98
|
+
ModuleDefinition(
|
|
99
|
+
name='logixclient',
|
|
100
|
+
help='poll/write to logix devices',
|
|
101
|
+
module_class='pymscada.iodrivers.logix_client:LogixClient'
|
|
102
|
+
),
|
|
103
|
+
ModuleDefinition(
|
|
104
|
+
name='modbusclient',
|
|
105
|
+
help='poll/write modbus devices',
|
|
106
|
+
module_class='pymscada.iodrivers.modbus_client:ModbusClient'
|
|
107
|
+
),
|
|
108
|
+
ModuleDefinition(
|
|
109
|
+
name='modbusserver',
|
|
110
|
+
help='serve modbus devices',
|
|
111
|
+
module_class='pymscada.iodrivers.modbus_server:ModbusServer'
|
|
112
|
+
),
|
|
113
|
+
ModuleDefinition(
|
|
114
|
+
name='openweatherclient',
|
|
115
|
+
help='poll OpenWeather current and forecast data',
|
|
116
|
+
module_class='pymscada.iodrivers.openweather:OpenWeatherClient'
|
|
117
|
+
),
|
|
118
|
+
ModuleDefinition(
|
|
119
|
+
name='pingclient',
|
|
120
|
+
help='ping network devices',
|
|
121
|
+
module_class='pymscada.iodrivers.ping_client:PingClient'
|
|
122
|
+
),
|
|
123
|
+
ModuleDefinition(
|
|
124
|
+
name='snmpclient',
|
|
125
|
+
help='poll SNMP devices',
|
|
126
|
+
module_class='pymscada.iodrivers.snmp_client:SnmpClient'
|
|
127
|
+
),
|
|
128
|
+
ModuleDefinition(
|
|
129
|
+
name='console',
|
|
130
|
+
help='interactive bus console',
|
|
131
|
+
module_class='pymscada.console:Console',
|
|
132
|
+
config=False,
|
|
133
|
+
await_future=False,
|
|
134
|
+
extra_args=[
|
|
135
|
+
ModuleArgument(
|
|
136
|
+
('-p', '--port'),
|
|
137
|
+
{'action': 'store', 'type': int, 'default': 1324,
|
|
138
|
+
'help': 'connect to port (default: 1324)'}
|
|
139
|
+
),
|
|
140
|
+
ModuleArgument(
|
|
141
|
+
('-i', '--ip'),
|
|
142
|
+
{'action': 'store', 'default': 'localhost',
|
|
143
|
+
'help': 'connect to ip address (default: localhost)'}
|
|
144
|
+
)
|
|
145
|
+
]
|
|
146
|
+
),
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
class ModuleFactory:
|
|
150
|
+
"""Creates and manages module instances."""
|
|
151
|
+
|
|
152
|
+
def __init__(self):
|
|
153
|
+
self.modules = {m.name: m for m in create_module_registry()}
|
|
154
|
+
|
|
155
|
+
def add_module_parser(self, subparser: argparse._SubParsersAction,
|
|
156
|
+
module_def: ModuleDefinition) -> argparse.ArgumentParser:
|
|
157
|
+
"""Add a parser for a module with its arguments."""
|
|
158
|
+
parser = subparser.add_parser(
|
|
159
|
+
module_def.name,
|
|
160
|
+
help=module_def.help,
|
|
161
|
+
epilog=module_def.epilog
|
|
162
|
+
)
|
|
163
|
+
if module_def.config:
|
|
164
|
+
parser.add_argument(
|
|
165
|
+
'--config',
|
|
166
|
+
metavar='file',
|
|
167
|
+
default=f'{module_def.name}.yaml',
|
|
168
|
+
help=f"Config file, default is '{module_def.name}.yaml'"
|
|
169
|
+
)
|
|
170
|
+
if module_def.tags:
|
|
171
|
+
parser.add_argument(
|
|
172
|
+
'--tags',
|
|
173
|
+
metavar='file',
|
|
174
|
+
default='tags.yaml',
|
|
175
|
+
help="Tags file, default is 'tags.yaml'"
|
|
176
|
+
)
|
|
177
|
+
parser.add_argument(
|
|
178
|
+
'--verbose',
|
|
179
|
+
action='store_true',
|
|
180
|
+
help="Set level to logging.INFO"
|
|
181
|
+
)
|
|
182
|
+
if module_def.extra_args:
|
|
183
|
+
for arg in module_def.extra_args:
|
|
184
|
+
parser.add_argument(*arg.args, **arg.kwargs)
|
|
185
|
+
return parser
|
|
186
|
+
|
|
187
|
+
def create_module(self, module_name: str, options: argparse.Namespace):
|
|
188
|
+
"""Create a module instance based on configuration and options."""
|
|
189
|
+
module_def = self.modules[module_name]
|
|
190
|
+
logging.info(f'Python Mobile SCADA {version("pymscada")} '
|
|
191
|
+
f'starting {module_def.name}')
|
|
192
|
+
# Import the module class only when needed
|
|
193
|
+
if isinstance(module_def.module_class, str):
|
|
194
|
+
module_path, class_name = module_def.module_class.split(':')
|
|
195
|
+
module = __import__(module_path, fromlist=[class_name])
|
|
196
|
+
actual_class = getattr(module, class_name)
|
|
197
|
+
else:
|
|
198
|
+
actual_class = module_def.module_class
|
|
199
|
+
|
|
200
|
+
kwargs = {}
|
|
201
|
+
if module_def.config:
|
|
202
|
+
kwargs.update(Config(options.config))
|
|
203
|
+
if module_def.tags:
|
|
204
|
+
kwargs['tag_info'] = dict(Config(options.tags))
|
|
205
|
+
if module_name == 'console':
|
|
206
|
+
return Console(options.ip, options.port,
|
|
207
|
+
kwargs.get('tag_info',{}))
|
|
208
|
+
return actual_class(**kwargs)
|