void doOnlineStoreFile(ClientThreadResource * res , ListenSocket clientSocket ,
		RuntimeErrorValidator * validator){

			int handleId = callKssOperationOpenFile(res->heapHandler, res->argument , OPENING_MODE_WRITE , validator);
			FileBlock * block = buildEmptyFileBlock(res->heapHandler);
	
			block->sector1.dataLength = receiveBytes(clientSocket , block->sector1.data , sizeof(block->sector1.data)); 			
			block->sector2.dataLength = receiveBytes(clientSocket , block->sector2.data , sizeof(block->sector2.data)); 
		
			while ( (block->sector1.dataLength + block->sector2.dataLength) > 0) {

				callKssOperationWrite(res->heapHandler , handleId , block , validator);

				if(hasError(validator)){
					break;
				}

				cleanBlock(block);				
				block->sector1.dataLength = receiveBytes(clientSocket , block->sector1.data , sizeof(block->sector1.data)); 			
				block->sector2.dataLength = receiveBytes(clientSocket , block->sector2.data , sizeof(block->sector2.data)); 
			}

			callKssOperationCloseFile(res->heapHandler , handleId , validator);
			
			if (!hasError(validator)) {
				res->resultMessage = buildResponseMessageType226(res->heapHandler);
			} else {
				res->resultMessage = buildResponseMessageType426(res->heapHandler);
			}
	}
	void doOfflineStoreFile(ClientThreadResource * res , ListenSocket clientSocket ,RuntimeErrorValidator * validator){
		int bytesWritten;
		int lastError = 0;
		char * receiveBuffer;

		HANDLE newFile = getWriteFileHandle(trim(res->argument , res->heapHandler));
		BOOL writeFlag;
		int received;
		char buffer[65536];
		ZeroMemory(buffer, 65536);
		received = receiveBytes(clientSocket , buffer , 65536);
		
		while ( received > 0) {
			writeFlag = WriteFile(newFile , buffer , received , &bytesWritten , NULL);
			if ( !writeFlag ){
				lastError = GetLastError();
				error("Error al escribir archivo");
				break;
			}		
			ZeroMemory(buffer, 65536);
			received = receiveBytes(clientSocket , buffer , 65536);
		}
		
		CloseHandle(newFile);
		if (lastError != ERROR_NO_MORE_FILES) {
			res->resultMessage = concat(res->heapHandler , 2 , 
				"226 transferencia realizada con exito" , CHARACTER_CRLF);
		} else {
			res->resultMessage = concat(res->heapHandler , 2 , 
				"426 accion no realizada, ocurrio un error" , CHARACTER_CRLF);
		}	
	}
Exemplo n.º 3
0
void baja_de_personaje(char id_pj,t_nivel* nivel,ITEM_NIVEL** listaItems){
    log_info(logger, "Ejecutando [baja_de_personaje]...");
	t_list* recursos_a_orquestador = list_create();
    log_info(logger, "[baja_de_personaje] Cargando recursos a orquestador...");
	cargarRecursosAOrquestador(recursos_a_orquestador,id_pj,nivel->personajes_deadlock);

	//int* socket = socket_create_sin_puerto();
	int* socket = socket_create(15000, logger);
	log_trace(logger, "Procesando [conectarse_a_orquestador]...");

	 if (socket_connect_with_retry(socket, nivel->ip, nivel->puerto, logger) < 0) {
		log_error(logger, "[baja_de_personaje] No pudo conectar");
		exit(EXIT_FAILURE);
	}
	log_trace(logger, "Saliendo [baja_de_personaje]...");


	int id_nivel = parsear_nivel(nivel->nombre);
	t_stream* stream=lista_liberados_serialize(recursos_a_orquestador,id_nivel);
	log_info(logger, "[baja_de_personaje] Sending bytes...");
	sendBytes(socket,stream->data,stream->size, logger);

	log_info(logger, "[baja_de_personaje] Borrando item para id_pj=[%c]...", id_pj);
	BorrarItem(&nivel->lista_items,id_pj);

	liberarPersonaje(nivel->personajes_deadlock,id_pj);
	log_info(logger, "[baja_de_personaje] recibiendo del orquestador posibles personajes desbloqueados...");
	char* data=receiveBytes(socket,sizeof(int)*2, logger);
	if(data!=NULL){
	    log_info(logger, "[baja_de_personaje] Deserializando data...");
		t_header* header=(t_header*)deserializar_header(data);
		switch (header->tipo){
			case NO_LIBERE:
			{
			    log_info(logger, "[baja_de_personaje] Agregando a disponibles...");
				agregarDisponibles(listaItems,recursos_a_orquestador);
				break;
			}
			case LIBERADOS:
			{
			    log_info(logger, "[baja_de_personaje] Liberados -> Recibiendo del orquestador Personajes Desbloqueados...");
				data = receiveBytes(socket,header->tamanio, logger);
				char* personajes = deserializar_liberados(data);

				actualizarPersonajesYActualizarDisponibles(personajes,nivel->personajes_deadlock,recursos_a_orquestador,listaItems);
				break;
			}
		}
	}

	log_info(logger, "[baja_de_personaje] cerrando socket=[%d]...", *socket);
	socket_close(socket, logger);
	log_info(logger, "Saliendo [baja_de_personaje]...");
}
Exemplo n.º 4
0
int CSocket::receiveMessage(CBuffer& pDestination)
{
    int retVal = -1;

    if(udp)
        return receiveBytes(pDestination);

     if(((retVal = receiveBytes(pDestination, 2))) == 2)
        return receiveBytes(pDestination, pDestination.readuShort());
    return retVal;
}
Exemplo n.º 5
0
void DialogSocket::refill()
{
	if (_pNext == _pEnd)
	{
		int n = receiveBytes(_pBuffer, RECEIVE_BUFFER_SIZE);
		_pNext = _pBuffer;
		_pEnd  = _pBuffer + n;
	}
}
Exemplo n.º 6
0
static BOOL
initSession( SOCKET sock )
{
    BYTE	buffer[ 1024 ];
    DWORD	length;
    BOOL	aes256 = FALSE;

    aes256 = (aesMaxKey >= 256);
    buffer[ 0 ] = aes256 ? 1 : 0;

    if ( ! (length = encodePK( sizeof( buffer ) - 1, &buffer[1] )) )
	return( FALSE );

    if ( verbose )
    {
	printf( "Session Initiation: \n" );
	hexDump( length + 1, buffer );
    }

    if ( ! sendBytes( sock, buffer, length + 1 ) )
	return( FALSE );

    if ( ! receiveBytes( sock, buffer, sizeof( buffer ), &length ) )
	return( FALSE );

    if ( ! length )
    {
	fprintf( stderr, "No session response from server\n" );
	return( FALSE );
    }

    if ( verbose )
    {
	printf( "Session Response: \n" );
	hexDump( length, buffer );
    }

    switch( buffer[ 0 ] )
    {
    case 0 :  aes256 = FALSE;	break;
    case 1 :
	if ( aes256 )  break;

	/*
	** Fall through for unsupported AES key length.
	*/

    default:
	fprintf( stderr, "Invalid AES key length returned: %d\n", buffer[0] );
	return( FALSE );
    }

    if ( ! decodeSK( aes256, length - 1, &buffer[1] ) )
	return( FALSE );

    return( TRUE );
}
Exemplo n.º 7
0
void StompSocket::refill()
{
	if (_pNext == _pEnd)
	{
		int n = receiveBytes(_pBuffer, RECEIVE_BUFFER_SIZE);
		_pNext = _pBuffer;
		_pEnd  = _pBuffer + n;
        //~ std::cout << "refill() read "<< n <<" bytes:'" << std::string(_pBuffer) << "'" << std::endl;
	}
}
	MpsHandshake * receiveMpsHandshake(ListenSocket l , RuntimeErrorValidator * v){
		MpsHeader header;
		int receivedBytes = receiveBytes(l , &header , sizeof(MpsHeader) );

		if(receivedBytes <= 0){
			setError(v, "No se han recivido bytes en el handshake");
		}

		return buildMpsHandhake( header.descriptorId , header.payloadDescriptor );
	}
Exemplo n.º 9
0
Serial::Serial(QString serial_port) : QextSerialPort("", QextSerialPort::EventDriven) {

    this->setPortName(serial_port);
    this->setBaudRate(BAUD115200);
    this->setFlowControl(FLOW_OFF);
    this->setParity(PAR_NONE);
    this->setDataBits(DATA_8);
    this->setStopBits(STOP_1);

/*    this->open(QIODevice::ReadWrite);
    if(port->isOpen()) {
        qWarning("Puerto serial %s abierto", serial_port.toAscii().data());
    } else {
        qWarning("No se pudo abrir puerto serial %s", serial_port.toAscii().data());
    }*/

    connect(this, SIGNAL(readyRead()), this, SLOT(receiveBytes()));
}
Exemplo n.º 10
0
int CSocket::receiveText(CString& pDestination, char* pSep)
{
    char buffer[65536];
    int size;

    if(!udp)
    {
        size = recv(sockId, buffer, sizeof(buffer), MSG_PEEK);
        if(size <= 0)
            return size;
        buffer[size] = 0;
        int length = (int)(strstr(buffer, pSep) - buffer);

        if(length >= 0)
            return receiveBytes(pDestination, length + (int)strlen(pSep));
        return -1;
    }
    return -1;
}
/*
 * Read packet header and insert into packet structure.
 * Allocate space for the data and fill it in.
 */
jint
shmemBase_receivePacket(SharedMemoryConnection *connection, jdwpPacket *packet)
{
    jint data_length;
    jint error;

    clearLastError();

    CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.id, sizeof(jint)));
    CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.flags, sizeof(jbyte)));

    if (packet->type.cmd.flags & JDWPTRANSPORT_FLAGS_REPLY) {
        CHECK_ERROR(receiveBytes(connection, &packet->type.reply.errorCode, sizeof(jshort)));
    } else {
        CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.cmdSet, sizeof(jbyte)));
        CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.cmd, sizeof(jbyte)));
    }

    CHECK_ERROR(receiveBytes(connection, &data_length, sizeof(jint)));

    if (data_length < 0) {
        return SYS_ERR;
    } else if (data_length == 0) {
        packet->type.cmd.len = 11;
        packet->type.cmd.data = NULL;
    } else {
        packet->type.cmd.len = data_length + 11;
        packet->type.cmd.data = (*callback->alloc)(data_length);
        if (packet->type.cmd.data == NULL) {
            return SYS_ERR;
        }

        error = receiveBytes(connection, packet->type.cmd.data, data_length);
        if (error != SYS_OK) {
            (*callback->free)(packet->type.cmd.data);
            return error;
        }
    }

    return SYS_OK;
}
Exemplo n.º 12
0
/*
 * Read packet header and insert into packet structure.
 * Allocate space for the data and fill it in.
 */
jint 
shmemBase_receivePacket(SharedMemoryConnection *connection, struct Packet *packet)
{
    jint length;
    jint error;

    CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.id, sizeof(jint)));
    CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.flags, sizeof(jbyte)));

    if (packet->type.cmd.flags & FLAGS_Reply) {
        CHECK_ERROR(receiveBytes(connection, &packet->type.reply.errorCode, sizeof(jshort)));
    } else {
        CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.cmdSet, sizeof(jbyte)));
        CHECK_ERROR(receiveBytes(connection, &packet->type.cmd.cmd, sizeof(jbyte)));
    }

    CHECK_ERROR(receiveBytes(connection, &length, sizeof(jint)));

    if (length < 0) {
        return SYS_ERR;
    } else if (length == 0) {
        packet->type.cmd.data.length = 0;
        packet->type.cmd.data.data = NULL;
        packet->type.cmd.data.next = NULL;
    } else {
        packet->type.cmd.data.length = length;
        packet->type.cmd.data.next = NULL;
        packet->type.cmd.data.data= (*callback->alloc)(length);
        if (packet->type.cmd.data.data == NULL) {
            return SYS_ERR;
        }

        error = receiveBytes(connection, packet->type.cmd.data.data, length);
        if (error != SYS_OK) {
            (*callback->free)(packet->type.cmd.data.data);
            return error;
        }
    }

    return SYS_OK;
}
Exemplo n.º 13
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow), sentBytes(NULL)
{
    ui->setupUi(this);

    //---- Menu Configuration ----
    machineGroup    = new QActionGroup(this);
    machineGroup->addAction(ui->actionScorpio);
    machineGroup->addAction(ui->actionQuadcopter);
    ui->actionScorpio->setChecked(true);
    viewGroup       =   new QActionGroup(this);
    viewGroup->addAction(ui->actionTracking);
    viewGroup->addAction(ui->actionTracking);
    viewGroup->addAction(ui->actionManual_Control);
    viewGroup->addAction(ui->actionCommand_Center);
    ui->actionCommand_Center->setChecked(true);
    //---- ----

    //---- Statusbar ----
    serialConnected=false;
    gpsFix=false;
    joystickConnected=false;
    gpsFooterStat       = new QLabel(this);
    connectedFooterStat = new QLabel(this);
    joystickFooterStat  = new QLabel(this);
    aliveFooterState    = new QLabel(this);
    connectedGPSFooterStat = new QLabel(this);
    ui->statusBar->addPermanentWidget(gpsFooterStat);
    ui->statusBar->addPermanentWidget(connectedFooterStat);
    ui->statusBar->addPermanentWidget(aliveFooterState);
    ui->statusBar->addPermanentWidget(joystickFooterStat);
    ui->statusBar->addPermanentWidget(connectedGPSFooterStat);
    //----  ----

    //---- Compass Graphics View ----
    compassPixmap = new QPixmap(":/img/CompassSquare150.png");
    ui->compassViewLabel->setPixmap(rotatePixmap(compassPixmap,0));
    //----  ----
    //---- Speedometer Graphics View ----
    ui->speedometerViewLabel->setPixmap(updateSpeedIndicator(0));
    //----  ----
    //---- Steer Graphics View ----
    ui->steerGraphicsView->setStyleSheet("background: transparent");
    steerGraphicsScene = new QGraphicsScene(this);
    QBrush  brush(QColor::fromRgb(59,174,227));
    steerRailIndicator = steerGraphicsScene->addRect(0,22.5,148,15,Qt::NoPen,brush);
    brush.setColor(Qt::red);
    QPen    pen(Qt::black);
    pen.setWidth(2);
    steerIndicator = steerGraphicsScene->addRect(67.5,5,15,50,Qt::NoPen,brush);
    updateSteerIndicator(-100);
    ui->steerGraphicsView->setScene(steerGraphicsScene);
    //----  ----

    //---- Tracker View ----
    ui->trackerGraphicsView->
            setBackgroundBrush(QBrush(QColor::fromRgb(237,200,90),Qt::Dense4Pattern));
    trackerScene = new QGraphicsScene(this);
    ui->trackerGraphicsView->setScene(trackerScene);
    QPolygonF NorthArrow;
    NorthArrow.append(QPointF(-5.,0)); NorthArrow.append(QPointF(0.,-20)); NorthArrow.append(QPointF(5.,0));
    NorthArrow.append(QPointF(0.,-5.)); NorthArrow.append(QPointF(-5.,0));
    brush.setColor(Qt::black);
    northArrowGraphicsItem = trackerScene->addPolygon(NorthArrow,Qt::NoPen,brush);
    northArrowGraphicsItem->setPos(800,10);
    northArrowGraphicsItem->setFlag(QGraphicsItem::ItemIgnoresTransformations);
    //Scorpio Graphics Item
    scorpio2DGraphicsItem = new GraphicsItemScorpio;
    trackerScene->addItem(scorpio2DGraphicsItem);
    scorpio2DGraphicsItem->setPos(500,150);
    wgs2utm(BASE_LATITUDE, BASE_LONGITUDE,&baseEasting,&baseNorthing, &baseUTMZone);
    lastPoKnown=false;
    //----  ----
    brush.setColor(QColor(255, 0, 0, 180));
    targetMarker    =   trackerScene->addEllipse(400,100,10,10,pen,brush);
    brush.setColor(QColor(255, 255, 0, 180));
    baseMarker      =   trackerScene->addRect(0,0,10,10,pen,brush);
    //----  ----
    connect(&timerTracker,SIGNAL(timeout()),this,SLOT(updateTrackerGraphics()));
    //TODO: another sig-slot for updating scene to zoom to fit
    timerTracker.start(100);
    //---- ---- ---- ----

    //---- Joystick Initialization ----
    myJoystick = new RR_SDLJoystick;
    myJoystickData = new RR_SDLJoystickData_t;
    QString *joystickInitError;

    if(!myJoystick->initJoystick(myJoystickData, joystickInitError)){
    ui->plainTextEdit->insertPlainText("Error Connecting Joystick");
    //TODO: Fix so that the insertPlainText takes the error code from Joystick Object.
    }
    else{
       ui->plainTextEdit->insertPlainText("Joystick Connected!");
       joystickConnected=true;
       connect(&timerJoystick,SIGNAL(timeout()),myJoystick ,SLOT(pollJoystick()));
       timerJoystick.start(150);
    }
    connect(myJoystick,SIGNAL(gotJoystick()),this,SLOT(updateGaugeIndicators()));
    connect(myJoystick,SIGNAL(gotJoystick()),this,SLOT(updateJoystickTelemetry()));
    //---- ----

    //---- Serial ----
    serialPort = new RR_QtSerial(57600,"COM26");

    connect(&timerSerial,SIGNAL(timeout()), serialPort,SLOT(receiveBytes()));
    connect(ui->actionConnect,SIGNAL(triggered(bool)),serialPort,SLOT(switchSerial(bool)));
    connect(serialPort,SIGNAL(gotConnected(bool)),this,SLOT(updateSerialStatusBar(bool)));
    connect(serialPort,SIGNAL(gotConnected(bool)),ui->actionConnect,SLOT(setChecked(bool)));
    timerSerial.start(150);
    //----- GPS ------
    serialGPSPort = new RR_QtSerial(57600,"COM19");
    connect(&timerGPSSerial, SIGNAL(timeout()),serialGPSPort, SLOT(receiveBytes()));
    connect(ui->actionConnect_GPS, SIGNAL(triggered(bool)), serialGPSPort, SLOT(switchSerial(bool)));
    connect(serialGPSPort,SIGNAL(gotConnected(bool)),this,SLOT(updateGPSSerialStatusBar(bool)));
    connect(serialGPSPort,SIGNAL(gotConnected(bool)),ui->actionConnect_GPS,SLOT(setChecked(bool)));
    timerGPSSerial.start(150);

    //-------
    //---- GPS Data Serialization ----
    receivedGPSData   = new RR_QtTelemetryReceivedData_t;
    sentGPSData       = new RR_QtTelemetrySentData_t;
    gps               = new RR_QtTelemetry(receivedGPSData,sentGPSData);
    receivedGPSData->fix=false;
    connect(serialGPSPort,SIGNAL(gotBytes(QByteArray*)),gps,SLOT(decodeBytes(QByteArray*)));
    connect(gps,SIGNAL(gotDecodedMessage()),this,SLOT(updateGPSData()));
    //----  ----
    //---- Telemetry ----
    receivedTelemetryData   = new RR_QtTelemetryReceivedData_t;
    sentTelemetryData       = new RR_QtTelemetrySentData_t;
    telemetry               = new RR_QtTelemetry(receivedTelemetryData,sentTelemetryData);
    receivedTelemetryData->fix=false;
    connect(this,SIGNAL(gotJoystickMessage()),telemetry,SLOT(sendMessage()));
    connect(telemetry,SIGNAL(gotEncodedBytes(QByteArray*)),serialPort,SLOT(sendBytes(QByteArray*)));
    connect(serialPort,SIGNAL(gotBytes(QByteArray*)),telemetry,SLOT(decodeBytes(QByteArray*)));
    connect(telemetry,SIGNAL(gotDecodedMessage()),this,SLOT(updateTelemetryGraphics()));
    //----  ----
    //---- Text Display ----
    connect(&timerSerialPrint,SIGNAL(timeout()),this, SLOT(printStuff()));
    timerSerialPrint.start(ui->printfreSlider->value());
    connect(ui->printfreSlider, SIGNAL(sliderMoved(int)),&timerSerialPrint,SLOT(start(int)));
    connect(ui->clearPushButton,SIGNAL(clicked()),ui->plainTextEdit,SLOT(clear()));
    connect(ui->printfreSlider,SIGNAL(sliderMoved(int)),this,SLOT(setPrintFrequencyText()));
    setPrintFrequencyText();
    //----  ----
    //---- Test and Debug ----
    connect(&timerTestDebug,SIGNAL(timeout()),this,SLOT(testdebug()));

    timerTestDebug.start(1000);
    //----  ----

    connect(&timerStatusBarUpdate, SIGNAL(timeout()), this, SLOT(updateGPSStatbar()));
    timerStatusBarUpdate.start(500);

    //Pulse Check
    connect(&timerPulseCheck,SIGNAL(timeout()), this, SLOT(checkPulse()));
    pulseSamplingTime = 5000;
    timerPulseCheck.start(pulseSamplingTime);
}
Exemplo n.º 14
0
void* algoritmoDeadLock(void* nivelVoid){
	char* data;
	t_nivel* nivel = (t_nivel*) nivelVoid;

	while(1){

		usleep(nivel->deadlock);
		pthread_mutex_lock(&mutex);

		log_info(logger,"se ha iniciado la deteccion de deadlock");

		disponibleAux = malloc(sizeof(t_recursos_cantidad)*cantidad_key);
		ITEM_NIVEL* items_aux = nivel->lista_items;
		int i = 0;
		while(i < cantidad_key){
			if(items_aux->item_type == 1){
				disponibleAux[i].id_recurso = items_aux->id;
				disponibleAux[i].cantidad = items_aux->quantity;
				i++;
			}
			items_aux = items_aux->next;
		}

		char* interbloqueados;
		interbloqueados = malloc(sizeof(char));

		if(checkAndDoDeadLock(nivel->personajes_deadlock,&interbloqueados)){

			//loguear personajes en deadlock
			for(i = 0; i < strlen(interbloqueados) ; i++){
				log_info(logger,"esta en deadlock:%c",interbloqueados[i]);
			}

			if(nivel->recovery){
				log_info(logger,"el recovery se encuentra activado");
				t_stream* stream = serializar_interbloqueados(interbloqueados);
				//todo ver esto del puerto
				int *socket_nivel = socket_create_sin_puerto(logger);
				conectarse_a_orquestador(socket_nivel,nivel);
				sendBytes(socket_nivel,stream->data,stream->size, logger);
				log_info(logger,"le envie al orquestador los personajes interbloqueados");
				data = receiveBytes(socket_nivel,sizeof(char), logger);

				if(data!=NULL){
					log_info(logger,"recibi del orquestador el personaje asesinado [%c]", data[0]);
					baja_de_personaje(data[0],nivel,&(nivel->lista_items));
				}

				log_info(logger,"[algoritmoDeadLock] llamando stream_destroy...");
				stream_destroy(stream);
				
				log_info(logger,"[algoritmoDeadLock] cerrando socket de nivel...");
				socket_close(socket_nivel, logger);

			}
		}
		else{
			log_info(logger,"no hay personajes en deadlock");
		}

		resetPersonajesToDefault(nivel->personajes_deadlock);

		free(disponibleAux);
		free(interbloqueados);

		pthread_mutex_unlock(&mutex);

	}
	return NULL;

}
Exemplo n.º 15
0
bool PBBP::readEeprom(uint8_t slave_addr, uint8_t eeprom_addr, uint8_t *buf, uint8_t len) {
  return sendCommand(slave_addr, CMD_READ_EEPROM) &&
         sendByte(eeprom_addr) &&
         receiveBytes(buf, len);
}
Exemplo n.º 16
0
int main(int argc, char **argv) {
	create_log();
	char* path;
	if (argc == 2) {
		path = argv[1];
	}

	bool termino = false;
	bool finaliza_nivel = false;
	t_personaje* personaje = configuracion_inicializar(path);

	signal(SIGTERM, handler);
	signal(SIGUSR1, handler);
	signal(SIGINT, handler);
	t_log* logger = recibir_logger();
	personaje->nivel_actual = personaje->planDeNiveles;

	// pj sin plan de niveles-->pasa directo koopa
	t_info_nivel* info_nivel=conectarme_y_pedir_a_orquestador(personaje->nivel_actual);
	personaje_conecta(info_nivel);
	personaje->nodo_recurso_actual=personaje->nivel_actual ->objetivos->head;
	char envioAPlanificador[2];


	while (termino == false) {
	//	recibir turno del planificador
		char* data = receiveBytes(personaje->sk_planificador, sizeof(char), logger);
		if(data != NULL)
			//log_debug(logger, "{%c} [Main] recibi sizeof(char) del planificador...",personaje->id);

		if((data != NULL) && (data[0] == PERSONAJE_MOVETE)){
			log_info(logger, "{%c} [Main] Recibi turno del Planificador del %s...",personaje->id,personaje->nivel_actual->nivel);
			if ((personaje->nivel_actual != NULL)) {
				//calculo movimiento y nivel me mueve
				hacer_movimiento(personaje->sk_nivel, &personaje->nodo_recurso_actual);

				if (llega_a_destino(personaje->actual, personaje->destino)) {
					log_info(logger, "{%c} [Main] Llegue a destino...",personaje->id);
					// le solicita a nivel el recurso y devuelve si me lo otorgo o no, ene sta parte el pj se bloquea-->esta bien!
					char* respuesta_a_solicitud = solicitar_recurso_a_nivel();

					switch (respuesta_a_solicitud[0]) {

						case RECURSO_OTORGADO: {
							//avanzo al proximo recurso o nivel
							char* recurso = (char*) (personaje->nodo_recurso_actual->data);
							log_info(logger, "{%c} [Main] Recibi el recurso: %c ...",personaje->id,*recurso);
							finaliza_nivel = false;
							termino = avanzar_proximo_objetivo(&finaliza_nivel);
							if(!finaliza_nivel){
								//notificar al planificador PERSONAJE_MOVIO
								envioAPlanificador[0] = PERSONAJE_MOVIO;
								log_info(logger, "{%c} [Main] Sending PERSONAJE_MOVIO al Planificador...",personaje->id);
								sendBytes(personaje->sk_planificador,&envioAPlanificador,sizeof(char)*2, logger);
								log_info(logger, "{%c} [Main] Send PERSONAJE_MOVIO al Planificador del %s...",personaje->id,personaje->nivel_actual->nivel);
							}
							break;
						}
						case NO_HAY_RECURSOS: {
							////notificar al planificador PERSONAJE_BLOQUEADO y ID de recurso
							personaje->bloqueado = 1;
							envioAPlanificador[0] = PERSONAJE_BLOQ;
							char* id_rec = (char*) (personaje->nodo_recurso_actual->data);
							envioAPlanificador[1] = *id_rec;
							log_info(logger, "{%c} [Main] No hay recurso: %c, ME ESTOY BLOQUEANDO...",personaje->id,envioAPlanificador[1]);
							log_info(logger, "{%c} [Main] Sending PERSONAJE_BLOQ al Planificador...",personaje->id);
							sendBytes(personaje->sk_planificador,&envioAPlanificador,sizeof(char)*2, logger);
							log_info(logger, "{%c} [Main] Send realizado con PERSONAJE_BLOQ al Planificador...",personaje->id);
							//tengo que hacer un recibe aca asi me bloqueo hasta no aver conseguido el recurso

//							//pollcito
//							struct pollfd pollcito;
//							  pollcito.fd=*personaje->sk_planificador;
//							  pollcito.events=POLLIN;
//							  pollcito.revents=0;
//                                bool boolean=false;
//							while (boolean==false) {
//                             poll(&pollcito, 2,50);//timeout 50
//                             if (pollcito.revents == POLLIN) {
//                                  boolean=true;
							char* data = receiveBytes(personaje->sk_planificador, sizeof(char), logger);
							if(data != NULL){
								switch(data[0]){
									case PERSONAJE_DESBLOQUEATE:{
										log_info(logger, "{%c} [Main] Recibi PERSONAJE_DESBLOQUEATE del Planificador...",personaje->id);
										personaje->bloqueado = 0;
										finaliza_nivel = false;
										termino = avanzar_proximo_objetivo(&finaliza_nivel);
										if(!finaliza_nivel) {
											char envioAPlataforma[2];
											envioAPlataforma[0] = IM_READY;
											envioAPlataforma[1] = personaje->id;
											log_info(logger,"{%c}[Main]: Sending IM_READY ...",personaje->id);
											sendBytes(personaje->sk_planificador,envioAPlataforma,sizeof(char)*2, logger);
											log_info(logger,"{%c}[Main]: Send realizado IM_READY ...",personaje->id);
										}
										break;
									}
									case TE_MATE:{
										log_info(logger,"{%c} [Main] Recibi TE_MATE, me mataron por interbloqueo",personaje->id);
										personaje->bloqueado = 0;
										personaje_morir();
										t_info_nivel* info_nivel = conectarme_y_pedir_a_orquestador(personaje->nivel_actual);
										//usleep(RECONEXION_LUEGO_DE_MUERTE);
										personaje_conecta(info_nivel);
										break;
									}
								}
//							}
//								}
							}
						break;
						}
					}

				}
				else{//No llegue a destino, entonces no solicite nada.
					envioAPlanificador[0] = PERSONAJE_MOVIO;
					sendBytes(personaje->sk_planificador,&envioAPlanificador,sizeof(char)*2, logger);
					log_info(logger, "{%c} [Main] Send PERSONAJE_MOVIO al Planificador del %s...",personaje->id,personaje->nivel_actual->nivel);
				}
			}
		}
		if(personaje->haceSigterm == 1){
			log_debug(logger,"[MAIN] Valor de haceSigterm = %d",personaje->haceSigterm);
			personaje->haceSigterm = funcionDelSigterm();
			log_debug(logger,"[MAIN] Valor de haceSigterm = %d",personaje->haceSigterm);
		}

	}

	destruir_personaje(personaje);
	destruir_log();
	return EXIT_SUCCESS;
}
Exemplo n.º 17
0
static BOOL
clientRequest( SOCKET sock, char *host, u_short port )
{
    BYTE	buffer[ 1024 ];
    BYTE	*ptr, *end;
    DWORD	length;
    BOOL	echo = FALSE;

    sprintf_s( buffer, sizeof( buffer ), REQUEST_TEMPLATE, host, port );
    length = strlen( buffer );

    if ( ! (length = encode( length, buffer, sizeof( buffer ) )) )
	return( FALSE );

    if ( verbose )
    {
	printf( "Client Request: \n" );
	hexDump( length, buffer );
    }

    if ( ! sendBytes( sock, buffer, length ) )
	return( FALSE );

    do
    {
	if ( ! receiveBytes( sock, buffer, sizeof( buffer ), &length ) )
	    return( FALSE );

	if ( ! length )
	{
	    fprintf( stderr, "No response from server\n" );
	    break;
	}

	if ( verbose )
	{
	    printf( "Server Response: \n" );
	    hexDump( length, buffer );
	}

	if ( ! (length = decode( length, buffer, sizeof( buffer ) )) )
	    return( FALSE );

	ptr = buffer;
	end = ptr + length;
	*end = 0;

	while( ptr < end )
	{
	    BYTE *eol, save;

	    for( eol = ptr; *eol  &&  *eol != '\n'; eol++ )  /* DO NOTHING */;
	    eol++;
	    save = *eol;
	    *eol = 0;

	    /*
	    ** Display response between 'BEGIN' and 'END'
	    */
	    if ( ! echo )
	    {
		/* Echo starts with 'BEGIN' */
		if ( ! strcmp( ptr, "BEGIN\r\n" )  ||  ! strcmp( ptr, "BEGIN\n" ) )
		    echo = TRUE;
	    }
	    else
	    {
		/* Echo finishes with 'END' */
		if ( ! strcmp( ptr, "END\r\n" )  ||  ! strcmp( ptr, "END\n" ) )
		    break;

		printf( "%s", ptr );
	    }

	    *eol = save;
	    ptr = eol;
        }
    } while( FALSE );

    return( TRUE );
}