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

Niharika Singh
Mar 17, 2018 · 6 min read
Image for post
Image for post
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/
Image for post
Image for post
Our stack.


Image for post
Image for post
Various layers in IoT Architecture

So what are the features of an ideal supply chain?

Image for post
Image for post

Bird’s eye view

Image for post
Image for post
/* 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);
}
}
$ npm install iothub-explorer -g
$ iothub-explorer login "*connection string*"
$ iothub-explorer sas-token *registeredDeviceName* -d 600000

Feel free to request a Demo for a better understanding of QuillTrace.

/*
* 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);
}
$ iothub-explorer monitor-events *your registered device* --login "*your connection string*"
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);
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;
});

}
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)))
}
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);
}
);

QuillHash

Delivering Enterprise-grade blockchain technology to…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store