static void dtls_handler(process_event_t ev, process_data_t data){ if (ev == dtls_event){ if (dtls_rehandshake()){ etimer_stop(&et); } else if (dtls_connected()){ connection = (Connection*)data; etimer_set(&et, SEND_INTERVAL); DTLS_Write(connection, hello_msg, 11); } else if (dtls_newdata()){ dtls_appdata[dtls_applen] = 0; } } else if (ev == PROCESS_EVENT_TIMER){ if (etimer_expired(&et)){ DTLS_Write(connection, hello_msg, 11); etimer_reset(&et); } if (etimer_expired(&et2)){ DTLS_Close(connection); etimer_stop(&et); etimer_stop(&et2); } } }
PROCESS_THREAD(blinker_process, ev, data) { static struct etimer etimer, pir_timer, vib_timer; static int on = 0; PROCESS_EXITHANDLER(goto exit); PROCESS_BEGIN(); etimer_stop(&pir_timer); etimer_stop(&vib_timer); etimer_set(&etimer, CLOCK_SECOND * 4); button_sensor.configure(SENSORS_ACTIVE, 1); vib_sensor.configure(SENSORS_ACTIVE, 1); pir_sensor.configure(SENSORS_ACTIVE, 1); while(1) { PROCESS_WAIT_EVENT(); if(ev == sensors_event) { if(data == &vib_sensor) { if(etimer_expired(&vib_timer)) { leds_on(LEDS_RED); etimer_set(&vib_timer, CLOCK_SECOND); } else { leds_off(LEDS_RED); etimer_stop(&vib_timer); } beep(); } else if(data == &pir_sensor) { leds_on(LEDS_YELLOW); etimer_set(&pir_timer, CLOCK_SECOND); } else if(data == &button_sensor) { beep_beep(100); } } else if(ev == PROCESS_EVENT_TIMER) { if(data == &etimer) { if(on) { etimer_set(&etimer, CLOCK_SECOND * 4); leds_off(LEDS_GREEN); } else { etimer_set(&etimer, CLOCK_SECOND / 2); leds_on(LEDS_GREEN); } on = !on; } else if(data == &pir_timer) { leds_off(LEDS_YELLOW); } else if(data == &vib_timer) { leds_off(LEDS_RED); } } } exit: leds_off(LEDS_ALL); PROCESS_END(); }
/*---------------------------------------------------------------------------*/ static void removesocket(struct http_socket *s) { etimer_stop(&s->timeout_timer); s->timeout_timer_started = 0; list_remove(socketlist, s); }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(rpl_root_process, ev, data) { static struct etimer et; PROCESS_BEGIN(); PRINTF("Multicast Engine: '%s'\n", UIP_MCAST6.name); NETSTACK_MAC.off(1); set_own_addresses(); prepare_mcast(); etimer_set(&et, START_DELAY * CLOCK_SECOND); while(1) { PROCESS_YIELD(); if(etimer_expired(&et)) { if(seq_id == ITERATIONS) { etimer_stop(&et); } else { multicast_send(); etimer_set(&et, SEND_INTERVAL); } } } PROCESS_END(); }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(otau_client_process, ev, data) { static struct etimer server_timer; uip_ip6addr_t *srv_addr; PROCESS_BEGIN(); servreg_hack_init(); set_global_address(); ota_mgr_init(); simple_udp_register(&unicast_connection, UDP_PORT, NULL, UDP_PORT, receiver); etimer_set(&server_timer, SEND_INTERVAL); while(1) { PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&server_timer)); srv_addr = servreg_hack_lookup(SERVICE_ID); if(srv_addr != NULL) { printf("Server address configured\r\n"); server_configured =1; configure_server_details(srv_addr); memcpy((uint8_t *)&(global_server_addr.u16[4]),&(srv_addr->u16[4]),NATIVE_ADDR_SIZE); //uip_create_linklocal_allnodes_mcast(srv_addr); etimer_stop(&server_timer); } else { etimer_reset(&server_timer); printf("server not found\r\n"); } } PROCESS_END(); }
void EXTI0_IRQHandler(void) { if(EXTI_GetITStatus(DIO0_IRQ) != RESET) { EXTI_ClearITPendingBit(DIO0_IRQ); hal_DIOx_ITConfig(all,DISABLE); if(g_fsk.states == RF_STATE_TX_RUNNING) { SX1276FskSetOpMode( RF_OPMODE_STANDBY ); g_fsk.states = RF_STATE_TX_DONE; process_post(&hal_RF_process, PROCESS_EVENT_MSG, (void *)(&g_fsk.states)); } if(g_fsk.states == RF_STATE_RX_SYNC) { SX1276FskSetOpMode( RF_OPMODE_STANDBY ); read_fifo(true); etimer_stop(&timer_rf); g_fsk.states = RF_STATE_RX_DONE; process_post(&hal_RF_process, PROCESS_EVENT_MSG, (void *)(&g_fsk.states)); } } }
/*---------------------------------------------------------------------------*/ void uip_ds6_send_rs(void) { #if CONF_6LOWPAN_ND uint16_t r; #endif /* CONF_6LOWPAN_ND */ if((uip_ds6_defrt_choose() == NULL) && (rscount < UIP_ND6_MAX_RTR_SOLICITATIONS)) { PRINTF("Sending RS %u\n", rscount); uip_nd6_rs_output(); rscount++; etimer_set(&uip_ds6_timer_rs, UIP_ND6_RTR_SOLICITATION_INTERVAL * CLOCK_SECOND); #if CONF_6LOWPAN_ND } else if(uip_ds6_defrt_choose() == NULL) { /* Slower retransmissions */ PRINTF("Sending RS slower %u\n", rscount); uip_nd6_rs_output(); rscount++; r = (((uint16_t)random_rand()) % ((2 << (rscount - 1) - 1) + 1)) * UIP_ND6_RTR_SOLICITATION_INTERVAL; if(r >= UIP_ND6_MAX_RTR_SOLICITATION_INTERVAL) { r = UIP_ND6_MAX_RTR_SOLICITATION_INTERVAL; } etimer_set(&uip_ds6_timer_rs, r * CLOCK_SECOND); #endif /* CONF_6LOWPAN_ND */ } else { PRINTF("Router found ? (boolean): %u\n", (uip_ds6_defrt_choose() != NULL)); etimer_stop(&uip_ds6_timer_rs); } return; }
/*---------------------------------------------------------------------------*/ static int radio_off(void) { // stop reset timer etimer_stop(&et_reset_rx); Radio.Sleep(); return 1; }
/*============================================================================*/ void ctimer_stop(struct ctimer *pst_stopTim) { if(gc_init) { etimer_stop(&pst_stopTim->etimer); } else { pst_stopTim->etimer.next = NULL; pst_stopTim->etimer.active = TMR_NOT_ACTIVE; } list_remove(gp_ctimList, pst_stopTim); }
/*---------------------------------------------------------------------------*/ void ctimer_stop(struct ctimer *c) { if(initialized) { etimer_stop(&c->etimer); } else { c->etimer.next = NULL; c->etimer.p = PROCESS_NONE; } list_remove(ctimer_list, c); }
static void* event_handler(process_event_t ev, process_data_t data) { if (0) { } /*{ if "tc_sleep" in all_syscalls }*/ else if (thread->syscall == SYSCALL_tc_sleep) { if (0) { } else if (ev == PROCESS_EVENT_TIMER && data == &thread->ctx.tc_sleep.et) { thread->ctx.tc_sleep.frame->ec_result = false; } else if (ev == PROCESS_EVENT_CONTINUE) { thread->ctx.tc_sleep.frame->ec_result = true; etimer_stop(&thread->ctx.tc_sleep.et); } else if (ev == PROCESS_EVENT_CONTINUE && data == &tc_sleep) { thread->ctx.tc_sleep.frame->ec_result = false; } else { ASSERT(false); } if (thread->ctx.tc_sleep.frame->cond) { thread->ctx.tc_sleep.frame->cond->waiting = false; } return thread->ctx.tc_sleep.frame->ec_cont; } /*{ endif }*/ /*{ if "tc_receive" in all_syscalls }*/ else if (thread->syscall == SYSCALL_tc_receive) { if (0) { } else if (ev == tcpip_event && uip_newdata()) { thread->ctx.tc_receive.frame->ec_result = false; } else if (ev == PROCESS_EVENT_CONTINUE) { thread->ctx.tc_receive.frame->ec_result = true; } else { ASSERT(false); } if (thread->ctx.tc_receive.frame->cond) { thread->ctx.tc_receive.frame->cond->waiting = false; } return thread->ctx.tc_receive.frame->ec_cont; } /*{ endif }*/ /*{ if "tc_condition_wait" in all_syscalls }*/ else if (thread->syscall == SYSCALL_tc_condition_wait) { if (0) { } else if (ev == PROCESS_EVENT_CONTINUE) { } else { ASSERT(false); } return thread->ctx.tc_condition_wait.frame->ec_cont; } /*{ endif }*/ else { ASSERT(false); return (void*) -1; } }
/*---------------------------------------------------------------------------*/ void uip_netif_dad(void) { /* * check if dad is running */ if(dad_ifaddr == NULL){ PRINTF("uip_netif_dad: DAD not running\n"); return; } /* * send dup_addr_detect_transmit NS for DAD */ if(dad_ns < uip_netif_physical_if.dup_addr_detect_transmit) { uip_nd6_io_ns_output(NULL, NULL, &dad_ifaddr->ipaddr); dad_ns++; etimer_set(&uip_netif_timer_dad, uip_netif_physical_if.retrans_timer / 1000 * CLOCK_SECOND); return; } /* * If we arrive here it means DAD succeeded, otherwise the dad process * would have been interrupted in nd6_dad_ns/na_input */ PRINTF("DAD succeeded for ipaddr:"); PRINT6ADDR(&(dad_ifaddr->ipaddr)); PRINTF("\n"); etimer_stop(&uip_netif_timer_dad); dad_ifaddr->state = PREFERRED; dad_ifaddr = NULL; dad_ns = 0; /* * check if we need to run DAD on another address * This is necessary because if you receive a RA, * you might want to run DAD for several addresses * Considering that we have structures to do DAD * for one address only, we start DAD for the subsequent * addresses here */ PRINTF("END of DAD\n"); for(i = 0; i < UIP_CONF_NETIF_MAX_ADDRESSES; i ++){ if(uip_netif_physical_if.addresses[i].state != NOT_USED){ PRINTF("address %u : ",i); PRINT6ADDR(&(uip_netif_physical_if.addresses[i].ipaddr)); PRINTF("\n"); } if(uip_netif_physical_if.addresses[i].state == TENTATIVE){ uip_netif_sched_dad(&uip_netif_physical_if.addresses[i]); return; } } }
/*---------------------------------------------------------------------------*/ void uip_netif_send_rs(void) { if((uip_nd6_choose_defrouter() == NULL) && (rs_count < UIP_ND6_MAX_RTR_SOLICITATIONS)){ PRINTF("Sending RS %u\n", rs_count); uip_nd6_io_rs_output(); rs_count++; etimer_set(&uip_netif_timer_rs, UIP_ND6_RTR_SOLICITATION_INTERVAL * CLOCK_SECOND); } else { PRINTF("Router found ? (boolean): %u\n", (uip_nd6_choose_defrouter() != NULL)); etimer_stop(&uip_netif_timer_rs); rs_count = 0; } }
/*---------------------------------------------------------------------------*/ void uip_ds6_send_rs(void) { if((uip_ds6_defrt_choose() == NULL) && (rscount < UIP_ND6_MAX_RTR_SOLICITATIONS)) { PRINTF("Sending RS u");//, rscount); uip_nd6_rs_output(); rscount++; etimer_set(&uip_ds6_timer_rs, tcpip_process, UIP_ND6_RTR_SOLICITATION_INTERVAL * CLOCK_SECOND); } else { PRINTF("Router found ? (boolean): u");//, (uip_ds6_defrt_choose() != NULL)); etimer_stop(&uip_ds6_timer_rs); } return; }
static void _bsp_ledCallback(c_event_t c_event, p_data_t p_data) { uint8_t j; for (j = 0; j < LEDS_SUPPORTED; j++) { if (etimer_expired(&st_ledsTims[j])) { if ((&(st_ledsTims[j])) == (struct etimer *)p_data){ // Timer has been found , so we can turn it off. hal_ledOff(j); etimer_stop((struct etimer *)p_data); break; } } } // Find etimer which was fired in the list }
PROCESS_THREAD(cc2420_retransmit_process, ev, data) { static char n; static struct etimer etimer; switch (ev) { default: case PROCESS_EVENT_INIT: return PT_WAITING; case PROCESS_EVENT_EXIT: return PT_ENDED; case PROCESS_EVENT_POLL: /* Cancel future retransmissions. */ etimer_stop(&etimer); neigbour_update(last_dst, n); return PT_WAITING; case PROCESS_EVENT_MSG: /* Send new packet. */ n = -1; /* FALLTHROUGH */ case PROCESS_EVENT_TIMER: if (last_dst == 0xffff) { n++; clock_delay(1 + (rand() & (2048 - 1))); if (cc2420_resend() == UIP_FW_OK) { PRINTF("REBCAST %d\n", n); return PT_WAITING; /* Final transmission attempt. */ } } else { if (cc2420_resend() == UIP_FW_OK) { n++; PRINTF("RETRANS %d to %d.%d\n", n, last_dst & 0xff, last_dst >> 8); } if (n == MAX_RETRANSMISSIONS) { neigbour_update(last_dst, n); return PT_WAITING; /* Final transmission attempt. */ } } /* * Schedule retransmission. */ etimer_set(&etimer, RETRANSMIT_TIMEOUT); return PT_WAITING; }
/*---------------------------------------------------------------------------*/ void uip_netif_dad_failed(uip_ipaddr_t *ipaddr) { UIP_LOG("DAD FAILED"); UIP_LOG("THE STACK IS GOING TO SHUT DOWN"); UIP_LOG("THE HOST WILL BE UNREACHABLE"); if(uip_ipaddr_cmp(&dad_ifaddr->ipaddr, ipaddr)){ etimer_stop(&uip_netif_timer_dad); dad_ifaddr->state = NOT_USED; dad_ifaddr = NULL; dad_ns = 0; } exit(-1); }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(key_sampling, ev, data) { PROCESS_BEGIN(); static struct etimer et; static int previous_key_value = 0; static char debounce_check = 0; int current_key_value; etimer_set(&et, CLOCK_SECOND / 50); while(1) { PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); if(ev == PROCESS_EVENT_TIMER) { /* Handle sensor reading. */ PRINTF("Key sample\n"); current_key_value = get_key_value(); if(debounce_check != 0) { /* Check if key remained constant */ if(previous_key_value == current_key_value) { sensors_changed(&button_sensor); key_value = current_key_value; debounce_check = 0; } else { /* Bouncing */ previous_key_value = current_key_value; } } else /* Check for new key change */ if(current_key_value != previous_key_value) { previous_key_value = current_key_value; debounce_check = 1; } etimer_reset(&et); } else { /* ev == PROCESS_EVENT_MSG */ if(*(buttons_status_t *)data == BUTTONS_STATUS_NOT_ACTIVE) { /* Stop sampling */ etimer_stop(&et); } else if((*(buttons_status_t *)data == BUTTONS_STATUS_ACTIVE)) { /* restart sampling */ etimer_restart(&et); } } } PROCESS_END(); }
/*---------------------------------------------------------------------------*/ void uip_ds6_send_rs(struct net_buf *buf) { if((uip_ds6_defrt_choose() == NULL) && (rscount < UIP_ND6_MAX_RTR_SOLICITATIONS)) { PRINTF("Sending RS %u\n", rscount); uip_nd6_rs_output(buf); rscount++; etimer_set(&uip_ds6_timer_rs, UIP_ND6_RTR_SOLICITATION_INTERVAL * CLOCK_SECOND, &tcpip_process); } else { PRINTF("Router found ? (boolean): %u\n", (uip_ds6_defrt_choose() != NULL)); etimer_stop(&uip_ds6_timer_rs); } return; }
/*---------------------------------------------------------------------------*/ static void new_net_config(void) { /* * We got a new configuration over the net. * * Disconnect from the current broker and stop the periodic timer. * * When the source of the new configuration is done, we will get notified * via an event. */ if(state == MQTT_CLIENT_STATE_NEWCONFIG) { return; } state = MQTT_CLIENT_STATE_NEWCONFIG; etimer_stop(&publish_periodic_timer); mqtt_disconnect(&conn); }
PROCESS_THREAD(command_process, ev, data) { static struct etimer commandTimeout; static unsigned char buttonCount = 0; PROCESS_BEGIN(); SENSORS_ACTIVATE(button_sensor); while(1) { PROCESS_WAIT_EVENT(); if(ev == sensors_event && data == &button_sensor){ ++buttonCount; printf("Button pressed %d times\n", buttonCount); if(buttonCount == 1)//first press, set the timer { etimer_set( &commandTimeout, COMMAND_TIMEOUT * CLOCK_SECOND ); } else { etimer_restart(&commandTimeout); } } else if(ev == PROCESS_EVENT_TIMER) { if(buttonCount != 0 && etimer_expired(&commandTimeout)) { printf("Timer expired: count is %d\n", buttonCount); etimer_stop(&commandTimeout); command_switch(buttonCount); buttonCount = 0; print_commands(); } } } PROCESS_END(); }
/* Process to get ht sensor value. ht sensor is sampled. Sampling stopped when sensor is de-activated. Event is generated if temp and/or hum value changed at least the value DELTA_TEMP_SENSOR_VALUE or DELTA_HUM_SENSOR_VALUE since last event. */ PROCESS_THREAD(HTSensorSampling, ev, data) { PROCESS_BEGIN(); static struct etimer et; etimer_set(&et, CLOCK_SECOND); while(1) { PROCESS_WAIT_EVENT_UNTIL((ev == PROCESS_EVENT_TIMER) || (ev == PROCESS_EVENT_MSG)); if(ev == PROCESS_EVENT_TIMER) { /* Handle sensor reading. */ vHTSstartReadTemp(); temp_sensor_value = u16HTSreadTempResult(); PRINTF("Temperature sample: %d\n", temp_sensor_value); vHTSstartReadHumidity(); hum_sensor_value = u16HTSreadHumidityResult(); PRINTF("Humidity sample: %d\n", hum_sensor_value); if((abs(temp_sensor_value - prev_temp_event_val) > DELTA_TEMP_SENSOR_VALUE) || (abs(hum_sensor_value - prev_hum_event_val) > DELTA_HUM_SENSOR_VALUE)) { prev_temp_event_val = temp_sensor_value; prev_hum_event_val = hum_sensor_value; sensors_changed(&ht_sensor); } etimer_reset(&et); } else { /* ev == PROCESS_EVENT_MSG */ if(*(int *)data == HT_SENSOR_STATUS_NOT_ACTIVE) { /* Stop sampling */ etimer_stop(&et); } else if((*(int *)data == HT_SENSOR_STATUS_ACTIVE)) { /* restart sampling */ etimer_restart(&et); } } } PROCESS_END(); }
/** * \brief A process that handles adding/removing * BLE IPSP interfaces. */ PROCESS_THREAD(ble_iface_observer, ev, data) { static struct etimer led_timer; PROCESS_BEGIN(); etimer_set(&led_timer, CLOCK_SECOND/2); while(1) { PROCESS_WAIT_EVENT(); if(ev == ble_event_interface_added) { etimer_stop(&led_timer); leds_off(LEDS_1); leds_on(LEDS_2); } else if(ev == ble_event_interface_deleted) { etimer_set(&led_timer, CLOCK_SECOND/2); leds_off(LEDS_2); } else if(ev == PROCESS_EVENT_TIMER && etimer_expired(&led_timer)) { etimer_reset(&led_timer); leds_toggle(LEDS_1); } } PROCESS_END(); }
/*------------------------------------------------------------------*/ static u8_t raven_gui_loop(process_event_t ev, process_data_t data) { uint8_t *ptr; int len = 0; if(ev == tcpip_event) { PRINTF("[APP] TCPIP event lport %u rport %u raddress\n",uip_udp_conn->lport, uip_udp_conn->rport); if(uip_udp_conn == node_conn) { PRINTF("[APP] UDP packet\n"); if(uip_newdata()) { ptr = (uint8_t *)uip_appdata; /* Make sure the data is terminated */ ptr[uip_datalen()] = 0; /* Command to this node */ switch(*ptr) { case 'T': send_frame(TEMP_REQUEST, 0, 0); len = snprintf(udp_data, DATA_LEN, "%c%s\r\n", *ptr, last_temp); if(len > 0) { reply_packet(udp_data, len); } break; case 'A': if(ptr[1] > 32) { invert_led = ptr[1] == '1'; send_frame(LED_REQUEST, 1, &invert_led); } len = sprintf(udp_data, "A%u\r\n", invert_led ? 1 : 0); if(len > 0) { reply_packet(udp_data, len); } break; case 'P': PRINTF("[APP] Request for periodic sending of temperatures\n"); if(sscanf((char *)ptr+1,"%d", &periodic_interval)) { PRINTF("[APP] Period %d\n", periodic_interval); if(periodic_interval == 0) { etimer_stop(&periodic_timer); } else { etimer_set(&periodic_timer, periodic_interval * CLOCK_SECOND); } len = snprintf(udp_data, DATA_LEN, "P%d\r\n", periodic_interval); if(len > 0) { reply_packet(udp_data, len); } } break; case 'C': PRINTF("[APP] Command %c\n",ptr[1]); if(sscanf((char *)ptr+2, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x %d", &addr[0],&addr[1],&addr[2],&addr[3],&addr[4], &addr[5],&addr[6],&addr[7],&len) >= 8) { uip_ip6addr(&locaddr, addr[0], addr[1],addr[2], addr[3],addr[4],addr[5],addr[6],addr[7]); if(ptr[1] == 'E') { PRINTF("[APP] Send ping to"); PRINT6ADDR(&locaddr); PRINTF("len %d\n", len); raven_ping6(&locaddr, len); } else if (ptr[1] == 'T') { PRINTF("[APP] Send temperature to"); PRINT6ADDR(&locaddr); PRINTF("\n"); len = snprintf(udp_data, DATA_LEN, "%c\r\n", ptr[1]); if(len > 0) { send_packet(&locaddr, HTONS(0xF0B0), udp_data, len); } } else { PRINTF("[APP] Command unknown\n"); } } break; default: break; } } } } else { switch (ev) { case ICMP6_ECHO_REQUEST: /* We have received a ping request over the air. Send frame back to 3290 */ send_frame(PING_REQUEST, 0, 0); break; case ICMP6_ECHO_REPLY: /* We have received a ping reply over the air. Send frame back to 3290 */ send_frame(PING_REPLY, 1, &seqno); break; case PROCESS_EVENT_TIMER: if(data == &periodic_timer) { PRINTF("[APP] Periodic Timer\n"); /* Send to server if time to send */ len = sprintf(udp_data, "T%s\r\n", last_temp); if(len > 0) { send_packet(&server_addr, SERVER_PORT, udp_data, len); } etimer_reset(&periodic_timer); send_frame(TEMP_REQUEST, 0, 0); } break; case PROCESS_EVENT_POLL: /* Check for command from serial port, execute it. */ if (cmd.done) { /* Execute the waiting command */ switch (cmd.cmd) { case CMD_PING: /* Send ping request over the air */ seqno = cmd.frame[0]; raven_ping6(&server_addr, 0); break; case CMD_TEMP: /* Copy sensor data until white space or end of string. The ATMega3290 sends temperature with both value and type (25 C) */ copy_value(cmd.frame, last_temp, sizeof(last_temp)); PRINTF("[APP] New temp value %s\n", last_temp); break; default: break; } /* Reset command done flag. */ cmd.done = 0; } break; default: break; } } return 0; }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(http_req_process, ev, data) { static struct etimer httptimeout; SOCKETMSG msg; PROCESS_BEGIN(); while(1) { //wait for TCP connected or uip_timeout. PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_MSG || ev == PROCESS_EVENT_TIMER || ev == PROCESS_EVENT_EXIT); if(ev == PROCESS_EVENT_MSG) { msg = *(SOCKETMSG *)data; if(msg.status == SOCKET_CONNECTED) { //send out the http request. if(httpreqdata.cmdlen) tcpsend(httpreqdata.httpsock, httpreqdata.httpcmd, httpreqdata.cmdlen); } else if(msg.status == SOCKET_SENDACK) { //set timeot for http response. etimer_set(&httptimeout, 10 * CLOCK_CONF_SECOND); } else if(msg.status == SOCKET_NEWDATA) { //Get http response, parse response and close socket. etimer_stop(&httptimeout); httpreqdata.rsplen = tcprecv(httpreqdata.httpsock, httpreqdata.httprsp, HTTPRSP_MAX); tcpclose(httpreqdata.httpsock); httpreqdata.httpsock = -1; httpreqdata.httpstatus = HTTP_IDLE; if(httpreqdata.rsplen > 0 && httpreqdata.callbackfn) { httpreqdata.httprsp[httpreqdata.rsplen] = 0; httprsp_parse(httpreqdata.httprsp, httpreqdata.rsplen); } } else if(msg.status == SOCKET_CLOSED) { //socket closed, if it is unnormal case, notify upper layer. if(httpreqdata.httpstatus != HTTP_IDLE) { if(httpreqdata.callbackfn) { httpmsg.msgtype = HTTPREQ_CONN_ERROR; httpmsg.rsp = NULL; httpreqdata.callbackfn(&httpmsg); } httpreqdata.httpsock = -1; httpreqdata.httpstatus = HTTP_IDLE; } } } else if(ev == PROCESS_EVENT_TIMER) { //http response timeout, close socket and notify upper layer. tcpclose(httpreqdata.httpsock); httpreqdata.httpsock = -1; httpreqdata.httpstatus = HTTP_IDLE; if(httpreqdata.callbackfn) { httpmsg.msgtype = HTTPREQ_RSP_TIMEOUT; httpmsg.rsp = NULL; httpreqdata.callbackfn(&httpmsg); } } else if(ev == PROCESS_EVENT_EXIT) { break; } } PROCESS_END(); }
PROCESS_THREAD(doorAutoOpeningProcess, ev, data) { static struct etimer initialDelay; static struct etimer blinkingTimer; static int blinkings; static clock_time_t remainingDelay; PROCESS_BEGIN(); printf("Door auto opening: started\n"); remainingDelay = DOOR_AUTO_OPENING_DELAY * CLOCK_SECOND; while(1) { printf("Door auto opening: waiting initial delay\n"); etimer_set(&initialDelay, remainingDelay); PROCESS_WAIT_EVENT(); if(ev == PROCESS_EVENT_TIMER && etimer_expired(&initialDelay)) break; else if( ev == alarm_toggled_event) { printf("Door auto opening: delay interrupted by alarm\n"); remainingDelay = etimer_expiration_time(&initialDelay) - clock_time(); etimer_stop(&initialDelay); PROCESS_WAIT_EVENT_UNTIL(ev == alarm_toggled_event); printf("Door auto opening: alarm stopped, resuming delay\n"); } } printf("Door auto opening: door opened\n"); setLock(UNLOCKED); printf("Door auto opening: blinking started\n"); blinkings = 0; leds_on(LEDS_BLUE); while(blinkings < AUTO_OPENING_BLINKINGS - 1) { etimer_set(&blinkingTimer, (AUTO_OPENING_LED_PERIOD / 2) * CLOCK_SECOND); PROCESS_WAIT_EVENT(); if(ev == PROCESS_EVENT_TIMER && etimer_expired(&blinkingTimer)) { printf("Door auto opening: blinking\n"); leds_toggle(LEDS_BLUE); etimer_reset(&blinkingTimer); blinkings++; } else if(ev == alarm_toggled_event) { printf("Door auto opening: blinking interrupted by alarm\n"); etimer_stop(&blinkingTimer); PROCESS_WAIT_EVENT_UNTIL(ev == alarm_toggled_event); printf("Door auto opening: alarm stopped, resuming blinking\n"); } } printf("Door auto opening: blinking stopped\n"); printf("Gate auto opening: door locked\n"); setLock(LOCKED); PROCESS_END(); }
PROCESS_THREAD(proc_epoch_syncer, ev, data) { static struct etimer send_timer; static struct etimer epoch_timer; static const struct broadcast_callbacks broadcast_cbs = {__broadcast_recv_cb, __broadcast_sent_cb}; static struct broadcast_conn conn; PROCESS_EXITHANDLER(broadcast_close(&conn)); PROCESS_BEGIN(); #ifdef TRACK_CONNECTIONS /* Log the node id */ printf("board-id64 0x%.16llx\n", board_get_id64()); #endif #ifdef XFER_CRC16 /* Log the node id */ printf("xfer crc16\n"); #endif printf("epoch interval %ld ticks\n", EPOCH_INTERVAL); /* * Alloc the two syncer events */ evt_epoch_synced = process_alloc_event(); evt_end_of_epoch = process_alloc_event(); /* * Open a `connection` on the syncer broadcasting channel */ broadcast_open(&conn, BROADCAST_CHANNEL_TIMESYNC, &broadcast_cbs); /* * init the epoch-syncer instance */ epoch_syncer_init(&__epoch_syncer); /* * This is the main syncer loop. Initially we try to sync the * epoch between nodes without concurrently running any other * algo. After a period, at which time the network is synced, * we start generating epoch events which can be * consumed by, e.g., the estimator process. */ etimer_set(&epoch_timer, __epoch_syncer.epoch_interval); __epoch_syncer.epoch_start_time = clock_time(); __epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer); while (1) { /* * The start of a new epoch ! */ epoch_syncer_at_epoch_start(&__epoch_syncer); clock_time_t now; clock_time_t time_to_epoch_end; now = clock_time(); assert(__epoch_syncer.epoch_end_time == etimer_expiration_time(&epoch_timer)); assert(__epoch_syncer.epoch_end_time > now); time_to_epoch_end = __epoch_syncer.epoch_end_time - now; /* * Setup a random wait time before sending the sync packet * * ! we cannot let send_timer delay the epoch_timer, especially * when the next `end-of-epoch-time` has been anticipated by a lot * (this can happen at startup) */ if (time_to_epoch_end > __epoch_syncer.epoch_sync_start) { long int send_wait; long int send_wait_rnd; long int rnd; rnd = rand(); send_wait_rnd = (unsigned)rnd % (unsigned) __epoch_syncer.epoch_sync_xfer_interval; send_wait = __epoch_syncer.epoch_sync_start + send_wait_rnd; assert(send_wait >= __epoch_syncer.epoch_sync_start); assert(send_wait <= __epoch_syncer.epoch_sync_start + __epoch_syncer.epoch_sync_xfer_interval); if (send_wait > time_to_epoch_end) send_wait = __epoch_syncer.epoch_sync_start; assert(send_wait < time_to_epoch_end); etimer_set(&send_timer, send_wait); PROCESS_WAIT_UNTIL(etimer_expired(&send_timer)); /* * Acquire the radio lock * * ! we don't use WAIT/YIELD_UNTIL() because * 1) we do not want to yield if we can acquire the lock on the first try * 2) no kernel signal is generated when the lock is released (we would `deadlock') */ do { if (!radio_trylock()) break; PROCESS_PAUSE(); } while (1); { clock_time_t now; struct epoch_sync_packet packet; /* * broadcast the sync packet * * ! We put this part into its own block since non static stack * variables/allocations in the parent block wouldn't get preserved trough * kernel calls (e.g. the PROCESS_PAUSE() a few lines above) */ #ifdef TRACK_CONNECTIONS packet.board_id16 = board_get_id16(); #endif packet.epoch = __epoch_syncer.epoch; now = clock_time(); assert(now > __epoch_syncer.epoch_start_time); assert(__epoch_syncer.epoch_end_time > now); packet.time_from_epoch_start = now - __epoch_syncer.epoch_start_time; packet.time_to_epoch_end = __epoch_syncer.epoch_end_time - now; #ifdef XFER_CRC16 /* * Compute the packet crc with the .crc16 field zeroed */ { uint16_t crc16; packet.crc16 = 0; crc16 = crc16_data((const unsigned char *)&packet, sizeof(struct epoch_sync_packet), 0); packet.crc16 = crc16; } #endif packetbuf_copyfrom(&packet, sizeof(struct epoch_sync_packet)); broadcast_send(&conn); } } else { printf("epoch-syncer: skipping sync send\n"); } /* * We cannot YIELD here: if epoch_timer has already expired there won't be * any event to wake us up. * * FIXME: if we get here and the epoch timer has fired * already print by how much we are late: this can be terribly useful * to trace bugs in the epoch sync code or the kernel. */ if (etimer_expired(&epoch_timer)) { long int now; now = clock_time(); assert(now > __epoch_syncer.epoch_end_time); } else { char do_wait; do_wait = 1; if (__epoch_syncer.sum_sync_offsets) { long int avg_offset = __epoch_syncer.sum_sync_offsets / __epoch_syncer.nr_offsets; const long int threshold = CLOCK_SECOND; if (avg_offset > threshold) { /* * if we are late don't wait until the timer expires * ! this migth give us the opportunity to re-enter the right sync_xfer_interval */ do_wait = 0; } else if (avg_offset < -threshold) { /* * we are too fast, delay end of epoch */ clock_time_t now; clock_time_t time_to_epoch_end; now = clock_time(); assert(__epoch_syncer.epoch_end_time == etimer_expiration_time(&epoch_timer)); assert(__epoch_syncer.epoch_end_time > now); time_to_epoch_end = __epoch_syncer.epoch_end_time - now; long int delay = time_to_epoch_end + (-avg_offset/2); static struct etimer delay_timer; trace("epoch-syncer: delaying end-of-epoch by %ld ticks\n", (-avg_offset/2)); etimer_set(&delay_timer, delay); __epoch_syncer.epoch_end_time += (-avg_offset/2); PROCESS_WAIT_UNTIL(etimer_expired(&delay_timer)); } } if (do_wait) { PROCESS_WAIT_UNTIL(etimer_expired(&epoch_timer)); } else { trace("epoch-syncer: not waiting for end-of-epoch\n"); } } trace("epoch-syncer: epoch %d ended\n", __epoch_syncer.epoch); #ifdef TRACK_CONNECTIONS connection_print_and_zero(CONNECTION_TRACK_SYNC, __epoch_syncer.epoch); #endif /* * Re-Set the end-of-epoch timer */ if (__epoch_syncer.epoch == EPOCHS_UNTIL_SYNCED) { /* * We have hopefully achieved sync at this point * * 1) update the epoch timings, and set the epoch timer * * 2) signal the size-estimator process that the epoch is now synced */ __epoch_syncer.epoch_interval = EPOCH_INTERVAL; __epoch_syncer.epoch_sync_start = EPOCH_SYNC_START; __epoch_syncer.epoch_sync_xfer_interval = EPOCH_SYNC_XFER_INTERVAL; etimer_stop(&epoch_timer); etimer_set(&epoch_timer, __epoch_syncer.epoch_interval); /* * The epoch timer has been re-set: update the time until the next epoch end * Increase the epoch count. * ! these operations must happen in a block which cannot block in kernel calls */ __epoch_syncer.epoch_start_time = clock_time(); __epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer); __epoch_syncer.epoch++; process_post(&proc_size_estimator, evt_epoch_synced, NULL); } else { /* * Re-set and adjust the epoch timer using the data received trough sync packets * (in this epoch) * * ! using re-set (instead of, e.g., restart) is important here in order to avoid * drifting */ etimer_reset(&epoch_timer); /* * The epoch timer has been re-set: update the time until the next epoch end * Increase the epoch count. * ! these operations must happen in a block which cannot block in kernel calls */ //__epoch_syncer.epoch_start_time = epoch_timer.timer.start; __epoch_syncer.epoch_start_time = clock_time(); __epoch_syncer.epoch_end_time = etimer_expiration_time(&epoch_timer); __epoch_syncer.epoch++; if (__epoch_syncer.sum_sync_offsets) { long int avg_offset = __epoch_syncer.sum_sync_offsets / __epoch_syncer.nr_offsets; const long int threshold = 1;//(CLOCK_SECOND/32);//*3; #if __CONTIKI_NETSTACK_RDC==__CONTIKI_NETSTACK_RDC_NULL const int tx_delay = 0; #elif __CONTIKI_NETSTACK_RDC==__CONTIKI_NETSTACK_RDC_CXMAC /* * When the cxmac RDC is used we must consider an added delay due to the fact that when * other nodes radios are turned off the sync packet must be re-sent. */ const int tx_delay = 8; #endif /* * estimate the avg tx delay */ avg_offset += tx_delay; trace("epoch-syncer: sync offsets %d ~ %ld < %ld < %ld\n", __epoch_syncer.nr_offsets, __epoch_syncer.min_offset + tx_delay, avg_offset, __epoch_syncer.max_offset+tx_delay); if ((avg_offset < -threshold) || (avg_offset > threshold)) { clock_time_t new_expiration_time; const long int adjust_threshold = CLOCK_SECOND/2; long int adjust; /* * feedback control the next expiration time */ adjust = -avg_offset/2; adjust = min(adjust, adjust_threshold); adjust = max(adjust, -adjust_threshold); if (adjust) etimer_adjust(&epoch_timer, adjust); new_expiration_time = etimer_expiration_time(&epoch_timer); __epoch_syncer.epoch_end_time = new_expiration_time; } } if (__epoch_syncer.epoch > EPOCHS_UNTIL_SYNCED) { /* * Signal the estimator-process that this epoch has ended */ process_post(&proc_size_estimator, evt_end_of_epoch, NULL); } } } PROCESS_END(); }
/*void start_no_data_timer() { etimer_set(&bad_etx_timer, NO_DATA_PERIOD); } void stop_no_data_timer(){ etimer_stop(&bad_etx_timer); }*/ void eventhandler(process_event_t ev, process_data_t data) { switch (ev) { case PARENT_UNREACHABLE: { instance = &instance_table[0]; dag = instance->current_dag; if (dag->preferred_parent != NULL) { p = dag->preferred_parent; PRINT6ADDR(rpl_get_parent_ipaddr(p)); } else { PRINTF("NULL"); } PRINTF("\n"); if (test_unreachable == 1 && hand_off_backoff_flag == 0) { PRINTF("Connection unstable\n"); reliable = 0; if (wait_dio_flag == 0) { PRINTF("Sending DIS to current parent\n"); dis_output(rpl_get_parent_ipaddr(p), 1, 0, 0, 0); /* Send DIS to assess parent */ wait_dio_flag = 1; /* * Wait DIO reply. If parent doesn't reply until timer finishes, * he's considered unreachable. */ etimer_set(&dio_check, WAIT_DIO); } else { etimer_set(&dio_check, WAIT_DIO); } } } break; case PARENT_REACHABLE: { uint8_t *dis_rssi; /* We received the DIO reply from parent but we need to check the RSSI value */ dis_rssi = data; rssi = dis_rssi - 45; if (dis_rssi > 200) { rssi = dis_rssi - 255 - 46; } PRINTF("RSSI response from parent = %d ->", rssi); if (rssi <= -85) { PRINTF(" Unreliable\n"); mobility_flag = 1; leds_on(LEDS_ALL); current_t = clock_time() * 1000 / CLOCK_SECOND; PRINTF("%u\n", current_t); dis_output(NULL, 1, counter, 0, 0); rpl_dis_burst(); } else { PRINTF(" Reliable\n"); reliable = 1; process_post(&tcpip_process, RESET_MOBILITY_FLAG, NULL); } } break; case DIS_BURST: { etimer_reset(&dis_timer); } break; /* DIO received when checking current parent, stop the timer */ case STOP_DIO_CHECK: { printf("stopping DIO CHECK\n"); etimer_stop(&dio_check); etimer_stop(&dis_timer); } break; case PROCESS_EVENT_TIMER: { /* Current parent Unreachable/Unreliable, print current time and start DIS_BURST */ if (data == &dio_check && etimer_expired(&dio_check) && !reliable && test_unreachable == 1) { mobility_flag = 1; if (dis_burst_flag == 0) { dis_burst_flag++; current_t = clock_time() * 1000 / CLOCK_SECOND; printf("Start %u\n", current_t); dis_output(NULL, 1, counter, 0, 0); etimer_set(&dis_timer, SEND_TIME); } else { rpl_dis_burst(); } } /* 1st DIS was sent above. Check for the backoff delay and keep sending (Total = 3DIS) */ if (data == &dis_timer && etimer_expired(&dis_timer)) { counter++; dis_output(NULL, 1, counter, 0, 0); if (counter < 3) { etimer_reset(&dis_timer); } else { counter = 1; dis_burst_flag = 0; } } }break; } }
void nanotorrent_retry_stop(nanotorrent_retry_t *retry) { // Stop timer etimer_stop(&retry->timer); }
/*---------------------------------------------------------------------------*/ PROCESS_THREAD(udp_client_process, ev, data) { static struct etimer periodic; static struct ctimer backoff_timer; static struct etimer wait; //static int tx[] = { 31, 27, 23, 19, 15, 11, 7, 3}; static int i ; #if WITH_COMPOWER static int print = 0; #endif PROCESS_BEGIN(); //powertrace_start(CLOCK_SECOND * 2); //elnaz cc2420_set_txpower(19); printf(" Tx=%d\n", cc2420_get_txpower()); PROCESS_PAUSE(); set_global_address(); PRINTF("UDP client process started\n"); print_local_addresses(); /* new connection with remote host */ client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); if(client_conn == NULL) { PRINTF("No UDP connection available, exiting the process!\n"); PROCESS_EXIT(); } udp_bind(client_conn, UIP_HTONS(UDP_CLIENT_PORT)); PRINTF("Created a connection with the server "); PRINT6ADDR(&client_conn->ripaddr); PRINTF(" local/remote port %u/%u\n", UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport)); #if WITH_COMPOWER powertrace_sniff(POWERTRACE_ON); #endif etimer_set(&periodic, SEND_INTERVAL); //for(i = 0 ; i<8 ; i++) //{ while(seq<100) { PROCESS_YIELD(); if(ev == tcpip_event) { tcpip_handler(); } if(etimer_expired(&periodic)) { etimer_reset(&periodic); ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL); } //end etimer_expired } seq = 0; etimer_stop(&periodic); etimer_set(&wait, WAIT_INTERVAL); PROCESS_WAIT_EVENT_UNTIL(ev == PROCESS_EVENT_TIMER); etimer_set(&periodic, SEND_INTERVAL); // } // end loop on Tx PROCESS_END(); }