|
| 1 | +// |
| 2 | +// HMAcessoryBrowser+Promise.swift |
| 3 | +// Onboarding |
| 4 | +// |
| 5 | +// Created by Chris Chares on 6/29/18. |
| 6 | +// Copyright © 2018 Hunter Douglas. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | +import HomeKit |
| 11 | +import PromiseKit |
| 12 | + |
| 13 | +public enum HMPromiseAccessoryBrowserError: Error { |
| 14 | + case noAccessoryFound |
| 15 | +} |
| 16 | + |
| 17 | +public class HMPromiseAccessoryBrowser { |
| 18 | + private var proxy: BrowserProxy? |
| 19 | + |
| 20 | + public func start(scanInterval: ScanInterval) -> Promise<[HMAccessory]> { |
| 21 | + return BrowserProxy(scanInterval: scanInterval).promise |
| 22 | + } |
| 23 | + |
| 24 | + public func stop() { |
| 25 | + proxy?.cancel() |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +private class BrowserProxy: PromiseProxy<[HMAccessory]>, HMAccessoryBrowserDelegate { |
| 30 | + let browser = HMAccessoryBrowser() |
| 31 | + let scanInterval: ScanInterval |
| 32 | + |
| 33 | + init(scanInterval: ScanInterval) { |
| 34 | + self.scanInterval = scanInterval |
| 35 | + super.init() |
| 36 | + |
| 37 | + browser.delegate = self; |
| 38 | + browser.startSearchingForNewAccessories() |
| 39 | + |
| 40 | + //if we have a timeout, set it up |
| 41 | + var timeout: TimeInterval? = nil |
| 42 | + switch scanInterval { |
| 43 | + case .returnAll(let interval): timeout = interval |
| 44 | + case .returnFirst(let interval): timeout = interval |
| 45 | + } |
| 46 | + |
| 47 | + if let timeout = timeout { |
| 48 | + after(seconds: timeout) |
| 49 | + .done { [weak self] () -> Void in |
| 50 | + guard let _self = self else { return } |
| 51 | + _self.reject(HMPromiseAccessoryBrowserError.noAccessoryFound) |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + override func fulfill(_ value: [HMAccessory]) { |
| 57 | + browser.stopSearchingForNewAccessories() |
| 58 | + super.fulfill(value) |
| 59 | + } |
| 60 | + |
| 61 | + override func reject(_ error: Error ) { |
| 62 | + browser.stopSearchingForNewAccessories() |
| 63 | + super.reject(error) |
| 64 | + } |
| 65 | + |
| 66 | + override func cancel() { |
| 67 | + browser.stopSearchingForNewAccessories() |
| 68 | + super.cancel() |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + HMAccessoryBrowser delegate |
| 73 | + */ |
| 74 | + func accessoryBrowser(_ browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory) { |
| 75 | + if case .returnFirst = scanInterval { |
| 76 | + fulfill(browser.discoveredAccessories) |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments