From DerIng

I wrote a small php-script to access my netatmo weather station from pimatic.

Needed packages on your linux machine (hope I did not forget some ;-))

  • php5-common
  • php5-cli
  • php5-curl

Install the netatmo sdk from https://github.com/Netatmo/Netatmo-API-PHP into a folder where pimatic have access.

Now copy this script into the same folder (e.g.scripts/netatmo/Netatmo-API-PHP-master/pimatic2netatmo.php), make it executable and don’t forget the configuration! (You need a user account, client_id and client_secret from https://dev.netatmo.com/dev/createapp - It’s for free!)

#!/usr/bin/php5
<?php
/*
# ===========================================================
# Script by DerIng to access netatmo weather
# station by pimatic
#
# Btw.: pimatic rocks!! 
#____________________________________________________________
# History:
# March 12 2015:  Initial Version
# ===========================================================
# Please configure before first run! See section 
#
# // BEGIN of USER configuration !
#
# below!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# ===========================================================
*/

require_once("NAApiClient.php");
$config = array();

//===========================================================
// BEGIN of USER configuration

// your pimatic server (e.g. 'mypimatic.dyndns.org')
$_SERVER['HTTP_HOST'] = 'mypimatic.dyndns.org';

// for use with HTTPS set to 'on'
$_SERVER['HTTPS'] = 'off';

// your netatmo client id
// (you can get it for free: https://dev.netatmo.com/dev/createapp)
$config['client_id'] = '123456789abcdef0987654321';

// your client_secret
$config['client_secret'] = 'acegikmoq9udldsernvkdefnklsdfjs';

// your netatmo username
$username = "netatmouser@gmail.com";

// your netatmo password
$pwd = "secretpassword";

// END of USER configuration
//===========================================================


$module="undefined";
$sensor="undefined";

if (CheckArguments(arguments($argv), $module, $sensor)== FALSE ) ShowUsage();


//application will have access to station
$config['scope'] = 'read_station';
$client = new NAApiClient($config);

$client->setVariable("username", $username);
$client->setVariable("password", $pwd);

try
{
	$tokens = $client->getAccessToken();        
	$refresh_token = $tokens["refresh_token"];
	$access_token = $tokens["access_token"];
}
catch(NAClientException $ex)
{
    	echo "An error happend while trying to retrieve your tokens\n";
}


try
{
	// First retrieve user device list
	$deviceList = $client->api("devicelist");        
	
	if(isset($deviceList["devices"][0]))
    	{
        	$device_id = $deviceList["devices"][0]["_id"];
		if ($module =='Outdoor') 
		{
			if(isset($deviceList["modules"][0])) $module_id = $deviceList["modules"][0]["_id"];
			$params = array("scale" =>"max",
                        		"type"=>$sensor,
	                     		"date_end"=>"last",
                        		"device_id"=>$device_id,
					"module_id"=>$module_id);

		} else {
			$params = array("scale" =>"max",
                       			"type"=>$sensor,
                       			"date_end"=>"last",
	                       		"device_id"=>$device_id);
		}
		
        	
		$res = $client->api("getmeasure", $params);
        
		if(isset($res[0]) && isset($res[0]["beg_time"]))
        	{
            		$t = $res[0]["value"][0][0];  
            		echo "$t\n";
        	} 
    	}
}
catch(NAClientException $ex)
{
    echo "User does not have any devices\n";
}


//===========================================================
//Functions
//===========================================================

//Check if arguments are valid and return [MODULE] and [SENSOR]
function CheckArguments($arguments, &$module, &$sensor)
{
$valid = FALSE;
if (count($arguments['arguments'])== 2){
switch (strtolower($arguments['arguments'][0])) {
	case "indoor":
		$module = "Indoor";
		$valid = TRUE;
		switch (strtolower($arguments['arguments'][1])) {
		case "temperature": 
			$sensor = "Temperature";
			break;
		case "co2":
			$sensor = "CO2";
			break;
		case "humidity":
			$sensor = "Humidity";
			break;
		case "pressure":
			$sensor = "Pressure";
			break;
		case "noise":
			$sensor = "Noise";
			break;	
		default: $valid = FALSE;
		}
		break;
	case "outdoor":
		$module = "Outdoor";
		$valid = TRUE;
		switch (strtolower($arguments['arguments'][1])) {
		case "temperature":
                        $sensor = "Temperature";
                        break;
		 case "humidity":
                        $sensor = "Humidity";
                        break;
		default: $valid = FALSE;
		}
		break;
	}
}
return $valid;
}

//Show usage
function ShowUsage()
{
echo "\nSyntax: pimatic2netatmo.php [MODULE] [SENSOR]\n";
echo "\n\tMODULE\t[Indoor|Outdoor]\n\n";
echo "Valid Indoor sensors:\n";
echo "\n\tSENSOR\t[Temperature|CO2|Humidity|Pressure|Noise]\n\n";
echo "Valid Outdoor sensors:\n";
echo "\n\tSENSOR\t[Temperature|Humidity]\n";
exit (-1);

}

//Get pimatic2netatmo function arguments as array
function arguments ( $args )
{
  array_shift( $args );
  $endofoptions = false;

  $ret = array
    (
    'commands' => array(),
    'options' => array(),
    'flags'    => array(),
    'arguments' => array(),
    );

  while ( $arg = array_shift($args) )
  {

    // if we have reached end of options,
    //we cast all remaining argvs as arguments
    if ($endofoptions)
    {
      $ret['arguments'][] = $arg;
      continue;
    }

    // Is it a command? (prefixed with --)
    if ( substr( $arg, 0, 2 ) === '--' )
    {

      // is it the end of options flag?
      if (!isset ($arg[3]))
      {
        $endofoptions = true;; // end of options;
        continue;
      }

      $value = "";
      $com   = substr( $arg, 2 );

      // is it the syntax '--option=argument'?
      if (strpos($com,'='))
        list($com,$value) = split("=",$com,2);

      // is the option not followed by another option but by arguments
      elseif (strpos($args[0],'-') !== 0)
      {
        while (strpos($args[0],'-') !== 0)
          $value .= array_shift($args).' ';
        $value = rtrim($value,' ');
      }

      $ret['options'][$com] = !empty($value) ? $value : true;
      continue;

    }

    // Is it a flag or a serial of flags? (prefixed with -)
    if ( substr( $arg, 0, 1 ) === '-' )
    {
      for ($i = 1; isset($arg[$i]) ; $i++)
        $ret['flags'][] = $arg[$i];
      continue;
    }

    // finally, it is not option, nor flag, nor argument
    $ret['commands'][] = $arg;
    continue;
  }

  if (!count($ret['options']) && !count($ret['flags']))
  {
    $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
    $ret['commands'] = array();
  }
return $ret;
}
?>

Usage:

Syntax: pimatic2netatmo.php [MODULE] [SENSOR]

        MODULE  [Indoor|Outdoor]

Valid Indoor sensors:

        SENSOR  [Temperature|CO2|Humidity|Pressure|Noise]

Valid Outdoor sensors:

        SENSOR  [Temperature|Humidity]

So please test this script at the command line before adding to pimatic!

If everything works fine then just add a new ShellSensor device to your pimatic configuration:

    {
      "id": "NetatmoTempIndoor",
      "name": "Indoor Temperatur:",
      "class": "ShellSensor",
      "attributeName": "tempIndoorNetatmo",
      "attributeType": "number",
      "attributeUnit": "°C",
      "command": "/home/pimatic/scripts/netatmo/Netatmo-API-PHP-master/pimatic2netatmo.php Indoor Temperature",
      "interval": 300000
    },

So at the end you can use all your netatmo weather station data to e.g. control your heating system (You can use it in your rules!) or just to record temperatures of the past (Since graphs with “historical” weather data are just part of the ShellSensors device!).
Alt text

Have fun + thanks for pimatic! It rocks!!

DerIng