Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

handle mqtt over info. server/client topics #350

Merged
merged 1 commit into from Oct 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 0 additions & 35 deletions include/emqttd.hrl

This file was deleted.

6 changes: 6 additions & 0 deletions include/n2o.hrl
Expand Up @@ -49,6 +49,12 @@

-define(N2O_JSON, (application:get_env(n2o,json,jsone))).

% MQTT topics

-define(VSN, "1").
-define(SRV_TOPIC(Node, M), iolist_to_binary([application:get_env(n2o,server_topic,"/events"), "/",?VSN,"/",Node,"/",M,"/#"])).
-define(CLI_TOPIC(M,Cid), iolist_to_binary([application:get_env(n2o,client_topic,"/actions"),"/",?VSN,"/",M,"/",Cid])).

% IO protocol

-include_lib("n2o/include/io.hrl").
Expand Down
24 changes: 13 additions & 11 deletions priv/mq.js
Expand Up @@ -7,16 +7,15 @@ var l = location.pathname,
x = l.substring(l.lastIndexOf("/") + 1),
ll = x.lastIndexOf("."),
module = x == "" ? "index" : (ll > 0 ? x.substring(0, ll) : x);
var ws = { send: function (payload, qos) {
mqtt.send(topic("/events"), payload, qos || 2, false);
}};

var ws = { send: function (payload, qos) { mqtt.send(events("/events"), payload, qos || 2, false); }};

var subscribeOptions = {
qos: 2, // QoS
invocationContext: { foo: true }, // Passed to success / failure callback
onSuccess: function (x) { console.log("Subscribed to ", x); },
onFailure: function (m) { console.log("MQTT Subscription failed: " + m.errorMessage); },
timeout: 2 };
timeout: 2,
onFailure: function(m) { console.log("MQTT Subscription failed: " + m.errorMessage); },
onSuccess: function(x) { console.log("MQTT Subscribe:", x); }};

var options = {
timeout: 2,
Expand All @@ -25,18 +24,21 @@ var options = {
cleanSession: false,
onFailure: function (m) { console.log("MQTT Connection failed: " + m.errorMessage); },
onSuccess: function () {
console.log("MQTT Connect");
mqtt.subscribe("/actions/1/index/#", subscribeOptions);
ws.send(enc(tuple(atom('init'),bin(token())))); //<<"N2o/Token">>
} };
mqtt.subscribe(actions("/actions"), {
qos:2,
onFailure: function(e) {console.log("Subscription failed:", m.errorMessage); },
onSuccess: function(x) {ws.send(enc(tuple(atom('init'),bin(token()))));}
});
doxtop marked this conversation as resolved.
Show resolved Hide resolved
}};

function gen_client() { return Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36); }
function pageModule() { return module || 'api'; }
function client() { var c = localStorage.getItem("client"), a;
if (null == c) { c = 'emqttd_' + gen_client(); }
localStorage.setItem("client", c); return c; }
function token() { return localStorage.getItem("token") || ''; };
function topic(prefix) { return prefix + "/1/" + rnd() + "/" + pageModule() + "/anon/" + client() + "/" + token(); }
function actions(pre) { return pre + "/1/" + pageModule() + "/" + client();}
function events(pre) { return pre + "/1/" + rnd() + "/" + pageModule() + "/anon/" + client() + "/" + token(); }
function rnd() { return Math.floor((Math.random() * nodes)+1); }

mqtt = new Paho.MQTT.Client(host, 8083, client());
Expand Down
42 changes: 18 additions & 24 deletions src/mqtt/n2o_mqtt.erl
Expand Up @@ -8,11 +8,9 @@ send(C,T,M) ->
proc(init,#pi{name=Name}=Async) ->
case emqtt:start_link(#{owner => self(), client_id => Name}) of
{ok, Conn} ->
["mqtt", M, Node] = string:tokens(Name, "/"),
Topic = iolist_to_binary(["/events/1/",Node,"/", M,"/#"]),
[_,M,Node|_] = string:tokens(Name, "/"),
emqtt:connect(Conn),
emqtt:subscribe(Conn, {Topic, 2}),
io:format("MQTT worker on ~p initalized. ~n", [Topic]),
emqtt:subscribe(Conn, {?SRV_TOPIC(Node,M),2}),
{ok,Async#pi{state=Conn}};
ignore -> ignore;
{error, Error} -> {error, Error}
Expand All @@ -25,27 +23,23 @@ proc({ring, Topic, Request}, State) ->
io:format("MQTT Ring message ~p~n.", [Request]),
proc({publish, #{payload => Request, topic => Topic}}, State);

proc({publish, #{payload := Request, topic := <<"/",Address/binary>>}}, State=#pi{state=C}) ->
[Pre,Vsn,Node,M,_Urs,Cid|_] = string:tokens(binary_to_list(Address),"/"),
io:format("MQTT Message to {Mod: ~p, Node: ~p, Cid ~p}.~n", [M, Node, Cid]),

Ctx = #cx{module=list_to_atom(M),node=Node,vsn=Vsn,client_pid=C, params=Cid, from=Address},
put(context, Ctx),

case n2o_proto:try_info(Request,[],Ctx) of
{reply,{_, <<>>},_,_} -> {noreply, State};
{reply,{bert, Term},_,#cx{from=X}} -> case send(C,X,n2o_bert:encode(Term)) of
ok -> {noreply, State};
{ok, _Pkid} -> {noreply, State};
{error, Error} -> {reply, {error, Error}, State} end;
{reply,{json, Term},_,#cx{from=X}} -> {reply, {ok,send(C,X,n2o_json:encode(Term))}, State};
{reply,{text, Term},_,#cx{from=X}} -> {reply, {ok,send(C,X,Term)}, State};
{reply,{binary, Term},_,#cx{from=X}} ->
proc({publish, #{payload := Request, topic := Topic}}, State=#pi{state=C}) ->
[_Ch,Vsn,Node,M,_Usr,Cid|_] = string:tokens(binary_to_list(Topic), "/"),
put(context,Cx=#cx{module=list_to_atom(M),node=Node,params=Cid,vsn=Vsn,client_pid=C,from=?CLI_TOPIC(M,Cid)}),

{reply, {ok,send(C,X,Term)}, State};
{reply,{default,Term},_,#cx{from=X}} -> {reply, {ok,send(C,X,n2o:encode(Term))}, State};
{reply,{Encoder,Term},_,#cx{from=X}} -> {reply, {ok,send(C,X,Encoder:encode(Term))}, State};
Reply -> {reply, {error,{"Invalid Return",Reply}}, State}
io:format("MQTTv5 [~p]: Message: ~p~n",[M,Request]),

% handle_info may initiate the proc
% so valid response are {noreply,_,_} variations and {stop,_,_}
case n2o_proto:try_info(n2o:decode(Request),[],Cx) of
{reply,{_, <<>>},_,_} -> {noreply, State};
{reply,{bert, Term},_,#cx{from=X}} -> send(C,X,n2o_bert:encode(Term)), {noreply, State};
{reply,{json, Term},_,#cx{from=X}} -> send(C,X,n2o_json:encode(Term)), {noreply,State};
{reply,{text, Term},_,#cx{from=X}} -> send(C,X,Term), {noreply, State};
{reply,{binary, Term},_,#cx{from=X}} -> send(C,X,Term), {noreply,State};
{reply,{default,Term},_,#cx{from=X}} -> send(C,X,n2o:encode(Term)), {noreply,State};
{reply,{Encoder,Term},_,#cx{from=X}} -> send(C,X,Encoder:encode(Term)), {noreply, State};
Reply -> {stop, {error,{"Invalid Return", Reply}}, State}
end;

proc(Unknown,Async=#pi{name=Name}) ->
Expand Down