Waveshare ups hat (b) python script values display in openhab

Hi guys, I’m new here and before going crazy trying to find things on my own, I will share with you all what I’m trying to do. I have a raspberry pi 4 b running openhabian with a Waveshare ups hat (b). The ups comes with a python script that prints out voltage/current/battery % in terminal. What would be the best way to get those values displayed in openhab instead. Thanks

If you already have a python script, then the best approach, in my opinion, would be to just modify that script to send the values directly to OH via the API. In the past, I’ve used the requests library for things like this.

Other secondary options might be:

  • If you already have mqtt running for some other reason or are comfortable using an mqtt broker, then there are mqtt libraries for python that would do the trick fairly easily as well, though I have less experience with them.
  • Replicate the script you have using HabApp which will also then allow you to send the values directly to OH items (this is equivalent to my first recommendation as HabApp just uses the API, but may be slightly easier depending on your setup).
  • Get the python script to write out the values to some log file and use the logReader binding to collect and parse the values.

There are so many communication routes for OH, I’m sure there are a dozen more options that are just as good as theses.

Thanks Justin for this fast response. It gives me some directions on how to target my research for this project.

Hello @Pascalost

it would be great if you could describe your solution here.

+1 to this. I wrote a tutorial for using NUT awhile back, and it would be great to have similar instructions for a Waveshare hat.

Anyone in this thread, any contribution to openHABian to support Waveshare UPS is welcome.
(BTW see /opt/openhabian/includes for INA219.py script).

See also add NUT Network UPS Tools · Issue #1712 · openhab/openhabian · GitHub

Here is a short tutorial on how to use the Waveshare UPS with the Raspberry Pi.

  1. Install raspberry-config and and enable I2C, I uninstalled it afterwards
apt-get install raspi-config
  1. Install smbus python library. Is needed by INA219.py
sudo apt-get install python3-smbus python3-dev i2c-tools
  1. Generate openHAB API token

  2. Install Exec Binding

  3. Adapt INA219.py and copy it to the Raspberry Pi

#Global Variables
openhabip = ''
access_token = 'oh.Test.9ylPIy9mtc5yLR3Hld57A'
headers = {'accept':'*/*','content-type':'application/json','Authorization': 'Bearer {}'.format(access_token)}
headers_post = {'accept':'*/*','content-type':'text/plain','Authorization': 'Bearer {}'.format(access_token)}
    # Create an INA219 instance.
    ina219 = INA219(addr=0x42)
    print("Percent:       {:3.1f}%".format(p))

    item_post1 = requests.put('http://'+openhabip+':8080/rest/items/LoadVoltage/state' , str(bus_voltage) , headers=headers_post)
    item_post2 = requests.put('http://'+openhabip+':8080/rest/items/Current/state' , str(current/1000) , headers=headers_post)
    item_post3 = requests.put('http://'+openhabip+':8080/rest/items/Power/state' , str(power) , headers=headers_post)
    item_post4 = requests.put('http://'+openhabip+':8080/rest/items/Percent/state' , str(p) , headers=headers_post)

  1. Create items LoadVoltage, Current, Power und Percent (see INA219.py)

  2. Create thing

UID: exec:command:UpsCommand
label: Befehl
thingTypeUID: exec:command
  transform: REGEX((.*))
  interval: 0
  autorun: false
  command: sudo -u openhab python3 /home/openhabian/INA219.py
  timeout: 15
  1. The file exec.whitelist is required by Exec Binding change under /etc/openhab/misc change
sudo -u openhabian python3 /home/openhabian/INA219.py
  1. Write a rule which executes the Exce command and calls the Python script cyclically to fill the items.
configuration: {}
  - id: "2"
      cronExpression: 0 * * * * ? *
    type: timer.GenericCronTrigger
conditions: []
  - inputs: {}
    id: "1"
      type: application/javascript;version=ECMAScript-2021
      script: |
        // Activät this for debugging
        //console.info('Rule start');
    type: script.ScriptAction
  - inputs: {}
    id: "3"
      command: ON
      itemName: UPSBefehl_Ausfuhrung
    type: core.ItemCommandAction
  1. Write rule that shuts down the Rasperry Pi. Example below:
configuration: {}
  - id: "2"
      cronExpression: 0 0/5 * * * ? *
    type: timer.GenericCronTrigger
conditions: []
  - inputs: {}
    id: "1"
      type: application/javascript;version=ECMAScript-2021
      script: >-
        var scriptExecution =
        var notificationAction = org.openhab.io.openhabcloud.NotificationAction;                    

        // Get last shutdwon status
        this.shutdownStatus = (this.shutdownStatus === undefined) ? 'OFF' : this.shutdownStatus;
        var timerFunction = function () {
          return function() {
            // timer code goes here
            console.info('shutdown ON');
            this.shutdownStatus = 'ON';
            actions.Exec.executeCommandLine('sudo', 'shutdown', '-r');

         * We use a function otherwise return is not working
        function mainFunction() {
          //console.info('Function start: ' + this.shutdownStatus + ', Value: '); //  + items.getItem('ShutdownZeit').state);

          if (items.getItem('Percent').state <= '50') {  //items.getItem('ShutdownZeit').state) {
            notificationAction.sendBroadcastNotification('UPS is low', 'battery', 'WARN');
            console.info('Start shutdown timer');
            if (this.timer != undefined) {
              if (this.timer.isActive()) {
                console.log('Timer is already running, return');
            this.timer = scriptExecution.createTimer(time.toZDT().plusMinutes(1), timerFunction());
          else {
            if (this.timer != undefined) {
              console.info('Timer cancel');
              this.timer = undefined;
            if (this.shutdownStatus == 'ON') {
              this.shutdownStatus = 'OFF'
              console.info('shutdown cancel');
              actions.Exec.executeCommandLine('sudo', 'shutdown', '-c');

        // Call your main function from the script
    type: script.ScriptAction
1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.