-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRoot.swift
More file actions
574 lines (497 loc) · 16.7 KB
/
Root.swift
File metadata and controls
574 lines (497 loc) · 16.7 KB
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
//
// Copyright (c) 2023 PADL Software Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AsyncExtensions
@_spi(SwiftOCAPrivate)
import SwiftOCA
extension OcaController {
typealias ID = ObjectIdentifier
nonisolated var id: ID {
ObjectIdentifier(self)
}
}
@OcaDevice
open class OcaRoot: CustomStringConvertible, Codable, Sendable, _OcaObjectKeyPathRepresentable {
open nonisolated class var classID: OcaClassID { OcaClassID("1") }
open nonisolated class var classVersion: OcaClassVersionNumber { 2 }
public nonisolated let objectNumber: OcaONo
public nonisolated let lockable: OcaBoolean
public nonisolated let role: OcaString
public internal(set) weak var deviceDelegate: OcaDevice?
enum LockState: Equatable, Sendable, CustomStringConvertible {
/// Oca-1-2023 uses this confusing `NoReadWrite` and `NoWrite` nomenclature
case unlocked
case lockedNoWrite(OcaController.ID)
case lockedNoReadWrite(OcaController.ID)
var lockState: OcaLockState {
switch self {
case .unlocked:
.noLock
case .lockedNoWrite:
.lockNoWrite
case .lockedNoReadWrite:
.lockNoReadWrite
}
}
var description: String {
switch self {
case .unlocked:
"Unlocked"
case .lockedNoWrite:
"Read locked"
case .lockedNoReadWrite:
"Read/write locked"
}
}
}
var lockStateSubject = AsyncCurrentValueSubject<LockState>(.unlocked)
private func notifySubscribers(
lockState: LockState
) async throws {
let event = OcaEvent(emitterONo: objectNumber, eventID: OcaPropertyChangedEventID)
let parameters = OcaPropertyChangedEventData<OcaLockState>(
propertyID: OcaPropertyID("1.6"),
propertyValue: lockState.lockState,
changeType: .currentChanged
)
try await deviceDelegate?.notifySubscribers(
event,
parameters: parameters
)
}
var lockState: LockState {
get {
lockStateSubject.value
}
set {
lockStateSubject.value = newValue
Task {
try? await notifySubscribers(lockState: newValue)
}
}
}
public nonisolated class var classIdentification: OcaClassIdentification {
OcaClassIdentification(classID: classID, classVersion: classVersion)
}
public var objectIdentification: OcaObjectIdentification {
OcaObjectIdentification(oNo: objectNumber, classIdentification: Self.classIdentification)
}
public init(
objectNumber: OcaONo? = nil,
lockable: OcaBoolean = true,
role: OcaString? = nil,
deviceDelegate: OcaDevice? = nil,
addToRootBlock: Bool = true
) async throws {
if let objectNumber {
precondition(objectNumber != OcaInvalidONo)
self.objectNumber = objectNumber
} else {
self.objectNumber = await deviceDelegate?.allocateObjectNumber() ?? OcaInvalidONo
}
self.lockable = lockable
self.role = role ?? String(self.objectNumber)
self.deviceDelegate = deviceDelegate
if let deviceDelegate {
try await deviceDelegate.register(object: self, addToRootBlock: addToRootBlock)
}
}
deinit {
for (_, propertyKeyPath) in allDevicePropertyKeyPathsUncached {
let property = self[keyPath: propertyKeyPath] as! (any OcaDevicePropertyRepresentable)
property.finish()
}
}
enum CodingKeys: String, CodingKey {
case objectNumber = "oNo"
case classIdentification = "1.1"
case lockable = "1.2"
case role = "1.3"
}
public nonisolated func encode(to encoder: Encoder) throws {
// Always encode as just the object number. Deep serialization of object
// state is handled by OcaBlock.serialize() which calls serialize() on
// each action object directly, not through Codable.
var container = encoder.singleValueContainer()
try container.encode(objectNumber)
}
public required nonisolated init(from decoder: Decoder) throws {
throw Ocp1Error.notImplemented
}
public nonisolated var description: String {
let objectNumberString = "0x\(objectNumber.hexString(width: 8))"
return "\(type(of: self))(objectNumber: \(objectNumberString), role: \(role))"
}
private func handlePropertyAccessor(
_ command: Ocp1Command,
from controller: any OcaController
) async throws -> Ocp1Response {
guard let method = OcaDevicePropertyKeyPathCache.shared
.lookupMethod(command.methodID, for: self)
else {
await deviceDelegate?.logger.info("unknown property accessor method \(command)")
throw Ocp1Error.status(.notImplemented)
}
let property = self[keyPath: method.1] as! (any OcaDevicePropertyRepresentable)
switch method.0 {
case .getter:
try decodeNullCommand(command)
try await ensureReadable(by: controller, command: command)
return try await property.getOcp1Response()
case .setter:
try await ensureWritable(by: controller, command: command)
try await property.set(object: self, command: command)
return Ocp1Response()
}
}
open func handleCommand(
_ command: Ocp1Command,
from controller: any OcaController
) async throws -> Ocp1Response {
switch command.methodID {
case OcaMethodID("1.1"):
struct GetClassIdentificationParameters: Ocp1ParametersReflectable {
let classIdentification: OcaClassIdentification
}
let response =
GetClassIdentificationParameters(
classIdentification: objectIdentification
.classIdentification
)
return try encodeResponse(response)
case OcaMethodID("1.2"):
try decodeNullCommand(command)
return try encodeResponse(lockable)
case OcaMethodID("1.3"):
try decodeNullCommand(command)
try lockNoReadWrite(controller: controller)
case OcaMethodID("1.4"):
try decodeNullCommand(command)
try unlock(controller: controller)
case OcaMethodID("1.5"):
try decodeNullCommand(command)
return try encodeResponse(role)
case OcaMethodID("1.6"):
try decodeNullCommand(command)
try lockNoWrite(controller: controller)
case OcaMethodID("1.7"):
try decodeNullCommand(command)
return try encodeResponse(lockState.lockState)
default:
return try await handlePropertyAccessor(command, from: controller)
}
return Ocp1Response()
}
public var isContainer: Bool {
false
}
open func ensureReadable(
by controller: any OcaController,
command: Ocp1Command
) async throws {
if let deviceManager = await deviceDelegate?.deviceManager, deviceManager != self {
try await deviceManager.ensureReadable(by: controller, command: command)
}
switch lockState {
case .unlocked:
break
case .lockedNoWrite:
break
case let .lockedNoReadWrite(lockholder):
guard controller.id == lockholder else {
throw Ocp1Error.status(.locked)
}
}
}
/// Important note: when subclassing you will typically want to override ensureWritable() to
/// implement your own form of access control.
open func ensureWritable(
by controller: any OcaController,
command: Ocp1Command
) async throws {
if let deviceManager = await deviceDelegate?.deviceManager, deviceManager != self {
try await deviceManager.ensureWritable(by: controller, command: command)
}
switch lockState {
case .unlocked:
break
case let .lockedNoWrite(lockholder):
fallthrough
case let .lockedNoReadWrite(lockholder):
guard controller.id == lockholder else {
throw Ocp1Error.status(.locked)
}
}
}
func lockNoWrite(controller: any OcaController) throws {
guard controller.flags.contains(.supportsLocking) else {
throw Ocp1Error.status(.permissionDenied)
}
if !lockable {
throw Ocp1Error.status(.notImplemented)
}
switch lockState {
case .unlocked:
lockState = .lockedNoWrite(controller.id)
case .lockedNoWrite:
throw Ocp1Error.status(.locked)
case let .lockedNoReadWrite(lockholder):
guard controller.id == lockholder else {
throw Ocp1Error.status(.locked)
}
// downgrade lock
lockState = .lockedNoWrite(controller.id)
}
}
func lockNoReadWrite(controller: any OcaController) throws {
guard controller.flags.contains(.supportsLocking) else {
throw Ocp1Error.status(.permissionDenied)
}
if !lockable {
throw Ocp1Error.status(.notImplemented)
}
switch lockState {
case .unlocked:
lockState = .lockedNoReadWrite(controller.id)
case let .lockedNoWrite(lockholder):
guard controller.id == lockholder else {
throw Ocp1Error.status(.locked)
}
lockState = .lockedNoReadWrite(controller.id)
case .lockedNoReadWrite:
throw Ocp1Error.status(.locked)
}
}
func unlock(controller: any OcaController) throws {
guard controller.flags.contains(.supportsLocking) else {
throw Ocp1Error.status(.permissionDenied)
}
if !lockable {
throw Ocp1Error.status(.notImplemented)
}
switch lockState {
case .unlocked:
throw Ocp1Error.status(.invalidRequest)
case let .lockedNoWrite(lockholder):
fallthrough
case let .lockedNoReadWrite(lockholder):
guard controller.id == lockholder else {
throw Ocp1Error.status(.locked)
}
lockState = .unlocked
}
}
func setLockState(to lockState: OcaLockState, controller: any OcaController) -> Bool {
do {
switch lockState {
case .noLock:
try unlock(controller: controller)
case .lockNoWrite:
try lockNoWrite(controller: controller)
case .lockNoReadWrite:
try lockNoReadWrite(controller: controller)
}
return true
} catch {
return false
}
}
open func serialize(
flags: SerializationFlags = [],
isIncluded: SerializationFilterFunction? = nil
) throws -> [String: any Sendable] {
var dict = [String: any Sendable]()
precondition(objectNumber != OcaInvalidONo)
guard self is OcaWorker || self is OcaManager || self is OcaAgent else {
return [:]
}
dict[objectNumberJSONKey] = objectNumber
dict[classIDJSONKey] = Self.classID.description
for (_, propertyKeyPath) in allDevicePropertyKeyPaths {
let property = self[keyPath: propertyKeyPath] as! (any OcaDevicePropertyRepresentable)
if let isIncluded, !isIncluded(self, property.propertyID, property.wrappedValue) {
continue
}
do {
dict[property.propertyID.description] = try property.getJsonValue()
} catch {
guard flags.contains(.ignoreEncodingErrors) else {
throw error
}
}
}
return dict
}
private static let _globalTypePropertyID = OcaPropertyID("3.5")
open func deserialize(
jsonObject: [String: Sendable],
flags: DeserializationFlags = []
) async throws {
guard let deviceDelegate else { throw Ocp1Error.notConnected }
let logger = await deviceDelegate.logger
guard let classIDString = jsonObject[classIDJSONKey] as? String else {
logger.warning("bad or missing object class when deserializing")
throw Ocp1Error.objectClassMismatch
}
let classID = try OcaClassID(unsafeString: classIDString)
guard objectIdentification.classIdentification.classID.isSubclass(of: classID) else {
logger.warning("object class mismatch between \(self) and \(classID)")
throw Ocp1Error.objectClassMismatch
}
if let blockGlobalType = (self as? any OcaBlockContainer)?.globalType,
let jsonGlobalType = jsonObject[Self._globalTypePropertyID.description] as? [String: Any]
{
guard let jsonGlobalType = OcaGlobalTypeIdentifier(jsonObject: jsonGlobalType) else {
logger.warning("bad or missing global type ID when deserializing")
throw Ocp1Error.status(.badFormat)
}
guard jsonGlobalType == blockGlobalType else {
logger
.warning(
"global type ID mismatch between: decoded \(jsonGlobalType), but expected \(blockGlobalType)"
)
throw Ocp1Error.globalTypeMismatch
}
} else {
guard let oNo = jsonObject[objectNumberJSONKey] as? OcaONo else {
logger.warning("bad or missing object number when deserializing")
throw Ocp1Error.status(.badFormat)
}
guard objectNumber == oNo else {
logger.warning("object number mismatch between \(self) and \(oNo)")
throw Ocp1Error.status(.badONo)
}
}
for (_, propertyKeyPath) in allDevicePropertyKeyPaths {
let property = self[keyPath: propertyKeyPath] as! (any OcaDevicePropertyRepresentable)
let propertyName = property.propertyID.description
guard let value = jsonObject[propertyName] else {
if flags.contains(.ignoreMissingProperties) {
continue
} else {
logger.warning("JSON object \(jsonObject) is missing \(propertyName)")
throw Ocp1Error.status(.parameterOutOfRange)
}
}
do {
try await property.set(object: self, jsonValue: value, device: deviceDelegate)
} catch {
logger
.warning(
"failed to set value \(value) on property \(propertyName) of \(self): \(error)"
)
if !flags.contains(.ignoreDecodingErrors) { throw error }
}
}
}
public var jsonObject: [String: any Sendable] {
try! serialize(flags: .ignoreEncodingErrors)
}
}
extension OcaRoot: Equatable {
public nonisolated static func == (lhs: OcaRoot, rhs: OcaRoot) -> Bool {
lhs.objectNumber == rhs.objectNumber
}
}
extension OcaRoot: Hashable {
public nonisolated func hash(into hasher: inout Hasher) {
hasher.combine(objectNumber)
}
}
protocol _OcaObjectKeyPathRepresentable: OcaRoot {}
extension OcaRoot {
fileprivate var _metaTypeObjectIdentifier: ObjectIdentifier {
ObjectIdentifier(type(of: self))
}
var allDevicePropertyKeyPaths: [String: AnyKeyPath] {
OcaDevicePropertyKeyPathCache.shared.keyPaths(for: self)
}
nonisolated(unsafe) var allDevicePropertyKeyPathsUncached: [String: AnyKeyPath] {
_allKeyPaths(value: self).reduce(into: [:]) {
if $1.key.hasPrefix("_") {
$0[String($1.key.dropFirst())] = $1.value
}
}.filter {
self[keyPath: $0.value] is any OcaDevicePropertyRepresentable
}
}
}
@OcaDevice
private final class OcaDevicePropertyKeyPathCache {
fileprivate static let shared = OcaDevicePropertyKeyPathCache()
enum AccessorType {
case getter
case setter
}
private struct CacheEntry {
let keyPaths: [String: AnyKeyPath]
let methods: [OcaMethodID: (AccessorType, AnyKeyPath)]
private init(keyPaths: [String: AnyKeyPath], object: some OcaRoot) {
self.keyPaths = keyPaths
methods = keyPaths.reduce(into: [:]) {
guard let value = object[keyPath: $1.value] as? any OcaDevicePropertyRepresentable else {
return
}
if let getMethodID = value.getMethodID {
$0[getMethodID] = (.getter, $1.value)
}
if let setMethodID = value.setMethodID {
$0[setMethodID] = (.setter, $1.value)
}
}
}
@OcaDevice
fileprivate init(object: some OcaRoot) {
let keyPaths = object.allDevicePropertyKeyPathsUncached
self.init(keyPaths: keyPaths, object: object)
}
}
private var _cache = [ObjectIdentifier: CacheEntry]()
private func addCacheEntry(for object: some OcaRoot) -> CacheEntry {
let cacheEntry = CacheEntry(object: object)
_cache[object._metaTypeObjectIdentifier] = cacheEntry
return cacheEntry
}
@OcaDevice
fileprivate func keyPaths(for object: some OcaRoot) -> [String: AnyKeyPath] {
if let cacheEntry = _cache[object._metaTypeObjectIdentifier] {
return cacheEntry.keyPaths
}
return addCacheEntry(for: object).keyPaths
}
@OcaDevice
fileprivate func lookupMethod(
_ methodID: OcaMethodID,
for object: some OcaRoot
) -> (AccessorType, AnyKeyPath)? {
if let cacheEntry = _cache[object._metaTypeObjectIdentifier] {
return cacheEntry.methods[methodID]
}
return addCacheEntry(for: object).methods[methodID]
}
}
@OcaDevice
public protocol OcaOwnable: OcaRoot {
var owner: OcaONo { get set }
}
public extension OcaOwnable {
func getOwnerObject<T>() async -> OcaBlock<T>? {
await deviceDelegate?.objects[owner] as? OcaBlock<T>
}
}
@OcaDevice
protocol OcaLabelRepresentable: OcaRoot {
var label: OcaString { get set }
}