1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "phy_device.h"
18 
19 #include <log.h>
20 
21 #include "phy_layer.h"
22 
23 namespace rootcanal {
24 
PhyDevice(std::string type,std::shared_ptr<Device> device)25 PhyDevice::PhyDevice(std::string type, std::shared_ptr<Device> device)
26     : id(device->id_), type(std::move(type)), device_(std::move(device)) {
27   using namespace std::placeholders;
28   ASSERT(device_ != nullptr);
29   device_->RegisterLinkLayerChannel(std::bind(&PhyDevice::Send, this, _1, _2, _3));
30 }
31 
Register(PhyLayer * phy)32 void PhyDevice::Register(PhyLayer* phy) { phy_layers_.insert(phy); }
33 
Unregister(PhyLayer * phy)34 void PhyDevice::Unregister(PhyLayer* phy) { phy_layers_.erase(phy); }
35 
Tick()36 void PhyDevice::Tick() { device_->Tick(); }
37 
GetAddress() const38 bluetooth::hci::Address PhyDevice::GetAddress() const { return device_->GetAddress(); }
39 
GetDevice() const40 std::shared_ptr<Device> PhyDevice::GetDevice() const { return device_; }
41 
SetAddress(bluetooth::hci::Address address)42 void PhyDevice::SetAddress(bluetooth::hci::Address address) {
43   device_->SetAddress(std::move(address));
44 }
45 
Receive(std::vector<uint8_t> const & packet,Phy::Type type,int8_t rssi)46 void PhyDevice::Receive(std::vector<uint8_t> const& packet, Phy::Type type, int8_t rssi) {
47   std::shared_ptr<std::vector<uint8_t>> packet_copy =
48           std::make_shared<std::vector<uint8_t>>(packet);
49   model::packets::LinkLayerPacketView packet_view =
50           model::packets::LinkLayerPacketView::Create(pdl::packet::slice(packet_copy));
51   if (packet_view.IsValid()) {
52     device_->ReceiveLinkLayerPacket(std::move(packet_view), type, rssi);
53   } else {
54     WARNING("received invalid LL packet");
55   }
56 }
57 
Send(std::vector<uint8_t> const & packet,Phy::Type type,int8_t tx_power)58 void PhyDevice::Send(std::vector<uint8_t> const& packet, Phy::Type type, int8_t tx_power) {
59   for (auto const& phy : phy_layers_) {
60     if (phy->type == type) {
61       phy->Send(packet, tx_power, id);
62     }
63   }
64 }
65 
ToString()66 std::string PhyDevice::ToString() { return device_->ToString(); }
67 
68 }  // namespace rootcanal
69