NodeJs Buffer CRLF - node.js

I want to use Nodejs bluetooth-serial-port plugin and Buffer to send "be\r\n" to my Bluetooth device. (It's works only with that)
With this Android tool it's working.
The problem is my Bluetooth device can't recognise the message.
Here is my code:
var btSerial = new (require('bluetooth-serial-port')).BluetoothSerialPort();
btSerial.connect(device, channel, function () {
var data = new Buffer('be\r\n', 'utf-8');
console.log('connected, sending: ' + JSON.stringify(data.toString('utf-8', 0, 4)));
btSerial.write(data, function (err, bytesWritten) {
if (bytesWritten) {
console.log("writed: " + bytesWritten);
btSerial.close();
console.log("disconnected.");
}
if (err) console.log(err);
});
btSerial.on('data', function (buffer) {
console.log(buffer.toString('utf-8'));
});
}, function () {
console.log('cannot connect');
});
And the output:
connected, sending: "be\r\n"
writed: 4
disconnected.

Finally I found the solution: The Bluetooth agent must run to work with bluetooth-serial-port, and also the encoding have to be ASCII.

Related

WebSocket to Serial bridge, send control chars like `\r\n` does not work

Im developing a WebSocket to Serial bridge.
The WebSocket server send some commands that are writen 1:1 to the serial device.
const { WebSocket } = require("ws");
const { autoDetect } = require("#serialport/bindings-cpp");
const { SerialPort } = require("serialport");
const binding = autoDetect()
const ws = new WebSocket("ws://example.com");
ws.on("open", () => {
console.log("WebSocket connected to:", ws.url);
const port = new SerialPort({
binding,
path: "/dev/ttyUSB0",
baudRate: 19200,
});
ws.on("message", (chunk) => {
console.log("From server", chunk);
port.write("sw i03\r\n"); // this works!
port.write(chunk) // this does not!
});
port.on("data", (data) => {
console.log("From port", data);
ws.send(data);
});
});
The messages string that comes from the server is sw i02\r\n.
Message format is the following, "sw i0\r\n", where <n> is a number between 1 - 8.
The problem is, \r\n is not interpreted as newline/control char, but literally as "\r\n" and not the control character they should represent.
Why does the serial device not recognize the message from the WebSocket as correct command, but when i rewrite it to a static port.write("sw i03\r\n")?
I simply dont understand whats the difference between the message from the WebSocket and the static port.write(..) i used to test.
The serial device is a Aten 8 port HDMI Switcher (VS0801H): https://www.aten.com/us/en/products/professional-audiovideo/video-switches/vs0801h/
EDIT/Workaround:
I changed the code/command payload, so now control character are stored in the backend/server side anymore and add them later on the "client"/serial side:
ws.on("message", (chunk) => {
console.log("From server", String(chunk));
port.write(`${chunk}\r\n`); // chunk = "sw i0<n>"
});
If any one know how to handle my problem, please let me know.
The solution i cam up with, feels more like a hack than a real problem solving solution.

How to execute a NestJs TCP Microservice command by nodeJs

I have a working Microservice(MS) based on https://docs.nestjs.com/microservices/basics using a TCP protocol. Executing a command from my NestJS API was easy by implementing the #nestjs/microservices Client.
Now im working on a Lambda (AWS) in plain nodeJs, this lambda contains a function that also need to send a command to the MS. I tried using net to create a Socket to send a command (stringified) but it doesn't trigger anything.
my example nodeJs code:
const net = require('net');
const saveProducts = (products) => {
let socket = new net.Socket();
socket.setEncoding('UTF8');
socket.on('data', function (data) {
console.log('ON DATA'); // print out data
console.log(data.toString()); // print out data
});
socket.connect(options.port, options.host, function () {
//called when connection is created
const command = JSON.stringify({ pattern: { cmd: 'update-many', ctrl: 'product' } });
socket.write(command, 'UTF8', function (err) {
console.log(err);
});
});
}
I have used a network sniffer to get an example message structure..
similar issue but the suggestion is only to add #nestjs/microservices, I was wondering how to do it without it.
After some long research found out what the pattern is what you need to send:
[MSG_LEN]#{ pattern: "[PATTERN_STRING]", data: "[DATA]", id: "[ID]" }
Example:
62#{"pattern":"find","id":"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4"}
The parameter id is for #MessagePattern, without it #EventPattern will be triggered.

Gphoto2 node ### An error occurred in the io-library ('Could not claim the USB device')

I am Working on Connectivity between RaspberryPi 3 and DSLR Camera (Canon 1300 D). When I run command for capture image , first time is working and when I run again I am having following issue:
An error occurred in the io-library ('Could not claim the USB device'): Could not claim interface 0 (Device or resource busy). Make sure no other program (gvfs-gphoto2-volume-monitor) or kernel module (such as sdc2xx, stv680, spca50x) is using the device and you have read/write access to the device.
Please give me solution for "How to communicate Raspberry Pi 3 with DSLR using NodeJs ?"
Code Example:
app.post('/onDemand', function(req, res) {
GPhoto.list(function (list) {
console.log('List:', list);
if (list.length === 0) return;
var camera = list[0];
camera.takePicture({download: true,keep: true}, function (er, data) {
fs.writeFileSync(__dirname + '/input/picture1.jpg', data);
var filePath = "./input/picture1.jpg";
var params = {
Bucket: 'marzs',
Body : fs.createReadStream(filePath),
Key : "marzs/"+Date.now()+"_"+path.basename(filePath)
};
s3.putObject(params, function (err, data) {
if (err) {
console.log('ERROR MSG: ', err);
res.status(500).send(err);
} else {
console.log('Successfully uploaded data');
res.status(200).send({ imageURL: data.Location });
}
res.status(200).send({ imageURL: data.Location });
});
});
});
});
Thanks in Advance.
Yogesh Waghmare
We need to install libusb on server and run following command.
gphoto2 --get-config=capturetarget
gphoto2 --set-config=capturetarget=1
gphoto2 --set-config shutterspeed=bulb
gphoto2 --wait-event=2s --set-config eosremoterelease=Immediate --wait-event=5s --set-config eosremoterelease=Off --wait-event-and-download=5s
After that we need to exit process with "process.exit();" after completion of process. and run via forever command
now code running properly.
Thanks & Regards,
Yogesh Waghmare

Serialport module in node.js works only if minicom is active on the port

I am using version 3.10 of the serialport module of Node.js.
I have a GSM modem attached to an Ubuntu machine's serialport and I am sending SMS through the modem. Here is the simplified code:
var serialPort = require("serialport");
const Readline = serialPort.parsers.Readline;
var portSerial = new serialPort("/dev/ttyUSB1", {
baudrate: 115200,
dataBits:8, stopBits:1, parity: 'none'
}, function (err) {
if (err)
//log error here
});
parser = new Readline();
portSerial.pipe(parser);
portSerial.on("open", function(err) {
if (err)
return console.log("Error in opening serial port");
console.log("Port opened");
});
portSerial.on('error', function(err) {
//log error
})
//Send SMS
setTimeout(function() {
portSerial.write('AT+CMGF=1\nAT+CMGS="'+SMSphone + '"\n' +
SMSmessage + '\032');
}, 1000);
Yes, I am setting SMSphone and SMSmessage variables. And the code is actually a bit more complex but the core code for sending SMS is as shown above.
PROBLEM: All works fine if I am running minicom when the SMS is sent. The moment I exit minicom, the SMS do not go out. portSerial.write stops working.
It was all working fine until I upgraded the serialport version.

Serial Port not working after disabling login shell

I'm trying to write a small program in node.js to communicate over serial port. I'm using node.js for that with a sample code like that:
var SerialPort = require("serialport");
var serialPort = new SerialPort("/dev/ttyAMA0", {
baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function (data) {
console.log('data received: ' + data);
});
setInterval(function () {
serialPort.write(new Buffer('4', 'ascii'), function (err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
}, 1000);
});
This is however not working at all after i disable the login shell over serial port serial port in raspi-config. After that i'm unable to send/recieve any data.
I connected pin 8 with pin 10 to create a self-loop and tried using minicom to send something over it with no success as well.
I checked the /boot/config.txt and enable_uart is set to 1.
I also checked the /boot/cmdline.txt and there are no entries with AMA0 port.
Can anybody provide me with a solution to this problem?
For anyone looking for solution - this did it for me and opened a serial port.
https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=159984&p=1039065#p1039065

Resources