Let op: Tweakers stopt per 2023 met Tweakblogs. In dit artikel leggen we uit waarom we hiervoor hebben gekozen.

How to automatically enable/disable your (Foscam) IP cam en

By temp00 on vrijdag 2 augustus 2019 20:55 - Comments (4)
Category: -, Views: 5.140

I recently bought a Foscam IP cam and like many other standalone IP cams, one of its biggest shortcomings is the inability to automatically enable/disable when not home/home. Sure, you can set a fixed schedule in the cam's settings but what person is home/not home on set schedules? I for one am not.

To fix this there's a lot of different approaches we can take. For example with the help of some extra hardware, we could enable/disable by NFC, bluetooth, GPS, radio controlled remote etc. Lots of options are possible. In this blog I'll demonstrate a simple yet pretty effective solution I engineered for my home setup. All you need is:
- A Foscam or any other IP cam that supports device control by HTTP get commands.
- A Raspberry Pi or any other device that is able to periodically run Curl and Bash scripts.
- A PHP enabled webhost (don't worry there are free ones out there that will suit our needs just fine).
- A smartphone that is able to run Tasker (app) or similar app that is able to send HTTP requests and is able to poll WiFi state.
- Basic computer, Linux, internet & webhost knowledge.

This blog assumes you've already set up your cam and Pi. I will provide you the necessary PHP and Bash scripts that are needed for this setup.

Before I get technical, let's see what we're trying to accomplish:

Ok so that's not too hard to get, right? When we arrive home Tasker (app) will automatically detect that we're connected to our local WiFi network and will consecutively send a HTTP command to the cam, ordering it to disable.

But what about enabling the cam when we leave home and us getting disconnected from our local LAN? How do we communicate with the cam when we're not connected to our local WiFi network anymore? Sure, we could open some static incoming network ports to the internet but that means that we have to expose our LAN to the internet which I'm sure most of you do not like. To work around this is where our Raspberry Pi and PHP enabled webhost step in:

Let's dissect what happens in the second picture.
1 - We leave home, Tasker detects us being disconnected from our local WiFi network and automatically sends a HTTP post command to our PHP enabled webhost telling it we're not home.
2 - The Pi is configured to periodically check the webserver for home/not home status. This means that the webserver never hard pushes any message (hence the 'simple' in simple solution), it just responds to the Pi's periodic get status check.
3 - Since we left home and our phone informed the server about this earlier, the webserver responds to the Pi's periodic check: user is not home.
4 - The Pi receives the not home status from the server and orders the cam to enable through HTTP get.

*A note before we get started, my Foscam supports wake/sleep commands but not every Foscam supports this, especially the older cams don't. This shouldn't be too big of a problem since you can substitute the wake/sleep command with for example, an enable/disable motion detect command which most cams support. At the end of this blog I'll give you some motion detect command examples in case your cam doesn't support wake/sleep commands.
Also, please note that because of the way Android works and idles network interfaces when the phone hasn't been actively used in a while, it might take 1 or 2 minutes for your phone to automatically connect to your local WiFi when you get home. For me this isn't a huge deal since I simply press my home button (unlock not needed) and the WiFi NIC instantly connects.


General
A1 - Download the example files from: http://storagehub.atwebpa...ZX8qi6PB/ExampleFiles.zip
(I apologize in advance to any programmer or code enthusiast for the probably silly and inefficient code found in these files :P.)

Webhost
B1 - First, create a free webserver account at https://www.000webhost.com/free-website-sign-up or any other PHP enabled webhost at your liking. Since you're presumed to have basic webhost knowledge I won't describe any steps on how to sign up but it shouldn't be too difficult. Once you're fully set up and you have your https://yoursitename.000webhost.com, use FTP or the site's own File Manager to create a folder in the root of your website. In this example, we name our folder hnh.
B2 - Next we enable a new user and password on our newly created hnh folder by going to the website settings in the 000webhost control panel: Control Panel > Website Settings > Security > Manage Password Protection > Add > add a username and password here (do not use the same user/pass as for your website's control panel). This prevents l33t h4ckz0rz from setting our home / not home status.
B3 - Next upload form.php from the example files to your newly created folder on your webhost.

Raspberry Pi
C1 - don't log into the Pi yet but open status.sh from the example files in an editor on your desktop and adjust the following data to reflect your own setup:
> WEBHOST: change to your own webhost adres & folder.
> WAKECAM: change the part that has the ipaddress and port to your cam's ip address and https port.
> WAKECAM: change exampleusr and examplepwd to an account you use to control your webcam.
> examplefolderuser: change all occurrences of examplefolderuser to the username you have created in step B2.
> examplefolderpassword: change all occurrences of examplefolderpassword to the password you have created in step B2.
C2 - For security purposes, we're gonna create a separate account, different from our regular Pi account, a service account, named statususer on our Pi to run our Bash script which periodically checks the home / not home status and executes the wake command with the program Curl.
Execute the following commands: sudo adduser statususer
C3 - Check if Curl is installed: curl --help
If Curl isn't installed, you can install it by: sudo apt install curl.
C4 - Switch to the newly created user by: su statususer
DO NOT USE SUDO IN COMMANDS C5 THROUGH C9.
C5 - Switch to statususer home folder if you haven't already landed in that folder: cd ~
C6 - Create a folder named status: mkdir status
C7 - Copy the content from status.sh on your own computer in your clipboard.
C8 - Edit the file status.sh: nano ~/status/status.sh
and paste the contents from status.sh on your computer into status.sh on your Pi. Save the file and exit Nano. If Nano isn't installed on your Pi, you can install it by: sudo apt install nano
or use any other editor like for example Vi.
C9 - Next we're gonna tell the Pi to periodically check the webserver for home / not home status. Our example checks once every minute. Execute the command: crontab -e
and insert the following below the #-lines: * * * * * /home/statususer/status/status.sh
Save your cron job and exit crontab.

It's best to skip the next step if you're still setting things up and/or are troubleshooting.
C10 - Finishing this section, we're gonna prevent the statususer from logging in so in case the account gets compromised, noone is able to log in to it.
Execute the following command to return to your regular Pi account: exit
After that, execute: sudo passwd -l statususer
(note: sudo su statususer still works regardless of the command above).
In case you need to login to statususer, execute the following command to unlock the account again: passwd -u statususer

Our webhost and Pi are all set up now. Disable your cam, go to https://yoursitename.000webhostapp.com/yourfoldername/form.php , set status 0 and check if your Pi and cam respond to it. Your cam should enable.
Note: since status checks are done periodically with 1 minute intervals by the Pi, it might take a max of 1 minute for your Pi to read the status and send the wake command to the cam. Sleep commands can't be tested at this point yet since those are sent by Tasker directly to the cam which we'll set up in the next section.

Tasker
D1 - Open Tasker, navigate to Tasks > Create a new task named: Sleep Cam By Local, Post 1
> Add action > Net > HTTP Get >
- Server:Port: https://YourCamIp:443
- Path: /cgi-bin/CGIProxy.fcgi?usr=
yourcamusername&pwd=yourcampassword&cmd=alexaSleep
- Mime type: text/html
- Trust Any Certificate: Yes

> Add action > Net > HTTP Auth >
- Method: Username and Password
- Username:
examplefolderuser
- Password:
examplefolderpassword
> Add action > Net > HTTP Request >
- Method: Post
- Url: https://
yoursitename.000webhostapp.com/yourfoldername/form.php
- Headers:
code:
1
2
%http_auth_headers
Content-Type: application/x-www-form-urlencoded

(do not add "code:" or the line numbers to the headers.)
- Body: formHnh=1&formSubmit=Submit
> Optional: Add action > Alert > Say > Cam disabled
D2 - Navigate to Profiles > create a new profile named: Sleep Cam By Wifi State
State > State > Net > WiFi Connected > SSID: select your home WiFi network.
Connect the task created in D1 to the profile Sleep Cam By WiFi State.
Long press the 'WiFi Connected' state in the Sleep Cam By WiFi State profile and select Add > State > Net > Airplane Mode > Invert.
D3 - Navigate to Tasks > Create a new task named: Wake Cam By Post 0
> Add action > Task > Wait > 5 seconds
> Add action > Net > HTTP Auth >
- Method: Username and Password
- Username:
examplefolderuser
- Password:
examplefolderpassword
> Add action > Net > HTTP Request >
- Method: Post
- Url: https://
yoursitename.000webhostapp.com/yourfoldername/form.php
- Headers:
code:
1
2
%http_auth_headers
Content-Type: application/x-www-form-urlencoded

(do not add "code:" or the line numbers to the headers.)
- Body: formHnh=0&formSubmit=Submit
> Optional: Add action > Alert > Say > Cam enabled
D4 - Navigate to Profiles > create a new profile named: Wake Cam By Wifi State
State > State > Net > WiFi Connected > SSID: select your home WiFi network > Invert.
Connect the task created in D3 to the profile Wake Cam By WiFi State.
Long press the 'Not WiFi Connected' state in the Wake Cam By WiFi State profile and select Add > State > Net > Airplane Mode > Invert.

You're done, your cam should automatically enable/disable now. Again, do mind that it might take 1 minute max. before your cam wakes up due to the Pi checking home/not home status on 1 minute intervals.


*Like mentioned before, if your cam doesn't support wake/sleep commands, you can use other commands like for example enable/disable motion detect commands. Substitute the sleep/wake commands with the commands supported by your own cam in the Tasker Tasks and Bash script. Motion detect examples would look like:

- show current motion detect config (older cams might have a different syntax):
code:
1
https://yourcamipaddress:443/cgi-bin/CGIProxy.fcgi?cmd=getMotionDetectConfig1&usr=yourcamusername&pwd=yourcampassword

- enable motion detect (older cams might have a different syntax):
code:
1
https://yourcamipaddress:443/cgi-bin/CGIProxy.fcgi?cmd=setMotionDetectConfig1&isEnable=1&linkage=142&snapInterval=5&triggerInterval=0&isMovAlarmEnable=1&isPirAlarmEnable=0&schedule0=281474976710655&schedule1=281474976710655&schedule2=281474976710655&schedule3=281474976710655&schedule4=281474976710655&schedule5=281474976710655&schedule6=281474976710655&x1=0&y1=0&width1=10000&height1=10000&threshold1=0&sensitivity1=0&valid1=1&usr=yourcamusername&pwd=yourcampassword

- disable motion detect (older cams might have a different syntax):
code:
1
https://yourcamipaddress:443/cgi-bin/CGIProxy.fcgi?cmd=setMotionDetectConfig1&isEnable=0&linkage=142&snapInterval=5&triggerInterval=0&isMovAlarmEnable=1&isPirAlarmEnable=0&schedule0=281474976710655&schedule1=281474976710655&schedule2=281474976710655&schedule3=281474976710655&schedule4=281474976710655&schedule5=281474976710655&schedule6=281474976710655&x1=0&y1=0&width1=10000&height1=10000&threshold1=0&sensitivity1=0&valid1=1&usr=yourcamusername&pwd=yourcampassword

Do not get tempted to only pass the enable/disable motion detect command to your cam, this will not work and will mess up your current schedule. You always need to pass the full command and schedule.

When testing out cam commands, the following status can be returned by the cam:
- 0 (Success)
- 1 (CGI request string format error)
- 2 (Username or password error)
- 3 (Access deny)
- 4 (CGI execute fail)
- 5 (Timeout)
- 6 (Reserve)
- 7 (Unknown error)
- 8 (Reserve)

Refer to the included commands.pdf for a more comprehensive list of commands and description.

Feel free to ask me any questions or provide me feedback. Good luck :)

Comments


By Tweakers user gatlarf, zaterdag 3 augustus 2019 00:24

Nice! That’s definitively something that I’m going to set up. Thanks for the idea and the tutorial! :Y)

By Tweakers user temp00, zaterdag 3 augustus 2019 08:57

gatlarf wrote on Saturday 3 August 2019 @ 00:24:
Nice! That’s definitively something that I’m going to set up. Thanks for the idea and the tutorial! :Y)
Cool en graag gedaan. Ik hoop dat je er iets aan hebt :)

By Tweakers user i-chat, maandag 5 augustus 2019 16:15

if your router supports it, openwrt could probably simplefy this a great deal.

a simple addon package for openwrt supporting a post and a get command would take away the need for both the silly free webhost (that may terminate service at any $random $date and you aditional pi zerro w.

in other usecases, i would recoment using the router's build-in vpn-connections in which case you still use the pie but here you connect directly to it, as well as get access to the cam's livestream when its active.

By Tweakers user temp00, maandag 5 augustus 2019 19:58

i-chat wrote on Monday 5 August 2019 @ 16:15:
if your router supports it, openwrt could probably simplefy this a great deal.

a simple addon package for openwrt supporting a post and a get command would take away the need for both the silly free webhost (that may terminate service at any $random $date and you aditional pi zerro w.

in other usecases, i would recoment using the router's build-in vpn-connections in which case you still use the pie but here you connect directly to it, as well as get access to the cam's livestream when its active.
Ik heb zelf geen OpenWRT router maar dat zou wellicht ook een mooie oplossing zijn.

Ik zie die gratis webhost niet echt als een probleem overigens. Qua security maakt het hoe ik het heb opgezet niet uit en als ze de service cancellen dan kom ik daar snel genoeg achter omdat ik dan geen enabled/disabled bericht meer hoor. In dat geval ga ik gewoon op zoek naar een ander, er zijn er zat. De Pi draait bij mij altijd dus dat is ook geen probleem, al zal dat voor sommige mensen misschien niet de meest ideale oplossing zijn.

VPN is niet echt nodig omdat je via de app en cloud dienst je beelden al kan bekijken zonder daarvoor VPN en/of open poorten nodig te hebben. VPN vind ik ook niet echt praktisch op een tel vergeleken met de setup hoe ik 'm nu heb.

Comment form
(required)
(required, but will not be displayed)
(optional)