Merge pull request #19 from s-allius/s-allius/issue18

S allius/issue18
This commit is contained in:
Stefan Allius
2023-10-20 20:09:56 +02:00
committed by GitHub
5 changed files with 48 additions and 31 deletions

View File

@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
- fix issue [#18](https://github.com/s-allius/tsun-gen3-proxy/issues/18)
- initialize the proxy statistics
## [0.4.0] - 2023-10-16 ## [0.4.0] - 2023-10-16
- fix issue [#8](https://github.com/s-allius/tsun-gen3-proxy/issues/8) - fix issue [#8](https://github.com/s-allius/tsun-gen3-proxy/issues/8)

View File

@@ -4,14 +4,28 @@ import struct, json, logging, os
class Infos: class Infos:
stat = {} stat = {}
app_name = os.getenv('SERVICE_NAME', 'proxy')
version = os.getenv('VERSION', 'unknown')
@classmethod
def static_init(cls):
logging.info('Initialize proxy statistics')
# init proxy counter in the class.stat dictionary
cls.stat['proxy'] = {}
for key in cls.__info_defs:
name = cls.__info_defs[key]['name']
if name[0]=='proxy':
cls.stat['proxy'][name[1]] = 0
# add values from the environment to the device definition table
prxy = cls.__info_devs['proxy']
prxy['sw'] = cls.version
prxy['mdl'] = cls.app_name
def __init__(self): def __init__(self):
self.db = {} self.db = {}
self.app_name = os.getenv('SERVICE_NAME', 'proxy')
self.version = os.getenv('VERSION', 'unknown')
self.tracer = logging.getLogger('data') self.tracer = logging.getLogger('data')
prxy = self.__info_devs['proxy']
prxy['sw'] = self.version
prxy['mdl'] = self.app_name
__info_devs={ __info_devs={
'proxy': {'singleton': True, 'name':'Proxy', 'mf':'Stefan Allius'}, 'proxy': {'singleton': True, 'name':'Proxy', 'mf':'Stefan Allius'},
@@ -236,24 +250,15 @@ class Infos:
yield json.dumps (attr), component, node_id, attr['uniq_id'] yield json.dumps (attr), component, node_id, attr['uniq_id']
def __init_counter (self, counter:str) -> dict:
'''init proxy statistic counter, when its missing'''
if not 'proxy' in self.stat:
self.stat['proxy'] = {}
dict = self.stat['proxy']
if not counter in dict:
dict[counter] = 0
return dict
def inc_counter (self, counter:str) -> None: def inc_counter (self, counter:str) -> None:
'''inc proxy statistic counter''' '''inc proxy statistic counter'''
dict = self.__init_counter (counter) dict = self.stat['proxy']
dict[counter] += 1 dict[counter] += 1
def dec_counter (self, counter:str) -> None: def dec_counter (self, counter:str) -> None:
'''dec proxy statistic counter''' '''dec proxy statistic counter'''
dict = self.__init_counter (counter) dict = self.stat['proxy']
dict[counter] -= 1 dict[counter] -= 1

View File

@@ -35,7 +35,7 @@ class Inverter(AsyncStream):
logging.debug ("disconnect client connection") logging.debug ("disconnect client connection")
self.remoteStream.disc() self.remoteStream.disc()
# await self.async_publ_mqtt() await self.__async_publ_mqtt_packet('proxy')
async def client_loop(self, addr): async def client_loop(self, addr):
'''Loop for receiving messages from the TSUN cloud (client-side)''' '''Loop for receiving messages from the TSUN cloud (client-side)'''
@@ -73,8 +73,6 @@ class Inverter(AsyncStream):
async def async_publ_mqtt(self) -> None: async def async_publ_mqtt(self) -> None:
'''puplish data to MQTT broker''' '''puplish data to MQTT broker'''
db = self.db.db
stat = self.db.stat
# check if new inverter or collector infos are available or when the home assistant has changed the status back to online # check if new inverter or collector infos are available or when the home assistant has changed the status back to online
if (('inverter' in self.new_data and self.new_data['inverter']) or if (('inverter' in self.new_data and self.new_data['inverter']) or
('collector' in self.new_data and self.new_data['collector']) or ('collector' in self.new_data and self.new_data['collector']) or
@@ -83,18 +81,23 @@ class Inverter(AsyncStream):
self.ha_restarts = self.mqtt.ha_restarts self.ha_restarts = self.mqtt.ha_restarts
for key in self.new_data: for key in self.new_data:
if self.new_data[key]: await self.__async_publ_mqtt_packet(key)
if key in db:
data_json = json.dumps(db[key]) async def __async_publ_mqtt_packet(self, key):
node_id = self.node_id db = self.db.db
elif key in stat: stat = self.db.stat
data_json = json.dumps(stat[key]) if self.new_data[key]:
node_id = self.proxy_node_id if key in db:
else: data_json = json.dumps(db[key])
continue node_id = self.node_id
logger_mqtt.debug(f'{key}: {data_json}') elif key in stat:
await self.mqtt.publish(f"{self.entity_prfx}{node_id}{key}", data_json) data_json = json.dumps(stat[key])
self.new_data[key] = False node_id = self.proxy_node_id
else:
return
logger_mqtt.debug(f'{key}: {data_json}')
await self.mqtt.publish(f"{self.entity_prfx}{node_id}{key}", data_json)
self.new_data[key] = False
async def __register_home_assistant(self) -> None: async def __register_home_assistant(self) -> None:
'''register all our topics at home assistant''' '''register all our topics at home assistant'''

View File

@@ -4,6 +4,7 @@ from async_stream import AsyncStream
from inverter import Inverter from inverter import Inverter
from config import Config from config import Config
from mqtt import Mqtt from mqtt import Mqtt
from infos import Infos
async def handle_client(reader, writer): async def handle_client(reader, writer):
@@ -69,6 +70,8 @@ if __name__ == "__main__":
# call Mqtt singleton to establisch the connection to the mqtt broker # call Mqtt singleton to establisch the connection to the mqtt broker
mqtt = Mqtt() mqtt = Mqtt()
# initialize the proxy statistics
Infos.static_init()
# #
# Register some UNIX Signal handler for a gracefully server shutdown on Docker restart and stop # Register some UNIX Signal handler for a gracefully server shutdown on Docker restart and stop

View File

@@ -2,7 +2,10 @@
import pytest import pytest
from app.src.messages import Message, Control from app.src.messages import Message, Control
from app.src.config import Config from app.src.config import Config
from app.src.infos import Infos
# initialize the proxy statistics
Infos.static_init()
class MemoryStream(Message): class MemoryStream(Message):
def __init__(self, msg, chunks = (0,)): def __init__(self, msg, chunks = (0,)):