Skip to content

Encode and Decode Delimited #531

@usmantahirr

Description

@usmantahirr

I am trying to encode/decode message using encodeDelimited and decodeDelimited functions.

I want to read header message and then decide which message to decode it. and same goes for encoding, I only want to send encode and send the message which I client needs. for example, if I am invoking a command with single param, I send only single param, and I decide it using my header. I need to use encodeDelimited to encode header and message with it so that my client can see which command I've sent and can read accordingly.

same goes for Javascript side as well. if the client sends me some encoded message, I need to decode it accordingly.

for reference, I've posted by Protobuf file here.

syntax = "proto2";

//Commands Structs
message header {
    required uint32 commandType = 1;
    required uint32 commandID = 2;
}

message singleParam {
    required uint32 parameter = 1;
}

//Response structs
message responseHeader {
    required uint32 responseType = 1;
    required uint32 responseID = 2;
}

message state {
    required uint32 ambientTemperature = 1;
    required uint32 current = 2;
    required uint32 horizontalAirFlowDirection = 3;
    required uint32 connected = 4;
    required uint32 power = 5;
    required uint32 standby = 6;
    required uint32 temprature = 7;
    required uint32 thermostatFanMode = 8;
    required uint32 thermostatMode = 9;
    required uint32 verticalAirFlowDirection = 10;
    required uint32 voltage = 11;
}

//Common Structs
message setMode{
    required uint32 thermostatMode = 1;
    required uint32 thermostatSetpoint = 2;
    required uint32 thermostatFanMode = 3;
}

message noParam {}

and this is my javascript code:

  const header = root.lookup('header');
  const singleParam = root.lookup('singleParam');

  const commandType = header.lookup('commandType').name;
  const commandID   = header.lookup('commandID').name;

  const parameter = singleParam.lookup('parameter').name;

  let out = {};
  out[commandType] = 1;
  out[commandID] = 1;

  let param = {};
  param[parameter]= '100';

  // this is encoding process. here I am encoding it to send it to Device via MQTT.
  const buffer = new protobuf.BufferWriter();

  let message = header.create(out);
  let message2 = singleParam.create(param);

  header.encodeDelimited(message, buffer);
  
  singleParam.encodeDelimited(message2, buffer);
  const output = buffer.finish();

  // here I am trying to decode same thing but its giving false output.
  header.decodeDelimited(output)
  singleParam.decodeDelimited(output)

and on decoding I am getting same error again and again. ie. invalid wire type: 4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions