From bda668eeed41b2a503c57bcb0a12dffb0b7f3cdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=89=E7=A4=BC=E6=88=90?= Date: Fri, 14 Apr 2023 14:18:47 +0800 Subject: [PATCH] add host mocker --- apps/iot/src/iot_host.erl | 2 +- apps/iot/src/iot_host_mocker.erl | 173 +++++++++++++++++++++++++++++++ 2 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 apps/iot/src/iot_host_mocker.erl diff --git a/apps/iot/src/iot_host.erl b/apps/iot/src/iot_host.erl index 2ac21bb..848c3e4 100644 --- a/apps/iot/src/iot_host.erl +++ b/apps/iot/src/iot_host.erl @@ -109,7 +109,7 @@ init([Host = #host{host_id = HostId}]) -> {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} | {stop, Reason :: term(), NewState :: #state{}}). 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}]), {reply, Result, State}. diff --git a/apps/iot/src/iot_host_mocker.erl b/apps/iot/src/iot_host_mocker.erl new file mode 100644 index 0000000..5dadb28 --- /dev/null +++ b/apps/iot/src/iot_host_mocker.erl @@ -0,0 +1,173 @@ +%%%------------------------------------------------------------------- +%%% @author aresei +%%% @copyright (C) 2023, +%%% @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 +%%%=================================================================== \ No newline at end of file