vincent wongmok mun fong
Published © GPL3+

Connected Mangroves (Initial Phase)

This is the intial phase for the Connected Mangroves project. This phase will post sensors data to IOTA network.

IntermediateFull instructions provided862
Connected Mangroves (Initial Phase)

Things used in this project

Story

Read more

Schematics

pi dht11 wiring diagram

Code

package.json

JSON
{
  "dependencies": {
    "@iota/converter": "^1.0.0-beta.8",
    "mam.client.js": "iotaledger/mam.client.js",
    "node-dht-sensor": "0.0.34",
    "node-fetch": "^2.3.0"
  }
}

config.json

JSON
{
  "sensorId": "mangroves-pi-01",
  "secretKey": "secret-key",
  "debug": false,
  "provider": "https://nodes.devnet.iota.org",
  "endpoint": "https://us-central1-iota-data-marketplace-demo.cloudfunctions.net/newData"
}

iota.js

JavaScript
const crypto = require('crypto');
const Mam = require('mam.client.js');
const { asciiToTrytes } = require('@iota/converter');
const { storeKey } = require('./keyStorage');
const { provider } = require('./config.json');

// Initialise MAM State
let mamState = Mam.init(provider);

// Random Key Generator
const generateRandomKey = length => {
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ9';
  const values = crypto.randomBytes(length);
  return Array.from(new Array(length), (x, i) => charset[values[i] % charset.length]).join('');
};

// Publish to Tangle
exports.publish = async payload => {
  const time = Date.now();
  const packet = { time, data: { ...payload } };

  // Change MAM encryption key on each loop
  let mamKey = generateRandomKey(81);

  // Set channel mode & update key
  mamState = Mam.changeMode(mamState, 'restricted', mamKey);

  // Create Trytes
  const trytes = asciiToTrytes(JSON.stringify(packet));

  // Get MAM payload
  const message = Mam.create(mamState, trytes);

  // Save new mamState
  mamState = message.state;

  // Attach the payload.
  await Mam.attach(message.payload, message.address);

  // console.log('Address:', message.address);
  // console.log('Attached Message:', message.state);

  // Store encryption key in Firebase
  const callbackResponse = await storeKey(mamKey, message.root, time);

  console.log('Payload:', packet);
  console.log(callbackResponse);
  console.log('==============================================================');
};

keyStorage.js

JavaScript
const fetch = require('node-fetch');
const { debug, endpoint, secretKey, sensorId } = require('./config.json');

// Push key to data marketplace.
exports.storeKey = async (sidekey, root, time) => {
  if (debug) return 'Debug mode';

  const packet = {
    sidekey,
    root,
    time,
  };

  try {
    // Initiate Fetch Call
    const resp = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ id: sensorId, packet, sk: secretKey }),
    });
    return await resp.json();
  } catch (error) {
    console.log('storeKey error', error);
    return error;
  }
};

mangroves-sensors.js

JavaScript
var sensorLib = require("node-dht-sensor");
const fetch = require('node-fetch');
const { publish } = require('./iota');
const { debug } = require('./config.json');

var sensor = {
    sensors: [ {
        name: "dht11",
        type: 11,
        pin: 4
    } ],
    read: async function() {
        for (var a in this.sensors) {
            var b = sensorLib.read(this.sensors[a].type, this.sensors[a].pin);
            var t = b.temperature.toFixed(2);
            var h = b.humidity.toFixed(2);

            console.log(this.sensors[a].name + ": " + t + "°C, " + h + "%");

            var payload = { "temp": t, "hum": h };

            if (debug) {
                console.log(payload);
            } else {
                // Publish sensor data to marketplace
                await publish(payload); // your sensor data goes here. Payload is any content in JSON format
            }
        }
        setTimeout(function() {
            sensor.read();
        }, 15000);
    }
};

sensor.read();

Credits

vincent wong

vincent wong

81 projects • 205 followers
mok mun fong

mok mun fong

2 projects • 2 followers

Comments