Ejemplo n.º 1
0
int llwrite(int fd, char * buffer, int length) {

    comporTramaI(TRANSMITTER, buffer, length);
    stuffing(info->frameSend, &info->frameSendLength);
    //printf("partes: %x, %x, %x, %x, %x, %x, %x, %x, %x \n", tramaI[0],tramaI[1],tramaI[2],tramaI[3],tramaI[4],tramaI[5],tramaI[6],tramaI[7],tramaI[8]);
    transmitirFrame(info->frameSend, info->frameSendLength);
    //printf("enviar frame I com sequenceNumber = %d \n", info->sequenceNumber);
    info->tentativas = tentativas;
    while(info->tentativas > 0) {
        start_alarm();
        info->frameTempLength = readFrame(info->frameTemp);
        if (info->sequenceNumber == 1) {
            if (verifyFrame(info->frameTemp, info->frameTempLength, "rr0")) {
                //printf("recebeu rr corretamente \n");
                stop_alarm();
                info->tentativas = tentativas;
                break;
            }
            else if (verifyFrame(info->frameTemp, info->frameTempLength, "rej0")) {
                //printf("recebeu rej0\n");
                transmitirFrame(info->frameSend, info->frameSendLength);
                continue;
            }
        }
        else if (info->sequenceNumber == 0) {
            if (verifyFrame(info->frameTemp, info->frameTempLength, "rr1")) {
                //printf("recebeu rr corretamente \n");
                stop_alarm();
                info->tentativas = tentativas;
                break;
            }
            else if (verifyFrame(info->frameTemp, info->frameTempLength, "rej1")) {
                //printf("recebeu rej1\n");
                transmitirFrame(info->frameSend, info->frameSendLength);
                continue;
            }
        }
    }
    if (info->tentativas == 0) {
        printf("Número de tentativas chegou ao fim. \n");
        exit(-1);
    }
    info->sequenceNumber = !info->sequenceNumber;
    //printf("retornar llwrite\n");
    return 1;
}
  // Initialization function
  void init() {
    // buzzer connected to A1 (aka digital out 15)
    mraa_init();

    buzzer = new mraa::Gpio(15);
    buzzer->dir(mraa::DIR_OUT);
    stop_alarm();

    // moisture sensor on analog (A2)
    moisture = new upm::GroveMoisture(2);
  }
Ejemplo n.º 3
0
/* 功能:报警器控制
 * 参数:同上
 * 返回值:无
 * */
void beep_control_req(char *pskb)
{
        struct BeepControl *pBeep       = (struct BeepControl*)pskb;
        
        /* 消息处理*/
        pBeep->BeepControlMsg.MsgId     = ARM_PC_BEEP_CONTROL_RSP;
        pBeep->BeepControlMsg.MsgLen    = sizeof(*pBeep)
                                            - sizeof(pBeep->BeepControlMsg);
        if(pBeep->Flag == 1) { //打开
                pBeep->Result = start_alarm();
        } else {        //关闭
                pBeep->Result = stop_alarm(); 
        }
}
Ejemplo n.º 4
0
void atende(int sig) {
    printf("alarme # %d\n", conta);
    flag=1;
    conta++;
    printf("tentativas = %d \n", info->tentativas);
    if (info->tentativas > 0) {
        transmitirFrame(info->frameSend, info->frameSendLength);
        info->tentativas--;
    }
    else {
        fprintf(stderr, "0 tentativas restantes \n");
        stop_alarm();
        exit(-1);
    }
}
Ejemplo n.º 5
0
/* 功能:报警器控制
 * 参数:MCM请求消息
 * 返回值:无
 * */
void beep_control_req(s8 *pskb)
{
        struct stru_beep_control_req    *prBeepCtrlReq  = (struct stru_beep_control_req *)pskb; 
        struct stru_beep_control_rsp    rBeepCtrlRsp;

        /* 消息处理*/
        rBeepCtrlRsp.struMsgHeader.u16MsgType           = O_MAINMCM_BEEP_RSP;
        rBeepCtrlRsp.struMsgHeader.u16MsgLength         = sizeof(rBeepCtrlRsp)
                                                                - sizeof(rBeepCtrlRsp.struMsgHeader);
        rBeepCtrlRsp.struMsgHeader.u8TransType          = prBeepCtrlReq->struMsgHeader.u8TransType;

        if(prBeepCtrlReq->u8BeepCtrlOperation == 1) { //打开
                rBeepCtrlRsp.bSuccessful = start_alarm();
        } else {        //关闭
                rBeepCtrlRsp.bSuccessful = stop_alarm();
        }

        send_rsp_message(&rBeepCtrlRsp, 
                                sizeof(rBeepCtrlRsp), 
                                prBeepCtrlReq->struMsgHeader.u8TransType);
}
Ejemplo n.º 6
0
__interrupt void TIMER0_A0_ISR(void)
{
    static u8 button_lock_counter = 0;

    // Disable IE
    TA0CCTL0 &= ~CCIE;
    // Reset IRQ flag
    TA0CCTL0 &= ~CCIFG;
    // Add 1 sec to TACCR0 register (IRQ will be asserted at 0x7FFF and 0xFFFF = 1 sec intervals)
    TA0CCR0 += 32768;
    // Enable IE
    TA0CCTL0 |= CCIE;

    // Add 1 second to global time
    clock_tick();

    // Set clock update flag
    display.flag.update_time = 1;

    // While SimpliciTI stack operates or BlueRobin searches, freeze system state
    if (is_rf() || is_bluerobin_searching())
    {
        // SimpliciTI automatic timeout
        if (sRFsmpl.timeout == 0)
        {
            simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
        }
        else
        {
            sRFsmpl.timeout--;
        }

        // switch message after received packet
        if (sRFsmpl.mode == SIMPLICITI_SYNC)
        {
            if (sRFsmpl.display_sync_done == 0)
            {
                display_chars(LCD_SEG_L2_5_0, (u8 *) "  SYNC", SEG_ON);
            }
            else
            {
                sRFsmpl.display_sync_done--;
            }
        }
        // Exit from LPM3 on RETI
        _BIC_SR_IRQ(LPM3_bits);
        return;
    }

    // -------------------------------------------------------------------
    // Service modules that require 1/min processing
    if (sTime.drawFlag >= 2)
    {
        // Measure battery voltage to keep track of remaining battery life
        request.flag.voltage_measurement = 1;

        // Check if alarm needs to be turned on
        check_alarm();
    }

    // -------------------------------------------------------------------
    // Service active modules that require 1/s processing

    // Generate alarm signal
    if (sAlarm.state == ALARM_ON)
    {
        // Decrement alarm duration counter
        if (sAlarm.duration-- > 0)
        {
            request.flag.buzzer = 1;
        }
        else
        {
            sAlarm.duration = ALARM_ON_DURATION;
            stop_alarm();
        }
    }

    // Do a temperature measurement each second while menu item is active
    if (is_temp_measurement())
        request.flag.temperature_measurement = 1;

    // Do a pressure measurement each second while menu item is active
    if (is_altitude_measurement())
    {
        // Countdown altitude measurement timeout while menu item is active
        sAlt.timeout--;

        // Stop measurement when timeout has elapsed
        if (sAlt.timeout == 0)
        {
            stop_altitude_measurement();
            // Show ---- m/ft
            display_chars(LCD_SEG_L1_3_0, (u8 *) "----", SEG_ON);
            // Clear up/down arrow
            display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
            display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
        }

        // In case we missed the IRQ due to debouncing, get data now
        if ((PS_INT_IN & PS_INT_PIN) == PS_INT_PIN)
            request.flag.altitude_measurement = 1;
    }

    // Count down timeout
    if (is_acceleration_measurement())
    {
        // Countdown acceleration measurement timeout
        sAccel.timeout--;

        // Stop measurement when timeout has elapsed
        if (sAccel.timeout == 0)
        {
            as_stop();
            // Show ----
            display_chars(LCD_SEG_L1_3_0, (u8 *) "----", SEG_ON);
            // Clear up/down arrow
            display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
            display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
            display_symbol(LCD_SEG_L1_DP1, SEG_OFF);
        }

        // If DRDY is (still) high, request data again
        if ((AS_INT_IN & AS_INT_PIN) == AS_INT_PIN)
            request.flag.acceleration_measurement = 1;
    }

    // If BlueRobin transmitter is connected, get data from API
    if (is_bluerobin())
        get_bluerobin_data();

    // If battery is low, decrement display counter
    if (sys.flag.low_battery)
    {
        if (sBatt.lobatt_display-- == 0)
        {
            message.flag.prepare = 1;
            message.flag.type_lobatt = 1;
            sBatt.lobatt_display = BATTERY_LOW_MESSAGE_CYCLE;
        }
    }

    // If a message has to be displayed, set display flag
    if (message.all_flags)
    {
        if (message.flag.prepare)
        {
            message.flag.prepare = 0;
            message.flag.show = 1;
        }
        else if (message.flag.erase)    // message cycle is over, so erase it
        {
            message.flag.erase = 0;
            display.flag.full_update = 1;
        }
    }

    // -------------------------------------------------------------------
    // Check idle timeout, set timeout flag
    if (sys.flag.idle_timeout_enabled)
    {
        if (sTime.system_time - sTime.last_activity > INACTIVITY_TIME)
            sys.flag.idle_timeout = 1;  //setFlag(sysFlag_g, SYS_TIMEOUT_IDLE);
    }

    // -------------------------------------------------------------------
    // Turn the Backlight off after timeout
    if (sButton.backlight_status == 1)
    {
        if (sButton.backlight_timeout > BACKLIGHT_TIME_ON)
        {
            //turn off Backlight
            P2OUT &= ~BUTTON_BACKLIGHT_PIN;
            P2DIR &= ~BUTTON_BACKLIGHT_PIN;
            sButton.backlight_timeout = 0;
            sButton.backlight_status = 0;
        }
        else
        {
            sButton.backlight_timeout++;
        }
    }

    // -------------------------------------------------------------------
    // Detect continuous button high states

    // Trying to lock/unlock buttons?
    if (BUTTON_NUM_IS_PRESSED && BUTTON_DOWN_IS_PRESSED)
    {
        if (button_lock_counter++ > LEFT_BUTTON_LONG_TIME)
        {
            // Toggle lock / unlock buttons flag
            sys.flag.lock_buttons = ~sys.flag.lock_buttons;

            // Show "buttons are locked/unlocked" message synchronously with next second tick
            message.flag.prepare = 1;
            if (sys.flag.lock_buttons)
                message.flag.type_locked = 1;
            else
                message.flag.type_unlocked = 1;

            // Reset button lock counter
            button_lock_counter = 0;
        }
    }
    else                        // Trying to create a long button press?
    {
        // Reset button lock counter
        button_lock_counter = 0;

        if (BUTTON_STAR_IS_PRESSED)
        {
            sButton.star_timeout++;

            // Check if button was held low for some seconds
            if (sButton.star_timeout > LEFT_BUTTON_LONG_TIME)
            {
                button.flag.star_long = 1;
                button.flag.star_not_long = 0;
                sButton.star_timeout = 0;
                // Return interrupt edge to normal value
                BUTTONS_IES &= ~BUTTON_STAR_PIN;
            }
        }
        else                    // there was a button press not long enough
        {
            sButton.star_timeout = 0;
        }

        if (BUTTON_NUM_IS_PRESSED)
        {
            sButton.num_timeout++;

            // Check if button was held low for some seconds
            if (sButton.num_timeout > LEFT_BUTTON_LONG_TIME)
            {
                button.flag.num_long = 1;
                button.flag.num_not_long = 0;
                sButton.num_timeout = 0;
                // Return interrupt edge to normal value
                BUTTONS_IES &= ~BUTTON_NUM_PIN;
            }
        }
        else                    // there was a button press not long enough
        {
            sButton.num_timeout = 0;
        }
    }

    // Exit from LPM3 on RETI
    _BIC_SR_IRQ(LPM3_bits);
}
void process_all_events(void)
{	
	TROUT_FUNC_ENTER;

	if(reset_mac_trylock() == 0)
	{
		return;
      }
	
	atomic_set(&g_event_cnt, get_total_num_pending_events());
	stop_alarm(g_mac_event_timer);
	
    while(atomic_read(&g_event_cnt) > 0)
    {		     

#ifdef TROUT_WIFI_POWER_SLEEP_ENABLE
#ifdef WIFI_SLEEP_POLICY
	if (mutex_is_locked(&suspend_mutex) || (g_wifi_suspend_status != wifi_suspend_nosuspend)) {
		//libing, 20140114, fix fake connection
		pr_info("We can't do %s during suspending, g_wifi_suspend_status = %d\n", __func__, g_wifi_suspend_status);
	        reset_mac_unlock();  
                return; 	
	}
#endif
#endif
        /* Process pending events in the event queues */
        process_event_queues();
	if (counter_tmpr++ > 100)//by lihua
	{
		counter_tmpr = 0;
#ifdef WAKE_LOW_POWER_POLICY
			if(g_wifi_power_mode != WIFI_NORMAL_POWER_MODE)
			{
				pr_info("We can't do %s during low power mode, g_wifi_suspend_status = %d\n", __func__, g_wifi_suspend_status);
				break;
			}
#endif
		tempr_compensated();		
	}

#ifndef MAC_HW_UNIT_TEST_MODE
        /* Handle lack of memory for WLAN Rx packets */
//        handle_rxq_replenishment();
#endif /* MAC_HW_UNIT_TEST_MODE */

#ifdef BSS_ACCESS_POINT_MODE
#ifdef ENABLE_PS_PKT_FLUSH
        /* Find the STA with maximum PS buffers  */
        find_max_ps_ae();
#endif /* ENABLE_PS_PKT_FLUSH */
#endif /* BSS_ACCESS_POINT_MODE */

#ifdef INT_WPS_SUPP //wxb add
#ifdef IBSS_BSS_STATION_MODE
    /* Handle scan request from user/protocol */
    if(g_wps_scan_req_from_user == BTRUE)// caisf add for fix wps scan bug. 1121
    {
        handle_start_scan_req();//may be reset_mac
        g_wps_scan_req_from_user = BFALSE;
    }
#endif
#endif /* ifdef INT_WPS_SUPP  */

        /* Service Watchdog */
        service_wdt();
    }

	//chenq add 2012-11-02
//	if((BOOL_T)atomic_read(&g_mac_reset_done) == BFALSE)	//shield by chengwg, 2013-01-11!
//		return;

    /* Handle system error due to any failure */
	active_netif_queue();	//add by chengwg.
    	handle_system_error();//may be reset_mac
	/* Handle scan request from user/protocol */
	//chenq mask 2012-10-29
	//handle_start_scan_req();
#ifdef INT_WPS_SUPP //wxb add
#ifdef IBSS_BSS_STATION_MODE
    /* Handle scan request from user/protocol */
    if(g_wps_scan_req_from_user == BTRUE)// caisf add for fix wps scan bug. 1121
    {
        handle_start_scan_req(); //the function may be reset_mac
        g_wps_scan_req_from_user = BFALSE;
    }
#endif
#endif /* ifdef INT_WPS_SUPP  */

    /* Service Watchdog */
    service_wdt();
    
    if(get_total_num_pending_events() > 0)
	{    
	    if(g_mac_event_timer == NULL)
        {
            g_mac_event_timer = create_alarm(mac_time2event_work, 0, NULL);
        }
		
        start_alarm(g_mac_event_timer, 100);
	}
     reset_mac_unlock();
    TRACE_FUNC_EXIT;
}
static void stop_hs_wake_timer(void)
{
    stop_alarm(g_hs_wake_timer);
}
Ejemplo n.º 9
0
/**
 * SSMsg paresed form mqtt message handle function
 * @param ssmsg
 */
void ssmsg_handle(SSMsg *ssmsg,const char* topicname)
{
	uint8_t buffer[MQTT_BUFFER_LEN];
	int msg_len;

	switch(ssmsg->msgtype)
	{
		case get_gateway_msg_reqtype: //todo: 换成宏或者enum
		{
			FILE *fd;
			fd=fopen(GATEWAY_MSG_PATH,"rb");
			if (fd == NULL)
			{
				log_printf(LOG_ERROR, "Can't open %s file!\n",
						GATEWAY_MSG_PATH);
				return;
			}
			fseek(fd,0,SEEK_END);
			msg_len = ftell(fd);
			rewind(fd);
			fread(buffer,1,msg_len,fd);

			publish_msg_2_mqtts_qos0(topicname, protobuf_header, 0x0091, msg_len, buffer);
			fclose(fd);
		}
			break;
		case get_devlist_reqtype:
			msg_len=ss_pb_encode(buffer,sizeof(buffer),get_devlist_reqtype,NULL);
			publish_msg_2_mqtts_qos0(topicname, protobuf_header, 0x0091, msg_len, buffer);
			break;
		case set_allow_jonin_net_reqtype:
		{
			access_netword();
			char *args[] = {"0"};
			msg_len = ss_pb_encode(buffer,sizeof(buffer),set_allow_jonin_net_reqtype,args);
			publish_msg_2_mqtts_qos0(topicname,protobuf_header,3,msg_len,buffer);
		}
			break;
		case del_dev_reqtype:
		{
			char path[50]={'\0'};
			strcat(path,DEVINFO_DIR);
			strcat(path,ssmsg->nwk_addr);

			if(access(path,F_OK)==0)
			{

				if (!del_dev(ssmsg->nwk_addr, ssmsg->ieee,ssmsg->ep))
				{
					remove(path);

					char *args[] = {"0"};
					msg_len = ss_pb_encode(buffer,sizeof(buffer),del_dev_reqtype,args);
					publish_msg_2_mqtts_qos0(topicname,protobuf_header, 4 , msg_len,buffer);
				}

			} else
			{
				// dev doesn't exist, return failure code
				char* args[] = { "-1" };
				msg_len = ss_pb_encode(buffer, sizeof(buffer), del_dev_reqtype, args);
				publish_msg_2_mqtts_qos0(topicname, protobuf_header, 0x0091, msg_len,buffer);
			}

		}
			break;
		case stop_alarm_reqtype:
		{
			stop_alarm();
			char *args[] = {"0"};
			msg_len = ss_pb_encode(buffer,sizeof(buffer),stop_alarm_reqtype,args);
			publish_msg_2_mqtts_qos0(topicname,protobuf_header,7,msg_len,buffer);
		}
			break;
		default:
			break;
	}

}
Ejemplo n.º 10
0
__interrupt void PORT2_ISR(void)
{
    // Clear flags
    u8 int_flag, int_enable;
    u8 buzzer = 0;
    u8 simpliciti_button_event = 0;
    static u8 simpliciti_button_repeat = 0;

    // Remember interrupt enable bits
    int_enable = BUTTONS_IE;

    if ((!button.flag.star_long) && (!button.flag.num_long))
    {
        // Clear button flags
        button.all_flags = 0;

        // Store valid button interrupt flag
        int_flag = BUTTONS_IFG & int_enable;

        // ---------------------------------------------------
        // While SimpliciTI stack is active, buttons behave differently:
        //  - Store button events in SimpliciTI packet data
        //  - Exit SimpliciTI when button DOWN was pressed
        if (is_rf())
        {
            // Erase previous button press after a number of resends (increase number if link
            // quality is low)
            // This will create a series of packets containing the same button press
            // Necessary because we have no acknowledge
            // Filtering (edge detection) will be done by receiver software
            if (simpliciti_button_repeat++ > 6)
            {
                simpliciti_data[0] &= ~0xF0;
                simpliciti_button_repeat = 0;
            }

            if ((int_flag & BUTTON_STAR_PIN) == BUTTON_STAR_PIN)
            {
                simpliciti_data[0] |= SIMPLICITI_BUTTON_STAR;
                simpliciti_button_event = 1;
            }
            else if ((int_flag & BUTTON_NUM_PIN) == BUTTON_NUM_PIN)
            {
                simpliciti_data[0] |= SIMPLICITI_BUTTON_NUM;
                simpliciti_button_event = 1;
            }
            else if ((int_flag & BUTTON_UP_PIN) == BUTTON_UP_PIN)
            {
                simpliciti_data[0] |= SIMPLICITI_BUTTON_UP;
                simpliciti_button_event = 1;
            }
            else if ((int_flag & BUTTON_DOWN_PIN) == BUTTON_DOWN_PIN)
            {
                simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
            }

            // Trigger packet sending inside SimpliciTI stack
            if (simpliciti_button_event)
                simpliciti_flag |= SIMPLICITI_TRIGGER_SEND_DATA;
        }
        else                    // Normal operation
        {
            // Debounce buttons
            if ((int_flag & ALL_BUTTONS) != 0)
            {
                // Disable PORT2 IRQ
                __disable_interrupt();
                BUTTONS_IE = 0x00;
                __enable_interrupt();

                // Debounce delay 1
                Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_IN));

                // Reset inactivity detection
                sTime.last_activity = sTime.system_time;
            }

            // ---------------------------------------------------
            // STAR button IRQ
            if (IRQ_TRIGGERED(int_flag, BUTTON_STAR_PIN))
            {
                // Filter bouncing noise
                if (BUTTON_STAR_IS_PRESSED)
                {
                    button.flag.star = 1;
                    button.flag.star_not_long = 0;
                    // Generate button click
                    buzzer = 1;
                }
                else if ((BUTTONS_IES & BUTTON_STAR_PIN) == BUTTON_STAR_PIN)
                {
                    button.flag.star = 1;
                    button.flag.star_not_long = 0;
                    BUTTONS_IES &= ~BUTTON_STAR_PIN;
                }
            }
            // ---------------------------------------------------
            // NUM button IRQ
            else if (IRQ_TRIGGERED(int_flag, BUTTON_NUM_PIN))
            {
                // Filter bouncing noise
                if (BUTTON_NUM_IS_PRESSED)
                {
                    button.flag.num = 1;
                    button.flag.num_not_long = 0;
                    // Generate button click
                    buzzer = 1;
                }
                else if ((BUTTONS_IES & BUTTON_NUM_PIN) == BUTTON_NUM_PIN)
                {
                    button.flag.num = 1;
                    button.flag.num_not_long = 0;
                    BUTTONS_IES &= ~BUTTON_NUM_PIN;
                }
            }
            // ---------------------------------------------------
            // UP button IRQ
            else if (IRQ_TRIGGERED(int_flag, BUTTON_UP_PIN))
            {
                // Filter bouncing noise
                if (BUTTON_UP_IS_PRESSED)
                {
                    button.flag.up = 1;

                    // Generate button click
                    buzzer = 1;
                }
            }
            // ---------------------------------------------------
            // DOWN button IRQ
            else if (IRQ_TRIGGERED(int_flag, BUTTON_DOWN_PIN))
            {
                // Filter bouncing noise
                if (BUTTON_DOWN_IS_PRESSED)
                {
                    button.flag.down = 1;

                    // Generate button click
                    buzzer = 1;

                    // Faster reaction for stopwatch stop button press
                    if (is_stopwatch() && !sys.flag.lock_buttons)
                    {
                        stop_stopwatch();
                        button.flag.down = 0;
                    }
                }
            }
            // ---------------------------------------------------
            // B/L button IRQ
            else if (IRQ_TRIGGERED(int_flag, BUTTON_BACKLIGHT_PIN))
            {
                // Filter bouncing noise
                if (BUTTON_BACKLIGHT_IS_PRESSED)
                {
                    sButton.backlight_status = 1;
                    sButton.backlight_timeout = 0;
                    P2OUT |= BUTTON_BACKLIGHT_PIN;
                    P2DIR |= BUTTON_BACKLIGHT_PIN;
                }
            }
        }

        // Trying to lock/unlock buttons?
        if (button.flag.num && button.flag.down)
        {
            // No buzzer output
            buzzer = 0;
            button.all_flags = 0;
        }

        // Generate button click when button was activated
        if (buzzer)
        {
            // Any button event stops active alarm
            if (sAlarm.state == ALARM_ON)
            {
                stop_alarm();
                button.all_flags = 0;
            }
            else if (!sys.flag.up_down_repeat_enabled)
            {
                start_buzzer(1, CONV_MS_TO_TICKS(20), CONV_MS_TO_TICKS(150));
            }

            // Debounce delay 2
            Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_OUT));
        }

        // ---------------------------------------------------
        // Acceleration sensor IRQ
        if (IRQ_TRIGGERED(int_flag, AS_INT_PIN))
        {
            // Get data from sensor
            request.flag.acceleration_measurement = 1;
        }

        // ---------------------------------------------------
        // Pressure sensor IRQ
        if (IRQ_TRIGGERED(int_flag, PS_INT_PIN))
        {
            // Get data from sensor
            request.flag.altitude_measurement = 1;
        }

        // ---------------------------------------------------
        // Safe long button event detection
        if (button.flag.star || button.flag.num)
        {
            // Additional debounce delay to enable safe high detection - 50ms
            Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_LEFT));

            // Check if this button event is short enough
            if (BUTTON_STAR_IS_PRESSED)
            {
                // Change interrupt edge to detect button release
                BUTTONS_IES |= BUTTON_STAR_PIN;
                button.flag.star = 0;
                // This flag is used to detect if the user released the button before the
                // time for a long button press (3s)
                button.flag.star_not_long = 1;
            }
            if (BUTTON_NUM_IS_PRESSED)
            {
                // Change interrupt edge to detect button release
                BUTTONS_IES |= BUTTON_NUM_PIN;
                button.flag.num = 0;
                // This flag is used to detect if the user released the button before the
                // time for a long button press (3s)
                button.flag.num_not_long = 1;
            }
        }

    }
    // Reenable PORT2 IRQ
    __disable_interrupt();
    BUTTONS_IFG = 0x00;
    BUTTONS_IE = int_enable;
    __enable_interrupt();

    // Exit from LPM3/LPM4 on RETI
    __bic_SR_register_on_exit(LPM4_bits);
}
Ejemplo n.º 11
0
__interrupt void RTC_A_ISR(void)
#endif
{
	sTime.second++;
	if (sTime.second == 60) sTime.second = 0;
	
	static u8 button_lock_counter = 0; //gibbons TODO: need to put these just in the 1-sec interrupt section?
	static u8 button_beep_counter = 0;
	
#ifdef CONFIG_CW
	u8 CW_Message[] = "NOON\0";
#endif
	
	switch (RTCIV) {
		case RTC_RT0PSIFG: // Interval timer (16384Hz - 128Hz interrupts (binary powers) )
			// gibbons TODO: put stopwatch 1/100 sec interrupt here?
			break;
			
		case RTC_RT1PSIFG: // Interval timer (64Hz - 0.5Hz interrupts (binary powers) )
			break;
			
		case RTC_RTCRDYIFG: // RTC registers ready and safe to read (Use this for 1-sec update)
			
			// Add 1 second to stored (global) time, update sTime.drawFlag appropriately
			clock_tick();
			
			// Set clock update flag
			display.flag.update_time = 1;
			
			// While SimpliciTI stack operates or BlueRobin searches, freeze system state
			//pfs
#ifdef ELIMINATE_BLUEROBIN
			if (is_rf())
#else
			if (is_rf() || is_bluerobin_searching()) 
#endif
			{
				// SimpliciTI automatic timeout
				if (sRFsmpl.timeout == 0) 
				{
					simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
				}
				else
				{
					sRFsmpl.timeout--;
				}
				
				// Exit from LPM3 on RETI
				_BIC_SR_IRQ(LPM3_bits);     
				return;
			}
			
			// -------------------------------------------------------------------
			// Service modules that require 1/min processing
			if (sTime.drawFlag >= 2) 
			{
				// Measure battery voltage to keep track of remaining battery life
				request.flag.voltage_measurement = 1;
				
				// Check if alarm needs to be turned on
				//check_alarm(); //gibbons TODO: remove
			}

			// -------------------------------------------------------------------
			// Service active modules that require 1/s processing
			
#ifdef CONFIG_EGGTIMER
			if (sEggtimer.state == EGGTIMER_RUN) {
				eggtimer_tick(); // Subtract 1 second from eggtimer's count
			}
			
			if (sEggtimer.state == EGGTIMER_ALARM) { // no "else if" intentional
				// Decrement alarm duration counter
				if (sEggtimer.duration-- > 0)
				{
					request.flag.eggtimer_buzzer = 1;
				}
				else
				{
					stop_eggtimer_alarm(); // Set state to Stop and reset duration
				}
			}
#endif
			
			// Generate alarm signal
			if (sAlarm.state == ALARM_ON) 
			{
				// Decrement alarm duration counter
				if (sAlarm.duration-- > 0)
				{
					request.flag.alarm_buzzer = 1;
				}
				else
				{
					stop_alarm();
				}
			}

#ifdef CONFIG_PROUT
			if (is_prout()) prout_tick();
#endif

#ifdef CONFIG_VARIO
			if(is_vario()) vario_tick();
#endif

#ifdef CONFIG_STRENGTH
			// One more second gone by.
			if(is_strength())
			{
				strength_tick();
			}            
#endif

			// Do a temperature measurement each second while menu item is active
			if (is_temp_measurement()) request.flag.temperature_measurement = 1;
			
			// Do a pressure measurement each second while menu item is active
#ifdef CONFIG_ALTITUDE
			if (is_altitude_measurement()) 
			{
				// Countdown altitude measurement timeout while menu item is active
				sAlt.timeout--;

				// Stop measurement when timeout has elapsed
				if (sAlt.timeout == 0)	
				{
					stop_altitude_measurement();
					// Show ---- m/ft
					display_chars(LCD_SEG_L1_3_0, (u8*)"----", SEG_ON);
					// Clear up/down arrow
					display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
					display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
				}
				
				// In case we missed the IRQ due to debouncing, get data now
				if ((PS_INT_IN & PS_INT_PIN) == PS_INT_PIN) request.flag.altitude_measurement = 1;
			}	
#endif

#ifdef FEATURE_PROVIDE_ACCEL
			// Count down timeout
			if (is_acceleration_measurement()) 
			{
				// Countdown acceleration measurement timeout 
				sAccel.timeout--;

				// Stop measurement when timeout has elapsed
				if (sAccel.timeout == 0) as_stop();	
				
				// If DRDY is (still) high, request data again
				if ((AS_INT_IN & AS_INT_PIN) == AS_INT_PIN) request.flag.acceleration_measurement = 1; 
			}	
#endif

			//pfs
#ifndef ELIMINATE_BLUEROBIN
			// If BlueRobin transmitter is connected, get data from API
			if (is_bluerobin()) get_bluerobin_data();
#endif
			
			// If battery is low, decrement display counter
			if (sys.flag.low_battery)
			{
				if (sBatt.lobatt_display-- == 0) 
				{
					message.flag.prepare = 1;
					message.flag.type_lobatt = 1;
					sBatt.lobatt_display = BATTERY_LOW_MESSAGE_CYCLE;
				}
			}
			
			// If a message has to be displayed, set display flag
			if (message.all_flags)
			{
				if (message.flag.prepare)
				{
					message.flag.prepare = 0;
					message.flag.show    = 1;
				}
				else if (message.flag.erase) // message cycle is over, so erase it
				{
					message.flag.erase       = 0;
					message.flag.block_line1 = 0;
					message.flag.block_line2 = 0;
					display.flag.full_update = 1;
				}	
			}
			
			// -------------------------------------------------------------------
			// Check idle timeout, set timeout flag
			if (sys.flag.idle_timeout_enabled)
			{
			    if (sTime.last_activity > 0) {
				if (--sTime.last_activity == 0) sys.flag.idle_timeout = 1; //setFlag(sysFlag_g, SYS_TIMEOUT_IDLE);
			    }
			}
			
			// -------------------------------------------------------------------
			// Detect continuous button high states

			if (BUTTON_STAR_IS_PRESSED && BUTTON_UP_IS_PRESSED)
			{
				if (button_beep_counter++ > LEFT_BUTTON_LONG_TIME)
				{
					// Toggle no_beep buttons flag
					sys.flag.no_beep = ~sys.flag.no_beep;
			
					// Show "beep / nobeep" message synchronously with next second tick
					message.flag.prepare = 1;
					if (sys.flag.no_beep)	message.flag.type_no_beep_on   = 1;
					else					message.flag.type_no_beep_off  = 1;
					
					// Reset button beep counter
					button_beep_counter = 0;
				}
			} else if (BUTTON_NUM_IS_PRESSED && BUTTON_DOWN_IS_PRESSED) // Trying to lock/unlock buttons?
			{
				if (button_lock_counter++ > LEFT_BUTTON_LONG_TIME)
				{
					// Toggle lock / unlock buttons flag
					sys.flag.lock_buttons = ~sys.flag.lock_buttons;
			
					// Show "buttons are locked/unlocked" message synchronously with next second tick
					message.flag.prepare = 1;
					if (sys.flag.lock_buttons)	message.flag.type_locked   = 1;
					else						message.flag.type_unlocked = 1;
					
					// Reset button lock counter
					button_lock_counter = 0;
				}
			}
			else // Trying to create a long button press?
			{
				// Reset button lock counter
				button_lock_counter = 0;
				
				if (BUTTON_STAR_IS_PRESSED) 	
				{
					sButton.star_timeout++;
					
					// Check if button was held low for some seconds
					if (sButton.star_timeout > LEFT_BUTTON_LONG_TIME) 
					{
						button.flag.star_long = 1;
						sButton.star_timeout = 0;
					}
				}
				else
				{
					sButton.star_timeout = 0;
				}
			
				if (BUTTON_NUM_IS_PRESSED) 	
				{
					sButton.num_timeout++;
				
					// Check if button was held low for some seconds
					if (sButton.num_timeout > LEFT_BUTTON_LONG_TIME) 
					{
						button.flag.num_long = 1;
						sButton.num_timeout = 0;
					}
				}
				else
				{
					sButton.num_timeout = 0;
				}
			}
			
			
			// Exit from LPM3 on RETI
			_BIC_SR_IRQ(LPM3_bits); //gibbons TODO: move this to other interrupts from the RTC?
			
			break;
			
		case RTC_RTCTEVIFG: // Interval alarm event (min or hour changed, or rollover to midnight or noon) (choose one)
			// Minute, hour, noon, or midnight rollover beep (same beep as button press, at least for now)
#ifdef CONFIG_TIMECHIME
#ifdef CONFIG_CW
			CW_Send_String(CW_Message);
#else
			start_buzzer(1, CONV_MS_TO_TICKS(20), CONV_MS_TO_TICKS(150));
#endif
			if (RTC_Toggle_12Hr) RTCCTL01 ^= 0x0100; // Toggle Time EVent between noon and midnight
#endif
			break;
			
		case RTC_RTCAIFG: // User-configurable alarm event
			// Indicate that alarm is on
			sAlarm.state = ALARM_ON;
			
			break;
	}

	//gibbons: TODO: Remove this old code? (Associated with Timer0_A0 1-sec ISR)
	// Disable IE 
	//TA0CCTL0 &= ~CCIE;
	// Reset IRQ flag  
	//TA0CCTL0 &= ~CCIFG;  
	// Add 1 sec to TACCR0 register (IRQ will be asserted at 0x7FFF and 0xFFFF = 1 sec intervals)
	//TA0CCR0 += 32768; //gibbons TODO: Should this perhaps be (32768 - 1) ?
	// Enable IE 
	//TA0CCTL0 |= CCIE;
}
Ejemplo n.º 12
0
Archivo: ports.c Proyecto: epall/cage
__interrupt void PORT2_ISR(void)
{
	u8 int_flag, int_enable;
	u8 buzzer = 0;
	u8 simpliciti_button_event = 0;
	static u8 simpliciti_button_repeat = 0;

	// Clear button flags
	button.all_flags = 0;

	// Remember interrupt enable bits
	int_enable = BUTTONS_IE;

	// Store valid button interrupt flag
	int_flag = BUTTONS_IFG & int_enable;

	// ---------------------------------------------------
	// While SimpliciTI stack is active, buttons behave differently:
	//  - Store M1/M2/S1 button events in SimpliciTI packet data
	//  - Exit SimpliciTI when S2 was pressed 
  	if (is_rf())
  	{
  		// Erase previous button press after a number of resends (increase number if link quality is low)
  		// This will create a series of packets containing the same button press
  		// Necessary because we have no acknowledge
  		// Filtering (edge detection) will be done by receiver software
  		if (simpliciti_button_repeat++ > 6) 
  		{
  			simpliciti_data[0] &= ~0xF0;
  			simpliciti_button_repeat = 0;
  		}
  		
  		if ((int_flag & BUTTON_M1_PIN) == BUTTON_M1_PIN)			
  		{
  			simpliciti_data[0] |= SIMPLICITI_BUTTON_M1;
  			simpliciti_button_event = 1;
  		}
  		else if ((int_flag & BUTTON_M2_PIN) == BUTTON_M2_PIN)	
  		{
  			simpliciti_data[0] |= SIMPLICITI_BUTTON_M2;
  			simpliciti_button_event = 1;
  		}
		else if ((int_flag & BUTTON_S1_PIN) == BUTTON_S1_PIN)	
		{
			simpliciti_data[0] |= SIMPLICITI_BUTTON_S1;
			simpliciti_button_event = 1;
		}
		else if ((int_flag & BUTTON_S2_PIN) == BUTTON_S2_PIN)	
		{
			simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
		}
		
		// Trigger packet sending inside SimpliciTI stack
		if (simpliciti_button_event) simpliciti_flag |= SIMPLICITI_TRIGGER_SEND_DATA;
  	}
  	else // Normal operation
  	{
		// Debounce buttons
		if ((int_flag & ALL_BUTTONS) != 0)
		{ 
			// Disable PORT2 IRQ
			__disable_interrupt();
			BUTTONS_IE = 0x00; 
			__enable_interrupt();
	
			// Debounce delay 1
			Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_IN));
	
			// Reset inactivity detection
			sTime.last_activity = sTime.system_time;
			
			// Reset M button high detection
			sTime.previous_m_button_event = sTime.system_time;
		}

		// ---------------------------------------------------
		// M1 button IRQ
		if (IRQ_TRIGGERED(int_flag, BUTTON_M1_PIN))
		{
			// Filter bouncing noise 
			if (BUTTON_M1_IS_PRESSED)
			{
				button.flag.m1 = 1;
				
				sys.flag.mask_m1_button = 0;
		
				// Generate button click
				buzzer = 1;
			}
		}
		// ---------------------------------------------------
		// M2 button IRQ
		else if (IRQ_TRIGGERED(int_flag, BUTTON_M2_PIN))
		{
			// Filter bouncing noise 
			if (BUTTON_M2_IS_PRESSED)
			{
				button.flag.m2 = 1;
				
				sys.flag.mask_m2_button = 0;
	
				// Generate button click
				buzzer = 1;
			}
		}
		// ---------------------------------------------------
		// S1 button IRQ
		else if (IRQ_TRIGGERED(int_flag, BUTTON_S1_PIN))
		{
			// Filter bouncing noise 
			if (BUTTON_S1_IS_PRESSED)
			{
				button.flag.s1 = 1;
		
				// Generate button click
				buzzer = 1;
			}
		}
		// ---------------------------------------------------
		// S2 button IRQ
		else if (IRQ_TRIGGERED(int_flag, BUTTON_S2_PIN))
		{
			// Filter bouncing noise 
			if (BUTTON_S2_IS_PRESSED)
			{
				button.flag.s2 = 1;
	
				// Generate button click
				buzzer = 1;
				
				// Faster reaction for stopwatch stop button press
				if (is_stopwatch()) 
				{
					stop_stopwatch();
					button.flag.s2 = 0;
				}
					
			}
		}
		// ---------------------------------------------------
		// B/L button IRQ
		else if (IRQ_TRIGGERED(int_flag, BUTTON_BL_PIN))
		{
			// Filter bouncing noise 
			if (BUTTON_BL_IS_PRESSED)
			{
				button.flag.bl = 1;
			}
		}	
	}

	// Generate button click when button was activated
	if (buzzer)
	{
		// Any button event stops active alarm
		if (sAlarm.state == ALARM_ON) 
		{
			stop_alarm();
			button.all_flags = 0;
		}
		else if (!sys.flag.s_button_repeat_enabled)
		{
			start_buzzer(1, CONV_MS_TO_TICKS(20), CONV_MS_TO_TICKS(150));
		}
		
		// Debounce delay 2
		Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_OUT));
	}
	
	// ---------------------------------------------------
	// Acceleration sensor IRQ
	if (IRQ_TRIGGERED(int_flag, AS_INT_PIN))
	{
		// Get data from sensor
		request.flag.acceleration_measurement = 1;
  	}
  	
  	// ---------------------------------------------------
	// Pressure sensor IRQ
	if (IRQ_TRIGGERED(int_flag, PS_INT_PIN)) 
	{
		// Get data from sensor
		request.flag.altitude_measurement = 1;
  	}
  	
  	// ---------------------------------------------------
  	// Enable safe long button event detection
  	if(button.flag.m1 || button.flag.m2) 
	{
		// Additional debounce delay to enable safe high detection
		Timer0_A4_Delay(CONV_MS_TO_TICKS(BUTTONS_DEBOUNCE_TIME_M));
	
		// Check if this button event is short enough
		if (BUTTON_M1_IS_PRESSED) button.flag.m1 = 0;
		if (BUTTON_M2_IS_PRESSED) button.flag.m2 = 0;	
	}
	
	// Reenable PORT2 IRQ
	__disable_interrupt();
	BUTTONS_IFG = 0x00; 	
	BUTTONS_IE  = int_enable; 	
	__enable_interrupt();

	// Exit from LPM3/LPM4 on RETI
	__bic_SR_register_on_exit(LPM4_bits); 
}
 // Sounds the alarm
 void alarm() {
   buzzer->write(0);
   sleep(1);
   stop_alarm();
 }
Ejemplo n.º 14
0
__interrupt void TIMER0_A0_ISR(void)
#endif
{
	static u8 button_lock_counter = 0;
	static u8 button_beep_counter = 0;
	
	// Disable IE 
	TA0CCTL0 &= ~CCIE;
	// Reset IRQ flag  
	TA0CCTL0 &= ~CCIFG;  
	// Add 1 sec to TACCR0 register (IRQ will be asserted at 0x7FFF and 0xFFFF = 1 sec intervals)
	TA0CCR0 += 32768;
	// Enable IE 
	TA0CCTL0 |= CCIE;
	
	// Add 1 second to global time
	clock_tick();
	
	// Set clock update flag
	display.flag.update_time = 1;
	
	// While SimpliciTI stack operates or BlueRobin searches, freeze system state
	//pfs
	#ifdef ELIMINATE_BLUEROBIN
	if (is_rf())
	#else
	if (is_rf() || is_bluerobin_searching()) 
	#endif
	{
		// SimpliciTI automatic timeout
		if (sRFsmpl.timeout == 0) 
		{
			simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
		}
		else
		{
			sRFsmpl.timeout--;
		}
		
		// Exit from LPM3 on RETI
		_BIC_SR_IRQ(LPM3_bits);     
		return;
	}
	
	// -------------------------------------------------------------------
	// Service modules that require 1/min processing
	if (sTime.drawFlag >= 2) 
	{
		#ifdef CONFIG_BATTERY
		// Measure battery voltage to keep track of remaining battery life
		request.flag.voltage_measurement = 1;
		#endif
		
		#ifdef CONFIG_ALARM
		// If the chime is enabled, we beep here
		if (sTime.minute == 0) {
			if (sAlarm.hourly == ALARM_ENABLED) {
				request.flag.alarm_buzzer = 1;
			}
            #if (CONFIG_DST > 0)
            if ((sTime.hour == 1) &&
                (dst_state == 0) &&
                dst_isDateInDST(sDate.month, sDate.day))
            {
                // spring forward
                sTime.hour++;
                dst_state = 1;
            }
            if ((sTime.hour == 2) &&
                (dst_state != 0) &&
                (!dst_isDateInDST(sDate.month, sDate.day)))
            {
                // fall back
                sTime.hour--;
                dst_state = 0;
            }
            #endif
		}
		// Check if alarm needs to be turned on
		check_alarm();
		#endif
		#ifdef CONFIG_ALTI_ACCUMULATOR
		// Check if we need to do an altitude accumulation
		if (alt_accum_enable)
			request.flag.altitude_accumulator = 1;
		#endif
	}

	// -------------------------------------------------------------------
	// Service active modules that require 1/s processing
#ifdef CONFIG_EGGTIMER
	if (sEggtimer.state == EGGTIMER_RUN) {
		eggtimer_tick(); // Subtract 1 second from eggtimer's count
	}

	if (sEggtimer.state == EGGTIMER_ALARM) { // no "else if" intentional
		// Decrement alarm duration counter
		if (sEggtimer.duration-- > 0)
		{
			request.flag.eggtimer_buzzer = 1;
		}
		else
		{
			stop_eggtimer_alarm(); // Set state to Stop and reset duration
		}
	}
#endif
	#ifdef CONFIG_ALARM
	// Generate alarm signal
	if (sAlarm.state == ALARM_ON) 
	{
		// Decrement alarm duration counter
		if (sAlarm.duration-- > 0)
		{
			request.flag.alarm_buzzer = 1;
		}
		else
		{
			sAlarm.duration = ALARM_ON_DURATION;
			stop_alarm();
		}
	}
	#endif
	
#ifdef CONFIG_PROUT
        if (is_prout()) prout_tick();
#endif
		
#ifdef CONFIG_STRENGTH
        // One more second gone by.
        if(is_strength())
	{
		strength_tick();
	}            
#endif

	// Do a temperature measurement each second while menu item is active
	if (is_temp_measurement()) request.flag.temperature_measurement = 1;
	
	// Do a pressure measurement each second while menu item is active
#ifdef CONFIG_ALTITUDE
	if (is_altitude_measurement()) 
	{
		// Countdown altitude measurement timeout while menu item is active
		sAlt.timeout--;

		// Stop measurement when timeout has elapsed
		if (sAlt.timeout == 0)	
		{
			stop_altitude_measurement();
			// Show ---- m/ft
			display_chars(LCD_SEG_L1_3_0, (u8*)"----", SEG_ON);
			// Clear up/down arrow
			display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
			display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
		}
		
		// In case we missed the IRQ due to debouncing, get data now
		if ((PS_INT_IN & PS_INT_PIN) == PS_INT_PIN) request.flag.altitude_measurement = 1;
	}	
#endif

#ifdef FEATURE_PROVIDE_ACCEL
	// Count down timeout
	if (is_acceleration_measurement()) 
	{
		// Countdown acceleration measurement timeout 
		sAccel.timeout--;

		// Stop measurement when timeout has elapsed
		if (sAccel.timeout == 0) as_stop();	
		
		// If DRDY is (still) high, request data again
		if ((AS_INT_IN & AS_INT_PIN) == AS_INT_PIN) request.flag.acceleration_measurement = 1; 
	}	
#endif

	//pfs
#ifndef ELIMINATE_BLUEROBIN
	// If BlueRobin transmitter is connected, get data from API
	if (is_bluerobin()) get_bluerobin_data();
#endif
	
	#ifdef CONFIG_BATTERY
	// If battery is low, decrement display counter
	if (sys.flag.low_battery)
	{
		if (sBatt.lobatt_display-- == 0) 
		{
			message.flag.prepare = 1;
			message.flag.type_lobatt = 1;
			sBatt.lobatt_display = BATTERY_LOW_MESSAGE_CYCLE;
		}
	}
	#endif
	
	// If a message has to be displayed, set display flag
	if (message.all_flags)
	{
		if (message.flag.prepare)
		{
			message.flag.prepare = 0;
			message.flag.show    = 1;
		}
		else if (message.flag.erase) // message cycle is over, so erase it
		{
			message.flag.erase       = 0;
			message.flag.block_line1 = 0;
			message.flag.block_line2 = 0;
			display.flag.full_update = 1;
		}	
	}
	
	// -------------------------------------------------------------------
	// Check idle timeout, set timeout flag
	if (sys.flag.idle_timeout_enabled)
	{
		if (sTime.system_time - sTime.last_activity > INACTIVITY_TIME) sys.flag.idle_timeout = 1; //setFlag(sysFlag_g, SYS_TIMEOUT_IDLE);
	}
	
	// -------------------------------------------------------------------
	// Turn the Backlight off after timeout
	if (sButton.backlight_status == 1)
	{
		if (sButton.backlight_timeout > BACKLIGHT_TIME_ON)
		{
			//turn off Backlight
			P2OUT &= ~BUTTON_BACKLIGHT_PIN;
			P2DIR &= ~BUTTON_BACKLIGHT_PIN;
			sButton.backlight_timeout = 0;
			sButton.backlight_status = 0;
		}
		else
		{
			sButton.backlight_timeout++;
		}
	}
	// -------------------------------------------------------------------
	// Detect continuous button high states

	if (BUTTON_STAR_IS_PRESSED && BUTTON_UP_IS_PRESSED)
	{
		if (button_beep_counter++ > LEFT_BUTTON_LONG_TIME)
		{
			// Toggle no_beep buttons flag
			sys.flag.no_beep = ~sys.flag.no_beep;
	
			// Show "beep / nobeep" message synchronously with next second tick
			message.flag.prepare = 1;
			if (sys.flag.no_beep)	message.flag.type_no_beep_on   = 1;
			else					message.flag.type_no_beep_off  = 1;
			
			// Reset button beep counter
			button_beep_counter = 0;
		}
	} else if (BUTTON_NUM_IS_PRESSED && BUTTON_DOWN_IS_PRESSED) // Trying to lock/unlock buttons?
	{
		if (button_lock_counter++ > LEFT_BUTTON_LONG_TIME)
		{
			// Toggle lock / unlock buttons flag
			sys.flag.lock_buttons = ~sys.flag.lock_buttons;
	
			// Show "buttons are locked/unlocked" message synchronously with next second tick
			message.flag.prepare = 1;
			if (sys.flag.lock_buttons)	message.flag.type_locked   = 1;
			else						message.flag.type_unlocked = 1;
			
			// Reset button lock counter
			button_lock_counter = 0;
		}
	}
	else // Trying to create a long button press?
	{
		// Reset button lock counter
		button_lock_counter = 0;
		
		if (BUTTON_STAR_IS_PRESSED) 	
		{
			sButton.star_timeout++;
			
			// Check if button was held low for some seconds
			if (sButton.star_timeout > LEFT_BUTTON_LONG_TIME) 
			{
				button.flag.star_long = 1;
				sButton.star_timeout = 0;
			}
		}
		else
		{
			sButton.star_timeout = 0;
		}
	
		if (BUTTON_NUM_IS_PRESSED) 	
		{
			sButton.num_timeout++;
		
			// Check if button was held low for some seconds
			if (sButton.num_timeout > LEFT_BUTTON_LONG_TIME) 
			{
				button.flag.num_long = 1;
				sButton.num_timeout = 0;
			}
		}
		else
		{
			sButton.num_timeout = 0;
		}
	}
	
	// Exit from LPM3 on RETI
	_BIC_SR_IRQ(LPM3_bits);               
}
Ejemplo n.º 15
0
/* Search thread main function */
void *search_loop(void *arg) {
    uint8_t ply;
    move_t mv, mv_tmp;

    SET_BLANK_MOVE(mv);
    SET_BLANK_MOVE(mv_tmp);

    pthread_mutex_lock(&mutex);

    /* Initializations */
    precompute_moves();
    precompute_distances();
    init_zobrist_keys();
    init_history();
    init_transposition_table();
    config_alarm(config->max_seconds);
    max_depth = config->max_depth;

    /* Setup board */
    board = set_board("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
    if(board == NULL)
    	quit("Error: Could not setup new board!\n");

    /* ECO = encyclopedia of chess openings */

    if(atoi(config->name) >= 50)
        if(!load_eco(board))
            quit("Error: Could not load Encyclopedia of Chess Openings!\n");

    pthread_mutex_unlock(&mutex);
 
    /* Keep alive until the status changes to QUIT */
    while(status != QUIT) {
    	switch(status) {
    	case NOP:
    	    /* NOP: just wait for a change in status */
    	    pthread_mutex_lock(&mutex);
    	    while(status == NOP)
    	    	pthread_cond_wait(&cond, &mutex);
    	    pthread_mutex_unlock(&mutex);
    	    break;
    	case FORCE:
    	    /* FORCE: wait for a change in status but don't start searches */
    	    pthread_mutex_lock(&mutex);
    	    while(status == FORCE)
    	    	pthread_cond_wait(&cond, &mutex);
    	    pthread_mutex_unlock(&mutex);
    	    break;
    	case SEARCH:
    	    /* Iterative Deepening Search */
    	    /* Save the on-move color */
    	    onmove = board->onmove;
    	    /* Sets as blank the move to be played*/
    	    SET_BLANK_MOVE(mv);
    	    /* Starts counting the time */
    	    start_alarm();
    	    /* For each depth, search with alpha-beta minimax */
    	    for(ply = 2; ply <= max_depth; ply += 2) {
    	    	mv_tmp = alpha_beta(board, -MAX_HEU, MAX_HEU, ply);
    	    	/* Did we run out of time? If so, stops deepening iterations */
    	    	if(get_timeout())
    	    	    break;
    	    	mv = mv_tmp;
    	    }
    	    /* Stops counting the time, if it hasn't already reached limit */
    	    stop_alarm();
    	    /* If the move is still blank, use the partial move found */
    	    if(IS_BLANK_MOVE(mv))
    	    	mv = mv_tmp;
    	    /* Perform the move found in the search */
    	    move(board, mv);
    	    /* Returns to the NOP status */
    	    set_status(NOP);
    	    break;
    	case PONDER:
    	    /* Reserved for future use */
    	    set_status(NOP);
    	    break;
    	default:
    	    quit("Error: Invalid search status!\n");
    	}
    }
    
    /* Clean up memory */
    clear_eco();
    clear_transposition_table();
    clear_history();
    clear_board(board);

    /* Exit Search Thread */
    return NULL;
}
Ejemplo n.º 16
0
int llopen(char * porta, int flag) {

    printf("FLAG (TRANS/REC) = %d \n", flag);
    info = malloc(sizeof(struct Info));
    info->dados = malloc(255);
    info->frameTemp = malloc(255);
    info->frameSend = malloc(255);
    info->timeout = timeOut;
    install_handler(atende, info->timeout);
    //printf("sequenceNumber: %d \n", info->sequenceNumber);
    info->tentativas = tentativas;
    info->flag = flag;

    info->endPorta = malloc(255);
    info->endPorta = porta;
    info->fd = open(info->endPorta, O_RDWR | O_NOCTTY);
    if (info->fd < 0) {
        perror(info->endPorta);
        exit(-1);
    }

    if ( tcgetattr(info->fd,&info->oldtio) == -1) { // save current port settings
        perror("tcgetattr");
        return -1;
    }

    bzero(&info->newtio, sizeof(info->newtio));

    info->newtio.c_cflag = BaudRate | CS8 | CLOCAL | CREAD;
    info->newtio.c_iflag = IGNPAR;
    info->newtio.c_oflag = OPOST;

    // set input mode (non-canonical, no echo,...)
    info->newtio.c_lflag = 0;

    info->newtio.c_cc[VTIME]    = 0;   // inter-character timer unused
    info->newtio.c_cc[VMIN]     = 1;   // blocking read until 5 chars received

    tcflush(info->fd, TCIFLUSH);

    if ( tcsetattr(info->fd,TCSANOW,&info->newtio) == -1) {
        perror("tcsetattr");
        return -1;
    }

    if (flag == TRANSMITTER) {
        printf("llopen de transmissor \n");
        buildFrame(flag, "set");
        transmitirFrame(info->frameSend, info->frameSendLength);
        while(info->tentativas > 0) {
            //printf("tentativasOpen = %d \n", info->tentativas);
            start_alarm();
            info->frameTempLength = readFrame(info->frameTemp);
            if (verifyFrame(info->frameTemp, info->frameTempLength, "ua")) {
                stop_alarm();
                info->tentativas = tentativas;
                return 1;
            }
        }
        if (info->tentativas == 0) {
            printf("Número de tentativas chegou ao fim. \n");
            exit(-1);
        }
    }
    else {
        printf("llopen de recetor \n");
        info->frameTempLength = readFrame(info->frameTemp);
        if (verifyFrame(info->frameTemp, info->frameTempLength, "set")) {
            buildFrame(flag, "ua");
            transmitirFrame(info->frameSend, info->frameSendLength);
            //printf("terminar llopen recetor \n");
            return 1;
        }
    }

    return info->fd;
}
Ejemplo n.º 17
0
__interrupt void TIMER0_A0_ISR(void)
{
	static u8 button_lock_counter = 0;
	
	// Disable IE 
	TA0CCTL0 &= ~CCIE;
	// Reset IRQ flag  
	TA0CCTL0 &= ~CCIFG;  
	// Add 1 sec to TACCR0 register (IRQ will be asserted at 0x7FFF and 0xFFFF = 1 sec intervals)
	TA0CCR0 += 32768;
	// Enable IE 
	TA0CCTL0 |= CCIE;
	
	// Add 1 second to global time
	clock_tick();

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Count down and up
	if (sCountup.mode == COUNTUP_MODE_ON)
	{
		countup_tick();

		if (sCountdown.mode == COUNTDOWN_MODE_ON)
		{
			// Countdown acceleration measurement timeout
			sAccel.timeout--;

			// Stop measurement when timeout has elapsed
			if (sAccel.timeout == 0) as_stop();

			// If DRDY is (still) high, request data again
			if ((AS_INT_IN & AS_INT_PIN) == AS_INT_PIN) request.flag.acceleration_measurement = 1;

			// sAccel.xyz[0] = xaxis, sAccel.xyz[0] = yaxis, sAccel.xyz[0] = zaxis

			if ((sAccel.xyz[0] < sCountdown.thresholdlow[0] || sAccel.xyz[0] > sCountdown.thresholdhigh[0]) &&
				(sAccel.xyz[1] < sCountdown.thresholdlow[1] || sAccel.xyz[1] > sCountdown.thresholdhigh[1]))
			{
			// UNDER THRESHOLD VALUES
				if (sCountdown.speed == 1)
				{
					// Clear timer interrupt enable
					TA0CCTL2 &= ~CCIE;

					countdown_tick();
				}
				if (sCountdown.speed == 2)
				{
					// Recovery loop - set back to default as below threshold
					if (sCountdown.exceedcount[0] != sCountdown.exceeddefault[0])
					{
						sCountdown.exceedcount[0] = sCountdown.exceeddefault[0];
					}

					// Recovery loop - reduce recovery value if under threshold
					if (sCountdown.recoverycount != 0)
					{
						sCountdown.recoverycount--;
					}
					// Set speed to 1 if recovery is back to 0
					else
					{
						sCountdown.speed = 1;
						sCountdown.recoverycount = sCountdown.recoverydefault;
						countdown_tick();
					}
				}
				if (sCountdown.speed == 3)
				{
					// Recovery loop - set back to default as below threshold
					if (sCountdown.exceedcount[1] != sCountdown.exceeddefault[1])
					{
						sCountdown.exceedcount[1] = sCountdown.exceeddefault[1];
					}

					// Recovery loop - reduce recovery value if under threshold
					if (sCountdown.recoverycount != 0)
					{
						sCountdown.recoverycount--;
					}
					// Set speed to 1 if recovery is back to 0
					else
					{
						sCountdown.speed = 1;
						sCountdown.recoverycount = sCountdown.recoverydefault;
						countdown_tick();
					}
				}
			}
			// OVER THRESHOLD VALUES
			else
			{

				sCountdown.recoverycount = sCountdown.recoverydefault;

				if (sCountdown.speed == 1)
				{
					// Increase countdown speed
					sCountdown.speed = 2;

					// Init CCR register with current time
					TA0CCR2 = TA0R;

					// Load CCR register with next capture time
					TA0CCR2 += sCountdown.tickspeed[0];

					// Reset IRQ flag
					TA0CCTL2 &= ~CCIFG;

					// Enable timer interrupt
					TA0CCTL2 |= CCIE;

					countdown_tick();
				}
				if (sCountdown.speed == 2)
				{
					// Counting down from exceed2 limit
					if (sCountdown.exceedcount[0] != 0)
					{
						sCountdown.exceedcount[0]--;
					}
					// Speed up if equal to 0
					else
					{
						sCountdown.exceedcount[0] = sCountdown.exceeddefault[0];

						// Increase countdown speed
						sCountdown.speed = 3;
					}
				}
				if (sCountdown.speed == 3)
				{
					// Counting down from exceed3 limit
					if (sCountdown.exceedcount[1] != 0)
					{
						sCountdown.exceedcount[1]--;
					}
					// Speed up if equal to 0
					else
					{
						countdown_droptozero();
					}
				}
			}
		}
	}
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	// Set clock update flag
	display.flag.update_time = 1;
	
	// While SimpliciTI stack operates or BlueRobin searches, freeze system state
	if (is_rf() || is_bluerobin_searching()) 
	{
		// SimpliciTI automatic timeout
		if (sRFsmpl.timeout == 0) 
		{
			simpliciti_flag |= SIMPLICITI_TRIGGER_STOP;
		}
		else
		{
			sRFsmpl.timeout--;
		}
		
		// Exit from LPM3 on RETI
		_BIC_SR_IRQ(LPM3_bits);     
		return;
	}
	
	// -------------------------------------------------------------------
	// Service modules that require 1/min processing
	if (sTime.drawFlag >= 2) 
	{
		// Measure battery voltage to keep track of remaining battery life
		request.flag.voltage_measurement = 1;
		
		// Check if alarm needs to be turned on
		check_alarm();
	}

	// -------------------------------------------------------------------
	// Service active modules that require 1/s processing
	
	// Generate alarm signal
	if (sAlarm.state == ALARM_ON) 
	{
		// Decrement alarm duration counter
		if (sAlarm.duration-- > 0)
		{
			request.flag.buzzer = 1;
		}
		else
		{
			sAlarm.duration = ALARM_ON_DURATION;
			stop_alarm();
		}
	}

	// Do a temperature measurement each second while menu item is active
	if (is_temp_measurement()) request.flag.temperature_measurement = 1;
	
	// Do a pressure measurement each second while menu item is active
	if (is_altitude_measurement()) 
	{
		// Countdown altitude measurement timeout while menu item is active
		sAlt.timeout--;

		// Stop measurement when timeout has elapsed
		if (sAlt.timeout == 0)	
		{
			stop_altitude_measurement();
			// Show ---- m/ft
			display_chars(LCD_SEG_L1_3_0, (u8*)"----", SEG_ON);
			// Clear up/down arrow
			display_symbol(LCD_SYMB_ARROW_UP, SEG_OFF);
			display_symbol(LCD_SYMB_ARROW_DOWN, SEG_OFF);
		}
		
		// In case we missed the IRQ due to debouncing, get data now
		if ((PS_INT_IN & PS_INT_PIN) == PS_INT_PIN) request.flag.altitude_measurement = 1;
	}	

	// Count down timeout
	if (is_acceleration_measurement()) 
	{
		// Countdown acceleration measurement timeout 
		sAccel.timeout--;

		// Stop measurement when timeout has elapsed
		if (sAccel.timeout == 0) as_stop();	
		
		// If DRDY is (still) high, request data again
		if ((AS_INT_IN & AS_INT_PIN) == AS_INT_PIN) request.flag.acceleration_measurement = 1; 
	}	

	// If BlueRobin transmitter is connected, get data from API
	if (is_bluerobin()) get_bluerobin_data();
	
	// If battery is low, decrement display counter
	if (sys.flag.low_battery)
	{
		if (sBatt.lobatt_display-- == 0) 
		{
			message.flag.prepare = 1;
			message.flag.type_lobatt = 1;
			sBatt.lobatt_display = BATTERY_LOW_MESSAGE_CYCLE;
		}
	}
	
	// If a message has to be displayed, set display flag
	if (message.all_flags)
	{
		if (message.flag.prepare)
		{
			message.flag.prepare = 0;
			message.flag.show    = 1;
		}
		else if (message.flag.erase) // message cycle is over, so erase it
		{
			message.flag.erase       = 0;
			display.flag.full_update = 1;
		}	
	}
	
	// -------------------------------------------------------------------
	// Check idle timeout, set timeout flag
	if (sys.flag.idle_timeout_enabled)
	{
		if (sTime.system_time - sTime.last_activity > INACTIVITY_TIME) sys.flag.idle_timeout = 1; //setFlag(sysFlag_g, SYS_TIMEOUT_IDLE);
	}
	
	// -------------------------------------------------------------------
	// Detect continuous button high states
	
	// Trying to lock/unlock buttons?
	if (BUTTON_NUM_IS_PRESSED && BUTTON_DOWN_IS_PRESSED)
	{
		if (button_lock_counter++ > LEFT_BUTTON_LONG_TIME)
		{
			// Toggle lock / unlock buttons flag
			sys.flag.lock_buttons = ~sys.flag.lock_buttons;
	
			// Show "buttons are locked/unlocked" message synchronously with next second tick
			message.flag.prepare = 1;
			if (sys.flag.lock_buttons)	message.flag.type_locked   = 1;
			else						message.flag.type_unlocked = 1;
			
			// Reset button lock counter
			button_lock_counter = 0;
		}
	}
	else // Trying to create a long button press?
	{
		// Reset button lock counter
		button_lock_counter = 0;
		
		if (BUTTON_UP_IS_PRESSED)
		{
			sButton.up_timeout++;
			
			// Check if button was held low for some seconds
			if (sButton.up_timeout > LEFT_BUTTON_LONG_TIME)
			{
				button.flag.up_long = 1;
				sButton.up_timeout = 0;
			}
		}
		else
		{
			sButton.up_timeout = 0;
		}
	
		if (BUTTON_DOWN_IS_PRESSED)
		{
			sButton.down_timeout++;
		
			// Check if button was held low for some seconds
			if (sButton.down_timeout > LEFT_BUTTON_LONG_TIME)
			{
				button.flag.down_long = 1;
				sButton.down_timeout = 0;
			}
		}
		else
		{
			sButton.down_timeout = 0;
		}

		if (BUTTON_NUM_IS_PRESSED)
		{
			sButton.num_timeout++;

			// Check if button was held low for some seconds
			if (sButton.num_timeout > LEFT_BUTTON_LONG_TIME)
			{
				button.flag.num_long = 1;
				sButton.num_timeout = 0;
			}
		}
		else
		{
			sButton.num_timeout = 0;
		}
	}
	
	// Exit from LPM3 on RETI
	_BIC_SR_IRQ(LPM3_bits);               
}