Ai-Thinker-Open / GPRS_C_SDK

Ai-Thinker A9/A9G GPRS (with GPS(A9G)) module C development SDK
https://ai-thinker-open.github.io/GPRS_C_SDK_DOC
MIT License
449 stars 236 forks source link

HOW TO COMBINE TWO CODES to send gps data to BROKER #165

Closed futechiot closed 6 years ago

futechiot commented 6 years ago

HELLO THERE,

I'm Trying to send GPS data through MQTT to the broker test.mosquitto.org, can anyone tell me how to combine these codes, how can I send variable GPS data in PUBLISH_PAYLOAD CAN ANYONE GUIDE ME? @Neutree THANK YOU.

NathansLab commented 6 years ago

I have tried the same, but had no succes. here is my code:

#include "stdbool.h"
#include "stdint.h"
#include "stdio.h"
#include "string.h"

#include "api_os.h"
#include "api_debug.h"
#include "api_event.h"
#include "api_mqtt.h"
#include "api_network.h"
#include "api_socket.h"

#include <string.h>
#include <api_gps.h>
#include <api_event.h>
#include <api_hal_uart.h>
#include "gps_parse.h"
#include "math.h"
#include "gps.h"

#define BROKER_IP  "scheufele.ddns.net"
#define BROKER_PORT 1883
#define CLIENT_ID  "gprs"
#define CLIENT_USER ""
#define CLIENT_PASS ""
#define SUBSCRIBE_TOPIC "app"
#define PUBLISH_TOPIC   "gps"
#define PUBLISH_INTERVAL 5000

#define MQTT_TASK_STACK_SIZE    (2048 * 2)
#define MQTT_TASK_PRIORITY      2
#define MQTT_TASK_NAME          "Main Test Task"

#define SECOND_TASK_STACK_SIZE    (2048 * 2)
#define SECOND_TASK_PRIORITY      3
#define SECOND_TASK_NAME          "MQTT Test Task"

#define GPS_TASK_STACK_SIZE    (2048 * 2)
#define GPS_TASK_PRIORITY      1
#define GPS_TAST_NAME          "GPS Test Task"

static HANDLE gpsTaskHandle = NULL;
bool flag = false;
bool isGpsOne = true;

static HANDLE mainTaskHandle = NULL;
static HANDLE secondTaskHandle = NULL;

static HANDLE semMqttStart = NULL;

char publish_payload[300] = "Hier wird die GPS-Information stehen.";
char buffer[300];

typedef enum{
    MQTT_EVENT_CONNECTED = 0,
    MQTT_EVENT_DISCONNECTED ,
    MQTT_EVENT_MAX
}MQTT_Event_ID_t;

typedef struct {
    MQTT_Event_ID_t id;
    MQTT_Client_t* client;
}MQTT_Event_t;

typedef enum{
    MQTT_STATUS_DISCONNECTED = 0,
    MQTT_STATUS_CONNECTED       ,
    MQTT_STATUS_MAX
}MQTT_Status_t;

MQTT_Status_t mqttStatus = MQTT_STATUS_DISCONNECTED;

static void EventDispatch(API_Event_t* pEvent)
{
    switch(pEvent->id)
    {
        case API_EVENT_ID_NO_SIMCARD:
            Trace(1,"!!NO SIM CARD%d!!!!",pEvent->param1);
            break;

        case API_EVENT_ID_SYSTEM_READY:
            Trace(1,"system initialize complete");
            break;

        case API_EVENT_ID_NETWORK_REGISTERED_HOME:
        case API_EVENT_ID_NETWORK_REGISTERED_ROAMING:
            Trace(1,"network register success");
            Network_StartAttach();
            break;

        case API_EVENT_ID_NETWORK_ATTACHED:
            Trace(1,"network attach success");
            Network_PDP_Context_t context = {
                .apn        ="internet.eplus.de",
                .userName   = "eplus"    ,
                .userPasswd = "gprs"
            };
            Network_StartActive(context);
            break;
        case API_EVENT_ID_GPS_UART_RECEIVED:
            Trace(1,"received GPS data,length:%d, data:%s,flag:%d",pEvent->param1,pEvent->pParam1,flag);
            GPS_Update(pEvent->pParam1,pEvent->param1);
            break;
        case API_EVENT_ID_UART_RECEIVED:
            if(pEvent->param1 == UART1)
            {
                uint8_t data[pEvent->param2+1];
                data[pEvent->param2] = 0;
                memcpy(data,pEvent->pParam1,pEvent->param2);
                Trace(1,"uart received data,length:%d,data:%s",pEvent->param2,data);
                if(strcmp(data,"close") == 0)
                {
                    Trace(1,"close gps");
                    GPS_Close();
                    isGpsOne = false;
                }
                else if(strcmp(data,"open") == 0)
                {
                    Trace(1,"open gps");
                    GPS_Open(NULL);
                    isGpsOne = true;
                }
            }
            break;

        case API_EVENT_ID_NETWORK_ACTIVATED:
            Trace(1,"network activate success..");
            OS_ReleaseSemaphore(semMqttStart);
            break;

        case API_EVENT_ID_SOCKET_CONNECTED:
            Trace(1,"socket connected");
            break;

        case API_EVENT_ID_SOCKET_CLOSED:
            Trace(1,"socket closed");

            break;

        default:
            break;
    }
}

void gps_testTask(void *pData)
{
    GPS_Info_t* gpsInfo = Gps_GetInfo();

    //wait for gprs register complete
    //The process of GPRS registration network may cause the power supply voltage of GPS to drop,
    //which resulting in GPS restart.
    while(!flag)
    {
        Trace(1,"wait for gprs regiter complete");
        OS_Sleep(2000);
    }

    //open GPS hardware(UART2 open either)
    GPS_Init();
    GPS_Open(NULL);

    //wait for gps start up, or gps will not response command
    while(gpsInfo->rmc.latitude.value == 0)
        OS_Sleep(1000);

    // set gps nmea output interval
    for(uint8_t i = 0;i<3;++i)
    {
        bool ret = GPS_SetOutputInterval(10000);
        Trace(1,"set gps ret:%d",ret);
        if(ret)
            break;
        OS_Sleep(1000);
    }

    // if(!GPS_ClearInfoInFlash())
    //     Trace(1,"erase gps fail");

    // if(!GPS_SetQzssOutput(false))
    //     Trace(1,"enable qzss nmea output fail");

    // if(!GPS_SetSearchMode(true,false,true,false))
    //     Trace(1,"set search mode fail");

    // if(!GPS_SetSBASEnable(true))
    //     Trace(1,"enable sbas fail");

    if(!GPS_GetVersion(buffer,150))
        Trace(1,"get gps firmware version fail");
    else
        Trace(1,"gps firmware version:%s",buffer);

    // if(!GPS_SetFixMode(GPS_FIX_MODE_LOW_SPEED))
        // Trace(1,"set fix mode fail");

    if(!GPS_SetOutputInterval(1000))
        Trace(1,"set nmea output interval fail");

    Trace(1,"init ok");

    while(1)
    {
        if(isGpsOne)
        {
            //show fix info
            uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type;
            char* isFixedStr;
            if(isFixed == 2)
                isFixedStr = "2D fix";
            else if(isFixed == 3)
            {
                if(gpsInfo->gga.fix_quality == 1)
                    isFixedStr = "3D fix";
                else if(gpsInfo->gga.fix_quality == 2)
                    isFixedStr = "3D/DGPS fix";
            }
            else
                isFixedStr = "no fix";

            //convert unit ddmm.mmmm to degree(°)
            int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
            double latitude = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
            temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
            double longitude = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;

            //you can copy ` latitude,longitude ` to http://www.gpsspg.com/maps.htm check location on map

            snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type,
                                                                gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude);
            //show in tracer
            Trace(2,buffer);
            //send to UART1
            UART_Write(UART1,buffer,strlen(buffer));
            UART_Write(UART1,"\r\n\r\n",4);
        }

        OS_Sleep(5000);
    }
}

void gps_MainTask(void *pData)
{
    API_Event_t* event=NULL;

    //open UART1 to print NMEA infomation
    UART_Config_t config = {
        .baudRate = UART_BAUD_RATE_115200,
        .dataBits = UART_DATA_BITS_8,
        .stopBits = UART_STOP_BITS_1,
        .parity   = UART_PARITY_NONE,
        .rxCallback = NULL,
        .useEvent   = true
    };
    UART_Init(UART1,config);

    //Create UART1 send task and location print task
    OS_CreateTask(gps_testTask,
            NULL, NULL, GPS_TASK_STACK_SIZE, GPS_TASK_PRIORITY, 0, 0, GPS_TAST_NAME);

    //Wait event
    while(1)
    {
        if(OS_WaitEvent(gpsTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
        {
            EventDispatch(event);
            OS_Free(event->pParam1);
            OS_Free(event->pParam2);
            OS_Free(event);
        }
    }
}

void OnMqttReceived(void* arg, const char* topic, uint32_t payloadLen)
{
    Trace(1,"MQTT received publish data request, topic:%s, payload length:%d",topic,payloadLen);
}

void OnMqttReceiedData(void* arg, const uint8_t* data, uint16_t len, MQTT_Flags_t flags)
{
    Trace(1,"MQTT recieved publish data,  length:%d,data:%s",len,data);
    if(flags == MQTT_FLAG_DATA_LAST)
        Trace(1,"MQTT data is last frame");
}

 void OnMqttSubscribed(void* arg, MQTT_Error_t err)
 {
     if(err != MQTT_ERROR_NONE)
        Trace(1,"MQTT subscribe fail,error code:%d",err);
     else
        Trace(1,"MQTT subscribe success,topic:%s",(const char*)arg);
 }

void OnMqttConnection(MQTT_Client_t *client, void *arg, MQTT_Connection_Status_t status)
{
    Trace(1,"MQTT connection status:%d",status);
    MQTT_Event_t* event = (MQTT_Event_t*)OS_Malloc(sizeof(MQTT_Event_t));
    if(!event)
    {
        Trace(1,"MQTT no memory");
        return ;
    }
    if(status == MQTT_CONNECTION_ACCEPTED)
    {
        Trace(1,"MQTT succeed connect to broker");
        //!!! DO NOT suscribe here(interrupt function), do MQTT suscribe in task, or it will not excute
        event->id = MQTT_EVENT_CONNECTED;
        event->client = client;
        OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL);
    }
    else
    {
        event->id = MQTT_EVENT_DISCONNECTED;
        event->client = client;
        OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL);
        Trace(1,"MQTT connect to broker fail,error code:%d",status);
    }
    Trace(1,"MQTT OnMqttConnection() end");
}

void StartTimerPublish(uint32_t interval,MQTT_Client_t* client);
void OnPublish(void* arg, MQTT_Error_t err)
{
    if(err == MQTT_ERROR_NONE)
        Trace(1,"MQTT publish success");
    else
        Trace(1,"MQTT publish error, error code:%d",err);
}

void OnTimerPublish(void* param)
{
    MQTT_Error_t err;
    MQTT_Client_t* client = (MQTT_Client_t*)param;
    if(mqttStatus != MQTT_STATUS_CONNECTED)
    {
        Trace(1,"MQTT not connected to broker! can not publish");
        return;
    }
    publish_payload = buffer;
    snprintf(buffer->member, sizeof(buffer->member), "%s", publish_payload);
    Trace(1,"MQTT OnTimerPublish");
    err = MQTT_Publish(client,PUBLISH_TOPIC,publish_payload,strlen(publish_payload),1,2,0,OnPublish,NULL);
    if(err != MQTT_ERROR_NONE)
        Trace(1,"MQTT publish error, error code:%d",err);
    StartTimerPublish(PUBLISH_INTERVAL,client);
}

void StartTimerPublish(uint32_t interval,MQTT_Client_t* client)
{
    OS_StartCallbackTimer(mainTaskHandle,interval,OnTimerPublish,(void*)client);
}

void SecondTaskEventDispatch(MQTT_Event_t* pEvent)
{
    switch(pEvent->id)
    {
        case MQTT_EVENT_CONNECTED:
            mqttStatus = MQTT_STATUS_CONNECTED;
            Trace(1,"MQTT connected, now subscribe topic:%s",SUBSCRIBE_TOPIC);
            MQTT_Error_t err;
            MQTT_SetInPubCallback(pEvent->client, OnMqttReceived, OnMqttReceiedData, NULL);
            err = MQTT_Subscribe(pEvent->client,SUBSCRIBE_TOPIC,2,OnMqttSubscribed,(void*)SUBSCRIBE_TOPIC);
            if(err != MQTT_ERROR_NONE)
                Trace(1,"MQTT subscribe error, error code:%d",err);
            StartTimerPublish(PUBLISH_INTERVAL,pEvent->client);
            break;
        case MQTT_EVENT_DISCONNECTED:
            mqttStatus = MQTT_STATUS_DISCONNECTED;
            break;
        default:
            break;
    }
}

void SecondTask(void *pData)
{
    MQTT_Event_t* event=NULL;
    semMqttStart = OS_CreateSemaphore(0);
    OS_WaitForSemaphore(semMqttStart,OS_WAIT_FOREVER);
    OS_DeleteSemaphore(semMqttStart);
    Trace(1,"start mqtt test");
    MQTT_Client_t* client = MQTT_ClientNew();
    MQTT_Connect_Info_t ci;
    MQTT_Error_t err;
    memset(&ci,0,sizeof(MQTT_Connect_Info_t));
    ci.client_id = CLIENT_ID;
    ci.client_user = CLIENT_USER;
    ci.client_pass = CLIENT_PASS;
    ci.keep_alive = 60;
    ci.clean_session = 1;
    ci.use_ssl = false;

    err = MQTT_Connect(client,BROKER_IP,BROKER_PORT,OnMqttConnection,NULL,&ci);
    if(err != MQTT_ERROR_NONE)
        Trace(1,"MQTT connect fail,error code:%d",err);

    while(1)
    {
        if(OS_WaitEvent(secondTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
        {
            SecondTaskEventDispatch(event);
            OS_Free(event);
        }
    }
}

void MainTask(void *pData)
{
    API_Event_t* event=NULL;

    secondTaskHandle = OS_CreateTask(SecondTask,
        NULL, NULL, SECOND_TASK_STACK_SIZE, SECOND_TASK_PRIORITY, 0, 0, SECOND_TASK_NAME);

    while(1)
    {
        if(OS_WaitEvent(mainTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
        {
            EventDispatch(event);
            OS_Free(event->pParam1);
            OS_Free(event->pParam2);
            OS_Free(event);
        }
    }
}

void mqtt_Main(void)
{
    delay(5000);
    Trace(1,"mqtt_Main task started");
    delay(5000);
    mainTaskHandle = OS_CreateTask(MainTask,
        NULL, NULL, MQTT_TASK_STACK_SIZE, MQTT_TASK_PRIORITY, 0, 0, MQTT_TASK_NAME);
    OS_SetUserMainHandle(&mainTaskHandle);
    gpsTaskHandle = OS_CreateTask(gps_MainTask,
        NULL, NULL, GPS_TASK_STACK_SIZE, GPS_TASK_PRIORITY, 0, 0, GPS_TAST_NAME);
    OS_SetUserMainHandle(&gpsTaskHandle);
}

However the code is not working yet, the compiler gives an error

PS C:\GPRS_C_SDK> ./build.bat demo mqtt
CSDTK PATH: C:\GPRS_C_SDK\CSDTK42
build folder exist
number of processors: 4
Build host is WINDOWS

MAKE              init

MAKE              libs

MAKE              libs/gps

MAKE              libs/gps/minmea

PREPARING         libgps_debug.a

MAKE              libs/utils

PREPARING         liblibs_debug.a

MAKE              demo/mqtt
CC                demo_mqtt.c
src/demo_mqtt.c: In function 'gps_testTask':
src/demo_mqtt.c:232: warning: format '%f' expects type 'double', but argument 12 has type 'struct minmea_float'
src/demo_mqtt.c: In function 'OnTimerPublish':
src/demo_mqtt.c:342: error: incompatible types when assigning to type 'char[300]' from type 'char *'
src/demo_mqtt.c:343: error: request for member 'member' in something not a structure or union
src/demo_mqtt.c:343: error: request for member 'member' in something not a structure or union
src/demo_mqtt.c: In function 'mqtt_Main':
src/demo_mqtt.c:431: warning: implicit declaration of function 'delay'
C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:958: recipe for target 'C:/GPRS_C_SDK/build/mqtt/demo/mqtt/obj/debug/de
mo_mqtt.o' failed
make[3]: *** [C:/GPRS_C_SDK/build/mqtt/demo/mqtt/obj/debug/demo_mqtt.o] Error 1
make[3]: *** Waiting for unfinished jobs....
C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:975: recipe for target 'dependencies' failed
make[2]: *** [dependencies] Error 2
C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:718: recipe for target 'C:/GPRS_C_SDK/build/mqtt//mqtt.srec' failed
make[1]: *** [C:/GPRS_C_SDK/build/mqtt//mqtt.srec] Error 2
C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:371: recipe for target 'lod' failed
make: *** [lod] Error 2
ROM    total:1048576 Bytes     used:2656 Bytes
RAM    total:1048576 Bytes     used:32 Bytes
=== Build Time: 1s at 19.07.2018 17:30:22,72 ===
_____________________________________________________
PS C:\GPRS_C_SDK>

somehow it seems that there is a problem converting char* to char[].

futechiot commented 6 years ago

Hello there, Thanks... But anyhow I want to make it work. We can put our combined efforts to solve this! If you don't mind. how can I reach you? Do you have Skype ID or something?

Thanks for your response.

On Thu 19 Jul, 2018, 9:11 PM Nathan Scheufele, notifications@github.com wrote:

I have tried the same, but had no succes. here is my code:

include "stdbool.h"

include "stdint.h"

include "stdio.h"

include "string.h"

include "api_os.h"

include "api_debug.h"

include "api_event.h"

include "api_mqtt.h"

include "api_network.h"

include "api_socket.h"

include

include

include

include

include "gps_parse.h"

include "math.h"

include "gps.h"

define BROKER_IP "scheufele.ddns.net"

define BROKER_PORT 1883

define CLIENT_ID "gprs"

define CLIENT_USER ""

define CLIENT_PASS ""

define SUBSCRIBE_TOPIC "app"

define PUBLISH_TOPIC "gps"

define PUBLISH_INTERVAL 5000

define MQTT_TASK_STACK_SIZE (2048 * 2)

define MQTT_TASK_PRIORITY 2

define MQTT_TASK_NAME "Main Test Task"

define SECOND_TASK_STACK_SIZE (2048 * 2)

define SECOND_TASK_PRIORITY 3

define SECOND_TASK_NAME "MQTT Test Task"

define GPS_TASK_STACK_SIZE (2048 * 2)

define GPS_TASK_PRIORITY 1

define GPS_TAST_NAME "GPS Test Task"

static HANDLE gpsTaskHandle = NULL; bool flag = false; bool isGpsOne = true;

static HANDLE mainTaskHandle = NULL; static HANDLE secondTaskHandle = NULL;

static HANDLE semMqttStart = NULL;

char publish_payload[300] = "Hier wird die GPS-Information stehen."; char buffer[300];

typedef enum{ MQTT_EVENT_CONNECTED = 0, MQTT_EVENT_DISCONNECTED , MQTT_EVENT_MAX }MQTT_Event_ID_t;

typedef struct { MQTT_Event_ID_t id; MQTT_Client_t* client; }MQTT_Event_t;

typedef enum{ MQTT_STATUS_DISCONNECTED = 0, MQTT_STATUS_CONNECTED , MQTT_STATUS_MAX }MQTT_Status_t;

MQTT_Status_t mqttStatus = MQTT_STATUS_DISCONNECTED;

static void EventDispatch(API_Event_t* pEvent) { switch(pEvent->id) { case API_EVENT_ID_NO_SIMCARD: Trace(1,"!!NO SIM CARD%d!!!!",pEvent->param1); break;

    case API_EVENT_ID_SYSTEM_READY:
        Trace(1,"system initialize complete");
        break;

    case API_EVENT_ID_NETWORK_REGISTERED_HOME:
    case API_EVENT_ID_NETWORK_REGISTERED_ROAMING:
        Trace(1,"network register success");
        Network_StartAttach();
        break;

    case API_EVENT_ID_NETWORK_ATTACHED:
        Trace(1,"network attach success");
        Network_PDP_Context_t context = {
            .apn        ="internet.eplus.de",
            .userName   = "eplus"    ,
            .userPasswd = "gprs"
        };
        Network_StartActive(context);
        break;
    case API_EVENT_ID_GPS_UART_RECEIVED:
        Trace(1,"received GPS data,length:%d, data:%s,flag:%d",pEvent->param1,pEvent->pParam1,flag);
        GPS_Update(pEvent->pParam1,pEvent->param1);
        break;
    case API_EVENT_ID_UART_RECEIVED:
        if(pEvent->param1 == UART1)
        {
            uint8_t data[pEvent->param2+1];
            data[pEvent->param2] = 0;
            memcpy(data,pEvent->pParam1,pEvent->param2);
            Trace(1,"uart received data,length:%d,data:%s",pEvent->param2,data);
            if(strcmp(data,"close") == 0)
            {
                Trace(1,"close gps");
                GPS_Close();
                isGpsOne = false;
            }
            else if(strcmp(data,"open") == 0)
            {
                Trace(1,"open gps");
                GPS_Open(NULL);
                isGpsOne = true;
            }
        }
        break;

    case API_EVENT_ID_NETWORK_ACTIVATED:
        Trace(1,"network activate success..");
        OS_ReleaseSemaphore(semMqttStart);
        break;

    case API_EVENT_ID_SOCKET_CONNECTED:
        Trace(1,"socket connected");
        break;

    case API_EVENT_ID_SOCKET_CLOSED:
        Trace(1,"socket closed");

        break;

    default:
        break;
}

}

void gps_testTask(void pData) { GPS_Info_t gpsInfo = Gps_GetInfo();

//wait for gprs register complete
//The process of GPRS registration network may cause the power supply voltage of GPS to drop,
//which resulting in GPS restart.
while(!flag)
{
    Trace(1,"wait for gprs regiter complete");
    OS_Sleep(2000);
}

//open GPS hardware(UART2 open either)
GPS_Init();
GPS_Open(NULL);

//wait for gps start up, or gps will not response command
while(gpsInfo->rmc.latitude.value == 0)
    OS_Sleep(1000);

// set gps nmea output interval
for(uint8_t i = 0;i<3;++i)
{
    bool ret = GPS_SetOutputInterval(10000);
    Trace(1,"set gps ret:%d",ret);
    if(ret)
        break;
    OS_Sleep(1000);
}

// if(!GPS_ClearInfoInFlash())
//     Trace(1,"erase gps fail");

// if(!GPS_SetQzssOutput(false))
//     Trace(1,"enable qzss nmea output fail");

// if(!GPS_SetSearchMode(true,false,true,false))
//     Trace(1,"set search mode fail");

// if(!GPS_SetSBASEnable(true))
//     Trace(1,"enable sbas fail");

if(!GPS_GetVersion(buffer,150))
    Trace(1,"get gps firmware version fail");
else
    Trace(1,"gps firmware version:%s",buffer);

// if(!GPS_SetFixMode(GPS_FIX_MODE_LOW_SPEED))
    // Trace(1,"set fix mode fail");

if(!GPS_SetOutputInterval(1000))
    Trace(1,"set nmea output interval fail");

Trace(1,"init ok");

while(1)
{
    if(isGpsOne)
    {
        //show fix info
        uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type;
        char* isFixedStr;
        if(isFixed == 2)
            isFixedStr = "2D fix";
        else if(isFixed == 3)
        {
            if(gpsInfo->gga.fix_quality == 1)
                isFixedStr = "3D fix";
            else if(gpsInfo->gga.fix_quality == 2)
                isFixedStr = "3D/DGPS fix";
        }
        else
            isFixedStr = "no fix";

        //convert unit ddmm.mmmm to degree(°)
        int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
        double latitude = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
        temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
        double longitude = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;

        //you can copy ` latitude,longitude ` to http://www.gpsspg.com/maps.htm check location on map

        snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type,
                                                            gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude);
        //show in tracer
        Trace(2,buffer);
        //send to UART1
        UART_Write(UART1,buffer,strlen(buffer));
        UART_Write(UART1,"\r\n\r\n",4);
    }

    OS_Sleep(5000);
}

}

void gps_MainTask(void pData) { API_Event_t event=NULL;

//open UART1 to print NMEA infomation
UART_Config_t config = {
    .baudRate = UART_BAUD_RATE_115200,
    .dataBits = UART_DATA_BITS_8,
    .stopBits = UART_STOP_BITS_1,
    .parity   = UART_PARITY_NONE,
    .rxCallback = NULL,
    .useEvent   = true
};
UART_Init(UART1,config);

//Create UART1 send task and location print task
OS_CreateTask(gps_testTask,
        NULL, NULL, GPS_TASK_STACK_SIZE, GPS_TASK_PRIORITY, 0, 0, GPS_TAST_NAME);

//Wait event
while(1)
{
    if(OS_WaitEvent(gpsTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
    {
        EventDispatch(event);
        OS_Free(event->pParam1);
        OS_Free(event->pParam2);
        OS_Free(event);
    }
}

}

void OnMqttReceived(void arg, const char topic, uint32_t payloadLen) { Trace(1,"MQTT received publish data request, topic:%s, payload length:%d",topic,payloadLen); }

void OnMqttReceiedData(void arg, const uint8_t data, uint16_t len, MQTT_Flags_t flags) { Trace(1,"MQTT recieved publish data, length:%d,data:%s",len,data); if(flags == MQTT_FLAG_DATA_LAST) Trace(1,"MQTT data is last frame"); }

void OnMqttSubscribed(void arg, MQTT_Error_t err) { if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe fail,error code:%d",err); else Trace(1,"MQTT subscribe success,topic:%s",(const char)arg); }

void OnMqttConnection(MQTT_Client_t client, void arg, MQTT_Connection_Status_t status) { Trace(1,"MQTT connection status:%d",status); MQTT_Event_t event = (MQTT_Event_t)OS_Malloc(sizeof(MQTT_Event_t)); if(!event) { Trace(1,"MQTT no memory"); return ; } if(status == MQTT_CONNECTION_ACCEPTED) { Trace(1,"MQTT succeed connect to broker"); //!!! DO NOT suscribe here(interrupt function), do MQTT suscribe in task, or it will not excute event->id = MQTT_EVENT_CONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); } else { event->id = MQTT_EVENT_DISCONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); Trace(1,"MQTT connect to broker fail,error code:%d",status); } Trace(1,"MQTT OnMqttConnection() end"); }

void StartTimerPublish(uint32_t interval,MQTT_Client_t client); void OnPublish(void arg, MQTT_Error_t err) { if(err == MQTT_ERROR_NONE) Trace(1,"MQTT publish success"); else Trace(1,"MQTT publish error, error code:%d",err); }

void OnTimerPublish(void param) { MQTT_Error_t err; MQTT_Client_t client = (MQTT_Client_t*)param; if(mqttStatus != MQTT_STATUS_CONNECTED) { Trace(1,"MQTT not connected to broker! can not publish"); return; } publish_payload = buffer; snprintf(buffer->member, sizeof(buffer->member), "%s", publish_payload); Trace(1,"MQTT OnTimerPublish"); err = MQTT_Publish(client,PUBLISH_TOPIC,publish_payload,strlen(publish_payload),1,2,0,OnPublish,NULL); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT publish error, error code:%d",err); StartTimerPublish(PUBLISH_INTERVAL,client); }

void StartTimerPublish(uint32_t interval,MQTT_Client_t client) { OS_StartCallbackTimer(mainTaskHandle,interval,OnTimerPublish,(void)client); }

void SecondTaskEventDispatch(MQTT_Event_t pEvent) { switch(pEvent->id) { case MQTT_EVENT_CONNECTED: mqttStatus = MQTT_STATUS_CONNECTED; Trace(1,"MQTT connected, now subscribe topic:%s",SUBSCRIBE_TOPIC); MQTT_Error_t err; MQTT_SetInPubCallback(pEvent->client, OnMqttReceived, OnMqttReceiedData, NULL); err = MQTT_Subscribe(pEvent->client,SUBSCRIBE_TOPIC,2,OnMqttSubscribed,(void)SUBSCRIBE_TOPIC); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe error, error code:%d",err); StartTimerPublish(PUBLISH_INTERVAL,pEvent->client); break; case MQTT_EVENT_DISCONNECTED: mqttStatus = MQTT_STATUS_DISCONNECTED; break; default: break; } }

void SecondTask(void pData) { MQTT_Event_t event=NULL; semMqttStart = OS_CreateSemaphore(0); OS_WaitForSemaphore(semMqttStart,OS_WAIT_FOREVER); OS_DeleteSemaphore(semMqttStart); Trace(1,"start mqtt test"); MQTT_Client_t* client = MQTT_ClientNew(); MQTT_Connect_Info_t ci; MQTT_Error_t err; memset(&ci,0,sizeof(MQTT_Connect_Info_t)); ci.client_id = CLIENT_ID; ci.client_user = CLIENT_USER; ci.client_pass = CLIENT_PASS; ci.keep_alive = 60; ci.clean_session = 1; ci.use_ssl = false;

err = MQTT_Connect(client,BROKER_IP,BROKER_PORT,OnMqttConnection,NULL,&ci);
if(err != MQTT_ERROR_NONE)
    Trace(1,"MQTT connect fail,error code:%d",err);

while(1)
{
    if(OS_WaitEvent(secondTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
    {
        SecondTaskEventDispatch(event);
        OS_Free(event);
    }
}

}

void MainTask(void pData) { API_Event_t event=NULL;

secondTaskHandle = OS_CreateTask(SecondTask,
    NULL, NULL, SECOND_TASK_STACK_SIZE, SECOND_TASK_PRIORITY, 0, 0, SECOND_TASK_NAME);

while(1)
{
    if(OS_WaitEvent(mainTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
    {
        EventDispatch(event);
        OS_Free(event->pParam1);
        OS_Free(event->pParam2);
        OS_Free(event);
    }
}

}

void mqtt_Main(void) { delay(5000); Trace(1,"mqtt_Main task started"); delay(5000); mainTaskHandle = OS_CreateTask(MainTask, NULL, NULL, MQTT_TASK_STACK_SIZE, MQTT_TASK_PRIORITY, 0, 0, MQTT_TASK_NAME); OS_SetUserMainHandle(&mainTaskHandle); gpsTaskHandle = OS_CreateTask(gps_MainTask, NULL, NULL, GPS_TASK_STACK_SIZE, GPS_TASK_PRIORITY, 0, 0, GPS_TAST_NAME); OS_SetUserMainHandle(&gpsTaskHandle); }

However the code is not working yet, the compiler gives an error

PS C:\GPRS_C_SDK> ./build.bat demo mqtt CSDTK PATH: C:\GPRS_C_SDK\CSDTK42 build folder exist number of processors: 4 Build host is WINDOWS

MAKE init

MAKE libs

MAKE libs/gps

MAKE libs/gps/minmea

PREPARING libgps_debug.a

MAKE libs/utils

PREPARING liblibs_debug.a

MAKE demo/mqtt CC demo_mqtt.c src/demo_mqtt.c: In function 'gps_testTask': src/demo_mqtt.c:232: warning: format '%f' expects type 'double', but argument 12 has type 'struct minmea_float' src/demo_mqtt.c: In function 'OnTimerPublish': src/demo_mqtt.c:342: error: incompatible types when assigning to type 'char[300]' from type 'char *' src/demo_mqtt.c:343: error: request for member 'member' in something not a structure or union src/demo_mqtt.c:343: error: request for member 'member' in something not a structure or union src/demo_mqtt.c: In function 'mqtt_Main': src/demo_mqtt.c:431: warning: implicit declaration of function 'delay' C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:958: recipe for target 'C:/GPRS_C_SDK/build/mqtt/demo/mqtt/obj/debug/de mo_mqtt.o' failed make[3]: [C:/GPRS_C_SDK/build/mqtt/demo/mqtt/obj/debug/demo_mqtt.o] Error 1 make[3]: Waiting for unfinished jobs.... C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:975: recipe for target 'dependencies' failed make[2]: [dependencies] Error 2 C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:718: recipe for target 'C:/GPRS_C_SDK/build/mqtt//mqtt.srec' failed make[1]: [C:/GPRS_C_SDK/build/mqtt//mqtt.srec] Error 2 C:/GPRS_C_SDK/platform/compilation/cust_rules.mk:371: recipe for target 'lod' failed make: *** [lod] Error 2 ROM total:1048576 Bytes used:2656 Bytes RAM total:1048576 Bytes used:32 Bytes === Build Time: 1s at 19.07.2018 17:30:22,72 ===


PS C:\GPRS_C_SDK>

somehow it seems that there is a problem converting char* to char[].

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/Ai-Thinker-Open/GPRS_C_SDK/issues/165#issuecomment-406321925, or mute the thread https://github.com/notifications/unsubscribe-auth/AkiMqiuiQWy4rz_MabyekMQa5NjQfvAVks5uIKiqgaJpZM4VQ67l .

futechiot commented 6 years ago

Hello,@neutree I already did this I'm able to send data to mosquitito server as well as to secure microsoft AZURE platform... Please don't close any issues if you can't help..!

😏🙄

Neutree commented 6 years ago

please close you ticket if you resolved your problem as you describe, and you can reopen it if not

ricardopera commented 5 years ago

This code is working, It sends gps data to demo.thingsboard.io.

`#include "string.h"

include "stdio.h"

include "api_os.h"

include "api_gps.h"

include "api_event.h"

include "api_hal_uart.h"

include "api_debug.h"

include "buffer.h"

include "gps_parse.h"

include "math.h"

include "gps.h"

include "stdbool.h"

include "stdint.h"

include "api_mqtt.h"

include "api_network.h"

include "api_socket.h"

define MAIN_TASK_STACK_SIZE (1024 * 2)

define MAIN_TASK_PRIORITY 0

define MAIN_TASK_NAME "Main Task"

define SECOND_TASK_STACK_SIZE (1024 * 2)

define SECOND_TASK_PRIORITY 1

define SECOND_TASK_NAME "Second Task"

define BROKER_IP "demo.thingsboard.io"

define BROKER_PORT 1883

define CLIENT_ID "A9G GPRS"

define CLIENT_USER "rieIPosjsTkdn6GbLFYs"

define CLIENT_PASS "mqtt"

define SUBSCRIBE_TOPIC "v1/devices/me/rpc/request/+"

define PUBLISH_TOPIC "v1/devices/me/telemetry"

define PUBLISH_INTERVAL 5000 //10s

define PUBLISH_PAYLOEAD "{\"temperature\":\"50\",\"humidity\":\"60\"}"

HANDLE mainTaskHandle = NULL; HANDLE secondTaskHandle = NULL;

//Variáveis MQTT static HANDLE semMqttStart = NULL; typedef enum{ MQTT_EVENT_CONNECTED = 0, MQTT_EVENT_DISCONNECTED , MQTT_EVENT_MAX }MQTT_Event_ID_t;

typedef struct { MQTT_Event_ID_t id; MQTT_Client_t* client; }MQTT_Event_t;

typedef enum{ MQTT_STATUS_DISCONNECTED = 0, MQTT_STATUS_CONNECTED , MQTT_STATUS_MAX }MQTT_Status_t;

MQTT_Status_t mqttStatus = MQTT_STATUS_DISCONNECTED;

// Variáveis GPS bool flag = false; bool isGpsOn = true;

void OnMqttReceived(void arg, const char topic, uint32_t payloadLen) { Trace(1,"MQTT received publish data request, topic:%s, payload length:%d",topic,payloadLen); }

void OnMqttReceiedData(void arg, const uint8_t data, uint16_t len, MQTT_Flags_t flags) { Trace(1,"MQTT recieved publish data, length:%d,data:%s",len,data); if(flags == MQTT_FLAG_DATA_LAST) Trace(1,"MQTT data is last frame"); }

void OnMqttSubscribed(void arg, MQTT_Error_t err) { if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe fail,error code:%d",err); else Trace(1,"MQTT subscribe success,topic:%s",(const char)arg); }

void OnMqttConnection(MQTT_Client_t client, void arg, MQTT_Connection_Status_t status) { Trace(1,"MQTT connection status:%d",status); MQTT_Event_t event = (MQTT_Event_t)OS_Malloc(sizeof(MQTT_Event_t)); if(!event) { Trace(1,"MQTT no memory"); return ; } if(status == MQTT_CONNECTION_ACCEPTED) { Trace(1,"MQTT succeed connect to broker"); //!!! DO NOT suscribe here(interrupt function), do MQTT suscribe in task, or it will not excute event->id = MQTT_EVENT_CONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); } else { event->id = MQTT_EVENT_DISCONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); Trace(1,"MQTT connect to broker fail,error code:%d",status); } Trace(1,"MQTT OnMqttConnection() end"); }

void StartTimerPublish(uint32_t interval,MQTT_Client_t client); void OnPublish(void arg, MQTT_Error_t err) { if(err == MQTT_ERROR_NONE) Trace(1,"MQTT publish success"); else Trace(1,"MQTT publish error, error code:%d",err); }

void OnTimerPublish(void param) { MQTT_Error_t err; MQTT_Client_t client = (MQTT_Client_t*)param; if(mqttStatus != MQTT_STATUS_CONNECTED) { Trace(1,"MQTT not connected to broker! can not publish"); return; }

GPS_Info_t* gpsInfo = Gps_GetInfo();
uint8_t buffer[300];
//show fix info
uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type;
char* isFixedStr;            
if(isFixed == 2)
    isFixedStr = "2D fix";
else if(isFixed == 3)
{
    if(gpsInfo->gga.fix_quality == 1)
        isFixedStr = "3D fix";
    else if(gpsInfo->gga.fix_quality == 2)
        isFixedStr = "3D/DGPS fix";
}
else
    isFixedStr = "no fix";

//convert unit ddmm.mmmm to degree(°) 
int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
double latitude = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
double longitude = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;

//you can copy ` latitude,longitude ` to http://www.gpsspg.com/maps.htm check location on map

//snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type,
//                                                  gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude);
//show in tracer
//Trace(2,buffer);
snprintf(buffer,sizeof(buffer),"{\"latitude\":\"%f\",\"longitude\":\"%f\"}",latitude,longitude);
Trace(2,buffer);
Trace(1,"MQTT OnTimerPublish");
err = MQTT_Publish(client,PUBLISH_TOPIC,buffer,strlen(buffer),1,2,0,OnPublish,NULL);
if(err != MQTT_ERROR_NONE)
    Trace(1,"MQTT publish error, error code:%d",err);
StartTimerPublish(PUBLISH_INTERVAL,client);

}

void StartTimerPublish(uint32_t interval,MQTT_Client_t client) { OS_StartCallbackTimer(mainTaskHandle,interval,OnTimerPublish,(void)client); }

void SecondTaskEventDispatch(MQTT_Event_t pEvent) { switch(pEvent->id) { case MQTT_EVENT_CONNECTED: mqttStatus = MQTT_STATUS_CONNECTED; Trace(1,"MQTT connected, now subscribe topic:%s",SUBSCRIBE_TOPIC); MQTT_Error_t err; MQTT_SetInPubCallback(pEvent->client, OnMqttReceived, OnMqttReceiedData, NULL); err = MQTT_Subscribe(pEvent->client,SUBSCRIBE_TOPIC,2,OnMqttSubscribed,(void)SUBSCRIBE_TOPIC); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe error, error code:%d",err); StartTimerPublish(PUBLISH_INTERVAL,pEvent->client); break; case MQTT_EVENT_DISCONNECTED: mqttStatus = MQTT_STATUS_DISCONNECTED; break; default: break; } }

void EventDispatch(API_Event_t* pEvent) { switch(pEvent->id) { case API_EVENT_ID_NETWORK_REGISTERED_HOME: case API_EVENT_ID_NETWORK_REGISTERED_ROAMING: Trace(1,"Network register complete"); Network_StartAttach(); flag = true; break;

    case API_EVENT_ID_GPS_UART_RECEIVED:
        Trace(1,"received GPS data,length:%d, data:%s,flag:%d",pEvent->param1,pEvent->pParam1,flag);
        GPS_Update(pEvent->pParam1,pEvent->param1);
        break;
    case API_EVENT_ID_UART_RECEIVED:
        if(pEvent->param1 == UART1)
        {
            uint8_t data[pEvent->param2+1];
            data[pEvent->param2] = 0;
            memcpy(data,pEvent->pParam1,pEvent->param2);
            Trace(1,"uart received data,length:%d,data:%s",pEvent->param2,data);
            if(strcmp(data,"close") == 0)
            {
                Trace(1,"close gps");
                GPS_Close();
                isGpsOn = false;
            }
            else if(strcmp(data,"open") == 0)
            {
                Trace(1,"open gps");
                GPS_Open(NULL);
                isGpsOn = true;
            }
        }
        break;

    case API_EVENT_ID_NO_SIMCARD:
        Trace(1,"!!NO SIM CARD%d!!!!",pEvent->param1);
        break;

    case API_EVENT_ID_SYSTEM_READY:
        Trace(1,"system initialize complete");
        break;

    case API_EVENT_ID_NETWORK_ATTACHED:
        Trace(1,"network attach success");
        Network_PDP_Context_t context = {
            .apn        ="cmnet",
            .userName   = ""    ,
            .userPasswd = ""
        };
        Network_StartActive(context);
        break;

    case API_EVENT_ID_NETWORK_ACTIVATED:
        Trace(1,"network activate success.."); 
        OS_ReleaseSemaphore(semMqttStart);
        break;

    case API_EVENT_ID_SOCKET_CONNECTED:
        Trace(1,"socket connected");
        break;

    case API_EVENT_ID_SOCKET_CLOSED:
        Trace(1,"socket closed");

        break;

    case API_EVENT_ID_SIGNAL_QUALITY:
        Trace(1,"CSQ:%d",pEvent->param1);
        break;
    default:
        break;
}

}

void LoopTask(VOID pData) { GPS_Info_t gpsInfo = Gps_GetInfo(); uint8_t buffer[300];

//wait for gprs register complete
//The process of GPRS registration network may cause the power supply voltage of GPS to drop,
//which resulting in GPS restart.
while(!flag)
{
    Trace(1,"wait for gprs regiter complete");
    OS_Sleep(2000);
}

//open GPS hardware(UART2 open either)
GPS_Init();
GPS_Open(NULL);

//wait for gps start up, or gps will not response command
while(gpsInfo->rmc.latitude.value == 0)
    OS_Sleep(1000);

// set gps nmea output interval
for(uint8_t i = 0;i<5;++i)
{
    bool ret = GPS_SetOutputInterval(10000);
    Trace(1,"set gps ret:%d",ret);
    if(ret)
        break;
    OS_Sleep(1000);
}

// if(!GPS_ClearInfoInFlash())
//     Trace(1,"erase gps fail");

// if(!GPS_SetQzssOutput(false))
//     Trace(1,"enable qzss nmea output fail");

// if(!GPS_SetSearchMode(true,false,true,false))
//     Trace(1,"set search mode fail");

// if(!GPS_SetSBASEnable(true))
//     Trace(1,"enable sbas fail");

if(!GPS_GetVersion(buffer,150))
    Trace(1,"get gps firmware version fail");
else
    Trace(1,"gps firmware version:%s",buffer);

// if(!GPS_SetFixMode(GPS_FIX_MODE_LOW_SPEED))
    // Trace(1,"set fix mode fail");

if(!GPS_SetOutputInterval(1000))
    Trace(1,"set nmea output interval fail");

Trace(1,"init ok");

MQTT_Event_t* event=NULL;
semMqttStart = OS_CreateSemaphore(0);
//OS_WaitForSemaphore(semMqttStart,OS_WAIT_FOREVER);
OS_DeleteSemaphore(semMqttStart);
Trace(1,"start mqtt test");
MQTT_Client_t* client = MQTT_ClientNew();
MQTT_Connect_Info_t ci;
MQTT_Error_t err;
memset(&ci,0,sizeof(MQTT_Connect_Info_t));
ci.client_id = CLIENT_ID;
ci.client_user = CLIENT_USER;
ci.client_pass = CLIENT_PASS;
ci.keep_alive = 60;
ci.clean_session = 1;
ci.use_ssl = false;

err = MQTT_Connect(client,BROKER_IP,BROKER_PORT,OnMqttConnection,NULL,&ci);
if(err != MQTT_ERROR_NONE)
    Trace(1,"MQTT connect fail,error code:%d",err);

while(1)
{
    if(isGpsOn)
    {
        //show fix info
        uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type;
        char* isFixedStr;            
        if(isFixed == 2)
            isFixedStr = "2D fix";
        else if(isFixed == 3)
        {
            if(gpsInfo->gga.fix_quality == 1)
                isFixedStr = "3D fix";
            else if(gpsInfo->gga.fix_quality == 2)
                isFixedStr = "3D/DGPS fix";
        }
        else
            isFixedStr = "no fix";

        //convert unit ddmm.mmmm to degree(°) 
        int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
        double latitude = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
        temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
        double longitude = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;

        //you can copy ` latitude,longitude ` to http://www.gpsspg.com/maps.htm check location on map

        snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type,
                                                            gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude);
        //show in tracer
        Trace(2,buffer);
    }

    if(OS_WaitEvent(secondTaskHandle, (void**)&event, OS_WAIT_FOREVER))
    {
        SecondTaskEventDispatch(event);
        OS_Free(event);
    }

    OS_Sleep(5000);
}

}

void AppMainTask(VOID pData) { API_Event_t event=NULL;

secondTaskHandle = OS_CreateTask(LoopTask ,
    NULL, NULL, SECOND_TASK_STACK_SIZE, SECOND_TASK_PRIORITY, 0, 0, SECOND_TASK_NAME);

while(1)
{
    if(OS_WaitEvent(mainTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER))
    {
        EventDispatch(event);
        OS_Free(event->pParam1);
        OS_Free(event->pParam2);
        OS_Free(event);
    }
}

} void app_Main(void) { mainTaskHandle = OS_CreateTask(AppMainTask , NULL, NULL, MAIN_TASK_STACK_SIZE, MAIN_TASK_PRIORITY, 0, 0, MAIN_TASK_NAME); OS_SetUserMainHandle(&mainTaskHandle); }`

CallaDai commented 5 years ago

I have a question. when I run this code, it reports me the error: I don't understand these errors. D:/GPRS_C_SDK_V2112/GPRS_C_SDK/build/testDai/init/lib\libinit_debug.a(sdk_init.o): In function user_Main': D:\GPRS_C_SDK_V2112\GPRS_C_SDK\init/src/sdk_init.c:30: undefined reference totestDai_Main' value:0, p:ffffffff88240018, addend:0, symbol:0 D:\GPRS_C_SDK_V2112\GPRS_C_SDK\init/src/sdk_init.c:30: relocation truncated to fit: R_MIPS16_26 against `testDai_Main' D:/GPRS_C_SDK_V2112/GPRS_C_SDK/platform/compilation/cust_rules.mk:722: recipe for target 'D:/GPRS_C_SDK_V2112/GPRS_C_SDK/build/testDai//testDai.elf' failed make[2]: [D:/nuvelos/GPRS_C_SDK_V2112/GPRS_C_SDK/build/testDai//testDai.elf] Error 1 D:/GPRS_C_SDK_V2112/GPRS_C_SDK/platform/compilation/cust_rules.mk:718: recipe for target 'D:/GPRS_C_SDK_V2112/GPRS_C_SDK/build/testDai//testDai.srec' failed make[1]: [D:/GPRS_C_SDK_V2112/GPRS_C_SDK/build/testDai//testDai.srec] Error 2 D:/GPRS_C_SDK_V2112/GPRS_C_SDK/platform/compilation/cust_rules.mk:371: recipe for target 'lod' failed make: *** [lod] Error 2

CRONOS-IOS commented 4 years ago

void StartTimerPublish (intervalo uint32_t, cliente MQTT_Client_t ) { OS_StartCallbackTimer (mainTaskHandle, intervalo, OnTimerPublish, (void ) cliente); }

void SecondTaskEventDispatch (MQTT_Event_t * pEvent) {

no compila el codigo....

mirekhk commented 3 years ago

This one will be compiled:-) `#include "string.h"

include "stdio.h"

include "api_os.h"

include "api_gps.h"

include "api_event.h"

include "api_hal_uart.h"

include "api_debug.h"

include "buffer.h"

include "gps_parse.h"

include "math.h"

include "gps.h"

include "stdbool.h"

include "stdint.h"

include "api_mqtt.h"

include "api_network.h"

include "api_socket.h"

define MAIN_TASK_STACK_SIZE (1024 * 2)

define MAIN_TASK_PRIORITY 0

define MAIN_TASK_NAME "Main Task"

define SECOND_TASK_STACK_SIZE (1024 * 2)

define SECOND_TASK_PRIORITY 1

define SECOND_TASK_NAME "Second Task"

define BROKER_IP "demo.thingsboard.io"

define BROKER_PORT 1883

define CLIENT_ID "A9G GPRS"

define CLIENT_USER "rieIPosjsTkdn6GbLFYs"

define CLIENT_PASS "mqtt"

define SUBSCRIBE_TOPIC "v1/devices/me/rpc/request/+"

define PUBLISH_TOPIC "v1/devices/me/telemetry"

define PUBLISH_INTERVAL 5000 //10s

define PUBLISH_PAYLOEAD "{"temperature":"50","humidity":"60"}"

HANDLE mainTaskHandle = NULL; HANDLE secondTaskHandle = NULL;

//Variáveis MQTT static HANDLE semMqttStart = NULL; typedef enum{ MQTT_EVENT_CONNECTED = 0, MQTT_EVENT_DISCONNECTED , MQTT_EVENT_MAX }MQTT_Event_ID_t;

typedef struct { MQTT_Event_ID_t id; MQTT_Client_t* client; }MQTT_Event_t;

typedef enum{ MQTT_STATUS_DISCONNECTED = 0, MQTT_STATUS_CONNECTED , MQTT_STATUS_MAX }MQTT_Status_t;

MQTT_Status_t mqttStatus = MQTT_STATUS_DISCONNECTED;

// Variáveis GPS bool flag = false; bool isGpsOn = true;

void OnMqttReceived(void arg, const char topic, uint32_t payloadLen) { Trace(1,"MQTT received publish data request, topic:%s, payload length:%d",topic,payloadLen); }

void OnMqttReceiedData(void arg, const uint8_t data, uint16_t len, MQTT_Flags_t flags) { Trace(1,"MQTT recieved publish data, length:%d,data:%s",len,data); if(flags == MQTT_FLAG_DATA_LAST) Trace(1,"MQTT data is last frame"); }

void OnMqttSubscribed(void arg, MQTT_Error_t err) { if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe fail,error code:%d",err); else Trace(1,"MQTT subscribe success,topic:%s",(const char)arg); }

void OnMqttConnection(MQTT_Client_t client, void arg, MQTT_Connection_Status_t status) { Trace(1,"MQTT connection status:%d",status); MQTT_Event_t event = (MQTT_Event_t)OS_Malloc(sizeof(MQTT_Event_t)); if(!event) { Trace(1,"MQTT no memory"); return ; } if(status == MQTT_CONNECTION_ACCEPTED) { Trace(1,"MQTT succeed connect to broker"); //!!! DO NOT suscribe here(interrupt function), do MQTT suscribe in task, or it will not excute event->id = MQTT_EVENT_CONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); } else { event->id = MQTT_EVENT_DISCONNECTED; event->client = client; OS_SendEvent(secondTaskHandle,event,OS_TIME_OUT_WAIT_FOREVER,OS_EVENT_PRI_NORMAL); Trace(1,"MQTT connect to broker fail,error code:%d",status); } Trace(1,"MQTT OnMqttConnection() end"); }

void StartTimerPublish(uint32_t interval,MQTT_Client_t client); void OnPublish(void arg, MQTT_Error_t err) { if(err == MQTT_ERROR_NONE) Trace(1,"MQTT publish success"); else Trace(1,"MQTT publish error, error code:%d",err); }

void OnTimerPublish(void param) { MQTT_Error_t err; MQTT_Client_t client = (MQTT_Client_t*)param; if(mqttStatus != MQTT_STATUS_CONNECTED) { Trace(1,"MQTT not connected to broker! can not publish"); return; }

GPS_Info_t gpsInfo = Gps_GetInfo(); uint8_t buffer[300]; //show fix info uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type; char isFixedStr;
if(isFixed == 2) isFixedStr = "2D fix"; else if(isFixed == 3) { if(gpsInfo->gga.fix_quality == 1) isFixedStr = "3D fix"; else if(gpsInfo->gga.fix_quality == 2) isFixedStr = "3D/DGPS fix"; } else isFixedStr = "no fix";

//convert unit ddmm.mmmm to degree(°) int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100); double latitude = temp+(double)(gpsInfo->rmc.latitude.value - tempgpsInfo->rmc.latitude.scale100)/gpsInfo->rmc.latitude.scale/60.0; temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100); double longitude = temp+(double)(gpsInfo->rmc.longitude.value - tempgpsInfo->rmc.longitude.scale100)/gpsInfo->rmc.longitude.scale/60.0;

//you can copy latitude,longitude to http://www.gpsspg.com/maps.htm check location on map

//snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type, // gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude); //show in tracer //Trace(2,buffer); snprintf(buffer,sizeof(buffer),"{\"latitude\":\"%f\",\"longitude\":\"%f\"}",latitude,longitude); Trace(2,buffer); Trace(1,"MQTT OnTimerPublish"); err = MQTT_Publish(client,PUBLISH_TOPIC,buffer,strlen(buffer),1,2,0,OnPublish,NULL); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT publish error, error code:%d",err); StartTimerPublish(PUBLISH_INTERVAL,client); }

void StartTimerPublish(uint32_t interval,MQTT_Client_t client) { OS_StartCallbackTimer(mainTaskHandle,interval,OnTimerPublish,(void)client); }

void SecondTaskEventDispatch(MQTT_Event_t pEvent) { switch(pEvent->id) { case MQTT_EVENT_CONNECTED: mqttStatus = MQTT_STATUS_CONNECTED; Trace(1,"MQTT connected, now subscribe topic:%s",SUBSCRIBE_TOPIC); MQTT_Error_t err; MQTT_SetInPubCallback(pEvent->client, OnMqttReceived, OnMqttReceiedData, NULL); err = MQTT_Subscribe(pEvent->client,SUBSCRIBE_TOPIC,2,OnMqttSubscribed,(void)SUBSCRIBE_TOPIC); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT subscribe error, error code:%d",err); StartTimerPublish(PUBLISH_INTERVAL,pEvent->client); break; case MQTT_EVENT_DISCONNECTED: mqttStatus = MQTT_STATUS_DISCONNECTED; break; default: break; } }

void EventDispatch(API_Event_t* pEvent) { switch(pEvent->id) { case API_EVENT_ID_NETWORK_REGISTERED_HOME: case API_EVENT_ID_NETWORK_REGISTERED_ROAMING: Trace(1,"Network register complete"); Network_StartAttach(); flag = true; break;

case API_EVENT_ID_GPS_UART_RECEIVED:
    Trace(1,"received GPS data,length:%d, data:%s,flag:%d",pEvent->param1,pEvent->pParam1,flag);
    GPS_Update(pEvent->pParam1,pEvent->param1);
    break;
case API_EVENT_ID_UART_RECEIVED:
    if(pEvent->param1 == UART1)
    {
        uint8_t data[pEvent->param2+1];
        data[pEvent->param2] = 0;
        memcpy(data,pEvent->pParam1,pEvent->param2);
        Trace(1,"uart received data,length:%d,data:%s",pEvent->param2,data);
        if(strcmp(data,"close") == 0)
        {
            Trace(1,"close gps");
            GPS_Close();
            isGpsOn = false;
        }
        else if(strcmp(data,"open") == 0)
        {
            Trace(1,"open gps");
            GPS_Open(NULL);
            isGpsOn = true;
        }
    }
    break;

case API_EVENT_ID_NO_SIMCARD:
    Trace(1,"!!NO SIM CARD%d!!!!",pEvent->param1);
    break;

case API_EVENT_ID_SYSTEM_READY:
    Trace(1,"system initialize complete");
    break;

case API_EVENT_ID_NETWORK_ATTACHED:
    Trace(1,"network attach success");
    Network_PDP_Context_t context = {
        .apn        ="cmnet",
        .userName   = ""    ,
        .userPasswd = ""
    };
    Network_StartActive(context);
    break;

case API_EVENT_ID_NETWORK_ACTIVATED:
    Trace(1,"network activate success.."); 
    OS_ReleaseSemaphore(semMqttStart);
    break;

case API_EVENT_ID_SOCKET_CONNECTED:
    Trace(1,"socket connected");
    break;

case API_EVENT_ID_SOCKET_CLOSED:
    Trace(1,"socket closed");

    break;

case API_EVENT_ID_SIGNAL_QUALITY:
    Trace(1,"CSQ:%d",pEvent->param1);
    break;
default:
    break;

} }

void LoopTask(void pData) { GPS_Info_t gpsInfo = Gps_GetInfo(); uint8_t buffer[300];

//wait for gprs register complete //The process of GPRS registration network may cause the power supply voltage of GPS to drop, //which resulting in GPS restart. while(!flag) { Trace(1,"wait for gprs regiter complete"); OS_Sleep(2000); }

//open GPS hardware(UART2 open either) GPS_Init(); GPS_Open(NULL);

//wait for gps start up, or gps will not response command while(gpsInfo->rmc.latitude.value == 0) OS_Sleep(1000);

// set gps nmea output interval for(uint8_t i = 0;i<5;++i) { bool ret = GPS_SetOutputInterval(10000); Trace(1,"set gps ret:%d",ret); if(ret) break; OS_Sleep(1000); }

// if(!GPS_ClearInfoInFlash()) // Trace(1,"erase gps fail");

// if(!GPS_SetQzssOutput(false)) // Trace(1,"enable qzss nmea output fail");

// if(!GPS_SetSearchMode(true,false,true,false)) // Trace(1,"set search mode fail");

// if(!GPS_SetSBASEnable(true)) // Trace(1,"enable sbas fail");

if(!GPS_GetVersion(buffer,150)) Trace(1,"get gps firmware version fail"); else Trace(1,"gps firmware version:%s",buffer);

// if(!GPS_SetFixMode(GPS_FIX_MODE_LOW_SPEED)) // Trace(1,"set fix mode fail");

if(!GPS_SetOutputInterval(1000)) Trace(1,"set nmea output interval fail");

Trace(1,"init ok");

MQTT_Event_t event=NULL; semMqttStart = OS_CreateSemaphore(0); //OS_WaitForSemaphore(semMqttStart,OS_WAIT_FOREVER); OS_DeleteSemaphore(semMqttStart); Trace(1,"start mqtt test"); MQTT_Client_t client = MQTT_ClientNew(); MQTT_Connect_Info_t ci; MQTT_Error_t err; memset(&ci,0,sizeof(MQTT_Connect_Info_t)); ci.client_id = CLIENT_ID; ci.client_user = CLIENT_USER; ci.client_pass = CLIENT_PASS; ci.keep_alive = 60; ci.clean_session = 1; ci.use_ssl = false;

err = MQTT_Connect(client,BROKER_IP,BROKER_PORT,OnMqttConnection,NULL,&ci); if(err != MQTT_ERROR_NONE) Trace(1,"MQTT connect fail,error code:%d",err);

while(1) { if(isGpsOn) { //show fix info uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type ?gpsInfo->gsa[0].fix_type:gpsInfo->gsa[1].fix_type; char* isFixedStr;
if(isFixed == 2) isFixedStr = "2D fix"; else if(isFixed == 3) { if(gpsInfo->gga.fix_quality == 1) isFixedStr = "3D fix"; else if(gpsInfo->gga.fix_quality == 2) isFixedStr = "3D/DGPS fix"; } else isFixedStr = "no fix";

    //convert unit ddmm.mmmm to degree(°) 
    int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
    double latitude = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
    temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
    double longitude = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;

    //you can copy ` latitude,longitude ` to http://www.gpsspg.com/maps.htm check location on map

    snprintf(buffer,sizeof(buffer),"GPS fix mode:%d, BDS fix mode:%d, fix quality:%d, satellites tracked:%d, gps sates total:%d, is fixed:%s, coordinate:WGS84, Latitude:%f, Longitude:%f, unit:degree,altitude:%f",gpsInfo->gsa[0].fix_type, gpsInfo->gsa[1].fix_type,
                                                        gpsInfo->gga.fix_quality,gpsInfo->gga.satellites_tracked, gpsInfo->gsv[0].total_sats, isFixedStr, latitude,longitude,gpsInfo->gga.altitude);
    //show in tracer
    Trace(2,buffer);
}

if(OS_WaitEvent(secondTaskHandle, (void**)&event, OS_WAIT_FOREVER))
{
    SecondTaskEventDispatch(event);
    OS_Free(event);
}

OS_Sleep(5000);

} }

void AppMainTask(void pData) { API_Event_t event=NULL;

secondTaskHandle = OS_CreateTask(LoopTask , NULL, NULL, SECOND_TASK_STACK_SIZE, SECOND_TASK_PRIORITY, 0, 0, SECOND_TASK_NAME);

while(1) { if(OS_WaitEvent(mainTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER)) { EventDispatch(event); OS_Free(event->pParam1); OS_Free(event->pParam2); OS_Free(event); } } } void app_Main(void) { mainTaskHandle = OS_CreateTask(AppMainTask , NULL, NULL, MAIN_TASK_STACK_SIZE, MAIN_TASK_PRIORITY, 0, 0, MAIN_TASK_NAME); OS_SetUserMainHandle(&mainTaskHandle); } `

This is compile result: `[LOD] D:/Documents/AiThinker/GPRS_C_SDK/hex/app/app_flash.lod [LODCOMBINE] Combine with Platform lod [LODCOMBINE] Combine sucessful


ROM total:1048576 Bytes used:17984 Bytes RAM total:1048576 Bytes used:5168 Bytes

Start Time : 16:11:52.42 End Time : 16:12:16.39 Build Time : 23.997s =================================================`

Thx a lot Riccardo, It explains a lot.

renatopspd commented 3 years ago

Iḿ trying to compile this codes with powershell, but it lists a lot of errors...How it can be compiled?