-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodbus_worker.py
40 lines (36 loc) · 1.21 KB
/
modbus_worker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from PyQt5.QtCore import QObject, pyqtSignal
import asyncio
from modbus_client import ModbusScanner
import json
class ModbusWorker(QObject):
finished = pyqtSignal(dict)
error = pyqtSignal(str)
def __init__(self, connection_params: dict):
super().__init__()
self.connection_params = connection_params
self.scanner = ModbusScanner(
host=self.connection_params['ip'],
port=self.connection_params.get('port', 502),
unit_id=self.connection_params.get('unit_id', 1)
)
async def run_async(self):
"""
Asynchronously connect to the Modbus server and scan registers.
"""
try:
data = await self.scanner.scan_registers()
self.finished.emit(data)
except Exception as e:
self.error.emit(f"Failed to connect or scan registers: {e}")
finally:
self.scanner.close()
def run(self):
"""
Wrapper to execute the asynchronous run in the asyncio event loop.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self.run_async())
finally:
loop.close()