Skip to content

Instantly share code, notes, and snippets.

@alishir
Last active March 9, 2020 18:05
Show Gist options
  • Save alishir/995442d95eebf8e01f4e4ee79e4066e1 to your computer and use it in GitHub Desktop.
Save alishir/995442d95eebf8e01f4e4ee79e4066e1 to your computer and use it in GitHub Desktop.
-module(tcp_to_mqtt).
-behaviour(ranch_protocol).
-export([start_link/4]).
-export([init/3]).
-include_lib("kernel/include/logger.hrl").
start_link(Ref, _Socket, Transport, Opts) ->
Pid = spawn_link(?MODULE, init, [Ref, Transport, Opts]),
{ok, Pid}.
init(Ref, Transport, _Opts = []) ->
{ok, Socket} = ranch:handshake(Ref),
loop(Socket, Transport).
loop(Socket, Transport) ->
case Transport:recv(Socket, 0, infinity) of
{ok, Data} when Data =/= <<4>> ->
io:format("~p~n", [Data]),
Json = jiffy(Data),
send_mqtt(Type, IMEI, Json),
loop(Socket, Transport);
_ ->
ok = Transport:close(Socket)
end.
send_mqtt(Type, Data, Json) ->
{ok, ConnPid} = emqtt:start_link([{clientid, <<"t2m">>}]),
{ok, _Props} = emqtt:connect(ConnPid),
case Type of
<<"ALERT">> ->
ok = emqtt:publish(ConnPid, <<"topic">>, #{}, Json, [{qos, 0}, {retain, true}]);
_ ->
ok
end,
ok = emqtt:publish(ConnPid, <<"topic2">>, #{}, Json, [{qos, 0}, {retain, true}]),
ok = emqtt:disconnect(ConnPid),
ok = emqtt:stop(ConnPid).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment