End-to-end tutorial to Trace Asset on Supply Chain with Blockchain and IoT

Before diving into the theoretics and hands-on knowledge to trace an asset on supply chain, I’ll briefly go though the course of the article so that it’s easier for you to navigate through it.

First of all, we’ll touch the current challenges which a supply chain faces. Secondly, we’ll see how the famous duo of ‘Blockchain + IoT’ come to the rescue along with a brief architecture for the same. Then we’ll dive into hands-on practice.

Blockchain and IoT in a picture. Whichever you like more can be your Batman. Source: https://www.geek.com/tech/stephen-king-wrote-a-tale-of-misery-about-batman-and-robin-1667629/

For hands-on knowledge — we’ll use ESP8266 module, RFID scanner, Microsoft Azure IoT Hub, BigChainDB.

Our stack.

Supply chain management is not as easy as one might think to see from a bird’s eye. Mismanagement of a supply chain may cost firms millions of dollars, along with a dented reputation. Hence, there is a need to address the problems that revolve around supply chain. With advent of Distributed Ledger Technology (like the Blockchain) and IoT, efficient management of supply chain is possible.

Supply chain challenges in today’s world can be summarised as follows:

  1. Increase in globalisation and global connectivity has lead to more complex supply chains.
  2. There are sudden and rapid changes in market environments. Businesses have to quickly react to them, and it becomes tough to align supply chain that quickly.
  3. There are multiple parties of suppliers, producers, distributors, consumers make supply chain more complex, thereby making it more tough to coordinate.
  4. Presently there are very few firms who have employed the tools to predict and manage risks to react aptly.
  5. There is no clear transparency. One can’t be sure if basic code of conduct is being followed.
  6. There is lacking trust among various stakeholders, so not all data is shared which makes reconciliation of data a tedious task.

Blockchain has become a hallmark for ‘trust economy’. Effectively, it is lifeblood for supply chain. The blockchain technology offers decentralised way to record digital moments which is designed the be secure, transparent, robust, auditable, and efficient. Which is in a way perfect for supply chain management! The picture would be complete when IoT would be infused with it. IoT would provide a medium to connect physical world with the digital world via the means of hardware. IoT sensors are capable of recording speed, temperature, humidity and all other physical parameters and then convey them efficiently over the network so that analytics can be drawn out of the same.

Various layers in IoT Architecture

Initiation triggers source of information through attached sensors. The raw information gathered from the sensors is transmitted over the network to the IoT hub where integration and consolidation of data takes place. In analysis section, risk prediction and management is done. According to the insights derived, human/machine behaviour is triggered.


So what are the features of an ideal supply chain?

  1. Transparency: Equal and 100% information should be available and visible to every stakeholder.
  2. Elasticity: The solution should empower the stakeholders to take rapid actions to quickly changing environments.
  3. Increased trust: There would be enhanced trust not between various stakeholders but upon the system upon which they’d be commonly operating.

Bird’s eye view

  1. Install Arduino inside ESP8266 module.
  2. Setup MFRC522 on ESP8266 module.
/* READ AN RFID TAG */
/*Use this sketch to verify that you have a working installation of the NodeMCU + MFRC522

* ---------------------------------------
* MFRC522 Arduino
* Reader/PCD Uno/101
* Signal Pin Pin
* ---------------------------------------
* RST/Reset RST D3
* SPI SS SDA(SS) D8
* SPI MOSI MOSI D7
* SPI MISO MISO D6
* SPI SCK SCK D5
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN D3
#define SS_PIN D8

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
}

void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}

// Dump debug info about the card; PICC_HaltA() is automatically called
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
delay(2000);
}

void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}

3. To connect with Azure IoT Hub, register your device on it and then get the connection string. After that, get your SAS token.

$ npm install iothub-explorer -g
$ iothub-explorer login "*connection string*"
$ iothub-explorer sas-token *registeredDeviceName* -d 600000

4. Arduino Sketch MQTT using PubSub client

/*
* Install PubSubClient and WiFiManager libraries
* Register your IoT devices on Azure IoT Hub
* Open a SAS token with the iothub-explorer
*
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <WiFiManager.h>

const char* mqtt_server = "technetwork.azure-devices.net";

WiFiClientSecure espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
Serial.begin(115200); // Initialize serial communications
WiFiManager wifiManager;
wifiManager.autoConnect("TECHFEST_NODE_AP");

client.setServer(mqtt_server, 8883);
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("**your_registered_device_id**", "**your_iot_hub_name**.azure-devices.net/**your_registered_device_id**","**your_sas_token**")) {
Serial.println("connected");
} else {
Serial.println("can't connect... trying again in 5 seconds");
delay(5000);
}
}
}

void loop() {

if (!client.connected()) {
reconnect();
}
client.publish("devices/esp8266_0BDAD6/messages/events/", "Test message");
//publish an event every 5 seconds
delay(5000);
}

To verify that your messages are going though, do the following:

$ iothub-explorer monitor-events *your registered device* --login "*your connection string*"

5. Getting MQTT messages from Azure IoT Hub

var EventHubClient = require('azure-event-hubs').Client;

var connectionString = 'HostName=technetwork.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=T70OrqQPOP26k/Izl7d1nrRpnmYxkolYIDAk4GtXTvk=';

var printError = function (err) {
console.log(err.message);
};

var client = EventHubClient.fromConnectionString(connectionString);
client.open()
.then(client.getPartitionIds.bind(client))
.then(function (partitionIds) {
return partitionIds.map(function (partitionId) {
return client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
console.log('Connected to Azure IoT hub');
receiver.on('errorReceived', printError);
receiver.on('message', receivedTransaction);
});
});
})
.catch(printError);

6. Create transaction in BigchainDB

function create_asset(assetid){

const tx = driver.Transaction.makeCreateTransaction(
{ asset_id: assetid },
{ what: 'Creation of the asset' , time: Date.now(), asset_id: assetid},
[ driver.Transaction.makeOutput(
driver.Transaction.makeEd25519Condition(tetrapak.publicKey))
],
tetrapak.publicKey
)

// Sign the transaction with private keys
const txSigned = driver.Transaction.signTransaction(tx, tetrapak.privateKey)

conn.postTransaction(txSigned)
.then(() => conn.pollStatusAndFetchTransaction(txSigned.id))
.then(retrievedTx => {
console.log('Transaction', retrievedTx, 'successfully posted.')
assets[assetid] = retrievedTx;
assets[retrievedTx] = assetid;
});

}

7. Transfer asset in bigchainDB

function transfer_asset(assetid){

console.log('Transaction', assets[assetid].id, 'successfully posted, now transferring')
// (tx, fromPublicKey, fromPrivateKey, toPublicKey, metadata)
const txTransfer = driver.Transaction.makeTransferTransaction(

assets[assetid],

{what: "Transfer of the asset", time:Date.now(), asset_id:assetid},
[
driver.Transaction.makeOutput(
driver.Transaction.makeEd25519Condition(tetrapak_facility1.publicKey)
)
],
0
)

const txTransferSigned = driver.Transaction.signTransaction(txTransfer, tetrapak.privateKey)
// send it off to BigchainDB
conn.postTransaction(txTransferSigned)
.then(() =>
conn.pollStatusAndFetchTransaction(txTransferSigned.id))
.then( txTransferSigned => console.log(util.inspect(txTransferSigned)))
}

8. Listening to transactions on bigchainDB

const ws = new WebSocket('wss://test.ipdb.io/api/v1/streams/valid_transactions');
const driver = require('bigchaindb-driver')
let conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
app_id: '95a772f7',
app_key: '247aebb45369a85075dc79f7013353d0'
})
const ws = new WebSocket('wss://test.ipdb.io/api/v1/streams/valid_transactions');
ws.on('open', function open() {
console.log('WebSocket connection to IPDB opened');
});

ws.on('message', function incoming(data) {
var o = JSON.parse(data);
console.log(data);

conn.getTransaction(o.transaction_id).then(details => {
console.log(details);
if (details.metadata.asset_id != null)
io.emit('transactionCreated', details);
}
);

And then run the express server!

Source: https://giphy.com/gifs/funny-art-cute-3o6vXURvyF7bmW1HGg

For more details, contact us at hello@quillhash.com