FOSCAM motion/sound detection and IR Led status in HA v2 (push method)

Hi,

I would like to share my new configuration for use motion and sound sensors built in foscam cameras (like FOSCAM C1) as binary sensors in HA.

In my old setup (https://community.home-assistant.io/t/foscam-motion-sound-detection-and-ir-led-status-in-ha/) I was using a polling method and the problem was the latency between updates in sensors, it could take about 2 or 3 seconds (for polling and updating interval) and this way wasn’t the best for automations like turn on lights.

In my new config i’m changing from a polling method to a push method, achieve this with a foscam camera is a bit complex because foscam doesn’t provide something like a “push url” for notify changes in motion or sound sensors so … the way that i choose is intercept the http request that the camera uses for push notifications (in official foscam app).

For this setup we need a domain name local server and a web server (like apache) with PHP support.

1. Resolve the domain push-access.myfoscam.com to your local apache server (192.168.1.31 for me) instead of foscam public one

I’m using bind9 so i added a new zone (in named.conf.default-zones for ubuntu):

zone "http://push-access.myfoscam.com." {

        type master;

        file "/etc/bind/db.fakeroot";

};

and this is the content for /etc/bind/db.fakeroot:

;

; BIND reverse data file for broadcast zone

;

$TTL    604800

@       IN      SOA     localhost. root.localhost. (

                              2         ; Serial

                         604800         ; Refresh

                          86400         ; Retry

                        2419200         ; Expire

                         604800 )       ; Negative Cache TTL

;

@       IN      NS      localhost.
push-access.myfoscam.com. IN A 192.168.1.31

You can test your Domain name server with dig, for example:

$ dig +short push-access.myfoscam.com @192.168.1.101
192.168.1.31 <-- your local IP where your apache server is listening

(where 192.168.1.101 is your local dns)

2. Config your foscam camera (in settings->network->IP configuration) for use your domain name server and enable the push notifications in Detector -> Action Detection and Sound Detection.

Foscam will send a POST request on every push notification (every 60 seconds) to http://push-access.myfoscam.com/gateway, the most important variables are msgType (1 for motion or 2 for sound) and senderTag (the camera ID or mac address).

3. Create a gateway.php in /var/www/html for example:

<?php

define('BROKER', '192.168.1.34');  //Your mosquitto server ip

define('PORT', 1883);

define('CLIENT_ID', "pubclient_" + getmypid());

//Get type (1 motion, 2 sound)

$alert_type = $_POST['msgType'];

//Get camera ID

$cam_id = $_POST['senderTag'];

//Get time

$alert_time = $_POST['msgTime'];

$client = new Mosquitto\Client(CLIENT_ID);

$client->Credentials('myuser', 'mypass');

$client->connect(BROKER, PORT, 60);

$topic = "ipcamera/$cam_id/$alert_type";

$client->publish($topic, 'on', 0, false);

$client->disconnect();

?>;

This PHP will receive the foscam request and will publish a message to mqtt server.

4. Configure apache for rewrite calls from /gateway to /gateway.php

<Directory /var/www/html>;

    AllowOverride All

    Require all granted

    RewriteEngine on

    RewriteRule "gateway$" /gateway.php

</Directory>;

EDIT: After updating my foscam firmware, now the camera attempts to connect using HTTPS (TCP 443) instead of HTTP (isn’t validating the ssl certificate yet) so you also need to add this configuration to apache using https (and configure SSL certificates, etc … )

5. Create binary sensors in HA

- platform: mqtt

  state_topic: 'ipcamera/<your camera ID>/1'

  name: cam_plantabaja_motion

  qos: 0

  payload_on: 'on'

  payload_off: 'off'

  sensor_class: motion

- platform: mqtt

  state_topic: “ipcamera/<your camera ID>/2"

  name: cam_plantabaja_sound

  qos: 0

  payload_on: 'on'

  payload_off: 'off'

  sensor_class: sound

6. Create automation and scripts for turn off sensor after 50 seconds for every sensor, this is an example for motion:

alias: Turn off motion sensor for plantabaja

hide_entity: True

initial_state: 'on'

trigger:

  - platform: state

    entity_id: binary_sensor.cam_plantabaja_motion

    to: 'on'

action:

  - service: script.timed_motion_plantabaja

And create the scripts:

timed_motion_plantabaja:

  sequence:

    - service: script.turn_off

      data:

         entity_id: script.timer_off_motion_plantabaja

    - service: script.turn_on

      data:

        entity_id: script.timer_off_motion_plantabaja

timer_off_motion_plantabaja:

  sequence:

    - delay:

        seconds: 50

    - service: mqtt.publish

      data:

        topic: 'ipcamera/<your camera ID>/1'

        payload: 'off'

NOTE: The php script uses mosquito php so you should install it

2 Likes

Thanks for sharing this, I’m currently polling for status every second, it is responsive enough for what I need at the moment but I’m not happy that it’s having to constantly hammer away over the WiFi. I’ll be giving your method a go when I have time.

Thanks!!

Definitively will give a try this weekend. will come back with results

I am about to try your approach, which seems really good. I am so annoyed of the lag the polling brings.
But before I start, I just wanted to check if you still use it and if it’s still working since the post is 18 months old.

So, is it worth giving it a shot?

Thanks!

Hi!

Yes, I’m still using this method but now I’m using pi-hole instead of my own bind9 configuration … but i’ts simple, you only have to redirect the domain push-access.myfoscam.com to your local ip http server and this is my last gateway.php version (is a really faaaaaast script but works!):

<?php

define('BROKER', 'localhost');
define('PORT', 1883);
define('CLIENT_ID', "pubclient_" . getmypid());


if ( !empty($_POST['msgType']) and !empty($_POST['senderTag']) and !empty($_POST['msgTime']))
{
  //Get type (1 motion, 2 sound)
  $alert_type = $_POST['msgType'];
  //Get camera ID
  $cam_id = $_POST['senderTag'];
  //Get time
  $alert_time = $_POST['msgTime'];

} else {
  exit("Missing post parameters");
}


$client = new Mosquitto\Client(CLIENT_ID);
$client->setCredentials('user', 'password');
$client->connect(BROKER, PORT, 60);

$topic = "ipcamera/$cam_id/$alert_type";
$client->publish($topic, 'on', 0, false);

$client->disconnect();
?>
1 Like

@jgon I try your configuration and it work
thank is great solutions
but i use off_delay pram and dosn’t need scrip or automation to back to off

binary_sensor:
  - platform: mqtt
    state_topic: "ipcamera/E8ABFA8CCD59/1"
    name: cam_bedroomc1_motion
    qos: 0
    payload_on: "on"
    payload_off: "off"
    device_class: motion
    off_delay: 20

in my next step i want chenge mqtt whit rest in php, in my opion is more clear and simple

Thanks for your response! I use Ad Guard, so I am about to do the re-write there.

I am not at all experienced in webservers so I take the liberty of asking a stupid question:
Could you use the HA webserver for the script, eliminating the need for an additional server?

I’ve tried creating a custom addon especially for this case but couldn’t get any messages from the camera’s to be passed even though the simulated postman commands did work.

I’ve moved this setup to my Synology NAS, working like a charm!
To summarise:

  1. Rewrote push-access.myfoscam.com and security-push-access.myfoscam.com (C2 V3 has slightly different firmware) to the external url of my Synology NAS with AdGuard.
  2. Installed Apache HTTP Server 2.2 and PHP 7.0 on the Synology NAS and cofigured Web Station to use those services.
  3. Created gateway.php as described below using a long-lived access token I created in Home Assistant.
  4. Created .htaccess file as described below
  5. Created some automations. Example HERE

For anyone willing to give the Apache addon another go, this is where I left it

gateway.php

<?php

// Initiate cURL
$endpoint = 'http://192.168.0.1:8123/api/events/foscam_intercept';
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_POST, 1);

// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json',
  'Authorization: Bearer paste-your-long-lived-access-token-here'
));

// Setup the JSON body
foreach($_POST as $key => $value) {
  $data->$key = $value;
}
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

// Send the request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);

?>

.htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteRule "gateway$" /gateway.php
1 Like

Are ya’ll still using this setup?
I’ve got a Foscam FI9816p but I don’t see any requests going to push-access.myfoscam.com.

the only traffic I see is going to api.myfoscam.com or p2p-foreign*.myfoscam.com.

Hope to hear from you.

Hi,

If you have your Foscam without internet access (in my case I have a VLAN only for ip-cameras without internet access), the Foscam cameras call tu api.myfoscam.com before push-access.myfoscam.com.

If you want to do this, you have to change api.myfoscam.com in your DNS to a controlled server and answer to:

https://api.myfoscam.com/gateway?service=push.getSendUrl&appKey=foscam-fosbaby-foscloud-push-key&secretKey=SECRET-FOSCAM-FOSCLOUD-PUSH-MESG&senderTag=XXXXXXXXXX&userTag=XXXXXXXXXXX&version=1.0.1-DEV

with:

{"errorCode":"","data":{"sendMsgUrl":"http://push-access.myfoscam.com:80","sendMsgUrlSecure":"https://push-access.myfoscam.com:443","url":"https://push.myfoscam.com:443","channelCount":0}}

You can use “https://push.myfoscam.com” or whatever domain name that you want for receive push notifications.

hi, can you help understand all the steps to do it using adguard?

Sorry, it was to much of a hassle so I bought BlueIris and integrated all my cameras that way instead.

I struggled a lot with my new Foscam R5 but finally got it connected to ONVIF integration by adding a new user with simple password and using port 888. Now I just have to see how motion sensing and recording works :crossed_fingers: