QT 简单连接WIFI模块

2024-01-10 07:27:12

目录

1 部分代码

2 代码解析


?

1 部分代码
bool WIFIRecvThread::linkAP()
{
    //QTcpSocket *tcpSocket;tcpSocket应在头文件中全局变量
    QString ssid = "ssid";
    QString password = "Password";

    QProcess process;

    QString cmd_password = QString("netsh wlan set profileparameter name=%1 keyMaterial=%2").arg(ssid).arg(password);
    QString cmd_connect = QString("netsh wlan connect name=%1 ssid=%2").arg(ssid).arg(ssid);
    QString cmd = "netsh wlan connect ssid=\"" + ssid + "\" name=\"" + ssid + "\" keyMaterial=\"" + password + "\"";
    bool blink = false;
    process.start(cmd_password);
    blink = process.waitForFinished();

    qDebug() << "\blink0:"<<blink;
    process.start(cmd_connect);
    blink = process.waitForFinished();
    qDebug() << "\blink1:"<<blink;
    QThread::msleep(1000);//
    tcpSocket->connectToHost("192.168.1.1", 80);

    if (tcpSocket->waitForConnected(2000)) {
        connect(tcpSocket, &QTcpSocket::readyRead, this,&WIFIRecvThread::run);
        qDebug() << "Connected!";
        bLink = true;
    } else {
        bLink = false;
        QMessageBox::warning(0,"warning","Socket operation timed out!");
        return false;
    }
    return true;
}
void WIFIRecvThread::run()
{
    QByteArray data = tcpSocket->readLine();
    RevDataALL.append(data);
    Calculating(data);

}
2 代码解析

(1)

    QString ssid = "ssid";
    QString password = "Password";

    QProcess process;

    QString cmd_password = QString("netsh wlan set profileparameter name=%1 keyMaterial=%2").arg(ssid).arg(password);
    QString cmd_connect = QString("netsh wlan connect name=%1 ssid=%2").arg(ssid).arg(ssid);
    QString cmd = "netsh wlan connect ssid=\"" + ssid + "\" name=\"" + ssid + "\" keyMaterial=\"" + password + "\"";
    bool blink = false;
    process.start(cmd_password);
    blink = process.waitForFinished();

    qDebug() << "\blink0:"<<blink;
    process.start(cmd_connect);
    blink = process.waitForFinished();
    qDebug() << "\blink1:"<<blink;

这一部分是使用命令连接对应的WIFI ,cmd_password 是设置的密码,cmd_connect应是连接相应的WIFI,此处是使用代码连接WIFI 若手动连接 可以将这部分注释掉

(2)

QThread::msleep(1000);

经过调试发现 若为代码连接WIFI 此处需要加上1秒的延时 若为手动连接WIFI 可注释掉

(3)

    tcpSocket->connectToHost(ip, port);

    if (tcpSocket->waitForConnected(2000)) {
        connect(tcpSocket, &QTcpSocket::readyRead, this,&WIFIRecvThread::run);
        qDebug() << "Connected!";
        bLink = true;
    } else {
        bLink = false;
        QMessageBox::warning(0,"warning","Socket operation timed out!");
        return false;
    }
    return true;

此处进行连接 等待超时时间2秒

文章来源:https://blog.csdn.net/weixin_44270564/article/details/135407130
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。