From 7fd82ac61df6f136041a67e2544c342c9fab7c7f Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Sat, 9 May 2026 17:12:56 +0800 Subject: [PATCH] fix heartbeat --- src/host/iot_host.erl | 18 +++++++++++++++++- src/iot_app.erl | 2 +- src/transport/udp/udp_server.erl | 7 ++++--- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/host/iot_host.erl b/src/host/iot_host.erl index 75ba4a9..3c89ced 100644 --- a/src/host/iot_host.erl +++ b/src/host/iot_host.erl @@ -307,7 +307,8 @@ handle_event(cast, {handle, {ping, Metrics}}, ?STATE_ACTIVATED, State = #state{u {keep_state, State#state{metrics = Metrics}}; %% 心跳机制 -handle_event(cast, heartbeat, _, State = #state{heartbeat_counter = HeartbeatCounter}) -> +handle_event(cast, heartbeat, _, State = #state{uuid = UUID, heartbeat_counter = HeartbeatCounter}) -> + maybe_mark_host_online(UUID), {keep_state, State#state{heartbeat_counter = HeartbeatCounter + 1}}; %% 没有收到心跳包,主机下线, 设备状态不变 @@ -403,3 +404,18 @@ maybe_mark_host_offline(UUID) -> logger:warning("[iot_host] host: ~p, load status failed while marking offline: ~p", [UUID, Other]), ok end. + +-spec maybe_mark_host_online(binary()) -> ok. +maybe_mark_host_online(UUID) -> + case iot_api_client:get_host_by_uuid(UUID) of + {ok, #host_info{status = ?HOST_OFFLINE}} -> + _ = iot_api_client:change_host_status(UUID, ?HOST_ONLINE), + ok; + {ok, #host_info{status = ?HOST_ONLINE}} -> + ok; + {ok, #host_info{status = ?HOST_NOT_JOINED}} -> + ok; + Other -> + logger:warning("[iot_host] host: ~p, load status failed while marking online: ~p", [UUID, Other]), + ok + end. diff --git a/src/iot_app.erl b/src/iot_app.erl index ce51d39..a24e8d7 100644 --- a/src/iot_app.erl +++ b/src/iot_app.erl @@ -146,4 +146,4 @@ ensure_efka_client_table() -> {error, Reason} -> logger:debug("[iot_app] create efka_client table failed with error: ~p", [Reason]), throw({init_tables, {efka_client, Reason}}) - end. + end. \ No newline at end of file diff --git a/src/transport/udp/udp_server.erl b/src/transport/udp/udp_server.erl index afb369b..d12002b 100644 --- a/src/transport/udp/udp_server.erl +++ b/src/transport/udp/udp_server.erl @@ -21,6 +21,7 @@ loop(Transport = {udp, Server, _Sock}, Peer) -> Pid = iot_host:get_pid(HostUUID), iot_host:heartbeat(Pid), loop(Transport, Peer); - {datagram, Server, _} -> - exit(normal) - end. \ No newline at end of file + {datagram, Server, Packet} -> + logger:warning("[udp_server] ignore invalid heartbeat packet from peer: ~p, packet: ~p", [Peer, Packet]), + loop(Transport, Peer) + end.