Lorawan para integracao com o Arquetipo Pulga

Dependencies:   pulga-lorawan-drv Si1133 BME280

main.cpp

Committer:
MatteusCarr
Date:
2021-05-03
Revision:
64:573096d2e9cc
Parent:
62:e2116ce452eb

File content as of revision 64:573096d2e9cc:

/**
 * Copyright (c) 2017, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <ctime> //samira-time
#include <chrono> 
#include <iostream> 

#include "lorawan/LoRaWANInterface.h"
#include "lorawan/system/lorawan_data_structures.h"
#include "events/EventQueue.h"

// Application helpers
//#include "DummySensor.h"
#include "trace_helper.h"
#include "lora_radio_helper.h"
#include "BME280.h"

using namespace events;

// Max payload size can be LORAMAC_PHY_MAXPAYLOAD.
// This example only communicates with much shorter messages (<30 bytes).
// If longer messages are used, these buffers must be changed accordingly.
//uint8_t tx_buffer[1000];
uint8_t rx_buffer[30];
uint8_t tx_buffer[256]; //= {0xd8, 0x60, 0x84, 0x43, 0xa1, 0x01, 0x0a, 0xa1, 0x05, 0x4c, 0x13, 0x28, 0x18, 0x7b, 0x01, 0xa1, 0x26, 0xca, 0xf7, 0x8e, 0x55, 0x51, 0x58, 0x6f, 0xa8, 0x00, 0x82, 0x64, 0xcf, 0xb0, 0x5e, 0x3d, 0x48, 0x7e, 0x30, 0x2f, 0x4c, 0xc3, 0x37, 0x6b, 0x4d, 0xdb, 0xb6, 0xa9, 0x1b, 0xc9, 0x4c, 0xcc, 0x8e, 0x92, 0x39, 0x8e, 0x4f, 0xe9, 0x3d, 0xb0, 0xa7, 0x48, 0x00, 0xfe, 0x38, 0xa7, 0xcd, 0x57, 0x7e, 0x04, 0x65, 0xb8, 0x2b, 0xf8, 0xc3, 0xbe, 0x33, 0x17, 0xf1, 0xe1, 0xfa, 0x88, 0x7d, 0x3b, 0xd4, 0xa0, 0xce, 0xed, 0x84, 0xed, 0x83, 0xdc, 0x57, 0xcf, 0xe8, 0x5b, 0x7e, 0xc0, 0x5c, 0x6b, 0xbd, 0xa1, 0xdb, 0x67, 0x5d, 0xae, 0xc4, 0x1f, 0x6d, 0x98, 0xf0, 0x97, 0xb6, 0x7a, 0x06, 0x55, 0x97, 0xe6, 0x11, 0x07, 0x52, 0x89, 0x73, 0x65, 0x28, 0x7c, 0xc8, 0x69, 0x39, 0x69, 0xde, 0x12, 0x71, 0x87, 0x43, 0xda, 0xd5, 0x11, 0xbf, 0x81, 0x83, 0x56, 0xa2, 0x01, 0x38, 0x1a, 0x04, 0x50, 0x88, 0x8a, 0x33, 0x0e, 0xc6, 0x2a, 0x43, 0xeb, 0xbf, 0x3c, 0xc9, 0x7c, 0xa6, 0x55, 0xed, 0x33, 0xa0, 0x40};

auto timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); 

#define wait_time    0

/*
 * Sets up an application dependent transmission timer in ms. Used only when Duty Cycling is off for testing
 */
#define TX_TIMER                        10000
#define DR                              DR_0

/**
 * Maximum number of events for the event queue.
 * 10 is the safe number for the stack events, however, if application
 * also uses the queue for whatever purposes, this number should be increased.
 */
#define MAX_NUMBER_OF_EVENTS            10

/**
 * Maximum number of retries for CONFIRMED messages before giving up
 */
#define CONFIRMED_MSG_RETRY_COUNTER     3

/**
 * Dummy pin for dummy sensor
 */
//#define PC_9                            0

/**
 * Dummy sensor class object
 */
//DS1820  ds1820(PC_9);
//BME280 sensor_amb(P0_13, P0_15, 0x77 << 1) ;

/**
 * Sensors Variables
 */
        uint32_t lux = 0;
        uint32_t amb = 0;
        float  sensor_get = 0;

/**
* This event queue is the global event queue for both the
* application and stack. To conserve memory, the stack is designed to run
* in the same thread as the application and the application is responsible for
* providing an event queue to the stack that will be used for ISR deferment as
* well as application information event queuing.
*/
static EventQueue ev_queue(MAX_NUMBER_OF_EVENTS *EVENTS_EVENT_SIZE);

/**
 * Event handler.
 *
 * This will be passed to the LoRaWAN stack to queue events for the
 * application which in turn drive the application.
 */
static void lora_event_handler(lorawan_event_t event);

/**
 * Constructing Mbed LoRaWANInterface and passing it the radio object from lora_radio_helper.
 */
static LoRaWANInterface lorawan(radio);

/**
 * Application specific callbacks
 */
static lorawan_app_callbacks_t callbacks;

/**
 * Entry point for application
 */
 
mbed::DigitalOut _alive_led(P1_13, 0);
mbed::DigitalOut _actuated_led(P1_14,1);
 int msg_seq_number;


/////////////////////////////////////////////////////////////////////////
//Samira
//define the channel
/////////////////////////////////////////////////////////////////////////


static loramac_channel_t testchannel[] = {
        {0, {916800000, 0, {(DR_5 << 4) | DR_0}, 1}},
        {1, {917000000, 0, {(DR_5 << 4) | DR_0}, 1}},
        {2, {917200000, 0, {(DR_5 << 4) | DR_0}, 1}},
        {3, {917400000, 0, {(DR_5 << 4) | DR_0}, 0}},
        {4, {917600000, 0, {(DR_5 << 4) | DR_0}, 0}},
        {5, {917800000, 0, {(DR_5 << 4) | DR_0}, 0}},
        {6, {918000000, 0, {(DR_5 << 4) | DR_0}, 0}},
        {7, {918200000, 0, {(DR_5 << 4) | DR_0}, 0}}
};

/*
To set the channel - execute the following code before calling lorawan.connect()
*/

void LoRa_SetChannelPlan() {
    lorawan_channelplan_t channelPlan {};
    loramac_channel_t channels[8];
    channelPlan.channels = (loramac_channel_t*) channels;

    //only activate the first three channels, up and downlink .
    channels[0] = testchannel[0];
    channels[1] = testchannel[1];
    channels[2] = testchannel[2];
    
    channelPlan.nb_channels = 3;

    //remove previously set channel plan
    if(lorawan.remove_channel_plan() == LORAWAN_STATUS_OK) {
        printf("[+] Removing old channels okay\n");
    } else {
        printf("[-] Removing old channels failed\n");
        
    }
    if (lorawan.set_channel_plan(channelPlan ) == LORAWAN_STATUS_OK) {
        printf("[+] Setting TTN channels okay\n");
    } else {
        printf("[-] Failed to set TTN channels! Debug return code.\n");
    }
}


/*
To print the channel After the CONNECTED event in the callback in the callback handler 
*/
void LoRa_PrintChannels() {
    /* print list of all channel frequencies */
    lorawan_channelplan_t channelPlan {};
 //   static loramac_channel_t channelbuf[10];
 //   channelPlan.channels = channelbuf;
    if (lorawan.get_channel_plan(channelPlan) == LORAWAN_STATUS_OK) {
        for (uint8_t i = 0; i < channelPlan.nb_channels; i++) {
            loramac_channel_t chan = channelPlan.channels[i];
            printf("CHAN %d ID %d FREQ %lu RX1FREQ %lu Band %d DR min %d max %d\n",
                   (int) i, (int) chan.id, chan.ch_param.frequency,
                   chan.ch_param.rx1_frequency, (int) chan.ch_param.band,
                   (int) chan.ch_param.dr_range.fields.min,
                   (int) chan.ch_param.dr_range.fields.max);
        }
    } else {
        printf("COULD NOT GET CHANNEL PLAN\n");
    }
}

/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////




int main(void)
{
    // setup tracing
    setup_trace();

    // stores the status of a call to LoRaWAN protocol
    lorawan_status_t retcode;

    // Initialize LoRaWAN stack
    if (lorawan.initialize(&ev_queue) != LORAWAN_STATUS_OK) {
        printf("\r\n LoRa initialization failed! \r\n");
        return -1;
    }

    printf("\r\n Mbed LoRaWANStack initialized \r\n");

    // prepare application callbacks
    callbacks.events = mbed::callback(lora_event_handler);
    lorawan.add_app_callbacks(&callbacks);

    // Set number of retries in case of CONFIRMED messages
    if (lorawan.set_confirmed_msg_retries(CONFIRMED_MSG_RETRY_COUNTER)
            != LORAWAN_STATUS_OK) {
        printf("\r\n set_confirmed_msg_retries failed! \r\n\r\n");
        return -1;
    }

    printf("\r\n CONFIRMED message retries : %d \r\n",
           CONFIRMED_MSG_RETRY_COUNTER);

    // Enable adaptive data rate
 /*   if (lorawan.enable_adaptive_datarate() != LORAWAN_STATUS_OK) {
        printf("\r\n enable_adaptive_datarate failed! \r\n");
        return -1;
    }

    printf("\r\n Adaptive data  rate (ADR) - Enabled \r\n");
    */
      if (lorawan.disable_adaptive_datarate() != LORAWAN_STATUS_OK) {
        printf("\r\ndisable_adaptive_datarate failed! \r\n");
        return -1;
    }

    printf("\r\n Adaptive data  rate (ADR) - Disabled \r\n");
      
  if (lorawan.set_datarate(DR) != LORAWAN_STATUS_OK) {
        printf("\r\n Couldn't set data rate to %d! \r\n", DR);
        return -1;
    }

  printf("\r\n Data rate = %d\r\n", DR);
  

    
    //samira - to set a channel plan
    //LoRa_SetChannelPlan();

        
    retcode = lorawan.connect();
 

    if (retcode == LORAWAN_STATUS_OK ||
            retcode == LORAWAN_STATUS_CONNECT_IN_PROGRESS) {
    } else {
        printf("\r\n Connection error, code = %d \r\n", retcode);
        return -1;
    }

    printf("\r\n Connection - In Progress ...\r\n");
    
_actuated_led =0;

     /*   set_time(1256729737);  // Set RTC time to Wed, 28 Oct 2009 11:35:37


        time_t seconds = time(NULL);

        //printf("Time as seconds since January 1, 1970 = %u\n", (unsigned int)seconds);

        //printf("Time as a basic string = %s", ctime(&seconds));

        char time_buffer[32];
        strftime(time_buffer, 32, "%I:%M %p\n", localtime(&seconds));
        printf("Time as a custom formatted string = %s", time_buffer);


    */
/* testing how wait works. it is for seconds
      //samira-time
   timenow =  chrono::system_clock::to_time_t(chrono::system_clock::now()); 
  
    cout << ctime(&timenow) << endl; 
    wait (1);
     timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); 
      cout << "wait was 1"<<ctime(&timenow) << endl; 
      wait (20);
        timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); 
      cout << "wait was 2"<<ctime(&timenow) << endl; 
      wait (30);
      timenow =   chrono::system_clock::to_time_t(chrono::system_clock::now()); 
      cout << "wait was 3"<<ctime(&timenow) << endl; 
      wait (40);
        timenow = chrono::system_clock::to_time_t(chrono::system_clock::now()); 
      cout << "wait was 4"<<ctime(&timenow) << endl; 
 */   
    // make your event queue dispatching events forever
 
     
    ev_queue.dispatch_forever();

    return 0;
}

static void print_lora_tx_buffer_hex(size_t bufSize){
    char hexa[2*bufSize + 1];

    for (int i = 0 ; i != bufSize ; i++) {
        sprintf(&hexa[2*i], "%02X", tx_buffer[i]);
    }
    hexa[2*bufSize] = '\0';
    printf("Size = %d. Message to sent: [ %s ]\n", bufSize, hexa);   
}   

/**
 * Sends a message to the Network Server
 */
static void send_message()
{
    printf("------------------------------------------\n");
    uint16_t packet_len;
    int16_t retcode;
    int32_t sensor_value;
    
    msg_seq_number = msg_seq_number + 1;
    printf("\r\n msgs %d is creating \r\n", msg_seq_number);
    
   // packet_len = sprintf((char *) tx_buffer, "Ø`„C¡¡L({¡&Ê÷ŽUQXo¨‚dÏ°^=H~0/LÃ7kMÛ¶©ÉL̎’9ŽOé=°§Hþ8§ÍW~e¸+øþ3ñáúˆ};Ô Îí„íƒÜWÏè[~À\k½¡Ûg]®Äm˜ð—¶zU—æR‰se(|Èi9iÞq‡CÚÕ¿ƒV¢8PˆŠ3Æ*Cë¿<É|¦Uí3 @", msg_seq_number);
    
    
    //packet_len = sprintf((char *) tx_buffer, "This is message with seq_number =  %d \n", msg_seq_number);
    packet_len = sprintf((char *) tx_buffer, "P");
    
   // packet_len = 162;
     
    
    printf("packet_len =  %d\n",  packet_len);
    printf("packet_content =  %s \n",  tx_buffer);
     //   std::cout<<tx_buffer<<endl;
    print_lora_tx_buffer_hex(packet_len);
    
    //////samira-time
   auto timenow = 
      chrono::system_clock::to_time_t(chrono::system_clock::now()); 
  
    cout << ctime(&timenow) << endl; 
     /////

    retcode = lorawan.send(MBED_CONF_LORA_APP_PORT, tx_buffer, packet_len,
                           MSG_UNCONFIRMED_FLAG);

    if (retcode < 0) {
        retcode == LORAWAN_STATUS_WOULD_BLOCK ? printf("send - WOULD BLOCK\r\n")
        : printf("\r\n send() - Error code %d \r\n", retcode);

        if (retcode == LORAWAN_STATUS_WOULD_BLOCK) {
            //retry in 3 seconds
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                ev_queue.call_in(3000, send_message);
            }
        }
        return;
    }

    printf("\r %d bytes scheduled for transmission \r\n", retcode);
    memset(tx_buffer, 0, sizeof(tx_buffer));
     printf("------------------------------------------\n");
    
}

/**
 * Receive a message from the Network Server
 */
static void receive_message()
{
    uint8_t port;
    int flags;
    int16_t retcode = lorawan.receive(rx_buffer, sizeof(rx_buffer), port, flags);

    if (retcode < 0) {
        printf("\r\n receive() - Error code %d \r\n", retcode);
        return;
    }

    printf(" RX Data on port %u (%d bytes): ", port, retcode);
    for (uint8_t i = 0; i < retcode; i++) {
        printf("%02x ", rx_buffer[i]);
    }
    printf("\r\n");
    
    memset(rx_buffer, 0, sizeof(rx_buffer));
}

/**
 * Event handler
 */
static void lora_event_handler(lorawan_event_t event)
{
    switch (event) {
        case CONNECTED:
            printf("\r\n Connection - Successful \r\n");
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                  

    
                send_message();

             // LoRa_PrintChannels();
              
               
              
              
            } else {
                ev_queue.call_every(TX_TIMER, send_message);
            }

            break;
        case DISCONNECTED:
            ev_queue.break_dispatch();
            printf("\r\n Disconnected Successfully \r\n");
            break;
        case TX_DONE:
            //samira-time wait for x minutes
            timenow =   chrono::system_clock::to_time_t(chrono::system_clock::now()); 
            cout << "time = "<<ctime(&timenow) << endl; 
            printf("\r Message Sent to Network Server \r\n");
            printf("\r device waits for %d minutes before sending next messages \r\n", wait_time);
            wait(wait_time);//samira-time wait for x seconds
            timenow =   chrono::system_clock::to_time_t(chrono::system_clock::now()); 
            cout << "wait time is finished time = "<<ctime(&timenow) << endl; 
            
            //printf("\r\n Message Sent to Network Server \r\n");
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
              send_message();
            }
            break;
        case TX_TIMEOUT:
        printf("\r\n Transmission Error TX_Timeout");
        case TX_ERROR:
        printf("\r\n Transmission Error TX_Error");
        case TX_CRYPTO_ERROR:
        printf("\r\n Transmission Error TX_Crypto_Error");
        case TX_SCHEDULING_ERROR:
            printf("\r\n Transmission Error - EventCode = %d \r\n", event);
            // try again
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                send_message();
            }
            break;
        case RX_DONE:
            printf("\r\n Received message from Network Server \r\n");
            receive_message();
            break;
        case RX_TIMEOUT:
        printf("\r\n Transmission Error RX_Timeout");
        case RX_ERROR:
            printf("\r\n Error in reception - Code = %d \r\n", event);
            break;
        case JOIN_FAILURE:
            printf("\r\n OTAA Failed - Check Keys \r\n");
            break;
        case UPLINK_REQUIRED:
            printf("\r\n Uplink required by NS \r\n");
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                send_message();
            }
            break;
        default:
            MBED_ASSERT("Unknown Event");
    }
}

// EOF