static int doRunInstance( struct nc_state_t *nc, ncMetadata *meta, char *instanceId, char *reservationId, virtualMachine *params, char *imageId, char *imageURL, char *kernelId, char *kernelURL, char *ramdiskId, char *ramdiskURL, char *keyName, // char *privMac, char *privIp, int vlan, netConfig *netparams, char *userData, char *launchIndex, char **groupNames, int groupNamesSize, ncInstance **outInst) { ncInstance * instance = NULL; * outInst = NULL; pid_t pid; netConfig ncnet; int error; memcpy(&ncnet, netparams, sizeof(netConfig)); /* check as much as possible before forking off and returning */ sem_p (inst_sem); instance = find_instance (&global_instances, instanceId); sem_v (inst_sem); if (instance) { logprintfl (EUCAFATAL, "Error: instance %s already running\n", instanceId); return 1; /* TODO: return meaningful error codes? */ } if (!(instance = allocate_instance (instanceId, reservationId, params, imageId, imageURL, kernelId, kernelURL, ramdiskId, ramdiskURL, instance_state_names[PENDING], PENDING, meta->userId, &ncnet, keyName, userData, launchIndex, groupNames, groupNamesSize))) { logprintfl (EUCAFATAL, "Error: could not allocate instance struct\n"); return 2; } change_state(instance, STAGING); sem_p (inst_sem); error = add_instance (&global_instances, instance); sem_v (inst_sem); if ( error ) { free_instance (&instance); logprintfl (EUCAFATAL, "Error: could not save instance struct\n"); return error; } instance->launchTime = time (NULL); /* instance->params.mem = params->mem; instance->params.cores = params->cores; instance->params.disk = params->disk; strcpy (instance->ncnet.privateIp, "0.0.0.0"); strcpy (instance->ncnet.publicIp, "0.0.0.0"); */ /* do the potentially long tasks in a thread */ pthread_attr_t* attr = (pthread_attr_t*) malloc(sizeof(pthread_attr_t)); if (!attr) { free_instance (&instance); logprintfl (EUCAFATAL, "Warning: out of memory\n"); return 1; } pthread_attr_init(attr); pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED); if ( pthread_create (&(instance->tcb), attr, startup_thread, (void *)instance) ) { pthread_attr_destroy(attr); logprintfl (EUCAFATAL, "failed to spawn a VM startup thread\n"); sem_p (inst_sem); remove_instance (&global_instances, instance); sem_v (inst_sem); free_instance (&instance); if (attr) free(attr); return 1; } pthread_attr_destroy(attr); if (attr) free(attr); * outInst = instance; return 0; }
/* * Parse succesive blocks of XML data, generating events for the * handlers/callbacks as we go. State is maintained in the * simple_xml_parser object. * If the top level XML document ends before the last character, * the "read" parameter indicates how much input was consumed. */ hcerr_t xml_parse(xml_parser *formal_parser, char s[], hc_long_t size, hc_long_t *read){ simple_xml_parser *parser = (simple_xml_parser *) formal_parser; int i = 0; if (DEBUG == TRUE){ print_state(parser->state, parser->depth); printf ("in parser with " LL_FORMAT " %s\n", size, s); fflush(stdout); } while (i < size){ switch(parser->state){ case OUTSIDE_ELEMENT: if (is_white_space(s[i])){ /*skip_white_space */ break; } if (s[i] == '<'){ parser->start_tag = TRUE; change_state(&parser->state, EXPECTING_OPEN_OR_CLOSE_TAG, parser->depth); } else { HC_ERR_LOG(("Expected '<', read %c at %d %s\n", s[i], i, s)); return HCERR_XML_EXPECTED_LT; } break; case DOCUMENT_ELEMENT: /* discard document element */ if (s[i] != '>'){ if (DEBUG == TRUE) printf("discarding %c", s[i]); break; } else{ parser->state = OUTSIDE_ELEMENT; break; } case EXPECTING_OPEN_OR_CLOSE_TAG: if (is_white_space(s[i])){ /*skip_white_space */ break; } if (s[i] == '/'){ if (DEBUG) printf("parser->start_tag = FALSE\n"); parser->start_tag = FALSE; break; } case EXPECTING_TAG: if (is_name_first_char(s[i]) == TRUE){ change_state(&parser->state, SCANNING_TAG, parser->depth); require_ok(token_append(&parser->buffer_list, s[i])); break; } /* Discard document element */ else if (s[i] == '?' && parser->depth == 0){ parser->state = DOCUMENT_ELEMENT; break; } else{ HC_ERR_LOG(("Invalid first character for element name : %c %d %s\n", s[i], i, s)); return HCERR_XML_INVALID_ELEMENT_TAG; } // FALLTHRU INTENTIONAL??? /* Start tag is terminated by whitespace, /, or > End tag is terminated by whitespace or > */ case SCANNING_TAG: /* Still reading token */ if (is_name_char(s[i]) == TRUE){ require_ok(token_append(&parser->buffer_list, s[i])); break; } else if (is_white_space(s[i]) == TRUE) { parser->current_tag = token_finish(&parser->buffer_list); if (parser->start_tag == TRUE){ /*printf("Start element: %s\n", parser->current_tag);*/ change_state(&parser->state, SCANNING_ATTRIBUTES, parser->depth); break; } else{ change_state(&parser->state, SCANNING_CLOSE_TAG, parser->depth); break; } } else if (s[i] == '>') { if (DEBUG == TRUE) printf("parser->depth: %d\n", parser->depth); require_ok(close_tag(&i, parser)); if (DEBUG == TRUE) printf("parser->depth: %d\n", parser->depth); if (parser->depth == 0){ *read = i + 1; return HCERR_OK; } } /* <element/> */ else if (s[i] == '/' && parser->start_tag == TRUE) { if (DEBUG == TRUE){ printf("Start element: %s\n", parser->current_tag); printf("End element: %s\n", parser->current_tag); } change_state(&parser->state, EXPECTING_RIGHT_BRACKET, parser->depth); break; } else { HC_ERR_LOG(("Invalid character '%c' in tag. %i %s\n", s[i], i, s)); return HCERR_XML_INVALID_ELEMENT_TAG; } break; case EXPECTING_RIGHT_BRACKET: if (s[i] != '>') { HC_ERR_LOG(("Unexpected character %c after close element. %d %s", s[i], i, s)); return HCERR_XML_MALFORMED_START_ELEMENT; } if (parser->depth == 0){ *read = i + 1; return HCERR_OK; } change_state(&parser->state, OUTSIDE_ELEMENT, parser->depth); break; case SCANNING_CLOSE_TAG: if (is_white_space(s[i])) { break; } if (DEBUG == TRUE) fprintf(stdout, "End element: %s\n", parser->current_tag); if (s[i] != '>') { HC_ERR_LOG(("Unexpected character %c after close element. %d %s", s[i], i, s)); return HCERR_XML_MALFORMED_END_ELEMENT; } require_ok((*parser->end_element_callback)(parser->current_tag, parser->data)); parser->depth--; if (parser->depth == 0){ *read = i + 1; return HCERR_OK; } change_state(&parser->state, OUTSIDE_ELEMENT, parser->depth); break; /* Expected tokens: * attribute_name * '/' * > */ case SCANNING_ATTRIBUTES: if (is_white_space(s[i])){ /*skip_white_space */ break; } if (is_name_first_char(s[i]) == TRUE) { change_state(&parser->state, SCANNING_ATTRIBUTE_NAME, parser->depth); require_ok(token_append(&parser->buffer_list, s[i])); } else if (s[i] == '/' && parser->start_tag == TRUE) { if (DEBUG == TRUE){ int j = 0; printf("SA Start element: %s\n", parser->current_tag); fprintf(stdout, "Start element: %s %d\n", parser->current_tag, parser->current_attribute); for (j = 0; j < parser->current_attribute; j++){ printf(" %s=\"%s\"", *(parser->attribute_names + j), *(parser->attribute_values + j)); } fprintf(stdout, "End element: %s\n", parser->current_tag); fflush(stdout); } require_ok((*parser->start_element_callback)(parser->current_tag, parser->data, parser->attribute_names, parser->attribute_values, parser->current_attribute)); require_ok((*parser->end_element_callback)(parser->current_tag, parser->data)); parser->current_attribute = 0; change_state(&parser->state, EXPECTING_RIGHT_BRACKET, parser->depth); } else if (s[i] == '>') { if (DEBUG == TRUE){ int j = 0; fprintf(stdout, "Start element event: %s %d\n", parser->current_tag, parser->current_attribute); for (j = 0; j < parser->current_attribute; j++){ printf(" %s=\"%s\"", *(parser->attribute_names + j), *(parser->attribute_values + j)); } } require_ok((*parser->start_element_callback)(parser->current_tag, parser->data, parser->attribute_names, parser->attribute_values, parser->current_attribute)); parser->current_attribute = 0; parser->depth++; change_state(&parser->state, OUTSIDE_ELEMENT, parser->depth); } else{ HC_ERR_LOG(("Unexpected character %c after close element. %d %s", s[i], i, s)); return HCERR_XML_MALFORMED_START_ELEMENT; } break; case SCANNING_ATTRIBUTE_NAME: if (s[i] == '='){ if (parser->current_attribute == parser->attribute_arrays_size){ require_ok(grow_attribute_arrays(parser)); } parser->attribute_names[parser->current_attribute] = token_finish(&parser->buffer_list); change_state(&parser->state, SCANNING_START_ATTRIBUTE_VALUE, parser->depth); } else if (is_name_char(s[i]) == TRUE) { require_ok(token_append(&parser->buffer_list, s[i])); } else{ HC_ERR_LOG(("Illegal char %c in attribute name. %i <<%s>>\n", s[i], i, s)); return HCERR_XML_BAD_ATTRIBUTE_NAME; } break; case SCANNING_START_ATTRIBUTE_VALUE: if (is_white_space(s[i])){ break; } else if (s[i] != '"'){ HC_ERR_LOG(("Attribute value does not begin with quote: '%c'. %i %s\n", s[i], i, s)); return HCERR_XML_BAD_ATTRIBUTE_NAME; } change_state(&parser->state, SCANNING_ATTRIBUTE_VALUE, parser->depth); break; case SCANNING_ATTRIBUTE_VALUE: if (s[i] == '\\') { if (parser->backslash == TRUE){ parser->backslash = FALSE; } else{ parser->backslash = TRUE; } } else if (s[i] == '"' && parser->backslash == FALSE) { parser->attribute_values[parser->current_attribute++] = token_finish(&parser->buffer_list); change_state(&parser->state, SCANNING_ATTRIBUTES, parser->depth); break; } require_ok(token_append(&parser->buffer_list, s[i])); break; } i++; } return HCERR_OK; }
/* Constructs and queues a request packet describing the http query pointed * to by 'start'. */ int make_request_packet(Server *serv, int fd, int num_chars) { struct sockaddr_in client_name, local_name; int client_namelen, local_namelen; int free_start, free_end; int packet_length; char *request; int len; client_namelen = sizeof(struct sockaddr_in); if (getpeername(fd, (struct sockaddr *) &client_name, &client_namelen) < 0) { syslog(LOG_INFO, "make_request_packet: failed to get peer " "name: %m\n"); return 0; } local_namelen = sizeof(struct sockaddr_in); if (getsockname(fd, (struct sockaddr *) &local_name, &local_namelen) < 0) { syslog(LOG_INFO, "make_request_packet: failed to get sock name: %m\n"); return 0; } change_state(serv, fd, fs_requested_backend); /* locate the free end of the buffer (possibly appending to previous * control packets) */ append_data(serv, serv->control_fd, &free_start, &free_end, fs_output); /* reserve the first 4 bytes of the packet for the size field */ packet_length = PAK_COM_OFF; /* add command field to packet */ serv->writebuf.buffer[free_start + packet_length++] = PAK_REQUEST; /* add unique ID field to packet */ write_long(&serv->writebuf.buffer[free_start], &packet_length, (getpid() & 0xffff) | (fd << 16), 1); /* add client IP field to packet */ write_long(&serv->writebuf.buffer[free_start], &packet_length, client_name.sin_addr.s_addr, 0); /* add local IP field to packet */ write_long(&serv->writebuf.buffer[free_start], &packet_length, local_name.sin_addr.s_addr, 0); /* add local port field to packet */ write_short(&serv->writebuf.buffer[free_start], &packet_length, serv->port, 1); /* write the http headers */ request = &serv->writebuf.buffer[serv->writebuf.pos[fd]]; while (request[0] == '\r' || request[0] == '\n') request++; for (len = 0; len < num_chars && !isspace(request[len]); len++) ; if (len < num_chars) { write_string(&serv->writebuf.buffer[free_start], &packet_length, "method"); write_string_n(&serv->writebuf.buffer[free_start], &packet_length, request, len); num_chars -= len; request += len; for (len = 0; len < num_chars && isspace(request[len]); len++) ; if (len < num_chars) { num_chars -= len; request += len; for (len = 0; request[len] && !isspace(request[len]); len++) ; write_string(&serv->writebuf.buffer[free_start], &packet_length, "uri"); write_string_n(&serv->writebuf.buffer[free_start], &packet_length, request, len); num_chars -= len; request += len; for (len = 0; len < num_chars && isspace(request[len]); len++) ; if (len < num_chars) { num_chars -= len; request += len; for (len = 0; request[len] && !isspace(request[len]); len++) ; write_string(&serv->writebuf.buffer[free_start], &packet_length, "version"); write_string_n(&serv->writebuf.buffer[free_start], &packet_length, request, len); /* each line should end with \r\n. Be a bit lenient, and * allow just \r or \n, too. End of request is indicated * by two such lines in a row */ if (request[len] == '\r') len++; if (request[len] == '\n') len++; num_chars -= len; request += len; /* find "field: value\r\n" on successive lines, adding them * to the buffer as field\0value\0 */ while (num_chars > 0 && request[0] != '\r' && request[0] != '\n') { for (len = 0; len < num_chars && request[len] != ':' && request[len] != '\r' && request[len] != '\n'; len++) ; if (len < num_chars && request[len] == ':') { write_string_n(&serv->writebuf.buffer[free_start], &packet_length, request, len); for (len++; len < num_chars && isspace(request[len]); len++) ; num_chars -= len; request += len; for (len = 0; len < num_chars && request[len] != '\r' && request[len] != '\n'; len++) ; write_string_n(&serv->writebuf.buffer[free_start], &packet_length, request, len); } if (request[len] == '\r') len++; if (request[len] == '\n') len++; num_chars -= len; request += len; } } } } /* set first 4 bytes of packet to the total packet length */ write_long(&serv->writebuf.buffer[free_start], NULL, packet_length, 1); /* add the packet to the output buffer properly */ if (free_end - free_start < packet_length) fatal(serv, "request packet overflowed the buffer\n"); add_data(serv, serv->control_fd, NULL, free_start, packet_length, fs_output); return 1; }
void state_driving() { do_driving(); do_shifting(); change_state(); }
void key_pressed(unsigned short key) { switch (state) { case main_menu: switch (key) { case UP_ARROW_MAKECODE: previous_button(start_menu); break; case DOWN_ARROW_MAKECODE: next_button(start_menu); break; case ENTER_MAKECODE: press_selected_button(start_menu); break; case ESC_MAKECODE: cancel_button(start_menu); break; } break; case singleplayer: switch (key) { case ESC_MAKECODE: //TODO add a pause menu singleplayer_game_over(); break; case RIGHT_ARROW_MAKECODE: if(controller == keyboard){ singleplayer_move(1); } break; case LEFT_ARROW_MAKECODE: if(controller == keyboard){ singleplayer_move(-1); } break; case SPACE_MAKECODE: if(controller == keyboard){ singleplayer_fire(); } break; } break; case multiplayer: switch(key){ case A_MAKECODE: versus_mp_move(1,-1); break; case D_MAKECODE: versus_mp_move(1,1); break; case W_MAKECODE: versus_mp_fire(1); break; case LEFT_ARROW_MAKECODE: versus_mp_move(2,-1); break; case RIGHT_ARROW_MAKECODE: versus_mp_move(2,1); break; case UP_ARROW_MAKECODE: versus_mp_fire(2); break; case ESC_MAKECODE: change_state(main_menu); break; } break; case highscore: switch(key){ case ESC_MAKECODE: highscore_back_on_click(); break; } break; case options: switch(key){ case ESC_MAKECODE: options_cancel_on_click(); break; case ENTER_MAKECODE: options_accept_on_click(); break; case RIGHT_ARROW_MAKECODE: options_next_ctrl_on_click(); break; case LEFT_ARROW_MAKECODE: options_prev_ctrl_on_click(); break; } break; } }
void event::remove_state(event_state new_state) { change_state(static_cast< event_state >(_state & ~new_state)); }
static void usbIRQHandler(uint32_t token) { // we need to mask because GINTSTS is set for a particular interrupt even if it's masked in GINTMSK (GINTMSK just prevents an interrupt being generated) uint32_t status = GET_REG(USB + GINTSTS) & GET_REG(USB + GINTMSK); int process = FALSE; //uartPrintf("<begin interrupt: %x>\r\n", status); if(status) { process = TRUE; } while(process) { if((status & GINTMSK_OTG) == GINTMSK_OTG) { // acknowledge OTG interrupt (these bits are all R_SS_WC which means Write Clear, a write of 1 clears the bits) SET_REG(USB + GOTGINT, GET_REG(USB + GOTGINT)); // acknowledge interrupt (this bit is actually RO, but should've been cleared when we cleared GOTGINT. Still, iBoot pokes it as if it was WC, so we will too) SET_REG(USB + GINTSTS, GINTMSK_OTG); process = TRUE; } else { // we only care about OTG process = FALSE; } if((status & GINTMSK_RESET) == GINTMSK_RESET) { bufferPrintf("usb: reset detected\r\n"); change_state(USBPowered); int retval = resetUSB(); SET_REG(USB + GINTSTS, GINTMSK_RESET); if(retval) { bufferPrintf("usb: listening for further usb events\r\n"); return; } process = TRUE; } if(((status & GINTMSK_INEP) == GINTMSK_INEP) || ((status & GINTMSK_OEP) == GINTMSK_OEP)) { // aha, got something on one of the endpoints. Now the real fun begins // first, let's get the interrupt status of individual endpoints getEndpointInterruptStatuses(); if(isSetupPhaseDone()) { // recall our earlier receiveControl calls. We now should have 8 bytes of goodness in controlRecvBuffer. USBSetupPacket* setupPacket = (USBSetupPacket*) controlRecvBuffer; uint16_t length; uint32_t totalLength; USBStringDescriptor* strDesc; if(USBSetupPacketRequestTypeType(setupPacket->bmRequestType) != USBSetupPacketVendor) { switch(setupPacket->bRequest) { case USB_GET_DESCRIPTOR: length = setupPacket->wLength; // descriptor type is high, descriptor index is low int stall = FALSE; switch(setupPacket->wValue >> 8) { case USBDeviceDescriptorType: if(length > sizeof(USBDeviceDescriptor)) length = sizeof(USBDeviceDescriptor); memcpy(controlSendBuffer, usb_get_device_descriptor(), length); break; case USBConfigurationDescriptorType: // hopefully SET_ADDRESS was received beforehand to set the speed totalLength = getConfigurationTree(setupPacket->wValue & 0xFF, usb_speed, controlSendBuffer); if(length > totalLength) length = totalLength; break; case USBStringDescriptorType: strDesc = usb_get_string_descriptor(setupPacket->wValue & 0xFF); if(length > strDesc->bLength) length = strDesc->bLength; memcpy(controlSendBuffer, strDesc, length); break; case USBDeviceQualifierDescriptorType: if(length > sizeof(USBDeviceQualifierDescriptor)) length = sizeof(USBDeviceQualifierDescriptor); memcpy(controlSendBuffer, usb_get_device_qualifier_descriptor(), length); break; default: bufferPrintf("Unknown descriptor request: %d\r\n", setupPacket->wValue >> 8); stall = TRUE; } if(gUsbState < USBError) { if(stall) stallControl(); else sendControl(controlSendBuffer, length); } break; case USB_SET_ADDRESS: usb_speed = DSTS_GET_SPEED(GET_REG(USB + DSTS)); usb_max_packet_size = packetsizeFromSpeed(usb_speed); SET_REG(USB + DCFG, (GET_REG(USB + DCFG) & ~DCFG_DEVICEADDRMSK) | ((setupPacket->wValue & DCFG_DEVICEADDR_UNSHIFTED_MASK) << DCFG_DEVICEADDR_SHIFT)); // send an acknowledgement sendControl(controlSendBuffer, 0); if(gUsbState < USBError) { change_state(USBAddress); } break; case USB_SET_INTERFACE: // send an acknowledgement sendControl(controlSendBuffer, 0); break; case USB_GET_STATUS: // FIXME: iBoot doesn't really care about this status *((uint16_t*) controlSendBuffer) = 0; sendControl(controlSendBuffer, sizeof(uint16_t)); break; case USB_GET_CONFIGURATION: // FIXME: iBoot just puts out a debug message on console for this request. break; case USB_SET_CONFIGURATION: setConfiguration(0); // send an acknowledgment sendControl(controlSendBuffer, 0); if(gUsbState < USBError) { change_state(USBConfigured); startHandler(); } break; default: // Unknown Request { int i; uint8_t *pktDump = (uint8_t*)setupPacket; bufferPrintf("Bad USB setup packet: "); for(i = 0; i < sizeof(USBSetupPacket); i++) { bufferPrintf("0x%08x ", pktDump[i]); } bufferPrintf("\n"); } //stallControl(); break; } // get the next SETUP packet receiveControl(controlRecvBuffer, sizeof(USBSetupPacket)); } } else { //uartPrintf("\t<begin callEndpointHandlers>\r\n"); callEndpointHandlers(); //uartPrintf("\t<end callEndpointHandlers>\r\n"); } process = TRUE; }
int main() { // instantiate the app class App *app = new App(); // gaffer loop time stuff sf::Clock clock; //double dt = 0.01f; //const double dt = 1.0f / 60.0f; // this is same as timeStep double alpha; double currentTime = clock.getElapsedTime().asSeconds(); double accumulator = 0.0f; // get a clock for calculating fps sf::Clock fps_clock; double lasttime = 0; // set initial state stateID = STATE_TITLE; currentState.reset(new Title(app)); pausedState.reset(new Pause(app)); // init the state stack TODO - just work with the stack directly instead of currentState? //std::vector<GameState>& state_stack; // main loop here while(stateID != STATE_EXIT) { double newTime = clock.getElapsedTime().asSeconds(); double frameTime = newTime - currentTime; // remove division by 1000 if using seconds if (frameTime > 0.55f) // was 0.25 frameTime = 0.55f; currentTime = newTime; accumulator += frameTime; // handle events currentState->handle_events(app); // fixed timestep update loop int count = 0; while ( accumulator >= app->TIMESTEP ) { //if (stateID != STATE_PAUSE) // do logic for current state currentState->logic(app); // decrement accumulator accumulator -= app->TIMESTEP; count += 1; } //std::cout << count << std::endl; // get the alpha alpha = accumulator / app->TIMESTEP; // change state if needed change_state(app); // render the state currentState->render(app, alpha); // update screen app->window.display(); // calculate FPS double fps_time = fps_clock.restart().asSeconds(); app->fps = 1 / (fps_time - lasttime); //std::cout << "state: " << stateID << "fps: " << fps << " accumulator: " << accumulator << " alpha: " << alpha << " frameTime: " << frameTime << std::endl; } // do cleanup clean_up(app); }
int main(int argc, char **argv) { enum state state; unsigned char command; struct timeval tval; struct packet pkt; /* Open a socket and start listening to a scpefied port */ open_udp_socket(); srand(time(NULL)); /* Startup: */ build_send_packet(BROADCAST, CMD_MASTERREQ, 0); /* Search for a master */ change_state(&state, STATE_STARTUP, &tval, NULL); for(;;) { struct timeval curtime; gettimeofday(&curtime, NULL); printf(" "); print_time(&curtime); /*printf(" TIME: %10d sec %10d usec\n", (unsigned int)curtime.tv_sec, (unsigned int)curtime.tv_usec);*/ recv_msg(&pkt, &tval); command = pkt.type; //printf("Command received = %d\n", command); switch(state | command) { /* STARTUP */ case(STATE_STARTUP | CMD_TIMEOUT): build_send_packet(BROADCAST, CMD_MASTERUP, 0); change_state(&state, STATE_MASTER, &tval, &master_timeout); break; case(STATE_STARTUP | CMD_MASTERUP): build_send_packet(pkt.ip, CMD_SLAVEUP, 0); // no break; case(STATE_STARTUP | CMD_MASTERREQ): case(STATE_STARTUP | CMD_MASTERACK): case(STATE_STARTUP | CMD_ELECTION): change_state(&state, STATE_SLAVE, &tval, NULL); break; /* MASTER */ /* Launch a new thread and process separately? Prevents loss of messages */ case(STATE_MASTER | CMD_TIMEOUT): /* Does the Master needs to send his clock? */ build_send_packet(BROADCAST, CMD_CLOCKREQ, 1); //change_state(&state, STATE_MASTER, &tval, MASTER_TIMEOUT); /* Change to an intermediate state in order to wait for all slaves * to send their clocks. After the MASTER_ADJTIME_TIMEOUT no more clock * packets will be accepted and the "slow" slaves, if any, won't * be synchronized*/ change_state(&state, STATE_MASTER_ADJTIME, &tval, &master_adjtime_timeout); /* Possibly new thread? Non blocking function...*/ adjust_master_prepare(); break; case(STATE_MASTER | CMD_MASTERREQ): build_send_packet(pkt.ip, CMD_MASTERACK, 0); break; case(STATE_MASTER | CMD_QUIT): build_send_packet(pkt.ip, CMD_ACK, 0); change_state(&state, STATE_SLAVE, &tval, NULL); break; case(STATE_MASTER | CMD_ELECTION): case(STATE_MASTER | CMD_MASTERUP): build_send_packet(pkt.ip, CMD_QUIT, 0); break; /* MASTER_ADJTIME */ case(STATE_MASTER_ADJTIME | CMD_CLOCKREQ_RESPONSE): /* Got time from client */ adjust_master_addslave(pkt.ip, &pkt.time); break; case(STATE_MASTER_ADJTIME | CMD_TIMEOUT): /* Calculate avg clocks and send to each slave his correction */ /* Restart the synchronization timer */ change_state(&state, STATE_MASTER, &tval, &master_timeout); adjust_master_calcandsend(); break; /* SLAVE */ case(STATE_SLAVE | CMD_CLOCKREQ): /* Send clock packet to master and change to an intermediate state * in order to wait for a synch packet */ build_send_packet(pkt.ip, CMD_CLOCKREQ_RESPONSE, 1); change_state(&state, STATE_SLAVE, &tval, NULL); break; case(STATE_SLAVE | CMD_TIMEOUT): build_send_packet(BROADCAST, CMD_ELECTION, 0); change_state(&state, STATE_CANDIDATE, &tval, &candidate_timeout); break; case(STATE_SLAVE | CMD_MASTERUP): build_send_packet(BROADCAST, CMD_SLAVEUP, 0); break; case(STATE_SLAVE | CMD_ELECTION): build_send_packet(pkt.ip, CMD_ACCEPT, 0); change_state(&state, STATE_ACCEPT, &tval, &accept_timeout); break; case(STATE_SLAVE | CMD_CLOCKSYNC): /* Receive packet from master, adjust local time and return to * your rightful state (slave of course... =])*/ adjust_slave_clock(&pkt.time); change_state(&state, STATE_SLAVE, &tval, NULL); break; /* CANDIDATE */ case(STATE_CANDIDATE | CMD_TIMEOUT): build_send_packet(BROADCAST, CMD_MASTERUP, 0); change_state(&state, STATE_MASTER, &tval, &master_timeout); break; case(STATE_CANDIDATE | CMD_ELECTION): build_send_packet(pkt.ip, CMD_REFUSE, 0); break; case(STATE_CANDIDATE | CMD_ACCEPT): build_send_packet(pkt.ip, CMD_ACK, 0); break; case(STATE_CANDIDATE | CMD_QUIT): case(STATE_CANDIDATE | CMD_REFUSE): build_send_packet(pkt.ip, CMD_ACK, 0); //no break case(STATE_CANDIDATE | CMD_MASTERREQ): change_state(&state, STATE_SLAVE, &tval, NULL); break; /* ACCEPT */ case(STATE_ACCEPT | CMD_TIMEOUT): change_state(&state, STATE_SLAVE, &tval, NULL); break; case(STATE_ACCEPT | CMD_ELECTION): build_send_packet(pkt.ip, CMD_REFUSE, 0); break; case(STATE_ACCEPT | CMD_MASTERUP): build_send_packet(pkt.ip, CMD_SLAVEUP, 0); break; } } return 0; }
void state_isotp() { int i, items, ret; char rxmsg[MAXLEN]; /* can to inet */ char buf[MAXLEN]; /* inet commands to can */ unsigned char isobuf[ISOTPLEN+1]; /* binary buffer for isotp socket */ unsigned char tmp; if(previous_state == STATE_ISOTP) { state_isotp_init(); previous_state = STATE_ISOTP; } FD_ZERO(&readfds); FD_SET(si, &readfds); FD_SET(client_socket, &readfds); /* * Check if there are more elements in the element buffer before calling select() and * blocking for new packets. */ if(more_elements) { FD_CLR(si, &readfds); } else { ret = select((si > client_socket)?si+1:client_socket+1, &readfds, NULL, NULL, NULL); if(ret < 0) { PRINT_ERROR("Error in select()\n") change_state(STATE_SHUTDOWN); return; } } if (FD_ISSET(si, &readfds)) { struct timeval tv = {0}; items = read(si, isobuf, ISOTPLEN); /* read timestamp data */ if(ioctl(si, SIOCGSTAMP, &tv) < 0) { PRINT_ERROR("Could not receive timestamp\n"); } if (items > 0 && items <= ISOTPLEN) { int startlen; sprintf(rxmsg, "< pdu %ld.%06ld ", tv.tv_sec, tv.tv_usec); startlen = strlen(rxmsg); for (i=0; i < items; i++) sprintf(rxmsg + startlen + 2*i, "%02X", isobuf[i]); sprintf(rxmsg + strlen(rxmsg), " >"); send(client_socket, rxmsg, strlen(rxmsg), 0); } } if (FD_ISSET(client_socket, &readfds)) { ret = receive_command(client_socket, buf); if(ret != 0) { change_state(STATE_SHUTDOWN); return; } if ( (ret = state_changed(buf, state)) ) { if(ret == CONTROL_SWITCH_STATE) state_isotp_deinit(); strcpy(buf, "< ok >"); send(client_socket, buf, strlen(buf), 0); return; } #if 0 if(!strcmp("< echo >", buf)) { send(client_socket, buf, strlen(buf), 0); return; } if(!strncmp("< sendpdu ", buf, 10)) { items = element_length(buf, 2); if (items & 1) { PRINT_ERROR("odd number of ASCII Hex values\n"); return; } items /= 2; if (items > ISOTPLEN) { PRINT_ERROR("PDU too long\n"); return; } for (i = 0; i < items; i++) { tmp = asc2nibble(buf[(2*i) + 10]); if (tmp > 0x0F) return; isobuf[i] = (tmp << 4); tmp = asc2nibble(buf[(2*i) + 11]); if (tmp > 0x0F) return; isobuf[i] |= tmp; } ret = write(si, isobuf, items); if(ret != items) { PRINT_ERROR("Error in write()\n") change_state(STATE_SHUTDOWN); return; } } else { PRINT_ERROR("unknown command '%s'.\n", buf) strcpy(buf, "< error unknown command >"); send(client_socket, buf, strlen(buf), 0); } #else ret = decode_command(buf); switch(ret) { case COMMAND_ECHO: send(client_socket, buf, strlen(buf), 0); break; case COMMAND_SENDPDU: items = element_length(buf, 2); if (items & 1) { PRINT_ERROR("odd number of ASCII Hex values\n"); return; } items /= 2; if (items > ISOTPLEN) { PRINT_ERROR("PDU too long\n"); return; } for (i = 0; i < items; i++) { tmp = asc2nibble(buf[(2*i) + 10]); if (tmp > 0x0F) return; isobuf[i] = (tmp << 4); tmp = asc2nibble(buf[(2*i) + 11]); if (tmp > 0x0F) return; isobuf[i] |= tmp; } ret = write(si, isobuf, items); if(ret != items) { PRINT_ERROR("Error in write()\n") change_state(STATE_SHUTDOWN); return; } break; /* COMMAND_SENDPDU */ case COMMAND_UNKNOWN: default: PRINT_ERROR("unknown command '%s'.\n", buf) strcpy(buf, "< error unknown command >"); send(client_socket, buf, strlen(buf), 0); break; /* COMMAND_UNKNOWN */ } #endif } }
void g_omx_core_pause (GOmxCore *core) { change_state (core, OMX_StatePause); wait_for_state (core, OMX_StatePause); }
void state_isotp_init() { int items, ret; struct sockaddr_can addr; struct ifreq ifr; static struct can_isotp_options opts; static struct can_isotp_fc_options fcopts; char buf[MAXLEN]; /* inet commands to can */ while(previous_state != STATE_ISOTP) { ret = receive_command(client_socket, buf); if(ret != 0) { change_state(STATE_SHUTDOWN); return; } strncpy(ifr.ifr_name, bus_name, IFNAMSIZ); if ( (ret = state_changed(buf, state)) ) { /* ensure proper handling in other states */ if(ret == CONTROL_SWITCH_STATE) previous_state = STATE_ISOTP; strcpy(buf, "< ok >"); send(client_socket, buf, strlen(buf), 0); return; } #if 0 if(!strcmp("< echo >", buf)) { send(client_socket, buf, strlen(buf), 0); continue; } memset(&opts, 0, sizeof(opts)); memset(&fcopts, 0, sizeof(fcopts)); memset(&addr, 0, sizeof(addr)); /* get configuration to open the socket */ if(!strncmp("< isotpconf ", buf, 12)) { items = sscanf(buf, "< %*s %x %x %x " "%hhu %hhx %hhu " "%hhx %hhx %hhx %hhx >", &addr.can_addr.tp.tx_id, &addr.can_addr.tp.rx_id, &opts.flags, &fcopts.bs, &fcopts.stmin, &fcopts.wftmax, &opts.txpad_content, &opts.rxpad_content, &opts.ext_address, &opts.rx_ext_address); /* < isotpconf XXXXXXXX ... > check for extended identifier */ if(element_length(buf, 2) == 8) addr.can_addr.tp.tx_id |= CAN_EFF_FLAG; if(element_length(buf, 3) == 8) addr.can_addr.tp.rx_id |= CAN_EFF_FLAG; if (((opts.flags & CAN_ISOTP_RX_EXT_ADDR) && items < 10) || ((opts.flags & CAN_ISOTP_EXTEND_ADDR) && items < 9) || ((opts.flags & CAN_ISOTP_RX_PADDING) && items < 8) || ((opts.flags & CAN_ISOTP_TX_PADDING) && items < 7) || (items < 5)) { PRINT_ERROR("Syntax error in isotpconf command\n"); /* try it once more */ continue; } /* open ISOTP socket */ if ((si = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP)) < 0) { PRINT_ERROR("Error while opening ISOTP socket %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } strcpy(ifr.ifr_name, bus_name); if(ioctl(si, SIOCGIFINDEX, &ifr) < 0) { PRINT_ERROR("Error while searching for bus %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } addr.can_family = PF_CAN; addr.can_ifindex = ifr.ifr_ifindex; /* only change the built-in defaults when required */ if (opts.flags) setsockopt(si, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts)); setsockopt(si, SOL_CAN_ISOTP, CAN_ISOTP_RECV_FC, &fcopts, sizeof(fcopts)); PRINT_VERBOSE("binding ISOTP socket...\n") if (bind(si, (struct sockaddr *)&addr, sizeof(addr)) < 0) { PRINT_ERROR("Error while binding ISOTP socket %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } /* ok we made it and have a proper isotp socket open */ previous_state = STATE_ISOTP; } #else ret = decode_command(buf); switch(ret) { case COMMAND_ECHO: send(client_socket, buf, strlen(buf), 0); continue; break; case COMMAND_ISOTPCONF: memset(&opts, 0, sizeof(opts)); memset(&fcopts, 0, sizeof(fcopts)); memset(&addr, 0, sizeof(addr)); /* get configuration to open the socket */ items = sscanf(buf, "< %*s %x %x %x " "%hhu %hhx %hhu " "%hhx %hhx %hhx %hhx >", &addr.can_addr.tp.tx_id, &addr.can_addr.tp.rx_id, &opts.flags, &fcopts.bs, &fcopts.stmin, &fcopts.wftmax, &opts.txpad_content, &opts.rxpad_content, &opts.ext_address, &opts.rx_ext_address); /* < isotpconf XXXXXXXX ... > check for extended identifier */ if(element_length(buf, 2) == 8) addr.can_addr.tp.tx_id |= CAN_EFF_FLAG; if(element_length(buf, 3) == 8) addr.can_addr.tp.rx_id |= CAN_EFF_FLAG; if (((opts.flags & CAN_ISOTP_RX_EXT_ADDR) && items < 10) || ((opts.flags & CAN_ISOTP_EXTEND_ADDR) && items < 9) || ((opts.flags & CAN_ISOTP_RX_PADDING) && items < 8) || ((opts.flags & CAN_ISOTP_TX_PADDING) && items < 7) || (items < 5)) { PRINT_ERROR("Syntax error in isotpconf command\n"); /* try it once more */ continue; } /* open ISOTP socket */ if ((si = socket(PF_CAN, SOCK_DGRAM, CAN_ISOTP)) < 0) { PRINT_ERROR("Error while opening ISOTP socket %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } strcpy(ifr.ifr_name, bus_name); if(ioctl(si, SIOCGIFINDEX, &ifr) < 0) { PRINT_ERROR("Error while searching for bus %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } addr.can_family = PF_CAN; addr.can_ifindex = ifr.ifr_ifindex; /* only change the built-in defaults when required */ if (opts.flags) setsockopt(si, SOL_CAN_ISOTP, CAN_ISOTP_OPTS, &opts, sizeof(opts)); setsockopt(si, SOL_CAN_ISOTP, CAN_ISOTP_RECV_FC, &fcopts, sizeof(fcopts)); PRINT_VERBOSE("binding ISOTP socket...\n") if (bind(si, (struct sockaddr *)&addr, sizeof(addr)) < 0) { PRINT_ERROR("Error while binding ISOTP socket %s\n", strerror(errno)); /* ensure proper handling in other states */ previous_state = STATE_ISOTP; state_isotp_deinit(); change_state(STATE_SHUTDOWN); return; } /* ok we made it and have a proper isotp socket open */ previous_state = STATE_ISOTP; break; case COMMAND_UNKNOWN: default: break; } /* switch */ #endif } /* while */
int main(int argc, char *argv[]) { pthread_t threads[2]; send_port = recv_port = 0; char *uart_port = ""; gettimeofday(&tm, NULL); old_time = (double)tm.tv_sec + (double)tm.tv_usec / 1000000.0; //ble_cmd_sm_set_bondable_mode(1); host = (struct hostent *) gethostbyname((char *)"127.0.0.1"); // Not enough command-line arguments if (argc <= CLARG_PORT) { usage(argv[0]); return 1; } // COM port argument if (argc > CLARG_PORT) { if (strcmp(argv[CLARG_PORT], "list") == 0) { uart_list_devices(); return 1; } else if (strcmp(argv[CLARG_PORT], "-h") == 0 || strcmp(argv[CLARG_PORT], "--help") == 0) { usage(argv[0]); } else { uart_port = argv[CLARG_PORT]; } } // Action argument if (argc > CLARG_ACTION) { int i; for (i = 0; i < strlen(argv[CLARG_ACTION]); i++) { argv[CLARG_ACTION][i] = tolower(argv[CLARG_ACTION][i]); } if (strcmp(argv[CLARG_ACTION], "scan") == 0) { action = action_scan; } else if (strcmp(argv[CLARG_ACTION], "info") == 0) { action = action_info; } else if (strcmp(argv[CLARG_ACTION], "broadcast") == 0 || strcmp(argv[CLARG_ACTION], "broadcast_connect") == 0) { action = action_broadcast; if (argc > CLARG_ACTION + 2) { send_port = atoi(argv[CLARG_ACTION + 1]); recv_port = atoi(argv[CLARG_ACTION + 2]); } else { usage(argv[0]); return 1; } if (strcmp(argv[CLARG_ACTION], "broadcast_connect") == 0) { connect_all = 1; action = action_broadcast_connect; } } else if (strcmp(argv[CLARG_ACTION], "all") == 0) { connect_all = 1; action = action_scan; if (argc > CLARG_ACTION + 2) { send_port = atoi(argv[CLARG_ACTION + 1]); recv_port = atoi(argv[CLARG_ACTION + 2]); } else { usage(argv[0]); return 1; } } else { int i; short unsigned int addr[6]; if (sscanf(argv[CLARG_ACTION], "%02hx:%02hx:%02hx:%02hx:%02hx:%02hx", &addr[5], &addr[4], &addr[3], &addr[2], &addr[1], &addr[0]) == 6) { for (i = 0; i < 6; i++) { connect_addr.addr[i] = addr[i]; } action = action_connect; if (argc > CLARG_ACTION + 2) { send_port = atoi(argv[CLARG_ACTION + 1]); recv_port = atoi(argv[CLARG_ACTION + 2]); } else { usage(argv[0]); return 1; } } } } if (action == action_none) { usage(argv[0]); return 1; } size_t i = 0; for (i = 0; i < argc; i++) { if(strcmp(argv[i],"log") == 0){ time_t timev; time(&timev); char timedate[256]; strftime(timedate, 256, "var/logs/%Y%m%d_%H%M%S.rssilog", localtime(&timev)); rssi_fp = fopen(timedate, "w"); if (!rssi_fp) { fprintf(stderr,"Unable to open file for logging: %s\n Make sure to run from paparazzi home\n", timedate); return -1; } } } // set BGLib output function pointer to "send_api_packet" function bglib_output = send_api_packet; if (uart_open(uart_port)) { fprintf(stderr, "ERROR: Unable to open serial port - %s\n", strerror(errno)); return 1; } // Reset dongle to get it into known state ble_cmd_system_reset(0); #if 0 // very soft "reset" // close current connection, stop scanning, stop advertising // (returns BLE device to a known state without a hard reset) ble_cmd_connection_disconnect(0); ble_cmd_gap_set_mode(0, 0); ble_cmd_gap_end_procedure(); #else // full reset // reset BLE device to get it into known state ble_cmd_system_reset(0); // close the serial port, since reset causes USB to re-enumerate uart_close(); // wait until USB re-enumerates and we can re-open the port // (not necessary if using a direct UART connection) do { usleep(500000); // 0.5s } while (uart_open(uart_port)); #endif // get the mac address of the dongle ble_cmd_system_address_get(); // advertise interval scales 625us, min, max, channels (0x07 = 3, 0x03 = 2, 0x04 = 1) if (action == action_broadcast) ble_cmd_gap_set_adv_parameters(0x20, 0x28, 0x07); // Execute action if (action == action_scan || action == action_broadcast || action == action_broadcast_connect) { ble_cmd_gap_discover(gap_discover_generic); } else if (action == action_info) { ble_cmd_system_get_info(); } else if (action == action_connect) { fprintf(stderr, "Trying to connect\n"); change_state(state_connecting); ble_cmd_gap_connect_direct(&connect_addr, gap_address_type_public, 8, 16, 100, 0); } pthread_create(&threads[0], NULL, send_msg, NULL); pthread_create(&threads[1], NULL, recv_paparazzi_comms, NULL); // Message loop while (state != state_finish) { if (read_api_packet(UART_TIMEOUT) > 0) { break; } } change_state(state_finish); ble_cmd_gap_end_procedure(); uart_close(); pthread_exit(NULL); if (rssi_fp) fclose(rssi_fp); }
/** * "connection_status" event handler * Occurs whenever a new connection is established, or an existing one is updated * * @param msg Event packet data payload */ void ble_evt_connection_status(const struct ble_msg_connection_status_evt_t *msg) { // updated connection if (msg->flags & connection_parameters_change) { fprintf(stderr, "Connection %d parameters updated, interval %fms\n", msg->connection, msg->conn_interval * 1.25); } // Encrypted previous connection else if (msg->flags & connection_encrypted) { fprintf(stderr, "Connection with %d is encrypted\n", msg->connection); } // Connection request completed else if (msg->flags & connection_completed) { if (msg->connection + 1 > connected_devices) { connected_devices++; } cpy_bdaddr(connected_addr[msg->connection].addr, msg->address.addr); //change_state(state_connected); connection_interval = msg->conn_interval * 1.25; fprintf(stderr, "Connected, nr: %d, connection interval: %d = %fms\n", msg->connection, msg->conn_interval, msg->conn_interval * 1.25); connected[msg->connection] = 1; if (rec_addr[msg->connection].sin_family != AF_INET && send_port && recv_port) { if ((sock[msg->connection] = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } send_addr[msg->connection].sin_family = AF_INET; send_addr[msg->connection].sin_port = htons(send_port + msg->connection); send_addr[msg->connection].sin_addr = *((struct in_addr *)host->h_addr); bzero(&(send_addr[msg->connection].sin_zero), 8); sin_size = sizeof(struct sockaddr); rec_addr[msg->connection].sin_family = AF_INET; rec_addr[msg->connection].sin_port = htons(recv_port + msg->connection); rec_addr[msg->connection].sin_addr = *((struct in_addr *)host->h_addr); bzero(&(rec_addr[msg->connection].sin_zero), 8); sin_size = sizeof(struct sockaddr); if (bind(sock[msg->connection], (struct sockaddr *)&rec_addr[msg->connection], sizeof(struct sockaddr)) == -1) { perror("Bind failed"); exit(1); } fprintf(stderr, "Comms port opened on port: %d %d\n", send_port + msg->connection, recv_port + msg->connection); } // Handle for Drone Data configuration already known if (drone_handle_configuration) { change_state(state_listening_measurements); enable_indications(msg->connection, drone_handle_configuration); //if (connect_all) { ble_cmd_gap_discover(gap_discover_generic); //} } // Find primary services else { change_state(state_finding_services); ble_cmd_attclient_read_by_group_type(msg->connection, FIRST_HANDLE, LAST_HANDLE, 2, primary_service_uuid); //if (connect_all) { ble_cmd_gap_discover(gap_discover_generic); //} } } }
bool cassette_image_device::call_load() { casserr_t err; int cassette_flags; const char *extension; int is_writable; device_image_interface *image = nullptr; interface(image); if ((has_been_created()) || (length() == 0)) { /* creating an image */ err = cassette_create((void *)image, &image_ioprocs, &wavfile_format, m_create_opts, CASSETTE_FLAG_READWRITE|CASSETTE_FLAG_SAVEONEXIT, &m_cassette); if (err) goto error; } else { /* opening an image */ do { is_writable = !is_readonly(); cassette_flags = is_writable ? (CASSETTE_FLAG_READWRITE|CASSETTE_FLAG_SAVEONEXIT) : CASSETTE_FLAG_READONLY; std::string fname; if (software_entry()==nullptr) { extension = filetype(); } else { fname = m_mame_file->filename(); int loc = fname.find_last_of('.'); if (loc!=-1) { extension = fname.substr(loc + 1,fname.length()-loc).c_str(); } else { extension = ""; } } err = cassette_open_choices((void *)image, &image_ioprocs, extension, m_formats, cassette_flags, &m_cassette); /* this is kind of a hack */ if (err && is_writable) make_readonly(); } while(err && is_writable); if (err) goto error; } /* set to default state, but only change the UI state */ change_state(m_default_state, CASSETTE_MASK_UISTATE); /* reset the position */ m_position = 0.0; m_position_time = device().machine().time().as_double(); /* default channel to 0, speed multiplier to 1 */ m_channel = 0; m_speed = 1; m_direction = 1; return IMAGE_INIT_PASS; error: image_error_t imgerr = IMAGE_ERROR_UNSPECIFIED; switch(err) { case CASSETTE_ERROR_INTERNAL: imgerr = IMAGE_ERROR_INTERNAL; break; case CASSETTE_ERROR_UNSUPPORTED: imgerr = IMAGE_ERROR_UNSUPPORTED; break; case CASSETTE_ERROR_OUTOFMEMORY: imgerr = IMAGE_ERROR_OUTOFMEMORY; break; case CASSETTE_ERROR_INVALIDIMAGE: imgerr = IMAGE_ERROR_INVALIDIMAGE; break; default: imgerr = IMAGE_ERROR_UNSPECIFIED; break; } image->seterror(imgerr, "" ); return IMAGE_INIT_FAIL; }
static void refresh_instance_info( struct nc_state_t *nc, ncInstance *instance) { int now = instance->state; if (! check_hypervisor_conn ()) return; /* no need to bug for domains without state on Hypervisor */ if (now==TEARDOWN || now==STAGING) return; sem_p(hyp_sem); virDomainPtr dom = virDomainLookupByName (nc_state.conn, instance->instanceId); sem_v(hyp_sem); if (dom == NULL) { /* hypervisor doesn't know about it */ if (now==RUNNING || now==BLOCKED || now==PAUSED || now==SHUTDOWN) { /* Most likely the user has shut it down from the inside */ if (instance->retries) { instance->retries--; logprintfl (EUCAWARN, "warning: hypervisor failed to find domain %s, will retry %d more times\n", instance->instanceId, instance->retries); } else { logprintfl (EUCAWARN, "warning: hypervisor failed to find domain %s, assuming it was shut off\n", instance->instanceId); change_state (instance, SHUTOFF); } } /* else 'now' stays in SHUTFOFF, BOOTING, CANCELED, or CRASHED */ return; } virDomainInfo info; sem_p(hyp_sem); int error = virDomainGetInfo(dom, &info); sem_v(hyp_sem); if (error < 0 || info.state == VIR_DOMAIN_NOSTATE) { logprintfl (EUCAWARN, "warning: failed to get informations for domain %s\n", instance->instanceId); /* what to do? hopefully we'll find out more later */ sem_p(hyp_sem); virDomainFree (dom); sem_v(hyp_sem); return; } int xen = info.state; switch (now) { case BOOTING: case RUNNING: case BLOCKED: case PAUSED: /* change to state, whatever it happens to be */ change_state (instance, xen); break; case SHUTDOWN: case SHUTOFF: case CRASHED: if (xen==RUNNING || xen==BLOCKED || xen==PAUSED) { /* cannot go back! */ logprintfl (EUCAWARN, "warning: detected prodigal domain %s, terminating it\n", instance->instanceId); sem_p (hyp_sem); virDomainDestroy (dom); sem_v (hyp_sem); } else { change_state (instance, xen); } break; default: logprintfl (EUCAERROR, "error: refresh...(): unexpected state (%d) for instance %s\n", now, instance->instanceId); return; } sem_p(hyp_sem); virDomainFree(dom); sem_v(hyp_sem); /* if instance is running, try to find out its IP address */ if (instance->state==RUNNING || instance->state==BLOCKED || instance->state==PAUSED) { char *ip=NULL; int rc; if (!strncmp(instance->ncnet.publicIp, "0.0.0.0", 24)) { if (!strcmp(nc_state.vnetconfig->mode, "SYSTEM") || !strcmp(nc_state.vnetconfig->mode, "STATIC")) { rc = mac2ip(nc_state.vnetconfig, instance->ncnet.privateMac, &ip); if (!rc) { if(ip) { logprintfl (EUCAINFO, "discovered public IP %s for instance %s\n", ip, instance->instanceId); strncpy(instance->ncnet.publicIp, ip, 24); free(ip); } } } } if (!strncmp(instance->ncnet.privateIp, "0.0.0.0", 24)) { rc = mac2ip(nc_state.vnetconfig, instance->ncnet.privateMac, &ip); if (!rc) { if(ip) { logprintfl (EUCAINFO, "discovered private IP %s for instance %s\n", ip, instance->instanceId); strncpy(instance->ncnet.privateIp, ip, 24); free(ip); } } } } }
void event::add_state(event_state new_state) { change_state(static_cast< event_state >(_state | new_state)); }
void * monitoring_thread (void *arg) { int i; struct nc_state_t *nc; if (arg == NULL) { logprintfl (EUCAFATAL, "NULL parameter!\n"); return NULL; } nc = (struct nc_state_t*)arg; logprintfl (EUCADEBUG, "Starting monitoring thread\n!\n"); for (;;) { bunchOfInstances *head; time_t now = time(NULL); sem_p (inst_sem); for ( head = global_instances; head; head = head->next ) { ncInstance * instance = head->instance; /* query for current state, if any */ refresh_instance_info (nc, instance); /* don't touch running or canceled threads */ if (instance->state!=STAGING && instance->state!=BOOTING && instance->state!=SHUTOFF && instance->state!=SHUTDOWN && instance->state!=TEARDOWN) continue; if (instance->state==TEARDOWN) { /* it's been long enough, we can forget the instance */ if ((now - instance->terminationTime)>teardown_state_duration) { remove_instance (&global_instances, instance); logprintfl (EUCAINFO, "forgetting about instance %s\n", instance->instanceId); free_instance (&instance); break; /* need to get out since the list changed */ } continue; } // time out logic for STAGING or BOOTING instances if (instance->state==STAGING && (now - instance->launchTime) < staging_cleanup_threshold) continue; // hasn't been long enough, spare it if (instance->state==BOOTING && (now - instance->bootTime) < booting_cleanup_threshold) continue; /* ok, it's been condemned => destroy the files */ if (!nc_state.save_instance_files) { logprintfl (EUCAINFO, "cleaning up state for instance %s\n", instance->instanceId); if (scCleanupInstanceImage(instance->userId, instance->instanceId)) { logprintfl (EUCAWARN, "warning: failed to cleanup instance image %s\n", instance->instanceId); } } else { logprintfl (EUCAINFO, "cleaning up state for instance %s (but keeping the files)\n", instance->instanceId); } /* check to see if this is the last instance running on vlan */ int left = 0; bunchOfInstances * vnhead; for (vnhead = global_instances; vnhead; vnhead = vnhead->next ) { ncInstance * vninstance = vnhead->instance; if (vninstance->ncnet.vlan == (instance->ncnet).vlan && strcmp(instance->instanceId, vninstance->instanceId)) { left++; } } if (left==0) { logprintfl (EUCAINFO, "stopping the network (vlan=%d)\n", (instance->ncnet).vlan); vnetStopNetwork (nc_state.vnetconfig, (instance->ncnet).vlan, NULL, NULL); } change_state (instance, TEARDOWN); /* TEARDOWN = no more resources */ instance->terminationTime = time (NULL); } sem_v (inst_sem); if (head) { /* we got out because of modified list, no need to sleep * now */ continue; } sleep (MONITORING_PERIOD); } return NULL; }
int usb_setup() { int i; if(usb_inited) { return 0; } InEPRegs = (USBEPRegisters*)(USB + USB_INREGS); OutEPRegs = (USBEPRegisters*)(USB + USB_OUTREGS); change_state(USBStart); // Power on hardware power_ctrl(POWER_USB, ON); udelay(USB_START_DELAYUS); // Initialize our data structures for(i = 0; i < USB_NUM_ENDPOINTS; i++) { switch(USB_EP_DIRECTION(i)) { case USB_ENDPOINT_DIRECTIONS_BIDIR: endpoint_directions[i] = USBBiDir; break; case USB_ENDPOINT_DIRECTIONS_IN: endpoint_directions[i] = USBIn; break; case USB_ENDPOINT_DIRECTIONS_OUT: endpoint_directions[i] = USBOut; break; } bufferPrintf("EP %d: %d\r\n", i, endpoint_directions[i]); } memset(usb_message_queue, 0, sizeof(usb_message_queue)); memset(endpoint_handlers, 0, sizeof(endpoint_handlers)); // Set up the hardware clock_gate_switch(USB_OTGCLOCKGATE, ON); clock_gate_switch(USB_PHYCLOCKGATE, ON); clock_gate_switch(EDRAM_CLOCKGATE, ON); // Generate a soft disconnect on host SET_REG(USB + DCTL, GET_REG(USB + DCTL) | DCTL_SFTDISCONNECT); udelay(USB_SFTDISCONNECT_DELAYUS); // power on OTG SET_REG(USB + USB_ONOFF, GET_REG(USB + USB_ONOFF) & (~USB_ONOFF_OFF)); udelay(USB_ONOFFSTART_DELAYUS); // power on PHY SET_REG(USB_PHY + OPHYPWR, OPHYPWR_POWERON); udelay(USB_PHYPWRPOWERON_DELAYUS); // select clock SET_REG(USB_PHY + OPHYCLK, (GET_REG(USB_PHY + OPHYCLK) & OPHYCLK_CLKSEL_MASK) | OPHYCLK_CLKSEL_48MHZ); // reset phy SET_REG(USB_PHY + ORSTCON, GET_REG(USB_PHY + ORSTCON) | ORSTCON_PHYSWRESET); udelay(USB_RESET2_DELAYUS); SET_REG(USB_PHY + ORSTCON, GET_REG(USB_PHY + ORSTCON) & (~ORSTCON_PHYSWRESET)); udelay(USB_RESET_DELAYUS); SET_REG(USB + GRSTCTL, GRSTCTL_CORESOFTRESET); // wait until reset takes while((GET_REG(USB + GRSTCTL) & GRSTCTL_CORESOFTRESET) == GRSTCTL_CORESOFTRESET); // wait until reset completes while((GET_REG(USB + GRSTCTL) & ~GRSTCTL_AHBIDLE) != 0); udelay(USB_RESETWAITFINISH_DELAYUS); // allow host to reconnect SET_REG(USB + DCTL, GET_REG(USB + DCTL) & (~DCTL_SFTDISCONNECT)); udelay(USB_SFTCONNECT_DELAYUS); // flag all interrupts as positive, maybe to disable them // Set 7th EP? This is what iBoot does InEPRegs[USB_NUM_ENDPOINTS].interrupt = USB_EPINT_INEPNakEff | USB_EPINT_INTknEPMis | USB_EPINT_INTknTXFEmp | USB_EPINT_TimeOUT | USB_EPINT_AHBErr | USB_EPINT_EPDisbld | USB_EPINT_XferCompl; OutEPRegs[USB_NUM_ENDPOINTS].interrupt = USB_EPINT_OUTTknEPDis | USB_EPINT_SetUp | USB_EPINT_AHBErr | USB_EPINT_EPDisbld | USB_EPINT_XferCompl; for(i = 0; i < USB_NUM_ENDPOINTS; i++) { InEPRegs[i].interrupt = USB_EPINT_INEPNakEff | USB_EPINT_INTknEPMis | USB_EPINT_INTknTXFEmp | USB_EPINT_TimeOUT | USB_EPINT_AHBErr | USB_EPINT_EPDisbld | USB_EPINT_XferCompl; OutEPRegs[i].interrupt = USB_EPINT_OUTTknEPDis | USB_EPINT_SetUp | USB_EPINT_AHBErr | USB_EPINT_EPDisbld | USB_EPINT_XferCompl; } // disable all interrupts until endpoint descriptors and configuration structures have been setup SET_REG(USB + GINTMSK, GINTMSK_NONE); SET_REG(USB + DIEPMSK, USB_EPINT_NONE); SET_REG(USB + DOEPMSK, USB_EPINT_NONE); interrupt_install(USB_INTERRUPT, usbIRQHandler, 0); usb_inited = TRUE; return 0; }
void *startup_thread (void * arg) { ncInstance * instance = (ncInstance *)arg; virDomainPtr dom = NULL; char *disk_path=NULL, *xml=NULL; char *brname=NULL; int error, i; if (! check_hypervisor_conn ()) { logprintfl (EUCAFATAL, "could not start instance %s, abandoning it\n", instance->instanceId); change_state (instance, SHUTOFF); return NULL; } error = vnetStartNetwork (nc_state.vnetconfig, instance->ncnet.vlan, NULL, NULL, &brname); if ( error ) { logprintfl (EUCAFATAL, "start network failed for instance %s, terminating it\n", instance->instanceId); change_state (instance, SHUTOFF); return NULL; } logprintfl (EUCAINFO, "network started for instance %s\n", instance->instanceId); error = scMakeInstanceImage (nc_state.home, instance->userId, instance->imageId, instance->imageURL, instance->kernelId, instance->kernelURL, instance->ramdiskId, instance->ramdiskURL, instance->instanceId, instance->keyName, &disk_path, addkey_sem, nc_state.convert_to_disk, instance->params.disk*1024); if (error) { logprintfl (EUCAFATAL, "Failed to prepare images for instance %s (error=%d)\n", instance->instanceId, error); change_state (instance, SHUTOFF); if (brname) free(brname); if (disk_path) free(disk_path); return NULL; } if (instance->state==TEARDOWN) { // timed out in STAGING if (disk_path) free(disk_path); if (brname) free(brname); return NULL; } if (instance->state==CANCELED) { logprintfl (EUCAFATAL, "Startup of instance %s was cancelled\n", instance->instanceId); change_state (instance, SHUTOFF); if (brname) free(brname); if (disk_path) free(disk_path); return NULL; } error = get_instance_xml (nc_state.gen_libvirt_cmd_path, instance->userId, instance->instanceId, instance->ramdiskId, instance->kernelId, disk_path, &(instance->params), instance->ncnet.privateMac, brname, nc_state.config_use_virtio_net, nc_state.config_use_virtio_root, &xml); if (brname) free(brname); if (disk_path) free(disk_path); if (xml) logprintfl (EUCADEBUG2, "libvirt XML config:\n%s\n", xml); if (error) { logprintfl (EUCAFATAL, "Failed to create libvirt XML config for instance %s\n", instance->instanceId); change_state (instance, SHUTOFF); return NULL; } scStoreStringToInstanceFile (instance->userId, instance->instanceId, "libvirt.xml", xml); /* for debugging */ scSaveInstanceInfo(instance); /* to enable NC recovery */ /* we serialize domain creation as hypervisors can get confused with * too many simultaneous create requests */ logprintfl (EUCADEBUG2, "about to start domain %s\n", instance->instanceId); print_running_domains (); for (i=0; i<5 && dom == NULL; i++) { sem_p (hyp_sem); dom = virDomainCreateLinux (nc_state.conn, xml, 0); sem_v (hyp_sem); } if (xml) free(xml); if (dom == NULL) { logprintfl (EUCAFATAL, "hypervisor failed to start domain\n"); change_state (instance, SHUTOFF); return NULL; } eventlog("NC", instance->userId, "", "instanceBoot", "begin"); // TODO: bring back correlationId sem_p(hyp_sem); virDomainFree(dom); sem_v(hyp_sem); sem_p (inst_sem); // check one more time for cancellation if (instance->state==TEARDOWN) { // timed out in BOOTING } else if (instance->state==CANCELED || instance->state==SHUTOFF) { logprintfl (EUCAFATAL, "startup of instance %s was cancelled\n", instance->instanceId); change_state (instance, SHUTOFF); } else { logprintfl (EUCAINFO, "booting VM instance %s\n", instance->instanceId); instance->bootTime = time (NULL); change_state (instance, BOOTING); } sem_v (inst_sem); return NULL; }
static void decrease_state(JScript *This, SCRIPTSTATE state) { if(This->ctx) { switch(This->ctx->state) { case SCRIPTSTATE_CONNECTED: change_state(This, SCRIPTSTATE_DISCONNECTED); if(state == SCRIPTSTATE_DISCONNECTED) return; /* FALLTHROUGH */ case SCRIPTSTATE_STARTED: case SCRIPTSTATE_DISCONNECTED: clear_script_queue(This); if(This->ctx->state == SCRIPTSTATE_DISCONNECTED) change_state(This, SCRIPTSTATE_INITIALIZED); if(state == SCRIPTSTATE_INITIALIZED) return; /* FALLTHROUGH */ case SCRIPTSTATE_INITIALIZED: if(This->ctx->host_global) { IDispatch_Release(This->ctx->host_global); This->ctx->host_global = NULL; } if(This->ctx->named_items) { named_item_t *iter, *iter2; iter = This->ctx->named_items; while(iter) { iter2 = iter->next; if(iter->disp) IDispatch_Release(iter->disp); heap_free(iter->name); heap_free(iter); iter = iter2; } This->ctx->named_items = NULL; } if(This->ctx->secmgr) { IInternetHostSecurityManager_Release(This->ctx->secmgr); This->ctx->secmgr = NULL; } if(This->ctx->site) { IActiveScriptSite_Release(This->ctx->site); This->ctx->site = NULL; } if(This->ctx->global) { jsdisp_release(This->ctx->global); This->ctx->global = NULL; } /* FALLTHROUGH */ case SCRIPTSTATE_UNINITIALIZED: change_state(This, state); break; default: assert(0); } change_state(This, state); }else if(state == SCRIPTSTATE_UNINITIALIZED) { if(This->site) IActiveScriptSite_OnStateChange(This->site, state); }else { FIXME("NULL ctx\n"); } if(state == SCRIPTSTATE_UNINITIALIZED) This->thread_id = 0; if(This->site) { IActiveScriptSite_Release(This->site); This->site = NULL; } }
void adopt_instances() { int dom_ids[MAXDOMS]; int num_doms = 0; int i; virDomainPtr dom = NULL; if (! check_hypervisor_conn()) return; logprintfl (EUCAINFO, "looking for existing domains\n"); virSetErrorFunc (NULL, libvirt_error_handler); num_doms = virConnectListDomains(nc_state.conn, dom_ids, MAXDOMS); if (num_doms == 0) { logprintfl (EUCAINFO, "no currently running domains to adopt\n"); return; } if (num_doms < 0) { logprintfl (EUCAWARN, "WARNING: failed to find out about running domains\n"); return; } for ( i=0; i<num_doms; i++) { int error; virDomainInfo info; const char * dom_name; ncInstance * instance; sem_p(hyp_sem); dom = virDomainLookupByID(nc_state.conn, dom_ids[i]); sem_v(hyp_sem); if (!dom) { logprintfl (EUCAWARN, "WARNING: failed to lookup running domain #%d, ignoring it\n", dom_ids[i]); continue; } sem_p(hyp_sem); error = virDomainGetInfo(dom, &info); sem_v(hyp_sem); if (error < 0 || info.state == VIR_DOMAIN_NOSTATE) { logprintfl (EUCAWARN, "WARNING: failed to get info on running domain #%d, ignoring it\n", dom_ids[i]); continue; } if (info.state == VIR_DOMAIN_SHUTDOWN || info.state == VIR_DOMAIN_SHUTOFF || info.state == VIR_DOMAIN_CRASHED ) { logprintfl (EUCADEBUG, "ignoring non-running domain #%d\n", dom_ids[i]); continue; } sem_p(hyp_sem); if ((dom_name = virDomainGetName(dom))==NULL) { sem_v(hyp_sem); logprintfl (EUCAWARN, "WARNING: failed to get name of running domain #%d, ignoring it\n", dom_ids[i]); continue; } sem_v(hyp_sem); if (!strcmp(dom_name, "Domain-0")) continue; if ((instance = scRecoverInstanceInfo (dom_name))==NULL) { logprintfl (EUCAWARN, "WARNING: failed to recover Eucalyptus metadata of running domain %s, ignoring it\n", dom_name); continue; } change_state (instance, info.state); sem_p (inst_sem); int err = add_instance (&global_instances, instance); sem_v (inst_sem); if (err) { free_instance (&instance); continue; } logprintfl (EUCAINFO, "- adopted running domain %s from user %s\n", instance->instanceId, instance->userId); /* TODO: try to look up IPs? */ sem_p(hyp_sem); virDomainFree (dom); sem_v(hyp_sem); } }
void engine_run(struct State *s) { int redraw = FALSE; if (engine_active) { return; } change_state(s, NULL); // Generate display events al_register_event_source(engine.event_queue, al_get_display_event_source(engine.display)); // Timer events al_register_event_source(engine.event_queue, al_get_timer_event_source(engine.timer)); // Keyboard events al_register_event_source(engine.event_queue, al_get_keyboard_event_source()); // Mouse events al_register_event_source(engine.event_queue, al_get_mouse_event_source()); al_start_timer(engine.timer); engine_active = TRUE; // Main game loop while (engine_active) { ALLEGRO_EVENT event; al_wait_for_event(engine.event_queue, &event); // Event processing engine.states[current_state]->_events(&event, &engine.sm); // If the close button was pressed... if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { engine_active = FALSE; break; } else if (event.type == ALLEGRO_EVENT_KEY_DOWN) { keys[event.keyboard.keycode] = TRUE; // F4 key will toggle full-screen if (event.keyboard.keycode == ALLEGRO_KEY_F4) { al_stop_timer(engine.timer); if (al_get_display_flags(engine.display) & ALLEGRO_FULLSCREEN_WINDOW) { al_toggle_display_flag(engine.display, ALLEGRO_FULLSCREEN_WINDOW, 0); } else { al_toggle_display_flag(engine.display, ALLEGRO_FULLSCREEN_WINDOW, 1); } aspect_ratio_transform(); al_start_timer(engine.timer); } } else if (event.type == ALLEGRO_EVENT_KEY_UP) { keys[event.keyboard.keycode] = FALSE; } else if (event.type == ALLEGRO_EVENT_TIMER) { engine.states[current_state]->_update(&engine.sm); redraw = TRUE; } if (redraw && engine_active && al_is_event_queue_empty(engine.event_queue)) { redraw = FALSE; if (MAINCONF->buffer) { al_set_target_bitmap(engine.buffer); } else { al_set_target_backbuffer(engine.display); } al_clear_to_color(engine.bg_color); engine.states[current_state]->_draw(&engine.sm); if (MAINCONF->buffer) { al_set_target_backbuffer(engine.display); al_clear_to_color(C_BLACK); al_draw_bitmap(engine.buffer, 0, 0, 0); } al_flip_display(); } } while (loaded_count > 0) { engine.loaded_states[--loaded_count]->_free(); } al_destroy_display(engine.display); al_destroy_timer(engine.timer); al_destroy_event_queue(engine.event_queue); al_destroy_font(font); if (MAINCONF->buffer) { al_destroy_bitmap(engine.buffer); } }
int S9xMovieOpen (const char* filename, bool8 read_only, uint8 sync_flags, uint8 sync_flags2) { FILE* fd; STREAM stream; int result; int fn; char movie_filename [_MAX_PATH]; #ifdef WIN32 _fullpath(movie_filename, filename, _MAX_PATH); #else strcpy(movie_filename, filename); #endif if(!(fd=fopen(movie_filename, "rb+"))) if(!(fd=fopen(movie_filename, "rb"))) return FILE_NOT_FOUND; else read_only = TRUE; const bool8 wasPaused = Settings.Paused; const uint32 prevFrameTime = Settings.FrameTime; // stop current movie before opening change_state(MOVIE_STATE_NONE); // read header if((result=read_movie_header(fd, &Movie))!=SUCCESS) { fclose(fd); return result; } read_movie_extrarominfo(fd, &Movie); fn=dup(fileno(fd)); fclose(fd); // apparently this lseek is necessary lseek(fn, Movie.SaveStateOffset, SEEK_SET); if(!(stream=REOPEN_STREAM(fn, "rb"))) return FILE_NOT_FOUND; // store previous, before changing to the movie's settings store_previous_settings(); // store default if (sync_flags & MOVIE_SYNC_DATA_EXISTS) { Settings.UseWIPAPUTiming = (sync_flags & MOVIE_SYNC_WIP1TIMING) ? TRUE : FALSE; Settings.SoundEnvelopeHeightReading = (sync_flags & MOVIE_SYNC_VOLUMEENVX) ? TRUE : FALSE; Settings.FakeMuteFix = (sync_flags & MOVIE_SYNC_FAKEMUTE) ? TRUE : FALSE; Settings.UpAndDown = (sync_flags & MOVIE_SYNC_LEFTRIGHT) ? TRUE : FALSE; // doesn't actually affect synchronization Settings.SoundSync = (sync_flags & MOVIE_SYNC_SYNCSOUND) ? TRUE : FALSE; // doesn't seem to affect synchronization Settings.InitFastROMSetting = (sync_flags2 & MOVIE_SYNC2_INIT_FASTROM) ? TRUE : FALSE; //Settings.ShutdownMaster = (sync_flags & MOVIE_SYNC_NOCPUSHUTDOWN) ? FALSE : TRUE; } // set from movie restore_movie_settings(); if(Movie.Opts & MOVIE_OPT_FROM_RESET) { Movie.State = MOVIE_STATE_PLAY; // prevent NSRT controller switching (in S9xPostRomInit) if(!Memory.LoadLastROM()) S9xReset(); Memory.ClearSRAM(false); // in case the SRAM read fails Movie.State = MOVIE_STATE_NONE; // save only SRAM for a from-reset snapshot result=(READ_STREAM(Memory.SRAM, 0x20000, stream) == 0x20000) ? SUCCESS : WRONG_FORMAT; } else { result=S9xUnfreezeFromStream(stream); } CLOSE_STREAM(stream); if(result!=SUCCESS) { return result; } if(!(fd=fopen(movie_filename, "rb+"))) if(!(fd=fopen(movie_filename, "rb"))) return FILE_NOT_FOUND; else read_only = TRUE; if(fseek(fd, Movie.ControllerDataOffset, SEEK_SET)) return WRONG_FORMAT; // read controller data Movie.File=fd; Movie.BytesPerFrame=bytes_per_frame(); Movie.InputBufferPtr=Movie.InputBuffer; uint32 to_read=Movie.BytesPerFrame * (Movie.MaxFrame+1); reserve_buffer_space(to_read); fread(Movie.InputBufferPtr, 1, to_read, fd); // read "baseline" controller data if(Movie.MaxFrame) read_frame_controller_data(); strncpy(Movie.Filename, movie_filename, _MAX_PATH); Movie.Filename[_MAX_PATH-1]='\0'; Movie.CurrentFrame=0; Movie.ReadOnly=read_only; change_state(MOVIE_STATE_PLAY); Settings.Paused = wasPaused; Settings.FrameTime = prevFrameTime; // restore emulation speed Movie.RecordedThisSession = false; S9xUpdateFrameCounter(-1); Movie.RequiresReset = false; S9xMessage(S9X_INFO, S9X_MOVIE_INFO, MOVIE_INFO_REPLAY); return SUCCESS; }
void engine_run(struct State *first) { int redraw = FALSE; if (engine_active) { puts("WARNING: Calling game_run() more than once"); return; } change_state(first); // Generate display events al_register_event_source(engine.event_queue, al_get_display_event_source(engine.display)); // Timer events al_register_event_source(engine.event_queue, al_get_timer_event_source(engine.timer)); // Keyboard events al_register_event_source(engine.event_queue, al_get_keyboard_event_source()); al_start_timer(engine.timer); engine_active = TRUE; // Main game loop while (engine_active) { ALLEGRO_EVENT event; al_wait_for_event(engine.event_queue, &event); // Event processing engine.states[current_state]->_events(&event); // If the close button was pressed... if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) { engine_active = FALSE; break; } else if (event.type == ALLEGRO_EVENT_KEY_DOWN) { keys[event.keyboard.keycode] = TRUE; // Escape key will end the game if (event.keyboard.keycode == ALLEGRO_KEY_ESCAPE) { engine_active = FALSE; break; } } else if (event.type == ALLEGRO_EVENT_KEY_UP) { keys[event.keyboard.keycode] = FALSE; } else if (event.type == ALLEGRO_EVENT_TIMER) { engine.states[current_state]->_update(); redraw = TRUE; } if (redraw && al_event_queue_is_empty(engine.event_queue)) { redraw = FALSE; al_set_target_backbuffer(engine.display); al_clear_to_color(engine.bg_color); engine.states[current_state]->_draw(); al_flip_display(); } } while (current_state >= 0) { engine.states[current_state--]->_end(); } al_destroy_display(engine.display); al_destroy_timer(engine.timer); al_destroy_event_queue(engine.event_queue); al_destroy_font(font); }
//----------------------------------------------------------------------------------- void check_set_ds1307() { // if(SET_BTN ==0 || set_flag==1) //neu dang o che do set change_state(); }
static int scanDFA( ScanValue *value ) /************************************/ { long newint; /* these are used to accumulate parts of */ VarString *newstring; /* a new value */ int token; #ifdef SCANDEBUG char debugstring[10]; #endif char *stringFromFile; int i; value->intinfo.type = SCAN_INT_TYPE_DEFAULT; value->string.string = NULL; longString = FALSE; state(S_START): if( isspace(LookAhead) ) { do_transition( S_START ); } else if( isdigit(LookAhead) ) { newint = LookAhead - '0'; newstring = VarStringStart(); VarStringAddChar( newstring, LookAhead ); if( LookAhead == '0' ) { do_transition( S_HEXSTART ); } else { do_transition( S_DECIMAL ); } } else if( isalpha(LookAhead) || LookAhead == '_' ) { newstring = VarStringStart(); VarStringAddChar( newstring, LookAhead ); if( LookAhead == 'l' || LookAhead == 'L' ) { do_transition( S_L_STRING ); } do_transition( S_NAME ); } else switch (LookAhead) { case '"': newstring = VarStringStart(); /* don't include the " */ newLineInString = 0; /* reset newline in string status */ do_transition( S_STRING ); case '.': newstring = VarStringStart(); VarStringAddChar( newstring, LookAhead ); do_transition( S_DOS_FILENAME ); case RC_EOF: DEBUGPUTS("RC_EOF") return( 0 ); /* yacc wants 0 on EOF */ case '#': do_transition( S_POUND_SIGN ); case '(': do_transition( S_LPAREN ); case ')': do_transition( S_RPAREN ); case '[': do_transition( S_LSQ_BRACKET ); case ']': do_transition( S_RSQ_BRACKET ); case '{': do_transition( S_LBRACE ); case '}': do_transition( S_RBRACE ); case '+': do_transition( S_PLUS ); case '-': do_transition( S_MINUS ); case '~': do_transition( S_BITNOT ); case '!': do_transition( S_NOT ); case '*': do_transition( S_TIMES ); case '/': do_transition( S_DIVIDE ); case '%': do_transition( S_MOD ); case '>': do_transition( S_GT ); case '<': do_transition( S_LT ); case '=': do_transition( S_EQ ); case '&': do_transition( S_BITAND ); case '^': do_transition( S_BITXOR ); case '|': do_transition( S_BITOR ); case '?': do_transition( S_QUESTION ); case ':': do_transition( S_COLON ); case ',': do_transition( S_COMMA ); case ';': do_transition( S_COMMENT ); case '\\': newstring = VarStringStart(); VarStringAddChar( newstring, LookAhead ); do_transition( S_DOS_FILENAME ); default: value->UnknownChar = LookAhead; do_transition( S_ERROR ); } state(S_L_STRING): if( LookAhead =='"' ) { longString = TRUE; RcMemFree( VarStringEnd( newstring, NULL ) ); change_state( S_START ); } else { change_state( S_NAME ); } state(S_ERROR): ErrorHasOccured = TRUE; return( Y_SCAN_ERROR ); state(S_COMMENT): if( LookAhead == '\n' || LookAhead == RC_EOF ) { do_transition( S_START ); } else { do_transition( S_COMMENT ); } state(S_POUND_SIGN): DEBUGPUTS( "#" ) return( Y_POUND_SIGN ); state(S_LPAREN): DEBUGPUTS( "(" ) return( Y_LPAREN ); state(S_RPAREN): DEBUGPUTS( ")" ) return( Y_RPAREN ); state( S_LSQ_BRACKET ): DEBUGPUTS( "[" ) return( Y_LSQ_BRACKET ); state( S_RSQ_BRACKET ): DEBUGPUTS( "]" ) return( Y_RSQ_BRACKET ); state(S_LBRACE): DEBUGPUTS( "{" ) return( Y_LBRACE ); state(S_RBRACE): DEBUGPUTS( "}" ) return( Y_RBRACE ); state(S_PLUS): DEBUGPUTS( "+" ) return( Y_PLUS ); state(S_MINUS): DEBUGPUTS( "-" ) return( Y_MINUS ); state(S_BITNOT): DEBUGPUTS( "~" ) return( Y_BITNOT ); state(S_NOT): if( LookAhead == '=' ) { do_transition( S_NE ); } else { DEBUGPUTS( "!" ) return( Y_NOT ); } state(S_TIMES): DEBUGPUTS( "*" ) return( Y_TIMES ); state(S_DIVIDE): DEBUGPUTS( "/" ) return( Y_DIVIDE ); state(S_MOD): DEBUGPUTS( "%" ) return( Y_MOD ); state(S_GT): switch (LookAhead) { case '>': do_transition( S_SHIFTR ); case '=': do_transition( S_GE ); default: DEBUGPUTS( ">" ) return( Y_GT ); } state(S_LT): switch (LookAhead) { case '<': do_transition( S_SHIFTL ); case '=': do_transition( S_LE ); default: DEBUGPUTS( "<" ) return( Y_LT ); } state(S_EQ): if( LookAhead == '=' ) { do_transition( S_ENDEQ ); } else { DEBUGPUTS( "=" ) return( Y_SINGLE_EQ ); } state(S_BITAND): if( LookAhead == '&' ) { do_transition( S_AND ); } else { DEBUGPUTS( "&" ) return( Y_BITAND ); } state(S_BITXOR): DEBUGPUTS( "^" ) return( Y_BITXOR ); state(S_BITOR): if( LookAhead == '|' ) { do_transition( S_OR ); } else { DEBUGPUTS( "|" ) return( Y_BITOR ); } state(S_QUESTION): DEBUGPUTS( "?" ) return( Y_QUESTION ); state(S_COLON): DEBUGPUTS( ":" ) return( Y_COLON ); state(S_COMMA): DEBUGPUTS( "," ) return( Y_COMMA ); state(S_NE): DEBUGPUTS( "!=" ) return( Y_NE ); state(S_SHIFTR): DEBUGPUTS( ">>" ) return( Y_SHIFTR ); state(S_GE): DEBUGPUTS( ">=" ) return( Y_GE ); state(S_SHIFTL): DEBUGPUTS( "<<" ) return( Y_SHIFTL ); state(S_LE): DEBUGPUTS( "<=" ) return( Y_LE ); state(S_ENDEQ): DEBUGPUTS( "==" ) return( Y_EQ ); state(S_AND): DEBUGPUTS( "&&" ) return( Y_AND ); state(S_OR): DEBUGPUTS( "||" ) return( Y_OR ); state(S_STRING): /* handle double-byte characters */ i = CharSetLen[LookAhead]; if( i ) { VarStringAddChar( newstring, LookAhead ); for( ; i > 0; --i ) { GetNextChar(); VarStringAddChar( newstring, LookAhead ); } do_transition( S_STRING ); } // if newline in string was detected, remove all whitespace from // begining of the next line if( newLineInString ) { if ( isspace( LookAhead ) ) { do_transition( S_STRING ); } else { // non whitespace was detected, reset newline flag, so whitespaces are treated normally newLineInString = 0; } } switch (LookAhead) { case '"': do_transition( S_STRINGEND ); case '\\': do_transition( S_ESCAPE_CHAR ); case '\n': if( RcIoIsCOrHFile() ) { value->string.string = VarStringEnd( newstring, &(value->string.length) ); DEBUGPUTS( "STRING" ) return( Y_STRING ); } else { // MSVC's RC uses this obscure way of handling newline in strings and we follow. // First store <space> and then <newline character>. Then on next line, all white // spaces from begining of line is removed VarStringAddChar( newstring, ' ' ); VarStringAddChar( newstring, LookAhead ); newLineInString = 1; do_transition( S_STRING ); } default: VarStringAddChar( newstring, LookAhead ); do_transition( S_STRING ); }
/* delete a state object */ void delete_state(struct state *st) { struct connection *const c = st->st_connection; struct state *old_cur_state = cur_state == st? NULL : cur_state; openswan_log("deleting state #%lu (%s)", st->st_serialno, enum_show(&state_names, st->st_state)); /* * for most IKEv2 things, we may have further things to do after marking the state deleted, * so we do not actually free it here at all, but back in the main loop when all the work is done. */ if(st->st_ikev2) { /* child sa*/ if(st->st_clonedfrom != 0) { DBG(DBG_CONTROL, DBG_log("received request to delete child state")); if(st->st_state == STATE_CHILDSA_DEL) { DBG(DBG_CONTROL, DBG_log("now deleting the child state")); } else { /* Only send request if child sa is established * otherwise continue with deletion */ if(IS_CHILD_SA_ESTABLISHED(st)) { DBG(DBG_CONTROL, DBG_log("sending Child SA delete equest")); send_delete(st); change_state(st, STATE_CHILDSA_DEL); /* actual deletion when we receive peer response*/ return; } } } else { DBG(DBG_CONTROL, DBG_log("considering request to delete IKE parent state")); /* parent sa */ if(st->st_state == STATE_IKESA_DEL) { DBG(DBG_CONTROL, DBG_log("now deleting the IKE (or parent) state")); } else { /* Another check to verify if a secured * INFORMATIONAL exchange can be sent or not */ if(st->st_skey_ei.ptr && st->st_skey_ai.ptr && st->st_skey_er.ptr && st->st_skey_ar.ptr) { DBG(DBG_CONTROL, DBG_log("sending IKE SA delete request")); send_delete(st); change_state(st, STATE_IKESA_DEL); /* actual deletion when we receive peer response*/ return; } } } } /* If DPD is enabled on this state object, clear any pending events */ if(st->st_dpd_event != NULL) delete_dpd_event(st); /* if there is a suspended state transition, disconnect us */ if (st->st_suspended_md != NULL) { passert(st->st_suspended_md->st == st); DBG(DBG_CONTROL, DBG_log("disconnecting state #%lu from md", st->st_serialno)); st->st_suspended_md->st = NULL; } /* tell the other side of any IPSEC SAs that are going down */ if (IS_IPSEC_SA_ESTABLISHED(st->st_state) || IS_ISAKMP_SA_ESTABLISHED(st->st_state)) send_delete(st); delete_event(st); /* delete any pending timer event */ /* Ditch anything pending on ISAKMP SA being established. * Note: this must be done before the unhash_state to prevent * flush_pending_by_state inadvertently and prematurely * deleting our connection. */ flush_pending_by_state(st); /* if there is anything in the cryptographic queue, then remove this * state from it. */ delete_cryptographic_continuation(st); /* effectively, this deletes any ISAKMP SA that this state represents */ unhash_state(st); /* tell kernel to delete any IPSEC SA * ??? we ought to tell peer to delete IPSEC SAs */ if (IS_IPSEC_SA_ESTABLISHED(st->st_state) || IS_CHILD_SA_ESTABLISHED(st)) delete_ipsec_sa(st, FALSE); else if (IS_ONLY_INBOUND_IPSEC_SA_ESTABLISHED(st->st_state)) delete_ipsec_sa(st, TRUE); if (c->newest_ipsec_sa == st->st_serialno) c->newest_ipsec_sa = SOS_NOBODY; if (c->newest_isakmp_sa == st->st_serialno) c->newest_isakmp_sa = SOS_NOBODY; /* * fake a state change here while we are still associated with a * connection. Without this the state logging (when enabled) cannot * work out what happened. */ fake_state(st, STATE_UNDEFINED); st->st_connection = NULL; /* we might be about to free it */ cur_state = old_cur_state; /* without st_connection, st isn't complete */ connection_discard(c); change_state(st, STATE_UNDEFINED); release_whack(st); change_state(st, STATE_CHILDSA_DEL); }
int S9xMovieCreate (const char* filename, uint8 controllers_mask, uint8 opts, const wchar_t* metadata, int metadata_length) { #ifndef __FLASH__ FILE* fd; STREAM stream; int fn; if(controllers_mask==0) return WRONG_FORMAT; char movie_filename [_MAX_PATH]; #ifdef __WIN32__ _fullpath(movie_filename, filename, _MAX_PATH); #else strcpy(movie_filename, filename); #endif if(!(fd=fopen(movie_filename, "wb"))) return FILE_NOT_FOUND; const bool8 wasPaused = Settings.Paused; // stop current movie before opening change_state(MOVIE_STATE_NONE); if(metadata_length>MOVIE_MAX_METADATA) { metadata_length=MOVIE_MAX_METADATA; } Movie.MovieId=(uint32)time(NULL); Movie.RerecordCount=0; Movie.MaxFrame=0; Movie.MaxSample=0; Movie.SaveStateOffset=SMV_HEADER_SIZE+(sizeof(uint16)*metadata_length) + SMV_EXTRAROMINFO_SIZE; Movie.ControllerDataOffset=0; Movie.ControllersMask=controllers_mask; Movie.Opts=opts; Movie.SyncFlags=MOVIE_SYNC_DATA_EXISTS|MOVIE_SYNC_HASROMINFO; // store previous, in case we switch to playback later store_previous_settings(); // store settings in movie store_movie_settings(); // extra rom info Movie.ROMCRC32 = Memory.ROMCRC32; strncpy(Movie.ROMName, Memory.ROMName, 23); write_movie_header(fd, &Movie); // convert wchar_t metadata string/array to a uint16 array if(metadata_length>0) { uint8 meta_buf[MOVIE_MAX_METADATA * sizeof(uint16)]; for(int i=0; i<metadata_length; ++i) { uint16 c=(uint16)metadata[i]; meta_buf[i+i] =(uint8)(c&0xff); meta_buf[i+i+1]=(uint8)((c>>8)&0xff); } fwrite(meta_buf, sizeof(uint16), metadata_length, fd); assert(!ferror(fd)); }
int main() { int puzzle_number; while(scanf("%d",&puzzle_number)!=EOF) { for(int i=0;i<puzzle_number;++i) { int init_state[5][6]; for(int j=0;j<5;++j) for(int k=0;k<6;++k) scanf("%d",&init_state[j][k]); printf("PUZZLE #%d\n",i+1); int button_state[5][6]; memset(button_state[0],0,sizeof(button_state[0])); while(true) { // try all the statement of the first row, and change the statement of subsequent rows according to the first row. memcpy(current_state,init_state,sizeof(current_state)); for(int j=0;j<6;++j) { if(button_state[0][j]==1) change_state(0,j); } for(int j=1;j<5;++j) { for(int k=0;k<6;++k) { if(current_state[j-1][k]==1) { button_state[j][k]=1; change_state(j,k); } else button_state[j][k]=0; } } bool succeed=true; for(int j=0;j<6;++j) { if(current_state[4][j]==1) { succeed=false; break; } } if(succeed) { for(int j=0;j<5;++j) { for(int k=0;k<6;++k) printf("%d%c",button_state[j][k],k==5?'\n':' '); } break; } int m=5; while(m>=0) { if(++button_state[0][m]==1) break; else { button_state[0][m]=0; --m; } } if(m<0) break; } } } return 0; }