Page 1 of 6

NUT Mini BATTERY SERVICE

Posted: Monday 27 February 2017 22:19
by emme
Thanks to my fellows we finally managed the script for the battery service for NUT mini beacons...

this is something that actually NUTSpace does not provide either (sorry guys, but this is a great goal for us :P :P :P)

here are the specs:
Image
Nut Mini is a simple BLE device.
it does nothing more that its presence AND now we were able to identify the battery service and its value.

Here is how it works:
This script just check the battery and write the value to Domoticz
you have an array to populate with all the datas you need
Because the battery inquiry could drain it, it would be better to run the script once/twice a day (via cron)
in my specific scenario I have a beacon service that check the presence of NUTs... but both script cannot cohexist, so the service must be disabled first if you do not have a service you will be able to skip this part)

Here are the Domoticz requirements:
- String Variable for each NUT where to store the value
- ON/OFF Switch linked to the NUT to check state for continuing (this can be avoided)
- NUT MAC ADDRESS

here is the script:

Code: Select all

#!/bin/bash 

# SETTING UP PARAMETERS

## DOMOTICZ SETUP (no authentication required, ensure that you have IP in whitelist)

DOMOIP="127.0.0.1"
DOMOPORT="8080"
DAWVAR="/json.htm?type=command&param=updateuservariable&vname=VARIABLENAME&vtype=2&vvalue=VARIABLEVALUE"
DARDEV="/json.htm?type=devices&rid=DEVICEIDX"

DCHECKSTS="1"
#Check status of switches before continuing
#Set to 0 to force all configured NUT

BATTUUID="0x2a19"
BATTAWAYMSG="UNAVAILABLE"

# Creating Main array (MAC Address - Variable Name - Switch Name)
NUTBATT=(
   "00:00:00:00:00:00" "Variabile_Nome_Batteria" "IDX switch ON/OFF"
   "00:00:00:00:00:00" "Variabile_Nome_Batteria" "IDX switch ON/OFF"
   "00:00:00:00:00:00" "Variabile_Nome_Batteria" "IDX switch ON/OFF"
)

# Other Parameters 
USEBEACONSERVICE="1"
#Set to 0 if you do not have a beaconing serive deamon running

BEACONSERVICENAME="NomeServizioBeacon.service"
HCIINTERFACE="hci0"

function domoWriteVar () {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DAWVAR
    URLREQ="${URLREQ/VARIABLENAME/${NUTBATT[arrNut+1]}}"
    URLREQ="${URLREQ/VARIABLEVALUE/$1}"
    dzAPIWriteVar=$(curl -s "$URLREQ" ) 
 
}

function domoGetStatus {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DARDEV
    #echo $URLREQ
    dzAPIStatus="${URLREQ/DEVICEIDX/${NUTBATT[arrNut+2]}}"

# Getting switch status prom Domoticz
    dzDevRAW=$(curl -s "$dzAPIStatus")
    dzDevJSON=$(echo ${dzDevRAW} | jq .result[0].Data)
    dzDevSTATUS=$(echo $dzDevJSON | sed "s/\"//g")
}


function svcBeacon() {
    if [[ $1 == "stop" ]]; then
        echo "Stopping Beaconing Service"
        sudo systemctl stop ${BEACONSERVICENAME}
    fi
    
    if [[ $1 == "start" ]]; then
        echo "Starting Beaconing Service"
        sudo systemctl start ${BEACONSERVICENAME}
    fi
}

function restartHCI () {
    sudo hciconfig ${HCIINTERFACE} down 
    sleep 1 
    sudo hciconfig ${HCIINTERFACE} up 
}

function getBLEBat (){
    restartHCI

    HANDLE=$(sudo hcitool lecc --random ${NUTBATT[arrNut]} | awk '{print $3}')
    sleep 1
    sudo hcitool ledc $HANDLE
    BATHEX=$(sudo gatttool -t random --char-read --uuid $BATTUUID -b ${NUTBATT[arrNut]} | awk '{print $4}')
    BATDEC=$((0x$BATHEX))

    if [ "$BATDEC" == "0" ]; then
       BATDEC=$BATTAWAYMSG
    fi
    echo "Risultato finale: HEX :"$BATHEX" DEC: "$BATDEC
    domoWriteVar $BATDEC
}


# BEGINNING MAIN SCRIPT

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "stop"
fi

    printf "\n- - - - - - - - - - - - - - -\n" 

for arrNut in $(seq 0 3 $((${#NUTBATT[@]} - 1))); do
    if [[ $DCHECKSTS == "1" ]]; then
        domoGetStatus
        echo "Analyzing NUT: "${NUTBATT[arrNut+1]}" Domoticz State: "$dzDevSTATUS
    else
        dzDevSTATUS="On"
    fi
    
    if [[ $dzDevSTATUS == "On" ]]; then
        echo "Proceeding seeking for Battery Info"
        restartHCI
        getBLEBat
        dzDevSTATUS="Off"
    else
       echo "NUT Unavailable, skipping"
    fi 
    printf "\n- - - - - - - - - - - - - - -\n" 
done

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "start"
fi
hope you will enjoy it! :P

Re: NUT Mini BATTERY SERVICE

Posted: Wednesday 01 March 2017 1:10
by deennoo
Great script !

Beacon Presence and battery check can be run on the same time ! just need to get two ble dongle ;-)

Please can you englize a bit your script or change name for the beacon presence script ? NomeServizioBeacon.service ?

how long it takes to get batterie statuts from the nut ?

Re: NUT Mini BATTERY SERVICE

Posted: Wednesday 01 March 2017 15:26
by emme
using the onboard BT radio on mi PI3 I cannot scan and get UUID ad the same time.
I need to recycle the interface HCI0

More, but I think this is Nut related, you cannot scan from one inferface and query from another....


here's a copy of a much more comprehensive script :P

ciao
M

Code: Select all

#!/bin/bash 

# NUTSpace NUT Mini Battery Service Inquiry
# -----------------------------------------
# Author: MrEmme
# ver.: 1.0
#
# INSTRUCTION
# -----------------------------------------
# This script will gather battery information
# from BLE device NUT Mini
# and update a Domoticz Variable with its value
# 
# Minimal user parameters are required:


# SETTING UP PARAMETERS
## DOMOTICZ SETUP (no authentication required, ensure that you have IP in whitelist)
DOMOIP="127.0.0.1"   # Domoticz Server IP 
DOMOPORT="8080"      # Domoticz Server Port

# DOMOTICZ STATUS INQUIRY
# Set to "1" if you want to check if the NUT switch is on before 
#            getting the battery data
# Set to anything else if you DO NOT want to check the status
#        and process all the NUT in the list (could take longer
#        and generate errors due to unavailability
DCHECKSTS="1"
# If a NUT is unaccessible enter the result string
# Otherwise it would be set to 0
BATTAWAYMSG="UNAVAILABLE"

# BEACON SERVICE DISCOVERY
# Battery and Beacon cannot coexist at the same time
# if you have a Beacon discovery service running
# this is the right place to identify it and 
# disable it while getting Batt information 
# Set to "1" if you want to disable the service
# Set to anything else if you DO NOT want to disable the service
USEBEACONSERVICE="1"
# Set the Service name 
BEACONSERVICENAME="beaconServiceName.service"
# INTERFACE NAME
# Once stopped the service, BLE interface needs to be resetted
# normally it is hci0
HCIINTERFACE="hci0"

# NUT LIST 
# Set the "MAC ADDRESS" "Domoticz Variable Name" "Switch IDX"
# each line is a NUT
# Add as many line as you need
NUTBATT=(
   "00:00:00:00:00:00" "Variabile_Nome_Batteria" "IDX switch ON/OFF"
)


# DO NOT CHANGE ANYTHING BEYOND THIS POINT
BATTUUID="0x2a19"   # UUID for Battery HEX Value
DAWVAR="/json.htm?type=command&param=updateuservariable&vname=VARIABLENAME&vtype=2&vvalue=VARIABLEVALUE"
DARDEV="/json.htm?type=devices&rid=DEVICEIDX"

function domoWriteVar () {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DAWVAR
    URLREQ="${URLREQ/VARIABLENAME/${NUTBATT[arrNut+1]}}"
    URLREQ="${URLREQ/VARIABLEVALUE/$1}"
    dzAPIWriteVar=$(curl -s "$URLREQ" ) 
 
}

function domoGetStatus {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DARDEV
    #echo $URLREQ
    dzAPIStatus="${URLREQ/DEVICEIDX/${NUTBATT[arrNut+2]}}"

# Getting switch status prom Domoticz
    dzDevRAW=$(curl -s "$dzAPIStatus")
    dzDevJSON=$(echo ${dzDevRAW} | jq .result[0].Data)
    dzDevSTATUS=$(echo $dzDevJSON | sed "s/\"//g")
}

function svcBeacon() {
    if [[ $1 == "stop" ]]; then
        echo "Stopping Beaconing Service"
        sudo systemctl stop ${BEACONSERVICENAME}
    fi
    
    if [[ $1 == "start" ]]; then
        echo "Starting Beaconing Service"
        sudo systemctl start ${BEACONSERVICENAME}
    fi
}

function restartHCI () {
    sudo hciconfig ${HCIINTERFACE} down 
    sleep 1 
    sudo hciconfig ${HCIINTERFACE} up 
}

function getBLEBat (){
    restartHCI

    HANDLE=$(sudo hcitool lecc --random ${NUTBATT[arrNut]} | awk '{print $3}')
    sleep 1
    sudo hcitool ledc $HANDLE
    BATHEX=$(sudo gatttool -t random --char-read --uuid $BATTUUID -b ${NUTBATT[arrNut]} | awk '{print $4}')
    BATDEC=$((0x$BATHEX))

    if [ "$BATDEC" == "0" ]; then
       BATDEC=$BATTAWAYMSG
    fi
    echo "Risultato finale: HEX :"$BATHEX" DEC: "$BATDEC
    domoWriteVar $BATDEC
}

# - - - - - - - - - - - 
# BEGINNING MAIN SCRIPT
# - - - - - - - - - - - 

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "stop"
fi

    printf "\n- - - - - - - - - - - - - - -\n" 

for arrNut in $(seq 0 3 $((${#NUTBATT[@]} - 1))); do
    if [[ $DCHECKSTS == "1" ]]; then
        domoGetStatus
        echo "Analyzing NUT: "${NUTBATT[arrNut+1]}" Domoticz State: "$dzDevSTATUS
    else
        dzDevSTATUS="On"
    fi
    
    if [[ $dzDevSTATUS == "On" ]]; then
        echo "Proceeding seeking for Battery Info"
        restartHCI
        getBLEBat
        dzDevSTATUS="Off"
    else
       echo "NUT Unavailable, skipping"
    fi 
    printf "\n- - - - - - - - - - - - - - -\n" 
done

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "start"
fi

Re: NUT Mini BATTERY SERVICE

Posted: Wednesday 30 August 2017 12:57
by emme
little short update....
I now used a different approach in contacting BLEs and check their availbility:
I use the result of hcitool lescan to grep the mac of my nuts... (uh oh... :o :o sounds wired... :o :o ) handling a simple boolean if there is or there is not...

I use one script to check presence and gathering the battery data.
Here's how it works:
I have 2 variable for each NUT: presence (Home/Away) and Battery level
and a switch for each person (that owns a Nut)

the script will:
- gather BLE device in the air
- Check the Macs
- Get the related switch status
- Compare presence/switch status and update accordingly
- if the state change from OFF to ON check the battery


here is the script:

Code: Select all

#!/bin/bash

# SETTING UP PARAMETERS

## DOMOTICZ SETUP (no authentication required, ensure that you have IP in whitelist)

DOMOIP="127.0.0.1"
DOMOPORT="8080"
DAWVAR="/json.htm?type=command&param=updateuservariable&vname=VARIABLENAME&vtype=2&vvalue=VARIABLEVALUE"
DARDEV="/json.htm?type=devices&rid=DEVICEIDX"


DCHECKSTS="1"
#Check status of switches before continuing
#Set to 0 to force all configured NUT

BATTUUID="0x2a19"
BATTAWAYMSG="UNAVAILABLE"

# Creating Main array (MAC Address UPPERCASE - Variable Name - Switch Name - NUT Device (variable) Name )
NUTBATT=(
   "XX:XX:XX:XX:XX:XX" "NUT_Name_Batery" "999" "NUT_Name"
   "XX:XX:XX:XX:XX:XX" "NUT_Name_Batery2" "998" "NUT_Name2"
)

# Other Parameters
USEBEACONSERVICE="0"
#Set to 0 if you do not have a beaconing serive deamon running

BEACONSERVICENAME="ble.service"
HCIINTERFACE="hci0"
BLEDISCOVERY=5   #Timeout for BLE Discovery
BLEDISCFILE="/home/pi/ScanResult.txt"

function domoWriteVar () {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DAWVAR
#    URLREQ="${URLREQ/VARIABLENAME/${NUTBATT[arrNut+1]}}"
    URLREQ="${URLREQ/VARIABLENAME/$2}"
    URLREQ="${URLREQ/VARIABLEVALUE/$1}"
    dzAPIWriteVar=$(curl -s "$URLREQ" )

}

function domoGetStatus {
    URLREQ="http://"$DOMOIP":"$DOMOPORT$DARDEV
    #echo $URLREQ
    dzAPIStatus="${URLREQ/DEVICEIDX/${NUTBATT[arrNut+2]}}"

# Getting switch status prom Domoticz
    dzDevRAW=$(curl -s "$dzAPIStatus")
    dzDevJSON=$(echo ${dzDevRAW} | jq .result[0].Data)
    dzDevSTATUS=$(echo $dzDevJSON | sed "s/\"//g")
}


function svcBeacon() {
    if [[ $1 == "stop" ]]; then
        echo "Stopping Beaconing Service"
        sudo systemctl stop ${BEACONSERVICENAME}
    fi

    if [[ $1 == "start" ]]; then
        echo "Starting Beaconing Service"
        sudo systemctl start ${BEACONSERVICENAME}
    fi
}

function restartHCI () {
    sudo hciconfig ${HCIINTERFACE} down
    sleep 1
    sudo hciconfig ${HCIINTERFACE} up
}

function getBLEBat (){
    restartHCI

    HANDLE=$(sudo hcitool lecc --random ${NUTBATT[arrNut]} | awk '{print $3}')
    sleep 1
    sudo hcitool ledc $HANDLE
    BATHEX=$(sudo gatttool -t random --char-read --uuid $BATTUUID -b ${NUTBATT[arrNut]} | awk '{print $4}')
    BATDEC=$((0x$BATHEX))

#    if [ "$BATDEC" == "0" ]; then
#       BATDEC=$BATTAWAYMSG
#    fi
    echo "Risultato finale: HEX :"$BATHEX" DEC: "$BATDEC

   if [ "$BATDEC" -ne "0" ]; then
       domoWriteVar $BATDEC ${NUTBATT[arrNut+1]}
    fi
}

function discBLE (){
   restartHCI
   timeout -s SIGINT ${BLEDISCOVERY}s hcitool -i $HCIINTERFACE lescan > $BLEDISCFILE
   restartHCI

}

function nutLookup (){
   if [ -s $BLEDISCFILE ]; then
      if grep -q "${NUTBATT[arrNut]}" ${BLEDISCFILE}; then
	     printf "== NUT found in BLE Scan!\n"
		 if [[ $dzDevSTATUS == "Off" ]]; then
		    printf "Updating Variable AWAY => HOME\n"
			domoWriteVar "HOME" ${NUTBATT[arrNut+3]}
			getBLEBat
		 fi
	  else
	     printf "XX NUT not found in BLE Scan!\n"
		 if [[ $dzDevSTATUS == "On" ]]; then
		    printf "Updating Variable HOME => AWAY\n"
			domoWriteVar "AWAY" ${NUTBATT[arrNut+3]}
		 fi
	  fi
   fi
}

# BEGINNING MAIN SCRIPT
discBLE

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "stop"
fi

    printf "\n- - - - - - - - - - - - - - -\n"

for arrNut in $(seq 0 4 $((${#NUTBATT[@]} - 1))); do
    if [[ $DCHECKSTS == "1" ]]; then
        domoGetStatus
        echo "Analyzing NUT: "${NUTBATT[arrNut+3]}" Domoticz State: "$dzDevSTATUS
    else
        dzDevSTATUS="On"
    fi
    nutLookup

    printf "\n- - - - - - - - - - - - - - -\n"
done

if [[ $USEBEACONSERVICE == "1" ]]; then
    svcBeacon "start"
fi

it requires jq utility

I also placed the script as a cronjob under ROOT (as pi it does not works :( )

Code: Select all

* * * * * sleep 30; /home/pi/script.sh
so it runs every 30 secs
It clould also work as a service placing a loop and a sleep ;)

Re: NUT Mini BATTERY SERVICE

Posted: Saturday 10 February 2018 14:16
by RedFish
Hi;

For this moment i work with JSON code here =>www.domoticz.com/wiki/Presence_detectio ... _Beacon%29

But for upload battery poucent you're code is very good; but i should know if you're code test presence and battery always or just changed switch when nut change status.

Sorry for my english.....

Re: NUT Mini BATTERY SERVICE

Posted: Sunday 11 February 2018 20:22
by emme
the script tests battery only once the first time the nut became available
it means that (for example) during the weened (from friday to monday) you won't get battery test if you don't go out :P :P

Re: NUT Mini BATTERY SERVICE

Posted: Tuesday 13 February 2018 18:54
by RedFish
Ok; i test this for watch !!

Have you got script for ring the Nut ??

Re: NUT Mini BATTERY SERVICE

Posted: Tuesday 13 February 2018 20:59
by RedFish
I try you're script but i've got an error:

pi@raspberry:/home/domoticz/scripts $ sudo python test.py
File "test.py", line 34
function domoWriteVar () {
^
SyntaxError: invalid syntax

Re: NUT Mini BATTERY SERVICE

Posted: Wednesday 14 February 2018 8:08
by emme
that is not a python script but a bash
you should name it .sh, give it +x rights and run it as sudo ./script.sh ;)

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 11:02
by Olivrius
Thank you very much for your script, it's great !!!

I try do use it and i have this following message with an error at the end :
"
- - - - - - - - - - - - - - -
Proceeding seeking for Battery Info
Risultato finale: HEX :64 DEC: 100

- - - - - - - - - - - - - - -
./bat_nut_info.sh: ligne 292: erreur de syntaxe : fin de fichier prématurée

Sorry, it's in French, the last line says : Line 292: syntax error: prematured end of file
"
I don't understand, there is no line 292 in your script. Can you still help me please ?

++

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 11:28
by emme
so.. it runs (you got the first BLE checked) but then there is an error....
line numbers changes if you add/remove BLE config... so....
could you please post line 292?

thanks
ciao
M

P.S.
line 292?!... the script does not arrive to such a line.....

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 12:13
by Olivrius
Hi emme,

Finaly it's OK, i've paste a bad code in the script.

I have this answer :

- - - - - - - - - - - - - - -
Proceeding seeking for Battery Info
Résultat final: HEX :64 DEC: 100

- - - - - - - - - - - - - - -

So my battery is still a level available of 64%. Isn't it ?

Thank you !!!

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 13:44
by emme
no.. 64 is the BLE HEX returned value
it gets converted to DEC ==> 100

in my opinion based on my experience with NUT that value is not extremely reliable... I don0t know exactely how NUT handle the battery service (NUTSPACE won't deliver API :( )
based on this... I changed the way to handle BLE... and I have discontinued the battery inquiry.... a 3 months reminder to replace the battery is enough
Even if I have seen lower RSSI values when the battery drains.

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 15:45
by Olivrius
OK thank you one more time for your advices.

So, if i understand, in my case, my battery is 100% charged.

++

Re: NUT Mini BATTERY SERVICE

Posted: Thursday 12 July 2018 15:50
by emme
that's correct

Re: NUT Mini BATTERY SERVICE

Posted: Sunday 23 September 2018 19:34
by pimseb
Hello

I have an error when trying to run the script :

sudo sh battery.sh
battery.sh: 20: battery.sh: Syntax error: "(" unexpected

line 20 corresponds to : NUTBATT=(

What's going on ?
Thank you

Re: NUT Mini BATTERY SERVICE

Posted: Monday 24 September 2018 8:14
by emme
if you copy/paste from the browser to the telnel/ssh console on a windows PC you could get some troubles with the CR code....

can you please post few lines above and under line 20?
ciao
M

Re: NUT Mini BATTERY SERVICE

Posted: Monday 24 September 2018 9:03
by pimseb
I copied it from the browser into my linux terminal (I'm under linux). I've also tried in windows

Code: Select all

pi@raspberrypi:~/domoticz $ sh beacon_battery.sh
beacon_battery.sh: 21: beacon_battery.sh: Syntax error: "(" unexpected
pi@raspberrypi:~/domoticz $
Here is my sh file :

Code: Select all

BATTUUID="0x2a19"
BATTAWAYMSG="UNAVAILABLE"

# Creating Main array (MAC Address UPPERCASE - Variable Name - Switch Name - NUT Device (variable) Name )
NUTBATT=(
   "A0:EF:34:0A:81:B0" "Tag_pim" "presence_pim" "NUT_pim"
)

# Other Parameters
USEBEACONSERVICE="0"
#Set to 0 if you do not have a beaconing serive deamon running

BEACONSERVICENAME="ble.service"

Re: NUT Mini BATTERY SERVICE

Posted: Monday 24 September 2018 9:07
by emme
mmmh... probably if you have just one nut, you won't need to split by lines....
tru with
NUTBATT=("A0:EF:34:0A:81:B0" "Tag_pim" "presence_pim" "NUT_pim")

also...
try with:
chmod +x <scriptname.sh>
and then call it using ./<scriptname.sh>

Re: NUT Mini BATTERY SERVICE

Posted: Monday 24 September 2018 9:17
by pimseb
it now works when I cal l it with ./<scriptname.sh> instead of sudo sh <scriptname.sh> !!
Thank you