blob: f387b8b4010a71cdc6a8ee7db9973ce22f7c11c1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
//
// RoomState.swift
// InfiniSolar WatchKit Extension
//
// Created by Evgeny Zinoviev on 09.08.2021.
//
import Alamofire
import SwiftyJSON
extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
public class RoomState: ObservableObject {
@Published var temp: Double
@Published var rh: Double
@Published var error: Bool
var timer: Timer?
var request: DataRequest?
init() {
self.error = false
self.timer = nil
self.request = nil
self.temp = 0
self.rh = 0
}
func start() {
if self.timer != nil {
self.stop()
}
self.timer = Timer.scheduledTimer(timeInterval: 5,
target: self,
selector: #selector(fetch),
userInfo: nil,
repeats: true)
self.timer?.fire()
}
func stop() {
if self.request != nil {
self.request?.cancel()
self.request = nil
}
self.error = false
self.timer?.invalidate()
self.timer = nil
}
@objc func fetch() {
self.request = AF.request("http://192.168.5.223:8381/read/").responseJSON { response in
self.request = nil
switch response.result {
case .success(let value):
let j = JSON(value)
self.temp = (j["temp"].double ?? 0).rounded(toPlaces: 2)
self.rh = (j["humidity"].double ?? 0).rounded(toPlaces: 2)
case .failure(let error):
switch (error) {
case .explicitlyCancelled:
break
default:
self.error = true
self.timer?.invalidate()
self.timer = nil
}
}
}
}
}
|