bool dispatch(Msg& msg) { PT_BEGIN() _gpio.init(); _gpio.setMode(Gpio::OUTPUT_PP); while (true) { timeout(_msecInterval); PT_YIELD_UNTIL( msg.is(_mqtt, SIG_CONNECTED) || msg.is(_mqtt, SIG_DISCONNECTED) || timeout()); switch (msg.signal) { case SIG_TICK: { _gpio.write(_isOn); _isOn = !_isOn; break; } case SIG_CONNECTED: { _msecInterval = 500; break; } case SIG_DISCONNECTED: { _msecInterval = 100; break; } default: { } } } PT_END() ; }
IROM bool LedBlink::dispatch(Msg& msg) { PT_BEGIN() PT_WAIT_UNTIL(msg.is(0, SIG_INIT)); init(); while (true) { timeout(_msecInterval); PT_YIELD_UNTIL( msg.is(_src, SIG_CONNECTED) || msg.is(_src, SIG_DISCONNECTED) || timeout()); switch (msg.signal()) { case SIG_TICK: { gpio16_output_set(_isOn); _isOn = !_isOn; break; } case SIG_CONNECTED: { _msecInterval = 1000; break; } case SIG_DISCONNECTED: { _msecInterval = 200; break; } default: { } } } PT_END(); return false; }
/** * The first protothread function. A protothread function must always * return an integer, but must NEVER explicitly return - returning is * performed inside the protothread statements. * * The protothread function is driven by the main loop further down in * the code. */ static PT_THREAD (protothread1(struct pt *pt)) { // mark beginning of thread PT_BEGIN(pt); /* We loop forever here. */ while(1) { //stop until thread 2 signals PT_SEM_WAIT(pt, &control_t1); // put a 2 microsec pulse on the debug pin with amplitude 3 PT_DEBUG_VALUE(3, 2) ; // toggle a port pin mPORTAToggleBits(BIT_0); // tell thread 2 to go PT_SEM_SIGNAL(pt, &control_t2); // Allow thread 3 to control blinking // thru command interface PT_YIELD_UNTIL(pt, cntl_blink) ; // This is a locally written macro using timer5 to count millisec // to program a yield time PT_YIELD_TIME_msec(wait_t1) ; // NEVER exit while } // END WHILE(1) // mark end the thread PT_END(pt); } // thread 1
char loop(struct rtimer* t, void *ptr){ PT_BEGIN(&pt); uint8_t packet[TIMESTAMP_BIT]; int packet_len = 0; sclock_init(&sclk, TYPE_CLOCK); ntp_init(&ntp, &sclk); static struct timestamp second; timestamp_init(&second); second.sec = 1; while(1) { sclock_etimer_set(&sclk, &et, &second); PT_YIELD_UNTIL(&pt,etimer_expired(&et)); leds_invert(LEDS_RED); #if REQUEST packet_len = ntp_make_request(&ntp, packet); packetbuf_copyfrom(packet, packet_len); abc_send(&abc); #endif } PT_END(&pt); }
/*---------------------------------------------------------------------*/ static PT_THREAD(recv_tcpthread(struct pt *pt)) { PT_BEGIN(pt); /* Read the header. */ PT_WAIT_UNTIL(pt, uip_newdata() && uip_datalen() > 0); if(uip_datalen() < sizeof(struct codeprop_tcphdr)) { PRINTF(("codeprop: header not found in first tcp segment\n")); uip_abort(); goto thread_done; } s.len = uip_htons(((struct codeprop_tcphdr *)uip_appdata)->len); s.addr = 0; uip_appdata += sizeof(struct codeprop_tcphdr); uip_len -= sizeof(struct codeprop_tcphdr); xmem_erase(XMEM_ERASE_UNIT_SIZE, EEPROMFS_ADDR_CODEPROP); /* Read the rest of the data. */ do { if(uip_len > 0) { xmem_pwrite(uip_appdata, uip_len, EEPROMFS_ADDR_CODEPROP + s.addr); s.addr += uip_len; } if(s.addr < s.len) { PT_YIELD_UNTIL(pt, uip_newdata()); } } while(s.addr < s.len); /* Kill old program. */ elfloader_unload(); /* Link, load, and start new program. */ int s; static char msg[30 + 10]; s = elfloader_load(EEPROMFS_ADDR_CODEPROP); if (s == ELFLOADER_OK) sprintf(msg, "ok\n"); else sprintf(msg, "err %d %s\n", s, elfloader_unknown); /* Return "ok" message. */ do { s = strlen(msg); uip_send(msg, s); PT_WAIT_UNTIL(pt, uip_acked() || uip_rexmit() || uip_closed()); } while(uip_rexmit()); /* Close the connection. */ uip_close(); thread_done:; PT_END(pt); }
//____________________________________________________________ // // //____________________________________________________________ // void Tcp::onReceive(Header hdr, Cbor& cbor) { PT_BEGIN() ; WIFI_DISCONNECTED: { while (true) { PT_YIELD_UNTIL(hdr.is(left(), self(), REPLY(CONNECT), ANY)); // LOGF("Tcp started. %x", this); goto CONNECTING; } } CONNECTING: { LOGF("CONNECTING"); while (true) { PT_YIELD(); if (hdr.is(self(), self(), REPLY(CONNECT), 0)) { right().tell(self(), REPLY(CONNECT), 0); _state=READY; goto CONNECTED; } else if (hdr.is(self(), self(), REPLY(DISCONNECT), 0)) { right().tell(self(), REPLY(DISCONNECT), 0); goto WIFI_DISCONNECTED; } } } CONNECTED: { LOGF("CONNECTED"); while (true) { setReceiveTimeout(5000); PT_YIELD(); if (hdr.is(self(), REPLY(DISCONNECT))) { // tcp link gone, callback was called right().tell(self(), REPLY(DISCONNECT), 0); goto CONNECTING; } else if (hdr.is(left(), REPLY(DISCONNECT))) { // wifi link gone right().tell(self(), REPLY(DISCONNECT), 0); goto WIFI_DISCONNECTED; } else if (hdr.is(right(), DISCONNECT)) { // wifi link gone disconnect(); goto CONNECTING; } else if (timeout()) { LOGF("%d:%d %d", _lastRxd + 5000, Sys::millis()); if ((_lastRxd + 5000) < Sys::millis()) { LOGF(" timeout - disconnect %X:%X", this, _conn); disconnect(); } } } } ; PT_END() }
/*---------------------------------------------------------------------------*/ static PT_THREAD(config_thread(struct pt *pt, process_event_t ev, process_data_t data)) { static struct etimer pushtimer; static int counter; PT_BEGIN(pt); while(1) { PT_WAIT_UNTIL(pt, ev == sensors_event && data == &button_sensor); beep(); leds_on(LEDS_YELLOW); etimer_set(&pushtimer, CLOCK_SECOND); for(counter = 0; !etimer_expired(&pushtimer); ++counter) { etimer_restart(&pushtimer); PT_YIELD_UNTIL(pt, (ev == sensors_event && data == &button_sensor) || etimer_expired(&pushtimer)); } place_id = counter; beep_quick(place_id); pingeron = 1; packet_count = 20; etimer_set(&etimer, CLOCK_SECOND / 2); leds_off(LEDS_YELLOW); leds_on(LEDS_RED); PT_WAIT_UNTIL(pt, packet_count == 0); pingeron = 0; leds_off(LEDS_RED); } PT_END(pt); }
// This thread is responsible for all the code not involving the TFT Display, it handled discharging and charging the capacitor and calculating the // capacitance of the capacitor. static PT_THREAD(protothread_cap(struct pt *pt)){ PT_BEGIN(pt); while(1){ // Discharge Capacitor // Set pin as output mPORTBSetPinsDigitalOut(BIT_3); // Drive RB3 low so capacitor can discharge into the pin mPORTBClearBits(BIT_3); // Yield until discharge is complete PT_YIELD_TIME_msec(2); // 2ms is given for the capacitor to discharge and for the display to update if needed Comp1Setup(); // Charge Capacitor // Set RB3 as an input to detect capacitor's current charge mPORTBSetPinsDigitalIn(BIT_3); // Set up the timer for charging the capcitor capTimerSetup(); // Set up the input capture to capture when the capacitor voltage reaches the reference voltage IC1setup(); // Yield while waiting for event from comparator PT_YIELD_UNTIL(pt, charged); CloseTimer2(); // Reset thread wait variable charged = 0; // Calculate capacitance in nF capacitance = (((charge_time*-1)/1000000)/(log(1-(VREF / VDD)) * RESISTOR))*1000000000; CMP1Close(); PT_YIELD_TIME_msec(20); } PT_END(pt); }
int DLGSM::PT_GSM_event_handler(struct pt *pt, char *ret) { char i = 0; static char iret; static struct pt child_pt; static int n = 0; PT_BEGIN(pt); PT_YIELD_UNTIL(pt, _gsmserial.available() > 1); // +CMTI: "SM",1 while (_gsmserial.available()) { PT_WAIT_THREAD(pt, PT_recvline(&child_pt, &iret, _gsm_buff, _gsm_buffsize, 1000, 1)); if (iret > 0) { // Call arriving, hang up? if (_gsm_buff[0] == 'R') { sprintf(_gsm_buff, "ATH\r\n"); PT_WAIT_THREAD(pt, PT_send_recv_confirm(&child_pt, &iret, _gsm_buff, "OK", 5000)); *ret = GSM_EVENT_STATUS_REQ; PT_EXIT(pt); } else if (_gsm_buff[0] == '+') { if (_gsm_buff[3] == 'T' && _gsm_buff[4] == 'I') { n = atoi((char *)(_gsm_buff+12)); PT_WAIT_THREAD(pt, PT_SMS_read(&child_pt,&iret,n)); iret = 0; PT_WAIT_THREAD(pt, PT_SMS_process(&child_pt, &iret, &curr_sms)); PT_WAIT_THREAD(pt, PT_SMS_delete(&child_pt, n)); *ret = iret; PT_EXIT(pt); } } else { GSM_process_line(NULL); } } } PT_END(pt); }
bool Usb::dispatch(Msg& msg) { uint8_t b; uint32_t i; uint32_t count; if ( msg.is(os,SIG_ERC,fd(),0)) { logger.level(Logger::WARN) << " error occured. Reconnecting."; logger.flush(); disconnect(); // connect(); return 0; } PT_BEGIN ( ); while(true) { PT_YIELD_UNTIL ( msg.is(this,SIG_CONNECTED)); while( true ) { PT_YIELD_UNTIL(msg.is(os,SIG_RXD,fd(),0)|| msg.is(os,SIG_ERC,fd(),0));//event->is(RXD) || event->is(FREE) || ( inBuffer.hasData() && (_isComplete==false)) ); if ( msg.is(os,SIG_RXD,fd(),0) && hasData()) { count =hasData(); for(i=0; i<count; i++) { b=read(); inBuffer.write(b); } logger.level(Logger::DEBUG)<< "recvd: " << inBuffer.size() << " bytes."; logger.flush(); while( inBuffer.hasData() ) { if ( _inBytes.Feed(inBuffer.read())) { Str l(256); _inBytes.toString(l); logger.level(Logger::DEBUG)<< "recv : " << l; logger.flush(); _inBytes.Decode(); if ( _inBytes.isGoodCrc() ) { _inBytes.RemoveCrc(); Str l(256); _inBytes.toString(l); logger.level(Logger::INFO)<<" recv clean : " <<l; logger.flush(); MqttIn* _mqttIn=new MqttIn(256); _inBytes.offset(0); while(_inBytes.hasData()) _mqttIn->Feed(_inBytes.read()); if ( _mqttIn->parse()) { MsgQueue::publish(this,SIG_RXD,_mqttIn->type(),_mqttIn); // _mqttIn will be deleted by msg process } else { Sys::warn(EINVAL, "MQTT"); delete _mqttIn; } } else { logger.level(Logger::WARN)<<"Bad CRC. Dropped packet. "; logger.flush(); _inBytes.clear(); // throw away bad data } _inBytes.clear(); } } } else if ( msg.is(os,SIG_ERC,fd(),0) ) { _inBytes.clear(); break; } PT_YIELD ( ); } } PT_END ( ); }
bool DWM1000_Anchor::dispatch(Msg& msg) { PT_BEGIN() PT_WAIT_UNTIL(msg.is(0, SIG_INIT)); init(); while (true) { WAIT_POLL: { dwt_setrxtimeout(0); /* Clear reception timeout to start next ranging process. */ dwt_rxenable(0); /* Activate reception immediately. */ // dwt_setinterrupt(DWT_INT_RFCG, 1); // enable RXD interrupt while (true) { /* Poll for reception of a frame or error/timeout. See NOTE 7 below. */ timeout(1000);/* This is the delay from the end of the frame transmission to the enable of the receiver, as programmed for the DW1000's wait for response feature. */ clearInterrupt(); PT_YIELD_UNTIL(timeout() || isInterruptDetected()); status_reg = _status_reg; LOG<< HEX << " status reg.:" << status_reg << " ,interrupts : " << interruptCount << FLUSH; status_reg = dwt_read32bitreg(SYS_STATUS_ID); LOG<< HEX << " IRQ pin : " << digitalRead(D2) << " status_reg DWM1000 " << status_reg << FLUSH;// PULL LOW if (status_reg & (SYS_STATUS_RXFCG | SYS_STATUS_ALL_RX_ERR)) break; } } ///____________________________________________________________________________ if (status_reg & SYS_STATUS_RXFCG) { LOG<< " $ "<<FLUSH; uint32 frame_len; dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_RXFCG); /* Clear good RX frame event in the DW1000 status register. */ /* A frame has been received, read it into the local buffer. */ frame_len = dwt_read32bitreg(RX_FINFO_ID) & RX_FINFO_RXFL_MASK_1023; if (frame_len <= RX_BUFFER_LEN) { dwt_readrxdata(rx_buffer, frame_len, 0); } /* Check that the frame is a poll sent by "DS TWR initiator" example. * As the sequence number field of the frame is not relevant, it is cleared to simplify the validation of the frame. */ rx_buffer[ALL_MSG_SN_IDX] = 0; if (memcmp(rx_buffer, rx_poll_msg, ALL_MSG_COMMON_LEN) == 0) { LOG<< " $$ "<<FLUSH; uint32 resp_tx_time; poll_rx_ts = get_rx_timestamp_u64(); /* Retrieve poll reception timestamp. */ /* Set send time for response. See NOTE 8 below. */ resp_tx_time = (poll_rx_ts + (POLL_RX_TO_RESP_TX_DLY_UUS * UUS_TO_DWT_TIME)) >> 8; dwt_setdelayedtrxtime(resp_tx_time); /* Set expected delay and timeout for final message reception. */ dwt_setrxaftertxdelay(RESP_TX_TO_FINAL_RX_DLY_UUS); dwt_setrxtimeout(FINAL_RX_TIMEOUT_UUS); /* Write and send the response message. See NOTE 9 below.*/ tx_resp_msg[ALL_MSG_SN_IDX] = frame_seq_nb; dwt_writetxdata(sizeof(tx_resp_msg), tx_resp_msg, 0); dwt_writetxfctrl(sizeof(tx_resp_msg), 0); dwt_starttx(DWT_START_TX_DELAYED | DWT_RESPONSE_EXPECTED); /* We assume that the transmission is achieved correctly, now poll for reception of expected "final" frame or error/timeout. * See NOTE 7 below. */ // while (true) { /* Poll for reception of a frame or error/timeout. See NOTE 7 below. */ timeout(10); dwt_setinterrupt(DWT_INT_RFCG, 1);// enable clearInterrupt(); // PT_YIELD_UNTIL(timeout() || isInterruptDetected()); status_reg = dwt_read32bitreg(SYS_STATUS_ID); // status_reg = _status_reg; LOG<< HEX << " status reg2:" << status_reg << FLUSH; // if (status_reg & (SYS_STATUS_RXFCG | SYS_STATUS_ALL_RX_ERR)) // break; // } // while (!((status_reg = dwt_read32bitreg(SYS_STATUS_ID)) & (SYS_STATUS_RXFCG | SYS_STATUS_ALL_RX_ERR))) // { }; /* Increment frame sequence number after transmission of the response message (modulo 256). */ frame_seq_nb++; if (status_reg & SYS_STATUS_RXFCG) { LOG<< " $$$ "<<FLUSH; /* Clear good RX frame event and TX frame sent in the DW1000 status register. */ dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_RXFCG | SYS_STATUS_TXFRS); /* A frame has been received, read it into the local buffer. */ frame_len = dwt_read32bitreg( RX_FINFO_ID) & RX_FINFO_RXFLEN_MASK; if (frame_len <= RX_BUF_LEN) { dwt_readrxdata(rx_buffer, frame_len, 0); } /* Check that the frame is a final message sent by "DS TWR initiator" example. * As the sequence number field of the frame is not used in this example, it can be zeroed to ease the validation of the frame. */ rx_buffer[ALL_MSG_SN_IDX] = 0; if (memcmp(rx_buffer, rx_final_msg, ALL_MSG_COMMON_LEN) == 0) { uint32 poll_tx_ts, resp_rx_ts, final_tx_ts; uint32 poll_rx_ts_32, resp_tx_ts_32, final_rx_ts_32; double Ra, Rb, Da, Db; int64 tof_dtu; /* Retrieve response transmission and final reception timestamps. */ resp_tx_ts = get_tx_timestamp_u64(); final_rx_ts = get_rx_timestamp_u64(); /* Get timestamps embedded in the final message. */ final_msg_get_ts(&rx_buffer[FINAL_MSG_POLL_TX_TS_IDX], &poll_tx_ts); final_msg_get_ts(&rx_buffer[FINAL_MSG_RESP_RX_TS_IDX], &resp_rx_ts); final_msg_get_ts(&rx_buffer[FINAL_MSG_FINAL_TX_TS_IDX], &final_tx_ts); /* Compute time of flight. 32-bit subtractions give correct answers even if clock has wrapped. See NOTE 10 below. */ poll_rx_ts_32 = (uint32) poll_rx_ts; resp_tx_ts_32 = (uint32) resp_tx_ts; final_rx_ts_32 = (uint32) final_rx_ts; Ra = (double) (resp_rx_ts - poll_tx_ts); Rb = (double) (final_rx_ts_32 - resp_tx_ts_32); Da = (double) (final_tx_ts - resp_rx_ts); Db = (double) (resp_tx_ts_32 - poll_rx_ts_32); tof_dtu = (int64) ((Ra * Rb - Da * Db) / (Ra + Rb + Da + Db)); tof = tof_dtu * DWT_TIME_UNITS; distance = tof * SPEED_OF_LIGHT; /* Display computed distance on LCD. */ // char dist_str[20]; // sprintf(dist_str,"%3.2f", distance); // lcd_display_str(dist_str); LOG<< " distance : " << (float)distance << "m. " << FLUSH; } } else { /* Clear RX error events in the DW1000 status register. */ dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_RX_ERR); } } } else {
/*---------------------------------------------------------------------------*/ static PT_THREAD(handle_dhcp(void)) { PT_BEGIN(&s.pt); /* try_again:*/ s.state = STATE_SENDING; s.ticks = CLOCK_SECOND; do { send_discover(); timer_set(&s.timer, s.ticks); PT_YIELD_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer)); if(uip_newdata() && parse_msg() == DHCPOFFER) { s.state = STATE_OFFER_RECEIVED; break; } if(s.ticks < CLOCK_SECOND * 60) { s.ticks *= 2; } } while(s.state != STATE_OFFER_RECEIVED); s.ticks = CLOCK_SECOND; do { send_request(); timer_set(&s.timer, s.ticks); PT_YIELD_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer)); if(uip_newdata() && parse_msg() == DHCPACK) { s.state = STATE_CONFIG_RECEIVED; break; } if(s.ticks <= CLOCK_SECOND * 10) { s.ticks += CLOCK_SECOND; } else { PT_RESTART(&s.pt); } } while(s.state != STATE_CONFIG_RECEIVED); #if 0 printf("Got IP address %d.%d.%d.%d\n", uip_ipaddr1(s.ipaddr), uip_ipaddr2(s.ipaddr), uip_ipaddr3(s.ipaddr), uip_ipaddr4(s.ipaddr)); printf("Got netmask %d.%d.%d.%d\n", uip_ipaddr1(s.netmask), uip_ipaddr2(s.netmask), uip_ipaddr3(s.netmask), uip_ipaddr4(s.netmask)); printf("Got DNS server %d.%d.%d.%d\n", uip_ipaddr1(s.dnsaddr), uip_ipaddr2(s.dnsaddr), uip_ipaddr3(s.dnsaddr), uip_ipaddr4(s.dnsaddr)); printf("Got default router %d.%d.%d.%d\n", uip_ipaddr1(s.default_router), uip_ipaddr2(s.default_router), uip_ipaddr3(s.default_router), uip_ipaddr4(s.default_router)); printf("Lease expires in %ld seconds\n", ntohs(s.lease_time[0])*65536ul + ntohs(s.lease_time[1])); #endif dhcpc_configured(&s); /* timer_stop(&s.timer);*/ /* * PT_END restarts the thread so we do this instead. Eventually we * should reacquire expired leases here. */ while(1) { PT_YIELD(&s.pt); } PT_END(&s.pt); }
/*---------------------------------------------------------------------------*/ static PT_THREAD(handle_dhcp(void)) { PT_BEGIN(&s.pt); #if defined PORT_APP_MAPPER dhcpc_running = 1; #endif if (s.state == STATE_RENEW) goto send_request_section; /* try_again:*/ s.state = STATE_SENDING; s.ticks = CLOCK_SECOND; //sendString("\r\ndhcpc handle dhcp passed: STATE_SENDING"); do { send_discover(); timer_set(&s.timer, s.ticks); // NOTE: fixed as per http://www.mail-archive.com/[email protected]/msg00003.html PT_YIELD_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer)); //sendString("Just got something\n\r"); if(uip_newdata()) { //sendString("Data\n\r"); if (parse_msg() == DHCPOFFER) { s.state = STATE_OFFER_RECEIVED; break; } } else { //sendString("Timeout\n\r"); if(s.ticks < CLOCK_SECOND * 60) { s.ticks *= 2; } else { s.ticks = CLOCK_SECOND; } } } while(s.state != STATE_OFFER_RECEIVED); //sendString("\r\ndhcpc handle dhcp passed: STATE_OFFER_RECEIVED"); s.ticks = CLOCK_SECOND; send_request_section: do { send_request(); timer_set(&s.timer, s.ticks); // NOTE: fixed as per http://www.mail-archive.com/[email protected]/msg00003.html PT_YIELD_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer)); if(uip_newdata()) { msg_type = parse_msg(); if (msg_type == DHCPACK) { s.state = STATE_CONFIG_RECEIVED; break; } else if (msg_type == DHCPNAK) { s.state = STATE_FAIL; goto close_and_clean_up; } } else { if(s.ticks <= CLOCK_SECOND * 10) { s.ticks += CLOCK_SECOND; } else { PT_RESTART(&s.pt); //sendString("\r\ndhcpc handle RESTARTING!"); } } } while(s.state != STATE_CONFIG_RECEIVED); //sendString("\r\ndhcpc handle dhcp passed: STATE_CONFIG_RECEIVED"); #if DEBUG_SERIAL printf_P(PSTR("Got IP address %d.%d.%d.%d\r\n"), uip_ipaddr1(s.ipaddr), uip_ipaddr2(s.ipaddr), uip_ipaddr3(s.ipaddr), uip_ipaddr4(s.ipaddr)); printf_P(PSTR("Got netmask %d.%d.%d.%d\r\n"), uip_ipaddr1(s.netmask), uip_ipaddr2(s.netmask), uip_ipaddr3(s.netmask), uip_ipaddr4(s.netmask)); printf_P(PSTR("Got DNS server %d.%d.%d.%d\r\n"), uip_ipaddr1(s.dnsaddr), uip_ipaddr2(s.dnsaddr), uip_ipaddr3(s.dnsaddr), uip_ipaddr4(s.dnsaddr)); printf_P(PSTR("Got default router %d.%d.%d.%d\r\n"), uip_ipaddr1(s.default_router), uip_ipaddr2(s.default_router), uip_ipaddr3(s.default_router), uip_ipaddr4(s.default_router)); printf_P(PSTR("Lease expires in %ld seconds\r\n"), ntohs(s.lease_time[0])*65536ul + ntohs(s.lease_time[1])); #endif dhcpc_configured(&s); /* timer_stop(&s.timer);*/ /* * PT_END restarts the thread so we do this instead. Eventually we * should reacquire expired leases here. */ /* while(1) { PT_YIELD(&s.pt); } */ close_and_clean_up: #if defined PORT_APP_MAPPER dhcpc_running = 0; #endif // all done with the connection, clean up uip_udp_remove(s.conn); s.conn = NULL; //sendString("\r\ndhcpc handle dhcp passed: END"); PT_END(&s.pt); }
/*---------------------------------------------------------------------------*/ static PT_THREAD(handle_dhcp(process_event_t ev, void *data)) { clock_time_t ticks; PT_BEGIN(&s.pt); // printf("handle_dhcp\n"); init: // printf("init\n"); xid++; s.state = STATE_SENDING; s.ticks = CLOCK_SECOND * 4; while(1) { while(ev != tcpip_event) { tcpip_poll_udp(s.conn); PT_YIELD(&s.pt); } send_discover(); etimer_set(&s.etimer, s.ticks); do { PT_YIELD(&s.pt); // printf("tcpip_event:%d ev:%d uip_newdata():%d msg_for_me():%d\n",tcpip_event, ev,uip_newdata(),msg_for_me()); if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPOFFER) { // printf("here2\n"); parse_msg(); s.state = STATE_OFFER_RECEIVED; goto selecting; } } while(!etimer_expired(&s.etimer)); if(s.ticks < CLOCK_SECOND * 60) { s.ticks *= 2; } } selecting: // printf("selecting\n"); xid++; s.ticks = CLOCK_SECOND; do { while(ev != tcpip_event) { tcpip_poll_udp(s.conn); PT_YIELD(&s.pt); } send_request(); etimer_set(&s.etimer, s.ticks); do { PT_YIELD(&s.pt); if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPACK) { parse_msg(); s.state = STATE_CONFIG_RECEIVED; goto bound; } } while (!etimer_expired(&s.etimer)); if(s.ticks <= CLOCK_SECOND * 10) { s.ticks += CLOCK_SECOND; } else { goto init; } } while(s.state != STATE_CONFIG_RECEIVED); bound: #if 0 printf("Got IP address %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.ipaddr)); printf("Got netmask %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.netmask)); printf("Got DNS server %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.dnsaddr)); printf("Got default router %d.%d.%d.%d\n", uip_ipaddr_to_quad(&s.default_router)); printf("Lease expires in %ld seconds\n", uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1])); #endif // printf("bound\n"); ip64_dhcpc_configured(&s); #define MAX_TICKS (~((clock_time_t)0) / 2) #define MAX_TICKS32 (~((uint32_t)0)) #define IMIN(a, b) ((a) < (b) ? (a) : (b)) if((uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]))*CLOCK_SECOND/2 <= MAX_TICKS32) { s.ticks = (uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]) )*CLOCK_SECOND/2; } else { s.ticks = MAX_TICKS32; } while(s.ticks > 0) { ticks = IMIN(s.ticks, MAX_TICKS); s.ticks -= ticks; etimer_set(&s.etimer, ticks); PT_YIELD_UNTIL(&s.pt, etimer_expired(&s.etimer)); } if((uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]))*CLOCK_SECOND/2 <= MAX_TICKS32) { s.ticks = (uip_ntohs(s.lease_time[0])*65536ul + uip_ntohs(s.lease_time[1]) )*CLOCK_SECOND/2; } else { s.ticks = MAX_TICKS32; } /* renewing: */ xid++; do { while(ev != tcpip_event) { tcpip_poll_udp(s.conn); PT_YIELD(&s.pt); } send_request(); ticks = IMIN(s.ticks / 2, MAX_TICKS); s.ticks -= ticks; etimer_set(&s.etimer, ticks); do { PT_YIELD(&s.pt); if(ev == tcpip_event && uip_newdata() && msg_for_me() == DHCPACK) { parse_msg(); goto bound; } } while(!etimer_expired(&s.etimer)); } while(s.ticks >= CLOCK_SECOND*3); /* rebinding: */ /* lease_expired: */ ip64_dhcpc_unconfigured(&s); goto init; PT_END(&s.pt); }
/*---------------------------------------------------------------------*/ static PT_THREAD(recv_tcpthread(struct pt *pt)) { u8_t *dataptr; struct codeprop_tcphdr *th; int datalen = uip_datalen(); PT_BEGIN(pt); while(1) { PT_WAIT_UNTIL(pt, uip_connected()); codeprop_exit_program(); s.state = STATE_RECEIVING_TCPDATA; s.addr = 0; s.count = 0; /* process_post(PROCESS_BROADCAST, codeprop_event_quit, (process_data_t)NULL); */ /* Read the header. */ PT_WAIT_UNTIL(pt, uip_newdata() && uip_datalen() > 0); dataptr = uip_appdata; if(uip_datalen() < sizeof(struct codeprop_tcphdr)) { PRINTF(("codeprop: header not found in first tcp segment\n")); uip_abort(); } th = (struct codeprop_tcphdr *)uip_appdata; s.len = htons(th->len); s.addr = 0; uip_appdata += sizeof(struct codeprop_tcphdr); datalen -= sizeof(struct codeprop_tcphdr); /* Read the rest of the data. */ do { if(datalen > 0) { /* printf("Got %d bytes\n", uip_len);*/ /* eeprom_write(EEPROMFS_ADDR_CODEPROP + s.addr, uip_appdata, uip_datalen());*/ cfs_seek(fd, s.addr, CFS_SEEK_SET); cfs_write(fd, uip_appdata, uip_datalen()); s.addr += datalen; } if(s.addr < s.len) { PT_YIELD_UNTIL(pt, uip_newdata()); } } while(s.addr < s.len); #if 1 { static int err; err = codeprop_start_program(); /* Print out the "OK"/error message. */ do { uip_send(err_msgs[err], strlen(err_msgs[err])); PT_WAIT_UNTIL(pt, uip_acked() || uip_rexmit() || uip_closed()); } while(uip_rexmit()); /* Close the connection. */ uip_close(); } #endif ++s.id; s.state = STATE_SENDING_UDPDATA; tcpip_poll_udp(udp_conn); PT_WAIT_UNTIL(pt, s.state != STATE_SENDING_UDPDATA); /* printf("recv_tcpthread: unblocked\n");*/ } PT_END(pt); }
/*---------------------------------------------------------------------*/ static PT_THREAD(recv_udpthread(struct pt *pt)) { int len; struct codeprop_udphdr *uh = (struct codeprop_udphdr *)uip_appdata; /* if(uip_newdata()) { PRINTF(("recv_udpthread: id %d uh->id %d\n", s.id, htons(uh->id))); }*/ PT_BEGIN(pt); while(1) { do { PT_WAIT_UNTIL(pt, uip_newdata() && uh->type == HTONS(TYPE_DATA) && htons(uh->id) > s.id); if(htons(uh->addr) != 0) { s.addr = 0; send_nack(uh, 0); } } while(htons(uh->addr) != 0); /* leds_on(LEDS_YELLOW); beep_down(10000);*/ s.addr = 0; s.id = htons(uh->id); s.len = htons(uh->len); timer_set(&s.timer, CONNECTION_TIMEOUT); /* process_post(PROCESS_BROADCAST, codeprop_event_quit, (process_data_t)NULL); */ while(s.addr < s.len) { if(htons(uh->addr) == s.addr) { /* leds_blink();*/ len = uip_datalen() - UDPHEADERSIZE; if(len > 0) { /* eeprom_write(EEPROMFS_ADDR_CODEPROP + s.addr, &uh->data[0], len);*/ cfs_seek(fd, s.addr, CFS_SEEK_SET); cfs_write(fd, &uh->data[0], len); /* beep();*/ PRINTF(("Saved %d bytes at address %d, %d bytes left\n", uip_datalen() - UDPHEADERSIZE, s.addr, s.len - s.addr)); s.addr += len; } } else if(htons(uh->addr) > s.addr) { PRINTF(("sending nack since 0x%x != 0x%x\n", htons(uh->addr), s.addr)); send_nack(uh, s.addr); } if(s.addr < s.len) { /* timer_set(&s.nacktimer, NACK_TIMEOUT);*/ do { timer_set(&s.nacktimer, HIT_NACK_TIMEOUT); PT_YIELD_UNTIL(pt, timer_expired(&s.nacktimer) || (uip_newdata() && uh->type == HTONS(TYPE_DATA) && htons(uh->id) == s.id)); if(timer_expired(&s.nacktimer)) { send_nack(uh, s.addr); } } while(timer_expired(&s.nacktimer)); } } /* leds_off(LEDS_YELLOW); beep_quick(2);*/ /* printf("Received entire bunary over udr\n");*/ codeprop_start_program(); PT_EXIT(pt); } PT_END(pt); }
bool DWM1000_Tag::dispatch(Msg& msg) { PT_BEGIN() PT_WAIT_UNTIL(msg.is(0, SIG_INIT)); init(); POLL_SEND: { while (true) { timeout(1000); // delay between POLL PT_YIELD_UNTIL(timeout()); /* Write frame data to DW1000 and prepare transmission. See NOTE 7 below. */ tx_poll_msg[ALL_MSG_SN_IDX] = frame_seq_nb; dwt_writetxdata(sizeof(tx_poll_msg), tx_poll_msg, 0); dwt_writetxfctrl(sizeof(tx_poll_msg), 0); /* Start transmission, indicating that a response is expected so that reception is enabled automatically after the frame is sent and the delay * set by dwt_setrxaftertxdelay() has elapsed. */ LOG<< " Start TXF " << FLUSH; dwt_starttx(DWT_START_TX_IMMEDIATE | DWT_RESPONSE_EXPECTED);// SEND POLL MSG dwt_setinterrupt(DWT_INT_TFRS, 0); dwt_setinterrupt(DWT_INT_RFCG, 1); // enable clearInterrupt(); _timeoutCounter = 0; /* We assume that the transmission is achieved correctly, poll for reception of a frame or error/timeout. See NOTE 8 below. */ timeout(10); PT_YIELD_UNTIL(timeout() || isInterruptDetected()); // WAIT RESP MSG if (isInterruptDetected()) LOG<< " INTERRUPT DETECTED " << FLUSH; status_reg = dwt_read32bitreg(SYS_STATUS_ID); LOG<< HEX <<" SYS_STATUS " << status_reg << FLUSH; if (status_reg == 0xDEADDEAD) { init(); } else if (status_reg & SYS_STATUS_RXFCG) goto RESP_RECEIVED; else if (status_reg & SYS_STATUS_ALL_RX_ERR) { if (status_reg & SYS_STATUS_RXRFTO) INFO(" RX Timeout"); else INFO(" RX error "); dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_ALL_RX_ERR); /* Clear RX error events in the DW1000 status register. */ } } } RESP_RECEIVED: { LOG<< " Received " <<FLUSH; frame_seq_nb++; /* Increment frame sequence number after transmission of the poll message (modulo 256). */ uint32 frame_len; /* Clear good RX frame event and TX frame sent in the DW1000 status register. */ dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_RXFCG | SYS_STATUS_TXFRS); /* A frame has been received, read iCHANGEt into the local buffer. */ frame_len = dwt_read32bitreg(RX_FINFO_ID) & RX_FINFO_RXFLEN_MASK; if (frame_len <= RX_BUF_LEN) { dwt_readrxdata(rx_buffer, frame_len, 0); } /* Check that the frame is the expected response from the companion "DS TWR responder" example. * As the sequence number field of the frame is not relevant, it is cleared to simplify the validation of the frame. */ rx_buffer[ALL_MSG_SN_IDX] = 0; if (memcmp(rx_buffer, rx_resp_msg, ALL_MSG_COMMON_LEN) == 0) { // CHECK RESP MSG uint32 final_tx_time; /* Retrieve poll transmission and response reception timestamp. */ poll_tx_ts = get_tx_timestamp_u64(); resp_rx_ts = get_rx_timestamp_u64(); /* Compute final message transmission time. See NOTE 9 below. */ final_tx_time = (resp_rx_ts + (RESP_RX_TO_FINAL_TX_DLY_UUS * UUS_TO_DWT_TIME)) >> 8; dwt_setdelayedtrxtime(final_tx_time); /* Final TX timestamp is the transmission time we programmed plus the TX antenna delay. */ final_tx_ts = (((uint64) (final_tx_time & 0xFFFFFFFE)) << 8) + TX_ANT_DLY; /* Write all timestamps in the final message. See NOTE 10 below. */ final_msg_set_ts(&tx_final_msg[FINAL_MSG_POLL_TX_TS_IDX], poll_tx_ts); final_msg_set_ts(&tx_final_msg[FINAL_MSG_RESP_RX_TS_IDX], resp_rx_ts); final_msg_set_ts(&tx_final_msg[FINAL_MSG_FINAL_TX_TS_IDX], final_tx_ts); /* Write and send final message. See NOTE 7 below. */ tx_final_msg[ALL_MSG_SN_IDX] = frame_seq_nb; dwt_writetxdata(sizeof(tx_final_msg), tx_final_msg, 0); dwt_writetxfctrl(sizeof(tx_final_msg), 0); dwt_starttx(DWT_START_TX_DELAYED); // SEND FINAL MSG /* Poll DW1000 until TX frame sent event set. See NOTE 8 below. */ timeout(10); PT_YIELD_UNTIL((dwt_read32bitreg(SYS_STATUS_ID) & SYS_STATUS_TXFRS) || timeout());; /* Clear TXFRS event. */ dwt_write32bitreg(SYS_STATUS_ID, SYS_STATUS_TXFRS); /* Increment frame sequence number after transmission of the final message (modulo 256). */ frame_seq_nb++; } else {
bool Wifi::dispatch(Msg& msg) { // INFO("line : %d ",_ptLine); // INFO("msg : %d:%d",msg.src(),msg.signal()); PT_BEGIN(); INIT : { PT_WAIT_UNTIL(msg.is(0,SIG_INIT)); struct station_config stationConf; INFO("WIFI_INIT"); if ( wifi_set_opmode(STATION_MODE) ){ ; // STATIONAP_MODE was STATION_MODE INFO("line : %d",__LINE__); if ( wifi_set_phy_mode(PHY_MODE_11B)) { os_memset(&stationConf, 0, sizeof(struct station_config)); ets_strncpy((char*)stationConf.ssid,_ssid,sizeof(stationConf.ssid)); ets_strncpy((char*)stationConf.password,_pswd,sizeof(stationConf.password)); stationConf.bssid_set=0; INFO("line : %d",__LINE__); if ( wifi_station_set_config(&stationConf) ){ if ( wifi_station_connect() ){ INFO("line : %d",__LINE__); goto DISCONNECTED;// wifi_station_set_auto_connect(TRUE); } } } } // wifi_station_set_auto_connect(FALSE); INFO(" WIFI INIT failed , retrying... "); goto INIT; }; DISCONNECTED: { while(true) { timeout(1000); PT_YIELD_UNTIL(timeout()); struct ip_info ipConfig; wifi_get_ip_info(STATION_IF, &ipConfig); wifiStatus = wifi_station_get_connect_status(); if ( wifi_station_get_connect_status()== STATION_NO_AP_FOUND || wifi_station_get_connect_status()==STATION_WRONG_PASSWORD || wifi_station_get_connect_status()==STATION_CONNECT_FAIL) { INFO(" NOT CONNECTED "); wifi_station_connect(); } else if (wifiStatus == STATION_GOT_IP && ipConfig.ip.addr != 0) { _connections++; union { uint32_t addr; uint8_t ip[4]; } v; v.addr = ipConfig.ip.addr; INFO(" IP Address : %d.%d.%d.%d ",v.ip[0],v.ip[1],v.ip[2],v.ip[3]); INFO(" CONNECTED "); Msg::publish(this,SIG_CONNECTED); _connected=true; timeout(2000); goto CONNECTED; } else { INFO(" STATION_IDLE "); } timeout(500); } }; CONNECTED : { while(true) { PT_YIELD_UNTIL(timeout()); struct ip_info ipConfig; wifi_get_ip_info(STATION_IF, &ipConfig); wifiStatus = wifi_station_get_connect_status(); if (wifiStatus != STATION_GOT_IP ) { Msg::publish(this,SIG_DISCONNECTED); timeout(500); _connected=false; goto DISCONNECTED; } timeout(2000); } }; PT_END(); }
/*---------------------------------------------------------------------*/ static PT_THREAD(recv_tcpthread(struct pt *pt)) { PT_BEGIN(pt); /* Read the header. */ PT_WAIT_UNTIL(pt, uip_newdata() && uip_datalen() > 0); if(uip_datalen() < sizeof(struct codeprop_tcphdr)) { PRINTF(("codeprop: header not found in first tcp segment\n")); uip_abort(); goto thread_done; } /* Kill old program. */ rudolph0_stop(&rudolph0); /* elfloader_unload();*/ s.len = htons(((struct codeprop_tcphdr *)uip_appdata)->len); s.addr = 0; uip_appdata += sizeof(struct codeprop_tcphdr); uip_len -= sizeof(struct codeprop_tcphdr); s.fd = cfs_open("codeprop.out", CFS_WRITE); cfs_close(s.fd); /* xmem_erase(XMEM_ERASE_UNIT_SIZE, EEPROMFS_ADDR_CODEPROP);*/ /* Read the rest of the data. */ do { leds_toggle(LEDS_RED); if(uip_len > 0) { s.fd = cfs_open("codeprop.out", CFS_WRITE + CFS_APPEND); cfs_seek(s.fd, s.addr, CFS_SEEK_SET); /* xmem_pwrite(uip_appdata, uip_len, EEPROMFS_ADDR_CODEPROP + s.addr);*/ cfs_write(s.fd, uip_appdata, uip_len); cfs_close(s.fd); PRINTF("Wrote %d bytes to file\n", uip_len); s.addr += uip_len; } if(s.addr < s.len) { PT_YIELD_UNTIL(pt, uip_newdata()); } } while(s.addr < s.len); leds_off(LEDS_RED); #if DEBUG { int i, fd, j; printf("Contents of file:\n"); fd = cfs_open("codeprop.out", CFS_READ); j = 0; printf("\n0x%04x: ", 0); for(i = 0; i < s.len; ++i) { unsigned char byte; cfs_read(fd, &byte, 1); printf("0x%02x, ", byte); ++j; if(j == 8) { printf("\n0x%04x: ", i + 1); j = 0; } clock_delay(400); } cfs_close(fd); } #endif int ret; ret = start_program(); #if CONTIKI_TARGET_NETSIM rudolph0_send(&rudolph0, CLOCK_SECOND / 4); #else /* CONTIKI_TARGET_NETSIM */ if(ret == ELFLOADER_OK) { /* Propagate program. */ rudolph0_send(&rudolph0, CLOCK_SECOND / 4); } #endif /* CONTIKI_TARGET_NETSIM */ /* Return "ok" message. */ do { ret = strlen(msg); uip_send(msg, ret); PT_WAIT_UNTIL(pt, uip_acked() || uip_rexmit() || uip_closed()); } while(uip_rexmit()); /* Close the connection. */ uip_close(); thread_done:; PT_END(pt); }
static PT_THREAD(recv_tcpthread(struct pt *pt)) { struct codeprop_tcphdr *th; int datalen = uip_datalen(); PT_BEGIN(pt); while(1) { PT_WAIT_UNTIL(pt, uip_connected()); codeprop_exit_program(); s.state = STATE_RECEIVING_TCPDATA; s.addr = 0; s.count = 0; /* Read the header. */ PT_WAIT_UNTIL(pt, uip_newdata() && uip_datalen() > 0); if(uip_datalen() < CODEPROP_TCPHDR_SIZE) { PRINTF(("codeprop: header not found in first tcp segment\n")); uip_abort(); } th = (struct codeprop_tcphdr *)uip_appdata; s.len = uip_htons(th->len); s.addr = 0; uip_appdata += CODEPROP_TCPHDR_SIZE; datalen -= CODEPROP_TCPHDR_SIZE; /* Read the rest of the data. */ do { if(datalen > 0) { /* printf("Got %d bytes\n", datalen); */ if (cfs_seek(fd, s.addr, CFS_SEEK_SET) != s.addr) { PRINTF(("codeprop: seek in buffer file failed\n")); uip_abort(); } if (cfs_write(fd, uip_appdata, datalen) != datalen) { PRINTF(("codeprop: write to buffer file failed\n")); uip_abort(); } s.addr += datalen; } if(s.addr < s.len) { PT_YIELD_UNTIL(pt, uip_newdata()); } } while(s.addr < s.len); #if 1 { static int err; err = codeprop_start_program(); /* Print out the "OK"/error message. */ do { if (err >= 0 && err < sizeof(err_msgs)/sizeof(char*)) { uip_send(err_msgs[err], strlen(err_msgs[err])); } else { uip_send("Unknown error\r\n", 15); } PT_WAIT_UNTIL(pt, uip_acked() || uip_rexmit() || uip_closed()); } while(uip_rexmit()); /* Close the connection. */ uip_close(); } #endif ++s.id; s.state = STATE_SENDING_UDPDATA; tcpip_poll_udp(udp_conn); PT_WAIT_UNTIL(pt, s.state != STATE_SENDING_UDPDATA); /* printf("recv_tcpthread: unblocked\n");*/ } PT_END(pt); }