RemoteViewController.swift 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // RemoteViewController.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2024-07-19.
  6. // Copyright © 2024 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. import SwiftUI
  11. import HealthKit
  12. class RemoteViewController: UIViewController {
  13. private var statusMessage: ObservableValue<String> {
  14. return Observable.shared.statusMessage
  15. }
  16. override func viewDidLoad() {
  17. super.viewDidLoad()
  18. let remoteView = RemoteView(
  19. onRefreshStatus: refreshStatus,
  20. onCancelExistingTarget: cancelExistingTarget,
  21. sendTempTarget: sendTempTarget
  22. )
  23. let hostingController = UIHostingController(rootView: remoteView)
  24. addChild(hostingController)
  25. view.addSubview(hostingController.view)
  26. hostingController.view.translatesAutoresizingMaskIntoConstraints = false
  27. NSLayoutConstraint.activate([
  28. hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
  29. hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
  30. hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
  31. hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
  32. ])
  33. hostingController.didMove(toParent: self)
  34. initialSetup()
  35. }
  36. private func initialSetup() {
  37. // Perform initial setup checks here
  38. // For example, load the Nightscout URL and token from user defaults or another source
  39. }
  40. private func refreshStatus() {
  41. // Refresh the status to check current temp targets and other relevant info
  42. }
  43. private func cancelExistingTarget() {
  44. // Cancel the existing temp target
  45. }
  46. private func sendTempTarget(newTarget: HKQuantity, duration: Int) {
  47. let tempTargetBody: [String: Any] = [
  48. "enteredBy": "LoopFollow",
  49. "eventType": "Temporary Target",
  50. "reason": "Manual",
  51. "targetTop": newTarget.doubleValue(for: .milligramsPerDeciliter),
  52. "targetBottom": newTarget.doubleValue(for: .milligramsPerDeciliter),
  53. "duration": duration,
  54. "created_at": ISO8601DateFormatter().string(from: Date())
  55. ]
  56. NightscoutUtils.executePostRequest(eventType: .treatments, body: tempTargetBody) { (result: Result<[TreatmentResponse], Error>) in
  57. switch result {
  58. case .success(let response):
  59. print("Success: \(response)")
  60. DispatchQueue.main.async {
  61. self.statusMessage.set("Temp target sent successfully.")
  62. }
  63. case .failure(let error):
  64. print("Error: \(error)")
  65. DispatchQueue.main.async {
  66. self.statusMessage.set("Failed to send temp target: \(error.localizedDescription)")
  67. }
  68. }
  69. }
  70. }
  71. }