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_assert/check.h>
18
19 #include "pw_bluetooth_sapphire/internal/host/common/log.h"
20 #include "pw_bluetooth_sapphire/internal/host/sm/smp.h"
21 #include "pw_bluetooth_sapphire/internal/host/sm/types.h"
22
23 namespace bt::sm {
24
PairingPhase(PairingChannel::WeakPtr chan,Listener::WeakPtr listener,Role role)25 PairingPhase::PairingPhase(PairingChannel::WeakPtr chan,
26 Listener::WeakPtr listener,
27 Role role)
28 : sm_chan_(std::move(chan)),
29 listener_(std::move(listener)),
30 role_(role),
31 has_failed_(false),
32 weak_channel_handler_(nullptr) {}
33
SetPairingChannelHandler(PairingChannelHandler & self)34 void PairingPhase::SetPairingChannelHandler(PairingChannelHandler& self) {
35 weak_channel_handler_ = WeakSelf(&self);
36 sm_chan().SetChannelHandler(weak_channel_handler_.GetWeakPtr());
37 }
38
InvalidatePairingChannelHandler()39 void PairingPhase::InvalidatePairingChannelHandler() {
40 weak_channel_handler_.InvalidatePtrs();
41 }
42
OnFailure(Error error)43 void PairingPhase::OnFailure(Error error) {
44 PW_CHECK(!has_failed());
45 bt_log(WARN, "sm", "pairing failed: %s", bt_str(error));
46 has_failed_ = true;
47 PW_CHECK(listener_.is_alive());
48 listener_->OnPairingFailed(error);
49 }
50
Abort(ErrorCode ecode)51 void PairingPhase::Abort(ErrorCode ecode) {
52 PW_CHECK(!has_failed());
53 Error error(ecode);
54 bt_log(INFO, "sm", "abort pairing: %s", bt_str(error));
55
56 sm_chan().SendMessage(kPairingFailed, ecode);
57 OnFailure(error);
58 }
59
HandleChannelClosed()60 void PairingPhase::HandleChannelClosed() {
61 bt_log(WARN, "sm", "channel closed while pairing");
62
63 OnFailure(Error(HostError::kLinkDisconnected));
64 }
65 } // namespace bt::sm
66