fix serilize

This commit is contained in:
anlicheng 2024-12-13 20:05:52 +08:00
parent 7f59936e0e
commit e02956eed4

View File

@ -95,6 +95,7 @@ handle_cast({forward, LocationCode, DynamicLocationCode, EventType, Params},
State = #state{url = Url, token = Token, logger_pid = LoggerPid, succ_counter = SuccCounter, fail_counter = FailCounter}) ->
Body = format_event(LocationCode, DynamicLocationCode, EventType, Params),
%%
Sign = iot_util:md5(iolist_to_binary([Token, Body, Token])),
Url1 = Url ++ "?sign=" ++ binary_to_list(Sign),
@ -146,7 +147,7 @@ do_post(Url, Body) when is_binary(Body) ->
Headers = [
{<<"content-type">>, <<"application/json">>}
],
case hackney:request(post, Url, Headers, Body) of
case hackney:request(post, Url, Headers, Body, [{pool, false}]) of
{ok, 200, _, ClientRef} ->
{ok, RespBody} = hackney:body(ClientRef),
hackney:close(ClientRef),
@ -176,12 +177,42 @@ format_event(LocationCode, DynamicLocationCode, EventType,
<<"https://lgsiot.njau.edu.cn/upload/2024/11/29/2024-11-29-1732842080-1732842100.jpg">>
],
%% key的顺序限制
Params = #{
<<"attachments">> => Attachments,
<<"eventLocation">> => <<"事件地点测试值"/utf8>>,
<<"eventType">> => <<"动火离人"/utf8>>,
<<"eventTime">> => Datetime,
<<"videoJkAddr">> => <<"rtsp://admin:admin@123@192.168.111.147/cam/realmonitor?channel=1&subtype=0">>,
<<"attachments">> => Attachments
<<"eventType">> => <<"动火离人"/utf8>>,
<<"videoJkAddr">> => <<"rtsp://admin:admin@123@192.168.111.147/cam/realmonitor?channel=1&subtype=0">>
},
iolist_to_binary(jiffy:encode(Params, [force_utf8])).
iolist_to_binary(serialize(Params)).
%%
-spec serialize(M :: map()) -> JsonString :: binary().
serialize(M) when is_map(M) ->
L = maps:to_list(M),
L1 = lists:sort(fun({K, _}, {K1, _}) -> K < K1 end, L),
serialize0(L1, []).
serialize0([], Target) ->
B = iolist_to_binary(lists:join(<<$,>>, lists:reverse(Target))),
<<${, B/binary, $}>>;
serialize0([{K, V}|T], Target) ->
V1 = if
is_integer(V) ->
integer_to_binary(V);
is_float(V) ->
float_to_binary(V);
is_binary(V) ->
<<$", V/binary, $">>;
is_boolean(V) andalso V ->
<<"true">>;
is_boolean(V) andalso not V ->
<<"false">>;
is_list(V) ->
V0 = iolist_to_binary(lists:join(<<$,>>, V)),
<<$[, V0/binary, $]>>
end,
Item = <<$", K/binary, $", $:, V1/binary>>,
serialize0(T, [Item|Target]).