中级
20 分钟

使用SARA U-201和PIC32MZ2048EFM100体验未来通信

通往终极蜂窝网络的门户!

3G SARA Click with Curiosity PIC32 MZ EF

已发布 6月 25, 2024

点击板

3G SARA Click

开发板

Curiosity PIC32 MZ EF

编译器

NECTO Studio

微控制器单元

PIC32MZ2048EFM100

踏入一个充满可能性的世界,体验我们的蜂窝网络通信解决方案。我们提供从网络指示到完整的TCP/UDP堆栈以及先进的HTTP/HTTPS传输功能,确保无与伦比的连接性和通信效率。

A

A

硬件概览

它是如何工作的?

3G SARA Click基于来自u-blox的紧凑型3.75G UMTS/HSPA调制解调器SARA U-201。SARA U-201模块可在全球范围内使用。有关模块的完整频率列表和其他相关信息可在SARA U-201数据手册中找到。该设备是点击板的主要组件,由几个内部块或部分组成,如天线切换部分、射频收发器部分、存储器、电源管理和最重要的 - 蜂窝基带处理器。此部分包含管理其他部分所需的逻辑,并提供与主机MCU的接口。此接口由几条线组成,报告天线状态、SIM卡状态、SIM卡接口线、GPIO、UART接口线、USB接口线、I2C总线线、设备控制线和I2S总线线。这些线路被路由到点击板的相应元素。SARA U-201模块必须由干净稳定的电源供电。模块正常工作所需的电压约为4V,通过Microchip的1A低压降输出(LDO)调节器MCP1826从5V mikroBUS™轨道派生。尽管SARA U-201是低功耗设备,但通常情况下,蜂窝网络模块以高功耗著称,因此必须使用1A LDO。SARA U-201的数字部分由内部供电1.8V,因此需要对连接主机MCU与模块的通信总线进行调理。出于这个原因,另一个小型LDO被使用,为来自Texas

Instruments的具有自动方向感测的6位双向电平转换和电压转换器TXB0106的一侧提供所需的参考电压。级联器的另一侧的参考电压来自板载SMD跳线,标记为PWR SEL。此跳线从mikroBUS™中选择3.3V和5V,取决于使用的MCU类型及其逻辑电压水平要求。SARA U-201模块的UART总线连接到级联器的一侧,而另一侧(转换后)连接到相应的mikroBUS™ UART引脚。然而,SARA U-201模块被设计为传统的DCE设备(Data Communication Equipment),提供完整的UART引脚数,包括硬件流控制引脚(CTS、RTS)。这些引脚被路由到mikroBUS™ CS (RTS)和INT引脚(CTS),如果需要硬件流控制,则可以在MCU软件中使用这些引脚。RI引脚是路由到mikroBUS™ PWM引脚的振铃指示器。STAT引脚用于信号网络连接状态。此引脚通过级联器路由到mikroBUS™ AN引脚,并使用黄色LED可视化地指示网络连接状态。红色TX LED用于指示传输状态,位于STAT LED旁边。PWRKEY引脚被路由到mikroBUS™ RST引脚,并在上电序列期间使用。如果提供了有效的供电电压,则在此引脚

上的低脉冲将启动设备。为了正确地与网络分离并将工作参数存储在其非易失性存储器中,模块应该通过发出AT+CPWROFF命令或在断开电源之前在PWRKEY引脚上产生至少1秒的低脉冲来安全地关闭电源。如前所述,SARA U-201提供了I2S接口,主要用于数字音频。来自Maxim Integrated的16位单声道音频语音编解码器IC MAX9860为3G SARA click板提供语音通信。此IC使用I2S和I2C接口与SARA U-201模块通信。它还通过LDO供电1.8V,因此不需要电平转换。此IC为连接耳机提供了清晰可听的模拟接口,具有一个音频输出通道和一个麦克风输入通道。耳机可以通过板载的3.5mm音频插孔连接。SARA 3G click配备了一个微型USB连接器。它允许通过个人计算机(PC)为模块供电和配置。u-blox公司提供了一个软件套件,可用于配置SARA U-201模块。点击板背面的Micro SIM卡槽用于安装SIM卡。没有有效的SIM卡,该设备无法使用,而SIM卡允许连接到蜂窝网络。支持1.8V和3V SIM卡类型。

3G SARA Click hardware overview image

功能概述

开发板

Curiosity PIC32 MZ EF 开发板是一个完全集成的 32 位开发平台,特点是高性能的 PIC32MZ EF 系列(PIC32MZ2048EFM),该系列具有 2MB Flash、512KB RAM、集成的浮点单元(FPU)、加密加速器和出色的连接选项。它包括一个集成的程序员和调试器,无需额外硬件。用户可以通过 MIKROE 

mikroBUS™ Click™ 适配器板扩展功能,通过 Microchip PHY 女儿板添加以太网连接功能,使用 Microchip 扩展板添加 WiFi 连接能力,并通过 Microchip 音频女儿板添加音频输入和输出功能。这些板完全集成到 PIC32 强大的软件框架 MPLAB Harmony 中,该框架提供了一个灵活且模块化的接口

来应用开发、一套丰富的互操作软件堆栈(TCP-IP、USB)和易于使用的功能。Curiosity PIC32 MZ EF 开发板提供了扩展能力,使其成为连接性、物联网和通用应用中快速原型设计的绝佳选择。

Curiosity PIC32MZ EF double side image

微控制器概述 

MCU卡片 / MCU

default

建筑

PIC32

MCU 内存 (KB)

2048

硅供应商

Microchip

引脚数

100

RAM (字节)

524288

你完善了我!

配件

橡胶天线 GSM/GPRS 直角天线是我们广泛产品线中所有 GSM Click board™ 的完美伴侣。这款专用天线旨在优化您的无线连接,具有令人印象深刻的特性。其广泛的频率范围涵盖 824-894/1710-1990MHz 或 890-960/1710-1890MHz,可以处理各种频段,确保无缝可靠的连接。该天线拥有 50 欧姆的阻抗和 2dB 的增益,增强了信号接收和发送。其 70/180MHz 带宽为不同应用提供了灵活性。垂直极化进一步提高了其性能。该天线具有最大输入功率容量为 50W,即使在苛刻的条件下也能确保强大的通信。该天线长 50mm,体积小巧,并配备 SMA 母头连接器,是您无线通信需求的多功能紧凑解决方案。

3G SARA Click accessories image

使用的MCU引脚

mikroBUS™映射器

Network Status
RPB4
AN
PowerKey
RA9
RST
UART RTS
RPD4
CS
NC
NC
SCK
NC
NC
MISO
NC
NC
MOSI
Power Supply
3.3V
3.3V
Ground
GND
GND
UART RI
RPE8
PWM
UART CTS
RF13
INT
UART TX
RPD10
TX
UART RX
RPD15
RX
NC
NC
SCL
NC
NC
SDA
Power Supply
5V
5V
Ground
GND
GND
1

“仔细看看!”

Click board™ 原理图

3G SARA Click Schematic schematic

一步一步来

项目组装

Curiosity PIC32MZ EF front image hardware assembly

从选择您的开发板和Click板™开始。以Curiosity PIC32 MZ EF作为您的开发板开始。

Curiosity PIC32MZ EF front image hardware assembly
GNSS2 Click front image hardware assembly
Prog-cut hardware assembly
GNSS2 Click complete accessories setup image hardware assembly
Curiosity PIC32 MZ EF MB 1 Access - upright/background hardware assembly
Necto image step 2 hardware assembly
Necto image step 3 hardware assembly
Necto image step 4 hardware assembly
Necto image step 5 hardware assembly
Necto image step 6 hardware assembly
Curiosity PIC32 MZ EF MCU Step hardware assembly
Necto No Display image step 8 hardware assembly
Necto image step 9 hardware assembly
Necto image step 10 hardware assembly
Debug Image Necto Step hardware assembly

实时跟踪您的结果

应用程序输出

1. 应用程序输出 - 在调试模式下,“应用程序输出”窗口支持实时数据监控,直接提供执行结果的可视化。请按照提供的教程正确配置环境,以确保数据正确显示。

2. UART 终端 - 使用UART Terminal通过USB to UART converter监视数据传输,实现Click board™与开发系统之间的直接通信。请根据项目需求配置波特率和其他串行设置,以确保正常运行。有关分步设置说明,请参考提供的教程

3. Plot 输出 - Plot功能提供了一种强大的方式来可视化实时传感器数据,使趋势分析、调试和多个数据点的对比变得更加直观。要正确设置,请按照提供的教程,其中包含使用Plot功能显示Click board™读数的分步示例。在代码中使用Plot功能时,请使用以下函数:plot(insert_graph_name, variable_name);。这是一个通用格式,用户需要将“insert_graph_name”替换为实际图表名称,并将“variable_name”替换为要显示的参数。

软件支持

库描述

这个库包含了3G SARA Click驱动程序的API。

关键函数:

  • c3gsara_set_sim_apn - 此函数设置SIM卡的APN

  • c3gsara_send_sms_text - 此函数向电话号码发送文本消息

  • c3gsara_send_sms_pdu - 此函数以PDU模式向电话号码发送文本消息

开源

代码示例

完整的应用程序代码和一个现成的项目可以通过NECTO Studio包管理器直接安装到NECTO Studio 应用程序代码也可以在MIKROE的GitHub账户中找到。

/*!
 * @file main.c
 * @brief 3G SARA Click Example.
 *
 * # Description
 * Application example shows device capability of connecting to the network and
 * sending SMS or TCP/UDP messages using standard "AT" commands.
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initializes the driver, tests the communication by sending "AT" command, and after that restarts the device.
 *
 * ## Application Task
 * Application task is split in few stages:
 *  - C3GSARA_CONFIGURE_FOR_NETWORK:
 * Sets configuration to device to be able to connect to the network.
 *
 *  - C3GSARA_WAIT_FOR_CONNECTION:
 * Waits for the network registration indicated via CREG URC event and then checks
 * the connection status.
 *
 *  - C3GSARA_CONFIGURE_FOR_EXAMPLE:
 * Sets the device configuration for sending SMS or TCP/UDP messages depending on the selected demo example.
 *
 *  - C3GSARA_EXAMPLE:
 * Depending on the selected demo example, it sends an SMS message (in PDU or TXT mode) or TCP/UDP message.
 *
 * By default, the TCP/UDP example is selected.
 *
 * ## Additional Function
 * - static void c3gsara_clear_app_buf ( void )
 * - static err_t c3gsara_process ( void )
 * - static void c3gsara_error_check( err_t error_flag )
 * - static void c3gsara_log_app_buf ( void )
 * - static err_t c3gsara_rsp_check ( uint8_t *rsp )
 * - static err_t c3gsara_configure_for_connection( void )
 * - static err_t c3gsara_check_connection( void )
 * - static err_t c3gsara_configure_for_messages( void )
 * - static err_t c3gsara_send_message( void )
 *
 * @note
 * In order for the examples to work, user needs to set the APN and SMSC (SMS PDU mode only)
 * of entered SIM card as well as the phone number (SMS mode only) to which he wants to send an SMS.
 * Enter valid values for the following macros: SIM_APN, SIM_SMSC and PHONE_NUMBER_TO_MESSAGE.
 * Example:
    SIM_APN "internet"
    SIM_SMSC "+381610401"
    PHONE_NUMBER_TO_MESSAGE "+381659999999"
 *
 * @author Stefan Filipovic
 *
 */

#include "board.h"
#include "log.h"
#include "c3gsara.h"
#include "conversions.h"

// Example selection macros
#define EXAMPLE_TCP_UDP                     0               // Example of sending messages to a TCP/UDP echo server
#define EXAMPLE_SMS                         1               // Example of sending SMS to a phone number
#define DEMO_EXAMPLE                        EXAMPLE_TCP_UDP // Example selection macro

// SIM APN config
#define SIM_APN                             ""              // Set valid SIM APN

// SMS example parameters
#define SIM_SMSC                            ""              // Set valid SMS Service Center Address - only in SMS PDU mode
#define PHONE_NUMBER_TO_MESSAGE             ""              // Set Phone number to message
#define SMS_MODE                            "1"             // SMS mode: "0" - PDU, "1" - TXT

// TCP/UDP example parameters
#define REMOTE_IP                           "77.46.162.162" // TCP/UDP echo server IP address
#define REMOTE_PORT                         "51111"         // TCP/UDP echo server port

// Message content
#define MESSAGE_CONTENT                     "3G SARA click board - demo example."

// Application buffer size
#define APP_BUFFER_SIZE                     256
#define PROCESS_BUFFER_SIZE                 256

/**
 * @brief Example states.
 * @details Predefined enum values for application example state.
 */
typedef enum
{
    C3GSARA_CONFIGURE_FOR_NETWORK = 1,
    C3GSARA_WAIT_FOR_CONNECTION,
    C3GSARA_CONFIGURE_FOR_EXAMPLE,
    C3GSARA_EXAMPLE

} c3gsara_example_state_t;

static c3gsara_t c3gsara;
static log_t logger;

/**
 * @brief Application example variables.
 * @details Variables used in application example.
 */
static uint8_t app_buf[ APP_BUFFER_SIZE ] = { 0 };
static int32_t app_buf_len = 0;
static err_t error_flag;
static c3gsara_example_state_t example_state;

/**
 * @brief Clearing application buffer.
 * @details This function clears memory of application
 * buffer and reset its length and counter.
 */
static void c3gsara_clear_app_buf ( void );

/**
 * @brief Data reading function.
 * @details This function reads data from device and
 * appends it to the application buffer.
 * @return @li @c  0 - Some data is read.
 *         @li @c -1 - Nothing is read.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_process ( void );

/**
 * @brief Check for errors.
 * @details This function checks for different types of
 * errors and logs them on UART or logs the response if no errors occured.
 * @param[in] error_flag  Error flag to check.
 */
static void c3gsara_error_check ( err_t error_flag );

/**
 * @brief Logs application buffer.
 * @details This function logs data from application buffer.
 */
static void c3gsara_log_app_buf ( void );

/**
 * @brief Response check.
 * @details This function checks for response and
 * returns the status of response.
 * @param[in] rsp  Expected response.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_rsp_check ( uint8_t *rsp );

/**
 * @brief Configure device for connection to the network.
 * @details Sends commands to configure and enable
 * connection to the specified network.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_configure_for_network ( void );

/**
 * @brief Wait for connection signal.
 * @details Wait for connection signal from CREG URC.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_check_connection ( void );

/**
 * @brief Configure device for example.
 * @details Configure device for the specified example.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_configure_for_example ( void );

/**
 * @brief Execute example.
 * @details This function executes SMS or TCP/UDP example depending on the DEMO_EXAMPLE macro.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_example ( void );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    c3gsara_cfg_t c3gsara_cfg;  /**< Click config object. */

    /**
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX
     * are defined as HAL_PIN_NC, you will
     * need to define them manually for log to work.
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    c3gsara_cfg_setup( &c3gsara_cfg );
    C3GSARA_MAP_MIKROBUS( c3gsara_cfg, MIKROBUS_1 );
    if ( UART_ERROR == c3gsara_init( &c3gsara, &c3gsara_cfg ) )
    {
        log_error( &logger, " Application Init Error. " );
        log_info( &logger, " Please, run program again... " );
        for ( ; ; );
    }
    
    c3gsara_set_power_state ( &c3gsara, C3GSARA_POWER_STATE_ON );
    
    c3gsara_process( );
    c3gsara_clear_app_buf( );

    // Check communication
    c3gsara_send_cmd( &c3gsara, C3GSARA_CMD_AT );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    
    // Restart device
    #define RESTART_DEVICE "1,1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CFUN, RESTART_DEVICE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    
    log_info( &logger, " Application Task " );
    example_state = C3GSARA_CONFIGURE_FOR_NETWORK;
}

void application_task ( void )
{
    switch ( example_state )
    {
        case C3GSARA_CONFIGURE_FOR_NETWORK:
        {
            if ( C3GSARA_OK == c3gsara_configure_for_network( ) )
            {
                example_state = C3GSARA_WAIT_FOR_CONNECTION;
            }
            break;
        }
        case C3GSARA_WAIT_FOR_CONNECTION:
        {
            if ( C3GSARA_OK == c3gsara_check_connection( ) )
            {
                example_state = C3GSARA_CONFIGURE_FOR_EXAMPLE;
            }
            break;
        }
        case C3GSARA_CONFIGURE_FOR_EXAMPLE:
        {
            if ( C3GSARA_OK == c3gsara_configure_for_example( ) )
            {
                example_state = C3GSARA_EXAMPLE;
            }
            break;
        }
        case C3GSARA_EXAMPLE:
        {
            c3gsara_example( );
            break;
        }
        default:
        {
            log_error( &logger, " Example state." );
            break;
        }
    }
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

static void c3gsara_clear_app_buf ( void )
{
    memset( app_buf, 0, app_buf_len );
    app_buf_len = 0;
}

static err_t c3gsara_process ( void )
{
    uint8_t rx_buf[ PROCESS_BUFFER_SIZE ] = { 0 };
    int32_t rx_size = 0;
    rx_size = c3gsara_generic_read( &c3gsara, rx_buf, PROCESS_BUFFER_SIZE );
    if ( rx_size > 0 ) 
    {
        int32_t buf_cnt = app_buf_len;
        if ( ( ( app_buf_len + rx_size ) > APP_BUFFER_SIZE ) && ( app_buf_len > 0 ) ) 
        {
            buf_cnt = APP_BUFFER_SIZE - ( ( app_buf_len + rx_size ) - APP_BUFFER_SIZE );
            memmove ( app_buf, &app_buf[ APP_BUFFER_SIZE - buf_cnt ], buf_cnt );
        }
        for ( int32_t rx_cnt = 0; rx_cnt < rx_size; rx_cnt++ ) 
        {
            if ( rx_buf[ rx_cnt ] ) 
            {
                app_buf[ buf_cnt++ ] = rx_buf[ rx_cnt ];
                if ( app_buf_len < APP_BUFFER_SIZE )
                {
                    app_buf_len++;
                }
            }
        }
        return C3GSARA_OK;
    }
    return C3GSARA_ERROR;
}

static err_t c3gsara_rsp_check ( uint8_t *rsp )
{
    uint32_t timeout_cnt = 0;
    uint32_t timeout = 120000;
    c3gsara_clear_app_buf( );
    c3gsara_process( );
    while ( ( 0 == strstr( app_buf, rsp ) ) &&
            ( 0 == strstr( app_buf, C3GSARA_RSP_ERROR ) ) )
    {
        c3gsara_process( );
        if ( timeout_cnt++ > timeout )
        {
            c3gsara_clear_app_buf( );
            return C3GSARA_ERROR_TIMEOUT;
        }
        Delay_ms ( 1 );
    }
    Delay_ms ( 100 );
    c3gsara_process( );
    if ( strstr( app_buf, rsp ) )
    {
        return C3GSARA_OK;
    }
    else if ( strstr( app_buf, C3GSARA_RSP_ERROR ) )
    {
        return C3GSARA_ERROR_CMD;
    }
    else
    {
        return C3GSARA_ERROR_UNKNOWN;
    }
}

static void c3gsara_error_check ( err_t error_flag )
{
    switch ( error_flag )
    {
        case C3GSARA_OK:
        {
            c3gsara_log_app_buf( );
            break;
        }
        case C3GSARA_ERROR:
        {
            log_error( &logger, " Overflow!" );
            break;
        }
        case C3GSARA_ERROR_TIMEOUT:
        {
            log_error( &logger, " Timeout!" );
            break;
        }
        case C3GSARA_ERROR_CMD:
        {
            log_error( &logger, " CMD!" );
            break;
        }
        case C3GSARA_ERROR_UNKNOWN:
        default:
        {
            log_error( &logger, " Unknown!" );
            break;
        }
    }
    Delay_ms ( 500 );
}

static void c3gsara_log_app_buf ( void )
{
    for ( int32_t buf_cnt = 0; buf_cnt < app_buf_len; buf_cnt++ )
    {
        log_printf( &logger, "%c", app_buf[ buf_cnt ] );
    }
}

static err_t c3gsara_configure_for_network ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    // Deregister from network
    #define DEREGISTER_FROM_NETWORK "2"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_COPS, DEREGISTER_FROM_NETWORK );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Set SIM APN
    c3gsara_set_sim_apn( &c3gsara, SIM_APN );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Enable full functionality
    #define FULL_FUNCTIONALITY "1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CFUN, FULL_FUNCTIONALITY );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Enable network registartion
    #define ENABLE_REG "2"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CREG, ENABLE_REG );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Automatic registration
    #define AUTOMATIC_REGISTRATION "0"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_COPS, AUTOMATIC_REGISTRATION );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#endif
    return func_error;
}

static err_t c3gsara_check_connection ( void )
{
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    #define CONNECTED "+CREG: 2,1"
    c3gsara_send_cmd_check ( &c3gsara, C3GSARA_CMD_CREG );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    if ( strstr( app_buf, CONNECTED ) )
    {
        Delay_ms ( 100 );
        c3gsara_process( );
        c3gsara_log_app_buf( );
        log_printf( &logger, "\r\n" );
        c3gsara_clear_app_buf( );
        // Check signal quality
        c3gsara_send_cmd( &c3gsara, C3GSARA_CMD_CSQ );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        c3gsara_error_check( error_flag );
        return error_flag;
    }
    Delay_ms ( 1000 );
    return C3GSARA_ERROR;
#endif
    return C3GSARA_OK;
}

static err_t c3gsara_configure_for_example ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    #define ACTIVATE_PDP_CONTEXT "1,1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CGACT, ACTIVATE_PDP_CONTEXT );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    #define ACTIVATE_PDP_PROFILE "1,3"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_UPSDA, ACTIVATE_PDP_PROFILE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CMGF, SMS_MODE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

static err_t c3gsara_example ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    uint8_t cmd_buf[ 100 ] = { 0 };
    uint8_t urc_buf[ 20 ] = { 0 };
    uint16_t timeout_cnt = 0;
    uint16_t timeout = 30000;
    uint8_t * __generic_ptr socket_num_buf = 0;
    uint8_t tcp_socket_num[ 2 ] = { 0 };
    uint8_t udp_socket_num[ 2 ] = { 0 };

    // Create TCP socket
    #define RSP_USOCR "+USOCR: "
    #define TCP_PROTOCOL "6"
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCR, TCP_PROTOCOL );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    tcp_socket_num[ 0 ] = *socket_num_buf;
    c3gsara_error_check( error_flag );

    // Create UDP socket
    #define UDP_PROTOCOL "17"
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCR, UDP_PROTOCOL );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    udp_socket_num[ 0 ] = *socket_num_buf;
    c3gsara_error_check( error_flag );

    // Connect TCP socket to remote IP and port
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_USOCO, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Connect UDP socket to remote IP and port
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCO, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Get message length
    uint8_t message_len_buf[ 5 ] = { 0 };
    uint16_t message_len = strlen( MESSAGE_CONTENT );
    uint16_to_str( message_len, message_len_buf );
    l_trim( message_len_buf );
    r_trim( message_len_buf );

    // Write message to TCP socket
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOWR, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Read response message from TCP socket
    #define URC_READ_SOCKET_DATA_TCP "+UUSORD: "
    strcpy( urc_buf, URC_READ_SOCKET_DATA_TCP );
    strcat( urc_buf, tcp_socket_num );
    for ( ; ; )
    {
        c3gsara_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms ( 100 );
            c3gsara_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, tcp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c3gsara_log_app_buf( );
            c3gsara_clear_app_buf( );
            c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USORD, cmd_buf );
            error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
            func_error |= error_flag;
            c3gsara_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms ( 1 );
    }
    timeout_cnt = 0;

    // Write message to UDP socket
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_USOWR, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Read response message from UDP socket
    #define URC_READ_SOCKET_DATA_UDP "+UUSORD: "
    strcpy( urc_buf, URC_READ_SOCKET_DATA_UDP );
    strcat( urc_buf, udp_socket_num );
    for ( ; ; )
    {
        c3gsara_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms ( 100 );
            c3gsara_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, udp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c3gsara_log_app_buf( );
            c3gsara_clear_app_buf( );
            c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USORF, cmd_buf );
            error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
            func_error |= error_flag;
            c3gsara_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms ( 1 );
    }
    
    // Close TCP socket
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCL, tcp_socket_num );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Close UDP socket
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCL, udp_socket_num );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    // Check SMS mode
    #define CMGF_PDU "+CMGF: 0"
    #define CMGF_TXT "+CMGF: 1"
    c3gsara_send_cmd_check( &c3gsara, C3GSARA_CMD_CMGF );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    if ( strstr( app_buf, CMGF_PDU ) )
    {
        // Send SMS in PDU mode
        c3gsara_send_sms_pdu( &c3gsara, SIM_SMSC, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        func_error |= error_flag;
        c3gsara_error_check( error_flag );
    }
    else if ( strstr( app_buf, CMGF_TXT ) )
    {
        // Send SMS in TXT mode
        c3gsara_send_sms_text ( &c3gsara, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        func_error |= error_flag;
        c3gsara_error_check( error_flag );
    }
    // 30 seconds delay
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

// ------------------------------------------------------------------------ END
/*!
 * @file main.c
 * @brief 3G SARA Click Example.
 *
 * # Description
 * Application example shows device capability of connecting to the network and
 * sending SMS or TCP/UDP messages using standard "AT" commands.
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initializes the driver, tests the communication by sending "AT" command, and after that restarts the device.
 *
 * ## Application Task
 * Application task is split in few stages:
 *  - C3GSARA_CONFIGURE_FOR_NETWORK:
 * Sets configuration to device to be able to connect to the network.
 *
 *  - C3GSARA_WAIT_FOR_CONNECTION:
 * Waits for the network registration indicated via CREG URC event and then checks
 * the connection status.
 *
 *  - C3GSARA_CONFIGURE_FOR_EXAMPLE:
 * Sets the device configuration for sending SMS or TCP/UDP messages depending on the selected demo example.
 *
 *  - C3GSARA_EXAMPLE:
 * Depending on the selected demo example, it sends an SMS message (in PDU or TXT mode) or TCP/UDP message.
 *
 * By default, the TCP/UDP example is selected.
 *
 * ## Additional Function
 * - static void c3gsara_clear_app_buf ( void )
 * - static err_t c3gsara_process ( void )
 * - static void c3gsara_error_check( err_t error_flag )
 * - static void c3gsara_log_app_buf ( void )
 * - static err_t c3gsara_rsp_check ( uint8_t *rsp )
 * - static err_t c3gsara_configure_for_connection( void )
 * - static err_t c3gsara_check_connection( void )
 * - static err_t c3gsara_configure_for_messages( void )
 * - static err_t c3gsara_send_message( void )
 *
 * @note
 * In order for the examples to work, user needs to set the APN and SMSC (SMS PDU mode only)
 * of entered SIM card as well as the phone number (SMS mode only) to which he wants to send an SMS.
 * Enter valid values for the following macros: SIM_APN, SIM_SMSC and PHONE_NUMBER_TO_MESSAGE.
 * Example:
    SIM_APN "internet"
    SIM_SMSC "+381610401"
    PHONE_NUMBER_TO_MESSAGE "+381659999999"
 *
 * @author Stefan Filipovic
 *
 */

#include "board.h"
#include "log.h"
#include "c3gsara.h"
#include "conversions.h"

// Example selection macros
#define EXAMPLE_TCP_UDP                     0               // Example of sending messages to a TCP/UDP echo server
#define EXAMPLE_SMS                         1               // Example of sending SMS to a phone number
#define DEMO_EXAMPLE                        EXAMPLE_TCP_UDP // Example selection macro

// SIM APN config
#define SIM_APN                             ""              // Set valid SIM APN

// SMS example parameters
#define SIM_SMSC                            ""              // Set valid SMS Service Center Address - only in SMS PDU mode
#define PHONE_NUMBER_TO_MESSAGE             ""              // Set Phone number to message
#define SMS_MODE                            "1"             // SMS mode: "0" - PDU, "1" - TXT

// TCP/UDP example parameters
#define REMOTE_IP                           "77.46.162.162" // TCP/UDP echo server IP address
#define REMOTE_PORT                         "51111"         // TCP/UDP echo server port

// Message content
#define MESSAGE_CONTENT                     "3G SARA click board - demo example."

// Application buffer size
#define APP_BUFFER_SIZE                     256
#define PROCESS_BUFFER_SIZE                 256

/**
 * @brief Example states.
 * @details Predefined enum values for application example state.
 */
typedef enum
{
    C3GSARA_CONFIGURE_FOR_NETWORK = 1,
    C3GSARA_WAIT_FOR_CONNECTION,
    C3GSARA_CONFIGURE_FOR_EXAMPLE,
    C3GSARA_EXAMPLE

} c3gsara_example_state_t;

static c3gsara_t c3gsara;
static log_t logger;

/**
 * @brief Application example variables.
 * @details Variables used in application example.
 */
static uint8_t app_buf[ APP_BUFFER_SIZE ] = { 0 };
static int32_t app_buf_len = 0;
static err_t error_flag;
static c3gsara_example_state_t example_state;

/**
 * @brief Clearing application buffer.
 * @details This function clears memory of application
 * buffer and reset its length and counter.
 */
static void c3gsara_clear_app_buf ( void );

/**
 * @brief Data reading function.
 * @details This function reads data from device and
 * appends it to the application buffer.
 * @return @li @c  0 - Some data is read.
 *         @li @c -1 - Nothing is read.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_process ( void );

/**
 * @brief Check for errors.
 * @details This function checks for different types of
 * errors and logs them on UART or logs the response if no errors occured.
 * @param[in] error_flag  Error flag to check.
 */
static void c3gsara_error_check ( err_t error_flag );

/**
 * @brief Logs application buffer.
 * @details This function logs data from application buffer.
 */
static void c3gsara_log_app_buf ( void );

/**
 * @brief Response check.
 * @details This function checks for response and
 * returns the status of response.
 * @param[in] rsp  Expected response.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_rsp_check ( uint8_t *rsp );

/**
 * @brief Configure device for connection to the network.
 * @details Sends commands to configure and enable
 * connection to the specified network.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_configure_for_network ( void );

/**
 * @brief Wait for connection signal.
 * @details Wait for connection signal from CREG URC.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_check_connection ( void );

/**
 * @brief Configure device for example.
 * @details Configure device for the specified example.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_configure_for_example ( void );

/**
 * @brief Execute example.
 * @details This function executes SMS or TCP/UDP example depending on the DEMO_EXAMPLE macro.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c3gsara_example ( void );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    c3gsara_cfg_t c3gsara_cfg;  /**< Click config object. */

    /**
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX
     * are defined as HAL_PIN_NC, you will
     * need to define them manually for log to work.
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    c3gsara_cfg_setup( &c3gsara_cfg );
    C3GSARA_MAP_MIKROBUS( c3gsara_cfg, MIKROBUS_1 );
    if ( UART_ERROR == c3gsara_init( &c3gsara, &c3gsara_cfg ) )
    {
        log_error( &logger, " Application Init Error. " );
        log_info( &logger, " Please, run program again... " );
        for ( ; ; );
    }
    
    c3gsara_set_power_state ( &c3gsara, C3GSARA_POWER_STATE_ON );
    
    c3gsara_process( );
    c3gsara_clear_app_buf( );

    // Check communication
    c3gsara_send_cmd( &c3gsara, C3GSARA_CMD_AT );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    
    // Restart device
    #define RESTART_DEVICE "1,1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CFUN, RESTART_DEVICE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    
    log_info( &logger, " Application Task " );
    example_state = C3GSARA_CONFIGURE_FOR_NETWORK;
}

void application_task ( void )
{
    switch ( example_state )
    {
        case C3GSARA_CONFIGURE_FOR_NETWORK:
        {
            if ( C3GSARA_OK == c3gsara_configure_for_network( ) )
            {
                example_state = C3GSARA_WAIT_FOR_CONNECTION;
            }
            break;
        }
        case C3GSARA_WAIT_FOR_CONNECTION:
        {
            if ( C3GSARA_OK == c3gsara_check_connection( ) )
            {
                example_state = C3GSARA_CONFIGURE_FOR_EXAMPLE;
            }
            break;
        }
        case C3GSARA_CONFIGURE_FOR_EXAMPLE:
        {
            if ( C3GSARA_OK == c3gsara_configure_for_example( ) )
            {
                example_state = C3GSARA_EXAMPLE;
            }
            break;
        }
        case C3GSARA_EXAMPLE:
        {
            c3gsara_example( );
            break;
        }
        default:
        {
            log_error( &logger, " Example state." );
            break;
        }
    }
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

static void c3gsara_clear_app_buf ( void )
{
    memset( app_buf, 0, app_buf_len );
    app_buf_len = 0;
}

static err_t c3gsara_process ( void )
{
    uint8_t rx_buf[ PROCESS_BUFFER_SIZE ] = { 0 };
    int32_t rx_size = 0;
    rx_size = c3gsara_generic_read( &c3gsara, rx_buf, PROCESS_BUFFER_SIZE );
    if ( rx_size > 0 ) 
    {
        int32_t buf_cnt = app_buf_len;
        if ( ( ( app_buf_len + rx_size ) > APP_BUFFER_SIZE ) && ( app_buf_len > 0 ) ) 
        {
            buf_cnt = APP_BUFFER_SIZE - ( ( app_buf_len + rx_size ) - APP_BUFFER_SIZE );
            memmove ( app_buf, &app_buf[ APP_BUFFER_SIZE - buf_cnt ], buf_cnt );
        }
        for ( int32_t rx_cnt = 0; rx_cnt < rx_size; rx_cnt++ ) 
        {
            if ( rx_buf[ rx_cnt ] ) 
            {
                app_buf[ buf_cnt++ ] = rx_buf[ rx_cnt ];
                if ( app_buf_len < APP_BUFFER_SIZE )
                {
                    app_buf_len++;
                }
            }
        }
        return C3GSARA_OK;
    }
    return C3GSARA_ERROR;
}

static err_t c3gsara_rsp_check ( uint8_t *rsp )
{
    uint32_t timeout_cnt = 0;
    uint32_t timeout = 120000;
    c3gsara_clear_app_buf( );
    c3gsara_process( );
    while ( ( 0 == strstr( app_buf, rsp ) ) &&
            ( 0 == strstr( app_buf, C3GSARA_RSP_ERROR ) ) )
    {
        c3gsara_process( );
        if ( timeout_cnt++ > timeout )
        {
            c3gsara_clear_app_buf( );
            return C3GSARA_ERROR_TIMEOUT;
        }
        Delay_ms ( 1 );
    }
    Delay_ms ( 100 );
    c3gsara_process( );
    if ( strstr( app_buf, rsp ) )
    {
        return C3GSARA_OK;
    }
    else if ( strstr( app_buf, C3GSARA_RSP_ERROR ) )
    {
        return C3GSARA_ERROR_CMD;
    }
    else
    {
        return C3GSARA_ERROR_UNKNOWN;
    }
}

static void c3gsara_error_check ( err_t error_flag )
{
    switch ( error_flag )
    {
        case C3GSARA_OK:
        {
            c3gsara_log_app_buf( );
            break;
        }
        case C3GSARA_ERROR:
        {
            log_error( &logger, " Overflow!" );
            break;
        }
        case C3GSARA_ERROR_TIMEOUT:
        {
            log_error( &logger, " Timeout!" );
            break;
        }
        case C3GSARA_ERROR_CMD:
        {
            log_error( &logger, " CMD!" );
            break;
        }
        case C3GSARA_ERROR_UNKNOWN:
        default:
        {
            log_error( &logger, " Unknown!" );
            break;
        }
    }
    Delay_ms ( 500 );
}

static void c3gsara_log_app_buf ( void )
{
    for ( int32_t buf_cnt = 0; buf_cnt < app_buf_len; buf_cnt++ )
    {
        log_printf( &logger, "%c", app_buf[ buf_cnt ] );
    }
}

static err_t c3gsara_configure_for_network ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    // Deregister from network
    #define DEREGISTER_FROM_NETWORK "2"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_COPS, DEREGISTER_FROM_NETWORK );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Set SIM APN
    c3gsara_set_sim_apn( &c3gsara, SIM_APN );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Enable full functionality
    #define FULL_FUNCTIONALITY "1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CFUN, FULL_FUNCTIONALITY );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Enable network registartion
    #define ENABLE_REG "2"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CREG, ENABLE_REG );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Automatic registration
    #define AUTOMATIC_REGISTRATION "0"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_COPS, AUTOMATIC_REGISTRATION );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#endif
    return func_error;
}

static err_t c3gsara_check_connection ( void )
{
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    #define CONNECTED "+CREG: 2,1"
    c3gsara_send_cmd_check ( &c3gsara, C3GSARA_CMD_CREG );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    c3gsara_error_check( error_flag );
    if ( strstr( app_buf, CONNECTED ) )
    {
        Delay_ms ( 100 );
        c3gsara_process( );
        c3gsara_log_app_buf( );
        log_printf( &logger, "\r\n" );
        c3gsara_clear_app_buf( );
        // Check signal quality
        c3gsara_send_cmd( &c3gsara, C3GSARA_CMD_CSQ );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        c3gsara_error_check( error_flag );
        return error_flag;
    }
    Delay_ms ( 1000 );
    return C3GSARA_ERROR;
#endif
    return C3GSARA_OK;
}

static err_t c3gsara_configure_for_example ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    #define ACTIVATE_PDP_CONTEXT "1,1"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CGACT, ACTIVATE_PDP_CONTEXT );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    #define ACTIVATE_PDP_PROFILE "1,3"
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_UPSDA, ACTIVATE_PDP_PROFILE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_CMGF, SMS_MODE );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

static err_t c3gsara_example ( void )
{
    err_t func_error = C3GSARA_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    uint8_t cmd_buf[ 100 ] = { 0 };
    uint8_t urc_buf[ 20 ] = { 0 };
    uint16_t timeout_cnt = 0;
    uint16_t timeout = 30000;
    uint8_t * __generic_ptr socket_num_buf = 0;
    uint8_t tcp_socket_num[ 2 ] = { 0 };
    uint8_t udp_socket_num[ 2 ] = { 0 };

    // Create TCP socket
    #define RSP_USOCR "+USOCR: "
    #define TCP_PROTOCOL "6"
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCR, TCP_PROTOCOL );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    tcp_socket_num[ 0 ] = *socket_num_buf;
    c3gsara_error_check( error_flag );

    // Create UDP socket
    #define UDP_PROTOCOL "17"
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCR, UDP_PROTOCOL );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    udp_socket_num[ 0 ] = *socket_num_buf;
    c3gsara_error_check( error_flag );

    // Connect TCP socket to remote IP and port
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_USOCO, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Connect UDP socket to remote IP and port
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCO, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Get message length
    uint8_t message_len_buf[ 5 ] = { 0 };
    uint16_t message_len = strlen( MESSAGE_CONTENT );
    uint16_to_str( message_len, message_len_buf );
    l_trim( message_len_buf );
    r_trim( message_len_buf );

    // Write message to TCP socket
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOWR, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Read response message from TCP socket
    #define URC_READ_SOCKET_DATA_TCP "+UUSORD: "
    strcpy( urc_buf, URC_READ_SOCKET_DATA_TCP );
    strcat( urc_buf, tcp_socket_num );
    for ( ; ; )
    {
        c3gsara_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms ( 100 );
            c3gsara_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, tcp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c3gsara_log_app_buf( );
            c3gsara_clear_app_buf( );
            c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USORD, cmd_buf );
            error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
            func_error |= error_flag;
            c3gsara_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms ( 1 );
    }
    timeout_cnt = 0;

    // Write message to UDP socket
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c3gsara_send_cmd_with_par( &c3gsara, C3GSARA_CMD_USOWR, cmd_buf );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );

    // Read response message from UDP socket
    #define URC_READ_SOCKET_DATA_UDP "+UUSORD: "
    strcpy( urc_buf, URC_READ_SOCKET_DATA_UDP );
    strcat( urc_buf, udp_socket_num );
    for ( ; ; )
    {
        c3gsara_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms ( 100 );
            c3gsara_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, udp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c3gsara_log_app_buf( );
            c3gsara_clear_app_buf( );
            c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USORF, cmd_buf );
            error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
            func_error |= error_flag;
            c3gsara_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms ( 1 );
    }
    
    // Close TCP socket
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCL, tcp_socket_num );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    
    // Close UDP socket
    c3gsara_send_cmd_with_par ( &c3gsara, C3GSARA_CMD_USOCL, udp_socket_num );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    // Check SMS mode
    #define CMGF_PDU "+CMGF: 0"
    #define CMGF_TXT "+CMGF: 1"
    c3gsara_send_cmd_check( &c3gsara, C3GSARA_CMD_CMGF );
    error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
    func_error |= error_flag;
    c3gsara_error_check( error_flag );
    if ( strstr( app_buf, CMGF_PDU ) )
    {
        // Send SMS in PDU mode
        c3gsara_send_sms_pdu( &c3gsara, SIM_SMSC, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        func_error |= error_flag;
        c3gsara_error_check( error_flag );
    }
    else if ( strstr( app_buf, CMGF_TXT ) )
    {
        // Send SMS in TXT mode
        c3gsara_send_sms_text ( &c3gsara, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c3gsara_rsp_check( C3GSARA_RSP_OK );
        func_error |= error_flag;
        c3gsara_error_check( error_flag );
    }
    // 30 seconds delay
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

// ------------------------------------------------------------------------ END

额外支持

资源

喜欢这个项目吗?

'购买此套件' 按钮会直接带您进入购物车,您可以在购物车中轻松添加或移除产品。