/
CCServerManager.swift
1706 lines (1365 loc) · 38.8 KB
/
CCServerManager.swift
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// CCServerManager.swift
// chickencoop
//
// Created by Vincent Moscaritolo on 1/1/22.
//
import Foundation
import SwiftRadix
import CoreLocation
import UIKit
//
//extension CaseIterable where Self: RawRepresentable {
//
// static var allValues: [RawValue] {
// return allCases.map { $0.rawValue }
// }
//}
enum device_state_t :Int{
case
DEVICE_STATE_UNKNOWN = 0,
DEVICE_STATE_DISCONNECTED,
DEVICE_STATE_CONNECTED,
DEVICE_STATE_ERROR,
DEVICE_STATE_TIMEOUT
}
extension device_state_t: Codable {
enum Key: CodingKey {
case rawValue
}
enum CodingError: Error {
case unknownValue
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
let rawValue = try container.decode(Int.self, forKey: .rawValue)
switch rawValue {
case 0:
self = .DEVICE_STATE_UNKNOWN
case 1:
self = .DEVICE_STATE_DISCONNECTED
case 2:
self = .DEVICE_STATE_CONNECTED
case 3:
self = .DEVICE_STATE_ERROR
case 4:
self = .DEVICE_STATE_TIMEOUT
default:
self = .DEVICE_STATE_UNKNOWN
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
switch self {
case .DEVICE_STATE_UNKNOWN:
try container.encode(0, forKey: .rawValue)
case .DEVICE_STATE_DISCONNECTED:
try container.encode(1, forKey: .rawValue)
case .DEVICE_STATE_CONNECTED:
try container.encode(2, forKey: .rawValue)
case .DEVICE_STATE_ERROR:
try container.encode(3, forKey: .rawValue)
case .DEVICE_STATE_TIMEOUT:
try container.encode(4, forKey: .rawValue)
}
}
}
enum DoorState :Int{
case
unknown = 0,
open,
opening,
closed,
closing
}
extension DoorState: Codable {
enum Key: CodingKey {
case rawValue
}
enum CodingError: Error {
case unknownValue
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
let rawValue = try container.decode(Int.self, forKey: .rawValue)
switch rawValue {
case 0:
self = .unknown
case 1:
self = .open
case 2:
self = .opening
case 3:
self = .closed
case 4:
self = .closing
default:
self = .unknown
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
switch self {
case .unknown:
try container.encode(0, forKey: .rawValue)
case .open:
try container.encode(1, forKey: .rawValue)
case .opening:
try container.encode(2, forKey: .rawValue)
case .closed:
try container.encode(3, forKey: .rawValue)
case .closing:
try container.encode(4, forKey: .rawValue)
}
}
func description() -> String {
var str = "Unknown"
switch self {
case .open: str = "Open"
case .opening: str = "Opening"
case .closed: str = "Closed"
case .closing: str = "Closing"
default:
break
}
return str
}
}
class RESTErrorInfo: Codable {
let code: Int
let message: String
let detail: String?
let cmdDetail: String?
}
class RESTError: Codable {
let error: RESTErrorInfo
}
enum RESTdeviceStatus : Int {
case unknown = 0
case disconnected
case connected
case error
case timeout
}
struct RESTStatus: Codable {
var state: Int
var cpuTemp: Double?
var stateString: String?
var buildtime: String
var version: String
let date: String
let uptime: Int
let os_sysname : String
let os_nodename : String
let os_release : String
let os_version : String
let os_machine : String
enum CodingKeys: String, CodingKey {
case state = "state"
case cpuTemp = "cpuTemp"
case stateString = "stateString"
case buildtime = "buildtime"
case version = "version"
case date = "date"
case uptime = "uptime"
case os_sysname = "os.sysname"
case os_nodename = "os.nodename"
case os_release = "os.release"
case os_version = "os.version"
case os_machine = "os.machine"
}
}
class RESTDateInfo: Codable {
let civilSunRise: Double?
let civilSunSet: Double?
let sunRise: Double?
let sunSet: Double?
let date: String
let gmtOffset: Int?
let latitude: Double?
let longitude: Double?
let midnight: Double?
let timeZone: String?
let uptime: Int
}
struct RESTValueDetails: Codable {
var display: String
var time: Double
var value: String
enum CodingKeys: String, CodingKey {
case display = "display"
case time = "time"
case value = "value"
}
}
enum RESTschemaTracking : Int {
case ignoreValue = 0
case staticValue = 1
case trackedValue = 2
case untrackedValue = 3
}
enum RESTschemaUnits : Int {
case INVALID = 0
case BOOL // Bool ON/OFF
case INT // Int
case MAH // mAh milliAmp hours
case PERMILLE // (per thousand) sign ‰
case PERCENT // (per hundred) sign ‰
case DEKAWATTHOUR // .01kWh
case WATTS // W
case MILLIVOLTS // mV
case MILLIAMPS // mA
case SECONDS // sec
case MINUTES // mins
case DEGREES_C // degC
case VOLTS // V
case HERTZ // Hz
case AMPS // A
case BINARY // Binary 8 bits 000001
case VE_PRODUCT // VE.PART
case STRING // string
case IGNORE
case DOOR_STATE
case ON_OFF
case UNKNOWN
}
struct RESTSchemaDetails: Codable {
var name: String
var suffix: String
var tracking: Int
var units: Int
enum CodingKeys: String, CodingKey {
case name = "name"
case suffix = "suffix"
case tracking = "tracking"
case units = "units"
}
init() {
name = String()
suffix = String()
tracking = RESTschemaTracking.ignoreValue.rawValue
units = RESTschemaUnits.UNKNOWN.rawValue
}
}
struct RESTSchemaList: Codable {
var schema: Dictionary<String, RESTSchemaDetails>
enum CodingKeys: String, CodingKey {
case schema = "schema"
}
}
struct RESTProperties: Codable {
var properties: Dictionary<String, String>
}
struct RESTErrorDetails: Codable {
var eTag: Double
var facility: UInt
var level: UInt
var device: UInt
var message: String
var errStr: String?
var time: Double
enum CodingKeys: String, CodingKey {
case eTag = "ETag"
case facility = "err.facility"
case level = "err.level"
case device = "err.device"
case message = "err.message"
case errStr = "err.error"
case time = "time"
}
/*
FAC_UNKNOWN,
FAC_I2C,
FAC_GPIO,
FAC_POWER,
FAC_SENSOR,
FAC_DEVICE
*/
func stringForFaciliy() -> String {
var str = ""
switch facility {
case 1: str = "I2C"
case 2: str = "GPIO"
case 3: str = "PWR"
case 4: str = "SEN"
case 5: str = "DEV"
default: break
}
return str
}
func stringForDevID() -> String {
var str = ""
if(device != 0){
str = String(format:"0x%02x", UInt8(device))
}
return str
}
func imageForLevel() -> UIImage {
var image:UIImage? = nil
switch level {
case 0: image = UIImage(systemName: "m.circle")
case 1: image = UIImage(systemName: "d.circle")
case 2: image = UIImage(systemName: "i.circle")
case 3: image = UIImage(systemName: "w.circle")
case 4: image = UIImage(systemName: "e.circle")
default: image = UIImage(systemName: "questionmark")
}
return image ?? UIImage()
}
func tintColorForLevel() ->UIColor {
var color:UIColor? = nil
switch level {
case 0: color = .lightGray
case 1: color = .systemTeal
case 2: color = .systemBlue
case 3: color = .systemOrange
case 4: color = .systemRed
default: color = UIColor()
}
return color ?? UIColor()
}
}
struct RESTErrorLog: Codable {
var errors: Array< RESTErrorDetails>?
var eTag: UInt64?
var count: UInt64
enum CodingKeys: String, CodingKey {
case errors = "errors"
case eTag = "ETag"
case count = "count"
}
init() {
errors = []
count = 0
}
}
struct RESTValuesList: Codable {
var values: Dictionary<String, RESTValueDetails>
var ETag: Int?
enum CodingKeys: String, CodingKey {
case values = "values"
case ETag = "ETag"
}
}
struct RESTTimeSpanItem: Codable {
var time: Double
var durration: TimeInterval
var value: String
}
struct RESTHistoryItem: Codable {
var time: Double
var value: String
enum CodingKeys: String, CodingKey {
case time = "time"
case value = "value"
}
}
struct RESTHistory: Codable {
var values: Array< RESTHistoryItem>
var eTag: Double?
enum CodingKeys: String, CodingKey {
case values = "values"
case eTag = "ETag"
}
init() {
values = []
}
func timeLine() -> Array<RESTTimeSpanItem> {
var timeline:Array<RESTTimeSpanItem> = []
let items = values.reversed()
let now = Date().timeIntervalSince1970
var lastValue:String = "<no value>"
var lastTime:Double = 0;
for item in items {
// did we change values
if (item.value != lastValue){
// if this is the first change - we subtract time from present
let interval:TimeInterval
= (lastTime == 0) ? now - item.time : lastTime - item.time
lastTime = item.time
lastValue = item.value
timeline.append( RESTTimeSpanItem(time: item.time,
durration: interval, value: item.value))
}
}
return timeline
}
}
struct RESTEventAction: Codable {
var cmd :String?
var deviceID :String?
enum CodingKeys: String, CodingKey {
case cmd
case deviceID
}
}
struct RESTEventTrigger: Codable {
var mins :Int?
var timeBase :Int?
var event :String?
enum CodingKeys: String, CodingKey {
case mins
case timeBase
case event
}
func triggerDate(_ solarTimes: ServerDateInfo ) ->Date {
var solarTimeFormat: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
formatter.timeZone = TimeZone(abbreviation: "UTC")
return formatter
}
var date: Date = Date.distantPast
if let sunSet = solarTimes.sunSet,
let civilSunSet = solarTimes.civilSunSet,
let civilSunRise = solarTimes.civilSunRise,
let sunRise = solarTimes.sunRise,
let midNight = solarTimes.midNight,
let mins = self.mins {
switch self.timeBase {
case 1: // TOD_ABSOLUTE
date = midNight.addingTimeInterval( Double(mins * 60))
break
case 2: // TOD_SUNRISE
date = sunRise.addingTimeInterval( Double(mins * 60))
break
case 3: // TOD_SUNSET
date = sunSet.addingTimeInterval( Double(mins * 60))
break
case 4: // TOD_CIVIL_SUNRISE
date = civilSunRise.addingTimeInterval( Double(mins * 60))
break
case 5: // TOD_CIVIL_SUNSET
date = civilSunSet.addingTimeInterval( Double(mins * 60))
break
default:
break
}
}
return date
}
}
struct RESTEventCreation: Codable {
var eventID : String?
var name : String
}
struct RESTEvent: Codable {
var eventID : String?
var name : String
var action : RESTEventAction
var trigger : RESTEventTrigger
init() {
name = String()
action = RESTEventAction()
action.cmd = String()
action.deviceID = String()
trigger = RESTEventTrigger()
trigger.timeBase = .none
trigger.mins = 0
trigger.event = nil
}
func JSON() throws -> Data? {
var json : [String: Any] = [:]
json["name"] = name
json["action"] = ["cmd" : action.cmd,
"deviceID" : action.deviceID ]
if isAppEvent() {
json["trigger"] = ["event": trigger.event]
}
else if isTimedEvent() {
json["trigger"] = ["mins": trigger.mins,
"timeBase": trigger.timeBase ]
}
let jsonData = try? JSONSerialization.data(withJSONObject: json)
return jsonData
}
func isValid() -> Bool {
return
self.eventType() != .unknown
&& deviceIDValue() != .invalid
&& cmdValue() != .invalid
}
func isTimedEvent() -> Bool {
return (self.trigger.timeBase != nil) && (self.trigger.mins != nil)
}
func isAppEvent() -> Bool {
return (self.trigger.event != nil)
}
enum eventType: Int {
case unknown = 0
case timed
case event
}
enum appEventTrigger: String, CaseIterable {
case invalid = ""
case startup = "startup"
case shutdown = "shutdown"
func description() -> String {
var str = "Invalid"
switch self {
case .startup: str = "Startup"
case .shutdown: str = "Shutdown"
default:
break
}
return str
}
}
enum timedEventTimeBase: Int,CaseIterable {
case invalid = 0
case midnight
case sunrise
case sunset
case civilSunrise
case civilSunset
func description() -> String {
var str = "Invalid"
switch self {
case .midnight: str = "Midnight"
case .sunrise: str = "SunRise"
case .sunset: str = "SunSet"
case .civilSunrise: str = "Civil SunRise"
case .civilSunset: str = "Civil SunSet"
default:
break
}
return str
}
func image() -> UIImage {
var image:UIImage? = nil
switch self {
case .midnight: image = UIImage(systemName: "clock")
case .sunrise: image = UIImage(systemName: "sunrise")
case .sunset: image = UIImage(systemName: "sunset")
case .civilSunrise: image = UIImage(systemName: "sunrise.fill")
case .civilSunset: image = UIImage(systemName: "sunset.fill")
default: image = UIImage(systemName: "questionmark")
}
return image ?? UIImage()
}
}
func eventType() -> eventType {
if(self.isTimedEvent()) {
return .timed
}
else if(self.isAppEvent()) {
return .event
}
return .unknown
}
enum actionCmd: String, CaseIterable {
case invalid = ""
case open = "open"
case close = "close"
case on = "on"
case off = "off"
func description() -> String {
var str = "Invalid"
switch self {
case .on: str = "On"
case .off: str = "Off"
case .open: str = "Open"
case .close: str = "Close"
default:
break
}
return str
}
}
func allCasesForDeviceID(devID :actionDeviceID) -> [actionCmd]{
var cmds : [actionCmd] = []
switch devID {
case .light,
.aux:
cmds = [.on, .off]
case .door:
cmds = [.open, .close]
default:break
}
return cmds
}
func normalizedEvent() -> RESTEvent {
var event = self
switch (event.deviceIDValue()) {
case .light,
.aux:
switch event.cmdValue() {
case .on, .off:
break // these are OK
case .close:
event.action.cmd = "off"
case .open:
event.action.cmd = "on"
default:
event.action.cmd = ""
}
case .door:
switch event.cmdValue() {
case .open, .close:
break // these are OK
case .on:
event.action.cmd = "open"
case .off:
event.action.cmd = "close"
default:
event.action.cmd = ""
}
default: break
}
return event
}
func cmdValue() -> actionCmd{
switch (action.cmd?.lowercased()){
case "open": return .open
case "close": return .close
case "on": return .on
case "off": return .off
default: return .invalid
}
}
func stringForActionCmd() -> String {
let cmd = self.cmdValue()
let str = cmd.description()
return str
}
enum actionDeviceID: String, CaseIterable {
case invalid = ""
case door = "door"
case light = "light"
case aux = "aux"
func description() -> String {
var str = "Invalid"
switch self {
case .door: str = "Coop Door"
case .light: str = "Coop Light"
case .aux: str = "Aux Relay"
default:
break
}
return str
}
}
func deviceIDValue() -> actionDeviceID{
switch (action.deviceID?.lowercased()){
case "door": return .door
case "light": return .light
case "aux": return .aux
default: return .invalid
}
}
func stringForActionDeviceID() -> String {
let cmd = self.deviceIDValue()
let str = cmd.description()
return str
}
func stringForTrigger() -> String {
var str = "Invalid"
switch self.eventType() {
case .timed:
if let timebase = self.trigger.timeBase,
let timedTrigger = timedEventTimeBase(rawValue: timebase) {
str = timedTrigger.description()
}
case .event:
if self.trigger.event == "startup" {
str = "Startup"
}
else if self.trigger.event == "shutdown" {
str = "Shutdown"
}
break
default:
break
}
return str
}
func imageForTrigger() -> UIImage {
var image = UIImage(systemName: "questionmark")
switch self.eventType() {
case .timed:
if let timebase = self.trigger.timeBase,
let timedTrigger = timedEventTimeBase(rawValue: timebase) {
image = timedTrigger.image()
}
case .event:
if self.trigger.event == "startup" {
image = UIImage(systemName: "power")
}
else if self.trigger.event == "shutdown" {
image = UIImage(systemName: "poweroff")
}
break
default:
break
}
return image ?? UIImage()
}
}
struct RESTEventTime: Decodable {
var eventID: String
var minsFromMidnight: Int
//var wrappedValue: (String, Int)
// func encode(to encoder: Encoder) throws {
// var unkeyedContainer = encoder.unkeyedContainer()
//
// }
init(from decoder: Decoder) throws {
eventID = ""
minsFromMidnight = 0
var container = try decoder.unkeyedContainer()
if (container.count == 2) {
eventID = try container.decodeIfPresent(String.self)!
minsFromMidnight = try container.decodeIfPresent(Int.self)!
}
}
}
struct RESTEventList: Decodable {
var eventIDs: Dictionary<String, RESTEvent>
var events_timed: [RESTEventTime]?
var future: [String]?
enum CodingKeys: String, CodingKey {
case eventIDs = "eventIDs"
case events_timed = "events.timed"
case future = "events.future"
}
// init(from decoder: Decoder) throws {
//
// let container = try decoder.container(keyedBy: CodingKeys.self)
// eventIDs = try container.decode([String: RESTEvent].self, forKey: CodingKeys.eventIDs)
// future = try? container.decode([String].self, forKey: CodingKeys.eventIDs)
//
// let arr = try container.decode(Array<Any>.self, forKey: CodingKeys.events_timed)
//
// events_timed = []
//// events_timed = try? container.decode([RESTEventTime].self, forKey: CodingKeys.events_timed)
//
// }
}
struct RESTDeviceDoor: Codable {
var door: DoorState.RawValue
enum CodingKeys: String, CodingKey {
case door = "door"
}
}
struct RESTDeviceLight: Codable {
var light: Bool
enum CodingKeys: String, CodingKey {
case light = "light"
}
}
struct RESTDeviceAux: Codable {
var aux: Bool
enum CodingKeys: String, CodingKey {
case aux = "aux"
}
}
enum BatteryStatus: UInt8 {
case normal = 0
case charging_from_in
case charging_from_5v
case not_present
case unknown
}
extension BatteryStatus: Codable {
enum Key: CodingKey {
case rawValue
}
enum CodingError: Error {
case unknownValue
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
let rawValue = try container.decode(Int.self, forKey: .rawValue)
switch rawValue {
case 0:
self = .normal
case 1:
self = .charging_from_in
case 2:
self = .charging_from_5v
case 3:
self = .not_present
default:
self = .unknown
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
switch self {
case .normal:
try container.encode(0, forKey: .rawValue)
case .charging_from_in:
try container.encode(1, forKey: .rawValue)
case .charging_from_5v:
try container.encode(2, forKey: .rawValue)
case .not_present:
try container.encode(3, forKey: .rawValue)
case .unknown:
break;
}
}
}
enum PowerInputStatus: UInt8 {
case not_present = 0
case weak
case bad
case present
case unknown
}
extension PowerInputStatus: Codable {
enum Key: CodingKey {
case rawValue
}
enum CodingError: Error {
case unknownValue
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
let rawValue = try container.decode(Int.self, forKey: .rawValue)