From e02956eed4c9344130a4f62a30a1f08cefec4dda Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Fri, 13 Dec 2024 20:05:52 +0800 Subject: [PATCH] fix serilize --- .../endpoint/iot_donghuoliren_endpoint.erl | 41 ++++++++++++++++--- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/apps/iot/src/endpoint/iot_donghuoliren_endpoint.erl b/apps/iot/src/endpoint/iot_donghuoliren_endpoint.erl index dfbdd01..399ee90 100644 --- a/apps/iot/src/endpoint/iot_donghuoliren_endpoint.erl +++ b/apps/iot/src/endpoint/iot_donghuoliren_endpoint.erl @@ -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])). \ No newline at end of file + 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]). \ No newline at end of file