コード例 #1
0
/*!

*/
void
MonitorServer::parseMonitorInit( const char * msg,
                                 const QHostAddress & addr,
                                 const quint16 port )
{
    double ver = 1.0;
    if ( ! std::strcmp( msg, "(dispinit)" ) )
    {
        RemoteMonitor * mon = new RemoteMonitor( this, 1 );
        if ( ! mon->connect( addr, port ) )
        {
            delete mon;
            return;
        }

        std::cout << "a new (v1) monitor connected" << std::endl;
        M_monitors.push_back( mon );
        sendInit( *mon );
        return;
    }

    if ( std::sscanf( msg, "(dispinit version %lf)", &ver ) == 1 )
    {
        if ( ver < 1.0 || 5.0 <= ver )
        {
            std::cout << "Unsupported monitor protocol version. " << ver
                      << std::endl;
            return;
        }

        // a new monitor connected
        RemoteMonitor * mon = new RemoteMonitor( this, static_cast< int >( ver ) );

        if( ! mon->connect( addr, port ) )
        {
            delete mon;
            return;
        }

        std::cout << "a new (v" << ver << ") monitor connected" << std::endl;
        M_monitors.push_back( mon );

        // send server parameter information & current display data to monitor
        sendInit( *mon );
        return;
    }

}
コード例 #2
0
int main() {
    srand(time(NULL));

    std::cout.sync_with_stdio(0);

    unsigned char myID;
    hlt::GameMap presentMap;
    getInit(myID, presentMap);
    sendInit("C++Bot");

    std::set<hlt::Move> moves;
    while(true) {
        moves.clear();

        getFrame(presentMap);

        for(unsigned short a = 0; a < presentMap.height; a++) {
            for(unsigned short b = 0; b < presentMap.width; b++) {
                if (presentMap.getSite({ b, a }).owner == myID) {

                    bool movedPiece = false;

                    for(int d : CARDINALS) {
                        if(presentMap.getSite({ b, a }, d).owner != myID && presentMap.getSite({ b, a }, d).strength < presentMap.getSite({ b, a }).strength) {
                            moves.insert({ { b, a }, d });
                            movedPiece = true;
                            break;
                        }
                    }

                    if(!movedPiece && presentMap.getSite({ b, a }).strength < presentMap.getSite({ b, a }).production * 5) {
                        moves.insert({ { b, a }, STILL });
                        movedPiece = true;
                    }

                    if(!movedPiece) {
                        moves.insert({ { b, a }, (bool)(rand() % 2) ? NORTH : WEST });
                        movedPiece = true;
                    }
                }
            }
        }

        sendFrame(moves);
    }

    return 0;
}
コード例 #3
0
ファイル: client.cpp プロジェクト: BlockMen/minetest
void Client::step(float dtime)
{
	DSTACK(FUNCTION_NAME);

	// Limit a bit
	if(dtime > 2.0)
		dtime = 2.0;

	if(m_ignore_damage_timer > dtime)
		m_ignore_damage_timer -= dtime;
	else
		m_ignore_damage_timer = 0.0;

	m_animation_time += dtime;
	if(m_animation_time > 60.0)
		m_animation_time -= 60.0;

	m_time_of_day_update_timer += dtime;

	ReceiveAll();

	/*
		Packet counter
	*/
	{
		float &counter = m_packetcounter_timer;
		counter -= dtime;
		if(counter <= 0.0)
		{
			counter = 20.0;

			infostream << "Client packetcounter (" << m_packetcounter_timer
					<< "):"<<std::endl;
			m_packetcounter.print(infostream);
			m_packetcounter.clear();
		}
	}

	// UGLY hack to fix 2 second startup delay caused by non existent
	// server client startup synchronization in local server or singleplayer mode
	static bool initial_step = true;
	if (initial_step) {
		initial_step = false;
	}
	else if(m_state == LC_Created) {
		float &counter = m_connection_reinit_timer;
		counter -= dtime;
		if(counter <= 0.0) {
			counter = 2.0;

			Player *myplayer = m_env.getLocalPlayer();
			FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");

			// Send TOSERVER_INIT_LEGACY
			// [0] u16 TOSERVER_INIT_LEGACY
			// [2] u8 SER_FMT_VER_HIGHEST_READ
			// [3] u8[20] player_name
			// [23] u8[28] password (new in some version)
			// [51] u16 minimum supported network protocol version (added sometime)
			// [53] u16 maximum supported network protocol version (added later than the previous one)

			char pName[PLAYERNAME_SIZE];
			char pPassword[PASSWORD_SIZE];
			memset(pName, 0, PLAYERNAME_SIZE * sizeof(char));
			memset(pPassword, 0, PASSWORD_SIZE * sizeof(char));

			std::string hashed_password = translatePassword(myplayer->getName(), m_password);
			snprintf(pName, PLAYERNAME_SIZE, "%s", myplayer->getName());
			snprintf(pPassword, PASSWORD_SIZE, "%s", hashed_password.c_str());

			sendLegacyInit(pName, pPassword);
			if (LATEST_PROTOCOL_VERSION >= 25)
				sendInit(myplayer->getName());
		}

		// Not connected, return
		return;
	}

	/*
		Do stuff if connected
	*/

	/*
		Run Map's timers and unload unused data
	*/
	const float map_timer_and_unload_dtime = 5.25;
	if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
		ScopeProfiler sp(g_profiler, "Client: map timer and unload");
		std::vector<v3s16> deleted_blocks;
		m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
			g_settings->getFloat("client_unload_unused_data_timeout"),
			g_settings->getS32("client_mapblock_limit"),
			&deleted_blocks);

		/*
			Send info to server
			NOTE: This loop is intentionally iterated the way it is.
		*/

		std::vector<v3s16>::iterator i = deleted_blocks.begin();
		std::vector<v3s16> sendlist;
		for(;;) {
			if(sendlist.size() == 255 || i == deleted_blocks.end()) {
				if(sendlist.empty())
					break;
				/*
					[0] u16 command
					[2] u8 count
					[3] v3s16 pos_0
					[3+6] v3s16 pos_1
					...
				*/

				sendDeletedBlocks(sendlist);

				if(i == deleted_blocks.end())
					break;

				sendlist.clear();
			}

			sendlist.push_back(*i);
			++i;
		}
	}

	/*
		Handle environment
	*/
	// Control local player (0ms)
	LocalPlayer *player = m_env.getLocalPlayer();
	assert(player != NULL);
	player->applyControl(dtime);

	// Step environment
	m_env.step(dtime);

	/*
		Get events
	*/
	for(;;) {
		ClientEnvEvent event = m_env.getClientEvent();
		if(event.type == CEE_NONE) {
			break;
		}
		else if(event.type == CEE_PLAYER_DAMAGE) {
			if(m_ignore_damage_timer <= 0) {
				u8 damage = event.player_damage.amount;

				if(event.player_damage.send_to_server)
					sendDamage(damage);

				// Add to ClientEvent queue
				ClientEvent event;
				event.type = CE_PLAYER_DAMAGE;
				event.player_damage.amount = damage;
				m_client_event_queue.push(event);
			}
		}
		else if(event.type == CEE_PLAYER_BREATH) {
				u16 breath = event.player_breath.amount;
				sendBreath(breath);
		}
	}

	/*
		Print some info
	*/
	float &counter = m_avg_rtt_timer;
	counter += dtime;
	if(counter >= 10) {
		counter = 0.0;
		// connectedAndInitialized() is true, peer exists.
		float avg_rtt = getRTT();
		infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
	}

	/*
		Send player position to server
	*/
	{
		float &counter = m_playerpos_send_timer;
		counter += dtime;
		if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
		{
			counter = 0.0;
			sendPlayerPos();
		}
	}

	/*
		Replace updated meshes
	*/
	{
		int num_processed_meshes = 0;
		while (!m_mesh_update_thread.m_queue_out.empty())
		{
			num_processed_meshes++;

			MinimapMapblock *minimap_mapblock = NULL;
			bool do_mapper_update = true;

			MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
			MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
			if (block) {
				// Delete the old mesh
				if (block->mesh != NULL) {
					delete block->mesh;
					block->mesh = NULL;
				}

				if (r.mesh) {
					minimap_mapblock = r.mesh->moveMinimapMapblock();
					if (minimap_mapblock == NULL)
						do_mapper_update = false;
				}

				if (r.mesh && r.mesh->getMesh()->getMeshBufferCount() == 0) {
					delete r.mesh;
				} else {
					// Replace with the new mesh
					block->mesh = r.mesh;
				}
			} else {
				delete r.mesh;
			}

			if (do_mapper_update)
				m_mapper->addBlock(r.p, minimap_mapblock);

			if (r.ack_block_to_server) {
				/*
					Acknowledge block
					[0] u8 count
					[1] v3s16 pos_0
				*/
				sendGotBlocks(r.p);
			}
		}

		if (num_processed_meshes > 0)
			g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
	}

	/*
		Load fetched media
	*/
	if (m_media_downloader && m_media_downloader->isStarted()) {
		m_media_downloader->step(this);
		if (m_media_downloader->isDone()) {
			received_media();
			delete m_media_downloader;
			m_media_downloader = NULL;
		}
	}

	/*
		If the server didn't update the inventory in a while, revert
		the local inventory (so the player notices the lag problem
		and knows something is wrong).
	*/
	if(m_inventory_from_server)
	{
		float interval = 10.0;
		float count_before = floor(m_inventory_from_server_age / interval);

		m_inventory_from_server_age += dtime;

		float count_after = floor(m_inventory_from_server_age / interval);

		if(count_after != count_before)
		{
			// Do this every <interval> seconds after TOCLIENT_INVENTORY
			// Reset the locally changed inventory to the authoritative inventory
			Player *player = m_env.getLocalPlayer();
			player->inventory = *m_inventory_from_server;
			m_inventory_updated = true;
		}
	}

	/*
		Update positions of sounds attached to objects
	*/
	{
		for(std::map<int, u16>::iterator
				i = m_sounds_to_objects.begin();
				i != m_sounds_to_objects.end(); ++i)
		{
			int client_id = i->first;
			u16 object_id = i->second;
			ClientActiveObject *cao = m_env.getActiveObject(object_id);
			if(!cao)
				continue;
			v3f pos = cao->getPosition();
			m_sound->updateSoundPosition(client_id, pos);
		}
	}

	/*
		Handle removed remotely initiated sounds
	*/
	m_removed_sounds_check_timer += dtime;
	if(m_removed_sounds_check_timer >= 2.32) {
		m_removed_sounds_check_timer = 0;
		// Find removed sounds and clear references to them
		std::vector<s32> removed_server_ids;
		for(std::map<s32, int>::iterator
				i = m_sounds_server_to_client.begin();
				i != m_sounds_server_to_client.end();) {
			s32 server_id = i->first;
			int client_id = i->second;
			++i;
			if(!m_sound->soundExists(client_id)) {
				m_sounds_server_to_client.erase(server_id);
				m_sounds_client_to_server.erase(client_id);
				m_sounds_to_objects.erase(client_id);
				removed_server_ids.push_back(server_id);
			}
		}

		// Sync to server
		if(!removed_server_ids.empty()) {
			sendRemovedSounds(removed_server_ids);
		}
	}

	// Write server map
	if (m_localdb && m_localdb_save_interval.step(dtime,
			m_cache_save_interval)) {
		m_localdb->endSave();
		m_localdb->beginSave();
	}
}
コード例 #4
0
ファイル: client.cpp プロジェクト: EXio4/minetest
void Client::step(float dtime)
{
	// Limit a bit
	if(dtime > 2.0)
		dtime = 2.0;

	if(m_ignore_damage_timer > dtime)
		m_ignore_damage_timer -= dtime;
	else
		m_ignore_damage_timer = 0.0;

	m_animation_time += dtime;
	if(m_animation_time > 60.0)
		m_animation_time -= 60.0;

	m_time_of_day_update_timer += dtime;

	ReceiveAll();

	/*
		Packet counter
	*/
	{
		float &counter = m_packetcounter_timer;
		counter -= dtime;
		if(counter <= 0.0)
		{
			counter = 20.0;

			infostream << "Client packetcounter (" << m_packetcounter_timer
					<< "):"<<std::endl;
			m_packetcounter.print(infostream);
			m_packetcounter.clear();
		}
	}

	// UGLY hack to fix 2 second startup delay caused by non existent
	// server client startup synchronization in local server or singleplayer mode
	static bool initial_step = true;
	if (initial_step) {
		initial_step = false;
	}
	else if(m_state == LC_Created) {
		float &counter = m_connection_reinit_timer;
		counter -= dtime;
		if(counter <= 0.0) {
			counter = 2.0;

			LocalPlayer *myplayer = m_env.getLocalPlayer();
			FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");

			sendInit(myplayer->getName());
		}

		// Not connected, return
		return;
	}

	/*
		Do stuff if connected
	*/

	/*
		Run Map's timers and unload unused data
	*/
	const float map_timer_and_unload_dtime = 5.25;
	if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) {
		ScopeProfiler sp(g_profiler, "Client: map timer and unload");
		std::vector<v3s16> deleted_blocks;
		m_env.getMap().timerUpdate(map_timer_and_unload_dtime,
			g_settings->getFloat("client_unload_unused_data_timeout"),
			g_settings->getS32("client_mapblock_limit"),
			&deleted_blocks);

		/*
			Send info to server
			NOTE: This loop is intentionally iterated the way it is.
		*/

		std::vector<v3s16>::iterator i = deleted_blocks.begin();
		std::vector<v3s16> sendlist;
		for(;;) {
			if(sendlist.size() == 255 || i == deleted_blocks.end()) {
				if(sendlist.empty())
					break;
				/*
					[0] u16 command
					[2] u8 count
					[3] v3s16 pos_0
					[3+6] v3s16 pos_1
					...
				*/

				sendDeletedBlocks(sendlist);

				if(i == deleted_blocks.end())
					break;

				sendlist.clear();
			}

			sendlist.push_back(*i);
			++i;
		}
	}

	/*
		Send pending messages on out chat queue
	*/
	if (!m_out_chat_queue.empty() && canSendChatMessage()) {
		sendChatMessage(m_out_chat_queue.front());
		m_out_chat_queue.pop();
	}

	/*
		Handle environment
	*/
	// Control local player (0ms)
	LocalPlayer *player = m_env.getLocalPlayer();
	assert(player);
	player->applyControl(dtime, &m_env);

	// Step environment
	m_env.step(dtime);
	m_sound->step(dtime);

	/*
		Get events
	*/
	while (m_env.hasClientEnvEvents()) {
		ClientEnvEvent envEvent = m_env.getClientEnvEvent();

		if (envEvent.type == CEE_PLAYER_DAMAGE) {
			if (m_ignore_damage_timer <= 0) {
				u8 damage = envEvent.player_damage.amount;

				if (envEvent.player_damage.send_to_server)
					sendDamage(damage);

				// Add to ClientEvent queue
				ClientEvent *event = new ClientEvent();
				event->type = CE_PLAYER_DAMAGE;
				event->player_damage.amount = damage;
				m_client_event_queue.push(event);
			}
		}
	}

	/*
		Print some info
	*/
	float &counter = m_avg_rtt_timer;
	counter += dtime;
	if(counter >= 10) {
		counter = 0.0;
		// connectedAndInitialized() is true, peer exists.
		float avg_rtt = getRTT();
		infostream << "Client: avg_rtt=" << avg_rtt << std::endl;
	}

	/*
		Send player position to server
	*/
	{
		float &counter = m_playerpos_send_timer;
		counter += dtime;
		if((m_state == LC_Ready) && (counter >= m_recommended_send_interval))
		{
			counter = 0.0;
			sendPlayerPos();
		}
	}

	/*
		Replace updated meshes
	*/
	{
		int num_processed_meshes = 0;
		while (!m_mesh_update_thread.m_queue_out.empty())
		{
			num_processed_meshes++;

			MinimapMapblock *minimap_mapblock = NULL;
			bool do_mapper_update = true;

			MeshUpdateResult r = m_mesh_update_thread.m_queue_out.pop_frontNoEx();
			MapBlock *block = m_env.getMap().getBlockNoCreateNoEx(r.p);
			if (block) {
				// Delete the old mesh
				delete block->mesh;
				block->mesh = nullptr;

				if (r.mesh) {
					minimap_mapblock = r.mesh->moveMinimapMapblock();
					if (minimap_mapblock == NULL)
						do_mapper_update = false;

					bool is_empty = true;
					for (int l = 0; l < MAX_TILE_LAYERS; l++)
						if (r.mesh->getMesh(l)->getMeshBufferCount() != 0)
							is_empty = false;

					if (is_empty)
						delete r.mesh;
					else
						// Replace with the new mesh
						block->mesh = r.mesh;
				}
			} else {
				delete r.mesh;
			}

			if (m_minimap && do_mapper_update)
				m_minimap->addBlock(r.p, minimap_mapblock);

			if (r.ack_block_to_server) {
				/*
					Acknowledge block
					[0] u8 count
					[1] v3s16 pos_0
				*/
				sendGotBlocks(r.p);
			}
		}

		if (num_processed_meshes > 0)
			g_profiler->graphAdd("num_processed_meshes", num_processed_meshes);
	}

	/*
		Load fetched media
	*/
	if (m_media_downloader && m_media_downloader->isStarted()) {
		m_media_downloader->step(this);
		if (m_media_downloader->isDone()) {
			delete m_media_downloader;
			m_media_downloader = NULL;
		}
	}

	/*
		If the server didn't update the inventory in a while, revert
		the local inventory (so the player notices the lag problem
		and knows something is wrong).
	*/
	if(m_inventory_from_server)
	{
		float interval = 10.0;
		float count_before = floor(m_inventory_from_server_age / interval);

		m_inventory_from_server_age += dtime;

		float count_after = floor(m_inventory_from_server_age / interval);

		if(count_after != count_before)
		{
			// Do this every <interval> seconds after TOCLIENT_INVENTORY
			// Reset the locally changed inventory to the authoritative inventory
			LocalPlayer *player = m_env.getLocalPlayer();
			player->inventory = *m_inventory_from_server;
			m_inventory_updated = true;
		}
	}

	/*
		Update positions of sounds attached to objects
	*/
	{
		for (auto &m_sounds_to_object : m_sounds_to_objects) {
			int client_id = m_sounds_to_object.first;
			u16 object_id = m_sounds_to_object.second;
			ClientActiveObject *cao = m_env.getActiveObject(object_id);
			if (!cao)
				continue;
			m_sound->updateSoundPosition(client_id, cao->getPosition());
		}
	}

	/*
		Handle removed remotely initiated sounds
	*/
	m_removed_sounds_check_timer += dtime;
	if(m_removed_sounds_check_timer >= 2.32) {
		m_removed_sounds_check_timer = 0;
		// Find removed sounds and clear references to them
		std::vector<s32> removed_server_ids;
		for (std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.begin();
				i != m_sounds_server_to_client.end();) {
			s32 server_id = i->first;
			int client_id = i->second;
			++i;
			if(!m_sound->soundExists(client_id)) {
				m_sounds_server_to_client.erase(server_id);
				m_sounds_client_to_server.erase(client_id);
				m_sounds_to_objects.erase(client_id);
				removed_server_ids.push_back(server_id);
			}
		}

		// Sync to server
		if(!removed_server_ids.empty()) {
			sendRemovedSounds(removed_server_ids);
		}
	}

	m_mod_storage_save_timer -= dtime;
	if (m_mod_storage_save_timer <= 0.0f) {
		verbosestream << "Saving registered mod storages." << std::endl;
		m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval");
		for (std::unordered_map<std::string, ModMetadata *>::const_iterator
				it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) {
			if (it->second->isModified()) {
				it->second->save(getModStoragePath());
			}
		}
	}

	// Write server map
	if (m_localdb && m_localdb_save_interval.step(dtime,
			m_cache_save_interval)) {
		m_localdb->endSave();
		m_localdb->beginSave();
	}
}
コード例 #5
0
int main(int argc, char **argv)
{
	// parameters that are provided.
	char *srv = "127.0.0.1";
	int port = DEFAULT_PORT;

	// this data object will be passed to all the callback routines.  Initialise it.
	data_t data;
	data.handle = -1;
	data.msg_id = 0;
	data.latest_msg_id = 0;
	data.name = NULL;

	// get the command line options.
	int c;
	while ((c = getopt(argc, argv, "p:s:h")) != -1) {
		switch (c) {
			case 'p':
				port = atoi(optarg);
				assert(port > 0);
				break;
			case 's':
				srv = strdup(optarg);
				assert(srv != NULL);
				break;				
			case 'h':
				printf("usage:\n\nrisp_chat_stream2 [-s server] [-p port] [-h]\n");
				exit(1);
				break;
			default:
				fprintf(stderr, "Illegal argument \"%c\"\n", c);
				return 1;
		}
	}

	// set the signal trap, so we can break out of the loop when user presses Ctrl-C.
	signal(SIGINT, sig_handler);
	
	// get an initialised risp structure.
	RISP_PTR risp = risp_init();
	assert(risp);

	// add the callback routines for the commands we are going to receive.
	risp_add_command(risp, CMD_NOP,              &cmdNop);
	risp_add_command(risp, CMD_HELLO_ACK,        &cmdHelloAck);
	risp_add_command(risp, CMD_MSG_ID,           &cmdMsgID);
	risp_add_command(risp, CMD_LATEST_MSG_ID,    &cmdLatestMsgID);
	risp_add_command(risp, CMD_NAME,             &cmdName);
	risp_add_command(risp, CMD_MESSAGE,          &cmdMessage);

	risp_add_invalid(risp, &cmdInvalid);

	
	// connect to the remote socket. We will leave it in blocking mode.  When we do the recv, we 
	// will specify that the recv operation is non-blocking.
	assert(srv && port > 0);
	data.handle = sock_connect(srv, port);
	if (data.handle <= 0) {
		printf("Unable to connect to %s:%d\n", srv, port);
	}
	else {
		// now that we are connected, first we need to send the HELLO and NO_FOLLOW commands.  
		// These commands could have been lumped together in a single send, but for the purpose of 
		// demonstrating RISP, this code does each operationg specifically.
		if (sendInit(data.handle) != 0) {
			// couldn't send the command, close the handle, and exit.
			close(data.handle);
			data.handle = -1;
		}
		
		// setup the initial buffer.  Since we dont really know how much data we will receive from 
		// the server, we will grow the buffer as needed.
		int max = 0;
		char *buffer = NULL;
		int used = 0;
		int goodbye_sent = 0;	// if we have sent a GOODBYE, we dont want to 
		
		// we will loop until the socket is closed.  If the user presses Ctrl-C, we will send a 
		// GOODBYE command to the server, which will then close the socket.  If the user presses 
		// Ctrl-C more than once, we will not wait for the server, and will close the socket 
		// directly.  Every time the user presses Ctrl-C, it should break out of the sleep, so it 
		// should respond pretty quickly.
		while (data.handle >= 0) {
		
// 			printf(".");
			
			assert(used <= max);
			
			if (max-used < CHUNK_SIZE) { 
				max += CHUNK_SIZE;
				buffer = realloc(buffer, max);
				assert(buffer);
// 				fprintf(stderr, "Increased Max Buffer to %d\n", max);
			}
			
			// check for data on the socket.  We will do the receive in non-blocking mode, so if 
			// there is no data, it will return immediately. If we received no data, we will wait for 
			// 1 second before trying again.  If we have waited for 5 seconds, then we need to 
			// send a NOP to keep the connection alive.
			char *ptr = buffer + used;
			int avail = max - used;
// 			fprintf(stderr, "About to recv.  avail=%d\n", avail);
			int result = recv(data.handle, ptr, avail, MSG_DONTWAIT);
// 			printf("Recv: result=%d, used=%d, max=%d\n", result, used, max);
			if (result < 0) {
				assert(result == -1);
				if (errno == EWOULDBLOCK || errno == EAGAIN) {
					// there was no data to read from the socket.
					// we will now sleep for 1 second.  If the user pressed Ctrl-C, then the sleep 
					// function will exit immediately. Only do the sleep if Ctrl-C hasn't been hit.
					if (_sigtrap == 0) { sleep(1); }
				}
				else {
					fprintf(stderr, "Unexpected result received from socket. errno=%d '%s'\n", errno, strerror(errno));
				}
			}
			else if (result == 0) {
				// socket has closed.
				close(data.handle);
				data.handle = -1;
			}
			else {
				assert(result > 0);
				assert(result <= avail);
				assert(used >= 0);
				used += result;
				assert(used <= max);
				
				// if we have some data received, then we need to process it.
// 				fprintf(stderr, "Processing: %d\n", used);
				risp_length_t processed = risp_process(risp, &data, used, buffer);
// 				fprintf(stderr, "Processed: %ld\n", processed);
				assert(processed >= 0);
				assert(processed <= used);
				
				if (processed < used) { 
					// Our commands have probably been fragmented.
					
// 					fprintf(stderr, "Fragmented commands: processed=%ld, used=%d, max=%d\n", processed, used, max);
					fflush(stdout);
					
					if (processed > 0) {
						// we need to remove from the buffer the data that we have processed.  
						// This is a simple approach, but not the most efficient.
						assert(sizeof(*buffer) == 1);
						char *ptr = buffer+processed;
						size_t length = used-processed;
						assert((processed + length) == used);
						
// 						fprintf(stderr, "Moving data.  length=%ld\n", length);
						
						memmove(buffer, ptr, length);
						
						used -= processed;
						assert(used > 0);
						assert(used < max);
						
// 						fprintf(stderr, "After move. used=%d, max=%d\n", used, max);
					}
				} 
				else { used = 0; }
				
				assert(used >= 0 && used <= max);
			}
			
			
			if (data.handle >= 0) {
				if (_sigtrap == 1 && goodbye_sent == 0) {
					fprintf(stderr, "Closing...\n");
					
					// TODO: shouldn't just close the socket.  Should instead send GOODBYE command and wait for socket to close.
					if (sendGoodbye(data.handle) != 0) {
						close(data.handle);
						data.handle = -1;
					}
					
					goodbye_sent ++;
				}
				else if (_sigtrap > 1) {
					close(data.handle);
					data.handle = -1;
				}
			}
		}
	}

	// clean up the risp structure.
	risp_shutdown(risp);
	risp = NULL;
	
	return 0;
}
コード例 #6
0
ファイル: OscProxyEventHandler.cpp プロジェクト: mikewoz/osg
 bool OscProxyEventHandler::handle (const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa, osg::Object *, osg::NodeVisitor *)
{
    bool do_send(false);
    switch(ea.getEventType())
    {
        case osgGA::GUIEventAdapter::FRAME:
            if (_firstRun)
            {
                _firstRun = false;
                sendInit(ea);
                do_send = true;
            }
            break;
        case osgGA::GUIEventAdapter::RESIZE:
            sendInit(ea);
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::SCROLL:
            _oscStream << osc::BeginMessage("/osgga/mouse/scroll") << ea.getScrollingMotion() << ea.getScrollingDeltaX() << ea.getScrollingDeltaY() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PEN_PRESSURE:
            _oscStream
                << osc::BeginMessage("/osgga/pen/pressure")
                << ea.getPenPressure()
                << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::PEN_ORIENTATION:
            
             _oscStream
                << osc::BeginMessage("/osgga/pen/orientation")
                << ea.getPenRotation()
                << ea.getPenTiltX()
                << ea.getPenTiltY()
                << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::PEN_PROXIMITY_ENTER:
            _oscStream
                << osc::BeginMessage("/osgga/pen/proximity/enter")
                << ea.getTabletPointerType()
                << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PEN_PROXIMITY_LEAVE:
            _oscStream
                << osc::BeginMessage("/osgga/pen/proximity/leave")
                << ea.getTabletPointerType()
                << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PUSH:
            _oscStream << osc::BeginMessage("/osgga/mouse/press") << ea.getX() << ea.getY() << getButtonNum(ea)  << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::RELEASE:
            _oscStream << osc::BeginMessage("/osgga/mouse/release") << ea.getX() << ea.getY() << getButtonNum(ea)  << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::DOUBLECLICK:
            _oscStream << osc::BeginMessage("/osgga/mouse/doublepress") << ea.getX() << ea.getY() << getButtonNum(ea) << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::MOVE:
        case osgGA::GUIEventAdapter::DRAG:
            _oscStream << osc::BeginMessage("/osgga/mouse/motion") << ea.getX() << ea.getY() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::KEYDOWN:
            _oscStream << osc::BeginMessage("/osgga/key/press") << ea.getKey() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::KEYUP:
            _oscStream << osc::BeginMessage("/osgga/key/release") << ea.getKey() << osc::EndMessage;
            do_send = true;
            break;
        
        default:
            break;
        
    }
    if (do_send)
    {
        OSG_INFO << "OscDevice :: sending event per OSC " << std::endl;
        
        _transmitSocket.Send( _oscStream.Data(), _oscStream.Size() );
        _oscStream.Clear();
    }
    
    return false;
}
コード例 #7
0
ファイル: OscSendingDevice.cpp プロジェクト: BodyViz/osg
void OscSendingDevice::sendEvent(const osgGA::GUIEventAdapter &ea)
{
    bool do_send(false);
    switch(ea.getEventType())
    {
        case osgGA::GUIEventAdapter::RESIZE:
            sendInit(ea);
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::SCROLL:
            _oscStream << osc::BeginMessage("/osgga/mouse/scroll") << ea.getScrollingMotion() << ea.getScrollingDeltaX() << ea.getScrollingDeltaY() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PEN_PRESSURE:
            _oscStream
                << osc::BeginMessage("/osgga/pen/pressure")
                << ea.getPenPressure()
                << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::PEN_ORIENTATION:
            
             _oscStream
                << osc::BeginMessage("/osgga/pen/orientation")
                << ea.getPenRotation()
                << ea.getPenTiltX()
                << ea.getPenTiltY()
                << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::PEN_PROXIMITY_ENTER:
            _oscStream
                << osc::BeginMessage("/osgga/pen/proximity/enter")
                << ea.getTabletPointerType()
                << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PEN_PROXIMITY_LEAVE:
            _oscStream
                << osc::BeginMessage("/osgga/pen/proximity/leave")
                << ea.getTabletPointerType()
                << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::PUSH:
            _oscStream << osc::BeginMessage("/osgga/mouse/press") << ea.getX() << ea.getY() << getButtonNum(ea)  << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::RELEASE:
            _oscStream << osc::BeginMessage("/osgga/mouse/release") << ea.getX() << ea.getY() << getButtonNum(ea)  << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::DOUBLECLICK:
            _oscStream << osc::BeginMessage("/osgga/mouse/doublepress") << ea.getX() << ea.getY() << getButtonNum(ea) << osc::EndMessage;
            do_send = true;
            break;
            
        case osgGA::GUIEventAdapter::MOVE:
            if (_firstRun)
            {
                _firstRun = false;
                sendInit(ea);
                do_send = true;
                break;
            }
            // break missing by intent;
            
        case osgGA::GUIEventAdapter::DRAG:
            _oscStream << osc::BeginMessage("/osgga/mouse/motion") << ea.getX() << ea.getY() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::KEYDOWN:
            _oscStream << osc::BeginMessage("/osgga/key/press") << ea.getKey() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::KEYUP:
            _oscStream << osc::BeginMessage("/osgga/key/release") << ea.getKey() << osc::EndMessage;
            do_send = true;
            break;
        
        case osgGA::GUIEventAdapter::USER:
            if (ea.getUserDataContainer())
            {
                std::string key = ea.getUserDataContainer()->getName();
                if (key.empty()) key = ea.getName();
                if (key.empty()) key = "user_data";
                
                sendUserDataContainer(transliterateKey(key), ea.getUserDataContainer(), true);
                
                do_send = true;
            }
        
        default:
            break;
        
    }
    if (do_send)
    {
        OSG_INFO << "OscDevice :: sending event per OSC " << std::endl;
        
        _transmitSocket.Send( _oscStream.Data(), _oscStream.Size() );
        _oscStream.Clear();
    }
}
コード例 #8
0
ファイル: main.c プロジェクト: davidgraeff/oldstuff
int main(void)
{
    // Alles TriState
    DDRA = 0;
    DDRB = 0;
    DDRC = 0;
    DDRD = 0;
    PORTA = 0;
    PORTB = 0;
    PORTC = 0;
    PORTD = 0;

    // save power
    MCUCR |= _BV(JTD);
    PRR |= _BV(PRTWI) | _BV(PRSPI) | _BV(PRADC);
    //ADCSRA &= ~_BV(ADEN);
    //ACSR |=_BV(ACD);

    // Power Led
    DDRA|=_BV(7);
    PIN_SET(A,7);

    sei();

    // Init: Subsysteme
    uart_init(UART_BAUD_SELECT(BAUD,F_CPU));
    stella_init();
//     curtain_init();
    //sensors_init();

    // Init: Variablen
    enum stateEnum {
        StateCommands,
        StateCurtainValue,
        StateLedChannel,
        StateLedValue
    } laststate, state = StateCommands;

    uint8_t slowdown_counter = 0;
    uint8_t slowdown_counter2 = 0;
    uint8_t panic_counter = 0;
	uint8_t panic_counter_led = 0;
	uint8_t panic_counter_brightness = 0;
    uint8_t stella_channel = 0;
    enum stella_set_function stella_fading = STELLA_SET_IMMEDIATELY;

	uint8_t packetPosition = 0;
	unsigned char lastChar, haslastChar = 0;
    slowdown_counter = 0;
    slowdown_counter2 = 0;
    stella_setValue(STELLA_SET_IMMEDIATELY, 0, 0);
    stella_process();

	 wdt_enable(WDTO_250MS);
	#define PANIC_THRESHOLD 150
    // Hauptprogramm
    while (1) {
		wdt_reset();
        stella_process();
        curtain_process();
        //sensors_process();

        //panic counter
        if (++slowdown_counter == 0) {

            if (++slowdown_counter2==0) {
                if (panic_counter < PANIC_THRESHOLD)
                    ++panic_counter;
            }
            
			if (panic_counter == PANIC_THRESHOLD) {
				panic_counter = PANIC_THRESHOLD+1;
				panic_counter_led = 0;
				panic_counter_brightness = 0;
				packetPosition = 0;
				storeValues();
				PIN_SET(A,6);
			}
			if (panic_counter == PANIC_THRESHOLD+1) {
				if (panic_counter_brightness==255) {
					panic_counter=PANIC_THRESHOLD+2;
					continue;
				}
				stella_setValue(STELLA_SET_FADE, panic_counter_led, ++panic_counter_brightness);
			}
			if (panic_counter == PANIC_THRESHOLD+2) {
				if (panic_counter_brightness==0) {
					panic_counter=PANIC_THRESHOLD+1;
					if (++panic_counter_led >= STELLA_CHANNELS)
						panic_counter_led = 0;
					continue;
				}
				stella_setValue(STELLA_SET_FADE, panic_counter_led, --panic_counter_brightness);
			}
        }

		uint16_t r = uart_getc();
		uint8_t info = r >> 8;
		if (r == UART_NO_DATA)
			continue;
		else if (info!=0) {
			PIN_SET(A,6);
			PIN_SET(A,7);
			packetPosition = 0;
			continue;
		}
		
		const unsigned char temp = haslastChar ? lastChar : 0;
		haslastChar = 1;
		lastChar = r & 0xff;
		if (lastChar == 0xff && temp == 0xff) { // two proceeding 255-values start a valid packet
			packetPosition = 1;
			state = StateCommands;
			continue;
		}

		if (!packetPosition)
			continue;
        
		// reset panic counter
		if (panic_counter) {
			if (panic_counter>=110) {
				restoreValues();
				PIN_CLEAR(A,6);
			}
			panic_counter = 0;
		}
		
		laststate = state;
		switch (state) {
		case StateCommands:
			switch (lastChar) {
			case 0xef: // get values
				sendInit();
				sendStella();
				//sendSensor();
				sendMotor();
				break;
			case 0xdf: // prepare for a curtain value
				state = StateCurtainValue;
				break;
			case 0xcf: // prepare for a led channel and value (fade:immediately)
				state = StateLedChannel;
				stella_fading = STELLA_SET_IMMEDIATELY;
				break;
			case 0xbf: // prepare for a led channel and value (fade:fade)
				state = StateLedChannel;
				stella_fading = STELLA_SET_FADE;
				break;
			case 0xaf: // prepare for a led channel and value (fade:fade flashy)
				state = StateLedChannel;
				stella_fading = STELLA_SET_FLASHY;
				break;
			case 0x9f: // prepare for a led channel and value (fade:fade immediately+relative)
				state = StateLedChannel;
				stella_fading = STELLA_SET_IMMEDIATELY_RELATIVE;
				break;
			case 0x00: // reset panic counter and acknowdlegde
				sendAck();
				break;
			}
			break;
		case StateCurtainValue:
			state = StateCommands;
			curtain_setPosition(lastChar);
			break;
		case StateLedChannel:
			state = StateLedValue;
			stella_channel = lastChar;
			break;
		case StateLedValue:
			state = StateCommands;
			stella_setValue(stella_fading, stella_channel, lastChar);
			break;
		}
		// the state has not changed -> a full packet has been received -> prepare for the next one
		if (laststate==state) {
			packetPosition=0;
		}
    }
    return 0;
}
コード例 #9
0
ファイル: p2os_ptz.cpp プロジェクト: Aharobot/p2os
//
// Core Functions
//
int P2OSPtz::setup()
{
  int err = 0;
  int num_inits = 7;
  is_on_ = true;
  for (int i = 1; i < num_inits; i++) {
    switch(i)
    {
      // case 0:
      //   do
      //   {
      //     ROS_DEBUG("Waiting for camera to power off.");
      //     err = setPower(POWER_OFF);
      //   } while (error_code_ == CAM_ERROR_BUSY);
      //   break;
      case 1:
        do
        {
          ROS_DEBUG("Waiting for camera to power on.");
          err = setPower(POWER_ON);
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      case 2:
        do
        {
          ROS_DEBUG("Waiting for camera mode to set");
          err = setControlMode();
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      case 3:
        do
        {
          ROS_DEBUG("Waiting for camera to initialize");
          err = sendInit();
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      case 4:
        do
        {
          for(int i = 0; i < 3; i++)
          {
            ROS_DEBUG("Waiting for camera to set default tilt");
            err = setDefaultTiltRange();
          }
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      case 5:
        do
        {
          ROS_DEBUG("Waiting for camera to set initial pan and tilt");
          err = sendAbsPanTilt(0, 0);
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      case 6:
        do
        {
          ROS_DEBUG("Waiting for camera to set initial zoom");
          err = sendAbsZoom(0);
        } while (error_code_ == CAM_ERROR_BUSY);
        break;
      default:
        err = -7;
        break;
    }

    // Check for erros after each attempt
    if (err)
    {
      ROS_ERROR("Error initiliazing PTZ at stage %i", i);
      switch(error_code_)
      {
        case CAM_ERROR_BUSY:
          ROS_ERROR("Error: CAM_ERROR_BUSY");
          break;
        case CAM_ERROR_PARAM:
          ROS_ERROR("Error: CAM_ERROR_PARAM");
          break;
        case CAM_ERROR_MODE:
          ROS_ERROR("Error: CAM_ERROR_MODE");
          break;
        default:
          ROS_ERROR("Error: Unknown error response from camera.");
          break;
      }
      return(-1);
    }
    else
    {
      ROS_DEBUG("Passed stage %i of PTZ initialization.", i);
    }
  }
  ROS_DEBUG("Finished initialization of the PTZ.");
  return 0;
}