Move battery handling into dedicated monitor class

This commit is contained in:
Sapphire
2026-11-11 16:23:54 -05:00
parent 2233817b59
commit 64ecbdc24b
15 changed files with 253 additions and 111 deletions
+20 -17
View File
@@ -2,6 +2,7 @@
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 Patrick Nicolas <patricknicolas@laposte.net>
* Copyright (C) 2026 Sapphire <imsapphire0@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,20 +20,19 @@
#include "battery.h"
#include "android/jnipp.h"
#include "application.h"
#include <mutex>
#include <spdlog/spdlog.h>
namespace
battery::battery(xr::instance & instance, xr::session & session, jobject activity) : battery(instance, session)
{
std::mutex last_status_lock;
battery_status last_status;
} // namespace
jni::object<""> act(activity);
auto app = act.call<jni::object<"android/app/Application">>("getApplication");
auto ctx = app.call<jni::object<"android/content/Context">>("getApplicationContext");
battery_status get_battery_status()
{
std::unique_lock _{last_status_lock};
return last_status;
auto bat_receiver = act.field<jni::object<"android/content/BroadcastReceiver">>("BatteryInfoReceiver");
ctx.call<jni::object<"android/content/Intent">>("registerReceiver", bat_receiver, jni::new_object<"android/content/IntentFilter">(jni::string{"android.intent.action.BATTERY_CHANGED"}));
}
extern "C" void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env, jobject instance, jobject ctxt_obj, jobject intent_obj)
@@ -51,16 +51,19 @@ extern "C" void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env,
auto scale_jint = intent.call<jni::Int>(get_int_extra, scale_jstr, default_jint);
auto plugged_jint = intent.call<jni::Int>(get_int_extra, plugged_jstr, default_jint);
{
std::unique_lock _{last_status_lock};
if (level_jint && level_jint.value >= 0 && scale_jint && scale_jint.value >= 0)
last_status.charge = (float)(level_jint.value) / (float)(scale_jint.value);
else
last_status.charge = std::nullopt;
std::optional<float> charge{};
if (level_jint && level_jint.value >= 0 && scale_jint && scale_jint.value >= 0)
charge = (float)(level_jint.value) / (float)(scale_jint.value);
last_status.charging = plugged_jint && plugged_jint.value > 0;
}
bool charging = plugged_jint && plugged_jint.value > 0;
if (level_jint and scale_jint and plugged_jint)
spdlog::debug("Received ACTION_BATTERY_CHANGED: level {}%, plugged {}", *last_status.charge * 100, last_status.charging);
spdlog::debug("Received ACTION_BATTERY_CHANGED: level {}%, plugged {}", *charge * 100, charging);
application::get_battery_monitor().on_status_update(
battery::device::head,
{
.charge = charge,
.charging = charging,
});
}
+7
View File
@@ -1501,6 +1501,12 @@ void application::initialize()
spaces[size_t(xr::spaces::view)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW);
spaces[size_t(xr::spaces::world)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE);
#ifdef __ANDROID__
battery_monitor.emplace(xr_instance, xr_session, app_info.native_app->activity->clazz);
#else
battery_monitor.emplace(xr_instance, xr_session);
#endif
config.emplace(xr_system_id, xr_session, application::get_config_path() / "client.json");
default_config.emplace(xr_system_id, xr_session);
@@ -1797,6 +1803,7 @@ application::~application()
void application::loop()
{
poll_events();
battery_monitor->poll_batteries();
auto scene = current_scene();
if (not is_session_running())
+8
View File
@@ -19,6 +19,7 @@
#pragma once
#include "battery.h"
#ifdef __ANDROID__
#include "android/hid.h"
#include <android_native_app_glue.h>
@@ -148,6 +149,7 @@ private:
std::filesystem::path cache_path;
std::shared_ptr<wifi_lock> wifi;
std::optional<battery> battery_monitor;
std::mutex server_intent_mutex;
std::optional<wivrn_discover::service> server_intent;
@@ -316,6 +318,12 @@ public:
return *instance().wifi;
}
static battery & get_battery_monitor()
{
assert(instance().battery_monitor);
return *instance().battery_monitor;
}
#ifdef __ANDROID__
void set_usb_networking(bool enabled);
#endif
+108
View File
@@ -0,0 +1,108 @@
/*
* WiVRn VR streaming
* Copyright (C) 2026 Sapphire <imsapphire0@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "battery.h"
#include "application.h"
#include "scene.h"
#include <chrono>
#include <magic_enum.hpp>
#include <spdlog/spdlog.h>
battery::battery(xr::instance & instance, xr::session & session) :
session(session)
{
if (instance.has_extension(XR_EXT_INTERACTION_PROFILE_BATTERY_STATE_DISPLAY_EXTENSION_NAME))
{
top_level_paths.emplace({
std::make_pair(instance.string_to_path("/user/hand/left"), device::left_controller),
std::make_pair(instance.string_to_path("/user/hand/right"), device::right_controller),
std::make_pair(instance.string_to_path("/user/gamepad"), device::gamepad),
});
}
}
void battery::poll_batteries()
{
using namespace std::chrono_literals;
auto now = std::chrono::steady_clock::now();
if (now - last_poll < 10s)
return;
last_poll = now;
spdlog::debug("Polling batteries");
std::lock_guard lock(m);
#ifndef __ANDROID__
{
battery_status status = get_hmd_battery();
if (status != statuses.at(device::head))
{
on_status_update(device::head, std::move(status));
}
}
#endif
if (top_level_paths)
{
for (auto [path, device]: *top_level_paths)
{
XrBatteryStateDisplayEXT battery_state{
.type = XR_TYPE_BATTERY_STATE_DISPLAY_EXT,
};
XrInteractionProfileState profile_state{
.type = XR_TYPE_INTERACTION_PROFILE_STATE,
.next = &battery_state,
};
try
{
CHECK_XR(xrGetCurrentInteractionProfile(session, path, &profile_state));
}
catch (std::exception & e)
{
spdlog::warn("Failed to get battery charge state for device {}: {}", magic_enum::enum_name(device), e.what());
continue;
}
std::optional<float> charge{};
if (battery_state.stateFlags & XR_BATTERY_STATE_DISPLAY_STATE_VALID_BIT_EXT)
charge = battery_state.batteryLevel;
battery_status status{
.charge = charge,
.charging = (battery_state.stateFlags & XR_BATTERY_STATE_DISPLAY_STATE_CHARGING_BIT_EXT) != 0,
};
if (status != statuses.at(device))
{
on_status_update(device, std::move(status));
}
}
}
}
void battery::on_status_update(battery::device device, battery::battery_status && new_status)
{
std::lock_guard lock(m);
if (std::shared_ptr<scene> s = application::instance().current_scene())
{
s->on_battery_update(device, new_status);
}
statuses.at(device) = std::move(new_status);
}
+62 -5
View File
@@ -2,6 +2,7 @@
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 Patrick Nicolas <patricknicolas@laposte.net>
* Copyright (C) 2026 Sapphire <imsapphire0@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,12 +20,68 @@
#pragma once
#include "xr/instance.h"
#include "xr/session.h"
#ifdef __ANDROID__
#include "jni.h"
#endif
#include <chrono>
#include <inplace_vector.hpp>
#include <magic_enum_containers.hpp>
#include <mutex>
#include <optional>
struct battery_status
class battery
{
std::optional<float> charge = std::nullopt;
bool charging = false;
};
public:
enum device : uint8_t
{
head = 0,
left_controller,
right_controller,
gamepad,
};
battery_status get_battery_status();
struct battery_status
{
std::optional<float> charge = std::nullopt;
bool charging = false;
bool operator!=(const battery_status & other) const
{
return charge != other.charge || charging != other.charging;
}
};
battery(xr::instance & instance, xr::session & session);
#ifdef __ANDROID__
battery(xr::instance & instance, xr::session & session, jobject activity);
#endif
private:
xr::session & session;
std::optional<beman::inplace_vector::inplace_vector<std::pair<XrPath, device>, 3>> top_level_paths;
std::recursive_mutex m;
magic_enum::containers::array<device, battery_status> statuses;
// we need to poll for controller batteries, there's no XR event sent when their state changes
// linux implementation also doesn't have an event-based API for battery
std::chrono::steady_clock::time_point last_poll{};
#ifndef __ANDROID__
battery_status get_hmd_battery();
#endif
public:
void poll_batteries();
// updates statuses and sends the new battery status to the focused scene
void on_status_update(device device, battery_status && new_status);
inline battery_status get_battery_status(device device)
{
std::lock_guard lock(m);
return statuses.at(device);
};
};
+2 -4
View File
@@ -16,7 +16,7 @@ public class MainActivity extends android.app.NativeActivity
@Override
public native void onActivityResult(int requestCode, int resultCode, android.content.Intent data);
private android.content.BroadcastReceiver BatteryInfoReceiver = null;
public android.content.BroadcastReceiver BatteryInfoReceiver = null;
public android.net.ConnectivityManager.NetworkCallback netcb = null;
@Override
@@ -24,9 +24,7 @@ public class MainActivity extends android.app.NativeActivity
{
super.onCreate(savedInstanceState);
this.BatteryInfoReceiver = new BroadcastReceiver();
this.BatteryInfoReceiver = new org.meumeu.wivrn.BroadcastReceiver();
this.netcb = new org.meumeu.wivrn.NetworkInfoCallback();
this.registerReceiver(this.BatteryInfoReceiver, new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED));
}
}
+3 -21
View File
@@ -25,10 +25,6 @@
namespace
{
std::mutex last_status_lock;
battery_status last_status;
std::chrono::steady_clock::time_point last_read;
std::optional<std::string> read_line(const std::filesystem::path & path)
{
std::ifstream file(path);
@@ -37,7 +33,6 @@ std::optional<std::string> read_line(const std::filesystem::path & path)
return line;
return std::nullopt;
}
std::optional<float> read_percent(const std::filesystem::path & path)
{
std::ifstream file(path);
@@ -47,7 +42,7 @@ std::optional<float> read_percent(const std::filesystem::path & path)
return std::nullopt;
}
battery_status read_battery_status(const std::filesystem::path & percent_path, const std::filesystem::path & status_path)
battery::battery_status read_battery_status(const std::filesystem::path & percent_path, const std::filesystem::path & status_path)
{
auto charge = read_percent(percent_path);
if (not charge)
@@ -58,8 +53,9 @@ battery_status read_battery_status(const std::filesystem::path & percent_path, c
.charging = status == "Charging" or status == "Full",
};
}
} // namespace
battery_status read_battery_status()
battery::battery_status battery::get_hmd_battery()
{
// SteamOS on the Steam Frame: the charger daemon's percentage is what the system UI shows
const std::filesystem::path deckard = "/run/deckardcharger";
@@ -78,17 +74,3 @@ battery_status read_battery_status()
return {};
}
} // namespace
battery_status get_battery_status()
{
// The lobby asks every frame, the files only change every few seconds
std::unique_lock _{last_status_lock};
auto now = std::chrono::steady_clock::now();
if (now - last_read > std::chrono::seconds(5))
{
last_status = read_battery_status();
last_read = now;
}
return last_status;
}
+1
View File
@@ -584,6 +584,7 @@ void scene::remove(entt::entity entity)
void scene::on_unfocused() {}
void scene::on_focused() {}
void scene::on_xr_event(const xr::event &) {}
void scene::on_battery_update(battery::device, const battery::battery_status &) {}
bool scene::on_input_key_down(uint8_t key_code)
{
+2
View File
@@ -19,6 +19,7 @@
#pragma once
#include "battery.h"
#include "render/image_loader.h"
#include "render/scene_loader.h"
#include "render/scene_renderer.h"
@@ -209,6 +210,7 @@ public:
void set_focused(bool status);
virtual void render(const XrFrameState &) = 0;
virtual void on_xr_event(const xr::event &);
virtual void on_battery_update(battery::device device, const battery::battery_status &);
virtual bool on_input_key_down(uint8_t key_code);
virtual bool on_input_key_up(uint8_t key_code);
+2 -1
View File
@@ -19,6 +19,7 @@
#include "gui_common.h"
#include "application.h"
#include "battery.h"
#include "render/ui_theme.h"
#include "render/ui_widgets.h"
@@ -37,7 +38,7 @@ float toggle_width()
std::optional<battery_indicator> battery_status_indicator(XrTime now)
{
const auto battery = get_battery_status();
const auto battery = application::get_battery_monitor().get_battery_status(battery::device::head);
if (not battery.charge)
return std::nullopt;
+5
View File
@@ -1411,6 +1411,11 @@ void scenes::lobby::on_xr_event(const xr::event & event)
if (next_scene)
next_scene->on_xr_event(event);
}
void scenes::lobby::on_battery_update(battery::device device, const battery::battery_status & battery)
{
if (next_scene)
next_scene->on_battery_update(device, battery);
}
scene::meta & scenes::lobby::get_meta_scene()
{
+1
View File
@@ -270,6 +270,7 @@ public:
void on_unfocused() override;
void on_focused() override;
void on_xr_event(const xr::event &) override;
void on_battery_update(battery::device device, const battery::battery_status &) override;
static meta & get_meta_scene();
};
+31
View File
@@ -1305,6 +1305,12 @@ void scenes::stream::setup(const to_headset::video_stream_description & descript
spdlog::info("setup, refresh rate {}", description.refresh_rate);
session.set_refresh_rate(description.refresh_rate);
battery & battery_monitor = application::get_battery_monitor();
for (auto device: magic_enum::enum_values<battery::device>())
{
on_battery_update(device, battery_monitor.get_battery_status(device));
}
std::unique_lock lock(decoder_mutex);
if (video_stream_description == description)
return;
@@ -1536,6 +1542,31 @@ void scenes::stream::on_xr_event(const xr::event & event)
}
}
void scenes::stream::on_battery_update(battery::device device, const battery::battery_status & battery)
{
device_id id = [&] {
switch (device)
{
case battery::device::head:
return device_id::HEAD;
case battery::device::left_controller:
return device_id::LEFT_CONTROLLER;
case battery::device::right_controller:
return device_id::RIGHT_CONTROLLER;
case battery::device::gamepad:
return device_id::GAMEPAD;
default:
assert(false);
__builtin_unreachable();
}
}();
network_session->send_control(from_headset::battery{
.device = id,
.charge = battery.charge,
.charging = battery.charging,
});
}
bool scenes::stream::forward_hid_input(from_headset::hid::input_t packet, bool device_enabled)
{
// hid_forwarding is whether the server permits it; device_enabled is the headset toggle.
+1
View File
@@ -248,6 +248,7 @@ public:
void on_focused() override;
void on_unfocused() override;
void on_xr_event(const xr::event &) override;
void on_battery_update(battery::device device, const battery::battery_status &) override;
bool on_input_key_down(uint8_t key_code) override;
bool on_input_key_up(uint8_t key_code) override;
-63
View File
@@ -18,7 +18,6 @@
*/
#include "application.h"
#include "battery.h"
#include "stream.h"
#include "utils/overloaded.h"
#include "wivrn_packets.h"
@@ -279,9 +278,6 @@ void scenes::stream::tracking()
application::instance().setup_jni();
#endif
XrTime next_battery_check = 0;
const XrDuration battery_check_interval = 30'000'000'000; // 30s
magic_enum::containers::array<device_id, XrSpace> spaces{};
const auto & config = application::get_config();
@@ -346,8 +342,6 @@ void scenes::stream::tracking()
std::vector<serialization_packet> packets;
const bool battery = instance.has_extension(XR_EXT_INTERACTION_PROFILE_BATTERY_STATE_DISPLAY_EXTENSION_NAME);
const bool hand_tracking = config.check_feature(feature::hand_tracking);
std::optional<xr::hand_tracker> left_hand;
std::optional<xr::hand_tracker> right_hand;
@@ -592,63 +586,6 @@ void scenes::stream::tracking()
throw;
}
// FIXME: switch to event based
if (next_battery_check < now)
{
auto status = get_battery_status();
network_session->send_control(from_headset::battery{
.device = device_id::HEAD,
.charge = status.charge,
.charging = status.charging,
});
if (battery)
{
static std::array paths{
std::make_pair("/user/hand/left", device_id::LEFT_CONTROLLER),
std::make_pair("/user/hand/right", device_id::RIGHT_CONTROLLER),
std::make_pair("/user/gamepad", device_id::GAMEPAD),
};
for (auto [path, device]: paths)
{
XrResult res;
XrPath p;
if (res = xrStringToPath(instance, path, &p); !XR_SUCCEEDED(res))
{
spdlog::warn("xrStringToPath(\"{}\") returned {} when querying battery, continuing", path, xr::to_string(res));
continue;
}
XrBatteryStateDisplayEXT battery_state{
.type = XR_TYPE_BATTERY_STATE_DISPLAY_EXT,
};
XrInteractionProfileState profile_state{
.type = XR_TYPE_INTERACTION_PROFILE_STATE,
.next = &battery_state,
};
if (res = xrGetCurrentInteractionProfile(session, p, &profile_state); !XR_SUCCEEDED(res))
{
spdlog::warn("xrGetCurrentInteractionProfile returned {} when querying battery, continuing", xr::to_string(res));
continue;
}
std::optional<float> charge{};
if (battery_state.stateFlags & XR_BATTERY_STATE_DISPLAY_STATE_VALID_BIT_EXT)
charge = battery_state.batteryLevel;
network_session->send_control(from_headset::battery{
.device = device,
.charge = charge,
.charging = (battery_state.stateFlags & XR_BATTERY_STATE_DISPLAY_STATE_CHARGING_BIT_EXT) != 0,
});
}
}
next_battery_check = now + battery_check_interval;
}
if (auto fb = std::get_if<xr::fb_body_tracker>(&body_tracker); fb and fb->should_send_skeleton())
{
try