private void _InitFlicClient() { if (_flicClient == null) { DebugEx.TraceLog("FlicClient is null, Find it!!!!"); while (true) { try { _flicClient = FlicClient.Create(ActiveCfg.FlicDaemonHostname, ActiveCfg.FlicDaemonPort); DebugEx.TraceLog("Connection to FlicClient successful"); if (_flicClient != null) { _flicClient.GetInfo( (bluetoothControllerState, myBdAddr, myBdAddrType, maxPendingConnections, maxConcurrentlyConnectedButtons, currentPendingConnections, currentlyNoSpaceForNewConnection, verifiedButtons) => { DebugEx.TraceLog("Bluetooth controller status: " + bluetoothControllerState.ToString()); foreach (var bdAddr in verifiedButtons) { GotButton(bdAddr); } }); } } catch (Exception ex) { DebugEx.TraceErrorException(ex); Thread.Sleep(500); continue; } break; } _flicClient.BluetoothControllerStateChange += (o, args) => { DebugEx.TraceLog("Bluetooth controller status: " + args.State.ToString()); }; _flicClient.NewVerifiedButton += (o, args) => { DebugEx.TraceLog("new NewVerifiedButtonEvent"); GotButton(args.BdAddr); }; TaskEx.RunSafe(() => { _flicClient.HandleEvents(); // HandleEvents returns when the socket has disconnected for any reason DebugEx.TraceError("BLE connection lost"); OnBLEDisconnected(); }); } }
private async void btnConnectDisconnect_Click(object sender, EventArgs e) { if (_flicClient == null) { btnConnectDisconnect.Enabled = false; try { _flicClient = await FlicClient.CreateAsync(txtServer.Text); } catch (Exception ex) { MessageBox.Show("Connect failed: " + ex.Message); btnConnectDisconnect.Enabled = true; return; } btnConnectDisconnect.Text = "Disconnect"; btnConnectDisconnect.Enabled = true; btnAddNewFlic.Text = "Add new Flic"; btnAddNewFlic.Enabled = true; _flicClient.BluetoothControllerStateChange += (o, args) => Invoke((MethodInvoker) delegate { lblBluetoothStatus.Text = "Bluetooth controller status: " + args.State.ToString(); }); _flicClient.NewVerifiedButton += (o, args) => Invoke((MethodInvoker) delegate { GotButton(args.BdAddr); }); _flicClient.GetInfo((bluetoothControllerState, myBdAddr, myBdAddrType, maxPendingConnections, maxConcurrentlyConnectedButtons, currentPendingConnections, currentlyNoSpaceForNewConnection, verifiedButtons) => Invoke((MethodInvoker) delegate { lblBluetoothStatus.Text = "Bluetooth controller status: " + bluetoothControllerState.ToString(); foreach (var bdAddr in verifiedButtons) { GotButton(bdAddr); } })); await Task.Run(() => _flicClient.HandleEvents()); // HandleEvents returns when the socket has disconnected for any reason buttonsList.Controls.Clear(); btnAddNewFlic.Enabled = false; _flicClient = null; lblConnectionStatus.Text = "Connection status: Disconnected"; lblBluetoothStatus.Text = "Bluetooth controller status:"; btnConnectDisconnect.Text = "Connect"; btnConnectDisconnect.Enabled = true; _currentScanWizard = null; lblScanWizardStatus.Text = ""; } else { _flicClient.Disconnect(); btnConnectDisconnect.Enabled = false; } }