Meshtastic-Apple/Meshtastic/Views/Settings/Config/PowerConfig.swift
Garth Vander Houwen 9797eb9a0e
2.7.4 Working Changes (#1415)
* Update messaging list separator insets

* Dont show unread messages or notifications for emoji reactions matching iMessage.

* Restore ble state method (#1416)

* Restore BLE State

* Log privacy

* AccessoryManager to handle restored connection

* Comment task out

* Update restore state function based on conversation with jake

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Two Column Node List (#1425)

* Restore BLE State

* Log privacy

* AccessoryManager to handle restored connection

* Comment task out

* Switch the node list to a two column layout

* Keep asian translations of channel details string

* Update restore state function based on conversation with jake

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* always show node list search bar

* Update auto correct modifier

* Dont show online animations for ios 17, remove online animation from node map, remove online circle from position popover

* Work in progress.

* Update detents

* Gate the discovery process while restoring

* Use geometry reader to size weather tiles on node details

* Update BLE Transport

* Update location weather condistion styles

* Log privacy in didReceive

* Remove extra dividers from admin key config, fix onboarding typo

* Bump minimum catalyst target

* Bump mac target version

* Use @FetchRequest for UserList to try and use less memory on ios 17

* Revert change to @fetchrequest

* Stab in the dark for Devices crash

* Updated UserList (back?) to @FetchRequest

* Set mac minimum to 15

* Nil out continuation after use

* Use @FetchRequest for the node list to stop crashes on iOS 17

* Handle failed connections during restoration

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update protos

* Update protos

* Remove stale keys

* Serbian translations update (#1422)

* Log privacy

* Add Serbian translations

---------

Co-authored-by: Garth Vander Houwen <garthvh@yahoo.com>

* Clarify public key sub-text in security settings (#1412)

* Clarify public key sub-text in settings

* Trigger lint

* freq slot num pad (#1410)

* kill keyboard toolbar on lora config

* delete extranious scrollDismissesKeyboard

* Properly set catalyst target

* Update Meshtastic/Views/Onboarding/DeviceOnboarding.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Views/Settings/Config/SecurityConfig.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Enums/DeviceEnums.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Make current location nilable, remove log spam

* clean up toUser logic

* Fix telemetry entity not added in nodeInfoPacket

* fix typo: powerMetrics.hasChXCurrent mismatch

* Duplicate decoding of telemetry.current removed

* Clean up mesh map fetch request and distance filter logic

* Revert attempt to fix message logic

* Bump datadog version

* Missing message fix, attempt #2 (#1431)

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>

* Retry fewer times for longer

* Revert "Missing message fix, attempt #2 (#1431)" (#1432)

This reverts commit a96d318adb.

* Make retry 2 seconds

* Add back link to node details from position popover without navigation stack and link, clear notifications when deleting database

* Add clear notifications function

* Link from channel messages to node info

* Link to node details

* Discovery on retry fix

* Discovery on retry fix fix

* Add contact to device node db if you get an encrypted send faild routing error

* Seperate channel message view into two views for better performance.

* Refactor User Message List

* Update device hardware

Add liquid glass to config save button

* Save button cleanup

* Update button structure on users view

* Move encrypted send logic out of the router. Update protos

* Restore node long- and short- names (#1442)

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLEConnection.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Revert routing error

* Toggle for enabling device telemetry broadcast enable

* Update

* Enhancements for interval dropdowns (#1445)

* Cleanup

* Fix core data version

* Add never to update interval

* Device telemetry Enabled Boolean (#1446)

* Update core data and interval picker

* Move formatter

* Rework to nest options under enabled

* Clearer names

* Safer devicehardware api call, remove node history filter from mesh map

* Fix build

* Simplify mesh map filter

* Remove stale translation keys

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Nikola Dašić <dasic.nikola@yandex.com>
Co-authored-by: Spencer Smith <dontaskspencer@gmail.com>
Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2025-10-05 17:51:18 -07:00

228 lines
7.7 KiB
Swift

import SwiftUI
import MeshtasticProtobufs
import OSLog
struct PowerConfig: View {
@Environment(\.managedObjectContext) private var context
@EnvironmentObject var accessoryManager: AccessoryManager
@Environment(\.dismiss) private var goBack
let node: NodeInfoEntity?
@State private var isPowerSaving = false
@State private var shutdownOnPowerLoss = false
@State private var shutdownAfterSecs: UpdateInterval = UpdateInterval(from: 0)
@State private var adcOverride = false
@State private var adcMultiplier: Float = 0.0
@State private var waitBluetoothSecs = 60
@State private var lsSecs = 300
@State private var minWakeSecs = 10
@State private var currentDevice: DeviceHardware?
@State private var hasChanges: Bool = false
@FocusState private var isFocused: Bool
var body: some View {
Form {
ConfigHeader(title: "Power Config", config: \.powerConfig, node: node, onAppear: setPowerValues)
Section {
if (currentDevice?.architecture == .esp32 || currentDevice?.architecture == .esp32S3) || (currentDevice?.architecture == .nrf52840 && (node?.deviceConfig?.role ?? 0 == 5 || node?.deviceConfig?.role ?? 0 == 6)) {
Toggle(isOn: $isPowerSaving) {
Label("Power Saving", systemImage: "bolt")
Text("Will sleep everything as much as possible, for the tracker and sensor role this will also include the lora radio. Don't use this setting if you want to use your device with the phone apps or are using a device without a user button.")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
Toggle(isOn: $shutdownOnPowerLoss) {
Label("Shutdown on Power Loss", systemImage: "power")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if shutdownOnPowerLoss {
UpdateIntervalPicker(
config: .all,
pickerLabel: "After",
selectedInterval: $shutdownAfterSecs
)
}
} header: {
Text("Power")
}
if currentDevice?.architecture == .esp32 || currentDevice?.architecture == .esp32S3 {
Section {
Toggle(isOn: $adcOverride) {
Text("ADC Override")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if adcOverride {
HStack {
Text("Multiplier")
Spacer()
FloatField(title: "Multiplier", number: $adcMultiplier) {
(2.0 ... 6.0).contains($0)
}
.focused($isFocused)
Spacer()
}
}
} header: {
Text("Battery")
}
}
}
.disabled(!accessoryManager.isConnected || node?.powerConfig == nil)
.safeAreaInset(edge: .bottom, alignment: .center) {
HStack(spacing: 0) {
SaveConfigButton(node: node, hasChanges: $hasChanges) {
guard let deviceNum = accessoryManager.activeDeviceNum,
let connectedNode = getNodeInfo(id: deviceNum, context: context),
let fromUser = connectedNode.user,
let toUser = node?.user else {
return
}
var config = Config.PowerConfig()
config.isPowerSaving = isPowerSaving
config.onBatteryShutdownAfterSecs = shutdownOnPowerLoss ? UInt32(shutdownAfterSecs.intValue) : 0
config.adcMultiplierOverride = adcOverride ? adcMultiplier : 0
config.waitBluetoothSecs = UInt32(waitBluetoothSecs)
config.lsSecs = UInt32(lsSecs)
config.minWakeSecs = UInt32(minWakeSecs)
Task {
_ = try await accessoryManager.savePowerConfig(
config: config,
fromUser: fromUser,
toUser: toUser
)
Task { @MainActor in
// Should show a saved successfully alert once I know that to be true
// for now just disable the button after a successful save
hasChanges = false
goBack()
}
}
}
}
}
.navigationTitle("Power Config")
.navigationBarItems(trailing: ZStack {
ConnectedDevice(deviceConnected: accessoryManager.isConnected, name: accessoryManager.activeConnection?.device.shortName ?? "?")
})
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Dismiss") {
isFocused = false
}
.font(.subheadline)
}
}
.onFirstAppear {
Api().loadDeviceHardwareData { (hw) in
for device in hw {
let currentHardware = node?.user?.hwModel ?? "UNSET"
let deviceString = device.hwModelSlug.replacingOccurrences(of: "_", with: "")
if deviceString == currentHardware {
currentDevice = device
}
}
}
// Need to request a NetworkConfig from the remote node before allowing changes
if let deviceNum = accessoryManager.activeDeviceNum, let node {
let connectedNode = getNodeInfo(id: deviceNum, context: context)
if let connectedNode {
if node.num != deviceNum {
if UserDefaults.enableAdministration {
/// 2.5 Administration with session passkey
let expiration = node.sessionExpiration ?? Date()
if expiration < Date() || node.powerConfig == nil {
Task {
do {
Logger.mesh.info("⚙️ Empty or expired power config requesting via PKI admin")
try await accessoryManager.requestPowerConfig(fromUser: connectedNode.user!, toUser: node.user!)
} catch {
Logger.mesh.info("🚨 Power config request failed")
}
}
}
} else {
/// Legacy Administration
Logger.mesh.info("☠️ Using insecure legacy admin that is no longer supported, please upgrade your firmware.")
}
}
}
}
}
.onChange(of: isPowerSaving) { oldIsPowerSaving, newIsPowerSaving in
if oldIsPowerSaving != newIsPowerSaving && newIsPowerSaving != node?.powerConfig?.isPowerSaving { hasChanges = true }
}
.onChange(of: shutdownOnPowerLoss) { _, newShutdownOnPowerLoss in
if newShutdownOnPowerLoss {
hasChanges = true
}
}
.onChange(of: shutdownAfterSecs.intValue) { oldShutdownAfterSecs, newShutdownAfterSecs in
if oldShutdownAfterSecs != newShutdownAfterSecs && newShutdownAfterSecs != node?.powerConfig?.minWakeSecs ?? -1 { hasChanges = true }
}
.onChange(of: adcOverride) {
hasChanges = true
}
.onChange(of: adcMultiplier) { _, newAdcMultiplier in
if newAdcMultiplier != node?.powerConfig?.adcMultiplierOverride ?? -1 { hasChanges = true }
}
.onChange(of: waitBluetoothSecs) { oldWaitBluetoothSecs, newWaitBluetoothSecs in
if oldWaitBluetoothSecs != newWaitBluetoothSecs && newWaitBluetoothSecs != node?.powerConfig?.waitBluetoothSecs ?? -1 { hasChanges = true }
}
.onChange(of: lsSecs) { _, newLsSecs in
if newLsSecs != node?.powerConfig?.lsSecs ?? -1 { hasChanges = true }
}
.onChange(of: minWakeSecs) { _, newMinWakeSecs in
if newMinWakeSecs != node?.powerConfig?.minWakeSecs ?? -1 { hasChanges = true }
}
}
private func setPowerValues() {
isPowerSaving = node?.powerConfig?.isPowerSaving ?? isPowerSaving
shutdownAfterSecs = UpdateInterval(from: Int(node?.powerConfig?.onBatteryShutdownAfterSecs ?? Int32(shutdownAfterSecs.intValue)))
shutdownOnPowerLoss = shutdownAfterSecs.intValue != 0
adcMultiplier = node?.powerConfig?.adcMultiplierOverride ?? adcMultiplier
adcOverride = adcMultiplier != 0
waitBluetoothSecs = Int(node?.powerConfig?.waitBluetoothSecs ?? Int32(waitBluetoothSecs))
lsSecs = Int(node?.powerConfig?.lsSecs ?? Int32(lsSecs))
minWakeSecs = Int(node?.powerConfig?.minWakeSecs ?? Int32(minWakeSecs))
}
}
/// Helper view for isolating user float input that can be validated before being applied.
private struct FloatField: View {
let title: String
@Binding var number: Float
var isValid: (Float) -> Bool = { _ in true }
@State private var typingNumber: Float = 0.0
var body: some View {
TextField(title.localized, value: $typingNumber, format: .number)
.foregroundColor(.gray)
.multilineTextAlignment(.trailing)
.onChange(of: typingNumber) {
if isValid(typingNumber) {
number = typingNumber
} else {
typingNumber = number
}
}
.keyboardType(.decimalPad)
.onAppear {
typingNumber = number
}
}
}