Qt World Summit: Submit your Presentation

BluetoothLowEnergy: Application for connecting to 2 devices with as little duplicate code as possible

  • Hi,
    I am relatively new to C ++ and Qt, but so far I have been able to create my own application (with QT Widgets GUI), with which I can connect to a Bluetooth Low Energy device and transfer data. I would now like to make it possible to do the whole thing for 2 devices at the same time. I simply copied all the code and added "_secondDevice" to the end of the variables and function names, for example, just to see if it worked and it does. Now I want to keep my code clear and avoid duplicate code.

    I have all the functionality for connecting in a class called "Connector". This class includes DeviceDsicovery, ServicesDiscovery, CharacteristicsDsicovery. To make the whole thing independent of the Ui I call all these functions from my MainWindow class. This means that when a user clicks on the "Scan" button, the "startDiscovery" function is called up in this slot in MainWindow.

    I thought that e.g. instead of two separate functions "startDiscovery" for both devices have a single generic function. But this function have i.e. three SLOTS which also have to be generic - so the only idea I have is to give the scanDevce function a parameter "device (first or second) and in the function I evaluate if(firstDevcie) then call Slot1,2,3 else call Sot 4,5,6 but this is I think the same bad coding as having 2 separate functions for both. (The following is from this example)

    void Connector::startDeviceDiscovery()
    m_deviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
    connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &DeviceFinder::addDevice);
    connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &DeviceFinder::scanFinished);
    connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::canceled, this, &DeviceFinder::scanFinished);

    Or for example this function:

    void Connector::connect()
    m_control = QLowEnergyController::createCentral(m_currentDevice->getDevice(), this);
    connect(m_control, &QLowEnergyController::serviceDiscovered,
            this, &DeviceHandler::serviceDiscovered);
    connect(m_control, &QLowEnergyController::discoveryFinished,
            this, &DeviceHandler::serviceScanDone);
    connect(m_control, &QLowEnergyController::connected, this, [this]() {
        setInfo("Controller connected. Search services...");
    connect(m_control, &QLowEnergyController::disconnected, this, [this]() {
        setError("LowEnergy controller disconnected");
    // Connect

    So does anyone have tips on how I can best design the whole thing without copying everything?

    Thank you very much!