summaryrefslogtreecommitdiff
path: root/watchos/InfiniSolar/InfiniSolar WatchKit Extension/InverterState.swift
blob: cd6d5fa739f431e91beed6f2f33547dcf1944a28 (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
//
//  InverterStatusFetcher.swift
//  InfiniSolar WatchKit Extension
//
//  Created by Evgeny Zinoviev on 03.08.2021.
//

import Alamofire
import SwiftyJSON

public class InverterState: ObservableObject {
    @Published var status: InverterStatus
    @Published var fetchError: Bool = false
    
    var timer: Timer?
    var request: DataRequest?
    
    func startFetching() {
        if self.timer != nil {
            self.stopFetching()
        }
        
        self.timer = Timer.scheduledTimer(timeInterval: 1,
                                          target: self,
                                          selector: #selector(fetchStatus),
                                          userInfo: nil,
                                          repeats: true)
//        self.timer?.fire()
    }
    
    func stopFetching() {
        if self.request != nil {
            self.request?.cancel()
            self.request = nil
        }
        
        self.fetchError = false
        self.timer?.invalidate()
        self.timer = nil
    }
    
    @objc func fetchStatus() {
        self.fetchError = false
        
        self.request = AF.request("http://192.168.5.223:8380/get-status/").responseJSON {
            response in
            switch response.result {
                case .success(let value):
                    let json = JSON(value)
                    self.status.activePower = json["data"]["ac_output_active_power"]["value"].int ?? 0
                    self.status.batteryVoltage = json["data"]["battery_voltage"]["value"].float ?? 0
                    self.status.batteryCapacity = json["data"]["battery_capacity"]["value"].int ?? 0
                    self.status.pvInputPower = json["data"]["pv1_input_power"]["value"].int ?? 0
            
                case .failure(let error):
                    switch (error) {
                    case .explicitlyCancelled:
                        print("InverterStatusFetcher: request has been canceled")
                        break
                        
                    default:
                        self.fetchError = true
                        self.timer?.invalidate()
                        self.timer = nil
                    }
            }
            
            self.request = nil
        }
    }
    
    init() {
        self.fetchError = false
        self.status = InverterStatus(batteryVoltage: 0, batteryCapacity: 0, activePower: 0, pvInputPower: 0)
        self.timer = nil
        self.request = nil
    }
}