-
Notifications
You must be signed in to change notification settings - Fork 880
/
sql_datastore.py
181 lines (159 loc) · 6.45 KB
/
sql_datastore.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""Datastore using SQL."""
# pylint: disable=missing-type-doc
try:
import sqlalchemy
import sqlalchemy.types as sqltypes
from sqlalchemy.pool import StaticPool
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.sql import and_
from sqlalchemy.sql.expression import bindparam
except ImportError:
pass
from pymodbus.datastore import ModbusBaseSlaveContext
from pymodbus.logging import Log
# --------------------------------------------------------------------------- #
# Context
# --------------------------------------------------------------------------- #
class SqlSlaveContext(ModbusBaseSlaveContext):
"""This creates a modbus data model with each data access in its a block."""
def __init__(self, *_args, **kwargs):
"""Initialize the datastores.
:param kwargs: Each element is a ModbusDataBlock
"""
self._engine = None
self._metadata = None
self._table = None
self._connection = None
self.table = kwargs.get("table", "pymodbus")
self.database = kwargs.get("database", "sqlite:///:memory:")
self._db_create(self.table, self.database)
def __str__(self):
"""Return a string representation of the context.
:returns: A string representation of the context
"""
return "Modbus Slave Context"
def reset(self):
"""Reset all the datastores to their default values."""
self._metadata.drop_all(None)
self._db_create(self.table, self.database)
def validate(self, fc, address, count=1):
"""Validate the request to make sure it is in range.
:param fc: The function we are working with
:param address: The starting address
:param count: The number of values to test
:returns: True if the request in within range, False otherwise
"""
address = address + 1 # section 4.4 of specification
Log.debug("validate[{}] {}:{}", fc, address, count)
return self._validate(self.decode(fc), address, count)
def getValues(self, fc, address, count=1):
"""Get `count` values from datastore.
:param fc: The function we are working with
:param address: The starting address
:param count: The number of values to retrieve
:returns: The requested values from a:a+c
"""
address = address + 1 # section 4.4 of specification
Log.debug("get-values[{}] {}:{}", fc, address, count)
return self._get(self.decode(fc), address, count)
def setValues(self, fc, address, values, update=True):
"""Set the datastore with the supplied values.
:param fc: The function we are working with
:param address: The starting address
:param values: The new values to be set
:param update: Update existing register in the db
"""
address = address + 1 # section 4.4 of specification
Log.debug("set-values[{}] {}:{}", fc, address, len(values))
if update:
self._update(self.decode(fc), address, values)
else:
self._set(self.decode(fc), address, values)
# ----------------------------------------------------------------------- #
# Sqlite Helper Methods
# ----------------------------------------------------------------------- #
def _db_create(self, table, database):
"""Initialize the database and handles.
:param table: The table name to create
:param database: The database uri to use
"""
self._engine = sqlalchemy.create_engine(
database,
echo=False,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
self._metadata = sqlalchemy.MetaData(self._engine)
self._table = sqlalchemy.Table(
table,
self._metadata,
sqlalchemy.Column("type", sqltypes.String(1)),
sqlalchemy.Column("index", sqltypes.Integer),
sqlalchemy.Column("value", sqltypes.Integer),
UniqueConstraint("type", "index", name="key"),
)
self._table.create(self._engine)
self._connection = self._engine.connect()
def _get(self, sqltype, offset, count):
"""Get."""
query = self._table.select(
and_(
self._table.c.type == sqltype,
self._table.c.index >= offset,
self._table.c.index <= offset + count - 1,
)
)
query = query.order_by(self._table.c.index.asc())
result = self._connection.execute(query).fetchall()
return [row.value for row in result]
def _build_set(self, sqltype, offset, values, prefix=""):
"""Generate the sql update context."""
result = []
for index, value in enumerate(values):
result.append(
{
prefix + "type": sqltype,
prefix + "index": offset + index,
"value": value,
}
)
return result
def _check(self, sqltype, offset, _values):
"""Check."""
result = self._get(sqltype, offset, count=1)
return (
False # pylint: disable=simplifiable-if-expression
if len(result) > 0
else True
)
def _set(self, sqltype, offset, values):
"""Set."""
if self._check(sqltype, offset, values):
context = self._build_set(sqltype, offset, values)
query = self._table.insert()
result = self._connection.execute(query, context)
return result.rowcount == len(values)
return False
def _update(self, sqltype, offset, values):
"""Update."""
context = self._build_set(sqltype, offset, values, prefix="x_")
query = self._table.update().values(value="value")
query = query.where(
and_(
self._table.c.type == bindparam("x_type"),
self._table.c.index == bindparam("x_index"),
)
)
result = self._connection.execute(query, context)
return result.rowcount == len(values)
def _validate(self, sqltype, offset, count):
"""Validate."""
query = self._table.select(
and_(
self._table.c.type == sqltype,
self._table.c.index >= offset,
self._table.c.index <= offset + count - 1,
)
)
result = self._connection.execute(query).fetchall()
return len(result) == count