Sainath Komakula
Published © GPL3+

Smart Vendy - Power By MediaTek Smart 7688 Duo

Tracking vendor sales so that effectively manage what inventory needs to buy before it gets out of stock & getting snacks using RFID.

AdvancedFull instructions providedOver 3 days1,342
Smart Vendy - Power By MediaTek Smart 7688 Duo

Things used in this project

Hardware components

Jumper wires (generic)
Jumper wires (generic)
×1
Breadboard (generic)
Breadboard (generic)
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1
RFID reader (generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE
Atom

Story

Read more

Code

Main node JS

JavaScript
var express = require('express');
var app = express();
var http = require('http').Server(app);
var path    = require("path");
var io = require('socket.io')(http);
var io_https = require('socket.io')(https);

var https = require('https');
var fs = require('fs');


var debug = require('debug')('rest-server:server');
var request = require('request');
var port = 3000;
var Secport = 3443;
var request = require('request');
var Authorization_code;
var access_token_DRS;
var refresh_token_DRS;
var slotID = 'bf3f0b71-7851-4b8c-9c6c-7364118d130f';
var serialPort = require('serialport');
var SerialPort = serialPort.SerialPort;
var Last_purchase_time;
var remainingQuantity_KitKat;
var remainingQuantity_Oreo;
var originalQuantity;
var KitKat;
var Oreo;

var Slot_status_import = require('./slot_status.js');
var DRS_call_import = require('./DRS_call.js');
var Subscription_import = require('./Suscribe_info.js');
var DeviceStatus_import = require('./Device_status.js');
var Deregister_import = require('./Deregistration.js');

//Configuring Serial port with MCU
var portName = '/dev/ttyS0';
serialPort = new SerialPort(portName, {
    baudrate: 57600,
    // def  aults for Arduino serial communication
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
});
app.use(express.static(__dirname + '/public'));
app.use(express.static(path.join(__dirname, '/public')))

//loading initial page
app.get('/', function(req, res) {
    res.sendfile('LWA.html');
});

//Webpage for Refilling stock
app.get('/contents_new', function(req, res) {
    res.sendFile(path.join(__dirname + '/contents_new.html'));
});

//Webpage to topup RFID
app.get('/Topup_RFID', function(req, res) {
    res.sendFile(path.join(__dirname + '/Topup_RFID.html'));
});


//Handling Socket io connection of http
io.on('connection', function(socket) {

    console.log('new client connected');

    //Socket event for input count of quantity at the time of refillment if user enter before login
    socket.on('KitKatQuantityEvent', function(data){
 console.log("Number of KitKat quantity"+ data);
 KitKat=data;
 remainingQuantity_KitKat=KitKat;
 serialPort.write(data+'&'); // & used to differentiate KitKat  and Oreo va;ue on MCU via serial communicarion
 //      serialPort.write("&");

        });

//
 socket.on('OreoQuatityEvent', function(data){
              console.log("Number of Oreo quantity"+ data);
Oreo=data;
remainingQuantity_Oreo=Oreo;
 serialPort.write(data);

            });
            socket.on('TopupEvent', function(data){
       console.log("Amount Topuped  ="+ data);
         serialPort.write(data);
                });
    /*    socket.on('OreoQuatityEvent', function(data){
              console.log("Number of Oreo quantity ="+ data);
       serialPort.write(data);
     });*/



});

//Initializing http server
http.listen(port, function() {
    console.log('listening on *:3000');
});


//Options for creating HTTPS server and reading file of PRIVATE  KEY and CERTIFICATE
var options = {

    key: fs.readFileSync(__dirname + '/25827299-localhost_3000.key'),
    cert: fs.readFileSync(__dirname + '/25827299-localhost_3000.cert')
};


//creating secure server
var secureServer = https.createServer(options, app)

//Initializing secure Socket IO events
var io_sec = require('socket.io')(secureServer);
//Initializing secure server
secureServer.listen(Secport, function() {
    console.log('Server listening on port ', Secport);

});

//Handling  secure Socket IO events
io_sec.on('connection', function(socket) {
    console.log('new secure client connected');

    //Socket event for input count of quantity at the time of refillment
    socket.on('KitKatQuantityEvent', function(data) {
        console.log('\n');
        console.log('\n');
        console.log("Number of KitKat quantity =" + data);

        console.log('\n');
        remainingQuantity = data;
        originalQuantity= data;
        serialPort.write(data);
    });

    //Authorization code socket event generted from HTML page
    socket.on('Auth_code', function(data) {
        console.log(data);
        Authorization_code = data;

        // calling access token function to get access_token

        access_token_function();
    });


    //Subscription_event
    socket.on('Subscription_event', function(data) {
        console.log(data);

        //Subscr_function call in Suscribe_info module
        Subscription_import.Subscr_function(access_token_DRS); //


    });

    //Socket of event DeviceStatus_event
    socket.on('DeviceStatus_event', function(data) {
        console.log(data);

        //deviceStatus_function call in Device_status.js module
        DeviceStatus_import.deviceStatus_function(access_token_DRS);


    });

    //Socket of event SlotStatus_event
    socket.on('SlotStatus_event', function(data) {
        console.log(data);

        //Slot_Status_function call in SlotStatus.js with Last purchase time parameter
        Slot_status_import.Slot_Status_function(access_token_DRS, Last_purchase_time ,remainingQuantity,originalQuantity);


    });
    socket.on('Deregister_device_event', function(data) {
        console.log(data);

        //Slot_Status_function call in SlotStatus.js
        Deregister_import.deregistration_function(access_token_DRS);


    });


});

//Access Token function
function access_token_function() {
    console.log("Calling Access Token Function");
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    // Configure the request
    var options = {
        url: 'https://api.amazon.com/auth/o2/token',
        port: 443,
        method: 'POST',
        headers: headers,
        form: {
            'grant_type': 'authorization_code',
            'code': Authorization_code,
            'client_id': 'amzn1.application-oa2-client.ad6e919aadf242b88ee0951a7e5a9399',
            'client_secret': '4030d7b62041b4a0cb887c5d9d013f11824dea8a3e241cb43e869c1e0bfea7bd',
            'redirect_uri': 'https://192.168.1.133:3443'
        }
    }

    // Start the request
    request(options, function(error, response, body) {
        console.log('statusCode:', response.statusCode);
        console.log('headers:', response.headers);
        if (!error && response.statusCode == 200) {
            // Print out the response body
            console.log(body);

            var Extract_access_token = JSON.parse(body);
            access_token_DRS = Extract_access_token.access_token;
            refresh_token_DRS = Extract_access_token.refresh_token;
            console.log('\n');
            console.log("Access token = " + access_token_DRS);
            console.log('\n');
            console.log("Refresh token = " + refresh_token_DRS);
            //    time_check_access_token_1 = new Date();

        }
    })


}


// Refresh Token fuction  Before placing order
function refresh_token_function() {
    var headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    // Configure the request
    var options = {
        url: 'https://api.amazon.com/auth/o2/token',
        port: 443,
        method: 'POST',
        headers: headers,
        form: {
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token_DRS,
            'client_id': 'amzn1.application-oa2-client.ad6e919aadf242b88ee0951a7e5a9399',
            'client_secret': '4030d7b62041b4a0cb887c5d9d013f11824dea8a3e241cb43e869c1e0bfea7bd',
            'redirect_uri': 'https://192.168.1.133:3443'
        }
    }

    // Start the request
    request(options, function(error, response, body) {
        console.log('statusCode:', response.statusCode);
        console.log('headers:', response.headers);
        if (!error && response.statusCode == 200) {
            // Print out the response body
            console.log(body);
            var Extract_access_token = JSON.parse(body);

            //assgning acess token value to  variable

            access_token_DRS = Extract_access_token.access_token;
            refresh_token_DRS = Extract_access_token.refresh_token;
            console.log('\n');
            console.log("Access token = " + access_token_DRS);
            console.log('\n');
            console.log("Refresh token = " + refresh_token_DRS);
        }
    })


    //calling DRS function to place order

}




//listening Serial Port from MCU ATMega32U4
serialPort.on('data', function(data) {
console.log('Hi');
Last_purchase_time = new Date();
if(data=="KitKat")
{
  var slot_number_1=1;
  var slot_number_2=2;
  remainingQuantity_KitKat = remainingQuantity_KitKat - 1;// deccrementiong by value 1 every time when it consumed
  console.log("Remaining Quantity of KitKat =" + remainingQuantity_KitKat)
}
else if((data=="Oreo"))
remainingQuantity_Oreo = remainingQuantity_Oreo - 1;
console.log("Remaining Quantity of Oreo =" + remainingQuantity_Oreo);
 // Decrease quantity by 1
// checking threshold level of KitKat , so that it  can order before it get out of stock
if (remainingQuantity_KitKat == "2") {
    console.log('\n');
    console.log("KitKat  are running out of stock");
    console.log('\n');
    console.log("Ordering using Amazon DRS")
    console.log('\n');

    //Calling refresh_token_function before placing order to avoid issue with access_token expire
    refresh_token_function();
    setTimeout(DRS_call_import.DRS_call_function(access_token_DRS,slot_number_1),3000);//Delay used to complete refresh_token_function action so that we get access token before reflenish order

}
// checking threshold level of Oreo , so that it  can order before it get out of stock

else if (remainingQuantity_Oreo=="2") {
  console.log('\n');
  console.log("KitKat  are running out of stock");
  console.log('\n');
  console.log("Ordering using Amazon DRS")
  console.log('\n');

  //Calling refresh_token_function before placing order to avoid issue with access_token expire
  refresh_token_function();
    setTimeout(DRS_call_import.DRS_call_function(access_token_DRS,slot_number_1),3000); //Delay used to complete refresh_token_function action so that we get access token before reflenish order

    }



});

HTML page

JavaScript
this page includes Login with Amazon along some additional pages for to Recharge/topup RFID card used to transact to get snacks & Re-fillement page to refill stock of snacls
<!DOCTYPE html>
<html>
<head>
<style>
form {
    border: 3px solid #f1f1f1;
}


.wrapper {
    text-align: center;
}

.cancelbtn {
    width: auto;
    padding: 10px 18px;
    background-color: #f44336;
}

.imgcontainer {
    text-align: center;
    margin: 24px 0 12px 0;
}

img.avatar {
    width: 25%;
    border-radius: 15%;
}
img.avatar_2 {
    width: 30%;
    height:5%;
}
.container {
    padding: 16px;
}

span.psw {
    float: right;
    padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
    span.psw {
       display: block;
       float: none;
    }
    .cancelbtn {
       width: 100%;
    }
}
</style>

<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Include jQuery Mobile stylesheets -->
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<!-- Include the jQuery library -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

<!-- Include the jQuery Mobile library -->
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

<script src="socket.io/socket.io.js"></script>
<title> Testing LWA</title>

<body>

  <div data-role="page" id="pageone">
  <div data-role="header" data-theme="b">
  <h1>Registraton page for Smart Vendy</h1>
<div  class="container_3">
<form action="/action_page.php">
  <div class="imgcontainer">
    <img src="Login with Amazon logo.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
  <!--  <input  onclick="LoginWithAmazon()" type="image" src="LWA logo.jpg" value="Login with Amazon" id="LoginWithAmazonID" alt="Submit" width="100"> -->
  <button onclick="LoginWithAmazon()" type="button"  value="Login with Amazon" id="LoginWithAmazonID" >Login With Amazon</button>
  <!--   <input type="checkbox" checked="checked"> Remember me  -->

  </div>

  <div class="container" style="background-color:#f1f1f1">
    <button type="button" class="cancelbtn">Cancel</button>
    <span class="psw">Forgot <a href="#">password?</a></span>
  </div>
</div>
</form>

  <div class="container_2" style="background-color:#f1f1f1">
<div style="text-align:center">
        <!-- panel content goes here -->
        <input onclick="Slot_status()" type="button" value="Check Slot status" id="SlotStatus"/><br>
        <input onclick="Subscription()" type="button" value="Check Subscription status" id="Subscription"/><br>
      <input onclick="DeviceStatus()" type="button" value="Check Device status" id="Device"/><br>
      <input onclick="Deregister()" type="button" value="Deregister Device" id="Deregister_Device"/><br>

      <input onclick="refillment()" type="button" value="Refill snacks" id="Refill snacks"/><br>
      <input onclick="Topup_wallet()" type="button" value="Topup wallet " id="Topup wallet"/><br>
</div>


</div>



  <script>
  var socket = io();

  //var socket_sec = io(URL_SERVER);
  function LoginWithAmazon() {
    window.open("https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.ad6e919aadf242b88ee0951a7e5a9399&scope=dash%3Areplenish&scope_data=%7B%22dash%3Areplenish%22%3A%7B%22device_model%22%3A%22Smart_Vendy%22%2C%22serial%22%3A%22arduino123456789%22%2C%22is_test_device%22%3Atrue%7D%7D&response_type=code&redirect_uri=https%3A%2F%2F192.168.1.133%3A3443");
  }

    function Auth() {

      var str = String(window.location);
    var check= str.indexOf("code=");
      if(check != -1)
      {


   var str = String(window.location);
   var res_auth = str.substring(check+5,check+25);

socket.emit('Auth_code', res_auth);

  document.getElementsByClassName("container_3")[0].style.display = 'none';
container_3.style.display = "none";

        }

  } function Sample() {
    var str = String(window.location);
  var check_2= str.indexOf("code=");
    if(check_2 == -1)
    {
    document.getElementsByClassName('container_2')[0].style.display = 'none';

    }
  }
  function Slot_status() {
    socket.emit("SlotStatus_event","Checking  Slot status");
  }
  function Subscription() {
      socket.emit('Subscription_event','Checking Subscription Status');
//window.open("https://192.168.1.133:3443/contents_new");
  }
  function DeviceStatus() {
    socket.emit('DeviceStatus_event', 'Checking  Device Status');
  }
  function Deregister(){
    socket.emit('Deregister_device_event', ' Deregistering  the Device ');
  }
function  refillment(){
  window.open("http://192.168.1.133:3000/contents_new"); // refillment page to entry quantity of stcok i.w KitKat or Oreo
}
function Topup_wallet(){
  window.open("http://192.168.1.133:3000/Topup_RFID");// Topup window where RFID can be Topup

}
  Auth(); // calling Auth fucntion to get Authorizationc code
  Sample(); // This fucntion is used to just hide other buttons like refillmentpage and Topup
    </script>
</body>
</html>

Arduino code

JavaScript
Stepper Motor ,Keypad & RFID interfacing with MCU part of 7688 duo
 /*

 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 
 The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
*/

#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <EEPROM.h>
#include <Keypad.h>

 
int INA1 =2;
int INA2 =3;
int INA3 =18;
int INA4 =19;

int INB1 =20;
int INB2  =21;
int INB3 =22;
int INB4 =23;

#define SS_PIN 9
#define RST_PIN 8
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //  Create LCD  instance.
String Array="40 50 62 7E"; // Authorized user
int Steps = 0; //Initializing Step count
int KitKat; // Quantity of Kitkat
int Oreo;// Quantity of Oreo
int add=0; // address used to storeBalace amount of user
boolean Direction = true;// 
unsigned long last_time; // Timing variable to allow stepper for rotation
unsigned long currentMillis ; //Timing variable to allow stepper for rotation

int steps_left;// variable to store number of steps to move stepper 
long time;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {   
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};  // initializing of Keypad 
byte rowPins[ROWS] = {10, 11, 12, 13}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 6, 7}; //connect to the column pinouts of the keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

//unsigned long loopCount = 0; 
//unsigned long timer_t = 0;
//int count_check=1;
byte nuidPICC[4]; // Storing byte of RFID card
int user_address=0;//address used to storeBalace amount of user

int slot_one_price=10; // Price of content in slot 1
int slot_two_price=15;// Price of content in slot 2
//int amount=0;
int Total_amount; // variable used to represent  Amoout of user 

// fuction  to set direction of stepper motor shaft movement( clockwise or anticlockwise)
void SetDirection(){
  if(Direction==1){ Steps++;} // clockwise
  if(Direction==0){ Steps--; }// anticlockwise
  if(Steps>7){Steps=0;} 
  if(Steps<0){Steps=7; }
}

void stepper(int xw,int IN1,int IN2,int IN3,int IN4){
  for (int x=0;x<xw;x++){
    SetDirection();
    switch(Steps){
       case 0:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, HIGH);
       break; 
       case 1:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, HIGH);
         digitalWrite(IN4, HIGH);
       break; 
       case 2:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, HIGH);
         digitalWrite(IN4, LOW);
       break; 
       case 3:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, HIGH);
         digitalWrite(IN3, HIGH);
         digitalWrite(IN4, LOW);
       break; 
       case 4:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, HIGH);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, LOW);
       break; 
       case 5:
         digitalWrite(IN1, HIGH); 
         digitalWrite(IN2, HIGH);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, LOW);
       break; 
         case 6:
         digitalWrite(IN1, HIGH); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, LOW);
       break; 
       case 7:
         digitalWrite(IN1, HIGH); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, HIGH);
       break; 
       default:
         digitalWrite(IN1, LOW); 
         digitalWrite(IN2, LOW);
         digitalWrite(IN3, LOW);
         digitalWrite(IN4, LOW);       break; 

    }
  }  
} 
void customStepRev(int movestep, int slot_check){
   steps_left=(-1)*movestep;
   Direction==-1;
   while(steps_left<0){
      currentMillis = micros();
      if(currentMillis-last_time>=1000){
      
      if(slot_check==1)
      stepper(1, INA1, INA2, INA3,INA4); 
      else
        stepper(1, INB1, INB2, INB3,INB4); 
      time=time+micros()-last_time;
      last_time=micros();
      steps_left++;
      }
    }
   //Serial.println(time);
   delay(2000);
} 

void setup() 
{
  pinMode(INA1, OUTPUT); 
  pinMode(INA2, OUTPUT); 
  pinMode(INA3, OUTPUT); 
  pinMode(INA4, OUTPUT); 
 pinMode(INB1, OUTPUT); 
  pinMode(INB2, OUTPUT); 
  pinMode(INB3, OUTPUT); 
  pinMode(INB4, OUTPUT); 
  

   kpd.setDebounceTime(10);  // setDebounceTime(mS)
   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  lcd.begin(16, 2);//Initiate LCD 16 X 2 
  lcd.print("Scan RFID Card");
  Serial1.begin(57600);// Baud rate used for Serial communication between MPU and MCU 
  Serial.begin(9600);// Baud rate used for Serial communication with PC to Arduino
 


delay(5000);
Serial.println("Pease Scan your RFID");
 

}
void loop() 
{
 
  User_check(user_address);
char key = kpd.getKey(); // capturing key character from Keypad 
if (key=='*')
{
   Serial.println(key);
   
  //Balance_check(user_address);
   Topup(user_address); // Calling Topup function to recharge ot Topup RFID 
  
}
if (key=='#')
{
  Serial.println(key);
  Get_Snacks(user_address);// Calling Get_Snacks function to get snacks from selected slots
 
  
}
if(Serial1.available())
{
  Refill_slots();// Calling Refill_slots function to refill quantity from web UI 
}

  }
  void Refill_slots()
{
  
   String buffer=Serial1.readString(); // reading Quantity of Kitkat & Lays from MPU via serial communication 
 int sub_buffer=buffer.indexOf('&');// Identifying '&' to differentiate quantity of KitiKat  read serially 
  KitKat =buffer.substring(0,sub_buffer).toInt(); //Extracting value  before '&' i.e Quantity of KitKat
  //KitKat = Serial1.readString().toInt();
  Oreo =buffer.substring(sub_buffer+1).toInt();//Extracting value  after  '&' i.e Quantity of Oreo
 Serial.print("Number of KitKat =");
 Serial.println(KitKat);
 /*/ delay(2000);
  Serial1.flush();
  Oreo = Serial1.readString().toInt();
  Serial1.flush();*/
  Serial.print("Number of Oreo =");
 Serial.println(Oreo);
}

  void User_check(int addr)
  {
  // int amount_read = EEPROM.read(addr);
    String content= ""; // Empty string initialization which is used to concat 
  byte letter;
    if ( ! mfrc522.PICC_IsNewCardPresent()) 
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) 
  {
    return;
  }
        for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = mfrc522.uid.uidByte[i];
    }
    
   for (byte i = 0; i < mfrc522.uid.size; i++) {
    content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
  
  }
  content.toUpperCase();
  content.substring(1);
  Serial.println(content.substring(1));
if(Array==content.substring(1))
{
  Serial.println("Authorized Person");

//Serial.println("Your Balamce Amount is ");
  //Serial.println(amount_read);
  Balance(addr);
   mfrc522.PICC_HaltA();
       mfrc522.PCD_StopCrypto1();
      
 Serial.println("Enter  to * to Top up your RFID");
 Serial.println("Enter  to # to get snacks");
 }
 else
 {
 Serial.println("Un-Authorized Person"); 
 setup();
  }
  }
 void Topup(int addr)
 {
  int amount_check=1;
  
  Serial.println("Enter the amount to Topup or press '#' to exit");
 
  while(amount_check==1){
     if(Serial1.available())
     {Total_amount =Serial1.readString().toInt();
  
 amount_check=0;
 }
 else if (kpd.getKey()=='#')
 {
  amount_check=0;
 }
   
  }
  
  Serial.println("Total amount is ");
  Serial.print(Total_amount);
  EEPROM.write(addr, Total_amount);
  
 }
 void Get_Snacks(int addr)
 {
  
  int snacks_check=1;
 //  int temp_amount=EEPROM.read(addr);

  Serial.println("Enter 1 to get KitKat");
  Serial.println("Enter 2 to get oreo");

  while(snacks_check==1)
 { 
 
    char slot_number = kpd.getKey();
    switch (slot_number) {
    case '1':
     Serial.println(slot_number);
   
    Total_amount=Total_amount-slot_one_price;
     Serial1.write("KitKat"); // Serial write to MediaTek_DRS.js to decrement value by 1
    
    customStepRev(4096,1);//Passing parameter is complete one revolution of stepper motor
    snacks_check=0;
    if(Total_amount>0)
    {
    EEPROM.write(addr,Total_amount);
    Balance(addr);}
    else
    Serial.println("You have insuffiecient Balance");
      //do something when var equals 1
      break;
    case '2':
    Serial.println(slot_number);
     Serial1.print("Oreo");
     customStepRev(4096,2);
   Total_amount=Total_amount-slot_two_price;
   
     snacks_check=0;
        if(Total_amount>0)
    {
    EEPROM.write(addr,Total_amount);
    Balance(addr);}
    else
 {    Serial.print("Amount is ");
     Serial.println(Total_amount);
    Serial.println("You have insuffiecient Balance");
 }
    break;
      
 
    }
    
  
 }
 }
 void Balance(int addr)
 {
  
   int Total_amount = EEPROM.read(addr);
   Serial.println("Your Balamce Amount is ");
  Serial.println(Total_amount);
  
 }

  

Slot status API

JavaScript
This API of Amazon Dash replenishment to check whether products are available in products
//sucessfull

var request = require('request');
var access_token_DRS;
var Last_purchase_time_slot;
var remainingQuantity_slot;
var originalQuantity_slot;

var Slot_Status_function = function access_token_function(access_token_DRS ,Last_purchase_time_slot,remainingQuantity_slot,originalQuantity_slot ) {
var https = require('https');
var today = new Date();
var Expected = new Date(today.getTime() + (1000*60*60*24));
var few_time_ago = Last_purchase_time_slot //new Date(today.getTime() - (1000*60*60));
var remainingQuantity_slot_int=parseInt(remainingQuantity_slot);
var originalQuantity_slot_int=parseInt(originalQuantity_slot);

var data = JSON.stringify({
  expectedReplenishmentDate : Expected,
  remainingQuantityInUnit : remainingQuantity_slot_int,
  originalQuantityInUnit : 10,
  totalQuantityOnHand : 20,
  lastUseDate : few_time_ago
  });

var options = {
  hostname: 'dash-replenishment-service-na.amazon.com',
  port: 443,
  path: '/slotStatus/bf3f0b71-7851-4b8c-9c6c-7364118d130f' ,
  method: 'POST',

  headers: {'Authorization' : 'Bearer ' + access_token_DRS, //"Atza|IwEBID4GwCjF-nX6Zhj6du-RHgHetMqSiwYFU7A3N7LzBrd5NRNyzOB5FfjInLEJUSFGi1Zg0VOImCd1DxmxdOTCXoxfQ9xllJv3zl5ue9i6zQMw6wWoz8L36OmOoJlv32bVcLXs5he1aR2s0PKB9w_VUetNj_Y8TLqK3zKC0ZCMdMU3ektVKiF8A8qUqMiq4zaLnXeE2oJdeFNHtzmfY7K-nMb5xJKX7Xx2w8pY-9DE4qylxsRhK6j2hlIXlpp8WyCw4Tiws841idLavlgg1sQb-l-0MR8NUQgNTyUMzfgwOJqmZgzVhUCvhIQD1vdxWD3aWlCsbuW6CAMb5zPLga8A6zK2HnKI9vRyOYRAO_3qOlnCjtE6DzOua7yQRu4T0yJ9KYuzK8dd5Qp_zGmHxetMKQtQSjB1iLTZ75saB510rfqiqQ",
          'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSlotStatusResult@1.0',
          'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSlotStatusInput@1.0',
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(data)
  }
};

var req = https.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('\n');
          console.log(today);
        console.log(data);
        console.log('\n');
          console.log('statusCode:', res.statusCode);
          console.log("body: " + chunk);
            console.log("sucessfully called slot status");


      });
  });

  req.write(data);
  req.end();

}

exports.Slot_Status_function = Slot_Status_function;

Device Status API

JavaScript
This API used to check Device is connected/enrolled of amazon dash replenishment service
//sucessfull
var request = require('request');
var access_token_DRS;
var https = require('https');
var deviceStatus_function = function Device_function(access_token_DRS) {

    var today = new Date();
    //var yesterday = new Date(today.getTime() - (1000*60*60*24));
    //var hourago = new Date(today.getTime() - (1000 * 60 * 60));

    var isoDate = new Date();
    var data = JSON.stringify({
        mostRecentlyActiveDate: isoDate
    });

    var options = {
        hostname: 'dash-replenishment-service-na.amazon.com',
        port: 443,
        path: '/deviceStatus',
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + access_token_DRS, //"Atza|IwEBIEnyPh02peJw0OCmDOuIhB77-CezF_T7FrerO5pKmf46wV_rFft6tJOl-qv807h-CWyuw7Zg26WXq2nr7_eITR12oXzfevauOYjCDQ8N3aoQ1WUsrDs6iPbv7UWehqkvX0PtYWbcxbpwPdrk9q-fThCidiuQWcRjL8YTOzYwUGgN6_k9-gpKcQaGt8zKdtRk_MHbGR5bEbR1rnQ1hKTTPlGDTfjNhKLHL8EyJkyPQcJgqEPjMh-7J8PlEOu5JAK_p8JvMjuUxyDSeh8Otdm-Br9E2mXOvpY_Q4mM2A4tp3336d0gFSLxWAJQa3b0d160WHdH1v4x6KGEdkRRdXLw8uNND4I0B7Dc0IDJAwySfZy5TGQfMaLm96wHsL1GRKjgzXgw6kIidF0pvmkeTcAnKraN1EcY91oK1kZMaQ9laGGpYg",
            'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeviceStatusResult@1.0',
            'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeviceStatusInput@1.0',
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(data)
        }
    };

    var req = https.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
              console.log('\n');
            console.log(isoDate);
            console.log(data);
    console.log('\n');
           console.log(today);
          //  console.log(yesterday);
          //  console.log(hourago);
            console.log('statusCode:', res.statusCode);
            console.log("body: " + chunk);
            console.log("Called Device status successfully");
    console.log('\n');

        });
    });

    req.write(data);
    req.end();
}
exports.deviceStatus_function = deviceStatus_function;

Dash replenish function

JavaScript
This function called from Main node js when products running low sensing quantity of it
var request = require('request');
var access_token_DRS;
var slot_number
var slot_ID;
var DRS_call_function = function DRS_function(access_token_DRS, slot_number) {
var headers = {
    'Authorization': 'Bearer ' + access_token_DRS,
    'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsReplenishResult@1.0',
    'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsReplenishInput@1.0'

}
var options = {

    url: 'https://dash-replenishment-service-na.amazon.com/replenish/bf3f0b71-7851-4b8c-9c6c-7364118d130f',
    port: 443,
    method: 'POST',
    headers: headers,
}
var options_2 = {

    url: 'https://dash-replenishment-service-na.amazon.com/replenish/a30ec848-664b-49b5-88d3-80631fbb34ea',
    port: 443,
    method: 'POST',
    headers: headers,
}


// Start the request
if(slot_number==1){
  request(options, function(error, response, body) {
    console.log('statusCode:', response.statusCode);
    console.log('headers:', response.headers);
    // Print out the response body
  //  console.log("HI");
    console.log(body);
        console.log("sucessfully called ordered KitKat");


    if (error) {
        console.log("error = " + error);
    }
})

}
else if(slot_number==2){
  request(options, function(error, response, body) {
    console.log('statusCode:', response.statusCode);
    console.log('headers:', response.headers);
    // Print out the response body
  //  console.log("HI");
    console.log(body);
        console.log("sucessfully called ordered oreo");


    if (error) {
        console.log("error = " + error);
    }
})
}


}
exports.DRS_call_function = DRS_call_function;

De-registration API

JavaScript
This API used to de-register service of Amazon Dash replenishment
var request = require("request");

var deregistration_function = function DeReg_function(access_token_DRS) {
    var options = {
        method: 'DELETE',
        url: 'https://dash-replenishment-service-na.amazon.com/registration',
        headers: {
            'Authorization': 'Bearer ' + access_token_DRS,
            'cache-control': 'no-cache',
            'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsDeregisterInput@2.0',
            'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsDeregisterResult@1.0',
            //authorization: 'Bearer  Atza|IwEBIHcxhtdKjbu2_N5QT9pE1ZS6eQaxkXVXrhOYjavjwEmE8s9TYIbPyVzPu46EvWqHZXNyjZ33T-n2zSkmoTV26nnpyB8CexOV2axaA-fBJlO59M6Z9QCdY5jwTSbgvU3XnwjgL-atojqmmGz4JjY-0nWZ_erNeZLMbqsYtz-VRqr7pLOXoXfNvkvJZ890ZtOZ7Pqe316UQix9R2LGAOMrNX03B_Mcap9e3M8dJisEUo6mhqdPNVV2t_OEvqtCK_Ld3Q08CsoAueKR52tEs7btosHXt-9uH3kKesCWt8-U9rrPV2x4XfDGjTpKfQMIGjB6JjmFMj9vD2q4moAJ4QceTrPE6qHQy68E5SSks6VcikpzePuqqvEERbL8479paLHP5AGP_Z4RSWAyHlgu8HNFemnQC_Q2V5GKbUQ-gYFhLAI7aA'
        }
    };

    request(options, function(error, response, body) {
        if (error) throw new Error(error);
    console.log('\n');
        console.log(body);
            console.log('\n');
            console.log("Device registration done successfully");
    });
}

exports.deregistration_function = deregistration_function;

Subscription API

JavaScript
This API is used to check whether used to subscribed to replenish products
//sucessfull

var request = require('request');
var access_token_DRS;

var Subscr_function = function Sub_function(access_token_DRS ) {
//sucessfull
var options = { method: 'GET',
  url: 'https://dash-replenishment-service-na.amazon.com/subscriptionInfo',
  headers:
   { 'postman-token': '3c220f05-a5cb-b50f-0750-058578f4055f',
     'cache-control': 'no-cache',
     'x-amzn-type-version': 'com.amazon.dash.replenishment.DrsSubscriptionInfoInput@1.0',
     'x-amzn-accept-type': 'com.amazon.dash.replenishment.DrsSubscriptionInfoResult@1.0',
     'Authorization': 'Bearer ' + access_token_DRS // Atza|IwEBIAj-O7u9wQKy91U2VaA7aFrrp5SzTAfY6J_kuyEVw0ZwUbJU6qNEG-NtK_nnmPeMCNkz7P9qgzu56LIKoZ0j4wqV3borMm5PnvgfltOo3KQGxFWCfbCeaQf5zRPH6c56UxRrcsD9WC4Xt_v2Ldk4yzUsE9mECjgoz-qVcleZQJI_xjyDKoj1vlIhDBgKKVmDkgfU_QtCE4Evb0383a22XCVja1j-rrBjOnv3-OyVnpSuDcMYkDxXNlh8zOea5L90BTKDDvwQYxL2uOpltHyKBjWqDtoW8KAATtgrmbMggHY_8bsJgG2txcNPtNqtvqDT95_1prT_I2LtAHVPCr71vGgGVzetF5WVXT6LqeYD4TYnW510WMVMdQYK3sxbDkzrOv_Xc3O9-Zdl7KZb8uL8V1EcTBaGliVdzBjMQ6UXDs-dJw'
    } };

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  console.log('\n');
  console.log(body);
    console.log('\n');
  console.log("sucessfully called subscriptionInfo")
});

}
exports.Subscr_function = Subscr_function;

Webpage for RFID recharge

HTML
A static web page which inform MCU about user recharge via serial communication
<!DOCTYPE html>
<html>
<head>
  <!-- Include meta tag to ensure proper rendering and touch zooming -->
  <meta name="viewport" content="width=device-width, initial-scale=1" >
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <!-- Include jQuery Mobile stylesheets -->
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<!-- Include the jQuery library -->
  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

<!-- Include the jQuery Mobile library -->
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

  <script src="socket.io/socket.io.js"></script>
  <title>Refillment products</title>
<style>
  .ui-bar-c{
    text-align: center;
    padding: 5px 4px;

  }
</style>

</head>
<body>
<div data-role="page" id="pageone">
  <div data-role="header" data-theme="b">
  <h1>Topup up RFID</h1>
  </div>
<div data-role="main" class="ui-content">
  <form action="">
  Enter the amount to Topup:
  <input type="number" name="firstname" placeholder="Enter Amount" id="Topup" >

  <input type="submit" value="Submit" id="AllValueSubmit">
</form>
      </div>
        </div>
</div>
<script>
var socket = io();
var amount;
$('#AllValueSubmit').on("click", function() {
  $("[name='firstname']").val(function(n, c){
            amount =c;

        });

 alert("Amount Topuped ="+ amount);
          socket.emit('TopupEvent',amount);

              });

</script>
</body>
</html>

Webpage for Refilling stock of snacks

JavaScript
A static web page which pass values of snacks to MPU via socket event
<!DOCTYPE html>
<html>
<head>
  <!-- Include meta tag to ensure proper rendering and touch zooming -->
  <meta name="viewport" content="width=device-width, initial-scale=1" >
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <!-- Include jQuery Mobile stylesheets -->
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<!-- Include the jQuery library -->
  <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>

<!-- Include the jQuery Mobile library -->
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

  <script src="socket.io/socket.io.js"></script>
  <title>Refillment products</title>
<style>
  .ui-bar-c{
    text-align: center;
    padding: 5px 4px;

  }
</style>

</head>
<body>
<div data-role="page" id="pageone">
  <div data-role="header" data-theme="b">
  <h1>Number of products</h1>
  </div>
<div data-role="main" class="ui-content">
  <form action="">
  Quantity of KitKat:
  <input type="number" name="firstname" placeholder="Enter quantity" id="KitKatQuantity" >
  <br>
  Quantity of Oreo:
  <input type="number" name="lastname" placeholder="Enter quantity" id="OreoQuatity">
  <input type="submit" value="Submit" id="AllValueSubmit">
</form>
      </div>
        </div>
</div>
<script>
var socket = io();
var KitKat,Oreo;
$('#AllValueSubmit').on("click", function() {
  $("[name='firstname']").val(function(n, c){
            KitKat =c;

        });
         $("[name='lastname']").val(function(n, c){
           Oreo =c;

        });
 alert("KitKat ="+ KitKat + "Oreo= "+Oreo);
          socket.emit('KitKatQuantityEvent',KitKat);
            socket.emit('OreoQuatityEvent',Oreo);

              });

</script>
</body>
</html>

Credits

Sainath Komakula

Sainath Komakula

3 projects • 5 followers

Comments