Author Topic: ping phones?  (Read 13276 times)

0 Members and 1 Guest are viewing this topic.

nime5ter

  • Administrator
  • Hero Member
  • *****
  • Posts: 2012
  • Karma: 61
    • View Profile
    • Getting Started with VoxCommando
Re: ping phones?
« Reply #15 on: October 25, 2014, 10:15:11 AM »
A module is just a .py file. https://docs.python.org/2/tutorial/modules.html

In VC, these modules go in the plugin's library directory (plugins\PY\Lib). If you look at any of the scripts you've used in the past that begin with an "import xxx" line, those are all just importing functions etc. from modules that are in the library.

However, some modules themselves rely on a lot of other modules, so it will depend on whether that bluetooth.py module is itself calling other non-standard modules.

There are no guarantees that all python modules that you try to add to the library will work correctly with Iron Python, but you can certainly try it, assuming you can track down the bluetooth.py file the guy is talking about--and any other custom modules that it's relying on.
« Last Edit: October 25, 2014, 04:17:36 PM by nime5ter »
TIPS: POST VC VERSION #. Explain what you want VC to do. Say what you've tried & what happened, or post a video demo. Attach VC log. Link to instructions followed.  Post your command (xml)

jitterjames

  • Administrator
  • Hero Member
  • *****
  • Posts: 7714
  • Karma: 116
    • View Profile
    • VoxCommando
Re: ping phones?
« Reply #16 on: October 25, 2014, 06:00:25 PM »
Your router should give it is ip as main DNS ... I do not have an issue with resolving names...

Your router will assign IP addresses to devices that use DHCP but this is not the issue that Nime5ter is talking about.

There is no problem using ping with IP addresses, but you asked if we could use names instead.

Some devices do not appear to have names, only IP addresses so you cannot ping them by name.  For example, all our mobile devices in our home running Android OS do not have names.  You can ping them by IP only and if you try to resolve a name from the IP address using ping it will not give you a name.  It will just give back an IP address.  I'm not sure if the same thing happens with iPhones.

If you can use bluetooth that will be a nice option for those who want to have Bluetooth enabled on their phones all them time.  I'm not sure it will necessarily be better than using ping, but I guess if it gets around the issue of devices which disconnect from WIFI to save battery power.  The problem with leaving Bluetooth on all the time is that it also uses battery power so some people do not want to do this.

Haddood

  • $upporter
  • Hero Member
  • *****
  • Posts: 688
  • Karma: 22
    • View Profile
Re: ping phones?
« Reply #17 on: October 26, 2014, 10:02:01 AM »

Some devices do not appear to have names, only IP addresses so you cannot ping them by name.  For example, all our mobile devices in our home running Android OS do not have names.  You can ping them by IP only and if you try to resolve a name from the IP address using ping it will not give you a name.  It will just give back an IP address.  I'm not sure if the same thing happens with iPhones.

Ah ... never seen this with a mobile device. I just have my washer and DVD player that are without names. Apple stuff has names on the network ... anyway I modified the script and it is working with names ...

If you can use bluetooth that will be a nice option for those who want to have Bluetooth enabled on their phones all them time.  I'm not sure it will necessarily be better than using ping, but I guess if it gets around the issue of devices which disconnect from WIFI to save battery power.  The problem with leaving Bluetooth on all the time is that it also uses battery power so some people do not want to do this.
all devices in the market are depending on Bluetooth for proximity ... it is way less energy consuming than Wi-Fi ... plus it seems Bluetooth never sleeps like Wi-Fi .... making it more reliable (my iPhone keep on signing in and out the Wi-Fi with this script)

BTW: any idea why the script stop after certain amount of loops ? isn't it supposed to go forever ?
When Voice command gets tough, use hand gestures

jitterjames

  • Administrator
  • Hero Member
  • *****
  • Posts: 7714
  • Karma: 116
    • View Profile
    • VoxCommando
Re: ping phones?
« Reply #18 on: October 26, 2014, 10:24:23 AM »
all devices in the market are depending on Bluetooth for proximity ... it is way less energy consuming than Wi-Fi ... plus it seems Bluetooth never sleeps like Wi-Fi .... making it more reliable (my iPhone keep on signing in and out the Wi-Fi with this script)

BTW: any idea why the script stop after certain amount of loops ? isn't it supposed to go forever ?

Some newer devices are using BTLE (bluetooth low energy) for proximity.  Many devices especially older ones are using bluetooth only for things like mouse, keyboard, and headsets and are not using BTLE.  Certainly, for those who have it, it looks like a great option.

I don't know why it is stopping, I guess I would need to see the final script you are using, and possibly I would need to do some debugging.  You might want to try only polling one device at a time to see if there is one causing the problem and then go from there.  Some exception handling in the loop might also be a good idea.

https://wiki.python.org/moin/HandlingExceptions

If an error is thrown in a thread it does not get picked up by the engine so no error will be shown by VC.  This is one of the many challenges of multi-threaded programming.

You can use "print" in your loop and it will print to the PY plugin console, or if you prefer you can use VC logging or write to you own text file...

Haddood

  • $upporter
  • Hero Member
  • *****
  • Posts: 688
  • Karma: 22
    • View Profile
Re: ping phones?
« Reply #19 on: October 26, 2014, 03:57:10 PM »
Thank you James for the guidelines. It helped me resolve the problem ... Though I added error trapping, no errors were thrown. But it made me think that the print command in check status might be flooding the log ( I check for about 10 devices). Commenting the print made it work. now I have script running for over 3 hours ...

I modified it so that it can take an IP or device name ... Since ping accept both ... That makes it flexible. I added error traping thought I am not sure I have done it right (first time in Python)

The on/off issue might be from my router as I am having the same issue with the iMac that connects through wifi

Here is the version I am using

Code: [Select]
import os,thread

class box(object):   
    def __init__(self, name=None, present=None):
        self.name = name
        self.present = present
    def checkStatus(self):
        try:
            ping = os.popen("ping %s -n 1 -w 450" %(self.name))
            pingResult= ping.read()   
            #print pingResult
            present = "bytes=32" in pingResult
            if(present!=self.present):           
                eventName='OnLine.%s.%s' %(present,self.name)
                vc.triggerEvent(eventName,None)
            self.present=present
            return self.present
        except:
            e = sys.exc_info()[0]
            print (str (e))
def pingLoop(delay): 
    x = 0
    while 1:
        #vc.triggerEvent("Ping Loop." + str (x), None)
        x = x +1
        for target in boxList:
            try:
                target.checkStatus()
            except:
                e = sys.exc_info()[0]
                vc.triggerEvent("Ping Loop error.", List [str](str (x),str (e)))
        time.sleep(delay) # pause between loops

def getPingList():
    mylist=""
    for target in boxList:
        mylist+=target.name
        if target.present:           
            mylist+=" on-line, "
        else:
            mylist+=" off-line, "
    mylist = mylist.strip()
    mylist = mylist.strip(',')
    return mylist

boxList = []
#----------------------- LAN Devices -----------------------
boxList.append(box("devicename", None)) #replace device name with actual device name
boxList.append(box("192.168.1.1", None)) #replace IP with actual fixed IP of device
# add more devices here

thread.start_new_thread( pingLoop, (60,) )
When Voice command gets tough, use hand gestures

jitterjames

  • Administrator
  • Hero Member
  • *****
  • Posts: 7714
  • Karma: 116
    • View Profile
    • VoxCommando
Re: ping phones?
« Reply #20 on: October 26, 2014, 05:31:52 PM »
Try changing the line:

Code: [Select]
ping = os.popen("ping %s -n 1 -w 450" %(self.name))
to

Code: [Select]
ping = os.popen("ping %s -n 1 -w 1000" %(self.name))
If you ping your devices manually you can see how long they take and get an idea.  You want to wait for the shortest time that is still reliable.

Once you get everything working correctly I suggest you increase the delay in your loops, otherwise you are basically in a constant state of ping.  I'm not sure how costly ping is to your machine and your network in general but I would err on the side of caution.  Set it to 3, 4, or 5 minutes and it will probably still work nicely.

Haddood

  • $upporter
  • Hero Member
  • *****
  • Posts: 688
  • Karma: 22
    • View Profile
Re: ping phones?
« Reply #21 on: October 26, 2014, 09:26:05 PM »
Oops you did it again !!!!  :biglaugh :biglaugh :biglaugh

You just helped me figure out the problem ... With Ethernet response is almost always less than 1ms. On wifi when there is something streaming, some ping time exceeds 450ms ... When n is 4 (manual ping) it is usually only one that exceeds 350, sometimes more than 1000ms and when it is the first ping, device reads offline, which explain the sporadic behaviour... So instead of increasing w I put it at 350ms but put n at 3, same amount of time but more redundant ....

In fact I just got the idea to modify the script to creat 2 groups one for wifi and one for ethernet ... And ping them with different parameters
When Voice command gets tough, use hand gestures

jitterjames

  • Administrator
  • Hero Member
  • *****
  • Posts: 7714
  • Karma: 116
    • View Profile
    • VoxCommando
Re: ping phones?
« Reply #22 on: October 26, 2014, 11:06:53 PM »
Doing 4 pings is less efficient.  Better to just increase the maximum wait time.

Because if the first ping is successful it will continue to ping it 3 more times for nothing.  With a long time out, it will only wait that long if the host is not present, otherwise it will stop as soon as it gets a reply.
« Last Edit: October 26, 2014, 11:15:27 PM by jitterjames »

Haddood

  • $upporter
  • Hero Member
  • *****
  • Posts: 688
  • Karma: 22
    • View Profile
Re: ping phones?
« Reply #23 on: October 28, 2014, 08:26:34 AM »
Doing 4 pings is less efficient.  Better to just increase the maximum wait time.

Because if the first ping is successful it will continue to ping it 3 more times for nothing.  With a long time out, it will only wait that long if the host is not present, otherwise it will stop as soon as it gets a reply.
I agree ... however I noticed that on my wifi sometimes out 4 pings I get 2 ... so redundancy is good in my case

I modified the script to
    1. make it accept both name / IP ...
    2. make 2 different loops, 2 different ping settings ...
       a. one super fast for LAN,
       b. one slower for wifi ...

I added more event so that VC is more aware of what is going on with monitoring. the pulse event is there for debugging or maybe later make VC aware that the monitoring has stopped

initial test with the 2 loops worked very well ...

however for some reason at a certain point the script stopped looping  ::confused ::confused

update: after testing the loops are stopping at the delay command (one loop triggers the pulse event, the other do not - as it is placed after the time delay)

update 2: figured it out ... I had to add import time  to the beginning .. now the script is ready and functional. though not sure how it was looping sometimes before  ::confused

help is really appreciated ...

Code: [Select]
import os,thread
import time

class box(object):   
    def __init__(self, name=None, interface=None, present=None):
        self.name = name
        self.interface = interface
        self.present = present
    def checkStatus(self):
        try:
            if self.interface == "LAN":
                ping = os.popen("ping %s -n 2 -w 5" %(self.name))
            else:
                ping = os.popen("ping %s -n 4 -w 1500" %(self.name))
            pingResult= ping.read()   
            #print pingResult
            #print 'pinging ' + str (self.name)
            present = "bytes=32" in pingResult
            if(present!=self.present):           
                # ---- event by device and its status
                #eventName='OnLine.%s.%s' %(present,self.name)
                #vc.triggerEvent(eventName,None)
               
                # ---- one event info by payload
                #eventPayload=List[str]([str(self.name),str(self.interface),str(present)])
                #vc.triggerEvent('OnLine', eventPayload)
               
                # ---- event by interface info by payload
                eventName= 'OnLine.%s' %(self.interface)
                eventPayload=List[str]([str(self.name),str(present)])
                vc.triggerEvent(eventName, eventPayload)
                self.present=present
            return self.present, pingResult
        except:
            e = sys.exc_info()[0]
            print (str (e))

def LANLoop(delay): 
    vc.triggerEvent("OnLineScanner.LAN.On", None)
    while 1:
        for target in LANList:
            try:
                target.checkStatus()
            except:
                e = sys.exc_info()[0]
                vc.triggerEvent("OnLineScanner.LAN.error", None)
        time.sleep(delay) # pause between loops
        vc.triggerEvent('OnLineScanner.LAN.Pulse', None)  #enable this to have pulse event every cycle

def WiFiLoop(delay): 
    vc.triggerEvent("OnLineScanner.WiFi.On", None)
    while 1:
        for target in WiFiList:
            try:
                target.checkStatus()
            except:
                e = sys.exc_info()[0]
                vc.triggerEvent("OnLineScanner.WiFi.error", None)
        time.sleep(delay) # pause between loops
        vc.triggerEvent('OnLineScanner.WiFi.Pulse', None)  #enable this to have pulse event every cycle

def getPingList(interface):
    mylist=""
    if interface == 'LAN':
        for target in LANList:
            mylist+=target.name
            if target.present:           
                mylist+=" on-line, "
            else:
                mylist+=" off-line, "
    else:
        for target in WiFiList:
            mylist+=target.name
            if target.present:           
                mylist+=" on-line, "
            else:
                mylist+=" off-line, "
    mylist = mylist.strip()
    mylist = mylist.strip(',')
    return mylist

# ----- third parameter in devices affects first run
# None triggers the current state
# False will assume the device is offline and will trigger when it comes online
# True will assume the device is online and will trigger when it goes offline

LANList = []
#----------------------- LAN Devices -----------------------
LANList.append(box("PC", "LAN", True))
#LANList.append(box("192.168.5.5", "LAN", None)) # example of device with fixed IP

WiFiList = []
#----------------------- WiFi Devices -----------------------
WiFiList.append(box("iPhone", "WiFi", None))
#WiFiList.append(box("Remote-Control", "WiFi", None))

thread.start_new_thread(LANLoop, (75,))
thread.start_new_thread(WiFiLoop, (90,))
« Last Edit: October 29, 2014, 04:50:31 AM by Haddood »
When Voice command gets tough, use hand gestures

Haddood

  • $upporter
  • Hero Member
  • *****
  • Posts: 688
  • Karma: 22
    • View Profile
Re: ping phones?
« Reply #24 on: October 28, 2014, 07:26:52 PM »
Some newer devices are using BTLE (bluetooth low energy) for proximity.  Many devices especially older ones are using bluetooth only for things like mouse, keyboard, and headsets and are not using BTLE.  Certainly, for those who have it, it looks like a great option.

did some research BLE is hardly supported in windows 8.1, BT will require pairing ... and the connected devices where giving me false indications with a BT scanner ... so we are stuck with IP pinging or buying external hardware (like smartthings hub)
When Voice command gets tough, use hand gestures

nime5ter

  • Administrator
  • Hero Member
  • *****
  • Posts: 2012
  • Karma: 61
    • View Profile
    • Getting Started with VoxCommando
Re: ping phones?
« Reply #25 on: November 02, 2014, 07:43:06 AM »

update 2: figured it out ... I had to add import time  to the beginning .. now the script is ready and functional. though not sure how it was looping sometimes before  

Good catch. There are several different "ping.py" files attached to posts in this thread (which is probably confusing for people...). One of them had the mistake you found. Amazing no one mentioned it before you, with 50 downloads.

I've updated that file now.
TIPS: POST VC VERSION #. Explain what you want VC to do. Say what you've tried & what happened, or post a video demo. Attach VC log. Link to instructions followed.  Post your command (xml)

nosehook

  • Jr. Member
  • **
  • Posts: 8
  • Karma: 0
    • View Profile
Re: ping phones?
« Reply #26 on: September 02, 2015, 05:02:47 PM »
Love the idea that has been proposed and have been trying to run the script, however...

My knowledge of Python is minimal, although I have been brushing up my knowledge and studied a book or two.
The problem I seem to run into is that the Python version on my computer is newer than this piece of code and some commands are changed and/or renamed, could this be true?

Also, what version of Py does VC run?

Hope you can help me out!

nime5ter

  • Administrator
  • Hero Member
  • *****
  • Posts: 2012
  • Karma: 61
    • View Profile
    • Getting Started with VoxCommando
Re: ping phones?
« Reply #27 on: September 02, 2015, 05:21:31 PM »
If you haven't yet done so, you should read our wiki documentation on the Python plugin: http://voxcommando.com/mediawiki/index.php?title=Python

It clarifies how VC uses Python (more precisely, IronPython), and what version of Python this is based on.

If you have some other version of Python installed separately on your computer, that should not be relevant. VC shouldn't be using those libraries.

That said, this thread contains a lot of different Python scripts. I have tested the the ping.py script attached to this post, and it seems fine: http://voxcommando.com/forum/index.php?topic=1301.msg11240#msg11240

You may want to use that as your starting point. In general, it's helpful if you can be more specific about what posts you're referring to, what you've done, what you're trying to do, and what specific errors you're experiencing.
TIPS: POST VC VERSION #. Explain what you want VC to do. Say what you've tried & what happened, or post a video demo. Attach VC log. Link to instructions followed.  Post your command (xml)

nosehook

  • Jr. Member
  • **
  • Posts: 8
  • Karma: 0
    • View Profile
Re: ping phones?
« Reply #28 on: September 03, 2015, 12:18:28 PM »
Hi Nime5ter,

Thank your for the help. I tried a more improved version of that script and that had some issues and then I made the mistake putting it in a 3.4.x. python shell.

I have read the wiki with regard to Python and VC and the script works for now, thank you again!

mr.niki

  • Contributor
  • ***
  • Posts: 84
  • Karma: 1
    • View Profile
Re: ping phones?
« Reply #29 on: February 15, 2016, 03:24:40 AM »
Code: [Select]
import os,thread, time

class box(object):   
    def __init__(self, name=None, ip=None, present=None):
        self.name = name
        self.ip = ip
        self.present = present
    def checkStatus(self):
        ping = os.popen("ping %s -n 1 -w 500" %(self.ip))
        pingResult= ping.read()   
        #print pingResult
        present = "(0% ¯®â¥àì)" in pingResult
        if(present != self.present):           
            eventName='Ping.%s.%s' %(present,self.name)
            vc.triggerEvent(eventName,None)
        self.present=present
        return self.present


def pingLoop(delay):   
    while 1:       
        print "looping"
        for target in boxList:
            target.checkStatus()           
        time.sleep(delay) # pause between loops
    print "loop has died?"
   
def pingUpdateOnce():   
    for target in boxList:
        target.checkStatus()           

def getlist():
    mylist=""
    for target in boxList:
        if target.present:
            mylist+=target.name+","
    mylist = mylist.strip(',')
    return mylist

boxList = []
boxList.append(box("google", "8.8.8.8", True))
boxList.append(box("MSI", "192.168.0.1", True))
boxList.append(box("asus", "192.168.1.1", True))


#temp disabled
thread.start_new_thread( pingLoop, (120,) )
this my code adn it work fine
and 1
Explain what team do a cyclic code execution
thread.start_new_thread( pingLoop, (120,) )
?????

And how to transfer the data directly to the map tabel
not through the Event


And is it possible
Add event
payloud
 for exempel
event : Ping.False.Херня великая
            {1} Херня великая
« Last Edit: February 15, 2016, 10:30:46 AM by jitterjames »