Most people might agree that vending machines are one of the greatest inventions. They provide a convenient lunch option for those who forgot to bring theirs, carry a selection of beverages and can help sate rumbly stomachs with a light snack. They’re a valuable asset to any work-space or public property until they stop working, of course
IntroductionRole of Amazon Dash Replenishment Service (DRS) :Amazon Dash Replenishment Service (DRS) API is backbone of ordering products which are out of stock.Servo motor placed behind each spiral part row in which products are placed and gets decrease count by -1 every time product gets purchased from machine and set to full count when re-filling done in each row. Controller sends request to Amazon website via DRS API when quantity of products low or out of stock.
Dash Replenishment Service set up:To setup DRS , You need to follow three steps.
1.Login With AmazonGo to Amazon Developer website and sign into account(If you are new user proceed for Signup).Under section of Apps & services ,click on security profile. Create security profile fill up necessary details and submit it .You will redirected to page where you can see Security profile ID, Client ID and Client secrete , copy them in one place.
Go to settings Icon at right side on same page where you see four options , opt for web-settings, there are two categories 1.Allowed Origins & 2.Allowed Return URL on basis on authorization types supported amazon , one of them is Implicit grant and other is Authorization Code Grant. In DRS Authorization process only Authorization grant type is used, so we don't need Allowed Origins i.e Implicit Grant type. In Allowed Return URL enter return URL ( the URL which is going to redirected by Amazon after completing setup of DRS in our case. P.S: Note exact entered URL because we have to use same URL in authorization request in UTF-8 format. So if you use '/' end of whole URL in Allowed Return Origins then error will be encountered at the time of Login process.
- Create an SNS Topic for DRS
Visit Amazon Web Services under section of Messaging , opt for SNS then click on the get started button. Create new topic and add Topic Name & display name then submit details.Topic Name - Used to create a permanent unique identifier called an Amazon Resource Name (ARN), which will be used to configure your SNS Notifications.
- To Allow DRS to Publish Messages
Click the ARN for the topic you’ve created then Click Other topic actions and then click Edit topic policy.From Basic View, under Allow these users to publish messages to this topic, select Only these AWS user and enter your AWS Account ID and the DRS AWS Account ID.To access your AWS Account ID, go to the AWS Console.Copy ARN ID which will be used in DRS registration process
Go to Amazon DRS page , sign in if session is expired . You will be redirected to main page of DRS site. Read the instruction of DRS program Requirement if you want to otherwise skip them. Then you pass through two step process to set DRS. On 1st page register with LWA, paste security profile ID which is copied in step 1. Login With Amazon.Then in 2nd page you need enter SNS ARN topic ID and click to next button.
After Setting up DRS with your account/security profile ID , then you need to create Device in DRS. So click on "Create Device" , choose name of your device and click on generate,model ID will get automatically created copy it. Add Logo of your device too. Click on next button.
Next page is where you need to add products , remember add similar or same category products in same slot so that customer can have maximum number of options to choose of them. If you are only one product manufacturer then add products on basis on quantity or quality. To add products it needs ASIN (please refer this website to know more about ASIN).Go to Amazon , click on the product which you want to add in slot. At the bottom page of product you will see Product details , in that description you'll notice ASIN, copy that number and go back to DRS device setup page and paste it. Same product will be filtered in results then click on add button to pass it in slot. After that Click on next to complete DRS device setup. Note: copy Slot ID and Device Model ID.
Three programming languages I have used in this project , HTML , Node JS and Arduino. In flow chart HTML page is created where user do Login with Amazon.Every action/event such as checking device status and de-registration etc is done through socket.io npm library in node js. MCU used to check availability of snacks in vending machine through counter index. Each time when snack is purchased its counter value will get decreases by 1 . This counter index is updated through serially to node js, Using threshold level check in node js Dash Replenish service will be called.I used MediaTek 7688 Duo which covers all of above units it has MPU MT7688AN which supports Node JS , HTML which I need most and MCU ATmega32U4 which supports Arduino so all in one tiny package, I Loved it and it suitable hardware especially things get it done like Dash Replenishment Service. To explain with flow chart which i have mentioned earlier, I have created small HTML page where you have do LWA(Login with Amazon ) process for first time, then another page for content filling which is very useful in my case where Vending machine has to Re-fill products once all orders from Amazon.So it difficulty to pass values from Web UI , where vendor gives number inputs , directly into Arduino code and assigns respective count for it. That's make very easy with Node JS on MT7688AN MPU platform on as it takes input from Web UI(HTMl page ) through socket event and writes it through serially to ATmega32U4 Microconroller.
Setting Up Software:1. HTMLFrankly saying no need to host your(manufacturer website) until unless you go for full fledged DRS associate manufacturer/ seller. I have tried many websites where you can host web sites but some may not support any programming on it they simple provide HTML modifications NO Javascript or Node JS support platform.After lot of search I came to know you/manufacturer can host your/his own tiny server in LAN , Yes it is true , Is that simple Right ?? But one point we need to remember in this case that this server/web page need to have Private Keys and Certificates to make website secure and LWA also need HTTPS web URL as its redirect URL after DRS setup. It is very costly to get such Private Keys and CertificatesLuckily there are online sites which generates keys and certificates get our work done, One of them i have used is Self-Signed Certificate Generator , it very simple website where we will get these stuff. I have created server in my LAN with private address of 192.168.1.133 2. Node JSSince MediaTek 7688 Duo MPU has OpenWRT OS , since it support Node JS and python also.In my project I have created two servers , one by requiring ‘http’ node module and other by ‘https’. You should need https server as Amazon redirect user/customer to only secure server (i.e https).So to create https server you need Private Key and Certificate , main purpose of key and certificate is explained here. Process of generating key and certificate is mentioned in snapshots, These files are stored in same folder where I am running MediaTek_DRS.js file
Note: localhost name in key and certificate is not have any relation with redirect URL , they are only name of file
//Secure Server code snippet
//Secure server
var https = require('https');
var Secport = 3443;
//creating secure socket connection
var io_sec = require('socket.io')(secureServer);
var options = {
key: fs.readFileSync(__dirname + '/25827299-localhost_3000.key'),
cert: fs.readFileSync(__dirname + '/25827299-localhost_3000.cert')
};
var secureServer = https.createServer(options, app)
secureServer.listen(Secport, function() {
console.log('Server listening on port ', Secport);
});
To set up serial operation in Node JS i.e in MPU to talk with MCU of 7688 Duo. Following parameters need to define before serial read/write operation. One important point I got to know there is no need to require SerialPort module in node js as LinkIt smart already defined module.Remember For serial communication between MCU ( ATMega32U4) and MPU (MT7688AN) LinkIT smart duo defined a baud rate of 57600, with this baud rate MPU/MCU can read and write operation with each other. Atom IDE for windows is best desktop application to programe/edit Node JS and HTML content
//Serial code snippet for node JS
var portName = '/dev/ttyS0';
serialPort = new SerialPort(portName, {
baudrate: 57600,
// default for Arduino serial communication
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
3 .Arduino MediaTek 7688 Duo MPU has also ATmega32U4 as Micro-controller ,it support Arduino code and to read/write serially we need to define serial baud rate for MCU side i.e 57600 in serial begin function
//Serial code snippet for Arduino
void setup() {
Serial1.begin(57600); // open internal serial connection to MT7688AN
}
void loop() {
// read the state of the pushbutton value:
if (Serial1.available() > 0)
{
Quantity = Serial1.readString().toInt();
}
// check if the pushbutton is pressed.
// if it is, the TouchSensor is HIGH:
TouchSensor = digitalRead(buttonPin);
// set the LED:
if (TouchSensor == HIGH) {
digitalWrite(ledPin, HIGH);
Serial1.print(1); // Serial write to MediaTek_DRS.js to decrement value by 1
customStepRev(4096);
// turn LED on:
}else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Setting Up Hardware & components:In this project, I used MediaTek Smart 7688 Duo , Stepper Motor and jumper wires , external power source for stepper motor Architecture of Smart Vendy :
Making of vending machine slot:I have made only one vending machine slot to demonstrate working of Amazon DRS . I bought a solid 0.5mm wire and made winding over bottom to gain shape of actual spring look. With small errors and bending finally spring look like shape.Then I took packaged cardboard and built into machine slot like shape.
To make spring rotate I used stepper motor along with help of 3D printed circular shape object and a bottle cap.A hot gum placed between bottle cap and 3D printed object. A small cardboard piece used to hold position of stepper motor properly Finally it will look like this.
Here is final look of machine slot along with spring
To subscribe products through Amazon DRS on behalf of Vending machine Re-filler/Retailer. Customer must to go through Login With Amazon(LWA) process.Which is one time signup/signin with Amazon DRS and Vending machine Retailer also. Then it will redirect through product page in slot wise. After choosing products , which customer/vending owner wish to order automatically, he/she will get notification of products subscription.So in my case there is main HTML page on which I have Login With Amazon button by clicking on it above mentioned procedure will be followed.At the bottom of page there is Re-fill button which is mainly for entering count/quantity of predefined products in that small pop-up page. Remaining buttons to check slot status , Device Status and Subscription status.
After LWA, Authorization code is generated to from index_testing.html page passed through socket event into MediaTek_DRS.js. With this Authorization code request is to Amazon to get access token and saved it in predifined variable so that it will be used to call DRS Replenish API. ( Amazon uses OAuth 2.0 frame work, which is explained here. An access token is an alphanumeric code 350 characters or more in length, with a maximum size of 2048 bytes. Access tokens begin with the characters 'Atza |'. Access tokens are only valid for sixty minutes and are specific to the user logging in and the data the app requested when it triggered the login. When you receive an access token, it is as a structure in JSON format with three pieces of information: the access_token,the token_type, and expires_in (the number of seconds before the token expires).
Remember ,this access token is have limited active time, after that it get expire. To avoid this OAuth 2.0 introduced refresh token, Refresh tokens follow the same format as access tokens, except they begin with the string 'Atzr | '. As per Amazon LWA documentation, refresh token has valid indefinitely, unless the user has removed the website or mobile app from the list of allowed apps for their account. Refresh tokens have a maximum size of 2048 bytes and it is specifically assigned to one client and cannot be used by another client.Refresh tokens are returned only in the Authorization Code Grant, this type of Grant type is used in Amazon Dash Replenishment process. Detailed explanation of Login with Amazon documentation explained here Let's back to project process ,As this count of products is read from socket event and serially write to MCU ATmega32U4 though serial write function and on other side this MCU read this through serially read and assign it to counter variable.
//Snippet from HTML , emitting socket event
// On node js sode . catching emitted event
socket.on('KitKatQuantityEvent', function(data) {
console.log("Number of KitKat quantity =" + data);
serialPort.write(data);
});
// Reading value in arduino
if (Serial1.available() > 0)
{
Quantity = Serial1.readString().toInt();
}
This counter is decreased by value '1' when purchase made from slot/machine, A pushbutton is used to rotate spring and when user press the button to purchase snack/product from it ( to avoid complexity of demonstration the process of purchasing from vending machine is not defined in my project).
// check if the TouchSensor is pressed.
// if it is, the TouchSensor is HIGH:
TouchSensor = digitalRead(buttonPin);
// set the LED:
if (TouchSensor == HIGH) {
digitalWrite(ledPin, HIGH);
Serial1.print(1); // Serial write to MediaTek_DRS.js to decrement value by 1
customStepRev(4096);
// turn LED on:
}else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
This counter variable is updated again to MPU MT7688AN through serial port. to check threshold value which is already set(in my case , I have set to 2) , if it crosses that level then it calls refresh token function to get fresh access token.
function refresh_token_function() {
//Configuration of request , refer is main code for complete configuration,
DRS_call_import.DRS_call_function(access_token_DRS);
//Calling DRS function to replenish
}
if (remainingQuantity == "2") {
console.log('\n');
console.log("products 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();
}
Then using newly obtained access token DRS function will be called order product automatically. Here is Test order working video .
Test order snap
Test order email confirmation.
I have used DRS APIs to check Slot status ,Subscription, Device status and Deregister DeviceSlot Status APISlot Status API used to know to status of products in slot wise.
Subscription API
Device Status API
De-registration API
RFID: I have interfaced RFID with smart vendy so that user/customer can transact via RFID i.e cashless , RFID recharge/topup can be done on static html page created
Keypad: Keypad used to enter slot number of snack placed in vending machine
Logs of RFID
Comments