emqx_request_sender.erl 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2019-2024 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_request_sender).
  17. -export([start_link/3, stop/1, send/6]).
  18. -include_lib("emqx/include/emqx_mqtt.hrl").
  19. start_link(ResponseTopic, QoS, Options0) ->
  20. Parent = self(),
  21. MsgHandler = make_msg_handler(Parent),
  22. Options = [{msg_handler, MsgHandler} | Options0],
  23. case emqtt:start_link(Options) of
  24. {ok, Pid} ->
  25. {ok, _} = emqtt:connect(Pid),
  26. try subscribe(Pid, ResponseTopic, QoS) of
  27. ok -> {ok, Pid};
  28. {error, _} = Error -> Error
  29. catch
  30. C:E:S ->
  31. emqtt:stop(Pid),
  32. {error, {C, E, S}}
  33. end;
  34. {error, _} = Error ->
  35. Error
  36. end.
  37. %% @doc Send a message to request topic with correlation-data `CorrData'.
  38. %% Response should be delivered as a `{response, CorrData, Payload}'
  39. send(Client, ReqTopic, RspTopic, CorrData, Payload, QoS) ->
  40. Props = #{
  41. 'Response-Topic' => RspTopic,
  42. 'Correlation-Data' => CorrData
  43. },
  44. Msg = #mqtt_msg{
  45. qos = QoS,
  46. topic = ReqTopic,
  47. props = Props,
  48. payload = Payload
  49. },
  50. case emqtt:publish(Client, Msg) of
  51. %% QoS = 0
  52. ok -> ok;
  53. {ok, _} -> ok;
  54. {error, _} = E -> E
  55. end.
  56. stop(Pid) ->
  57. emqtt:disconnect(Pid).
  58. subscribe(Client, Topic, QoS) ->
  59. case emqtt:subscribe(Client, Topic, QoS) of
  60. {ok, _, _} -> ok;
  61. {error, _} = Error -> Error
  62. end.
  63. make_msg_handler(Parent) ->
  64. #{
  65. publish => fun(Msg) -> handle_msg(Msg, Parent) end,
  66. puback => fun(_Ack) -> ok end,
  67. disconnected => fun(_Reason) -> ok end
  68. }.
  69. handle_msg(Msg, Parent) ->
  70. #{properties := Props, payload := Payload} = Msg,
  71. CorrData = maps:get('Correlation-Data', Props),
  72. Parent ! {response, CorrData, Payload},
  73. ok.