// Method for sending message from CPP to the targetted platform
    void SendMessageWithParams(string methodName, CCObject* methodParams)
    {
        if (0 == strcmp(methodName.c_str(), ""))
            return;
        
        json_t *toBeSentJson = json_object();
        json_object_set_new(toBeSentJson, __CALLED_METHOD__, json_string(methodName.c_str()));
        
        if (methodParams != NULL)
        {
            json_t* paramsJson = NDKHelper::GetJsonFromCCObject(methodParams);
            json_object_set_new(toBeSentJson, __CALLED_METHOD_PARAMS__, paramsJson);
        }
        
        #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        JniMethodInfo t;
        
		if (JniHelper::getStaticMethodInfo(t,
                                           CLASS_NAME,
                                           "RecieveCppMessage",
                                           "(Ljava/lang/String;)V"))
		{
            char* jsonStrLocal = json_dumps(toBeSentJson, JSON_COMPACT | JSON_ENSURE_ASCII);
            string jsonStr(jsonStrLocal);
            free(jsonStrLocal);
            
            jstring stringArg1 = t.env->NewStringUTF(jsonStr.c_str());
            t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1);
            t.env->DeleteLocalRef(stringArg1);
			t.env->DeleteLocalRef(t.classID);
		}
        #endif
        
        #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
        json_t *jsonMessageName = json_string(methodName.c_str());
        
        if (methodParams != NULL)
        {
            json_t *jsonParams = NDKHelper::GetJsonFromCCObject(methodParams);
            IOSNDKHelperImpl::RecieveCPPMessage(jsonMessageName, jsonParams);
            json_decref(jsonParams);
        }
        else
        {
            IOSNDKHelperImpl::RecieveCPPMessage(jsonMessageName, NULL);
        }
        
        json_decref(jsonMessageName);
        #endif
        
        json_decref(toBeSentJson);
    }
    cocos2d::CCObject *CCSoomlaNdkBridge::callNative(cocos2d::CCDictionary *params, CCSoomlaError **pError) {
        cocos2d::CCDictionary *methodParams = params;

        json_t *toBeSentJson = CCSoomlaJsonHelper::getJsonFromCCObject(methodParams);
        json_t *retJsonParams;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
        JniMethodInfo t;

		if (JniHelper::getStaticMethodInfo(t,
                                           CLASS_NAME,
                                           "receiveCppMessage",
                                           "(Ljava/lang/String;)Ljava/lang/String;")) {

            char* jsonStrLocal = json_dumps(toBeSentJson, JSON_COMPACT | JSON_ENSURE_ASCII);
            string jsonStr(jsonStrLocal);
            free(jsonStrLocal);

            jstring stringArg1 = t.env->NewStringUTF(jsonStr.c_str());
            jstring retString = (jstring) t.env->CallStaticObjectMethod(t.classID, t.methodID, stringArg1);

            t.env->DeleteLocalRef(stringArg1);
			t.env->DeleteLocalRef(t.classID);

		    const char *nativeString = t.env->GetStringUTFChars(retString, 0);
		    string retParamsStr(nativeString);
		    t.env->ReleaseStringUTFChars(retString, nativeString);


            const char *jsonCharArray = retParamsStr.c_str();

            json_error_t error;
            retJsonParams = json_loads(jsonCharArray, 0, &error);

            if (!retJsonParams) {
                fprintf(stderr, "error: at line #%d: %s\n", error.line, error.text);
                return CCDictionary::create();
            }
		}
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
        retJsonParams = soomla::CCSoomlaNdkBridgeIos::receiveCppMessage(toBeSentJson);
#endif

        json_decref(toBeSentJson);
        CCObject *retParams = CCSoomlaJsonHelper::getCCObjectFromJson(retJsonParams);

        CCSoomlaError *error = CCSoomlaError::createWithObject(retParams);
        if (error != NULL) {
            *pError = error;
        }

        return retParams;
    }
示例#3
0
std::string Message::toJSON() {
	json_t* jsonMessage = json_object();
	json_object_set_new(jsonMessage, "action", json_string(action.c_str()));
	json_t* jsonObject = json_object();
	bundle.toJSON(jsonObject);
	json_object_set_new(jsonMessage, "data", jsonObject);
	char* jsonStrLocal = json_dumps(jsonMessage,
	JSON_COMPACT | JSON_ENSURE_ASCII);
	std::string jsonStr(jsonStrLocal);
	json_decref(jsonObject);
	json_decref(jsonMessage);
	return jsonStr;
}
示例#4
0
void MainWindow::ffprobeInfo() {

    QProcess builder;
    builder.setProcessChannelMode(QProcess::MergedChannels);

    QStringList args;

    args << "-v"; args << "quiet";
    args << "-print_format"; args << "json";
    args << "-show_format";
    args << ui->filePath->text();

    builder.start(ffprobeBin, args);

    if (!builder.waitForFinished()) {
        qDebug() << "failed:" << builder.errorString();
    }
    else {
        QString jsonStr(builder.readAll());

        QJsonDocument doc(QJsonDocument::fromJson(jsonStr.toUtf8()));
        QJsonObject json = doc.object();

        QJsonObject format(json["format"].toObject()); // We just want the "format" field

        QStandardItemModel *model = new QStandardItemModel(0, 2, this);
        model->setHorizontalHeaderItem(0, new QStandardItem(QString("Info")));
        model->setHorizontalHeaderItem(1, new QStandardItem(QString("Value")));

        ui->infoTable->setModel(model);
        ui->infoTable->verticalHeader()->setVisible(false); // remove index number

        QStandardItem *firstRow = new QStandardItem(QString("ColumnValue"));
        model->setItem(0, 0, firstRow);

        // Populate the table
        int i = 0;
        foreach (auto key, format.keys()) {
            QJsonValue val(format[key]);
            if(val.isString() || val.isDouble()) {
                model->setItem(i, 0, new QStandardItem(key));
                model->setItem(i, 1, new QStandardItem(val.toString()));
                ++i;
            }
        }

        for (int c = 0; c < ui->infoTable->horizontalHeader()->count(); ++c) {
            ui->infoTable->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch);
        }

        int duration(format["duration"].toString().split(".")[0].toInt());

        // Convert seconds duration to hh:mm:ss
        int seconds = (int) (duration % 60);
        duration /= 60;
        int minutes = (int) (duration % 60);
        duration /= 60; int hours = (int) (duration % 24);

        // Duration

        QTime time(hours, minutes, seconds);

        // Set timeStart and timeStop limits
        ui->timeStop->setTime(time);
        ui->timeStop->setMaximumTime(time);
        ui->timeStart->setMaximumTime(time);
        // Put the cursor to the "second" section
        ui->timeStop->setCurrentSection(QDateTimeEdit::SecondSection);
        ui->timeStart->setCurrentSection(QDateTimeEdit::SecondSection);


    }

}
示例#5
0
int CHttpServer::processHttpMessage(int nClientFD, message *m)
{
	const char *http_res = 
		"HTTP/1.1 200 OK\r\n"
		"Server: pm_manager\r\n"
		"Date: Wed, 07 Mar 2012 09:43:02 GMT\r\n"
		"Content-Type: application/json; charset=utf-8\r\n"
		"Connection: keep-alive\r\n"

#ifdef NOSETEST
		"Content-Length: 20\r\n\r\n{\"result\":\"success\"}";
#else
		"Content-Length: 15\r\n\r\n{\"result\":true}";
#endif

	if (m->method == HTTP_POST) 
	{
		_DBG("client POST to: %s", m->url);
		_DBG("content: %s", m->body);

		if (strncmp("/event", m->url, 6) == 0)
		{
			//std::string jsonStr = "{\"sn\":123456789,\"component_name\":\"sensor\",\"event\":\"shutdown\",\"hostname\":\"TPE1A0109\"}";
			if (strlen(m->body) == 0) return 1;
			std::string jsonStr(m->body);
			
			Json::Reader reader;  
			Json::Value value;
			if(reader.parse(jsonStr, value))
			{
				char hostname[BUF_SIZE], event[BUF_SIZE];
				
				_DBG("GOT HTTP event: %s", value["event"].asString().c_str());
				
				strcpy(event, value["event"].asString().c_str());

				if (strncmp(event, "poweroff", 8) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());
						_DBG("%s is POWERED OFF !!", hostname);
						if (-1 != m_nEventFilter)
						{
							sendMessage(m_nEventFilter, EVENT_MONITOR_SHUTDOWN, nClientFD, strlen(hostname), hostname);
						}
						else
						{
							sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_SHUTDOWN, nClientFD, strlen(hostname), hostname);
						}
					}
				}
				else if (strncmp(event, "heartbeat", 9) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());

						if (strncmp(status, "heartbeat", 9) == 0)
						{
							if (-1 != m_nEventFilter)
							{
								sendMessage(m_nEventFilter, EVENT_MONITOR_BOOT, nClientFD, strlen(hostname), hostname);
							}
							else
							{
								sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_BOOT, nClientFD, strlen(hostname), hostname);
							}
						}
					}
				}
				else if (strncmp(event, "dead", 4) == 0)
				{
					char status[BUF_SIZE];
					Json::Value nodes = value["nodes"];
					
					for (unsigned int index = 0; index < nodes.size(); ++index)
					{
						memset(hostname, 0, sizeof(hostname));
						memset(status, 0, sizeof(status));
						strcpy(hostname, nodes[index]["hostname"].asString().c_str());
						strcpy(status, nodes[index]["status"].asString().c_str());
						_DBG("%s is DEAD !! T_T", hostname);
						if (-1 != m_nEventFilter)
						{
							sendMessage(m_nEventFilter, EVENT_MONITOR_DEAD, nClientFD, strlen(hostname), hostname);
						}
						else
						{
							sendMessage(EVENT_FILTER_HTTP_SERVER, EVENT_MONITOR_DEAD, nClientFD, strlen(hostname), hostname);
						}
					}
				}
			}

		}
	}

	socketSend(nClientFD, http_res, strlen(http_res));

	return 0;
}
示例#6
0
void LevelLoader::Load(const char* fileName)
{
	std::ifstream file(fileName);

	if (!file.is_open())
	{
		SDL_Log("Level file %s not found", fileName);
		return;
	}

	std::stringstream fileStream;
	fileStream << file.rdbuf();
	std::string contents = fileStream.str();
	rapidjson::StringStream jsonStr(contents.c_str());
	rapidjson::Document doc;
	doc.ParseStream(jsonStr);

	if (!doc.IsObject())
	{
		SDL_Log("Level file %s is not valid JSON", fileName);
		DbgAssert(false, "Level file is not valid JSON!");
		return;
	}

	std::string str = doc["metadata"]["type"].GetString();
	int ver = doc["metadata"]["version"].GetInt();

	// Check the metadata
	if (!doc["metadata"].IsObject() ||
		str != "itplevel" ||
		ver != 1)
	{
		SDL_Log("Level %s is not a know level file format", fileName);
		return;
	}

	// Step 1: Setup any overall world properties
	if(doc["world"].IsObject())
	{
		Vector3 ambientLight;
		GetVectorFromJSON(doc["world"], "ambientLight", ambientLight);

		mGame.GetRenderer().SetAmbientLight(ambientLight);
	}
	

	// Step 2: Setup the actors (and each of their components)
	const rapidjson::Value& actorsRoot = doc["actors"];
	for (rapidjson::SizeType i = 0; i < actorsRoot.Size(); i++)
	{
		std::string type = actorsRoot[i]["type"].GetString();
		ActorSpawnFunc & f = mActorSpawnMap.find(type)->second;
		ActorPtr actor = f(mGame, actorsRoot[i]["properties"]);
		
		//Iterate updated components
		const rapidjson::Value& updatedComponents = actorsRoot[i]["updatedComponents"];
		for (rapidjson::SizeType j = 0; j < updatedComponents.Size(); j++)
		{
			std::string componentType = updatedComponents[j]["type"].GetString();

			ComponentInfo & typeinfo = mCompSpawnMap.find(componentType)->second;
			ComponentPtr component = actor->GetComponentFromType(typeinfo.mType);
			if(component != nullptr)
			{
				component->SetProperties(updatedComponents[j]["properties"]);
			}
		}

		//Iterate new components
		const rapidjson::Value& newComponents = actorsRoot[i]["newComponents"];
		for(rapidjson::SizeType j = 0; j < newComponents.Size(); j++)
		{
			std::string componentType = newComponents[j]["type"].GetString();
			ComponentInfo & typeinfo = mCompSpawnMap.find(componentType)->second;

			Component::UpdateType updateType = Component::UpdateType::PreTick;
			std::string update = newComponents[j]["update"].GetString();
			if(update == "PostTick")
			{
				updateType = Component::UpdateType::PostTick;
			}

			typeinfo.mFunc(*actor, updateType , newComponents[j]["properties"]);
		}

		//Begin actor
		actor->BeginPlay();
	}
}
示例#7
0
bool Skeleton::Load(const char* fileName, class AssetCache* cache)
{
	std::ifstream file(fileName);
	if (!file.is_open())
	{
		SDL_Log("File not found: Skeleton %s", fileName);
		return false;
	}

	std::stringstream fileStream;
	fileStream << file.rdbuf();
	std::string contents = fileStream.str();
	rapidjson::StringStream jsonStr(contents.c_str());
	rapidjson::Document doc;
	doc.ParseStream(jsonStr);

	if (!doc.IsObject())
	{
		SDL_Log("Skeleton %s is not valid json", fileName);
		return false;
	}

	std::string str = doc["metadata"]["type"].GetString();
	int ver = doc["metadata"]["version"].GetInt();

	// Check the metadata
	if (!doc["metadata"].IsObject() ||
		str != "itpskel" ||
		ver != 1)
	{
		SDL_Log("Skeleton %s unknown format", fileName);
		return false;
	}

	const rapidjson::Value& bonecount = doc["bonecount"];
	if (!bonecount.IsUint())
	{
		SDL_Log("Skeleton %s doesn't have a bone count.", fileName);
		return false;
	}

	size_t count = bonecount.GetUint();

	DbgAssert(count <= MAX_SKELETON_BONES, "Skeleton exceeds maximum allowed bones.");

	mBones.reserve(count);

	const rapidjson::Value& bones = doc["bones"];
	if (!bones.IsArray())
	{
		SDL_Log("Skeleton %s doesn't have a bone array?", fileName);
		return false;
	}

	if (bones.Size() != count)
	{
		SDL_Log("Skeleton %s has a mismatch between the bone count and number of bones", fileName);
		return false;
	}

	Bone temp;

	for (rapidjson::SizeType i = 0; i < count; i++)
	{
		if (!bones[i].IsObject())
		{
			SDL_Log("Skeleton %s: Bone %d is invalid.", fileName, i);
			return false;
		}

		const rapidjson::Value& name = bones[i]["name"];
		temp.mName = name.GetString();

		const rapidjson::Value& parent = bones[i]["parent"];
		temp.mParent = parent.GetInt();

		const rapidjson::Value& bindpose = bones[i]["bindpose"];
		if (!bindpose.IsObject())
		{
			SDL_Log("Skeleton %s: Bone %d is invalid.", fileName, i);
			return false;
		}

		const rapidjson::Value& rot = bindpose["rot"];
		const rapidjson::Value& trans = bindpose["trans"];

		if (!rot.IsArray() || !trans.IsArray())
		{
			SDL_Log("Skeleton %s: Bone %d is invalid.", fileName, i);
			return false;
		}

		temp.mLocalBindPose.mRotation.x = rot[0].GetDouble();
		temp.mLocalBindPose.mRotation.y = rot[1].GetDouble();
		temp.mLocalBindPose.mRotation.z = rot[2].GetDouble();
		temp.mLocalBindPose.mRotation.w = rot[3].GetDouble();

		temp.mLocalBindPose.mTranslation.x = trans[0].GetDouble();
		temp.mLocalBindPose.mTranslation.y = trans[1].GetDouble();
		temp.mLocalBindPose.mTranslation.z = trans[2].GetDouble();

		mBones.emplace_back(temp);
	}

	// Now that we have the bones
	ComputeGlobalInvBindPose();

	return true;
}