Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes snaptec repo #1072

Merged
merged 27 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 5 additions & 14 deletions packages/modules/devices/rct/bat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,23 +27,14 @@ def update(self, rct_client: RCT) -> None:
# read all parameters
rct_client.read(my_tab)

# postprocess values
soc = socx.value
power = int(watt1.value) * -1.0
imported = int(watt2.value)
exported = int(watt3.value)
stat1 = int(stat1.value)
stat2 = int(stat2.value)
stat3 = int(stat3.value)

if (stat1 + stat2 + stat3) > 0:
if (stat1.value + stat2.value + stat3.value) > 0:
raise FaultState.error("Alarm Status Speicher ist ungleich 0.")

bat_state = BatState(
power=int(power) * -1,
soc=soc * 100,
imported=int(imported),
exported=int(exported)
power=watt1.value * -1,
soc=socx.value * 100,
imported=watt2.value,
exported=watt3.value
)
self.store.set(bat_state)

Expand Down
12 changes: 6 additions & 6 deletions packages/modules/devices/rct/counter.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@ def update(self, rct_client: RCT):
# read all parameters
rct_client.read(my_tab)

if (stat1 + stat2 + stat3 + stat4) > 0:
if (stat1.value + stat2.value + stat3.value + stat4.value) > 0:
raise FaultState.error("Alarm Status Zähler ist ungleich 0.")

counter_state = CounterState(
imported=int(imported.value),
imported=imported.value,
exported=exported.value*-1.0,
power=int(power.value),
frequency=int(freq.value),
powers=[int(power1.value), int(power2.value), int(power3.value)],
voltages=[int(volt1.value), int(volt2.value), int(volt3.value)]
power=power.value,
frequency=freq.value,
powers=[power1.value, power2.value, power3.value],
voltages=[volt1.value, volt2.value, volt3.value]
)
self.store.set(counter_state)

Expand Down
70 changes: 24 additions & 46 deletions packages/modules/devices/rct/rct_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@

log = logging.getLogger(__name__)

# helper function to print and error


# helper function to print and error
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
Expand Down Expand Up @@ -75,7 +74,7 @@ def __init__(self, msgid, idx, name, data_type=rct_data.t_unknown, desc=''):
self.name = name
self.desc = desc
self.value = None
self.pending = False # used to read pending
self.pending = False # used to read pending

# decode a value according to the id data type
def decode_value(self, data):
Expand Down Expand Up @@ -130,21 +129,21 @@ def decode_value(self, data):
cmd_long_response = 0x06
cmd_extension = 0x3C

HEADER_WITH_LENGTH = 1 + 1 + 2 # frame length for header, command and 2 byte length
FRAME_TYPE_STANDARD = 4 # standard frame with id
FRAME_TYPE_PLANT = 8 # plant frame with id and address
FRAME_CRC16_LENGTH = 2 # nr of bytes for CRC16 field
HEADER_WITH_LENGTH = 1 + 1 + 2 # frame length for header, command and 2 byte length
FRAME_TYPE_STANDARD = 4 # standard frame with id
FRAME_TYPE_PLANT = 8 # plant frame with id and address
FRAME_CRC16_LENGTH = 2 # nr of bytes for CRC16 field


class Frame:
def __init__(self, command=0, address=0, frame_type=FRAME_TYPE_STANDARD):
self.command = command
self.address = address # for plant communication only
self.address = address # for plant communication only
self.idList = []
self.frame_type = frame_type
self.bEscapeMode = False
self.rxStream = b""
self.pendingCount = False # nr of id's which are not yet handled
self.pendingCount = False # nr of id's which are not yet handled
self.statisticRxDropped = 0
self.statisticRxConsumed = 0
self.statisticRxDuplicate = 0
Expand All @@ -167,7 +166,7 @@ def add(self, item):
self.pendingCount += 1

# consume all data, extract frames and decode them.
# Incomplete frames remain in self.rxStream for the nexht data chunk
# Incomplete frames remain in self.rxStream for the next data chunk
def consume(self, data):
for d in data:
c = bytes([d])
Expand All @@ -182,7 +181,7 @@ def consume(self, data):
self.bEscapeMode = False
else:
if c == escape_token:
self.bEscapeMode = True # escape mode -> set mode and don't add byte
self.bEscapeMode = True # escape mode -> set mode and don't add byte
continue

# add byte to receive stream
Expand All @@ -193,11 +192,11 @@ def consume(self, data):
if len(self.rxStream) == HEADER_WITH_LENGTH:
cmd = struct.unpack("B", bytes([self.rxStream[1]]))[0]
if cmd == cmd_long_response or cmd == cmd_long_write:
self.FrameLength = struct.unpack(">H", self.rxStream[2:4])[0] + 2 # 2 byte length MSBF
self.FrameLength = struct.unpack(">H", self.rxStream[2:4])[0] + 2 # 2 byte length MSBF
else:
self.FrameLength = struct.unpack(">B", bytes([self.rxStream[2]]))[0] + 1 # 1 byte length
self.FrameLength = struct.unpack(">B", bytes([self.rxStream[2]]))[0] + 1 # 1 byte length

self.FrameLength += 2 # 2 bytes header
self.FrameLength += 2 # 2 bytes header
else:
if len(self.rxStream) == self.FrameLength + FRAME_CRC16_LENGTH:
# print(binascii.hexlify(self.rxStream))
Expand All @@ -222,10 +221,10 @@ def decode(self):
data_length = struct.unpack(">H", self.rxStream[2:4])[0] # 2 byte length MSBF
idx = 4
else:
data_length = struct.unpack(">B", bytes([self.rxStream[2]]))[0] # 1 byte length
data_length = struct.unpack(">B", bytes([self.rxStream[2]]))[0] # 1 byte length
idx = 3

# substract frame type specific length
# subtract frame type specific length
data_length -= self.frame_type

# extract 32 bit ID
Expand Down Expand Up @@ -299,18 +298,18 @@ def encode(self):

# just for completeness but PLANT frames are not used in send direction
if self.frame_type == FRAME_TYPE_PLANT:
buf += struct.pack('>I', self.address) # 4 bytes
buf += struct.pack('>I', self.address) # 4 bytes

# append id
buf += struct.pack('>I', item.id) # 4 bytes
buf += struct.pack('>I', item.id) # 4 bytes

# append data if used
if item.value is not None:
buf += self.encode_by_type(item.data_type, item.value)

# calculate and append CRC16
crc16 = self.CRC16(buf)
buf += struct.pack('>H', crc16) # 2 bytes
buf += struct.pack('>H', crc16) # 2 bytes

# add start token and inject escape tokens in buf where necessary to buf_all
buf_all += struct.pack('c', start_token) + self.createStream(buf)
Expand Down Expand Up @@ -445,7 +444,7 @@ def connect_to_server(self):
self.socket.settimeout(2.0)
try:
self.socket.connect((self.host, self.port))
log.debug('connect to ', self.host, 'port', self.port)
log.debug('connect to {} port {}'.format(self.host, self.port))
return True
except Exception:
print("-"*100)
Expand Down Expand Up @@ -530,27 +529,6 @@ def close(self):
print("-"*100)
traceback.print_exc(file=sys.stdout)

# write value to a ramdisk variable
def write_ramdisk(self, fn, val, rctname):
try:
fnn = "/var/www/html/openWB/ramdisk/"+str(fn)
with open(fnn, 'w') as f:
f.write(str(val))
except Exception:
return

# helper function to print debug messages
def errlog(self, *args):
self.logger.error(' '.join(map(str, args)))

# helper function to print debug messages
def dbglog(self, *args):
self.logger.debug(' '.join(map(str, args)))

# helper function to print info messages
def infolog(self, *args):
self.logger.info(' '.join(map(str, args)))

def id_tab_setup(self):
# add all known id's with name, data type, description and unit to the id table
self.id_tab.append(rct_id(0x0104EB6A, 0, "rb485.f_grid[2]",
Expand All @@ -562,7 +540,7 @@ def id_tab_setup(self):
self.id_tab.append(rct_id(0x01676FA6, 3, "battery.cells_stat[3]",
rct_data.t_string, "battery.cells_stat[3]"))
self.id_tab.append(rct_id(0x019C0B60, 4, "cs_neg[2]",
rct_data.t_float, "Miltiply value of the current sensor 2 by"))
rct_data.t_float, "Multiply value of the current sensor 2 by"))
self.id_tab.append(rct_id(0x02247588, 5, "battery_placeholder[0].cells_stat[2].u_min.value",
rct_data.t_float, "battery_placeholder[0].cells_stat[2].u_min.value"))
self.id_tab.append(rct_id(0x031A6110, 6, "energy.e_ext_month",
Expand Down Expand Up @@ -1068,7 +1046,7 @@ def id_tab_setup(self):
self.id_tab.append(rct_id(0x4BE02BB7, 256, "energy.e_load_day_sum",
rct_data.t_float, "energy.e_load_day_sum"))
self.id_tab.append(rct_id(0x4C12C4C7, 257, "cs_neg[1]",
rct_data.t_float, "Miltiply value of the current sensor 1 by"))
rct_data.t_float, "Multiply value of the current sensor 1 by"))
self.id_tab.append(rct_id(0x4C14CC7C, 258, "logger.year_ea_log_ts",
rct_data.t_log_ts, "logger.year_ea_log_ts"))
self.id_tab.append(rct_id(0x4C2A7CDC, 259, "nsm.cos_phi_p[2][1]",
Expand Down Expand Up @@ -1488,7 +1466,7 @@ def id_tab_setup(self):
self.id_tab.append(rct_id(0x81AF854E, 466, "nsm.pu_use",
rct_data.t_bool, "P(U) active"))
self.id_tab.append(rct_id(0x82258C01, 467, "cs_neg[0]",
rct_data.t_float, "Miltiply value of the current sensor 0 by"))
rct_data.t_float, "Multiply value of the current sensor 0 by"))
self.id_tab.append(rct_id(0x82CD1525, 468, "grid_mon[1].u_under.threshold",
rct_data.t_float, "Min. voltage level 2 [V]"))
self.id_tab.append(rct_id(0x82E3C121, 469, "g_sync.q_ac[1]",
Expand Down Expand Up @@ -1815,8 +1793,8 @@ def id_tab_setup(self):
rct_data.t_float, "Grid power phase 3 [W]"))
self.id_tab.append(rct_id(0xB228EC94, 630, "battery_placeholder[0].cells_stat[3].t_max.time",
rct_data.t_uint32, "battery_placeholder[0].cells_stat[3].t_max.time"))
self.id_tab.append(rct_id(0xB238942F, 631, "last_successfull_flash_op",
rct_data.t_int16, "last_successfull_flash_op"))
self.id_tab.append(rct_id(0xB238942F, 631, "last_successful_flash_op",
rct_data.t_int16, "last_successful_flash_op"))
self.id_tab.append(rct_id(0xB298395D, 632, "dc_conv.dc_conv_struct[0].u_sg_lp",
rct_data.t_float, "Solar generator A voltage [V]"))
self.id_tab.append(rct_id(0xB2FB9A90, 633, "bat_mng_struct.k_trust",
Expand Down
24 changes: 6 additions & 18 deletions packages/modules/smarthome/idm/off.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,21 @@
#!/usr/bin/python3
import sys
import os
import struct
from pymodbus.client.sync import ModbusTcpClient
import logging
from smarthome.smartlog import initlog
devicenumber = int(sys.argv[1])
ipadr = str(sys.argv[2])
uberschuss = int(sys.argv[3])
try:
navvers = str(sys.argv[4])
except Exception:
navvers = "2"
navvers = str(sys.argv[4])
bp = '/var/www/html/openWB/ramdisk/smarthome_device_'
# standard
file_stringpv = bp + str(devicenumber) + '_pv'
file_stringcount = bp + str(devicenumber) + '_count'
file_stringcount5 = bp + str(devicenumber) + '_count5'
initlog("idm", devicenumber)
log = logging.getLogger("idm")
log.info(" devicenr %d ipadr %s ueberschuss %6d try to connect (modbus)"
log.info(" off.py devicenr %d ipadr %s ueberschuss %6d "
% (devicenumber, ipadr, uberschuss))
client = ModbusTcpClient(ipadr, port=502)
start = 4122
if navvers == "2":
rr = client.read_input_registers(start, 2, unit=1)
else:
rr = client.read_holding_registers(start, 2, unit=1)
raw = struct.pack('>HH', rr.getRegister(1), rr.getRegister(0))
lkw = float(struct.unpack('>f', raw)[0])
aktpower = int(lkw*1000)
log.info(" devicenr %d ipadr %s Akt Leistung %6d"
% (devicenumber, ipadr, aktpower))
pvmodus = 0
if os.path.isfile(file_stringpv):
with open(file_stringpv, 'r') as f:
Expand All @@ -44,3 +29,6 @@
count1 = 999
with open(file_stringcount, 'w') as f:
f.write(str(count1))
count5 = 999
with open(file_stringcount5, 'w') as f:
f.write(str(count5))
24 changes: 6 additions & 18 deletions packages/modules/smarthome/idm/on.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,27 @@
#!/usr/bin/python3
import sys
import struct
from pymodbus.client.sync import ModbusTcpClient
import logging
from smarthome.smartlog import initlog
devicenumber = int(sys.argv[1])
ipadr = str(sys.argv[2])
uberschuss = int(sys.argv[3])
bp = '/var/www/html/openWB/ramdisk/smarthome_device_'
try:
navvers = str(sys.argv[4])
except Exception:
navvers = "2"
navvers = str(sys.argv[4])
initlog("idm", devicenumber)
log = logging.getLogger("idm")
# standard
# lesen
# own log
file_stringpv = bp + str(devicenumber) + '_pv'
file_stringcount = bp + str(devicenumber) + '_count'
log.info("devicenr %d ipadr %s ueberschuss %6d try to connect (modbus)"
file_stringcount5 = bp + str(devicenumber) + '_count5'
log.info("on.py devicenr %d ipadr %s ueberschuss %6d"
% (devicenumber, ipadr, uberschuss))
client = ModbusTcpClient(ipadr, port=502)
start = 4122
if navvers == "2":
rr = client.read_input_registers(start, 2, unit=1)
else:
rr = client.read_holding_registers(start, 2, unit=1)
raw = struct.pack('>HH', rr.getRegister(1), rr.getRegister(0))
lkw = float(struct.unpack('>f', raw)[0])
aktpower = int(lkw*1000)
log.info("devicenr %d ipadr %s Akt Leistung %6d " %
(devicenumber, ipadr, aktpower))
with open(file_stringpv, 'w') as f:
f.write(str(1))
count1 = 999
with open(file_stringcount, 'w') as f:
f.write(str(count1))
count5 = 999
with open(file_stringcount5, 'w') as f:
f.write(str(count5))
5 changes: 4 additions & 1 deletion packages/modules/smarthome/idm/smartidm.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,18 @@ def updatepar(self, input_param: Dict[str, str]) -> None:

def getwatt(self, uberschuss: int, uberschussoffset: int) -> None:
self.prewatt(uberschuss, uberschussoffset)
forcesend = self.checkbefsend()
argumentList = ['python3', self._prefixpy + 'idm/watt.py',
str(self.device_nummer), str(self._device_ip),
str(self.devuberschuss), str(self._device_idmnav)]
str(self.devuberschuss), str(self._device_idmnav),
str(self.pvwatt), str(forcesend)]
try:
self.callpro(argumentList)
self.answer = self.readret()
self.newwatt = int(self.answer['power'])
self.newwattk = int(self.answer['powerc'])
self.relais = int(self.answer['on'])
self.checksend(self.answer)
except Exception as e1:
log.warning("(" + str(self.device_nummer) +
") Leistungsmessung %s %d %s Fehlermeldung: %s "
Expand Down
Loading