Skip to content

Commit

Permalink
velib_python clone
Browse files Browse the repository at this point in the history
  • Loading branch information
falcovd committed Jan 3, 2025
1 parent 66da184 commit 4d4df98
Show file tree
Hide file tree
Showing 23 changed files with 3,417 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ext/velib_python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
16 changes: 16 additions & 0 deletions ext/velib_python/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
language: python
dist: focal

python:
- "3.7"

before_install:
- sudo apt-get update
- sudo apt-get install dbus-x11 libcairo2-dev libdbus-1-dev libgirepository1.0-dev pkg-config
- python -m pip install --upgrade pip

install:
- pip3 install dbus-python PyGObject

script:
- eval `dbus-launch --sh-syntax` && cd test && python3 test_vedbus.py -v
20 changes: 20 additions & 0 deletions ext/velib_python/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2014 Victron Energy BV

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
102 changes: 102 additions & 0 deletions ext/velib_python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
velib_python
============

[![Build Status](https://travis-ci.com/victronenergy/velib_python.svg?branch=master)](https://travis-ci.org/victronenergy/velib_python)

This is the general python library within Victron. It contains code that is related to D-Bus and the Color
Control GX. See http://www.victronenergy.com/panel-systems-remote-monitoring/colorcontrol/ for more
infomation about that panel.

Files busitem.py, dbusitem.py and tracing.py are deprecated.

The main files are vedbus.py, dbusmonitor.py and settingsdevice.py.

- Use VeDbusService to put your process on dbus and let other services interact with you.
- Use VeDbusItemImport to read a single value from other processes the dbus, and monitor its signals.
- Use DbusMonitor to monitor multiple values from other processes
- Use SettingsDevice to store your settings in flash, via the com.victronenergy.settings dbus service. See
https://github.com/victronenergy/localsettings for more info.

Code style
==========

Comply with PEP8, except:
- use tabs instead of spaces, since we use tabs for all projects within Victron.
- max line length = 110

Run this command to set git diff to tabsize is 4 spaces. Replace --local with --global to do it globally for the current
user account.

git config --local core.pager 'less -x4'

Run this command to check your code agains PEP8

pep8 --max-line-length=110 --ignore=W191 *.py

D-Bus
=====

D-Bus is an/the inter process communication bus used on Linux for many things. Victron uses it on the CCGX to have all the different processes exchange data. Protocol drivers publish data read from products (for example battery voltage) on the D-Bus, and other processes (the GUI for example) takes it from the D-Bus to show it on the display.

Libraries that implement D-Bus connectivity are available in many programming languages (C, Python, etc). There are also many commandline tools available to talk to a running process via D-bus. See for example the dbuscli (executeable name dbus): http://code.google.com/p/dbus-tools/wiki/DBusCli, and also dbus-monitor and dbus-send.

There are two sides in using the D-Bus, putting information on it (exporting as service with objects) and reading/writing to a process exporting a service. Note that instead of reading with GetValue, you can also subscribe to receive a signal when datachanges. Doing this saves unncessary context-switches in most cases.

To get an idea of how to publish data on the dbus, run the example:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ python vedbusservice_example.py
vedbusservice_example.py starting up
/Position value is 5
/Position value is now 10
try changing our RPM by executing the following command from a terminal

dbus-send --print-reply --dest=com.victronenergy.example /RPM com.victronenergy.BusItem.SetValue int32:1200
Reply will be <> 0 for values > 1000: not accepted. And reply will be 0 for values < 1000: accepted.

Leave that terminal open, start a second terminal, and interrogate above service from the commandline:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus
org.freedesktop.DBus
org.freedesktop.PowerManagement
com.victronenergy.example
org.xfce.Terminal5
org.xfce.Xfconf
[and many more services in which we are not interested]

To get more details, add the servicename:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus com.victronenergy.example
/
/Float
/Int
/NegativeInt
/Position
/RPM
/String

And get the value for the position:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus com.victronenergy.example /RPM GetValue
100

And setting the value is also possible, the % makes dbus evaluate what comes behind it, resulting in an int instead of the default (a string).:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus com.victronenergy.example /RPM SetValue %1
0

In this example, the 0 indicates succes. When trying an unsupported value, 2000, this is what happens:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus com.victronenergy.example /RPM SetValue %2000
2

Exporting services, and the object paths (/Float, /Position, /Group1/Value1, etcetera) is standard D-Bus functionality. At Victron we designed and implemented a D-Bus interface, called com.victronenergy.BusItem. Example showing all interfaces supported by an object:

matthijs@matthijs-VirtualBox:~/dev/velib_python/examples$ dbus com.victronenergy.example /RPM
Interface org.freedesktop.DBus.Introspectable:
String Introspect()

Interface com.victronenergy.BusItem:
Int32 SetValue(Variant newvalue)
String GetDescription(String language, Int32 length)
String GetText()
Variant GetValue()
103 changes: 103 additions & 0 deletions ext/velib_python/dbusdummyservice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#!/usr/bin/env python3

"""
A class to put a simple service on the dbus, according to victron standards, with constantly updating
paths. See example usage below. It is used to generate dummy data for other processes that rely on the
dbus. See files in dbus_vebus_to_pvinverter/test and dbus_vrm/test for other usage examples.
To change a value while testing, without stopping your dummy script and changing its initial value, write
to the dummy data via the dbus. See example.
https://github.com/victronenergy/dbus_vebus_to_pvinverter/tree/master/test
"""
from gi.repository import GLib
import platform
import argparse
import logging
import sys
import os

# our own packages
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '../ext/velib_python'))
from vedbus import VeDbusService

class DbusDummyService(object):
def __init__(self, servicename, deviceinstance, paths, productname='Dummy product', connection='Dummy service', productid=0):
self._dbusservice = VeDbusService(servicename)
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', 'Unkown version, and running on 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', productid)
self._dbusservice.add_path('/ProductName', productname)
self._dbusservice.add_path('/FirmwareVersion', 0)
self._dbusservice.add_path('/HardwareVersion', 0)
self._dbusservice.add_path('/Connected', 1)

for path, settings in self._paths.items():
self._dbusservice.add_path(
path, settings['initial'], writeable=True, onchangecallback=self._handlechangedvalue)

self._dbusservice.register()
GLib.timeout_add(1000, self._update)

def _update(self):
with self._dbusservice as s:
for path, settings in self._paths.items():
if 'update' in settings:
update = settings['update']
if callable(update):
s[path] = update(path, s[path])
else:
s[path] += update
logging.debug("%s: %s" % (path, s[path]))
return True

def _handlechangedvalue(self, path, value):
logging.debug("someone else updated %s to %s" % (path, value))
return True # accept the change


# === All code below is to simply run it from the commandline for debugging purposes ===

# It will created a dbus service called com.victronenergy.pvinverter.output.
# To try this on commandline, start this program in one terminal, and try these commands
# from another terminal:
# dbus com.victronenergy.pvinverter.output
# dbus com.victronenergy.pvinverter.output /Ac/Energy/Forward GetValue
# dbus com.victronenergy.pvinverter.output /Ac/Energy/Forward SetValue %20
#
# Above examples use this dbus client: http://code.google.com/p/dbus-tools/wiki/DBusCli
# See their manual to explain the % in %20

def main():
logging.basicConfig(level=logging.DEBUG)

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)

pvac_output = DbusDummyService(
servicename='com.victronenergy.dummyservice.ttyO1',
deviceinstance=0,
paths={
'/Ac/Energy/Forward': {'initial': 0, 'update': 1},
'/Position': {'initial': 0, 'update': 0},
'/Nonupdatingvalue/UseForTestingWritesForExample': {'initial': None},
'/DbusInvalid': {'initial': None}
})

logging.info('Connected to dbus, and switching over to GLib.MainLoop() (= event based)')
mainloop = GLib.MainLoop()
mainloop.run()


if __name__ == "__main__":
main()
Loading

0 comments on commit 4d4df98

Please sign in to comment.