wirelessgateway/threadfunc/SH_ThreadFunc.cpp

994 lines
31 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <map>
#include <time.h>
#include <math.h>
#include <string.h>
#include <cstdlib>
#include <linux/types.h>
#include <sys/sysinfo.h>
#include <boost/typeof/typeof.hpp>
#include "SH_ThreadFunc.hpp"
#include "../API_log/SH_log.h"
#include "../uart/SH_Uart.hpp"
#include "../common/SH_CommonFunc.hpp"
#include "../dial5G/Dial.h"
#include "../wifi/wpa_client.h"
#include <dirent.h>
namespace{
Uart *pUart = Uart::instance();
LocalServer *cidwServer = LocalServer::instance();
}
static std::string serverPort;
static std::string uptime;
static long long connect_lost_time = 0; //ms
static long long connect_time = 0; //ms
Dial dial;
void CheckThread()
{
print_info("ENTER CHECK THREAD \n");
std::string runinfo = "系统循环检测模块启动";
int heart_count = 0;
int time_check = 0;
int reset_flag = 0;
int online_check = 0;
int HardStatus = 0;
int logClean = 0;
int Battery = 0;
int UpdateZigbee = 0;
int commSignal = 0;
int loose_check = 0;
int mqttresend = 0;
int rebootsystem = 0;
int ModifyAddr = 0;
int wifi_reconnect_count = 0;
int checkNet0 = 0;
int connectCount = 0;
while (GlobalConfig::QuitFlag_G) {
if (10 == heart_count) {
// StatusPub();
if (GlobalConfig::LinkCount > 30) {
//exit(0);
}
std::string ipTemp = IpAddrInit();
GlobalConfig::IpAddr_G = ipTemp;
if ( 0 != ipTemp.compare(GlobalConfig::IpAddr_G)) {
//exit(0);
}
heart_count = 0;
}
#ifdef G2UL_GATEWAY
if(checkNet0 == 5){
checkNet0 = 0;
int iStatus = get_netlink_status("eth0");
if(iStatus == 1 && GlobalConfig::net0Status == 0){
system("ifconfig eth0:1 192.168.188.188 netmask 255.255.255.0");
}
GlobalConfig::net0Status = iStatus;
}
#endif
if (300 == time_check) {
char buf[256] = {0};
sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}",
GlobalConfig::MacAddr_G.c_str());
std::string str = std::string(buf);
time_check = 0;
int iRet = data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
if(iRet != 0 )
{
LOG_ERROR("MQTT connect failed\n");
//bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000);
#ifdef NR5G_MODULE
#ifdef IMX6UL_GATEWAY
dial.closePort();
gpio_set(GlobalConfig::GPIO_G.commRest,0);
LOG_DEBUG("GPIO 8 start\n");
sleep(2);
gpio_set(GlobalConfig::GPIO_G.commRest,1);
LOG_DEBUG("GPIO 8 End\n");
sleep(20);
dial.openPort("/dev/ttyUSB2");
dial.setState();
#endif
#ifdef G2UL_GATEWAY
dial.closePort();
gpio_set(GlobalConfig::GPIO_G.commPower,0);
LOG_DEBUG("commPower start\n");
sleep(2);
gpio_set(GlobalConfig::GPIO_G.commPower,1);
LOG_DEBUG("commPower End\n");
sleep(20);
connectCount ++;
if(connectCount > 10){
LOG_ERROR("5G reset error ,reboot!\n");
system("reboot");
}
#ifndef NR5G_MEIGE
dial.openPort("/dev/ttyUSB2");
dial.setState();
#else
char szquectel[100]={0x00};
std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN");
sprintf(szquectel,"/opt/quectel-CM/Meig-CM -s %s &",strAPN.c_str());
system(szquectel);
#endif
#endif
#endif
#ifdef WIFI_MODULE
LOG_ERROR("WiFi reset!\n");
#ifdef IMX6UL_GATEWAY
gpio_set(GlobalConfig::GPIO_G.wifiReset,0);
sleep(5);
gpio_set(GlobalConfig::GPIO_G.wifiReset,1);
sleep(5);
wifi::WPAClient wpa;
wpa.ReconnectWiFi();
system("/etc/init.d/wpa_restart");
system("udhcpc -i wlan2 &");
#endif
#ifdef G2UL_GATEWAY
system("/etc/init.d/wpa_restart");
sleep(5);
string strip = GetGwIp_("wlan0");
print_info("strip = %s\n",strip.c_str());
if (strip.compare("0.0.0.0") != 0) {
}else{
gpio_set(GlobalConfig::GPIO_G.wifiReset,1);
sleep(5);
gpio_set(GlobalConfig::GPIO_G.wifiReset,0);
sleep(30);
wifi::WPAClient wpa;
wpa.ReconnectWiFi();
system("/etc/init.d/wpa_restart");
sleep(5);
system("udhcpc -b -i wlan0 &");
}
#endif
#endif
}else{
connectCount = 0;
}
}
if(HardStatus == 3600){//one hour 3600
JsonData jd;
std::string data = jd.JsonCmd_07();
data_publish(data.c_str(), GlobalConfig::Topic_G.mPubStatus.c_str());
HardStatus = 0;
}
if(mqttresend == 1800){
mqttresend = 0;
#ifdef WIFI_MODULE
bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000);
if(status != 0){
LOG_INFO("===========net status ========failed \n");
LOG_ERROR("openSwitch\n");
sleep(20);
gpio_set(GlobalConfig::GPIO_G.power,1);
}
#endif
LOG_INFO("mqttresend check\n");
Json::Value jsHeart;
Json::FastWriter fw;
jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
jsHeart["status"] = "online_V" + GlobalConfig::Version;
jsHeart["IP"] = GlobalConfig::IpAddr_G;
std::string strJson = fw.write(jsHeart);
int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str());
if(iRet == 0){
sql_ctl->QueryofflineData();
}
}
if (600 == online_check) {
online_check = 0;
int Count = sql_ctl->GetTableRows(T_SENSOR_INFO(TNAME), NULL);
if(Count > 0){
JsonData jd;
jd.DataNodeStatusCheck();
Param_29 param;
std::string cmd29 = jd.JsonCmd_29(param);
int iRet = data_publish(cmd29.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
char localtimestamp[32] = { 0 };
GetTimeNet(localtimestamp, 1);
std::string nowTimetamp = std::string(localtimestamp);
char selectCon[128] = { 0 };
sprintf(selectCon, " sendMsg <> '' ORDER BY timeStamp DESC LIMIT 0,1");
sleep(1);
std::string strTime = sql_ctl->GetData(T_DATASTATIC_INFO(TNAME), "timeStamp", selectCon);
long lTime = atol(nowTimetamp.c_str())-atol(strTime.c_str());
LOG_INFO("online check = %d\n",lTime);
if(lTime > 1800){
LOG_ERROR("nowTimetamp = %s,lastTime = %s,lTime = %d\n",nowTimetamp.c_str(),strTime.c_str(),lTime);
}
}
}if(21000 == Battery){
Battery = 0;
sql_ctl->CalculateBattery();
}
// if(10800 == UpdateZigbee){
// UpdateZigbee = 0;
// pUart->UpdateZigbeeInfoCtrl();
// }
if(21000 == loose_check){
loose_check = 0;
sql_ctl->CalculateDip();
}
if(ModifyAddr == 21000 && pUart->bModifyAddr){
//#ifdef IMX6UL_GATEWAY
LOG_ERROR("ModifyAddr failed \n");
exit(0);
//#endif
}
if(ModifyAddr == 21000){
ModifyAddr = 0;
}
if(18000 == commSignal){ //5h
Json::Value jsBody,jsonVal;
Json::FastWriter showValue;
if(GlobalConfig::NetStatus == "\"NOCONN\"" || GlobalConfig::NetStatus == "\"CONNECT\""){
if(GlobalConfig::NetSignal == 0){
jsBody["communicationSignal"] = "未知";
}
else if(GlobalConfig::NetSignal > -80){
jsBody["commSignal"] = "";
}else if(GlobalConfig::NetSignal > -90 && GlobalConfig::NetSignal < -80){
jsBody["commSignal"] = "";
}else if(GlobalConfig::NetSignal > -105 && GlobalConfig::NetSignal < -90){
jsBody["commSignal"] = "一般";
}else if(GlobalConfig::NetSignal < -105){
jsBody["commSignal"] = "";
}else if(GlobalConfig::NetSignal < -115){
jsBody["commSignal"] = "不稳定";
}
}else if(GlobalConfig::NetStatus == "\"SEARCH\""){
jsBody["commSignal"] = "搜索网络";
}else if(GlobalConfig::NetStatus == "\"LIMSRV\""){
jsBody["commSignal"] = "未插卡";
}else{
jsBody["commSignal"] = "未知";
}
jsonVal["cmd"] = "53";
std::string dataBody = showValue.write(jsBody);
jsonVal["cmdBody"] = dataBody;
data_publish(showValue.write(jsonVal).c_str(), GlobalConfig::Topic_G.mPubConfig.c_str());
}
if(21000 == logClean){
logClean = 0;
DIR *dp; //创建一个指向root路径下每个文件的指针
struct dirent *dirp;
string root="/opt/log/";
if((dp = opendir(root.c_str()))==NULL)
cout << "can't open"<< root << endl;
while((dirp = readdir(dp)) != NULL){
if((!strcmp(dirp->d_name,".")||(!strcmp(dirp->d_name,".."))))
continue;
struct timeval curTime;
gettimeofday(&curTime, NULL);
char buffer[80] = {0};
char fileMonth[11] = {0};
char todayMonth[11]={0};
char fileDay[11] = {0};
char todayDay[11]={0};
struct tm nowTime;
localtime_r(&curTime.tv_sec, &nowTime);//把得到的值存入临时分配的内存中,线程安全
strftime(buffer, sizeof(buffer), "%Y-%m-%d", &nowTime);
memcpy(fileDay,dirp->d_name+8,2);
memcpy(todayDay,buffer+8,2);
memcpy(fileMonth,dirp->d_name+5,2);
memcpy(todayMonth,buffer+5,2);
string filename = root+ string(dirp->d_name);
if(atoi(fileMonth) == atoi(todayMonth) ? abs(atoi(todayDay) - atoi(fileDay)) > 15: abs(abs(30-(atoi(fileDay)) + atoi(todayDay))) > 15){
LOG_INFO("filename = %s\n",filename.c_str());
remove(filename.c_str());
}
}
/*staticData = 0;
Json::Value jsHeart;
Json::FastWriter fw;
jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
jsHeart["status"] = "online";
std::string strJson = fw.write(jsHeart);
int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str());
if(iRet == 0){
JsonData jd;
std::string data = jd.JsonCmd_52();
}
double freeDisk = GetHardDiskFree();
if(freeDisk < 90){
char whereCon[512] = {0x00};
time_t timestamp;
long timeStamp = time(&timestamp) ;//秒级时间戳
memset(whereCon,0x00,sizeof(whereCon));
sprintf(whereCon,"sendMsg = '0' and timeStamp < '%s'",timeStamp-1); //1 week
sql_ctl->DeleteTableData(T_DATA_INFO(TNAME),whereCon,0);
sql_ctl->DeleteTableData(T_DATASTATIC_INFO(TNAME),whereCon,0);
}*/
}
#ifdef WIFI_MODULE
if (wifi_reconnect_count == 600) { // 每 10分钟重连WiFi网络
wifi_reconnect_count = 0;
wifi::WPAClient wpa;
std::string netssid = wpa.GetNetSsid();
std::string currentssid = "";
if (0 == netssid.compare("")) {
netssid = wpa.GetNetSsid();
}
if (netssid.length() > 0) {
currentssid = wpa.GetCurrentSSID();
if (currentssid.length() > 0) {
char buf[64] = {0};
std::string rssiSend = "";
#ifdef G2UL_GATEWAY
rssiSend = "/usr/sbin/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='";
#endif
#ifdef IMX6UL_GATEWAY
rssiSend = "/opt/Cidn/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='";
#endif
system_custom(rssiSend.c_str(), buf);
std::string Rssi = std::string(buf);
memset(buf, 0, 64);
sprintf(buf, "wifi:true Rssi:%s", Rssi.c_str());
print_info("%s\n", buf);
LOG_INFO("%s\n",buf);
} else {
std::string runinfo = "wifi:false\n";
print_info("%s\n", runinfo.c_str());
}
}
if (wpa.ReconnectWiFi()) {
print_info("wifi reconnect ok\n");
}
}
#endif
if ( reset_flag > 7200) {
reset_flag = 0;
//exit(0);
}
Battery ++;
reset_flag++;
time_check++;
heart_count++;
online_check++;
HardStatus ++;
//UpdateZigbee ++;
logClean ++ ;
loose_check ++;
ModifyAddr ++;
mqttresend ++;
#ifdef G2UL_GATEWAY
checkNet0 ++;
#endif
#ifdef WIFI_MODULE
wifi_reconnect_count ++;
#endif
//rebootsystem ++;
if(GlobalConfig::EnterZigBeeWaveTransmittingFlag_G == ENTER_TRANSMITTING_STATUS) {
GlobalConfig::EnterZigBeeWaveTransmittingCnt_G ++;
if(GlobalConfig::EnterZigBeeWaveTransmittingCnt_G >= 180) {
GlobalConfig::EnterZigBeeWaveTransmittingFlag_G = NO_ENTER_TRANSMITTING_STATUS;
GlobalConfig::EnterZigBeeWaveTransmittingCnt_G = 0;
LOG_ERROR("[---- ZigBee error--!] ZigBee PanID is 9999 over time for 3 minutes !\n");
// 重新写入 0x8888
unsigned short shortAddr = 0x8888;
pUart->modify_LocalAddr(0x8888);
GlobalConfig::Zigbee_G.MyAddr = 0x8888;
// pUart->WriteShortAddr2Zigbee(shortAddr);
// 延时1秒
sleep(1);
// 重新读回 GlobalConfig::ZigbeeInfo_G.PanID
pUart->UpdateZigbeeInfoCtrl();
pUart->bUpdateconfig = false;
pUart->bUpdate = false;
// 延时1秒
sleep(1);
std::string str("8888");
if( GlobalConfig::ZigbeeInfo_G.MyAddr.compare(str) == 0 ){
LOG_INFO("[---- ZigBee INFO ----!] ZigBee PanID come back to be 8888 !\n");
}
else {
LOG_ERROR("[---- ZigBee error--!] ZigBee PanID cannot come back to be 8888 !\n");
}
}
}
sleep(1);;
}
}
void StartCgiServer()
{
print_info("start deal cgi\n");
TcpCgi *tcpCgi = TcpCgi::instance();
while (1) {
tcpCgi->startCgiServer();
sleep(10);
}
}
void RunLED()
{
while(1){
gpio_set(GlobalConfig::GPIO_G.runLed,1);
sleep(1);
gpio_set(GlobalConfig::GPIO_G.runLed,0);
sleep(1);
}
}
void HeartRep()
{
int count = 0;
while(1) {
Json::Value jsHeart;
Json::FastWriter fw;
jsHeart["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
jsHeart["status"] = "online_V" + GlobalConfig::Version;
jsHeart["IP"] = GlobalConfig::IpAddr_G;
std::string strJson = fw.write(jsHeart);
int iRet = data_publish(strJson.c_str(), GlobalConfig::Topic_G.mPubHeart.c_str());
print_info("heart = %s,iRet = %d\n",strJson.c_str(),iRet);
if(iRet != 0){
count ++;
gpio_set(GlobalConfig::GPIO_G.errorLed,1);
sleep(1);
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
sleep(1);
gpio_set(GlobalConfig::GPIO_G.errorLed,1);
sleep(1);
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
sleep(1);
gpio_set(GlobalConfig::GPIO_G.errorLed,1);
sleep(1);
GlobalConfig::serverStatus = 1;
}else{
GlobalConfig::serverStatus = 0;
count = 0;
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
}
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
// if(count > 0){
// bool status = Ping( GlobalConfig::ServerIP.c_str(), 10000);
// if(status != 0)
// //LOG_INFO("===========net status ========failed heart count %d\n",count);
// if(status != 0 && count > 30){
// LOG_ERROR("heart send failed,heart count %d\n",count);
// count = 0;
// sleep(20);
// gpio_set(GlobalConfig::GPIO_G.power,1);
// }
// }
// if(count > 1000){
// gpio_set(GlobalConfig::GPIO_G.power,1);
// count = 0;
// }
// write_data(fd,"AT+QENG=\"servingcell\"\r\n",27);
// //sleep(1);
// char buff[1024]={0x00};
// int ret = read_data(fd, buff, 1024, 10);
// print_info("ret = %d,buff = %s\n",ret,buff);
// const char *str2 = "+QENG: ";
// char csq[128] = {0};
// char *pdata = strstr((char*)buff, str2);
// if(pdata){
// strncpy(csq, pdata+7, sizeof(csq));
// }
// else {
// }
//
// //printf("SIM-CSQ: %s\n", csq);
// GlobalConfig::NetStatus = GetOneContent(csq,1,",");
// string signal = GetOneContent(csq,13,",");
// GlobalConfig::NetSignal = atoi(signal.c_str());
// print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal);
//GlobalConfig::NetSignal = getcsq();
/*if(GlobalConfig::NetSignal <= -105 ){
gpio_set(130,1);
}else if(GlobalConfig::NetSignal > -105 ){
gpio_set(130,0);
}else{
gpio_set(130,1);
}*/
sleep(10);
//socketHeart(strJson.c_str());
}
}
void GetCSQ()
{
#ifdef NR5G_MODULE
//5G
int iRet = -1;
open5G:
iRet = dial.openPort("/dev/ttyUSB2");
if (iRet < 0){
sleep(5);
goto open5G;
}
#ifdef NR5G_MEIGE
dial.closePort();
char szquectel[100]={0x00};
std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN");
sprintf(szquectel,"/opt/quectel-CM/Meig-CM -s %s &",strAPN.c_str());
system(szquectel);
#else
dial.recvData();
#endif
#endif
#ifdef Q4G_MODULE
//4G
int fd = -1;
open4G:
fd = config_uart("/dev/ttyUSB2",115200);
if (fd < 0){
sleep(5);
goto open4G;
}
char szbuffer[200]={0x00};
int offSize = 0;
int timeoutflag = 0;
write_data(fd,"AT+QENG=\"servingcell\"\r\n",27);
while(1){
char buff[1024]={0x00};
int ret = read_data(fd, buff, 1024, 10);
if(ret <= 0){
timeoutflag ++;
if(timeoutflag > 5){
print_info("timeoutflag = %d\n",timeoutflag);
timeoutflag = 0;
const char *str2 = "+QENG: ";
char csq[128] = {0};
char *pdata = strstr((char*)szbuffer, str2);
if(pdata){
strncpy(csq, pdata+7, sizeof(csq));
//printf("SIM-CSQ: %s\n", csq);
GlobalConfig::NetStatus = GetOneContent(csq,1,",");
string signal = GetOneContent(csq,13,",");
GlobalConfig::NetSignal = atoi(signal.c_str());
GlobalConfig::NetType = GetOneContent(csq,2,",");
print_info("NetStatus = %s,NetSignal = %d\n",GlobalConfig::NetStatus.c_str(),GlobalConfig::NetSignal);
}
memset(szbuffer,0x00,sizeof(szbuffer));
offSize = 0;
write_data(fd,"AT+QENG=\"servingcell\"\r\n",27);
}
usleep(10000);
}else if(ret > 0){
print_info("ret = %d,buff = %s\n",ret,buff);
memcpy(szbuffer + offSize,buff,ret);
offSize = offSize + ret;
print_info("szbuffer = %s\n",szbuffer);
continue;
}
sleep(10);
}
#endif
}
void Dial5G()
{
sleep(2);
dial5G:
if(dial.m_fd > 0){
dial.dial5G();
}else{
sleep(5);
goto dial5G;
}
}
void UartStart()
{
// onReceiveUart cb = (onReceiveUart)&ProtoConvert::HandleFromUart;
// pUart->setCallBack(cb);
InitGpio(GlobalConfig::GPIO_G.zigAckrep,0);//ACK
InitGpio(GlobalConfig::GPIO_G.zigAckreset,1);//ACK reset
InitGpio(GlobalConfig::GPIO_G.zigReset,1);//Zigbee reset
gpio_set(GlobalConfig::GPIO_G.zigAckreset,1);
gpio_set(GlobalConfig::GPIO_G.zigReset,1);
#ifdef IMX6UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.errorLed,1);//指示灯
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
InitGpio(GlobalConfig::GPIO_G.power,1);//power reset
gpio_set(GlobalConfig::GPIO_G.power,0);
#endif
#ifdef G2UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.runLed,1);
InitGpio(GlobalConfig::GPIO_G.errorLed,1);
gpio_set(GlobalConfig::GPIO_G.runLed,1);
gpio_set(GlobalConfig::GPIO_G.errorLed,0);
InitGpio(GlobalConfig::GPIO_G.netResetNet0,1);
gpio_set(GlobalConfig::GPIO_G.netResetNet0,0);
#endif
GlobalConfig::Zigbee_G.Serial_Rate = 0x07;
GlobalConfig::Zigbee_G.Serial_DataB = 0x08;
GlobalConfig::Zigbee_G.Serial_StopB = 0x01;
pUart->InitUart(B115200);
char buffer[1100]={0x00};
sleep(1);
pUart->UartRecv(pUart->fd,1,buffer);
sleep(1);
}
void InitModule()
{
#ifdef NR5G_MODULE
#ifdef G2UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.commPower,1);//4G,5G模组供电
gpio_set(GlobalConfig::GPIO_G.commPower,1);
InitGpio(GlobalConfig::GPIO_G.vol3_8,1);//5G 高电平3.8V低电平3.3V
gpio_set(GlobalConfig::GPIO_G.vol3_8,1);
InitGpio(GlobalConfig::GPIO_G.commRest,1);
gpio_set(GlobalConfig::GPIO_G.commRest,0);//高电平复位
#endif
#ifdef IMX6UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.commRest,1);
gpio_set(GlobalConfig::GPIO_G.commRest,1);//
#endif
#endif
#ifdef Q4G_MODULE
#ifdef G2UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.commPower,1);//4G,5G模组供电
gpio_set(GlobalConfig::GPIO_G.commPower,1);
InitGpio(GlobalConfig::GPIO_G.commRest,1);
gpio_set(GlobalConfig::GPIO_G.commRest,0);//高电平复位
sleep(10);
char szquectel[100]={0x00};
std::string strAPN = ReadStrByOpt(SERVERCONFIG, "Server", "APN");
sprintf(szquectel,"/opt/quectel-CM/quectel-CM -s %s &",strAPN.c_str());
system(szquectel);
#endif
#endif
#ifdef WIFI_MODULE
print_info("Init WiFi!\n");
#ifdef IMX6UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.wifiReset,1);//WiFi模组复位0复位1取消复位
gpio_set(GlobalConfig::GPIO_G.wifiReset,1);
sleep(10);
wifi::WPAClient wpa;
wpa.ReconnectWiFi();
system("/etc/init.d/wpa_restart");
system("udhcpc -i wlan2 &");
#endif
#ifdef G2UL_GATEWAY
InitGpio(GlobalConfig::GPIO_G.wifiReset,1);//WiFi模组复位1复位0取消复位
gpio_set(GlobalConfig::GPIO_G.wifiReset,0);
InitGpio(GlobalConfig::GPIO_G.wifiPower,1);//WiFi模组上电
gpio_set(GlobalConfig::GPIO_G.wifiPower,1);
sleep(10);
wifi::WPAClient wpa;
wpa.ReconnectWiFi();
system("/usr/sbin/wpa_supplicant -Dnl80211 -iwlan0 -c/etc/wpa_supplicant.conf &");
system("udhcpc -b -i wlan0 &");
#endif
#endif
}
void TestUart()
{
pUart->InitTestUart(B115200);
pUart->ReadTestUart();
}
void UartStartWave()
{
pUart->DealWaveThread();
}
void StartUdpSys()
{
UdpSys *udpsys = UdpSys::instance();
udpsys->StartConnectSysUdp();
}
void WatchDog()
{
int fd = OpenWatchDog();
while(1){
WriteWatchDog(fd);
sleep(50);
}
close(fd);
}
static const char* LOCAL_WILL_TOPIC = "up/uart/will";
void my_publish_callback(struct mosquitto *mosq, void *obj, int mid)
{
}
void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
{
struct userdata *ud;
ud = (struct userdata *)obj;
if (!result){
for (int i = 0; i < ud->topic_count; i++){
print_purple("mosquitto_subscribe ud->topics[%d]:%s\n", i, ud->topics[i]);
int iret = mosquitto_subscribe(mosq, NULL, ud->topics[i], ud->topic_qos);
print_purple("mosquitto_subscribe ret:%d\n", iret);
}
int iret = mosquitto_subscribe(mosq, NULL, GlobalConfig::Topic_G.mSubData.c_str(), 1);
print_debug("mosquitto_subscribe's return value: %d\n", iret);
char gwTime[32] = { 0 };
GetTimeNet(gwTime, 0);
connect_time = strtoll(gwTime, NULL, 10);
print_debug("connect_time:%lld\n", connect_time);
long long difftime_ms = connect_time - connect_lost_time;
if (difftime_ms > 20*1000) { // 超过20秒判定为连接断开
char reply_string[256] = {0};
std::string startStatus = "0";
if (access(SYSTEMSTART, 0) >= 0) {
startStatus = GetFileContent(SYSTEMSTART, 1);
}
sprintf(reply_string, "{\"dataNodeGatewayNo\":\"%s\",\"softVersion\":\"%s\",\"status\":\"%s\"}",
GlobalConfig::MacAddr_G.c_str(), GlobalConfig::Version.c_str(), startStatus.c_str());
Json::Value jsData;
Json::Value jsVal;
Json::FastWriter fw;
jsData["cmd"] = "15";
jsData["dataNodeGatewayNo"] = GlobalConfig::MacAddr_G;
std::string strCmd15 = fw.write(jsData);
std::string instr = std::string(reply_string);
std::string topic = "equipment/state/" + GlobalConfig::MacAddr_G;
int ret = data_publish(instr.c_str(), topic.c_str());
if (ret != MOSQ_ERR_SUCCESS) {
print_debug("Publish failed:%d, %s\n", ret, instr.c_str());
disconnect();
}
}
GlobalConfig::LinkStatus_G = 1;
print_debug("Connect to server success.\n");
// std::string cmd20 = JsonCmd_Cgi_20();
// data_publish(cmd20.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
char buf[256] = {0};
sprintf(buf, "{\"dataNodeGatewayNo\":\"%s\",\"cmd\":\"12\",\"status\":\"REQ\"}",
GlobalConfig::MacAddr_G.c_str());
std::string str = std::string(buf);
// data_publish(str.c_str(), GlobalConfig::Topic_G.mPubCmd.c_str());
std::string runinfo = "本地服务器连接成功";
}
else{
if (result && !ud->quiet){
fprintf(stderr, "%s\n", mosquitto_connack_string(result));
if(result == 1) {
//Connection Refused: unacceptable protocol version
} else if (result == 2) {
//Connection Refused: identifier rejected
} else if (result == 3) {
//Connection Refused: server unavailable
} else if (result == 4) {
//Connection Refused: bad user name or password
// exit(0);
} else if (result == 5) {
//Connection Refused: not authorized
}
}
}
}
void my_disconnect_callback(struct mosquitto *mosq, void *obj, int result)
{
int ret = 0;
ret = disconnect();
//LOG_ERROR("The MQTT connection lost:%d\n", ret);
print_debug("The MQTT connection lost\n");
char gwTime[32] = { 0 };
GetTimeNet(gwTime, 0);
uptime = std::string(gwTime);
connect_lost_time = strtoll(uptime.c_str(), NULL, 10);
print_debug("connect_lost_time:%lld\n", connect_lost_time);
GlobalConfig::LinkStatus_G = 0;
GlobalConfig::LinkCount = GlobalConfig::LinkCount + 1;
#ifdef WIFI_MODULE
char buf[128] = {0};
std::string wpa_state = "";
#ifdef G2UL_GATEWAY
wpa_state = "/usr/sbin/wpa_cli status|grep wpa_state | cut -f 2 -d '='";
#endif
#ifdef IMX6UL_GATEWAY
wpa_state = "/opt/Cidn/wpa_cli status|grep wpa_state | cut -f 2 -d '='";
#endif
system_custom(wpa_state.c_str(), buf);
std::string state = std::string(buf);
std::string RSSI_cmd = "";
#ifdef G2UL_GATEWAY
RSSI_cmd = "/usr/sbin/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='";
#endif
#ifdef IMX6UL_GATEWAY
RSSI_cmd = "/opt/Cidn/wpa_cli signal_poll|grep RSSI | cut -f 2 -d '='";
#endif
system_custom(RSSI_cmd.c_str(), buf);
std::string RSSI = std::string(buf);
int iRet = reconnect();
memset(buf, 0, sizeof(buf));
sprintf(buf, "wifi RSSI:%s,state:%s,MQTT reconnect :%d\n", RSSI.c_str(),state.c_str(),iRet);
//LOG_WARN(" %s\n",buf);
int status = Ping( GlobalConfig::ServerIP.c_str(), 10000);;
//LOG_WARN(" netStatus %d\n",status);
print_info("%s\n", buf);
#else
int iRet = reconnect();
#endif
}
void my_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
struct userdata *ud;
bool res;
assert(obj);
ud = (struct userdata *)obj;
if (message->retain && ud->no_retain) return;
if (ud->filter_outs) {
for (int i = 0; i < ud->filter_out_count; i++) {
mosquitto_topic_matches_sub(ud->filter_outs[i], message->topic, &res);
if (res) return;
}
}
if (ud->verbose) {
if (message->payloadlen) {
std::string strtopic(message->topic);
print_info("strtopic : %s \n", strtopic.c_str());
cidwServer->HandleFromServer((const char *)message->payload,message->payloadlen,message->topic);
if (ud->eol) {
print_brown("\n");
}
} else {
if (ud->eol) {
print_brown("%s (null)\n", message->topic);
}
}
fflush(stdout);
} else {
if (message->payloadlen) {
fwrite(message->payload, 1, message->payloadlen, stdout);
if (ud->eol) {
print_red("\n");
}
fflush(stdout);
}
}
}
void my_subscribe_callback(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
{
int i;
struct userdata *ud;
assert(obj);
ud = (struct userdata *)obj;
if (!ud->quiet) print_brown("Subscribed (mid: %d): %d", mid, granted_qos[0]);
for (i = 1; i < qos_count; i++){
if (!ud->quiet) print_brown(", %d", granted_qos[i]);
}
}
void my_log_callback(struct mosquitto *mosq, void *obj, int level, const char *str)
{
if (level == MOSQ_LOG_ERR) {
//LOG_ERROR("%s\n", str);
} else if (level == MOSQ_LOG_WARNING) {
// LOG_WARN("%s\n", str);
} else if (level == MOSQ_LOG_NOTICE) {
//LOG_INFO("%s\n", str);
}
}
void StartMqttClient()
{
print_info("start mqtt \n");
std::string runinfo = "MQTT通信模块启动";
while (1) {
if (GlobalConfig::ServerIP.length() > 0) {
std::string strEqupNo = GlobalConfig::MacAddr_G;
std::string strVersion = GlobalConfig::Version;
std::string salt;
register_collback(my_connect_callback, my_message_callback, my_subscribe_callback, my_log_callback, my_disconnect_callback, my_publish_callback);
start_client(strEqupNo.c_str(), GlobalConfig::MacAddr_G.c_str(), GlobalConfig::ServerIP.c_str(), strVersion.c_str(), "11111111", salt);
}
sleep(3);
}
}
void SearchThread()
{
std::string runinfo = "设备搜索模块启动";
while (GlobalConfig::QuitFlag_G) {
if (GlobalConfig::IpAddr_G.length() > 0 && 0 != GlobalConfig::IpAddr_G.compare("0.0.0.0")) {
print_info("%s\n",runinfo.c_str());
boost::asio::io_service io_service;
SearchDev *searchDevObj = new SearchDev(io_service);
searchDevObj->MultiCastRecv();
io_service.run();
delete searchDevObj;
}
sleep(5);
print_error("SearchThred restart.\n");
}
}
void RecvUpdateFile()
{
boost::asio::io_service iosev;
boost::asio::ip::tcp::acceptor acceptor(iosev,
boost::asio::ip::tcp::endpoint(
boost::asio::ip::tcp::v4(), 7304));
for(;;) {
boost::asio::ip::tcp::socket socket(iosev);
acceptor.accept(socket);
boost::system::error_code ec;
if(ec) {
print_error("%s\n", boost::system::system_error(ec).what());
//return -1;
}
FILE *fp;
char buffer[1024];
size_t len = 0;
int write_len;
bzero(buffer,1024);
fp = fopen("/tmp/upgrade.tar.gz", "w");
if(NULL == fp ) {
print_info("File:\t Can Not Open To Write\n");
exit(1);
}
while(len = socket.read_some(boost::asio::buffer(buffer),ec)) {
if(len < 0) {
print_info("Receive Data From Server Failed! \n");
break;
}
write_len = fwrite(buffer, sizeof(char), len, fp);
if(write_len < len) {
print_info("File:test Write Failed!\n");
break;
}
bzero(buffer, 1024);
}
print_info("Receive File From Server Finished! \n");
fclose(fp);
Json::Value jsData;
Json::FastWriter fw;
jsData["cmd"] = "03";
jsData["updatefilename"] = "updatefile";
std::string str = fw.write(jsData);
system("/etc/init.d/sysupgrade.sh");
}
}