From 0f4ad8e9f1affb2e9016244ebd77611304fa53ca Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Mon, 17 Nov 2025 16:54:54 +0800 Subject: [PATCH] add mqtt subscriber --- apps/iot/src/mocker/endpoint_kafka_test.erl | 4 +- .../src/mocker/endpoint_mqtt_subscriber.erl | 163 ++++++++++++++++++ 2 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 apps/iot/src/mocker/endpoint_mqtt_subscriber.erl diff --git a/apps/iot/src/mocker/endpoint_kafka_test.erl b/apps/iot/src/mocker/endpoint_kafka_test.erl index b9d566b..7196ed8 100644 --- a/apps/iot/src/mocker/endpoint_kafka_test.erl +++ b/apps/iot/src/mocker/endpoint_kafka_test.erl @@ -40,7 +40,6 @@ start_test() -> test_consumer() -> KafkaBootstrapEndpoints = [{"118.178.229.213", 9092}], Topic = <<"dhlr_data">>, - Partition = 0, ClientConfig = [ {sasl, {plain, <<"test">>, <<"test123">>}}, @@ -49,11 +48,10 @@ test_consumer() -> ], ok = brod:start_client(KafkaBootstrapEndpoints, client1, ClientConfig), - SubscriberCallbackFun = fun(Partition, Msg, ShellPid = CallbackState) -> + SubscriberCallbackFun = fun(_Partition, Msg, ShellPid = CallbackState) -> lager:debug("call here msg: ~p", [Msg]), ShellPid ! Msg, {ok, ack, CallbackState} end, - Receive = fun() -> receive Msg -> Msg after 1000 -> timeout end end, Res = brod_topic_subscriber:start_link(client1, Topic, all, _ConsumerConfig=[{begin_offset, 0}], _CommittedOffsets=[], message, SubscriberCallbackFun, diff --git a/apps/iot/src/mocker/endpoint_mqtt_subscriber.erl b/apps/iot/src/mocker/endpoint_mqtt_subscriber.erl new file mode 100644 index 0000000..2bce1ab --- /dev/null +++ b/apps/iot/src/mocker/endpoint_mqtt_subscriber.erl @@ -0,0 +1,163 @@ +%%%------------------------------------------------------------------- +%%% @author anlicheng +%%% @copyright (C) 2025, +%%% @doc +%%% +%%% @end +%%% Created : 17. 11月 2025 16:48 +%%%------------------------------------------------------------------- +-module(endpoint_mqtt_subscriber). +-author("anlicheng"). + +-author("aresei"). +-include("iot.hrl"). + +-behaviour(gen_server). + +%% API +-export([start_link/0]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). + +-define(SERVER, ?MODULE). + +%% 需要订阅的主题信息 +-define(Topics,[ + {<<"/dhlr/data">>, 0} +]). + +-record(state, { + conn_pid :: pid() +}). + +%%%=================================================================== +%%% API +%%%=================================================================== + +%% @doc Spawns the server and registers the local name (unique) +-spec(start_link() -> + {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). + +%%%=================================================================== +%%% 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([]) -> + %% 建立到emqx服务器的连接 + ClientId = <<"mqtt-client-test-host-subscriber">>, + Opts = [ + {clientid, ClientId}, + {host, "118.178.229.213"}, + {port, 1883}, + {owner, self()}, + {tcp_opts, []}, + {username, "admin"}, + {password, "admin"}, + {keepalive, 86400}, + {auto_ack, true}, + {proto_ver, v5}, + {retry_interval, 5} + ], + + lager:debug("[opts] is: ~p", [Opts]), + case emqtt:start_link(Opts) of + {ok, ConnPid} -> + %% 监听和host相关的全部事件 + lager:debug("[iot_mqtt_subscriber] start conntecting, pid: ~p", [ConnPid]), + {ok, _} = emqtt:connect(ConnPid), + lager:debug("[iot_mqtt_subscriber] connect success, pid: ~p", [ConnPid]), + SubscribeResult = emqtt:subscribe(ConnPid, ?Topics), + + lager:debug("[iot_mqtt_subscriber] subscribe topics: ~p, result is: ~p", [?Topics, SubscribeResult]), + + {ok, #state{conn_pid = ConnPid}}; + ignore -> + lager:debug("[iot_mqtt_subscriber] connect emqx get ignore"), + {stop, ignore}; + {error, Reason} -> + lager:debug("[iot_mqtt_subscriber] 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(_Info, _From, State = #state{conn_pid = _ConnPid}) -> + {reply, ok, 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{}) -> + lager:debug("[iot_mqtt_subscriber] Recv a DISONNECT packet - ReasonCode: ~p, Properties: ~p", [ReasonCode, Properties]), + {stop, disconnected, State}; +%% 必须要做到消息的快速分发,数据的json反序列需要在host进程进行 +handle_info({publish, #{packet_id := _PacketId, payload := Payload, qos := Qos, topic := Topic}}, State = #state{conn_pid = _ConnPid}) -> + lager:debug("[iot_mqtt_subscriber] Recv a topic: ~p, publish packet: ~p, qos: ~p", [Topic, Payload, Qos]), + %% 将消息分发到对应的host进程去处理 + {noreply, State}; +handle_info({puback, Packet = #{packet_id := _PacketId}}, State = #state{}) -> + lager:debug("[iot_mqtt_subscriber] receive puback packet: ~p", [Packet]), + {noreply, State}; + +handle_info(Info, State = #state{}) -> + lager:debug("[iot_mqtt_subscriber] get info: ~p", [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{conn_pid = ConnPid}) when is_pid(ConnPid) -> + %% 取消topic的订阅 + TopicNames = lists:map(fun({Name, _}) -> Name end, ?Topics), + {ok, _Props, _ReasonCode} = emqtt:unsubscribe(ConnPid, #{}, TopicNames), + + ok = emqtt:disconnect(ConnPid), + lager:debug("[iot_mqtt_subscriber] terminate with reason: ~p", [Reason]), + ok; +terminate(Reason, _State) -> + lager:debug("[iot_mqtt_subscriber] 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