Tutoriel: utiliser l'API pour poster des données de tous vos capteurs sur la plateforme eGreen

A quoi sert le webservice eGreen
Récupération de la clé d'API
Afin de pouvoir communiquer avec le l'API d'eGreen, il est nécessaire de faire la demande d'une clé d'API. Pour cela, envoyez-nous un email à contact@egreen.fr.
Cette clé, vous sera fournie accompagnée d'un code secret utile pour l'authentification lors des envois de données.
Envoyer des données
Principe
Actuellement seul l'envoi de données est autorisé. Il n'est donc pas possible de les récupérer ou de les modifier. Vous pourrez néanmoins télécharger l’ensemble de vos données sur la plateforme eGreen au format .xls ou .csv.
Pour pouvoir envoyer les données il suffit de procéder de la manière décrite ci-dessous.
- Les données doivent être envoyées à l'adresse suivante : https://rest.egreen.fr/energy/create
- Les paramètres doivent être envoyés en utilisant la méthode POST.
- Les paramètres à transmettre avec la requète:
- apiKey string(10)
- sig
- recDate YYYY-mm-dd
- recTime HH:ii
- sensorId string(50)
- energyType string(20)
- Un des deux paramètres suivant est obligatoire suivant le type de donnée envoyé
- consoEnergy decimal(10,3) : dans le cas d'une consommation d'energie depuis le dernier envoie ou dans le cas de données de température ou humidité.
- sensorValue decimal(18,2) : dans le cas d'un index de consommation (une différence sera faite sur notre serveur avec le dernier index reçu).
Le paramètre sig correspond à un hash calculé en utilisant l'algorithme MD5. La chaîne de caractère à utiliser pour calculer ce hash est la suivante:
api_secretapiKeyapi_keysensorIdsensor_idenergyTypeenergy_typeconsoEnergyconso_energy_or_sensor_value
Ce qui est en italique est à remplacer par les valeurs des paramètres de la requête et ce qui est en gras doit être écrit tel quel. L'api_secret correspond au code qui vous a été fourni avec votre clé d'API.
« conso_energy_or_sensor_value » est à remplacer par celui des deux paramètres que vous avez décidé d’envoyer.
Exemple de code
Arduino
/* Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen modified 27 March 2014 by Irwin Lourtet */ #include <SPI.h> #include <Ethernet.h> // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // Set the static IP address to use if the DHCP fails to assign IPAddress ip(192,168,0,177); // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; void setup() { //Initialise variables String sensor_id = String("YOUR SENSOR ID"); String energy_type = String("electricity"); String api_key = String("YOUR API KEY"); String api_secret = String("YOUR API SECRET"); String rec_date = String("YYYY-MM-dd"); String rec_time = String("HH:ii"); //Compute sig //Use an md5 library like https://github.com/tzikis/ArduinoMD5 String data = String("apiKey="+api_key+"&sensorId="+sensor_id+"&energyType="+energy_type+"&recTime"+rec_time+"&recDate="+rec_date); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection: if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip); } // give the Ethernet shield a second to initialize: delay(1000); Serial.println("connecting..."); // if you get a connection, report back via serial: if (client.connect("diy.egreen.fr", 80)) { client.println( "POST http://diy.egreen.fr/energy/create HTTP/1.1" ); client.println( "Host: diy.egreen.fr" ); client.println("User-Agent: Arduino/1.0"); client.println( "Content-Type: application/x-www-form-urlencoded" ); client.println( "Connection: close" ); client.print("Content-Length: "); client.println(data.length()); client.println(); client.print(data); client.println(); } else { // kf you didn't get a connection to the server: Serial.println("connection failed"); } } void loop() { // if there are incoming bytes available // from the server, read them and print them: if (client.available()) { char c = client.read(); Serial.print(c); } // if the server's disconnected, stop the client: if (!client.connected()) { Serial.println(); Serial.println("disconnecting."); client.stop(); // do nothing forevermore: while(true); } }
Python
from urllib2 import Request, urlopen from urllib import urlencode import md5 # Initialisation des variables url = 'https://rest.egreen.fr/energy/create' api_key = 'YOUR_API_KEY' api_secret = 'YOUR_API_SECRET' conso_energy = 25.6 # Votre consommation # Le type d'energie associé au capteur (electricity, water, gas, fuel, # temperature, humidity) energy_type = 'electricity' rec_date = 'YYYY-mm-dd' rec_time = 'HH:ii' sensor_id = 'YOUR SENSOR ID' # Calcul du sig m = md5.new(api_secret + 'apiKey' + api_key + "sensorId" + sensor_id + "energyType" + energy_type + "consoEnergy" + conso_energy) sig = m.hexdigest() # Preparation et execution de la requête query_args = { 'apiKey': api_key, 'consoEnergy': conso_energy, 'energyType': energy_type, 'recDate': rec_date, 'recTime': rec_time, 'sensorId': sensor_id, 'sig': sig} data = urlencode(query_args) request = Request(url, data) urlopen(request)
PHP
//Initialisation des paramètres $conso_energy = 25; $sensor_id = "YOUR_SENSOR_ID"; $api_key = 'YOUR_API_KEY'; $api_secret = 'YOUR_API_SECRET'; $energy_type = 'electricity'; $rec_date = 'YYYY-mm-dd', $rec_time = 'HH:ii'; //Calcul du hash $sig = md5("${api_secret}apiKey{$api_key}sensorId{$sensor_id}energyType{$energy_type}consoEnergy{$conso_energy}"); //Execution de la requête $ch = curl_init("https://rest.egreen.fr/energy/create"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('consoEnergy' => $conso_energy, 'energyType' => $energy_type, 'sensorId' => $sensor_id, 'apiKey' => $api_key, 'recDate' => $rec_date, 'recTime' => $rec_time))); $result = curl_exec($ch); curl_close($ch);