-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedge-impulse-classify.js
81 lines (64 loc) · 3.14 KB
/
edge-impulse-classify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const fs = require("fs");
module.exports = function(RED) {
"use strict";
const fs = require("fs-extra");
function EdgeImpulseClassifyNode(config) {
RED.nodes.createNode(this,config);
this.path = config.path;
this.edge_impulse_module = this.path + "/edge-impulse-standalone";
/** A copy of 'this' object in case we need it in context of callbacks of other functions.*/
const node = this;
try {
if (!(fs.existsSync(this.edge_impulse_module + ".js"))) throw new Error('no edge impulse at location:' + this.edge_impulse_module + '.js');
this.status({fill:"yellow",shape:"dot",text:"loading edge-impulse:" + this.edge_impulse_module });
// based on https://docs.edgeimpulse.com/docs/through-webassembly
// Load the inferencing WebAssembly module
let Module = require( this.edge_impulse_module);
// Classifier module
let classifierInitialized = false;
Module.onRuntimeInitialized = () => {
classifierInitialized = true;
node.status({fill:"green",shape:"dot",text:"successfully loaded edge-impulse:" + node.edge_impulse_module });
};
function _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 };
}
function _classify(rawData, debug = false) {
if (!classifierInitialized) throw new Error('Module is not initialized');
const obj = _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;
}
this.on('input', function(msg) {
msg.payload = _classify(msg.payload);
this.send(msg);
});
this.on('close', function() {
// unloading edge impulse module
var name = require.resolve(this.edge_impulse_module);
delete require.cache[name];
});
}
catch(err){
this.status({fill:"red",shape:"ring",text:err.message});
}
}
RED.nodes.registerType("edge-impulse-classify",EdgeImpulseClassifyNode);
}