wireless connect/disconnect

This commit is contained in:
jzxc95 2021-07-09 09:16:49 +08:00
parent 38c052912e
commit 3d82cfb811
8 changed files with 496 additions and 276 deletions

View File

@ -1,8 +1,43 @@
#include "kylinnetworkconnect.h"
#include "sys/syslog.h"
NetworkManager::ConnectionSettings::Ptr assembleWpaXPskSettings(const NetworkManager::AccessPoint::Ptr accessPoint, const QString &psk)
{
NetworkManager::ConnectionSettings::Ptr settings{new NetworkManager::ConnectionSettings{NetworkManager::ConnectionSettings::Wireless}};
settings->setId(accessPoint->ssid());
settings->setUuid(NetworkManager::ConnectionSettings::createNewUuid());
settings->setAutoconnect(true);
//Note: workaround for wrongly (randomly) initialized gateway-ping-timeout
settings->setGatewayPingTimeout(0);
NetworkManager::WirelessSetting::Ptr wifi_sett
= settings->setting(NetworkManager::Setting::Wireless).dynamicCast<NetworkManager::WirelessSetting>();
wifi_sett->setInitialized(true);
wifi_sett->setSsid(accessPoint->ssid().toUtf8());
wifi_sett->setSecurity("802-11-wireless-security");
NetworkManager::WirelessSecuritySetting::Ptr security_sett
= settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast<NetworkManager::WirelessSecuritySetting>();
security_sett->setInitialized(true);
if (NetworkManager::AccessPoint::Adhoc == accessPoint->mode())
{
wifi_sett->setMode(NetworkManager::WirelessSetting::Adhoc);
security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaNone);
} else
{
security_sett->setKeyMgmt(NetworkManager::WirelessSecuritySetting::WpaPsk);
}
security_sett->setPsk(psk);
return settings;
}
KyNetworkConnect::KyNetworkConnect()
{
m_networkResourceInstance = KyNetworkResourceManager::getInstance();
connect(this, &KyNetworkConnect::checkActiveonnection, this, &KyNetworkConnect::onCheckActiveonnection);
}
KyNetworkConnect::~KyNetworkConnect()
@ -133,3 +168,275 @@ void KyNetworkConnect::requestAllWifiScan()
{
return;
}
void KyNetworkConnect::activateWirelessConnection(NetworkManager::WirelessNetwork::Ptr wirelessNet)
{
qDebug() << "activateWirelessConnections" ;
emit starWaiting();
QString conn_uni;
QString dev_uni;
QString conn_name;
QString dev_name;
QString spec_object;
auto access_point = wirelessNet->referenceAccessPoint();
Q_ASSERT(!access_point.isNull());
dev_uni = wirelessNet->device();
syslog(LOG_DEBUG,"dev_uni %s",dev_uni.toUtf8().data());
auto dev = m_networkResourceInstance->findDeviceUni(dev_uni);
Q_ASSERT(!dev.isNull());
auto spec_dev = dev->as<NetworkManager::WirelessDevice>();
Q_ASSERT(nullptr != spec_dev);
conn_uni = access_point->uni();
syslog(LOG_DEBUG,"conn_uni %s",conn_uni.toUtf8().data());
conn_name = access_point->ssid();
syslog(LOG_DEBUG,"conn_name %s",conn_name.toUtf8().data());
//find the device name
NetworkManager::Connection::Ptr conn;
dev_name = dev->interfaceName();
syslog(LOG_DEBUG,"dev_name %s",dev_name.toUtf8().data());
for (auto const & dev_conn : dev->availableConnections())
{
syslog(LOG_DEBUG,"dev_conn->settings()->id() %s",dev_conn->settings()->id().toUtf8().data());
if (dev_conn->settings()->id() == conn_name)
{
conn = dev_conn;
}
}
conn_uni = conn->path();
qDebug()<<conn_uni;
QDBusPendingCallWatcher * watcher;
watcher = new QDBusPendingCallWatcher{NetworkManager::activateConnection(conn_uni, dev_uni, spec_object), this};
connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) {
if (watcher->isError() || !watcher->isValid())
{
//TODO: in what form should we output the warning messages
qWarning() << QStringLiteral("activation of connection failed: %1").arg(watcher->error().message());
} else {
emit checkActiveonnection((qdbus_cast<QDBusObjectPath>(watcher->reply().arguments().at(0))).path());
}
qDebug() <<" " << (qdbus_cast<QDBusObjectPath>(watcher->reply().arguments().at(0))).path();
watcher->deleteLater();
});
}
void KyNetworkConnect::addAndActivateWirelessConnection(NetworkManager::WirelessNetwork::Ptr wirelessNet, const QString &psk)
{
qDebug() << "addAndActivateWirelessConnection" ;
emit starWaiting();
QString conn_uni;
QString dev_uni;
QString conn_name;
QString dev_name;
QString spec_object;
NMVariantMapMap map_settings;
auto access_point = wirelessNet->referenceAccessPoint();
Q_ASSERT(!access_point.isNull());
dev_uni = wirelessNet->device();
syslog(LOG_DEBUG,"dev_uni %s",dev_uni.toUtf8().data());
auto dev = m_networkResourceInstance->findDeviceUni(dev_uni);
Q_ASSERT(!dev.isNull());
auto spec_dev = dev->as<NetworkManager::WirelessDevice>();
Q_ASSERT(nullptr != spec_dev);
conn_uni = access_point->uni();
syslog(LOG_DEBUG,"conn_uni %s",conn_uni.toUtf8().data());
conn_name = access_point->ssid();
syslog(LOG_DEBUG,"conn_name %s",conn_name.toUtf8().data());
//find the device name
NetworkManager::Connection::Ptr conn;
dev_name = dev->interfaceName();
syslog(LOG_DEBUG,"dev_name %s",dev_name.toUtf8().data());
//TODO: in what form should we output the warning messages
qWarning() << QStringLiteral("can't find connection for '%1' on device '%2', will create new...").arg(conn_name).arg(dev_name);
spec_object = conn_uni;
NetworkManager::WirelessSecurityType sec_type = NetworkManager::findBestWirelessSecurity(spec_dev->wirelessCapabilities()
, true, (spec_dev->mode() == NetworkManager::WirelessDevice::Adhoc)
, access_point->capabilities(), access_point->wpaFlags(), access_point->rsnFlags());
qDebug() << "findBestWirelessSecurity type "<< sec_type;
switch (sec_type)
{
case NetworkManager::UnknownSecurity:
qWarning() << QStringLiteral("unknown security to use for '%1'").arg(conn_name);
case NetworkManager::NoneSecurity:
//nothing to do
break;
case NetworkManager::WpaPsk:
case NetworkManager::Wpa2Psk:
if (NetworkManager::ConnectionSettings::Ptr settings = assembleWpaXPskSettings(access_point,psk))
{
map_settings = settings->toMap();
} else
{
qWarning() << QStringLiteral("connection settings assembly for '%1' failed, abandoning activation...").arg(conn_name);
return;
}
break;
//TODO: other types...
}
QDBusPendingCallWatcher * watcher;
watcher = new QDBusPendingCallWatcher{NetworkManager::addAndActivateConnection(map_settings, dev_uni, spec_object), this};
connect(watcher, &QDBusPendingCallWatcher::finished, [&] (QDBusPendingCallWatcher * watcher) {
if (watcher->isError() || !watcher->isValid())
{
//TODO: in what form should we output the warning messages
qDebug() << "activation of connection failed " << watcher->error().message();
}
else{
emit checkActiveonnection((qdbus_cast<QDBusObjectPath>(watcher->reply().arguments().at(1))).path());
}
watcher->deleteLater();
});
}
void KyNetworkConnect::onActivateWirelessConnection(const QString &connectSsid, const QString &connectUuid)
{
qDebug() << "onActivateWirelessConnection" << connectSsid;
NetworkManager::WirelessNetwork::Ptr wirelessNet = nullptr;
for (auto const & net : m_networkResourceInstance->m_wifiNets)
{
if (net->ssid() == connectSsid)
{
wirelessNet = net;
break;
}
}
if (wirelessNet.isNull())
{
//TODO:隐藏wifi不会存在与AP中需要新建connection去连接
qDebug() << "hidewifi";
return;
}
qDebug() << "非隐藏wifi";
NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid);
if (connectPtr.isNull())
{
//无配置文件前段输入完密码直接调用addAndActivateWirelessConnection
qDebug() << "emit noConnection";
emit noConnection();
return;
}
// //获取安全类型
// NetworkManager::ConnectionSettings::Ptr settings = connectPtr->settings();
// NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity =
// settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast<NetworkManager::WirelessSecuritySetting>();
// int key_mgmt = wifiSecurity->keyMgmt();
//获取密码存储策略 0:所有用户存储 1:当前用户存储 2:每次连接询问
NetworkManager::ConnectionSettings::Ptr settings = connectPtr->settings();
NetworkManager::WirelessSecuritySetting::Ptr wifiSecurity =
settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast<NetworkManager::WirelessSecuritySetting>();
int psk_flag = wifiSecurity->pskFlags();
qDebug() << "psk_flag=" <<psk_flag;
if(psk_flag == NetworkManager::Setting::SecretFlagType::NotSaved)
{
//每次都要询问,前端弹出窗口
qDebug() << "emit notSavedConnection";
emit notSavedConnection();
return;
}
activateWirelessConnection(wirelessNet);
}
void KyNetworkConnect::onActivateWirelessConnectionWithPWD(const QString &connectSsid, const QString &psk, bool isNotSaved, const QString &connectUuid)
{
qDebug() << "onActivateWirelessConnectionWithPWD" << connectSsid;
if(isNotSaved && !connectUuid.isEmpty())
{
qDebug() << "每次都要询问";
//修改connection psk
NetworkManager::Connection::Ptr connectPtr = m_networkResourceInstance->getConnect(connectUuid);
if (connectPtr.isNull())
{
return;
}
NetworkManager::ConnectionSettings::Ptr settings = connectPtr->settings();
NetworkManager::WirelessSecuritySetting::Ptr security_sett
= settings->setting(NetworkManager::Setting::WirelessSecurity).dynamicCast<NetworkManager::WirelessSecuritySetting>();
qDebug() << connectPtr->path();
security_sett->setPsk(psk);
//
NetworkManager::WirelessNetwork::Ptr wirelessNet = nullptr;
for (auto const & net : m_networkResourceInstance->m_wifiNets)
{
if (net->ssid() == connectSsid)
{
wirelessNet = net;
break;
}
}
activateWirelessConnection(wirelessNet);
return;
}
NetworkManager::WirelessNetwork::Ptr wirelessNet = nullptr;
for (auto const & net : m_networkResourceInstance->m_wifiNets)
{
if (net->ssid() == connectSsid)
{
wirelessNet = net;
break;
}
}
if (wirelessNet.isNull())
{
//TODO:隐藏wifi不会存在与AP中需要新建connection去连接
qDebug() << "hidewifi";
return;
}
addAndActivateWirelessConnection(wirelessNet,psk);
}
void KyNetworkConnect::onCheckActiveonnection(const QString &activeConnPath)
{
if (m_networkResourceInstance->m_activeConns.size() == 0)
{
qDebug() << "不存在activeConnPath";
emit connResult(1);
return;
}
for (auto const & activeConn : m_networkResourceInstance->m_activeConns)
{
if (activeConn->path() == activeConnPath)
{
qDebug() << "存在activeConnPath,且匹配"<<activeConnPath;
qDebug() << activeConn->state();
connect(activeConn.data(), &NetworkManager::ActiveConnection::stateChangedReason, this, &KyNetworkConnect::onStateChangedReason);
return;
}
}
qDebug() << "存在activeConnPath,但不匹配"<<activeConnPath;
emit connResult(1);
}
void KyNetworkConnect::onStateChangedReason(NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason)
{
qDebug() << "onStateChangedReason state:" << state << " reason" << reason;
if (state == NetworkManager::ActiveConnection::State::Activated)
{
emit connResult(0);
} else if (state == NetworkManager::ActiveConnection::State::Deactivating || state == NetworkManager::ActiveConnection::State::Deactivated) {
emit connResult(1);
}
}

View File

@ -13,6 +13,8 @@ public:
public:
int addAndActivateConnect(const QString );
int activateConnection(const QString connectUuid);
void activateWirelessConnection(NetworkManager::WirelessNetwork::Ptr wirelessNet);
void addAndActivateWirelessConnection(NetworkManager::WirelessNetwork::Ptr wirelessNet, const QString &psk);
int deactivateConnection(const QString connectName, const QString &uuid);
void requestScan(const QString ifaceName);
void requestAllWifiScan();
@ -21,6 +23,20 @@ signals:
void activateConnectionFinished(NetworkManager::Connection::Ptr conn);
void deactivateConnectionFinished(NetworkManager::Connection::Ptr conn);
void noConnection();
void notSavedConnection();
signals:
void checkActiveonnection(const QString &activeConn);
void connResult(int);
void starWaiting();
public slots:
void onActivateWirelessConnection(const QString &connectSsid, const QString &connectUuid);
void onActivateWirelessConnectionWithPWD(const QString &connectSsid, const QString &psk, bool isNotSaved, const QString &connectUuid);
void onCheckActiveonnection(const QString &activeConn);
void onStateChangedReason(NetworkManager::ActiveConnection::State state, NetworkManager::ActiveConnection::Reason reason);
private:
KyNetworkResourceManager *m_networkResourceInstance = nullptr;
};

View File

@ -291,6 +291,10 @@ NetworkManager::ActiveConnection::Ptr KyNetworkResourceManager::getActiveConnect
NetworkManager::Connection::Ptr KyNetworkResourceManager::getConnect(const QString connectUuid)
{
if(connectUuid.isEmpty()) {
return nullptr;
}
int index = 0;
NetworkManager::Connection::Ptr connectPtr = nullptr;
@ -478,3 +482,13 @@ void KyNetworkResourceManager::onConnectionRemoved(QString const & path)
emit connectionRemove(conn.data());
}
}
void KyNetworkResourceManager::removeConnection(QString const & uuid)
{
NetworkManager::Connection::Ptr conn = this->getConnect(uuid);
if(!conn.isNull())
{
conn->disconnect(this);
conn->remove();
}
}

View File

@ -66,6 +66,8 @@ public:
void requestScan(NetworkManager::WirelessDevice * dev);
void removeConnection(QString const & uuid);
public:
NetworkManager::Device::Ptr getNetworkDevice(const QString ifaceName);
NetworkManager::ActiveConnection::Ptr getActiveConnect(const QString uuid);

View File

@ -792,12 +792,14 @@ void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
this->showNormal();
this->raise();
this->activateWindow();
currSelNetName = "";
if (is_btnLanList_clicked == 1&& is_stop_check_net_state==0) {
onBtnNetListClicked(0);
}
if (!is_init_wifi_list && !is_connect_hide_wifi && is_stop_check_net_state==0) {
is_stop_check_net_state = 1;
is_stop_:check_net_state = 1;
if (is_btnWifiList_clicked == 1) {
BackThread *loop_bt = new BackThread();
IFace *loop_iface = loop_bt->execGetIface();
@ -1679,7 +1681,7 @@ void MainWindow::on_wifi_changed()
*/
void MainWindow::onNewConnAdded(int type) {
if (type == 1) {
isAddedWifi = true;
// isAddedWifi = true;
}
this->ksnm->execGetConnList();
}
@ -2100,20 +2102,20 @@ void MainWindow::getConnListDone(QStringList slist)
break;
}
}
if (isAddedWifi) {
isAddedWifi = false;
//如果是新添加的wifi尝试激活这个wifi
if (! is_stop_check_net_state) {
this->is_stop_check_net_state = 1;
BackThread *bt = new BackThread();
// connect(bt, SIGNAL(connDone(int)), this, SLOT(connWifiDone(int)));
connect(bt, &BackThread::connDone, this, [ = ](int res) {
connWifiDone(res);
bt->deleteLater();
});
bt->execConnWifi(lastAddedConn, objKyDBus->dbusWiFiCardName);
}
}
// if (isAddedWifi) {
// isAddedWifi = false;
// //如果是新添加的wifi尝试激活这个wifi
// if (! is_stop_check_net_state) {
// this->is_stop_check_net_state = 1;
// BackThread *bt = new BackThread();
//// connect(bt, SIGNAL(connDone(int)), this, SLOT(connWifiDone(int)));
// connect(bt, &BackThread::connDone, this, [ = ](int res) {
// connWifiDone(res);
// bt->deleteLater();
// });
// bt->execConnWifi(lastAddedConn, objKyDBus->dbusWiFiCardName);
// }
// }
oldConnSlist.clear();
oldConnSlist = newConnSlist;
return;
@ -3155,6 +3157,7 @@ void MainWindow::updateWifiListDone(QStringList slist)
this->wifiListWidget->show();
this->topWifiListWidget->show();
this->stopLoading();
is_stop_check_net_state = 0;
emit this->getWifiListFinished();
}
@ -3922,7 +3925,6 @@ void MainWindow::onExternalConnectionChange(QString type, bool isConnUp)
if (!is_connect_hide_wifi && !is_stop_check_net_state) {
is_stop_check_net_state = 1;
if (type == "802-3-ethernet" || type == "ethernet") {
if (is_connect_net_failed) {
qDebug()<<"debug: connect wired network failed, no need to refresh wired interface";

View File

@ -164,7 +164,7 @@ public:
NetworkSpeed *objNetSpeed = nullptr;
SwitchButton *btnWireless = nullptr;
SwitchButton *btnWired = nullptr;
KyNetworkResourceManager *m_networkResourceInstance = nullptr;
//状态设置,0为假1为真
int current_wifi_list_state = LOAD_WIFI_LIST;
int is_init_wifi_list = 0; //是否在启动软件时正在获取wifi的列表
@ -379,8 +379,6 @@ private:
QDBusInterface *mDbusXrandInter;
QDBusInterface *kdsDbus;
KyNetworkResourceManager *m_networkResourceInstance = nullptr;
private slots:
void iconActivated(QSystemTrayIcon::ActivationReason reason);

View File

@ -228,11 +228,25 @@ OneConnForm::OneConnForm(QWidget *parent, MainWindow *mainWindow, ConfForm *conf
m_menu = new QMenu();//右键菜单
connect(m_menu, &QMenu::triggered, this, &OneConnForm::onMenuTriggered);
m_networkConnect = new KyNetworkConnect();
connect(this, &OneConnForm::activateWirelessConnection, m_networkConnect, &KyNetworkConnect::onActivateWirelessConnection);
connect(this, &OneConnForm::activateWirelessConnectionWithPWD, m_networkConnect, &KyNetworkConnect::onActivateWirelessConnectionWithPWD);
connect(m_networkConnect, &KyNetworkConnect::noConnection, this, &OneConnForm::onNoConnetion);
connect(m_networkConnect, &KyNetworkConnect::notSavedConnection, this, &OneConnForm::onNotSavedConnection);
connect(m_networkConnect, &KyNetworkConnect::connResult, this ,&OneConnForm::slotConnWifiResult);
connect(m_networkConnect, &KyNetworkConnect::starWaiting, [=](){
this->startWifiWaiting(true);
});
connect(this, SIGNAL(connDone(int)), mw, SLOT(connWifiDone(int)));
}
OneConnForm::~OneConnForm()
{
delete ui;
delete m_networkConnect;
if (m_menu) {
delete m_menu;
m_menu = nullptr;
@ -253,15 +267,14 @@ void OneConnForm::mousePressEvent(QMouseEvent *event)
m_menu->move(cursor().pos());
m_menu->show();
}
qDebug() << "selectedOneWifiForm";
emit selectedOneWifiForm(wifiBSsid, H_WIFI_ITEM_BIG_EXTEND);
}
bool OneConnForm::checkIsSaved()
{
QString name = this->wifiName;
QString currStr = "nmcli -f connection.type connection show \"" + name.replace("\"","\\\"") + "\"";
int status = system(currStr.toUtf8().data());
if (status != 0){
QString uuid = getUuidByWifiName(wifiName);
if (uuid.isEmpty()){
qDebug()<<"There is no configuration for wifi "<<this->wifiName;
return false;
} else {
@ -282,13 +295,9 @@ bool OneConnForm::onMenuTriggered(QAction *action)
this->on_btnConn_clicked();
return true;
} else if (action->text() == tr("Forget")) {
QString name = this->wifiName;
QString currStr = "nmcli connection delete \"" + name.replace("\"","\\\"") + "\"";
int status = system(currStr.toUtf8().data());
if (status != 0){
qDebug()<<"Delete wifi failed. wifi="<<this->wifiName;
return false;
}
QString uuid = getUuidByWifiName(wifiName);
mw->m_networkResourceInstance->removeConnection(uuid);
hasPwd = false;
return true;
}
}
@ -533,8 +542,12 @@ void OneConnForm::setSignal(QString lv, QString secu, QString category, bool has
{
this->m_signal = lv.toInt();
int signal = lv.toInt();
if (secu == "--" || secu == "") {
QString uuid = getUuidByWifiName(wifiName);
if (uuid.isEmpty())
{
hasPwd = false;
this->lbPwdTip->hide();
} else {
hasPwd = true;
}
@ -635,6 +648,7 @@ void OneConnForm::slotConnWifiPWD()
//点击后断开wifi网络
void OneConnForm::on_btnDisConn_clicked()
{
qDebug()<<"on_btnDisConn_clicked";
if (mw->is_stop_check_net_state == 1) {
return;
}
@ -647,9 +661,9 @@ void OneConnForm::on_btnDisConn_clicked()
this->startWifiWaiting(false);
mw->is_stop_check_net_state = 1;
//mw->on_btnHotspotState();
//kylin_network_set_con_down(wifiName.toUtf8().data());
kylin_network_set_con_down(wifiUuid.toUtf8().data());
QString uuid = getUuidByWifiName(wifiName);
m_networkConnect->deactivateConnection(wifiName,uuid);
disconnect(this, SIGNAL(selectedOneWifiForm(QString,int)), mw, SLOT(oneTopWifiFormSelected(QString,int)));
emit requestHandleWifiDisconn();
}
@ -657,12 +671,18 @@ void OneConnForm::on_btnDisConn_clicked()
//点击列表item扩展时会出现该按钮 用于连接网络
void OneConnForm::on_btnConnSub_clicked()
{
qDebug()<<"on_btnConnSub_clicked";
if (mw->is_stop_check_net_state == 1) {
return;
}
if (lbPwdTip->isVisible() && this->hasPwd) {
this->slotConnWifiResult(2);
qDebug()<<"check lbPwdTip";
if (lbPwdTip->isVisible()) {
QString uuid = getUuidByWifiName(wifiName);
mw->m_networkResourceInstance->removeConnection(uuid);
hasPwd = false;
showLePassword();
lbPwdTip->hide();
return;
}
@ -673,21 +693,73 @@ void OneConnForm::on_btnConnSub_clicked()
//无需密码的wifi连接
void OneConnForm::on_btnConn_clicked()
{
qDebug()<<"on_btnConn_clicked";
if (mw->is_stop_check_net_state == 1) {
return;
}
if (lbPwdTip->isVisible() && this->hasPwd) {
this->slotConnWifiResult(2);
qDebug()<<"check lbPwdTip";
if (lbPwdTip->isVisible()) {
QString uuid = getUuidByWifiName(wifiName);
mw->m_networkResourceInstance->removeConnection(uuid);
hasPwd = false;
showLePassword();
lbPwdTip->hide();
return;
}
qDebug()<<"A button named btnConn about wifi net is clicked.";
toConnectWirelessNetwork();
}
//无配置文件认为是第一次连接的wifi需要显示密码输入框
void OneConnForm::onNoConnetion()
{
qDebug()<<"onNoConnetion";
showLePassword();
mw->is_stop_check_net_state = 0;
}
void OneConnForm::onNotSavedConnection()
{
qDebug()<<"onNotSavedConnection";
mw->is_stop_check_net_state = 0;
showLePassword();
}
//显示密码框
void OneConnForm::showLePassword()
{
// mw->currSelNetName = "";
emit selectedOneWifiForm(wifiBSsid, H_WIFI_ITEM_SMALL_EXTEND);
resize(W_ITEM, H_ITEM_MIDDLE);
ui->wbg->hide();
ui->wbg_2->show();
ui->wbg_3->hide();
ui->leInfo_1->hide();
ui->leInfo_2->hide();
ui->leInfo_3->hide();
ui->btnHideConn->hide();
ui->btnDisConn->hide();
ui->btnConn->hide();
ui->btnConnSub->hide();
ui->line->move(X_LINE_SMALL_EXTEND, Y_LINE_SMALL_EXTEND);
ui->lePassword->show();
ui->checkBoxPwd->show();
ui->btnConnPWD->show();
this->isSelected = true;
//设置输入密码框被选中
ui->lePassword->setFocus();
ui->lePassword->setEchoMode(QLineEdit::Password);
ui->checkBoxPwd->setChecked(false);
}
void OneConnForm::toConnectWirelessNetwork()
{
qDebug() << "toConnectWirelessNetwork";
if (wifiSecu.contains("802.1x", Qt::CaseInsensitive)) {
//企业wifi
WifiConfig wc;
@ -733,203 +805,48 @@ void OneConnForm::toConnectWirelessNetwork()
return;
}
if (ui->lbConned->text() == "--" || ui->lbConned->text() == " ") {
if (!isWifiConfExist(wifiName)) {
//没有配置文件使用有密码的wifi连接
psk_flag = 0;
on_btnConnPWD_clicked();
return;
}
}
//有配置文件需要判断一下当前配置文件wifi安全性是不是wpa-eap若是需要把原配置文件删除重新配置
QProcess * process = new QProcess(this);
connect(process, static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished), this, [ = ]() {
process->deleteLater();
});
connect(process, &QProcess::readyReadStandardOutput, this, [ = ]() {
QString str = process->readAllStandardOutput();
key_mgmt = str.mid(str.lastIndexOf(":") + 1).trimmed();
});
process->start(QString("nmcli -f 802-11-wireless-security.key-mgmt connection show \"%1\"").arg(wifiName));
process->waitForFinished();
QString cur_secu;
//企业wifi内容逻辑暂时不动
QString uuid = getUuidByWifiName(wifiName);
mw->is_stop_check_net_state = 1;
emit activateWirelessConnection(wifiName,uuid);
/*QString cur_secu;
if (wifiSecu.contains("WPA3"))
cur_secu = "sae";
else if (wifiSecu.contains("--"))
cur_secu = "--";
else
cur_secu = "wpa-psk";
if (!hasPwd && !key_mgmt.isEmpty()) {
QString cmdStr = "nmcli connection delete \"" + wifiName + "\"";
Utils::m_system(cmdStr.toUtf8().data());
psk_flag = 0;
if (lbPwdTip->isVisible()) {
lbPwdTip->hide();
mw->m_wifi_list_pwd_changed.removeOne(wifiName);
}
toConnectWirelessNetwork();
return;
} else if (!key_mgmt.isEmpty() && QString::compare(key_mgmt, cur_secu) != 0) {
//原配置文件与当前加密方式不一致,删掉,请求输入新的密码
QString cmdStr = "nmcli connection delete \"" + wifiName + "\"";
Utils::m_system(cmdStr.toUtf8().data());
psk_flag = 0;
slotConnWifiResult(2); //现在已无配置文件,申请输入密码
return;
}
cur_secu = "wpa-psk";*/
if (isWifiConfExist(wifiName)) {
//有配置文件,获取密码存储策略
QProcess * process = new QProcess(this);
process->start(QString("nmcli -f 802-11-wireless-security.psk-flags connection show \"%1\"").arg(wifiName));
connect(process, static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished), this, [ = ]() {
process->deleteLater();
});
connect(process, &QProcess::readyReadStandardOutput, this, [ = ]() {
//QString str = process->readAllStandardOutput();
//psk_flag = str.mid(str.lastIndexOf(" ") - 1, 1).toInt();
QString str = process->readAllStandardOutput();
QString regExpPattern("[ ][0-9][ (]");
QRegExp regExpTest(regExpPattern);
int pos = str.indexOf(regExpTest);
psk_flag = str.mid(pos,2).trimmed().toInt();
});
process->waitForFinished();
}
if (key_mgmt == "wpa-psk" && this->getPskFlag() == 2) {
//当设置为每次询问密码时执行
QPoint pos = QCursor::pos();
QRect primaryGeometry;
for (QScreen *screen : qApp->screens()) {
if (screen->geometry().contains(pos)) {
primaryGeometry = screen->geometry();
}
}
if (primaryGeometry.isEmpty()) {
primaryGeometry = qApp->primaryScreen()->geometry();
}
QApplication::setQuitOnLastWindowClosed(false);
WiFiConfigDialog *wifiConfigDialog = new WiFiConfigDialog();
wifiConfigDialog->move(primaryGeometry.width() / 2 - wifiConfigDialog->width() / 2, primaryGeometry.height() / 2 - wifiConfigDialog->height() / 2);
wifiConfigDialog->show();
wifiConfigDialog->raise();
return;
}
if (psk_flag != 0) { //未为所有用户存储密码
QString homePath = getenv("HOME");
if (QFile(QString("%1/.config/%2.psk").arg(homePath).arg(wifiName)).exists()) { //已为该用户存储密码
mw->is_stop_check_net_state = 1;
QThread *t = new QThread();
BackThread *bt = new BackThread();
bt->moveToThread(t);
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
connect(t, &QThread::started, this, [ = ]() {
this->startWifiWaiting(true);
QString cmdStr = "nmcli connection up '" + wifiName + "' passwd-file " + homePath +"/.config/" + wifiName + ".psk";
qDebug()<<"Trying to connect wifi. ssid="<<wifiName;
emit this->sigConnWifiPsk(cmdStr);
});
connect(this, SIGNAL(sigConnWifiPsk(QString)), bt, SLOT(execConnWifiPsk(QString)));
connect(bt, &BackThread::connDone, this, [ = ](int res) {
this->stopWifiWaiting(true);
mw->is_stop_check_net_state = 0;
if (res) {
QFile::remove(QString("%1/.config/%2.psk").arg(homePath).arg(wifiName).toUtf8());
}
mw->connWifiDone(res);
});
connect(bt, SIGNAL(btFinish()), t, SLOT(quit()));
t->start();
} else { //没有为该用户存储密码
slotConnWifiResult(2);
}
return;
} else { //为所有用户存储密码
QString homePath = getenv("HOME");
QFile::remove(QString("%1/.config/%2.psk").arg(homePath).arg(wifiName).toUtf8()); //删除密码文件
}
mw->is_stop_check_net_state = 1;
m_connWithPwd = false;
QThread *t = new QThread();
BackThread *bt = new BackThread();
bt->moveToThread(t);
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
connect(t, SIGNAL(started()), this, SLOT(slotConnWifi()));
connect(this, SIGNAL(sigConnWifi(QString, QString)), bt, SLOT(execConnWifi(QString, QString)));
connect(bt, SIGNAL(connDone(int)), mw, SLOT(connWifiDone(int)));
connect(bt, SIGNAL(connDone(int)), this, SLOT(slotConnWifiResult(int)));
connect(bt, SIGNAL(btFinish()), t, SLOT(quit()));
t->start();
}
//需要密码的wifi连接
void OneConnForm::on_btnConnPWD_clicked()
{
qDebug()<<"on_btnConnPWD_clicked";
mw->m_is_inputting_wifi_password = false; //点击连接表示密码输入已完成
m_connWithPwd = true;
bool bIsNotSaved = false;
qDebug()<<"A button named btnConnPWD about wifi net is clicked.";
QString uuid = getUuidByWifiName(wifiName);
if (lbPwdTip->isVisible()) {
QString modifyCmd = "nmcli connection modify \""+ wifiName + "\" " + "802-11-wireless-security.psk " + ui->lePassword->text();
int mdf_res = system(modifyCmd.toUtf8().data());
qDebug()<<"Modified wifi password, cmd="<<modifyCmd<<";res="<<mdf_res;
lbPwdTip->hide();
mw->m_wifi_list_pwd_changed.removeOne(wifiName);
}
if (this->getPskFlag() != 0) {
// QString cmdStr = 0;
QString homePath = getenv("HOME");
QFile *passwdFile = new QFile(QString("%1/.config/%2.psk").arg(homePath).arg(wifiName));
if (passwdFile->open(QIODevice::ReadWrite)) {
passwdFile->write(QString("802-11-wireless-security.psk:%1").arg(ui->lePassword->text()).toUtf8());
passwdFile->close();
// cmdStr = "nmcli connection up " + wifiName + " passwd-file " + homePath +"/.config/" + wifiName + ".psk";
if (!uuid.isEmpty())
{
bIsNotSaved = true;
}
mw->is_stop_check_net_state = 1;
QThread *t = new QThread();
BackThread *bt = new BackThread();
bt->moveToThread(t);
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
connect(t, &QThread::started, this, [ = ]() {
this->startWifiWaiting(true);
QString cmdStr = "nmcli connection up '" + wifiName + "' passwd-file " + homePath +"/.config/" + wifiName + ".psk";
qDebug()<<"Trying to connect wifi. ssid="<<wifiName;
emit this->sigConnWifiPsk(cmdStr);
});
connect(this, SIGNAL(sigConnWifiPsk(QString)), bt, SLOT(execConnWifiPsk(QString)));
connect(bt, &BackThread::connDone, this, [ = ](int res) {
this->stopWifiWaiting(true);
mw->is_stop_check_net_state = 0;
if (res) {
QFile::remove(QString("%1/.config/%2.psk").arg(homePath).arg(wifiName).toUtf8());
}
mw->connWifiDone(res);
});
connect(bt, SIGNAL(btFinish()), t, SLOT(quit()));
t->start();
}
if (! mw->is_stop_check_net_state) {
mw->is_stop_check_net_state = 1;
QThread *t = new QThread();
BackThread *bt = new BackThread();
bt->moveToThread(t);
connect(t, SIGNAL(finished()), t, SLOT(deleteLater()));
connect(t, SIGNAL(started()), this, SLOT(slotConnWifiPWD()));
connect(this, SIGNAL(sigConnWifiPWD(QString, QString, QString, QString, QString)),
bt, SLOT(execConnWifiPWD(QString, QString, QString, QString, QString)));
connect(bt, SIGNAL(connDone(int)), mw, SLOT(connWifiDone(int)));
connect(bt, SIGNAL(connDone(int)), this, SLOT(slotConnWifiResult(int)));
connect(bt, SIGNAL(btFinish()), t, SLOT(quit()));
t->start();
}
emit activateWirelessConnectionWithPWD(wifiName,ui->lePassword->text(),bIsNotSaved,uuid);
}
//点击后弹出连接隐藏wifi网络窗口
@ -1088,6 +1005,8 @@ void OneConnForm::slotConnWifiResult(int connFlag)
}
connType = "";
emit connDone(connFlag);
if (connFlag == 0) {
if (mw->isHuaWeiPC) {
//network-manager可能会连接到其他bssid对应的网络改成我们想要连接的那个网络
@ -1116,60 +1035,28 @@ void OneConnForm::slotConnWifiResult(int connFlag)
}
disconnect(this, SIGNAL(selectedOneWifiForm(QString,int)), mw, SLOT(oneWifiFormSelected(QString,int)));
if (lbPwdTip&&lbPwdTip->isVisible())
this->lbPwdTip->hide();
}
if (connFlag == 1 || connFlag == 4) {
if (!m_connWithPwd && hasPwd) {
//用原有配置文件连接失败,显示密码错误
qDebug()<<"Connected failed with old configuration. ssid="<<wifiName;
if(connFlag == 1)
{
qDebug() << "11111111111111111111111";
if (hasPwd) {
if (mw)
mw->m_wifi_list_pwd_changed.append(wifiName);
if (lbPwdTip)
this->lbPwdTip->show();
} else {
// 使用密码连接失败,需要删除该配置文件
QString cmd = "export LANG='en_US.UTF-8';export LANGUAGE='en_US';nmcli connection delete '" + wifiName + "'";
int status = system(cmd.toUtf8().data());
if (status != 0) {
qDebug()<<"execute 'nmcli connection delete' in function 'slotConnWifiResult' failed.";
}
mw->m_networkResourceInstance->removeConnection(getUuidByWifiName(wifiName));
hasPwd = false;
}
}
if (connFlag == 2 || connFlag == 4 || connFlag == 1) {
mw->currSelNetName = "";
emit selectedOneWifiForm(wifiBSsid, H_WIFI_ITEM_SMALL_EXTEND);
resize(W_ITEM, H_ITEM_MIDDLE);
ui->wbg->hide();
ui->wbg_2->show();
ui->wbg_3->hide();
ui->leInfo_1->hide();
ui->leInfo_2->hide();
ui->leInfo_3->hide();
ui->btnHideConn->hide();
ui->btnDisConn->hide();
ui->btnConn->hide();
ui->btnConnSub->hide();
ui->line->move(X_LINE_SMALL_EXTEND, Y_LINE_SMALL_EXTEND);
ui->lePassword->show();
ui->checkBoxPwd->show();
ui->btnConnPWD->show();
this->isSelected = true;
//if (connFlag == 2) {
// mw->is_stop_check_net_state = 0;
//} else {
// mw->is_stop_check_net_state = 0;
// //connType = "RequestPassword";
//}
//设置输入密码框被选中
ui->lePassword->setFocus();
ui->lePassword->setEchoMode(QLineEdit::Password);
ui->checkBoxPwd->setChecked(false);
showLePassword();
}
this->stopWifiWaiting(true);
@ -1205,6 +1092,7 @@ void OneConnForm::waitAnimStep()
void OneConnForm::startWifiWaiting(bool isToConnect)
{
qDebug() << "startWifiWaiting " << isToConnect;
this->isWaiting = true;
if (isToConnect) {
ui->btnCancel->show();
@ -1225,6 +1113,7 @@ void OneConnForm::startWifiWaiting(bool isToConnect)
void OneConnForm::stopWifiWaiting(bool isUpdateTrayIcon)
{
qDebug() << "stopWifiWaiting";
ui->lbWaitingIcon->move(380, 20);
ui->btnCancel->hide();
this->isWaiting = false;
@ -1240,12 +1129,6 @@ void OneConnForm::stopWifiWaiting(bool isUpdateTrayIcon)
void OneConnForm::on_btnCancel_clicked()
{
// QString cmd = "kill -9 $(pidof nmcli)"; //杀掉当前正在进行的有关nmcli命令的进程
// int status = system(cmd.toUtf8().data());
// if (status != 0) {
// qDebug()<<"execute 'kill -9 $(pidof nmcli)' in function 'on_btnCancel_clicked' failed";
// }
KylinDBus myKylinDbus;
QStringList wifiListInfo;
QList<QString> wifiSsidAndUuid = myKylinDbus.getAtiveWifiBSsidUuid(wifiListInfo);
@ -1256,24 +1139,6 @@ void OneConnForm::on_btnCancel_clicked()
this->stopWifiWaiting(true);
}
int OneConnForm::getPskFlag()
{
QProcess * process = new QProcess(this);
process->start(QString("nmcli -f 802-11-wireless-security.psk-flags connection show \"%1\"").arg(wifiName));
connect(process, static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished), this, [ = ]() {
process->deleteLater();
});
connect(process, &QProcess::readyReadStandardOutput, this, [ = ]() {
QString str = process->readAllStandardOutput();
QString regExpPattern("[ ][0-9][ (]");
QRegExp regExpTest(regExpPattern);
int pos = str.indexOf(regExpTest);
psk_flag = str.mid(pos,2).trimmed().toInt();
});
process->waitForFinished();
return psk_flag;
}
/**
* @brief OneConnForm::getWifiConfig
* @param wc
@ -1345,3 +1210,9 @@ bool OneConnForm::getWifiConfig(WifiConfig &wc, QString netName)
return false;
}
QString OneConnForm::getUuidByWifiName(const QString &wifiname)
{
KylinDBus mKylinDBus;
return mKylinDBus.checkHasWifiConfigFile(wifiname);
}

View File

@ -33,6 +33,7 @@
#include "backthread.h"
#include "ksimplenm.h"
#include "wpawifidialog.h"
#include "kylinnetworkconnect.h"
#define FRAME_SPEED 150
#define LIMIT_TIME 90*1000
@ -86,6 +87,8 @@ public:
bool isWifiConfExist(QString netName);
void setlbPwdTipVisble(const bool&);
QString getUuidByWifiName(const QString &wifiname);
QString wifiName;
QString wifiBSsid;
QString wifiUuid;
@ -108,6 +111,8 @@ public slots:
void startWifiWaiting(bool isToConnect);
void stopWifiWaiting(bool isUpdateTrayIcon);
void onBtnPropertyClicked();
void onNoConnetion();
void onNotSavedConnection();
protected:
void mousePressEvent(QMouseEvent *event);
@ -116,6 +121,7 @@ protected:
private:
bool getWifiConfig(WifiConfig &wc, QString netName);
bool checkIsSaved();
void showLePassword();
private slots:
void on_btnConn_clicked();
@ -162,6 +168,7 @@ private:
QString key_mgmt, funcBtnQss;
QPushButton *btnProperty = nullptr;
QMenu * m_menu = nullptr;
KyNetworkConnect *m_networkConnect = nullptr;
signals:
void selectedOneWifiForm(QString wifiName, int extendLength);
@ -172,6 +179,9 @@ signals:
void sigConnWifi(QString, QString);
void sigConnWifiPWD(QString, QString, QString, QString, QString);
void sigConnWifiPsk(QString);
void activateWirelessConnection(const QString &connectSsid, const QString &connectUuid);
void activateWirelessConnectionWithPWD(const QString &connectSsid, const QString &psk, bool isNotSaved, const QString &connectUuid);
};
#endif // ONECONNFORM_H