Meshtastic-Apple/Meshtastic/Views/Settings/Config/Module/DetectionSensorConfig.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

263 lines
9.8 KiB
Swift

//
// DetectionSensorModule.swift
// Meshtastic
//
// Copyright(c) Garth Vander Houwen 8/16/23.
//
import MeshtasticProtobufs
import OSLog
import SwiftUI
enum DetectionSensorRole: String, CaseIterable, Equatable, Decodable {
case sensor
case client
var description: String {
switch self {
case .sensor:
return "Sensor"
case .client:
return "Client"
}
}
var localized: String { self.rawValue.localized }
}
struct DetectionSensorConfig: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var accessoryManager: AccessoryManager
@Environment(\.dismiss) private var goBack
var node: NodeInfoEntity?
@State private var isPresentingSaveConfirm: Bool = false
@State var hasChanges: Bool = false
@AppStorage("detectionSensorRole") private var role: DetectionSensorRole = .sensor
@AppStorage("enableDetectionNotifications") private var detectionNotificationsEnabled = false
/// Module Config Settings
@State var enabled = false
@State var sendBell: Bool = false
@State var name: String = ""
@State var triggerType = 0
@State var usePullup: Bool = false
@State private var minimumBroadcastSecs: UpdateInterval = UpdateInterval(from: 0)
@State private var stateBroadcastSecs: UpdateInterval = UpdateInterval(from: 0)
@State var monitorPin = 0
var body: some View {
Form {
ConfigHeader(title: "Detection Sensor", config: \.detectionSensorConfig, node: node, onAppear: setDetectionSensorValues)
Section(header: Text("Options")) {
Toggle(isOn: $enabled) {
Label("Enabled", systemImage: "dot.radiowaves.right")
Text("Enables the detection sensor module, it needs to be enabled on both the node with the sensor, and any nodes that you want to receive detection sensor text messages or view the detection sensor log and chart.")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if enabled {
HStack {
Picker(selection: $role, label: Text("Role")) {
ForEach(DetectionSensorRole.allCases, id: \.self) { r in
Text(r.description)
.tag(r)
}
}
.pickerStyle(SegmentedPickerStyle())
.padding(.top, 5)
.padding(.bottom, 5)
}
}
}
if enabled && role == .client {
Section(header: Text("Client options")) {
Toggle(isOn: $detectionNotificationsEnabled) {
Label("Enable Notifications", systemImage: "bell.badge")
Text("Detection sensor messages are received as text messages. If you enable notifications you will recieve a notification for each detection message received and a corresponding unread message badge.")
}
}
}
if enabled && role == .sensor {
Section(header: Text("Sensor options")) {
Toggle(isOn: $sendBell) {
Label("Send Bell", systemImage: "bell")
Text("Send ASCII bell with alert message. Useful for triggering external notification on bell.")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
HStack {
Label("Name", systemImage: "signature")
TextField("Friendly name", text: $name, axis: .vertical)
.foregroundColor(.gray)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: name) {
var totalBytes = name.utf8.count
// Only mess with the value if it is too big
while totalBytes > 20 {
name = String(name.dropLast())
totalBytes = name.utf8.count
}
}
}
.listRowSeparator(.hidden)
Text("Friendly name used to format message sent to mesh. Example: A name \"Motion\" would result in a message \"Motion detected\"")
.font(.callout)
.foregroundStyle(.gray)
Picker("GPIO Pin to monitor", selection: $monitorPin) {
ForEach(0..<49) {
if $0 == 0 {
Text("Unset")
} else {
Text("Pin \($0)")
}
}
}
.pickerStyle(DefaultPickerStyle())
Picker("TriggerType", selection: $triggerType) {
ForEach(TriggerTypes.allCases) { tt in
Text(tt.name).tag(tt.rawValue)
}
}
.pickerStyle(DefaultPickerStyle())
.listRowSeparator(.hidden)
Toggle(isOn: $usePullup) {
Label("Uses pullup resistor", systemImage: "arrow.up.to.line")
Text("Whether or not use INPUT_PULLUP mode for GPIO pin. Only applicable if the board uses pull-up resistors on the pin")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
Section(header: Text("Update Interval")) {
UpdateIntervalPicker(
config: .detectionSensorMinimum,
pickerLabel: "Minimum time between detection broadcasts",
selectedInterval: $minimumBroadcastSecs
)
.listRowSeparator(.hidden)
Text("Mininum time between detection broadcasts. Default is 45 seconds.")
.font(.callout)
.foregroundStyle(.gray)
.listRowSeparator(.visible)
UpdateIntervalPicker(
config: .detectionSensorState,
pickerLabel: "State Broadcast Interval",
selectedInterval: $stateBroadcastSecs
)
.listRowSeparator(.hidden)
Text("How often to send detection sensor state to mesh regardless of detection. Default is Never.")
.font(.callout)
.foregroundStyle(.gray)
}
}
}
.scrollDismissesKeyboard(.interactively)
.disabled(!accessoryManager.isConnected || node?.detectionSensorConfig == nil)
.safeAreaInset(edge: .bottom, alignment: .center) {
HStack(spacing: 0) {
SaveConfigButton(node: node, hasChanges: $hasChanges) {
let connectedNode = getNodeInfo(id: accessoryManager.activeDeviceNum ?? -1, context: context)
if connectedNode != nil {
var dsc = ModuleConfig.DetectionSensorConfig()
dsc.enabled = self.enabled
dsc.sendBell = self.sendBell
dsc.name = self.name
dsc.monitorPin = UInt32(self.monitorPin)
dsc.detectionTriggerType = TriggerTypes(rawValue: triggerType)!.protoEnumValue()
dsc.usePullup = self.usePullup
dsc.minimumBroadcastSecs = UInt32(self.minimumBroadcastSecs.intValue)
dsc.stateBroadcastSecs = UInt32(self.stateBroadcastSecs.intValue)
Task {
do {
_ = try await accessoryManager.saveDetectionSensorModuleConfig(config: dsc, fromUser: connectedNode!.user!, toUser: node!.user!)
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()
}
} catch {
Logger.mesh.error("Unable to save detection sensor module config")
}
}
}
}}}
.navigationTitle("Detection Sensor Config")
.navigationBarItems(
trailing: ZStack {
ConnectedDevice(
deviceConnected: accessoryManager.isConnected,
name: accessoryManager.activeConnection?.device.shortName ?? "?"
)
}
)
.onFirstAppear {
// Need to request a DetectionSensorModuleConfig 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 && node.num != connectedNode.num {
/// 2.5 Administration with session passkey
let expiration = node.sessionExpiration ?? Date()
if expiration < Date() || node.detectionSensorConfig == nil {
Task {
do {
Logger.mesh.info("⚙️ Empty or expired detection sensor module config requesting via PKI admin")
try await accessoryManager.requestDetectionSensorModuleConfig(fromUser: connectedNode.user!, toUser: node.user!)
} catch {
Logger.mesh.info("🚨 Unable to send detection sensor module config request")
}
}
}
} else {
/// Legacy Administration
Logger.mesh.info("☠️ Using insecure legacy admin that is no longer supported, please upgrade your firmware.")
}
}
}
}
}
.onChange(of: enabled) { _, newEnabled in
if newEnabled != node?.detectionSensorConfig?.enabled { hasChanges = true }
}
.onChange(of: sendBell) { _, newSendBell in
if newSendBell != node?.detectionSensorConfig?.sendBell { hasChanges = true }
}
.onChange(of: triggerType) { _, newTriggerType in
if newTriggerType != node?.detectionSensorConfig?.triggerType ?? 0 { hasChanges = true }
}
.onChange(of: usePullup) { _, newUsePullup in
if newUsePullup != node?.detectionSensorConfig?.usePullup { hasChanges = true }
}
.onChange(of: name) { _, newName in
if newName != node?.detectionSensorConfig?.name ?? "" { hasChanges = true }
}
.onChange(of: monitorPin) { _, newMonitorPin in
if newMonitorPin != node?.detectionSensorConfig?.monitorPin ?? 0 { hasChanges = true }
}
.onChange(of: minimumBroadcastSecs.intValue) { _, newMinimumBroadcastSecs in
if newMinimumBroadcastSecs != node?.detectionSensorConfig?.minimumBroadcastSecs ?? 0 { hasChanges = true }
}
.onChange(of: stateBroadcastSecs.intValue) { _, newStateBroadcastSecs in
if newStateBroadcastSecs != node?.detectionSensorConfig?.stateBroadcastSecs ?? 0 { hasChanges = true }
}
.onChange(of: detectionNotificationsEnabled) { _, newDetectionNotificationsEnabled in
UserDefaults.enableDetectionNotifications = newDetectionNotificationsEnabled
}
}
func setDetectionSensorValues() {
self.enabled = (node?.detectionSensorConfig?.enabled ?? false)
self.sendBell = (node?.detectionSensorConfig?.sendBell ?? false)
self.name = (node?.detectionSensorConfig?.name ?? "")
self.monitorPin = Int(node?.detectionSensorConfig?.monitorPin ?? 0)
self.usePullup = (node?.detectionSensorConfig?.usePullup ?? false)
self.triggerType = Int(node?.detectionSensorConfig?.triggerType ?? 0)
self.minimumBroadcastSecs = UpdateInterval(from: Int(node?.detectionSensorConfig?.minimumBroadcastSecs ?? 60))
self.stateBroadcastSecs = UpdateInterval(from: Int(node?.detectionSensorConfig?.stateBroadcastSecs ?? 0))
self.hasChanges = false
}
}