Saving and restoring lights (HMCharacteristics)
I am using HomeKit related lights for notifications. I would like to take the current state (color, brightness, on / off) of each light in use and restore the light to that state after the notification is complete. However, it doesn't work.
This is how I try to do it:
I have a dictionary that displays a dictionary of characteristics and their values for each light (HMService).
I am running the following code to process and save the current state of the lights:
for service in services {
for characteristic in service.characteristics {
if characteristic.characteristicType == HMCharacteristicTypeHue ||
characteristic.characteristicType == HMCharacteristicTypeSaturation ||
characteristic.characteristicType == HMCharacteristicTypeBrightness {
characteristic.readValue(completionHandler: { (error) in
if error != nil {
print(error!.localizedDescription)
} else {
var characteristicsStore: [String : Any?] = [:]
if let existingCharacteristics = self.services[service] {
characteristicsStore = existingCharacteristics
}
characteristicsStore.updateValue(characteristic.value, forKey: characteristic.characteristicType)
self.services.updateValue(characteristicsStore, forKey: service)
}
})
}
}
}
Then, after the notification is complete, I run this code, which should set the characteristics of the lights back to the values I saved, but doesn't work:
for (service, characteristics) in services {
for (characteristicType, characteristicValue) in characteristics {
if let characteristic = service.characteristics.first(where: { (aCharacteristic) -> Bool in
aCharacteristic.characteristicType == characteristicType
}) {
characteristic.writeValue(characteristicValue, completionHandler: { (error) in
if error != nil {
print(error!.localizedDescription)
didSucceed = false
numberOfErrors += 1
} else {
print("Updated \(characteristic.characteristicTypeToString()) to \(characteristicValue as! Float)")
}
})
} else {
print("Did not find the characteristic")
}
}
}
I am getting the error: Unconfigured Parameter when I try to read or write values.
UPDATE:
I did make progress and then update on my Hue models. Now I am worse than before. I cannot access any of the accessory properties of the HMService objects, making it impossible to check if an accessory is available without a ton of rewriting.
If anyone can help me figure out what I am doing wrong, or if I am completely missing something, we would be very grateful.
source to share
No one has answered this question yet
Check out similar questions: