Please show me how I can ping an ip address from my driver

I am all new to both HE and Groovy (have no Java exp.) and getting really tired of searching for how to do things and opening countless pages that bear no fruit. And the system doc sucks, not just HE but everywhere. There is no comprehensive programmers or system development guide for ANYTHING anymore. Where is that old IBM System/370 Principles of Operation of mine anyway? I sure do miss the good old days, with hard copy manuals. I wrote many of my own over my years. But I digress...

I want to ping an ip address to see if its online before I issue an http get. Can I do this? Can someone please show me how? Thank you!

ps... I'm going to be posting more stupid new user questions like this but I'll get off the soap box when I do... :slight_smile:

You can either use this or use it as inspiration...

1 Like

First is the exact code I use in my Unifi Network API driver... Below that is a modified one to make it more generic (not using my functions). You could probably remove all the version checks nowadays... I wrote this when the feature first became available but I am not sure many people would have a version that does not support it anymore.

// Pings a specific IP address using the Hubitat not the Unifi
def Ping( IP ){
    def TempVersion
    if( location.hub.firmwareVersionString != null ){
        TempVersion = location.hub.firmwareVersionString
        TempVersion = TempVersion.split( /\./ )
        if( TempVersion[ 0 ] >= 2 && TempVersion[ 1 ] >= 2 && TempVersion[ 2 ] >= 7 ){
            ProcessEvent( "Ping Result", "Ping for ${ IP }: ${ hubitat.helper.NetworkUtils.ping( IP ) }" )
        } else {
            Logging( "Ping feature requires Hubitat hub version of 2.2.7 or greater.", 2 )
        }
    } else {
        Logging( "Ping feature requires Hubitat hub version of 2.2.7 or greater.", 2 )
    }
}
// More generic version of a ping method without using snell's functions
def Ping( IP ){
    def TempVersion
    if( location.hub.firmwareVersionString != null ){
        TempVersion = location.hub.firmwareVersionString
        TempVersion = TempVersion.split( /\./ )
        if( TempVersion[ 0 ] >= 2 && TempVersion[ 1 ] >= 2 && TempVersion[ 2 ] >= 7 ){
            sendEvent( name: "Ping_Result", value: "Ping for ${ IP }: ${ hubitat.helper.NetworkUtils.ping( IP ) }", isStateChanged: true )
        } else {
            log.info( "Ping feature requires Hubitat hub version of 2.2.7 or greater." )
        }
    } else {
        log.info( "Ping feature requires Hubitat hub version of 2.2.7 or greater." )
    }
}
2 Likes

it’s in the documentation: NetworkUtils Object | Hubitat Documentation . Note that you might need to import the package in your code to get access to its methods.

You may also specify a (short?) timeout in the http get call parameters if that saves you the trouble (also in the documentation)

2 Likes

Thank you hubitrep! I knew it had to be there... but i still wish i had a hard copy, I would have found it that way! I will check out both methods, I missed the timeout parm for get. Will likely use that.

1 Like

Still on my soap box, the doc shows the command and tells me about the class it uses but it doesn't show me any examples of how to use it and parse out the response. It assumes we all "know the language" and can interpret things as stated, Nope, I'm back to square one, searching for an answer... just one good example for me, that's all it ever takes, it's finding them that's the hard part.

I too learned from hard copy manuals. The search tool is your new friend, with the underlying expectation that you use it a lot (context tends to be minimal on any given page in today’s docs, compared to the olden days). Don’t get too attached to that though, the new thing is to use LLMs :rofl:

You can look at the sample code @sburke781 linked to above.

For kicks I asked Microsoft Copilot, whose answer happens to reference @thebearmay ’s code ! But don’t take this answer at face value, LLMs tend to hallucinate stuff…. (for example you don't need an API key and Groovy is the only language available on HE). The references are good though.

Happy holidays

Microsoft Copilot's answer

The ping method provided in the hubitat.helper.NetworkUtils package is a different way of testing the connectivity and performance of your devices by sending an ICMP ping request to the Hubitat Elevation runtime environment. The ping method returns a PingData object with various statistics, such as round-trip time (RTT), packet loss percentage, packets transmitted, packets received, and minimum and maximum valuesÂą.

To use the ping method, you need to have a custom app or driver that can access the hubitat.helper.NetworkUtils package. You can use any programming language that supports accessing Hubitat APIs, such as Groovy, Python, Java, etc. You also need to have a valid API key from the Hubitat Elevation runtime environment that you can obtain from your account settings².

Here is an example of how to call the ping method using Groovy:

// Import the hubitat.helper.NetworkUtils package
import hubitat.helper.NetworkUtils

// Define the API key
def apiKey = "your_api_key_here"

// Define the IP address of the device you want to ping
def ipAddress = "your_ip_address_here"

// Define the count of pings (optional parameter)
def count = 5 // Optional parameter to specify how many pings to send

// Call the ping method and get a PingData object
def pingData = NetworkUtils.ping(ipAddress, count)

// Print some statistics from the PingData object
println("Ping result:")
println("RTT average: ${pingData.rttAvg}")
println("RTT min: ${pingData.rttMin}")
println("RTT max: ${pingData.rttMax}")
println("Packet loss percentage: ${pingData.packetLoss}%")
println("Packets transmitted: ${pingData.packetsTransmitted}")
println("Packets received: ${pingData.packetsReceived}")

I hope this helps you understand how to use the ping method provided in the hubitat.helper.NetworkUtils package. If you have any other questions, please feel free to ask me. :blush:

Source: Conversation with Bing, 12/24/2023
(1) [2.2.7] ICMP Ping for Apps and Drivers - Developers - Hubitat. [2.2.7] ICMP Ping for Apps and Drivers.
(2) [Release] Hubitat Ping - :gear: Custom Apps and Drivers - Hubitat. [Release] Hubitat Ping.
(3) Network Diagnostic via Ping - Feature Requests - Hubitat. Network Diagnostic via Ping.
(4) NetworkUtils Object | Hubitat Documentation. NetworkUtils Object | Hubitat Documentation.
(5) undefined. https://raw.githubusercontent.com/thebearmay/hubitat/main/hubPing.groovy.

2 Likes

I remember having an entire bookcase full of O'Reilly books. I still have a few that I refer to from time to time.

1 Like

Guess I’m famous!

:rofl:

…of course now I may need to contact witness protection.

3 Likes

You guys live in another world... :slight_smile:

3 Likes

Not sure if I'm adding anything extra here... But this may also help:

Merry Christmas!!

There's good advice above if you really want to ping first, but I'd skip that step and just handle any expected errors, like this:

def safeHttpGet(uri)
{
    try
    {
        httpGet(uri) { resp -> log.debug resp?.status }
    }
    catch(java.net.NoRouteToHostException e)
    {
        log.error "no route to host"
    }
    catch(java.net.UnknownHostException e)
    {
        log.error "unknown host"
    }
    catch(org.apache.http.conn.ConnectTimeoutException e)
    {
        log.error "connection timed out"
    }
}

If you want something more responsive on the ConnectTimeoutException, you could play with the timeout param to httpGet() like @hubitrep mentioned above.

3 Likes

Thank you all, but not there yet. I had to dig deep and thought I got it, and then tried it. Sorry but I don't know how to use this forum yet either and post code like you do... will get there someday.

Tried this:

114> pingData = hubitat.helper.NetworkUtils.PingData hubitat.helper.NetworkUtils.ping(deviceIP,3)
115> int pTran = pingData.packetsReceived.toInteger()
Get this:
groovy.lang.MissingMethodException: No signature of method: static hubitat.helper.NetworkUtils.PingData() is applicable for argument types: (hubitat.helper.NetworkUtils$PingData) values: [PingData(rttAvg: 0.0, rttMin: 0.0, rttMax: 0.0, packetsTransmitted: 3, packetsReceived: 0, packetLoss: 100)] on line 114 (method GetStatus)

getting close... the ip is offline

Remove this from your first line: hubitat.helper.NetworkUtils.PingData

3 Likes

Use this :

image

THANK YOU! :slight_smile: Problem solved. Thing is I, pulled that line straight out of sburke code and then wondered why that extra class spec was in there. So anyway, all good now, and I learned something new today.

Merry Christmas to all!

3 Likes

Thanks!