Skip to content

Commit

Permalink
Merge pull request #106 from salewis38:main
Browse files Browse the repository at this point in the history
Alignment with PALM v1.1.0
  • Loading branch information
britkat1980 authored Oct 22, 2023
2 parents 882cbaa + c1af0bc commit ef4238c
Show file tree
Hide file tree
Showing 6 changed files with 838 additions and 718 deletions.
28 changes: 16 additions & 12 deletions GivTCP/GivLUT.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
"""GivLUT: Various objects to interface to GivEnergy inverters """

class GivClient:
"""Definition of GivEnergy client """
def getData(fullrefresh: bool):
from givenergy_modbus.client import GivEnergyClient
from settings import GiV_Settings
from givenergy_modbus.model.plant import Plant
from givenergy_modbus.model.plant import Plant
client= GivEnergyClient(host=GiV_Settings.invertorIP)
numbat=GiV_Settings.numBatteries
plant=Plant(number_batteries=numbat)
client.refresh_plant(plant,GiV_Settings.isAIO,GiV_Settings.isAC,fullrefresh)
return (plant)
return plant

class GivQueue:
from redis import Redis
from rq import Queue
from settings import GiV_Settings
redis_connection = Redis(host='127.0.0.1', port=6379, db=0)
q = Queue("GivTCP_"+str(GiV_Settings.givtcp_instance),connection=redis_connection)

class GEType:
def __init__(self,dT,sC,cF,mn,mx,aZ,sM,oI):
self.devType = dT
Expand All @@ -40,7 +43,8 @@ class GivLUT:
import logging, os, zoneinfo
from settings import GiV_Settings
from logging.handlers import TimedRotatingFileHandler
logging.basicConfig(format='%(asctime)s - Inv'+ str(GiV_Settings.givtcp_instance)+' - %(module)-11s - [%(levelname)-8s] - %(message)s')
logging.basicConfig(format='%(asctime)s - Inv'+ str(GiV_Settings.givtcp_instance)+ \
' - %(module)-11s - [%(levelname)-8s] - %(message)s')
formatter = logging.Formatter(
'%(asctime)s - %(module)s - [%(levelname)s] - %(message)s')
fh = TimedRotatingFileHandler(GiV_Settings.Debug_File_Location, when='midnight', backupCount=7)
Expand Down Expand Up @@ -77,7 +81,7 @@ class GivLUT:


if hasattr(GiV_Settings,'timezone'): # If in Addon, use the HA Supervisor timezone
timezone=zoneinfo.ZoneInfo(key=GiV_Settings.timezone)
timezone=zoneinfo.ZoneInfo(key=GiV_Settings.timezone)
elif "TZ" in os.environ: # Otherwise use the ENV (for Docker)
timezone=zoneinfo.ZoneInfo(key=os.getenv("TZ"))
else:
Expand Down Expand Up @@ -182,7 +186,7 @@ class GivLUT:
"Discharge_end_time_slot_10":GEType("select","","setDischargeEnd10","","",False,False,False),
"Battery_pause_start_time_slot":GEType("select","","setPauseStart","","",False,False,False),
"Battery_pause_end_time_slot":GEType("select","","setPauseEnd","","",False,False,False),

"Charge_start_time_slot_1":GEType("select","","setChargeStart1","","",False,False,False),
"Charge_end_time_slot_1":GEType("select","","setChargeEnd1","","",False,False,False),
"Charge_start_time_slot_2":GEType("select","","setChargeStart2","","",False,False,False),
Expand All @@ -203,7 +207,7 @@ class GivLUT:
"Charge_end_time_slot_9":GEType("select","","setChargeEnd9","","",False,False,False),
"Charge_start_time_slot_10":GEType("select","","setChargeStart10","","",False,False,False),
"Charge_end_time_slot_10":GEType("select","","setChargeEnd10","","",False,False,False),

"Battery_Serial_Number":GEType("sensor","string","","","",False,True,False),
"Battery_SOC":GEType("sensor","battery","",0,100,False,False,False),
"Battery_Capacity":GEType("sensor","","",0,250,False,True,False),
Expand Down Expand Up @@ -322,7 +326,7 @@ class GivLUT:
"22:00:00","22:01:00","22:02:00","22:03:00","22:04:00","22:05:00","22:06:00","22:07:00","22:08:00","22:09:00","22:10:00","22:11:00","22:12:00","22:13:00","22:14:00","22:15:00","22:16:00","22:17:00","22:18:00","22:19:00","22:20:00","22:21:00","22:22:00","22:23:00","22:24:00","22:25:00","22:26:00","22:27:00","22:28:00","22:29:00","22:30:00","22:31:00","22:32:00","22:33:00","22:34:00","22:35:00","22:36:00","22:37:00","22:38:00","22:39:00","22:40:00","22:41:00","22:42:00","22:43:00","22:44:00","22:45:00","22:46:00","22:47:00","22:48:00","22:49:00","22:50:00","22:51:00","22:52:00","22:53:00","22:54:00","22:55:00","22:56:00","22:57:00","22:58:00","22:59:00",
"23:00:00","23:01:00","23:02:00","23:03:00","23:04:00","23:05:00","23:06:00","23:07:00","23:08:00","23:09:00","23:10:00","23:11:00","23:12:00","23:13:00","23:14:00","23:15:00","23:16:00","23:17:00","23:18:00","23:19:00","23:20:00","23:21:00","23:22:00","23:23:00","23:24:00","23:25:00","23:26:00","23:27:00","23:28:00","23:29:00","23:30:00","23:31:00","23:32:00","23:33:00","23:34:00","23:35:00","23:36:00","23:37:00","23:38:00","23:39:00","23:40:00","23:41:00","23:42:00","23:43:00","23:44:00","23:45:00","23:46:00","23:47:00","23:48:00","23:49:00","23:50:00","23:51:00","23:52:00","23:53:00","23:54:00","23:55:00","23:56:00","23:57:00","23:58:00","23:59:00"
]

delay_times=["Normal","Running","Cancel","2","15","30","45","60","90","120","150","180"]
modes=["Eco","Eco (Paused)","Timed Demand","Timed Export","Unknown"]
rates=["Day","Night"]
Expand All @@ -332,8 +336,8 @@ class GivLUT:

def getTime(timestamp):
timeslot=timestamp.strftime("%H:%M")
return (timeslot)
return timeslot


'''
Firmware Versions for each Model
Expand All @@ -342,4 +346,4 @@ def getTime(timestamp):
Gen 2 909+ New. 99x Beta
Gen3 303+ New 39x Beta
AIO 6xx New 69x Beta
'''
'''
27 changes: 14 additions & 13 deletions GivTCP/HA_Discovery.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
"""HA_Discovery: """
# version 2022.01.21
import sys, time, json
import paho.mqtt.client as mqtt
import sys
import time
import json
import paho.mqtt.client as mqtt
from settings import GiV_Settings
from givenergy_modbus.model.inverter import Model
from mqtt import GivMQTT
Expand Down Expand Up @@ -40,7 +43,7 @@ def on_connect(client, userdata, flags, rc):
#client.subscribe(topic)
else:
logger.error("Bad connection Returned code= "+str(rc))

def publish_discovery(array,SN): #Recieve multiple payloads with Topics and publish in a single MQTT connection
mqtt.Client.connected_flag=False #create flag in class
client=mqtt.Client("GivEnergy_GivTCP_"+str(GiV_Settings.givtcp_instance))
Expand Down Expand Up @@ -82,16 +85,14 @@ def publish_discovery(array,SN): #Recieve multiple payloads with Topics and pu
# client.publish("homeassistant2/binary_sensor/GivEnergy/"+str(topic).split("/")[-1]+"/config",HAMQTT.create_binary_sensor_payload(topic,SN),retain=True)
elif GivLUT.entity_type[str(topic).split("/")[-1]].devType=="select":
client.publish("homeassistant/select/GivEnergy/"+SN+"_"+str(topic).split("/")[-1]+"/config",HAMQTT.create_device_payload(topic,SN),retain=True)

client.loop_stop() #Stop loop
client.disconnect()

except:
e = sys.exc_info()
logger.error("Error connecting to MQTT Broker: " + str(e))

return



def create_device_payload(topic,SN):
tempObj={}
Expand All @@ -100,7 +101,7 @@ def create_device_payload(topic,SN):
tempObj["pl_avail"]= "online"
tempObj["pl_not_avail"]= "offline"
tempObj['device']={}

GiVTCP_Device=str(topic).split("/")[2]
if "Battery_Details" in topic:
tempObj["name"]=GiV_Settings.ha_device_prefix+" "+str(topic).split("/")[3].replace("_"," ")+" "+str(topic).split("/")[-1].replace("_"," ") #Just final bit past the last "/"
Expand Down Expand Up @@ -161,12 +162,12 @@ def create_device_payload(topic,SN):
tempObj['device_class']="Battery"
tempObj['state_class']="measurement"
if GivLUT.entity_type[str(topic).split("/")[-1]].sensorClass=="timestamp":
del(tempObj['unit_of_meas'])
del tempObj['unit_of_meas']
tempObj['device_class']="timestamp"
if GivLUT.entity_type[str(topic).split("/")[-1]].sensorClass=="datetime":
del(tempObj['unit_of_meas'])
del tempObj['unit_of_meas']
if GivLUT.entity_type[str(topic).split("/")[-1]].sensorClass=="string":
del(tempObj['unit_of_meas'])
del tempObj['unit_of_meas']
elif GivLUT.entity_type[str(topic).split("/")[-1]].devType=="switch":
tempObj['payload_on']="enable"
tempObj['payload_off']="disable"
Expand Down Expand Up @@ -207,4 +208,4 @@ def create_device_payload(topic,SN):
tempObj['payload_press']="restart"
## Convert this object to json string
jsonOut=json.dumps(tempObj)
return(jsonOut)
return jsonOut
18 changes: 8 additions & 10 deletions GivTCP/REST.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
# version 2021.12.22
from flask import Flask, json, request
from os.path import exists
from flask import Flask, request
from flask_cors import CORS
import read as rd #grab passthrough functions from main read file
import write as wr #grab passthrough functions from main write file
import config_dash as cfdash
from GivLUT import GivQueue, GivLUT
from os.path import exists

logger = GivLUT.logger

Expand All @@ -19,7 +19,7 @@
def get_config_page():
if request.method=="GET":
return cfdash.get_config()
elif request.method=="POST":
if request.method=="POST":
return cfdash.set_config(request.form)

#Read from Invertor put in cache and publish
Expand All @@ -41,7 +41,7 @@ def rdData():
def gtCache():
return rd.getCache()

#Read from Invertor put in cache
# Read from Invertor put in cache
@giv_api.route('/getData', methods=['GET'])
def gtData():
return GivQueue.q.enqueue(rd.getData,True)
Expand All @@ -51,7 +51,7 @@ def gtData():
def enChargeTrgt():
payload = request.get_json(silent=True, force=True)
return wr.enableChargeTarget(payload)

@giv_api.route('/enableChargeSchedule', methods=['POST'])
def enableChrgSchedule():
payload = request.get_json(silent=True, force=True)
Expand Down Expand Up @@ -148,8 +148,7 @@ def frceChrg():
return wr.cancelJob(jobid)
else:
logger.error("Force Charge is not currently running")
else:
return wr.forceCharge(payload)
return wr.forceCharge(payload)

@giv_api.route('/forceExport', methods=['POST'])
def frceExprt():
Expand All @@ -161,8 +160,7 @@ def frceExprt():
return wr.cancelJob(jobid)
else:
logger.error("Force Charge is not currently running")
else:
return wr.forceExport(payload)
return wr.forceExport(payload)

@giv_api.route('/setBatteryMode', methods=['POST'])
def setBattMode():
Expand All @@ -180,4 +178,4 @@ def swRates():
return wr.switchRate(payload)

if __name__ == "__main__":
giv_api.run()
giv_api.run()
21 changes: 18 additions & 3 deletions GivTCP/palm_settings.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,27 @@
# version 2023.06.21
# Settings file for use with palm.py: 30-minute calculations (v0.9.0) and weightings for daily historical consumption (v0.10.0)

# version 2023.08.07
"""
Settings file for use with palm.py: Compatible with v0.9, v0.10, v1.0.x and v1.1.x
"""
from settings import GiV_Settings
from GivLUT import GivLUT
import pickle
from os.path import exists
import os

class pg:
"""PALM global variable definitions. Used by palm_utils and project-specific wrappers"""

test_mode: bool = False
debug_mode: bool = False
once_mode: bool = False
long_t_now: str = ""
month: str = ""
t_now: str = ""
t_now_mins: int = 0
loop_counter: int = 0 # 1 minute minor frame. "0" = initialise
pvo_tstamp: int = 0 # Records value of loop_counter when PV data last written
palm_version: str = ""

# User settings for GivEnergy inverter API
class GE:
enable = True
Expand Down
Loading

0 comments on commit ef4238c

Please sign in to comment.