202 lines
8.5 KiB
Erlang
202 lines
8.5 KiB
Erlang
|
||
%%%-------------------------------------------------------------------
|
||
%%% @author aresei
|
||
%%% @copyright (C) 2023, <COMPANY>
|
||
%%% @doc
|
||
%%%
|
||
%%% @end
|
||
%%% Created : 06. 7月 2023 12:02
|
||
%%%-------------------------------------------------------------------
|
||
-module(endpoint_mqtt).
|
||
|
||
-include("endpoint.hrl").
|
||
-behaviour(gen_server).
|
||
|
||
%% API
|
||
-export([start_link/2]).
|
||
|
||
%% gen_server callbacks
|
||
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
|
||
|
||
%% 消息重发间隔
|
||
-define(RETRY_INTERVAL, 5000).
|
||
|
||
-define(DISCONNECTED, disconnected).
|
||
-define(CONNECTED, connected).
|
||
|
||
-record(state, {
|
||
endpoint :: #endpoint{},
|
||
buffer :: endpoint_buffer:buffer(),
|
||
conn_pid :: undefined | pid(),
|
||
%% 待确认的数据, #{PacketId :: integer() => Id :: integer()}
|
||
inflight = #{},
|
||
|
||
status = disconnected
|
||
}).
|
||
|
||
%%%===================================================================
|
||
%%% API
|
||
%%%===================================================================
|
||
|
||
%% @doc Creates a gen_statem process which calls Module:init/1 to
|
||
%% initialize. To ensure a synchronized start-up procedure, this
|
||
%% function does not return until Module:init/1 has returned.
|
||
start_link(LocalName, Endpoint = #endpoint{}) when is_atom(LocalName) ->
|
||
gen_server:start_link({local, LocalName}, ?MODULE, [Endpoint], []).
|
||
|
||
%%%===================================================================
|
||
%%% gen_statem callbacks
|
||
%%%===================================================================
|
||
|
||
%% @private
|
||
%% @doc Whenever a gen_statem is started using gen_statem:start/[3,4] or
|
||
%% gen_statem:start_link/[3,4], this function is called by the new
|
||
%% process to initialize.
|
||
init([Endpoint = #endpoint{matcher = Matcher}]) ->
|
||
% erlang:process_flag(trap_exit, true),
|
||
endpoint_subscription:subscribe(Matcher, self()),
|
||
|
||
%% 创建转发器, 避免阻塞当前进程的创建,因此采用了延时初始化的机制
|
||
erlang:start_timer(0, self(), create_postman),
|
||
%% 初始化存储
|
||
Buffer = endpoint_buffer:new(Endpoint, 10),
|
||
|
||
{ok, #state{endpoint = Endpoint, buffer = Buffer, status = ?DISCONNECTED}}.
|
||
|
||
%% @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(get_stat, _From, State = #state{buffer = Buffer}) ->
|
||
Stat = endpoint_buffer:stat(Buffer),
|
||
{reply, {ok, Stat}, 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({forward, ServiceId, Metric}, State = #state{buffer = Buffer}) ->
|
||
NBuffer = endpoint_buffer:append({ServiceId, Metric}, Buffer),
|
||
{noreply, State#state{buffer = NBuffer}}.
|
||
|
||
%% @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({timeout, _, create_postman}, State = #state{buffer = Buffer, status = ?DISCONNECTED,
|
||
endpoint = #endpoint{title = Title, config = #mqtt_endpoint{host = Host, port = Port, username = Username, password = Password, client_id = ClientId}}}) ->
|
||
lager:debug("[endpoint_mqtt] endpoint: ~ts, create postman", [Title]),
|
||
Opts = [
|
||
{owner, self()},
|
||
{clientid, ClientId},
|
||
{host, binary_to_list(Host)},
|
||
{port, Port},
|
||
{tcp_opts, []},
|
||
{username, binary_to_list(Username)},
|
||
{password, binary_to_list(Password)},
|
||
{keepalive, 86400},
|
||
{auto_ack, true},
|
||
{connect_timeout, 5000},
|
||
{proto_ver, v5},
|
||
{retry_interval, 5000}
|
||
],
|
||
|
||
{ok, ConnPid} = emqtt:start_link(Opts),
|
||
lager:debug("[endpoint_mqtt] start connect, options: ~p", [Opts]),
|
||
case catch emqtt:connect(ConnPid, 5000) of
|
||
{ok, _} ->
|
||
lager:debug("[endpoint_mqtt] connect success, pid: ~p", [ConnPid]),
|
||
NBuffer = endpoint_buffer:trigger_n(Buffer),
|
||
{noreply, State#state{conn_pid = ConnPid, buffer = NBuffer, status = ?CONNECTED}};
|
||
{error, Reason} ->
|
||
lager:warning("[endpoint_mqtt] connect get error: ~p", [Reason]),
|
||
erlang:start_timer(5000, self(), create_postman),
|
||
{noreply, State};
|
||
Error ->
|
||
lager:warning("[endpoint_mqtt] connect get error: ~p", [Error]),
|
||
erlang:start_timer(5000, self(), create_postman),
|
||
{noreply, State}
|
||
end;
|
||
|
||
%% 离线时,忽略数据发送逻辑
|
||
handle_info({next_data, _Id, _Tuple}, State = #state{status = ?DISCONNECTED}) ->
|
||
{keep_state, State};
|
||
%% 发送数据到mqtt服务器
|
||
handle_info({next_data, Id, {ServiceId, Metric}}, State = #state{status = ?CONNECTED, conn_pid = ConnPid, buffer = Buffer, inflight = InFlight,
|
||
endpoint = #endpoint{config = #mqtt_endpoint{topic = Topic0, qos = Qos}}}) ->
|
||
|
||
Topic = re:replace(Topic0, <<"\\${service_id}">>, ServiceId, [global, {return, binary}]),
|
||
lager:debug("[endpoint_mqtt] will publish topic: ~p, metric: ~p, qos: ~p", [Topic, Metric, Qos]),
|
||
case emqtt:publish(ConnPid, Topic, #{}, Metric, [{qos, Qos}, {retain, true}]) of
|
||
ok ->
|
||
NBuffer = endpoint_buffer:ack(Id, Buffer),
|
||
{noreply, State#state{buffer = NBuffer}};
|
||
{ok, PacketId} ->
|
||
{noreply, State#state{inflight = maps:put(PacketId, Id, InFlight)}};
|
||
{error, Reason} ->
|
||
lager:warning("[endpoint_mqtt] send message to topic: ~p, get error: ~p", [Topic, Reason]),
|
||
{stop, Reason, State}
|
||
end;
|
||
|
||
handle_info({disconnected, ReasonCode, Properties}, State = #state{status = ?CONNECTED}) ->
|
||
lager:debug("[endpoint_mqtt] Recv a DISONNECT packet - ReasonCode: ~p, Properties: ~p", [ReasonCode, Properties]),
|
||
erlang:start_timer(?RETRY_INTERVAL, self(), create_postman),
|
||
{noreply, State#state{conn_pid = undefined, status = ?DISCONNECTED}};
|
||
|
||
handle_info({publish, Message = #{packet_id := _PacketId, payload := Payload}}, State = #state{status = ?CONNECTED}) ->
|
||
lager:debug("[endpoint_mqtt] Recv a publish packet: ~p, payload: ~p", [Message, Payload]),
|
||
{noreply, State};
|
||
|
||
%% 收到确认的消息
|
||
handle_info({puback, #{packet_id := PacketId}}, State = #state{status = ?CONNECTED, inflight = Inflight, buffer = Buffer}) ->
|
||
case maps:take(PacketId, Inflight) of
|
||
{Id, RestInflight} ->
|
||
NBuffer = endpoint_buffer:ack(Id, Buffer),
|
||
{noreply, State#state{buffer = NBuffer, inflight = RestInflight}};
|
||
error ->
|
||
{noreply, State}
|
||
end;
|
||
|
||
%% postman进程挂掉时,重新建立新的
|
||
handle_info({'EXIT', ConnPid, Reason}, State = #state{endpoint = #endpoint{title = Title}, conn_pid = ConnPid}) ->
|
||
lager:warning("[endpoint_mqtt] endpoint: ~p, conn pid exit with reason: ~p", [Title, Reason]),
|
||
erlang:start_timer(?RETRY_INTERVAL, self(), create_postman),
|
||
{noreply, State#state{conn_pid = undefined, status = ?DISCONNECTED}};
|
||
|
||
handle_info(Info, State = #state{status = Status}) ->
|
||
lager:warning("[endpoint_mqtt] unknown message: ~p, status: ~p", [Info, Status]),
|
||
{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{endpoint = #endpoint{title = Title}, buffer = Buffer}) ->
|
||
lager:debug("[endpoint_mqtt] endpoint: ~p, terminate with reason: ~p", [Title, Reason]),
|
||
endpoint_buffer:cleanup(Buffer),
|
||
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
|
||
%%%=================================================================== |