BEGINNER Guide to iPhone Presence?

Many, many apologies for the Newbie questions in advance!

I’ve been reading all of the posts for setting up Presence detection using OpenHAB, but there is a lot of conflicting information and incomplete steps. I’m unable to find a step-by-step guide on the boards, Reddit or any guides. Can someone please assist? I’m open to any solution that works reliably to flip a virtual switch that shows I’m home when my phone is home.

I am currently using Raspbian Jessie, OH1 and have an iPhone 6.

I found the IP and MACs for my phone and created a script (iPhoneDetect.script), but I don’t know what to do/install next:

!/bin/bash
declare -a DEVICES
hping3 -2 -c 10 -p 5353 -i u1 <phone IP>-q >/dev/null 2>&1 
DEVICES=arp -an | awk '{print $4}'
CHECK="phone mac addr"
if [[ ${DEVICES[*]} =~ $CHECK ]]
then
echo "Present"
else
echo "Absent
"
fi

You can use the NetworkHealth binding. It pings your phone periodically and sets a switch to OFF is it didn’t get a response. Sometimes the iPhone goes to sleep so pinging doesn’t always work.

Search the forum for hping and you will find how some are using that to get over this problem.

You can run your script using the exec binding or executeCommandLine action in a rule.

You can use my script to detect your iPhone by Bluetooth.

I find a combo between Bluetooth and Network Health works great.

I’ve read through all of those pages and they are exactly what I was referring to when I said “incomplete” and “conflicting”. However, based on those pages, here is what I have so far:

Items:

String Venice "To House [%s]" (Presence) { exec="<[/etc/openhab/configurations/scripts/iPhoneDetect.script:60000:REGEX((.*?))]" }

Sitemap:

Text item=Venice icon="presence" valuecolor=[Present="green",Absent="blue"]

In my addons, I have the org.openhab.binding.ntp-1.8.3.jar. (Not sure what other bindings I may need)

The openhab.log doesn’t show any errors. My sitemap says “To House”, but no indicator/switch showing if I’m home or away.

To use the exec biding you must have the exec binding installed. There should be an org.openhab.binding.exec-1.8.3.jar file as well. You actually don’t need the NTP binding at all if all you are doing is calling this script.

OK, I found that binding and placed it in my addons folder. Restarted OpenHab. Still no errors and no change. I still see “To House” and nothing to the right of the label.

Make sure the openhab user has permission to execute that script and everything that is in that script.

Try calling the script from a rule using executeCommandLine to see what is being printed when OH attempts to execute the script.

Make sure the iPhoneDetect.script file has execute permissions (NOTE: files in the configurations/scripts folder have their permissions reset every time OH starts and the execute permissions are stripped from the files. That folder is intended for OH scripts, not shell scripts.

    val results = executeCommandLine("/etc/openhab/configurations/scripts/iPhoneDetect.script", 5000)
    logInfo("iPhone", results)

I get

-bash: syntax error near unexpected token `(’

Is there any information in the logfile you could provide to us?
I had problems with the exec binding (didn’t work at all), but using rules worked fine for me.

Here is what is in my home.rules:

import org.openhab.core.library.types.*

rule "Update max and min temperatures"
when
        Item Weather_Temperature changed or
        Time cron "1 0 0 * * ?" or
        System started
then
        val startOfDay = now.withTimeAtStartOfDay
        if(Weather_Temperature != null) {
        postUpdate(Weather_Temp_Max, Weather_Temperature.maximumSince(startOfDay).state)
        postUpdate(Weather_Temp_Min, Weather_Temperature.minimumSince(startOfDay).state)
    }
end

rule "Records last weather update time"
when
  Item Weather_Temperature received update
then
  postUpdate(Weather_LastUpdate, new DateTimeType())
end

and here is the log file for openhab.log:

2016-09-16 13:58:20.080 [INFO ] [c.internal.ModelRepositoryImpl] - Refreshing model 'home.items'
2016-09-16 13:58:20.356 [INFO ] [.service.AbstractActiveService] - Exec Refresh Service has been shut down
2016-09-16 13:58:20.365 [INFO ] [.service.AbstractActiveService] - Exec Refresh Service has been started
2016-09-16 13:58:23.385 [INFO ] [.o.b.w.i.s.WeatherJobScheduler] - Deleting weatherJob-home
2016-09-16 13:58:23.387 [INFO ] [.o.b.w.i.s.WeatherJobScheduler] - Starting and scheduling weatherJob-home with interval of 10 minutes
2016-09-16 13:58:23.388 [INFO ] [.b.a.internal.job.JobScheduler] - Deleting astro job: Season
2016-09-16 13:58:23.396 [INFO ] [.b.a.internal.job.JobScheduler] - Deleting astro job: DailyJob
2016-09-16 13:58:23.401 [INFO ] [.b.a.internal.job.JobScheduler] - Scheduled a daily job at midnight for astro calculation
2016-09-16 13:58:23.612 [ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule 'Compute humidex': Cannot cast org.openhab.core.types.UnDefType to org.openhab.core.library.types.DecimalType
2016-09-16 13:58:23.666 [INFO ] [g.openhab.model.script.Weather] - Temperature evolved of null degrees.
2016-09-16 13:58:23.816 [ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule 'Compute humidex': The name 'Weather_Humidex' cannot be resolved to an item or type.
2016-09-16 14:00:00.314 [ERROR] [.o.m.r.i.engine.ExecuteRuleJob] - Error during the execution of rule Set random room temperatures
java.lang.RuntimeException: The name 'Temperature' cannot be resolved to an item or type.
        at org.openhab.model.script.interpreter.ScriptInterpreter.internalFeatureCallDispatch(ScriptInterpreter.java:67) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter._evaluateAbstractFeatureCall(XbaseInterpreter.java:658) ~[na:na]
        at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
        at org.eclipse.xtext.util.PolymorphicDispatcher.invoke(PolymorphicDispatcher.java:291) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter.internalEvaluate(XbaseInterpreter.java:218) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter._evaluateMemberFeatureCall(XbaseInterpreter.java:545) ~[na:na]
        at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
        at org.eclipse.xtext.util.PolymorphicDispatcher.invoke(PolymorphicDispatcher.java:291) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter.internalEvaluate(XbaseInterpreter.java:218) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter._evaluateMemberFeatureCall(XbaseInterpreter.java:545) ~[na:na]
        at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
        at org.eclipse.xtext.util.PolymorphicDispatcher.invoke(PolymorphicDispatcher.java:291) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter.internalEvaluate(XbaseInterpreter.java:218) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter._evaluateBlockExpression(XbaseInterpreter.java:321) ~[na:na]
        at sun.reflect.GeneratedMethodAccessor66.invoke(Unknown Source) ~[na:na]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_65]
        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_65]
        at org.eclipse.xtext.util.PolymorphicDispatcher.invoke(PolymorphicDispatcher.java:291) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter.internalEvaluate(XbaseInterpreter.java:218) ~[na:na]
        at org.eclipse.xtext.xbase.interpreter.impl.XbaseInterpreter.evaluate(XbaseInterpreter.java:204) ~[na:na]
        at org.openhab.model.script.internal.engine.ScriptImpl.execute(ScriptImpl.java:59) ~[na:na]
        at org.openhab.model.rule.internal.engine.ExecuteRuleJob.execute(ExecuteRuleJob.java:55) ~[na:na]
        at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-all-2.1.7.jar:na]

That clearly states that the script you are using is syntactically incorrect. And indeed from looking at the script I see some oddness which I don’t know if is a copy and past problem or the way you are really trying to run it.

Have you actually confirmed that the script runs and detects your phone as written?

I tried to make it work and I’m getting all sorts of errors just trying to run it. In particular there needs to be a “#” at the start of the first line, a space between the IP and the “-q”, the command that populates DEVICES needs to be in back ticks, and there shouldn’t be a newline before the end quote in the “echo “Absent””.

The big problem with that thread where you grabbed this script is they did not use the forum’s code formatting so a lot of really really importing parts of the script got mangled. I don’t have an iPhone at home right now so can’t really test this but those changes above should at least get you closer to a valid script. The following is at least syntactically correct.

#!/bin/bash
declare -a DEVICES
hping3 -2 -c 10 -p 5353 -i u1 192.168.1.xxx -q >/dev/null 2>&1
DEVICES=`arp -an | awk '{print $4}'`
CHECK="YY:YY:YY:YY:YY:YY"
if [[ ${DEVICES[*]} =~ $CHECK ]]; then
  echo "Present"
else
  echo "Absent"
fi

Remember to replace the IP address and MAC with your iPhone’s address.

NOTE: This is far from a beginner thing you are trying to do. Don’t feel bad that it is so hard to get working.

1 Like

THANK YOU!!

I’ve replaced my script with the script you wrote (and added back my IP and MAC). I’m still getting the same error trying to run it via the command line (via putty).

Have you thought about solving your first question with IFTTT? I set a rule on IFTTT to tell my openhab via REST when my phone is home or not. Checking the network never really worked in my case, therefore I started using my geofence on my phone. Just a thought to give it a try.

What is very odd is there isn’t a single “(” in the script. How are you running it from the command line? Post your exact command line text as you are entering it in putty here. Wrap that line in back tics so the forum doesn’t mangle the format (see below).

Post the exact script you are using. Replace the numbers of your IP with x’s and the MAC address with y’s for privacy. But make not other edits.

Put three back tics before and three after so the forum formatting doesn’t mangle the script.

```
Your script text goes here
```

In that hping3 thread they called these “French quotes”.

Either you are executing the script in an incorrect manner or the script itself has stuff in it that is not in the above.

Also, it occurred to me to ask whether you have actually installed hping3 as well. That isn’t related to the error you are seeing but I had to install it separately when I tried out the script above. This is important because if you do not have hping3 installed the script will not show an error, it will just never report your phone as present.

Yes. I linked IFTTT to OpenHAB, but I could never get any items to show up in IFTTT. I searched the forums, OpenHAB and IFTTT for a solution and although I found several people with the problem, none of them walked through how they solved it.

I didn’t actively install it - is it a binding? I don’t see anything with the name hping3 in my addon folder.

Exactly what I typed on the command line:

val results = executeCommandLine("/etc/openhab/configurations/scripts/iPhoneDetect.script", 5000) logInfo("iPhone", results)

Hmm, hping3 is a program you have to install on the Linux machine; e.g.
sudo apt-get install hping3
… it has nothing to do with OH, and is not a binding.

However, for this bash script (iPhoneDetect) to work, you need org.openhab.binding.exec-1.8.3.jar in your OH addons folder / directory
… and as Rich pointed out, the script needs to be set to executable.
Best place to put it is in /usr/local/bin and make it executable like so:
chmod +x iPhoneDetect.script

OK, you really are a beginner.

I recommend you spend some time reading and learning about how to get around on Linux, or run openHAB on an OS that you are more familiar with.

  • On your Raspberry Pi you are running a Linux based operating system (OS) called Raspbian (probably the Jessy version since that is the latest). Just like Windows 10 and OSX, Raspbian is a generic platform upon which you run programs.

  • openHAB is a program that runs on top of, in this case, the Raspbian OS. It is a Java based program which lets it run on most OS’s, but since you are working with a Raspberry Pi with Raspbian Jessy I’ll limit the discussion to that.

  • openHAB supports addons which allow it to support communicating with different bindings. Two different types of these addons are called bindings and actions. Bindings allow one to represent something in the real world as an Item within openHAB (e.g. represent a zwave switch as a Switch in openHAB). Actions allow one to call something in the real world directly.

  • One such binding is the Exec binding. This allows one to represent a command entered on a command line as an Item. For example, have it execute a bash script when a Switch is toggled. The command line string and the shell script are executed by the OS completely outside of openHAB.

  • Similarly one such action is the executCommandLine action. This allows one to execute a command entered on a command line directly from within a Rule.

  • A Rule is a bit of code written in a language that openHAB knows how to understand which tells it to do something in response to some event. Your line above is a valid line calling executeCommandLine from a Rule that is executed by openHAB.

  • When you Putty/ssh login to the Raspberry Pi, you are interacting with Raspbian. openHAB may not even be running! So you must communicate with the command line you are using (almost certainly bash) in a way that it understands. val results = executeCommandLine("/etc/openhab/configurations/scripts/iPhoneDetect.script", 5000) logInfo("iPhone", results) is nonsensical to bash. That is the openHAB Rule’s language.

  • What executeCommandLine does is pass the contents of the first String on to the operating system and says "Hey, execute this and tell me what it says.

  • So, when you Putty/ssh over to your Pi to execute this script yourself, all you type in is that first String.

/etc/openhab/configurations/scripts/iPhoneDetect.script

All of the above is really basic computer knowledge and is understood to be known by users of openHAB on Linux. Based on this I would not recommend moving forward with use of the Exec binding or the executeCommandLine action until you gain a bit more knowledge and experience about how Linux works. Or run openHAB on a Windows or OSX machine upon which you are more familiar in which case the string you would pass to executeCommandLine would be the same thing you would type in a CMD window.

1 Like

As always: thank you for your reply! And more so for actually replying, an not just keeping quiet, because it was on those newbie question (like many others would do).

Unfortunately (or fortunately) I can relate to the OP all too well.
When I started, I ran into exactly the same problems… the major one being “incomplete” information to arrive at the desired result being shown.
I also understand that it is neither realistic nor reasonable feasible to explain from Adam & Eve how to detect a phone…

What would help is a prescribed way on how to set-up OH on Linux – with permanent top posts, on the forum like: Warning! Post should refer to the OH recommended process of installing OH on Linux… and a pointer to the wiki article.

I re-installed OH when I started, because the article I found useful at the time of getting started did not use the apt-get install process, thus resulting in OH files and directories not being where a standard (proper) install would expect these.

Maybe responses to newbie question should be to ask first: do you have the file XYZ in this directory; with XYZ referencing a file that would only be there when the proper installation process was used.
The reply should be: given the multitude of problems which will eventually occur due to a non-standard install, we highly recommend to re-install OH, try the desired solution again, and if it still fails, come back to the forum.

May sound harsh, but I reckon – once this is consistently enforced – the forum will gain more value to anyone needing help with OH… and may – most likely – result in members to actually try to help.

I was never peeved off that I had to re-install; quite the opposite – I am now certain that my foundation is right, and can be ruled out as a source of error (unless a bug appears)…

As for common ‘knowledge’… starting with Linux is no mean feast for a beginner… IMHO it takes many days to even complete the simplest of tasks. BUT, your right, if you want to run things on Linux a basic understanding is required to even dare to go there.

I digress… I had no intention at present to do iPhone detection, but while I saw the post, I thought I give this approach a try and it worked eventually. However, it took a while to figure where to put the script, what rights to give it, and needed debug enabled to realise I pointed the .item to to the wrong path. :frowning:

Good luck to the OP! Be persistent, you will be rewarded with success.

I don’t disagree, but the installation instructions for both OH 1 and OH 2 and there are even special instructions for installation on the Raspberry Pi are actually fairly well documented. But OP didn’t have trouble installing OH, he/she had a fundamental misunderstanding about where the border is between OH and the OS.

@ThomDietrich is currently working out a documentation scheme with stickies in the forum. I’m not certain this is exactly what he is after given how much documentation already exists for installation in the official docs, but the conversation is worth having.

I completely understand the frustrations newcomers have when coming to an application as complex as openHAB but the developers and documenters have to draw the line somewhere and I’m firmly of the opinion that Linux fundamentals is beyond the scope of what should be documented in OH. Particularly since OH runs perfectly well on pretty much all the other platforms.

I do think perhaps some guidance and/or documented prerequisites (as in what knowledge users are assumed to possess) might be in order. Also, @ThomDietrich’s work with openHABian will go a long way towards making the Pi (and soon other platforms) easier to get up and running for the new user.

But there will always be a few bindings/actions which will require a greater amount of knowledge to use effectively no matter how easy openHAB becomes to install and configure. I’d put Exec, Serial, TCP/UDP, GPIO, and HTTP bindings in that category for sure. All things considered, I would not recommend any of these bindings to inexperienced users.

That is a challenge that I’ve not figured out a way to address. It is a clear problem because there are tons and tons of tutorials out there written by third parties of various vintages and almost none of them use apt-get. Even such authoritative sources as Makezine follow a “manual” wget based installation process (I posted a comment on that posting).

I’m not convinced a sticky will help this problem. There are (as linked above) well written instructions in the official docs for installation and people are not checking those before installing. Because these third party instructions use wget, most of these users don’t even visit the openhab website or this forum until after they installed and are having problems.

I agree, I should do this more. But it isn’t always clear who the newbies are (though in this case it is clear) and being too basic and basic in our first response can come across as condescending as well. Its a hard balance to reach. Though once the openHAB 2 documents are a bit more complete I do have planned in the back of my mind a troubleshooting document or wizard or the like to walk new users through the basic troubleshooting steps (is it running? are there errors in the log? is the addon installed? …).

I actually think the number of active helpers on this forum is pretty high when compared to other forums. Most have their specialties (e.g. chris jumps on zwave questions, watou is great with mqtt, and several folks help out newbie type questions, etc). Compared to most forums for OS projects of this nature, that is a really high level of participation. Most have only one or two active helpers. Is the OH forum as helpful as it could be? Probably not. But this is THE challenge with 100% volunteer projects like this.

Care to post how you got it to work as a tutorial? I don’t have an iPhone in the house (and the script doesn’t work on Android, I tried) so I can’t get any further than what I’ve already posted here. @ThomDietrich is leading an effort to get a bunch of tutorials like this into the forum under the Tutorials and Examples tag and this is a perfect candidate to get a good and complete example written up.

1 Like

As usual: good points…

Did not try to say: nobody is helping :slight_smile:

As for the ‘sticky’ … maybe there should be one in each forum: "Did you install OH with apt-get? If not you will have problems! … and then describe what and why, and how… pointing to links etc.

Convinced or not… I am sure that a notice put up, will persuade a bunch of newbies to re-install their OH system… and try again.

this is not about multiple ways to skin a cat, but about consistency, as a prerequisite for proper support. Linux is unfortunately known for its ability to solve problems in far too many ways. RO like the saying: if we have a problem, we route around it :slight_smile:

Happy to post a tutorial… what is the process?

On another note for this particular solution: It takes a while for a switched off phone to be removed from the arp cache.
The arp command will list all IPs / MACs it has in its cache, even if the phone is switched off it will be shown as present, until the arp entry is removed – which is usually 60 seconds.
find out with cat /proc/sys/net/ipv4/neigh/default/gc_stale_time