Developer Center

C uses the TCP SDK to access the instance

1. Download the C version of the SDK

Download the C language version of the SDK from the Newland Cloud Platform, which currently provides Linux system operation examples. Place the code in the /home directory (or something else) in Ubuntu as follows:

2. Establish a TCP connection

Modify the IP address and port of the ECS in main.c as follows: #define SERVER_IP "120.77.58.34"
#define SERVER_PORT 8600
Note: Please make sure that your Ubuntu can be connected to the public network normally

3. The device is connected to the platform with a handshake

Use the documented "Device ID" and "Transfer Key". as a parameter, In the post_process function of main.c, modify the device identifier and transmission key, organize TCP handshake connection packets, and send them to the platform to establish a handshake connection with the .

                    
        /* Define the struct of the connection request according to the protocol */
        con_req.msg_type = PACKET_TYPE_CONN_REQ; 
        con_req.device_id = "qiuzhb";
        con_req.key= "677abb3a5ff3456fb831c96482f11536";
        con_req.ver = "V1.0";

        /* Use the packet_msg method in the cloud.h SDK to encapsulate the connection protocol */
        packet = packet_msg(&con_req);

        /*Send connection protocol packet data*/
        ret = send_packet(sock, packet, strlen(packet), 0);
                
            

If the handshake connection is successful, the cloud will send a response success message, and you will see an online flag in Device Management: If the handshake connection fails, the cloud will also send a response failure message to tell you the reason for the failure.

4.Add sensing and data reporting

Use the interface functions provided in the SDK to write code to report data to the platform. For example, upload a set of data with a temperature of 30°C and a humidity of 80%RH.

                    
        Data type is 1 (JSON format 1 string)
        post_req.msg_type = PACKET_TYPE_POST_DATA;
        post_req.msg_id++;
        post_req.data_type = 1;
        post_req.data = "{\
            \"nl_temperature\": \"23\",\
            \"nl_light\": 2000\
        }";
        post_req.data_len = strlen(post_req.data);
        packet = packet_msg(&post_req);
        if(packet == NULL){
            MAIN_ERR("packet_msg JSON 1 error\n");
        }else{
            MAIN_DBG("POST JSON 1 n");
            send_flag = 1;
        }

        /*Send packet data, report sensor data*/
        if(send_flag) {
            ret = send_packet(sock, packet, strlen(packet), 0);
            if(ret < 0){
                MAIN_ERR("PACKET_TYPE_POST_DATA error\n");
            }
            free_packet_msg(packet);
            send_flag = 0;
        }
                
            

5. Regenerate a new executable file

Enter "make clean" to clear the old executable file, and then enter "make" to regenerate the new executable file as follows: Enter "./main" to run the program, you can see that the program will automatically connect to the cloud platform, and the online icon will light up; The temperature and light sensor data were uploaded to the cloud platform, as follows: Click the on/off button of the fan to control the downlink as follows: At the same time, you can see the following output on the terminal in Ubuntu, that is, the downstream command successfully received:

                
        {
            "t":        6,
            "cmdid":    24061,
            "apitag":   "nl_fan",
            "data":     1
        }
                
            

Json/binary data transfer instance

1. Brief description

JSON is a lightweight data exchange format, binary is also a widely used number system in network communication, the platform supports these two formats of data reporting and command delivery, need to do the following conversion, the basic principle is In the TCP protocol or MQTT protocol, the reporting or delivery of data is based on the JSON format, and you want to include JSON objects or binary data in the JSON format protocol, and convert them into strings for transmission, roughly as follows:

2. Key code parsing

Taking the Ubuntu environment and the gateway developed in C language as the device access end, and the host computer application developed in C# as an example, the transmission of JSON is introduced.
1) Add the corresponding projects, devices, sensors, and actuators to the cloud platform, and the sensors and actuators are shown in the following figure:
2) Upload the key code of JSON and binary in C language

                 
    //////////////////////////////////////////////Data Reporting Format//////////////////////////////////////////////
    {
        "t": 3,
        "datatype": 1,
        "datas": 
        {
            "jsonsensor": "{\"UserName\":\"Li Si\",\"Age\":23,\"Sex\":1,\"IsMarry\":false}", //JSON serialized as a string
            "binarysensor": "AQIDBAU="                              //{ 0x01, 0x02, 0x03, 0x04, 0x05 }Base64-encoded string
        },
        "msgid": 123
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////

    //Send data to platform functions
    int send_data_to_cloud(void)
    {
        char jsonData[] = "{\"UserName\":\"Li Si\",\"Age\":23,\"Sex\":1,\"IsMarry\":false}";
        char binaryData[] = {0x02,0x04,0x06,0x08};
        int binlength = 4;

        int send_sock = tcpSend_fd_read();
        send_json_data(send_sock, 1, jsonData);
        sleep(5);

        send_binary_data(send_sock, 2, binaryData, binlength);
        sleep(5);

        return 0;
    }

    //Send a JSON data function
    int send_json_data(int sock,int msgid,char *jsonData)
    {
        int ret;
        char data[512] = {0};

        sprintf(data, "{\"t\":3,\"datatype\":1,\"msgid\":%d,\"datas\":{\"jsonsensor\":%s}}", msgid, jsonData);

        printf("/********************************** SEND JSON DATA **********************************/\r\n");
        printf("%s\r\n",data);
        printf("/********************************** ************** **********************************/\r\n\r\n");

        ret = send_packet(sock, data, strlen(data), 0);
        if(ret < 0){
            CLIENT_SEND_ERR("send packet to cloud fail\r\n");
            return -1;
        }

        return 0;
    }

    //Send binary data functions
    int send_binary_data(int sock,int msgid,char *binaryData, int binlength)
    {

        int ret;

        char data[512] = {0};
        char base64[256] = {0};

        ret = base64_encode(binaryData, base64, binlength);
        if(ret == BASE64FAIL)
        {
            printf("binary to base64 faill\r\n");
            return -1;
        }

        sprintf(data, "{\"t\":3,\"datatype\":1,\"msgid\":%d,\"datas\":{\"binarysensor\":\"%s\"}}", msgid, base64);

        printf("/********************************* SEND Binary DATA *********************************/\r\n");
        printf("%s\r\n",data);
        printf("/********************************** ************** **********************************/\r\n\r\n");

        ret = send_packet(sock, data, strlen(data), 0);
        if(ret < 0){
            CLIENT_SEND_ERR("send packet to cloud fail\r\n");
            return -1;
        }

        return 0;
    }
                
            

3) The cloud platform queries the uploaded data records
Go to Project -> Device Management -> Historical Sensing Data
4) The upper computer application obtains the key code of the data

                
    //Call the call to query the latest device data in batches
    ResultMsg<IEnumerable<DeviceSensorDataDTO>> qry = SDK.GetDevicesDatas(Cfg.deviceId.ToString(), Token);
    Console.WriteLine(lineNum + ". Query the latest data of the device in batches and return the following JSON:" + Environment.NewLine);
    Console.WriteLine(SerializeToJson(qry) + Environment.NewLine);
    lineNum++;

    if (qry.IsSuccess())
    {
        var dev = qry.ResultObj.FirstOrDefault();
        try
        {
            SensorDataDTO jsonSensor = dev.Datas.FirstOrDefault(item => { return item.ApiTag == Cfg.jsonApiTag; });
            if (jsonSensor != null && jsonSensor.Value != null && jsonSensor.Value.ToString() != "")
            {
                //Use JsonConvert to convert the JSON string transmitted by the device to an object
                Member user = new Member();
                user = JsonConvert.DeserializeObject<Member>(jsonSensor.Value.ToString());

                Console.WriteLine(lineNum + ". JSON sensor value: "+ Environment.NewLine);
                Console.WriteLine(String.Format("{0}/{1}/{2}/{3}"
                    , user.UserName
                    , user.Age
                    , user.Sex
                    , user.IsMarry) + Environment.NewLine); 
                lineNum++;
            }

            SensorDataDTO binarySensor = dev.Datas.FirstOrDefault(item => { return item.ApiTag == Cfg.binaryApiTag; });
            if (binarySensor != null && binarySensor.Value != null && binarySensor.Value.ToString() != "")
            {
                //Decode the Base64 string transmitted by the device into byte using Base64 []
                Byte[] ary = Convert.FromBase64String(binarySensor.Value.ToString());
                Console.WriteLine(lineNum + ". binary sensor value: "+ Environment.NewLine);
                Console.WriteLine(String.Format("{0}/{1}/{2}/{3}"
                    , ary[0]
                    , ary[1]
                    , ary[2]
                    , ary[3]) + Environment.NewLine);
                lineNum++;                                                                                  
            }
        }
        catch { }
    }
                
            

5) The host computer application issues JSON and binary key code

            
    //Send a command in JSON format
    Member user = new Member() { UserName = "Zhang San", Sex = 1, Age = Int32.Parse(CreateRandomNum(2)), IsMarry = false };
    String json = JsonConvert.SerializeObject(user); 
    var qry = SDK.Cmds(Cfg.deviceId, Cfg.jsonActuator, json, Token);
    Console.WriteLine(lineNum + ". send JSON format command to return JSON:" + Environment.NewLine);
    Console.WriteLine(SerializeToJson(qry) + Environment.NewLine);
    lineNum++;

    //Send a command in "binary format".
    byte[] ary = new Byte[] { 0x10, 0x09, 0x08, 0x07, 0x06 };
    String binary = Convert.ToBase64String(ary); 
    qry = SDK.Cmds(Cfg.deviceId, Cfg.binaryActuator, binary, Token);
    Console.WriteLine(lineNum + ". send binary format command returns JSON:" + Environment.NewLine);
    Console.WriteLine(SerializeToJson(qry) + Environment.NewLine);
    lineNum++;
            
            

6) Parse JSON and binary command key code
on the device side

                
    static void control_command_deal(void* msg_unpacket)
    {
        CMD_REQ* cmd_rcv = (CMD_REQ*)msg_unpacket;
        int is_cmd_need_rsp = 0;
        CMD_REQ_RSP* cmd_rsp = (CMD_REQ_RSP*)cmd_rcv;    //CMD_REQ struct is same with CMD_REQ_RSP struct

        CLIENT_RCV_DBG("recv CMD, data type:%d\n", cmd_rcv->data_type);
        switch(cmd_rcv->data_type){
            case CMD_DATA_TYPE_NUM:
                is_cmd_need_rsp = 1;
        
                CLIENT_RCV_DBG("1.unpacket, msg_type:%d, msg_id:%d apitag:%s, data:%d\n", 
                        cmd_rcv->msg_type, cmd_rcv->cmd_id, cmd_rcv->api_tag, *((int*)cmd_rcv->data));
                break;
            case CMD_DATA_TYPE_DOUBLE:
                is_cmd_need_rsp = 1;
                CLIENT_RCV_DBG("2.unpacket, msg_type:%d, msg_id:%d apitag:%s, data:%f\n", 
                        cmd_rcv->msg_type, cmd_rcv->cmd_id, cmd_rcv->api_tag, *((double*)cmd_rcv->data));
                break;
            case CMD_DATA_TYPE_STRING:
                is_cmd_need_rsp = 1;

                CLIENT_RCV_DBG("3.unpacket, msg_type:%d, msg_id:%d apitag:%s, data:%s\n", 
                        cmd_rcv->msg_type, cmd_rcv->cmd_id, cmd_rcv->api_tag, (char*)cmd_rcv->data);

                cJSON *msg_json = NULL;
                msg_json = cJSON_Parse((char*)cmd_rcv->data);
                if(msg_json != NULL)
                {
                    if(msg_json->type == cJSON_Object){
                        cJSON *name_json = NULL;
                        cJSON *age_json = NULL;
                        name_json = cJSON_GetObjectItem(msg_json, "UserName");
                        if(name_json && name_json->type != cJSON_String){
                            CLIENT_RCV_ERR("name_json ->type(%d) error\n", name_json ->type);
                            return NULL;
                        }

                        age_json = cJSON_GetObjectItem(msg_json, "Age");
                        if(age_json && age_json->type != cJSON_Number){
                            CLIENT_RCV_ERR("age_json ->type(%d) error\n", age_json ->type);
                            return NULL;
                        }
                        printf("/================ RCV Str DATA ================/\r\n");
                        printf("msg_type:%d\r\n",cmd_rcv->msg_type);
                        printf("msg_id  :%d\r\n",cmd_rcv->cmd_id);
                        printf("apitag  :%s\r\n",cmd_rcv->api_tag);
                        printf("UserName:%s\r\n",name_json->valuestring);
                        printf("Age     :%d\r\n",age_json->valueint);
                        printf("/================ ======== ================/\r\n\r\n");

                    }
                }
                else
                {
                    printf("/================ RCV Bin DATA ================/\r\n");
                    uint8_t bindata[256] = {0};
                    int len = base64_decode((char*)cmd_rcv->data, bindata);
                    printf("msg_type:%d\r\n",cmd_rcv->msg_type);
                    printf("msg_id  :%d\r\n",cmd_rcv->cmd_id);
                    printf("apitag  :%s\r\n",cmd_rcv->api_tag);
                    printf("apitag  :%s\r\n",cmd_rcv->data);
                    printf("changhex:");
                    print_hex(bindata,len);
                    printf("/================ ======== ================/\r\n\r\n");
                }
                
            
            
                CLIENT_RCV_DBG("3.unpacket, msg_type:%d, msg_id:%d apitag:%s, data:%s\n", 
                        cmd_rcv->msg_type, cmd_rcv->cmd_id, cmd_rcv->api_tag, (char*)cmd_rcv->data);
                break;
            case CMD_DATA_TYPE_JSON:
                is_cmd_need_rsp = 1;
                CLIENT_RCV_DBG("4.unpacket, msg_type:%d, msg_id:%d apitag:%s, data:%s\n", 
                        cmd_rcv->msg_type, cmd_rcv->cmd_id, cmd_rcv->api_tag, (char*)cmd_rcv->data);
                break;
            default:
                CLIENT_RCV_ERR("data_type(%d) error\n", cmd_rcv->data_type);
        }
        if(is_cmd_need_rsp){
            if(gataways_send_answer_to_cloud(cmd_rsp) == -1){
                CLIENT_RCV_ERR("gataways_send_answer_to_cloud fail");
            }
        }
    
    }
                
            

7) Download the source code of the case
click to download