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

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 = '192.168.153.256'
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))
    print("")

    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)

    print(item_post1)
    print(item_post2)
    print(item_post3)
    print(item_post4)
  1. Create items LoadVoltage, Current, Power und Percent (see INA219.py)

  2. Create thing

UID: exec:command:UpsCommand
label: Befehl
thingTypeUID: exec:command
configuration:
  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
    enter
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: {}
triggers:
  - id: "2"
    configuration:
      cronExpression: 0 * * * * ? *
    type: timer.GenericCronTrigger
conditions: []
actions:
  - inputs: {}
    id: "1"
    configuration:
      type: application/javascript;version=ECMAScript-2021
      script: |
        // Activät this for debugging
        //console.info('Rule start');
    type: script.ScriptAction
  - inputs: {}
    id: "3"
    configuration:
      command: ON
      itemName: UPSBefehl_Ausfuhrung
    type: core.ItemCommandAction
  1. Write rule that shuts down the Rasperry Pi. Example below:
configuration: {}
triggers:
  - id: "2"
    configuration:
      cronExpression: 0 0/5 * * * ? *
    type: timer.GenericCronTrigger
conditions: []
actions:
  - inputs: {}
    id: "1"
    configuration:
      type: application/javascript;version=ECMAScript-2021
      script: >-
        var scriptExecution =
        Java.type('org.openhab.core.model.script.actions.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');
                return;
              }
            }
            this.timer = scriptExecution.createTimer(time.toZDT().plusMinutes(1), timerFunction());
          }
          else {
            if (this.timer != undefined) {
              console.info('Timer cancel');
              this.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
        mainFunction();
    type: script.ScriptAction
2 Likes