Transmit collection of information to mqtt using Node.js

I'm facing an issue with sending an array of data from my node to the MQTT server.

Although I have a receive function that is working fine, I'm unable to get it working in the opposite direction.

  var message = new Array();
  message[0]  = 108;
  message[1]  = 11;
  client.publish("/topic", message, {
            retain: false,
            qos: 0
        });

However, I keep receiving the following error:

[ERROR] TypeError: invalid data

I'm unsure of how to properly declare the array in order to populate it with data and send it. In my receive function, the message variable is passed as an argument and I can access it as an array: message[x]...

Answer №1

When working with mqtt, you have the option to use Buffer or String data types.

If you need to use typed arrays, you will first need to convert them to buffers. You can achieve this by using the npm module available at https://www.npmjs.com/package/typedarray-to-buffer.

var toBuffer = require('typedarray-to-buffer')
  var message = [];
  message[0]  = 108;
  message[1]  = 11;
var arr = new Uint8Array(message)
arr = toBuffer(arr)

/*
arr.toString()  // '\u0001\u0002\u0003' 
arr.readUInt16BE(0)  // 258 
*/
// The array has been successfully converted to a buffer! 
  client.publish("/topic", arr, {
            retain: false,
            qos: 0
        }, function(){
  console.log("message published"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterate over the associative array obtained from mysqli_fetch_assoc using a loop

As a novice in the world of web development, I find myself struggling with a particular problem. The task at hand is to retrieve a list of videos along with their corresponding tags. Within my database, I have three tables - one for videos, one for tags, a ...

A Guide on Displaying Values Saved as Arrays in MySQL

Hello, I am currently using a MYSQL database to store form data and PHP to retrieve and display the information. Recently, I added a checkbox that stores its values as an array. However, when I echo the database content, I get outputs like: Name, Date, Ar ...

Efficient State Management with React-Redux for Streamlined HTTP Requests

In the process of developing a React-Redux application, I have encountered a situation where I need to display a cancel button while a specific HTTP request is ongoing. Upon successful execution of the request, the UI should display the results. If the use ...

Executing an onscroll function based on window.innerWidth in JavaScript

I want to trigger my scroller function only when the window width exceeds 599 pixels and the user is scrolling. The function itself works fine during scrolling, but adding an event listener seems to cause it not to work. Can anyone offer guidance on how ...

The $watch feature in AngularJS does not function properly within a directive when a controller is used to update data

I created a custom directive and also have a controller to bind data to the directive. The data is retrieved from the server and bound to the directive. However, I noticed that the data in the directive on the page does not update when I change the scope ...

jQuery document.ready not triggering on second screen on Android device

Why is jQuery docment.ready not firing on the second screen, but working fine on the first/initial screen? I also have jQuery Mobile included in the html. Could jQuery Mobile be causing document.ready to not work? I've heard that we should use jQuery ...

Transforming S3 Buffer Information into a PDF Document

Utilizing an express route to fetch the s3 object through the AWS SDK: router.get('/myRoute', (req, res) => { const s3 = new AWS.S3({apiVersion: '2006-03-01'}); s3.getObject({Bucket: 'my-bucket', Key: 'my-key'}, ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Remove nested comments using Ajax

I'm encountering a problem while attempting to delete my comments using Ajax. I believe I am on the right track but could use some guidance. Still in the process of familiarizing myself with jquery and similar technologies. While I can remove the comm ...

The occurrence of Multiple Button events leads to an error message stating: "Uncaught TypeError: Cannot read property 'remove' of undefined"

I am struggling to add an EventListener to each Delete Button (1,2,3) as I keep encountering an error that says "add" is undefined. Do you have any suggestions on how to fix this issue? My goal is to display a confirmation window when the DELETE button is ...

An external script containing icons is supposed to load automatically when the page is loaded, but unfortunately, the icons fail to display

Hello and thank you for taking the time to read my query! I am currently working in a Vue file, specifically in the App.vue where I am importing an external .js file containing icons. Here is how I import the script: let recaptchaScript2 = document.creat ...

Limit the number input to only allow values between 0 and 100

I am utilizing the Number input component from MUI, which includes Increment and Decrement buttons for adjusting numbers. Is there a method to limit the input to only accept values ranging from 0 to 100 ? Additionally, how can I decrease the width of the ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

Sharing data between child and parent components, and then passing it on to another child component in React Js

I have a scenario where I am passing props from a child component B to parent component A, and then from parent component A to child component C. Everything works fine when I pass the data from component B to A, but I encounter an issue when I try to set a ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...

"Can you please show me how to create a hover effect on a button when it

To change the image on button click "Click here to change image with hover effect" with the current hover effect (using this library) without the hover effect, follow these steps. The example is hosted on my server because jsfiddle does not support WebGl. ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

Maximizing Content Width in FullCalendar v5 to Ensure Screen Compatibility

As I develop a calendar and timeline view using fullcalendar v5, my clients are requesting a month view that displays the entire month without any scroll bars. While I am aware of setting the contentHeight to auto, there seems to be no option for adjusting ...

Having trouble setting up an input tag to successfully submit the form and trigger the opening of a BootStrap Modal

Is there a way for me to submit a form to my servlet and open a BootStrap Modal simultaneously using an input tag in my .jsp file? I've tried setting the input tag type to "button" but then I can't submit the form. And when I set it to "submit", ...

$q.all - successfully resolving some HTTP requests while encountering errors on others

I encountered a coding scenario like this angular.forEach(config.tvshows.shows, function(show) { promises.push($http.get('http://epguides.frecar.no/show/' + show.replace(/\s|\./g, '') + '/next/')); }); re ...