diff --git a/apps/emqx_gateway/src/emqx_gateway_utils.erl b/apps/emqx_gateway/src/emqx_gateway_utils.erl index 634a02f03..eb4ce9fdf 100644 --- a/apps/emqx_gateway/src/emqx_gateway_utils.erl +++ b/apps/emqx_gateway/src/emqx_gateway_utils.erl @@ -46,7 +46,8 @@ global_chain/1, listener_chain/3, find_gateway_definitions/0, - plus_max_connections/2 + plus_max_connections/2, + random_clientid/1 ]). -export([stringfy/1]). @@ -631,3 +632,6 @@ ensure_gateway_loaded() -> emqx_gateway_mqttsn ] ). + +random_clientid(GwName) when is_atom(GwName) -> + iolist_to_binary([atom_to_list(GwName), "-", emqx_utils:gen_id()]). diff --git a/apps/emqx_gateway_coap/src/emqx_coap_channel.erl b/apps/emqx_gateway_coap/src/emqx_coap_channel.erl index 21066655e..a48589e36 100644 --- a/apps/emqx_gateway_coap/src/emqx_coap_channel.erl +++ b/apps/emqx_gateway_coap/src/emqx_coap_channel.erl @@ -486,46 +486,35 @@ enrich_conninfo( conninfo = ConnInfo } ) -> - %% FIXME: generate a random clientid if absent - case Queries of - #{<<"clientid">> := ClientId} -> - Interval = maps:get(interval, emqx_keepalive:info(KeepAlive)), - NConnInfo = ConnInfo#{ - clientid => ClientId, - proto_name => <<"CoAP">>, - proto_ver => <<"1">>, - clean_start => true, - keepalive => Interval, - expiry_interval => 0 - }, - {ok, Channel#channel{conninfo = NConnInfo}}; - _ -> - {error, "invalid queries", Channel} - end. + ClientId = + case maps:get(<<"clientid">>, Queries, undefined) of + undefined -> + emqx_gateway_utils:random_clientid(coap); + ClientId0 -> + ClientId0 + end, + Interval = maps:get(interval, emqx_keepalive:info(KeepAlive)), + NConnInfo = ConnInfo#{ + clientid => ClientId, + proto_name => <<"CoAP">>, + proto_ver => <<"1">>, + clean_start => true, + keepalive => Interval, + expiry_interval => 0 + }, + {ok, Channel#channel{conninfo = NConnInfo}}. enrich_clientinfo( {Queries, Msg}, - Channel = #channel{clientinfo = ClientInfo0} + Channel = #channel{conninfo = ConnInfo, clientinfo = ClientInfo0} ) -> - %% FIXME: - %% 1. generate a random clientid if absent; - %% 2. assgin username, password to `undefined` if absent - case Queries of - #{ - <<"username">> := UserName, - <<"password">> := Password, - <<"clientid">> := ClientId - } -> - ClientInfo = ClientInfo0#{ - username => UserName, - password => Password, - clientid => ClientId - }, - {ok, NClientInfo} = fix_mountpoint(Msg, ClientInfo), - {ok, Channel#channel{clientinfo = NClientInfo}}; - _ -> - {error, "invalid queries", Channel} - end. + ClientInfo = ClientInfo0#{ + clientid => maps:get(clientid, ConnInfo), + username => maps:get(<<"username">>, Queries, undefined), + password => maps:get(<<"password">>, Queries, undefined) + }, + {ok, NClientInfo} = fix_mountpoint(Msg, ClientInfo), + {ok, Channel#channel{clientinfo = NClientInfo}}. set_log_meta(_Input, #channel{clientinfo = #{clientid := ClientId}}) -> emqx_logger:set_metadata_clientid(ClientId),