vincent wongmok mun fong
Published © GPL3+

Elephant Activity Dashboard

This dashboard displays elephant activities and alerts certain types of activities.

IntermediateFull instructions providedOver 2 days407
Elephant Activity Dashboard

Things used in this project

Software apps and online services

Edge Impulse Studio
Edge Impulse Studio
IoTConnect
Node-RED
Node-RED

Story

Read more

Code

send_data_w1.js

JavaScript
send weather data to iotconnect
'use strict';

var sdk = require('iotconnect-sdk');

//"Get your ENV and CPID from the portal key vaults module or visit https://help.iotconnect.io SDK section."
var cpId = "CPID from the portal key vaults module";
var uniqueId = "W1";
var env = "Avnet";
var intervalLimit = 60; //Time Interval in Seconds
var iotConnectSDK = "";
var curr_temperature = 25;

setTimeout(() => {
	if(!cpId || !uniqueId){
        if(!cpId)
			console.log("cpId can not be blank");
		if(!uniqueId)
			console.log("uniqueId can not be blank");
        process.exit();
    } else {
		iotConnectSDK = new sdk(cpId, uniqueId, callbackMessage, twinCallbackMessage, env);
		console.log("Initializing...");
	}
}, 500);

var callbackMessage = function callbackMessage(data){
    
    if(data != null && data != undefined && data.ack != undefined && data.cmdType != null)
    {
        if(data.cmdType == '0x01') {
            console.log("\n"+"--- Device Command Received ---");
            console.log(data.ack);
            console.log(data.ackId);
            console.log(data.command);
            console.log(data.uniqueId);
            var obj = {
                "ackId": data.ackId,
                "st": 6,
                "msg": "",
                "childId": ""
            }
            var mt = 5;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
            
        } else if(data.cmdType == '0x02') {
            console.log("\n"+"--- Firmware Command Received ---");
            console.log(data);
            var obj = {
                "ackId": data.ackId,
                "st": 7,
                "msg": "",
                "childId": ""
            }
            var mt = 11;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
        }
    }
    else
    {
        if(data.cmdType == null && data.command == "device_connected") {
            try {
                console.log("Device connected...", new Date());
            } catch (error) {
                console.log("Error while getting attributes :: ",error.message);
            }
        } else {
            //console.log(data);
        }
    }
}

var twinCallbackMessage = function twinCallbackMessage(data){
    console.log("\n--- Twin desired message received ---");
    console.log(data);
}


setTimeout(() => {
    setInterval(() => {
        curr_temperature = nextTemperatureValue(curr_temperature);
        var obj = [
            {
                "uniqueId":uniqueId,
                "time":new Date(),
                "data": {
                    "temperature": curr_temperature.toFixed(2),
                    "humidity": nextHumidityValue() 
                    //"Temp":"11"  // Your Device attributes
                }
            }
        ]
        console.log(obj)
        iotConnectSDK.SendData(obj)
    }, intervalLimit * 1000);
}, 10000);

var updateTwin = function updateTwin(){
    var key = "firmware_version";
    var value = "4.0";
    iotConnectSDK.UpdateTwin(key,value, function (response) {
        console.log("Twin update :: ",response);
    })
}

function disconnectDevice(){
    iotConnectSDK.disconnectDevice(function (response) {
        if(response.status){
            console.log("\nDevice disconnected :: ", new Date());
            process.exit();
        } else {
            console.log("Device disconnection :: ", response);
        }
    })
}

function sendAck(jsonObj, time, mt){
    iotConnectSDK.sendAck(jsonObj, time, mt, function (response) {
        if(response.status){
            console.log("\nCommand acknowledgement sent :: SUCCESS:: ", new Date());
        } else {
            console.log("\nCommand acknowledgement sent :: FAILED :: ", new Date());
        }
    })
}

function nextTemperatureValue(curr) {
  if (curr < 21) curr = 21.0;
  else if (curr > 30) curr += Math.random() - 1.5; 
  else curr += -0.75 + Math.random() * 2.5;
  return curr;
}

function nextHumidityValue() {
  let curr = (Math.random() * (27 - 24) + 24).toFixed(2);
  return curr;
}


function getRandomValue(min, max) {
    return (Math.random() * (max - min) + min).toFixed(0);
}

send_data_e2.js

JavaScript
send random activity level data of elephant 2 (E2) to iotconnect
'use strict';

var sdk = require('iotconnect-sdk');

//"Get your ENV and CPID from the portal key vaults module or visit https://help.iotconnect.io SDK section."
var cpId = "CPID from the portal key vaults module";
var uniqueId = "E2";
var env = "Avnet";
var intervalLimit = 30; //Time Interval in Seconds
var iotConnectSDK = "";

setTimeout(() => {
	if(!cpId || !uniqueId){
        if(!cpId)
			console.log("cpId can not be blank");
		if(!uniqueId)
			console.log("uniqueId can not be blank");
        process.exit();
    } else {
		iotConnectSDK = new sdk(cpId, uniqueId, callbackMessage, twinCallbackMessage, env);
		console.log("Initializing...");
	}
}, 500);

var callbackMessage = function callbackMessage(data){
    
    if(data != null && data != undefined && data.ack != undefined && data.cmdType != null)
    {
        if(data.cmdType == '0x01') {
            console.log("\n"+"--- Device Command Received ---");
            console.log(data.ack);
            console.log(data.ackId);
            console.log(data.command);
            console.log(data.uniqueId);
            var obj = {
                "ackId": data.ackId,
                "st": 6,
                "msg": "",
                "childId": ""
            }
            var mt = 5;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
            
        } else if(data.cmdType == '0x02') {
            console.log("\n"+"--- Firmware Command Received ---");
            console.log(data);
            var obj = {
                "ackId": data.ackId,
                "st": 7,
                "msg": "",
                "childId": ""
            }
            var mt = 11;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
        }
    }
    else
    {
        if(data.cmdType == null && data.command == "device_connected") {
            try {
                console.log("Device connected...", new Date());
            } catch (error) {
                console.log("Error while getting attributes :: ",error.message);
            }
        } else {
            //console.log(data);
        }
    }
}

var twinCallbackMessage = function twinCallbackMessage(data){
    console.log("\n--- Twin desired message received ---");
    console.log(data);
}


setTimeout(() => {
    setInterval(() => {
        var obj = [
            {
                "uniqueId":uniqueId,
                "time":new Date(),
                "data": {
                    "latitude": 8,
                    "longitude": 38,
                    "level": getRandomValue(1, 4)
                    //"Temp":"11"  // Your Device attributes
                }
            }
        ]
        console.log(obj)
        iotConnectSDK.SendData(obj)
    }, intervalLimit * 1000);
}, 10000);

var updateTwin = function updateTwin(){
    var key = "firmware_version";
    var value = "4.0";
    iotConnectSDK.UpdateTwin(key,value, function (response) {
        console.log("Twin update :: ",response);
    })
}

function disconnectDevice(){
    iotConnectSDK.disconnectDevice(function (response) {
        if(response.status){
            console.log("\nDevice disconnected :: ", new Date());
            process.exit();
        } else {
            console.log("Device disconnection :: ", response);
        }
    })
}

function sendAck(jsonObj, time, mt){
    iotConnectSDK.sendAck(jsonObj, time, mt, function (response) {
        if(response.status){
            console.log("\nCommand acknowledgement sent :: SUCCESS:: ", new Date());
        } else {
            console.log("\nCommand acknowledgement sent :: FAILED :: ", new Date());
        }
    })
}

function getRandomValue(min, max) {
    return (Math.random() * (max - min) + min).toFixed(0);
}

send_data_e1_files.js

JavaScript
send sample activity level data of elephant 1 (E1). those sample data are activity fragments of gesture tutorial from edge impulse
'use strict';

const Module = require('./edge-impulse/edge-impulse-standalone');

const path = require('path');
const fs = require('fs');

const dirPath = path.join(__dirname, 'data');
const files = fs.readdirSync(dirPath);

console.log(files);

// Classifier module
let classifierInitialized = false;
Module.onRuntimeInitialized = function() {
    classifierInitialized = true;
};

class EdgeImpulseClassifier {
    //_initialized = false;

    init() {
        if (classifierInitialized === true) return Promise.resolve();

        return new Promise((resolve) => {
            Module.onRuntimeInitialized = () => {
                resolve();
                classifierInitialized = true;
            };
        });
    }

    classify(rawData, debug = false) {
        if (!classifierInitialized) throw new Error('Module is not initialized');

        const obj = this._arrayToHeap(rawData);
        let ret = Module.run_classifier(obj.buffer.byteOffset, rawData.length, debug);
        Module._free(obj.ptr);

        if (ret.result !== 0) {
            throw new Error('Classification failed (err code: ' + ret.result + ')');
        }

        let jsResult = {
            anomaly: ret.anomaly,
            results: []
        };

        for (let cx = 0; cx < ret.classification.size(); cx++) {
            let c = ret.classification.get(cx);
            jsResult.results.push({ label: c.label, value: c.value });
        }

        return jsResult;
    }

    _arrayToHeap(data) {
        let typedArray = new Float32Array(data);
        let numBytes = typedArray.length * typedArray.BYTES_PER_ELEMENT;
        let ptr = Module._malloc(numBytes);
        let heapBytes = new Uint8Array(Module.HEAPU8.buffer, ptr, numBytes);
        heapBytes.set(new Uint8Array(typedArray.buffer));
        return { ptr: ptr, buffer: heapBytes };
    }
}


// Initialize the classifier, and invoke with the argument passed in
var classifier = new EdgeImpulseClassifier();
var level;

function classify(i) {

let data = fs.readFileSync(path.join(dirPath, files[i]), 'utf8');

classifier.init().then(() => {
    //let result = classifier.classify(process.argv[2].trim().split(',').map(n => Number(n)));
    let result = classifier.classify(data.trim().split(',').map(n => Number(n)));

    console.log(result);

    console.log(...result.results.map(x => x.value));
    
    var a = result.results;
    var k = a.reduce((j, x, i, a) => x.value > a[j].value ? i : j, 0);
    console.log(k, a[k].label);

    level = k + 1;

}).catch(err => {
    console.error('Failed to initialize classifier', err);
});
}


///classify(3);
///classify(0);

//////

var sdk = require('iotconnect-sdk');

//"Get your ENV and CPID from the portal key vaults module or visit https://help.iotconnect.io SDK section."
var cpId = "CPID from the portal key vaults module";
var uniqueId = "E1";
var env = "Avnet";
var intervalLimit = 30; //Time Interval in Seconds
var iotConnectSDK = "";
var i = 0;

setTimeout(() => {
	if(!cpId || !uniqueId){
        if(!cpId)
			console.log("cpId can not be blank");
		if(!uniqueId)
			console.log("uniqueId can not be blank");
        process.exit();
    } else {
		iotConnectSDK = new sdk(cpId, uniqueId, callbackMessage, twinCallbackMessage, env);
		console.log("Initializing...");
	}
}, 500);

var callbackMessage = function callbackMessage(data){
    
    if(data != null && data != undefined && data.ack != undefined && data.cmdType != null)
    {
        if(data.cmdType == '0x01') {
            console.log("\n"+"--- Device Command Received ---");
            console.log(data.ack);
            console.log(data.ackId);
            console.log(data.command);
            console.log(data.uniqueId);
            var obj = {
                "ackId": data.ackId,
                "st": 6,
                "msg": "",
                "childId": ""
            }
            var mt = 5;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
            
        } else if(data.cmdType == '0x02') {
            console.log("\n"+"--- Firmware Command Received ---");
            console.log(data);
            var obj = {
                "ackId": data.ackId,
                "st": 7,
                "msg": "",
                "childId": ""
            }
            var mt = 11;
            if(data.ackId != null)
			    sendAck(obj, null, mt);
        }
    }
    else
    {
        if(data.cmdType == null && data.command == "device_connected") {
            try {
                console.log("Device connected...", new Date());
            } catch (error) {
                console.log("Error while getting attributes :: ",error.message);
            }
        } else {
            //console.log(data);
        }
    }
}

var twinCallbackMessage = function twinCallbackMessage(data){
    console.log("\n--- Twin desired message received ---");
    console.log(data);
}


setTimeout(() => {
    setInterval(async () => {
        await classify(i);  i = (i+1) % files.length;
        console.log('level>>> ', level);
        console.log('i>>> ', i);
        var obj = [
            {
                "uniqueId":uniqueId,
                "time":new Date(),
                "data": {
                    "latitude": 10,
                    "longitude": 10,
                    //"level": getRandomValue(1, 4)
                    "level": level 
                    //"Temp":"11"  // Your Device attributes
                }
            }
        ]
        console.log(obj)
        iotConnectSDK.SendData(obj)
    }, intervalLimit * 1000);
}, 10000);

var updateTwin = function updateTwin(){
    var key = "firmware_version";
    var value = "4.0";
    iotConnectSDK.UpdateTwin(key,value, function (response) {
        console.log("Twin update :: ",response);
    })
}

function disconnectDevice(){
    iotConnectSDK.disconnectDevice(function (response) {
        if(response.status){
            console.log("\nDevice disconnected :: ", new Date());
            process.exit();
        } else {
            console.log("Device disconnection :: ", response);
        }
    })
}

function sendAck(jsonObj, time, mt){
    iotConnectSDK.sendAck(jsonObj, time, mt, function (response) {
        if(response.status){
            console.log("\nCommand acknowledgement sent :: SUCCESS:: ", new Date());
        } else {
            console.log("\nCommand acknowledgement sent :: FAILED :: ", new Date());
        }
    })
}

function getRandomValue(min, max) {
    return (Math.random() * (max - min) + min).toFixed(0);
}

Credits

vincent wong

vincent wong

80 projects • 203 followers
mok mun fong

mok mun fong

2 projects • 2 followers

Comments