170 lines
6.6 KiB
Erlang
170 lines
6.6 KiB
Erlang
%%%-------------------------------------------------------------------
|
|
%%% @author aresei
|
|
%%% @copyright (C) 2023, <COMPANY>
|
|
%%% @doc
|
|
%%%
|
|
%%% @end
|
|
%%% Created : 12. 3月 2023 21:27
|
|
%%%-------------------------------------------------------------------
|
|
-module(iot_host).
|
|
-author("aresei").
|
|
-include("iot.hrl").
|
|
|
|
-behaviour(gen_server).
|
|
|
|
%% API
|
|
-export([test/1]).
|
|
-export([start_link/2, get_name/1, get_pid/1, publish/4]).
|
|
|
|
%% gen_server callbacks
|
|
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
|
|
|
|
-define(SERVER, ?MODULE).
|
|
|
|
-record(state, {
|
|
host :: #host{},
|
|
emqx_pid :: pid(),
|
|
is_connected = false :: boolean()
|
|
}).
|
|
|
|
test(Id) when is_binary(Id) ->
|
|
Pid = get_pid(<<"1">>),
|
|
publish(Pid, <<"/host/", Id/binary>>, <<"hello world">>, 1).
|
|
|
|
%%%===================================================================
|
|
%%% API
|
|
%%%===================================================================
|
|
get_pid(HostId) when is_binary(HostId) ->
|
|
Name = get_name(HostId),
|
|
global:whereis_name(Name).
|
|
|
|
get_name(HostId) when is_binary(HostId) ->
|
|
binary_to_atom(<<"iot_host:", HostId/binary>>).
|
|
|
|
publish(Pid, Topic, Message, Qos) when is_pid(Pid), is_binary(Topic) ->
|
|
gen_server:call(Pid, {publish, Topic, Message, Qos}).
|
|
|
|
%% @doc Spawns the server and registers the local name (unique)
|
|
-spec(start_link(Name :: atom(), Host :: #host{}) ->
|
|
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
|
|
start_link(Name, Host = #host{}) ->
|
|
gen_server:start_link({global, Name}, ?MODULE, [Host], []).
|
|
|
|
%%%===================================================================
|
|
%%% gen_server callbacks
|
|
%%%===================================================================
|
|
|
|
%% @private
|
|
%% @doc Initializes the server
|
|
-spec(init(Args :: term()) ->
|
|
{ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} |
|
|
{stop, Reason :: term()} | ignore).
|
|
init([Host = #host{host_id = HostId}]) ->
|
|
lager:debug("[iot_host] host is: ~p", [Host]),
|
|
%% 建立到emqx服务器的连接
|
|
{ok, Props} = application:get_env(iot, emqx_server),
|
|
EMQXHost = proplists:get_value(host, Props),
|
|
EMQXPort = proplists:get_value(port, Props, 18080),
|
|
Username = proplists:get_value(username, Props),
|
|
Password = proplists:get_value(password, Props),
|
|
RetryInterval = proplists:get_value(retry_interval, Props, 5),
|
|
Keepalive = proplists:get_value(keepalive, Props, 86400),
|
|
Opts = [
|
|
{host, EMQXHost},
|
|
{port, EMQXPort},
|
|
{owner, self()},
|
|
{tcp_opts, []},
|
|
{username, Username},
|
|
{password, Password},
|
|
{keepalive, Keepalive},
|
|
{retry_interval, RetryInterval}
|
|
],
|
|
|
|
case emqtt:start_link(Opts) of
|
|
{ok, ConnPid} ->
|
|
lager:debug("[iot_host] connect success, pid: ~p", [ConnPid]),
|
|
%% 监听和host相关的全部事件
|
|
{ok, _} = emqtt:connect(ConnPid),
|
|
Topics = [
|
|
{<<"/host/", HostId/binary>>, qos1}
|
|
],
|
|
SubscribeResult = emqtt:subscribe(ConnPid, Topics),
|
|
lager:debug("subscribe result is: ~p", [SubscribeResult]),
|
|
|
|
{ok, #state{host = Host, is_connected = true, emqx_pid = ConnPid}};
|
|
ignore ->
|
|
lager:debug("[iot_host] connect emqx get ignore"),
|
|
{stop, ignore};
|
|
{error, Reason} ->
|
|
lager:debug("[iot_host] connect emqx get error: ~p", [Reason]),
|
|
{stop, Reason}
|
|
end.
|
|
|
|
%% @private
|
|
%% @doc Handling call messages
|
|
-spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()},
|
|
State :: #state{}) ->
|
|
{reply, Reply :: term(), NewState :: #state{}} |
|
|
{reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} |
|
|
{noreply, NewState :: #state{}} |
|
|
{noreply, NewState :: #state{}, timeout() | hibernate} |
|
|
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
|
|
{stop, Reason :: term(), NewState :: #state{}}).
|
|
handle_call({publish, Topic, Message, Qos}, _From, State = #state{emqx_pid = ConnPid}) ->
|
|
Result = emqtt:publish(ConnPid, Topic, #{}, Message, [{qos, Qos}]),
|
|
{reply, Result, State}.
|
|
|
|
%% @private
|
|
%% @doc Handling cast messages
|
|
-spec(handle_cast(Request :: term(), State :: #state{}) ->
|
|
{noreply, NewState :: #state{}} |
|
|
{noreply, NewState :: #state{}, timeout() | hibernate} |
|
|
{stop, Reason :: term(), NewState :: #state{}}).
|
|
handle_cast(_Request, State = #state{}) ->
|
|
{noreply, State}.
|
|
|
|
%% @private
|
|
%% @doc Handling all non call/cast messages
|
|
-spec(handle_info(Info :: timeout() | term(), State :: #state{}) ->
|
|
{noreply, NewState :: #state{}} |
|
|
{noreply, NewState :: #state{}, timeout() | hibernate} |
|
|
{stop, Reason :: term(), NewState :: #state{}}).
|
|
handle_info({disconnect, ReasonCode, Properties}, State = #state{host = #host{host_id = HostId}}) ->
|
|
lager:debug("[iot_host] host: ~p, Recv a DISONNECT packet - ReasonCode: ~p, Properties: ~p", [HostId, ReasonCode, Properties]),
|
|
{stop, disconnected, State};
|
|
handle_info({publish, Message = #{packet_id := PacketId, payload := Payload}}, State = #state{emqx_pid = ConnPid, host = #host{host_id = HostId}}) ->
|
|
lager:debug("[iot_host] host: ~p, Recv a publish packet: ~p, payload: ~p", [HostId, Message, Payload]),
|
|
% emqtt:pubrec(ConnPid, PacketId),
|
|
{noreply, State};
|
|
handle_info({puback, #{packet_id := PacketId, reason_code := ReasonCode}}, State = #state{host = #host{host_id = HostId}}) ->
|
|
lager:debug("[iot_host] host: ~p, receive puback packet_id: ~p, reason_code: ~p", [HostId, PacketId, ReasonCode]),
|
|
{noreply, State};
|
|
|
|
handle_info(Info, State = #state{host = #host{host_id = HostId}}) ->
|
|
lager:debug("host_id: ~p, get info: ~p", [HostId, Info]),
|
|
{noreply, State}.
|
|
|
|
%% @private
|
|
%% @doc This function is called by a gen_server when it is about to
|
|
%% terminate. It should be the opposite of Module:init/1 and do any
|
|
%% necessary cleaning up. When it returns, the gen_server terminates
|
|
%% with Reason. The return value is ignored.
|
|
-spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()),
|
|
State :: #state{}) -> term()).
|
|
terminate(_Reason, _State = #state{emqx_pid = ConnPid}) ->
|
|
{ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, <<"hello">>),
|
|
ok = emqtt:disconnect(ConnPid),
|
|
ok = emqtt:stop(ConnPid),
|
|
ok.
|
|
|
|
%% @private
|
|
%% @doc Convert process state when code is changed
|
|
-spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{},
|
|
Extra :: term()) ->
|
|
{ok, NewState :: #state{}} | {error, Reason :: term()}).
|
|
code_change(_OldVsn, State = #state{}, _Extra) ->
|
|
{ok, State}.
|
|
|
|
%%%===================================================================
|
|
%%% Internal functions
|
|
%%%=================================================================== |