/* for reporting a sample that satisfies the reporting criteria and resetting the state machine */ int report_sample(sample s) { if(send_notification(s)){ // sends current_sample if observing is on last_band = band(s); // limits state machine high_step = s + LWM2M_step; // reset floating band upper limit defined by step low_step = s - LWM2M_step; // reset floating band lower limit defined by step pmin_timer.detach(); pmin_exceeded = false; // state machine to inhibit reporting at intervals < pmin pmin_timer.attach(&on_pmin, LWM2M_pmin); pmax_timer.detach(); pmax_timer.attach(&on_pmax, LWM2M_pmax); return 1; } else return 0; }
static void on_write(ble_evt_t * p_ble_evt) { ble_gatts_evt_write_t * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write; // Check if this the correct CCCD if ( (p_evt_write->handle == m_conn_params_config.start_on_notify_cccd_handle) && (p_evt_write->len == 2) ) { // Check if this is a 'start notification' if (ble_srv_is_notification_enabled(p_evt_write->data)) { // Do connection parameter negotiation if necessary conn_params_negotiation(); } else { #ifdef USE_APP_TIMER uint32_t err_code; // Stop timer if running err_code = app_timer_stop(m_conn_params_timer_id); if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) { m_conn_params_config.error_handler(err_code); } #else /* #if !USE_APP_TIMER */ m_conn_params_timer.detach(); #endif /* #if !USE_APP_TIMER */ } } }
/*! * \brief Function to be executed on MAC layer event */ static void OnMacEvent( LoRaMacEventFlags_t *flags, LoRaMacEventInfo_t *info ) { if( flags->Bits.JoinAccept == 1 ) { #if( OVER_THE_AIR_ACTIVATION != 0 ) JoinReqTimer.detach( ); #endif IsNetworkJoined = true; } if( flags->Bits.Tx == 1 ) { } if( flags->Bits.Rx == 1 ) { if( flags->Bits.RxData == true ) { ProcessRxFrame( flags, info ); } } // Schedule a new transmission TxDone = true; }
int main() { isLogging = RJ_LOGGING_EN; rjLogLevel = INF2; lifeLight.attach(&imAlive, ALIVE_BLINK_RATE); pc.baud(BAUD_RATE); shared_ptr<SharedSPI> sharedSPI = make_shared<SharedSPI>(RJ_SPI_MOSI, RJ_SPI_MISO, RJ_SPI_SCK); sharedSPI->format(8, 0); FILE* fp = fopen(filename.c_str(), "r"); AVR910 programmer(sharedSPI, RJ_KICKER_nCS, RJ_KICKER_nRESET); if (fp == nullptr) { pc.printf("Failed to open file.\r\n"); return -1; } pc.printf("Attempting to program...\r\n"); bool nSuccess = programmer.program(fp, ATTINY84A_PAGESIZE, ATTINY84A_NUM_PAGES); if (nSuccess) { pc.printf("Programming failed.\r\n"); } else { pc.printf("Programming succeeded.\r\n"); } fclose(fp); lifeLight.detach(); return 0; }
void pppSurfing(void const*) { while (pppDialingSuccessFlag == 0) { Thread::wait(500); } NetLED_ticker.detach(); NetLED_ticker.attach(&toggle_NetLed, 0.5); //net is connect startRemoteUpdate(); }
uint32_t ble_conn_params_stop(void) { #ifdef USE_APP_TIMER return app_timer_stop(m_conn_params_timer_id); #else /* #if !USE_APP_TIMER */ m_conn_params_timer.detach(); return NRF_SUCCESS; #endif /* #if !USE_APP_TIMER */ }
void pushUp(){ freq += FREQ_SIZE; if (freq >= MAX_FREQ) freq = MAX_FREQ; dx = 1.0/(DX_LEN * freq); controller.detach(); controller.attach(&bldcval, dx); DBG("freq = %d\r\n", freq); }
void debounce_handler() { if (debounce.read_ms() >= 500) { debounce.reset(); training_mode = !training_mode; if (training_mode) tcontrol.attach(checkTimers, 1); else tcontrol.detach(); led4 = !led4; turnoffgreen(); greenlightact(); } }
void timerCallback(void) { DEBUG("start timer callback"); sprintf(answer,"+.!"); DEBUG("writing beatpulse \"%s\" with len %d to ble\n",answer,strlen(answer)); int l = strlen(answer); for(int i = 0; i*20 < strlen(answer); i++) { int len = 20 < l ? 20 : l; ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(), (uint8_t *)&answer[i*20], len); l -= 20; } ticker.detach(); }
/* handler for the pmin timer, called when pmin expires if no reportable events have occurred, set the pmin expired flag to inform the report scheduler to report immediately If a reportable event has occured, report a new sample */ void on_pmin() { if (report_scheduled){ report_scheduled = false; pmin_trigger = true; // diagnostic for state machine visibility report_sample(get_sample()); } else{ pmin_exceeded = true; // state machine pmin_timer.detach(); } return; }
static void update_timeout_handler(void * p_context) { UNUSED_PARAMETER(p_context); #else /* #if !USE_APP_TIMER */ static void update_timeout_handler(void) { m_conn_params_timer.detach(); /* this is supposed to be a single-shot timer callback */ #endif /* #if !USE_APP_TIMER */ if (m_conn_handle != BLE_CONN_HANDLE_INVALID) { // Check if we have reached the maximum number of attempts m_update_count++; if (m_update_count <= m_conn_params_config.max_conn_params_update_count) { uint32_t err_code; // Parameters are not ok, send connection parameters update request. err_code = sd_ble_gap_conn_param_update(m_conn_handle, &m_preferred_conn_params); if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) { m_conn_params_config.error_handler(err_code); } } else { m_update_count = 0; // Negotiation failed, disconnect automatically if this has been configured if (m_conn_params_config.disconnect_on_fail) { uint32_t err_code; err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE); if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) { m_conn_params_config.error_handler(err_code); } } // Notify the application that the procedure has failed if (m_conn_params_config.evt_handler != NULL) { ble_conn_params_evt_t evt; evt.evt_type = BLE_CONN_PARAMS_EVT_FAILED; m_conn_params_config.evt_handler(&evt); } } } }
void resetSnake(LLRoot * master) { if(master == NULL) return; if(LLDEBUG) printf("###### GAME RESET; Setting snake back to 0,0,0 ######\r\n\r\n"); tick.detach(); freeListLL(master); myCube.clearCube(); initializeSnake(master); //sysClock.reset(); if(LLDEBUG) printListLL(master); }
//////////////////////////////////////////////////////////////// //Pause du jeu // //////////////////////////////////////////////////////////////// int A25(void) { son.MusicOff(); scanShip.detach(); T_MS1=500; T_MS2=500; space.Pause(); Chrono.stop(); lcd.cls(); lcd.printf("[]***PAUSE***[]"); lcd.locate(0,1); lcd.printf("=>Jouer Menu"); printf("Action = A25\n\r"); printf("Etat = LCDGAME\n\r"); return LCDGAME; }
void blink(void *argument) { // read the value of 'Pattern' status_ticker.detach(); green_led = LED_OFF; M2MObjectInstance* inst = led_object->object_instance(); M2MResource* res = inst->resource("5853"); // Clear previous blink data blink_args->clear(); // values in mbed Client are all buffers, and we need a vector of int's uint8_t* buffIn = NULL; uint32_t sizeIn; res->get_value(buffIn, sizeIn); // turn the buffer into a string, and initialize a vector<int> on the heap std::string s((char*)buffIn, sizeIn); free(buffIn); printf("led_execute_callback pattern=%s\n", s.c_str()); // our pattern is something like 500:200:500, so parse that std::size_t found = s.find_first_of(":"); while (found!=std::string::npos) { blink_args->blink_pattern.push_back(atoi((const char*)s.substr(0,found).c_str())); s = s.substr(found+1); found=s.find_first_of(":"); if(found == std::string::npos) { blink_args->blink_pattern.push_back(atoi((const char*)s.c_str())); } } // check if POST contains payload if (argument) { M2MResource::M2MExecuteParameter* param = (M2MResource::M2MExecuteParameter*)argument; String object_name = param->get_argument_object_name(); uint16_t object_instance_id = param->get_argument_object_instance_id(); String resource_name = param->get_argument_resource_name(); int payload_length = param->get_argument_value_length(); uint8_t* payload = param->get_argument_value(); printf("Resource: %s/%d/%s executed\n", object_name.c_str(), object_instance_id, resource_name.c_str()); printf("Payload: %.*s\n", payload_length, payload); } // do_blink is called with the vector, and starting at -1 blinky_thread.start(callback(this, &LedResource::do_blink)); }
static void on_disconnect(ble_evt_t * p_ble_evt) { #ifdef USE_APP_TIMER uint32_t err_code; #endif m_conn_handle = BLE_CONN_HANDLE_INVALID; // Stop timer if running m_update_count = 0; // Connection parameters updates should happen during every connection #ifdef USE_APP_TIMER err_code = app_timer_stop(m_conn_params_timer_id); if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) { m_conn_params_config.error_handler(err_code); } #else m_conn_params_timer.detach(); #endif }
// Entry point to the program int main() { unsigned int seed; size_t len; #ifdef MBEDTLS_ENTROPY_HARDWARE_ALT // Used to randomize source port mbedtls_hardware_poll(NULL, (unsigned char *) &seed, sizeof seed, &len); #elif defined MBEDTLS_TEST_NULL_ENTROPY #warning "mbedTLS security feature is disabled. Connection will not be secure !! Implement proper hardware entropy for your selected hardware." // Used to randomize source port mbedtls_null_entropy_poll( NULL,(unsigned char *) &seed, sizeof seed, &len); #else #error "This hardware does not have entropy, endpoint will not register to Connector.\ You need to enable NULL ENTROPY for your application, but if this configuration change is made then no security is offered by mbed TLS.\ Add MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES and MBEDTLS_TEST_NULL_ENTROPY in mbed_app.json macros to register your endpoint." #endif srand(seed); red_led = LED_OFF; blue_led = LED_OFF; status_ticker.attach_us(blinky, 250000); // Keep track of the main thread mainThread = osThreadGetId(); printf("\nStarting mbed Client example in "); #if defined (MESH) || (MBED_CONF_LWIP_IPV6_ENABLED==true) printf("IPv6 mode\n"); #else printf("IPv4 mode\n"); #endif mbed_trace_init(); NetworkInterface* network = easy_connect(true); if(network == NULL) { printf("\nConnection to Network Failed - exiting application...\n"); return -1; } // we create our button and LED resources ButtonResource button_resource; LedResource led_resource; BigPayloadResource big_payload_resource; #ifdef TARGET_K64F // On press of SW3 button on K64F board, example application // will call unregister API towards mbed Device Connector //unreg_button.fall(&mbed_client,&MbedClient::test_unregister); unreg_button.fall(&unregister); // Observation Button (SW2) press will send update of endpoint resource values to connector obs_button.fall(&button_clicked); #else // Send update of endpoint resource values to connector every 15 seconds periodically timer.attach(&button_clicked, 15.0); #endif // Create endpoint interface to manage register and unregister mbed_client.create_interface(MBED_SERVER_ADDRESS, network); // Create Objects of varying types, see simpleclient.h for more details on implementation. M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info M2MDevice* device_object = mbed_client.create_device_object(); // device resources object // Create list of Objects to register M2MObjectList object_list; // Add objects to list object_list.push_back(device_object); object_list.push_back(button_resource.get_object()); object_list.push_back(led_resource.get_object()); object_list.push_back(big_payload_resource.get_object()); // Set endpoint registration object mbed_client.set_register_object(register_object); // Register with mbed Device Connector mbed_client.test_register(register_object, object_list); registered = true; while (true) { updates.wait(25000); if(registered) { if(!clicked) { mbed_client.test_update_register(); } }else { break; } if(clicked) { clicked = false; button_resource.handle_button_click(); } } mbed_client.test_unregister(); status_ticker.detach(); }
void MotorControl::stop_turn() { pid_interval_ticker.detach(); pid->reset(); }
void callback(const MQTT::Publish& pub) { yield(); if (millis() - MQTTtick > MQTTlimit) { MQTTtick = millis(); int commandLoc; String command = ""; String deviceName = ""; String endPoint = ""; topic = pub.topic(); payload = pub.payload_string(); // -- topic parser // syntax: // global: / global / path / command / function // device setup: / deviceInfo / command / name // normal: path / command / name / endpoint // check item 1 in getValue String firstItem = getValue(topic, '/', 1); if (firstItem == "global") { // -- do nothing until I change to $ prefix before command types } else if (firstItem == "deviceInfo") { // get name and command deviceName = getValue(topic, '/', 3); command = getValue(topic, '/', 2); if ((deviceName == thisDeviceName) && (command == "control")) { if (payload == "no states") { // -- do something to send the default states, but now that this is managed by persistence this shouldn't be necessary // -- maybe it just resets all the states to 0 or whatever was originally programmed into the sketch //sendJSON = true; } else if (payload == "blink on") { Serial.end(); pinMode(BUILTIN_LED, OUTPUT); ticker.attach(0.6, tick_fnc); } else if (payload == "blink off") { ticker.detach(); digitalWrite(BUILTIN_LED, HIGH); pinMode(BUILTIN_LED, INPUT); Serial.begin(115200); } else { // -- persistence will no longer send the default object, if it's an arduino based esp chip, it will just send the control messages to /[device_path]/control/[device_name]/[endpoint_key] } } } else { int i; int maxitems; // count number of items for (i=1; i<topic.length(); i++) { String chunk = getValue(topic, '/', i); if (chunk == NULL) { break; } } // get topic variables maxitems = i; for (i=1; i<maxitems; i++) { String chunk = getValue(topic, '/', i); if (chunk == "control") { commandLoc = i; command = chunk; deviceName = getValue(topic, '/', i + 1); endPoint = getValue(topic, '/', i + 2); break; } } //Serial.println("device and endpoint incoming..."); //Serial.println(deviceName); //Serial.println(endPoint); // send endpoint_key to function stored in namepins.h at compile time // function returns static_endpoint_id associated with that endpoint String lookup_val = lookup(endPoint); //Serial.println("looking value incoming..."); //Serial.println(lookup_val); // sketch acts on that value as it normally would, using the static_endpoint_id to know for sure what it should do (turn output pin on/off, adjust RGB light, etc) if (lookup_val == "RGB") { // deserialize payload, get valueKey // or just look for value or red,green,blue String findKey = getValue(payload, '"', 1); String findValue = getValue(payload, ':', 1); findValue.remove(findValue.length() - 1); if (findKey == "red") { redValue = findValue.toInt(); } else if (findKey == "green") { greenValue = findValue.toInt(); } else if (findKey == "blue") { blueValue = findValue.toInt(); } //neoPixelChange = true; } /* else if (lookup_val == "SECOND STATIC ENDPOINT ID") { } else if (lookup_val == "THIRD STATIC ENDPOINT ID") { } */ // sketch confirms the value by sending it back on /[path]/[confirm]/[device_name]/[endpoint_key] confirmPath = ""; confirmPath = thisDevicePath; confirmPath += "/confirm/"; confirmPath += thisDeviceName; confirmPath += "/"; confirmPath += endPoint; confirmPayload = payload; //sendConfirm = true; client.publish(MQTT::Publish(confirmPath, confirmPayload).set_qos(2)); } } }
void userFirmwareSend(void const*) { char readBuf[BAG_SIZE];//»º´æ SPI spi(PC_3, PC_2, PB_13); // mosi, miso, sclk spi.format(8, 0); spi.frequency(16 * 1000 * 1000); flash25spi w25q64(&spi, PB_12); #if 0 for (int i = 0; i < USER_IMG_MAP_BUF_SIZE*2/USER_IMG_MAP_BLOCK_SIZE; i++) w25q64.clearBlock(0x00000 + i * USER_IMG_MAP_BLOCK_SIZE); #endif Serial userCom(PA_9, PA_10); //UART1; tx, rx INFO("Start userFirmwareSend thread.........\n"); while (true) { userfwpro userFWPro(&userCom); osEvent evt = queue.get(); if (evt.status == osEventMessage) { char *ch = (char *)evt.value.p; INFO("Get userFirmwareSend osEventMessage value id is %d\n", *ch); } DataLED_ticker.detach(); dataLed = 0; //download is over, the led is on while (userFWPro.getUserVersion()) { Thread::wait(500); } DataLED_ticker.attach(&toggle_DataLed, 0.1); UINT32 blockAddr = USER_IMG_MAP_BUF_CLEAR_FLAG; for (int i = 0; i < 2; i++) { int bufFlagValue; if (w25q64.read(USER_IMG_MAP_BUF_START + i * USER_IMG_MAP_BUF_SIZE, USER_IMG_MAP_BUF_FLAG_LEN, (char *)&bufFlagValue) == false) { INFO("Read user image bufFlagValue from flash failure"); continue; } // printf("block%d, blockAddr[0x%08X], bufFlagValue[0x%08X].........\n", i, // USER_IMG_MAP_BUF_START + i * USER_IMG_MAP_BUF_SIZE, bufFlagValue); if (bufFlagValue == USER_IMG_MAP_BUF_VAILE_FLAG) { if (i == 0) { blockAddr = USER_IMG_MAP_BUF_START + USER_IMG_MAP_BUF_FLAG_LEN; } else if (i == 1) { blockAddr = USER_IMG_MAP_BUF_START + USER_IMG_MAP_BUF_SIZE + USER_IMG_MAP_BUF_FLAG_LEN; } break; } } if (blockAddr == USER_IMG_MAP_BUF_CLEAR_FLAG) { INFO("No valid flash is available ."); DataLED_ticker.detach(); return; } for (int j = 0; j < updateinfo.fileLength/BAG_SIZE + 2; j++) { if (w25q64.read(blockAddr + j * BAG_SIZE, BAG_SIZE, readBuf) == false) { INFO("Read user image bytestreams from flash failure"); continue; } if (userFWPro.sendUserFirmware(readBuf, BAG_SIZE, updateinfo.fileLength)) { INFO("Send user firmware failure"); DataLED_ticker.detach(); continue; } printf("."); } if (userFWPro.runUserFirmware()) { INFO("Run user firmware failure\n"); } else { userFirmwareSendCompleteFlag = 1; } DataLED_ticker.detach(); dataLed = 1; //send bytes is over, the led is off } }
/** * Main application entry point. */ int main( void ) { #if( OVER_THE_AIR_ACTIVATION != 0 ) uint8_t sendFrameStatus = 0; #endif bool trySendingFrameAgain = false; // float tempLightValue = 0; // LightMode = 0; // 0: manual, 1: automatic buzzer = 0; // 0: OFF, 1: ON bar.setLevel(0); debug( "\n\n\r LoRaWAN Class A Demo code \n\n\r" ); BoardInitMcu( ); BoardInitPeriph( ); // Initialize LoRaMac device unique ID BoardGetUniqueId( DevEui ); LoRaMacEvents.MacEvent = OnMacEvent; LoRaMacInit( &LoRaMacEvents ); IsNetworkJoined = false; #if( OVER_THE_AIR_ACTIVATION == 0 ) // Random seed initialization srand( RAND_SEED ); // Choose a random device address // NwkID = 0 // NwkAddr rand [0, 33554431] if( ( DevAddr == 0 ) || ( DevAddr == 0xFFFFFFFF ) ) { // Generate random DevAddr if it does not exist debug("Generate random DevAddr\n\r"); DevAddr = randr( 0, 0x01FFFFFF ); } debug( "- DevAddr = 0x%x\n\r" , DevAddr); LoRaMacInitNwkIds( 0x000000, DevAddr, NwkSKey, AppSKey ); IsNetworkJoined = true; #endif TxNextPacket = true; LoRaMacSetAdrOn( false ); LoRaMacSetDutyCycleOn( false ); while( 1 ) { while( IsNetworkJoined == false ) { #if( OVER_THE_AIR_ACTIVATION != 0 ) if( TxNextPacket == true ) { TxNextPacket = false; sendFrameStatus = LoRaMacJoinReq( DevEui, AppEui, AppKey ); debug("Req Sent\n\r"); switch( sendFrameStatus ) { case 1: // BUSY break; case 0: // OK case 2: // NO_NETWORK_JOINED case 3: // LENGTH_PORT_ERROR case 4: // MAC_CMD_ERROR case 6: // DEVICE_OFF default: // Relaunch timer for next trial JoinReqTimer.attach_us( &OnJoinReqTimerEvent, OVER_THE_AIR_ACTIVATION_DUTYCYCLE ); break; } } // TimerLowPowerHandler( ); #endif } if( TxDone == true ) { TxDone = false; debug( "TxDone \n\n\r" ); // Schedule next packet transmission TxDutyCycleTime = APP_TX_DUTYCYCLE + randr( -APP_TX_DUTYCYCLE_RND, APP_TX_DUTYCYCLE_RND ); TxNextPacketTimer.attach_us( &OnTxNextPacketTimerEvent, TxDutyCycleTime ); } if( trySendingFrameAgain == true ) { trySendingFrameAgain = SendFrame( ); } if( TxNextPacket == true ) { TxNextPacketTimer.detach( ); TxNextPacket = false; PrepareTxFrame( AppPort ); trySendingFrameAgain = SendFrame( ); } /* Read light sensor tempLightValue = LightSens.read( ) * 1.65; LightValue = ( 1 - tempLightValue ); // Set automatic RGB from light sensor if( LightMode == 0 ) { color_led.setColorRGB( 0, ( uint8_t )( 255 * LightValue ), ( uint8_t )( 255 * LightValue ), ( uint8_t )( 255 * LightValue ) ); }*/ // TimerLowPowerHandler( ); } }
void onDisconnection(const Gap::DisconnectionCallbackParams_t *params) { echoer.detach(); ble.startAdvertising(); }
/*! * \brief Function executed on TxNextPacket Timeout event */ static void OnTxNextPacketTimerEvent( void ) { TxNextPacket = true; TxNextPacketTimer.detach( ); }
/*! * \brief Function executed on JoinReq Timeout event */ static void OnJoinReqTimerEvent( void ) { TxNextPacket = true; JoinReqTimer.detach( ); }
static void OnBuzTimerEvent( void ) { buzzer = 0; BuzTimer.detach( ); }