1 /*
2 * Copyright 2018 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_layer.h"
18
19 #include <sstream>
20
21 namespace rootcanal {
22
PhyLayer(Identifier id,Phy::Type type)23 PhyLayer::PhyLayer(Identifier id, Phy::Type type) : id(id), type(type) {}
24
Register(std::shared_ptr<PhyDevice> device)25 void PhyLayer::Register(std::shared_ptr<PhyDevice> device) {
26 device->Register(this);
27 phy_devices_.push_back(device);
28 }
29
Unregister(PhyDevice::Identifier id)30 void PhyLayer::Unregister(PhyDevice::Identifier id) {
31 for (auto& device : phy_devices_) {
32 if (device->id == id) {
33 device->Unregister(this);
34 phy_devices_.remove(device);
35 return;
36 }
37 }
38 }
39
UnregisterAll()40 void PhyLayer::UnregisterAll() {
41 for (auto& device : phy_devices_) {
42 device->Unregister(this);
43 }
44 phy_devices_.clear();
45 }
46
ComputeRssi(PhyDevice::Identifier,PhyDevice::Identifier,int8_t)47 int8_t PhyLayer::ComputeRssi(PhyDevice::Identifier /*sender_id*/,
48 PhyDevice::Identifier /*receiver_id*/, int8_t /*tx_power*/) {
49 // Perform no RSSI computation by default.
50 // Clients overriding this function should use the TX power and
51 // positional information to derive correct device-to-device RSSI.
52 static uint8_t rssi = 0;
53 rssi = (rssi + 5) % 128;
54 return static_cast<int8_t>(-rssi);
55 }
56
Send(std::vector<uint8_t> const & packet,int8_t tx_power,PhyDevice::Identifier sender_id)57 void PhyLayer::Send(std::vector<uint8_t> const& packet, int8_t tx_power,
58 PhyDevice::Identifier sender_id) {
59 for (const auto& device : phy_devices_) {
60 // Do not send the packet back to the sender.
61 if (sender_id != device->id) {
62 device->Receive(packet, type, ComputeRssi(sender_id, device->id, tx_power));
63 }
64 }
65 }
66
Tick()67 void PhyLayer::Tick() {
68 for (auto& device : phy_devices_) {
69 device->Tick();
70 }
71 }
72
ToString() const73 std::string PhyLayer::ToString() const {
74 std::stringstream factory;
75 switch (type) {
76 case Phy::Type::LOW_ENERGY:
77 factory << "LOW_ENERGY: ";
78 break;
79 case Phy::Type::BR_EDR:
80 factory << "BR_EDR: ";
81 break;
82 default:
83 factory << "Unknown: ";
84 }
85 for (auto& device : phy_devices_) {
86 factory << device->id;
87 factory << ",";
88 }
89
90 return factory.str();
91 }
92
93 } // namespace rootcanal
94