Ejemplo n.º 1
0
bool CPhilipsHue::GetLights(const Json::Value &root)
{
	if (root["lights"].empty())
		return false;

	for (Json::Value::const_iterator iLight = root["lights"].begin(); iLight != root["lights"].end(); ++iLight)
	{
		Json::Value light = *iLight;
		if (light.isObject())
		{
			std::string szLID = iLight.key().asString();
			int lID = atoi(szLID.c_str());
			_tHueLight tlight;
			tlight.level = 0;
			tlight.sat = 0; // Philips 0- 254, should be corrected to 0 - 255 ?
			tlight.hue = 0; // Philips 0 - 65535, should be converted to 0 - 255 ?
			tlight.on = light["state"]["on"].asBool();
			bool bDoSend = true;
			_eHueLightType LType = HLTYPE_NORMAL;
	
			if (!light["state"]["bri"].empty())
			{
				//Lamp with brightness control
				LType = HLTYPE_DIM;
				int tbri = light["state"]["bri"].asInt();
				if ((tbri != 0) && (tbri != 255))
					tbri += 1; //hue reports 255 as 254
				tlight.level = int((100.0f / 255.0f)*float(tbri));
			}
			if ((!light["state"]["sat"].empty()) && (!light["state"]["hue"].empty()))
			{
				//Lamp with hue/sat control
				LType = HLTYPE_RGBW;
				tlight.sat = light["state"]["sat"].asInt();
				tlight.hue = light["state"]["hue"].asInt();
			}
			if (m_lights.find(lID) != m_lights.end())
			{
				_tHueLight alight = m_lights[lID];
				if (
					(alight.on == tlight.on) &&
					(alight.level == tlight.level) &&
					(alight.sat == tlight.sat) &&
					(alight.hue == tlight.hue)
					)
				{
					bDoSend = false;
				}
			}
			m_lights[lID] = tlight;
			if (bDoSend)
			{
				//_log.Log(LOG_STATUS, "HueBridge state change: tbri = %d, level = %d", tbri, tlight.level);
				InsertUpdateSwitch(lID, LType, tlight.on, tlight.level, tlight.sat, tlight.hue, light["name"].asString(), "");
			}
		}
	}
	return true;
}
Ejemplo n.º 2
0
void Config_Cache::refresh_server_id_ip_cache(void) {
	const Json::Value &game_server_list = CONFIG_INSTANCE->config_json()["server_global_conf"]["server_maintainer"]["game_server_list"];
	int server_id = 0;
	IP_Info ip_info;
	for (Json::Value::const_iterator it = game_server_list.begin(); it != game_server_list.end(); ++it) {
		server_id = atoi(it.key().asCString());
		ip_info.telecom_ip = (*it)["telecom_ip"].asString();
		ip_info.unicom_ip = (*it)["unicom_ip"].asString();
		set_map_second_value_by_key(server_id, server_ip_ip_cache_, ip_info);
	}
}
Ejemplo n.º 3
0
// Recursive function to convert JSON --> Lua table
static bool push_json_value_helper(lua_State *L, const Json::Value &value,
		int nullindex)
{
	switch(value.type()) {
		case Json::nullValue:
		default:
			lua_pushvalue(L, nullindex);
			break;
		case Json::intValue:
			lua_pushinteger(L, value.asInt());
			break;
		case Json::uintValue:
			lua_pushinteger(L, value.asUInt());
			break;
		case Json::realValue:
			lua_pushnumber(L, value.asDouble());
			break;
		case Json::stringValue:
			{
				const char *str = value.asCString();
				lua_pushstring(L, str ? str : "");
			}
			break;
		case Json::booleanValue:
			lua_pushboolean(L, value.asInt());
			break;
		case Json::arrayValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
				push_json_value_helper(L, *it, nullindex);
				lua_rawseti(L, -2, it.index() + 1);
			}
			break;
		case Json::objectValue:
			lua_newtable(L);
			for (Json::Value::const_iterator it = value.begin();
					it != value.end(); ++it) {
#ifndef JSONCPP_STRING
				const char *str = it.memberName();
				lua_pushstring(L, str ? str : "");
#else
				std::string str = it.name();
				lua_pushstring(L, str.c_str());
#endif
				push_json_value_helper(L, *it, nullindex);
				lua_rawset(L, -3);
			}
			break;
	}
	return true;
}
Ejemplo n.º 4
0
CRpcHelper::str_unique_list CRpcHelper::GetLabelList()
{
    str_unique_list result;

    Json::Value args;
    args.append( MAX_CONF );
    const Json::Value labels = json_from_string( m_rpc->Send( "listaccounts", args ) );

    for( Json::Value::const_iterator it = labels.begin(); it != labels.end(); ++it )
    {
        bool ok = result.insert( it.key().asString() ).second;
        assert( ok );
    }
    return result;
}
Ejemplo n.º 5
0
bool Tree::ParseFromJsonInternal(const Json::Value &json)
{
    size_t index = 0;
    for (Json::Value::const_iterator p = json.begin(); p != json.end(); ++p) {
        const Json::Value &j = *p;
        std::string key = p.name();
        if (key.empty()) {
            std::ostringstream s;
            s << '[' << index++ << ']';
            key = s.str();
        }

        std::string full_path = GetFullPath(key);
        if (j.isArray() || j.isObject()) { // Go recursively.
            Tree *child = new Tree(full_path, key, std::string());
            _children.insert(std::make_pair(key, child));

            if (!child->ParseFromJsonInternal(j)) {
                return false;
            }

            continue;
        }

        std::ostringstream s;
#ifdef JSON_HAS_INT64
        if (j.isInt64() ) { s << j.asInt64();   } else
        if (j.isUInt64()) { s << j.asUInt64();  } else
#endif
        if (j.isInt()   ) { s << j.asInt();     } else
        if (j.isUInt()  ) { s << j.asUInt();    } else
        if (j.isDouble()) { s << j.asDouble();  } else
                          { s << j.asString();  }

        const std::string &value = s.str();
        Tree *child = new Tree(full_path, key, value);
        _children.insert(std::make_pair(key, child));
    }

    return true;
}
Ejemplo n.º 6
0
bool cStatSerializer::LoadStatFromJSON(const Json::Value & a_In)
{
	m_Manager->Reset();

	for (Json::Value::const_iterator it = a_In.begin() ; it != a_In.end() ; ++it)
	{
		AString StatName = it.key().asString();

		eStatistic StatType = cStatInfo::GetType(StatName);

		if (StatType == statInvalid)
		{
			LOGWARNING("Invalid statistic type \"%s\"", StatName.c_str());
			continue;
		}

		const Json::Value & Node = *it;

		if (Node.isInt())
		{
			m_Manager->SetValue(StatType, Node.asInt());
		}
		else if (Node.isObject())
		{
			StatValue Value = Node.get("value", 0).asInt();

			// TODO 2014-05-11 xdot: Load "progress"

			m_Manager->SetValue(StatType, Value);
		}
		else
		{
			LOGWARNING("Invalid statistic value for type \"%s\"", StatName.c_str());
		}
	}

	return true;
}
Ejemplo n.º 7
0
void JsonConf::reLoad()
{
    struct stat st;
    Thread::RWLock::WRScoped l(locker);

    for( stat(fileName.c_str(), &st); mTime != st.st_mtime; stat( fileName.c_str(), &st) ){
        mTime = st.st_mtime;
        std::ifstream ifs( fileName.c_str() );
        SectionType section;
        SectionMap sMap;
        if( !jsonConfMap.empty() ){
            jsonConfMap.clear();
        }
        
        if( !ifs.is_open() ){
            Logger::file()->error("json file open failed! {}", fileName);
            return;
        }
        Json::Reader reader;
        Json::Value root;
        if( !reader.parse(ifs, root, false) ){
            Logger::file()->error("json file parse failed! {}", fileName);
            return;
        }

        for( Json::Value::const_iterator fit = root.begin(); fit != root.end(); ++fit){
            std::string sectionKey = fit.key().asString();
            SectionMap mapTmp;
            for( Json::Value::const_iterator sit = fit->begin(); sit != fit->end(); ++sit ){
                std::string key = sit.key().asString();
                mapTmp[key] = sit->asString();
            }
            if( !mapTmp.empty() ){
                jsonConfMap[sectionKey] = mapTmp;
            }
        }
    }
}
Ejemplo n.º 8
0
bool CPhilipsHue::GetScenes(const Json::Value &root)
{
	if (root["scenes"].empty())
		return false;

	for (Json::Value::const_iterator iScene = root["scenes"].begin(); iScene != root["scenes"].end(); ++iScene)
	{
		Json::Value scene = *iScene;
		if (scene.isObject())
		{
			_tHueScene hscene;
			hscene.id = iScene.key().asString();;
			hscene.name = scene["name"].asString();
			hscene.lastupdated = scene["lastupdated"].asString();
			if (hscene.lastupdated.empty())
				continue; //old scene/legacy scene
			
			//Strip some info
			size_t tpos = hscene.name.find(" from ");
			if (tpos != std::string::npos)
			{
				hscene.name = hscene.name.substr(0, tpos);
			}

			bool bDoSend = true;
			if (m_scenes.find(hscene.id) != m_scenes.end())
			{
				_tHueScene ascene = m_scenes[hscene.id];
				if (ascene.lastupdated == hscene.lastupdated)
				{
					bDoSend = false;
				}
			}
			m_scenes[hscene.id] = hscene;

			if (bDoSend)
			{
				int sID = -1;
				std::vector<std::vector<std::string> > result;
				result = m_sql.safe_query("SELECT ID FROM WOLNodes WHERE (HardwareID==%d) AND (MacAddress=='%q')", m_HwdID, hscene.id.c_str());
				if (!result.empty())
				{
					//existing scene
					sID = atoi(result[0][0].c_str());
				}
				else
				{
					//New scene
					m_sql.safe_query("INSERT INTO WOLNodes (HardwareID, Name, MacAddress) VALUES (%d, '%q', '%q')", m_HwdID, hscene.name.c_str(), hscene.id.c_str());
					result = m_sql.safe_query("SELECT ID FROM WOLNodes WHERE (HardwareID==%d) AND (MacAddress=='%q')", m_HwdID, hscene.id.c_str());
					if (result.empty())
					{
						_log.Log(LOG_ERROR, "Philips Hue: Problem adding new Scene!!");
						return false;
					}
					sID = atoi(result[0][0].c_str());
				}
				std::string Name = "Scene " + hscene.name;
				InsertUpdateSwitch(2000 + sID, HLTYPE_SCENE, false, 100, 0, 0, Name, hscene.id);
			}
		}
	}
	return true;
}
Ejemplo n.º 9
0
// Note:
// Some groups have only White lights,
// We whould find a way to have these working as normal lights instead of RGBW
bool CPhilipsHue::GetGroups(const Json::Value &root)
{
	//Groups (0=All)

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

	_eHueLightType LType;

	for (Json::Value::const_iterator iGroup = root["groups"].begin(); iGroup != root["groups"].end(); ++iGroup)
	{
		Json::Value group = *iGroup;
		if (group.isObject())
		{
			std::string szGID = iGroup.key().asString();
			int gID = atoi(szGID.c_str());
			_tHueLight tstate;
			tstate.on = false;
			tstate.level = 0;
			tstate.sat = 0;
			tstate.hue = 0;

			if (!group["action"]["on"].empty())
				tstate.on = group["action"]["on"].asBool();
			if (!group["action"]["bri"].empty())
			{
				int tbri = group["action"]["bri"].asInt();
				if ((tbri != 0) && (tbri != 255))
					tbri += 1; //hue reports 255 as 254
				tstate.level = int((100.0f / 255.0f)*float(tbri));
			}

			LType = HLTYPE_RGBW;// HLTYPE_NORMAL;

			if (!group["action"]["sat"].empty())
			{
				tstate.sat = group["action"]["sat"].asInt();
				//LType = HLTYPE_RGBW;
			}
			if (!group["action"]["hue"].empty())
			{
				tstate.hue = group["action"]["hue"].asInt();
				//LType = HLTYPE_RGBW;
			}
			
			bool bDoSend = true;
			if (m_groups.find(gID) != m_groups.end())
			{
				_tHueGroup agroup = m_groups[gID];
				if (
					(agroup.gstate.on == tstate.on) &&
					(agroup.gstate.level == tstate.level) &&
					(agroup.gstate.sat == tstate.sat) &&
					(agroup.gstate.hue == tstate.hue)
					)
				{
					bDoSend = false;
				}
			}
			m_groups[gID].gstate = tstate;
			if (bDoSend)
			{
				std::string Name = "Group " + group["name"].asString();
				InsertUpdateSwitch(1000 + gID, LType, tstate.on, tstate.level, tstate.sat, tstate.hue, Name, "");
			}
		}
	}
	//Special Request for Group0 (All Lights)
	std::stringstream sstr2;
	sstr2 << "http://" << m_IPAddress
		<< ":" << m_Port
		<< "/api/" << m_UserName
		<< "/groups/0";
	std::string sResult;
	std::vector<std::string> ExtraHeaders;
	if (!HTTPClient::GET(sstr2.str(), ExtraHeaders, sResult))
	{
		//No group all(0)
		return true;
	}
	Json::Reader jReader;
	Json::Value root2;
	bool ret = jReader.parse(sResult, root2);

	if (!ret)
	{
		_log.Log(LOG_ERROR, "Philips Hue: Invalid data received, or invalid IPAddress/Username!");
		return false;
	}

	if (sResult.find("\"error\":") != std::string::npos)
	{
		//We had an error
		_log.Log(LOG_ERROR, "Philips Hue: Error received: %s", root2[0]["error"]["description"].asString().c_str());
		return false;
	}

	if (sResult.find("lights") == std::string::npos)
	{
		return false;
	}
	_tHueLight tstate;
	tstate.on = false;
	tstate.level = 0;
	tstate.sat = 0;
	tstate.hue = 0;

	LType = HLTYPE_RGBW;// HLTYPE_NORMAL;

	if (!root2["action"]["on"].empty())
		tstate.on = root2["action"]["on"].asBool();
	if (!root2["action"]["bri"].empty())
	{
		int tbri = root2["action"]["bri"].asInt();
		if ((tbri != 0) && (tbri < 3))
			tbri = 3;
		tstate.level = int((100.0f / 254.0f)*float(tbri));
	}
	if (!root2["action"]["sat"].empty())
	{
		tstate.sat = root2["action"]["sat"].asInt();
		//LType = HLTYPE_RGBW;
	}
	if (!root2["action"]["hue"].empty())
	{
		tstate.hue = root2["action"]["hue"].asInt();
		//LType = HLTYPE_RGBW;
	}

	bool bDoSend = true;
	int gID = 0;
	if (m_groups.find(gID) != m_groups.end())
	{
		_tHueGroup agroup = m_groups[gID];
		if (
			(agroup.gstate.on == tstate.on) &&
			(agroup.gstate.level == tstate.level) &&
			(agroup.gstate.sat == tstate.sat) &&
			(agroup.gstate.hue == tstate.hue)
			)
		{
			bDoSend = false;
		}
	}
	m_groups[gID].gstate = tstate;
	if (bDoSend)
	{
		std::string Name = "Group All Lights";
		InsertUpdateSwitch(1000 + gID, LType, tstate.on, tstate.level, tstate.sat, tstate.hue, Name,"");
	}
	return true;
}
Ejemplo n.º 10
0
// {
//   account: <account>|<account_public_key>
//   account_index: <number>        // optional, defaults to 0.
//   ledger_hash : <ledger>
//   ledger_index : <ledger_index>
//   limit: integer                 // optional
//   marker: opaque                 // optional, resume previous query
// }
Json::Value doAccountOffers (RPC::Context& context)
{
    auto const& params (context.params);
    if (! params.isMember (jss::account))
        return RPC::missing_field_error (jss::account);

    Ledger::pointer ledger;
    Json::Value result (RPC::lookupLedger (params, ledger, context.netOps));
    if (! ledger)
        return result;

    std::string strIdent (params[jss::account].asString ());
    bool bIndex (params.isMember (jss::account_index));
    int const iIndex (bIndex ? params[jss::account_index].asUInt () : 0);
    DivvyAddress divvyAddress;

    Json::Value const jv = RPC::accountFromString (
        divvyAddress, bIndex, strIdent, iIndex, false);
    if (! jv.empty ())
    {
        for (Json::Value::const_iterator it (jv.begin ()); it != jv.end (); ++it)
            result[it.memberName ()] = it.key ();

        return result;
    }

    // Get info on account.
    result[jss::account] = divvyAddress.humanAccountID ();

    if (bIndex)
        result[jss::account_index] = iIndex;

    if (! ledger->exists(getAccountRootIndex(
            divvyAddress.getAccountID())))
        return rpcError (rpcACT_NOT_FOUND);

    unsigned int limit;
    if (params.isMember (jss::limit))
    {
        auto const& jvLimit (params[jss::limit]);
        if (! jvLimit.isIntegral ())
            return RPC::expected_field_error (jss::limit, "unsigned integer");

        limit = jvLimit.isUInt () ? jvLimit.asUInt () :
            std::max (0, jvLimit.asInt ());

        if (context.role != Role::ADMIN)
        {
            limit = std::max (RPC::Tuning::minOffersPerRequest,
                std::min (limit, RPC::Tuning::maxOffersPerRequest));
        }
    }
    else
    {
        limit = RPC::Tuning::defaultOffersPerRequest;
    }

    AccountID const& raAccount (divvyAddress.getAccountID ());
    Json::Value& jsonOffers (result[jss::offers] = Json::arrayValue);
    std::vector <std::shared_ptr<SLE const>> offers;
    unsigned int reserve (limit);
    uint256 startAfter;
    std::uint64_t startHint;

    if (params.isMember(jss::marker))
    {
        // We have a start point. Use limit - 1 from the result and use the
        // very last one for the resume.
        Json::Value const& marker (params[jss::marker]);

        if (! marker.isString ())
            return RPC::expected_field_error (jss::marker, "string");

        startAfter.SetHex (marker.asString ());
        auto const sleOffer = fetch (*ledger, startAfter,
            getApp().getSLECache());

        if (sleOffer == nullptr ||
            sleOffer->getType () != ltOFFER ||
            raAccount != sleOffer->getFieldAccount160 (sfAccount))
        {
            return rpcError (rpcINVALID_PARAMS);
        }

        startHint = sleOffer->getFieldU64(sfOwnerNode);

        // Caller provided the first offer (startAfter), add it as first result
        Json::Value& obj (jsonOffers.append (Json::objectValue));
        sleOffer->getFieldAmount (sfTakerPays).setJson (obj[jss::taker_pays]);
        sleOffer->getFieldAmount (sfTakerGets).setJson (obj[jss::taker_gets]);
        obj[jss::seq] = sleOffer->getFieldU32 (sfSequence);
        obj[jss::flags] = sleOffer->getFieldU32 (sfFlags);

        offers.reserve (reserve);
    }
    else
    {
        startHint = 0;
        // We have no start point, limit should be one higher than requested.
        offers.reserve (++reserve);
    }

    if (! forEachItemAfter(*ledger, raAccount, getApp().getSLECache(),
            startAfter, startHint, reserve,
        [&offers](std::shared_ptr<SLE const> const& offer)
        {
            if (offer->getType () == ltOFFER)
            {
                offers.emplace_back (offer);
                return true;
            }

            return false;
        }))
    {
        return rpcError (rpcINVALID_PARAMS);
    }

    if (offers.size () == reserve)
    {
        result[jss::limit] = limit;

        result[jss::marker] = to_string (offers.back ()->getIndex ());
        offers.pop_back ();
    }

    for (auto const& offer : offers)
    {
        Json::Value& obj (jsonOffers.append (Json::objectValue));
        offer->getFieldAmount (sfTakerPays).setJson (obj[jss::taker_pays]);
        offer->getFieldAmount (sfTakerGets).setJson (obj[jss::taker_gets]);
        obj[jss::seq] = offer->getFieldU32 (sfSequence);
        obj[jss::flags] = offer->getFieldU32 (sfFlags);
    }

    context.loadType = Resource::feeMediumBurdenRPC;
    return result;
}