                                  didDiscover peripheral: CBPeripheral,
                                  advertisementData: [String : Any], rssi RSSI: NSNumber) {
         // Is this a device we are looking for?
-        if peripheralSelector.select(peripheral, advertisementData: advertisementData as [String : AnyObject], RSSI: RSSI, hint: bootloaderName) {
+        if peripheralSelector.select(peripheral, advertisementData: advertisementData as [String : AnyObject],
+                                     RSSI: RSSI, hint: bootloaderName) {
             // Hurray!
+            connectionTimer?.cancel()
+            connectionTimer = nil
             central.stopScan()
             
             if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {

     Connects to the peripheral and performs service discovery.
     */
    fileprivate func connect() {
        let name = peripheral!.name ?? "Unknown device"
        logger.v("Connecting to \(name)...")
        // Set a connection timer.
        connectionTimer = DispatchSource.makeTimerSource()
        connectionTimer?.setEventHandler {
            if let peripheral = self.peripheral {
                self.connectionTimer?.cancel()
                self.logger.w("Connection timeout!")
                self.logger.d("centralManager.cancelPeripheralConnection(peripheral)")
                self.centralManager.cancelPeripheralConnection(peripheral)
            }
        }
        connectionTimer?.schedule(deadline: .now() + connectionTimeout)
        connectionTimer?.resume()
        logger.d("centralManager.connect(peripheral, options: nil)")
        centralManager.connect(peripheral!, options: nil)
    }
    
    fileprivate func cleanUp() {

            
            // Check if there is another part to be sent.
            if (delegate?.peripheralDidDisconnectAfterFirmwarePartSent() ?? false) {
                // As we are already in bootloader mode, the peripheral set
                // may be reused for sending a second part.
                connectOrSwitchToNewPeripheral(after: 3.0)
            } else {
                // Upload is completed.
                // Peripheral has been destroyed and state is now .completed.
