Exemplo n.º 1
0
static int __client_auth(modem_status_t status)
{
    bson        req;
    modem_ret_t ret;

    (void)status;


    switch (__auth) {
    case DEV_AUTH:     /* Already authenticated */
        return 0;
    case DEV_NOAUTH:   /* No auth, no request sent */
        printf("Sending authentication request.\n");

        req = __auth_form_req();
        if (req.err != BSON_VALID)
            return -1;

        ret = modem_send_packet(TCS_SERVICE_PROF,
                                (uint8_t *)req.data, bson_size(&req));
        bson_destroy(&req);
        printf("Auth request sent=%d\n", ret);
        if (ret != MODEM_RET_OK)
            return -1;

        __auth      = DEV_AUTHWAIT;
        __auth_tries = 0;
        break;
    case DEV_AUTHWAIT: /* No auth, request sent */
        if (__auth_tries > AUTH_MAX_TRIES) { /* Reply wait limit exceeded */
            __auth = DEV_NOAUTH;
            return -1;
        }

        if (__check_auth_reply() == 0) {
            __auth = DEV_AUTH;
            return 0;
        }

        __auth_tries ++;
        break;
    }

    return 1;
}
Exemplo n.º 2
0
Arquivo: main.c Projeto: kLabUM/IoT
void main(){

    CyGlobalIntEnable;

    // Start up initial mote processes
    SleepTimer_Start();
    isr_SleepTimer_StartEx(sleepTimerWake_INT);
    FS_Init();  // SD Card
    modem_set_api_feed(FEED_ID, API_KEY);
    modem_start();
    ultrasonic_start();
    solinst_start();
    ADC_SAR_1_Start();
    //modem_power_off();
    
    packet_ready = 0u; 
    take_reading = 1u;
    t_sample = 2u;                                  // Initialize Sample Period to 2 minutes
    trigger_sampler = 0u;                           // Initialize automated sampler to not take a sample    
    bottle_count = 0u;                              // Initialize bottle count to zero

    NeoRTC_Start(rtcCallBackReceived);              // Start and enable the RTC.   
    NeoRTC_Set_Repeating_Minute_Alarm(t_sample);    // Set 1-minute alarm
   
    
    //  Uncomment below to set RTC
    /*
    NeoRtcTimeStruct tm = {
      .second = 00,
      .minute = 54,
      .hour = 18,
      .day = 27,
      .weekday = 2,
      .month = 5,
      .year = 2014,
    } ;
    RTC_WriteTime(tm); //sets time
    */


    for(;;){
    
        RTC_Process_Tasks();
        
        // Loop continuously and take a reading  
        // every "t_sample" minutes.
        // The variable "take_reading" is set to TRUE 
        // by rtcCallBackReceived() defined after the for() loop
        if(take_reading){ 

            // Turn on the modem to update state variables:
            //  sampling frequency; triggering the autosampler
            modem_power_on();   
           
            if (clear_packet(data_packet)) {
                packet_ready = 0u;
            }
                        
            // To communicate with the IoT platform, the node 
            // 1) listens on a given port and 2) parses an incoming string 
            // for relevant commands. Once a packet is ready to send (3), 
            // the node 4) transmits the packet.  This is achieved in as little 
            // as four lines of code by leveraging an existing TCP/IP library.
            //
            // 1) modem_get_packet()
            // 2) packet_get_uint8()
            // 3) sprintf(data_packet, ...
            // 4) modem_send_packet()
            //
            if (modem_get_packet(data_packet,"t_sample,trigger_sampler")) {
                
                // Read in any updated values
                if(packet_get_uint8(data_packet, "t_sample", &tmp)){
                    t_sample = tmp;
                }
                if(packet_get_uint8(data_packet, "trigger_sampler", &tmp)){
                    trigger_sampler = tmp;
                }
            }

            /*
            if (send_attempts > 0) {
                debug_write("New reading taken before previous packet was sent");
            }
            */

            // Trigger the autosampler to collect the sample 
            // if a sample is requested
            if (trigger_sampler){
                
                // Send in acknowledgement that packet containing
                // info re:automated sampler has been received:
                modem_send_packet("trigger_sampler, 0");
                
                trigger_sampler = 0; // Update the value locally
                
                // Trigger the autosampler as long as there are still available samples
                // If bottle_count >= MAX_BOTTLE_COUNT, skip taking a sample and avoid
                // waiting for the code to timeout
                if (bottle_count < MAX_BOTTLE_COUNT) {
                    // Turn off modem to conserve energy
                    modem_power_off();
                    
                    // Start up the autosampler processes 
                    // and power on the autosampler
                    autosampler_start();
                    autosampler_power_on();
                    

                    // Trigger the autosampler and update current bottle_count
                    autosampler_take_sample(&bottle_count);
                    
                    // Power off the autosampler
                    // and shut down the autosampler processes 
                    autosampler_power_off(); 
                    autosampler_stop();    
                }
                else {
                    debug_write("bottle_count >= MAX_BOTTLE_COUNT");
                }
            }
            
            // Construct the data packet that will be transmitted
            // by the sensor node, starting with the bottle the
            // autosampler last collected a sample in
            // (the packet is in .csv format)
            sprintf(data_packet,"%s, %u\r\n",
                "bottle", bottle_count);

            // Get Sensor Readings for:
            //  Depth, Pressure, Temperature, Conductivity
            // and update the data packet                
            if (solinst_get_reading(&solinst_reading)){
                sprintf(data_packet,"%s%s, %f\r\n", data_packet,
                    "depth_press", solinst_reading.depth);            
                    
                sprintf(data_packet,"%s%s, %f\r\n", data_packet,
                    "temp_press", solinst_reading.temp);                      
            }
            
            if (ultrasonic_get_reading(&ultrasonic_reading)){
                sprintf(data_packet,"%s%s, %f\r\n", data_packet,
                    "depth_sonic", ultrasonic_reading.depth);              
            }
            if (ReadBatteryVoltage(&vBattery)){
                sprintf(data_packet,"%s%s, %f\r\n", data_packet,
                    "V_batt", vBattery);              
            }

            // An example of writing data in JSON format
            // This was replaced with .csv format due to 
            // .csv's smaller packet size
            /*
            sprintf(data_packet, "{"
                      "\"method\":\"put\","
                      "\"resource\":\"/feeds/%d\","
                      "\"headers\":{\"X-ApiKey\":\"%s\"},"
                      "\"body\":{\"version\":\"1.0.0\",\"datastreams\":["
                            "{ \"id\" : \"depth_sonic\", \"current_value\" : \"%f\"},"
                            "{ \"id\" : \"depth_press\", \"current_value\" : \"%f\"},"
                            "{ \"id\" : \"temp_press\", \"current_value\" : \"%f\"},"
                            "{ \"id\" : \"trigger_sampler\", \"current_value\" : \"%d\"},"
                            "{ \"id\" : \"V_batt\",  \"current_value\" : \"%f\"}"
                      "]}}",
                      FEED_ID,API_KEY,
                      ultrasonic_reading.depth, solinst_reading.depth, solinst_reading.temp,0u,vBattery);
            */

            // Update flags for sending a packet and taking sensor readings
            packet_ready = 1u;
            take_reading = 0u;
            //send_attempts = 0u;
        
        // Once the flag for packet_ready has been set, 
        // send the packet and save the packet locally
        } else if(packet_ready){
            isr_SleepTimer_Stop;  //  <============= ADDRESS THIS WITH B.K.
            
            // Power on the modem in case it was turned off
            modem_power_on();
            
            // modem_state should now be IDLE or READY
            // and we can send the packet
            modem_send_packet(data_packet);
            
            // Power off the modem and conserve energy
            modem_power_off();
            
            // Backup data to SD Card
            // Use the current time to time-stamp the current reading
            NeoRtcTimeStruct tm_neo = NeoRTC_Read_Time();

            // Overwrite current data_packet with time-stamped data
            sprintf(data_packet, "\r\n%d:%d:%d %d/%d/%d -- [ID %d] u_d=%f s_d=%f s_t=%f bottle=%d v_b=%f", tm_neo.hour, tm_neo.minute,
                             tm_neo.second, tm_neo.day, tm_neo.month, tm_neo.year, moteID,
                             ultrasonic_reading.depth, solinst_reading.depth, solinst_reading.temp,bottle_count,vBattery);
            
            // Write data_packet to a *.txt file on the SD Card
            Write_To_SD_Card("data.txt","a",data_packet,strlen(data_packet));            

            // Clear the current packet in preparation for the next reading
            // when the node awakens from sleep
            if (clear_packet(data_packet)) {
                packet_ready = 0u;
            }
        
        // If either the sensor node should take a reading nor send a packet
        // go to low power mode to increase battery life    
        }else{
            // Set repeating alarm to trigger every "t_sample" minutes
            NeoRTC_Set_Repeating_Minute_Alarm(t_sample);  
            Goto_Low_Power_Mode();
        }
    CyDelay(1u);  // Quick Pause to prevent locking
    }
}
Exemplo n.º 3
0
Arquivo: main.c Projeto: kLabUM/IoT
void main()
{
    /* Place your initialization/startup code here (e.g. MyInst_Start()) */
    CyGlobalIntEnable; /* Uncomment this line to enable global interrupts. */
	
	CyDelay(5u);  // Short delay to make sure device is ready for low power entry
	
	sleep_isr_StartEx(Wakeup_ISR); // Start Sleep ISR
	SleepTimer_Start();			   // Start SleepTimer Compnent	
    
    modem_set_api_feed(FEED_ID, API_KEY);
    
    //ADC_SAR_1_Start();
    //modem_start();
    //modem_power_on();    
    //modem_get_serial_number();
    
    // Check/set flow control: Change from 3 (default - bidirectional) to 0 (no flow control) --> Did NOT fix ability to connect using AT#SD
    /*
	modem_set_flow_control(0u); 
    modem_get_profile(); //
    modem_get_sw_version();
	modem_set_error_reports(2u);
	*/
	
	// Init and enable CDMA
	/*
	modem_set_user("");
	modem_set_password("");	
	modem_test_CDMA_data();
	modem_enable_CDMA_data(1u);
	modem_test_CDMA_data();
	*/

    // Initialize variables
    ready			= 1u;
	loops			= 0u;
	lock			= 0u;
	packet_ready	= 0u;
	iter            = 0;
    sign            = 1;
    packet_len      = 0u;
	wakeup_interval_counter = 0u;	
    v_out           = 0.0;

    
    VBAT_READ_EN_Write(0u);
	Pin2_Write(0u);
	Pin17_Write(0u);
	Pin18_Write(0u);
    Pin37_Write(0u);
    Pin38_Write(0u);
    Pin39_Write(0u);
    //Pin34_Write(0u);
    //Pin35_Write(0u);
    
//    WaveDAC8_1_Start(); /* Start WaveDAC8  */


    for(;;)
	{
		if ( ready == 1u ){
			iter = 0;
			if (clear_packet(data_packet)) {
                packet_len = 0u;
                packet_ready = 0u;
            }
			
			blink_LED(3u);
			
            if (ultrasonic_get_reading(&ultrasonic_reading)){
                sprintf(data_packet,"%s%s, %d\r\n", data_packet,
                    "depth_sonic", (uint16) (ultrasonic_reading.depth));              
            }
			
			blink_LED(3u);
			
			// Set up the modem and connect to network					
			LED_Write(!LED_Read());
			if (modem_startup()) {
				//modem_get_serial_number();

				
				// Send a packet
				LED_Write(!LED_Read());	
				sprintf(data_packet,"%s%s, %u\r\n", data_packet,
	        		"tmp", loops);  
				ready = modem_send_packet(data_packet);
				CyDelay(5000u);
				
				if (clear_packet(data_packet)) {
	                packet_len = 0u;
	                packet_ready = 0u;
	            }
				
				// Request a packet
				LED_Write(!LED_Read());	
				if( modem_get_packet(data_packet,"lock,tmp") ){
				
					// Code to test moving the actuator 					
					if(packet_get_uint8(data_packet,"lock",&lock)){
						if(lock == 1u){	
							// Supply power to breakout board
							// This powers the Reed Switch
							Pin2_Write(1u);
							CyDelay(1000u);
							
							// Move the actuator out
							Pin17_Write(1u);
							CyDelay(3000u);
							Pin17_Write(0u);
							
							CyDelay(2000u);
							
							// Move the actuator in
							Pin18_Write(1u);
							CyDelay(3000u);
							Pin18_Write(0u);
							
							// Cut power to breakout board
							CyDelay(1000u);
							Pin2_Write(0u);
						}
					}	
				}								
				
				/* 
				modem_power_off();
				modem_stop();
				*/
			}
			modem_shutdown();
			
			loops += 10;
			ready = 0u;
		}
		/* If not ready, update the counter for the sleep timer */
		else {
			/* Blink the LED to indicate sleeping */
			blink_LED(5u);
			
			/* Prepares system clocks for the Sleep mode */
	        CyPmSaveClocks();

	        do
	        {
	            /*******************************************************************
	            * Switch to the Sleep Mode for the other devices:
	            *  - PM_SLEEP_TIME_NONE: wakeup time is defined by Sleep Timer
	            *  - PM_SLEEP_SRC_CTW :  wakeup on CTW sources is allowed
	            *******************************************************************/
	            CyPmSleep(PM_SLEEP_TIME_NONE, PM_SLEEP_SRC_CTW);


	            /***********************************************************************
	            * After the device is woken up the Sleep Timer's ISR is executed.
	            * Afterwards the CyPmSleep() execution is finished the clock
	            * configuration is restored.
	            ***********************************************************************/
	            if(SLEEPTIMER_INTERVAL_COUNTER == wakeup_interval_counter)
	            {
	                /* Blink with LED */
	                //(0u == LED_P1_2_Read()) ? LED_P1_2_Write(1u) : LED_P1_2_Write(0u);
	                wakeup_interval_counter = 0u;
					ready = 1u;
	            }
	            else
	            {
	                wakeup_interval_counter++;
	            }
	                
	        } while (wakeup_interval_counter != 0u);
	        

	        /* Restore clock configuration */
	        CyPmRestoreClocks();
		}
		
		/*
        // Place your application code here.
        Pin37_Write(!Pin37_Read());
        
        clear_packet(data_packet);
        sprintf(data_packet,"%s, %u\r\n", "tmp", iter);
        
        modem_connect();
        LED_Write(!LED_Read());
        
        // modem_state should now be IDLE or READY
        //modem_send_packet(data_packet);        
        modem_get_google(); //Can't get to work
               
        if (tmp > 10) {
            sign = -1;
        } else if (tmp < -10) {
            sign = 1;
        }
        tmp = tmp + sign;        
        
        
        Pin37_Write(!Pin37_Read());
        LED_Write(!LED_Read());
        CyDelay(100u);  
        
        modem_get_time();
        Pin38_Write(!Pin38_Read());
        LED_Write(!LED_Read());
        CyDelay(100u);      
        
        modem_get_signal_quality();
        Pin39_Write(!Pin39_Read());
        LED_Write(!LED_Read());
        CyDelay(100u);  
        
        modem_check_network();
        //Pin34_Write(!Pin34_Read());
        LED_Write(!LED_Read());
        CyDelay(100u);  
        
        modem_get_serial_number();
        //modem_disconnect();
        //Pin35_Write(!Pin35_Read());
        LED_Write(!LED_Read());
        CyDelay(100u);   
        
        ADC_SAR_1_StartConvert();
        ADC_SAR_1_IsEndConversion(ADC_SAR_1_WAIT_FOR_RESULT);
        v_out = ADC_SAR_1_CountsTo_Volts(ADC_SAR_1_GetResult16());        
        //v_out = Pin30_Read();
        Pin25_Write(v_out);
		*/
    }
	
	/*
	modem_power_off();  
	modem_stop();
	
	blink_LED(3u);		
	CyPmSaveClocks();
	CyPmHibernate();
	*/
}