i want to send message without Enterkey in node.js - javascript

AndroidPhone---------Raspberry Pi ------------Arduino
(server) (server) (bluetooth)
(bluetooth)
Now i can send message(0or1) from Android to Raspberry Pi by app
and i want to send this message to Arduino
However, when i play this code, message is not sent by bluetooth.
I think (stdin.process.on) is need input by enter.
but i cant. please help me
if (req.payload.toString() === '0') {
console.log('0');
process.stdin.on('data', function(data) {
var buf1 = Buffer.from(data);
serial.write(buf1,fuction(err, bytesWritten) {
if (err) console.log(err);
});
};
serial.on('data',function(data){ console.log('Received'+data);
});

If your code was copied and pasted, you should fix that misspelled "fuction" on line 5 first.
Edit:
i want to know how to use stdin.on without console input
Sorry, I don't know much about messaging between devices but process.stdin is meant specifically to read standard input, which means either console input or messages piped to your node process from another process' stdout.

Related

Required JSON file has old values from before running the program

I am writing a discord bot using javascript (discord.js).
I use json files to store my data and of course always need the latest data.
I do the following steps:
I start the bot
I run a function that requires the config.json file every time a message is sent
I increase the xp a user gets from the message he sent
I update the users xp in the config.json
I log the data
So now after logging the first time (aka sending the first message) I get the data that was in the json file before I started the bot (makes sense). But after sending the second message, I expect the xp value to be higher than before, because the data should have been updated, the file new loaded and the data logged again.
(Yes I do update the file every time. When I look in the file by myself, the data is always up to date)
So is there any reason the file is not updated after requiring it the second time? Does require not reload the file?
Here is my code:
function loadJson() {
var jsonData = require("./config.json")
//here I navigate through my json file and end up getting to the ... That won't be needed I guess :)
return jsonData
}
//edits the xp of a user
function changeUserXP(receivedMessage) {
let xpPerMessage = getJsonData(receivedMessage)["levelSystemInfo"].xpPerMessage
jsonReader('./config.json', (err, data) => {
if (err) {
console.log('Error reading file:',err)
return
}
//increase the users xp
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].xp += Number(xpPerMessage)
data.guilds[receivedMessage.guild.id].members[receivedMessage.author.id].stats.messagesSent += 1
fs.writeFile('./test_config.json', JSON.stringify(data, null, 4), (err) => {
if (err) console.log('Error writing file:', err)
})
})
}
client.on("message", (receivedMessage) => {
changeUserXP(receivedMessage)
console.log(loadJson(receivedMessage))
});
I hope the code helps :)
If my question was not precise enough or if you have further questions, feel free to comment
Thank you for your help <3
This is because require() reads the file only once and caches it. In order to read the same file again, you should first delete its key (the key is the path to the file) from require.cache

Node.js - Serverside Command Promp Commands input?

I´m writing a Web MMO with Node.js and for debug and maintenance reasons i would love to have the ability to open my SSH connection, where i also start my server, and write a command like "logout all".
So what are my options to get command prompt input and use it while my server runs?
Example:
I start my server with "node app.js" - server starts.
Now i want to write something into the command prompt - how do i get said input so i can use it in my code?
I was trying to read into node.js-readline but i cant seem to find much about it and everything that i found about it needs a "question" to be asked so it can get the input.
I would love to have something like this:
var command = getCommandlineInput(); //command = "logout all"
It need to get any input any time. A callback function would be good aswell, so i can direktly run it throu a checkCommand() function.
So i just figured out how to do this:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.on('line', (input) => {
useCommand(input);
});
function useCommand (input)
{
switch (input) {
case "show userlist":
CMD_showUserlist();
break;
}
}
First we initiate readline.
With readline.on we listen for any input you type into the command prompt.
useCommand() takes this input and chose what function to run.
How to work with the given input string is up to you, in my example i just made a hard coded command "show userlist".

Unable to get Notify data using Noble

Can't receive any notifications sent from the Server peripheral.
I am using ESP32 as Server with the "BLE_notify" code that you can find in the Arduino app (File> Examples ESP32 BLE Arduino > BLE_notify).
With this code the ESP32 starts notifying new messages every second once a Client connects.
The client used is a Raspberry Pi with Noble node library installed on it (https://github.com/abandonware/noble). this is the code I am using.
noble.on('discover', async (peripheral) => {
console.log('found peripheral:', peripheral.advertisement);
await noble.stopScanningAsync();
await peripheral.connectAsync();
console.log("Connected")
try {
const services = await peripheral.discoverServicesAsync([SERVICE_UUID]);
const characteristics = await services[0].discoverCharacteristicsAsync([CHARACTERISTIC_UUID])
const ch = characteristics[0]
ch.on('read', function(data, isNotification) {
console.log(isNotification)
console.log('Temperature Value: ', data.readUInt8(0));
})
ch.on('data', function(data, isNotification) {
console.log(isNotification)
console.log('Temperature Value: ', data.readUInt8(0));
})
ch.notify(true, function(error) {
console.log(error)
console.log('temperature notification on');
})
} catch (e) {
// handle error
console.log("ERROR: ",e)
}
});
SERVICE_UUID and CHARACTERISTIC_UUID are obviously the UUIDs coded in the ESP32.
This code sort of works, it can find Services and Characteristics and it can successfully connect to the peripheral, but it cannot receive messages notifications.
I also tried an Android app that works as client, from that app I can get all the messages notified by the peripheral once connected to it. So there is something missing in the noBLE client side.
I think there is something wrong in the on.read/on.data/notify(true) callback methods. Maybe these are not the methods to receive notifications from Server?
I also tried the subscribe methods but still not working.
The official documentation is not clear. Anyone could get it up and running? Please help.
on.read/on.data/ are event listeners. There is nothing wrong with them. They are invoked when there is a certain event.
For example adding characteristic.read([callback(error, data)]); would have invoked the on.read.
From the source:
Emitted when:
Characteristic read has completed, result of characteristic.read(...)
Characteristic value has been updated by peripheral via notification or indication, after having been enabled with
characteristic.notify(true[, callback(error)])
I resolve using the following two envs NOBLE_MULTI_ROLE=1 and NOBLE_REPORT_ALL_HCI_EVENTS=1 (see the documentation https://github.com/abandonware/noble)

Input through node JS in Terminal

I am trying to make a program in Node.JS that will display some text, using console.log("");, then wait for the user to input some commands. First of all, I want to run this through the Linux Terminal on Cloud9 IDE, which does not pause long enough to input anything. Second of all, I want it to be like its own little command line. (I mean respond to certain case-sensitive commands, and ignore anything else.) Can anyone help with this?
Check out prompt. https://www.npmjs.com/package/prompt It works like:
var prompt = require('prompt');
prompt.start();
prompt.get(['hello'], function (err, result) {
console.log('you typed ' + result.hello);
});
Will do:
$ nodejs prompt.js
prompt: hello: world
you typed world
Happy coding ^^

Alertifyjs alerts shown to the person who triggered it

As a disclaimer, I'm new to nodejs and express framework in general so please bear with me while I'm still trying to learn.
I'm using alertifyjs library to show notifications for various alerts to a user. Now, the problem is that the notifications are showing for everyone who is on the site. I get why this is happening and it makes sense. How do I go about making it so a specific alert only shows for the person that triggered it? What exactly do I use to make this happen? Cookies?
Thank you for your help and let me know if you need any more information.
Here's a code example...
//client code
socket.on('word length', function(data) {
alertify.error('Check word length!');
});
//server code
if (word.length > 50 || word.length <= 1) { // check word length:
io.sockets.emit('word length', word);
}
This is nothing to do with alertify but more to do with how socket.io works. The io.socket.emit call will broadcast a message to all connected sockets.
You want to call emit on the client socket only
io.on('connection', function (socket) {
io.socket.emit('message', 'to everyone');
socket.emit('message', 'to this client only');
});

Categories