Plugin - SNMP Value Reader (Debian)

Python and python framework

Moderator: leecollings

Post Reply
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Plugin - SNMP Value Reader (Debian)

Post by ycahome »

Hi there,

just finished the first version of the "SNMP Value Reader" plugin.

With this plugin you can bring one SNMP OID each time on your Domoticz server.

Debian Requirements:
- Install "python-pysnmp-common" with "sudo apt-get install python3-pysnmp4"

Domoticz Installation instructions:
- Create Plugin Folder "SNMPreader" under "domoticz/plugins" folder
- Save this script as "plugin.py" on "SNMPreader" folder
- Restart domoticz service.
- Add a new entry of this Hardware on your domoticz installation (Setup/Hardware/select and add "Wan Ip Checker")

Hope you like it!!


Version 1.0.0 - Updated on 2017-03-17

Develompent is maintained to GitHub - https://github.com/ycahome/SNMPreader

Code: Select all


#
#   SNMPreader Plugin
#
#   Ycahome, 2017
#   https://www.domoticz.com/forum
#
#
"""
<plugin key="SNMPreader" name="SNMP Value Reader" author="ycahome" version="1.0.0" wikilink="m" externallink="https://www.domoticz.com/forum/viewtopic.php?f=65">
    <params>
        <param field="Address" label="Server IP" width="200px" required="true" default="192.168.1.1"/>
        <param field="Mode1" label="OID" width="200px" required="true" default="1.3.6.1.2.1.25.3.2.1.1.2"/>
        <param field="Mode2" label="Community" width="200px" required="true" default="public"/>
        <param field="Mode3" label="Domoticz TypeName" width="200px">
            <options>
                <option label="Custom" value="Custom"/>
                <option label="Text" value="Text"/>
                <option label="Temperature" value="Temperature"  default="true" />
            </options>
        </param>
        <param field="Mode6" label="Debug" width="75px">
            <options>
                <option label="True" value="Debug"/>
                <option label="False" value="Normal"  default="true" />
            </options>
        </param>
    </params>
</plugin>
"""
import Domoticz

import sys
sys.path.append('/usr/lib/python2.7/dist-packages/')
from pysnmp.entity.rfc3413.oneliner import cmdgen


import json
import urllib.request
import urllib.error

from math import radians, cos, sin, asin, sqrt
from datetime import datetime, timedelta


#############################################################################
#                      Domoticz call back functions                         #
#############################################################################

def onStart():

    global gdeviceSuffix
    global gdeviceTypeName

    gdeviceSuffix = "(SNMP)"
    interval = 1

    createDevices()
    if Parameters["Mode6"] == "Debug":
        DumpConfigToDebug()
    DumpConfigToLog()


    ServerIP = str(Parameters["Address"])
    snmpOID = str(Parameters["Mode1"])
    snmpCommunity = Parameters["Mode2"]

    snmpDataValue = getSNMPvalue(ServerIP,snmpOID,snmpCommunity)


    Domoticz.Heartbeat(interval)
    return True

def onHeartbeat():

    ServerIP = str(Parameters["Address"])
    snmpOID = str(Parameters["Mode1"])
    snmpCommunity = Parameters["Mode2"]

    # Get new information and update the devices
    snmpDataValue = getSNMPvalue(ServerIP,snmpOID,snmpCommunity)



    UpdateDevice(1,0,snmpDataValue)

    if Parameters["Mode6"] == "Debug":
        Domoticz.Log("SNMP Value retrieved:"+snmpDataValue)


    return True

#############################################################################
#                         Domoticz helper functions                         #
#############################################################################

def DumpConfigToDebug():
    for x in Parameters:
        if Parameters[x] != "":
            Domoticz.Log("'" + x + "':'" + str(Parameters[x]) + "'")
    Domoticz.Debug("Device count: " + str(len(Devices)))
    for x in Devices:
        Domoticz.Log("Device:           " + str(x) + " - " + str(Devices[x]))
        Domoticz.Log("Device ID:       '" + str(Devices[x].ID) + "'")
        Domoticz.Log("Device Name:     '" + Devices[x].Name + "'")
        Domoticz.Log("Device nValue:    " + str(Devices[x].nValue))
        Domoticz.Log("Device sValue:   '" + Devices[x].sValue + "'")

def DumpConfigToLog():
    for x in Parameters:
        if Parameters[x] != "":
            Domoticz.Log("'" + x + "':'" + str(Parameters[x]) + "'")
    Domoticz.Log("Device count: " + str(len(Devices)))
    for x in Devices:
        Domoticz.Log("Device:           " + str(x) + " - " + str(Devices[x]))
        Domoticz.Log("Device ID:       '" + str(Devices[x].ID) + "'")
        Domoticz.Log("Device Name:     '" + Devices[x].Name + "'")
        Domoticz.Log("Device nValue:    " + str(Devices[x].nValue))
        Domoticz.Log("Device sValue:   '" + Devices[x].sValue + "'")

def UpdateDevice(Unit, nValue, sValue):

    # Make sure that the Domoticz device still exists before updating it.
    # It can be deleted or never created!
    if (Unit in Devices):

        Devices[Unit].Update(nValue, str(sValue))
        if Parameters["Mode6"] == "Debug":
            Domoticz.Debug("Update " + str(nValue) + ":'" + str(sValue) + "' (" + Devices[Unit].Name + ")")

#############################################################################
#                       Device specific functions                           #
#############################################################################

def createDevices():

    # Are there any devices?
    if len(Devices) != 0:
        # Could be the user deleted some devices, so do nothing
        if Parameters["Mode6"] == "Debug":
            Domoticz.Debug("Devices Already Exist.")
        return

    # Give the devices a unique unit number. This makes updating them more easy.
    # UpdateDevice() checks if the device exists before trying to update it.

    # Add Power and temperature device(s)
    Domoticz.Device(Name=gdeviceSuffix, Unit=1, TypeName=Parameters["Mode3"]).Create()

    Domoticz.Log("Devices created.")


def getSNMPvalue(ServerIP,snmpOID,snmpCommunity):

    if Parameters["Mode6"] == "Debug":
        Domoticz.Log("var ." + str(ServerIP))
        Domoticz.Log("var ." + str(snmpOID))
        Domoticz.Log("var ." + str(snmpCommunity))

    cmdGen = cmdgen.CommandGenerator()

    #genData = cmdgen.CommunityData('public')
    genData = cmdgen.CommunityData(str(snmpCommunity))
    if Parameters["Mode6"] == "Debug":
        Domoticz.Log("genData Loaded." + str(genData))

    TTData = cmdgen.UdpTransportTarget((str(ServerIP), 161), retries=2)
    if Parameters["Mode6"] == "Debug":
        Domoticz.Log("TTData Loaded." + str(TTData))

    errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(genData,TTData,snmpOID)
    if Parameters["Mode6"] == "Debug":
        Domoticz.Log("DATA Loaded." + str(varBinds))

    # Check for errors and print out results
    if errorIndication:
        Domoticz.Log(str(errorIndication))
    else:
        if errorStatus:
            Domoticz.Log('%s at %s' % (errorStatus.prettyPrint(),errorIndex and varBinds[int(errorIndex)-1] or '?'))
        else:
            for name, val in varBinds:
                if Parameters["Mode6"] == "Debug":
                    Domoticz.Log('%s = %s' % (name.prettyPrint(), val.prettyPrint()))


                    return val.prettyPrint()

#
# Parse an int and return None if no int is given
#

def parseIntValue(s):

        try:
            return int(s)
        except:
            return None

#
# Parse a float and return None if no float is given
#

def parseFloatValue(s):

        try:
            return float(s)
        except:
            return None



Last edited by ycahome on Wednesday 01 April 2020 19:58, edited 3 times in total.
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

Next version will contain simple calculations on the value returned.
Let me know if anyone interested...
gerardvs
Posts: 81
Joined: Sunday 04 January 2015 0:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest-1
Location: /dev/null
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by gerardvs »

Nice! This was also on my todo list.
Do you have the code on github so we can easily install and maintain subsequent releases?

I know there are other opinions but new Python code should be written in in Python3. ;)

--Gerard
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

gerardvs wrote:Nice! This was also on my todo list.
Do you have the code on github so we can easily install and maintain subsequent releases?

I know there are other opinions but new Python code should be written in in Python3. ;)

--Gerard

Hello Gerard,

no, unfortunately am not yet a github user. Also, we are not yet "close friends" with python.
Feel free to suggest mods!!

I believe that this functionality should be native on Domoticz, with a similar implementation like "System Checker"
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

gerardvs wrote: Friday 17 March 2017 15:59 Do you have the code on github so we can easily install and maintain subsequent releases?
Finally I have managed to use GitHub for some of my plugins. List will be updated soon.
Feel free to clone/contribute.
gerardvs
Posts: 81
Joined: Sunday 04 January 2015 0:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest-1
Location: /dev/null
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by gerardvs »

I see on your github you use python 2.7. Is that wise to do since Domoticz has a dependency of Python 3?

A year ago I also made a proof of concept which works fine but there is a memory leak (due to Python3? ;) ) so I didn't continue so far.

I will follow you progress, good luck!
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

gerardvs wrote: Saturday 17 February 2018 17:55 I see on your github you use python 2.7. Is that wise to do since Domoticz has a dependency of Python 3?

A year ago I also made a proof of concept which works fine but there is a memory leak (due to Python3? ;) ) so I didn't continue so far.

I will follow you progress, good luck!

You are totally right.
Unfortunately, didn't found yet a way to make "pysnmp" work with python 3.5+

If you have an idea, am all ears!!! :-)
gerardvs
Posts: 81
Joined: Sunday 04 January 2015 0:01
Target OS: Raspberry Pi / ODroid
Domoticz version: latest-1
Location: /dev/null
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by gerardvs »

This is how I made a simple piece to test. https://github.com/seventer/tonq Don't mind the name, i assume you get the origin of it. :geek:
Be aware of the memory leak so some refactoring of the code is needed. So far I hadn't the time to look into it.

--Gerard
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

gerardvs wrote: Saturday 17 February 2018 21:28 This is how I made a simple piece to test. https://github.com/seventer/tonq Don't mind the name, i assume you get the origin of it. :geek:
Be aware of the memory leak so some refactoring of the code is needed. So far I hadn't the time to look into it.

--Gerard
I think that I 've managed to make it work with python3. (https://github.com/ycahome/SNMPreader)
Am testing it now.
assenzuid
Posts: 135
Joined: Friday 13 November 2015 9:11
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: The Netherlands, Emmen Area
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by assenzuid »

I want to monitor a remote nas where I have change the default port in the router to response at.

xxxxxxbackup:port is not working,

Log

Code: Select all

2018-05-31 23:21:23.006 Error: (xxxxxxbackup Temp) 'onHeartbeat' failed 'PySnmpError'.
2018-05-31 23:21:23.006 Error: (xxxxxxbackup Temp) ----> Line 89 in /home/pi/domoticz/plugins/SNMPreader/plugin.py, function onHeartbeat
2018-05-31 23:21:23.007 Error: (xxxxxxbackup Temp) ----> Line 152 in /home/pi/domoticz/plugins/SNMPreader/plugin.py, function getSNMPvalue
2018-05-31 23:21:23.007 Error: xxxxxxbackup Temp) ----> Line 10 in /usr/lib/python3/dist-packages/pysnmp/entity/rfc3413/oneliner/target.py, function __init__
2018-05-31 23:21:23.007 Error: (nashomebackup Temp) ----> Line 45 in /usr/lib/python3/dist-packages/pysnmp/entity/rfc3413/oneliner/target.py, function _resolveAddr
pizzulicchio
Posts: 15
Joined: Wednesday 24 April 2019 14:01
Target OS: Linux
Domoticz version: beta
Location: Italy
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by pizzulicchio »

Hi,
i'm using this plugin with success, but i have noticed that isn't possible to retreive data from device with snmp version 1.0
I'm be able to use every device with correct id and snmp version 2c.

Is it possible to add support for snmp v1 ?

Many old or elementary devices use only snmp v1.

Have a nice day
Draakje
Posts: 140
Joined: Thursday 22 October 2015 21:14
Target OS: Linux
Domoticz version: 4.11539
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by Draakje »

I would also love to see some support for v1 snmp.

My device (Atal Temp/humidity sensor) does only do v1 ..

I can read it out with snmp but my knowledge of python is just to low to fix the script
Hardware: Raspberry Pi 3, OTGW, 433MHz Superheterodyne 3310 RF Link
Software: Ubuntu 16.04, Domoticz v3.5468, WiringPi, rc-switch
User avatar
ycahome
Posts: 248
Joined: Sunday 12 February 2017 10:55
Target OS: Linux
Domoticz version: lat Beta
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by ycahome »

Hello,

SNMP v2 is not tested with this plugin and i think that uses variables instead of keys (or both).
plugin language is not so flexible with different set of plugin variable requirements.

So, seems that a different plugin might need to be created.
I will try to find time to write it. Feel free to collaborate on github bellow

https://github.com/ycahome/SNMPreader
Draakje
Posts: 140
Joined: Thursday 22 October 2015 21:14
Target OS: Linux
Domoticz version: 4.11539
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by Draakje »

We were talking about v1 :) but that doesn't matter.


I have created my own dzvents script (with some help from other scripts.)

Here is my script.. It is quite simpel and it could be made better :) (more modulair or whatever)
But it does the trick.

It was based on a lua script made by papoo .(synology2.lua source: https://github.com/papo-o/domoticz_scri ... ology2.lua)

I create this for simple SNMP read out (version can simple be changed to v2)

Code: Select all

--[[
Install SNMP on Raspberry Pi
Log in to you Raspberry Pi and issue:
sudo apt-get install snmpd
sudo apt-get install snmp

Create Virtual/Dummy devices in domoticz

--]]
return {
    active = true,
    on = {
    timer = {'every minute'}
    },    


logging =   {  --level    =    domoticz.LOG_DEBUG,                                              -- Only one level can be active; comment others                                      
                level    =   domoticz.LOG_INFO,                                            
                -- level    =   domoticz.LOG_ERROR,
                -- level    =   domoticz.LOG_MODULE_EXEC_INFO,
                   marker    =   "ATAL Temperature/Humidity"      },                            --Display name in LOG


execute = function(domoticz, device)
    
    local DeviceIP = "<ip addres>"                                                               --Device IP Address
    local CommunityPassword = "<password>"                                                          --SNMP Community password

    local Device_Temp = "ATAL Temperature"                                                      --Device Name in Domoticz
    local Device_Hum = "ATAL Humidity"                                                          --Device Name in Domoticz

    local OID_Temperature = '1.3.6.1.4.1.22626.1.2.1.1.0'                                       --OID for Temperature
    local OID_Humidity = '1.3.6.1.4.1.22626.1.2.1.2.0'                                          --OID for Humidity

    local command = 'snmpget -v 1 -c '..CommunityPassword..' -O qv '..DeviceIP..' '..OID_Temperature..' '..OID_Humidity..' '    --Define Bash command to readout SNMP
    
    local i, results = 0, {}                                                                    --Define local Variables to be able to use them later
    
    local handle = assert(io.popen(command))                                                    --Execute command to get SNMP info
        for line in handle:lines() do                                                           --Capture SNMP output in Array
            results[i] =  line:gsub('"','')                                                     --Remove Double Quotes from entry
            i = i + 1                                                                           --Increment Array index
        end
    handle:close()

    if results[0] then domoticz.log(""..Device_Temp.." : "..results[0],domoticz.LOG_DEBUG)      --If Array index 0 is present print Debug if debug is active (see above)
        domoticz.devices(Device_Temp).updateTemperature(results[0]) end                         --Update Device in Domoticz with value from Array

    if results[1] then domoticz.log( "" ..Device_Hum.. " : "..results[1],domoticz.LOG_DEBUG)    --If Array index 1 is present print Debug if debug is active (see above)
        local hum = domoticz.utils.round((results[1]),0)                                        --Round value with no decimals, Humidity is displayed in a round percentage
        local temp = tonumber(results[0])                                                       --Convert Temperature (Array Index0) to number to be able to compare
        
        if (hum < 30) then                                                                      --If Humidity is lower than 30% condition is DRY (equals to 2)
            humstat = 2
        elseif (hum > 70) then                                                                  --If Humidity is higher than 70% condition is WET (equals to 3)
            humstat = 3
        elseif ((hum >= 30 and hum <=70) and (temp >= 22 and temp <= 26)) then                  --If Humidity is between 30% and 70% AND temperature is between 22 Degrees and 26 Degrees condition is Comfort (equals to 1)
            humstat = 1
        else
            humstat = 0 end                                                                     --Set Humidity to condition NORMAL if non of the above apply (equals to 0)
        
        domoticz.devices(Device_Hum).update(hum,humstat)                                        --Update Device in Domoticz with value from array and condition.
  end      

end
}

Hardware: Raspberry Pi 3, OTGW, 433MHz Superheterodyne 3310 RF Link
Software: Ubuntu 16.04, Domoticz v3.5468, WiringPi, rc-switch
kllngtme
Posts: 47
Joined: Tuesday 14 June 2016 16:56
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: East Coast, USA
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by kllngtme »

Draakje wrote: Thursday 02 April 2020 20:33 I have created my own dzvents script (with some help from other scripts.)

Here is my script.. It is quite simpel and it could be made better :) (more modulair or whatever)
I'm trying to utilize the same idea with a device in my network. I can run an snmpget on the pi with no issues and bring up the results but I'm having issues incorporating the script and such into Domoticz.

I added the dzvents script much like you did but I'm not getting the virtual sensor to update. I created a temperature virtual sensor and had it named accordingly. Am I missing something else?

Code: Select all

--[[
Install SNMP on Raspberry Pi
Log in to you Raspberry Pi and issue:
sudo apt-get install snmpd
sudo apt-get install snmp

Create Virtual/Dummy devices in domoticz

--]]
return {
    active = true,
    on = {
    timer = {'every minute'}
    },    


logging =   {  --level    =    domoticz.LOG_DEBUG,                                              -- Only one level can be active; comment others                                      
                level    =   domoticz.LOG_INFO,                                            
                -- level    =   domoticz.LOG_ERROR,
                -- level    =   domoticz.LOG_MODULE_EXEC_INFO,
                   marker    =   "Attic"      },                            --Display name in LOG


execute = function(domoticz, device)
    
    local DeviceIP = "192.168.1.24"                                                               --Device IP Address
    local CommunityPassword = "public"                                                          --SNMP Community password

    local Device_Temp = "AtticTemp"                                                      --Device Name in Domoticz
    local Device_Hum = "AtticHumid"                                                          --Device Name in Domoticz

    local OID_Temperature = '1.3.6.1.4.1.20916.1.6.1.2.2.1.0'                                       --OID for Temperature for Attic
    local OID_Humidity = '1.3.6.1.4.1.20916.1.6.1.2.2.3.0'                                          --OID for Humidity for Attic

    local command = 'snmpget -v 1 -c '..CommunityPassword..' -O qv '..DeviceIP..' '..OID_Temperature..' '..OID_Humidity..' '    --Define Bash command to readout SNMP
    
    local i, results = 0, {}                                                                    --Define local Variables to be able to use them later
    
    local handle = assert(io.popen(command))                                                    --Execute command to get SNMP info
        for line in handle:lines() do                                                           --Capture SNMP output in Array
            results[i] =  line:gsub('"','')                                                     --Remove Double Quotes from entry
            i = i + 1                                                                           --Increment Array index
        end
    handle:close()

    if results[0] then domoticz.log(""..Device_Temp.." : "..results[0],domoticz.LOG_DEBUG)      --If Array index 0 is present print Debug if debug is active (see above)
        domoticz.devices(Device_Temp).updateTemperature(results[0]) end                         --Update Device in Domoticz with value from Array

    if results[1] then domoticz.log( "" ..Device_Hum.. " : "..results[1],domoticz.LOG_DEBUG)    --If Array index 1 is present print Debug if debug is active (see above)
        local hum = domoticz.utils.round((results[1]),0)                                        --Round value with no decimals, Humidity is displayed in a round percentage
        local temp = tonumber(results[0])                                                       --Convert Temperature (Array Index0) to number to be able to compare
        
        if (hum < 30) then                                                                      --If Humidity is lower than 30% condition is DRY (equals to 2)
            humstat = 2
        elseif (hum > 70) then                                                                  --If Humidity is higher than 70% condition is WET (equals to 3)
            humstat = 3
        elseif ((hum >= 30 and hum <=70) and (temp >= 22 and temp <= 26)) then                  --If Humidity is between 30% and 70% AND temperature is between 22 Degrees and 26 Degrees condition is Comfort (equals to 1)
            humstat = 1
        else
            humstat = 0 end                                                                     --Set Humidity to condition NORMAL if non of the above apply (equals to 0)
        
        domoticz.devices(Device_Hum).update(hum,humstat)                                        --Update Device in Domoticz with value from array and condition.
  end      

end
}
Domoticz logs:
2021-01-29 16:10:00.111 Status: dzVents: Info: Attic: ------ Start internal script: Attic:, trigger: "every minute"
2021-01-29 16:10:00.114 Status: dzVents: Info: Attic: ------ Finished Attic
Draakje
Posts: 140
Joined: Thursday 22 October 2015 21:14
Target OS: Linux
Domoticz version: 4.11539
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by Draakje »

Whatis the snmpget command you use? (the one that is working manually)

I can't see anything wrong with the script (as is is pretty much the same as mine)
you can also set debugging on by putting the level on debug (and disable info logging)

logging = { level = domoticz.LOG_DEBUG, -- Only one level can be active; comment others
--level = domoticz.LOG_INFO,
-- level = domoticz.LOG_ERROR,
-- level = domoticz.LOG_MODULE_EXEC_INFO,
marker = "ATAL Temperature/Humidity" },



kllngtme wrote: Friday 29 January 2021 22:13
Draakje wrote: Thursday 02 April 2020 20:33 I have created my own dzvents script (with some help from other scripts.)

Here is my script.. It is quite simpel and it could be made better :) (more modulair or whatever)
I'm trying to utilize the same idea with a device in my network. I can run an snmpget on the pi with no issues and bring up the results but I'm having issues incorporating the script and such into Domoticz.

I added the dzvents script much like you did but I'm not getting the virtual sensor to update. I created a temperature virtual sensor and had it named accordingly. Am I missing something else?

Code: Select all

--[[
Install SNMP on Raspberry Pi
Log in to you Raspberry Pi and issue:
sudo apt-get install snmpd
sudo apt-get install snmp

Create Virtual/Dummy devices in domoticz

--]]
return {
    active = true,
    on = {
    timer = {'every minute'}
    },    


logging =   {  --level    =    domoticz.LOG_DEBUG,                                              -- Only one level can be active; comment others                                      
                level    =   domoticz.LOG_INFO,                                            
                -- level    =   domoticz.LOG_ERROR,
                -- level    =   domoticz.LOG_MODULE_EXEC_INFO,
                   marker    =   "Attic"      },                            --Display name in LOG


execute = function(domoticz, device)
    
    local DeviceIP = "192.168.1.24"                                                               --Device IP Address
    local CommunityPassword = "public"                                                          --SNMP Community password

    local Device_Temp = "AtticTemp"                                                      --Device Name in Domoticz
    local Device_Hum = "AtticHumid"                                                          --Device Name in Domoticz

    local OID_Temperature = '1.3.6.1.4.1.20916.1.6.1.2.2.1.0'                                       --OID for Temperature for Attic
    local OID_Humidity = '1.3.6.1.4.1.20916.1.6.1.2.2.3.0'                                          --OID for Humidity for Attic

    local command = 'snmpget -v 1 -c '..CommunityPassword..' -O qv '..DeviceIP..' '..OID_Temperature..' '..OID_Humidity..' '    --Define Bash command to readout SNMP
    
    local i, results = 0, {}                                                                    --Define local Variables to be able to use them later
    
    local handle = assert(io.popen(command))                                                    --Execute command to get SNMP info
        for line in handle:lines() do                                                           --Capture SNMP output in Array
            results[i] =  line:gsub('"','')                                                     --Remove Double Quotes from entry
            i = i + 1                                                                           --Increment Array index
        end
    handle:close()

    if results[0] then domoticz.log(""..Device_Temp.." : "..results[0],domoticz.LOG_DEBUG)      --If Array index 0 is present print Debug if debug is active (see above)
        domoticz.devices(Device_Temp).updateTemperature(results[0]) end                         --Update Device in Domoticz with value from Array

    if results[1] then domoticz.log( "" ..Device_Hum.. " : "..results[1],domoticz.LOG_DEBUG)    --If Array index 1 is present print Debug if debug is active (see above)
        local hum = domoticz.utils.round((results[1]),0)                                        --Round value with no decimals, Humidity is displayed in a round percentage
        local temp = tonumber(results[0])                                                       --Convert Temperature (Array Index0) to number to be able to compare
        
        if (hum < 30) then                                                                      --If Humidity is lower than 30% condition is DRY (equals to 2)
            humstat = 2
        elseif (hum > 70) then                                                                  --If Humidity is higher than 70% condition is WET (equals to 3)
            humstat = 3
        elseif ((hum >= 30 and hum <=70) and (temp >= 22 and temp <= 26)) then                  --If Humidity is between 30% and 70% AND temperature is between 22 Degrees and 26 Degrees condition is Comfort (equals to 1)
            humstat = 1
        else
            humstat = 0 end                                                                     --Set Humidity to condition NORMAL if non of the above apply (equals to 0)
        
        domoticz.devices(Device_Hum).update(hum,humstat)                                        --Update Device in Domoticz with value from array and condition.
  end      

end
}
Domoticz logs:
2021-01-29 16:10:00.111 Status: dzVents: Info: Attic: ------ Start internal script: Attic:, trigger: "every minute"
2021-01-29 16:10:00.114 Status: dzVents: Info: Attic: ------ Finished Attic
Hardware: Raspberry Pi 3, OTGW, 433MHz Superheterodyne 3310 RF Link
Software: Ubuntu 16.04, Domoticz v3.5468, WiringPi, rc-switch
kllngtme
Posts: 47
Joined: Tuesday 14 June 2016 16:56
Target OS: Raspberry Pi / ODroid
Domoticz version: Beta
Location: East Coast, USA
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by kllngtme »

Draakje wrote: Saturday 30 January 2021 11:50 Whatis the snmpget command you use? (the one that is working manually)
This works with no issues:
snmpget -v 1 -c public -O qv 192.168.1.6 1.3.6.1.4.1.20916.1.6.1.2.2.1.0 1.3.6.1.4.1.20916.1.6.1.2.2.3.0


Is it the type of dummy switch I have? Does it need to be text or something?
Draakje
Posts: 140
Joined: Thursday 22 October 2015 21:14
Target OS: Linux
Domoticz version: 4.11539
Contact:

Re: Plugin - SNMP Value Reader (Debian)

Post by Draakje »

Could be..

Commands looks good so I guess in dzvents script it should also work

I am using 2 dummys. 1 is a temp type and the other is a humidity type
Hardware: Raspberry Pi 3, OTGW, 433MHz Superheterodyne 3310 RF Link
Software: Ubuntu 16.04, Domoticz v3.5468, WiringPi, rc-switch
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest