其实wpa_supplicant工具不太好用,按顺序执行
1、wpa_supplicant -B -i wlan0 -c /data/cfg/wpa_supplicant.conf
2、wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan
3、wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan_results (搜索WiFi列表)
4、vi /data/cfg/wpa_supplicant.conf
输入:a
输入:WiFi名称、密码
退出保存:Esc —— Shift:—— wq —— 回车
配置文件最好是下面的格式否则可能不生效,如果你还有还有其他的配置项根据自己的wifi来配置
ctrl_interface=/var/run/wpa_supplicant
ap_scan=1
update_config=1
network={
ssid="WiFi名称"
psk="WiFi密码"
key_mgmt=WPA-PSK
}
5、reboot
6、wpa_supplicant -B -i wlan0 -c /data/cfg/wpa_supplicant.conf (连接)
7、ifconfig (查看wlan0网卡信息IP)
killall wpa_supplicant(结束程序)
头文件wifimanage.h
#ifndef FORMWIFIMANAGE_H
#define FORMWIFIMANAGE_H
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QTableWidgetItem>
class CDialogBox;
namespace Ui {
class FormWifiManage;
}
//bssid / frequency / signal level / flags / ssid
//94:d9:b3:a8:4d:c0 2412 -39 [WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][ESS] clefine
typedef struct wifi_info_s{
QString bssid;
int frequency;
int signal_level;
QString flags;
QString ssid;
}wifi_info_t;
class FormWifiManage : public QWidget
{
Q_OBJECT
public:
explicit FormWifiManage(QWidget *parent = nullptr);
~FormWifiManage();
private:
void setLabelText(const QString &);
QString getPassword() const;
void initTabWidget();
void showWifiInfo();
private slots:
void slotScanWifi();
void slotConnectWifi(QTableWidgetItem*);
void slotConnectToWifi();
void wifiPassword(const QString&);
void reconnectWifi();
void slotTimeout();
void disconnectWifi();
private:
Ui::FormWifiManage *ui;
QString m_name;
QString m_password;
CDialogBox *dialog;
QTimer *timer;
bool isscaning;
bool selectIndex;
QModelIndex curindex;
QLabel *label;
QString wpa_state;
QString ssid;
QLineEdit *password;
QList<wifi_info_t> wifi_list;
QTableWidgetItem* m_current_item;
};
#endif // FORMWIFIMANAGE_H
头文件wifimanage.cpp
#include "formwifimanage.h"
#include "ui_formwifimanage.h"
#include <QDebug>
#include <QDialog>
#include <QLineEdit>
#include "CDialogBox.h"
#include "Logger.h"
#include <QFile>
#include <unistd.h>
#include <QTimer>
#include "CMessageBox.h"
#include <QStandardItem>
#define CMD_RESULT_BUF_SIZE 10240
QString characterConversion(const QString& ss)
{
QString string1;
QString string2;
QString string3;
bool ok;
char ch[512] = { 0 };
QString result = "";
int icount = 0;
for (int i = 0; i < ss.length(); )
{
if ((i + 4) <= ss.length()) {
if (ss.at(i) == '\\' && ss.at(i + 1) == 'x') {
QString tmpstring = QString(ss.at(i + 2)) + ss.at(i + 3);
tmpstring = "0x" + tmpstring;
ch[icount] = static_cast<char>(tmpstring.toInt(&ok, 16));
icount++;
i += 4;
if (string2.size() > 0) {
result += string2;
string2.clear();
}
if (string3.size() > 0) {
result += string3;
string3.clear();
}
} else {
string1 = ch;
if (string1.size() > 0) {
result += string1;
icount = 0;
string1.clear();
memset(ch, 0, sizeof(ch));
}
if (string3.size() > 0) {
result += string3;
string3.clear();
}
string2 = string2 + ss.at(i);
i++;
}
} else {
string1 = ch;
if (string1.size() > 0) {
result += string1;
icount = 0;
string1.clear();
memset(ch, 0, sizeof(ch));
}
if (string2.size() > 0) {
result += string2;
string2.clear();
}
string3 = string3 + ss.at(i);
i++;
}
}
string1 = ch;
if (string1.size() > 0) {
result += string1;
}
if (string2.size() > 0) {
result += string2;
}
if (string3.size() > 0) {
result += string3;
}
return result;
}
extern "C" QStringList exec_cmd(const char *_cmd)
{
QStringList list;
FILE *file;
char line[CMD_RESULT_BUF_SIZE];
file = popen(_cmd, "r");
if (NULL != file)
{
while (fgets(line, CMD_RESULT_BUF_SIZE, file) != NULL)
{
printf("line: %s\n", line);
}
}else {
printf("popen %s error\n", _cmd);
}
pclose(file);
return list;
}
extern "C" void scanwifi(QList<wifi_info_t> &list)
{
usleep(200000);
system("wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan");
FILE *file;
char line[CMD_RESULT_BUF_SIZE];
char tmp[4][500];
file = popen("wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan_results", "r");
if (NULL != file)
{
while (fgets(line, CMD_RESULT_BUF_SIZE, file) != NULL)
{
int frequency=0,signal_level=0;
sscanf(line, "%s %d %d %s %[^\x01\n]", tmp[0], &frequency, &signal_level, tmp[1], tmp[2]);
if (strcmp("bssid", tmp[0])==0){
continue;
}
wifi_info_t wifi;
wifi.bssid=tmp[0];
wifi.frequency=frequency;
wifi.signal_level=signal_level;
wifi.flags=tmp[1];
wifi.ssid=characterConversion(tmp[2]);
list << wifi;
}
}else {
printf("popen %s error\n", "wpa_cli -i wlan0 -p /var/run/wpa_supplicant scan_results");
}
pclose(file);
}
FormWifiManage::FormWifiManage(QWidget *parent) :
QWidget(parent),
ui(new Ui::FormWifiManage)
{
ui->setupUi(this);
isscaning=false;
label=nullptr;
password=nullptr;
m_current_item=nullptr;
selectIndex=false;
wpa_state = "";
ssid= "";
connect(ui->toolButton_Scan, SIGNAL(clicked()), this, SLOT(slotScanWifi()));
connect(ui->toolButton_Connect, SIGNAL(clicked()), this, SLOT(reconnectWifi()));
connect(ui->toolButton_Disconnect, SIGNAL(clicked()), this, SLOT(disconnectWifi()));
connect(ui->tableWidget, SIGNAL(itemClicked(QTableWidgetItem*)),
this, SLOT(slotConnectWifi(QTableWidgetItem*)));
slotTimeout();
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(slotTimeout()));
timer->start(2000);
initTabWidget();
}
FormWifiManage::~FormWifiManage()
{
delete ui;
}
void FormWifiManage::initTabWidget()
{
QString qssTV = "QTableWidget::item:hover{background-color:rgb(92,188,227,200)}"
"QTableWidget::item:selected{background-color:#1B89A1}"
"QHeaderView::section,QTableCornerButton:section{ \
padding:3px; margin:0px; color:#DCDCDC; border:1px solid #242424; \
border-left-width:0px; border-right-width:1px; border-top-width:0px; border-bottom-width:1px; \
background:qlineargradient(spread:pad,x1:0,y1:0,x2:0,y2:1,stop:0 #646464,stop:1 #525252); }"
"QTableWidget{background-color:white;border:none;}";
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选中的方式
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); //禁止编辑
ui->tableWidget->horizontalHeader()->setStretchLastSection(true); //行头自适应表格
ui->tableWidget->horizontalHeader()->setFont(QFont("song", 12));
//点击表时不对表头行光亮(获取焦点)
ui->tableWidget->horizontalHeader()->setHighlightSections(false);
//设置表头字体加粗
QFont font = ui->tableWidget->horizontalHeader()->font();
font.setBold(true);
ui->tableWidget->horizontalHeader()->setFont(font);
//ui->tableWidget->horizontalHeader()->setStyleSheet("QHeaderView::section{background:lightblue;}"); //skyblue设置表头背景色
//ui->tableWidget->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色
ui->tableWidget->setStyleSheet(qssTV);
ui->tableWidget->horizontalHeader()->setHighlightSections(false); //点击表头时不对表头光亮
ui->tableWidget->setSelectionMode(QAbstractItemView::ContiguousSelection);//选中模式为多行选中
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
//所有单元格的字体 设置成一样
ui->tableWidget->setFont(QFont("song", 12));
ui->tableWidget->setRowCount(1); //设置行数
ui->tableWidget->setColumnCount(2); //设置列数
ui->tableWidget->setWindowTitle("SQL数据");
QStringList header;
header<<"ssid"<<"signal";
ui->tableWidget->setHorizontalHeaderLabels(header);
//去掉默认行号 可以用horizontalHeader()->setVisible(false)隐藏横向表头
QHeaderView *header1 = ui->tableWidget->verticalHeader();
header1->setHidden(true);
//设置单元格大小
ui->tableWidget->horizontalHeader()->setDefaultSectionSize(50); //设置默认宽度
ui->tableWidget->verticalHeader()->setDefaultSectionSize(30); //设置一行默认高度
ui->tableWidget->setColumnWidth(0,450);
ui->tableWidget->setColumnWidth(1,30);
}
void FormWifiManage::showWifiInfo()
{
// 清空表格并重新设置行列数
ui->tableWidget->clearContents();
ui->tableWidget->setRowCount(0);
ui->tableWidget->setColumnCount(2);
ui->tableWidget->setHorizontalHeaderLabels(QStringList{"ssid","signal"});
int size = wifi_list.size();
ui->tableWidget->setRowCount(size);
ui->tableWidget->insertRow(size);
QTableWidgetItem *item=nullptr;
for(int i = 0; i < size; i++){
//插入数据
item=new QTableWidgetItem(wifi_list.at(i).ssid);
ui->tableWidget->setItem(i,0,item);
item=new QTableWidgetItem(QString::number(wifi_list.at(i).signal_level));
ui->tableWidget->setItem(i,1,item);
}
ui->tableWidget->setSortingEnabled(true); //排序
ui->tableWidget->sortItems(1, Qt::DescendingOrder);
}
void FormWifiManage::disconnectWifi()
{
system("wpa_cli disconnect");
}
void FormWifiManage::slotTimeout()
{
QString list;
QString ipaddress;
const char *_cmd = "wpa_cli -i wlan0 status";
FILE *file;
char line[CMD_RESULT_BUF_SIZE];
file = popen(_cmd, "r");
if (NULL != file)
{
while (fgets(line, CMD_RESULT_BUF_SIZE, file) != NULL)
{
//printf("line: %s\n", line);
QString linedata = line;
if (linedata.contains("wpa_state")){
list += linedata;
wpa_state = linedata.mid(QString("wpa_state=").size(),
linedata.size()- QString("wpa_state=").size()-1);
}
if (linedata.contains("ip_address")){
list += linedata;
ipaddress=linedata.mid(QString("ip_address=").size(),
linedata.size()- QString("ip_address=").size()-1);
}
if (linedata.contains("ssid=")){
ssid = linedata.mid(QString("ssid=").size(), linedata.size()- QString("ssid=").size()-1);
}
}
}else {
printf("popen %s error\n", _cmd);
}
pclose(file);
//qDebugInfo() << ssid << ", " << wpa_state << ", " << ipaddress;
ssid=characterConversion(ssid);
ui->label_ssid_name->setText(ssid);
QString connectstate = wpa_state=="COMPLETED" ? QString("已连接(%1)").arg(wpa_state):
QString("已断开(%1)").arg(wpa_state);
ui->label_status_2->setText(connectstate);
ui->label_ip_address->setText(ipaddress);
}
void FormWifiManage::reconnectWifi()
{
if (!selectIndex){
return ;
}
m_name = m_current_item->text();
if (m_name.isEmpty()) return;
dialog = new CDialogBox(this);
dialog->setWindowTitle("WIFI");
dialog->setFixedSize(400, 250);
dialog->setWindowModality(Qt::WindowModal);
password = new QLineEdit(dialog);
label = new QLabel(dialog);
setLabelText(m_name);
label->setGeometry(5, 60, 380, 40);
QLabel *lblpassword = new QLabel(dialog);
lblpassword->setText("密码:");
lblpassword->setGeometry(5, 130, 60, 40);
connect(password, SIGNAL(textChanged(const QString &)),
this, SLOT(wifiPassword(const QString&)));
password->setGeometry(70, 130, 280, 40);
QToolButton *confirm = new QToolButton(dialog);
confirm->setText("确定");
confirm->setGeometry(220, 190, 100, 50);
QToolButton *cancel = new QToolButton(dialog);
cancel->setText("取消");
cancel->setGeometry(100, 190, 100, 50);
connect(confirm, SIGNAL(clicked()), this, SLOT(slotConnectToWifi()));
connect(cancel, SIGNAL(clicked()), dialog, SLOT(close()));
dialog->exec();
}
void FormWifiManage::setLabelText(const QString &text)
{
if(label!=nullptr){
label->setText("SSID: " + text);
}
}
QString FormWifiManage::getPassword() const
{
if (password!=nullptr){
return password->text();
}
return "";
}
void FormWifiManage::slotConnectToWifi()
{
if (getPassword().size()<8){
CMessageBox::critical(dialog, "ERR", "密码不能为空或小于八位");
return;
}
dialog->done(0);
qDebug() << wpa_state << ", " << ssid << ", " << m_name;
if (wpa_state.contains("COMPLETED")&&ssid==m_name){
qDebug() << "************************";
return;
}
system("wpa_cli disconnect");
usleep(100000);
QString wificonf = QString(
"ctrl_interface=/var/run/wpa_supplicant\n"
"ap_scan=1\n"
"update_config=1\n"
"\n"
"network={\n"
" ssid=\"%1\"\n"
" psk=\"%2\"\n"
" key_mgmt=WPA-PSK\n"
"}\n").arg(m_name.simplified()).arg(m_password);
qDebugInfo() << wificonf;
//wpa_passphrase wifi_name wifi_password12345678 >/data/cfg/wpa_supplicant.conf
QFile file("/data/cfg/wpa_supplicant.conf");
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
file.write(wificonf.toUtf8());
}else{
qDebug() << file.errorString();
}
fsync(file.handle());
file.close();
system("wpa_cli reconfigure");
usleep(100000);
system("wpa_cli reconnect");
}
void FormWifiManage::wifiPassword(const QString& password)
{
m_password = password;
}
void FormWifiManage::slotConnectWifi(QTableWidgetItem* item)
{
selectIndex=true;
m_current_item=item;
}
void FormWifiManage::slotScanWifi()
{
isscaning=true;
wifi_list.clear();
scanwifi(wifi_list);
// foreach(wifi_info_t wifi, wifi_list){
// qDebug() << wifi.bssid << ", " << wifi.frequency << ", "
// << wifi.signal_level << ", " << wifi.flags << ", "
// << wifi.ssid;
// }
showWifiInfo();
}
效果就是下面这样了