xref: /aosp_15_r20/external/pigweed/pw_bluetooth_sapphire/host/sm/pairing_phase.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_bluetooth_sapphire/internal/host/sm/pairing_phase.h"
16 
17 #include "pw_bluetooth_sapphire/internal/host/common/log.h"
18 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
19 #include "pw_bluetooth_sapphire/internal/host/sm/types.h"
20 
21 namespace bt::sm {
22 
PairingPhase(PairingChannel::WeakPtr chan,Listener::WeakPtr listener,Role role)23 PairingPhase::PairingPhase(PairingChannel::WeakPtr chan,
24                            Listener::WeakPtr listener,
25                            Role role)
26     : sm_chan_(std::move(chan)),
27       listener_(std::move(listener)),
28       role_(role),
29       has_failed_(false),
30       weak_channel_handler_(nullptr) {}
31 
SetPairingChannelHandler(PairingChannelHandler & self)32 void PairingPhase::SetPairingChannelHandler(PairingChannelHandler& self) {
33   weak_channel_handler_ = WeakSelf(&self);
34   sm_chan().SetChannelHandler(weak_channel_handler_.GetWeakPtr());
35 }
36 
InvalidatePairingChannelHandler()37 void PairingPhase::InvalidatePairingChannelHandler() {
38   weak_channel_handler_.InvalidatePtrs();
39 }
40 
OnFailure(Error error)41 void PairingPhase::OnFailure(Error error) {
42   PW_CHECK(!has_failed());
43   bt_log(WARN, "sm", "pairing failed: %s", bt_str(error));
44   has_failed_ = true;
45   PW_CHECK(listener_.is_alive());
46   listener_->OnPairingFailed(error);
47 }
48 
Abort(ErrorCode ecode)49 void PairingPhase::Abort(ErrorCode ecode) {
50   PW_CHECK(!has_failed());
51   Error error(ecode);
52   bt_log(INFO, "sm", "abort pairing: %s", bt_str(error));
53 
54   sm_chan().SendMessage(kPairingFailed, ecode);
55   OnFailure(error);
56 }
57 
HandleChannelClosed()58 void PairingPhase::HandleChannelClosed() {
59   bt_log(WARN, "sm", "channel closed while pairing");
60 
61   OnFailure(Error(HostError::kLinkDisconnected));
62 }
63 }  // namespace bt::sm
64