Beispiel #1
0
void CThermosmart::SetPauseStatus(const bool bIsPause)
{
	if (m_bDoLogin)
	{
		if (!Login())
			return;
	}

	std::string szPostdata = "{\"pause\":";
	szPostdata += (bIsPause) ? "true" : "false";
	szPostdata += "}";

	std::vector<std::string> ExtraHeaders;
	ExtraHeaders.push_back("Content-Type: application/json");
	std::string sResult;

	std::string sURL = THERMOSMART_SET_PAUZE;
	stdreplace(sURL, "[TID]", m_ThermostatID);
	stdreplace(sURL, "[access_token]", m_AccessToken);

	if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error setting Pause status!");
		m_bDoLogin = true;
		return;
	}
}
Beispiel #2
0
void CThermosmart::SetOutsideTemp(const float temp)
{
	if (m_bDoLogin)
	{
		if (!Login())
			return;
	}

	char szTemp[20];
	sprintf(szTemp, "%.1f", temp);
	std::string sTemp = szTemp;

	std::string szPostdata = "outside_temperature=" + sTemp;
	std::vector<std::string> ExtraHeaders;
	std::string sResult;

	std::string sURL = THERMOSMART_SETPOINT_PATH;
	stdreplace(sURL, "[TID]", m_ThermostatID);
	stdreplace(sURL, "[access_token]", m_AccessToken);
	if (!HTTPClient::PUT(sURL, szPostdata, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error setting thermostat data!");
		m_bDoLogin = true;
		return;
	}
}
Beispiel #3
0
void CThermosmart::SetPauseStatus(const bool bIsPause)
{
	if (m_bDoLogin)
	{
		if (!Login())
			return;
	}
	std::string sURL;
	std::stringstream sstr;
	std::string pState = (bIsPause == true) ? "true" : "false";
	sstr << "pause=" << pState;
	std::string szPostdata = sstr.str();
	std::vector<std::string> ExtraHeaders;
	std::string sResult;

	sURL = THERMOSMART_SET_PAUZE;
	stdreplace(sURL, "[TID]", m_ThermostatID);
	stdreplace(sURL, "[access_token]", m_AccessToken);

	if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error setting Pause status!");
		m_bDoLogin = true;
		return;
	}
}
std::string CNotificationHelper::ParseCustomMessage(const std::string &cMessage, const std::string &sName, const std::string &sValue)
{
	std::string ret = cMessage;
	stdreplace(ret, "$name", sName);
	stdreplace(ret, "$value", sValue);
	return ret;
}
Beispiel #5
0
void CYouLess::GetMeterDetails()
{
	std::string sResult;

	char szURL[200];

	if(m_Password.size() == 0)
	{
		sprintf(szURL,"http://%s:%d/a",m_szIPAddress.c_str(), m_usIPPort);
	}
	else
	{
		sprintf(szURL,"http://%s:%d/a&w=%s",m_szIPAddress.c_str(), m_usIPPort, m_Password.c_str());
	}

	if (!HTTPClient::GET(szURL,sResult))
	{
		_log.Log(LOG_ERROR,"YouLess: Error connecting to: %s", m_szIPAddress.c_str());
		return;
	}

	std::vector<std::string> results;
	StringSplit(sResult, "\n", results);
	if (results.size()<2)
	{
		_log.Log(LOG_ERROR,"YouLess: Error connecting to: %s", m_szIPAddress.c_str());
		return;
	}
	int fpos;
	std::string pusage=stdstring_trim(results[0]);
	fpos=pusage.find_first_of(" ");
	if (fpos!=std::string::npos)
		pusage=pusage.substr(0,fpos);
	stdreplace(pusage,",","");

	std::string pcurrent=stdstring_trim(results[1]);
	fpos=pcurrent.find_first_of(" ");
	if (fpos!=std::string::npos)
		pcurrent=pcurrent.substr(0,fpos);
	stdreplace(pcurrent,",","");

	m_meter.powerusage=atol(pusage.c_str());
	m_meter.usagecurrent=atol(pcurrent.c_str());
	sDecodeRXMessage(this, (const unsigned char *)&m_meter);//decode message
}
Beispiel #6
0
std::string CNotificationBase::MakeHtml(const std::string &txt)
{
	std::string sRet = txt;

	stdreplace(sRet, "&", "&amp;");
	stdreplace(sRet, "\"", "&quot;");
	stdreplace(sRet, "'", "&apos;");
	stdreplace(sRet, "<", "&lt;");
	stdreplace(sRet, ">", "&gt;");
	stdreplace(sRet, "\r\n", "<br/>");
	return sRet;
}
Beispiel #7
0
void CHardwareMonitor::RunWMIQuery(const char* qTable, const std::string &qType)
{
	if ((m_pServicesOHM == NULL) || (m_pServicesSystem == NULL))
		return;
	HRESULT hr;
	int dindex = 0;
	std::string query = "SELECT * FROM ";
	query.append(qTable);
	query.append(" WHERE SensorType = '");
	query.append(qType);
	query.append("'");
	IEnumWbemClassObject* pEnumerator = NULL; 
	hr = m_pServicesOHM->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (!FAILED(hr))
	{
		// Get the data from the query
		IWbemClassObject *pclsObj = NULL;
		while (pEnumerator)
		{
			ULONG uReturn = 0;
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if (FAILED(hr) || (0 == uReturn))
			{
				break;
			}

			VARIANT vtProp;

			hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
			if (SUCCEEDED(hr))
			{
				std::string itemName = _bstr_t(vtProp.bstrVal);
				stdreplace(itemName, "#", "");
				VariantClear(&vtProp);

				hr = pclsObj->Get(L"Value", 0, &vtProp, 0, 0);
				if (SUCCEEDED(hr))
				{
					float fItemValue = float(vtProp.fltVal);
					std::ostringstream itemValue;
					if ((qType == "Load") || (qType == "Temperature")) {
						itemValue.precision(3);
					}
					itemValue << fItemValue;
					VariantClear(&vtProp);

					//hr = pclsObj->Get(L"InstanceId", 0, &vtProp, 0, 0);
					hr = pclsObj->Get(L"Identifier", 0, &vtProp, 0, 0); // instance id seems to drift
					if (SUCCEEDED(hr))
					{
						std::string itemId = _bstr_t(vtProp.bstrVal);
						if (itemId.find("/hdd") != std::string::npos)
						{
							itemName = itemId + " " + itemName;
						}
						//itemId = "WMI"+itemId;
						//_log.Log(LOG_NORM, "Hardware Monitor: %s, %s, %s",itemId.c_str(), itemName.c_str(),itemValue.str().c_str());
						UpdateSystemSensor(qType, dindex, itemName, itemValue.str());
						VariantClear(&vtProp);
						dindex++;
					}
				}
			}
			pclsObj->Release();
		}
		pEnumerator->Release();
	}
}
Beispiel #8
0
void CThermosmart::GetMeterDetails()
{
	if (m_UserName.empty() || m_Password.empty() )
		return;
	std::string sResult;
#ifdef DEBUG_ThermosmartThermostat_read
	sResult = ReadFile("E:\\thermosmart_getdata.txt");
#else	
	if (m_bDoLogin)
	{
		if (!Login())
			return;
	}
	std::string sURL = THERMOSMART_ACCESS_PATH;
	stdreplace(sURL, "[TID]", m_ThermostatID);
	stdreplace(sURL, "[access_token]", m_AccessToken);
	if (!HTTPClient::GET(sURL, sResult))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error getting thermostat data!");
		m_bDoLogin = true;
		return;
	}

#ifdef DEBUG_ThermosmartThermostat
	SaveString2Disk(sResult, "E:\\thermosmart_getdata.txt");
#endif
#endif
	Json::Value root;
	Json::Reader jReader;
	bool ret = jReader.parse(sResult, root);
	if (!ret)
	{
		_log.Log(LOG_ERROR, "Thermosmart: Invalid/no data received...");
		m_bDoLogin = true;
		return;
	}

	if (root["target_temperature"].empty() || root["room_temperature"].empty())
	{
		_log.Log(LOG_ERROR, "Thermosmart: Invalid/no data received...");
		m_bDoLogin = true;
		return;
	}

	float temperature;
	temperature = (float)root["target_temperature"].asFloat();
	SendSetPointSensor(1, temperature, "target temperature");

	temperature = (float)root["room_temperature"].asFloat();
	SendTempSensor(2, 255, temperature, "room temperature");

	if (!root["outside_temperature"].empty())
	{
		temperature = (float)root["outside_temperature"].asFloat();
		SendTempSensor(3, 255, temperature, "outside temperature");
	}
	if (!root["source"].empty())
	{
		std::string actSource = root["source"].asString();
		bool bPauzeOn = (actSource == "pause");
		SendSwitch(1, 1, 255, bPauzeOn, 0, "Thermostat Pause");
	}
}
Beispiel #9
0
bool CThermosmart::Login()
{
	if (!m_AccessToken.empty())
	{
		Logout();
	}
	if (m_UserName.empty())
		return false;
	m_AccessToken = "";
	m_ThermostatID = "";

	std::string sURL;
	std::stringstream sstr;
	sstr << "username="******"&password="******"Thermosmart: Error login!");
			return false;
		}

#ifdef DEBUG_ThermosmartThermostat
	SaveString2Disk(sResult, "E:\\thermosmart1.txt");
#endif

	//# 2. Get Authorize Dialog
	sURL = THERMOSMART_AUTHORISE_PATH;
	stdreplace(sURL, "client123", "api-rob-b130d8f5123bf24b");
	ExtraHeaders.clear();
	if (!HTTPClient::GET(sURL, sResult))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!");
		return false;
	}

#ifdef DEBUG_ThermosmartThermostat
	SaveString2Disk(sResult, "E:\\thermosmart2.txt");
#endif

	size_t tpos = sResult.find("value=");
	if (tpos == std::string::npos)
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!, check username/password");
		return false;
	}
	sResult = sResult.substr(tpos + 7);
	tpos = sResult.find("\">");
	if (tpos == std::string::npos)
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!, check username/password");
		return false;
	}
	std::string TID = sResult.substr(0, tpos);

	//# 3. Authorize  (read out transaction_id from the HTML form received in the previous step). transaction_id prevents from XSRF attacks.
	szPostdata = "transaction_id=" + TID;
	ExtraHeaders.clear();
	sURL = THERMOSMART_DECISION_PATH;
	if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult, false))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!, check username/password");
		return false;
	}

#ifdef DEBUG_ThermosmartThermostat
	SaveString2Disk(sResult, "E:\\thermosmart3.txt");
#endif

	tpos = sResult.find("code=");
	if (tpos == std::string::npos)
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!, check username/password");
		return false;
	}
	std::string CODE = sResult.substr(tpos + 5);

	//# 4. Exchange authorization code for Access token (read out the code from the previous response)
	szPostdata = "grant_type=authorization_code&code=" + CODE + "&redirect_uri=http://clientapp.com/done";
	sURL = THERMOSMART_TOKEN_PATH;

	stdreplace(sURL, "username", "api-rob-b130d8f5123bf24b");
	stdreplace(sURL, "password", "c1d91661eef0bc4fa2ac67fd");

	if (!HTTPClient::POST(sURL, szPostdata, ExtraHeaders, sResult, false))
	{
		_log.Log(LOG_ERROR, "Thermosmart: Error login!, check username/password");
		return false;
	}

#ifdef DEBUG_ThermosmartThermostat
	SaveString2Disk(sResult, "E:\\thermosmart4.txt");
#endif

	Json::Value root;
	Json::Reader jReader;
	bool ret = jReader.parse(sResult, root);
	if (!ret)
	{
		_log.Log(LOG_ERROR, "Thermosmart: Invalid/no data received...");
		return false;
	}

	if (root["access_token"].empty()||root["thermostat"].empty())
	{
		_log.Log(LOG_ERROR, "Thermosmart: No access granted, check username/password...");
		return false;
	}

	m_AccessToken = root["access_token"].asString();
	m_ThermostatID = root["thermostat"].asString();

	_log.Log(LOG_STATUS, "Thermosmart: Login successfull!...");

	m_bDoLogin = false;
	return true;
}
Beispiel #10
0
void CSBFSpot::GetMeterDetails()
{
	if (m_SBFDataPath.size() == 0)
	{
		_log.Log(LOG_ERROR, "SBFSpot: Data path empty!");
		return;
	}
	if (m_SBFPlantName.size() == 0)
	{
		_log.Log(LOG_ERROR, "SBFSpot: Plant name empty!");
		return;
	}

	time_t atime = time(NULL);
	struct tm ltime;
	localtime_r(&atime, &ltime);

	int ActHourMin = (ltime.tm_hour * 60) + ltime.tm_min;

	int sunRise = getSunRiseSunSetMinutes(true);
	int sunSet = getSunRiseSunSetMinutes(false);

	//We only poll one hour before sunrise till one hour after sunset
	if (ActHourMin + 120 < sunRise)
		return;
	if (ActHourMin - 120 > sunSet)
		return;

	char szLogFile[256];
	char szDateStr[50];
	strcpy(szDateStr, strftime_t("%Y%m%d", atime));
	sprintf(szLogFile, "%s%s-Spot-%s.csv", strftime_t(m_SBFDataPath.c_str(), atime), m_SBFPlantName.c_str(), szDateStr);

	std::string szSeperator = ";";
	bool bHaveVersion = false;
	std::string tmpString;
	std::ifstream infile;
	std::string szLastDate = "";
	std::vector<std::string> szLastLines;
	std::vector<std::string> results;
	std::string sLine;
	infile.open(szLogFile);
	if (!infile.is_open())
	{
		if ((ActHourMin > sunRise) && (ActHourMin < sunSet))
		{
			_log.Log(LOG_ERROR, "SBFSpot: Could not open spot file: %s", szLogFile);
		}
		return;
	}
	while (!infile.eof())
	{
		getline(infile, sLine);
		sLine.erase(std::remove(sLine.begin(), sLine.end(), '\r'), sLine.end());
		if (sLine.size() != 0)
		{
			if (sLine.find("sep=") == 0)
			{
				tmpString = sLine.substr(strlen("sep="));
				if (tmpString != "")
				{
					szSeperator = tmpString;
				}
			}
			else if (sLine.find("Version CSV1") == 0)
			{
				bHaveVersion = true;
			}
			else if (bHaveVersion)
			{
				if (
					(sLine.find(";DeviceName") == std::string::npos) &&
					(sLine.find(";Watt") == std::string::npos)
					)
				{
					StringSplit(sLine, szSeperator, results);
					if (results.size() >= 30)
					{
						if (m_SBFInverter.empty() || (m_SBFInverter == results[3]))
						{
							if (szLastDate.empty() || (szLastDate != results[0]))
							{
								szLastDate = results[0];
								szLastLines.clear();
							}
							if (szLastDate == results[0])
							{
								szLastLines.push_back(sLine);
							}
						}
					}
				}
			}
		}
	}
	infile.close();

	if (szLastLines.empty())
	{
		_log.Log(LOG_ERROR, "SBFSpot: No data record found in spot file!");
		return;
	}

	if (szLastDate == m_LastDateTime)
	{
		return;
	}
	m_LastDateTime = szLastDate;

	double kWhCounter = 0;
	double Pac = 0;
	int InvIdx = 0;

	std::vector<std::string>::const_iterator itt;
	for (itt = szLastLines.begin(); itt != szLastLines.end(); ++itt)
	{
		StringSplit(*itt, szSeperator, results);

		if (results[1].size() < 1)
		{
			_log.Log(LOG_ERROR, "SBFSpot: No data record found in spot file!");
			return;
		}
		if ((results[28] != "OK") && (results[28] != "Ok"))
		{
			_log.Log(LOG_ERROR, "SBFSpot: Invalid field [28] should be OK!");
			return;
		}

		std::string szKwhCounter = results[23];
		stdreplace(szKwhCounter, ",", ".");
		kWhCounter += atof(szKwhCounter.c_str());
		std::string szPacActual = results[20];
		stdreplace(szPacActual, ",", ".");
		Pac += atof(szPacActual.c_str());

		float voltage;
		tmpString = results[16];
		stdreplace(tmpString, ",", ".");
		voltage = static_cast<float>(atof(tmpString.c_str()));
		SendVoltageSensor(0, (InvIdx * 10) + 1, 255, voltage, "Volt uac1");
		tmpString = results[17];
		stdreplace(tmpString, ",", ".");
		voltage = static_cast<float>(atof(tmpString.c_str()));
		if (voltage != 0) {
			SendVoltageSensor(0, (InvIdx * 10) + 2, 255, voltage, "Volt uac2");
		}
		tmpString = results[18];
		stdreplace(tmpString, ",", ".");
		voltage = static_cast<float>(atof(tmpString.c_str()));
		if (voltage != 0) {
			SendVoltageSensor(0, (InvIdx * 10) + 3, 255, voltage, "Volt uac3");
		}

		float percentage;
		tmpString = results[21];
		stdreplace(tmpString, ",", ".");
		percentage = static_cast<float>(atof(tmpString.c_str()));
		SendPercentageSensor((InvIdx * 10) + 1, 0, 255, percentage, "Efficiency");
		tmpString = results[24];
		stdreplace(tmpString, ",", ".");
		percentage = static_cast<float>(atof(tmpString.c_str()));
		SendPercentageSensor((InvIdx * 10) + 2, 0, 255, percentage, "Hz");
		tmpString = results[27];
		stdreplace(tmpString, ",", ".");
		percentage = static_cast<float>(atof(tmpString.c_str()));
		SendPercentageSensor((InvIdx * 10) + 3, 0, 255, percentage, "BT_Signal");

		if (results.size() >= 31)
		{
			tmpString = results[30];
			stdreplace(tmpString, ",", ".");
			float temperature = static_cast<float>(atof(tmpString.c_str()));
			SendTempSensor((InvIdx * 10) + 1, 255, temperature, "Temperature");
		}
		InvIdx++;
	}
	//Send combined counter/pac
	if (kWhCounter != 0)
	{
		double LastUsage = 0;
		double LastTotal = 0;
		if (GetMeter(0, 1, LastUsage, LastTotal))
		{
			if (kWhCounter < (int)(LastTotal * 100) / 100)
			{
				_log.Log(LOG_ERROR, "SBFSpot: Actual KwH counter (%f) less then last Counter (%f)!", kWhCounter, LastTotal);
				return;
			}
		}
		SendMeter(0, 1, Pac / 1000.0, kWhCounter, "SolarMain");
	}
}
Beispiel #11
0
void CSBFSpot::ImportOldMonthData(const unsigned long long DevID, const int Year, const int Month)
{
	if (m_SBFDataPath.size() == 0)
		return;
	if (m_SBFPlantName.size() == 0)
		return;

	int iInvOff = 1;
	char szLogFile[256];
	std::string tmpPath = m_SBFDataPath;
	std::stringstream sstr;
	sstr << Year;
	stdreplace(tmpPath, "%Y", sstr.str());
	sprintf(szLogFile, "%s%s-%04d%02d.csv", tmpPath.c_str(), m_SBFPlantName.c_str(),Year, Month);

	std::ifstream infile;
	infile.open(szLogFile);
	if (!infile.is_open())
	{
		return;
	}

	std::string tmpString;
	std::string szSeperator = "";
	std::vector<std::string> results;
	std::string sLine;
	bool bHaveVersion = false;
	bool bHaveDefinition = false;
	size_t dayPos = std::string::npos;
	size_t monthPos = std::string::npos;
	size_t yearPos = std::string::npos;

	bool bIsSMAWebExport = false;

	while (!infile.eof())
	{
		getline(infile, sLine);
		sLine.erase(std::remove(sLine.begin(), sLine.end(), '\r'), sLine.end());
		if (sLine.size() != 0)
		{
			if (bIsSMAWebExport)
			{
				int day = atoi(sLine.substr(dayPos, 2).c_str());
				int month = atoi(sLine.substr(monthPos, 2).c_str());
				int year = atoi(sLine.substr(yearPos, 4).c_str());

				std::string szKwhCounter = sLine.substr(18);
				size_t pPos = szKwhCounter.find('.');
				if (pPos==std::string::npos)
					continue;
				szKwhCounter = szKwhCounter.substr(0, pPos);
				pPos = szKwhCounter.find(',');
				if (pPos == std::string::npos)
					szKwhCounter = "0," + szKwhCounter;
				stdreplace(szKwhCounter, ",", ".");
				double kWhCounter = atof(szKwhCounter.c_str()) * 100000;
				unsigned long long ulCounter = (unsigned long long)kWhCounter;

				//check if this day record does not exists in the database, and insert it
				std::vector<std::vector<std::string> > result;

				char szDate[40];
				sprintf(szDate, "%04d-%02d-%02d", year, month, day);

				result = m_sql.safe_query("SELECT Value FROM Meter_Calendar WHERE (DeviceRowID==%llu) AND (Date=='%q')", DevID, szDate);
				if (result.size() == 0)
				{
					//Insert value into our database
					m_sql.safe_query("INSERT INTO Meter_Calendar (DeviceRowID, Value, Date) VALUES ('%llu', '%llu', '%q')", DevID, ulCounter, szDate);
					_log.Log(LOG_STATUS, "SBFSpot Import Old Month Data: Inserting %s",szDate);
				}

			}
			else if (sLine.find("Time,Energy (Wh)") == 0)
			{
				dayPos = 0;
				monthPos = 3;
				yearPos = 6;
				bIsSMAWebExport = true;
				continue;
			}
			else if (sLine.find("sep=") == 0)
			{
				tmpString = sLine.substr(strlen("sep="));
				if (tmpString != "")
				{
					szSeperator = tmpString;
				}
			}
			else if (sLine.find("Version CSV1") == 0)
			{
				bHaveVersion = true;
			}
			else if (bHaveVersion)
			{
				StringSplit(sLine, szSeperator, results);
				if (results.size() == 3)
				{
					if (!bHaveDefinition)
					{
						if (results[iInvOff] == "kWh")
						{
							dayPos = results[0].find("dd");
							if (dayPos == std::string::npos)
							{
								infile.close();
								return;
							}
							monthPos = results[0].find("MM");
							yearPos = results[0].find("yyyy");
							bHaveDefinition = true;
						}
					}
					else
					{
						int day = atoi(results[0].substr(dayPos, 2).c_str());
						int month = atoi(results[0].substr(monthPos, 2).c_str());
						int year = atoi(results[0].substr(yearPos, 4).c_str());

						std::string szKwhCounter = results[iInvOff + 1];
						stdreplace(szKwhCounter, ",", ".");
						double kWhCounter = atof(szKwhCounter.c_str()) * 100000;
						unsigned long long ulCounter = (unsigned long long)kWhCounter;

						//check if this day record does not exists in the database, and insert it
						std::vector<std::vector<std::string> > result;

						char szDate[40];
						sprintf(szDate, "%04d-%02d-%02d", year, month, day);

						result = m_sql.safe_query("SELECT Value FROM Meter_Calendar WHERE (DeviceRowID==%llu) AND (Date=='%q')",
							DevID, szDate);
						if (result.size() == 0)
						{
							//Insert value into our database
							m_sql.safe_query("INSERT INTO Meter_Calendar (DeviceRowID, Value, Date) VALUES ('%llu', '%llu', '%q')",
								DevID, ulCounter, szDate);
							_log.Log(LOG_STATUS, "SBFSpot Import Old Month Data: Inserting %s", szDate);
						}
					}
				}
			}
			else if ((szSeperator != "") && (m_SBFInverter != ""))
			{
				StringSplit(sLine, szSeperator, results);
				for (size_t l = 0; l < results.size(); l++)
				{
					if (results[l] == m_SBFInverter)
						iInvOff = l;
				}
			}
		}
	}
	infile.close();
}
Beispiel #12
0
void CKodi::Do_Node_Work(const KodiNode &Node)
{
	bool			bPingOK = false;
	_eMediaStatus	nStatus = MSTAT_UNKNOWN;
	std::string		sStatus = "";

	// http://<ip_address>:8080/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetActivePlayers%22,%22id%22:1}
	//		{"id":1,"jsonrpc":"2.0","result":[{"playerid":1,"type":"video"}]}

	// http://<ip_address>:8080/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetItem%22,%22id%22:1,%22params%22:{%22playerid%22:0,%22properties%22:[%22artist%22,%22year%22,%22channel%22,%22season%22,%22episode%22]}}
	//		{"id":1,"jsonrpc":"2.0","result":{"item":{"artist":["Coldplay"],"id":25,"label":"The Scientist","type":"song","year":2002}}}

	// http://<ip_address>:8080/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetProperties%22,%22id%22:1,%22params%22:{%22playerid%22:1,%22properties%22:[%22totaltime%22,%22percentage%22,%22time%22]}}
	//		{"id":1,"jsonrpc":"2.0","result":{"percentage":22.207427978515625,"time":{"hours":0,"milliseconds":948,"minutes":15,"seconds":31},"totaltime":{"hours":1,"milliseconds":560,"minutes":9,"seconds":56}}}

	try
	{
		Json::Value root = Query(Node.IP, Node.Port, "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetActivePlayers%22,%22id%22:1}");
		if (!root.size())
			nStatus = MSTAT_OFF;
		else
		{
			bPingOK = true;
			std::string	sPlayerId;	
			if (root["result"].empty() == true)
			{
				nStatus = MSTAT_IDLE;
			}
			else if (root["result"][0]["type"].empty() == true)
			{
				nStatus = MSTAT_UNKNOWN;
			}
			else
			{
				std::string	sMedia = root["result"][0]["type"].asCString();
				if (root["result"][0]["playerid"].empty() == true)
				{
					_log.Log(LOG_ERROR, "Kodi: No PlayerID returned when player is not idle!");
					return;
				}
				if (sMedia == "video") nStatus = MSTAT_VIDEO;
				if (sMedia == "audio") nStatus = MSTAT_AUDIO;
				if (sMedia == "picture") nStatus = MSTAT_PHOTO;
				sPlayerId = SSTR((int)root["result"][0]["playerid"].asInt());
			}

			// If player is active then pick up additional details
			if (sPlayerId != "")
			{
				std::string	sTitle;
				std::string	sPercent;
				std::string	sYear;

				root = Query(Node.IP, Node.Port, "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetItem%22,%22id%22:1,%22params%22:{%22playerid%22:" + sPlayerId + ",%22properties%22:[%22artist%22,%22year%22,%22channel%22,%22showtitle%22,%22season%22,%22episode%22,%22title%22]}}");
				if (root.size())
				{
					std::string	sType;
					if (root["result"]["item"]["type"].empty() != true)
					{
						sType = root["result"]["item"]["type"].asCString();
					}

					if (sType == "song")
					{
						if (root["result"]["item"]["artist"][0].empty() != true)
						{
							sTitle = root["result"]["item"]["artist"][0].asCString();
							sTitle += " - ";
						}
					}

					if (sType == "episode")
					{
						if (root["result"]["item"]["showtitle"].empty() != true)
						{
							sTitle = root["result"]["item"]["showtitle"].asCString();
						}
						if (root["result"]["item"]["season"].empty() != true)
						{
							sTitle += " [S";
							sTitle += SSTR((int)root["result"]["item"]["season"].asInt());
						}
						if (root["result"]["item"]["episode"].empty() != true)
						{
							sTitle += "E";
							sTitle += SSTR((int)root["result"]["item"]["episode"].asInt());
							sTitle += "], ";
						}
					}

					if (sType == "channel")
					{
						if (root["result"]["item"]["channel"].empty() != true)
						{
							sTitle = root["result"]["item"]["channel"].asCString();
							sTitle += " - ";
						}
					}

					if (root["result"]["item"]["year"].empty() != true)
					{
						sYear = SSTR((int)root["result"]["item"]["year"].asInt());
						if (sYear.length() > 2) sYear = " (" + sYear + ")";
						else sYear = "";
					}

					if (root["result"]["item"]["title"].empty() != true)
					{
						std::string	sLabel = root["result"]["item"]["title"].asCString();
						if ((!sLabel.length()) && (root["result"]["item"]["label"].empty() != true))
						{
							sLabel = root["result"]["item"]["label"].asCString();
						}
						// if title is too long shorten it by removing things in brackets, followed by things after a ", "
						boost::algorithm::trim(sLabel);
						if (sLabel.length() > MAX_TITLE_LEN)
						{
							boost::algorithm::replace_all(sLabel, " - ", ", ");
						}
						while (sLabel.length() > MAX_TITLE_LEN)
						{
							int begin = sLabel.find_last_of("(");
							int end = sLabel.find_last_of(")");
							if ((std::string::npos == begin) || (std::string::npos == end) || (begin >= end)) break;
							sLabel.erase(begin, end - begin + 1);
						}
						while (sLabel.length() > MAX_TITLE_LEN)
						{
							int end = sLabel.find_last_of(",");
							if (std::string::npos == end) break;
							sLabel = sLabel.substr(0, end);
						}
						boost::algorithm::trim(sLabel);
						stdreplace(sLabel, " ,", ",");
						sLabel = sLabel.substr(0, MAX_TITLE_LEN);
						sTitle = sLabel;
					}
				}

				root = Query(Node.IP, Node.Port, "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22Player.GetProperties%22,%22id%22:1,%22params%22:{%22playerid%22:" + sPlayerId + ",%22properties%22:[%22live%22,%22percentage%22,%22speed%22]}}");
				if (root.size())
				{
					bool	bLive = root["result"]["live"].asBool();
					if (bLive) sYear = " (Live)";
					int		iSpeed = root["result"]["speed"].asInt();
					if (iSpeed == 0) nStatus = MSTAT_PAUSED;
					float	fPercent = root["result"]["percentage"].asFloat();
					if (fPercent > 1.0) sPercent = SSTR((int)round(fPercent)) + "%";
				}

				// Assemble final status
				sStatus = sTitle;
				if (sStatus.length() < (MAX_TITLE_LEN-7)) sStatus += sYear;
				if (sPercent.length() != 0) sStatus += ", " + sPercent;
			}
		}
	}
	catch (std::exception& e)
	{
		bPingOK = false;
	}
	catch (...)
	{
		bPingOK = false;
	}
	UpdateNodeStatus(Node, nStatus, sStatus, bPingOK);
	if (m_iThreadsRunning > 0) m_iThreadsRunning--;
}
Beispiel #13
0
bool CNotificationEmail::SendMessageImplementation(
	const uint64_t Idx,
	const std::string &Name,
	const std::string &Subject,
	const std::string &Text,
	const std::string &ExtraData,
	const int Priority,
	const std::string &Sound,
	const bool bFromNotification)
{
	if (bFromNotification)
	{
		if (_UseEmailInNotifications != 1) {
			return true; //we are not using email for sending notification messages
		}
	}

	SMTPClient sclient;

	std::string MessageText = Text;
	stdreplace(MessageText, "&lt;br&gt;", "<br>");
	
	std::string HtmlBody;
	
	if (Idx != 0)
	{
		HtmlBody = szHTMLMail;

		std::stringstream sstr;
		sstr << Idx;
		stdreplace(HtmlBody, "$DEVIDX", sstr.str());
		stdreplace(HtmlBody, "$DEVNAME", Name);
		stdreplace(HtmlBody, "$MESSAGE", MessageText);

		char szDate[100];
#if !defined WIN32
		// Get a timestamp
		struct timeval tv;
		gettimeofday(&tv, NULL);

		struct tm timeinfo;
		localtime_r(&tv.tv_sec, &timeinfo);

		// create a time stamp string for the log message
		snprintf(szDate, sizeof(szDate), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
			timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday,
			timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, (int)tv.tv_usec / 1000);
#else
		// Get a timestamp
		SYSTEMTIME time;
		::GetLocalTime(&time);

		// create a time stamp string for the log message
		sprintf_s(szDate, sizeof(szDate), "%04d-%02d-%02d %02d:%02d:%02d.%03d", time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond, time.wMilliseconds);
#endif
		stdreplace(HtmlBody, "$DATETIME", szDate);
	}
	else
	{
		HtmlBody = std::string("<html>\n<body>\n<b>") + MessageText + std::string("</body>\n</html>\n");
	}

	sclient.SetFrom(_EmailFrom.c_str());
	sclient.SetTo(_EmailTo.c_str());
	if (_EmailUsername != "" && _EmailPassword != "") {
		sclient.SetCredentials(_EmailUsername.c_str(), _EmailPassword.c_str());
	}
	sclient.SetServer(_EmailServer.c_str(), _EmailPort);
	sclient.SetSubject(Subject.c_str());
	sclient.SetHTMLBody(HtmlBody.c_str());
	bool bRet=sclient.SendEmail();
	if (!bRet) {
		_log.Log(LOG_ERROR, std::string("Failed to send email notification : ").c_str());
	}
	return bRet;
}
Beispiel #14
0
void CAnnaThermostat::GetMeterDetails()
{
	if (m_UserName.size() == 0)
		return;
	if (m_Password.size() == 0)
		return;
	std::string sResult;
#ifdef DEBUG_AnnaThermostat
	sResult = ReadFile("E:\\appliances.xml");
#else
	//Get Data
	std::stringstream szURL;

	if (m_Password.empty())
	{
		szURL << "http://" << m_IPAddress << ":" << m_IPPort;
	}
	else
	{
		szURL << "http://" << m_UserName << ":" << m_Password << "@" << m_IPAddress << ":" << m_IPPort;
	}
	szURL << ANNA_GET_STATUS;

	if (!HTTPClient::GET(szURL.str(), sResult))
	{
		_log.Log(LOG_ERROR, "AnnaThermostat: Error getting current state!");
		return;
	}
#endif
	if (sResult.empty())
	{
		_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
		return;
	}

	stdreplace(sResult, "\r\n", "");

	TiXmlDocument doc;
	if (doc.Parse(sResult.c_str()))
	{
		_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
		return;
	}

	TiXmlElement *pRoot;
	TiXmlElement *pAppliance, *pElem;
	TiXmlAttribute *pAttribute;
	std::string sname, tmpstr;

	pRoot = doc.FirstChildElement("appliances");
	if (!pRoot)
	{
		_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
		return;
	}
	pAppliance = pRoot->FirstChildElement("appliance");
	while (pAppliance)
	{
		TiXmlHandle hAppliance = TiXmlHandle(pAppliance);

		pElem = pAppliance->FirstChildElement("name");
		if (pElem == NULL)
		{
			_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
			return;
		}
		std::string ApplianceName=pElem->GetText();

		if ((m_ThermostatID.empty()) && (ApplianceName == "Anna"))
		{
			pAttribute = pAppliance->FirstAttribute();
			if (pAttribute != NULL)
			{
				std::string aName = pAttribute->Name();
				if (aName == "id")
				{
					m_ThermostatID = pAttribute->Value();
				}
			}
		}

		//Handle point_log
		pElem = hAppliance.FirstChild("logs").FirstChild().Element();
		if (!pElem)
		{
			_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
			return;
		}
		TiXmlHandle hLogs = TiXmlHandle(pElem);
		pElem = hAppliance.FirstChild("logs").Child("point_log", 0).ToElement();
		if (!pElem)
		{
			_log.Log(LOG_ERROR, "AnnaThermostat: Invalid data received!");
			return;
		}
		for (pElem; pElem; pElem = pElem->NextSiblingElement())
		{
			sname = GetElementChildValue(pElem, "type");
			if (sname == "temperature")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendTempSensor(1, 255, temperature, sname);
				}
			}
			else if (sname == "illuminance")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float illuminance = (float)atof(tmpstr.c_str());
					SendLuxSensor(2, 1, 255, illuminance, sname);
				}
			}
			else if (sname == "thermostat")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendSetPointSensor(3, temperature, sname);
				}
			}
			/*
			else if (sname == "intended_boiler_temperature")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendTempSensor(4, 255, temperature, sname);
				}
			}
			*/
			else if (sname == "return_water_temperature")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendTempSensor(5, 255, temperature, sname);
				}
			}
			else if (sname == "boiler_temperature")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendTempSensor(6, 255, temperature, sname);
				}
			}
			else if (sname == "maximum_boiler_temperature")
			{
				tmpstr = GetPeriodMeasurement(pElem);
				if (!tmpstr.empty())
				{
					float temperature = (float)atof(tmpstr.c_str());
					SendTempSensor(7, 255, temperature, sname);
				}
			}
		}

		pAppliance = pAppliance->NextSiblingElement("appliance");
	}
	return;
}
Beispiel #15
0
bool CNotificationHTTP::SendMessageImplementation(
	const uint64_t Idx,
	const std::string &Name,
	const std::string &Subject,
	const std::string &Text,
	const std::string &ExtraData,
	const int Priority,
	const std::string &Sound,
	const bool bFromNotification)
{
	std::string destURL = _HTTPURL;
	bool bSuccess = false;

	size_t uPos = destURL.find("://");
	if (uPos == std::string::npos)
		return false;

	char szPriority[64];
	sprintf(szPriority, "%d", Priority);

	if (destURL.find("http") == 0)
	{
		//HTTP/HTTPS
		stdreplace(destURL, "#FIELD1", CURLEncode::URLEncode(_HTTPField1));
		stdreplace(destURL, "#FIELD2", CURLEncode::URLEncode(_HTTPField2));
		stdreplace(destURL, "#FIELD3", CURLEncode::URLEncode(_HTTPField3));
		stdreplace(destURL, "#FIELD4", CURLEncode::URLEncode(_HTTPField4));
		stdreplace(destURL, "#TO", CURLEncode::URLEncode(_HTTPTo));
		stdreplace(destURL, "#SUBJECT", CURLEncode::URLEncode(Subject));
		stdreplace(destURL, "#MESSAGE", CURLEncode::URLEncode(Text));
		stdreplace(destURL, "#PRIORITY", CURLEncode::URLEncode(std::string(szPriority)));

		std::string sResult;
		if (_HTTPPostData.length() > 0)
		{
			std::vector<std::string> ExtraHeaders;
			ExtraHeaders.push_back("Content-type: " + _HTTPPostContentType);
			if (_HTTPPostHeaders.length() > 0)
			{
				std::vector<std::string> ExtraHeaders2;
				StringSplit(_HTTPPostHeaders, "\r\n", ExtraHeaders2);
				for (size_t i = 0; i < ExtraHeaders2.size(); i++)
				{
					ExtraHeaders.push_back(ExtraHeaders2[i]);
				}
			}
			std::string httpData = _HTTPPostData;
			stdreplace(httpData, "#FIELD1", _HTTPField1);
			stdreplace(httpData, "#FIELD2", _HTTPField2);
			stdreplace(httpData, "#FIELD3", _HTTPField3);
			stdreplace(httpData, "#FIELD4", _HTTPField4);
			stdreplace(httpData, "#TO", _HTTPTo);
			stdreplace(httpData, "#SUBJECT", Subject);
			stdreplace(httpData, "#MESSAGE", Text);
			stdreplace(httpData, "#PRIORITY", std::string(szPriority));
			bSuccess = HTTPClient::POST(destURL, httpData, ExtraHeaders, sResult);
		}
		else
		{
			bSuccess = HTTPClient::GET(destURL, sResult, true);
		}
		if (!bSuccess)
			_log.Log(LOG_ERROR, "HTTP: %s", sResult.c_str());
	}
	else if (destURL.find("script://") == 0)
	{
		//Script
		stdreplace(destURL, "#FIELD1", _HTTPField1);
		stdreplace(destURL, "#FIELD2", _HTTPField2);
		stdreplace(destURL, "#FIELD3", _HTTPField3);
		stdreplace(destURL, "#FIELD4", _HTTPField4);
		stdreplace(destURL, "#TO", _HTTPTo);
		stdreplace(destURL, "#SUBJECT", CURLEncode::URLDecode(Subject));
		stdreplace(destURL, "#MESSAGE", CURLEncode::URLDecode(Text));

		std::string scriptname = destURL.substr(9);
		std::string scriptparams = "";
#if !defined WIN32
		if (scriptname.find("/") != 0)
			scriptname = szUserDataFolder + "scripts/" + scriptname;
#endif
		//Add parameters
		uPos = scriptname.find(" ");
		if (uPos != std::string::npos)
		{
			scriptparams = scriptname.substr(uPos + 1);
			scriptname = scriptname.substr(0, uPos);
		}
		if (file_exist(scriptname.c_str()))
		{
			m_sql.AddTaskItem(_tTaskItem::ExecuteScript(0.2f, scriptname, scriptparams));
			bSuccess = true;
		}
	}
	return bSuccess;
}
bool CNotificationHTTP::SendMessageImplementation(const std::string &Subject, const std::string &Text, const std::string &ExtraData, const int Priority, const std::string &Sound, const bool bFromNotification)
{
	std::string destURL = _HTTPURL;
	bool bRet = false;

	size_t uPos = destURL.find("://");
	if (uPos == std::string::npos)
		return false;

	if (destURL.find("http") == 0)
	{
		//HTTP/HTTPS
		destURL = stdreplace(destURL, "#FIELD1", CURLEncode::URLEncode(_HTTPField1));
		destURL = stdreplace(destURL, "#FIELD2", CURLEncode::URLEncode(_HTTPField2));
		destURL = stdreplace(destURL, "#FIELD3", CURLEncode::URLEncode(_HTTPField3));
		destURL = stdreplace(destURL, "#FIELD4", CURLEncode::URLEncode(_HTTPField4));
		destURL = stdreplace(destURL, "#TO", CURLEncode::URLEncode(_HTTPTo));
		destURL = stdreplace(destURL, "#SUBJECT", CURLEncode::URLEncode(Subject));
		destURL = stdreplace(destURL, "#MESSAGE", CURLEncode::URLEncode(Text));
		std::string sResult;
		bRet = HTTPClient::GET(destURL, sResult);
	}
	else if (destURL.find("script://") == 0)
	{
		//Script

		destURL = stdreplace(destURL, "#FIELD1", _HTTPField1);
		destURL = stdreplace(destURL, "#FIELD2", _HTTPField2);
		destURL = stdreplace(destURL, "#FIELD3", _HTTPField3);
		destURL = stdreplace(destURL, "#FIELD4", _HTTPField4);
		destURL = stdreplace(destURL, "#TO", _HTTPTo);
		destURL = stdreplace(destURL, "#SUBJECT", CURLEncode::URLDecode(Subject));
		destURL = stdreplace(destURL, "#MESSAGE", CURLEncode::URLDecode(Text));

		std::string scriptname = "";
		std::string scriptparams = "";
#if !defined WIN32
		if (destURL.find("script:///") != std::string::npos)
			scriptname = destURL.substr(9);
		else
			scriptname = destURL.substr(8);
#else
		scriptname = destURL.substr(9);
#endif
		//Add parameters
		uPos = scriptname.find(" ");
		if (uPos != std::string::npos)
		{
			scriptparams = scriptname.substr(uPos + 1);
			scriptname = scriptname.substr(0, uPos);
		}
		if (file_exist(scriptname.c_str()))
		{
			m_sql.AddTaskItem(_tTaskItem::ExecuteScript(1, scriptname, scriptparams));
			bRet = true;
		}
	}
	return bRet;
}