Accessing RPC inside a RPC

#1

If you are asking a question, please follow this template:

  1. My goal is: [Accessing device info and transfer it over MQTT]
  2. My actions are:
    So basically I want to access Sys.GetInfo RPC locally and send its response over mqtt and here is code I try :-

`

let  deviceInfo = "test" ;
RPC.addHandler('Token_verify', function(args) {	

RPC.call(RPC.LOCAL, 'Sys.GetInfo', null, function(resp, ud) {
  deviceInfo =  JSON.stringify(resp);
}, null); 
if (typeof(args) === 'object' && typeof(args.token) === 'number') {
  MQTT.pub('my/topic',args.token );
  MQTT.pub('my/topic',deviceInfo );
return deviceInfo;
} else {
return "Fail"
}
})

`

  1. The result I see is:
    First time I call this RPC it returns test and second time it return device structure.

  2. My expectation & question is: So here expectation is result should be returned correctly at first time.

Thanks

PS: I am new to js.

#2

The problem here is that the rpc calls are asynchronous, and deviceInfo will get a value AFTER the handler function will be finished. When you call Token_verify the second time, deviceInfo will have the value returned by the first call.

The solution is to pass args as the user data argument of RPC.call. The arguments of the handler should be resp, err_code, err_msg, ud, not resp, ud.

IMO, a better way to handle embedded rpc calls is in C/C++ where you have more control on handling errors and even returning data. Fortunately, in this case, Sys.GetInfo will never fail.