Convert ASCII to Base64 then Binary with NodeJS - node.js

I'm trying to convert a text string AAIA to binary. This is how Salesforce manages dependent picklists.
I essentially need to go from ascii to base64 to binary, but I think the binary needs to be bytes, not text.
Expected result is AAIA => 00000000 00000010 00000000, which means 15th item in my other list controls this one. I can't figure out how to make this work in Node! Using the above mentioned values on this site works, but no luck in Node.

You want to convert a string to binary.
You want to convert a string value of AAIA to 00000000 00000010 00000000.
You want to achieve this using Node.js.
If my understanding is correct, how about this answer?
Sample script:
In this sample, there are the outputs of 3 patterns.
const str = "AAIA";
// Pattern 1
const buf = Buffer.from(str, 'base64');
console.log(buf); // <--- <Buffer 00 02 00>
// Pattern 2
const byteAr = Uint8Array.from(buf);
console.log(byteAr); // <--- Uint8Array [ 0, 2, 0 ]
// Pattern 3
const result = buf.reduce((s, e) => {
const temp = e.toString(2);
return s += "00000000".substring(temp.length) + temp + " ";
}, "");
console.log(result); // <--- 00000000 00000010 00000000
References:
Buffer.from(string[, encoding])
Uint8Array
toString()
If I misunderstood your question and these were not the results you want, I apologize.

Related

extracting and formatting a macAddress from buffer

I am trying to extract and format a mac address from a buffer as 00:04:a3:01:02:90
> const buffer = Buffer.from([0x00,0x04,0xa3,0x01,0x02,0x90]);
> console.log(buffer)
<Buffer 00 04 a3 01 02 90>
> console.log (buffer.slice(0, 6).map(byte => byte.toString(16).padStart(2, '0')).join(':'));
0:4:0:1:2:90
The output I am getting is removing the leading 0s and incorrectly displaying the third hex element 0xa3.
How do I correctly extract and format the bytes the mac address -> 00:04:a3:01:02:90?
Converting buffer into HEX string and then some string manipulation can give you the expected MAC Address. Try this script:
const buffer = Buffer.from([0x00,0x04,0xa3,0x01,0x02,0x90]);
const bufferString = buffer.toString('hex')
const macAddress = bufferString.split(/(..)/).filter(s => s).join(":")
console.log(macAddress)

Read DTC codes OBD2 using arduino

I try read dtc codes using a obd device (sparkfun obd based on stn1110) and an arduino. Running this code
uint16_t codes[6];
byte dtcCount = obd.readDTC(codes, 6);
if (dtcCount == 0) {
Serial.println("No DTC");
} else {
Serial.print(dtcCount);
Serial.print(" DTC:");
for (byte n = 0; n < dtcCount; n++) {
Serial.print(' ');
Serial.print(codes[n], HEX);
}
Serial.println();
}
delay(5000);
}
Returns:
2 DTC: 3303 100
How can I interpret those codes? I mean usually I saw error codes are like PXXXX ...
Thanks a lot
L.E.
I scanned same car using a "proffesional" tester and found following codes (see pictures).
What I am doing wrong with my code or how should I interpret my results in order to get same codes as the service scanner?
Basically my code show 2 dtc's but the scanner found 5 in total
Dig further and I think the function used for read dtc is somehow wrong:
this is the function
byte COBD::readDTC(uint16_t codes[], byte maxCodes)
{
byte codesRead = 0;
for (byte n = 0; n < 6; n++) {
char buffer[128];
sprintf_P(buffer, n == 0 ? PSTR("03\r") : PSTR("03%02X\r"), n);
write(buffer);
if (receive(buffer, sizeof(buffer)) > 0) {
Serial.print("received buffer :");
Serial.println(buffer);
if (!strstr_P(buffer, PSTR("NO DATA"))) {
char *p = strstr(buffer, "43");
if (p) {
while (codesRead < maxCodes && *p) {
p += 6;
if (*p == '\r') {
p = strchr(p, ':');
if (!p) break;
p += 2;
}
uint16_t code = hex2uint16(p);
if (code == 0) break;
codes[codesRead++] = code;
}
}
break;
}
}
}
return codesRead;
}
As you see I printed "received buffer" to see what I get from OBD and the result is:
received buffer :43 01 33 03 01 00 00
>
I think is something wrong here, or I miss something in the answer
why i get that">" on a new line?
also according to https://en.wikipedia.org/wiki/OBD-II_PIDs (chapter Service 03 (no PID required))
i delete "43" from my buffer and get "01 33 03 01 00 00"
then "01" means "C - Chassis"
but then nothing match to the decoding description...so I became almost sure that I don t ask / read as it should this thing. I think i get an invalid answer somehow ...
Again any help will be appreciated :)
Thanks
L.E.2 - did another progess step.
According to this document - https://www.elmelectronics.com/wp-content/uploads/2016/07/ELM327DS.pdf , on page 34
first should find out the number of dtc stored and then try to read them.
Sending >0101 to obd return me "41 01 82 07 61 01"
and if I do 82 - 80 => I have 2 trouble codes ?!?! why I have 5 of them on the tester?
From my previous response, also according to that document
"43 01 33 03 01 00 00" means P0133 and P0301
But on the tester, except those 2, I had also - P0303 , P0300 and C1513
How to get to read correctly the dtc codes?
Thanks again

node.js Buffer from Uint16Array

const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);
console.log(buf1, buf2 );
// Prints: <Buffer 88 a0>
// Prints: <Buffer 88 13 a0 0f>
i look at the nodejs document where i see that
and my question is why buf1 is not <Buffer 88 13 a0 0f> ?
It is explained here that Buffer.from behaves as new Uint8Array() which can only contain numbers from 0 to 255 (1 byte) and here is stated that each value is converted and the result array length will be the same (so it can't have 4 elements). When converted, 2 byte value will be trimmed to 1 byte value, ignoring the second byte (88 13 -> 88, a0 0f -> a0).

How to convert to ascii using node.js

I am trying to convert length message to ascii.
My length message is like
var ll = "0170";
In node js , is there some kind of function which converts into ascii?
Please help?
Here's a simple function(ES6) which converts a string into ASCII characters using charCodeAt()
const toAscii = (string) => string.split('').map(char=>char.charCodeAt(0)).join(" ")
console.log(toAscii("Hello, World"))
Output:
-> 72 101 108 108 111 44 32 87 111 114 108 100
You could create a prototype function aswell. There are many solutions :)
you can't have an ascii code for a whole string.
An ascii code is an integer value for a character, not a string. Then for your string "0170" you will get 4 ascii codes
you can display these ascii codes like this
var str = "0170";
for (var i = 0, len = str.length; i < len; i++) {
console.log(str[i].charCodeAt());
}
Ouput : 48 49 55 48
use charCodeAt() function to covert asscii format.
var ll = "0170";
function ascii (a) { return a.charCodeAt(); }
console.log(ascii(ll[0]),ascii(ll[1]), ascii(ll[2]), ascii(ll[3]) )
result:
48 49 55 48

how to convert node Buffer to string like console.log show

I want log the buffer to string, but I am not want to use buffer.toString() method
console.log(new Buffer(12))
show
< Buffer 00 22 33 11 55 ...>
but console.log('buffer:' + new Buffer(12))
show
buffer: something can't read
I want
buffer: < Buffer 00 22 33 11 55 ...>
Doing
var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log(b);
// <Buffer 41 42 43 44>
is the same as doing
console.log(b.inspect());
whereas
var b = new Buffer([0x41, 0x42, 0x43, 0x44]);
console.log('str' + b);
// strABCD
is the same as doing
console.log('str' + b.toString());
because using string concatenation using + automatically converts both sides of the operator to strings using .toString(). console.log(...) on the other hand converts its arguments to strings by calling .inspect() when possible.
The easiest way to do what you want to do is to just let console.log do its thing by passing it multiple arguments
console.log('buffer:', new Buffer(12))
Note, the , instead of a +, so instead of concatenating using .toString, you let console.log stringify each of its arguments on its own.

Resources