Project in progress
DRS Enabled Smart Pantry

DRS Enabled Smart Pantry © Apache-2.0

A pantry which can automatically replenish kitchen items.

  • 9,961 views
  • 7 comments
  • 24 respects

Components and supplies

Apps and online services

Ide web
Arduino IDE
Simpleicon sns
Amazon Web Services AWS SNS
Icon
Amazon Web Services Amazon Dash Replenishment Service

About this project

Most of the times, when I want to cook something I find some cooking ingredient (onion, garlic, chili etc.) is running low. In some cases I buy wrong item such as garlic instead of onion. When I reach at my kitchen I observe that, I have a plenty of onion but no garlic. How will you feel in such a situation?

To get rid from such situation I built a Smart Pantry which can order automatically to replenish every ingredients of my pantry with Amazon DRS. Busy life, easy solution!!!

Here, I will show you how I made such hi-tech pantry and I hope you will able to reproduce it as your requirement.

So, let's get started. First I will explain how I prepared my pantry to sense the shortage of any ingredient. I used Force Sensitive Resistor (FSR) to detect the absence of ingredient in a specific box of the pantry. Arduino UNO is used to to read the sensor value.

Preparing the Pantry

I took a 3 compartment kitchen box for my demo project and it can house three different ingredients into it's three separate box. For sensing the shortage of ingredients in a box I am measuring weight of each box with force sensitive resistor. Though FSR is not very accurate for weight measurement but enough for this project for identifying a blank box.

Photos attached above shows how I placed fsr in the box. I placed one fsr below each compartment and tried to put it at the center of the compartment. Using mini drill I made two holes for every sensor to bring out the pin of the sensor out of the box. Then I soldered jumper wire to each pin of the sensors to connect it with Arduino.

Three sensors are used for three separate parts of the box and sensors are placed in the center of each box.

Force sensitive resistor change its value when a force is applied to it. Pressure from a hard surface is not good for FSR and you will not get accurate result. For better output I place a small piece of foam on the bottom of every inner box using double sided tape. Place it in such position that it exactly be on the sensor.

Our pantry is ready!!!

Setup Amazon Dash Replenishment Service

DRS provides connected devices with direct access to Amazon’s powerful retail platform to order any item automatically. With easy-to-use APIs, device manufacturers can take advantage of Amazon's authentication and payment service.

After integrating with Amazon services like Login with Amazon (LWA) and Simple Notification Service (SNS), a simple API call allows a manufacturer to place a product order on behalf of a customer.

Let's get started with DRS.

Log in to Amazon Developer and AWS Account

If you don't have Amazon Developer or AWS (Amazon Web Services) Account then sign up for it.

Creating LWA Security Profile

For creating Amazon Security Profile:

1. Log into Amazon Developer Portal

2. After Successful Login to Developer Portal go to "Login with Amazon" from Apps & Services tab.

3. Click on Create a New Security Profile.

  • Write your Profile Namen in Security Profile Name field
  • Write your Profile's Description in Security Profile Description field
  • Privacy URL field is for writing Privacy Notice URL and click Save button.

4. Now Click on Web Settings from Manage drop-down

5. Click on Edit button and then Enter Allowed URL, Allowed Return URLs and Click Save button.

(Note: We will host a html page in a URL and the address of that page would be the return URL. You can set it later).

6. Now, click on General tab and note down the Security Profile ID and Client ID which will be required later.

Creating a new Amazon Web Services SNS

Amazon Simple Notification Service (Amazon SNS) is a fast, flexible, fully managed push notification service that lets you send individual messages or to fan-out messages to large numbers of recipients. Amazon SNS makes it simple and cost effective to send push notifications to mobile device users, email recipients or even send messages to other distributed services.

For Creating new Amazon Web Services SNS:

1. Login into Amazon Web Services Console

2. After Successful login in AWS Account search SNS and click on it.

3. Click on Create topic button.

4. A popup for SNS will be displayed. Enter Topic Name and Display name respectively. After writing this click Create Topic button.

5. Click on Edit Topic Policy from Other Topic Actions

6. Chose the option of "Only these AWS users" and then write AWS Account ID

You can get your AWS Account ID from My Account option

7. Now click on Update Policy button.

8. Note down the SNS Topic ARN(Amazon Resource Number).

9. Now, click on Create subscription

10. From the Protocol field select Email and enter your email address in Endpoint field.

11. Click on request confirmation. An email will be sent to your account.

12. From the provided link confirm your subscription.

Creating Amazon Dash Replenishment Service

1. Login to Amazon Developer Portal and go to "Dash Replenishment Service"

2. Click on Begin button. So, it will be redirected to Register with LWA page. Enter your LWA Security Profile ID (which noted earlier) and click next button.

3. Now Enter your Amazon Web Services SNS ARN (which noted earlier) and click next and Done button.

4. Now it is the right time to add a device in DRS account. Click on CREATE A DEVICE.

5. Enter your Device name and click to GENERATE button to generate a Model ID. Then Upload a photo. After that click next button.

6. Add Slots to your Device

Create as many slots as many you want for your device. Enter Product ASNs to slots. For information of Finding ASNs click on the "How to find ASNs" Google. Add items to your slot and submit.

Now you can use the Amazon DRS API in your application. For API and other help of DRS please visit: developer.amazon.com/public/solutions/devices/dash-replenishment-service.

Product registration using Customer facing webpage

Once we are done with creating all the individual elements, we are now ready to generate the authorization code from the DRS service that will be used to place order by Pantry.

For creating your own product registration page, you may use any of the free hosting platforms available.

Here is web page I have hosted on for register product from customer end to Amazon DRS. You may visit following link:

https://smart-pantry.000webhostapp.com/

And try to register by providing random serial no.

The html code for the website has been uploaded to code section.

To register your product:

1. Click on Login with Amazon and click on Okay button.

2. Choose the product for first slot and than click to next for second slot

3. Select product for second slot and so on.

4. Click to Complete Setup to Confirm Details.

5. After successful confirmation you will get an Authorization Code

6. You will also get an email about the confirmation.

Code

Code for AutorizationHTML
<html>
<body>
<div id="first" style="clear: both; text-align: center;">
<h1>
Success...!!!</h1>
<a href="https://cdn.instructables.com/FWA/9JHC/IX6FV7HW/FWA9JHCIX6FV7HW.LARGE.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="255" src="https://cdn.instructables.com/FWA/9JHC/IX6FV7HW/FWA9JHCIX6FV7HW.LARGE.jpg" width="400" /></a><br />
<b> Your 20 character Authorisation Code is... </b>
<h2 id="auth">
</h2> 
Please press config button on your device and enter above Authorisation Code to Validate your Device with Amazon DRS
<br />
</div>
<div id="myDiv" style="clear: both; text-align: center;">
<h1>
Register to Smart Pantry with Amazon DRS</h1>
<a href="https://cdn.instructables.com/FWA/9JHC/IX6FV7HW/FWA9JHCIX6FV7HW.LARGE.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://cdn.instructables.com/FWA/9JHC/IX6FV7HW/FWA9JHCIX6FV7HW.LARGE.jpg" width="500" /></a>
<form action="form_action.asp" id="frm1">
  <b>PRODUCT MODEL ID </b> <br /> <input maxlength="36" name="pname" size="38" style="text-align: center;" type="text" value="smart-pantry" /><br /><br />
  <b>SERIAL NO </b><br /> <input maxlength="12" name="sname" size="14" style="text-align: center;" type="text" value="abcd1234" /><br /><br />
  <input onclick="lwaFunction()" type="button" value="Login with Amazon" />
</form>
</div>
<br />
<br />

<script>
function defFunction() {
    var str = String(window.location);
    var pos = str.indexOf("code=");
    if(pos != -1)
    {
       myDiv.style.display = "none";
       var str = String(window.location);
       var res = str.substring(pos+5,pos+25);
       document.getElementById("auth").innerHTML = res;
    }
}
function lwaFunction() {
    var str = String(window.location);
    var pos = str.indexOf("code=");
    if(pos == -1)
    {
        var x1 = document.getElementById("frm1");
        var productid = String(x1.elements[0].value);
        var serialno = String(x1.elements[1].value);
        window.open("https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.d509830261df448d88558424c8b09714&scope=dash%3Areplenish&scope_data=%7B%22dash%3Areplenish%22%3A%7B%22device_model%22%3A%22"+productid+"%22%2C%22serial%22%3A%22"+serialno+"%22%2C%22is_test_device%22%3A%22true%22%7D%7D&response_type=code&redirect_uri=https://smart-pantry.000webhostapp.com/index.html");
    }
}
function fstFunction() {
    var str = String(window.location);
    var pos = str.indexOf("code=");
    if(pos == -1)
    {
        first.style.display = "none";
    }
}
defFunction();
fstFunction() 
</script>
</body>

</html>
Arduino SketchC/C++
/* FSR testing sketch. 
 
Connect one end of FSR to 5V, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground

 
*/
 
#ifdef ESP8266 
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#else
#include <WiFi101.h>
#endif

#include "AmazonDRS.h"

AmazonDRS DRS = AmazonDRS();

//WiFi creds ----------------------------------------------------------------------------------
char ssid[] = ""; //  your network SSID (name)
char pass[] = "";    // your network password (use for WPA, or use as key for WEP)
//------------------------------------------------------------------------------------------------------

#define slotNumber 3 //This will vary for multi slot devices - dash buttons typically only serve one product/slot

static String slotStatus = "true"; //boolean which depicts if slot is available for replenishment
static String slotId;
static String slotIdOnion = "0977cac3-39f5-4da5-8a8d-fe1cf692dea2";     //unique slot id ex: 0a5038b7-7609-4b81-b87e-3e291f386324
static String slotIdGarlic = "d36ffb44-a380-4cbf-8a5b-6747cb686fbd";     //unique slot id ex: 0a5038b7-7609-4b81-b87e-3e291f386324
static String slotIdPotato = "0e0d8d1f-1035-4784-9227-1b98a0988c6a";     //unique slot id ex: 0a5038b7-7609-4b81-b87e-3e291f386324

int status = WL_IDLE_STATUS;
 
int fsrAnalogOnion = A0; // FSR is connected to analog 0
int fsrAnalogPotato = A1; // FSR is connected to analog 1
int fsrAnalogGarlic = A2; // FSR is connected to analog 2, 

int fsrReading;      // the analog reading from the FSR resistor divider

void setup(void) {
  Serial.begin(9600);   // We'll send dat via the Serial port

  #ifdef ESP8266 
   WiFiClientSecure client;
   #else
   WiFiSSLClient client;
   #endif
   //Start up DRS
   DRS.begin(&client);

  //connect to WiFi
  Serial.println("Initializing DRS... connecting to WiFi");
  while (status != WL_CONNECTED) {
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    Serial.println(".");
    delay(3000);
    status = WiFi.status();
  }

  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());

  //initialize slots
  DRS.retrieveSubscriptionInfo();  //check slot statuses

  slotStatus = DRS.getSlotStatus(slotNumber);
  slotId = DRS.getSlotId(slotNumber);
}
 
void loop(void) {
 
  fsrReading = analogRead(fsrAnalogPotato);
  if(fsrReading<20)
   {
       //Check if slot is available, if so replenish

        if(slotStatus == "true")   //if the product in slot are available
        {
            //we have a match! replenish the products associated with that slot!
            DRS.requestReplenishmentForSlot(slotIdPotato);
        }
        else
        {
          Serial.print("Sorry, slot ");
          Serial.print(slotIdPotato);
          Serial.println(" is not available at this time");
        }

    }
  fsrReading = analogRead(fsrAnalogOnion);
  if(fsrReading<20)
   {
       //Check if slot is available, if so replenish

        if(slotStatus == "true")   //if the product in slot are available
        {
            //we have a match! replenish the products associated with that slot!
            DRS.requestReplenishmentForSlot(slotIdOnion);
        }
        else
        {
          Serial.print("Sorry, slot ");
          Serial.print(slotIdOnion);
          Serial.println(" is not available at this time");
        }

    }
  fsrReading = analogRead(fsrAnalogGarlic);
  if(fsrReading<20)
   {
       //Check if slot is available, if so replenish

        if(slotStatus == "true")   //if the product in slot are available
        {
            //we have a match! replenish the products associated with that slot!
            DRS.requestReplenishmentForSlot(slotIdGarlic);
        }
        else
        {
          Serial.print("Sorry, slot ");
          Serial.print(slotIdGarlic);
          Serial.println(" is not available at this time");
        }

    }
   
  delay(1000);
}
AmazonDRS.cppC/C++
https://github.com/andium/AmazonDRS
/*******************************************************************
 Check out the included Arduino sketches and the getting started
 guide here!
 https://github.com/andium/AmazonDRS

 This is an Arduino implementation of an Amazon Dash Replenishment
 device. It currently supports the critical API endpoints necessary
 for registering a device and submitting replenishment requests. This
 library is tightly coupled to the WiFi101 library, which means it will
 work great with the Arduino MKR1000, Adafruit Feather MO w/ the ATWINC1500,
 Arduino WiFi101 shiled or anywhere the WiFi library is supported. Json
 parsing is provided via ArduinoJson, thanks bblanchon!
 https://github.com/bblanchon/ArduinoJson

 Written by Brian Carbonette Copyright  2017 Andium

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Andres Sabas @ Electronic Cats added ESP8266 support @ 2017

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 *******************************************************************/

#include "AmazonDRS.h"



AmazonDRS::AmazonDRS()
{


}

#ifdef ESP8266 

void AmazonDRS::begin(Client * client)
{
  m_client=client;
}
#else
void AmazonDRS::begin(WiFiSSLClient * client)
{
 m_client=client;

}
#endif

void AmazonDRS::requestNewAccessTokens()
{
    char server[] = "api.amazon.com";    //api endpoint uri
    //assemble the body
    String refreshTokenBody = assembleRefreshTokenBody(refresh_token, client_id, client_secret, redirect_uri);
    //----------------------------------------------------------------
    //Request for new Access Token using Refresh Token
    //----------------------------------------------------------------

    if (m_client->connect(server, 443))
    {
      m_client->println("POST /auth/o2/token HTTP/1.1");
      m_client->println("Host: api.amazon.com");
      m_client->println("Cache-Control: no-cache");
      m_client->println("Content-Type: application/x-www-form-urlencoded");
      m_client->print("Content-Length: ");
      m_client->println(refreshTokenBody.length());
      m_client->println();
      m_client->println(refreshTokenBody);
      //----------------------------------------------------------------
      m_client->println("Connection: close");
      m_client->println();
    }

    delay(1000);
    processRefreshTokenResponse();

}

void AmazonDRS::requestReplenishmentForSlot(String slotId)
{
    Serial.print("Requesting Replenishment for slotId ");
    Serial.println(slotId);
    char server[] = "dash-replenishment-service-na.amazon.com";    //api endpoint uri
    // Assemble POST request:
    //----------------------------------------------------------------
    //Request replenishment for supplied slotId
    //----------------------------------------------------------------
    if (m_client->connect(server, 443))
    {
      m_client->print("POST /replenish/");
      m_client->print(slotId);
      m_client->println(" HTTP/1.1");
      m_client->println("Host: dash-replenishment-service-na.amazon.com");
      m_client->print("Authorization: Bearer ");
      m_client->println(access_token);
      m_client->println("x-amzn-accept-type: com.amazon.dash.replenishment.DrsReplenishResult@1.0");
      m_client->println("x-amzn-type-version: com.amazon.dash.replenishment.DrsReplenishInput@1.0");
      m_client->println("Cache-Control: no-cache");
      //----------------------------------------------------------------
      m_client->println("Connection: close");
      m_client->println();
    }
    delay(1000);

     while (m_client->available()) {
    char c = m_client->read();
    Serial.write(c);
    }

    m_client->stop();

}

void AmazonDRS::retrieveSubscriptionInfo()
{
    requestNewAccessTokens();

    #ifdef DEBUG_DASH
    Serial.println("Updating subscription info for all slots!");
    #endif

    char server[] = "dash-replenishment-service-na.amazon.com";    //api endpoint uri
    // Assemble GET request:
    //----------------------------------------------------------------
    //Request to gather subscription info {"slot_id":true/false}
    //----------------------------------------------------------------
    if (m_client->connect(server, 443))
    {
      m_client->println("GET /subscriptionInfo HTTP/1.1");
      m_client->println("Host: dash-replenishment-service-na.amazon.com");
      m_client->print("Authorization: Bearer ");
      m_client->println(access_token);
      m_client->println("x-amzn-accept-type: com.amazon.dash.replenishment.DrsSubscriptionInfoResult@1.0");
      m_client->println("x-amzn-type-version: com.amazon.dash.replenishment.DrsSubscriptionInfoInput@1.0");
      m_client->println("Cache-Control: no-cache");
      //----------------------------------------------------------------
      m_client->println("Connection: close");
      m_client->println();
    }
    delay(1000);
    processSubscriptionInfoResponse();


}

void AmazonDRS::requestBearerAndRefreshTokens()
{
    char server[] = "api.amazon.com";    //api endpoint uri
    //assemble the body
    String authCodeBody = assembleAuthCodeBody(authorization_grant_code, client_id, client_secret, redirect_uri);
    // Assemble POST request:
    //----------------------------------------------------------------
    //Request for Bearer and Refresh Tokens
    //----------------------------------------------------------------
    if (m_client->connect(server, 443))
    {
      m_client->println("POST /auth/o2/token HTTP/1.1");
      m_client->println("Host: api.amazon.com");
      m_client->println("Cache-Control: no-cache");
      m_client->println("Content-Type: application/x-www-form-urlencoded");
      m_client->print("Content-Length: ");
      m_client->println(authCodeBody.length());
      m_client->println();
      m_client->println(authCodeBody);
      //----------------------------------------------------------------
      m_client->println("Connection: close");
      m_client->println();
    }

    while (m_client->available())
     {
      char c = m_client->read();

     // #ifdef DEBUG_DASH
      Serial.write(c);
     // #endif

        if(c == '{')
        {
          _jsonBody = true;
        }

        if(_jsonBody)
        {
          _responseBody += c;
        }
     }

    delay(1000);
    processRefreshTokenResponse();

}


String AmazonDRS::assembleRefreshTokenBody(String refreshToken, String clientId, String clientSecret, String redirectUri)
{
   String tempTokenBody = "";

   tempTokenBody += "grant_type=refresh_token";
   tempTokenBody += "&";
   tempTokenBody += "refresh_token=";
   tempTokenBody += refreshToken;
   tempTokenBody += "&";
   tempTokenBody += "client_id=";
   tempTokenBody += clientId;
   tempTokenBody += "&";
   tempTokenBody += "client_secret=";
   tempTokenBody += clientSecret;
   tempTokenBody += "&";
   tempTokenBody += "redirect_uri=";
   tempTokenBody += redirectUri;

   return tempTokenBody;
}

String AmazonDRS::assembleAuthCodeBody(String authCode, String clientId, String clientSecret, String redirectUri)
{
  String tempTokenBody = "";

   tempTokenBody += "grant_type=authorization_code";
   tempTokenBody += "&";
   tempTokenBody += "code=";
   tempTokenBody += authCode;
   tempTokenBody += "&";
   tempTokenBody += "client_id=";
   tempTokenBody += clientId;
   tempTokenBody += "&";
   tempTokenBody += "client_secret=";
   tempTokenBody += clientSecret;
   tempTokenBody += "&";
   tempTokenBody += "redirect_uri=";
   tempTokenBody += redirectUri;

   return tempTokenBody;
}

void AmazonDRS::processSubscriptionInfoResponse()
{
  while (m_client->available())
     {
      char c = m_client->read();

      #ifdef DEBUG_DASH
      Serial.write(c);
      #endif

        if(c == '{') //catch the beginning of the json
        {
          _jsonBody = true;
        }

        if(_jsonBody)
        {
          _responseBody += c;
        }
     }

     delay(1000);
      StaticJsonBuffer<1000> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(_responseBody);
       if (!root.success())
       {
        Serial.println("parse subscriptionStatus failed");
        return;
       }
       String temp = root["slotsSubscriptionStatus"];
       slotsSubscriptionStatus = temp;
       //Serial.println(slotsSubscriptionStatus);
       //clear response body for next process
       _responseBody = "";
       _jsonBody = false;

       parseSlotIds(slotsSubscriptionStatus);
       m_client->stop();

}

void AmazonDRS::parseSlotIds(String subscriptionStatus)
{
    StaticJsonBuffer<1000> jsonBuffer;
    JsonObject&  root = jsonBuffer.parseObject(subscriptionStatus);

    if (!root.success())
    {
      Serial.println("parseObject() failed");
      return;
    }

  int j=1; //So slot# correlates with App slot#'s
  //iterate through all slots and store their status
  for(JsonObject::iterator it=root.begin(); it!=root.end(); ++it)
  {
    slotId[j] = it->key;
    slotStatus[j] = it->value.asString();
    j++; //number of slots

  }

  numSlots = j-1;

  Serial.print(numSlots);
  Serial.println(" Slot(s) statuses have been updated!");
}

void AmazonDRS::processRefreshTokenResponse()
{
     while (m_client->available())
     {
      char c = m_client->read();

     // #ifdef DEBUG_DASH
      Serial.write(c);
     // #endif

        if(c == '{')
        {
          _jsonBody = true;
        }

        if(_jsonBody)
        {
          _responseBody += c;
        }
     }


      //Parse the json resposne constaining access and refresh tokens
      StaticJsonBuffer<1100> jsonBuffer;
      JsonObject& root = jsonBuffer.parseObject(_responseBody);
       if (!root.success())
       {
        Serial.println("refresh token response parse failed");
        return;
       }
       String newAccessToken = root["access_token"];
       String newRefreshToken = root["refresh_token"]; //refresh token does not change unless LWA is deauthorized
       access_token = newAccessToken;
       refresh_token = newRefreshToken;
       //clear response body for next process
       _responseBody = "";
       _jsonBody = false;

       #ifdef DEBUG_DASH
       Serial.println(access_token);
       Serial.println(refresh_token);
       Serial.println("Tokens updated!");
       #endif

       m_client->stop();
}

void AmazonDRS::setAuthCode(String authCode)
{
  authorization_grant_code = authCode;
}

String AmazonDRS::getRefreshToken()
{
  return refresh_token;
}

//Slot getters so Arduino app can make decisions based on slot availability
String AmazonDRS::getSlotStatus(int slotNumber)
{
  return slotStatus[slotNumber];
}

String AmazonDRS::getSlotId(int slotNumber)
{
  return slotId[slotNumber];
}
AmazonDRS.hC/C++
/*******************************************************************
 Check out the included Arduino sketches and the getting started
 guide here!
 https://github.com/andium/AmazonDRS

 This is an Arduino implementation of an Amazon Dash Replenishment
 device. It currently supports the critical API endpoints necessary
 for registering a device and submitting replenishment requests. This
 library is tightly coupled to the WiFi101 library, which means it will
 work great with the Arduino MKR1000, Adafruit Feather MO w/ the ATWINC1500,
 Arduino WiFi101 shiled or anywhere the WiFi library is supported. Json
 parsing is provided via ArduinoJson, thanks bblanchon!
 https://github.com/bblanchon/ArduinoJson

 Written by Brian Carbonette Copyright  2017 Andium

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Andres Sabas @ Electronic Cats added ESP8266 support @ 2017

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 *******************************************************************/

#ifndef __AmazonDRS_H
#define __AmazonDRS_H

#ifdef ESP8266 
#include <Client.h>
#else
#include <WiFi101.h>
#endif 

#include "Arduino.h"
#include <ArduinoJson.h>
#include "AmazonTokens.h"

#define DEBUG_DASH 

class AmazonDRS
{ 

	public:

		#ifdef ESP8266 
		Client * m_client;
		void begin(Client * client);
		#else
	        WiFiSSLClient * m_client;
	    	void begin(WiFiSSLClient * client);
		#endif 

		//Slot Subscription Status
		String slotsSubscriptionStatus = "";

		//Slot Id Array and Statuses---
	  	String slotId[10] = {};
		String slotStatus[10] = {};
	  	int numSlots = 0;

		AmazonDRS();

   		void requestNewAccessTokens();
		void requestReplenishmentForSlot(String slotId);
		void requestBearerAndRefreshTokens();

		void retrieveSubscriptionInfo();

		String getRefreshToken();
		String getSlotStatus(int slotNumber);
	  	String getSlotId(int slotNumber);

	  	void setAuthCode(String authCode);


	private:
		//json parsing vars---------
		String _responseBody = "";
		bool _jsonBody = false;
		//----------------------------
		String assembleRefreshTokenBody(String refreshToken, String clientId, String clientSecret, String redirectUri);
		String assembleAuthCodeBody(String authCode, String clientId, String clientSecret, String redirectUri);
		void parseSlotIds(String subscriptionStatus);
	  	void processSubscriptionInfoResponse();
		void processRefreshTokenResponse();


};






#endif /*__AmazonDRS_H */
AmazonTokensC/C++
/*******************************************************************
 Check out the included Arduino sketches and the getting started 
 guide here! 
 https://github.com/andium/AmazonDRS
 
 This is an Arduino implementation of an Amazon Dash Replenishment
 device. It currently supports the critical API endpoints necessary
 for registering a device and submitting replenishment requests. This 
 library is tightly coupled to the WiFi101 library, which means it will 
 work great with the Arduino MKR1000, Adafruit Feather MO w/ the ATWINC1500, 
 Arduino WiFi101 shiled or anywhere the WiFi101 library is supported. Json 
 parsing is provided via ArduinoJson, thanks bblanchon!
 https://github.com/bblanchon/ArduinoJson
 
 Written by Brian Carbonette Copyright  2016 Andium

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 *******************************************************************/

#ifndef __AmazonTokens_H
#define __AmazonTokens_H


//API Definitions---------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------

//OAuth2 Creds------------------------------------------------------------------------------------------
//These can be found in your DRS app's LWA details screen https://developer.amazon.com/lwa/sp/overview.html
//------------------------------------------------------------------------------------------------------

#define client_id "amzn1.application-oa2-client.02d6a3b6f7ad45589b344e71ab040cff"

#define client_secret "c0daf124d15f7717de644109b7ef77769c68ed0155cf33156b926cd8c8b78541"

//------------------------------------------------------------------------------------------------------

//Redirect URI------------------------------------------------------------------------------------------

#define redirect_uri "https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback" //must be URI encoded and https
                     //^^you could use this one from Postman if you'd like if you have an app or site replace 
					 //this wth your sites uri encoded callback
//------------------------------------------------------------------------------------------------------

//Refresh Token-----------------------------------------------------------------------------------------
//Used for all subsequent calls to requestNewAccessTokens() new access_token is valid for 1hr
//Refresh tokens are always valid and won't change as long as you keep your app authroized under your Amazon account
//Log in and go to 'Your Account >> Manage Login With Amazon' to see where to deauthorize and invalidate this token

static String refresh_token = "Atzr|IwEBIIKDkzgMa5g7O0R1mLZZ6YZo-Z1Ae5Ffj6wmV_rPbmAI0oixxTff8g3PN6MrOIEQpB9o_6BlDjiR6gkfRS_82Wp_0GWWvTrtYehcFJ8iKjuqf8n1ff9OrdHQU1_5nW_5Hf5loeIQ88TGazK2wy18UmOXOz1lbl9FDvWVQZl4t_6ggzDfMTVupvNr_ZtDrPm72auzoJIkGmGIM4S1RUw-Ru8X4q-UlzzYYfvRSJnPLAUTM3tTOEkv5e33SzExAaHl0tF22drRqvR1dEVlR_Zzw_IZ-1hzhIAvHrJs22K5dSEmkJKN7g8sD1tUKkn-ErMJhJrMehmvjwanF_O141Z5bVokmOLwiQKq_AYKGz8mJ0WPjBNQ3TbZ1g-3Xp-LqeMcKViNImcl1-_K89K5rupwAh-OmIPP5VhBArvhdeqEnreNU7LVLNoHvvyFB5ypwKQsHLe8";


//------------------------------------------------------------------------------------------------------

//Authorization Code------------------------------------------------------------------------------------
//Upon Authorizing DRS via LWA this is passed to requestBearerAndRefreshTokens() to grab first pair of tokens
//copy the string following code= from the LWA response ex:https://localhost/?code=ANdNAVhyhqirUelHGEHA&scope=dash:replenish

static String authorization_grant_code = "ANEcEEKnDNSZsbKveGOR";

//------------------------------------------------------------------------------------------------------

//Access Token------------------------------------------------------------------------------------------
//must be passed in all API calls in order to authenticate, requestNewAccessTokens() prior to making an api call
//to automaticall udpate this
static String access_token = "";

//------------------------------------------------------------------------------------------------------


#endif /*__AmazonTokens_H */

Schematics

Schematic
Schematic bb igz1fscaor

Comments

Similar projects you might like

Home Smart Home

Project tutorial by Syed Sanoor

  • 68,541 views
  • 10 comments
  • 193 respects

Smart Parking System

Project in progress by Md. Khairul Alam

  • 43,049 views
  • 32 comments
  • 104 respects

Amazon Kitchen DRS

Project in progress by Tanner Stinson

  • 4,028 views
  • 4 comments
  • 20 respects

Smart Wardrobe

Project in progress by Tan See Youu

  • 18,852 views
  • 8 comments
  • 46 respects

Home Monitoring System and Smart Home Solution

Project showcase by Akash Kumar

  • 5,471 views
  • 0 comments
  • 21 respects

Smart 3D Printer Filament Counter (FilamentBot)

Project tutorial by ArtSuzhou

  • 8,682 views
  • 3 comments
  • 24 respects
Add projectSign up / Login