/*
 * Update the location of the device. This method converts the
 * date in the required format. The caller needs to pass the date in string in ISO8601 format.
 * 
 * @param client reference to the ManagedDevice
 *
 * @param latitude	Latitude in decimal degrees using WGS84
 *
 * @param longitude Longitude in decimal degrees using WGS84
 *
 * @param elevation	Elevation in meters using WGS84
 *
 * @param measuredDateTime When the location information is retrieved
 *
 * @param accuracy	Accuracy of the position in meters
 *
 * @param reqId Function returns the reqId if the updateLocation request is successful.
 *
 * @return code indicating whether the update is successful or not
 *        (200 means success, otherwise unsuccessful)

 */
void updateLocation(ManagedDevice* client, double latitude, double longitude, double elevation, char* measuredDateTime, double accuracy, char* reqId)
{
	int rc = -1;

	char uuid_str[40];
	generateUUID(uuid_str);
	strcpy(currentRequestID,uuid_str);

	char data[500];
	sprintf(data,"{\"d\":{\"longitude\":%f,\"latitude\":%f,\"elevation\":%f,\"measuredDateTime\":\"%s\",\"accuracy\":%f},\"reqId\":\"%s\"}", latitude, longitude, elevation, measuredDateTime, accuracy, uuid_str);

	rc = publish(client, UPDATE_LOCATION, data);
	if(rc == SUCCESS)
		strcpy(reqId, uuid_str);
}
/**
 * The Log message that needs to be added to the Watson IoT Platform.
 *
 * @param message The Log message that needs to be added to the Watson IoT Platform.
 *
 * @param timestamp The Log timestamp 
 *
 * @param data The optional diagnostic string data
 *
 * @param severity The Log severity
 *
 * @param reqId Function returns the reqId if the addLog request is successful.
 *
 * @return code indicating whether the update is successful or not
 *        (200 means success, otherwise unsuccessful)
 */
void addLog(char* message, char* data ,int severity, char* reqId)
{
	char uuid_str[40];
	int rc = -1;
	generateUUID(uuid_str);
	strcpy(currentRequestID,uuid_str);
	time_t t = 0;
	char updatedDateTime[50];//"2016-03-01T07:07:56.323Z"
	strftime(updatedDateTime, sizeof(updatedDateTime), "%Y-%m-%dT%TZ", localtime(&t));
	char payload[125];
	sprintf(payload,"{\"d\":{\"message\":\"%s\",\"timestamp\":\"%s\",\"data\":\"%s\",\"severity\":%d},\"reqId\":\"%s\"}",message,updatedDateTime,data,severity, uuid_str);

	rc = publish(ADD_DIAG_LOG, payload );
	if(rc == SUCCESS)
		strcpy(reqId, uuid_str);
}
/**
* <p>Send a device manage request to Watson IoT Platform</p>
* 
* <p>A Device uses this request to become a managed device. 
* It should be the first device management request sent by the 
* Device after connecting to the IBM Watson IoT Platform. 
* It would be usual for a device management agent to send this 
* whenever is starts or restarts.</p>
* 
* <p>This method connects the device to Watson IoT Platform connect if its not connected already</p>
* 
* @param lifetime The length of time in seconds within 
*        which the device must send another Manage device request.
*        if set to 0, the managed device will not become dormant. 
*        When set, the minimum supported setting is 3600 (1 hour).
* 
* @param supportFirmwareActions Tells whether the device supports firmware actions or not.
*        The device must add a firmware handler to handle the firmware requests.
* 
* @param supportDeviceActions Tells whether the device supports Device actions or not.
*        The device must add a Device action handler to handle the reboot and factory reset requests.
*
* @param reqId Function returns the reqId if the publish Manage request is successful.
* 
* @return
*/
void publishManageEvent(long lifetime, int supportFirmwareActions,
	int supportDeviceActions, char* reqId)
{
		char uuid_str[40];
		generateUUID(uuid_str);
		strcpy(currentRequestID,uuid_str);
		char* strPayload = "{\"d\": {\"metadata\":%s ,\"lifetime\":%ld ,\"supports\": {\"deviceActions\":%d,\"firmwareActions\":%d},\"deviceInfo\": {\"serialNumber\":\"%s\",\"manufacturer\":\"%s\",\"model\":\"%s\",\"deviceClass\":\"%s\",\"description\":\"%s\",\"fwVersion\":\"%s\",\"hwVersion\":\"%s\",\"descriptiveLocation\":\"%s\"}},\"reqId\": \"%s\"}" ;//cJSON_Print(jsonPayload);
		char payload[1500];
		sprintf(payload,strPayload,dmClient.DeviceData.metadata.metadata,lifetime, supportDeviceActions, supportFirmwareActions, dmClient.DeviceData.deviceInfo.serialNumber,dmClient.DeviceData.deviceInfo.manufacturer, dmClient.DeviceData.deviceInfo.model,dmClient.DeviceData.deviceInfo.deviceClass,dmClient.DeviceData.deviceInfo.description,dmClient.DeviceData.deviceInfo.fwVersion,dmClient.DeviceData.deviceInfo.hwVersion,dmClient.DeviceData.deviceInfo.descriptiveLocation,uuid_str);
		int rc = -1;
		rc = publish(MANAGE, payload);
		if(rc == SUCCESS){
			strcpy(reqId, uuid_str);
			printf("publish success\n");
		}
}
std::string
ServerMethods::connectEventHandler (std::shared_ptr<MediaObjectImpl> obj,
                                    const std::string &sessionId, const std::string &eventType,
                                    std::shared_ptr<EventHandler> handler)
{
  std::string subscriptionId;

  if (!obj->connect (eventType, handler) ) {
    throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
  }

  subscriptionId = generateUUID();

  registerEventHandler (obj, sessionId, subscriptionId, handler);

  return subscriptionId;
}
        ProcessCallbackI::ProcessCallbackI(
                const Ice::ObjectAdapterPtr& adapter,
                const ProcessPrx& process,
                bool poll) :
            ProcessCallback(),
            adapter(adapter),
            id(Ice::Identity()),
            poll(poll),
            result(std::string()),
            process(process) {

            std::string uuid = generateUUID();
            this->id.category = "ProcessCallback";
            this->id.name = uuid;
            Ice::ObjectPrx prx = adapter->add(this, this->id);
            omero::grid::ProcessCallbackPrx pcb = ProcessCallbackPrx::uncheckedCast(prx);
            process->registerCallback(pcb);

        };
Example #6
0
void UserModule::sendAccount(WebPage *page, HttpRequest &request) {
	MySQL *query = manager->newQuery();
	String guid = generateUUID();
	String email = request.header.POST.getValue("email");
	String login = request.header.POST.getValue("login");
	if (email != "") {
		String password = manager->generateUserPassword();
		String sql = "select * from users where email='" + email + "'";
		if (query->exec(sql)) {
			if (query->storeResult()) {
				int count = query->getRowCount();
				if (count > 0) {
					guid = query->getFieldValue(0, "uuid");
					sql = "update users set newPassword='******', uuid='" + guid + "' where email='" + email + "'";
					if (query->exec(sql)) {}
				}
				else {
					sql = "insert into users (email, login, newPassword, uuid) values('" + email + "', '" + login + "', '" + password + "', '" + guid + "')";
					if (query->exec(sql)) {}
				}
			}
		}
		WebTemplate * tplEmail = new WebTemplate();
		String userTpl = "email_tpl.html";
		if (tplEmail->open(manager->modulePath + "/user/" + userTpl)) {
			tplEmail->out("host", page->site->host);
			tplEmail->out("email", email);
			tplEmail->out("password", password);
			tplEmail->out("guid", guid);
			tplEmail->exec();
			sendMail(email, "no-reply@" + page->site->host, page->site->host + ": подтверждение аккаунта", tplEmail->html);
		}

		WebTemplate * tpl = new WebTemplate();
		if (tpl->open(manager->modulePath + "/user/loginSendAccount_tpl.html")) {
			tpl->out("out", email);
			tpl->exec();
			page->out("content", tpl->html);
		}
	}
	manager->deleteQuery(query);
}
void
ServerMethods::subscribe (const Json::Value &params, Json::Value &response)
{
  std::shared_ptr<MediaObject> obj;
  std::string eventType;
  std::string handlerId;
  std::string sessionId;
  std::string objectId;

  requireParams (params);

  JsonRpc::getValue (params, "type", eventType);
  JsonRpc::getValue (params, OBJECT, objectId);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    generateUUID (sessionId);
  }

  try {
    obj = MediaSet::getMediaSet().getMediaObject (sessionId, objectId);

    handlerId = connectEventHandler (obj, sessionId, eventType, params);

    if (handlerId == "") {
      throw KurentoException (MEDIA_OBJECT_EVENT_NOT_SUPPORTED, "Event not found");
    }
  } catch (KurentoException &ex) {
    Json::Value data;
    data["code"] = ex.getCode();
    data["message"] = ex.getMessage();

    JsonRpc::CallException e (JsonRpc::ErrorCode::SERVER_ERROR_INIT,
                              ex.what(), data);
    throw e;
  }

  response["sessionId"] = sessionId;
  response["value"] = handlerId;
}
void
ServerMethods::create (const Json::Value &params,
                       Json::Value &response)
{
  std::string type;
  std::shared_ptr<Factory> factory;
  std::string sessionId;

  requireParams (params);

  JsonRpc::getValue (params, TYPE, type);

  try {
    JsonRpc::getValue (params, SESSION_ID, sessionId);
  } catch (JsonRpc::CallException e) {
    sessionId = generateUUID ();
  }

  try {
    factory = moduleManager.getFactory (type);

    checkResources (resourceLimitPercent);

    std::shared_ptr <MediaObjectImpl> object;

    object = std::dynamic_pointer_cast<MediaObjectImpl> (
               factory->createObject (config, sessionId, params["constructorParams"]) );

    response[VALUE] = object->getId();
    response[SESSION_ID] = sessionId;
  } catch (KurentoException &ex) {
    Json::Value data;

    data[TYPE] = ex.getType();

    throw JsonRpc::CallException (ex.getCode (), ex.getMessage (), data);
  }
}
Example #9
0
void vs_assign_guids()
{
	int p;
	for (p = 0; p < prj_get_numpackages(); ++p)
	{
		VsPkgData* data = ALLOCT(VsPkgData);
		prj_select_package(p);
		prj_set_data(data);
	
		generateUUID(data->projGuid);

		prj_select_config(0);
		if (version >= VS2005 && prj_is_kind("aspnet"))
		{
			strcpy(data->toolGuid, "E24C65DC-7377-472B-9ABA-BC803B73C61A");
			strcpy(data->projExt, "");
			strcpy(data->projType, "");
		}
		else if (prj_is_lang("c++") || prj_is_lang("c"))
		{
			strcpy(data->toolGuid, "8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942");
			strcpy(data->projExt, "vcproj");
			strcpy(data->projType, "Win32");
		}
		else if (prj_is_lang("c#"))
		{
			strcpy(data->toolGuid, "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC");
			strcpy(data->projExt, "csproj");
			if (version < VS2005)
				strcpy(data->projType, ".NET");
			else
				strcpy(data->projType, "Any CPU");
		}

		data->numDependencies = 0;
	}
}
    GameObjectSpec* gameObjectFromStream(IFileStream& stream){
        std::string mesh, physics;
        GameObjectFlagsFlags flags = GameObjectFlags::Enum(0);
        GameObjectSpec* gameObject = new GameObjectSpec;
        gameObject->position[0] = gameObject->position[1] = gameObject->position[2] = 0.0;
        gameObject->rotation[0] = gameObject->rotation[1] = gameObject->rotation[2] = gameObject->rotation[3] = 0.0;
        gameObject->scaling[0] = gameObject->scaling[1] = gameObject->scaling[2] = 0.0;

        String line;
        while(std::getline(stream, line)){
            if(line.compare("end obj") == 0)
                break;
            size_t eq_pos = line.find("=");
            if(eq_pos == std::string::npos || eq_pos >= line.length() - 1)
                continue;
            std::string identifier = line.substr(0, eq_pos);
            std::string data = line.substr(eq_pos + 1);
            std::transform(identifier.begin(), identifier.end(), identifier.begin(), ::tolower);
            std::transform(data.begin(), data.end(), data.begin(), ::tolower);
            if(identifier.compare("position") == 0){
                std::stringstream dataS(data);
                for(int i = 0; i < 3; ++i){
                    std::string f;
                    std::getline(dataS, f, ',');
                    gameObject->position[i] = std::stof(f);
                }
            } else if(identifier.compare("rotation") == 0){
                std::stringstream dataS(data);
                for(int i = 0; i < 4; ++i){
                    std::string f;
                    std::getline(dataS, f, ',');
                    gameObject->rotation[i] = std::stof(f);
                }
            } else if(identifier.compare("scaling") == 0){
                std::stringstream dataS(data);
                for(int i = 0; i < 3; ++i){
                    std::string f;
                    std::getline(dataS, f, ',');
                    gameObject->scaling[i] = std::stof(f);
                }
            } else if(identifier.compare("triggerarea") == 0){
                if(std::stof(data) == 1)
                    flags.set(GameObjectFlags::TriggerArea);
                else if(std::stof(data) == 0)
                    flags.unset(GameObjectFlags::TriggerArea);
            } else if(identifier.compare("mesh") == 0){
                mesh = data;
            } else if(identifier.compare("physics") == 0){
                physics = data;
            }
        }

        gameObject->uuid = generateUUID();
        PhysicsSpec* phySpec = physicsByFileName(physics);
        if(phySpec != nullptr){
            gameObject->physicsId = phySpec->uuid;
            flags.set(GameObjectFlags::Physics);
        } else {
            flags.unset(GameObjectFlags::Physics);
        }
        MeshSpec* meshSpec = meshByName(mesh);
        if(meshSpec != nullptr){
            gameObject->meshId = meshSpec->uuid;
            flags.set(GameObjectFlags::Mesh);
        } else {
            flags.unset(GameObjectFlags::Mesh);
        }
        gameObject->flags = flags;

        return gameObject;
    }
ServerMethods::ServerMethods (const boost::property_tree::ptree &config) :
  config (config), moduleManager (getModuleManager() )
{
  std::string version (get_version() );
  std::vector<std::shared_ptr<ModuleInfo>> modules;
  std::shared_ptr<ServerType> type (new ServerType (ServerType::KMS) );
  std::vector<std::string> capabilities;
  std::shared_ptr <ServerInfo> serverInfo;
  std::shared_ptr<MediaObjectImpl> serverManager;

  resourceLimitPercent =
    config.get<float> ("mediaServer.resources.exceptionLimit",
                       DEFAULT_RESOURCE_LIMIT_PERCENT);

  GST_INFO ("Not enough resources exception will be raised when resources reach %f ",
            resourceLimitPercent);

  instanceId = generateUUID();

  for (auto moduleIt : moduleManager.getModules () ) {
    std::vector<std::string> factories;

    for (auto factIt : moduleIt.second->getFactories() ) {
      factories.push_back (factIt.first);
    }

    modules.push_back (std::shared_ptr<ModuleInfo> (new ModuleInfo (
                         moduleIt.second->getVersion(), moduleIt.second->getName(), factories) ) );
  }

  capabilities.push_back ("transactions");

  serverInfo = std::shared_ptr <ServerInfo> (new ServerInfo (version, modules,
               type, capabilities) );

  serverManager = MediaSet::getMediaSet ()->ref (new ServerManagerImpl (
                    serverInfo, config, moduleManager) );
  MediaSet::getMediaSet ()->setServerManager (std::dynamic_pointer_cast
      <ServerManagerImpl> (serverManager) );

  cache = std::shared_ptr<RequestCache> (new RequestCache (REQUEST_TIMEOUT) );

  handler.setPreProcess (std::bind (&ServerMethods::preProcess, this,
                                    std::placeholders::_1,
                                    std::placeholders::_2) );
  handler.setPostProcess (std::bind (&ServerMethods::postProcess, this,
                                     std::placeholders::_1,
                                     std::placeholders::_2) );

  handler.addMethod ("connect", std::bind (&ServerMethods::connect, this,
                     std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("create", std::bind (&ServerMethods::create, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("invoke", std::bind (&ServerMethods::invoke, this,
                                          std::placeholders::_1,
                                          std::placeholders::_2) );
  handler.addMethod ("subscribe", std::bind (&ServerMethods::subscribe, this,
                     std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("unsubscribe", std::bind (&ServerMethods::unsubscribe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("release", std::bind (&ServerMethods::release,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("ref", std::bind (&ServerMethods::ref,
                                       this, std::placeholders::_1,
                                       std::placeholders::_2) );
  handler.addMethod ("unref", std::bind (&ServerMethods::unref,
                                         this, std::placeholders::_1,
                                         std::placeholders::_2) );
  handler.addMethod ("keepAlive", std::bind (&ServerMethods::keepAlive,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("describe", std::bind (&ServerMethods::describe,
                     this, std::placeholders::_1,
                     std::placeholders::_2) );
  handler.addMethod ("transaction", std::bind (&ServerMethods::transaction,
                     this, std::placeholders::_1, std::placeholders::_2) );
}