Lorawan to Pulga

Dependencies:   pulga-lorawan-drv SPI_MX25R Si1133 BME280

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /**
00002  * Copyright (c) 2017, Arm Limited and affiliates.
00003  * SPDX-License-Identifier: Apache-2.0
00004  *
00005  * Licensed under the Apache License, Version 2.0 (the "License");
00006  * you may not use this file except in compliance with the License.
00007  * You may obtain a copy of the License at
00008  *
00009  *     http://www.apache.org/licenses/LICENSE-2.0
00010  *
00011  * Unless required by applicable law or agreed to in writing, software
00012  * distributed under the License is distributed on an "AS IS" BASIS,
00013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00014  * See the License for the specific language governing permissions and
00015  * limitations under the License.
00016  */
00017 #include <stdio.h>
00018 
00019 #include "lorawan/LoRaWANInterface.h"
00020 #include "lorawan/system/lorawan_data_structures.h"
00021 #include "events/EventQueue.h"
00022 
00023 // Application helpers
00024 //#include "DummySensor.h"
00025 #include "trace_helper.h"
00026 #include "lora_radio_helper.h"
00027 //#include "BME280.h"
00028 
00029 using namespace events;
00030 
00031 // Max payload size can be LORAMAC_PHY_MAXPAYLOAD.
00032 // This example only communicates with much shorter messages (<30 bytes).
00033 // If longer messages are used, these buffers must be changed accordingly.
00034 uint8_t tx_buffer[256];
00035 uint8_t rx_buffer[30];
00036 
00037 /*
00038  * Sets up an application dependent transmission timer in ms. Used only when Duty Cycling is off for testing
00039  */
00040 #define TX_TIMER                        10000
00041 
00042 /**
00043  * Maximum number of events for the event queue.
00044  * 10 is the safe number for the stack events, however, if application
00045  * also uses the queue for whatever purposes, this number should be increased.
00046  */
00047 #define MAX_NUMBER_OF_EVENTS            10
00048 
00049 /**
00050  * Maximum number of retries for CONFIRMED messages before giving up
00051  */
00052 #define CONFIRMED_MSG_RETRY_COUNTER     3
00053 
00054 /**
00055  * Dummy pin for dummy sensor
00056  */
00057 //#define PC_9                            0
00058 
00059 /**
00060  * Dummy sensor class object
00061  */
00062 //DS1820  ds1820(PC_9);
00063 //BME280 sensor_amb(P0_13, P0_15, 0x77 << 1) ;
00064 
00065 /**
00066  * Sensors Variables
00067  */
00068 //        uint32_t lux = 0;
00069 //        uint32_t amb = 0;
00070 //        float  sensor_get = 0;
00071 
00072 /**
00073 * This event queue is the global event queue for both the
00074 * application and stack. To conserve memory, the stack is designed to run
00075 * in the same thread as the application and the application is responsible for
00076 * providing an event queue to the stack that will be used for ISR deferment as
00077 * well as application information event queuing.
00078 */
00079 static EventQueue ev_queue(MAX_NUMBER_OF_EVENTS *EVENTS_EVENT_SIZE);
00080 
00081 /**
00082  * Event handler.
00083  *
00084  * This will be passed to the LoRaWAN stack to queue events for the
00085  * application which in turn drive the application.
00086  */
00087 static void lora_event_handler(lorawan_event_t event);
00088 
00089 /**
00090  * Constructing Mbed LoRaWANInterface and passing it the radio object from lora_radio_helper.
00091  */
00092 static LoRaWANInterface lorawan(radio);
00093 
00094 /**
00095  * Application specific callbacks
00096  */
00097 static lorawan_app_callbacks_t callbacks;
00098 
00099 /**
00100  * Entry point for application
00101  */
00102  
00103 mbed::DigitalOut _alive_led(P1_13, 0);
00104 mbed::DigitalOut _actuated_led(P1_14,1);
00105 int lat=0;
00106 int lon=0;
00107 int latitude=0;
00108 int longitude=0;
00109 
00110 
00111 //Temperature, Pressure, Humidity Sensor
00112 #include "BME280.txt"
00113 #include "BMX160.txt"
00114 #include "gps.txt"
00115 
00116 void BMX160Read (void)
00117 {    
00118     /*Le os Registradores do Acelerometro*/
00119         i2c_reg_buffer[0] = 0x12;
00120         i2c.write(BMI160_ADDR, i2c_reg_buffer, 1, true);
00121         i2c.read(BMI160_ADDR, (char *)&acc_sample_buffer, sizeof(acc_sample_buffer), false);
00122         
00123         /*Le os Registradores do Giroscopio*/
00124         i2c_reg_buffer[0] = 0x0C;
00125         i2c.write(BMI160_ADDR, i2c_reg_buffer, 1, true);
00126         i2c.read(BMI160_ADDR, (char *)&gyr_sample_buffer, sizeof(gyr_sample_buffer), false);
00127         
00128         /*Ajusta dados brutos Acelerometro em unidades de g */
00129         acc_result_buffer[0] = (acc_sample_buffer[0]/16384.0);
00130         acc_result_buffer[1] = (acc_sample_buffer[1]/16384.0);
00131         acc_result_buffer[2] = (acc_sample_buffer[2]/16384.0);
00132         
00133         /*Ajusta dados Brutos do Giroscopio em unidades de deg/s */
00134         gyr_result_buffer[0] = (gyr_sample_buffer[0]/131.2);
00135         gyr_result_buffer[1] = (gyr_sample_buffer[1]/131.2);
00136                 
00137         /*Calcula os Angulos de Inclinacao com valor do Acelerometro*/
00138         accel_ang_x=atan(acc_result_buffer[0]/sqrt(pow(acc_result_buffer[1],2) + pow(acc_result_buffer[2],2)))*RAD_DEG;
00139         accel_ang_y=atan(acc_result_buffer[1]/sqrt(pow(acc_result_buffer[0],2) + pow(acc_result_buffer[2],2)))*RAD_DEG;
00140         
00141         /*Calcula os Angulos de Rotacao com valor do Giroscopio e aplica filtro complementar realizando a fusao*/
00142         tiltx = (0.98*(tiltx_prev+(gyr_result_buffer[0]*0.001)))+(0.02*(accel_ang_x));
00143         tilty = (0.98*(tilty_prev+(gyr_result_buffer[1]*0.001)))+(0.02*(accel_ang_y));
00144         
00145         tiltx_prev = tiltx;
00146         tilty_prev = tilty;                                 
00147         
00148         /*Imprime os dados ACC pre-formatados*/
00149         printf("%.3f,%.3f;",tiltx, tilty);
00150     
00151     }
00152 
00153 void GPS_Read(void)
00154 {
00155     gps_print_local();
00156     printf ("gps longitude=%d \n",lon);
00157     printf ("gps latitude=%d \n",lat);
00158     if(lat!=0 && lon!=0){
00159         longitude=lon;
00160         latitude=lat;
00161 //        led1 = !led1;
00162         }
00163      }
00164 
00165 int main(void)
00166 {
00167     gps_config();
00168     gps_leBootMsg();
00169     gps_config_gnss ();
00170     init();
00171     
00172     //BMX160 Declaration######################################
00173     //    pc.printf("Teste BMI160\n\r");
00174 //    printf("Configurando BMX160...\n\r");
00175     wait_ms(250);
00176     
00177     /*Config Freq. I2C Bus*/
00178     i2c.frequency(20000);
00179     
00180     /*Reset BMI160*/
00181     i2c_reg_buffer[0] = 0x7E;
00182     i2c_reg_buffer[1] = 0xB6;    
00183     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00184     wait_ms(200);
00185 //    printf("BMI160 Resetado\n\r");
00186     
00187     /*Habilita o Acelerometro*/
00188     i2c_reg_buffer[0] = 0x7E;
00189     i2c_reg_buffer[1] = 0x11; //PMU Normal   
00190     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00191 //    printf("Acc Habilitado\n\r");
00192     
00193     /*Habilita o Giroscopio*/
00194     i2c_reg_buffer[0] = 0x7E;
00195     i2c_reg_buffer[1] = 0x15;  //PMU Normal 
00196     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00197 //    printf("Gyr Habilitado\n\r");
00198     
00199     /*Config o Data Rate ACC em 1600Hz*/
00200     i2c_reg_buffer[0] = 0x40;
00201     i2c_reg_buffer[1] = 0x2C;    
00202     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00203 //    printf("Data Rate ACC Selecionado a 1600Hz\n\r");
00204     
00205     /*Config o Data Rate GYR em 1600Hz*/
00206     i2c_reg_buffer[0] = 0x42;
00207     i2c_reg_buffer[1] = 0x2C;    
00208     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00209 //    printf("Data Rate GYR Selecionado a 1600Hz\n\r");
00210     
00211     /*Config o Range GYR em 250º/s*/
00212     i2c_reg_buffer[0] = 0x43;
00213     i2c_reg_buffer[1] = 0x03;    
00214     i2c.write(BMI160_ADDR, i2c_reg_buffer, sizeof(i2c_reg_buffer), false);
00215 //    printf("Range GYR Selecionado a 250deg/s\n\r");
00216     
00217     printf("BMX160 Configurado\n\r");
00218     
00219     //########################################################
00220     // setup tracing
00221     setup_trace();
00222 
00223     // stores the status of a call to LoRaWAN protocol
00224     lorawan_status_t retcode;
00225 
00226     // Initialize LoRaWAN stack
00227     if (lorawan.initialize(&ev_queue) != LORAWAN_STATUS_OK) {
00228         printf("\r\n LoRa initialization failed! \r\n");
00229         return -1;
00230     }
00231 
00232     printf("\r\n Mbed LoRaWANStack initialized \r\n");
00233 
00234     // prepare application callbacks
00235     callbacks.events = mbed::callback(lora_event_handler);
00236     lorawan.add_app_callbacks(&callbacks);
00237 
00238     // Set number of retries in case of CONFIRMED messages
00239     if (lorawan.set_confirmed_msg_retries(CONFIRMED_MSG_RETRY_COUNTER)
00240             != LORAWAN_STATUS_OK) {
00241         printf("\r\n set_confirmed_msg_retries failed! \r\n\r\n");
00242         return -1;
00243     }
00244 
00245     printf("\r\n CONFIRMED message retries : %d \r\n",
00246            CONFIRMED_MSG_RETRY_COUNTER);
00247 
00248     // Enable adaptive data rate
00249     if (lorawan.enable_adaptive_datarate() != LORAWAN_STATUS_OK) {
00250         printf("\r\n enable_adaptive_datarate failed! \r\n");
00251         return -1;
00252     }
00253 
00254     printf("\r\n Adaptive data  rate (ADR) - Enabled \r\n");
00255 
00256     retcode = lorawan.connect();
00257 
00258     if (retcode == LORAWAN_STATUS_OK ||
00259             retcode == LORAWAN_STATUS_CONNECT_IN_PROGRESS) {
00260     } else {
00261         printf("\r\n Connection error, code = %d \r\n", retcode);
00262         return -1;
00263     }
00264 
00265     printf("\r\n Connection - In Progress ...\r\n");
00266     
00267 _actuated_led =0;
00268     // make your event queue dispatching events forever
00269     ev_queue.dispatch_forever();
00270 
00271     return 0;
00272 }
00273 
00274 /**
00275  * Sends a message to the Network Server
00276  */
00277 static void send_message()
00278 {
00279     uint16_t packet_len;
00280     int16_t retcode;
00281     int32_t sensor_value;
00282     gps_print_local();
00283     
00284     packet_len = sprintf((char *) tx_buffer, "%2.2f, %04.2f, %2.2f, %d, %d\n", getTemperature(), getPressure(), getHumidity(), lon, lat);
00285 
00286     retcode = lorawan.send(MBED_CONF_LORA_APP_PORT, tx_buffer, packet_len,
00287                            MSG_UNCONFIRMED_FLAG);
00288 
00289     if (retcode < 0) {
00290         retcode == LORAWAN_STATUS_WOULD_BLOCK ? printf("send - WOULD BLOCK\r\n")
00291         : printf("\r\n send() - Error code %d \r\n", retcode);
00292 
00293         if (retcode == LORAWAN_STATUS_WOULD_BLOCK) {
00294             //retry in 3 seconds
00295             if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
00296                 ev_queue.call_in(10000, send_message);
00297             }
00298         }
00299         return;
00300     }
00301 
00302     printf("%2.2f;%04.2f;%2.2f;", getTemperature(), getPressure(), getHumidity());
00303     BMX160Read();
00304     printf ("%d;",lon);
00305     printf ("%d \r\n",lat);
00306 //    printf("\r\n %d bytes scheduled for transmission \r\n", retcode);
00307     memset(tx_buffer, 0, sizeof(tx_buffer));
00308 }
00309 
00310 /**
00311  * Receive a message from the Network Server
00312  */
00313 static void receive_message()
00314 {
00315     uint8_t port;
00316     int flags;
00317     int16_t retcode = lorawan.receive(rx_buffer, sizeof(rx_buffer), port, flags);
00318 
00319     if (retcode < 0) {
00320 //        printf("\r\n receive() - Error code %d \r\n", retcode);
00321         return;
00322     }
00323 
00324 //    printf(" RX Data on port %u (%d bytes): ", port, retcode);
00325     for (uint8_t i = 0; i < retcode; i++) {
00326         printf("%02x ", rx_buffer[i]);
00327     }
00328     printf("\r\n");
00329     
00330     memset(rx_buffer, 0, sizeof(rx_buffer));
00331 }
00332 
00333 /**
00334  * Event handler
00335  */
00336 static void lora_event_handler(lorawan_event_t event)
00337 {
00338     switch (event) {
00339         case CONNECTED:
00340             printf("\r\n Connection - Successful \r\n");
00341             if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
00342                 send_message();
00343             } else {
00344                 ev_queue.call_every(TX_TIMER, send_message);
00345             }
00346 
00347             break;
00348         case DISCONNECTED:
00349             ev_queue.break_dispatch();
00350             printf("\r\n Disconnected Successfully \r\n");
00351             break;
00352         case TX_DONE:
00353 //            printf("\r\n Message Sent to Network Server \r\n");
00354             if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
00355                 send_message();
00356             }
00357             break;
00358         case TX_TIMEOUT:
00359 //        printf("\r\n Transmission Error TX_Timeout");
00360         case TX_ERROR:
00361 //        printf("\r\n Transmission Error TX_Error");
00362         case TX_CRYPTO_ERROR:
00363 //        printf("\r\n Transmission Error TX_Crypto_Error");
00364         case TX_SCHEDULING_ERROR:
00365 //            printf("\r\n Transmission Error - EventCode = %d \r\n", event);
00366             // try again
00367             if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
00368                 send_message();
00369             }
00370             break;
00371         case RX_DONE:
00372 //            printf("\r\n Received message from Network Server \r\n");
00373             receive_message();
00374             break;
00375         case RX_TIMEOUT:
00376 //        printf("\r\n Transmission Error RX_Timeout");
00377         case RX_ERROR:
00378 //            printf("\r\n Error in reception - Code = %d \r\n", event);
00379             break;
00380         case JOIN_FAILURE:
00381 //            printf("\r\n OTAA Failed - Check Keys \r\n");
00382             break;
00383         case UPLINK_REQUIRED:
00384 //            printf("\r\n Uplink required by NS \r\n");
00385             if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
00386                 send_message();
00387             }
00388             break;
00389         default:
00390             MBED_ASSERT("Unknown Event");
00391     }
00392 }
00393 
00394 // EOF