Raw keyboard capture with process.stdin doesn't work as expected? - node.js

I'm having problems capturing Raw keyboard input in a terminal on windows. This is driving me crazy, because I know that I had implemented this with older versions of nodejs (a year + ago)
Using the latest versions of NodeJS (currently using 4.2.2), capturing input seems buggy.. Unless I am missing something?
What I am running:
stdin = process.stdin;
stdin.on('data', function (data) {
if (data == '\u0003') { process.exit(); }
process.stdout.write('Captured Key : ' + data + "\n");
});
stdin.setEncoding('utf8');
stdin.setRawMode(true);
stdin.resume();
What I am expecting:
Immediately after running, the program should react to whatever key is pressed, and output:
Captured Key : T
Captured Key : E
Captured Key : S
. . . etc
What I am getting:
After running the program, the first keyboard input, acts as if it is NOT captured in Raw and it is captured and displayed on screen.
Then when I press the ENTER key, the text I just typed gets pushed to the handler function, AND THEN the program will accept further input in raw as expected.
Looks like as if the program requires an ENTER keystroke to initiate a proper raw mode input mode?
pic related: I typed TEST (ENTER). Then the program works as expected.
Anyone knows what is this all about? I can't find anything. Also I don't want to use any external libraries. Thanks!

Related

NodeJS blessed no key events

I am new to using the blessed library and so far, I could not get key events to work.
I would expect the following piece of code to print q whenever the Q key is pressed and Enter whenever the Enter key is pressed. It should also print keypress whenever any key is pressed.
const blessed = require('blessed');
const screen = blessed.screen({
smartCSR: true,
title: 'Title',
});
screen.key('q', () => console.log('q'));
screen.key('Enter', () => console.log('Enter'));
screen.on('keypress', () => console.log('keypress'));
screen.render();
The actual behavior is that if any "printable" key (such as alphanumeric characters) is pressed then that key is just written to the console (just as if it was typed regularly). keypress is not printed either.
The behavior is slightly different for the Enter key. Enter is still not being printed, but keypress is.
Is there anything wrong with my setup? I am using the default Gnome terminal under ArchLinux. However, that should not cause an issue because the program json-log-viewer, which is also blessed-based, works just fine.
The problem was with nodemon, fixed by passing the flag -I. See here.

Want to make Node Red on Raspberry Pi detected Data from Arduino and React to it but unsure how to do so?

I recently made a sensor that can correctly display the distances on the Serial Monitor on the Arduino, it would continuously display the distance as I would move my hand up/down the sensor. Thing is though, I intended on connecting this to a Pi (mine being Pi 3B+), use Node Red and basically have it detect that whenever the distance was "20cm" for example, then it would go straight to a YouTube video and play it. I tried researching all over the net to see if such had been done before, but to no avail as I found content much different than what I tried to pull off with Node Red and my Arduino.
I did try on my end to set up a function on Node Red to my Arduino, using a conditional statement to detect something and print something else out.
Overview of what I tried to do on Node Red
As you can see, there was not much to add as I was initially trying to test the conditional statement I made, making it output something on the debug screen using the code below:
Contents of the function created
var newMsg = {payload:msg.payload.toString()}:
if (newMsg == 'Distance: 20cm') {
newMsg = 'Distance is 20, nice'
return newMsg;
}
return newMsg;
Even with the little test I created to return a message to the debug did not work, so I'm not sure what I'm missing here.
First, you should not be creating new message objects as a rule, this breaks flows that use things like http-in/http-response nodes that require the original message to pass from start to end.
Second, you can't compare an Object to a String and get anything meaningful. The function node probably should looks something like the following:
if (msg.payload === "Distance: 20") {
msg.payload = "Distance is 20cm, nice"
return msg;
}
Third, the input message appears to be terminated with a new line character so the test should probably be:
if (msg.payload === "Distance: 20\n") {

Detect Key Press in System

I am trying to detect a keypress event outside the console tab, I have allready tried input-event (for linux), hotkeys-js (for browser), and iohook (gives error). How can I do it?
I found a way. I used iohook, but the version 0.6.6 since the new version crashed, and called the start method.
iohook.on('keypress', (res) => {
let key = String.fromCharCode(res.rawcode);
console.log(key);
});
iohook.start();

Weird node.js console.log() output behaviour when printing arrays

I have the following, somewhat simple code in VSCode(Mac OS) which I run in node.js v14.13.1 environment:
let fruits = ['Apple', 'Banana'];
let fruits1 = ['Apple1', 'Banana1'];
console.log(fruits);
console.log(fruits1);
The output behaviour seems very weird to me, it prints either:
(2) ['Apple', 'Banana']
or
(2) ['Apple', 'Banana']
(2) ['Apple1', 'Banana1']
or
(2) ['Apple', 'Banana']
Canceled
I couldn't find any particular pattern of printing (except for first two outputs are printed more often than the third one), so it seems as if it 'randomly decides' what to output.
This code, however, outputs always as expected when executed via Mac terminal(node my_file.js), i.e.:
[ 'Apple', 'Banana' ]
[ 'Apple1', 'Banana1' ]
Is that some kind of VSCode bug, or there is something about printing arrays with console.log() (with strings and integers it works just fine) what I don't take into account?
One solution you could try is to convert the array to a string when doing the console.log command:
let fruits = [['Apple', 'Banana'],['Apple', 'Banana']];
console.log(fruits.toString()); // Apple,Banana,Apple,Banana
console.log('' + fruits); // Apple,Banana,Apple,Banana
console.log(JSON.stringify(fruits)); // [["Apple","Banana"],["Apple","Banana"]]
I like the last one because it keeps this array displayed within brackets, even with multidimensional arrays.
However, one problem I found with this is when working with regular expression, there is addition output lost when converting to a string:
let str = 'xyz';
let pat = /y/;
let res = str.match(pat);
console.log(res); // ['y', index: 1, input: 'xyz', groups: undefined]
console.log(res.toString()); // y
console.log('' + res); // y
console.log(JSON.stringify(res)); // ["y"]
I believe this error may be occurring because the debugger is stopping before the output is sent to the debug console? Therefore For another solution, either add an empty line at the end of your code and add a breakpoint there; this seems to allow all the output to be generated when doing a multiple console.logs on arrays. Or, at the end of the code, add:
setTimeout(() => { }, 1000)
Which also seems to be adding enough time to properly output all the console.log of arrays. The advantage to the former is, you can expand the array details in the debug console, until you continue to the end of the code, but the con is you still have to chose to continue the code for it to end. The latter also allows you to expand the details of the object in the output, but only for the duration of the timer.
I also found, you can add either of these to your launch.json file (within the appropriate node configuration object, and don't forget to add a common to either the end the line before and/or the the end of either of these lines depending on where you are inserting):
"console": "integratedTerminal"
Or:
"console": "externalTerminal"
These send the output to either the VS Code terminal pane or an external cmd window.
And finally I also found instead of either of these console command, you can add this to the launch.json:
"outputCapture": "std"
This will keep the output in the debug console. It looks a bit different with color & some other messages, but seems to successfully output arrays.
I have the same problem. I think it is some kind of VSCode bug.
When I print the data in a event callback, console.log behave as expected. But after a while, the main thread exists and console.log output Canceled.
import some modules...
vtgeojson(tiles, { tilesOnly: true })
.on('data', function (data) {
featurecollection.features.push(data);
console.log(data)
})
.on('end', function () {
console.log(featurecollection);
console.log(featurecollection.features.length);
})
The problem disappears when I set the breakpoint and print the data line by line.
The problem also disappears when I run the script in the powershell.
Although the console.log is canceled, the data has been successfully pushed into the feature list. The behavior is most likely caused by the vscode terminal or the way that vscode handle the console.log command.
My node version is v12.20.0 and VSCode version is:
Version: 1.51.1 (system setup)
Commit: e5a624b788d92b8d34d1392e4c4d9789406efe8f
Date: 2020-11-10T23:34:32.027Z
Electron: 9.3.3
Chrome: 83.0.4103.122
Node.js: 12.14.1
V8: 8.3.110.13-electron.0
OS: Windows_NT x64 10.0.17763
I find someone else has a similar problem.
console.log() is “Canceled” when looping unattended
This seems quite interesting. I have tried running it multiple times and got the same result as output from Chrome's console:
["Apple", "Banana"]
["Apple1", "Banana1"]
The issue could be related either to the version of Node.js you are running on your computer or the terminal on the version of VSCode you have.
Because I tried running it from the VSCode terminal and got the same result:

Sending command to OBDII using Ionic 3 native bluetooth plugin

I'm trying to get data from OBDII using ionic native bluetooth plugin. However, when i called write method to send the command to the device, no data was returned. The code I used is as below:
readData(device){
this.bluetoothSerial.write('010D').then( (success) => {
alert('Connected to ' + device.name + '. Data reading is successful: ' + new Uint8Array(success));
},
(error) => {
alert('reading failed:' + error );
});
}
The result is shown as below:
My question is: what is the proper way to send command to OBDII to retrieve data using native plugin.
Try with "010D\r" where \r is a carriage return....and read the Hex response.
If you receive NoData means that or the sensor is not in the car or you send an incorrect command.
Remember that the ELM327 can manage one command per time, so you must use something like Queue for manage multi command.
PS:read some documentation about ELM327 and how it manage commands and configuration

Resources