Exemplo n.º 1
0
async def async_setup_platform(opp,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the SNMP sensor."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    unit = config.get(CONF_UNIT_OF_MEASUREMENT)
    version = config.get(CONF_VERSION)
    username = config.get(CONF_USERNAME)
    authkey = config.get(CONF_AUTH_KEY)
    authproto = config.get(CONF_AUTH_PROTOCOL)
    privkey = config.get(CONF_PRIV_KEY)
    privproto = config.get(CONF_PRIV_PROTOCOL)
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    value_template = config.get(CONF_VALUE_TEMPLATE)

    if value_template is not None:
        value_template.opp = opp

    if version == "3":

        if not authkey:
            authproto = "none"
        if not privkey:
            privproto = "none"

        request_args = [
            SnmpEngine(),
            UsmUserData(
                username,
                authKey=authkey or None,
                privKey=privkey or None,
                authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
            ),
            UdpTransportTarget((host, port)),
            ContextData(),
        ]
    else:
        request_args = [
            SnmpEngine(),
            CommunityData(community, mpModel=SNMP_VERSIONS[version]),
            UdpTransportTarget((host, port)),
            ContextData(),
        ]

    errindication, _, _, _ = await getCmd(*request_args,
                                          ObjectType(ObjectIdentity(baseoid)))

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return

    data = SnmpData(request_args, baseoid, accept_errors, default_value)
    async_add_entities([SnmpSensor(data, name, unit, value_template)], True)
Exemplo n.º 2
0
    def __init__(
        self,
        name,
        host,
        port,
        community,
        baseoid,
        commandoid,
        version,
        username,
        authkey,
        authproto,
        privkey,
        privproto,
        payload_on,
        payload_off,
        command_payload_on,
        command_payload_off,
    ):
        """Initialize the switch."""

        self._name = name
        self._baseoid = baseoid

        # Set the command OID to the base OID if command OID is unset
        self._commandoid = commandoid or baseoid
        self._command_payload_on = command_payload_on or payload_on
        self._command_payload_off = command_payload_off or payload_off

        self._state = None
        self._payload_on = payload_on
        self._payload_off = payload_off

        if version == "3":

            if not authkey:
                authproto = "none"
            if not privkey:
                privproto = "none"

            self._request_args = [
                SnmpEngine(),
                UsmUserData(
                    username,
                    authKey=authkey or None,
                    privKey=privkey or None,
                    authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                    privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
                ),
                UdpTransportTarget((host, port)),
                ContextData(),
            ]
        else:
            self._request_args = [
                SnmpEngine(),
                CommunityData(community, mpModel=SNMP_VERSIONS[version]),
                UdpTransportTarget((host, port)),
                ContextData(),
            ]
Exemplo n.º 3
0
async def async_setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    async_add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up the SNMP sensor."""
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    community = config.get(CONF_COMMUNITY)
    baseoid = config.get(CONF_BASEOID)
    version = config[CONF_VERSION]
    username = config.get(CONF_USERNAME)
    authkey = config.get(CONF_AUTH_KEY)
    authproto = config[CONF_AUTH_PROTOCOL]
    privkey = config.get(CONF_PRIV_KEY)
    privproto = config[CONF_PRIV_PROTOCOL]
    accept_errors = config.get(CONF_ACCEPT_ERRORS)
    default_value = config.get(CONF_DEFAULT_VALUE)
    unique_id = config.get(CONF_UNIQUE_ID)

    if version == "3":

        if not authkey:
            authproto = "none"
        if not privkey:
            privproto = "none"

        request_args = [
            SnmpEngine(),
            UsmUserData(
                username,
                authKey=authkey or None,
                privKey=privkey or None,
                authProtocol=getattr(hlapi, MAP_AUTH_PROTOCOLS[authproto]),
                privProtocol=getattr(hlapi, MAP_PRIV_PROTOCOLS[privproto]),
            ),
            UdpTransportTarget((host, port), timeout=DEFAULT_TIMEOUT),
            ContextData(),
        ]
    else:
        request_args = [
            SnmpEngine(),
            CommunityData(community, mpModel=SNMP_VERSIONS[version]),
            UdpTransportTarget((host, port), timeout=DEFAULT_TIMEOUT),
            ContextData(),
        ]

    errindication, _, _, _ = await getCmd(
        *request_args, ObjectType(ObjectIdentity(baseoid))
    )

    if errindication and not accept_errors:
        _LOGGER.error("Please check the details in the configuration file")
        return

    data = SnmpData(request_args, baseoid, accept_errors, default_value)
    async_add_entities([SnmpSensor(hass, data, config, unique_id)], True)
Exemplo n.º 4
0
def run_watt(pdu_ip, pdu_node_port):
    snmpEngine = SnmpEngine()
    errorIndication, errorStatus, errorIndex, varBinds = yield from getCmd(
        snmpEngine, CommunityData('public', mpModel=1),
        UdpTransportTarget((pdu_ip, 161)), ContextData(),
        ObjectType(
            ObjectIdentity('1.3.6.1.4.1.318.1.1.26.9.4.3.1.7.' +
                           str(pdu_node_port))),
        ObjectType(ObjectIdentity('1.3.6.1.4.1.318.2.1.6.1.0')),
        ObjectType(ObjectIdentity('1.3.6.1.4.1.318.2.1.6.2.0')))

    watt = None
    timestamp = None

    if errorIndication:
        LOGGER.error(errorIndication)
    elif errorStatus:
        LOGGER.error('%s at %s' %
                     (errorStatus.prettyPrint(),
                      errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
    else:
        watt = int(varBinds[0][1])
        timestamp_str = str(varBinds[1][1]) + " " + str(varBinds[2][1])
        timestamp = int(
            time.mktime(
                datetime.datetime.strptime(timestamp_str,
                                           "%m/%d/%Y %H:%M:%S").timetuple()))

    snmpEngine.transportDispatcher.closeDispatcher()

    return watt, timestamp
Exemplo n.º 5
0
 def __init__(self, targets):
     self.requests = []
     self.targets = targets
     self.results = []
     self.community_string = get_config('snmp')['COMM_STRING']
     self.timeout = get_config('snmp')['TIMEOUT']
     self.snmpEngine = SnmpEngine()
     self.mibBuilder = self.snmpEngine.getMibBuilder()
     self.mibViewController = view.MibViewController(self.mibBuilder)
     self.loop = asyncio.get_event_loop()
Exemplo n.º 6
0
def snmp_polling(queue): #This is to query SNMP OID, and the data transferred to plot_drawing() using Queue() between multiproces.
    
        snmpEngine = SnmpEngine()
        loop = asyncio.get_event_loop()

        task = loop.create_task(async_next_snmp_request(snmpEngine, HOSTNAME, OIDS, SLEEP_TIME_1,comment_1 ,queue))  

        loop.run_until_complete(task)
    
        loop.run_until_complete(unconfigure(snmpEngine)) 
        loop.close()
Exemplo n.º 7
0
async def collect_periodically(work, result_queue, interval):
    snmp_engine = SnmpEngine()
    deadline = time.time() + interval
    while True:
        get_data = []
        while deadline <= time.time():
            logging.warning('missed deadline')
            deadline += interval
        sleep_var = deadline - time.time()
        await asyncio.sleep(sleep_var)
        deadline += interval
        for host, community_string, objects in work:
            get_data.append(
                get_one(snmp_engine, (host, 161), community_string, objects))

        ret = await asyncio.gather(*get_data)

        #print("Worker putting {} results into queue...".format(len(ret)))
        for r in ret:
            if r:
                result_queue.put_nowait(r)