Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
vincent wong
Created July 23, 2019 © GPL3+

IOTA Toll System

Build an IOTA based toll payment system.

IntermediateFull instructions provided174

Things used in this project

Story

Read more

Code

get-account-data.js

JavaScript
get toll system and vehicle wallet account data
const createHttpClient = require('@iota/http-client').createHttpClient;
const createGetAccountData = require('@iota/core').createGetAccountData


const client = new createHttpClient({
    provider: 'https://nodes.devnet.iota.org:443'
})


const tollSeed = 'TOLLSEED';
const vehicleSeed = 'VEHICLESEED';


function getAccountData(seed) {
    const getAccountData = createGetAccountData(client)

    getAccountData(seed, { start: 0, end: 10, security: 2})
        .then(accountData => {
            const { addresses, inputs, transactions, balance } = accountData;
            console.log(addresses, inputs, transactions, balance);
        })
        .catch(error => {})
}


getAccountData(tollSeed)
getAccountData(vehicleSeed)

send-toll-token.js

JavaScript
send tokens to toll system
const Iota = require('@iota/core');

const iota = Iota.composeAPI({
provider: 'https://nodes.devnet.iota.org:443'
});


const vehicleSeed = 'VEHICLESEED';     // vehicle seed
const tollSeed = 'TOLLSEED';     // toll seed

const main = async () => {

  const receivingAddress = await iota.getNewAddress(tollSeed, {
    index: 2,
    total: 1
  });


  const transfers = [
    {
      value: 500,
      address: receivingAddress[0],
      tag: 'PAYTOLL'
    }
  ];


  console.log('Sending 500i to ' + receivingAddress);

  try {
    const trytes = await iota.prepareTransfers(vehicleSeed, transfers);

    const response = await iota.sendTrytes(trytes, 3, 9);

    console.log('Bundle sent');

    response.map(tx => console.log(tx));
  } catch (error) {
    console.log(error);
  }
}



main();

get-available-balance.js

JavaScript
const createHttpClient = require('@iota/http-client').createHttpClient;
const createGetAccountData = require('@iota/core').createGetAccountData


const client = new createHttpClient({

    // replace with your IRI node address 
    // or connect to a Devnet node for testing: 'https://nodes.devnet.iota.org:443'

    provider: 'https://nodes.devnet.iota.org:443'
    //provider: 'http://localhost:14265'

})


const seed = 'PUEOTSEITFEVEWCWBTSIZM9NKRGJEIMXTULBACGFRQK9IMGICLBKW9TTEVSDQMGWKBXPVCBMMCXWMNPDX';
const tollSeed = '';
const vehicleSeed = '';

function getAccountData(seed) {
    const getAccountData = createGetAccountData(client)

    getAccountData(seed, { start: 0, end: 30, security: 2})
        .then(accountData => {
            const { addresses, inputs, transactions, balance } = accountData;
            console.log(addresses, inputs, transactions, balance);
        })
        .catch(error => {})
}






//getAccountData(seed)


var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);

switch (myArgs[0]) {
case 'toll':
    console.log('>>> toll wallet <<<')
    getAccountData(tollSeed)
    break;
case 'vehicle':
    console.log('>>> vehicle wallet <<<')
    getAccountData(vehicleSeed)
    break;
default:
    console.log('>>> vehicle wallet <<<')
    getAccountData(vehicleSeed)
}

hello-iota.js

JavaScript
rest api to turn on/off led and pay toll
const express = require('express')
const app = express()
const port = 9000

const turnled = require('./turn-led.js');
const paytoll = require('./pay-toll.js');

app.get('/', (req, res) => res.send('Hello IOTA!'))
app.get('/on', (req, res) => { res.send('Hello IOTA! on!'); turnled.run(true); } )
app.get('/off', (req, res) => { res.send('Hello IOTA! off!'); turnled.run(false); } )
app.get('/paytoll', (req, res) => { res.send('Hello IOTA! pay toll!'); paytoll.run(); } )

app.listen(port, () => console.log(`IOTA app listening on port ${port}!`))

pay-toll.js

JavaScript
vehicle wallet pay toll to toll wallet
const { createAccount }  = require('@iota/account')
const CDA = require('@iota/cda');

const turnled = require('./turn-led.js');

// Connect to a node;

const provider = 'https://nodes.devnet.iota.org:443';


const magnetLink = 'iota://PD9QTKAADVXT9QIGZAMAHPFIODAONVGVKHWRRZSQONJKCSDQKX9YVCN9GFELLIWMIEHLLQEOVLXN9PURBVROCHWZRF/?timeout_at=1576203208650&multi_use=1';
const { address, timeoutAt, multiUse, expectedAmount } = CDA.parseCDAMagnet(magnetLink);

console.log('Sending to:', address, timeoutAt, multiUse, expectedAmount);

const seed = 'VEHICLESEED';     // vehicle seed

const account = createAccount({
    seed,
    provider
});


function run() {

const cda = account.generateCDA({
    timeoutAt: Date.now() + 24 * 60 * 60 * 1000
})
.then(cda => {
    account.sendToCDA({
        address,
        timeoutAt,
        multiUse,
        expectedAmount,
        value: 150
})
.then((trytes) => {
    console.log('Successfully prepared transaction trytes:', trytes)

    turnled.run(true)
})
})

}   // end run function


module.exports = {
    run: function(o) { run(o) }
  }

turn-led.js

JavaScript
turn on/off led
var CryptoJS = require("crypto-js");

var hubname= 'IOTHUBNAME';
var expiresinmins = '60';
var signingkey = 'POLICYKEY';   // policy shared access key
var policyname = 'iothubowner';


function run(o) {
var resourceUri = encodeURIComponent(hubname + '.azure-devic.net'); 
var expiry = Math.ceil((Date.now() / 1000) + expiresinmins * 60); 
var uriExpiry = resourceUri + '\n' + expiry; 
var decodedKey = CryptoJS.enc.Base64.parse(signingkey); 
var signature = CryptoJS.HmacSHA256(uriExpiry, decodedKey); 
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); 


var token = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry;

token += "&skn="+ policyname;



console.log("Shared Access Signature:" + token);

var myArgs = process.argv.slice(2);

console.log('myArgs[0]: ', myArgs[0]);
console.log('o: ', o);




var unirest = require("unirest");


var req = unirest("PATCH", "https://IOTHUBNAME.azure-devices.net/twins/DEVICENAME");


req.query({

  "api-version": "2018-06-30"

});



req.headers({

  "Authorization": token,

  "Content-Type": "application/json"

});



req.type("json");

req.send({

  "properties": {

    "desired": {

      "userLedRed": o 
      //"userLedRed": myArgs[0] == 'true'

    }

  }

});



req.end(function (res) {

  if (res.error) throw new Error(res.error);



  console.log(res.body);

});

} // end run function

module.exports = {
  run: function(o) { run(o) }
}

get-total-balance.js

JavaScript
const { createAccount }  = require('@iota/account')

// Connect to a node;

const provider = 'https://nodes.devnet.iota.org:443';

//const seed = 'TOLLSYSTEMTOLLSYSTEMTOLLSYSTEMTOLLSYSTEMTOLLSYSTEMTOLLSYSTEMTOLLSYSTEMAAAAAAAAAAA';

const tollSeed = '';
const vehicleSeed = '';


function getTotalBalance(seed) {
    let account = createAccount({
        seed,
        provider
    });

    account.getTotalBalance()
    .then(balance => console.log(balance))    
}


var myArgs = process.argv.slice(2);
console.log('myArgs: ', myArgs);

switch (myArgs[0]) {
case 'toll':
    console.log('>>> toll wallet <<<')
    getTotalBalance(tollSeed)
    break;
case 'vehicle':
    console.log('>>> vehicle wallet <<<')
    getTotalBalance(vehicleSeed)
    break;
default:
    console.log('>>> vehicle wallet <<<')
    getTotalBalance(vehicleSeed)
}

generate-magnet-link.js

JavaScript
genereate magnet link of toll account
const CDA = require('@iota/cda');
const { createAccount }  = require('@iota/account')


//const seed = 'PUEOTSEITFEVEWCWBTSIZM9NKRGJEIMXTULBACGFRQK9IMGICLBKW9TTEVSDQMGWKBXPVCBMMCXWMNPDX';
let seed = '';     // toll seed


// Connect to a node;

const provider = 'https://nodes.devnet.iota.org:443';

const account = createAccount({
      seed,
      provider

});

const cda = account
    .generateCDA({
        timeoutAt: Date.now() + 100 * 24 * 60 * 60 * 1000,     // expires in 100 days
        multiUse: true
    });


cda.then((cda) => {
    const magnetLink = CDA.serializeCDAMagnet(cda);
    // iota://MBREWACWIPRFJRDYYHAAME…AMOIDZCYKW/?timeout_at=1548337187&multi_use=1

    console.log(magnetLink);

});

button_led_http.js

JavaScript
this runs on raspberry pi which turn on/off led and call paytoll rest API when button is pressed
const Gpio = require('onoff').Gpio;
const led = new Gpio(17, 'out');
const button = new Gpio(2, 'in', 'rising', {debounceTimeout: 10});

var request = require('request');


button.watch((err, value) => {
  if (err) {
    throw err;
  }

  led.writeSync(led.readSync() ^ 1);

  request
    .get('http://192.168.2.99:9000/paytoll')
    .on('error', function(err) {
      console.log(err)
    })

});

process.on('SIGINT', () => {
  led.unexport();
  button.unexport();
});

Credits

vincent wong

vincent wong

81 projects • 205 followers

Comments