Anyone know that companies are interested in smart fridge : Samsung have build their ones , LG have too , etc. but noone have make a way to transform a traditional fridge in a smart one. My solution is the simpliest ever maden , is inexpensive and can be used by every one thanks to Alexa echo dot 2.
The main difference is that user have to put only few information about the food tha put into the fridge and that information will be saved for the next time so after a trial period user virtually have to put and pick up food from fridge naturally, without spend time to collect infos or to store into db manually by smartphone.
The concept is very easy , so natural, that every one can do it. You can said "Alexa ask food scanner to charge the fridge" that, in a second, you can scan food using the barcode scanner installed into my product and in a minute you have filled up your fridge with your shopping and automatically into the db. Food Scanner return to normal mode after 15 minutes automatically or you can set it manually by telling Alexa that your've finished.
When you pick up some food from the fridge you should scan it before eat it , that's all! In this way your db is always updated and respect what do you have into the fridge anytime.
Having a virtual copy of your fridge you can do anything :
- you can send recipes based on what you have ,
- you can prefer recipes that contains food with a sooner expiration date,
- you can create, on the fly, a shopping list that match with your abitual food that you haven't into the fridge
- you can ask Alexa to send you recipes based on your lifestyle (diet, fitness , etc.) ( To implement! )
- you can do all of these things from outside home with Reverb for Alexa App
What do you need for build your own food scanner:
- An arduino Mkr1000
- a barcode scanner (you can buy it from Amazon marketplace for less than € 18,00)
- a led for a visual feedback of Food Scanner state
- Alexa echo dot 2
That's it!
This is how unmount barcode scanner:
Let's start with Arduino ....soldering pins:
Wiring is so simple that it can be maden by a children :
Ok let's start with the arduino's code . Arduino connects with your wifi network and Artik Cloud via MQTT protocol . Each time a barcode is acquired it send it to Artik Cloud passing the mode parameter . Artik Cloud store it and have a rule to send these values to a gateway that perform action with the server (store, update, send email , and search).
/*
this script is written by Jordy De Rosa who is the unique owner of this software
This is a project submitted to The Alexa and Arduino Smart Home Challenge contest on
https://www.hackster.io/contests/alexasmarthome
*/
#include <MQTTClient.h>
#include <ArduinoJson.h>
#include <SPI.h>
#include <WiFi101.h>
#include "TimerObject.h"
const char* _SSID = ""; //Wi-Fi SSID
const char* _PASSWORD = ""; // Wi-Fi Password
// MQTT - Artik Cloud Server params
char Artik_Cloud_Server[] = "api.artik.cloud"; // Server
int Artik_Cloud_Port = 8883; // MQTT Port
char Client_Name[] = ""; // Any Name
char Device_ID[] = ""; // DEVICE ID
char Device_TOKEN[] = ""; // DEVICE TOKEN
char buf[200];
char MQTT_Subscription[] = "/v1.1/actions/YOU_DEVICE_ID"; // (/v1.1/actions/"DEVICE ID")
char MQTT_Publish[] = "/v1.1/messages/YOUR_DEVICE_ID"; // (/v1.1/messages/"DEVICE ID")
TimerObject *timer1 = new TimerObject(900000); //Timeout to change food scanner mode carica/scarica
WiFiSSLClient client;
MQTTClient MQTT_Artik_Client; // MQTT Protocol
//led SET
int ledPin=17; //define a led pin in my case arduino pin n. 17
//function to manage received action from Artik Cloud
void messageReceived(String &topic, String &payload)
{
DynamicJsonBuffer jsonBuffer(200); //you can save memory by declaring a static buffer
Serial.println("incoming: " + topic + " - " + payload);
JsonObject& jsonresponse = jsonBuffer.parseObject(payload);//parse json message from Artik Cloud
String action=jsonresponse["actions"][0]["name"];
if(action=="setOn")
{
digitalWrite(ledPin,HIGH);
timer1->Start();
}
else if(action=="setOff")
digitalWrite(ledPin,LOW);
}
void setup()
{
//inizialize pin and Serial port
pinMode(ledPin,OUTPUT);
pinMode(16,OUTPUT); //i've attached led ground pin to Arduino pin n. 16 and setted it to LOW
digitalWrite(16,LOW);
//set timer to change food scanner mode
timer1->setOnTimer(&ResetMode);
//Inizialize Serial(to communicate with USB) and Serial1 (to communicate with barcode scanner)
Serial.begin(9600);
Serial1.begin(9600);
// Wifi Setting
WiFi.begin(_SSID, _PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//Some debug strings to return to serial monitor
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
MQTT_Artik_Client.begin(Artik_Cloud_Server, Artik_Cloud_Port,client); // Connect to Artik Server
while (!MQTT_Artik_Client.connect(Client_Name, Device_ID, Device_TOKEN)) { // Connect to Artik IOT Device
Serial.print("*");
delay(1000);
}
//MQTT listner
MQTT_Artik_Client.subscribe(MQTT_Subscription);
MQTT_Artik_Client.onMessage(messageReceived);
}
void loop()
{
MQTT_Artik_Client.loop();
if (Serial1.available())
{
// If anything comes in Serial1 (pins 0 & 1)
//Serial.write(Serial1.read()); // read it and send it out Serial (USB)
//Serial.print("Barcode=");
String barcode=Serial1.readString();
Serial.println();
//publish on artik cloud
//this function build json payload and return buffer lenght too
loadBuffer(barcode);
Serial.print("Publishing--->");
Serial.println(buf);
//publishing message to Artik Cloud
MQTT_Artik_Client.publish(MQTT_Publish,buf);
}
//Update Timer1
timer1->Update();
}
int loadBuffer(String t )
{
DynamicJsonBuffer jsonBuffer(200); // reserve spot in memory
JsonObject& root = jsonBuffer.createObject(); // create root objects
root["led"]="";
if(digitalRead(ledPin)==HIGH)
root["mode"]= "carica";
else
root["mode"]= "scarica";
root["barcode"] = t;
root.printTo(buf, sizeof(buf)); // JSON-print to buffer
return (root.measureLength()); // also return length
}
//this function is fired by timeout and turn off led on food scanner and change mode from carica to scarica
void ResetMode()
{
digitalWrite(ledPin,LOW);
timer1->Stop();
}
Ok Arduino is now programmed and ready.
Arduino connects with Artik Cloud so you have to create a new Device and Manifst. You can find other mkr1000 device type or create your own. Anyway you have to create variable in the manifest that are:
barcode : String
led: String
mode: String
and the create rule that monitor incoming barcode values from food scanner and make http request to gateway.php stored in your own server.
gateway.php
<?php
$user_name="YOU NAME";
$user_mail="EMAIL ADDRESS";
/*this script is written by Jordy De Rosa who is the unique owner of this software
This is a project submitted to The Alexa and Arduino Smart Home Challenge contest on
https://www.hackster.io/contests/alexasmarthome
This is the API called from Amazon Alexa and it manage action by server side as send email, add/sub food into the fridge
table and manage all sort of report to the user.
I've planned these actions:
spesa -> It create a shopping list based on what the user buy and eat daily.
My software can learn from user and then suggest to buy food that usually user eats.
So basically software checks what do you need consulting DB (frigo table) and search it on amazon.com collecting
images and the link of the firs Amazon seller that have it to purchase it easly.
All these informations will be sent by email to the user for consulting and/or buying from Amazon.com or local
market. User can speak with Alexa inside or outside home by using the Reverb for Amazon Alexa app available for Ios and Android
By the way in the future, i have not enought time to develop it right now, i can implement another Alexa function
to grab the shopping list already sent to the user and buy all the items from amazon.com
ricetta -> It search and send by email recipes based on food that you have into the fridge (stored by my food scanner hw).
Foods are selected randomly from frigo table
The results will be sent by email to the user for consulting
For this function i've subscribed a free plan on https://spoonacular.com that provide a lot of infos to do that and more.
in the future i can easly implement a function to prefer recipes that matchs with our lifestyle consulting
carbs , fats and more infos from theri db. But i have not enought time to develope it until contest ends.
registra -> It add or sub my food into the fridge table in my db .
First of all it invoke IsMyFood function to search if the food i want to insert into the fridge table exists on my
prodotti table(searching EAN barcode sent by my food scanner HW in prodotti table).
If the product is already known software store values into the db->frigo table and set my_exp_date adding
prodotti.exp_date values to the values returned by NOW() mysql function
If it is a new product software will send an email with a form to the user in a way to teach db what you're
putting into your fridge.
The other lines of codes are aux function to perform the actions describes before.
*/
if($_GET['action']=="spesa")
{
//cosamanca() return an associative array with all foods you needs. Software searchs into the db and count how many times
//i have eaten a food for each foods into frigo table(usato='1'). Then i calculate an average of all that values
//to have a threshold to filter data and to know which food i eat more and put them into my shopping list
//There is another values , VIF (Very Important Food) , that software will ad to you shopping list automatically
//if that vif food isn't in your frigo table (your real fridge)
//vif is a boolean variable that user have to choose when adding new food to the prodotti db
$lista=cosamanca();
//creating mail body text and table
$body="Hello $user_name you should buy these products :<br>
<table border='0'><th>Product</th><th>Amazon Link</th><th>Image</th>";
for($i=0;$i<count($lista);$i++)
{
//getLinks returns an associative array with image url and shopping url from Amazon searching by barcode or descr values
getLinks($lista[$i]['ean'],$links);
//if not founded on Amazon by barcode getLinks() returns "Not available on Amazon" -> try search it by descr value
if($links['link']=="Not available on Amazon")
{
//try search it on Amazon by descr value
getLinks($lista[$i]['descr'],$links);
}
//anyway these infos will be added to body of the shopping list email to send to the user
$link=$links['link'];
$img=$links['img'];
$descr=$lista[$i]['descr'];
$descr=ucwords(strtolower($descr));
$body .="<tr>
<td>$descr</td><td>$link</td><td>$img</td>
</tr>";
}
$body .="</table>";
$headers = "From: noreply@foodscanner.it\r\n";
$headers .= "Reply-To: noreply@foodscanner.it\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($user_mail,"Shopping List From Food Scanner",$body,$headers))
echo "Shopping list sent!";//this text will be said by Alexa
else
echo "Error while sending email";
}
else if($_GET['action']=="registra")
{
$descr=$_GET['descr'];
$exp=$_GET['g_scadenza'];
//calcolate a % of g_scadenza to store values into db. In this way i can exstimate food expiration date because i can
//purchase a product not so fresh sometime and other time fresh
$exp=round(0.8*$exp);
$vif=$_GET['vif'];
$barcode=$_GET['barcode'];
$barcode=str_replace("\r","",$barcode);
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open a db connection
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
if(mysqli_query($connection, "INSERT INTO prodotti (ean,vif,exp_date,descr) VALUES ('$barcode','$vif','$exp','$descr')"))
{
echo "New food created successfully";
//get new record infos to perform a second query that will add product into the fridge table
if(IsMyFood($barcode,$food))
AddFoodToFridge($food);//add food to the frigo table
else
echo "Error! Can't find food just added to prodotti table";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
//close db connection
$connection->close();
}
else if($_GET['action']=="ricetta")
{
//search food that have into the frigo table not used and ordered by expiration date in a way that i will
//search some recipes to eat food with sooner expiration date
$search_food_string=random_food();
//if $search_food_string isn't empty do:
if($search_food_string!="")
{
//Unirest Class to perform http request to spoonacular API
require_once 'Unirest/src/Unirest.php';
$response = Unirest\Request::get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/food/site/search?query=$search_food_string",
array(
"X-Mashape-Key" => "MY KEY",
"Accept" => "application/json"
)
);
//transform response in json format and parse it
$json_response=json_decode($response->raw_body,true);
if(count($json_response["Recipes"]>0))
{
//building mail body text and table
$messaggio="<html><body><table><th>Recipe Name</th><th>Recipe Image</th>";
// echo "<br>count=".count($json_response["Recipes"])."<br>";
for($i=0;$i<count($json_response["Recipes"]);$i++)
{
$link= $json_response["Recipes"][$i]["link"];
$img=$json_response["Recipes"][$i]["image"];
$name=$json_response["Recipes"][$i]["name"];
$messaggio .="<tr><td><a href='$link'><strong style='font-size: 35px;'>$name</strong></a><td><img src='$img' alt='Recipe Image'></td></tr>";
}
$messaggio .="</table></body></html>";
$headers = "From: noreply@foodscanner.it\r\n";
$headers .= "Reply-To: noreply@foodscanner.it\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($user_mail,"Some Recipes For You",$messaggio,$headers))
echo "Mail with recipes sent!";//This text will be said by Alexa
else
echo "ERROR";//This text will be said by Alexa
}
else
echo "Fridge is empty!";//This text will be said by Alexa
}
else
echo "No Recipes Founded";//This text will be said by Alexa
}
else // action called by Artik Cloud triggered by food scanner HW
{
$msg="";
//get headers from http request and store Barcode and Mode values
foreach (getallheaders() as $name => $value)
{
$msg .=$name." - ".$value."
";
if($name=="Barcode")
$barcode=$value;
if($name=="Mode")
$inserire=$value;
}
//delete \r from barcode values
$barcode=str_replace("\r","",$barcode);
$message="Barcode=$barcode, Mode=$inserire";
if($barcode=="")
exit();
//search if barcode is already known the add/sub food into/to the fridge or send email to request infos about it
if(IsMyFood($barcode,$food))
{
//if mode is carica add to the frigo table else sub it
if($inserire=="carica")
AddFoodToFridge($food);
else
SubFoodFromFridge($food);
}
else
{
//new food to store into prodotti table->ask user to provide infos about it-> send email
invia_email_inserimento($barcode);
}
}
function AddFoodToFridge($food)
{
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open connection with db
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
//format data and add $food["exp_date"] stored into prodotti table to today values
$exp_date=date("Y-m-d", mktime(0, 0, 0, date('m'), date('d')+$food["exp_date"], date("Y")));
//add food into frigo table
if(mysqli_query($connection, "Insert into frigo (id_prodotti,my_exp_date,usato) VALUES ('".$food['id']."','$exp_date','0')"))
{
echo "New record to frigo created successfully -> id=".$food['id'].", exp_date=$exp_date, usato=0";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
//close connection with db
$connection->close();
}
function SubFoodFromFridge($food)
{
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open connection with db
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
//query to change usato value to 1 because i want to eat it but i want to remember that i have it in the future
$sql="SELECT * FROM frigo WHERE id_prodotti='".$food["id"]."' AND usato='0' ORDER BY my_exp_date DESC";
$msg="sql=$sql
";
$risultato=mysqli_query($connection, $sql);
if(mysqli_num_rows($risultato) > 0)
{
while($row=mysqli_fetch_array($risultato))
{
$id_frigo=$row['id'];
}
$sql2="UPDATE frigo SET usato = '1' WHERE id ='$id_frigo'";
if(mysqli_query($connection,$sql2))
$msg.= "<br>Frigo agggiornato ->usato prodotto con id=$id_frigo<br>";
else
$msg .= "Error: " . $sql2 . "<br>" . $conn->error;
}
else
$msg .= "il prodotto non c'è in frigo";
//close connection with db
$connection->close();
}
function IsMyFood($barcode,&$MyFoodValues)
{
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open connection with db
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
$barcode=trim($barcode);
//search if i have this barcode into my db and return it
$risultato=mysqli_query($connection, "SELECT * FROM prodotti WHERE ean='$barcode'");//8722700480297
$esiste=false;
$id_prodotto="";
$exp_date="";
if(mysqli_num_rows($risultato) > 0)
{
//esiste
$esiste=true;
while($row=mysqli_fetch_array($risultato))
{
$MyFoodValues=$row;
}
}
else
$esiste=false;
$connection->close();
echo "<br>esiste=$esiste<br>";
return $esiste;
}
function invia_email_inserimento($barcode)
{
$message= "<html><body>
Barcode number $barcode is missing in your db. Please provide informations below to add this food in your fridge.
<form method='get' action='URL_OF_THIS/gateway.php?action=registra'>
Food Description(es name): <input type='text' name='descr'><br><br>
How many days does it expire ? <input type='text' name='g_scadenza'><br><br>
This is a must have food? <select name='vif'>
<option value='SI' selected='selected'>YES</option>
<option value='NO'>NO</option>
</select>
<input type='hidden' name='barcode' value='$barcode'>
<input type='hidden' name='action' value='registra'>
<br>
<input type='submit' value='ADD PRODUCT'>
</form>
</body></html>";
$headers = "From: noreply@foodscanner.it\r\n";
$headers .= "Reply-To: noreply@foodscanner.it\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if(mail($user_mail,"Please Complete Food Form",$message,$headers))
echo "Mail with form sent successfuly";
else
echo "Error while sending email";
}
function random_food()
{
//extract a random food from frigo db ordered by expiration date
$str="";
$sql= "SELECT * FROM (
SELECT descr,id_prodotti,usato,my_exp_date
FROM prodotti join frigo on frigo.id_prodotti=prodotti.id where usato='0' and my_exp_date>=now()
ORDER BY rand () limit 2
) AS tmp_table GROUP BY id_prodotti order by my_exp_date DESC";
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open connection with db
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
$risultato=mysqli_query($connection, $sql);
if(mysqli_num_rows($risultato) > 0)
{
$i=0;
while($row=mysqli_fetch_array($risultato))
{
$str .=$row['descr'];
if($i==0)
$str .="+";
$i++;
}
}
//close connection and return food string
$connection->close();
return $str;
}
function cosamanca()
{
//as described before this function will search missing food and return them
$sql="SELECT descr, count(*) as hits
FROM frigo join prodotti on prodotti.id=frigo.id_prodotti
GROUP BY descr";
$host="HOST";
$my_db_user="DB_USER";
$my_db_user_pass="DB_PASS";
$db="DB_USER_4";
//open connection with db and perform query
$connection = mysqli_connect($host, $my_db_user, $my_db_user_pass, $db);
$media=0;
$risultato=mysqli_query($connection, $sql);
if(mysqli_num_rows($risultato) > 0)
{
$num_count=0;
$i=0;
while($row=mysqli_fetch_array($risultato))
{
$num_count +=$row['hits'];
$i++;
}
//calculation average for threshold
$media=round($num_count/$i);
}
//adjust average dinamically
if($media<=2)
$media=1;
//collect food for shopping list
$sql="SELECT descr,frigo.id,ean,vif, COUNT(*) AS cnt
FROM frigo join prodotti on frigo.id_prodotti=prodotti.id where usato='1' and vif='0'
GROUP BY descr
HAVING cnt >= '$media'";
$i=0;
$risultato=mysqli_query($connection, $sql);
if(mysqli_num_rows($risultato) > 0)
{
while($row=mysqli_fetch_array($risultato))
{
$lista_della_spesa[$i]['ean']=$row['ean'];
$lista_della_spesa[$i]['descr']=$row['descr'];
$i++;
}
}
//get VIF (Very Important Food) from prodotti that i don't have into the fridge and add them to the shopping list
$sql="SELECT descr,ean,vif from prodotti join frigo on frigo.id_prodotti=prodotti.id where usato='1' and vif='1'";
$risultato=mysqli_query($connection, $sql);
if(mysqli_num_rows($risultato) > 0)
{
while($row=mysqli_fetch_array($risultato))
{
$lista_della_spesa[$i]['ean']=$row['ean'];
$lista_della_spesa[$i]['descr']=$row['descr'];
}
}
//close connection with db
$connection->close();
//return shopping list
return $lista_della_spesa;
}
function getLinks($ean, &$link_array)
{
//get html page from amazon search
$html=file_get_contents("https://www.amazon.it/s/field-keywords=$ean");
//if no results store Not available on Amazon
if(strpos($html,"non coincide con alcun prodotto"))
{
$link_array['link']="Not available on Amazon";
$link_array['img']="Not available on Amazon";
}
else
{ //parse Amazon results page
$prima=strpos($html,"a-link-normal a-text-normal");
$html=substr($html,$prima);
$href=strpos($html,"href=");
$html=substr($html,$href);
$fine_href=strpos($html,">");
$fine_href -=7;
$link = substr($html,6,$fine_href);
$html= substr($html,$fine_href);
$fine_img=strpos($html,'.jpg');
$img=substr($html,8,$fine_img+4).'">';
$link_array['link']=$link;
$link_array['img']=$img;
}
}
?>
In the code i've commented step by step so it's easy to understand. You need UNIREST library that can be donwloaded from here .
Ok we have completed communication Arduino -> Artik Cloud -> gateway.php
gateway.php read, write from a mysql db that have this structure:
and this is the file to generate db LINK.
Now the core ALEXA. You have to create an amazon developer account to write an Alexa Skill and Lambda function.
This is the interactino model for Alexa
{
"languageModel": {
"intents": [
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "Charging",
"samples": [
"Charging charge the fridge",
"Charging put the shopping into the fridge"
],
"slots": []
},
{
"name": "SendRecipe",
"samples": [
"suggest me a recipe",
"surprise me with a recipe",
"i want to cook something",
"give me a recipe",
"what should i eat today",
"what can i cook",
"what can i cook today",
"what should i eat",
"send me recipes",
"send me some recipe"
],
"slots": []
},
{
"name": "Shopping",
"samples": [
"what should i have to buy",
"give me shopping list",
"help me with shopping list",
"what should i have into the fridge",
"what is missing into the fridge",
"write me shopping list"
],
"slots": []
},
{
"name": "StopScanning",
"samples": [
"shopping bag is empty",
"stop filling fridge",
"i have finished",
"i've finished",
"stop scanning food"
],
"slots": []
}
],
"invocationName": "food scanner"
}
}
and this is the lambda function linked to this skill
var http = require('http');
var https = require('https');
var request =require('request');
'use strict';
const Alexa = require('alexa-sdk');
const APP_ID = undefined; // TODO replace with your app ID (OPTIONAL).
exports.handler = function (event, context) {
const alexa = Alexa.handler(event, context);
alexa.APP_ID = APP_ID;
alexa.registerHandlers(handlers);
alexa.execute();
};
const handlers = {
'LaunchRequest': function ()
{
this.emit(":tell","Launch Intent","");
},
//StopScanning Alexa Intent Function
'StopScanning': function ()
{
//referencing to self variable
var self=this;
//perform with REQUEST module post to artik cloud api to turnOff led off my Food Scanner HW
request.post(url2(), function(error, response, body)
{
//Alexa speak after request is completed
self.emit(":tell","Ok. Scanning stopped","")
})
},
//Chargin Alexa Intent Function
'Charging': function()
{
var self=this;
//perform post with REQUEST module to artik cloud api to turnOff led on my Food Scanner HW
request.post(url(), function(error, response, body)
{
//Alexa speak after request is completed
self.emit(":tell","Hello. I'm ready. Scan your foods and then put it into the fridge!","")
})
},
//SendRecipe Alexa Intent Function
'SendRecipe': function()
{
var self=this;
//store Alexa base speech text
var myspeech="Let me see what do you have in the fridge. Ok. I will send you an email with some recipe based on what do you have into the fridge.";
var jsonObject = JSON.stringify("");
// the post options
var options =
{
//replace with your host and path
host: 'host',
path: '/path_to_gateway/gateway.php?action=ricetta',
method: 'GET',
headers:
{
'Content-Type': 'application/json',
}
};
//perform http request with HTTP module
var reqPost = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
myspeech +=chunk;
self.emit(":tell",myspeech);
});
});
reqPost.write(jsonObject);
reqPost.end();
},
'Shopping': function () {
var self=this;
var myspeech = "Ok. Let me think about what you should buy today. I will send you an email with these informations in a second. ";
var jsonObject = JSON.stringify("");
// the post options
//replace with your host and path
var options = {
host: 'host',
path: '/path_to_gateway/gateway.php?action=spesa',
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
};
var reqPost = http.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
myspeech +="<amazon:effect name='whispered'>"+chunk+"</amazon:effect>";
self.emit(":tell",myspeech);
});
});
reqPost.write(jsonObject);
reqPost.end();
},
'AMAZON.HelpIntent': function () {
this.emit(':tell', "Help Intent","");
},
'AMAZON.CancelIntent': function () {
this.emit(':tell', "Cancel Intent","");
},
'AMAZON.StopIntent': function () {
this.emit(':tell', "Stop Intent","");
},
};
function url() {
//replace with your device id
var mydata ='{"sdid":"YOUR_DEVICE_ID","type":"message","data":{"led":"ON"}}'
return {
//replace with your device token
url: "https://api.artik.cloud/v1.1/messages",
headers: {
"Authorization" : "Bearer YOUR_DEVICE_TOKEN",
"Content-Type" : "application/json"
},
form : mydata
}
}
function url2() {
//replace with your device id
var mydata ='{"sdid":"YOUR_DEVICE_ID","type":"message","data":{"led":"OFF"}}'
return {
//replace with your device token
url: "https://api.artik.cloud/v1.1/messages",
headers: {
"Authorization" : "Bearer YOUR_DEVICE_TOKEN",
"Content-Type" : "application/json"
},
form : mydata
}
}
I have commented step by step code so you can understand all easly.
This is the link to the deploy with request module (not included in Lambda environment by default)
That's all!.
Thanks for watching.
Best Regards
Jordy De Rosa
Comments