Skip to content

Commit 9d13bb8

Browse files
committed
Fix ESP32 wifi scan handling
Fetch AP records in the scan-done callback before offloading packaging to a worker task, and clean up blocking scan replies so scans complete without deadlocking or leaking state.
1 parent dc233f9 commit 9d13bb8

File tree

2 files changed

+135
-145
lines changed

2 files changed

+135
-145
lines changed

libs/avm_network/src/network.erl

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -732,13 +732,12 @@ handle_info({Ref, {sntp_sync, TimeVal}} = _Msg, #state{ref = Ref, config = Confi
732732
maybe_sntp_sync_callback(Config, TimeVal),
733733
{noreply, State};
734734
handle_info(
735-
{ScanRef, {scan_results, _Results} = Msg}, #state{scan_receiver = {_Pid, ScanRef}} = State
735+
{ScanRef, {scan_results, _Results} = Msg},
736+
#state{scan_receiver = {Receiver, ScanRef}} = State
736737
) ->
737-
%% We have results, so to avoid a race if a new wifi_scan request is made, spawn
738-
%% the handler, and immediately update the state so handle_call does not reply to
739-
%% this caller with {error,canceled} before we can send the results (avoiding a
740-
%% crash if this is a blocking scan request).
741-
spawn(fun() -> scan_reply_or_callback(Msg, State) end),
738+
%% Spawn the reply handler so the state is cleared before a caller can issue
739+
%% another scan and race with cancellation of the previous request.
740+
spawn(fun() -> scan_reply_or_callback(Msg, Receiver) end),
742741
{noreply, State#state{scan_receiver = undefined}};
743742
handle_info({_ScanRef, {scan_results, _Results}} = Msg, State) ->
744743
%% late, (likely incomplete or inaccurate) results for canceled scan.
@@ -795,21 +794,23 @@ wait_for_port_close(PortMonitor, Port) ->
795794
%% Internal operations
796795
%%
797796

798-
scan_reply_or_callback({scan_results, Results} = Msg, #state{scan_receiver = Receiver} = _State) ->
797+
scan_reply_or_callback({scan_results, Results} = Msg, Receiver) ->
799798
case Receiver of
800799
undefined ->
801800
ok;
802-
{From, _} when is_tuple(From) ->
801+
{Pid, Ref} = From when is_pid(Pid), is_reference(Ref) ->
803802
case Results of
804803
{error, _} ->
805804
gen_server:reply(From, Results);
806805
_ ->
807806
gen_server:reply(From, {ok, Results})
808807
end;
809-
{Pid, _} when is_pid(Pid) ->
808+
Pid when is_pid(Pid) ->
810809
Pid ! Msg;
811-
{Fun, _} when is_function(Fun, 1) ->
812-
spawn(fun() -> Fun(Results) end)
810+
Fun when is_function(Fun, 1) ->
811+
spawn(fun() -> Fun(Results) end);
812+
_Other ->
813+
ok
813814
end,
814815
ok.
815816

0 commit comments

Comments
 (0)