186 lines
No EOL
7.2 KiB
Python
186 lines
No EOL
7.2 KiB
Python
#!/usr/bin/env python
|
|
|
|
# import normal packages
|
|
import platform
|
|
import logging
|
|
import sys
|
|
import os
|
|
import sys
|
|
if sys.version_info.major == 2:
|
|
import gobject
|
|
else:
|
|
from gi.repository import GLib as gobject
|
|
import sys
|
|
import time
|
|
import requests # for http GET
|
|
|
|
# our own packages from victron
|
|
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '/opt/victronenergy/dbus-systemcalc-py/ext/velib_python'))
|
|
from vedbus import VeDbusService
|
|
|
|
|
|
class NodeRedPVinverter:
|
|
def __init__(self, servicename, deviceinstance, paths, productname='PV-Inverter', connection='Node RED HTTP JSON service'):
|
|
self._dbusservice = VeDbusService("{}.http_{:02d}".format(servicename, deviceinstance))
|
|
self._paths = paths
|
|
|
|
logging.debug("%s /DeviceInstance = %d" % (servicename, deviceinstance))
|
|
|
|
# Create the management objects, as specified in the ccgx dbus-api document
|
|
self._dbusservice.add_path('/Mgmt/ProcessName', __file__)
|
|
self._dbusservice.add_path('/Mgmt/ProcessVersion', 'Python ' + platform.python_version())
|
|
self._dbusservice.add_path('/Mgmt/Connection', connection)
|
|
|
|
# Create the mandatory objects
|
|
self._dbusservice.add_path('/DeviceInstance', deviceinstance)
|
|
self._dbusservice.add_path('/ProductId', 0xFFFF)
|
|
self._dbusservice.add_path('/ProductName', productname)
|
|
self._dbusservice.add_path('/CustomName', productname)
|
|
self._dbusservice.add_path('/FirmwareVersion', 1.0)
|
|
self._dbusservice.add_path('/HardwareVersion', 0)
|
|
self._dbusservice.add_path('/Connected', 1)
|
|
self._dbusservice.add_path('/Position', 0)
|
|
self._dbusservice.add_path('/Serial', 12345678)
|
|
self._dbusservice.add_path('/UpdateIndex', 0)
|
|
self._dbusservice.add_path('/StatusCode', 0)
|
|
|
|
# add path values to dbus
|
|
for path, settings in self._paths.items():
|
|
self._dbusservice.add_path(
|
|
path, settings['initial'], gettextcallback=settings['textformat'], writeable=True, onchangecallback=self._handlechangedvalue)
|
|
|
|
# last update
|
|
self._lastUpdate = 0
|
|
|
|
# add _update function 'timer'
|
|
gobject.timeout_add(500, self._update) # pause 500ms before the next request
|
|
|
|
# add _Status 'timer' to get feedback in log every 5minutes
|
|
gobject.timeout_add(self._getStatusInterval()*60*1000, self._Status)
|
|
|
|
def _getStatusInterval(self):
|
|
value = 1
|
|
|
|
if not value:
|
|
value = 0
|
|
|
|
return int(value)
|
|
|
|
def _getNodeRedData(self):
|
|
URL = "http://localhost:1880/meters"
|
|
meter_r = requests.get(url = URL)
|
|
|
|
# check for response
|
|
if not meter_r:
|
|
raise ConnectionError("No response from NodeRed - %s" % (URL))
|
|
|
|
meter_data = meter_r.json()
|
|
|
|
# check for Json
|
|
if not meter_data:
|
|
raise ValueError("Converting response to JSON failed")
|
|
|
|
|
|
return meter_data
|
|
|
|
|
|
def _Status(self):
|
|
logging.debug("Last update: %s" % (self._lastUpdate))
|
|
logging.debug("Last '/Ac/Power': %s" % (self._dbusservice['/Ac/Power']))
|
|
return True
|
|
|
|
def _update(self):
|
|
try:
|
|
#get data from NodeRed 3em
|
|
meter_data = self._getNodeRedData()
|
|
|
|
#send data to DBus
|
|
self._dbusservice['/Ac/Voltage'] = meter_data['pv_inverter']['voltage']
|
|
self._dbusservice['/Ac/L1/Voltage'] = meter_data['pv_inverter']['voltage']
|
|
self._dbusservice['/Ac/Current'] = meter_data['pv_inverter']['current']
|
|
self._dbusservice['/Ac/L1/Current'] = meter_data['pv_inverter']['current']
|
|
self._dbusservice['/Ac/Power'] = meter_data['pv_inverter']['power']
|
|
self._dbusservice['/Ac/L1/Power'] = meter_data['pv_inverter']['power']
|
|
self._dbusservice['/Ac/Energy/Forward'] = meter_data['pv_inverter']['energy']
|
|
self._dbusservice['/Ac/L1/Energy/Forward'] = meter_data['pv_inverter']['energy']
|
|
|
|
#logging
|
|
logging.debug("Inverter Power (/Ac/Power): %s" % (self._dbusservice['/Ac/Power']))
|
|
logging.debug("Inverter Energy(/Ac/Energy/Forward): %s" % (self._dbusservice['/Ac/Energy/Forward']))
|
|
logging.debug("---");
|
|
|
|
# increment UpdateIndex - to show that new data is available
|
|
index = self._dbusservice['/UpdateIndex'] + 1 # increment index
|
|
if index > 255: # maximum value of the index
|
|
index = 0 # overflow from 255 to 0
|
|
self._dbusservice['/UpdateIndex'] = index
|
|
|
|
#update lastupdate vars
|
|
self._lastUpdate = time.time()
|
|
except Exception as e:
|
|
logging.critical('Error at %s', '_update', exc_info=e)
|
|
|
|
# return true, otherwise add_timeout will be removed from GObject - see docs http://library.isr.ist.utl.pt/docs/pygtk2reference/gobject-functions.html#function-gobject--timeout-add
|
|
return True
|
|
|
|
def _handlechangedvalue(self, path, value):
|
|
logging.debug("someone else updated %s to %s" % (path, value))
|
|
return True # accept the change
|
|
|
|
|
|
|
|
def main():
|
|
#configure logging
|
|
logging.basicConfig( format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
|
|
datefmt='%Y-%m-%d %H:%M:%S',
|
|
level=logging.INFO,
|
|
handlers=[
|
|
logging.FileHandler("%s/current.log" % (os.path.dirname(os.path.realpath(__file__)))),
|
|
logging.StreamHandler()
|
|
])
|
|
|
|
try:
|
|
logging.info("Start");
|
|
|
|
from dbus.mainloop.glib import DBusGMainLoop
|
|
# Have a mainloop, so we can send/receive asynchronous calls to and from dbus
|
|
DBusGMainLoop(set_as_default=True)
|
|
|
|
#formatting
|
|
_kwh = lambda p, v: (str(round(v, 2)) + ' KWh')
|
|
_a = lambda p, v: (str(round(v, 1)) + ' A')
|
|
_w = lambda p, v: (str(round(v, 1)) + ' W')
|
|
_v = lambda p, v: (str(round(v, 1)) + ' V')
|
|
|
|
#start our main-service
|
|
pvac_output = NodeRedPVinverter(
|
|
servicename='com.victronenergy.pvinverter',
|
|
deviceinstance=46,
|
|
paths={
|
|
'/Ac/Energy/Forward': {'initial': None, 'textformat': _kwh}, # energy produced by pv inverter
|
|
'/Ac/Power': {'initial': 0, 'textformat': _w},
|
|
|
|
'/Ac/Current': {'initial': 0, 'textformat': _a},
|
|
'/Ac/Voltage': {'initial': 0, 'textformat': _v},
|
|
|
|
'/Ac/L1/Voltage': {'initial': 0, 'textformat': _v},
|
|
'/Ac/L2/Voltage': {'initial': 0, 'textformat': _v},
|
|
'/Ac/L3/Voltage': {'initial': 0, 'textformat': _v},
|
|
'/Ac/L1/Current': {'initial': 0, 'textformat': _a},
|
|
'/Ac/L2/Current': {'initial': 0, 'textformat': _a},
|
|
'/Ac/L3/Current': {'initial': 0, 'textformat': _a},
|
|
'/Ac/L1/Power': {'initial': 0, 'textformat': _w},
|
|
'/Ac/L2/Power': {'initial': 0, 'textformat': _w},
|
|
'/Ac/L3/Power': {'initial': 0, 'textformat': _w},
|
|
'/Ac/L1/Energy/Forward': {'initial': None, 'textformat': _kwh},
|
|
'/Ac/L2/Energy/Forward': {'initial': None, 'textformat': _kwh},
|
|
'/Ac/L3/Energy/Forward': {'initial': None, 'textformat': _kwh},
|
|
})
|
|
|
|
logging.info('Connected to dbus, and switching over to gobject.MainLoop() (= event based)')
|
|
mainloop = gobject.MainLoop()
|
|
mainloop.run()
|
|
except Exception as e:
|
|
logging.critical('Error at %s', 'main', exc_info=e)
|
|
if __name__ == "__main__":
|
|
main() |