summaryrefslogtreecommitdiff
path: root/watchos/InfiniSolar/InfiniSolar WatchKit Extension/PumpState.swift
blob: 4d4e5cc7598fa18f8dae0510d708d0a9c09a761c (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
85
86
//
//  PumpState.swift
//  InfiniSolar WatchKit Extension
//
//  Created by Evgeny Zinoviev on 09.08.2021.
//

import Alamofire
import SwiftyJSON

public class PumpState: ObservableObject {
    @Published var isEnabled: Bool
    @Published var error: Bool
    @Published var loading: Bool
    @Published var setting: Bool
    
    var request: DataRequest?
    
    init() {
        self.loading = true
        self.error = false
        self.isEnabled = false
        self.request = nil
        self.setting = false
    }
    
    func fetch() {
        self.request = AF.request("http://192.168.5.223:8382/get/").responseJSON { response in
            self.loading = false
            
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                self.isEnabled = json["data"].string == "on"
                
            case .failure(let error):
                switch (error) {
                case .explicitlyCancelled:
                    break
                    
                default:
                    print(error)
                    self.error = true
                }
            }
            
//            self.loading = false
            self.request = nil
        }
    }
    
    func setState(on: Bool) {
        self.setting = true
        self.request = AF.request("http://192.168.5.223:8382/" + (on ? "on" : "off") + "/").responseJSON { response in
            self.setting = false
            
            switch response.result {
            case .success(_):
                self.isEnabled = on
                
            case .failure(let error):
                switch (error) {
                case .explicitlyCancelled:
                    break
                    
                default:
                    print(error)
                    self.error = true
                }
            }
            
            self.request = nil
        }
    }
    
    func abort() {
        if self.request != nil {
            self.request?.cancel()
            self.request = nil
        }
        
        self.error = false
        self.loading = true
        self.isEnabled = false
    }
}