/// <summary>
    /// PlayFab Title cannot be created from SDK tests, so you must provide your titleId to run unit tests.
    /// (Also, we don't want lots of excess unused titles)
    /// </summary>
    bool SetTitleInfo(Document &testInputs)
    {
        CCLOG("%s", "SetTitleInfo");

        // Parse all the inputs
        auto end = testInputs.MemberEnd();
        auto each = testInputs.FindMember("titleId");
        if (each != end) PlayFabSettings::titleId = each->value.GetString(); else return false;
        each = testInputs.FindMember("developerSecretKey");
        if (each != end) PlayFabSettings::developerSecretKey = each->value.GetString(); else return false;

        string blah;
        each = testInputs.FindMember("titleCanUpdateSettings");
        if (each != end) blah = each->value.GetString(); else return false;
        TITLE_CAN_UPDATE_SETTINGS = (blah.compare("true") == 0 || blah.compare("True") == 0 || blah.compare("TRUE") == 0);

        each = testInputs.FindMember("userName");
        if (each != end) USER_NAME = each->value.GetString(); else return false;
        each = testInputs.FindMember("userEmail");
        if (each != end) USER_EMAIL = each->value.GetString(); else return false;
        each = testInputs.FindMember("userPassword");
        if (each != end) USER_PASSWORD = each->value.GetString(); else return false;

        each = testInputs.FindMember("characterName");
        if (each != end) CHAR_NAME = each->value.GetString(); else return false;

        // Verify all the inputs won't cause crashes in the tests
        return !PlayFabSettings::titleId.empty()
            && !PlayFabSettings::developerSecretKey.empty()
            && !USER_NAME.empty()
            && !USER_EMAIL.empty()
            && !USER_PASSWORD.empty()
            && !CHAR_NAME.empty();
    }
Exemplo n.º 2
0
LRESULT Cdispatcher_uiDlg::OnReadStats(WPARAM wparam, LPARAM lParam) {
	char *buf = (char*)wparam;
	Document d;
	if (d.Parse(buf).HasParseError()) {
		int unicodeLen = MultiByteToWideChar(CP_ACP, 0, buf, -1, 0, 0);
		wchar_t *wc = new wchar_t[unicodeLen+1];
		memset(wc, 0, (unicodeLen + 1)*sizeof(wchar_t));
		MultiByteToWideChar(CP_ACP, 0, buf, -1, wc, unicodeLen);
		m_static_msg.SetWindowText(wc);
		delete[]wc;
	}
	else {
		//read/stats
		uint64_t count_service = 0;
		uint64_t count_dispatch = 0;
		for (Value::ConstMemberIterator iter = d.MemberBegin(); iter != d.MemberEnd(); ++iter) {
			const char * app = iter->name.GetString();
			count_service += iter->value["service"].GetUint64();
			count_dispatch += iter->value["dispatch"].GetUint64();
		}

		wchar_t tmp[1024];
		swprintf_s(tmp, L"%lld", count_dispatch);
		m_dispatch_count.SetWindowTextW(tmp);
		swprintf_s(tmp, L"%lld", count_service);
		m_service_count.SetWindowTextW(tmp);
	}
	return 0;
}
Exemplo n.º 3
0
/**
 * Merge one set of options into this one.
 * All settings in the input take precedence over anything currently stored.
 * @param json_string The serialised JSON string to merge from.
 * @return true iff successfully merged.
 */
bool Options::Merge(const char *json_string) {
    if (json_string) {
        Document d;
        d.Parse<0>(json_string);
        if (!d.HasParseError() && d.IsObject()) {
            //Loop through each family
            for (Value::ConstMemberIterator it = d.MemberBegin();
                 it != d.MemberEnd(); it++)
            {
                //Do we have a family of options? (e.g. an object)
                if (it->value.IsObject()) {
                    SetFamily(it->name.GetString());
                    //Loop through each option
                    for (Value::ConstMemberIterator optit = it->value.MemberBegin();
                         optit != it->value.MemberEnd(); optit++)
                    {
                        const char *optkey = optit->name.GetString();
                        switch (optit->value.GetType()) {
                            case kFalseType: case kTrueType:
                                Set(optkey, optit->value.GetBool());
                            case kNumberType:
                                if (optit->value.IsInt()) {
                                    Set(optkey, optit->value.GetInt());
                                } else if (optit->value.IsNumber()) {
                                    Set(optkey, optit->value.GetDouble());
                                } else if (optit->value.IsBool()) {
                                    Set(optkey, optit->value.GetBool());
                                }
                            break;
                            case kStringType:
                                Set(optkey, optit->value.GetString());
                            break;
                            case kNullType: //Ignore
                            break;
                            default:
                                Log(LOG_WARNING, "Ignoring unknown option %s of type %d",
                                    optkey, optit->value.GetType());
                        }
                    }
                } else {
                    Log(LOG_WARNING, "Ignoring unknown family %s of type %d",
                        it->name.GetString(), it->value.GetType());
                }
            }
            return true;
        }
    }

    return false;
}
std::map<std::string, std::string> ConfigParser::GetConfigMap()
{
    std::map<std::string, std::string> configMap;

    stringstream err;
    FILE* fp = fopen(configPath.c_str(), "rb");

    if(!fp){
        err << "Could not open file " << configPath << "!";
        errors.push_back(err.str());
        return configMap;
    }

    char readBuffer[CONFIGPARSER_BUF_SIZE] = {};
    FileReadStream configStream(fp, readBuffer, sizeof(readBuffer));

    Document d;
    d.ParseStream(configStream);

    if(!d.IsObject()){
        return configMap; 
    }


    for(Value::MemberIterator it = d.MemberBegin(); it != d.MemberEnd(); ++it){
        if ( !it->name.IsString() )
        {
            LOG_RELEASE("Warning: JSON key value is not a string.");
            continue;
        }
        if(strcmp(it->name.GetString(),"Port") == 0){
            configMap[it->name.GetString()] = "";
        }
        else if(strcmp(it->name.GetString(),"Roster") == 0){
            configMap[it->name.GetString()] = "";
        }
        else{
            // Ignore non-string
            if ( it->value.IsString() )
            {
                configMap[it->name.GetString()] = it->value.GetString();
            }
        }
    }
    fclose(fp);

    return configMap;
}
Exemplo n.º 5
0
	Config::ElementGroupType
	getAllElementGroups(const Document& doc, const std::vector<SvgElement>& all_elements_)
	{
		const auto element_groups_it = doc.FindMember("element_groups");
		assert(element_groups_it != doc.MemberEnd());
		assert(element_groups_it->value.IsArray());
		const auto raw_array_of_groups = element_groups_it->value.GetArray();

		Config::ElementGroupType all_element_groups;
		all_element_groups.set_empty_key(std::string{""});
		for (const auto& raw_single_group: raw_array_of_groups)
		{
			assert(raw_single_group.IsObject());
			const auto& single_group = raw_single_group.GetObject();
			//group name
			const auto group_name_it = single_group.FindMember("name");
			assert(group_name_it != single_group.MemberEnd());
			assert(group_name_it->value.IsString());
			const auto group_name = std::string {group_name_it->value.GetString(), group_name_it->value.GetStringLength()};

			//all the elements that are part of the group
			std::vector<std::string> single_group_members;
			const auto raw_single_group_members = single_group.FindMember("elements");
			assert(raw_single_group_members != single_group.MemberEnd());
			assert(raw_single_group_members->value.IsArray());
			const auto raw_array_of_group_members = raw_single_group_members->value.GetArray();

			for (const auto& raw_single_group_element : raw_array_of_group_members)
			{
				assert(raw_single_group_element.IsString());
				single_group_members.emplace_back(std::string{raw_single_group_element.GetString(),
				                                              raw_single_group_element.GetStringLength()});
			}
			all_element_groups[group_name] = std::move(single_group_members);
		}


		for (auto& array_name_pair : all_element_groups)
		{
			auto& element_vector = array_name_pair.second;
			std::sort(std::begin(element_vector), std::end(element_vector));
		}
		// TODO: this line is for debug purposes, should be removed
		std::cout << all_elements_;
		return all_element_groups;
	}
Exemplo n.º 6
0
Sprites parseSprite(const std::string& image, const std::string& json) {
    using namespace rapidjson;

    Sprites sprites;

    // Parse the sprite image.
    const util::Image raster(image);
    if (!raster) {
        Log::Warning(Event::Sprite, "Could not parse sprite image");
        return sprites;
    }

    Document doc;
    doc.Parse<0>(json.c_str());

    if (doc.HasParseError()) {
        Log::Warning(Event::Sprite, std::string{ "Failed to parse JSON: " } + doc.GetParseError() +
                                        " at offset " + std::to_string(doc.GetErrorOffset()));
        return sprites;
    } else if (!doc.IsObject()) {
        Log::Warning(Event::Sprite, "Sprite JSON root must be an object");
        return sprites;
    } else {
        for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr) {
            const std::string name = { itr->name.GetString(), itr->name.GetStringLength() };
            const Value& value = itr->value;

            if (value.IsObject()) {
                const uint16_t x = getUInt16(value, "x", 0);
                const uint16_t y = getUInt16(value, "y", 0);
                const uint16_t width = getUInt16(value, "width", 0);
                const uint16_t height = getUInt16(value, "height", 0);
                const double pixelRatio = getDouble(value, "pixelRatio", 1);
                const bool sdf = getBoolean(value, "sdf", false);

                auto sprite = createSpriteImage(raster, x, y, width, height, pixelRatio, sdf);
                if (sprite) {
                    sprites.emplace(name, sprite);
                }
            }
        }
    }

    return sprites;
}
Exemplo n.º 7
0
	Config::ElementContainerType getAllElements(const Document& doc)
	{
		// load elements
		const auto elements_it = doc.FindMember("elements");
		assert(elements_it != doc.MemberEnd());
		assert(elements_it->value.IsArray());

		std::vector<SvgElement> all_elements;
		const auto raw_elements = elements_it->value.GetArray();;
		for (SizeType i = 0; i < raw_elements.Size(); ++i)
		{
			const Value& singleElement = raw_elements[i];
			assert(singleElement.IsString());
			all_elements.emplace_back(SvgElement{singleElement.GetString()});
		}
		std::sort(std::begin(all_elements), std::end(all_elements));
		return all_elements;
	}
Exemplo n.º 8
0
    /// <summary>
    /// PlayFab Title cannot be created from SDK tests, so you must provide your titleId to run unit tests.
    /// (Also, we don't want lots of excess unused titles)
    /// </summary>
    static void SetTitleInfo(Document &testInputs)
    {
        // Parse all the inputs
        auto end = testInputs.MemberEnd();
        auto each = testInputs.FindMember("titleId");
        if (each != end) playFabSettings->titleId = each->value.GetString();

        string blah;
        each = testInputs.FindMember("titleCanUpdateSettings");
        if (each != end) blah = each->value.GetString();
        TITLE_CAN_UPDATE_SETTINGS = (blah.compare("true") == 0 || blah.compare("True") == 0 || blah.compare("TRUE") == 0);

        each = testInputs.FindMember("userName");
        if (each != end) userName = each->value.GetString();
        each = testInputs.FindMember("userEmail");
        if (each != end) userEmail = each->value.GetString();
        each = testInputs.FindMember("userPassword");
        if (each != end) userPassword = each->value.GetString();

        each = testInputs.FindMember("characterName");
        if (each != end) characterName = each->value.GetString();
    }
/* ****************************************************************************
*
* parseContextAttributeCompoundValueStandAlone - 
*/
std::string parseContextAttributeCompoundValueStandAlone
(
  Document&            document,
  ContextAttribute*    caP,
  orion::ValueType     valueType
)
{
  caP->compoundValueP            = new orion::CompoundValueNode();
  caP->compoundValueP->name      = "TOP";
  caP->compoundValueP->container = caP->compoundValueP;
  caP->compoundValueP->valueType = caP->valueType;  // Convert to other type?
  caP->compoundValueP->path      = "/";
  caP->compoundValueP->rootP     = caP->compoundValueP;
  caP->compoundValueP->level     = 0;
  caP->compoundValueP->siblingNo = 0;

  orion::CompoundValueNode*   parent  = caP->compoundValueP;


  //
  // Children of the node
  //
  if (caP->valueType == orion::ValueTypeVector)
  {
    int counter  = 0;

    for (Value::ConstValueIterator iter = document.Begin(); iter != document.End(); ++iter)
    {
      std::string                nodeType  = jsonParseTypeNames[iter->GetType()];
      orion::CompoundValueNode*  cvnP      = new orion::CompoundValueNode();
      char                       itemNo[4];

      snprintf(itemNo, sizeof(itemNo), "%03d", counter);

      cvnP->valueType  = stringToCompoundType(nodeType);
      cvnP->container  = parent;
      cvnP->rootP      = parent->rootP;
      cvnP->level      = parent->level + 1;
      cvnP->siblingNo  = counter;
      cvnP->path       = parent->path + "[" + itemNo + "]";


      if (nodeType == "String")
      {
        cvnP->stringValue = iter->GetString();
      }
      else if (nodeType == "Number")
      {
        cvnP->numberValue = iter->GetDouble();
      }
      else if ((nodeType == "True") || (nodeType == "False"))
      {
        cvnP->boolValue   = (nodeType == "True")? true : false;
      }
      else if (nodeType == "Null")
      {
        cvnP->valueType = orion::ValueTypeNone;
      }
      else if (nodeType == "Object")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeObject;
      }
      else if (nodeType == "Array")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeVector;
      }

      parent->childV.push_back(cvnP);

      //
      // Start recursive calls if Object or Array
      //
      if ((nodeType == "Object") || (nodeType == "Array"))
      {
        parseContextAttributeCompoundValue(iter, caP, cvnP);
      }
      else if (!caP->typeGiven)
      {
        caP->type = defaultType(caP->valueType);
      }

      ++counter;
    }
  }
  else if (caP->valueType == orion::ValueTypeObject)
  {
    int counter  = 0;

    for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
    {
      std::string                nodeType = jsonParseTypeNames[iter->value.GetType()];
      orion::CompoundValueNode*  cvnP     = new orion::CompoundValueNode();

      cvnP->name       = iter->name.GetString();
      cvnP->valueType  = stringToCompoundType(nodeType);
      cvnP->container  = parent;
      cvnP->rootP      = parent->rootP;
      cvnP->level      = parent->level + 1;
      cvnP->siblingNo  = counter;
      cvnP->path       = parent->path + cvnP->name;

      if (nodeType == "String")
      {
        cvnP->stringValue = iter->value.GetString();
      }
      else if (nodeType == "Number")
      {
        cvnP->numberValue = iter->value.GetDouble();
      }
      else if ((nodeType == "True") || (nodeType == "False"))
      {
        cvnP->boolValue   = (nodeType == "True")? true : false;
      }
      else if (nodeType == "Null")
      {
        cvnP->valueType = orion::ValueTypeNone;
      }
      else if (nodeType == "Object")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeObject;
      }
      else if (nodeType == "Array")
      {
        cvnP->path += "/";
        cvnP->valueType = orion::ValueTypeVector;
      }

      parent->childV.push_back(cvnP);
        
      //
      // Start recursive calls if Object or Array
      //
      if ((nodeType == "Object") || (nodeType == "Array"))
      {
        parseContextAttributeCompoundValue(iter, caP, cvnP);
      }
      else if (!caP->typeGiven)
      {
        caP->type = defaultType(caP->valueType);
      }

      ++counter;
    }
  }

  return "OK";
}
/* ****************************************************************************
*
* parseAttributeValue - 
*/
std::string parseAttributeValue(ConnectionInfo* ciP, ContextAttribute* caP)
{
  Document   document;
  OrionError oe;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    LM_W(("Bad Input (JSON parse error)"));
    oe.fill(SccBadRequest, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  if (!document.IsObject())
  {
    LM_E(("Bad Input (JSON Parse Error)"));
    oe.fill(SccBadRequest, "Error parsing incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  if (!document.HasMember("value"))
  {
    LM_W(("Bad Input (No attribute value specified"));
    oe.fill(SccBadRequest, "no attribute value specified");
    ciP->httpStatusCode = SccBadRequest;;
    return oe.render(ciP, "");
  }


  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name != "value")
    {
      LM_W(("Bad Input (unexpected JSON field - accepting only 'value'"));
      oe.fill(SccBadRequest, "unexpected JSON field - accepting only /value/");
      ciP->httpStatusCode = SccBadRequest;;
      return oe.render(ciP, "");
    }


    if (type == "String")
    {
      caP->valueType   = orion::ValueTypeString;
      caP->stringValue = iter->value.GetString();
    }
    else if (type == "Number")
    {
      caP->numberValue  = iter->value.GetDouble();
      caP->valueType    = orion::ValueTypeNumber;
    }
    else if (type == "True")
    {
      caP->boolValue    = true;
      caP->valueType    = orion::ValueTypeBoolean;
    }
    else if (type == "False")
    {
      caP->boolValue    = false;
      caP->valueType    = orion::ValueTypeBoolean;
    }
    else if (type == "Array")
    {
      caP->valueType    = orion::ValueTypeVector;

      std::string r = parseContextAttributeCompoundValue(iter, caP, NULL);
      if (r != "OK")
      {
        LM_W(("Bad Input (json error in ContextAttributeObject::Vector"));
        return "json error in ContextAttributeObject::Vector";
      }
    }
    else if (type == "Object")
    {
      caP->valueType    = orion::ValueTypeObject;

      std::string r = parseContextAttributeCompoundValue(iter, caP, NULL);
      if (r != "OK")
      {
        LM_W(("Bad Input (json error in ContextAttributeObject::Object"));
        return "json error in ContextAttributeObject::Object";
      }
    }
  }

  return "OK";
}
Exemplo n.º 11
0
/* ****************************************************************************
*
* parseEntity - 
*
* This function is used to parse two slightly different payloads:
* - POST /v2/entities
* - POST /v2/entities/<eid>
*
* In the latter case, "id" CANNOT be in the payload, while in the former case, 
* "id" MUST be in the payload.
*
* In the case of /v2/entities/<eid>, the entityId of 'Entity* eP' is set in
* the service routine postEntity.
* 
*/
std::string parseEntity(ConnectionInfo* ciP, Entity* eP, bool eidInURL)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    LM_W(("Bad Input (JSON parse error)"));
    eP->errorCode.fill("ParseError", "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return eP->render(ciP, EntitiesRequest);
  }


  if (!document.IsObject())
  {
    LM_E(("Bad Input (JSON Parse Error)"));
    eP->errorCode.fill("ParseError", "Error parsing incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;;
    return eP->render(ciP, EntitiesRequest);
  }


  if (eidInURL == false)
  {
    if (!document.HasMember("id"))
    {
      LM_W(("Bad Input (No entity id specified"));
      eP->errorCode.fill("ParseError", "no entity id specified");
      ciP->httpStatusCode = SccBadRequest;;
      return eP->render(ciP, EntitiesRequest);
    }
  }


  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "id")
    {
      if (eidInURL == false)
      {
        if (type != "String")
        {
          LM_W(("Bad Input (invalid JSON type for entity id"));
          eP->errorCode.fill("ParseError", "invalid JSON type for entity id");
          ciP->httpStatusCode = SccBadRequest;;
          return eP->render(ciP, EntitiesRequest);
        }

        eP->id = iter->value.GetString();
      }
      else  // "id" present in payload for /v2/entities/<eid> - not a valid payload
      {
        LM_W(("Bad Input ('id' is not a valid attribute"));
        eP->errorCode.fill("ParseError", "invalid input, 'id' as attribute");
        ciP->httpStatusCode = SccBadRequest;;
        return eP->render(ciP, EntitiesRequest);
      }
    }
    else if (name == "type")
    {
      if (type != "String")
      {
        LM_W(("Bad Input (invalid JSON type for entity type"));
        eP->errorCode.fill("ParseError", "invalid JSON type for entity type");
        ciP->httpStatusCode = SccBadRequest;;
        return eP->render(ciP, EntitiesRequest);
      }

      eP->type = iter->value.GetString();
    }
    else
    {
      ContextAttribute* caP = new ContextAttribute();
      eP->attributeVector.push_back(caP);

      std::string r = parseContextAttribute(ciP, iter, caP);
      if (r != "OK")
      {
        LM_W(("Bad Input (parse error in context attribute)"));
        eP->errorCode.fill("ParseError", r);
        ciP->httpStatusCode = SccBadRequest;
        return eP->render(ciP, EntitiesRequest);
      }
    }
  }

  if (eidInURL == false)
  {
    if (eP->id == "")
    {
      LM_W(("Bad Input (empty entity id"));
      eP->errorCode.fill("ParseError", "empty entity id");
      ciP->httpStatusCode = SccBadRequest;;
      return eP->render(ciP, EntitiesRequest);
    }
  }

  eP->present("");
  return "OK";
}
GameState* JsonEncodeDecode::decode(const char *buffer)
{
	Document doc;

	// Parse and catch errors
	if (doc.Parse(buffer).HasParseError())
	{
		printf("\n----------\nError (offset %u): %s\n----------\n",
				(unsigned)doc.GetErrorOffset(),
				GetParseError_En(doc.GetParseError()));
		return NULL;
	}

	// Create new GameState
	GameState* state = new GameState();

	// Iterate through JSON document
	for (Value::ConstMemberIterator itr = doc.MemberBegin(); itr != doc.MemberEnd(); ++itr)
	{
		/*
		 * GAME OVER STATE
		 */
		if (strcmp(itr->name.GetString(), "GameOver") == 0)
		{
			int gameOver = itr->value.GetInt();
			state->setGameOver(gameOver);
		}

		/*
		 * TIME TO RESTART
		 */
		if (strcmp(itr->name.GetString(), "SecToRestart") == 0)
		{
			int secToRestart = itr->value.GetInt();
			state->setSecToRestart(secToRestart);
		}

		/*
		 * VEHICLES
		 */
		if (strcmp(itr->name.GetString(), "Vehicles") == 0)
		{
			// If Vehicles is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Vehicles array is not array\n----------\n");
				return NULL;
			}

			const Value& vehicleArray = itr->value;
			for (SizeType i = 0; i < vehicleArray.Size(); i++)
			{
				if (decodeVehicle(state, vehicleArray[i]) == -1)
				{
					printf("\n----------\nError decoding vehicles\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BULLETS
		 */
		if (strcmp(itr->name.GetString(), "Bullets") == 0)
		{
			// If Bullets is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bullets array is not array\n----------\n");
				return NULL;
			}

			const Value& bulletArray = itr->value;
			for (SizeType i = 0; i < bulletArray.Size(); i++)
			{
				if (decodeBullet(state, bulletArray[i]) == -1)
				{
					printf("\n----------\nError decoding bullets\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * BASES
		 */
		if (strcmp(itr->name.GetString(), "Bases") == 0)
		{
			// If Bases is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Bases array is not array\n----------\n");
				return NULL;
			}

			const Value& basesArray = itr->value;
			for (SizeType i = 0; i < basesArray.Size(); i++)
			{
				if (decodeBase(state, basesArray[i]) == -1)
				{
					printf("\n----------\nError decoding bases\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * SHIELDS
		 */
		if (strcmp(itr->name.GetString(), "Shields") == 0)
		{
			// If Shields is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Shields array is not array\n----------\n");
				return NULL;
			}

			const Value& shieldsArray = itr->value;
			for (SizeType i = 0; i < shieldsArray.Size(); i++)
			{
				if (decodeShield(state, shieldsArray[i]) == -1)
				{
					printf("\n----------\nError decoding shields\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * SHIELD GENERATORS
		 */
		if (strcmp(itr->name.GetString(), "ShieldGenerators") == 0)
		{
			// If ShieldGenerators is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Shield gens array is not array\n----------\n");
				return NULL;
			}

			const Value& shieldGenArray = itr->value;
			for (SizeType i = 0; i < shieldGenArray.Size(); i++)
			{
				if (decodeShieldGen(state, shieldGenArray[i]) == -1)
				{
					printf("\n----------\nError decoding shield gens\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * POWERUPS
		 */
		if (strcmp(itr->name.GetString(), "PowerUps") == 0)
		{
			// If Powerups is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Powerups array is not array\n----------\n");
				return NULL;
			}

			const Value& powerupArray = itr->value;
			for (SizeType i = 0; i < powerupArray.Size(); i++)
			{
				if (decodePowerup(state, powerupArray[i]) == -1)
				{
					printf("\n----------\nError decoding powerups\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * ROCKETS
		 */
		if (strcmp(itr->name.GetString(), "Rockets") == 0)
		{
			// If Rockets is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: Rockets array is not array\n----------\n");
				return NULL;
			}

			const Value& rocketArray = itr->value;
			for (SizeType i = 0; i < rocketArray.Size(); i++)
			{
				if (decodeRocket(state, rocketArray[i]) == -1)
				{
					printf("\n----------\nError decoding rockets\n----------\n");
					return NULL;
				}
			}
		}

		/*
		 * GRAVITY WELLS
		 */
		if (strcmp(itr->name.GetString(), "GravityWells") == 0)
		{
			// If GravityWells is not an array, something went wrong
			if (!itr->value.IsArray())
			{
				printf("\n----------\nError: GravityWells array is not array\n----------\n");
				return NULL;
			}

			const Value& gravWellArray = itr->value;
			for (SizeType i = 0; i < gravWellArray.Size(); i++)
			{
				if (decodeGravWell(state, gravWellArray[i]) == -1)
				{
					printf("\n----------\nError decoding gravity wells\n----------\n");
					return NULL;
				}
			}
		}
	}

	return state;
}
Exemplo n.º 13
0
int NodeBtHandler (int argc, char *argv[])
{
  // DDS değişkenleri
  DDSEntityManager                    mgrBtPub;
  DDSEntityManager                    mgrReqSub;
  ReturnCode_t                        status;
  SampleInfoSeq_var                   infoSeq = new SampleInfoSeq();
  BtSeq*                              btSeqInstance = new BtSeq();
  ServerReqSeq                        serverReqSeq;

  // Zaman ile alakalı değişkenler
  long int                            messageIDCount = 0;
  Time_t                              tsBeforeTheScan = { 0, 0 };
  Time_t                              tsAfterTheScan = { 0, 0 };
  //Time_t                              tsWifiPub = { 0, 0 };
  struct timeval                      tsConverter;
  DDS::Duration_t                     waitAckTime = { 0, 800000000 }; //800ms
  int                                 refreshRate = 60;

  // Veri tutucular (data structures)
  vector<string>                      btMacHolder;
  vector<int>                         btRssiHolder;
  string                              btFileContenHolder;

  // Bluetooth tarama sonuçlarının yazdırıldığı dosyadan okuma yapacak
  // olan değişken
  boost::filesystem::ifstream         fIn;

  // Bluetooth tarama sıklığı ayarlayan değişken
  int                                 refreshRateCounter = -1;

  char                                hostName[1024];
  gethostname(hostName, 1024);


  // !!! Bluetooth tarama mesajlarını Publish edecek Topic yaratılıyor
  // ve o Topic'e ait konfigürasyon ayarları yapılıyor.

  // Domain participant yaratılıyor
  mgrBtPub.createParticipant ("KonSens_BtSeq_Participant");

  // BtSeq tipi yaratılıyor
  BtSeqTypeSupport_var btSeqTs = new BtSeqTypeSupport();
  mgrBtPub.registerType(btSeqTs.in());

  // Topic yaratılıyor
  char btPubTopicName[] = "KonSensData_BtSeq_Topic";
  mgrBtPub.createTopic(btPubTopicName);

  // Publisher yaratılıyor
  mgrBtPub.createPublisher();

  // DataWriter yaratılıyor
  bool autodispose_unregistered_instances = false;
  mgrBtPub.createWriter(autodispose_unregistered_instances,
                        KEEP_ALL_HISTORY_QOS,
                        BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS);

  // Yaratılan DataWriter, BtSeq tipi için özelleştiriliyor
  DataWriter_var dWriter = mgrBtPub.getWriter ();
  BtSeqDataWriter_var btSeqWriter = BtSeqDataWriter::_narrow(dWriter.in());

  // Düğüm numarasını atanıyor
  btSeqInstance->userID = 13;

  // Publish edilecek olan mesajlara zaman etiketi takabilmek için
  // btSeqInstance değişkeni register ediliyor
  //userHandle = btSeqWriter->register_instance_w_timestamp(*btSeqInstance,
  //                                                        tsWifiPub);

  cout << "=== [Publisher of KonSensData_BtSeq_Topic] Ready ..." << endl;


  // !!! Sunucudan gelen komutlara Subscribe olacak olan Topic yaratılıyor
  // ve o Topic için gerekli konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrReqSub.createParticipant(
        "KonSensData_ServerReq_Participant_Server_to_Node");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrSubscriberTS = new ServerReqTypeSupport();
  mgrReqSub.registerType(mgrSubscriberTS.in());

  // Topic yaratılıyor
  char reqSubTopicName[] = "KonSensData_ServerReq_Topic_Server_to_Node";
  mgrReqSub.createTopic(reqSubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Subscriber yaratılıyor
  mgrReqSub.createSubscriber();

  // DataReader yaratılıyor
  mgrReqSub.createReader(KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataReader_var dReaderSub = mgrReqSub.getReader();
  ServerReqDataReader_var serverReqReader =
      ServerReqDataReader::_narrow(dReaderSub.in());
  checkHandle(serverReqReader.in(), "ServerReqDataReader::_narrow");

  cout << "=== [Subscriber KonSensData_ServerReq_Topic_Server_to_Node]"
          " Ready ..." << endl;


  // Bluetooth aktif hale getiriliyor.
  system("sudo hciconfig -a hci0 up");
  stringstream ssBtName;
  ssBtName << "sudo bt-adapter -a hci0 --set Name \"" << hostName << "\"";
  system(ssBtName.str().c_str());
  system("sudo bt-adapter -a hci0 --set Discoverable 1");

  // Yenileme sıklığını belirleyecek olan 'timelimit' değişkeni yaratılıyor.
  Timeout timelimit(std::chrono::milliseconds(refreshRate*1000));


  while (true)
  {
    if (timelimit.isExpired() || refreshRateCounter == -1)
    {

      // BT mesajını Publish etmek için hazırlık yapılıyor.

      cout << "-----------------------------------" << endl;

      btSeqInstance->messageID = messageIDCount;

      // Tarama öncesi alınan zaman etiketi (timestamp[0])
      gettimeofday(&tsConverter, NULL);
      tsBeforeTheScan.sec = tsConverter.tv_sec;
      tsBeforeTheScan.nanosec = (tsConverter.tv_usec * 1000);
      cout << " timestamp[0] (before the scan) = " << tsBeforeTheScan.sec
           << '.';
      cout << setfill('0') << setw(9) << (tsBeforeTheScan.nanosec)
           << endl;

      // BT taraması yapılıyor ve ardından tarama sonuçları 'bt_rssi'
      // dosyasına yazdırılıyor.
      system("sudo hciconfig hci0 reset");
      FakeDelay();
      system("sudo bt-adapter -a hci0 -d >> bt_rssi.txt");
      FakeDelay();

      cout << "Bluetooth message is publishing..." << endl;

      try
      {
        // BT tarama dosyası okunuyor
        fIn.open ("bt_rssi.txt", ios::in);
        stringstream ssBt;
        ssBt << fIn.rdbuf();
        btFileContenHolder = ssBt.str();
        system("rm bt_rssi.txt");

        // Okunan dosya boost kütüphane yardımıyla ayrıştırılıyor
        boost::regex expAd( "Address: ([0-9A-F:]{17})" ) ;
        boost::regex expBt( "RSSI:.*?([0-9]+)") ;
        boost::match_results<string::const_iterator> whatAd;

        string::const_iterator startAd = btFileContenHolder.begin();
        string::const_iterator finishAd = btFileContenHolder.end();

        while (boost::regex_search(startAd, finishAd, whatAd, expAd))
        {
          btMacHolder.push_back(whatAd[1]);
          startAd = whatAd[0].second ;
        }

        boost::match_results<string::const_iterator> whatBt;
        startAd = btFileContenHolder.begin() ;
        finishAd = btFileContenHolder.end() ;

        while (boost::regex_search(startAd, finishAd, whatBt, expBt))
        {
          string foundRssi(whatBt[1]);
          btRssiHolder.push_back(atoi(foundRssi.c_str()));
          startAd = whatBt[0].second ;
        }

        cout << "Number of BT connection that has been found: "
             << btRssiHolder.size() << endl;
        cout << "MessageID: " << btSeqInstance->messageID << endl;

        // Tarama sonrası alınan zaman etiketi (timestamp[1])
        gettimeofday(&tsConverter, NULL);
        tsAfterTheScan.sec = tsConverter.tv_sec;
        tsAfterTheScan.nanosec =( tsConverter.tv_usec * 1000);
        cout << " timestamp[1] (after the scan) = "
             << tsAfterTheScan.sec << '.';
        cout << setfill('0') << setw(9) << (tsAfterTheScan.nanosec)
             << endl;


        // Ayrıştırılan BT tarama dosyası ve alınan zaman etiketleri,
        // Publish edilecek olan mesaj değişkenlerine kaydediliyor.
        btSeqInstance->timestamp[0][0] = tsBeforeTheScan.nanosec;
        btSeqInstance->timestamp[0][1] = tsBeforeTheScan.sec;
        btSeqInstance->timestamp[1][0] = tsAfterTheScan.nanosec;
        btSeqInstance->timestamp[1][1] = tsAfterTheScan.sec;

        btSeqInstance->messages.length(btMacHolder.size());
        for(int i = 0; i < btMacHolder.size(); i++)
        {
          Msg msg;
          msg.devID = DDS::string_dup(btMacHolder[i].c_str());
          msg.hostName = DDS::string_dup(hostName);
          msg.dbm = -btRssiHolder[i];
          btSeqInstance->messages[i] = msg;
        }

        // Publish edilmeden önce, bir önceki mesajın acknowlegde mesajı
        // bekleniyor
        btSeqWriter->wait_for_acknowledgments(waitAckTime);

        status = btSeqWriter->write(*btSeqInstance,
                                    DDS::HANDLE_NIL);
        checkStatus(status, "BtSeqDataWriter::write");
        messageIDCount++;
      }

      catch ( boost::bad_expression & ex )
      {
        std::cout << ex.what() ;
        break;
      }

      btMacHolder.clear();
      btRssiHolder.clear();
      fIn.close();

      cout << "-----------------------------------" << endl;

      // Tarama sıklığını belirleyen değişken sıfırlanıyor
      timelimit.setTimerToZero();
      refreshRateCounter = 0;
      cout << refreshRateCounter << endl;

    } // BT Publisher kısmının sonu


    // Sunucu tarafından gönderilen Matlab komutlarına Subscribe olunuyor
    else
    {
      status = serverReqReader->take(serverReqSeq,
                                     infoSeq,
                                     LENGTH_UNLIMITED,
                                     ANY_SAMPLE_STATE,
                                     ANY_VIEW_STATE,
                                     ANY_INSTANCE_STATE);
      checkStatus(status, "severReqDataReader::read");

      for (DDS::ULong j = 0; j < serverReqSeq.length(); j++)
      {
        if(infoSeq[j].valid_data)
        {
          cout << "=== [Subscriber] message received :" << endl;
          cout << "    Received Request Message  : "
               << serverReqSeq[j].request << endl;
          cout << "    Received RequestID : \""
               << serverReqSeq[j].requestID << "\"" << endl;

          // Rapidjson yapılandırıcısı yaratılıyor
          Document d;
          if(d.Parse(serverReqSeq[j].request).HasParseError())
            cout << " Parsing Error!" << endl;

          StringBuffer nodeIdBuffer;
          Writer<StringBuffer> nodeIdWriter(nodeIdBuffer);
          d["NodeID"].Accept(nodeIdWriter);

          string tempNodeId = nodeIdBuffer.GetString();

          // Subscribe olunan mesajın düğüme ait olup olmadığı kontrol ediliyor
          if (tempNodeId == "\"SensDug13\"")
          {
            StringBuffer buffer;

            Value::ConstMemberIterator itr = d.FindMember("SetRefreshRate");
            // Ref Rate komutunun gelip gelmediği kontrol ediliyor
            if(itr != d.MemberEnd())
            {
              string refreshRateString;
              int refreshRateInt;

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d["SetRefreshRate"].Accept(writer);
              refreshRateString = buffer.GetString();

              // Gelen mesajda fazladan çift tırnak ile bulunuyor
              // Örneğin, ""15""
              // Bu yüzden ilk son karakterler kırpılıyor
              refreshRateString =
                  refreshRateString.substr(1, refreshRateString.size()-1);
              // Refresh rate değeri stringden integera çevriliyor
              refreshRateInt = atoi(refreshRateString.c_str());

              refreshRate = refreshRateInt;
              timelimit.setMaxDuration(std::chrono::milliseconds
                                       (refreshRate*1000));

            }
          }
          else
            cout << "Invalid NodeID!" << endl;
        }
      }

      status = serverReqReader->return_loan(serverReqSeq, infoSeq);
      checkStatus(status, "ServerReqDataReader::return_loan");

      refreshRateCounter++;
      cout << refreshRateCounter << endl;

    } // Matlab komutuna Subscribe olma kısmının sonu

    // Terminalde akacak olan çıktıları dah gözle görülebilir bir şekilde
    // yazdırmak için koyulmuştur
    FakeDelay();
  }

  // Hafıza temizle işlemleri gerçekleştiriliyor

  mgrBtPub.deleteWriter();
  mgrBtPub.deletePublisher();
  mgrBtPub.deleteTopic();
  mgrBtPub.deleteParticipant();

  mgrReqSub.deleteReader();
  mgrReqSub.deleteSubscriber();
  mgrReqSub.deleteTopic();
  mgrReqSub.deleteParticipant();

  return 0;
}
Exemplo n.º 14
0
/* ****************************************************************************
*
* parseBatchQuery - 
*/
std::string parseBatchQuery(ConnectionInfo* ciP, BatchQuery* bqrP)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  if (!document.IsObject())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill("BadRequest", "JSON Parse Error");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (document.ObjectEmpty())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Empty JSON payload");
    ec.fill("BadRequest", "empty payload");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("entities") && !document.HasMember("attributes") && !document.HasMember("scopes"))
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Invalid JSON payload, no relevant fields found");
    ec.fill("BadRequest", "Invalid JSON payload, no relevant fields found");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "entities")
    {
      std::string r = parseEntityVector(ciP, iter, &bqrP->entities, false);  // param 4: attributes are NOT allowed in payload

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "attributes")
    {
      std::string r = parseAttributeList(ciP, iter, &bqrP->attributeV);

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "scopes")
    {
      std::string r = parseScopeVector(ciP, iter, &bqrP->scopeV);

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else
    {
      std::string  description = std::string("Unrecognizedfield in JSON payload: /") + name + "/";
      ErrorCode    ec("BadRequest", description);

      alarmMgr.badInput(clientIp, description);
      ciP->httpStatusCode = SccBadRequest;

      return ec.toJson(true);
    }
  }

  return "OK";
}
Exemplo n.º 15
0
int NodeWifiHandler (int argc, char *argv[])
{

  // DDS değişkenleri
  ReturnCode_t                        status;
  InstanceHandle_t                    userHandle;
  DDSEntityManager                    mgrReqSub;
  DDSEntityManager                    mgrReqPub;
  DDSEntityManager                    mgrWifiPub;
  WifiSeq                             *wifiSeqInstance = new WifiSeq();;
  ServerReqSeq                        serverReqSeq;
  ServerReq                           *serverReq = new ServerReq();
  SampleInfoSeq_var                   infoSeq = new SampleInfoSeq();

  // Zaman ile alakalı değişkenler
  DDS::Duration_t                     waitAckTime = { 0, 800000000 }; //800ms
  int                                 refreshRate = 60;
  long int                            messageIDCount = 0;
  Time_t                              tsBeforeTheScan = { 0, 0 };
  Time_t                              tsAfterTheScan = { 0, 0 };
  struct timeval                      tsConverter;

  // Veri tutucular (data structures)
  vector<string>                      modemIdHolder;
  vector<int>                         dbmHolder;
  string                              wifiFileContenHolder;
  string                              ifconfigFileContentHolder;


  // Wifi tarama sonuçlarının yazdırıldığı dosyadan okuma yapacak
  // olan değişken
  boost::filesystem::ifstream         fInWifiScan, fInIfconfig;

  // Matlab komutları ayrıştırılmasında kullanılacak olan değişkenler
  string                              ip, subnet, gateway, dns, nodeName;

  char                                hostName[1024];
  gethostname(hostName, 1024);

  // Bluetooth tarama sıklığı ayarlayan değişken
  int refreshRateCounter = -1;


  // !!! Wifi tarama mesajlarını Publish edecek Topic yaratılıyor
  // ve o Topic'e ait konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrWifiPub.createParticipant("KonSensData_WifiSeq_Participant");

  // WifiSeq tipi yaratılıyor
  WifiSeqTypeSupport_var wifiSeqTS = new WifiSeqTypeSupport();
  mgrWifiPub.registerType(wifiSeqTS.in());

  // Topic yaratılıyor
  char wifiPubTopicName[] = "KonSensData_WifiSeq_Topic";
  mgrWifiPub.createTopic(wifiPubTopicName);

  // Publisher yaratılıyor
  mgrWifiPub.createPublisher();

  // DataWriter yaratılıyor
  bool autodisposeUnregisteredInstances = false;
  mgrWifiPub.createWriter(autodisposeUnregisteredInstances,
                          KEEP_ALL_HISTORY_QOS,
                          BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS);

  // Yaratılan DataWriter, WifiSeq tipi için özelleştiriliyor
  DataWriter_var dWriterWifPub = mgrWifiPub.getWriter();
  WifiSeqDataWriter_var wifiSeqWriter =
      WifiSeqDataWriter::_narrow(dWriterWifPub.in());

  // Düğüm numarası atanıyor
  wifiSeqInstance->userID = 13;

  cout << "=== [Publisher of KonSensData_WifiSeq_Topic] Ready ..." << endl;


  // !!! Sunucudan gelen komutlara Subscribe olacak olan Topic yaratılıyor
  // ve o Topic için gerekli konfigürasyon ayarları yapılıyor

  // Domain participant yaratılıyor
  mgrReqSub.createParticipant(
        "KonSensData_ServerReq_Participant_Server_to_Node");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrSubscriberTS = new ServerReqTypeSupport();
  mgrReqSub.registerType(mgrSubscriberTS.in());

  // Topic yaratılıyor
  char reqSubTopicName[] = "KonSensData_ServerReq_Topic_Server_to_Node";
  mgrReqSub.createTopic(reqSubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Subscriber yaratılıyor
  mgrReqSub.createSubscriber();

  // DataReader yaratılıyor
  mgrReqSub.createReader(KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataReader_var dReadeSub = mgrReqSub.getReader();
  ServerReqDataReader_var serverReqReader =
      ServerReqDataReader::_narrow(dReadeSub.in());
  checkHandle(serverReqReader.in(), "ServerReqDataReader::_narrow");

  cout << "=== [Subscriber of KonSensData_ServerReq_Topic_Server_to_Node]"
          " Ready ..." << endl;


  // !!! Sunucudan gelen komutlar ayrıştırılıp işlendikten sonra Response
  // mesajını Publish edecek olan Topic yaratılıyor

  // Domain participant yaratılıyor
  mgrReqPub.createParticipant(
        "KonSensData_ServerReq_Participant_Node_to_Server");

  // ServerReq tipi yaratılıyor.
  ServerReqTypeSupport_var mgrPublisherTS = new ServerReqTypeSupport();
  mgrReqPub.registerType(mgrPublisherTS.in());

  // Topic yaratılıyor
  char reqPubTopicName[] = "KonSensData_ServerReq_Topic_Node_to_Server";
  mgrReqPub.createTopic(reqPubTopicName, RELIABLE_RELIABILITY_QOS,
                        VOLATILE_DURABILITY_QOS);

  // Publisher yaratılıyor
  mgrReqPub.createPublisher();

  // DataWriter yaratılıyor
  // Not: Kullanılan autodisposeUnregisteredInstances değişkeni
  // WifiSeqDataWriter yaratılırken ki kullananla aynıdır
  mgrReqPub.createWriter(autodisposeUnregisteredInstances,
                         KEEP_LAST_HISTORY_QOS, 1);

  // Yaratılan DataReader, ServerReq tipi için özelleştiriliyor.
  DataWriter_var dWriterPub = mgrReqPub.getWriter();
  ServerReqDataWriter_var serverReqWriter =
      ServerReqDataWriter::_narrow(dWriterPub.in());

  cout << "=== [Publisher of KonSensData_ServerReq_Topic_Node_to_Server] "
          "Ready ..." << endl;

  // Yenileme sıklığını belirleyecek olan 'timelimit' değişkeni yaratılıyor.
  Timeout timeLimit(std::chrono::milliseconds(refreshRate*1000));

  while(true)
  {
    if (timeLimit.isExpired() || refreshRateCounter == -1)
    {

      // Wifi mesajını Publish etmek için hazırlık yapılıyor.
      cout << "-----------------------------------" << endl;

      wifiSeqInstance->messageID = messageIDCount;

      // Tarama öncesi alınan zaman etiketi (timestamp[0])
      gettimeofday(&tsConverter, NULL);
      tsBeforeTheScan.sec = tsConverter.tv_sec;
      tsBeforeTheScan.nanosec = (tsConverter.tv_usec * 1000);
      cout << " timestamp[0] (before the scan) = " << tsBeforeTheScan.sec
           << '.';
      cout << setfill('0') << setw(9) << (tsBeforeTheScan.nanosec)
           << endl;

      // Wifi taraması yapılıyor ve ardından tarama sonuçları 'wifi_rssi'
      // dosyasına yazdırılıyor.
      system("sudo iwlist wlan0 scanning >> wifi_rssi.txt");

      // Wifi bağlantısı kapatılıyor
      system("sudo ifconfig wlan0 down");

      // Wifi tarama dosyası okunuyor
      fInWifiScan.open("wifi_rssi.txt",ios::in);

      stringstream ssWifi;
      ssWifi << fInWifiScan.rdbuf();
      wifiFileContenHolder = ssWifi.str();
      system("rm wifi_rssi.txt");
      try
      {
        // Okunan dosya boost kütüphane yardımıyla ayrıştırılıyor
        boost::regex exp( "Signal level=.*?([0-9]+)") ;
        boost::regex expAd( "Address: ([0-9A-F:]{17})" ) ;
        boost::match_results<string::const_iterator> whatAd;
        string::const_iterator startAd =
            wifiFileContenHolder.begin() ;
        string::const_iterator finishAd =
            wifiFileContenHolder.end() ;

        while (boost::regex_search(startAd, finishAd,
                                   whatAd, expAd))
        {
          modemIdHolder.push_back(whatAd[1]);
          startAd = whatAd[0].second ;
        }

        boost::match_results<string::const_iterator> what;

        string::const_iterator start = wifiFileContenHolder.begin();
        string::const_iterator finish = wifiFileContenHolder.end();

        while (boost::regex_search(start, finish, what, exp))
        {
          string foundDbm(what[1]);
          dbmHolder.push_back(atoi(foundDbm.c_str()));
          start = what[0].second ;
        }

        cout << " Number of Wifi Network that has been founded: "
             << dbmHolder.size() << endl;

        // Tarama sonrası alınan zaman etiketi (timestamp[1])
        gettimeofday(&tsConverter, NULL);
        tsAfterTheScan.sec = tsConverter.tv_sec;
        tsAfterTheScan.nanosec = (tsConverter.tv_usec * 1000);
        cout << " timestamp[1] (after the scan) = "
             << tsAfterTheScan.sec << '.';
        cout << setfill('0') << setw(9) << (tsAfterTheScan.nanosec)
             << endl;

        // Ayrıştırılan Wifi tarama dosyası ve alınan zaman etiketleri,
        // Publish edilecek olan mesaj değişkenlerine kaydediliyor
        wifiSeqInstance->timestamp[0][0] = tsBeforeTheScan.nanosec;
        wifiSeqInstance->timestamp[0][1] = tsBeforeTheScan.sec;
        wifiSeqInstance->timestamp[1][0] = tsAfterTheScan.nanosec;
        wifiSeqInstance->timestamp[1][1] = tsAfterTheScan.sec;

        wifiSeqInstance->messages.length(modemIdHolder.size());
        cout << " MessageID: " << wifiSeqInstance->messageID << endl;
        for(int i = 0; i < modemIdHolder.size(); i++)
        {
          Msg msg;
          msg.devID = DDS::string_dup(modemIdHolder[i].c_str());
          msg.hostName = DDS::string_dup(hostName);
          msg.dbm = -dbmHolder[i];
          wifiSeqInstance->messages[i] = msg;

        }

        // Publish edilmeden önce, bir önceki mesajın acknowlegde mesajı
        // bekleniyor
        wifiSeqWriter->wait_for_acknowledgments(waitAckTime);
        status = wifiSeqWriter->write(*wifiSeqInstance,DDS::HANDLE_NIL);

        checkStatus(status, "konsensSensDugWifiSeqTopic::"
                            "WifiSeqDataWriter::write_w_timestamp");

        // Wifi bağlantısı tekrar açılıyor
        system("sudo ifconfig wlan0 up");

        messageIDCount++;
      }

      catch ( boost::bad_expression & ex )
      {
        cout << ex.what() ;
      }

      modemIdHolder.clear();
      dbmHolder.clear();
      wifiFileContenHolder.clear();
      fInWifiScan.close();

      cout << "-----------------------------------" << endl;

      timeLimit.setTimerToZero();

      // Tarama sıklığını belirleyen değişken sıfırlanıyor
      refreshRateCounter = 0;
      cout << refreshRateCounter << endl;

    } // Wifi Publisher kısmının sonu


    // Sunucu tarafından gönderilen Matlab komutlarına Subscribe olunuyor
    else
    {
      status = serverReqReader->take(serverReqSeq,
                                     infoSeq,
                                     LENGTH_UNLIMITED,
                                     ANY_SAMPLE_STATE,
                                     ANY_VIEW_STATE,
                                     ANY_INSTANCE_STATE);
      checkStatus(status, "severReqDataReader::take");

      // isDataReceived değişkeni bir kontrol değişkeni olup, Matlab komut
      // bilgisini içeren mesaja Subscribe olunduysa true, olunmadıysa false
      // değerini tutar
      bool isDataReceived = false;

      for (DDS::ULong j = 0; j < serverReqSeq.length(); j++)
      {

        if(infoSeq[j].valid_data)
        {
          cout << "=== [Subscriber] message received :" << endl;
          cout << "    Received Request Message  : "
               << serverReqSeq[j].request << endl;
          cout << "    Received RequestID : \""
               << serverReqSeq[j].requestID << "\"" << endl;

          // Rapidjson yapılandırıcısı yaratılıyor
          Document d;
          if(d.Parse(serverReqSeq[j].request).HasParseError())
            cout << " Parsing Error!" << endl;
          StringBuffer nodeIdBuffer;
          Writer<StringBuffer> nodeIdWriter(nodeIdBuffer);
          d["NodeID"].Accept(nodeIdWriter);
          string tempNodeId = nodeIdBuffer.GetString();

          // Subscribe olunan mesajın düğüme ait olup olmadığı kontrol ediliyor
          if (tempNodeId == "\"SensDug13\"")
          {
            StringBuffer buffer;

            // Reset komutunun gelip gelmediği kontrol ediliyor.
            Value::ConstMemberIterator itr = d.FindMember("Reset");
            if(itr != d.MemberEnd())
            {
              // Resetin değeri falsedan trueya çevriliyor
              Value& s = d["Reset"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d.Accept(writer);

              cout << "    Request Message is modified to  : "
                   << buffer.GetString() << endl;

              // Publish edilecek Response mesajı hazırlanıyor
              string str = buffer.GetString();
              str.append("\n");
              serverReq->request = DDS::string_dup(str.c_str());
              serverReq->requestID = serverReqSeq[j].requestID;

              if(!isDataReceived && status == DDS::RETCODE_OK)
              {
                // Response mesajı gönderiliyor
                ReturnCode_t tempStatus = serverReqWriter->write(
                      *serverReq, DDS::HANDLE_NIL);
                checkStatus(tempStatus, "severReqDataReader::write");
                isDataReceived = true;

                cout << "    Response Request Message is sent : "
                     << serverReq->request << endl;
                cout << "    Response RequestID is sent : \""
                     << serverReq->requestID << "\"" << endl;

              }

              // Sistem yeniden başlatılıyor !!!
              cout << "reboot" << endl;
              system("sudo reboot");
            }

            // GetRefreshRate ve SetRefreshRate komutundan herhangi birinin
            // gelip gelmediği kontrol ediliyor
            itr = d.FindMember("SetRefreshRate");
            if(itr != d.MemberEnd())
            {
              string refreshRateString;
              int refreshRateInt;

              // Status değeri falsedan trueya çevriliyor
              Value& s = d["Status"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d["SetRefreshRate"].Accept(writer);
              refreshRateString = buffer.GetString();

              // Gelen mesajda fazladan çift tırnak ile bulunuyor
              // Örneğin, ""15""
              // Bu yüzden ilk son karakterler kırpılıyor
              refreshRateString =
                  refreshRateString.substr(1, refreshRateString.size()-1);
              // Refresh rate değeri stringden integera çevriliyor
              refreshRateInt = atoi(refreshRateString.c_str());

              // Refresh rate değişkeni güncelleniyor
              refreshRate = refreshRateInt;
              timeLimit.setMaxDuration(std::chrono::milliseconds
                                       (refreshRate*1000));

            }

            itr = d.FindMember("GetRefreshRate");
            if(itr != d.MemberEnd())
            {
              // Status değeri falsedan trueya çevriliyor
              Value& s = d["Status"];
              s.SetBool(true);

              Value& tempRefreshRate = d["GetRefreshRate"];

              // Güncel refresh rate değişken bilgisi alınıyor
              string str = to_string(refreshRate);
              tempRefreshRate.SetString(str.c_str(), str.length());
            }

            // GetAliveStatus komutunun gönderilip gönderilmediği kontrol
            // ediliyor.
            itr = d.FindMember("Alive");
            if(itr != d.MemberEnd())
            {
              // Alive değeri truedan false çevriliyor
              Value& s = d["Alive"];
              s.SetBool(true);

              // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
              Writer<StringBuffer> writer(buffer);
              d.Accept(writer);
            }

            // GetNetStatus komutunun gelip gelmediği kontrol ediliyor
            itr = d.FindMember("IP");
            if(itr != d.MemberEnd())
            {
              cout << "-----------------------------------" << endl;

              // Ağ durum bilgisi ifconfig.txt dosyasına yazdırılıyor
              system("cat /etc/network/interfaces >> ifconfig.txt");
              system("cat /etc/resolv.conf >> ifconfig.txt");
              system("echo -n hostname >> ifconfig.txt && hostname "
                     ">> ifconfig.txt");

              // ifconfig.txt dosyası açılıyor
              fInIfconfig.open("ifconfig.txt",ios::in);
              stringstream ssIfconfig;
              ssIfconfig << fInIfconfig.rdbuf();
              ifconfigFileContentHolder = ssIfconfig.str();
              system("rm ifconfig.txt");

              // Dosya içeriği ayrıştırılıyor
              try
              {
                boost::regex expIp
                    ("address (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expSubnet
                    ("netmask (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expGateway
                    ("gateway (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expDns
                    ("nameserver (\\d{1,3}(\\.\\d{1,3}){3})");
                boost::regex expNoneName
                    ("hostname.*");

                string::const_iterator startAd =
                    ifconfigFileContentHolder.begin() ;
                string::const_iterator finishAd =
                    ifconfigFileContentHolder.end() ;

                boost::match_results<string::const_iterator> whatIp;
                if ( boost::regex_search(startAd, finishAd,
                                         whatIp, expIp) )
                {
                  ip = whatIp[0];
                  cout << ip << endl;
                  string chopped_str = "address ";
                  string::size_type i = ip.find(chopped_str);
                  if (i != string::npos)
                    ip.erase(i, chopped_str.length());

                  Value& tempIp = d["IP"];
                  tempIp.SetString(ip.c_str(), ip.length());
                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;

                boost::match_results<string::const_iterator> whatSubnet;
                if ( boost::regex_search(startAd, finishAd,
                                         whatSubnet, expSubnet) )
                {
                  subnet = whatSubnet[0];
                  cout << subnet << endl;
                  string chopped_str = "netmask ";
                  string::size_type i = subnet.find(chopped_str);
                  if (i != string::npos)
                    subnet.erase(i, chopped_str.length());

                  Value& tempSubnet = d["Subnet"];
                  tempSubnet.SetString(subnet.c_str(),
                                       subnet.length());

                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatGateway;

                if ( boost::regex_search(startAd, finishAd,
                                         whatGateway, expGateway) )
                {
                  gateway = whatGateway[0];
                  cout << gateway << endl;
                  string chopped_str = "gateway ";
                  string::size_type i = gateway.find(chopped_str);
                  if (i != string::npos)
                    gateway.erase(i, chopped_str.length());

                  Value& tempGateway = d["Gateway"];
                  tempGateway.SetString(gateway.c_str(),
                                        gateway.length());


                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatDns;

                if ( boost::regex_search(startAd, finishAd,
                                         whatDns, expDns) )
                {
                  dns = whatDns[0];
                  cout << dns << endl;
                  string chopped_str = "nameserver ";
                  string::size_type i = dns.find(chopped_str);
                  if (i != string::npos)
                    dns.erase(i, chopped_str.length());

                  Value& tempDns = d["DNS"];
                  tempDns.SetString(dns.c_str(), dns.length());
                }

                startAd = ifconfigFileContentHolder.begin() ;
                finishAd = ifconfigFileContentHolder.end() ;
                boost::match_results<string::const_iterator> whatNodeName;

                if ( boost::regex_search(startAd, finishAd,
                                         whatNodeName, expNoneName) )
                {
                  nodeName = whatNodeName[0];
                  cout << nodeName << endl;
                  string chopped_str = "hostname";
                  string::size_type i = nodeName.find(chopped_str);
                  if (i != string::npos)
                    nodeName.erase(i, chopped_str.length());
                  nodeName.erase(remove(nodeName.begin(),
                                        nodeName.end(),
                                        '\n'),
                                 nodeName.end());

                  Value& tempNodeName = d["Name"];
                  tempNodeName.SetString(nodeName.c_str(),
                                         nodeName.length());
                }

                cout << ip << endl;
                cout << subnet << endl;
                cout << dns << endl;
                cout << nodeName << endl;
              } // Dosya ayrıştırma işlemi bitti

              catch ( boost::bad_expression & ex )
              {
                cout << ex.what() ;
              }

              ifconfigFileContentHolder.clear();
              fInIfconfig.close();

              cout << "-----------------------------------" << endl;

              // GetNetStatus komutuna ait status değeri falsedan trueya
              // çevriliyor.
              Value& s = d["Status"];
              s.SetBool(true);
            }

            // Matlab'dan gelen mesaj içeriğinin ayrıştırılıp düzenlenme işlemi
            // tamamlandı ve sunucuya Response mesajını Publish etmek için
            // aşağıdaki adımlar gerçekleştiriliyor

            // Document formatındaki JSON mesajı StrinBuffer'a dönüştürülüyor
            StringBuffer responseBuffer;
            Writer<StringBuffer> writer(responseBuffer);
            d.Accept(writer);

            cout << "    Request Message is modified to  : "
                 << responseBuffer.GetString() << endl;

            // Response mesajı hazırlanıyor
            string str = responseBuffer.GetString();
            str.append("\n");
            serverReq->request = DDS::string_dup(str.c_str());
            //serverReq->request = DDS::string_dup("Hello World\n");
            serverReq->requestID = serverReqSeq[j].requestID;

            if(!isDataReceived && status == DDS::RETCODE_OK)
            {
              // Response mesajı Publish ediliyor
              ReturnCode_t tempStatus = serverReqWriter->write(
                    *serverReq, DDS::HANDLE_NIL);
              checkStatus(tempStatus, "severReqDataReader::write");
              isDataReceived = true;

              cout << "    Response Request Message is sent : "
                   << serverReq->request << endl;
              cout << "    Response RequestID is sent : \""
                   << serverReq->requestID << "\"" << endl;
            }
          }

          else
            cout << "Invalid NodeID!" << endl;
        }

      }

      status = serverReqReader->return_loan(serverReqSeq, infoSeq);
      checkStatus(status, "MsgDataReader::return_loan");

      refreshRateCounter++;
      cout << refreshRateCounter << endl;

    } // Matlab komutuna Subscribe olma kısmının sonu

    // Terminalde akacak olan çıktıları dah gözle görülebilir bir şekilde
    // yazdırmak için koyulmuştur
    fake_delay();
  }

  // Hafıza temizle işlemleri gerçekleştiriliyor

  status = wifiSeqWriter->dispose(*wifiSeqInstance, userHandle);
  checkStatus(status, "WifiSeqDataWriter::dispose");
  status = wifiSeqWriter->unregister_instance(*wifiSeqInstance, userHandle);
  checkStatus(status, "WifiSeqDataWriter::unregister_instance");

  delete wifiSeqInstance;
  delete serverReq;

  mgrWifiPub.deleteWriter();
  mgrWifiPub.deletePublisher();
  mgrWifiPub.deleteTopic();
  mgrWifiPub.deleteParticipant();

  mgrReqSub.deleteReader();
  mgrReqSub.deleteSubscriber();
  mgrReqSub.deleteTopic();
  mgrReqSub.deleteParticipant();

  mgrReqPub.deletePublisher();
  mgrReqPub.deleteWriter();
  mgrReqPub.deleteTopic();
  mgrReqPub.deleteParticipant();

  return 0;
}
Exemplo n.º 16
0
/* ****************************************************************************
*
* parseEntity - 
*
* This function is used to parse two slightly different payloads:
* - POST /v2/entities
* - POST /v2/entities/<eid>
*
* In the latter case, "id" CANNOT be in the payload, while in the former case, 
* "id" MUST be in the payload.
*
* In the case of /v2/entities/<eid>, the entityId of 'Entity* eP' is set in
* the service routine postEntity.
*
* Also, if the URI param 'options' includes the value 'keyValues', then the
* parse changes for compound values of attributes. If the value is a JSON object
* then there is no looking inside to find the 'value' field, but the attribute is
* always treated as a compound attribute.
* 
*/
std::string parseEntity(ConnectionInfo* ciP, Entity* eP, bool eidInURL)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    alarmMgr.badInput(clientIp, "JSON parse error");
    eP->oe.fill(SccBadRequest, "Errors found in incoming JSON buffer", ERROR_STRING_PARSERROR);
    ciP->httpStatusCode = SccBadRequest;
    return eP->render(ciP, EntitiesRequest);
  }


  if (!document.IsObject())
  {
    alarmMgr.badInput(clientIp, "JSON Parse Error");
    eP->oe.fill(SccBadRequest, "Errors found in incoming JSON buffer", ERROR_STRING_PARSERROR);
    ciP->httpStatusCode = SccBadRequest;
    return eP->render(ciP, EntitiesRequest);
  }


  if (eidInURL == false)
  {
    if (!document.HasMember("id"))
    {
      alarmMgr.badInput(clientIp, "No entity id specified");
      eP->oe.fill(SccBadRequest, "no entity id specified", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }
  }


  if (eidInURL == true)
  {
    if (document.HasMember("id"))
    {
      alarmMgr.badInput(clientIp, "entity id specified in payload");
      eP->oe.fill(SccBadRequest, "entity id specified in payload", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }

    if (document.HasMember("type"))
    {
      alarmMgr.badInput(clientIp, "entity type specified in payload");
      eP->oe.fill(SccBadRequest, "entity type specified in payload", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;;

      return eP->render(ciP, EntitiesRequest);
    }
  }
  else if (document.ObjectEmpty()) 
  {
    //
    // Initially we used the method "Empty". As the broker crashed inside that method, some
    // research was made and "ObjectEmpty" was found. As the broker stopped crashing and complaints
    // about crashes with small docs and "Empty()" were found on the internet, we opted to use ObjectEmpty
    //
    alarmMgr.badInput(clientIp, "Empty payload");
    eP->oe.fill(SccBadRequest, "empty payload", "BadRequest");
    ciP->httpStatusCode = SccBadRequest;

    return eP->render(ciP, EntitiesRequest);
  }

  int membersFound = 0;
  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    ++membersFound;

    if (name == "id")
    {
      if (eidInURL == false)
      {
        if (type != "String")
        {
          alarmMgr.badInput(clientIp, "invalid JSON type for entity id");
          eP->oe.fill(SccBadRequest, "invalid JSON type for entity id", "BadRequest");
          ciP->httpStatusCode = SccBadRequest;;

          return eP->render(ciP, EntitiesRequest);
        }

        eP->id = iter->value.GetString();
      }
      else  // "id" is present in payload for /v2/entities/<eid> - not a valid payload
      {
        alarmMgr.badInput(clientIp, "'id' is not a valid attribute");
        eP->oe.fill(SccBadRequest, "invalid input, 'id' as attribute", "BadRequest");
        ciP->httpStatusCode = SccBadRequest;;

        return eP->render(ciP, EntitiesRequest);
      }
    }
    else if (name == "type")
    {
      if (type != "String")
      {
        alarmMgr.badInput(clientIp, "invalid JSON type for entity type");
        eP->oe.fill(SccBadRequest, "invalid JSON type for entity type", "BadRequest");
        ciP->httpStatusCode = SccBadRequest;;

        return eP->render(ciP, EntitiesRequest);
      }

      eP->type      = iter->value.GetString();
      eP->typeGiven = true;
    }
    else  // attribute
    {
      ContextAttribute* caP = new ContextAttribute();
      
      eP->attributeVector.push_back(caP);

      std::string r = parseContextAttribute(ciP, iter, caP);
      if (r != "OK")
      {
        alarmMgr.badInput(clientIp, "parse error in context attribute");
        eP->oe.fill(SccBadRequest, r, "BadRequest");
        ciP->httpStatusCode = SccBadRequest;

        return eP->render(ciP, EntitiesRequest);
      }
    }
  }

  if (membersFound == 0)
  {
    eP->oe.fill(SccBadRequest, "empty payload", "BadRequest");
    ciP->httpStatusCode = SccBadRequest;
    return eP->render(ciP, EntitiesRequest);
  }

  if (eidInURL == false)
  {
    if (eP->id == "")
    {
      alarmMgr.badInput(clientIp, "empty entity id");
      eP->oe.fill(SccBadRequest, "empty entity id", "BadRequest");
      ciP->httpStatusCode = SccBadRequest;

      return eP->render(ciP, EntitiesRequest);
    }
  }

  if (!eP->typeGiven)
  {
    eP->type = DEFAULT_ENTITY_TYPE;
  }

  return "OK";
}
Exemplo n.º 17
0
void convert(const char* nameJSON, const char* nameCSV)	{
	
	//Prepare Input
	struct stat statbuf;
	stat(nameJSON, &statbuf);
	size_t fsize = statbuf.st_size;

	int fd = open(nameJSON, O_RDONLY);
	if (fd == -1) {
		throw runtime_error(string("json.open"));
	}

	const char *bufJSON = (const char*) mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
	if (bufJSON == MAP_FAILED) {
		throw runtime_error(string("json.mmap"));
	}
	//Prepare output
	ofstream outFile;
	outFile.open(nameCSV);

	Document d;
	d.Parse(bufJSON);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	stringstream ss;
	Value::ConstMemberIterator itrDoc = d.MemberBegin();
	Value::ConstMemberIterator itrDocEnd = d.MemberEnd();

	if (itrDoc != itrDocEnd) {
		if (itrDoc->value.IsObject()) {
			Value::ConstMemberIterator itr_ = itrDoc->value.MemberBegin();
			Value::ConstMemberIterator itrEnd_ = itrDoc->value.MemberEnd();
			iterateObject(itr_, itrEnd_, &buffer, &writer, ss);
		} else if (itrDoc->value.IsArray()) {
			Value::ConstValueIterator itr_ = itrDoc->value.Begin();
			Value::ConstValueIterator itrEnd_ = itrDoc->value.End();
			iterateArray(itr_, itrEnd_, &buffer, &writer, ss);
		} else if (itrDoc->value.IsBool()) {
			ss << itrDoc->value.GetBool();
		} else if (itrDoc->value.IsInt()) {
			ss << itrDoc->value.GetInt();
		} else if (itrDoc->value.IsInt64()) {
			ss << itrDoc->value.GetInt64();
		} else if (itrDoc->value.IsDouble()) {
			ss << itrDoc->value.GetDouble();
		} else if (itrDoc->value.IsString()) {
			ss << "\"" << itrDoc->value.GetString() << "\"";
		} else {
			throw runtime_error(string("Case missing from tokenizer"));
		}
	}
	itrDoc++;
	iterateObject(itrDoc, itrDocEnd, &buffer, &writer, ss);

	outFile << ss.rdbuf();
	outFile.close();

	close(fd);
	munmap((void*) bufJSON,fsize);
}
Exemplo n.º 18
0
/* ****************************************************************************
*
* parseBatchUpdate - 
*/
std::string parseBatchUpdate(ConnectionInfo* ciP, BatchUpdate* burP)
{
  Document document;

  document.Parse(ciP->payload);

  if (document.HasParseError())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill(ERROR_STRING_PARSERROR, "Errors found in incoming JSON buffer");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  if (!document.IsObject())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "JSON Parse Error");
    ec.fill("BadRequest", "JSON Parse Error");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (document.ObjectEmpty())
  {
    ErrorCode ec;

    alarmMgr.badInput(clientIp, "Empty JSON payload");
    ec.fill("BadRequest", "empty payload");
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("entities"))
  {
    ErrorCode    ec;
    std::string  details = "Invalid JSON payload, mandatory field /entities/ not found";

    alarmMgr.badInput(clientIp, details);
    ec.fill("BadRequest", details);
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }
  else if (!document.HasMember("actionType"))
  {
    ErrorCode    ec;
    std::string  details = "Invalid JSON payload, mandatory field /actionType/ not found";

    alarmMgr.badInput(clientIp, details);
    ec.fill("BadRequest", details);
    ciP->httpStatusCode = SccBadRequest;

    return ec.toJson(true);
  }

  for (Value::ConstMemberIterator iter = document.MemberBegin(); iter != document.MemberEnd(); ++iter)
  {
    std::string name   = iter->name.GetString();
    std::string type   = jsonParseTypeNames[iter->value.GetType()];

    if (name == "entities")
    {
      std::string r = parseEntityVector(ciP, iter, &burP->entities, true); // param 4: attributes are allowed in payload

      if (r != "OK")
      {
        ErrorCode ec("BadRequest", r);

        alarmMgr.badInput(clientIp, r);
        ciP->httpStatusCode = SccBadRequest;
        return ec.toJson(true);
      }
    }
    else if (name == "actionType")
    {
      burP->updateActionType.set(iter->value.GetString());
    }
    else
    {
      std::string  description = std::string("Unrecognized field in JSON payload: /") + name + "/";
      ErrorCode    ec("BadRequest", description);

      alarmMgr.badInput(clientIp, description);
      ciP->httpStatusCode = SccBadRequest;

      return ec.toJson(true);
    }
  }

  return "OK";
}
Exemplo n.º 19
0
void convertMultiple(const char* nameJSON, const char* nameCSV)	{
	//Prepare Input
	struct stat statbuf;
	stat(nameJSON, &statbuf);
	size_t fsize = statbuf.st_size;

	int fd = open(nameJSON, O_RDONLY);
	if (fd == -1) {
		throw runtime_error(string("json.open"));
	}

	const char *bufJSON = (const char*) mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
	if (bufJSON == MAP_FAILED) {
		throw runtime_error(string("json.mmap"));
	}

	//Prepare output
	ofstream outFile;
	outFile.open(nameCSV);

	//Input loop
	size_t obj_start = 0;
	size_t obj_end = 0;
	char *line_bufJSON = NULL;
	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	stringstream ss;


	int flushCount = 0;
	while (obj_start < fsize) {
		size_t i = obj_start;
		for (; bufJSON[i] != '\n'; i++) {}
		obj_end = i;
		line_bufJSON = new char[obj_end - obj_start + 1];
		line_bufJSON[obj_end - obj_start] = '\0';
		memcpy(line_bufJSON, bufJSON + obj_start, obj_end - obj_start);

		//Triggering parser
		Document d;
		d.Parse(line_bufJSON);

		Value::ConstMemberIterator itrDoc = d.MemberBegin();
		Value::ConstMemberIterator itrDocEnd = d.MemberEnd();
		buffer.Clear();
		writer.Reset(buffer);

		//1st iteration unrolled to avoid unnecessary "if(first)" checks
		if (itrDoc != itrDocEnd) {
			if (itrDoc->value.IsObject()) {
				Value::ConstMemberIterator itr_ = itrDoc->value.MemberBegin();
				Value::ConstMemberIterator itrEnd_ = itrDoc->value.MemberEnd();
				iterateObject(itr_, itrEnd_, &buffer, &writer, ss);
			} else if (itrDoc->value.IsArray()) {
				Value::ConstValueIterator itr_ = itrDoc->value.Begin();
				Value::ConstValueIterator itrEnd_ = itrDoc->value.End();
				iterateArray(itr_, itrEnd_, &buffer, &writer, ss);
			} else if (itrDoc->value.IsBool()) {
				ss << itrDoc->value.GetBool();
			} else if (itrDoc->value.IsInt()) {
				ss << itrDoc->value.GetInt();
			} else if (itrDoc->value.IsInt64()) {
				ss << itrDoc->value.GetInt64();
			} else if (itrDoc->value.IsDouble()) {
				ss << itrDoc->value.GetDouble();
			} else if (itrDoc->value.IsString()) {
				ss << "\"" << itrDoc->value.GetString() << "\"";
			} else {
				throw runtime_error(string("Case missing from tokenizer"));
			}
		}
		itrDoc++;
		iterateObject(itrDoc, itrDocEnd, &buffer, &writer, ss);
		ss << "\n";

		//flushing to output file every 1000 entries
		flushCount++;
		if(flushCount % 1000 == 0)	{
			outFile << ss.rdbuf();
			ss.clear();
		}

		//Prepare next loop + cleanup
		delete line_bufJSON;
		obj_start = ++i;

	}

	outFile << ss.rdbuf();
	outFile.close();

	close(fd);
	munmap((void*) bufJSON,fsize);
}
Exemplo n.º 20
0
int main(int, char*[]) {
	////////////////////////////////////////////////////////////////////////////
	// 1. Parse a JSON text string to a document.

	const char json[] = " { \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3, 4] } ";
	printf("Original JSON:\n %s\n", json);

	Document document;  // Default template parameter uses UTF8 and MemoryPoolAllocator.

#if 0
	// "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().
	if (document.Parse(json).HasParseError())
		return 1;
#else
	// In-situ parsing, decode strings directly in the source string. Source must be string.
	char buffer[sizeof(json)];
	memcpy(buffer, json, sizeof(json));
	if (document.ParseInsitu(buffer).HasParseError())
		return 1;
#endif

	printf("\nParsing to document succeeded.\n");

	////////////////////////////////////////////////////////////////////////////
	// 2. Access values in document. 

	printf("\nAccess values in document:\n");
	assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.

	assert(document.HasMember("hello"));
	assert(document["hello"].IsString());
	printf("hello = %s\n", document["hello"].GetString());

	// Since version 0.2, you can use single lookup to check the existing of member and its value:
	Value::MemberIterator hello = document.FindMember("hello");
	assert(hello != document.MemberEnd());
	assert(hello->value.IsString());
	assert(strcmp("world", hello->value.GetString()) == 0);
	(void)hello;

	assert(document["t"].IsBool());     // JSON true/false are bool. Can also uses more specific function IsTrue().
	printf("t = %s\n", document["t"].GetBool() ? "true" : "false");

	assert(document["f"].IsBool());
	printf("f = %s\n", document["f"].GetBool() ? "true" : "false");

	printf("n = %s\n", document["n"].IsNull() ? "null" : "?");

	assert(document["i"].IsNumber());   // Number is a JSON type, but C++ needs more specific type.
	assert(document["i"].IsInt());      // In this case, IsUint()/IsInt64()/IsUInt64() also return true.
	printf("i = %d\n", document["i"].GetInt()); // Alternative (int)document["i"]

	assert(document["pi"].IsNumber());
	assert(document["pi"].IsDouble());
	printf("pi = %g\n", document["pi"].GetDouble());

	{
		const Value& a = document["a"]; // Using a reference for consecutive access is handy and faster.
		assert(a.IsArray());
		for (SizeType i = 0; i < a.Size(); i++) // rapidjson uses SizeType instead of size_t.
			printf("a[%d] = %d\n", i, a[i].GetInt());

		int y = a[0].GetInt();
		(void)y;

		// Iterating array with iterators
		printf("a = ");
		for (Value::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
			printf("%d ", itr->GetInt());
		printf("\n");
	}

	// Iterating object members
	static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
	for (Value::ConstMemberIterator itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr)
		printf("Type of member %s is %s\n", itr->name.GetString(), kTypeNames[itr->value.GetType()]);

	////////////////////////////////////////////////////////////////////////////
	// 3. Modify values in document.

	// Change i to a bigger number
	{
		uint64_t f20 = 1;   // compute factorial of 20
		for (uint64_t j = 1; j <= 20; j++)
			f20 *= j;
		document["i"] = f20;    // Alternate form: document["i"].SetUint64(f20)
		assert(!document["i"].IsInt()); // No longer can be cast as int or uint.
	}

	// Adding values to array.
	{
		Value& a = document["a"];   // This time we uses non-const reference.
		Document::AllocatorType& allocator = document.GetAllocator();
		for (int i = 5; i <= 10; i++)
			a.PushBack(i, allocator);   // May look a bit strange, allocator is needed for potentially realloc. We normally uses the document's.

		// Fluent API
		a.PushBack("Lua", allocator).PushBack("Mio", allocator);
	}

	// Making string values.

	// This version of SetString() just store the pointer to the string.
	// So it is for literal and string that exists within value's life-cycle.
	{
		document["hello"] = "rapidjson";    // This will invoke strlen()
		// Faster version:
		// document["hello"].SetString("rapidjson", 9);
	}

	// This version of SetString() needs an allocator, which means it will allocate a new buffer and copy the the string into the buffer.
	Value author;
	{
		char buffer[10];
		int len = sprintf(buffer, "%s %s", "Milo", "Yip");  // synthetic example of dynamically created string.

		author.SetString(buffer, static_cast<size_t>(len), document.GetAllocator());
		// Shorter but slower version:
		// document["hello"].SetString(buffer, document.GetAllocator());

		// Constructor version: 
		// Value author(buffer, len, document.GetAllocator());
		// Value author(buffer, document.GetAllocator());
		memset(buffer, 0, sizeof(buffer)); // For demonstration purpose.
	}
	// Variable 'buffer' is unusable now but 'author' has already made a copy.
	document.AddMember("author", author, document.GetAllocator());

	assert(author.IsNull());        // Move semantic for assignment. After this variable is assigned as a member, the variable becomes null.

	////////////////////////////////////////////////////////////////////////////
	// 4. Stringify JSON

	printf("\nModified JSON with reformatting:\n");
	StringBuffer sb;
	PrettyWriter<StringBuffer> writer(sb);
	document.Accept(writer);    // Accept() traverses the DOM and generates Handler events.
	puts(sb.GetString());

	return 0;
}
Exemplo n.º 21
0
AbstractWorkSource::Events AbstractWorkSource::Refresh(bool canRead, bool canWrite) {
    // This is public and due to TCP async connect nature, we cannot assume we're ready to go so shortcircuit if still waiting.
    if(!stratum) return Events();

    // As a start, dispatch my data to the server. It is required to do this first as we need to
    // initiate connection with a mining.subscribe. Each tick, we send as many bytes as we can until
    // write buffer is exhausted.
	const time_t PREV_WORK_STAMP(stratum->LastNotifyTimestamp());
    if(stratum->pending.size() && canWrite) {
        asizei count = 1;
        while(count && stratum->pending.size()) {
			StratumState::Blob &msg(stratum->pending.front());
            auto sent(Send(msg.data + msg.sent, msg.total - msg.sent));
            if(sent.first == false) {
                Events ohno;
                ohno.connFailed = true;
                return ohno;
            }
            count = sent.second;
            msg.sent += count;
            if(msg.sent == msg.total) {
#if STRATUM_DUMPTRAFFIC
				stratumDump<<">>sent to server:"<<std::endl;
				for(asizei i = 0; i < msg.total; i++) stratumDump<<msg.data[i];
				stratumDump<<std::endl;
#endif
				stratum->pending.pop();
			}
		}
	}
    Events ret;
	if(canRead == false) return ret; // sends are still considered nops, as they don't really change the hi-level state
    auto received(Receive(recvBuffer.NextBytes(), recvBuffer.Remaining()));
    if(received.first == false) {
        ret.connFailed = true;
        return ret;
    }
    else if(received.second == 0) return ret;
    ret.bytesReceived += received.second;
	recvBuffer.used += received.second;
	if(recvBuffer.Full()) recvBuffer.Grow();
	
	using namespace rapidjson;
	Document object;
	char *pos = recvBuffer.data.get();
	char *lastEndl = nullptr;
    const auto prevDiff(GetCurrentDiff());
    const auto prevJob(stratum->GetCurrentJob());
	while(pos < recvBuffer.NextBytes()) {
		char *limit = std::find(pos, recvBuffer.NextBytes(), '\n');
		if(limit >= recvBuffer.NextBytes()) pos = limit;
		else { // I process one line at time
#if STRATUM_DUMPTRAFFIC
			stratumDump<<">>from server:";
			for(asizei i = 0; pos + i < limit; i++) stratumDump<<pos[i];
			stratumDump<<std::endl;
#endif
			lastEndl = limit;
			ScopedFuncCall restoreChar([limit]() { *limit = '\n'; }); // not really necessary but I like the idea
			*limit = 0;
			object.ParseInsitu(pos);
			const Value::ConstMemberIterator &id(object.FindMember("id"));
			const Value::ConstMemberIterator &method(object.FindMember("method"));
			// There was a time in which stratum had "notifications" and "requests". They were the same thing basically but requests had an id 
			// to be used for confirmations. Besides some idiot wanted to use 0 as an ID, P2Pool servers always attach an ID even to notifications,
			// which is a less brain-damaged thing but still mandated some changes here.
			std::string idstr;
			aulong idvalue = 0;
			if(id != object.MemberEnd()) {
				switch(id->value.GetType()) {
				case kNumberType: {
					if(id->value.IsUint()) idvalue = id->value.GetUint();
					else if(id->value.IsInt()) idvalue = id->value.GetInt();
					else if(id->value.IsUint64()) idvalue = id->value.GetUint64();
					else if(id->value.IsInt64()) idvalue = id->value.GetInt64();
					idstr = std::to_string(idvalue);
					break;
				}
				case kStringType: 
					idstr.assign(id->value.GetString(), id->value.GetStringLength());
					for(size_t check = 0; check < idstr.length(); check++) {
						char c = idstr[check];
						if(c < '0' || c > '9') throw std::exception("All my ids are naturals>0, this should be a natural>0 number!");
					}
					idvalue = strtoul(idstr.c_str(), NULL, 10);
					break;
				}
			}
			/* If you read the minimalistic documentation of stratum you get the idea you can trust on some things.
			No, you don't. The only real thing you can do is figure out if something is a request from the server or a reply. */
			if(method != object.MemberEnd() && method->value.IsString()) {
				if(method->value.GetString()) MangleMessageFromServer(idstr, method->value.GetString(), object["params"]);
			}
			else { // I consider it a reply. Then it has .result or .error... MAYBE. P2Pool for example sends .result=.error=null as AUTH replies to say it doesn't care about who's logging in!
				MangleReplyFromServer(idvalue, object["result"], object["error"]);
			}
			pos = lastEndl + 1;
		}
	}
	if(lastEndl) { // at least a line has been mangled
		const char *src = lastEndl + 1;
		char *dst = recvBuffer.data.get();
		for(; src < recvBuffer.NextBytes(); src++, dst++) *dst = *src;
		recvBuffer.used = src - (lastEndl + 1);
#if _DEBUG
		for(; dst < recvBuffer.data.get() + recvBuffer.allocated; dst++) *dst = 0;
#endif
	}
	else return ret;
    const auto nowDiff(GetCurrentDiff());
    const auto nowJob(stratum->GetCurrentJob());
    auto different = [](const stratum::MiningNotify &one, const stratum::MiningNotify &two) {
        if(one.job != two.job || one.ntime != two.ntime || one.clear != two.clear) return true; // most likely
        if(one.prevHash != two.prevHash) return true; // fairly likely
        // blockVer is mostly constant,
        // nbits is... ?
        if(one.merkles.size() != two.merkles.size()) return true; // happens quite often
        if(one.coinBaseOne.size() != two.coinBaseOne.size() || one.coinBaseTwo.size() != two.coinBaseTwo.size()) return true; // not likely, if at all possible
        bool diff = false;
        for(asizei i = 0; i < one.merkles.size(); i++) diff |= one.merkles[i].hash != two.merkles[i].hash;
        for(asizei i = 0; i < one.coinBaseOne.size(); i++) diff |= one.coinBaseOne[i] != two.coinBaseOne[i];
        for(asizei i = 0; i < one.coinBaseTwo.size(); i++) diff |= one.coinBaseTwo[i] != two.coinBaseTwo[i];
        return diff;
    };
    ret.diffChanged = nowDiff != prevDiff;
    ret.newWork = different(prevJob, nowJob) && GetCurrentDiff().shareDiff != .0; // new work is to be delayed as long as diff is 0
    if(prevDiff.shareDiff == .0 && nowDiff.shareDiff != .0) {
        // When this happens and we already have a job of any sort we can finally flush the new work to the outer code
        if(nowJob.job.size()) ret.newWork = true;
    }
    return ret;
}