12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292 |
- /*
- * Module_Wifi.c
- *
- * Created on: 2020-01-14
- * Author: Jerry Wang
- * Version: D0.01
- */
- #include <sys/time.h>
- #include <sys/timeb.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <sys/ioctl.h>
- #include <sys/socket.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #include <sys/shm.h>
- #include <sys/mman.h>
- #include <linux/wireless.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <unistd.h>
- #include <stdarg.h>
- #include <stdio.h> /*標準輸入輸出定義*/
- #include <stdlib.h> /*標準函數庫定義*/
- #include <unistd.h> /*Unix 標準函數定義*/
- #include <fcntl.h> /*檔控制定義*/
- #include <termios.h> /*PPSIX 終端控制定義*/
- #include <errno.h> /*錯誤號定義*/
- #include <errno.h>
- #include <string.h>
- #include <time.h>
- #include <ctype.h>
- #include <ifaddrs.h>
- //#include "define.h"
- #include "../Projects/define.h"
- #define DEBUG_INFO(format, args...) StoreLogMsg("[%s:%d][%s][Info] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #define DEBUG_WARN(format, args...) StoreLogMsg("[%s:%d][%s][Warn] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #define DEBUG_ERROR(format, args...) StoreLogMsg("[%s:%d][%s][Error] "format, __FILE__, __LINE__, __FUNCTION__, ##args)
- #define Debug
- #define ARRAY_SIZE(A) (sizeof(A) / sizeof(A[0]))
- #define PASS 1
- #define FAIL -1
- #define true 1
- #define false 0
- #define IP_TYPE_DHCP 0
- #define IP_TYPE_STATIC 1
- #define AUTH_TYPE_NONE 0
- #define AUTH_TYPE_WEP 1
- #define AUTH_TYPE_WPAPSK 2
- #define AUTH_TYPE_WPA2PSK 3
- #define WIFI_MODE_DISABLE 0
- #define WIFI_MODE_STA 1
- #define WIFI_MODE_AP 2
- #define WIFI_MODE_ADHOC 3
- #define STA_STATE_INIT 0
- #define STA_STATE_DEVICE_DETECT 1
- #define STA_STATE_AP_CONNECTED 2
- #define STA_STATE_INTERNET_CHECKING 3
- #define AP_STATE_INIT 0
- #define AP_STATE_DEVICE_DETECT 1
- #define AP_STATE_AP_START 2
- #define AP_STATE_SERVER_LISTEN 3
- #define LISTEN_PORT 8856
- #define CONNECTION_LIMIT 1
- #define PROTOCOL_ADDR 0
- #define UBLOX
- //#define MT7601U
- struct interface_info
- {
- int ipType;
- int authType;
- int rssi;
- int cnt_InternetFail;
- char *currentInterface;
- char currentSSID[256];
- char currentPasswd[256];
- char currentMAC[24];
- char currentIPAddr[24];
- char currentNetmask[24];
- char currentGateway[24];
- char staticIPAddr[24];
- }Wifi;
- struct Display_Request
- {
- unsigned char isShowed_IF_info:1;
- unsigned char isShowed_IP_info:1;
- }dispReq;
- struct auth_info
- {
- int auth_type;
- unsigned char ssid[256];
- unsigned char passwd[256];
- }Wifi_A;
- struct SysConfigAndInfo *ShmSysConfigAndInfo;
- struct StatusCodeData *ShmStatusCodeData;
- int isFindInterface();
- int getInterfaceInfo();
- int isReachableInternet();
- int getLinkQuality();
- char* getTimeString(void);
- int setWPAconf();
- int restartWPA();
- void refreshUSB();
- void getParameters();
- int Wifi_module_sts = STA_STATE_INIT;
- int isSetWPA_OK = false;
- int cnt_pingDNS_Fail;
- int cnt_getAP_Fail;
- int cnt_getIP_Fail;
- void trim(char *s);
- int mystrcmp(char *p1,char *p2);
- void substr(char *dest, const char* src, unsigned int start, unsigned int cnt);
- void split(char **arr, char *str, const char *del);
- int isValidCheckSum(uint8_t *message);
- char *Support_InterfaceSTA[2] = {"mlan0", "wlan0"};
- char *Support_InterfaceAP[1] = {"uap0"};
- char *valid_Internet[2] = {"8.8.8.8", "180.76.76.76"};
- int StoreLogMsg(const char *fmt, ...)
- {
- char Buf[4096+256];
- char buffer[4096];
- time_t CurrentTime;
- struct tm *tm;
- va_list args;
- va_start(args, fmt);
- int rc = vsnprintf(buffer, sizeof(buffer), fmt, args);
- va_end(args);
- memset(Buf,0,sizeof(Buf));
- CurrentTime = time(NULL);
- tm=localtime(&CurrentTime);
- sprintf(Buf,"echo \"[%04d.%02d.%02d %02d:%02d:%02d] - %s\" >> /Storage/SystemLog/[%04d.%02d]Wifi_SystemLog",
- tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec,
- buffer,
- tm->tm_year+1900,tm->tm_mon+1);
- #ifdef SystemLogMessage
- system(Buf);
- #endif
- printf("[%04d.%02d.%02d %02d:%02d:%02d] - %s", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec, buffer);
- return rc;
- }
- int DiffTimeb(struct timeb ST, struct timeb ET)
- {
- //return milli-second
- unsigned int StartTime,StopTime;
- StartTime=(unsigned int)ST.time;
- StopTime=(unsigned int)ET.time;
- return (StopTime-StartTime)*1000+ET.millitm-ST.millitm;
- }
- //==========================================
- // Init all share memory
- //==========================================
- int InitShareMemory()
- {
- int result = PASS;
- int MeterSMId;
- //creat ShmSysConfigAndInfo
- if ((MeterSMId = shmget(ShmSysConfigAndInfoKey, sizeof(struct SysConfigAndInfo), 0777)) < 0)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("shmget ShmSysConfigAndInfo NG\n");
- #endif
- result = FAIL;
- }
- else if ((ShmSysConfigAndInfo = shmat(MeterSMId, NULL, 0)) == (void *) -1)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("shmat ShmSysConfigAndInfo NG\n");
- #endif
- result = FAIL;
- }
- else
- {}
- //creat ShmStatusCodeData
- if ((MeterSMId = shmget(ShmStatusCodeKey, sizeof(struct StatusCodeData), 0777)) < 0)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("shmget ShmStatusCodeData NG\n");
- #endif
- result = FAIL;
- }
- else if ((ShmStatusCodeData = shmat(MeterSMId, NULL, 0)) == (void *) -1)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("shmat ShmStatusCodeData NG\n");
- #endif
- result = FAIL;
- }
- else
- {}
- return result;
- }
- //==========================================
- // Get parameters from shared memory
- //==========================================
- void getParameters(void)
- {
- DEBUG_INFO("============= Configuration ===============\r\n");
- strcpy((char*)Wifi_A.ssid, (const char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSsid);
- DEBUG_INFO("Wifi SSID: %s\n", Wifi_A.ssid);
- strcpy((char*)Wifi_A.passwd, (const char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiPassword);
- DEBUG_INFO("Wifi Password: %s\n", Wifi_A.passwd);
- if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiIpAddress != NULL)
- strcpy((char*)Wifi.staticIPAddr, (const char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiIpAddress);
- DEBUG_INFO("Wifi Static IP: %s\n", Wifi.staticIPAddr);
- Wifi.ipType = ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpClient;
- DEBUG_INFO("DHCP client flag: %d\n", Wifi.ipType);
- DEBUG_INFO("===========================================\r\n");
- }
- //==========================================
- // Refresh USB interface
- //==========================================
- void refreshUSB(void)
- {
- FILE *fp;
- char cmd[256];
- // Get IP address & net mask
- strcpy(cmd, "echo '1-1'> /sys/bus/usb/drivers/usb/unbind");
- fp = popen(cmd, "r");
- sleep(2);
- pclose(fp);
- strcpy(cmd, "echo '1-1'> /sys/bus/usb/drivers/usb/bind");
- fp = popen(cmd, "r");
- sleep(5);
- pclose(fp);
- }
- //==========================================
- // Check wifi interface status
- //==========================================
- int isFindInterface()
- {
- int result = FAIL;
- struct ifaddrs *ifaddr, *ifa;
- //refreshUSB();
- if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode == WIFI_MODE_AP)
- {
- if (getifaddrs(&ifaddr) != FAIL)
- {
- for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
- {
- if (ifa->ifa_addr == NULL ||
- ifa->ifa_addr->sa_family != AF_PACKET) continue;
- for(int idx=0;idx<ARRAY_SIZE(Support_InterfaceAP);idx++)
- {
- if(mystrcmp(ifa->ifa_name, Support_InterfaceAP[idx]) == PASS)
- {
- Wifi.currentInterface = ifa->ifa_name;
- result = PASS;
- }
- }
- }
- freeifaddrs(ifaddr);
- freeifaddrs(ifa);
- }
- }
- else
- {
- if (getifaddrs(&ifaddr) != FAIL)
- {
- for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
- {
- if (ifa->ifa_addr == NULL ||
- ifa->ifa_addr->sa_family != AF_PACKET) continue;
- for(int idx=0;idx<ARRAY_SIZE(Support_InterfaceSTA);idx++)
- {
- if(mystrcmp(ifa->ifa_name, Support_InterfaceSTA[idx]) == PASS)
- {
- Wifi.currentInterface = ifa->ifa_name;
- result = PASS;
- }
- }
- }
- freeifaddrs(ifaddr);
- freeifaddrs(ifa);
- }
- }
- return result;
- }
- //==========================================
- // Get wifi interface info
- //==========================================
- int getInterfaceInfo()
- {
- int result = PASS;
- FILE *fp;
- char cmd[256];
- char buf[512];
- char tmp[512];
- // Get IP address & net mask
- strcpy(cmd, "ifconfig ");
- strcat(cmd, Wifi.currentInterface);
- fp = popen(cmd, "r");
- if(fp == NULL)
- result = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "HWaddr") > 0)
- {
- sscanf(buf, "%*s%*s%*s%*s%s", tmp);
- strcpy(Wifi.currentMAC, tmp);
- }
- if(strstr(buf, "inet addr:") > 0)
- {
- sscanf(buf, "%*s%s", tmp);
- substr(Wifi.currentIPAddr, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
- sscanf(buf, "%*s%*s%*s%s", tmp);
- substr(Wifi.currentNetmask, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
- }
- }
- }
- pclose(fp);
- // Get gateway
- fp = popen("ip route", "r");
- if(fp == NULL)
- result = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strncmp(buf, "default", strlen("default")) == 0)
- break;
- }
- sscanf(buf, "%*s%*s%s", tmp);
- substr(Wifi.currentGateway, tmp, 0, strlen(tmp));
- }
- pclose(fp);
- if(!dispReq.isShowed_IF_info)
- {
- DEBUG_INFO("MAC: %s\n", Wifi.currentMAC);
- dispReq.isShowed_IF_info = true;
- }
- if(!dispReq.isShowed_IP_info)
- {
- DEBUG_INFO("IP address: %s\n", Wifi.currentIPAddr);
- DEBUG_INFO("Net mask: %s\n", Wifi.currentNetmask);
- DEBUG_INFO("Default gateway: %s\n", Wifi.currentGateway);
- dispReq.isShowed_IP_info = true;
- }
- strcpy((char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiIpAddress, (const char*)Wifi.currentIPAddr);
- strcpy((char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSubmaskAddress, (const char*)Wifi.currentNetmask);
- strcpy((char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiGatewayAddress, (const char*)Wifi.currentGateway);
- strcpy((char*)ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMacAddress, (const char*)Wifi.currentMAC);
- return result;
- }
- //==========================================
- // Check if module connect to wifi AP
- //==========================================
- int isConnectAP()
- {
- int result = PASS;
- FILE *fp;
- char cmd[256];
- char buf[512];
- // Get IP address & net mask
- strcpy(cmd, "/root/iwconfig ");
- strcat(cmd, Wifi.currentInterface);
- fp = popen(cmd, "r");
- if(fp == NULL)
- result = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "Not-Associated") > 0)
- {
- result = FAIL;
- DEBUG_INFO("AP check: Not-Associated.\n");
- }
- }
- }
- pclose(fp);
- return result;
- }
- //==========================================
- // Check internet access status
- //==========================================
- int isReachableInternet()
- {
- int result = FAIL;
- FILE *fp;
- char cmd[256];
- char buf[512];
- //char tmp[512];
- for(int idx=0;idx<ARRAY_SIZE(valid_Internet);idx++)
- {
- strcpy(cmd, "ping -c 1 -w 3 ");
- strcat(cmd, valid_Internet[idx]);
- fp = popen(cmd, "r");
- if(fp != NULL)
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "transmitted") > 0)
- {
- //sscanf(buf, "%*s%*s%*s%*s%*s%*s%s", tmp);
- if(strstr(buf,"100%") != NULL)
- {
- }
- else
- {
- result = PASS;
- }
- //DEBUG_INFO("%s",buf);
- //DEBUG_INFO("%s\n",tmp);
- }
- }
- }
- pclose(fp);
- }
- return result;
- }
- //==========================================
- // Check module soft AP is start up
- //==========================================
- int isStartUpAP()
- {
- int result = FAIL;
- FILE *fp;
- char cmd[256];
- char buf[512];
- // Get IP address & net mask
- strcpy(cmd, "/root/uaputl sys_cfg_bss_status");
- fp = popen(cmd, "r");
- if(fp != NULL)
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "BSS status = started") > 0)
- {
- result = PASS;
- DEBUG_INFO("AP already start up.\n");
- }
- }
- }
- pclose(fp);
- return result;
- }
- //==========================================
- // Get wifi connection quality
- //==========================================
- int getLinkQuality()
- {
- int result = FAIL;
- FILE *fp;
- char cmd[256];
- char buf[512];
- char tmp[512];
- strcpy(cmd, "/root/iwconfig ");
- strcat(cmd, Wifi.currentInterface);
- fp = popen(cmd, "r");
- if(fp == NULL)
- result = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "Signal level") > 0)
- {
- sscanf(buf, "%*s%*s%*s%s", tmp);
- substr(tmp, tmp, strspn(tmp, "Signal level="), strlen(buf)-strspn(tmp, "Signal level="));
- Wifi.rssi = atoi(tmp);
- result = PASS;
- }
- }
- }
- pclose(fp);
- return result;
- }
- //==========================================
- // WPA parameter set
- //==========================================
- int setWPAconf()
- {
- int result = FAIL;
- char cmdBuf[512];
- FILE *pFile;
- char buffer[500]="ctrl_interface=/var/run/wpa_supplicant\nupdate_config=1\n";
- // Stop dhcp client or server
- sprintf(cmdBuf, "pgrep -f \"udhcpc -i %s\" | xargs kill", Wifi.currentInterface);
- system(cmdBuf);
- sprintf(cmdBuf, "pgrep -f \"udhcpd\" | xargs kill");
- system(cmdBuf);
- // Clear wifi configuration file
- system("cat /dev/null > /etc/wpa.conf");
- switch(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode)
- {
- case WIFI_MODE_STA:
- // Fill out configuration value depend on share memory setting
- if(strlen((const char*)Wifi_A.passwd)>0)
- {
- if(strlen((const char*)Wifi_A.passwd)>=8)
- {
- strcat(buffer, "network={\n ssid=\"");
- strcat(buffer, (char*)Wifi_A.ssid);
- strcat(buffer, "\"\n key_mgmt=WPA-EAP WPA-PSK \n");
- strcat(buffer, " psk=\"");
- strcat(buffer, (char*)Wifi_A.passwd);
- strcat(buffer, "\"\n}\n\n");
- }
- if(strlen((const char*)Wifi_A.passwd)==5 || strlen((const char*)Wifi_A.passwd)==13)
- {
- strcat(buffer, "network={\n ssid=\"");
- strcat(buffer, (char*)Wifi_A.ssid);
- strcat(buffer, "\"\n key_mgmt=NONE\n");
- strcat(buffer, " wep_key0=\"");
- strcat(buffer, (char*)Wifi_A.passwd);
- strcat(buffer, "\"\n auth_alg=OPEN SHARED\n");
- strcat(buffer, "\n}\n\n");
- }
- strcat(buffer, "network={\n ssid=\"");
- strcat(buffer, (char*)Wifi_A.ssid);
- strcat(buffer, "\"\n key_mgmt=NONE");
- strcat(buffer, "\n}");
- }
- else
- {
- strcat(buffer, "network={\n ssid=\"");
- strcat(buffer, (char*)Wifi_A.ssid);
- strcat(buffer, "\"\n key_mgmt=NONE");
- strcat(buffer, "\n}");
- }
- // Configuration value write to /etc/wpa.conf
- pFile = fopen("/etc/wpa.conf","w");
- fwrite(buffer,strlen(buffer), 1, pFile);
- fclose(pFile);
- // Restart wpa_supplicant
- sprintf(cmdBuf, "pgrep -f \"wpa_supplicant\" | xargs kill");
- system(cmdBuf);
- sprintf(cmdBuf, "/root/wpa_supplicant -i %s -c /etc/wpa.conf -B", Wifi.currentInterface);
- system(cmdBuf);
- // Stop wifi AP
- sprintf(cmdBuf, "/root/uaputl bss_stop");
- system(cmdBuf);
- sleep(5);
- // Wifi IP set by DHCP client or static
- if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpClient==0)
- {
- sprintf(cmdBuf, "/sbin/udhcpc -i %s -s /root/dhcp_script/wifi.script > /dev/null &", Wifi.currentInterface);
- system(cmdBuf);
- }
- else
- {
- strcpy(cmdBuf, "ifconfig ");
- strcat(cmdBuf, Wifi.currentInterface);
- strcat(cmdBuf, " ");
- strcat(cmdBuf, Wifi.staticIPAddr);
- system(cmdBuf);
- DEBUG_INFO("Setting %s static IP to %s ...\n", Wifi.currentInterface, Wifi.staticIPAddr);
- }
- break;
- case WIFI_MODE_AP:
- // Stop wifi AP
- sprintf(cmdBuf, "/root/uaputl bss_stop");
- system(cmdBuf);
- // Reset AP configuration
- sprintf(cmdBuf, "/root/uaputl sys_reset");
- system(cmdBuf);
- // Set SSID to uaputl.conf
- sprintf(cmdBuf, "sed -i 's/ SSID=.*$/ SSID=\"%s\"/' /root/uaputl_config/uaputl.conf", Wifi_A.ssid);
- system(cmdBuf);
- // Set AP configuration by uaputl.conf
- sprintf(cmdBuf, "/root/uaputl sys_config /root/uaputl_config/uaputl.conf");
- system(cmdBuf);
- // Start up wifi AP
- sprintf(cmdBuf, "/root/uaputl bss_start");
- system(cmdBuf);
- sleep(5);
- // Set wifi AP ip address
- sprintf(cmdBuf, "ifconfig %s 192.168.10.10", Wifi.currentInterface);
- system(cmdBuf);
- DEBUG_INFO("Setting %s static IP to 192.168.10.10...\n", Wifi.currentInterface);
- // Start DHCP server
- if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpServer==0)
- {
- sprintf(cmdBuf, "/usr/sbin/udhcpd /etc/udhcpd.conf > /dev/null &");
- system(cmdBuf);
- }
- break;
- case WIFI_MODE_ADHOC:
- break;
- case WIFI_MODE_DISABLE:
- default:
- break;
- }
- result = PASS;
- return result;
- }
- //==========================================
- // Socket server routine
- //==========================================
- int socketServerStart()
- {
- int sockFd = 0;
- int clientSockFd = 0;
- uint8_t inputBuffer[2048] = {};
- uint8_t outBuffer[2048] = {};
- uint8_t cmdBuf[128];
- uint8_t chksum;
- int8_t read_size;
- int8_t tx_size;
- struct sockaddr_in serverInfo, clientInfo;
- socklen_t addrlen = sizeof(clientInfo);
- sockFd = socket(AF_INET , SOCK_STREAM , 0);
- if(sockFd == -1)
- {
- DEBUG_ERROR("InitSocketServer NG\n");
- sleep(5);
- return 0;
- }
- bzero(&serverInfo,sizeof(serverInfo));
- serverInfo.sin_family = PF_INET;
- serverInfo.sin_addr.s_addr = htonl(INADDR_ANY);
- serverInfo.sin_port = htons(LISTEN_PORT);
- bind(sockFd, (struct sockaddr *)&serverInfo, sizeof(serverInfo));
- listen(sockFd, CONNECTION_LIMIT);
- // Main loop
- for(;;)
- {
- clientSockFd = accept(sockFd, (struct sockaddr*) &clientInfo, &addrlen);
- DEBUG_INFO("Client connect in.\r\n");
- while((read_size = recv(clientSockFd, inputBuffer, sizeof(inputBuffer), 0)) > 0)
- {
- if(isValidCheckSum(inputBuffer))
- {
- chksum = 0;
- memset(outBuffer, 0x00, sizeof(outBuffer));
- switch(inputBuffer[3])
- {
- case 0:
- tx_size = 9;
- outBuffer[0] = 0xaa;
- outBuffer[1] = PROTOCOL_ADDR;
- outBuffer[2] = inputBuffer[1];
- outBuffer[3] = 0x00;
- outBuffer[4] = 0x01;
- outBuffer[5] = 0x00;
- outBuffer[6] = 0x01;
- outBuffer[7] = 0x01;
- break;
- default:
- tx_size = 9;
- outBuffer[0] = 0xaa;
- outBuffer[1] = PROTOCOL_ADDR;
- outBuffer[2] = inputBuffer[1];
- outBuffer[3] = inputBuffer[3];
- outBuffer[4] = 0x01;
- outBuffer[5] = 0x00;
- outBuffer[6] = 0x00;
- outBuffer[7] = 0x00;
- break;
- }
- }
- else
- {
- tx_size = 9;
- outBuffer[0] = 0xaa;
- outBuffer[1] = PROTOCOL_ADDR;
- outBuffer[2] = inputBuffer[1];
- outBuffer[3] = inputBuffer[3];
- outBuffer[4] = 0x01;
- outBuffer[5] = 0x00;
- outBuffer[6] = 0x00;
- outBuffer[7] = 0x00;
- }
- send(clientSockFd, outBuffer, tx_size, 0);
- }
- if(read_size == 0)
- {
- DEBUG_INFO("Client disconnected.\r\n");
- fflush(stdout);
- }
- else if(read_size == -1)
- {
- DEBUG_ERROR("Socket recv failed.\r\n");
- }
- sleep(1);
- }
- return -1;
- }
- //==========================================
- // Common routine
- //==========================================
- char* getTimeString(void)
- {
- char *result=malloc(21);
- time_t timep;
- struct tm *p;
- time(&timep);
- p=gmtime(&timep);
- sprintf(result, "[%04d-%02d-%02d %02d:%02d:%02d]", (1900+p->tm_year), (1+p->tm_mon), p->tm_mday, p->tm_hour, p->tm_hour, p->tm_sec);
- return result;
- }
- void trim(char *s)
- {
- int i=0, j, k, l=0;
- while((s[i]==' ')||(s[i]=='\t')||(s[i]=='\n'))
- i++;
- j = strlen(s)-1;
- while((s[j]==' ')||(s[j]=='\t')||(s[j]=='\n'))
- j--;
- if(i==0 && j==strlen(s)-1) { }
- else if(i==0) s[j+1] = '\0';
- else {
- for(k=i; k<=j; k++) s[l++] = s[k];
- s[l] = '\0';
- }
- }
- int mystrcmp(char *p1,char *p2)
- {
- while(*p1==*p2)
- {
- if(*p1=='\0' || *p2=='\0')
- break;
- p1++;
- p2++;
- }
- if(*p1=='\0' && *p2=='\0')
- return(PASS);
- else
- return(FAIL);
- }
- void substr(char *dest, const char* src, unsigned int start, unsigned int cnt)
- {
- strncpy(dest, src + start, cnt);
- dest[cnt] = 0;
- }
- void split(char **arr, char *str, const char *del)
- {
- char *s = strtok(str, del);
- while(s != NULL)
- {
- *arr++ = s;
- s = strtok(NULL, del);
- }
- }
- int isValidCheckSum(uint8_t *message)
- {
- uint8_t chksum=0;
- for(int idx = 0;idx<((message[4] | message[5]<<8)>1024?1024:(message[4] | message[5]<<8));idx++)
- {
- chksum ^= message[6+idx];
- }
- return ((chksum == message[6+((message[4] | message[5]<<8)>1024?1024:(message[4] | message[5]<<8))]) ? PASS : FAIL);
- }
- int checkIP(void)
- {
- // DHCP or static setting
- int isGetIP = FAIL;
- FILE *fp;
- char buf[512];
- char tmp[512];
- char cmd[512];
- if(Wifi.ipType == IP_TYPE_DHCP) {
- // Get IP address & net mask
- strcpy(cmd, "ifconfig ");
- strcat(cmd, Wifi.currentInterface);
- fp = popen(cmd, "r");
- if(fp == NULL)
- isGetIP = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "addr:") > 0)
- {
- if(strstr(buf, "192.168.1.10") > 0)
- {
- DEBUG_INFO("IP cannot be same as default value of Ethernet...\n");
- }
- else
- {
- isGetIP = PASS;
- cnt_getIP_Fail = 0;
- }
- sscanf(buf, "%*s%s", tmp);
- substr(Wifi.currentIPAddr, tmp, strspn(tmp, "addr:"), strlen(buf)-strspn(tmp, "addr:"));
- sscanf(buf, "%*s%*s%*s%s", tmp);
- substr(Wifi.currentNetmask, tmp, strspn(tmp, "Mask:"), strlen(buf)-strspn(tmp, "Mask:"));
- }else {
- }
- }
- }
- if(isGetIP == FAIL && cnt_getIP_Fail<3) {
- sprintf(cmd, "pgrep -f \"udhcpc -i %s\" | xargs kill", Wifi.currentInterface);
- system(cmd);
- if(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiDhcpClient==0)
- {
- sprintf(cmd, "/sbin/udhcpc -i %s -s /root/dhcp_script/wifi.script > /dev/null &", Wifi.currentInterface);
- system(cmd);
- }
- DEBUG_INFO("Sending DHCP request...\n");
- cnt_getIP_Fail++;
- sleep(5);
- }
- pclose(fp);
- }else {
- strcpy(cmd, "ifconfig ");
- strcat(cmd, Wifi.currentInterface);
- strcat(cmd, " ");
- strcat(cmd, Wifi.staticIPAddr);
- fp = popen(cmd, "r");
- DEBUG_INFO("Setting static IP to %s ...\n", Wifi.staticIPAddr);
- pclose(fp);
- isGetIP = PASS;
- }
- cnt_getIP_Fail = 0;
- return isGetIP;
- }
- int restartWPA(void)
- {
- int result = FAIL;
- FILE *fp;
- char buf[512];
- char cmd[50];
- // Get IP address & net mask
- strcpy(cmd, "wpa_cli -i ");
- strcat(cmd, Wifi.currentInterface);
- strcat(cmd, " reconfigure");
- fp = popen(cmd, "r");
- DEBUG_INFO("WPA reconfigure %s ...\n", Wifi.currentInterface);
- if(fp == NULL)
- result = FAIL;
- else
- {
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "OK") > 0)
- {
- DEBUG_INFO("reconfigure OK.\n");
- result = PASS;
- }else {
- DEBUG_INFO("reconfigure failed.\n");
- result = FAIL;
- }
- }
- }
- pclose(fp);
- if(result == PASS) {
- strcpy(cmd, "wpa_cli -i ");
- strcat(cmd, Wifi.currentInterface);
- strcat(cmd, " reconfigure");
- fp = popen(cmd, "r");
- DEBUG_INFO("WPA reconnect %s ...\n", Wifi.currentInterface);
- if(fp == NULL)
- result = FAIL;
- else{
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- if(strstr(buf, "OK") > 0){
- DEBUG_INFO("reconnect OK.\n");
- result = PASS;
- }else {
- DEBUG_INFO("reconnect failed.\n");
- result = FAIL;
- }
- }
- }
- pclose(fp);
- }
- return result;
- }
- void proc_sta()
- {
- switch(Wifi_module_sts)
- {
- case STA_STATE_INIT:
- dispReq.isShowed_IF_info = false;
- // get info from shared memory
- getParameters();
- ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi=1;
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=1;
- isSetWPA_OK = false;
- // check interface
- if((strlen((const char*)Wifi_A.ssid)>0) && (isFindInterface() == PASS))
- {
- DEBUG_INFO("Wifi interface: %s\n", Wifi.currentInterface);
- Wifi_module_sts = STA_STATE_DEVICE_DETECT;
- ShmStatusCodeData->FaultCode.FaultEvents.bits.WiFiModuleBroken=0;
- DEBUG_INFO("=================[State 1]===================\n");
- }
- else
- {
- ShmStatusCodeData->FaultCode.FaultEvents.bits.WiFiModuleBroken=1;
- DEBUG_ERROR("Wifi support interface valid result: Fail\n");
- sleep(30);
- }
- break;
- case STA_STATE_DEVICE_DETECT:
- dispReq.isShowed_IP_info = false;
- if(!isSetWPA_OK && (setWPAconf() == PASS))
- {
- isSetWPA_OK = true;
- ShmStatusCodeData->AlarmCode.AlarmEvents.bits.WiFiModuleCommFail=0;
- sleep(5);
- }
- else if((isSetWPA_OK == true) && (isConnectAP() == PASS))
- {
- Wifi_module_sts = STA_STATE_AP_CONNECTED;
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=0;
- DEBUG_INFO("=================[State 2]===================\n");
- }
- else
- {
- cnt_getAP_Fail++;
- DEBUG_INFO("Fail to connect to the AP %d times...\n",cnt_getAP_Fail);
- if(cnt_getAP_Fail>=3)
- {
- Wifi_module_sts = STA_STATE_INIT;
- cnt_getAP_Fail = 0;
- ShmStatusCodeData->AlarmCode.AlarmEvents.bits.WiFiModuleCommFail=1;
- DEBUG_INFO("=================[State 0]===================\n");
- }
- else
- {
- sleep(10);
- }
- }
- break;
- case STA_STATE_AP_CONNECTED:
- getInterfaceInfo();
- getLinkQuality();
- DEBUG_INFO("Wifi quality: %d dBm\n", Wifi.rssi);
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi = Wifi.rssi;
- if(isReachableInternet() == PASS)
- {
- DEBUG_INFO("Wifi internet valid result: Pass\n");
- ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi=0;
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiNetworkConn=1;
- ShmSysConfigAndInfo->SysInfo.InternetConn=1;
- cnt_pingDNS_Fail = 0;
- sleep(30);
- }
- else
- {
- cnt_pingDNS_Fail++;
- DEBUG_INFO("Wifi internet valid result: Fail %d time\n", cnt_pingDNS_Fail);
- sleep(5);
- }
- if(cnt_pingDNS_Fail >= 3)
- {
- ShmStatusCodeData->InfoCode.InfoEvents.bits.InternetDisconnectViaWiFi=1;
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiNetworkConn=0;
- ShmSysConfigAndInfo->SysInfo.InternetConn=0;
- cnt_pingDNS_Fail = 0;
- DEBUG_INFO("Ping DNS failed...");
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSubmaskAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSubmaskAddress);
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiGatewayAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiGatewayAddress);
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMacAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMacAddress);
- if(isFindInterface() == PASS)
- {
- DEBUG_INFO("Wifi interface: %s\n", Wifi.currentInterface);
- isSetWPA_OK = false;
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi = 0;
- Wifi_module_sts = STA_STATE_DEVICE_DETECT;
- DEBUG_INFO("=================[State 1]===================\n");
- }
- else
- {
- DEBUG_INFO("Wifi support interface valid result: Fail\n");
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi = 0;
- Wifi_module_sts = STA_STATE_INIT;
- DEBUG_INFO("=================[State 0]===================\n");
- }
- }
- break;
- default:
- Wifi_module_sts = STA_STATE_INIT;
- break;
- }
- }
- void proc_ap()
- {
- switch(Wifi_module_sts)
- {
- case AP_STATE_INIT:
- // get info from shared memory
- getParameters();
- isSetWPA_OK = false;
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=1;
- // check interface
- if((strlen((const char*)Wifi_A.ssid)>0) && (isFindInterface() == PASS))
- {
- DEBUG_INFO("Wifi interface: %s\n", Wifi.currentInterface);
- Wifi_module_sts = AP_STATE_DEVICE_DETECT;
- ShmStatusCodeData->FaultCode.FaultEvents.bits.WiFiModuleBroken=0;
- DEBUG_INFO("=================[State 1]===================\n");
- }
- else
- {
- ShmStatusCodeData->FaultCode.FaultEvents.bits.WiFiModuleBroken=1;
- DEBUG_ERROR("Wifi support interface valid result: Fail\n");
- sleep(30);
- }
- break;
- case AP_STATE_DEVICE_DETECT:
- if(!isSetWPA_OK && (setWPAconf() == PASS))
- {
- isSetWPA_OK = true;
- ShmStatusCodeData->AlarmCode.AlarmEvents.bits.WiFiModuleCommFail=0;
- sleep(5);
- }
- else if(isSetWPA_OK && (isStartUpAP() == PASS))
- {
- Wifi_module_sts = AP_STATE_AP_START;
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=0;
- DEBUG_INFO("=================[State 2]===================\n");
- }
- else
- {
- cnt_getAP_Fail++;
- DEBUG_INFO("Fail to start up AP %d times...\n",cnt_getAP_Fail);
- if(cnt_getAP_Fail>=3)
- {
- Wifi_module_sts = AP_STATE_INIT;
- cnt_getAP_Fail = 0;
- ShmStatusCodeData->AlarmCode.AlarmEvents.bits.WiFiModuleCommFail=1;
- DEBUG_INFO("=================[State 0]===================\n");
- }
- else
- {
- sleep(10);
- }
- }
- break;
- case AP_STATE_AP_START:
- getInterfaceInfo();
- if(isStartUpAP() == PASS)
- {
- DEBUG_INFO("Wifi AP start up valid result: Pass\n");
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=0;
- cnt_pingDNS_Fail = 0;
- sleep(30);
- }
- else
- {
- cnt_pingDNS_Fail++;
- DEBUG_INFO("Wifi AP start up valid result: Fail %d time\n", cnt_pingDNS_Fail);
- sleep(5);
- }
- if(cnt_pingDNS_Fail >= 3)
- {
- ShmStatusCodeData->InfoCode.InfoEvents.bits.ApDisconnectViaWiFi=1;
- cnt_pingDNS_Fail = 0;
- DEBUG_INFO("Wifi AP start up status failed...");
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSubmaskAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiSubmaskAddress);
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiGatewayAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiGatewayAddress);
- memset(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMacAddress, 0, sizeof ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMacAddress);
- if(isFindInterface() == PASS)
- {
- DEBUG_INFO("Wifi interface: %s\n", Wifi.currentInterface);
- isSetWPA_OK = false;
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi = 0;
- Wifi_module_sts = STA_STATE_DEVICE_DETECT;
- DEBUG_INFO("=================[State 1]===================\n");
- }
- else
- {
- DEBUG_INFO("Wifi support interface valid result: Fail\n");
- ShmSysConfigAndInfo->SysConfig.AthInterface.WifiRssi = 0;
- Wifi_module_sts = STA_STATE_INIT;
- DEBUG_INFO("=================[State 0]===================\n");
- }
- }
- break;
- default:
- Wifi_module_sts = AP_STATE_INIT;
- break;
- }
- }
- //==========================================
- // Main loop
- //==========================================
- int main(void)
- {
- pid_t pid;
- if(InitShareMemory() == FAIL)
- {
- #ifdef SystemLogMessage
- DEBUG_ERROR("InitShareMemory NG\n");
- #endif
- if(ShmStatusCodeData!=NULL)
- {
- ShmStatusCodeData->AlarmCode.AlarmEvents.bits.FailToCreateShareMemory=1;
- }
- sleep(5);
- return 0;
- }
- //check internet status
- pid = fork();
- if(pid == 0)
- {
- socketServerStart();
- }
- //=============================================
- // Install WIFI module driver
- //=============================================
- #ifdef UBLOX
- system("insmod /lib/modules/mlan.ko");
- system("insmod /lib/modules/usb8801.ko");
- sleep(5);
- system("ifconfig mlan0 up");
- system("ifconfig uap0 up");
- #endif
- #ifdef MT7601U
- system("insmod /lib/modules/mt7601u.ko");
- sleep(5);
- system("ifconfig wlan0 up");
- #endif
- DEBUG_INFO("=================[State 0]===================\n");
- for(;;)
- {
- switch(ShmSysConfigAndInfo->SysConfig.AthInterface.WifiMode)
- {
- case WIFI_MODE_STA:
- proc_sta();
- break;
- case WIFI_MODE_AP:
- proc_ap();
- break;
- case WIFI_MODE_ADHOC:
- break;
- case WIFI_MODE_DISABLE:
- default:
- break;
- }
- }
- return 0;
- }
|