EMQTT - emq_plugin_template POST to API (SQL) issue with gateway client only

595 views Asked by At

I have followed a tutorial from Ravi Pujar on passing MQTT messages to SQL using EMQ and an api interface (he has also got some help from here to make the relevant plugin work).

I am entirely new to Erlang + EMQ, any help on resolving why only my gateway’s messages aren’t saved when posted from EMQ plugin is appreciated :


  • When I post with postman through HTTP API the log is saved fine into SQL fine.

  • When I connect to the broker and publish using MQTTfx to the topic it gets saved fine into SQL as well (which is through the plugin).

  • When my gateway publishes to the topic the published messages aren’t logged into the SQL (through the plugin again) but publish fine on the topic.

SQL table has just one string field which allows null. Example gateway message (Saves fine if posted from postman to api or published on topic from MQTTfx): $GPRP,745HHBCC5FF,EC16CRH9FFC,-54,0201135644GG46E0082D8A80EFD6EAD1E9A1B132BE1,153656726

I am using “emq_plugin_template.erl” and “on_message_publish” to send my request. Plugin compiles with no errors,EMQ restarted, plugin enabled on the board and it runs smoothly. I am also subscribed to the correct topic of course on the gateway.

on_message_publish(Message, _Env) ->
    io:format("publish ~s~n", [emqttd_message:format(Message)]),

MessageBin = element(12, Message),
MessageStr = binary_to_list(MessageBin),

inets:start(),
Method = post,
URL = "http://127.0.0.1/api/v2/GatewaySQL/1234",
Header = [{"X-DreamFactory-Api-Key", "1234"}],
Type = "application/json",
%%Body = MessageStr, %%just that didn't work with gateway
Body = "{\"resource\":[{\"TagRAW\":\"" ++ MessageStr ++ "\"}]}",
HTTPOptions = [],
Options = [],
R = httpc:request(Method, {URL, Header, Type, Body},HTTPOptions,Options),
    {ok, Message}.

Checking QOS: I have confirmed QOS (QOS 0 messages) topic subscribe is correct should i check somewhere else for a mismatch? Same QOS from MQTTfx saved fine into SQL though and published on the topic.

Removing commas in received message: I have just in case tried removing commas from the message (and the $ in one of the attempts below, had more attempts some compiled fine but then the broker might have got stuck):

%%lists:delete($$,MessageStr),
%%lists:flatten(MessageStr),            %%tried without flattening it as well
%%Segmented = string:tokens(MessageStr, ","),
%%lists:flatten(Segmented),

%%IOMessageStr = io_lib:format("~w",[MessageStr]),
%%Flattened = lists:flatten(IOMessageStr),

Thank you for your time :)

1

There are 1 answers

1
Mahmood Khan On

Try to replace

MessageBin = element(12, Message),

with

MessageBin = element(8, Message),

Hope, this will work for you.