1 /*
2 * Copyright (C) 2023 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 "host/frontend/webrtc/sensors_handler.h"
18
19 #include <android-base/logging.h>
20
21 #include <sstream>
22 #include <string>
23
24 namespace cuttlefish {
25 namespace webrtc_streaming {
26
SensorsHandler()27 SensorsHandler::SensorsHandler() {}
28
~SensorsHandler()29 SensorsHandler::~SensorsHandler() {}
30
31 // Get new sensor values and send them to client.
HandleMessage(const double x,const double y,const double z)32 void SensorsHandler::HandleMessage(const double x, const double y, const double z) {
33 sensors_simulator_->RefreshSensors(x, y, z);
34 UpdateSensors();
35 }
36
Subscribe(std::function<void (const uint8_t *,size_t)> send_to_client)37 int SensorsHandler::Subscribe(std::function<void(const uint8_t*, size_t)> send_to_client) {
38 int subscriber_id = ++last_client_channel_id_;
39 {
40 std::lock_guard<std::mutex> lock(subscribers_mtx_);
41 client_channels_[subscriber_id] = send_to_client;
42 }
43
44 // Send device's initial state to the new client.
45 std::string new_sensors_data = sensors_simulator_->GetSensorsData();
46 const uint8_t* message =
47 reinterpret_cast<const uint8_t*>(new_sensors_data.c_str());
48 send_to_client(message, new_sensors_data.size());
49
50 return subscriber_id;
51 }
52
UnSubscribe(int subscriber_id)53 void SensorsHandler::UnSubscribe(int subscriber_id) {
54 std::lock_guard<std::mutex> lock(subscribers_mtx_);
55 client_channels_.erase(subscriber_id);
56 }
57
UpdateSensors()58 void SensorsHandler::UpdateSensors() {
59 std::string new_sensors_data = sensors_simulator_->GetSensorsData();
60 const uint8_t* message =
61 reinterpret_cast<const uint8_t*>(new_sensors_data.c_str());
62 std::lock_guard<std::mutex> lock(subscribers_mtx_);
63 for (auto itr = client_channels_.begin(); itr != client_channels_.end();
64 itr++) {
65 itr->second(message, new_sensors_data.size());
66 }
67 }
68
69 } // namespace webrtc_streaming
70 } // namespace cuttlefish
71