Files
2026-10-19 17:48:03 +08:00

1820 lines
58 KiB
C++

#include "NetworkManager.h"
#include "ui_NetworkManager.h"
#include <QDebug>
#include <QProcess>
#include <QNetworkInterface>
#include <QMessageBox>
#include "myinclude.h"
#include "dirent.h"
#include "common/wpa_ctrl.h"
#define LANINTERFACE_NAME "eth0"
#ifdef Q_OS_WIN
#include <wbemidl.h>
#include <comdef.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Wbemuuid.lib")
#else
#define BUFSIZE 8192
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/socket.h>
#include <linux/rtnetlink.h>
#include <unistd.h>
#include "LogInfo.h"
#include<iostream>
#include<string>
struct route_info {
in_addr dstAddr;
in_addr srcAddr;
in_addr gateWay;
char ifName[IF_NAMESIZE];
};
int readNlSock(int sockFd, char *bufPtr, unsigned int seqNum, int pId) {
struct nlmsghdr *nlHdr;
int readLen = 0, msgLen = 0;
do {
if ((readLen = recv(sockFd, bufPtr, BUFSIZE - msgLen, 0)) < 0) {
perror("SOCK READ: ");
return -1;
}
nlHdr = (struct nlmsghdr *)bufPtr;
if ((NLMSG_OK(nlHdr, readLen) == 0) || (nlHdr->nlmsg_type == NLMSG_ERROR)) {
perror("Error in received packet");
return -1;
}
if (nlHdr->nlmsg_type == NLMSG_DONE)
break;
bufPtr += readLen;
msgLen += readLen;
if ((nlHdr->nlmsg_flags & NLM_F_MULTI) == 0)
break;
} while ((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != (unsigned)pId));
return msgLen;
}
void parseRoutes(struct nlmsghdr *nlHdr, struct route_info *rtInfo) {
struct rtmsg *rtMsg = (struct rtmsg *)NLMSG_DATA(nlHdr);
if ((rtMsg->rtm_family != AF_INET) || (rtMsg->rtm_table != RT_TABLE_MAIN))
return;
struct rtattr *rtAttr = (struct rtattr *)RTM_RTA(rtMsg);
int rtLen = RTM_PAYLOAD(nlHdr);
for (; RTA_OK(rtAttr, rtLen); rtAttr = RTA_NEXT(rtAttr, rtLen)) {
switch (rtAttr->rta_type) {
case RTA_OIF:
if_indextoname(*(int *)RTA_DATA(rtAttr), rtInfo->ifName);
break;
case RTA_GATEWAY:
rtInfo->gateWay = *(in_addr *)RTA_DATA(rtAttr);
break;
case RTA_PREFSRC:
rtInfo->srcAddr = *(in_addr *)RTA_DATA(rtAttr);
break;
case RTA_DST:
rtInfo->dstAddr = *(in_addr *)RTA_DATA(rtAttr);
break;
}
}
}
#endif
class NetworkHelper {
public:
static QString DefaultGateway() {
QString ret;
#ifdef Q_OS_WIN
CoInitialize(NULL);
if (CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0) != S_OK)
return ret;
IWbemLocator *pLoc = NULL;
if (CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown, (void **)&pLoc) != S_OK)
return ret;
IWbemServices *pSvc = NULL;
if (pLoc->ConnectServer(L"root\\cimv2", NULL, NULL, NULL, 0, NULL, NULL, &pSvc) != S_OK)
return ret;
IEnumWbemClassObject *pEnumerator = NULL;
HRESULT hr = pSvc->ExecQuery(L"WQL", L"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'", WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
if (FAILED(hr)) {
pSvc->Release();
pLoc->Release();
CoUninitialize();
return ret;
}
IWbemClassObject *pclsObj = NULL;
while (pEnumerator && ret.isEmpty()) {
_variant_t vaDefaultIPGateway;
ULONG uReturn;
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
if (!uReturn)
break;
hr = pclsObj->Get(L"DefaultIPGateway", 0, &vaDefaultIPGateway, NULL, NULL);
if (hr == WBEM_S_NO_ERROR && vaDefaultIPGateway.vt != VT_NULL) {
LONG lLow = 0;
LONG lUp = 0;
::SafeArrayGetLBound(vaDefaultIPGateway.parray, 1, &lLow);
::SafeArrayGetUBound(vaDefaultIPGateway.parray, 1, &lUp);
for (LONG i = lLow; i <= lUp; i++) {
BSTR bsDefaultIPGateway;
if (::SafeArrayGetElement(vaDefaultIPGateway.parray, &i, &bsDefaultIPGateway) == S_OK) {
ret = QString::fromUtf16(reinterpret_cast<const ushort *>(bsDefaultIPGateway));
::SysFreeString(bsDefaultIPGateway);
break;
}
}
}
VariantClear(&vaDefaultIPGateway);
}
if (pclsObj)
pclsObj->Release();
if (pEnumerator)
pEnumerator->Release();
if (pSvc)
pSvc->Release();
if (pLoc)
pLoc->Release();
CoUninitialize();
#else
int sock, msgSeq = 0;
if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) {
perror("Socket Creation: ");
return ret;
}
char msgBuf[BUFSIZE];
memset(msgBuf, 0, BUFSIZE);
struct nlmsghdr *nlMsg = (struct nlmsghdr *)msgBuf;
nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
nlMsg->nlmsg_type = RTM_GETROUTE;
nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
nlMsg->nlmsg_seq = msgSeq++;
nlMsg->nlmsg_pid = getpid();
if (send(sock, nlMsg, nlMsg->nlmsg_len, 0) < 0)
return ret;
int len;
if ((len = readNlSock(sock, msgBuf, msgSeq, getpid())) < 0)
return ret;
struct route_info *rtInfo = (struct route_info *)malloc(sizeof(struct route_info));
for (; NLMSG_OK(nlMsg, len); nlMsg = NLMSG_NEXT(nlMsg, len)) {
memset(rtInfo, 0, sizeof(struct route_info));
parseRoutes(nlMsg, rtInfo);
if (strstr((char *)inet_ntoa(rtInfo->dstAddr), "0.0.0.0") && !strstr((char *)inet_ntoa(rtInfo->gateWay), "0.0.0.0")) {
char buf[64];
inet_ntop(AF_INET, &rtInfo->gateWay, buf, sizeof(buf));
ret = QString(buf);
break;
}
}
free(rtInfo);
close(sock);
#endif
return ret;
}
};
NetworkManager::NetworkManager(QWidget *parent) :
QWidget(parent),
ui(new Ui::NetworkManager)
{
ui->setupUi(this);
Json_ip_init_done =false;
net_data = new PrintNet();
connect(net_data,SIGNAL(json_server_error()),this,SLOT(onjson_server_error()));
connect(net_data,SIGNAL(receiveJSONDatafinish()),this,SLOT(onfinish_get_json()));
connect(net_data,SIGNAL(showMessege()),this,SLOT(ShowNet_dataMessege()));
QRegExp regExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
QRegExpValidator *pValidator = new QRegExpValidator(regExp, this);
// ui->lineEditLanGW->setValidator(new QRegExpValidator(pValidator));
// ui->lineEditLanGW->setInputMask("000.000.000.000;");
ui->spinBoxLanIP3->setDisabled(true);
ui->spinBoxLanIP2->setDisabled(true);
ui->spinBoxLanIP1->setDisabled(true);
ui->spinBoxLanIP0->setDisabled(true);
ui->spinBoxLanMask3->setDisabled(true);
ui->spinBoxLanMask2->setDisabled(true);
ui->spinBoxLanMask1->setDisabled(true);
ui->spinBoxLanMask0->setDisabled(true);
// ui->lineEditLanGW->setDisabled(true);
ui->spinBoxLanGW3->setDisabled(true);
ui->spinBoxLanGW2->setDisabled(true);
ui->spinBoxLanGW1->setDisabled(true);
ui->spinBoxLanGW0->setDisabled(true);
ui->pushButtonSetCancel->setDisabled(true);
connect(ui->networkSelect, SIGNAL(activated(const QString&)), this,
SLOT(selectNetwork(const QString&)));
ctrl_iface = NULL;
ctrl_conn = NULL;
monitor_conn = NULL;
msgNotifier = NULL;
ctrl_iface_dir = strdup("/var/run/wpa_supplicant");
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), SLOT(ping()));
timer->setSingleShot(false);
timer->start(3000);
Json_timer = new QTimer(this);
connect(Json_timer, SIGNAL(timeout()), SLOT(onjson_timer_handler()));
Json_timer->stop();
Jsom_timer_stop =true;
// Json_timer->start(1000);
wlanStartUpFailed = false;
if (openCtrlConnection(ctrl_iface) < 0) {
qDebug()<<"Failed to open control connection to "
"wpa_supplicant.";
wlanStartUpFailed = true;
}
if(wlanStartUpFailed)
return;
updateStatus();
networkMayHaveChanged = true;
updateNetworks();
updateSysStatusToUI();
}
NetworkManager::~NetworkManager()
{
delete ui;
//delete processNetwork;
}
void NetworkManager::onfinish_get_json()
{
net_data->getJson_data(&sysPara->Get_JSON_DATA);
if(Jsom_timer_stop == true){
Json_timer->start(1000);
Jsom_timer_stop = false;
}
ui->messege_info_label->setText( net_data->getMessege() );
emit updateJSONData();
}
void NetworkManager::ShowNet_dataMessege()
{
ui->messege_info_label->setText( net_data->getMessege());
}
void NetworkManager::bindSysPara(SysPara *sysPara){
this->sysPara = sysPara;
const QString cip=getCurrentNetworkIP();
qDebug()<<LANINTERFACE_NAME<<"当前IP地址是:"<<cip;
if(cip.startsWith("0"))//0.0.0.0
{
qDebug()<<"1秒后设置静态IP";
QTimer::singleShot(1000,this,SLOT(setEth0StaticIP_Thread()));
}
}
void NetworkManager::updateSysStatusToUI()
{
if(sysPara){
if(!Json_ip_init_done){
Json_ip_init_done = true;
ui->deviceID_lineEdit->setText(QString(sysPara->para.Json_device_code));
QString ip_str;
ip_str = QString::number(sysPara->para.Json_IP[0]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[1]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[2]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[3]);
ui->SeverIP_lineEdit->setText(ip_str);
ui->server_port_lineEdit->setText(QString::number(sysPara->para.Json_server_port));
}
ui->checkBoxRemoveCode->setCheckState(sysPara->para.isRemoveCode ? Qt::Checked : Qt::Unchecked);
ui->checkBoxRemoveDigitCode->setCheckState(sysPara->para.isRemoveDigitCode ? Qt::Checked : Qt::Unchecked);
ui->radioButtonGetDataEnable->setChecked(sysPara->para.isEnableGetDataButton);
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); //QNetworkInterface::interfaceFromName(LANINTERFACE_NAME);
//获取所有网络接口的列表
foreach(QNetworkInterface interface,list)
{
if(QString::compare(interface.name(), LANINTERFACE_NAME)==0)
{
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
//获取IP地址条目列表,每个条目中包含一个IP地址,一个子网掩码和一个广播地址
foreach(QNetworkAddressEntry entry,entryList)
{
QStringList lanIpList = entry.ip().toString().split(".");
if (lanIpList.size() == 4) {
ui->spinBoxLanIP3->setValue(lanIpList.at(0).toInt());
ui->spinBoxLanIP2->setValue(lanIpList.at(1).toInt());
ui->spinBoxLanIP1->setValue(lanIpList.at(2).toInt());
ui->spinBoxLanIP0->setValue(lanIpList.at(3).toInt());
}
else if (lanIpList.size() == 0) {
ui->spinBoxLanIP3->setValue(0);
ui->spinBoxLanIP2->setValue(0);
ui->spinBoxLanIP1->setValue(0);
ui->spinBoxLanIP0->setValue(0);
}
QStringList lanMaskList = entry.netmask().toString().split(".");
if (lanMaskList.size() == 4) {
ui->spinBoxLanMask3->setValue(lanMaskList.at(0).toInt());
ui->spinBoxLanMask2->setValue(lanMaskList.at(1).toInt());
ui->spinBoxLanMask1->setValue(lanMaskList.at(2).toInt());
ui->spinBoxLanMask0->setValue(lanMaskList.at(3).toInt());
}
else if (lanMaskList.size() == 0) {
ui->spinBoxLanMask3->setValue(0);
ui->spinBoxLanMask2->setValue(0);
ui->spinBoxLanMask1->setValue(0);
ui->spinBoxLanMask0->setValue(0);
}
//ui->lineEditLanGW->setText(entry.netmask().toString());
QString GatewayAddr = NetworkHelper::DefaultGateway();
//ui->lineEditLanGW->setText(GatewayAddr);
QStringList lanGWList = GatewayAddr.split(".");
if (lanGWList.size() == 4) {
ui->spinBoxLanGW3->setValue(lanGWList.at(0).toInt());
ui->spinBoxLanGW2->setValue(lanGWList.at(1).toInt());
ui->spinBoxLanGW1->setValue(lanGWList.at(2).toInt());
ui->spinBoxLanGW0->setValue(lanGWList.at(3).toInt());
}
else if (lanGWList.size() == 0) {
ui->spinBoxLanGW3->setValue(0);
ui->spinBoxLanGW2->setValue(0);
ui->spinBoxLanGW1->setValue(0);
ui->spinBoxLanGW0->setValue(0);
}
return;
}
}
}
//ui->radioButtonGetDataEnable->setChecked(ui->radioButtonGetDataEnable ? true: false);
}
}
#define INTERFACE_OTHERS "# The loopback interface \n\
auto lo \n\
iface lo inet loopback \n\
\n \
# Wireless interfaces \n\
auto wlan0 \n\
iface wlan0 inet dhcp \n\
wireless_mode managed \n\
wireless_essid any \n\
wpa-driver wext \n\
wpa-conf /etc/wpa_supplicant.conf\n"
void NetworkManager::applyLanUIPara(void)
{
if(sysPara){
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); //QNetworkInterface::interfaceFromName(LANINTERFACE_NAME);
//获取所有网络接口的列表
foreach(QNetworkInterface interface,list) {
if(QString::compare(interface.name(), LANINTERFACE_NAME)==0)
{
uint8_t ip3 = ui->spinBoxLanIP3->value();
uint8_t ip2 = ui->spinBoxLanIP2->value();
uint8_t ip1 = ui->spinBoxLanIP1->value();
uint8_t ip0 = ui->spinBoxLanIP0->value();
uint8_t lanMask3 = ui->spinBoxLanMask3->value();
uint8_t lanMask2 = ui->spinBoxLanMask2->value();
uint8_t lanMask1 = ui->spinBoxLanMask1->value();
uint8_t lanMask0 = ui->spinBoxLanMask0->value();
uint8_t lanGW0 = ui->spinBoxLanGW0->value();
QString ipAddrStr(QString("%1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(ip0));
QString netMaskStr(QString("%1.%2.%3.%4").arg(lanMask3).arg(lanMask2).arg(lanMask1).arg(lanMask0));
// QHostAddress ipAddr(ipAddrStr);
// QHostAddress netMask(netMaskStr);
qDebug() << "set ip:"<<ipAddrStr;
// entry.setIp(ipAddr);
// entry.setNetmask(netMask);
//process->start("ifconfig", QStringList() << LANINTERFACE_NAME << "192.168.1.100");
//startDetached(const QString &program, const QStringList &arguments, const QString &workingDirectory,
// qint64 *pid = 0)
QStringList argrList;
if (!(ip3|ip2|ip1|ip0)) {
// 动态IP
//qDebug() << "set dhcp";
QProcess dhcpProcess;
dhcpProcess.startDetached("/bin/cp /etc/network/interfaces_dhcp /etc/network/interfaces", argrList);
argrList<< LANINTERFACE_NAME << ipAddrStr;
}
else {
// 静态IP
QFile netInterface("/etc/network/interfaces");
netInterface.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate);
if (netInterface.isOpen()) {
QTextStream stream(&netInterface);
stream.seek(0);
stream << INTERFACE_OTHERS;
stream << " " <<"\n";
stream << "# eth0 interfaces" <<"\n";
stream << "auto eth0" <<"\n";
stream << "iface eth0 inet static" <<"\n";
stream << QString("address %1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(ip0) <<"\n";
stream << QString("gateway %1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(lanGW0) <<"\n";
stream << QString("netmask %1.%2.%3.%4").arg(lanMask3).arg(lanMask2).arg(lanMask1).arg(lanMask0) <<"\n";
stream << " \n";
netInterface.close();
}
argrList<< LANINTERFACE_NAME << ipAddrStr << "netmask" << netMaskStr;
system("sudo systemctl restart networking");
}
return;
}
}
}
}
qint32 NetworkManager::isIpv4Address(QString ip)
{
QRegExp regExp("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
if( !regExp.exactMatch(ip) )
{
return false;
}
return true;
}
void NetworkManager::on_pushButtonSetIP_clicked(bool checked)
{
if(sysPara){
if(sysPara->status.bLanConfigManual)
{
applyLanUIPara();
ui->pushButtonSetIP->setText(QObject::tr("手动设定"));
ui->spinBoxLanIP3->setDisabled(true);
ui->spinBoxLanIP2->setDisabled(true);
ui->spinBoxLanIP1->setDisabled(true);
ui->spinBoxLanIP0->setDisabled(true);
ui->spinBoxLanMask3->setDisabled(true);
ui->spinBoxLanMask2->setDisabled(true);
ui->spinBoxLanMask1->setDisabled(true);
ui->spinBoxLanMask0->setDisabled(true);
ui->spinBoxLanGW0->setDisabled(true);
ui->pushButtonSetCancel->setDisabled(true);
sysPara->status.bLanConfigManual = false;
}
else
{
sysPara->status.bLanConfigManual = true;
ui->spinBoxLanIP3->setDisabled(false);
ui->spinBoxLanIP2->setDisabled(false);
ui->spinBoxLanIP1->setDisabled(false);
ui->spinBoxLanIP0->setDisabled(false);
ui->spinBoxLanMask3->setDisabled(false);
ui->spinBoxLanMask2->setDisabled(false);
ui->spinBoxLanMask1->setDisabled(false);
ui->spinBoxLanMask0->setDisabled(false);
ui->spinBoxLanGW0->setDisabled(false);
ui->pushButtonSetIP->setText(QObject::tr("应用"));
ui->pushButtonSetCancel->setDisabled(false);
}
}
}
void NetworkManager::on_pushButtonSetCancel_clicked(bool checked)
{
if(sysPara){
if(sysPara->status.bLanConfigManual)
{
sysPara->status.bLanConfigManual = false;
ui->spinBoxLanIP3->setDisabled(true);
ui->spinBoxLanIP2->setDisabled(true);
ui->spinBoxLanIP1->setDisabled(true);
ui->spinBoxLanIP0->setDisabled(true);
ui->spinBoxLanMask3->setDisabled(true);
ui->spinBoxLanMask2->setDisabled(true);
ui->spinBoxLanMask1->setDisabled(true);
ui->spinBoxLanMask0->setDisabled(true);
ui->pushButtonSetCancel->setDisabled(true);
ui->pushButtonSetIP->setText(QObject::tr("手动设定"));
}
}
}
int NetworkManager::openCtrlConnection(const char *ifname)
{
char *cfile;
int flen;
// char buf[2048], *pos, *pos2;
// size_t len;
if (ifname) {
if (ifname != ctrl_iface) {
free(ctrl_iface);
ctrl_iface = strdup(ifname);
}
} else {
#ifdef CONFIG_CTRL_IFACE_UDP
free(ctrl_iface);
ctrl_iface = strdup("udp");
#endif /* CONFIG_CTRL_IFACE_UDP */
#ifdef CONFIG_CTRL_IFACE_UNIX
struct dirent *dent;
DIR *dir = opendir(ctrl_iface_dir);
free(ctrl_iface);
ctrl_iface = NULL;
if (dir) {
while ((dent = readdir(dir))) {
#ifdef _DIRENT_HAVE_D_TYPE
/* Skip the file if it is not a socket.
* Also accept DT_UNKNOWN (0) in case
* the C library or underlying file
* system does not support d_type. */
if (dent->d_type != DT_SOCK &&
dent->d_type != DT_UNKNOWN)
continue;
#endif /* _DIRENT_HAVE_D_TYPE */
if (strcmp(dent->d_name, ".") == 0 ||
strcmp(dent->d_name, "..") == 0)
continue;
printf("Selected interface '%s'\n",
dent->d_name);
ctrl_iface = strdup(dent->d_name);
break;
}
closedir(dir);
}
#endif /* CONFIG_CTRL_IFACE_UNIX */
#ifdef CONFIG_CTRL_IFACE_NAMED_PIPE
struct wpa_ctrl *ctrl;
int ret;
free(ctrl_iface);
ctrl_iface = NULL;
ctrl = wpa_ctrl_open(NULL);
if (ctrl) {
len = sizeof(buf) - 1;
ret = wpa_ctrl_request(ctrl, "INTERFACES", 10, buf,
&len, NULL);
if (ret >= 0) {
connectedToService = true;
buf[len] = '\0';
pos = strchr(buf, '\n');
if (pos)
*pos = '\0';
ctrl_iface = strdup(buf);
}
wpa_ctrl_close(ctrl);
}
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
}
if (ctrl_iface == NULL) {
#ifdef CONFIG_NATIVE_WINDOWS
static bool first = true;
if (first && !serviceRunning()) {
first = false;
if (QMessageBox::warning(
this, qAppName(),
tr("wpa_supplicant service is not "
"running.\n"
"Do you want to start it?"),
QMessageBox::Yes | QMessageBox::No) ==
QMessageBox::Yes)
startService();
}
#endif /* CONFIG_NATIVE_WINDOWS */
return -1;
}
#ifdef CONFIG_CTRL_IFACE_UNIX
flen = strlen(ctrl_iface_dir) + strlen(ctrl_iface) + 2;
cfile = (char *) malloc(flen);
if (cfile == NULL)
return -1;
snprintf(cfile, flen, "%s/%s", ctrl_iface_dir, ctrl_iface);
#else /* CONFIG_CTRL_IFACE_UNIX */
flen = strlen(ctrl_iface) + 1;
cfile = (char *) malloc(flen);
if (cfile == NULL)
return -1;
snprintf(cfile, flen, "%s", ctrl_iface);
#endif /* CONFIG_CTRL_IFACE_UNIX */
if (ctrl_conn) {
wpa_ctrl_close(ctrl_conn);
ctrl_conn = NULL;
}
if (monitor_conn) {
delete msgNotifier;
msgNotifier = NULL;
wpa_ctrl_detach(monitor_conn);
wpa_ctrl_close(monitor_conn);
monitor_conn = NULL;
}
printf("Trying to connect to '%s'\n", cfile);
ctrl_conn = wpa_ctrl_open(cfile);
if (ctrl_conn == NULL) {
free(cfile);
return -1;
}
monitor_conn = wpa_ctrl_open(cfile);
free(cfile);
if (monitor_conn == NULL) {
wpa_ctrl_close(ctrl_conn);
return -1;
}
if (wpa_ctrl_attach(monitor_conn)) {
printf("Failed to attach to wpa_supplicant\n");
wpa_ctrl_close(monitor_conn);
monitor_conn = NULL;
wpa_ctrl_close(ctrl_conn);
ctrl_conn = NULL;
return -1;
}
#if defined(CONFIG_CTRL_IFACE_UNIX) || defined(CONFIG_CTRL_IFACE_UDP)
msgNotifier = new QSocketNotifier(wpa_ctrl_get_fd(monitor_conn),
QSocketNotifier::Read, this);
connect(msgNotifier, SIGNAL(activated(int)), SLOT(receiveMsgs()));
#endif
printf("network out to '%s'\n", cfile);
return 0;
}
int NetworkManager::ctrlRequest(const char *cmd, char *buf, size_t *buflen)
{
int ret;
if (ctrl_conn == NULL)
return -3;
ret = wpa_ctrl_request(ctrl_conn, cmd, strlen(cmd), buf, buflen, NULL);
if (ret == -2)
printf("'%s' command timed out.\n", cmd);
else if (ret < 0)
printf("'%s' command failed.\n", cmd);
return ret;
}
QString NetworkManager::wpaStateTranslate(char *state)
{
if (!strcmp(state, "DISCONNECTED"))
{
//QProcess process;
//process.startDetached("killall udhcpc");
return tr("Disconnected");
}
else if (!strcmp(state, "INACTIVE"))
return tr("Inactive");
else if (!strcmp(state, "SCANNING"))
return tr("Scanning");
else if (!strcmp(state, "AUTHENTICATING"))
return tr("Authenticating");
else if (!strcmp(state, "ASSOCIATING"))
return tr("Associating");
else if (!strcmp(state, "ASSOCIATED"))
return tr("Associated");
else if (!strcmp(state, "4WAY_HANDSHAKE"))
return tr("4-Way Handshake");
else if (!strcmp(state, "GROUP_HANDSHAKE"))
return tr("Group Handshake");
else if (!strcmp(state, "COMPLETED"))
{
QProcess process;
process.startDetached("/home/plg/checkUdhcpcRun.sh");
return tr("Completed");
}
else
return tr("Unknown");
}
void NetworkManager::updateStatus()
{
char buf[2048], *start, *end, *pos;
size_t len;
pingsToStatusUpdate = 10;
len = sizeof(buf) - 1;
if (ctrl_conn == NULL || ctrlRequest("STATUS", buf, &len) < 0) {
ui->textStatus->setText(tr("Could not get status from "
"wpa_supplicant"));
//ui->textAuthentication->clear();
//ui->textEncryption->clear();
ui->textSSID->clear();
//ui->textBssid->clear();
ui->textIPAdrr->clear();
return;
}
buf[len] = '\0';
bool auth_updated = false, ssid_updated = false;
bool bssid_updated = false, ipaddr_updated = false;
bool status_updated = false;
char *pairwise_cipher = NULL, *group_cipher = NULL;
char *mode = NULL;
start = buf;
while (*start) {
bool last = false;
end = strchr(start, '\n');
if (end == NULL) {
last = true;
end = start;
while (end[0] && end[1])
end++;
}
*end = '\0';
pos = strchr(start, '=');
if (pos) {
*pos++ = '\0';
if (strcmp(start, "bssid") == 0) {
bssid_updated = true;
//textBssid->setText(pos);
} else if (strcmp(start, "ssid") == 0) {
ssid_updated = true;
ui->textSSID->setText(pos);
} else if (strcmp(start, "ip_address") == 0) {
ipaddr_updated = true;
ui->textIPAdrr->setText(pos);
} else if (strcmp(start, "wpa_state") == 0) {
status_updated = true;
ui->textStatus->setText(wpaStateTranslate(pos));
} else if (strcmp(start, "key_mgmt") == 0) {
auth_updated = true;
//textAuthentication->setText(pos);
/* TODO: could add EAP status to this */
} else if (strcmp(start, "pairwise_cipher") == 0) {
pairwise_cipher = pos;
} else if (strcmp(start, "group_cipher") == 0) {
group_cipher = pos;
} else if (strcmp(start, "mode") == 0) {
mode = pos;
}
}
if (last)
break;
start = end + 1;
}
if (status_updated && mode)
ui->textStatus->setText(ui->textStatus->text() + " (" + mode + ")");
if (pairwise_cipher || group_cipher) {
QString encr;
if (pairwise_cipher && group_cipher &&
strcmp(pairwise_cipher, group_cipher) != 0) {
encr.append(pairwise_cipher);
encr.append(" + ");
encr.append(group_cipher);
} else if (pairwise_cipher) {
encr.append(pairwise_cipher);
} else {
encr.append(group_cipher);
encr.append(" [group key only]");
}
//textEncryption->setText(encr);
} else
//textEncryption->clear();
;
if (!status_updated)
ui->textStatus->clear();
//if (!auth_updated)
// textAuthentication->clear();
if (!ssid_updated)
ui->textSSID->clear();
//if (!bssid_updated)
// textBssid->clear();
if (!ipaddr_updated)
ui->textIPAdrr->clear();
}
void NetworkManager::updateNetworks()
{
char buf[2048], *start, *end, *id, *ssid, *bssid, *flags;
size_t len;
int first_active = -1;
int was_selected = -1;
bool current = false;
if(wlanStartUpFailed)
return;
if (!networkMayHaveChanged)
return;
//if (networkList->currentRow() >= 0)
// was_selected = networkList->currentRow();
ui->networkSelect->clear();
//ui->scanSSIDSelect->clear();
//networkList->clear();
if (ctrl_conn == NULL)
return;
len = sizeof(buf) - 1;
if (ctrlRequest("LIST_NETWORKS", buf, &len) < 0)
return;
buf[len] = '\0';
start = strchr(buf, '\n');
if (start == NULL)
return;
start++;
while (*start) {
bool last = false;
end = strchr(start, '\n');
if (end == NULL) {
last = true;
end = start;
while (end[0] && end[1])
end++;
}
*end = '\0';
id = start;
ssid = strchr(id, '\t');
if (ssid == NULL)
break;
*ssid++ = '\0';
bssid = strchr(ssid, '\t');
if (bssid == NULL)
break;
*bssid++ = '\0';
flags = strchr(bssid, '\t');
if (flags == NULL)
break;
*flags++ = '\0';
if (strstr(flags, "[DISABLED][P2P-PERSISTENT]")) {
if (last)
break;
start = end + 1;
continue;
}
QString network(id);
network.append(": ");
network.append(ssid);
ui->networkSelect->addItem(network);
//networkList->addItem(network);
//scanSSIDSelect
if (strstr(flags, "[CURRENT]")) {
ui->networkSelect->setCurrentIndex(ui->networkSelect->count() -
1);
current = true;
} else if (first_active < 0 &&
strstr(flags, "[DISABLED]") == NULL)
first_active = ui->networkSelect->count() - 1;
if (last)
break;
start = end + 1;
}
if (ui->networkSelect->count() > 1)
ui->networkSelect->addItem(tr("Select any network"));
if (!current && first_active >= 0)
ui->networkSelect->setCurrentIndex(first_active);
networkMayHaveChanged = false;
}
static int str_match(const char *a, const char *b)
{
return strncmp(a, b, strlen(b)) == 0;
}
void NetworkManager::processMsg(char *msg)
{
char *pos = msg, *pos2;
int priority = 2;
if (*pos == '<') {
/* skip priority */
pos++;
priority = atoi(pos);
pos = strchr(pos, '>');
if (pos)
pos++;
else
pos = msg;
}
WpaMsg wm(pos, priority);
//if (eh)
// eh->addEvent(wm);
//if (peers)
// peers->event_notify(wm);
msgs.append(wm);
while (msgs.count() > 100)
msgs.pop_front();
/* Update last message with truncated version of the event */
if (strncmp(pos, "CTRL-", 5) == 0) {
pos2 = strchr(pos, str_match(pos, WPA_CTRL_REQ) ? ':' : ' ');
if (pos2)
pos2++;
else
pos2 = pos;
} else
pos2 = pos;
QString lastmsg = pos2;
lastmsg.truncate(40);
//textLastMessage->setText(lastmsg);
pingsToStatusUpdate = 0;
networkMayHaveChanged = true;
if (str_match(pos, WPA_CTRL_REQ))
//processCtrlReq(pos + strlen(WPA_CTRL_REQ));
;
else if (str_match(pos, WPA_EVENT_SCAN_RESULTS) && beSentScanCmd)
{
updateResults();
beSentScanCmd = false;
}
else if (str_match(pos, WPA_EVENT_DISCONNECTED))
//showTrayMessage(QSystemTrayIcon::Information, 3,
// tr("Disconnected from network."));
ui->textStatus->setText("Disconnected");
else if (str_match(pos, WPA_EVENT_CONNECTED)) {
//showTrayMessage(QSystemTrayIcon::Information, 3,
//tr("Connection to network established."));
//QTimer::singleShot(5 * 1000, this, SLOT(showTrayStatus()));
//stopWpsRun(true);
ui->textStatus->setText("Connected");
}
}
void NetworkManager::receiveMsgs()
{
char buf[256];
size_t len;
qDebug()<<"receiveMsgs";
while (monitor_conn && wpa_ctrl_pending(monitor_conn) > 0) {
len = sizeof(buf) - 1;
if (wpa_ctrl_recv(monitor_conn, buf, &len) == 0) {
buf[len] = '\0';
processMsg(buf);
}
}
}
void NetworkManager::updateResults()
{
char reply[2048];
size_t reply_len;
int index;
char cmd[20];
//qDebug()<<"updateResults";
//ui->networkSelect->clear();
ui->scanSSIDSelect->clear();
scanResultMap.clear();
index = 0;
while (1)
{
snprintf(cmd, sizeof(cmd), "BSS %d", index++);
if (index > 1000)
break;
reply_len = sizeof(reply) - 1;
if (ctrlRequest(cmd, reply, &reply_len) < 0)
break;
reply[reply_len] = '\0';
QString bss(reply);
if (bss.isEmpty() || bss.startsWith("FAIL"))
break;
QString ssid, bssid, freq, signal, flags;
QStringList lines = bss.split(QRegExp("\\n"));
for (QStringList::Iterator it = lines.begin();
it != lines.end(); it++) {
int pos = (*it).indexOf('=') + 1;
if (pos < 1)
continue;
if ((*it).startsWith("bssid="))
bssid = (*it).mid(pos);
else if ((*it).startsWith("freq="))
freq = (*it).mid(pos);
else if ((*it).startsWith("qual="))
signal = (*it).mid(pos);
else if ((*it).startsWith("flags="))
flags = (*it).mid(pos);
else if ((*it).startsWith("ssid="))
ssid = (*it).mid(pos);
}
ui->scanSSIDSelect->addItem(ssid);
QStringList resultList;
resultList<<ssid <<bssid <<freq <<signal <<flags;
//ScanResultList.append(resultList);
//strcpy(scanResult[index].ssid,ssid);
//strcpy(scanResult[index].bssid,bssid);
//strcpy(scanResult[index].signal,signal);
//strcpy(scanResult[index].flags,flags);
//strcpy(scanResult[index].bssid,bssid);
scanResultMap[ssid] = resultList;
//qDebug()<<"ssid:"<<ssid;
if (bssid.isEmpty())
break;
}
}
QString NetworkManager::processHandle(QString cmd){
QProcess process;
// 确保进程结束时会被清理
process.setProcessChannelMode(QProcess::MergedChannels);
// 启动进程
process.start("/bin/sh", QStringList() << "-c" << cmd);
if (!process.waitForStarted()) {
qDebug() << "Failed to start process";
return QString();
}
// 等待进程完成,设置合理的超时时间(例如30秒)
if (!process.waitForFinished(10000)) {
qDebug() << "Process timed out";
process.terminate(); // 先尝试正常终止
if (!process.waitForFinished(1000)) {
process.kill(); // 强制终止
}
return QString();
}
if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) {
return QString::fromUtf8(process.readAllStandardOutput());
} else {
qDebug() << "Process failed with exit code" << process.exitCode()
<< "and error:" << QString::fromUtf8(process.readAllStandardError());
return QString();
}
}
void NetworkManager::on_pushButtonScan_pressed()
{
/*
char reply[10];
size_t reply_len = sizeof(reply);
if(wlanStartUpFailed)
return;
// if (wpagui == NULL)
// return;
ctrlRequest("SCAN", reply, &reply_len);
beSentScanCmd = true;
*/
// 强制刷新Wi-Fi网络列表
QProcess::execute("sudo", QStringList() << "nmcli" << "dev" << "wifi" << "rescan");
//QMessageBox::information(nullptr, "Wi-Fi", "Wi-Fi网络列表已刷新");
// 列出可用的Wi-Fi网络
QProcess process;
// process.start("nmcli", QStringList() << "dev" << "wifi" << "list");
process.start("nmcli", QStringList() << "-t" << "-f" << "IN-USE,SSID" << "dev" << "wifi" << "list");
process.waitForFinished();
QString output = process.readAllStandardOutput();
// QMessageBox::information(nullptr, "可用的Wi-Fi网络", output);
QStringList lines = output.split('\n');
for (const QString &line : lines) {
QStringList parts = line.split(':');
if (parts.size() == 2) {
QString ssid = parts[1].trimmed();
if (!ssid.isEmpty()) {
ui->scanSSIDSelect->addItem(ssid);
}
}
}
}
void NetworkManager::selectSSID( const QString & sel )
{
//if (openCtrlConnection(sel.toLatin1().constData()) < 0)
// printf("Failed to open control connection to "
// "wpa_supplicant.\n");
//updateStatus();
//updateNetworks();
}
int NetworkManager::setNetworkParam(int id, const char *field,
const char *value, bool quote)
{
char reply[10], cmd[256];
size_t reply_len;
snprintf(cmd, sizeof(cmd), "SET_NETWORK %d %s %s%s%s",
id, field, quote ? "\"" : "", value, quote ? "\"" : "");
reply_len = sizeof(reply);
ctrlRequest(cmd, reply, &reply_len);
return strncmp(reply, "OK", 2) == 0 ? 0 : -1;
}
void NetworkManager::addNetwork()
{
char reply[10], cmd[256];
size_t reply_len;
int id;
int psklen = ui->pskEdit->text().length();
int auth = ui->authSelect->currentIndex();
if (auth == AUTH_WPA_PSK || auth == AUTH_WPA2_PSK) {
if (psklen < 8 || psklen > 64) {
QMessageBox::warning(
this,
tr("WPA Pre-Shared Key Error"),
tr("WPA-PSK requires a passphrase of 8 to 63 "
"characters\n"
"or 64 hex digit PSK"));
ui->pskEdit->setFocus();
return;
}
}
memset(reply, 0, sizeof(reply));
reply_len = sizeof(reply) - 1;
if (1) {
ctrlRequest("ADD_NETWORK", reply, &reply_len);
if (reply[0] == 'F') {
QMessageBox::warning(this, "wpa_gui",
tr("Failed to add "
"network to wpa_supplicant\n"
"configuration."));
return;
}
id = atoi(reply);
} else
id = edit_network_id;
//setNetworkParam(id, "ssid", ssidEdit->text().toLatin1().constData(),
// true);
setNetworkParam(id, "ssid", ui->scanSSIDSelect->currentText().toLatin1().constData(),
true);
const char *key_mgmt = NULL, *proto = NULL, *pairwise = NULL;
switch (auth) {
case AUTH_NONE_OPEN:
case AUTH_NONE_WEP:
case AUTH_NONE_WEP_SHARED:
key_mgmt = "NONE";
break;
case AUTH_IEEE8021X:
key_mgmt = "IEEE8021X";
break;
case AUTH_WPA_PSK:
key_mgmt = "WPA-PSK";
proto = "WPA";
break;
case AUTH_WPA_EAP:
key_mgmt = "WPA-EAP";
proto = "WPA";
break;
case AUTH_WPA2_PSK:
key_mgmt = "WPA-PSK";
proto = "WPA2";
break;
case AUTH_WPA2_EAP:
key_mgmt = "WPA-EAP";
proto = "WPA2";
break;
}
if (auth == AUTH_NONE_WEP_SHARED)
setNetworkParam(id, "auth_alg", "SHARED", false);
else
setNetworkParam(id, "auth_alg", "OPEN", false);
if (auth == AUTH_WPA_PSK || auth == AUTH_WPA_EAP ||
auth == AUTH_WPA2_PSK || auth == AUTH_WPA2_EAP) {
int encr = ui->EncryptionSelect->currentIndex();
if (encr == 0)
pairwise = "TKIP";
else
pairwise = "CCMP";
}
if (proto)
setNetworkParam(id, "proto", proto, false);
if (key_mgmt)
setNetworkParam(id, "key_mgmt", key_mgmt, false);
if (pairwise) {
setNetworkParam(id, "pairwise", pairwise, false);
setNetworkParam(id, "group", "TKIP CCMP WEP104 WEP40", false);
}
if (ui->pskEdit->isEnabled() &&
strcmp(ui->pskEdit->text().toLatin1().constData(),
WPA_GUI_KEY_DATA) != 0)
setNetworkParam(id, "psk",
ui->pskEdit->text().toLatin1().constData(),
psklen != 64);
setNetworkParam(id, "phase2", "NULL", false);
setNetworkParam(id, "identity", "NULL", false);
if (ui->passwordEdit->isEnabled() && ui->passwordEdit->text().length() > 0 &&
strcmp(ui->passwordEdit->text().toLatin1().constData(),
WPA_GUI_KEY_DATA) != 0)
setNetworkParam(id, "password",
ui->passwordEdit->text().toLatin1().constData(),
true);
else if (ui->passwordEdit->text().length() == 0)
setNetworkParam(id, "password", "NULL", false);
setNetworkParam(id, "ca_cert", "NULL", false);
setNetworkParam(id, "id_str", "NULL", false);
snprintf(cmd, sizeof(cmd), "ENABLE_NETWORK %d", id);
reply_len = sizeof(reply);
ctrlRequest(cmd, reply, &reply_len);
if (strncmp(reply, "OK", 2) != 0) {
QMessageBox::warning(this, "wpa_gui",
tr("Failed to enable "
"network in wpa_supplicant\n"
"configuration."));
/* Network was added, so continue anyway */
}
triggerUpdate();
ctrlRequest("SAVE_CONFIG", reply, &reply_len);
//close();
}
void NetworkManager::authChanged(int sel)
{
ui->EncryptionSelect->setEnabled(sel != AUTH_NONE_OPEN && sel != AUTH_NONE_WEP &&
sel != AUTH_NONE_WEP_SHARED);
ui->pskEdit->setEnabled(sel == AUTH_WPA_PSK || sel == AUTH_WPA2_PSK);
bool eap = sel == AUTH_IEEE8021X || sel == AUTH_WPA_EAP ||
sel == AUTH_WPA2_EAP;
//eapSelect->setEnabled(eap);
//identityEdit->setEnabled(eap);
ui->passwordEdit->setEnabled(eap);
//cacertEdit->setEnabled(eap);
//phase2Select->setEnabled(eap);
//if (eap)
// eapChanged(eapSelect->currentIndex());
while (ui->EncryptionSelect->count())
ui->EncryptionSelect->removeItem(0);
if (sel == AUTH_NONE_OPEN || sel == AUTH_NONE_WEP ||
sel == AUTH_NONE_WEP_SHARED || sel == AUTH_IEEE8021X) {
ui->EncryptionSelect->addItem("None");
ui->EncryptionSelect->addItem("WEP");
ui->EncryptionSelect->setCurrentIndex(sel == AUTH_NONE_OPEN ? 0 : 1);
} else {
ui->EncryptionSelect->addItem("TKIP");
ui->EncryptionSelect->addItem("CCMP");
ui->EncryptionSelect->setCurrentIndex((sel == AUTH_WPA2_PSK ||
sel == AUTH_WPA2_EAP) ? 1 : 0);
}
//wepEnabled(sel == AUTH_NONE_WEP || sel == AUTH_NONE_WEP_SHARED);
}
void NetworkManager::selectNetwork( const QString & sel )
{
QString cmd(sel);
char reply[10];
size_t reply_len = sizeof(reply);
if (cmd.contains(QRegExp("^\\d+:")))
cmd.truncate(cmd.indexOf(':'));
else
cmd = "any";
cmd.prepend("SELECT_NETWORK ");
ctrlRequest(cmd.toLatin1().constData(), reply, &reply_len);
triggerUpdate();
}
void NetworkManager::triggerUpdate()
{
updateStatus();
networkMayHaveChanged = true;
updateNetworks();
}
void NetworkManager::ping()
{
char buf[10];
size_t len;
if(wlanStartUpFailed)
return;
len = sizeof(buf) - 1;
if (ctrlRequest("PING", buf, &len) < 0) {
qDebug()<<"PING failed - trying to reconnect";
if (openCtrlConnection(ctrl_iface) >= 0) {
qDebug()<<"Reconnected successfully";
pingsToStatusUpdate = 0;
}
}
pingsToStatusUpdate--;
if (pingsToStatusUpdate <= 0) {
updateStatus();
updateNetworks();
}
#ifndef CONFIG_CTRL_IFACE_NAMED_PIPE
/* Use less frequent pings and status updates when the main window is
* hidden (running in taskbar). */
int interval = isHidden() ? 20000 : 3000;
if (timer->interval() != interval)
timer->setInterval(interval);
#endif /* CONFIG_CTRL_IFACE_NAMED_PIPE */
}
void NetworkManager::on_pushButtonConnect_pressed()
{
on_pushButtonDisconnect_pressed();
char reply[10];
size_t reply_len = sizeof(reply);
ctrlRequest("REASSOCIATE", reply, &reply_len);
}
void NetworkManager::on_pushButtonDisconnect_pressed()
{
char reply[10];
size_t reply_len = sizeof(reply);
ctrlRequest("DISCONNECT", reply, &reply_len);
}
void NetworkManager::on_scanSSIDSelect_activated(const QString &arg1)
{
//if (openCtrlConnection(sel.toLatin1().constData()) < 0)
// printf("Failed to open control connection to "
// "wpa_supplicant.\n");
updateStatus();
updateNetworks();
QStringList networkString=scanResultMap[arg1];
if(networkString.isEmpty())
{
return;
}
// QString flags = sel->text(4);
QString flags = networkString.at(4);
int auth, encr = 0;
if (flags.indexOf("[WPA2-EAP") >= 0)
auth = AUTH_WPA2_EAP;
else if (flags.indexOf("[WPA-EAP") >= 0)
auth = AUTH_WPA_EAP;
else if (flags.indexOf("[WPA2-PSK") >= 0)
auth = AUTH_WPA2_PSK;
else if (flags.indexOf("[WPA-PSK") >= 0)
auth = AUTH_WPA_PSK;
else
auth = AUTH_NONE_OPEN;
if (flags.indexOf("-CCMP") >= 0)
encr = 1;
else if (flags.indexOf("-TKIP") >= 0)
encr = 0;
else if (flags.indexOf("WEP") >= 0) {
encr = 1;
if (auth == AUTH_NONE_OPEN)
auth = AUTH_NONE_WEP;
} else
encr = 0;
ui->authSelect->setCurrentIndex(auth);
authChanged(auth);
ui->EncryptionSelect->setCurrentIndex(encr);
//wepEnabled(auth == AUTH_NONE_WEP);
//getEapCapa();
//if (flags.indexOf("[WPS") >= 0)
// useWpsButton->setEnabled(true);
//bssid = sel.text(1);
}
void NetworkManager::on_pushButtonAddNetworkd_pressed()
{
// addNetwork();
// 连接到指定的Wi-Fi网络
QString ssid = ui->scanSSIDSelect->currentText(); //Wi-Fi网络名称
QString password = ui->passwordEdit->text(); //Wi-Fi密码
QProcess::execute("sudo", QStringList() << "nmcli" << "dev" << "wifi" << "connect" << ssid << "password" << password);
// QMessageBox::information(nullptr, "Wi-Fi", "正在尝试连接到 " + ssid);
// 查询网络接口状态
QProcess process;
process.start("ifconfig", QStringList() << "wlan0");
process.waitForFinished();
QString output = process.readAllStandardOutput();
// QMessageBox::information(nullptr, "网络接口状态", output);
// 判断是否连接成功
if (isWifiConnected(output)) {
QMessageBox::information(nullptr, "Wi-Fi", "成功连接到 " + ssid);
} else {
QMessageBox::information(nullptr, "Wi-Fi", "连接失败");
}
}
bool NetworkManager::isWifiConnected(const QString &output) {
// 使用正则表达式检查是否有inet地址
QRegularExpression re("inet\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+)");
QRegularExpressionMatch match = re.match(output);
return match.hasMatch();
}
void NetworkManager::removeNetwork()
{
char reply[10], cmd[256];
size_t reply_len;
int id;
if (QMessageBox::information(
this, "wpa_gui",
tr("This will permanently remove the network\n"
"from the configuration. Do you really want\n"
"to remove this network?"),
tr("Yes"), tr("No")) != 0)
return;
id = ui->networkSelect->currentIndex();
snprintf(cmd, sizeof(cmd), "REMOVE_NETWORK %d", id);
reply_len = sizeof(reply);
ctrlRequest(cmd, reply, &reply_len);
if (strncmp(reply, "OK", 2) != 0) {
QMessageBox::warning(this, "wpa_gui",
tr("Failed to remove network from "
"wpa_supplicant\n"
"configuration."));
} else {
triggerUpdate();
ctrlRequest("SAVE_CONFIG", reply, &reply_len);
}
}
void NetworkManager::on_pushButtonRemove_pressed()
{
removeNetwork();
}
void NetworkManager::on_GetJsonpushButton_clicked()
{
QMessageBox::StandardButton ret;
ret = QMessageBox::question(this, tr("提示"),tr("是否去获取数据!"), QMessageBox::Ok | QMessageBox::Cancel);
if(ret != QMessageBox::Ok)
{
return;
}
// qDebug()<<"on_GetJsonpushButton_clicked";
QString str = "http://";
//str += ui->SeverIP_lineEdit->text();
QString ip_str;
ip_str = QString::number(sysPara->para.Json_IP[0]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[1]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[2]);
ip_str += ".";
ip_str += QString::number(sysPara->para.Json_IP[3]);
str += ip_str;
str += ":";
//str += ui->server_port_lineEdit->text();
str +=QString::number(sysPara->para.Json_server_port);
if(ui->TestradioButton->isChecked()){
// qDebug()<<"get test value";
// str += "/KLAPS/APSServer/ECode/GetProductUniqueCodeTest";
str = "http://www.anhuikinglan.top:63025/KLAPS/APSServer/ECode/GetProductUniqueCodeTest";
}else{
str += "/KLAPS/APSServer/ECode/GetProductUniqueCode";
}
//net_data->PrintNetGetData(str, ui->deviceID_lineEdit->text());
net_data->PrintNetGetData(str, QString(sysPara->para.Json_device_code));
ui->messege_info_label->setText(tr("获取数据中..."));
}
void NetworkManager::onjson_timer_handler()
{
static int count_time = 0;
count_time++;
ui->messege_info_label->setText( net_data->getMessege() );
// qDebug()<<"on_json_timer_handler";
if(sysPara->para.totalProductCnt != 0 && sysPara->para.totalProductCnt >= sysPara->Get_JSON_DATA.ProductPlanQty){
QString str = "http://";
str += ui->SeverIP_lineEdit->text();
str += ":";
str += ui->server_port_lineEdit->text();
if(ui->TestradioButton->isChecked()){
str += "/KLAPS/APSServer/ECode/UsedProductUniqueCodeTest";
}else{
str += "/KLAPS/APSServer/ECode/UsedProductUniqueCode";
}
net_data->PrintNetPostFinish(str);
sysPara->devOp->clearProductCnt(1 | 0x10 );// [3]总产品计数器清零FPGA
sysPara->para.totalProductCnt = 0;
emit net_stopPrint();
ui->messege_info_label->setText(tr("上报数据中..."));
if(sysPara->Get_JSON_DATA.TaskSwitchingMode == 1){
on_GetJsonpushButton_clicked();
}
}
if(count_time == 20){
count_time = 0;
QString str = "http://";
str += ui->SeverIP_lineEdit->text();
str += ":";
str += ui->server_port_lineEdit->text();
if(ui->TestradioButton->isChecked()){
str += "/KLAPS/APSServer/ECode/SubmitEquipmentCurrentStateTest";
}else{
str += "/KLAPS/APSServer/ECode/SubmitEquipmentCurrentState";
}
net_data->PrintNetPostFinish(str);
// qDebug()<<"upload data";
ui->messege_info_label->setText(tr("上报数据中..."));
}
}
void NetworkManager::onjson_server_error()
{
// ui->net_state_label->setText(tr("通信失败"));
// qDebug()<<"on_json_server_error";
}
void NetworkManager::on_applicate_pushButton_clicked()
{
QString ip_str = ui->SeverIP_lineEdit->text();
QStringList ip_list = ip_str.split(".");
QString ip1,ip2,ip3,ip4;
if (ip_list.size() < 4){
QMessageBox::information(this,tr("提示"),tr("IP设置错误!"));
return;
}
ip1 = ip_list.at(0);
ip2 = ip_list.at(1);
ip3 = ip_list.at(2);
ip4 = ip_list.at(3);
sysPara->para.Json_IP[0] = ip1.toInt();
sysPara->para.Json_IP[1] = ip2.toInt();
sysPara->para.Json_IP[2] = ip3.toInt();
sysPara->para.Json_IP[3] = ip4.toInt();
if(sysPara->para.Json_IP[0] > 255 || sysPara->para.Json_IP[1] > 255
||sysPara->para.Json_IP[2] > 255 ||sysPara->para.Json_IP[3] > 255){
QMessageBox::information(this,tr("提示"),tr("IP设置错误!"));
return;
}
// strcpy(sysPara->para.Json_IP, std_str);
//sysPara->para.Json_device_code = ui->deviceID_lineEdit->text().toInt();
strncpy(sysPara->para.Json_device_code, ui->deviceID_lineEdit->text().toStdString().data(),sizeof(sysPara->para.Json_device_code)-1);
sysPara->para.Json_server_port = ui->server_port_lineEdit->text().toInt();
QMessageBox::information(this,tr("提示"),tr("应用成功"));
// qDebug()<<"Json_device_code="<<sysPara->para.Json_device_code
// <<"Json_server_port="<<sysPara->para.Json_server_port
// <<"sysPara->para.Json_IP="<<sysPara->para.Json_IP[0] << sysPara->para.Json_IP[1]
// <<sysPara->para.Json_IP[2]<<sysPara->para.Json_IP[3];
sysPara->saveParaToFile();
}
//void NetworkManager::on_checkBoxShortNet_clicked(bool checked)
//{
// net_data->m_bShortNet = checked;
//}
void NetworkManager::on_checkBoxRemoveDigitCode_clicked(bool checked)
{
sysPara->para.isRemoveDigitCode = checked;
emit OpenNewFile();
}
void NetworkManager::on_checkBoxRemoveCode_clicked(bool checked)
{
//emit VariablePositionChange(checked);
sysPara->para.isRemoveCode = checked;
//emit OpenNewFile();
}
void NetworkManager::on_radioButtonGetDataEnable_clicked(bool checked)
{
sysPara->para.isEnableGetDataButton = checked;
}
void NetworkManager::updateAuthorization(int auth)
{
if(auth & AUTH_SUPER_USER2)
{
ui->GetJsonpushButton->show();
ui->GetJsonpushButton->show();
ui->messege_info_label->show();
ui->label->show();
ui->deviceID_lineEdit->show();
ui->label_2->show();
ui->SeverIP_lineEdit->show();
ui->label_4->show();
ui->server_port_lineEdit->show();
ui->TestradioButton->show();
// ui->checkBoxShortNet->show();
ui->checkBoxRemoveDigitCode->show();
ui->applicate_pushButton->show();
ui->checkBoxRemoveCode->show();
ui->radioButtonGetDataEnable->show();
}
else
{
ui->GetJsonpushButton->hide();
ui->GetJsonpushButton->hide();
ui->messege_info_label->hide();
ui->label->hide();
ui->deviceID_lineEdit->hide();
ui->label_2->hide();
ui->SeverIP_lineEdit->hide();
ui->label_4->hide();
ui->server_port_lineEdit->hide();
ui->TestradioButton->hide();
// ui->checkBoxShortNet->hide();
ui->checkBoxRemoveDigitCode->hide();
ui->applicate_pushButton->hide();
ui->checkBoxRemoveCode->hide();
ui->radioButtonGetDataEnable->hide();
//sysPara->para.isEnableGetDataButton = false;
}
}
bool NetworkManager::setEth0StaticIP()
{
const uint8_t ip3=192,ip2=168,ip1=0,ip0=66;//100+QDateTime::currentDateTime().time().second();//IP
const uint8_t /*ip3=192,ip2=168,ip1=1,ip0=66,*/lanGW0=1;//网关
const uint8_t lanMask3=255,lanMask2=255,lanMask1=255,lanMask0=0;//子网掩码
// 静态IP
QFile netInterface("/etc/network/interfaces");
netInterface.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate);
if (netInterface.isOpen()) {
QTextStream stream(&netInterface);
stream.seek(0);
stream << INTERFACE_OTHERS;
stream << " " <<"\n";
stream << "# eth0 interfaces" <<"\n";
stream << "auto eth0" <<"\n";
stream << "iface eth0 inet static" <<"\n";
stream << QString("address %1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(ip0) <<"\n";
stream << QString("gateway %1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(lanGW0) <<"\n";
stream << QString("netmask %1.%2.%3.%4").arg(lanMask3).arg(lanMask2).arg(lanMask1).arg(lanMask0) <<"\n";
stream << " \n";
netInterface.close();
QStringList argrList;
QString ipAddrStr(QString("%1.%2.%3.%4").arg(ip3).arg(ip2).arg(ip1).arg(ip0));
QString netMaskStr(QString("%1.%2.%3.%4").arg(lanMask3).arg(lanMask2).arg(lanMask1).arg(lanMask0));
argrList<< LANINTERFACE_NAME << ipAddrStr << "netmask" << netMaskStr;
qDebug() << "setEth0StaticIP->set argu:" << argrList;
QProcess process;
process.startDetached("/sbin/ifconfig", argrList);
return true;
}
else
{
const QFile::FileError eno=netInterface.error();
qDebug()<<"打开网络设置文件失败,error="<<eno<<",errstr="<<netInterface.errorString();
}
return false;
}
void NetworkManager::setEth0StaticIP_Thread()
{
if(!sysPara->status.bLanConfigManual && this->setEth0StaticIP())
{
qDebug()<<"设置静态IP-完成";
sysPara->status.bLanConfigManual=true;
updateSysStatusToUI();
}
else
{
qDebug()<<"设置静态IP-失败";
}
}
/**
只有返回全是0的地址才需要设置成192.168.0.66这个固定地址
* @brief NetworkManager::getCurrentNetworkIP
* @return 返回当前机器的IP地址
*/
QString NetworkManager::getCurrentNetworkIP()const
{
QString cip("0.0.0.0");
if(sysPara){
QList<QNetworkInterface> list = QNetworkInterface::allInterfaces(); //QNetworkInterface::interfaceFromName(LANINTERFACE_NAME);
//获取所有网络接口的列表
foreach(QNetworkInterface interface,list)
{
foreach(QNetworkAddressEntry entry,interface.addressEntries())
{
qDebug()<<interface.name()<<interface.hardwareAddress()<<entry.ip().toString()
<<"IsRunning="<<interface.flags().testFlag(QNetworkInterface::IsRunning)
<<"IsLoopBack="<<interface.flags().testFlag(QNetworkInterface::IsLoopBack)
<<"IsPointToPoint="<<interface.flags().testFlag(QNetworkInterface::IsPointToPoint)
<<"isValid="<<interface.isValid()
<<entry.ip().protocol();
auto lanIpList=entry.ip().toString().split(".");
if(!interface.flags().testFlag(QNetworkInterface::IsLoopBack) && QAbstractSocket::NetworkLayerProtocol::IPv4Protocol==entry.ip().protocol())
{
ui->spinBoxLanIP3->setValue(lanIpList.at(0).toInt());
ui->spinBoxLanIP2->setValue(lanIpList.at(1).toInt());
ui->spinBoxLanIP1->setValue(lanIpList.at(2).toInt());
ui->spinBoxLanIP0->setValue(lanIpList.at(3).toInt());
}
}
if(QString::compare(interface.name(), LANINTERFACE_NAME)==0)
{
QList<QNetworkAddressEntry> entryList = interface.addressEntries();
//获取IP地址条目列表,每个条目中包含一个IP地址,一个子网掩码和一个广播地址
foreach(QNetworkAddressEntry entry,entryList)
{
QStringList lanIpList = entry.ip().toString().split(".");
if (lanIpList.size() == 4) {
return QString("%1.%2.%3.%4").arg(lanIpList.at(0)).arg(lanIpList.at(1)).arg(lanIpList.at(2)).arg(lanIpList.at(3));
}
return cip;
}
}
}
}
return cip;
}