Exemplo n.º 1
0
int nonlinHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;
	int logglin, loglfl;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

  /* Flags to record whether GLINCORR and LFLGCORR was performed */
	logglin = 0;
  loglfl = 0;

	if (!OmitStep (acs->glincorr))
    if (UpdateSwitch ("GLINCORR", acs->glincorr, phdr, &logglin))
      return (status);

	if (!OmitStep (acs->lflgcorr))
    if (UpdateSwitch ("LFLGCORR", acs->lflgcorr, phdr, &loglfl))
      return (status);

  /* If either was performed, then record in History comments
   WJH  27 July 1999
   */
	if (logglin || loglfl)
    if (TabHistory (&acs->mlin, phdr))
      return (status);

	return (status);
}
Exemplo n.º 2
0
int flashHistory (ACSInfo *acs, Hdr *phdr) {

    extern int status;

    int logit;  /* true if we should log file name */
    int OmitStep (int);
    int ImgHistory (const RefImage *, Hdr *);
    int UpdateSwitch (char *, int, Hdr *, int *);

    if (OmitStep (acs->flashcorr))
        return (status);

    if (UpdateSwitch ("FLSHCORR", acs->flashcorr, phdr, &logit))
        return (status);

    if (logit) {
        if (acs->pctecorr == PERFORM) {
            if (ImgHistory (&acs->flashcte, phdr))
                return (status);
        } else {
            if (ImgHistory (&acs->flash, phdr))
                return (status);
	}
    }

    return (status);
}
Exemplo n.º 3
0
bool CHarmonyHub::UpdateActivities()
{
	if(SubmitCommand(m_commandcsocket, m_szAuthorizationToken, GET_CONFIG_COMMAND, "", "") == 1)
	{
		_log.Log(LOG_ERROR,"Harmony Hub: Get activities failed");
		return false;
	}

	std::map< std::string, std::string> mapActivities;
	std::vector< Device > vecDevices;
	if(ParseConfiguration(m_szResultString, mapActivities, vecDevices) == 1)
	{
		_log.Log(LOG_ERROR,"Harmony Hub: Parse activities and devices failed");
		return false;
	}

	std::map< std::string, std::string>::iterator it = mapActivities.begin();
	std::map< std::string, std::string>::iterator ite = mapActivities.end();
	int cnt=0;
	for(; it != ite; ++it)
	{
		UpdateSwitch(cnt++, it->first.c_str(), strcmp(m_szCurActivityID.c_str(), it->first.c_str())==0, it->second);
		/*m_szResultString.append(it->first);
		m_szResultString.append(" - ");
		m_szResultString.append(it->second);
		m_szResultString.append("\n");*/

	}
	return true;
}
Exemplo n.º 4
0
void CHarmonyHub::CheckSetActivity(const std::string &activityID, const bool on)
{
	//get the device id from the db (if alread inserted)
	int actId=atoi(activityID.c_str());
	std::stringstream hexId ;
	hexId << std::setw(7)  << std::hex << std::setfill('0') << std::uppercase << (int)( actId) ;
	std::string actHex = hexId.str();
	std::vector<std::vector<std::string> > result;
	result = m_sql.safe_query("SELECT Name,DeviceID FROM DeviceStatus WHERE (HardwareID==%d) AND (DeviceID=='%q')", m_HwdID, actHex.c_str());
	if (result.size() > 0) //if not yet inserted, it will be inserted active upon the next check of the activities list
	{
		UpdateSwitch(atoi(result[0][1].c_str()), activityID.c_str(),on,result[0][0]);
	}
}
Exemplo n.º 5
0
int fluxHistory (WF3Info *wf3, Hdr *phdr) {

	extern int status;
	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->fluxcorr))
	    return (status);

	if (UpdateSwitch ("FLUXCORR", wf3->fluxcorr, phdr, &logit))
	    return (status);

	return (status);
}
Exemplo n.º 6
0
bool CToonThermostat::ParseDeviceStatusData(const Json::Value &root)
{
	//ZWave Devices
	if (root["deviceStatusInfo"].empty())
		return false;

	if (root["deviceStatusInfo"]["device"].empty())
		return false;

	int totDevices = root["deviceStatusInfo"]["device"].size();
	for (int ii = 0; ii < totDevices; ii++)
	{
		std::string deviceName = root["deviceStatusInfo"]["device"][ii]["name"].asString();
		std::string uuid = root["deviceStatusInfo"]["device"][ii]["devUUID"].asString();
		int state = root["deviceStatusInfo"]["device"][ii]["currentState"].asInt();

		int Idx;
		if (!GetUUIDIdx(uuid, Idx))
		{
			if (!AddUUID(uuid, Idx))
			{
				_log.Log(LOG_ERROR, "ToonThermostat: Error adding UUID to database?! Uuid=%s", uuid.c_str());
				return false;
			}
		}
		UpdateSwitch(Idx, state != 0, deviceName);

		if (root["deviceStatusInfo"]["device"][ii]["currentUsage"].empty() == false)
		{
			double currentUsage = root["deviceStatusInfo"]["device"][ii]["currentUsage"].asDouble();
			double DayCounter = root["deviceStatusInfo"]["device"][ii]["dayUsage"].asDouble();

			//double ElecOffset = GetElectricOffset(Idx, DayCounter);
			double OldDayCounter = m_LastElectricCounter[Idx];
			if (DayCounter < OldDayCounter)
			{
				//daily counter went to zero
				m_OffsetElectricUsage[Idx] += OldDayCounter;
			}
			m_LastElectricCounter[Idx] = DayCounter;
			SendKwhMeterOldWay(Idx, 1, 255, currentUsage / 1000.0, (m_OffsetElectricUsage[Idx] + m_LastElectricCounter[Idx]) / 1000.0, deviceName);
		}
	}
	return true;
}
Exemplo n.º 7
0
void CGpio::UpdateDeviceStates(bool forceUpdate)
{
	boost::mutex::scoped_lock lock(m_pins_mutex);
	for(std::vector<CGpioPin>::iterator it = pins.begin(); it != pins.end(); ++it)
	{
		if (it->GetIsInput())
		{
			int value = GPIOReadFd(it->GetReadValueFd());
			if (value == -1)
				continue;
			bool updateDatabase = forceUpdate;
			bool state = false;

			if (it->GetActiveLow() && !value)
				state = true;
			else if (value)
				state = true;

			if (it->GetDBState() != state || updateDatabase)
			{
				std::vector<std::vector<std::string> > result;
				char szIdx[10];

				result = m_sql.safe_query("SELECT Name,nValue,sValue,Used FROM DeviceStatus WHERE (HardwareID==%d) AND (Unit==%d)",
					m_HwdID, it->GetPin());

				if ((!result.empty()) && (result.size() > 0))
				{
					std::vector<std::string> sd = result[0];

					if (atoi(sd[3].c_str()) == 1) /* Check if device is used */
					{
						bool db_state = (atoi(sd[1].c_str()) == 1);
						if (db_state != state)
							updateDatabase = true;

						if (updateDatabase)
							UpdateSwitch(it->GetPin(), state);
					}
				}
			}
		}
	}
}
Exemplo n.º 8
0
int cteHistory (WF3Info *wf3, Hdr *phdr) {
	extern int status;
	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->pctecorr))
	    return (status);

	if (UpdateSwitch ("PCTECORR", wf3->pctecorr, phdr, &logit))
	    return (status);

	addHistoryKw (phdr, "CTE parameters table: ");
	if (TabHistory (&wf3->pctetab, phdr))
	    return (status);

	return (status);
}
Exemplo n.º 9
0
int flatHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (const RefImage *, Hdr *);
	int TabHistory (RefTab *, Hdr *);
	int GotFileName (char *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->flatcorr))
    return (status);

	if (UpdateSwitch ("FLATCORR", acs->flatcorr, phdr, &logit))
    return (status);

	if (logit) {

    if (GotFileName (acs->pflt.name)) {
      if (ImgHistory (&acs->pflt, phdr))	/* pixel-to-pixel */
		    return (status);
    }

    if (GotFileName (acs->dflt.name)) {
      if (ImgHistory (&acs->dflt, phdr))	/* delta flat */
		    return (status);
    }

    if (GotFileName (acs->lflt.name)) {
      if (ImgHistory (&acs->lflt, phdr))	/* low-order flat */
		    return (status);
    }
    if (GotFileName (acs->cflt.name)) {
      if (ImgHistory (&acs->cflt, phdr))	/* coronographic flat */
		    return (status);
	    if (TabHistory (&acs->spot, phdr)) /* spot reference table */
        return (status);
    }
	}

	return (status);
}
Exemplo n.º 10
0
bool CHarmonyHub::UpdateActivities()
{
	if(!SubmitCommand(GET_CONFIG_COMMAND_RAW, "", ""))
	{
		_log.Log(LOG_ERROR,"Harmony Hub: Get activities failed");
		return false;
	}

	std::map< std::string, std::string> mapActivities;

	Json::Reader jReader;
	Json::Value root;
	bool ret = jReader.parse(m_szResultString, root);
	if (!ret)
	{
		_log.Log(LOG_ERROR, "Harmony Hub: Invalid data received! (Update Activities)");
		return false;
	}

	if (root["activity"].empty())
	{
		_log.Log(LOG_ERROR, "Harmony Hub: Invalid data received! (Update Activities)");
		return false;
	}

	int totActivities = (int)root["activity"].size();
	for (int ii = 0; ii < totActivities; ii++)
	{
		std::string aID = root["activity"][ii]["id"].asString();
		std::string aLabel = root["activity"][ii]["label"].asString();
		mapActivities[aID] = aLabel;
	}

	std::map< std::string, std::string>::const_iterator itt;
	int cnt = 0;
	for (itt = mapActivities.begin(); itt != mapActivities.end(); ++itt)
	{
		UpdateSwitch(cnt++, itt->first.c_str(), (m_szCurActivityID == itt->first), itt->second);
	}
	return true;
}
Exemplo n.º 11
0
int shadHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;
	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (const RefImage *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->shadcorr))
    return (status);

	if (UpdateSwitch ("SHADCORR", acs->shadcorr, phdr, &logit))
    return (status);

	if (logit) {
    if (ImgHistory (&acs->shad, phdr))
      return (status);
	}

	return (status);
}
Exemplo n.º 12
0
int darkHistory (WF3Info *wf3, Hdr *phdr) {

	extern int status;
	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (RefImage *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->darkcorr))
	    return (status);

	if (UpdateSwitch ("DARKCORR", wf3->darkcorr, phdr, &logit))
	    return (status);

	if (logit) {
	    if (ImgHistory (&wf3->dark, phdr))
		return (status);
	}

	return (status);
}
Exemplo n.º 13
0
int photHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;
	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->photcorr))
    return (status);

	if (UpdateSwitch ("PHOTCORR", acs->photcorr, phdr, &logit))
    return (status);

	if (logit) {
    if (TabHistory (&acs->phot, phdr))
      return (status);
	}

	return (status);
}
Exemplo n.º 14
0
int dqiHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;
	int logit;			/* true if we should log file name */
	int flag;
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->dqicorr))
    return (status);

	if (acs->bpix.exists == EXISTS_YES) {
    if (acs->bpix.goodPedigree == GOOD_PEDIGREE)
      flag = PERFORM;
    else if (acs->bpix.goodPedigree == DUMMY_PEDIGREE)
      flag = DUMMY;
    else
      flag = IGNORED;
	} else {
    flag = PERFORM;
	}

	if (UpdateSwitch ("DQICORR", flag, phdr, &logit))
    return (status);

	if (logit) {
    if (acs->detector != MAMA_DETECTOR) {
      addHistoryKw (phdr, "  values checked for saturation");
    }

    if (acs->bpix.exists == EXISTS_YES) {
      addHistoryKw (phdr, "  DQ array initialized ...");
      if (TabHistory (&acs->bpix, phdr))
        return (status);
    }
	}

	return (status);
}
Exemplo n.º 15
0
int flashHistory (WF3Info *wf3, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (RefImage *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->flashcorr))
	    return (status);

	if (UpdateSwitch ("FLSHCORR", wf3->flashcorr, phdr, &logit))
	    return (status);

	/* Write history records for the flash image. */
	if (logit) {
	    if (ImgHistory (&wf3->flash, phdr))
		return (status);
	}

	return (status);
}
Exemplo n.º 16
0
int pcteHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->pctecorr))		/* nothing to do */
    return (status);

	if (UpdateSwitch ("PCTECORR", acs->pctecorr, phdr, &logit))
    return (status);

	/* Write history records for the PCTE table. */
	if (logit) {
    if (TabHistory (&acs->pcte, phdr))
      return (status);
	}

	return (status);
}
Exemplo n.º 17
0
int biasHistory (ACSInfo *acs, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (const RefImage *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (acs->biascorr))
    return (status);

	if (UpdateSwitch ("BIASCORR", acs->biascorr, phdr, &logit))
    return (status);

	/* Write history records for the bias image. */
	if (logit) {
    if (ImgHistory (&acs->bias, phdr))
      return (status);
	}

	return (status);
}
Exemplo n.º 18
0
int sinkHistory (const ACSInfo *acs, Hdr *phdr) {

    extern int status;

    int logit; // True if we should log file name
    int OmitStep (int);
    int ImgHistory (const RefImage *, Hdr *);
    int UpdateSwitch (char *, int, Hdr *, int *);

    if (OmitStep (acs->sinkcorr))
        return (status = HSTCAL_OK);

    if ((status = UpdateSwitch ("SINKCORR", acs->sinkcorr, phdr, &logit)))
        return (status);

    // Write history records for the bias image.
    if (logit) {
        if ((status = ImgHistory (&acs->sink, phdr)))
            return (status);
    }

    return (status = HSTCAL_OK);
}
Exemplo n.º 19
0
int atodHistory (WF3Info *wf3, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int TabHistory (RefTab *, Hdr *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->atodcorr))		/* nothing to do */
	    return (status);

	if (UpdateSwitch ("ATODCORR", wf3->atodcorr, phdr, &logit))
	    return (status);

	/* Write history records for the A-to-D table. */
	if (logit) {
	    if (TabHistory (&wf3->atod, phdr))
		return (status);
	}

	return (status);
}
Exemplo n.º 20
0
int flatHistory (WF3Info *wf3, Hdr *phdr) {

	extern int status;

	int logit;			/* true if we should log file name */
	int OmitStep (int);
	int ImgHistory (RefImage *, Hdr *);
	int GotFileName (char *);
	int UpdateSwitch (char *, int, Hdr *, int *);

	if (OmitStep (wf3->flatcorr))
	    return (status);

	if (UpdateSwitch ("FLATCORR", wf3->flatcorr, phdr, &logit))
	    return (status);

	if (logit) {

	    if (GotFileName (wf3->pflt.name)) {
		if (ImgHistory (&wf3->pflt, phdr))	/* pixel-to-pixel */
		    return (status);
	    }

	    if (GotFileName (wf3->dflt.name)) {
		if (ImgHistory (&wf3->dflt, phdr))	/* delta flat */
		    return (status);
	    }

	    if (GotFileName (wf3->lflt.name)) {
		if (ImgHistory (&wf3->lflt, phdr))	/* low-order flat */
		    return (status);
	    }
	}

	return (status);
}
Exemplo n.º 21
0
void CNest::GetMeterDetails()
{
	std::string sResult;
#ifdef DEBUG_NextThermostatR
	sResult = ReadFile("E:\\nest.json");
#else
	if (m_UserName.size()==0)
		return;
	if (m_Password.size()==0)
		return;
	if (m_bDoLogin)
	{
		if (!Login())
		return;
	}
	std::vector<std::string> ExtraHeaders;

	ExtraHeaders.push_back("user-agent:Nest/1.1.0.10 CFNetwork/548.0.4");
	ExtraHeaders.push_back("Authorization:Basic " + m_AccessToken);
	ExtraHeaders.push_back("X-nl-user-id:" + m_UserID);
	ExtraHeaders.push_back("X-nl-protocol-version:1");

	//Get Data
	std::string sURL = m_TransportURL + NEST_GET_STATUS + m_UserID;
	if (!HTTPClient::GET(sURL, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "Nest: Error getting current state!");
		m_bDoLogin = true;
		return;
	}
#endif

#ifdef DEBUG_NextThermostatW
	SaveString2Disk(sResult, "E:\\nest.json");
#endif

	Json::Value root;
	Json::Reader jReader;
	if (!jReader.parse(sResult, root))
	{
		_log.Log(LOG_ERROR, "Nest: Invalid data received!");
		m_bDoLogin = true;
		return;
	}

	bool bHaveShared = !root["shared"].empty();
	bool bHaveTopaz = !root["topaz"].empty();

	if ((!bHaveShared) && (!bHaveTopaz))
	{
		_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	//Protect
	if (bHaveTopaz)
	{
		if (root["topaz"].size() < 1)
		{
			_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
			m_bDoLogin = true;
			return;
		}
		Json::Value::Members members = root["topaz"].getMemberNames();
		if (members.size() < 1)
		{
			_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
			m_bDoLogin = true;
			return;
		}
		int SwitchIndex = 1;
		for (Json::Value::iterator itDevice = root["topaz"].begin(); itDevice != root["topaz"].end(); ++itDevice)
		{
			Json::Value device = *itDevice;
			std::string devstring = itDevice.key().asString();
			if (device["where_id"].empty())
				continue;
			std::string whereid = device["where_id"].asString();
			//lookup name
			std::string devName = devstring;
			if (!root["where"].empty())
			{
				for (Json::Value::iterator itWhere = root["where"].begin(); itWhere != root["where"].end(); ++itWhere)
				{
					Json::Value iwhere = *itWhere;
					if (!iwhere["wheres"].empty())
					{
						for (Json::Value::iterator itWhereNest = iwhere["wheres"].begin(); itWhereNest != iwhere["wheres"].end(); ++itWhereNest)
						{
							Json::Value iwhereItt = *itWhereNest;
							if (!iwhereItt["where_id"].empty())
							{
								std::string tmpWhereid = iwhereItt["where_id"].asString();
								if (tmpWhereid == whereid)
								{
									devName = iwhereItt["name"].asString();
									break;
								}
							}
						}
					}
					
				}
			}
			bool bIAlarm = false;
			bool bBool;
			if (!device["component_speaker_test_passed"].empty())
			{
				bBool = device["component_speaker_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_smoke_test_passed"].empty())
			{
				bBool = device["component_smoke_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_heat_test_passed"].empty())
			{
				bBool = device["component_heat_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_buzzer_test_passed"].empty())
			{
				bBool = device["component_buzzer_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_us_test_passed"].empty())
			{
				bBool = device["component_us_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_temp_test_passed"].empty())
			{
				bBool = device["component_temp_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_wifi_test_passed"].empty())
			{
				bBool = device["component_wifi_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_als_test_passed"].empty())
			{
				bBool = device["component_als_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_co_test_passed"].empty())
			{
				bBool = device["component_co_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			if (!device["component_hum_test_passed"].empty())
			{
				bBool = device["component_hum_test_passed"].asBool();
				if (!bBool)
					bIAlarm = true;
			}
			UpdateSmokeSensor(SwitchIndex, bIAlarm, devName);
			SwitchIndex++;
		}
	}

	//Thermostat
	if (!bHaveShared)
		return;
	if (root["shared"].size()<1)
	{
		if (bHaveTopaz)
			return;
		_log.Log(LOG_ERROR, "Nest: request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	size_t iThermostat = 0;
	for (Json::Value::iterator ittStructure = root["structure"].begin(); ittStructure != root["structure"].end(); ++ittStructure)
	{
		Json::Value nstructure = *ittStructure;
		if (!nstructure.isObject())
			continue;
		std::string StructureID = ittStructure.key().asString();
		std::string StructureName = nstructure["name"].asString();

		for (Json::Value::iterator ittDevice = nstructure["devices"].begin(); ittDevice != nstructure["devices"].end(); ++ittDevice)
		{
			std::string devID = (*ittDevice).asString();
			if (devID.find("device.")==std::string::npos)
				continue;
			std::string Serial = devID.substr(7);
			if (root["device"].empty())
				continue;
			if (root["device"][Serial].empty())
				continue; //not found !?
			if (root["shared"][Serial].empty())
				continue; //Nothing shared?


			Json::Value ndevice = root["device"][Serial];
			if (!ndevice.isObject())
				continue;

			std::string Name = "Thermostat";
			if (!ndevice["where_id"].empty())
			{
				//Lookup our 'where' (for the Name of the thermostat)
				std::string where_id = ndevice["where_id"].asString();

				if (!root["where"].empty())
				{
					if (!root["where"][StructureID].empty())
					{
						for (Json::Value::iterator ittWheres = root["where"][StructureID]["wheres"].begin(); ittWheres != root["where"][StructureID]["wheres"].end(); ++ittWheres)
						{
							Json::Value nwheres = *ittWheres;
							if (nwheres["where_id"] == where_id)
							{
								Name = StructureName + " " + nwheres["name"].asString();
								break;
							}
						}
					}
				}
			}

			_tNestThemostat ntherm;
			ntherm.Serial = Serial;
			ntherm.StructureID = StructureID;
			ntherm.Name = Name;
			m_thermostats[iThermostat] = ntherm;

			Json::Value nshared = root["shared"][Serial];

			//Setpoint
			if (!nshared["target_temperature"].empty())
			{
				float currentSetpoint = nshared["target_temperature"].asFloat();
				SendSetPointSensor((const unsigned char)(iThermostat * 3) + 1, currentSetpoint, Name + " Setpoint");
			}
			//Room Temperature/Humidity
			if (!nshared["current_temperature"].empty())
			{
				float currentTemp = nshared["current_temperature"].asFloat();
				int Humidity = root["device"][Serial]["current_humidity"].asInt();
				SendTempHumSensor((iThermostat * 3) + 2, 255, currentTemp, Humidity, Name + " TempHum");
			}

			// Check if thermostat is currently Heating
			if (nshared["can_heat"].asBool() && !nshared["hvac_heater_state"].empty())
			{
				bool bIsHeating = nshared["hvac_heater_state"].asBool();
				UpdateSwitch((unsigned char)(113 + (iThermostat * 3)), bIsHeating, Name + " HeatingOn");
			}

			// Check if thermostat is currently Cooling
			if (nshared["can_cool"].asBool() && !nshared["hvac_ac_state"].empty())
			{
				bool bIsCooling = nshared["hvac_ac_state"].asBool();
				UpdateSwitch((unsigned char)(114 + (iThermostat * 3)), bIsCooling, Name + " CoolingOn");
			}

			//Away
			if (!nstructure["away"].empty())
			{
				bool bIsAway = nstructure["away"].asBool();
				SendSwitch((iThermostat * 3) + 3, 1, 255, bIsAway, 0, Name + " Away");
			}
			iThermostat++;
		}
	}
}
Exemplo n.º 22
0
void CToonThermostat::GetMeterDetails()
{
	if (m_UserName.size()==0)
		return;
	if (m_Password.size()==0)
		return;
	if (m_bDoLogin)
	{
		if (!Login())
		return;
	}
	std::string sResult;
	std::vector<std::string> ExtraHeaders;

	std::stringstream sstr2;
	sstr2 << "?clientId=" << m_ClientID
		<< "&clientIdChecksum=" << m_ClientIDChecksum
		<< "&random=" << GetRandom();
	std::string szPostdata = sstr2.str();
	//Get Data
	std::string sURL = TOON_HOST + TOON_UPDATE_PATH + szPostdata;
	if (!HTTPClient::GET(sURL, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "ToonThermostat: Error getting current state!");
		m_bDoLogin = true;
		return;
	}

	time_t atime = mytime(NULL);

	Json::Value root;
	Json::Reader jReader;
	if (!jReader.parse(sResult, root))
	{
		_log.Log(LOG_ERROR, "ToonThermostat: Invalid data received!");
		m_bDoLogin = true;
		return;
	}
	if (root["success"].empty() == true)
	{
		_log.Log(LOG_ERROR, "ToonThermostat: ToonState request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}
	if (root["success"] == false)
	{
		_log.Log(LOG_ERROR, "ToonThermostat: ToonState request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	//thermostatInfo
	if (root["thermostatInfo"].empty() == false)
	{
		float currentTemp = root["thermostatInfo"]["currentTemp"].asFloat() / 100.0f;
		float currentSetpoint = root["thermostatInfo"]["currentSetpoint"].asFloat() / 100.0f;
		SendSetPointSensor(1, currentSetpoint, "Room Setpoint");
		SendTempSensor(1, currentTemp, "Room Temperature");

		//int programState = root["thermostatInfo"]["programState"].asInt();
		//int activeState = root["thermostatInfo"]["activeState"].asInt();

		if (root["thermostatInfo"]["burnerInfo"].empty() == false)
		{
			//burnerinfo
			//0=off
			//1=heating
			//2=hot water
			//3=pre-heating
			if (root["thermostatInfo"]["burnerInfo"].isString())
			{
				std::string sBurnerInfo = root["thermostatInfo"]["burnerInfo"].asString();
				int burnerInfo = atoi(sBurnerInfo.c_str());
				UpdateSwitch(113, burnerInfo != 0, "FlameOn");
			}
			else if (root["thermostatInfo"]["burnerInfo"].isInt())
			{
				int burnerInfo = root["thermostatInfo"]["burnerInfo"].asInt();
				UpdateSwitch(113, burnerInfo != 0, "FlameOn");
			}
		}
	}

	if (root["gasUsage"].empty() == false)
	{
		m_p1gas.gasusage = (unsigned long)(root["gasUsage"]["meterReading"].asFloat());
	}

	if (root["powerUsage"].empty() == false)
	{
		m_p1power.powerusage1 = (unsigned long)(root["powerUsage"]["meterReading"].asFloat());
		m_p1power.powerusage2 = (unsigned long)(root["powerUsage"]["meterReadingLow"].asFloat());

		if (root["powerUsage"]["meterReadingProdu"].empty() == false)
		{
			m_p1power.powerdeliv1 = (unsigned long)(root["powerUsage"]["meterReadingProdu"].asFloat());
			m_p1power.powerdeliv2 = (unsigned long)(root["powerUsage"]["meterReadingLowProdu"].asFloat());
		}

		m_p1power.usagecurrent = (unsigned long)(root["powerUsage"]["value"].asFloat());	//Watt
	}

	//Send Electra if value changed, or at least every 5 minutes
	if (
		(m_p1power.usagecurrent != m_lastelectrausage) ||
		(atime - m_lastSharedSendElectra >= 300)
		)
	{
		if ((m_p1power.powerusage1 != 0) || (m_p1power.powerusage2 != 0) || (m_p1power.powerdeliv1 != 0) || (m_p1power.powerdeliv2 != 0))
		{
			m_lastSharedSendElectra = atime;
			m_lastelectrausage = m_p1power.usagecurrent;
			sDecodeRXMessage(this, (const unsigned char *)&m_p1power);
		}
	}
	
	//Send GAS if the value changed, or at least every 5 minutes
	if (
		(m_p1gas.gasusage != m_lastgasusage) ||
		(atime - m_lastSharedSendGas >= 300)
		)
	{
		if (m_p1gas.gasusage != 0)
		{
			m_lastSharedSendGas = atime;
			m_lastgasusage = m_p1gas.gasusage;
			sDecodeRXMessage(this, (const unsigned char *)&m_p1gas);
		}
	}
}
Exemplo n.º 23
0
/*  acsrej_do -- Perform the cosmic ray rejection for ACS images

  Description:
  ------------
  This is mostly a file bookkeeping routine for the cosmic ray rejection task.
  It takes care of input/output files open/close, check for dimensions, read/
  write data from/to files, allocate memory spaces etc.

    Date          Author          Description
    ----          ------          -----------
    06-May-1996   J.-C. Hsu       Adapt from the SPP code crrej_do.x
    05-Aug-1998   W. Hack         Modified to handle ACS data
    11-Feb-1999   W. Hack         EXPTIME now in Pri. Hdr.
    18-Mar-1999   W.J. Hack       Revised to read EXPTIMEs from Primary headers
                                  for cr_scaling using tpin directly
    14-Sep-1999   W.J. Hack       Cleaned up SHADCORR usage. Added check for max
                                  number of files here.
*/
int acsrej_do (IRAFPointer tpin, char *outfile, char *mtype, clpar *par, int newpar[])
{
    extern int  status;

    IODescPtr   ipsci[MAX_FILES];   /* science image descriptor */
    IODescPtr   ipdq[MAX_FILES];    /* data quality image descriptor */
    float       skyval[MAX_FILES];  /* background DN values */
    float       efac[MAX_FILES];    /* exposure factors */
    multiamp    noise;              /* readout noise */
    multiamp    gain;               /* A-to-D gain factors */
    float       exptot;
    float       texpt;
    int         nimgs;
    SingleGroup sg;
    int         niter = 0;
    float       sigma[MAX_ITER];

    Hdr         phdr;               /* primary header */
    int         extver;             /* Current extension being processed*/
    int         numext;             /* Number of extensions in each image */
    int         nextend;            /* Number of output extensions */
    char        imgname[MAX_FILES][CHAR_FNAME_LENGTH];
    char        fimage[CHAR_FNAME_LENGTH];  /* Name of first image in list */
    char        root[CHAR_FNAME_LENGTH];    /* ROOTNAME for output CRJ file */
    char        uroot[CHAR_FNAME_LENGTH];   /* Upper case version of rootname */
    char        *shadrefname;

    int         ext[MAX_FILES];
    int         dim_x, dim_y;       /* image dimensions */
    int         i, j, n;            /* loop indices */
    float       *efacsum, *work;
    int         nrej;               /* total number of rejected pixels */
    float       skysum;             /* total sky level */
    int         logit;
    RefImage    shadref;
    int         shadswitch;
    double      expend, expstart;
    int         non_zero;           /* number of input images with EXPTIME>0.*/
    int         found;
    char        imgdefault[CHAR_FNAME_LENGTH];  /* name of first input image with EXPTIME > 0. */

    int     GetSwitch (Hdr *, char *, int *);
    int     UpdateSwitch (char *, int, Hdr *, int *);

    void    InitRefImg (RefImage *);
    int     ImgHistory (const RefImage *, Hdr *);
    int     ImgPedigree (RefImage *);

    int     acsrej_check (IRAFPointer, int, int, clpar *, int [],  char [][CHAR_FNAME_LENGTH],
                int [], IODescPtr [], IODescPtr [],
                multiamp *, multiamp *, int *,
                int *, int);
    int     cr_scaling (char *, IRAFPointer, float [], int *, double *, double *);
    int     rejpar_in(clpar *, int [], int, float,   int *, float []);
    void    acsrej_sky (char *, IODescPtr [], IODescPtr [], int, short, float []);
    void    cr_history (SingleGroup *, clpar *, int);
    int     acsrej_init (IODescPtr [], IODescPtr [], clpar *, int, int, int,
                multiamp, multiamp, float [], float [],
                SingleGroup *,   float *);
    int     acsrej_loop (IODescPtr [], IODescPtr [], char [][CHAR_FNAME_LENGTH],
                int [], int, clpar *, int, int, int, float [],
                multiamp, multiamp, float [], float [],
                FloatTwoDArray *, FloatTwoDArray *, float *,
                ShortTwoDArray *, int *, char *);
    int     PutKeyFlt (Hdr *, char *, float, char *);
    int     PutKeyDbl (Hdr *, char *, double, char *);
    int     PutKeyStr (Hdr *, char *, char *, char *);
    int     GetKeyStr (Hdr *, char *, int, char *, char *, int);
    int     PutKeyInt (Hdr *, char *, int, char *);
    int     GetKeyInt (Hdr *, char *, int, int, int *);
    void    UFilename (char *, Hdr *);
    void    UMemType (char *, Hdr *);
    void    UExpname (char *, Hdr *);
    int     LoadHdr (char *, Hdr *);
    void    UpperAll (char *, char *, int);
    void    TimeStamp (char *, char *);
    void    WhichError (int);
    void    PrSwitch (char *, int);
    void    FindAsnRoot (char *, char *);
    void    initmulti (multiamp *);
    /* -------------------------------- begin ---------------------------------- */
    /* Initialize necessary structures */
    InitRefImg (&shadref);
    root[0] = '\0';
    uroot[0] = '\0';
    initmulti (&noise);
    initmulti (&gain);

    numext = 0;
    nextend = 0;


    /* Since CR-SPLIT images are in separate files, we need to
        combine the same chip's exposure from each file.  Therefore
        we will loop over each extension in the first image, determine
        what chip that corresponds to, and get the same chip from the
        rest of the images (which could be in any arbitrary
        extension in each of the images).
    */

    /* First, let's determine how many extensions/chips in each file */
    c_imtgetim (tpin, fimage, CHAR_FNAME_LENGTH);

    if (LoadHdr (fimage, &phdr) )
        return (status = ERROR_RETURN);

    if (GetKeyInt (&phdr, "NEXTEND", NO_DEFAULT, 0, &nextend) == 0)
        numext = nextend / EXT_PER_GROUP;
    else
        numext = 1;

    shadswitch = 0;
    /* Check to see if SHADCORR was set to PERFORM in image header */
    if (GetSwitch (&phdr, "SHADCORR", &shadswitch) )
        return(status);

    /* If shadcorr was set either by the user on the command line
        or in the image header, initialize shadcorr processing.
    */
    if (par->shadcorr == PERFORM || shadswitch == PERFORM) {

        /* Use par->shadcorr as switch for performing shading correction */
        par->shadcorr = PERFORM;
        shadrefname = calloc(CHAR_FNAME_LENGTH, sizeof(char));

        if (GetKeyStr (&phdr, "SHADFILE", NO_DEFAULT, "", shadrefname, CHAR_FNAME_LENGTH) )
            return(status);
        strcpy (shadref.name, shadrefname);
        /* Read in PEDIGREE and DESCRIPTION for SHADFILE */
        if (ImgPedigree (&shadref) )
            return (status);
        /* If a DUMMY shadfile was specified, turn off shadcorr */
        if (shadref.goodPedigree == DUMMY)
            par->shadcorr = OMIT;
        free (shadrefname);
    }

    freeHdr (&phdr);

    /* Initialize efac */
    for (n = 0; n < MAX_FILES; n++) efac[n] = 1.0;

    /* calculate the scaling factors due to different exposure time */
    strcpy (par->expname, "EXPTIME");
    if (cr_scaling (par->expname, tpin, efac, &nimgs, &expend, &expstart) ){
        WhichError (status);
        return (status);
    }

    /* make sure there is more than one image to process */
    if (nimgs < 2) {
        trlmessage ("Needs more than one input image.");
        return (status = NOTHING_TO_DO);
    }

    /* calculate the total exposure time */
    exptot = 0.;
    non_zero = 0;
    for (n = 0; n < nimgs; ++n) {
        exptot += efac[n];
        /* Count how many inputs have non-zero(valid) EXPTIME */
        if (efac[n] > 0.) non_zero++;
    }
    /* for the case of all images have zero exposure time, use equal
        exposure time of 1. */
    if (exptot == 0.) {
        for (n = 0; n < nimgs; ++n) {
            efac[n] = 1.;
        }
        texpt = (float) nimgs;
        non_zero = nimgs;
    } else {
        texpt = exptot;
    }

    /* Now, start the loop. */
    for (extver = 1; extver <= numext; extver++) {

        if (par->printtime) {
            TimeStamp ("Start cosmic ray rejection","");
        }

        /* open input files and temporary files, check the parameters */
        if (acsrej_check (tpin, extver, numext, par, newpar, imgname, ext,
            ipsci, ipdq, &noise, &gain, &dim_x, &dim_y, nimgs)) {
            WhichError (status);
            return(status);
        }

        /* Now that we have read in SHADCORR, report if it will be performed */
        PrSwitch ("shadcorr", par->shadcorr);

        /* read in the parameters */
        if (rejpar_in (par, newpar, nimgs, exptot,   &niter, sigma) )
            return(status);

        /* allocate array space */
        efacsum = calloc (dim_x*dim_y, sizeof(float));
        work    = calloc (nimgs*dim_x, sizeof(float));

        /* calculate the sky levels */
        acsrej_sky (par->sky, ipsci, ipdq, nimgs, par->badinpdq, skyval);
        if (status != ACS_OK) {
            WhichError (status);
            return (status);
        }
        if (par->verbose) {
            for (n = 0; n < nimgs; n++) {
                sprintf (MsgText, "sky of '%s[sci,%d]' is %0.3f DN", imgname[n], ext[n], skyval[n]);
                trlmessage (MsgText);
            }
        }

        /* use the first input image to set up the data structure */
        initSingleGroup (&sg);

        /* Find the first image in the input list which has an
            EXPTIME > 0. to use for initializing the output SingleGroup.
        */
        found = 0;
        n = 0;
        /* By default, simply use the first one, so initialize accordingly.*/
        strcpy (imgdefault, imgname[0]);
        do {
            if (efac[n] > 0.) {
                strcpy(imgdefault,imgname[n]);
                found = 1;
            }
            n++;
        } while (found == 0);

        getSingleGroup (imgdefault, extver, &sg);

        if (non_zero > 1){
            /* compute the initial pixel values to be used to compare against all
               images. */
            if (non_zero < nimgs){
                trlwarn ("Some input exposures had EXPTIME = 0.");
            }

            if (acsrej_init (ipsci, ipdq, par, nimgs, dim_x, dim_y,
                    noise, gain, efac, skyval, &sg, work) ) {
                WhichError(status);
                closeSciDq(nimgs, ipsci, ipdq, par);
                return (status);
            }

            if (par->printtime)
                TimeStamp ("Calculated initial guess for extension", "");

            /* do the iterative cosmic ray rejection calculations */
            if (acsrej_loop (ipsci, ipdq, imgname, ext, nimgs, par, niter, dim_x, dim_y,
                    sigma, noise, gain, efac, skyval,
                    &sg.sci.data, &sg.err.data, efacsum, &sg.dq.data,
                    &nrej, shadref.name) ) {
                WhichError(status);
                closeSciDq(nimgs, ipsci, ipdq, par);
                return (status);
            }
        } else {
            trlwarn ("Cosmic-ray rejection NOT performed!");
            if (non_zero > 0) {
                trlwarn ("Some input exposures had EXPTIME = 0.");
                trlwarn ("Output product will not be cosmic-ray cleaned!");
            } /*else {
                trlwarn ("ALL input exposures had EXPTIME = 0.");
                trlwarn ("Output product will be BLANK!");
            } */
        } /* End if(non_zero) block */


        /* must close all images, now that we are done reading them */
        closeSciDq(nimgs, ipsci, ipdq, par);

        /* calculate the total sky ... */
        skysum = 0.;
        for (n = 0; n < nimgs; ++n) {
            skysum += skyval[n];
        }
        /* ... and force it to be non-negative */
        if (skysum < 0.) skysum = 0.;

        if (par->printtime){
            if (non_zero > 1){
                TimeStamp ("Finished detecting cosmic rays on extension", "");
            } else {
                TimeStamp ("Done checking this extension","");
            }
        }

        /* write to the output image */
        if (non_zero > 0){
            for (j = 0; j < dim_y; ++j) {
                for (i = 0; i < dim_x; ++i) {
                    PPix(&sg.sci.data,i,j) = PPix(&sg.sci.data,i,j)*texpt + skysum;
                    PPix(&sg.err.data,i,j) *= texpt;
                }
            }
        } else {
            for (j = 0; j < dim_y; ++j) {
                for (i = 0; i < dim_x; ++i) {
                    PPix(&sg.sci.data,i,j) = par->fillval;
                    PPix(&sg.err.data,i,j) = 0.;
                    /* Set DQ value to one which will always be considered BAD */
                    PPix(&sg.dq.data,i,j) = 1;
                }
            }
                    /* Set at least one pixel to a different value to insure
                      that an image array actually gets produced. */
                    PPix(&sg.err.data,0,0) = -1.;
                    PPix(&sg.dq.data,0,0) = 8;
        }

        /* update the exposure time of the output images */
        PutKeyFlt (sg.globalhdr, "TEXPTIME", exptot, "");
        PutKeyFlt (sg.globalhdr, "SKYSUM", skysum, "Total sky level (DN)");
        PutKeyDbl (sg.globalhdr, "EXPSTART", expstart, "computed exposure start time (Modified Julian Date)");
        PutKeyDbl (sg.globalhdr, "EXPEND", expend, "exposure end time (Modified Julian Date)");
        /*
            Updated REJ_RATE to use 'texpt' as a safe value when
            EXPTIME=0 for all members. WJH, 24 Feb 2003
        */
        PutKeyFlt (sg.globalhdr, "REJ_RATE", (float)nrej/texpt,
                "Cosmic ray impact rate (pixels/sec)");
        PutKeyFlt (sg.globalhdr, "EXPTIME", exptot, "");
        if (par->shadcorr) {
            logit = 0;
            if (UpdateSwitch ("SHADCORR", par->shadcorr, sg.globalhdr, &logit) )
                return (status);

                PrSwitch ("shadcorr", COMPLETE);

            if (logit) {
                /*Records SHADFILE information in header comments... */
                if (ImgHistory (&shadref, sg.globalhdr))
                    return (status);

            }
        }

        /* record parameters to the output file */
        cr_history (&sg, par, nextend);
        PutKeyInt (&sg.sci.hdr, "NCOMBINE", nimgs, "");
        UFilename (outfile, sg.globalhdr);
        UMemType (mtype, sg.globalhdr);
        FindAsnRoot (outfile, root);
        UpperAll (root, uroot, strlen(root)+1 );
        /*  EXPNAME values modified for all extensions in a SingleGroup.
                   WJH 7 July 1999
        */
        UExpname (root, &sg.sci.hdr);
        UExpname (root, &sg.err.hdr);
        UExpname (root, &sg.dq.hdr);

        PutKeyStr (sg.globalhdr, "ROOTNAME", uroot,"Rootname of the observation set");

        /* Output CHIP to the same EXTVER as the CHIP ID */
        putSingleGroup (outfile, extver, &sg, 0);
        freeSingleGroup (&sg);

        if (par->printtime)
            TimeStamp ("Finished writing out extension", "");

        /* deallocate memories */
        free (efacsum);
        free (work);

    }
    /* Set status to a value which will be understood by
        CALACS to turn off subsequent processing. */
    if (non_zero == 0) status = NO_GOOD_DATA;

    return (status);
}
Exemplo n.º 24
0
void OTGWBase::ParseLine()
{
	if (m_bufferpos<2)
		return;
	std::string sLine((char*)&m_buffer);

	std::vector<std::string> results;
	StringSplit(sLine,",",results);
	if (results.size()==25)
	{
		//status report
		//0    Status (MsgID=0) - Printed as two 8-bit bitfields
		//1    Control setpoint (MsgID=1) - Printed as a floating point value
		//2    Remote parameter flags (MsgID= 6) - Printed as two 8-bit bitfields
		//3    Maximum relative modulation level (MsgID=14) - Printed as a floating point value
		//4    Boiler capacity and modulation limits (MsgID=15) - Printed as two bytes
		//5    Room Setpoint (MsgID=16) - Printed as a floating point value
		//6    Relative modulation level (MsgID=17) - Printed as a floating point value
		//7    CH water pressure (MsgID=18) - Printed as a floating point value
		//8    Room temperature (MsgID=24) - Printed as a floating point value
		//9    Boiler water temperature (MsgID=25) - Printed as a floating point value
		//10    DHW temperature (MsgID=26) - Printed as a floating point value
		//11    Outside temperature (MsgID=27) - Printed as a floating point value
		//12    Return water temperature (MsgID=28) - Printed as a floating point value
		//13    DHW setpoint boundaries (MsgID=48) - Printed as two bytes
		//14    Max CH setpoint boundaries (MsgID=49) - Printed as two bytes
		//15    DHW setpoint (MsgID=56) - Printed as a floating point value
		//16    Max CH water setpoint (MsgID=57) - Printed as a floating point value
		//17    Burner starts (MsgID=116) - Printed as a decimal value
		//18    CH pump starts (MsgID=117) - Printed as a decimal value
		//19    DHW pump/valve starts (MsgID=118) - Printed as a decimal value
		//20    DHW burner starts (MsgID=119) - Printed as a decimal value
		//21    Burner operation hours (MsgID=120) - Printed as a decimal value
		//22    CH pump operation hours (MsgID=121) - Printed as a decimal value
		//23    DHW pump/valve operation hours (MsgID=122) - Printed as a decimal value
		//24    DHW burner operation hours (MsgID=123) - Printed as a decimal value 
		_tOTGWStatus _status;
		int idx=0;

		_status.MsgID=results[idx++];
		if (_status.MsgID.size()==17)
		{
			bool bCH_enabled=(_status.MsgID[7]=='1');										UpdateSwitch(101,bCH_enabled,"CH_enabled");
			bool bDHW_enabled=(_status.MsgID[6]=='1');										UpdateSwitch(102,bDHW_enabled,"DHW_enabled");
			bool bCooling_enable=(_status.MsgID[5]=='1');									UpdateSwitch(103,bCooling_enable,"Cooling_enable");
			bool bOTC_active=(_status.MsgID[4]=='1');										UpdateSwitch(104,bOTC_active,"OTC_active");
			bool bCH2_enabled=(_status.MsgID[3]=='1');										UpdateSwitch(105,bCH2_enabled,"CH2_enabled");

			bool bFault_indication=(_status.MsgID[9+7]=='1');								UpdateSwitch(110,bFault_indication,"Fault_indication");
			bool bCH_active=(_status.MsgID[9+6]=='1');										UpdateSwitch(111,bCH_active,"CH_active");
			bool bDHW_active=(_status.MsgID[9+5]=='1');										UpdateSwitch(112,bDHW_active,"DHW_active");
			bool bFlameOn=(_status.MsgID[9+4]=='1');										UpdateSwitch(113,bFlameOn,"FlameOn");
			bool bCooling_Mode_Active=(_status.MsgID[9+3]=='1');							UpdateSwitch(114,bCooling_Mode_Active,"Cooling_Mode_Active");
			bool bCH2_Active=(_status.MsgID[9+2]=='1');										UpdateSwitch(115,bCH2_Active,"CH2_Active");
			bool bDiagnosticEvent=(_status.MsgID[9+1]=='1');								UpdateSwitch(116,bDiagnosticEvent,"DiagnosticEvent");
		}
		
		_status.Control_setpoint=(float)atof(results[idx++].c_str());						UpdateTempSensor(idx-1,_status.Control_setpoint,"Control Setpoint");
		_status.Remote_parameter_flags=results[idx++];
		_status.Maximum_relative_modulation_level=(float)atof(results[idx++].c_str());
		_status.Boiler_capacity_and_modulation_limits=results[idx++];
		_status.Room_Setpoint=(float)atof(results[idx++].c_str());							UpdateSetPointSensor(idx-1,_status.Room_Setpoint,"Room Setpoint");
		_status.Relative_modulation_level=(float)atof(results[idx++].c_str());
		_status.CH_water_pressure=(float)atof(results[idx++].c_str());
		if (_status.CH_water_pressure!=0)
		{
			UpdatePressureSensor(idx-1,_status.CH_water_pressure,"CH Water Pressure");
		}

		_status.Room_temperature=(float)atof(results[idx++].c_str());						UpdateTempSensor(idx-1,_status.Room_temperature,"Room Temperature");
		_status.Boiler_water_temperature=(float)atof(results[idx++].c_str());				UpdateTempSensor(idx-1,_status.Boiler_water_temperature,"Boiler Water Temperature");
		_status.DHW_temperature=(float)atof(results[idx++].c_str());						UpdateTempSensor(idx-1,_status.DHW_temperature,"DHW Temperature");
		_status.Outside_temperature=(float)atof(results[idx++].c_str());					UpdateTempSensor(idx-1,_status.Outside_temperature,"Outside Temperature");
		_status.Return_water_temperature=(float)atof(results[idx++].c_str());				UpdateTempSensor(idx-1,_status.Return_water_temperature,"Return Water Temperature");
		_status.DHW_setpoint_boundaries=results[idx++];
		_status.Max_CH_setpoint_boundaries=results[idx++];
		_status.DHW_setpoint=(float)atof(results[idx++].c_str());							UpdateSetPointSensor(idx-1,_status.DHW_setpoint,"DHW Setpoint");
		_status.Max_CH_water_setpoint=(float)atof(results[idx++].c_str());					UpdateSetPointSensor(idx-1,_status.Max_CH_water_setpoint,"Max_CH Water Setpoint");
		_status.Burner_starts=atol(results[idx++].c_str());
		_status.CH_pump_starts=atol(results[idx++].c_str());
		_status.DHW_pump_valve_starts=atol(results[idx++].c_str());
		_status.DHW_burner_starts=atol(results[idx++].c_str());
		_status.Burner_operation_hours=atol(results[idx++].c_str());
		_status.CH_pump_operation_hours=atol(results[idx++].c_str());
		_status.DHW_pump_valve_operation_hours=atol(results[idx++].c_str());
		_status.DHW_burner_operation_hours=atol(results[idx++].c_str());
		return;
	}
	else
	{
		if (sLine=="SE")
		{
			_log.Log(LOG_ERROR,"OTGW: Error received!");
		}
		else
		{
			if (
				(sLine.find("OT")==std::string::npos)&&
				(sLine.find("PS")==std::string::npos)
				)
			{
				//Dont report OT/PS feedback
				_log.Log(LOG_STATUS,"OTGW: %s",sLine.c_str());
			}
		}
	}

}
Exemplo n.º 25
0
void CGpio::InterruptHandler()
{
	char c;
	int pin, fd, count, counter = 0, sched, priority;
	uint32_t diff = 1;
	bool bRead;
	struct timeval tvBegin, tvEnd, tvDiff;

	// Higher priority and real-time scheduling is only effective if we run as root
	GetSchedPriority(&sched, &priority);
	SetSchedPriority(SCHED_RR, (sched == SCHED_RR ? priority : 1), (sched == SCHED_RR));

	for(std::vector<CGpioPin>::iterator it = pins.begin(); it != pins.end(); ++it)
		if (it->GetPin() == pinPass)
		{
			if ((fd = it->GetReadValueFd()) == -1)
			{
				_log.Log(LOG_STATUS, "GPIO: Could not open file descriptor for GPIO %d", pinPass);
				pinPass = -1;
				return;
			}
			break;
		}

	pin = pinPass;
	pinPass = -1;

	if (ioctl (fd, FIONREAD, &count) != -1)
		for (int i = 0 ; i < count ; i++) // Clear any initial pending interrupt
			bRead = read(fd, &c, 1); // Catch value to suppress compiler unused warning

	_log.Log(LOG_STATUS, "GPIO: Interrupt handler for GPIO %d started (TID: %d)", pin, (pid_t)syscall(SYS_gettid));
	while (!m_stoprequested)
	{
		if (waitForInterrupt(fd, 2000) > 0)
		{
			if (counter > 100)
			{
				_log.Log(LOG_STATUS, "GPIO: Suppressing interruptstorm on GPIO %d, sleeping for 2 seconds..", pin);
				counter = -1;
				sleep_milliseconds(2000);
			}
			if (m_period > 0)
			{
				getclock(&tvEnd);
				if (timeval_subtract(&tvDiff, &tvEnd, &tvBegin)) {
					tvDiff.tv_sec = 0;
					tvDiff.tv_usec = 0;
				}
				diff = tvDiff.tv_usec + tvDiff.tv_sec * 1000000;
				getclock(&tvBegin);
			}
			if (diff > m_period * 1000 && counter != -1)
			{
				_log.Log(LOG_NORM, "GPIO: Processing interrupt for GPIO %d...", pin);
				if (m_debounce > 0)
					sleep_milliseconds(m_debounce); // Debounce reading
				UpdateSwitch(pin, GPIOReadFd(fd));
				_log.Log(LOG_NORM, "GPIO: Done processing interrupt for GPIO %d.", pin);

				if (counter > 0)
				{
					//_log.Log(LOG_STATUS, "GPIO: Suppressed %d interrupts on previous call for GPIO %d.", counter, pin);
					counter = 0;
				}
			}
			else
				counter++;
		}
		else
			if (fd != -1)
				close(fd);
	}
	_log.Log(LOG_STATUS, "GPIO: Interrupt handler for GPIO %d stopped", pin, (pid_t)syscall(SYS_gettid));
	return;
}
Exemplo n.º 26
0
void SwitchNode::update() 
{
	UpdateSwitch(this);
}
Exemplo n.º 27
0
void FootBall::Update()
{
	clock_t CurTime = clock();
	UpdateSwitch(CurTime);
}
Exemplo n.º 28
0
void MySensorsBase::SendSensor2Domoticz(_tMySensorNode *pNode, _tMySensorChild *pChild, const _eSetType vType)
{
	m_iLastSendNodeBatteryValue = 255;
	if (pChild->hasBattery)
	{
		m_iLastSendNodeBatteryValue = pChild->batValue;
	}
	int cNode = (pChild->nodeID << 8) | pChild->childID;
	int intValue;
	float floatValue;
	std::string stringValue;

	switch (vType)
	{
	case V_TEMP:
	{
		float Temp = 0;
		pChild->GetValue(V_TEMP, Temp);
		_tMySensorChild *pChildHum = FindChildWithValueType(pChild->nodeID, V_HUM);
		_tMySensorChild *pChildBaro = FindChildWithValueType(pChild->nodeID, V_PRESSURE);
		if (pChildHum && pChildBaro)
		{
			int Humidity;
			float Baro;
			bool bHaveHumidity = pChildHum->GetValue(V_HUM, Humidity);
			bool bHaveBaro = pChildBaro->GetValue(V_PRESSURE, Baro);
			if (bHaveHumidity && bHaveBaro)
			{
				int forecast = bmpbaroforecast_unknown;
				_tMySensorChild *pSensorForecast = FindChildWithValueType(pChild->nodeID, V_FORECAST);
				if (pSensorForecast)
				{
					pSensorForecast->GetValue(V_FORECAST, forecast);
				}
				if (forecast == bmpbaroforecast_cloudy)
				{
					if (Baro < 1010)
						forecast = bmpbaroforecast_rain;
				}

				//We are using the TempHumBaro Float type now, convert the forecast
				int nforecast = wsbaroforcast_some_clouds;
				if (Baro <= 980)
					nforecast = wsbaroforcast_heavy_rain;
				else if (Baro <= 995)
				{
					if (Temp > 1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}
				else if (Baro >= 1029)
					nforecast = wsbaroforcast_sunny;
				switch (forecast)
				{
				case bmpbaroforecast_sunny:
					nforecast = wsbaroforcast_sunny;
					break;
				case bmpbaroforecast_cloudy:
					nforecast = wsbaroforcast_cloudy;
					break;
				case bmpbaroforecast_thunderstorm:
					nforecast = wsbaroforcast_heavy_rain;
					break;
				case bmpbaroforecast_rain:
					if (Temp>1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}
				SendTempHumBaroSensorFloat(cNode, pChild->batValue, Temp, Humidity, Baro, nforecast, (!pChild->childName.empty()) ? pChild->childName : "TempHumBaro");
			}
		}
		else if (pChildHum) {
			int Humidity;
			bool bHaveHumidity = pChildHum->GetValue(V_HUM, Humidity);
			if (bHaveHumidity)
			{
				SendTempHumSensor(cNode, pChild->batValue, Temp, Humidity, (!pChild->childName.empty()) ? pChild->childName : "TempHum");
			}
		}
		else
		{
			SendTempSensor(cNode, pChild->batValue, Temp, (!pChild->childName.empty()) ? pChild->childName : "Temp");
		}
	}
	break;
	case V_HUM:
	{
		_tMySensorChild *pChildTemp = FindChildWithValueType(pChild->nodeID, V_TEMP);
		_tMySensorChild *pChildBaro = FindChildWithValueType(pChild->nodeID, V_PRESSURE);
		int forecast = bmpbaroforecast_unknown;
		_tMySensorChild *pSensorForecast = FindChildWithValueType(pChild->nodeID, V_FORECAST);
		if (pSensorForecast)
		{
			pSensorForecast->GetValue(V_FORECAST, forecast);
		}
		if (forecast == bmpbaroforecast_cloudy)
		{
			if (pChildBaro)
			{
				float Baro;
				if (pChildBaro->GetValue(V_PRESSURE, Baro))
				{
					if (Baro < 1010)
						forecast = bmpbaroforecast_rain;
				}
			}
		}
		float Temp;
		float Baro;
		int Humidity;
		pChild->GetValue(V_HUM, Humidity);
		if (pChildTemp && pChildBaro)
		{
			bool bHaveTemp = pChildTemp->GetValue(V_TEMP, Temp);
			bool bHaveBaro = pChildBaro->GetValue(V_PRESSURE, Baro);
			if (bHaveTemp && bHaveBaro)
			{
				cNode = (pChildTemp->nodeID << 8) | pChildTemp->childID;

				//We are using the TempHumBaro Float type now, convert the forecast
				int nforecast = wsbaroforcast_some_clouds;
				if (Baro <= 980)
					nforecast = wsbaroforcast_heavy_rain;
				else if (Baro <= 995)
				{
					if (Temp > 1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}
				else if (Baro >= 1029)
					nforecast = wsbaroforcast_sunny;
				switch (forecast)
				{
				case bmpbaroforecast_sunny:
					nforecast = wsbaroforcast_sunny;
					break;
				case bmpbaroforecast_cloudy:
					nforecast = wsbaroforcast_cloudy;
					break;
				case bmpbaroforecast_thunderstorm:
					nforecast = wsbaroforcast_heavy_rain;
					break;
				case bmpbaroforecast_rain:
					if (Temp > 1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}

				SendTempHumBaroSensorFloat(cNode, pChildTemp->batValue, Temp, Humidity, Baro, nforecast, (!pChild->childName.empty()) ? pChild->childName : "TempHumBaro");
			}
		}
		else if (pChildTemp) {
			bool bHaveTemp = pChildTemp->GetValue(V_TEMP, Temp);
			if (bHaveTemp)
			{
				cNode = (pChildTemp->nodeID << 8) | pChildTemp->childID;
				SendTempHumSensor(cNode, pChildTemp->batValue, Temp, Humidity, (!pChild->childName.empty()) ? pChild->childName : "TempHum");
			}
		}
		else
		{
			SendHumiditySensor(cNode, pChild->batValue, Humidity);
		}
	}
	break;
	case V_PRESSURE:
	{
		float Baro;
		pChild->GetValue(V_PRESSURE, Baro);
		_tMySensorChild *pSensorTemp = FindChildWithValueType(pChild->nodeID, V_TEMP);
		_tMySensorChild *pSensorHum = FindChildWithValueType(pChild->nodeID, V_HUM);
		int forecast = bmpbaroforecast_unknown;
		_tMySensorChild *pSensorForecast = FindChildWithValueType(pChild->nodeID, V_FORECAST);
		if (pSensorForecast)
		{
			pSensorForecast->GetValue(V_FORECAST, forecast);
		}
		if (forecast == bmpbaroforecast_cloudy)
		{
			if (Baro < 1010)
				forecast = bmpbaroforecast_rain;
		}
		if (pSensorTemp && pSensorHum)
		{
			float Temp;
			int Humidity;
			bool bHaveTemp = pSensorTemp->GetValue(V_TEMP, Temp);
			bool bHaveHumidity = pSensorHum->GetValue(V_HUM, Humidity);

			if (bHaveTemp && bHaveHumidity)
			{
				cNode = (pSensorTemp->nodeID << 8) | pSensorTemp->childID;
				//We are using the TempHumBaro Float type now, convert the forecast
				int nforecast = wsbaroforcast_some_clouds;
				if (Baro <= 980)
					nforecast = wsbaroforcast_heavy_rain;
				else if (Baro <= 995)
				{
					if (Temp > 1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}
				else if (Baro >= 1029)
					nforecast = wsbaroforcast_sunny;
				switch (forecast)
				{
				case bmpbaroforecast_sunny:
					nforecast = wsbaroforcast_sunny;
					break;
				case bmpbaroforecast_cloudy:
					nforecast = wsbaroforcast_cloudy;
					break;
				case bmpbaroforecast_thunderstorm:
					nforecast = wsbaroforcast_heavy_rain;
					break;
				case bmpbaroforecast_rain:
					if (Temp > 1)
						nforecast = wsbaroforcast_rain;
					else
						nforecast = wsbaroforcast_snow;
					break;
				}
				SendTempHumBaroSensorFloat(cNode, pSensorTemp->batValue, Temp, Humidity, Baro, nforecast, (!pChild->childName.empty()) ? pChild->childName : "TempHumBaro");
			}
		}
		else
			SendBaroSensor(pChild->nodeID, pChild->childID, pChild->batValue, Baro, forecast);
	}
	break;
	case V_TRIPPED:
		//	Tripped status of a security sensor. 1 = Tripped, 0 = Untripped
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID, (intValue == 1), 100, "Security Sensor");
		break;
	case V_ARMED:
		//Armed status of a security sensor. 1 = Armed, 0 = Bypassed
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID, (intValue == 1), 100, "Security Sensor");
		break;
	case V_LOCK_STATUS:
		//Lock status. 1 = Locked, 0 = Unlocked
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID, (intValue == 1), 100, "Lock Sensor");
		break;
	case V_STATUS:
		//	Light status. 0 = off 1 = on
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID, (intValue != 0), 100, "Light");
		break;
	case V_SCENE_ON:
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID + intValue, true, 100, "Scene");
		break;
	case V_SCENE_OFF:
		if (pChild->GetValue(vType, intValue))
			UpdateSwitch(pChild->nodeID, pChild->childID + intValue, false, 100, "Scene");
		break;
	case V_PERCENTAGE:
		//	Dimmer value. 0 - 100 %
		if (pChild->GetValue(vType, intValue))
		{
			int level = intValue;
			UpdateSwitch(pChild->nodeID, pChild->childID, (level != 0), level, "Light");
		}
		break;
	case V_RGB:
		//RRGGBB
		if (pChild->GetValue(vType, intValue))
			SendRGBWSwitch(pChild->nodeID, pChild->childID, pChild->batValue, intValue, false, (!pChild->childName.empty()) ? pChild->childName : "RGB Light");
		break;
	case V_RGBW:
		//RRGGBBWW
		if (pChild->GetValue(vType, intValue))
			SendRGBWSwitch(pChild->nodeID, pChild->childID, pChild->batValue, intValue, true, (!pChild->childName.empty()) ? pChild->childName : "RGBW Light");
		break;
	case V_UP:
	case V_DOWN:
	case V_STOP:
		if (pChild->GetValue(vType, intValue))
			SendBlindSensor(pChild->nodeID, pChild->childID, pChild->batValue, intValue, (!pChild->childName.empty()) ? pChild->childName : "Blinds/Window");
		break;
	case V_LIGHT_LEVEL:
		if (pChild->GetValue(vType, floatValue))
		{
			_tLightMeter lmeter;
			lmeter.id1 = 0;
			lmeter.id2 = 0;
			lmeter.id3 = 0;
			lmeter.id4 = pChild->nodeID;
			lmeter.dunit = pChild->childID;
			lmeter.fLux = floatValue;
			lmeter.battery_level = pChild->batValue;
			if (pChild->hasBattery)
				lmeter.battery_level = pChild->batValue;
			sDecodeRXMessage(this, (const unsigned char *)&lmeter);
		}
		break;
	case V_LEVEL:
		if ((pChild->presType == S_DUST)|| (pChild->presType == S_AIR_QUALITY))
		{
			if (pChild->GetValue(vType, intValue))
			{
				_tAirQualityMeter meter;
				meter.len = sizeof(_tAirQualityMeter) - 1;
				meter.type = pTypeAirQuality;
				meter.subtype = sTypeVoltcraft;
				meter.airquality = intValue;
				meter.id1 = pChild->nodeID;
				meter.id2 = pChild->childID;
				sDecodeRXMessage(this, (const unsigned char *)&meter);
			}
		}
		else if (pChild->presType == S_LIGHT_LEVEL)
		{
			if (pChild->GetValue(vType, intValue))
			{
				_tLightMeter lmeter;
				lmeter.id1 = 0;
				lmeter.id2 = 0;
				lmeter.id3 = 0;
				lmeter.id4 = pChild->nodeID;
				lmeter.dunit = pChild->childID;
				lmeter.fLux = (float)intValue;
				lmeter.battery_level = pChild->batValue;
				if (pChild->hasBattery)
					lmeter.battery_level = pChild->batValue;
				sDecodeRXMessage(this, (const unsigned char *)&lmeter);
			}
		}
		else if (pChild->presType == S_SOUND)
		{
			if (pChild->GetValue(vType, intValue))
				SendSoundSensor(cNode, pChild->batValue, intValue, (!pChild->childName.empty()) ? pChild->childName : "Sound Level");
		}
		else if (pChild->presType == S_MOISTURE)
		{
			if (pChild->GetValue(vType, intValue))
			{
				_tGeneralDevice gdevice;
				gdevice.subtype = sTypeSoilMoisture;
				gdevice.intval1 = intValue;
				gdevice.id = pChild->nodeID;
				sDecodeRXMessage(this, (const unsigned char *)&gdevice);
			}
		}
		break;
	case V_RAIN:
		if (pChild->GetValue(vType, floatValue))
			SendRainSensor(cNode, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Rain");
		break;
	case V_WATT:
		{
			if (pChild->GetValue(vType, floatValue))
			{
				_tMySensorChild *pSensorKwh = pNode->FindChildWithValueType(pChild->childID, V_KWH);// FindChildWithValueType(pChild->nodeID, V_KWH);
				if (pSensorKwh) {
					float Kwh;
					if (pSensorKwh->GetValue(V_KWH, Kwh))
						SendKwhMeter(pSensorKwh->nodeID, pSensorKwh->childID, pSensorKwh->batValue, floatValue / 1000.0f, Kwh, (!pChild->childName.empty()) ? pChild->childName : "Meter");
				}
				else {
					SendWattMeter(pChild->nodeID, pChild->childID, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Usage");
				}
			}
		}
		break;
	case V_KWH:
		if (pChild->GetValue(vType, floatValue))
		{
			_tMySensorChild *pSensorWatt = pNode->FindChildWithValueType(pChild->childID, V_WATT);// FindChildWithValueType(pChild->nodeID, V_WATT);
			if (pSensorWatt) {
				float Watt;
				if (pSensorWatt->GetValue(V_WATT, Watt))
					SendKwhMeter(pChild->nodeID, pChild->childID, pChild->batValue, Watt / 1000.0f, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Meter");
			}
			else {
				SendKwhMeter(pChild->nodeID, pChild->childID, pChild->batValue, 0, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Meter");
			}
		}
		break;
	case V_DISTANCE:
		if (pChild->GetValue(vType, floatValue))
			SendDistanceSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue);
		break;
	case V_FLOW:
		//Flow of water in meter (for now send as a percentage sensor)
		if (pChild->GetValue(vType, floatValue))
			SendPercentageSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Water Flow");
		break;
	case V_VOLUME:
		//Water Volume
		if (pChild->GetValue(vType, floatValue))
			SendMeterSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Water");
		break;
	case V_VOLTAGE:
		if (pChild->GetValue(vType, floatValue))
			SendVoltageSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Voltage");
		break;
	case V_UV:
		if (pChild->GetValue(vType, floatValue))
			SendUVSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue);
		break;
	case V_IMPEDANCE:
		if (pChild->GetValue(vType, floatValue))
			SendPercentageSensor(pChild->nodeID, pChild->childID, pChild->batValue, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Impedance");
		break;
	case V_WEIGHT:
		if (pChild->GetValue(vType, floatValue))
		{
			while (1 == 0);
		}
		break;
	case V_CURRENT:
		if (pChild->GetValue(vType, floatValue))
			SendCurrentSensor(cNode, pChild->batValue, floatValue, 0, 0, (!pChild->childName.empty()) ? pChild->childName : "Current");
		break;
	case V_FORECAST:
		if (pChild->GetValue(vType, intValue))
		{
			_tMySensorChild *pSensorBaro = FindChildWithValueType(pChild->nodeID, V_PRESSURE);
			if (pSensorBaro)
			{
				float Baro;
				if (pSensorBaro->GetValue(V_PRESSURE, Baro))
				{
					int forecast = intValue;
					if (forecast == bmpbaroforecast_cloudy)
					{
						if (Baro < 1010)
							forecast = bmpbaroforecast_rain;
					}
					SendBaroSensor(pSensorBaro->nodeID, pSensorBaro->childID, pSensorBaro->batValue, Baro, forecast);
				}
			}
			else
			{
				if (pChild->GetValue(V_FORECAST, stringValue))
				{
					std::stringstream sstr;
					sstr << pChild->nodeID;
					std::string devname = (!pChild->childName.empty()) ? pChild->childName : "Forecast";
					m_sql.UpdateValue(m_HwdID, sstr.str().c_str(), pChild->childID, pTypeGeneral, sTypeTextStatus, 12, pChild->batValue, 0, stringValue.c_str(), devname);
				}
			}
		}
		break;
	case V_WIND:
	case V_GUST:
	case V_DIRECTION:
		MakeAndSendWindSensor(pChild->nodeID, (!pChild->childName.empty()) ? pChild->childName : "Wind");
		break;
	case V_HVAC_SETPOINT_HEAT:
		if (pChild->GetValue(vType, floatValue))
		{
			SendSetPointSensor(pNode->nodeID, pChild->childID, floatValue, (!pChild->childName.empty()) ? pChild->childName : "Heater Setpoint");
		}
		break;
	}
}
Exemplo n.º 29
0
void CSterbox::GetMeterDetails()
{
	std::string sResult;
	std::stringstream szURL;

	//if(m_Password.empty())
	//{
		szURL << "http://" << m_szIPAddress << ":" << m_usIPPort;
	//}
	//else
	//{
	//	szURL << "http://" << m_Username << ":" << m_Password << "@" << m_szIPAddress << ":" << m_usIPPort;
	//}

	szURL << "/x.cgi"; 

	if (!HTTPClient::GET(szURL.str(),sResult))
	{
		_log.Log(LOG_ERROR,"Sterbox: Error connecting to: %s", m_szIPAddress.c_str());
		return;
	}
	std::vector<std::string> results;
	std::vector<std::string> outputs;
	std::vector<std::string> inputs;
	std::vector<std::string> analog;
	StringSplit(sResult, "<br>", results);
	if (results.size()<8)
	{
		_log.Log(LOG_ERROR,"Sterbox: Result 8 Error connecting to: %s", m_szIPAddress.c_str());
		return;
	}
	//if (results[0] != "<body>")
	std::string tmpstr;
	std::string tmpstr2;
	std::string tmpinp;
	tmpstr = results[0];
	if (tmpstr.find("<title>SterBox_State</title>") != std::string::npos)
	{
		_log.Log(LOG_ERROR, "Sterbox: Error getting status");
		return;
	}
	size_t ii;
	size_t jj;
	int pos1;
	int Idx = 0;

	if (m_Username.empty())
	{
		StringSplit("o,o,o,o,i,i,i,i", ",", inputs);
	}
	else
	{
		StringSplit(m_Username, ",", inputs);
		//_log.Log(LOG_ERROR,"Sterbox: Username : %s , IP: %s", m_Username.c_str(), m_szIPAddress.c_str());
	}

	for (ii = 1; ii < results.size(); ii++)
	{
		tmpstr = results[ii];
		if (tmpstr.find("OU") != std::string::npos)
		{
			tmpstr = tmpstr.substr(strlen("OU"));
			pos1 = tmpstr.find("=");
			if (pos1 != std::string::npos)
			{	
				tmpstr = tmpstr.substr(pos1+1);
				//_log.Log(LOG_ERROR,"Sterbox: OU Status: %s", tmpstr.c_str());
				StringSplit(tmpstr, ",", outputs);
				for (jj = 0; jj < inputs.size(); jj++) 
				{	
					tmpinp = inputs[jj];
					//if (( jj < 4 || jj > 7  ))
					pos1 = tmpinp.find("o");
					if (pos1 != std::string::npos)
					{
					int lValue = 0;
					//tmpstr = tmpstr.substr(pos1+1);
					tmpstr2 = outputs[jj];
					//_log.Log(LOG_ERROR,"Sterbox: OU Status: %s", tmpstr2.c_str());
					pos1 = tmpstr2.find("s");
					if (pos1 != std::string::npos)
					{
						lValue = 1;
					}
					else
					{
						lValue = 0;
					}
					std::stringstream sstr;
					sstr << "Relay " << jj;
					UpdateSwitch(1, jj, (lValue == 1) ? true : false, 100, sstr.str());
					}
				}
			}
		}
		else if (tmpstr.find("IN") != std::string::npos)
		{
			tmpstr = tmpstr.substr(strlen("IN"));
			pos1 = tmpstr.find("=");
			if (pos1 != std::string::npos)
			{	
				tmpstr = tmpstr.substr(pos1+1);
				//_log.Log(LOG_ERROR,"Sterbox: OU Status: %s", tmpstr.c_str());
				StringSplit(tmpstr, ",", outputs);
				for (jj = 0; jj < inputs.size(); jj++) 
				{	
					tmpinp = inputs[jj];
					//if (( jj > 3 && jj < 8  ))
					pos1 = tmpinp.find("i");
					if (pos1 != std::string::npos)
					{
					int lValue = 0;
					//tmpstr = tmpstr.substr(pos1+1);
					tmpstr2 = outputs[jj];
					//_log.Log(LOG_ERROR,"Sterbox: OU Status: %s", tmpstr2.c_str());
					pos1 = tmpstr2.find("S");
					if (pos1 != std::string::npos)
					{
						lValue = 1;
					}
					else
					{
						lValue = 0;
					}
					std::stringstream sstr;
					sstr << "Relay " << jj;
					UpdateSwitch(1, jj, (lValue == 1) ? true : false, 100, sstr.str());
					}
				}
			}
		}
		else if (tmpstr.find("AN") != std::string::npos)
		{
			tmpstr = tmpstr.substr(strlen("AN"));
			pos1 = tmpstr.find("=");
			if (pos1 != std::string::npos)
			{
				tmpstr = tmpstr.substr(pos1+1);
				StringSplit(tmpstr, ",", outputs);
				if (m_Password.empty())
				{
					StringSplit("t,t,t", ",", analog);
				}
				else
				{
					//StringSplit("t,t,t", ",", inputs);
					StringSplit(m_Password, ",", analog);
				//_log.Log(LOG_ERROR,"Sterbox: Pass : %s", m_Password.c_str());

				}
				for (jj = 0; jj < 3; jj++)
				{
					tmpstr2 = outputs[jj];
					tmpinp = analog[jj];
					tmpstr2 = tmpstr2.substr(1, 10);

					float lValue = (float)atof(tmpstr2.c_str());
					std::stringstream sstr;
					sstr << "Analog " << jj;
					pos1 = tmpinp.find("t");
					if (pos1 != std::string::npos)
					{
						SendTempSensor(jj,255,lValue, sstr.str());
					}
					pos1 = tmpinp.find("v");
					if (pos1 != std::string::npos)
					{
						SendVoltageSensor(0, jj, 255, lValue, sstr.str());
					}
					pos1 = tmpinp.find("l");
					if (pos1 != std::string::npos)
					{
						SendLuxSensor(0, jj, 255,lValue, sstr.str());
					}
					pos1 = tmpinp.find("h");
					if (pos1 != std::string::npos)
					{
						SendHumiditySensor(jj,255,int(lValue), sstr.str());
					}
	
					//SendTempSensor(jj,255,lValue, sstr.str());
					//_log.Log(LOG_ERROR,"Sterbox: OU Status: %s", tmpstr2.c_str());

				}
				//Idx = atoi(tmpstr.substr(0, pos1).c_str());
				//tmpstr = tmpstr.substr(pos1 + 1);
				//pos1 = tmpstr.find("<");
				//if (pos1 != std::string::npos)
				//{
				//	int lValue = atoi(tmpstr.substr(0, pos1).c_str());
				//	float voltage = (float)(5.0f / 1023.0f)*lValue;
				//	if (voltage > 5.0f)
				//		voltage = 5.0f;
				//	std::stringstream sstr;
				//	sstr << "Voltage " << Idx;
				//	SendVoltageSensor(0, Idx, 255, voltage, sstr.str());
				//}
			}
		}
	}
}
Exemplo n.º 30
0
void CToonThermostat::GetMeterDetails()
{
	if (m_UserName.size()==0)
		return;
	if (m_Password.size()==0)
		return;
	std::string sResult;
	if (m_bDoLogin)
	{
		if (!Login())
		return;
	}
	std::vector<std::string> ExtraHeaders;

	std::stringstream sstr2;
	sstr2 << "?clientId=" << m_ClientID
		<< "&clientIdChecksum=" << m_ClientIDChecksum
		<< "&random=" << GetRandom();
	std::string szPostdata = sstr2.str();
	//Get Data
	std::string sURL = TOON_HOST + TOON_UPDATE_PATH + szPostdata;
	if (!HTTPClient::GET(sURL, ExtraHeaders, sResult))
	{
		_log.Log(LOG_ERROR, "ToonThermostat: Error getting current state!");
		m_bDoLogin = true;
		return;
	}
	time_t atime = mytime(NULL);

#ifdef DEBUG_ToonThermostat
	char szFileName[MAX_PATH];
	static int sNum = 1;
	sprintf_s(szFileName, "E:\\toonresult_%03d.txt", sNum++);
	SaveString2Disk(sResult, szFileName);
#endif

	Json::Value root;
	Json::Reader jReader;
	if (!jReader.parse(sResult, root))
	{
		_log.Log(LOG_ERROR, "ToonThermostat: Invalid data received!");
		m_bDoLogin = true;
		return;
	}
	if (root["success"].empty() == true)
	{
		_log.Log(LOG_ERROR, "ToonThermostat: ToonState request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}
	if (root["success"] == false)
	{
		_log.Log(LOG_ERROR, "ToonThermostat: ToonState request not successful, restarting..!");
		m_bDoLogin = true;
		return;
	}

	//ZWave Devices
	if (root["deviceStatusInfo"].empty() == false)
	{
		if (root["deviceStatusInfo"]["device"].empty() == false)
		{
			int totDevices = root["deviceStatusInfo"]["device"].size();
			for (int ii = 0; ii < totDevices; ii++)
			{
				std::string deviceName = root["deviceStatusInfo"]["device"][ii]["name"].asString();
				std::string uuid = root["deviceStatusInfo"]["device"][ii]["devUUID"].asString();
				int state = root["deviceStatusInfo"]["device"][ii]["currentState"].asInt();

				int Idx;
				if (!GetUUIDIdx(uuid, Idx))
				{
					if (!AddUUID(uuid, Idx))
					{
						_log.Log(LOG_ERROR, "ToonThermostat: Error adding UUID to database?! Uuid=%s", uuid.c_str());
						return;
					}
				}
				UpdateSwitch(Idx, state != 0, deviceName);
			}
		}
	}

	//thermostatInfo
	if (root["thermostatInfo"].empty() == false)
	{
		float currentTemp = root["thermostatInfo"]["currentTemp"].asFloat() / 100.0f;
		float currentSetpoint = root["thermostatInfo"]["currentSetpoint"].asFloat() / 100.0f;
		SendSetPointSensor(1, currentSetpoint, "Room Setpoint");
		SendTempSensor(1, currentTemp, "Room Temperature");

		//int programState = root["thermostatInfo"]["programState"].asInt();
		//int activeState = root["thermostatInfo"]["activeState"].asInt();

		if (root["thermostatInfo"]["burnerInfo"].empty() == false)
		{
			//burnerinfo
			//0=off
			//1=heating
			//2=hot water
			//3=pre-heating
			int burnerInfo = 0;

			if (root["thermostatInfo"]["burnerInfo"].isString())
			{
				burnerInfo = atoi(root["thermostatInfo"]["burnerInfo"].asString().c_str());
			}
			else if (root["thermostatInfo"]["burnerInfo"].isInt())
			{
				burnerInfo = root["thermostatInfo"]["burnerInfo"].asInt();
			}
			if (burnerInfo == 1)
			{
				UpdateSwitch(113, true, "HeatingOn");
				UpdateSwitch(114, false, "TapwaterOn");
				UpdateSwitch(115, false, "PreheatOn");
			}
			else if (burnerInfo == 2)
			{
				UpdateSwitch(113, false, "HeatingOn");
				UpdateSwitch(114, true, "TapwaterOn");
				UpdateSwitch(115, false, "PreheatOn");
			}
			else if (burnerInfo == 3)
			{
				UpdateSwitch(113, false, "HeatingOn");
				UpdateSwitch(114, false, "TapwaterOn");
				UpdateSwitch(115, true, "PreheatOn");
			}
			else
			{
				UpdateSwitch(113, false, "HeatingOn");
				UpdateSwitch(114, false, "TapwaterOn");
				UpdateSwitch(115, false, "PreheatOn");
			}
		}
	}

	if (root["gasUsage"].empty() == false)
	{
		m_p1gas.gasusage = (unsigned long)(root["gasUsage"]["meterReading"].asFloat());
	}

	if (root["powerUsage"].empty() == false)
	{
		m_p1power.powerusage1 = (unsigned long)(root["powerUsage"]["meterReadingLow"].asFloat());
		m_p1power.powerusage2 = (unsigned long)(root["powerUsage"]["meterReading"].asFloat());

		if (root["powerUsage"]["meterReadingProdu"].empty() == false)
		{
			m_p1power.powerdeliv1 = (unsigned long)(root["powerUsage"]["meterReadingLowProdu"].asFloat());
			m_p1power.powerdeliv2 = (unsigned long)(root["powerUsage"]["meterReadingProdu"].asFloat());
		}

		m_p1power.usagecurrent = (unsigned long)(root["powerUsage"]["value"].asFloat());	//Watt
	}

	//Send Electra if value changed, or at least every 5 minutes
	if (
		(m_p1power.usagecurrent != m_lastelectrausage) ||
		(atime - m_lastSharedSendElectra >= 300)
		)
	{
		if ((m_p1power.powerusage1 != 0) || (m_p1power.powerusage2 != 0) || (m_p1power.powerdeliv1 != 0) || (m_p1power.powerdeliv2 != 0))
		{
			m_lastSharedSendElectra = atime;
			m_lastelectrausage = m_p1power.usagecurrent;
			sDecodeRXMessage(this, (const unsigned char *)&m_p1power);
		}
	}
	
	//Send GAS if the value changed, or at least every 5 minutes
	if (
		(m_p1gas.gasusage != m_lastgasusage) ||
		(atime - m_lastSharedSendGas >= 300)
		)
	{
		if (m_p1gas.gasusage != 0)
		{
			m_lastSharedSendGas = atime;
			m_lastgasusage = m_p1gas.gasusage;
			sDecodeRXMessage(this, (const unsigned char *)&m_p1gas);
		}
	}
}