<commit_before>//
//  BLECManager.swift
//  Pods
//
//  Created by <NAME> on 7/5/16.
//
//

import Foundation
import CoreBluetooth


public enum BLECentralState {
    case initial
    case unknown
    case unsupported
    case unauthorized
    case poweredOff
    case poweredOn
    case resetting

    case searching
}


@objc open class BLECManager: NSObject {

    enum ManagerError: Error {
        case notConnected
    }

    fileprivate let _config: BLECConfig
    fileprivate var _manager: CBCentralManager!
    fileprivate var _devices = [BLECDevice]()

    open var state = BLECentralState.initial
    open weak var delegate: BLECDeviceDelegate?


    public init?(config: BLECConfig, queue: DispatchQueue?) {
        _config = config
        super.init()
        _manager = CBCentralManager(delegate: self, queue: queue)
    }
}


// MARK: - CBCentralManagerDelegate methods

extension BLECManager: CBCentralManagerDelegate {

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    DLog("centralManagerDidUpdateState")
        switch central.state {
        case .unsupported:
            state = .unsupported
        case .unauthorized:
            state = .unauthorized
        case .poweredOff:
            state = .poweredOff
        case .poweredOn:
            if !_search() { return }
        case .resetting:
            state = .resetting
            DLog("resetting called, pairing refused?")
        case .unknown:
            state = .unknown
        }
        DLog("Central manager state: \(state)")
        delegate?.centralDidUpdateState(self)
    }

    public func centralManager(_ central: CBCentralManager,
                               didDiscover peripheral: CBPeripheral,
                               advertisementData: [String : Any],
                               rssi RSSI: NSNumber) {
        DLog("didDiscoverPeripheral with advertisementData items: \(advertisementData.count)")
        #if DEBUG
            var i = 0
            for (key, value) in advertisementData {
                DLog("advertisementData \(i): \(key): \(value)")
                i += 1
            }
        #endif  // DEBUG

        let isConn = advertisementData[CBAdvertisementDataIsConnectable]
        if isConn == nil || (isConn! as AnyObject).boolValue == false {
            DLog("isConn: \(isConn), not try to connect.")
            return
        }

        //---- verify advertised services ----
        if let advertUUIDs = _config.advertServiceUUIDs {
            guard let services = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] else {
                DLog("no services advertised.")
                return
            }

            for uuid in advertUUIDs {
                guard let _ = services.index(of: uuid) else {
                    DLog("No advert service found: \(uuid)")
                    return
                }
            }
        }

        delegate?.central(self, didDiscoverPeripheral: peripheral, RSSI: RSSI.intValue)
        _connect(peripheral)
    }

    public func centralManager(_ central: CBCentralManager,
                               didConnect peripheral: CBPeripheral) {
        DLog("didConnectPeripheral, delegate: \(delegate)")
        delegate?.central(self, didConnectPeripheral:peripheral)

        //---- Get the services ----
        let uuids = _config.serviceUUIDs
        peripheral.discoverServices(uuids)
    }

    public func centralManager(_ central: CBCentralManager,
                               didDisconnectPeripheral peripheral: CBPeripheral,
                               error: Error?) {
        //---- set device's state ----
        guard let index = _findDeviceByPeripheral(peripheral) else {
            DLog("device not found for \(peripheral)")
            return
        }
        assert(_devices[index].UUID == peripheral.identifier, "should be equal.")

        _devices[index].characteristics.removeAll()
        DLog("didDisonnectPeripheral, delegate: \(delegate)")
        delegate?.central(self, didDisconnectDevice: _devices[index], error: error)

        _devices[index].peripheral = nil
        _devices[index].state = .None

        //---- workaround attempt for code 6, 10, ... errors ----
        if error != nil {
            _manager.stopScan()
            _search()
        }
    }

    public func centralManager(_ central: CBCentralManager,
                               didFailToConnect peripheral: CBPeripheral,<commit_msg>Fix compilation warning.<commit_after>//
//  BLECManager.swift
//  Pods
//
//  Created by <NAME> on 7/5/16.
//
//

import Foundation
import CoreBluetooth


public enum BLECentralState {
    case initial
    case unknown
    case unsupported
    case unauthorized
    case poweredOff
    case poweredOn
    case resetting

    case searching
}


@objc open class BLECManager: NSObject {

    enum ManagerError: Error {
        case notConnected
    }

    fileprivate let _config: BLECConfig
    fileprivate var _manager: CBCentralManager!
    fileprivate var _devices = [BLECDevice]()

    open var state = BLECentralState.initial
    open weak var delegate: BLECDeviceDelegate?


    public init?(config: BLECConfig, queue: DispatchQueue?) {
        _config = config
        super.init()
        _manager = CBCentralManager(delegate: self, queue: queue)
    }
}


// MARK: - CBCentralManagerDelegate methods

extension BLECManager: CBCentralManagerDelegate {

    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
    DLog("centralManagerDidUpdateState")
        switch central.state {
        case .unsupported:
            state = .unsupported
        case .unauthorized:
            state = .unauthorized
        case .poweredOff:
            state = .poweredOff
        case .poweredOn:
            if !_search() { return }
        case .resetting:
            state = .resetting
            DLog("resetting called, pairing refused?")
        case .unknown:
            state = .unknown
        }
        DLog("Central manager state: \(state)")
        delegate?.centralDidUpdateState(self)
    }

    public func centralManager(_ central: CBCentralManager,
                               didDiscover peripheral: CBPeripheral,
                               advertisementData: [String : Any],
                               rssi RSSI: NSNumber) {
        DLog("didDiscoverPeripheral with advertisementData items: \(advertisementData.count)")
        #if DEBUG
            var i = 0
            for (key, value) in advertisementData {
                DLog("advertisementData \(i): \(key): \(value)")
                i += 1
            }
        #endif  // DEBUG

        let isConn = advertisementData[CBAdvertisementDataIsConnectable]
        if isConn == nil || (isConn! as AnyObject).boolValue == false {
            DLog("isConn: \(isConn), not try to connect.")
            return
        }

        //---- verify advertised services ----
        if let advertUUIDs = _config.advertServiceUUIDs {
            guard let services = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] else {
                DLog("no services advertised.")
                return
            }

            for uuid in advertUUIDs {
                guard let _ = services.index(of: uuid) else {
                    DLog("No advert service found: \(uuid)")
                    return
                }
            }
        }

        delegate?.central(self, didDiscoverPeripheral: peripheral, RSSI: RSSI.intValue)
        _connect(peripheral)
    }

    public func centralManager(_ central: CBCentralManager,
                               didConnect peripheral: CBPeripheral) {
        DLog("didConnectPeripheral, delegate: \(delegate)")
        delegate?.central(self, didConnectPeripheral:peripheral)

        //---- Get the services ----
        let uuids = _config.serviceUUIDs
        peripheral.discoverServices(uuids)
    }

    public func centralManager(_ central: CBCentralManager,
                               didDisconnectPeripheral peripheral: CBPeripheral,
                               error: Error?) {
        //---- set device's state ----
        guard let index = _findDeviceByPeripheral(peripheral) else {
            DLog("device not found for \(peripheral)")
            return
        }
        assert(_devices[index].UUID == peripheral.identifier, "should be equal.")

        _devices[index].characteristics.removeAll()
        DLog("didDisonnectPeripheral, delegate: \(delegate)")
        delegate?.central(self, didDisconnectDevice: _devices[index], error: error)

        _devices[index].peripheral = nil
        _devices[index].state = .None

        //---- workaround attempt for code 6, 10, ... errors ----
        if error != nil {
            _manager.stopScan()
            _ = _search()
        }
    }

    public func centralManager(_ central: CBCentralManager,
                               didFailToConnect peripheral: CBPeripheral,
{'fraction_non_alphanumeric': 0.08942275608942275, 'fraction_numerical': 0.002002002002002002, 'mean_word_length': 1.880204996796925, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '903289', 'n_tokens_mistral': 2463, 'n_tokens_neox': 2266, 'n_words': 597}