How to execute node.js protoype function from html? - javascript

I have a program that will work to start a motion sensor when running the file from the command line, but when I try to call the function from HTML, it recognizes the prototype as 'undefined' and will not execute.
Here is the full code:
var sleep = require('sleep');
var Gpio = require('onoff').Gpio;
var LED = new Gpio(18, 'out');
var sensor = new Gpio(17, 'in', 'both');
sensor.watch(function(err, value){
if (err){
console.log('error');
exit();
}
if(value == 1) {
console.log('Motion Detected');
LED.writeSync(value);
sleep.sleep(3);
}
else if(value == 0) {
console.log('No Motion');
LED.writeSync(value);
sleep.sleep(3);
}
});
function exit() {
LED.unexport();
sensor.unexport();
process.exit();
}
dev tools says 'sensor' is undefined.
How do I run sensor.watch(callback) from html?
Thanks!

Related

looping the callback function in node js

This is a piece of code which writes data to a ble device and reads data from it. data is written to the device in the form of a buffer. the value in 'mydata' (AAAD0000) is the command to be written in order to read the data.
function named chara3() consists of write and read function which is a callback function in which the command is passed read back.
My requirement is the 'mydata' value which i said earlier, the last two zeros is the memory address. i need to read the data in different memory addresses starting from zero to 59. That is AAAD0000 to AAAD0059. so of course i need to run a loop. If I'm reading the zeroth location, the code is quite fine and i got the output as well but when i tried to make it inside a loop, the code is all a mess. the read part is not executing.
can any one suggest a better way to read data from zeroth memory location to 59th memory location (AAAD0000 to AAAD0059)???
first command writes to it
then reads data
memory location incremented by 1
this should repeat up to 59
var mydata = 'AAAD0000';
function chara3() {
var buff2 = new Buffer(mydata, 'hex');
SensorCharacteristic.write(buff2, false, function(error) { //[0x002d]
console.log('Writing command SUCCESSFUL',mydata);
if (!error) {
SensorCharacteristic.read((error, data) => {
console.log("i just entered");
if (data.toString('hex') != '0000') {
console.log('Temperature History: ', data.toString('hex'));
enter();
}
else {
console.log('contains null value');
} //else
});
}
function enter()
{
mydata = (parseInt(mydata, 16) + 00000001).toString(16);
}
}); //.write
} //chara3
there's no error. But some part of the code is not executing.
You can use the recursion by wrapping your methods into a promise
async function chara3(mydata = 'AAAD0000') {
if (mydata === 'AAAD0059') {
return;
}
var buff2 = new Buffer(mydata, 'hex');
return new Promise((resolve) => {
SensorCharacteristic.write(buff2, false, function (error) { //[0x002d]
console.log('Writing command SUCCESSFUL', mydata);
if (!error) {
SensorCharacteristic.read(async (error, data) => {
console.log("i just entered");
if (data.toString('hex') != '0000') {
console.log('Temperature History: ', data.toString('hex'));
let next = await chara3(enter())
return resolve(next);
}
else {
console.log('contains null value');
return resolve();
} //else
});
}
}); //.write
});
} //chara3
function enter() {
return (parseInt(mydata, 16) + 00000001).toString(16);
}
Also if you can convert your methods SensorCharacteristic.write and SensorCharacteristic.read into promises you can simply map
function chara3(mydata) {
var buff2 = new Buffer(mydata, 'hex');
await SensorCharacteristic.write(buff2, false);
console.log('Writing command SUCCESSFUL', mydata);
let data = await SensorCharacteristic.read();
if (data.toString('hex') != '0000') {
console.log('Temperature History: ', data.toString('hex'));
enter();
} else {
console.log('contains null value');
}
};
let promiseArray = Array(60).fill().map((_, i) => (parseInt('AAAD0000', 16) + i).toString(16)).map(chara3);
Promise.all(promiseArray).then(() => console.log('done'));

Variable not accessing inside of function

ive made a function for my twitch bot. which when they input a command checks if they are already in the list. if they are not in the list it will add them to the list. The code below outputs this : [ undefined ]
[17:53] info: [#kong_plays] *<kng_bot>: 1
var wtpLength = [];
function lfg(user){
WTPLength = viewersWTP.length;
if (WTPLength !== 0) {
viewersWTP = viewersWTP - 1
while(WTPLength !== -1){
if(user === viewersWTP[WTPLength]){
console.log("Already in list")
client.action("kong_plays",user+" you cannot execute this command again until kong pulls a viewer to play with him!")
}else{
viewersWTP.push(user['display-name'])
console.log("Added into list")
client.action("kong_plays",viewersWTP)
}
}
}else{
viewersWTP.push(user['display-name'])
console.log(viewersWTP)
client.action("kong_plays","1"+viewersWTP)
}
}
Something like this may work for you. You are using variables that are undefined. It also looks as though you are not paying attention to the cases of the variables that you are defining.
var viewersWTP = []; // add this or define it elsewhere
function lfg(user){
var wtpLength = viewersWTP.length;
if (wtpLength !== 0) {
viewersWTP = viewersWTP - 1
while(wtpLength !== -1){
if(user === viewersWTP[wtpLength]){
console.log("Already in list")
client.action("kong_plays",user+" you cannot execute this command again until kong pulls a viewer to play with him!")
}else{
viewersWTP.push(user['display-name'])
console.log("Added into list")
client.action("kong_plays",viewersWTP)
}
}
}else{
viewersWTP.push(user['display-name'])
console.log(viewersWTP)
client.action("kong_plays","1"+viewersWTP)
}
}
Change the user['display-name'] into user. You passed that var throught the function

Node.js driving things in right order in basic code

I am struggling with node.js asynchronous world, I am noob in node.js. I don't understand how to drive basic program flow. I use package iotdb-arp to print ip adress and mac adress on network. I need to run this code, execute function scan, wait until variable arr is full then print that arr and ending message. I know that I should use callbacks but I am really lost. Could someone point me to right direction, how to run things in right order? Now when I execute that it prints "[+] Program start", then it prints "IP of this machine is : 192.168.1.2" then scan is executed but program is simultaneously in the end, arr is empty because scan is still running. Here is my code:
console.log("[+] Program start");
var ip = require('ip');
var browser = require('iotdb-arp');
var arr = [];
var myIp = ip.address();
console.log("IP of this machine is : " + myIp.toString());
function scan(){
browser.browser({},function(error, data) {
if (error) {
console.log("#", error);
} else if (data) {
console.log(data);
arr.push(data);
} else {
}
});
}
/*function callback(){
console.log(arr);
console.log("[+] Program End");
}*/
scan();
console.log(arr); // Here in the end i need print arr
console.log("[!] Program End"); // Here I need print message "[+] Program End"
The function parameter in the "browser" call is a callback. Which means that when the "browser" function end , it is calling the parameter function you inserted. This is what you have to do in your "scan" function.
console.log("[+] Program start");
var ip = require('ip');
var browser = require('iotdb-arp');
var arr = [];
var myIp = ip.address();
console.log("IP of this machine is : " + myIp.toString());
function scan(callb){
browser.browser({},function(error, data) {
if (error) {
console.log("#", error);
callb(err);
} else if (data) {
console.log(data);
arr.push(data);
} else {
callb()
}
});
}
scan(function(err){
if(err) {return;} /// handle error here
else {
console.log(arr); // Here in the end i need print arr
console.log("[!] Program End"); // Here I need print message "[+] Program End"
}
});

Plupload retry if error

I'm trying to setup plupload so that if a file upload fails according to a certain error code, plupload will try to upload it again. Without success.
What I currently have
Here is my piece of code for now :
var attempts = 0; // number of attempts
function init(uploader) {
uploader.bind('Error', function(up, file) {
var code = JSON.parse(file.response).error.code;
console.log(code); //logs the error code
if(code === 503 && attempts > 3) {
up.stop();
file.status = plupload.FAILED;
file.retry = false;
// do stuff...
up.state = plupload.STARTED;
up.trigger("StateChanged");
attempts = 0;
}
else {
console.log("attempt : "+ attempts);
up.stop();
file.status = plupload.QUEUED;
attempts++;
file.retry = true;
up.state = plupload.STARTED;
up.trigger("StateChanged");
up.trigger("QueueChanged"); // ERROR HERE
}
})
}
Where I indicated the "ERROR HERE", my console shows me this :
TypeError: n.getSource is not a function
What am I doing wrong ?
Thanks a lot !
Why don't you add the file again on the queue?
http://www.plupload.com/docs/Uploader#addFile-filefileName-method
addFile(file, [fileName])

Application infinite loop with processMessage failed error

My Cordova app not running in browser and mobile it shows an error
processMessage failed
Screenshot:
and goes infinite loop and it freezes the device any solution?
This question is already in asked here Cordova not running normally but there is not an answer so thats why I have to asked it again.
Getting the same issue (using Chrome with the phonegap desktop emulator. What I see as happening is this.
There seems to be a bug in Cordova.js that fails to check for an empty message.
When the app sends out alerts:
gap_init:2
gap:[0,"StatusBar","_ready","StatusBar1593157203"]
gap:[0,"App","show","App1593157204"]
gap:[0,"File","requestAllPaths","File1593157205"]
gap:[0,"NetworkStatus","getConnectionInfo","NetworkStatus1593157206"]
gap:[0,"Device","getDeviceInfo","Device1593157207"]
and you just hit 'OK', instead of clearing out the contents of that dialog box it going on to cause an infinite loooooop. I don't know the significance of these messages yes as I'm pretty new to Cordova, but it's hell and gone from the principle of least surprise!
So you can clear out the messages, or modify the cordova.js code where it gets stuck in the loop. You also could turn off the alerts that also works.
the function processMessage() (see below) doesn't test for an empty string, which in and of itself might be fine, but it is called from a while loop which only checks for "*" if its going to pop.
while (messagesFromNative.length) {
var msg = popMessageFromQueue();
// The Java side can send a * message to indicate that it
// still has messages waiting to be retrieved.
if (msg == '*' && messagesFromNative.length === 0) {
setTimeout(pollOnce, 0);
return;
}
processMessage(msg);
}
// Processes a single message, as encoded by NativeToJsMessageQueue.java.
function processMessage(message) {
try {
var firstChar = message.charAt(0);
if (firstChar == 'J') {
eval(message.slice(1));
} else if (firstChar == 'S' || firstChar == 'F') {
var success = firstChar == 'S';
var keepCallback = message.charAt(1) == '1';
var spaceIdx = message.indexOf(' ', 2);
var status = +message.slice(2, spaceIdx);
var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1);
var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx);
var payloadKind = message.charAt(nextSpaceIdx + 1);
var payload;
if (payloadKind == 's') {
payload = message.slice(nextSpaceIdx + 2);
} else if (payloadKind == 't') {
payload = true;
} else if (payloadKind == 'f') {
payload = false;
} else if (payloadKind == 'N') {
payload = null;
} else if (payloadKind == 'n') {
payload = +message.slice(nextSpaceIdx + 2);
} else if (payloadKind == 'A') {
var data = message.slice(nextSpaceIdx + 2);
var bytes = window.atob(data);
var arraybuffer = new Uint8Array(bytes.length);
for (var i = 0; i < bytes.length; i++) {
arraybuffer[i] = bytes.charCodeAt(i);
}
payload = arraybuffer.buffer;
} else if (payloadKind == 'S') {
payload = window.atob(message.slice(nextSpaceIdx + 2));
} else {
payload = JSON.parse(message.slice(nextSpaceIdx + 1));
}
cordova.callbackFromNative(callbackId, success, status, [payload], keepCallback);
} else {
console.log("processMessage failed: invalid message: " + JSON.stringify(message));
}
} catch (e) {
console.log("processMessage failed: Error: " + e);
console.log("processMessage failed: Stack: " + e.stack);
console.log("processMessage failed: Message: " + message);
}
}
Check your cordova js loading properly? is the path for cordova js is proper?
give path like this in your index.html:
<script type="text/javascript" src="cordova.js">
I had the problem in an Angular 6 project. It was simply solved by deleting cordova.js which was under src folder.
I was not able to resolve this issue when viewing the /android platform option for cordova serve; however, the /ios platform option did function properly.
Not much of a solution, but perhaps a mildly helpful workaround for those who follow.

Categories