【QT上位机/嵌入式项目】基于IMX6ull--Bluez蓝牙健康助手上位机

演示链接

【QT上位机/嵌入式项目】基于IMX6ull--Bluez蓝牙健康助手上位机

代码实现

代码非完整代码,有需要源码可私信我!

#include "bluetooth_page.h"
#include "remoteselector.h"
#include "chatserver.h"
#include "chatclient.h"
#include <qbluetoothuuid.h>
#include <qbluetoothserver.h>
#include <qbluetoothservicediscoveryagent.h>
#include <qbluetoothdeviceinfo.h>
#include <qbluetoothlocaldevice.h>
#include <QGuiApplication>
#include <QScreen>
#include <QRect>
#include <QTimer>
#include <QDebug>
#include <QTabBar>
#include <QHeaderView>
#include <QTableView>

ChatServer *server;

static const QLatin1String
serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");

Bluetooth_Page::Bluetooth_Page(QWidget *parent, Home_Page *homePageInstance, PageManage *pageManager)
    : QWidget(parent), pageManager(pageManager), homePage(homePageInstance)
{
    blue_page_Widget = new QWidget(this);
    blue_page_Widget->setGeometry(0, 0, 800, 480);
    blue_page_Widget->setFixedSize(800, 480);

    layoutInit();
    localAdapterInit();
}

Bluetooth_Page::~Bluetooth_Page()
{
    qDeleteAll(clients);
    delete server;
}

/* 初始化本地蓝牙,作为服务端 */
void Bluetooth_Page::localAdapterInit()
{
    /* 查找本地蓝牙的个数 */
    localAdapters = QBluetoothLocalDevice::allDevices();
    qDebug() << "localAdapter: " << localAdapters.count();

    QBluetoothLocalDevice localDevice;
    localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);

    QBluetoothAddress adapter = QBluetoothAddress();
    remoteSelector = new RemoteSelector(adapter, this);
    connect(remoteSelector,
            SIGNAL(newServiceFound(QListWidgetItem*)),
            this, SLOT(newServiceFound(QListWidgetItem*)));

    /* 初始化服务端 */
    server = new ChatServer(homePage, this);
    //server = new ChatServer(this);

    connect(server, SIGNAL(clientConnected(QString)),
            this, SLOT(connected(QString)));

    connect(server, SIGNAL(clientDisconnected(QString)),
            this, SLOT(disconnected(QString)));

    connect(server, SIGNAL(messageReceived(QString, QString)),
            this, SLOT(showMessage(QString, QString)));

    connect(this, SIGNAL(sendMessage(QString)),
            server, SLOT(sendMessage(QString)));

    connect(this, SIGNAL(disconnect()),
            server, SLOT(disconnect()));

    server->startServer();

    /* 获取本地蓝牙的名称 */
    localName = QBluetoothLocalDevice().name();
}

void Bluetooth_Page::layoutInit()
{
    top_frame = new QFrame(blue_page_Widget);
    top_frame->setGeometry(0, 0, 800, 50);
    top_frame->setFrameShape(QFrame::NoFrame); // QFrame::Box

    topLabel = new QLabel("蓝牙列表", top_frame);
    topLabel->setAlignment(Qt::AlignCenter);
    topFont = topLabel->font();
    topFont.setPointSize(24);
    topLabel->setFont(topFont);
    topLabel->setGeometry(0, -5, 800, 50);

    backPushButton = new QPushButton("返回", top_frame);
    backPushButton->setMinimumSize(120, 40);
    backPushButton->setGeometry(0, 0, 120, 40);
    connect(backPushButton, SIGNAL(clicked()),
            this, SLOT(backToHomePage()));

//    topHLayout->addSpacerItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));

//    topLabel = new QLabel("蓝牙列表", top_frame);
//    topLabel->setAlignment(Qt::AlignCenter);
//    topFont = topLabel->font();
//    topFont.setPointSize(24);
//    topLabel->setFont(topFont);
//    topLabel->setFixedSize(800, 50);
//    topHLayout->addWidget(topLabel);

//    topHLayout->addSpacerItem(new QSpacerItem(80, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));

    //top_frame->setLayout(topHLayout);

    list_frame = new QFrame(blue_page_Widget);
    list_frame->setGeometry(0, 60, 600, 400);
    list_frame->setFrameShape(QFrame::NoFrame); // QFrame::Box
    listWidget = new QListWidget(list_frame);
    listVLayout = new QVBoxLayout(list_frame);
    listVLayout->setContentsMargins(0, 0, 0, 0);
    listVLayout->addWidget(listWidget);
    list_frame->setLayout(listVLayout);

    bluetooth_btn_frame = new QFrame(blue_page_Widget);
    bluetooth_btn_frame->setGeometry(610, 60, 170, 400);
    bluetooth_btn_frame->setFrameShape(QFrame::NoFrame); // QFrame::Box

    bluetooth_btn_VLayout = new QVBoxLayout(bluetooth_btn_frame);
    bluetooth_btn_VLayout->setContentsMargins(0, 0, 0, 0);
    bluetooth_btn_frame->setLayout(bluetooth_btn_VLayout);

    /* 0为扫描按钮,1为连接按钮 */
    pushButton[0] = new QPushButton();
    pushButton[1] = new QPushButton();
    pushButton[2] = new QPushButton();
    pushButton[3] = new QPushButton();
    pushButton[4] = new QPushButton();

    /* 页面一 */
    bluetooth_btn_VLayout->addWidget(pushButton[0]);
    bluetooth_btn_VLayout->addWidget(pushButton[1]);
    bluetooth_btn_VLayout->addWidget(pushButton[2]);
    bluetooth_btn_VLayout->addWidget(pushButton[3]);
    pushButton[0]->setMinimumSize(120, 40);
    pushButton[1]->setMinimumSize(120, 40);
    pushButton[2]->setMinimumSize(120, 40);
    pushButton[3]->setMinimumSize(120, 40);
    pushButton[0]->setText("开始扫描");
    pushButton[1]->setText("停止扫描");
    pushButton[2]->setText("连接");
    pushButton[3]->setText("断开");

    /* 开始搜寻蓝牙 */
    connect(pushButton[0], SIGNAL(clicked()),
            this, SLOT(searchForDevices()));

    /* 停止搜寻蓝牙 */
    connect(pushButton[1], SIGNAL(clicked()),
            this, SLOT(stopSearch()));

    /* 点击连接按钮,本地蓝牙作为客户端去连接外界的服务端 */
    connect(pushButton[2], SIGNAL(clicked()),
            this, SLOT(connectToDevice()));

    /* 点击断开连接按钮,断开连接 */
    connect(pushButton[3], SIGNAL(clicked()),
            this, SLOT(toDisconnected()));

    /* 发送消息 */
    connect(pushButton[4], SIGNAL(clicked()),
            this, SLOT(sendMessage()));
}

/* 作为客户端去连接 */
void Bluetooth_Page::connectToDevice()
{
    if (listWidget->currentRow() == -1)
        return;

    QString name = listWidget->currentItem()->text();
    qDebug() << "Connecting to " << name;

    // Trying to get the service
    QBluetoothServiceInfo service;
    QMapIterator<QString,QBluetoothServiceInfo>
            i(remoteSelector->m_discoveredServices);
    bool found = false;
    while (i.hasNext()){
        i.next();

        QString key = i.key();

        /* 判断连接的蓝牙名称是否在发现的设备里 */
        if (key == name) {
            qDebug() << "The device is found";
            service = i.value();
            qDebug() << "value: " << i.value().device().address();
            found = true;
            break;
        }
    }

    /* 如果找到,则连接设备 */
    if (found) {
        qDebug() << "Going to create client";
        ChatClient *client = new ChatClient(this);
        qDebug() << "Connecting...";

        connect(client, SIGNAL(messageReceived(QString,QString)),
                this, SLOT(showMessage(QString,QString)));
        connect(client, SIGNAL(disconnected()),
                this, SLOT(clientDisconnected()));;
        connect(client, SIGNAL(connected(QString)),
                this, SLOT(connected(QString)));
        connect(this, SIGNAL(sendMessage(QString)),
                client, SLOT(sendMessage(QString)));
        connect(this, SIGNAL(disconnect()),
                client, SLOT(disconnect()));

        qDebug() << "Start client";
        client->startClient(service);

        clients.append(client);
    }
}

/* 本地蓝牙选择,默认使用第一个蓝牙 */
int Bluetooth_Page::adapterFromUserSelection() const
{
    int result = 0;
    QBluetoothAddress newAdapter = localAdapters.at(0).address();
    return result;
}

void Bluetooth_Page::backToHomePage()
{
    if (pageManager)
    {
        pageManager->showHomePage();  // 切换到蓝牙页面
    }
    else
    {
        qDebug() << "Error: pageManager is null!";
    }
}

/* 开始搜索 */
void Bluetooth_Page::searchForDevices()
{
    /* 先清空 */
    listWidget->clear();
    qDebug() << "search for devices!";
    if (remoteSelector) {
        delete remoteSelector;
        remoteSelector = NULL;
    }

    QBluetoothAddress adapter = QBluetoothAddress();
    remoteSelector = new RemoteSelector(adapter, this);

    connect(remoteSelector,
            SIGNAL(newServiceFound(QListWidgetItem*)),
            this, SLOT(newServiceFound(QListWidgetItem*)));

    remoteSelector->m_discoveredServices.clear();
    remoteSelector->startDiscovery(QBluetoothUuid(serviceUuid));
    connect(remoteSelector, SIGNAL(finished()),
            this, SIGNAL(discoveryFinished()));
}

/* 停止搜索 */
void Bluetooth_Page::stopSearch()
{
    qDebug() << "Going to stop discovery...";
    if (remoteSelector) {
        remoteSelector->stopDiscovery();
    }
}

/* 找到蓝牙服务 */
void Bluetooth_Page::newServiceFound(QListWidgetItem *item)
{
    /* 设置项的大小 */
    item->setSizeHint(QSize(listWidget->width(), 50));

    /* 添加项 */
    listWidget->addItem(item);

    /* 设置当前项 */
    listWidget->setCurrentRow(listWidget->count() - 1);

    qDebug() << "newServiceFound";

    // get all of the found devices
    QStringList list;

    QMapIterator<QString, QBluetoothServiceInfo>
            i(remoteSelector->m_discoveredServices);
    while (i.hasNext()){
        i.next();
        qDebug() << "key: " << i.key();
        qDebug() << "value: " << i.value().device().address();
        list << i.key();
    }

    qDebug() << "list count: "  << list.count();

    emit newServicesFound(list);
}

/* 已经连接 */
void Bluetooth_Page::connected(const QString &name)
{
    qDebug() << "已连接\n";
    if (pageManager)
    {
        pageManager->showHomePage();  // 切换到蓝牙页面
    }
    else
    {
        qDebug() << "Error: pageManager is null!";
    }
}

/* 接收消息 */
void Bluetooth_Page::showMessage(const QString &sender,
                             const QString &message)
{
    if (pageManager)
    {
        pageManager->showHomePage();  // 切换到蓝牙页面
    }
    else
    {
        qDebug() << "Error: pageManager is null!";
    }
}

/* 发送消息 */
void Bluetooth_Page::sendMessage()
{
    showMessage(localName, lineEdit->text());
    emit sendMessage(lineEdit->text());
}

/* 作为客户端断开连接 */
void Bluetooth_Page::clientDisconnected()
{
    ChatClient *client = qobject_cast<ChatClient *>(sender());
    if (client) {
        clients.removeOne(client);
        client->deleteLater();
    }
    if (pageManager)
    {
        pageManager->showHomePage();  // 切换到蓝牙页面
    }
    else
    {
        qDebug() << "Error: pageManager is null!";
    }
}

/* 主动断开连接 */
void Bluetooth_Page::toDisconnected()
{
    emit disconnect();
}

/* 作为服务端时,客户端断开连接 */
void Bluetooth_Page::disconnected(const QString &name)
{
    qDebug() << "已断开\n";
    if (pageManager)
    {
        pageManager->showHomePage();  // 切换到蓝牙页面
    }
    else
    {
        qDebug() << "Error: pageManager is null!";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值