您的位置:首页 > 编程语言

wince天气代码

2015-12-08 09:44 369 查看
#ifndef COMMON_H
#define COMMON_H

#include <Windows.h>

typedef struct _operateInfo
{
HANDLE hSemaphore;
LPCTSTR pBuf;
}OPERATEINFO;

#define URLLENGTH 2083
#define DATALENGTH 1024*1024

#endif


#ifndef	QUERYINFO_H
#define QUERYINFO_H

#include <string>
#include "define.h"
#include "com.h"
#include "QueryInfo.h"
#include "SysTime.h"

class CHCQueryInfo
{
public:
CHCQueryInfo();
~CHCQueryInfo();

public:
//初始化,调用其它接口前必须先调用此接口
int Init();

//从搜狗获得天气信息
bool GetWeatherInfo(IN HCString strCityCode, OUT WEATHERINFOVEC &weatherInfo, OUT HCString &strUpdateTime);

//从360获得天气信息
bool GetWeatherInfo360(IN HCString strCityCode, OUT WEATHERINFOVEC &weatherInfo, OUT HCString &strUpdateTime);

//从新浪获得天气信息
bool GetWeatherInfoSina(IN HCString strCityName, OUT WEATHERINFOVEC &weatherInfoVec, OUT HCString &strUpdateTime);

private:
OPERATEINFO CreatMapping(TCHAR szMappingName[], TCHAR szSemName[], int size);
void StartServer();
bool ParserWeatherInfo(TCHAR* szWeatherInfo, WEATHERINFOVEC &weatherInfo, HCString &strUpdateTime);
bool ParserWeatherInfo360(TCHAR* szWeatherInfo, WEATHERINFOVEC &weatherInfo, HCString &strUpdateTime);
bool ParserWeatherInfoSina(char* szWeatherInfo, WEATHERINFO &weatherInfo, HCString &strUpdateTime);
void secondToDate(UINT nSeconds, HCString &strDate);
void GetDayOfWeek(HCString strDate, HCString &strDayOfWeek);
void GetDayOfWeekEx(UINT uDayOfWeek, HCString &strDayOfWeek);
void UnicodeToChinese(std::string strUnicode, HCString &strChinese);

private:
OPERATEINFO writeInfo;
OPERATEINFO readInfo;
CHCSysTime m_sysTime;
};

#endif


#include <string>
#include "define.h"
#include "com.h"
#include "QueryInfo.h"
#include <tchar.h>
#include "json/json.h"
#include "WideMultiChange.h"
#include <time.h>
#include "web.h"
#include <stdlib.h>
#include "string.hpp"
#include "tinyxml/tinyxml.h"

using namespace openutils;

CHCQueryInfo::CHCQueryInfo()
{

}

CHCQueryInfo::~CHCQueryInfo()
{
}

int CHCQueryInfo::Init()
{
// 	if (m_sysTime.SetSysTime() == FALSE)
// 	{
// 		return -1;
// 	}

return 0;

// 	TCHAR szMapWriteName[]=TEXT("Global\\FileMappingWriteObject");    //指向同一块共享内存的名字
// 	TCHAR szSemClentName[]=TEXT("Global\\SemaphoreClentObject");    //客户端生成信号量的名称
//
// 	writeInfo = CreatMapping(szMapWriteName, szSemClentName, URLLENGTH);
// 	if(writeInfo.hSemaphore == NULL || writeInfo.pBuf == NULL)
// 		return -1;
// 	//WriteLog("writeInfo.hSemaphore = %d, writeInfo.pBuf = %d\n", writeInfo.hSemaphore, writeInfo.pBuf);
//
// 	TCHAR szMapReadName[]=TEXT("Global\\FileMappingReadObject");    //指向同一块共享内存的名字
// 	TCHAR szSemServerName[]=TEXT("Global\\SemaphoreServerObject");    //服务器生成信号量的名称
//
// 	readInfo = CreatMapping(szMapReadName, szSemServerName, DATALENGTH);
// 	if(readInfo.hSemaphore == NULL|| readInfo.pBuf == NULL )
// 		return -1;
// 	//WriteLog("readInfo.hSemaphore = %d, readInfo.pBuf = %d\n", readInfo.hSemaphore, readInfo.pBuf);
//
// 	//StartServer();

}

bool CHCQueryInfo::GetWeatherInfo(HCString strCityCode, WEATHERINFOVEC &weatherInfo, HCString &strUpdateTime)
{
//CHCSysTime sysTime;
//DWORD dwTime;
//sysTime.GetSysTime(dwTime);

strCityCode = _T("CN") + strCityCode;
CWideToMulti MultiCityCode(strCityCode.c_str());
char *szRead = new char[DATALENGTH];

try{
WebForm wf;
wf.setHost("http://123.sogou.com");
wf.setScriptFile("/get123.php");
wf.putVariable("block","wt");
wf.putVariable("ver","v32");
wf.putVariable("city",MultiCityCode.c_str());
wf.sendRequest();
wf.getResponse(szRead,DATALENGTH - 1);

// 		WebForm wf;
//  		wf.setHost("http://cdn.weather.hao.360.cn");
//  		wf.setScriptFile("/api_weather_info.php");
//  		wf.putVariable("app","hao360");
//  		wf.putVariable("_jsonp","");
//  		wf.putVariable("code",MultiCityCode.c_str());
// 		wf.sendRequest();
// 		wf.getResponse(szRead,DATALENGTH - 1);

}catch(WebFormException ex) {
if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}
return false;
}

CMultiToWide wideRead(szRead);
bool bReturn = ParserWeatherInfo(const_cast<TCHAR*>( wideRead.wc_str() ), weatherInfo, strUpdateTime);
//bool bReturn = ParserWeatherInfo(const_cast<TCHAR*>( wideRead.wc_str() ), weatherInfo, strUpdateTime);

if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}

return bReturn;

//	TCHAR tagUrl[URLLENGTH];
//  _stprintf(tagUrl, _T("http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=&code=%s"), strCityCode.c_str());

// 	memset((void*)writeInfo.pBuf, 0, URLLENGTH ); //共享内存清零
// 	memcpy( (void*)writeInfo.pBuf, tagUrl, URLLENGTH );
//
// 	ReleaseSemaphore(writeInfo.hSemaphore, 1, NULL);
//
// 	TCHAR *szRead = new TCHAR[DATALENGTH];
// 	WaitForSingleObject(readInfo.hSemaphore, INFINITE);
// 	memcpy(szRead,(PVOID)readInfo.pBuf, DATALENGTH);
//
// 	bool bReturn = ParserWeatherInfo(szRead, weatherInfo, strUpdateTime);
//
// 	if ( szRead != NULL )
// 	{
// 		delete []szRead;
// 		szRead = NULL;
// 	}
//
// 	return bReturn;
}

bool CHCQueryInfo::GetWeatherInfo360(IN HCString strCityCode, OUT WEATHERINFOVEC &weatherInfo, OUT HCString &strUpdateTime)
{
CWideToMulti MultiCityCode(strCityCode.c_str());
char *szRead = new char[DATALENGTH];

try{
WebForm wf;
wf.setHost("http://cdn.weather.hao.360.cn");
wf.setScriptFile("/api_weather_info.php");
wf.putVariable("app","hao360");
wf.putVariable("_jsonp","");
wf.putVariable("code",MultiCityCode.c_str());
wf.sendRequest();
wf.getResponse(szRead,DATALENGTH - 1);

}catch(WebFormException ex) {
if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}
return false;
}

CMultiToWide wideRead(szRead);
bool bReturn = ParserWeatherInfo360(const_cast<TCHAR*>( wideRead.wc_str() ), weatherInfo, strUpdateTime);

if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}

return bReturn;

}

bool CHCQueryInfo::GetWeatherInfoSina(IN HCString strCityName, OUT WEATHERINFOVEC &weatherInfoVec, OUT HCString &strUpdateTime)
{
CWideToMulti W2MCityCode(strCityName.c_str());
char *szRead = new char[DATALENGTH];

for (int i = 0; i < 5; i++)
{
memset(szRead, 0, DATALENGTH);
char cDay[2] = {0};
sprintf(cDay, "%d", i);

try{
WebForm wf;
wf.setHost("http://php.weather.sina.com.cn");
wf.setScriptFile("/xml.php");
wf.putVariable("city",W2MCityCode.c_str());
wf.putVariable("password","DJOYnieT8234jlsK");
wf.putVariable("day",cDay);
wf.sendRequest();
wf.getResponse(szRead,DATALENGTH - 1);

}catch(WebFormException ex) {
if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}
return false;
}

WEATHERINFO weatherInfo;
bool bReturn = ParserWeatherInfoSina(szRead, weatherInfo, strUpdateTime);
if (bReturn == true)
{
weatherInfoVec.push_back(weatherInfo);
}

}

if ( szRead != NULL )
{
delete []szRead;
szRead = NULL;
}

return true;
}

bool CHCQueryInfo::ParserWeatherInfo(TCHAR* szWeatherInfo, WEATHERINFOVEC &weatherInfo, HCString &strUpdateTime)
{
//DWORD dwTime;
m_sysTime.GetCurrentTime(strUpdateTime);
//secondToDate(dwTime, strUpdateTime);

HCString str(szWeatherInfo);
HCString strWeatherInfo;

std::size_t firstIndex = str.find_first_of('(');
std::size_t endIndex = str.find_first_of(')');
if (firstIndex != std::wstring::npos && endIndex != std::wstring::npos)
{
strWeatherInfo = str.substr(firstIndex + 1, endIndex - firstIndex - 1);
}

Json::Reader reader;

Json::Value root;

CWideToUtf8  infoUtf8(strWeatherInfo.c_str());
CWideToMulti Info(strWeatherInfo.c_str());
if (reader.parse(Info.c_str(), root))
{
Json::Value wt7 = root["wt7"];
if (!wt7.isNull())
{
int wt7Size = wt7.size();

std::string strWeather;
std::string strTemperature;
std::string strWD;
std::string strWS;
int subindex = 0;
for (int i = 0; i < wt7Size; i++)
{
WEATHERINFO tmpWeatherInfo;
subindex = 0;

std::string strDate = wt7[i][subindex++].asString();
CMultiToWide WideDate(strDate.c_str());
tmpWeatherInfo.data = WideDate.wc_str();

UINT uDayOfWeek = wt7[i][subindex++].asUInt();
HCString strDayOfWeek;
GetDayOfWeekEx(uDayOfWeek, strDayOfWeek);
tmpWeatherInfo.dayOfWeek = strDayOfWeek;

strWeather = wt7[i][subindex++].asString();
//将间改为转
{
unsigned pos = strWeather.find("38388");
if (pos != std::string::npos)
{
strWeather.replace( pos , 5, "36716");
}

}
UnicodeToChinese(strWeather, tmpWeatherInfo.weather);

subindex++;

int uTemp1 = wt7[i][subindex++].asInt();
char szTemp1[4];
_itoa_s(uTemp1, szTemp1, 4, 10);
CMultiToWide WideTemp1(szTemp1);
tmpWeatherInfo.temp1 = WideTemp1.wc_str();

int uTemp2 = wt7[i][subindex++].asInt();
char szTemp2[4];
_itoa_s(uTemp2, szTemp2, 4, 10);
CMultiToWide WideTemp2(szTemp2);
tmpWeatherInfo.temp2 = WideTemp2.wc_str();

std::string strWDWS =  wt7[i][subindex++].asString();
std::vector<std::string> ret = tokenize(strWDWS, " ");
int size = ret.size();
if (1 == size )
{
UnicodeToChinese(ret[0].c_str(), tmpWeatherInfo.WD);
}
else if (2 == size )
{
UnicodeToChinese(ret[0].c_str(), tmpWeatherInfo.WD);
if (ret[1].compare("微风") == 0)
{
tmpWeatherInfo.WS = _T("微风");
}
else
{
std::vector<std::string> WSVec = tokenize(ret[1].c_str(), "&");
CMultiToWide WideWS(WSVec[0].c_str());
tmpWeatherInfo.WS = WideWS.wc_str();
tmpWeatherInfo.WS = tmpWeatherInfo.WS + _T("级");
}
}

weatherInfo.push_back(tmpWeatherInfo);
}
}
}

return true;
}

bool CHCQueryInfo::ParserWeatherInfo360(TCHAR* szWeatherInfo, WEATHERINFOVEC &weatherInfo, HCString &strUpdateTime)
{
HCString str(szWeatherInfo);
HCString strWeatherInfo;

std::size_t firstIndex = str.find_first_of('(');
std::size_t endIndex = str.find_first_of(')');
if (firstIndex != std::wstring::npos && endIndex != std::wstring::npos)
{
strWeatherInfo = str.substr(firstIndex + 1, endIndex - firstIndex - 1);
}

Json::Reader reader;

Json::Value root;

CWideToUtf8  infoUtf8(strWeatherInfo.c_str());
CWideToMulti Info(strWeatherInfo.c_str());
if (reader.parse(Info.c_str(), root))
{
UINT nSeconds = root["time"].asUInt();
secondToDate(nSeconds, strUpdateTime);

Json::Value weather = root["weather"];
if (!weather.isNull())
{
int weatherSize = weather.size();

std::string strWeather;
std::string strTemperature;
std::string strWD;
std::string strWS;
if (weatherSize > 0)
{
WEATHERINFO tmpWeatherInfo;
int index = 0;
std::string strDate = weather[index]["date"].asString();
CMultiToWide WideDate(strDate.c_str());
tmpWeatherInfo.data = WideDate.wc_str();

HCString strDayOfWeek;
GetDayOfWeek(WideDate.wc_str(), strDayOfWeek);
tmpWeatherInfo.dayOfWeek = strDayOfWeek;

Json::Value info = weather[index]["info"];
if (!info["dawn"].isNull())
{
strWeather = info["dawn"][1].asString();
CUtf8ToWide  WideWeather(strWeather.c_str());
CWideToMulti ByteWeather(WideWeather.wc_str()) ;
CMultiToWide tmpWeather(ByteWeather.c_str());
tmpWeatherInfo.weather = tmpWeather.wc_str();

//温度
{
strTemperature = info["dawn"][2].asString();
CMultiToWide dawnTemperature(strTemperature.c_str());
tmpWeatherInfo.temp1 = dawnTemperature.wc_str();
tmpWeatherInfo.temp2 = dawnTemperature.wc_str();

strTemperature = info["day"][2].asString();
CMultiToWide dayTemperature(strTemperature.c_str());
if ( tmpWeatherInfo.temp1.compare(dayTemperature.wc_str()) >= 0 )
{
tmpWeatherInfo.temp1 = dayTemperature.wc_str();
}
else
{
tmpWeatherInfo.temp2 = dayTemperature.wc_str();
}

strTemperature = info["night"][2].asString();
CMultiToWide nightTemperature(strTemperature.c_str());
if ( tmpWeatherInfo.temp1.compare(nightTemperature.wc_str()) > 0 )
{
tmpWeatherInfo.temp1 = nightTemperature.wc_str();
}
else if( tmpWeatherInfo.temp2.compare(nightTemperature.wc_str()) < 0 )
{
tmpWeatherInfo.temp2 = nightTemperature.wc_str();
}
}

strWD = info["dawn"][3].asString();
CUtf8ToWide  WideWD(strWD.c_str());
CWideToMulti ByteWD(WideWD.wc_str()) ;
CMultiToWide tmpWD(ByteWD.c_str());
tmpWeatherInfo.WD = tmpWD.wc_str();

strWS = info["dawn"][4].asString();
CUtf8ToWide  WideWS(strWS.c_str());
CWideToMulti ByteWS(WideWS.wc_str()) ;
CMultiToWide tmpWS(ByteWS.c_str());
tmpWeatherInfo.WS = tmpWS.wc_str();
}
else
{
if (!info["day"].isNull())
{
strWeather = info["day"][1].asString();
CUtf8ToWide  WideWeather(strWeather.c_str());
CWideToMulti ByteWeather(WideWeather.wc_str()) ;
CMultiToWide tmpWeather(ByteWeather.c_str());
tmpWeatherInfo.weather = tmpWeather.wc_str();

//温度
{
strTemperature = info["day"][2].asString();
CMultiToWide dayTemperature(strTemperature.c_str());
tmpWeatherInfo.temp1 = dayTemperature.wc_str();
tmpWeatherInfo.temp2 = dayTemperature.wc_str();

strTemperature = info["night"][2].asString();
CMultiToWide nightTemperature(strTemperature.c_str());
if ( tmpWeatherInfo.temp1.compare(nightTemperature.wc_str()) >= 0 )
{
tmpWeatherInfo.temp1 = nightTemperature.wc_str();
}
else
{
tmpWeatherInfo.temp2 = nightTemperature.wc_str();
}
}

strWD = info["day"][3].asString();
CUtf8ToWide  WideWD(strWD.c_str());
CWideToMulti ByteWD(WideWD.wc_str()) ;
CMultiToWide tmpWD(ByteWD.c_str());
tmpWeatherInfo.WD = tmpWD.wc_str();

strWS = info["day"][4].asString();
CUtf8ToWide  WideWS(strWS.c_str());
CWideToMulti ByteWS(WideWS.wc_str()) ;
CMultiToWide tmpWS(ByteWS.c_str());
tmpWeatherInfo.WS = tmpWS.wc_str();
}
else
{
strWeather = info["night"][1].asString();
CUtf8ToWide  WideWeather(strWeather.c_str());
CWideToMulti ByteWeather(WideWeather.wc_str()) ;
CMultiToWide tmpWeather(ByteWeather.c_str());
tmpWeatherInfo.weather = tmpWeather.wc_str();

strTemperature = info["night"][2].asString();
CMultiToWide dayTemperature(strTemperature.c_str());
tmpWeatherInfo.temp1 = dayTemperature.wc_str();
tmpWeatherInfo.temp2 = dayTemperature.wc_str();

strWD = info["night"][3].asString();
CUtf8ToWide  WideWD(strWD.c_str());
CWideToMulti ByteWD(WideWD.wc_str()) ;
CMultiToWide tmpWD(ByteWD.c_str());
tmpWeatherInfo.WD = tmpWD.wc_str();

strWS = info["night"][4].asString();
CUtf8ToWide  WideWS(strWS.c_str());
CWideToMulti ByteWS(WideWS.wc_str()) ;
CMultiToWide tmpWS(ByteWS.c_str());
tmpWeatherInfo.WS = tmpWS.wc_str();
}
}

weatherInfo.push_back(tmpWeatherInfo);

}

for (int i = 1; i < weatherSize; i++)
{
WEATHERINFO tmpWeatherInfo;
std::string strDate = weather[i]["date"].asString();
CMultiToWide WideDate(strDate.c_str());
tmpWeatherInfo.data = WideDate.wc_str();

HCString strDayOfWeek;
GetDayOfWeek(WideDate.wc_str(), strDayOfWeek);
tmpWeatherInfo.dayOfWeek = strDayOfWeek;

Json::Value info = weather[i]["info"];
if (!info["day"].isNull())
{
strWeather = info["day"][1].asString();
CUtf8ToWide  WideWeather(strWeather.c_str());
CWideToMulti ByteWeather(WideWeather.wc_str()) ;
CMultiToWide tmpWeather(ByteWeather.c_str());
tmpWeatherInfo.weather = tmpWeather.wc_str();

//温度
{
strTemperature = info["dawn"][2].asString();
CMultiToWide dawnTemperature(strTemperature.c_str());
tmpWeatherInfo.temp1 = dawnTemperature.wc_str();
tmpWeatherInfo.temp2 = dawnTemperature.wc_str();

strTemperature = info["day"][2].asString();
CMultiToWide dayTemperature(strTemperature.c_str());
if ( tmpWeatherInfo.temp1.compare(dayTemperature.wc_str()) >= 0 )
{
tmpWeatherInfo.temp1 = dayTemperature.wc_str();
}
else
{
tmpWeatherInfo.temp2 = dayTemperature.wc_str();
}

strTemperature = info["night"][2].asString();
CMultiToWide nightTemperature(strTemperature.c_str());
if ( tmpWeatherInfo.temp1.compare(nightTemperature.wc_str()) > 0 )
{
tmpWeatherInfo.temp1 = nightTemperature.wc_str();
}
else if( tmpWeatherInfo.temp2.compare(nightTemperature.wc_str()) < 0 )
{
tmpWeatherInfo.temp2 = nightTemperature.wc_str();
}
}

strWD = info["day"][3].asString();
CUtf8ToWide  WideWD(strWD.c_str());
CWideToMulti ByteWD(WideWD.wc_str()) ;
CMultiToWide tmpWD(ByteWD.c_str());
tmpWeatherInfo.WD = tmpWD.wc_str();

strWS = info["day"][4].asString();
CUtf8ToWide  WideWS(strWS.c_str());
CWideToMulti ByteWS(WideWS.wc_str()) ;
CMultiToWide tmpWS(ByteWS.c_str());
tmpWeatherInfo.WS = tmpWS.wc_str();

weatherInfo.push_back(tmpWeatherInfo);
}
}
}
}
else
{
return false;
}

return true;
}

bool CHCQueryInfo::ParserWeatherInfoSina(char* szWeatherInfo, WEATHERINFO &weatherInfo, HCString &strUpdateTime)
{
TiXmlDocument* pDoc = new TiXmlDocument();
pDoc->Parse(szWeatherInfo);

TiXmlElement* rootElement = pDoc->RootElement();//Profiles

TiXmlElement* weatherElement = rootElement->FirstChildElement();//Weather
if (weatherElement == NULL)
{
return false;
}

TiXmlElement* dateElement = weatherElement->FirstChildElement("savedate_weather");//savedate_weather 日期
string strDate = dateElement->GetText();
CUtf8ToWide T2WDate(strDate.c_str());
weatherInfo.data = T2WDate.wc_str();

HCString strDayOfWeek; //星期
GetDayOfWeek(T2WDate.wc_str(), strDayOfWeek);
weatherInfo.dayOfWeek = strDayOfWeek;

TiXmlElement* statusElement = weatherElement->FirstChildElement("status1");//status1 天气情况
string strStatus = statusElement->GetText();
CUtf8ToWide T2WStatus(strStatus.c_str());
weatherInfo.weather = T2WStatus.wc_str();

TiXmlElement* tmp1Element = weatherElement->FirstChildElement("temperature1");//temperature1 温度1
string strTmp1 = tmp1Element->GetText();

TiXmlElement* tmp2Element = weatherElement->FirstChildElement("temperature2");//temperature2 温度2
const char* pTmp2 = tmp2Element->GetText();
string strTmp2;
if(NULL != pTmp2)
{
strTmp2  = pTmp2;
}

int Tmp1 = -100;
if (strTmp1.empty() != true)
{
Tmp1 = atoi(strTmp1.c_str());
}
int Tmp2 = -100;
if (strTmp2.empty() != true)
{
Tmp2 = atoi(strTmp2.c_str());
}

if (Tmp1 == -100 && Tmp2 == -100)
{
weatherInfo.temp1 = _T("");
weatherInfo.temp2 = _T("");
}
else if ( Tmp1 == -100 && Tmp2 != -100)
{
CUtf8ToWide T2WTmp2(strTmp2.c_str());
weatherInfo.temp1 = T2WTmp2.wc_str();
weatherInfo.temp2 = T2WTmp2.wc_str();
}
else if ( Tmp1 != -100 && Tmp2 == -100)
{
CUtf8ToWide T2WTmp1(strTmp1.c_str());
weatherInfo.temp1 = T2WTmp1.wc_str();
weatherInfo.temp2 = T2WTmp1.wc_str();
}
else if (Tmp1 <=  Tmp2)
{
CUtf8ToWide T2WTmp1(strTmp1.c_str());
weatherInfo.temp1 = T2WTmp1.wc_str();
CUtf8ToWide T2WTmp2(strTmp2.c_str());
weatherInfo.temp2 = T2WTmp2.wc_str();
}
else
{
CUtf8ToWide T2WTmp1(strTmp1.c_str());
weatherInfo.temp2 = T2WTmp1.wc_str();
CUtf8ToWide T2WTmp2(strTmp2.c_str());
weatherInfo.temp1 = T2WTmp2.wc_str();
}

TiXmlElement* directionElement = weatherElement->FirstChildElement("direction1"); //direction1 风向
string strDirection = directionElement->GetText();
CUtf8ToWide T2WDirection(strDirection.c_str());
weatherInfo.WD = T2WDirection.wc_str();

TiXmlElement* powerElement = weatherElement->FirstChildElement("power1");//power1 风力
string strPower = powerElement->GetText();
CUtf8ToWide T2WPower(strPower.c_str());
weatherInfo.WS = T2WPower.wc_str();

return true;
}

OPERATEINFO CHCQueryInfo::CreatMapping(TCHAR szMappingName[], TCHAR szSemName[], int size)
{
HANDLE hMapFile;
OPERATEINFO operateInfo = {NULL, NULL};

hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE,    // use paging file
NULL,                    // default security
PAGE_READWRITE,          // read/write access
0,                       // maximum object size (high-order DWORD)
size,                // maximum object size (low-order DWORD)
szMappingName);                 // name of mapping object

if (NULL == hMapFile)
{
//WriteLog("Could not create file mapping object (%d).\n",GetLastError());;
return operateInfo;
}

operateInfo.pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
size);

if (operateInfo.pBuf == NULL)
{
//WriteLog("Could not map view of file (%d).\n",GetLastError());
CloseHandle(hMapFile);
return operateInfo;
}

operateInfo.hSemaphore = CreateSemaphore(NULL, 0, 1, szSemName);
if ( NULL == operateInfo.hSemaphore)
{
//WriteLog("CreateSemaphore error: %d\n", GetLastError());
return operateInfo;
}

return operateInfo;
}

void CHCQueryInfo::StartServer()
{
WCHAR szExe[] = _T("\\StorageCard\\TOOL\\3.5FW\\NetworkService.exe");
HANDLE hWaitServerRunFinish = NULL;//等待键盘加载完成事件
if (NULL==hWaitServerRunFinish)
{
hWaitServerRunFinish = CreateEvent(NULL, FALSE, FALSE, _T("FinishCreateServerEvnet"));
}
ResetEvent(hWaitServerRunFinish);	//防止其他程序多次设置事件,带来连锁反应
WCHAR szAppName[_MAX_PATH]={0};		// 父目录的路径, 最后不带"\"
WCHAR szServerPath[_MAX_PATH]={0};
WCHAR * pLastSlash;
GetModuleFileNameW(NULL, szAppName, _MAX_PATH);
pLastSlash = wcsrchr(szAppName, _T('\\'));
if (pLastSlash != NULL)
pLastSlash[1] = _T('\0');
wsprintf(szServerPath,_T("%sNetworkService.exe"),szAppName);
PROCESS_INFORMATION liProcessInfo;

DWORD Time=GetTickCount();
CreateProcess(szExe,	0,NULL,NULL,false,0,NULL,NULL,NULL,&liProcessInfo);
if (hWaitServerRunFinish)
{
if(WAIT_OBJECT_0 == WaitForSingleObject(hWaitServerRunFinish, 5000))
{
RETAILMSG(1, (_T("-----------wait Sever run OK---------\n")));
}
else
{
RETAILMSG(1, (_T("-----------wait Sever run time out 5 s---------\n")));
}
RETAILMSG(1,(TEXT("_________KY_______Creagte Time=%d\r\n"),GetTickCount()-Time));
}
}

void CHCQueryInfo::secondToDate(UINT nSeconds, HCString &strDate)
{
UINT myear,mday,oday;
UINT  msec;
UINT ttmonth[12]={
31,28,31,30,31,30,
31,31,30,31,30,31
};
mday=nSeconds/(24*3600);
msec=nSeconds-mday*(24*3600);
myear=mday/365;
oday=mday-myear*365-(myear+1)/4;
int y, i=0;
UINT iimoth;
y=(1970+myear);
iimoth=((y%4==0)&&(y%100!=0))||(y%400==0);
for(i=0;i<12;i++)
{
if((y=oday-ttmonth[i])>0)
oday-=ttmonth[i]+(i==1?iimoth:0);
else
break;

}
UINT iday=oday+2;
UINT imonth=i+1;
UINT iyear=1900+myear;
UINT ihour=msec/3600;
UINT imin=(msec-ihour*3600)/60;
ihour+=8;//中国8时区
UINT isec=msec%60;

TCHAR buf[20];
_stprintf(buf,_T("%04d-%02d-%02d %02d:%02d:%02d"),iyear, imonth, iday, ihour, imin, isec);
strDate = buf;
}

void CHCQueryInfo::GetDayOfWeek(HCString strDate, HCString &strDayOfWeek)
{
int flag=0,year,month,day;
CWideToMulti date(strDate.c_str());
std::string strDateTmp = date.c_str();

std::string strYear = strDateTmp.substr(0 , 4);
year = atoi(strYear.c_str());

std::string strMonth = strDateTmp.substr(5, 2);
month = atoi((strMonth.c_str()));

std::string strDay = strDateTmp.substr(8, 2);
day = atoi(strDay.c_str());

int days = 0;
days = (year - 1) * 365;
days += (year - 1) / 4;
days -= (year - 1) /100;
days += (year - 1) / 400;

switch(month - 1)
{
case 11:
days += 30;
case 10:
days += 31;
case 9:
days += 30;
case 8:
days += 31;
case 7:
days += 31;
case 6:
days += 30;
case 5:
days += 31;
case 4:
days += 30;
case 3:
days += 31;
case 2:
if(( year % 4 == 0) && year % 100 != 0 || (year % 400 == 0 ))
days += 29;
else
days += 28;
case 1:
days += 31;
}

days += day;

days %= 7;//折成星期几,若为0,则为星期天

switch(days)
{
case 0:strDayOfWeek = _T("星期天");break;
case 1:strDayOfWeek = _T("星期一");break;
case 2:strDayOfWeek = _T("星期二"); break;
case 3:strDayOfWeek = _T("星期三");break;
case 4:strDayOfWeek = _T("星期四"); break;
case 5:strDayOfWeek = _T("星期五");break;
case 6:strDayOfWeek = _T("星期六");break;
}
}

void CHCQueryInfo::GetDayOfWeekEx(UINT uDayOfWeek, HCString &strDayOfWeek)
{
switch(uDayOfWeek)
{
case 0:strDayOfWeek = _T("星期天");break;
case 1:strDayOfWeek = _T("星期一");break;
case 2:strDayOfWeek = _T("星期二"); break;
case 3:strDayOfWeek = _T("星期三");break;
case 4:strDayOfWeek = _T("星期四"); break;
case 5:strDayOfWeek = _T("星期五");break;
case 6:strDayOfWeek = _T("星期六");break;
}
}

void CHCQueryInfo::UnicodeToChinese(std::string strUnicode, HCString &strChinese)
{
std::vector<std::string> ret = tokenize(strUnicode, ";");
int size = ret.size();
if (size > 0)
{
WCHAR *buf = new WCHAR[size];
int i = 0;
for (; i <  size; ++i)
{
ret[i].replace(0, 2, "");
int num = atoi(ret[i].c_str());
buf[i] = num;
}
buf[i] = '\0';

strChinese = buf;
if ( buf != NULL )
{
delete []buf;
buf = NULL;
}
}
else
{
strChinese = _T("");
}

}


/** web.h
* 1.Declares a class to encode strings converting a String
* into a MIME format called "x-www-form-urlencoded" format.
*	To convert a String, each character is examined in turn:
*		1) The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same.
* 	2) The space character ' ' is converted into a plus sign '+'.
*		3) All other characters are converted into the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the lower 8-bits of the character.
* 2.Declares a class to decode such strings
* 3. Declares the WebForm class to wrap win32 HTTP calls
* Author: Vijay Mathew Pandyalakal
* Date: 18/10/03
**/

#ifndef WEB_H_
#define WEB_H_

#include <wininet.h>

using namespace std;

namespace openutils {

struct CHCRequestInfo{
string form_action;
HINTERNET hRequest;
};

class URLEncoder {
public:
static string encode(string str);
private:
static bool isOrdinaryChar(char c);
};

class URLDecoder {
public:
static string decode(string str);
private:
static int convertToDec(const char* hex);
static void getAsDec(char* hex);
};

class WebForm {
private:
vector<string> m_vctVars;
vector<string> m_vctVals;
string m_strHostName;
string m_strScriptFile;
HINTERNET m_hSession;
HINTERNET m_hRequest;
unsigned long m_lBytesRead;
HANDLE m_hThread;

public:
WebForm();
void putVariable(const char* var_name,const char* value);
string getVariable(const char* var_name) const;
void setHost(const char* host);
void setScriptFile(const char* sf);
string getHost() const;
string getScriptFile() const;
void sendRequest();
bool getResponse(char* buff,int sz);
unsigned long getBytesRead() { return m_lBytesRead; }
~WebForm();
private:
bool isDuplicateVar(const char* var_name);
};

class WebFormException {
private:
string err;
public:
WebFormException(const char* str) {
err = str;
}
string getMessage() {
return err;
}
};
} // openutils

#endif


/** web.cpp
* Implements classes declared in web.h
* Author: Vijay Mathew Pandyalakal
* Date: 18/10/03
**/

#include <string>
#include <vector>
using namespace std;

#include <windows.h>
#include <wininet.h>
#include <tchar.h>
#include "WideMultiChange.h"
#include <Windows.h>

#include "web.h"
using namespace openutils;

string URLEncoder::encode(string str) {
int len = str.length();
char* buff = new char[len + 1];
strcpy(buff,str.c_str());
string ret = "";
for(int i=0;i<len;i++) {
if(isOrdinaryChar(buff[i])) {
ret = ret + buff[i];
}else if(buff[i] == ' ') {
ret = ret + "+";
}else {
char tmp[6];
sprintf(tmp,"%%%x",buff[i]);
ret = ret + tmp;
}
}
delete[] buff;
return ret;
}

bool URLEncoder::isOrdinaryChar(char c) {
char ch = tolower(c);
if(ch == 'a' || ch == 'b' || ch == 'c' || ch == 'd' || ch == 'e'
|| ch == 'f' || ch == 'g' || ch == 'h' || ch == 'i' || ch == 'j'
|| ch == 'k' || ch == 'l' || ch == 'm' || ch == 'n' || ch == 'o'
|| ch == 'p' || ch == 'q' || ch == 'r' || ch == 's' || ch == 't'
|| ch == 'u' || ch == 'v' || ch == 'w' || ch == 'x' || ch == 'y'
|| ch == 'z' || ch == '0' || ch == '1' || ch == '2' || ch == '3'
|| ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8'
|| ch == '9') {
return true;
}
return false;
}

string URLDecoder::decode(string str) {
int len = str.length();
char* buff = new char[len + 1];
strcpy(buff,str.c_str());
string ret = "";
for(int i=0;i<len;i++) {
if(buff[i] == '+') {
ret = ret + " ";
}else if(buff[i] == '%') {
char tmp[4];
char hex[4];
hex[0] = buff[++i];
hex[1] = buff[++i];
hex[2] = '\0';
//int hex_i = atoi(hex);
sprintf(tmp,"%c",convertToDec(hex));
ret = ret + tmp;
}else {
ret = ret + buff[i];
}
}
delete[] buff;
return ret;
}

int URLDecoder::convertToDec(const char* hex) {
char buff[12];
sprintf(buff,"%s",hex);
int ret = 0;
int len = strlen(buff);
for(int i=0;i<len;i++) {
char tmp[4];
tmp[0] = buff[i];
tmp[1] = '\0';
getAsDec(tmp);
int tmp_i = atoi(tmp);
int rs = 1;
for(int j=i;j<(len-1);j++) {
rs *= 16;
}
ret += (rs * tmp_i);
}
return ret;
}

void URLDecoder::getAsDec(char* hex) {
char tmp = tolower(hex[0]);
if(tmp == 'a') {
strcpy(hex,"10");
}else if(tmp == 'b') {
strcpy(hex,"11");
}else if(tmp == 'c') {
strcpy(hex,"12");
}else if(tmp == 'd') {
strcpy(hex,"13");
}else if(tmp == 'e') {
strcpy(hex,"14");
}else if(tmp == 'f') {
strcpy(hex,"15");
}else if(tmp == 'g') {
strcpy(hex,"16");
}
}

DWORD WINAPI ThreadFun(LPVOID lpParam )
{
CHCRequestInfo* pRequestInfo = static_cast<CHCRequestInfo*>(lpParam);
HINTERNET hSession = InternetOpen(_T("WebForm 1"),
PRE_CONFIG_INTERNET_ACCESS,
NULL,
INTERNET_INVALID_PORT_NUMBER,
0);

if (hSession == NULL)
{
//throw WebFormException("Error:- InternetOpen()");
return -1;
}

//	CMultiToWide wideform_action(pRequestInfo->form_action.c_str());
//	CWideToUtf8  utf8form_action(wideform_action.wc_str());

pRequestInfo->hRequest = InternetOpenUrlA(hSession,
pRequestInfo->form_action.c_str(),
NULL,
0,
INTERNET_FLAG_RELOAD,
0);
if(pRequestInfo->hRequest == NULL) {
//throw WebFormException("Error:- InternetOpenUrl()");
return -1;
}

return 0;
}

WebForm::WebForm() {
string m_strContentType = "Content-Type: application/x-www-form-urlencoded";
string m_strHostName = "localhost:8080";
string m_strScriptFile = "";
HINTERNET m_hSession = NULL;
HINTERNET m_hConnect = NULL;
HINTERNET m_hRequest = NULL;
HINTERNET m_hResponse = NULL;
m_hThread = NULL;
}
void WebForm::putVariable(const char* var_name,const char* value) {
if(isDuplicateVar(var_name)) {
string str = "Duplicate variable name - ";
str = str + var_name;
throw WebFormException(str.c_str());
}else {
m_vctVars.push_back(var_name);
m_vctVals.push_back(value);
}
}

string WebForm::getVariable(const char* var_name) const {
for(int i=0;i<m_vctVars.size();i++) {
//	if(strcmpi(var_name,m_vctVars[i].c_str()) == 0) {
if(strcmp(var_name,m_vctVars[i].c_str()) == 0) {
return m_vctVals[i];
}
}
string str = "Variable not found - ";
str = str + var_name;
throw WebFormException(str.c_str());
}

void WebForm::setHost(const char* host) {
m_strHostName = host;
}

void WebForm::setScriptFile(const char* sf) {
m_strScriptFile = sf;
}

string WebForm::getHost() const {
return m_strHostName;
}

string WebForm::getScriptFile() const {
return m_strScriptFile;
}

void WebForm::sendRequest() {

string host = m_strHostName;
string form_action = host + m_strScriptFile + "?";
int sz = m_vctVars.size();
for(int i=0;i<sz;i++) {
string var = m_vctVars[i];
string enc_var = URLEncoder::encode(var);
string val = m_vctVals[i];
//  string enc_val = URLEncoder::encode(val);
form_action = form_action + enc_var;
form_action = form_action + "=";
form_action = form_action + val;
if(i != (sz-1)) {
form_action = form_action + "&";
}
}

m_hSession = InternetOpen(_T("WebForm 1"),
PRE_CONFIG_INTERNET_ACCESS,
NULL,
INTERNET_INVALID_PORT_NUMBER,
0);

if (m_hSession == NULL)
{
throw WebFormException("Error:- InternetOpen()");
return;
}

CMultiToWide wideform_action(form_action.c_str());
CWideToUtf8  utf8form_action(wideform_action.wc_str());
m_hRequest = InternetOpenUrlA(m_hSession,
utf8form_action.c_str(),
NULL,
0,
INTERNET_FLAG_RELOAD,
0);
if(m_hRequest == NULL) {
throw WebFormException("Error:- InternetOpenUrl()");
return;
}

//CHCRequestInfo requestInfo;
//requestInfo.form_action = form_action;

//if (NULL == m_hThread )
//{
//	 m_hThread = CreateThread( NULL, 0, ThreadFun, static_cast<LPVOID>(&requestInfo), 0, NULL);
//}

//if ( WAIT_TIMEOUT == WaitForSingleObject(m_hThread, 3000))
//{
//	throw WebFormException("Error:- TimeOut");
//	return;
//}

//m_hRequest = requestInfo.hRequest;
// 	if (m_hSession == NULL)
// 	{
// 		throw WebFormException("Error:- InternetOpen()");
// 		return;
// 	}
//
//  	CMultiToWide wideform_action(form_action.c_str());
//  	m_hRequest = InternetOpenUrl(m_hSession,
//                                  wideform_action.wc_str(),
//                                  NULL,
//                                  0,
//                                  INTERNET_FLAG_RELOAD,
//                                  0);
//  	if(m_hRequest == NULL) {
//  		throw WebFormException("Error:- InternetOpenUrl()");
//  		return;
//  	}

}

bool WebForm::getResponse(char* buff,int sz) {

if(m_hRequest == NULL) {
throw WebFormException("No request made to server !");
return false;
}

BOOL bRecv = TRUE;
DWORD dwTotalRecved = 0;
DWORD dwRecv = 0;
char szBuff[100] = {0};

while (1)
{
bRecv = InternetReadFile(m_hRequest, buff + dwTotalRecved, sz - dwTotalRecved, &dwRecv);

if (dwRecv > 0)
{
dwTotalRecved += dwRecv;
}

if (0 == dwRecv)
{
break;
}
}

return true;

//	if(m_hRequest == NULL) {
//		throw WebFormException("No request made to server !");
//		return false;
//	}

//BOOL bRecv = TRUE;
//DWORD dwTotalRecved = 0;
//DWORD dwRecv = 0;
//char szBuff[100] = {0};

//	while (1)
//{
//	bRecv = InternetReadFile(m_hRequest, szBuff, sizeof(szBuff), &dwRecv);

//		if (dwRecv > 0)
//		{
//		memcpy(buff + dwTotalRecved, szBuff, dwRecv);
//		dwTotalRecved += dwRecv;
//		}

//	if (0 == dwRecv)
//	{
//		break;
//	}
//	}

//	return true;
}

bool WebForm::isDuplicateVar(const char* var_name) {
for(int i=0;i<m_vctVars.size();i++) {
//		if(strcmpi(var_name,m_vctVars[i].c_str()) == 0) {
if(strcmp(var_name,m_vctVars[i].c_str()) == 0) {
return true;
}
}
return false;
}

WebForm::~WebForm() {
if(m_hSession != NULL) InternetCloseHandle(m_hSession);
if(m_hRequest != NULL) InternetCloseHandle(m_hRequest);
if (m_hThread != NULL)
{
CloseHandle(m_hThread);
m_hThread = NULL;
}
}


#pragma once

class CWideToMulti
{
public:
// m_nLength包括末尾的'\0'
CWideToMulti(const wchar_t* szWideChar)
{
m_nLength = WideCharToMultiByte(CP_ACP, 0, szWideChar, -1, NULL, 0, NULL, NULL);
m_pszMultiChar = new char[m_nLength];
memset(m_pszMultiChar, 0, sizeof(char) * m_nLength);
WideCharToMultiByte(CP_ACP, 0, szWideChar, -1, m_pszMultiChar, m_nLength, NULL, NULL);
}

// m_nLength不包括末尾的'\0',cchWideChar是该宽字节字符串的字符数
CWideToMulti(const wchar_t* szWideChar, int cchWideChar)
{
m_nLength = WideCharToMultiByte(CP_ACP, 0, szWideChar, cchWideChar, NULL, 0, NULL, NULL);
m_pszMultiChar = new char[m_nLength + 1];
memset(m_pszMultiChar, 0, sizeof(char) * (m_nLength + 1));
WideCharToMultiByte(CP_ACP, 0, szWideChar, cchWideChar, m_pszMultiChar, m_nLength, NULL, NULL);
}

~CWideToMulti(void) { delete[] m_pszMultiChar; m_pszMultiChar = NULL; }

const char* c_str(void) { return m_pszMultiChar; }

unsigned long length(void) { return m_nLength; }

protected:
char* m_pszMultiChar;
unsigned long m_nLength;
};

class CMultiToWide
{
public:
// m_nLength包括末尾的'\0'
CMultiToWide(const char* szMultiChar)
{
m_nLength = MultiByteToWideChar(CP_ACP, 0, szMultiChar, -1, NULL, 0);
m_pszWideChar = new wchar_t[m_nLength];
memset(m_pszWideChar, 0, sizeof(wchar_t) * m_nLength);
MultiByteToWideChar(CP_ACP, 0, szMultiChar, -1, m_pszWideChar, m_nLength);
}

// m_nLength包括末尾的'\0',cbMultiChar是多字节字符串的字节数
CMultiToWide(const char* szMultiChar, int cbMultiChar)
{
m_nLength = MultiByteToWideChar(CP_ACP, 0, szMultiChar, cbMultiChar, NULL, 0);
m_pszWideChar = new wchar_t[m_nLength + 1];
memset(m_pszWideChar, 0, sizeof(wchar_t) * (m_nLength + 1));
MultiByteToWideChar(CP_ACP, 0, szMultiChar, cbMultiChar, m_pszWideChar, m_nLength);
}

~CMultiToWide(void) { delete[] m_pszWideChar; m_pszWideChar = NULL; }

const wchar_t* wc_str(void) { return m_pszWideChar; }

unsigned long length(void) { return m_nLength; }

protected:
wchar_t* m_pszWideChar;
unsigned long m_nLength;
};

class CWideToUtf8
{
public:
// m_nLength包括末尾的'\0'
CWideToUtf8(const wchar_t* szWideChar)
{
m_nLength = WideCharToMultiByte(CP_UTF8, 0, szWideChar, -1, NULL, 0, NULL, NULL);
m_pszMultiChar = new char[m_nLength];
memset(m_pszMultiChar, 0, sizeof(char) * m_nLength);
WideCharToMultiByte(CP_UTF8, 0, szWideChar, -1, m_pszMultiChar, m_nLength, NULL, NULL);
}

// m_nLength不包括末尾的'\0',cchWideChar是该宽字节字符串的字符数
CWideToUtf8(const wchar_t* szWideChar, int cchWideChar)
{
m_nLength = WideCharToMultiByte(CP_UTF8, 0, szWideChar, cchWideChar, NULL, 0, NULL, NULL);
m_pszMultiChar = new char[m_nLength + 1];
memset(m_pszMultiChar, 0, sizeof(char) * (m_nLength + 1));
WideCharToMultiByte(CP_UTF8, 0, szWideChar, cchWideChar, m_pszMultiChar, m_nLength, NULL, NULL);
}

~CWideToUtf8(void) { delete[] m_pszMultiChar; m_pszMultiChar = NULL; }

const char* c_str(void) { return m_pszMultiChar; }

unsigned long length(void) { return m_nLength; }

protected:
char* m_pszMultiChar;
unsigned long m_nLength;
};

class CUtf8ToWide
{
public:
// m_nLength包括末尾的'\0'
CUtf8ToWide(const char* szMultiChar)
{
m_nLength = MultiByteToWideChar(CP_UTF8, 0, szMultiChar, -1, NULL, 0);
m_pszWideChar = new wchar_t[m_nLength];
memset(m_pszWideChar, 0, sizeof(wchar_t) * m_nLength);
MultiByteToWideChar(CP_UTF8, 0, szMultiChar, -1, m_pszWideChar, m_nLength);
}

// m_nLength包括末尾的'\0',cbMultiChar是多字节字符串的字节数
CUtf8ToWide(const char* szMultiChar, int cbMultiChar)
{
m_nLength = MultiByteToWideChar(CP_UTF8, 0, szMultiChar, cbMultiChar, NULL, 0);
m_pszWideChar = new wchar_t[m_nLength + 1];
memset(m_pszWideChar, 0, sizeof(wchar_t) * (m_nLength + 1));
MultiByteToWideChar(CP_UTF8, 0, szMultiChar, cbMultiChar, m_pszWideChar, m_nLength);
}

~CUtf8ToWide(void) { delete[] m_pszWideChar; m_pszWideChar = NULL; }

const wchar_t* wc_str(void) { return m_pszWideChar; }

unsigned long length(void) { return m_nLength; }

protected:
wchar_t* m_pszWideChar;
unsigned long m_nLength;
};


#ifndef DEFINE_H
#define DEFINE_H

#include <string>
#include <vector>

#ifdef UNICODE
typedef std::wstring HCString;
#else
typedef std::string HCString;
#endif

typedef struct _cityInfo
{
HCString section;
HCString name;
HCString code;
HCString time1;    //系统时间
HCString time2;    //保留
HCString dayOfWeek1;
HCString weather1;
HCString temp11;
HCString temp21;
HCString WD1;
HCString WS1;
HCString dayOfWeek2;
HCString weather2;
HCString temp12;
HCString temp22;
HCString WD2;
HCString WS2;
HCString dayOfWeek3;
HCString weather3;
HCString temp13;
HCString temp23;
HCString WD3;
HCString WS3;
HCString dayOfWeek4;
HCString weather4;
HCString temp14;
HCString temp24;
HCString WD4;
HCString WS4;
HCString dayOfWeek5;
HCString weather5;
HCString temp15;
HCString temp25;
HCString WD5;
HCString WS5;
HCString dayOfWeek6;
HCString weather6;
HCString temp16;
HCString temp26;
HCString WD6;
HCString WS6;
HCString dayOfWeek7;
HCString weather7;
HCString temp17;
HCString temp27;
HCString WD7;
HCString WS7;

}CITYINFO, *PCITYINFO;

typedef std::vector<CITYINFO> CITYINFOVEC;

typedef struct _weatherInfo
{
HCString data;               //日期      格式:2014-06-06
HCString dayOfWeek;          //星期几
HCString weather;            //天气情况,喻:雷阵雨,晴,阴
HCString temp1;              //最低温度
HCString temp2;              //最高温度
HCString WD;                 //风向, 喻:东风,东南方,南风,西北风
HCString WS;                 //风力, 喻:3~4级

_weatherInfo()
{
data = _T("");
dayOfWeek = _T("");
weather = _T("");
temp1 = _T("");
temp2 = _T("");
WD = _T("");
WS = _T("");
}
}WEATHERINFO, *PWEATHERINFO;

typedef std::vector<WEATHERINFO> WEATHERINFOVEC;

#endif;


#ifndef YSSTIME_H
#define YSSTIME_H
#include <windef.h>
#include <TCHAR.H>
#include <winsock.h>
#include "define.h"

#define UNICODE
#define _UNICODE

#define _countof(array) (sizeof(array)/sizeof(array[0]))
#define HIGHTIME		21968699 // 21968708 // Jan 1, 1900 FILETIME.highTime
#define LOWTIME			4259332096 // 1604626432 // Jan 1, 1900 FILETIME.lowtime

////NTP服务器列表
//struct NISTSVR{
//	int     key;	//编号
//	in_addr addr;	//IP地址
//	LPCTSTR server;	//域名
//	LPCTSTR info;	//信息
//} NISTSVRSARY[] = {
//	{ 0, {0,0,0,0}, NULL, NULL},
//	{ 1, {129,6,15,28}, _T("time-a.nist.gov"),_T("NIST,盖士堡,马里兰州") },
//	{ 2, {129,6,15,29}, _T("time-b.nist.gov"),_T("NIST,盖士堡,马里兰州") },
//	{ 3, {132,163,4,101}, _T("time-a.timefreq.bldrdoc.gov"),_T("NIST,博耳德市,科罗拉多州") },
//	{ 4, {132,163,4,102}, _T("time-b.timefreq.bldrdoc.gov"),_T("NIST,博耳德市,科罗拉多州") },
//	{ 5, {132,163,4,103}, _T("time-c.timefreq.bldrdoc.gov"),_T("NIST,博耳德市,科罗拉多州") },
//	{ 6, {128,138,140,44}, _T("tutcnist.colorado.edu"),_T("科罗拉多大学,博耳德市") },
//	{ 7, {192,43,244,18}, _T("time.nist.gov"),_T("NCAR,博耳德市,科罗拉多州") },
//	{ 8, {131,107,1,10}, _T("time-nw.nist.gov"),_T("Microsoft,雷蒙德,华盛顿州") },
//	{ 9, {208,184,49,129}, _T("nist1.nyc.certifiedtime.com"),_T("Abovnet,纽约市") },
//};
////所选择的NTP服务器
//static int choice = 0;

class CHCSysTime
{
public:
CHCSysTime();
~CHCSysTime();
void GetCurrentTime(HCString &strCurrentTime);
BOOL SetSysTime();

private:
BOOL UpdateSysTime(DWORD dwTime);
BOOL GetTimeFromServer(DWORD *lpdwTime);

};
#endif


#include "SysTime.h"
#pragma comment (lib,"ws2")
//#pragma comment (lib,"winsock")

CHCSysTime::CHCSysTime()
{

}

CHCSysTime::~CHCSysTime()
{

}

void CHCSysTime::GetCurrentTime(HCString &strCurrentTime)
{
SYSTEMTIME sys;
GetLocalTime( &sys );
TCHAR buf[20];
_stprintf(buf,_T("%04d-%02d-%02d %02d:%02d:%02d"),sys.wYear,sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond);
strCurrentTime = buf;
}

BOOL CHCSysTime::SetSysTime()
{
//  	WSADATA WSAData;
//  	if(WSAStartup (MAKEWORD(1,1), &WSAData) != 0)
//  	{
//  		WSACleanup();
//  		return FALSE;
//  	}

//取服务器时间
DWORD dwTime;
BOOL bReturn = FALSE;
if (GetTimeFromServer(&dwTime))
{
//更新系统时间
if (UpdateSysTime(dwTime))
{
bReturn = TRUE;
}else{
bReturn = FALSE;
}
}

WSACleanup();

return bReturn;
}

BOOL CHCSysTime::UpdateSysTime(DWORD dwTime)
{
UINT64 uiCurTime, uiBaseTime, uiResult;
SYSTEMTIME st;

uiBaseTime = ((UINT64) HIGHTIME << 32) + LOWTIME;

uiCurTime = (UINT64)dwTime * (UINT64)10000000;
uiResult = uiBaseTime + uiCurTime;

FileTimeToSystemTime((LPFILETIME)&uiResult, &st);

return SetSystemTime(&st);
}

DWORD WINAPI ThreadTime(LPVOID lpParam )
{
DWORD* lpdwTime = static_cast<DWORD*>(lpParam);

DWORD dwReturn = 0;

WSADATA wsd;
if(WSAStartup(MAKEWORD(1,1),&wsd))
{
WSACleanup();
return -1;
}

SOCKET sSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(INVALID_SOCKET != sSock)
{
struct sockaddr_in sin;
in_addr addr = {129,6,15,29};

memcpy(&sin.sin_addr, &addr, sizeof(in_addr));
sin.sin_family = AF_INET;
sin.sin_port = htons(IPPORT_TIMESERVER);

if(connect(sSock,(struct sockaddr *)&sin,sizeof(struct sockaddr_in)) == 0)
{
int iResult, iRead;

for(iRead = 0; iRead < 4; iRead += iResult)
{
iResult = recv(sSock, (char*)lpdwTime + iRead, 4 - iRead, 0);
if(iResult < 1)
break;
}

if(4 == iRead)
{
*lpdwTime = ntohl(*lpdwTime);

dwReturn = 0;
}
else
{
dwReturn = -1;
}
}

closesocket(sSock);
}

return dwReturn;
}

BOOL CHCSysTime::GetTimeFromServer(DWORD *lpdwTime)
{
*lpdwTime = 0;
BOOL bReturn= TRUE;

HANDLE hThread = CreateThread( NULL, 0, ThreadTime, static_cast<LPVOID>(lpdwTime), 0, NULL);

if ( WAIT_TIMEOUT == WaitForSingleObject(hThread, 3000))
{
bReturn =  FALSE;
}

return bReturn;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: