Bad data received from Arduino serial while reading from analog port - javascript

Maybe this is just a nonsense, but it's driving me crazy. I'm trying to read one analog port in Arduino and send the value through the serial port to JavaScript using node. When I show the data in the Arduino console, everything works fine, but when I use the terminal in Mac, some values appear splited in two lines.
460
460
4
60
460
The code I'm using is:
Arduino:
const int analogInPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(500000);
}
void loop() {
sensorValue = analogRead(analogInPin);
Serial.print(sensorValue);
delay(200);
}
Node:
var com = require('serialport').SerialPort;
var opts = {baudrate: 500000};
var serialPort = new com('/dev/tty.usbmodem641', opts);
serialPort.on('data', function(data) {
console.log(data.toString());
});
The code couldn't be simpler, but still doesn't work properly. I know I'm missing something but I can't see it. I have tested different baudrates, but nothings works. Could you please help me?
Thanks in advance

I think maybe Elias Benevedes is trying to suggest this in their answer: right now your Arduino data is not delimited at all. Suppose your sensorValue always reads as 1. In this case the output from Arduino will be
11111111111111111111111111111111111111111111111111111111111....
And so on; because you print the integer value without any delimiters. The way it is parsed into different numbers, therefore, has to do with the timing of the arrival of the data. Continuing with the example above then, sometimes your value is read as 1, sometimes as 11, sometimes as 111 and so on, just depending on the timing of the reads and the writes.
The way to begin to fix it is to insert some non-numeric data between your sensor reading outpus. One (again, this is perhaps what Elias Benevedes has in mind) is to insert line breaks between every number printed
Serial.println(sensorValue);
Another way would be to add spaces between the data
Serial.print(sensorValue);
Serial.print(" ");
Either solution would separate your numeric readings from each other, which is what you want.

I had this happen to me once also. Serial.print() sends data to the arduino. Serial.println() will send information from the arduino to the computer Serial message board (or whatever you want to call it.

Related

Node - safest way to execute code from a string during runtime

My Node app gets an HTML page via axios, parses it via htmlparser2 then sends the valuable information to a frontend JS app as JSON.
The HTML page has some JavaScript in it that creates an array, and I need to work with that array in my code. htmlparser2 gets the content of the script as a string. I have two options to handle it as far as I know:
Write a parser that goes through the string and extracts the required info (doable, but complicated)
Run string as some JavaScript code and handle the values from that.
Assume I want to go with option 2. According to this StackOverflow question, using Node's VM module is possible, but the official documentation says "The node:vm module is not a security mechanism. Do not use it to run untrusted code."
I consider the code in my use case untrusted. What would be a safe solution for this?
EDIT: A snippet from the string:
hatizsakCucc = new Array();
hazbanCucc = new Array();
function adatokMessage(targyIndexStr,tomb) {
var targyIndex = parseInt(targyIndexStr);
if (tomb.length<1) alert("Nincs semmi!");
else alert(tomb[targyIndex]);
}
hatizsakCucc[0]="Név: ezüst\nSúly: 0.0001 kg.\nMennyiség: 453\nÖsszsúly: 0.0453 kg.\n";
hatizsakCucc[1]="Név: kaja\nSúly: 0.4 kg.\nÁr: 2 ezüst\nMennyiség: 68\nÖsszár: 136 ezüst\nÖsszsúly: 27.2 kg.\n";
hatizsakCucc[2]="Típus: fegyver\nNév: bot\nSúly: 2 kg.\nÁr: 6 ezüst\nMin. szint: 1\nMaximum sebzés: 6\nSebzés szórás: 5\nFajta: ütő/zúzó\n";
hatizsakCucc[3]="Típus: fegyver\nNév: parittya\nSúly: 0.3 kg.\nÁr: 14 ezüst\nMin. szint: 1\nMaximum sebzés: 7\nSebzés szórás: 4\nFajta: távolsági\n";
hatizsakCucc[4]="Név: csodatarisznya\nSúly: 4 kg.\nÁr: 1000 ezüst\nExtra: templomi árú\n";
hatizsakCucc[5]="Név: imamalom\nSúly: 5 kg.\nÁr: 150 ezüst\nExtra: templomi árú\n";
The whole string is about 100 lines of this, so it's not too much data.
What I need is the contents of the hatizsakCucc array. Actually, getting an array of that it not too difficult with a regex, I'm realizing now.
hatizsakSzkript.match(/hatizsakCucc(.*)\\n/g);
This gives me an array of the hatizsakCucc elements, so I guess my problem is solved.
That said, I'm still curious about the possibility of running "untrusted" code safely.
Further context:
I plan parse each array element so it will be an object, the object elements will be the substring separated by the \n-s
So the expected result for the first array element will be:
hatizsakCucc[0]{
nev: "ezüst",
suly: 0.0001,
mennyiseg: ...
}
I'll write a function that splits the string to substrings at the \n then parse the data with a match().

DiscordJS: Check if input is in a string

Hello!
I will try to do my best as possible to explain this issue i have.
A bin with some of the code mentioned, with comments:
Codebin
I am currently working on a Discord bot, where there is data stored in a .json file (As string).
Maybe this should be converted to an array instead?
A user writes a command and the bot initializes a sequence where it will go through several options depending on whats found in the string.
I've been struggling with this far too long (atleast 10 hours now & i am severely out of ideas now) on getting a check in for user response, to see if the input he does is in the array.
If i write !color 76561197458345 - it starts the process as seen below:
As you see the Available Options for found Dino (Carnotaurus) is:
[Utah1, Utah2]
Which is correct since its listed as the detailcrest options for Carnotaurus below in my json
[
{
"name": "Acrocanthosaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
},
{
"name": "Carnotaurus",
"detailcrest": "[Utah1, Utah2]",
"underbelly": "[Utah3, Utah4]",
"body1": "[Utah5, Utah6]",
"body2": "[Utah7, Utah8]",
"body3": "[Utah9, Utah10]"
}
]
What then happens is that the user is gonna give a input based on the options found (This case Utah1, Utah2).
I want the bot to check the response from user in chat, if his answer is existing in the json file.
If respond to the bot in chat with Utah1 - it would proceed to next question (Because it exists).
If respond to the bot in chat with Pizza2 - it would respond (Not found, please select available options)
TL;DR:
I simply need a way to check if user response (word) is existing in the string
If Yes: continue, If No: error
I hope someone can give tips, or atleast push in the right direction on how to procceed with this.
I found a simple, but obviously not the most smart answer to my own solution - however it works as expected.
I've changed my .json strings to simply not include any brackets
"detailcrest": "Utah1, Utah2",
To search through my string i applied a .split() function (to seperate words with ,)
const inputCheck = color.detailcrest.toLowerCase().split(',').includes(detailcrest);
If i then do a if else statement on it, it returns true or false - for the given input, if it exists in the json file.
if (inputCheck === true) {
console.log("found")
} else {
console.log("False")
}
Obviously this wouldn't be the smartest way to proceed in a professional
But in my little bot it should work out with what is expected.
Due to limits, i will accept my own answer as solution in two days.

Node console.log on large array shows "... 86 more items"

I'm new to puppeteer. I used to have PhantomJS and CasperJS but while setting a newer server (freebsd 12) found out that support for PhantomJS is gone and CasperJS gives me segmentation faults.
I was able to port my applications to puppeteer just fine but ran into the problem that when I want to capture data from a table, this data seems to be incomplete or truncated.
I need all the info from a table but always end up getting less.
I have tried smaller tables but it also comes out truncated.
I don't know if the console.log buffer can be extended or not, or if there is a better way to get the values of all tds in the table.
const data = await page.$$eval('table.dtaTbl tr td', tds => tds.map((td) => {
return td.innerHTML;
}));
console.log(data);
I should be able to get all rows but instead I get this
[ 'SF xx/xxxx 3-3999 06-01-16',
'Sample text - POLE',
'',
/* tons of other rows (removed by me in this example) <- */
'',
/* end of output */ ... 86 more items ]
I need the 86 other items!!!
because I'm having PHP pick it up from stdout as the code is executed.
Why console.log does not work
Under the hood, console.log uses util.inspect, which produces output intended for debugging. To create reasonable debugging information, this function will truncate output which would be too long. To quote the docs:
The util.inspect() method returns a string representation of object that is intended for debugging. The output of util.inspect may change at any time and should not be depended upon programmatically.
Solution: Use process.stdout
If you want to write output to stdout you can use process.stdout which is a writable stream. It will not modify/truncate what you write on the stream. You can use it like this:
process.stdout.write(JSON.stringify(data) + '\n');
I added a line break at the end, as the function will not produce a line break itself (in contrast to console.log). If your script does not rely on it you can simply remove it.
You can also use
console.log(JSON.stringify(data, null, 4));
instead of
process.stdout.write(JSON.stringify(data) + '\n');
I know the question is from a couple of years ago, but this has been an issue I've seen time and time again. Discovering (through this thread) the underlying util.inspect call has helped me to overcome this issue in the following way:
process.stdout.write(`${util.inspect(data, { maxArrayLength: 1000 })}\n`)
By default maxArrayLength is 100 which is why the data is truncated for longer arrays.
Do you absolutely have to use stdout? It's not recommended to do that for monitoring because it's very easy for stdout to overrun the buffer (or have incomplete output) - as you've seen illustrating the problem.
Why not modify the PHP script to read from a file as a stream using the readfile function, and write to that stream from your JS code using fs?
https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_class_fs_writestream
https://www.php.net/manual/en/function.readfile.php

DiscordAPIError Invalid Form Body when Trying to Purge Messages

So I was pretty sure that this code worked correctly at one point, but recently it was brought to my attention that it sometimes works but not always (read: It will always purge my messages by n amount, but it might not purge another members).
Because I was teaching myself how to use multiple files on this project, the code is actually split between two files. I'm not sure if that has anything to do with the issue or not. Given the size of the two files, I've uploaded them both to pastebin.
The command code.
The Function code.
It purges just fine when I try and purge n where n is any number within the acceptable range, but when I try and purge n by username I get an error message stating
DiscordAPIError: Invalid Form Body
limit: Value "" is not int.
(note that is two double quotes, the formatting is a little unclear)
I'm confused as to where it is getting a value that is not an int, as I'm running the amount through praseInt. I've snipped out the code segment that checks if a user is defined and posted it below as I believe it to be the problem:
if (user) { // If User is Provided
debug.run(`Filtering messages by ${user.username}`);
const filterBy = user ? user.id : client.user.id;
messages = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
}
Any assistance would be greatly appreciated. I'm more or less about to scrap the user feature if I can't figure it out.
Also I apologize for the formatting. I can never get the hang of this sites formatting.
Try getting rid of
.array().slice(0, amount).
The array of fetched messages doesn't need to be cut by the amount variable if the message.channel.fetchMessages({ limit: amount }).then((messages) => { line already limits it.

html5 websockets and long strings

I have a websocket HTML5 page that receives data from the server, but curiously the onmessage event seems to fire multiple times for long strings.
w.onmessage = function(e) {
console.log ("\n\n message received... "+e.data);
}
If I have a string 3000 characters long, the above code will print out the first 2048 characters and then whatever is left over on the second time around.
Is there anyway for me to check for something like (pseudo-code) (e.state == FINISHED) or (e.state != UPDATING) or something so I don't execute my code until I have all of the data? Right now, the onmessage function is getting called multiple times when it receives a message and this is messing up the code.
Can you split the string in the server side? Add some thing at the end to indicate that there are more characters behind.

Categories

Resources