add host mocker

This commit is contained in:
安礼成 2023-04-14 14:18:47 +08:00
parent 9c27328853
commit bda668eeed
2 changed files with 174 additions and 1 deletions

View File

@ -109,7 +109,7 @@ init([Host = #host{host_id = HostId}]) ->
{stop, Reason :: term(), Reply :: term(), NewState :: #state{}} | {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} |
{stop, Reason :: term(), NewState :: #state{}}). {stop, Reason :: term(), NewState :: #state{}}).
handle_call({publish, Message}, _From, State = #state{emqx_pid = ConnPid, host = #host{host_id = HostId}}) -> handle_call({publish, Message}, _From, State = #state{emqx_pid = ConnPid, host = #host{host_id = HostId}}) ->
Topic = <<"/host/", HostId/binary, "/upstream">>, Topic = <<"/host/", HostId/binary, "/downstream">>,
Result = emqtt:publish(ConnPid, Topic, #{}, Message, [{qos, ?QOS}]), Result = emqtt:publish(ConnPid, Topic, #{}, Message, [{qos, ?QOS}]),
{reply, Result, State}. {reply, Result, State}.

View File

@ -0,0 +1,173 @@
%%%-------------------------------------------------------------------
%%% @author aresei
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 12. 3 2023 21:27
%%%-------------------------------------------------------------------
-module(iot_host_mocker).
-author("aresei").
-include("iot.hrl").
-behaviour(gen_server).
%% API
-export([start_link/1, publish/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
%% qos等级
-define(QOS, 1).
-record(state, {
host_id :: binary(),
emqx_pid :: pid()
}).
%%%===================================================================
%%% API
%%%===================================================================
-spec publish(pid(), binary()) -> {ok, PacketId :: integer()} | {error, term()}.
publish(Pid, Message) when is_pid(Pid), is_binary(Message) ->
gen_server:call(Pid, {publish, Message}).
%% @doc Spawns the server and registers the local name (unique)
-spec(start_link(HostId :: binary()) ->
{ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link(HostId) when is_binary(HostId) ->
gen_server:start_link(?MODULE, [HostId], []).
%%%===================================================================
%%% 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([HostId]) ->
%% 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]),
%% iot_host_sup的启动
erlang:start_timer(0, self(), subscribe_ticker),
{ok, #state{host_id = HostId, 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, Message}, _From, State = #state{emqx_pid = ConnPid, host_id = HostId}) ->
Topic = <<"/host/", HostId/binary, "/upstream">>,
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{}}).
%% topic的订阅事件
handle_info({timeout, _, subscribe_ticker}, State = #state{emqx_pid = ConnPid, host_id = HostId}) ->
%% host相关的全部事件
{ok, _} = emqtt:connect(ConnPid),
Topics = [
{<<"/host/", HostId/binary, "/downstream">>, ?QOS}
],
SubscribeResult = emqtt:subscribe(ConnPid, Topics),
lager:debug("[iot_host] host_id: ~p, subscribe result is: ~p", [HostId, SubscribeResult]),
{noreply, State#state{emqx_pid = ConnPid}};
handle_info({disconnect, ReasonCode, Properties}, State = #state{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_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_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_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}) when is_pid(ConnPid) ->
{ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, <<"hello">>),
ok = emqtt:disconnect(ConnPid),
ok = emqtt:stop(ConnPid),
ok;
terminate(Reason, _State) ->
lager:debug("[iot_host] terminate with reason: ~p", [Reason]),
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
%%%===================================================================