0

I am trying to publish few real time values using MQTT javascript. Here below I need set proper JSON format values. Here I can send only one value for all buses but I need to send Seperate buses seperate values. How to do that.

My Current Code:

var data = {
    Buses: "BusA", "BusB", "BusC",
    Speed: BusA_minspeed + (BusA_maxspeed - BusA_minspeed) * Math.random(), // It should be use seperate values seperate Buses
    FL: BusA_minfl + (BusA_maxfl - BusA_minfl) * Math.random()
};

My Expectations:

Buses  Speed FL
BusA    123  80
BusB    231  40
BusC    124  50

My Publishing Part

function publishTelemetry() {
    data.Speed = genNextValue(data.Speed, BusA_minspeed, BusA_maxspeed);
    data.FL = genNextValue(data.Fl, BusA_minfl, BusA_maxfl);
    client.publish('v1/devices/me/telemetry', JSON.stringify(data));
}

function genNextValue(prevValue, min, max) {
    var value = prevValue + ((max - min) * (Math.random() - 0.5)) * 0.03;
    value = Math.max(min, Math.min(max, value));
    return Math.round(value * 10) / 10;
}
Ben
  • 73
  • 2
  • 12

1 Answers1

1

From your expectation I see you should have a JSON structure like this

data has a property Buses which is an array of following object

{
  Name: BUS_NAME,
  Speed: BUSS_SPEED,
  FL: YOUR_FL
} 

JSON

var data = {
  Buses: [{ 
    Name: 'BusA'
    Speed: BusA_minspeed + (BusA_maxspeed - BusA_minspeed) * Math.random(), // It should be use seperate values seperate Buses
    FL: BusA_minfl + (BusA_maxfl - BusA_minfl) * Math.random()
  },{
    Name: 'BusB'
    Speed: BusB_minspeed + (BusB_maxspeed - BusB_minspeed) * Math.random(), // It should be use seperate values seperate Buses
    FL: BusB_minfl + (BusB_maxfl - BusB_minfl) * Math.random()
  },{
    Name: 'BusC'
    Speed: BusC_minspeed + (BusC_maxspeed - BusC_minspeed) * Math.random(), // It should be use seperate values seperate Buses
    FL: BusC_minfl + (BusC_maxfl - BusC_minfl) * Math.random()
  }] 
}

If you have above structure of JSON you can send separate data as follows

Use the follwing function and pass the busName to get the object of a perticular bus

function getBusData(busName){
   return data.buses.filter(function(bus){
      return bus.Name == busName;
  })[0];
}

USAGE

 var busA_data = getBusData('BusA');

Now, use your busA_data which should contain

{ 
    Name: 'BusA'
    Speed: 123,
    FL: 80
}

To publish you need to convert JSON to string using JSON.stringify and publish as follows

client.publish(YOUR_BROKER, JSON.stringify(busA_data));

and You need to do the opposite in .on('message', fn), e.g.

client.on('message', function (topic, payload) {
  const obj = JSON.parse(payload.toString()) // payload is your JSON as string
})
Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33