• 10 dec 2017: forum version update. In case of issues use this topic.
  • 30 nov 2017: pilight moved servers. In case of issues use this topic.
Hello There, Guest! Login Register


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Ping pilight detect mobilephone
#1
Hello All

First of all I want to say a big thanks for those involved in the pilight project. Smile
A marvelous, highly efficient piece of code I got running on the raspberry.

I have written my own piece of python program to monitor if my phone (me) is home or not.
Unfortunately I was not able to do this reliably with pilight ping as the phone enters some of a "power save mode" and doesn't respond to ping for quite some time.

So the python code have a threshold so it requiters a defined amount of failed pings before saying that device is down.

The code I did is posted below, and tested running on windows machine for now. Would appreciate any comments on the method I use to write to control messages to pilight Angel


Code:
######################
# Import necessary modules
import os
import sys
import subprocess
import time
import json
import requests
#####################

#######################################################
#######################-Config-########################
#-Name of file with hosts
hosts = "hosts.txt"
#-Number of pings each time
retries = 2
#-Delay between pings in seconds
delay = 2
#-Delay between program runs in seconds
delay_prog = 10
#-Number of failed pings before device is down. (24 works good for me)
failed = 24
#-Number of success pings before device is up
success = 1
#-pilight core adress ex: <http://192.168.1.162:5000>
pilight = "http://192.168.1.162:5000"
#-Update failed ping counts label to pilight label device "PythonFailCount"
pilight_count = True
#######################################################
#######################################################
#######################################################




def ping(host):
    # Open a devnull device. "Black hole" to put shit in.
    DEVNULL = open(os.devnull, 'w')    
    try:
        # Do shell command and wait for return. Input/Output to black hole devnull.
        subprocess.check_call(["ping","-n","1","-w","1",host],stdout=DEVNULL, stderr=DEVNULL)
        # Return true if ping responded
        return True
    # CalledProcessError goes True when no response on ping.
    except subprocess.CalledProcessError:
        return False

def SendPilightCount():
    # Copy global variable to local
    count = count_down
    # If count is 0 then label color should be green otherwise red
    if count == 0:
        color = "green"
    else:
        color = "red"
    # Make JSON prepared string with data for pilight
    data = {"action": "control", "code": {"device": "PythonFailCount", "values": {"label": count, "color": color}}}
    # Convert to JSON
    data_json = json.dumps(data)
    # Copy to payload
    payload = data_json
    #-Send to pilight
    requests.post(pilight, data=payload)

def SendPilightUp():
    # Make JSON prepared string with data for pilight
    data = {"action": "control", "code": {"device": "CustomPython", "state": "on"}}
    # Convert to JSON
    data_json = json.dumps(data)
    # Copy to payload
    payload = data_json
    #-Send to pilight
    requests.post(pilight, data=payload)

def SendPilightDown():
    # Make JSON prepared string with data for pilight
    data = {"action": "control", "code": {"device": "CustomPython", "state": "off"}}
    # Convert to JSON
    data_json = json.dumps(data)
    # Copy to payload
    payload = data_json
    #-Send to pilight
    requests.post(pilight, data=payload)


def action_up():

    # Reset counters
    count_down = 0
    count_up = 0

    # Tell function to use global variables
    global up_exec
    global down_exec  
    # Set flag that action_up have been executed and reset flag action_down
    up_exec = True
    down_exec = False

    #  Set request to pilight core with device and status
    SendPilightUp()

# Function to do when devices is down
def action_down():

    # Reset counters
    count_down = 0
    count_up = 0

    # Tell function to use global variables
    global down_exec
    global up_exec  
    
    # Set flag that action_down have been executed and reset flag action_up
    down_exec = True
    up_exec = False

    # Set request to pilight core with device and status
    SendPilightDown()

# Declare and reset counter integers
count_down = 0
count_up = 0

# Declare and reset executed bools
down_exec = False
up_exec = False

#-Mainprogram
while True:
    try:
        #Do this indentation with file open for reading as hostsFile
        with open(hosts,'r') as hostsFile:
            #For each line in file do indentation.
            for line in hostsFile:
                #Do indentation
                for i in range(0,retries):
                    #Call ping function with adress from line in file. .rstrip('\n') is to remove empty space.
                    #Assign return value to variable "is_up"
                    is_up=ping(line.rstrip('\n'))

                    #If ping respond, count up else count down.
                    if is_up:
                        #Don count if variable is above 99
                        if count_up <= 99:
                            count_up+=1
                            count_down=0
                    else:
                        #Don count if variable is above 99
                        if count_down <= 99:
                            count_down+=1
                            count_up=0
                    # Sleep for delay before next ping.
                    time.sleep(delay)
            #Go back to for loop and do same for next host from file.

        #-If function active send count information to pilight.
        if pilight_count:
            SendPilightCount()

        #iF counter device up reached above success and action not executed. Execute action.
        #Else if counter device down reached above failed and action not executed. Execute action.
        if (count_up >= success and not up_exec):
            action_up()
        elif count_down >= failed and not down_exec:
            action_down()

        #Delay program before next ping session
        time.sleep(delay_prog)
        
# Exit if somebody press CTRL + C in terminal
    except KeyboardInterrupt:
        break

# Print that we are exiting and exit.  
print("Exiting")
sys.exit()
 
Reply
  


Possibly Related Threads...
Thread Author Replies Views Last Post
  Does piSchedule work with pilight 8.1.1-nightly Peter S 0 1,484 06-29-2018, 07:57 PM
Last Post: Peter S
  pilight-console - an LCD / keypad interface for pilight frenchie71 3 1,253 11-21-2017, 11:15 PM
Last Post: curlymo
  Connect pilight to your hue bridge hannemann 3 2,556 01-03-2017, 11:26 PM
Last Post: hannemann
Wink PHP class using pilight socket connection Dan 0 1,443 11-03-2016, 11:41 AM
Last Post: Dan
  piScheduler -- A pilight extension for the daily switch plan gneandr 159 62,763 08-09-2016, 04:33 PM
Last Post: gneandr
  Controlling a RGB Led Strip over pilight mightyuhu 2 2,349 08-06-2016, 09:10 PM
Last Post: JohannK
  HomeBridge with pilight on raspbian Jurre 10 11,139 04-06-2016, 07:45 AM
Last Post: tomtom
  pilight voice commands kniazio 11 5,529 01-29-2016, 07:51 PM
Last Post: sral
  pilight config editor ktams 16 7,699 01-06-2016, 02:42 PM
Last Post: ktams
  command processing between pilight and openhab royhofman1989 3 2,780 07-13-2015, 11:26 AM
Last Post: curlymo

Forum Jump:


Browsing: 1 Guest(s)