forked from greentangerine/ME3000
-
Notifications
You must be signed in to change notification settings - Fork 0
/
me3000.py
executable file
·349 lines (278 loc) · 10.4 KB
/
me3000.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python
import struct
from serial import Serial, PARITY_NONE
import socket
import configparser
#from umodbus.client.serial import tcp
import umodbus.client.tcp as tcp
from umodbus.functions import function_code_to_function_map, ModbusFunction
def MyConfiguration():
file = 'agile.cfg'
parser = configparser.ConfigParser()
parser.optionxform = str # make option names case sensitive
found = parser.read(file)
if not found:
raise ValueError('No config file found!')
return parser
cfg = MyConfiguration()
class ME3000:
# some constants from the Passive protocol
DISCHARGE=0x0101
CHARGE=0x0102
AUTO=0x0103
STANDBY = 0x0100
STANDBY_VAL = 0x5555
ME_HOLDING=0x0200
NUM_HOLDING=69
# specific holding registers
ME_STATE=0x0200
BATTPCT=0x0210
ME_INPUT=0x10B0
NUM_INPUT=13
INV_STATES = ("WAIT", "CHECK CHARGE", "CHARGE", "CHECK DISCHARGE",
"DISCHARGE", "EPS", "FAULT", "PERM FAULT")
port_id = None
slave_id = None
def __init__(self, slave):
# self.port_id = port
self.slave_id = slave
self.modbus_tcp = self.get_tcp()
def connect(self):
if self.modbus_tcp is not None:
self.modbus_tcp = self.get_tcp()
def get_tcp(self):
""" Return sock instance, ready to use for TCP."""
tcp_ = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
ip_ = cfg['sofar']['ip']
port_ = int (cfg['sofar']['port'])
try:
tcp_.connect ((ip_, port_))
except Exception as error:
print('get_tcp error: {}'.format(error))
return tcp_
def disconnect(self):
if self.modbus_tcp is not None:
self.close_tcp_port()
def close_tcp_port(self):
self.modbus_tcp.close()
self.modbus_tcp = None
def set_auto(self):
""" Switch inverter to AUTO."""
ret_status = True
message = write_passive_register(slave_id=self.slave_id,
address=self.AUTO,
value=0)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def set_charge(self, charge=3000):
""" Set charge value."""
ret_status = True
message = write_passive_register(slave_id=self.slave_id,
address=self.CHARGE,
value=charge)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def set_discharge(self, discharge=3000):
""" Set discharge value."""
ret_status = True
message = write_passive_register(slave_id=self.slave_id,
address=self.DISCHARGE,
value=discharge)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def read_holding(self):
""" Read all the holding registers from inverter."""
ret_status = True
message = tcp.read_holding_registers(slave_id=self.slave_id,
starting_address=self.ME_HOLDING,
quantity=self.NUM_HOLDING)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def read_input(self):
""" Read the inverter's input registers."""
ret_status = True
message = tcp.read_input_registers(slave_id=self.slave_id,
starting_address=self.ME_INPUT,
quantity=self.NUM_INPUT)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def get_inverter_state(self):
""" Return the inverter state."""
ret_status = True
message = tcp.read_holding_registers(slave_id=self.slave_id,
starting_address=self.ME_STATE,
quantity=1)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = [-1]
return ret_status, response[0], self.INV_STATES[response[0]]
def get_battery_percentage(self):
""" Return the current charge percentage of the batteries."""
ret_status = True
message = tcp.read_holding_registers(slave_id=self.slave_id,
starting_address=self.BATTPCT,
quantity=1)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = [-1]
return ret_status, response[0]
def set_standby(self):
""" Switch inverter to STANDBY."""
ret_status = True
message = write_passive_register(slave_id=self.slave_id,
address=self.STANDBY,
value=self.STANDBY_VAL)
try:
response = tcp.send_message(message, self.modbus_tcp)
except:
ret_status = False
response = 0
return ret_status, response
def write_passive_register(slave_id, address, value):
""" Return ADU for Modbus extended function code 66: Write Passive Register.
:param slave_id: Number of slave.
:return: Byte array with ADU.
"""
function = WritePassiveRegister()
function._address = address
function._value = value
return tcp._create_request_adu(slave_id, function.request_pdu)
# SoFar ME30000 Passive Mode
WRITE_PASSIVE_REGISTER = 66
class WritePassiveRegister(ModbusFunction):
""" Implement SoFar Modbus function code 66.
This function code is used to write a single holding register in a
remote device.
The Request PDU specifies the address of the register to
be written.
The response is consists of the slave id, function code, byte count
and status bytes.
The request PDU with function code 66 must be 5 bytes:
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Address 2
Value 2
================ ===============
The PDU can unpacked to this:
..
Note: the backslash in the bytes below are escaped using an extra back
slash. Without escaping the bytes aren't printed correctly in the HTML
output of this docs.
To work with the bytes in Python you need to remove the escape sequences.
`b'\\x01\\x00d` -> `b\x01\x00d`
.. code-block:: python
>>> struct.unpack('>BHh', b'\\x42\\x00d\\x00\\x03')
(6, 100, 3)
The reponse PDU is a two byte status value.
================ ===============
Field Length (bytes)
================ ===============
Function code 1
Byte Count 1
Status Value 2
================ ===============
"""
function_code = WRITE_PASSIVE_REGISTER
_address = None
_count = 2
_value = None
data = None
@property
def value(self):
return self._value
@value.setter
def value(self, value):
""" Value to be written on register.
:param value: An integer.
:raises: IllegalDataValueError when value isn't in range.
"""
try:
struct.pack('>h', value)
except struct.error:
raise IllegalDataValueError
self._value = value
@property
def request_pdu(self):
""" Build request PDU to write single register.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self._address, self._value]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHh', self.function_code,
self._address, self._value)
@staticmethod
def create_from_request_pdu(pdu):
""" Create instance from request PDU.
:param pdu: A request PDU.
"""
_, address, value = \
struct.unpack('>BHh', pdu)
instance = WritePassiveRegister()
instance._address = address
instance._value = value
return instance
@property
def expected_response_pdu_size(self):
""" Return number of bytes expected for response PDU.
:return: number of bytes.
"""
return 4
def create_response_pdu(self):
fmt = '>BBH'
ret_val = struct.pack(fmt,
self.function_code, self._count, self.data)
return ret_val
@staticmethod
def create_from_response_pdu(resp_pdu):
""" Create instance from response PDU.
:param resp_pdu: Byte array with request PDU.
:return: Instance of :class:`WritePassiveRegister`.
"""
write_passive_register = WritePassiveRegister()
quantity, value = struct.unpack('>BH', resp_pdu[1:4])
write_passive_register._address = quantity
write_passive_register.data = value
return write_passive_register
def execute(self, slave_id, route_map):
""" Execute the Modbus function registered for a route.
:param slave_id: Slave id.
:param eindpoint: Instance of modbus.route.Map.
"""
endpoint = route_map.match(slave_id, self.function_code, self._address)
try:
endpoint(slave_id=slave_id,
address=self._address,
value=self._value,
function_code=self.function_code)
# route_map.match() returns None if no match is found. Calling None
# results in TypeError.
except TypeError:
raise IllegalDataAddressError()
function_code_to_function_map[WRITE_PASSIVE_REGISTER] = WritePassiveRegister