RaspberrPi project source code
guowenxue
2024-03-14 b3dc672c57aa5374fcd1ba1da5321d6c63d68e0f
commit | author | age
29b331 1 /*********************************************************************************
GW 2  *      Copyright:  (C) 2022 LingYun IoT System Studio
3  *                  All rights reserved.
4  *
5  *       Filename:  packet.c
6  *    Description:  This file is packet API functions
7  *
8  *        Version:  1.0.0(18/04/22)
9  *         Author:  Guo Wenxue <guowenxue@gmail.com>
10  *      ChangeLog:  1, Release initial version on "18/04/22 16:30:25"
11  *
12  ********************************************************************************/
13
14 #include <stdio.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <time.h>
18 #include "packet.h"
19 #include "logger.h"
20 #include "ds18b20.h"
21
22 int get_devid(char *devid, int size, int sn)
23 {
24     if( !devid || size<DEVID_LEN )
25     {
26         log_error("Invalid input arugments\n");
27         return -1;
28     }
29
30     memset(devid, 0, size);
31     snprintf(devid, size, "rpi#%04d", sn);
32     return 0;
33 }
34
35 int get_time(struct tm *ptm)
36 {
37     if( !ptm )
38     {
39         log_error("Invalid input arugments\n");
40         return -1;
41     }
42
43     time_t now = time(NULL);
44     localtime_r(&now, ptm);
45
46     return 0;
47 }
48
49 int packet_segmented_pack(pack_info_t *pack_info, char *pack_buf, int size)
50 {
51     char              strtime[TIME_LEN] = {'\0'};
52     struct tm        *ptm;
53
54     if( !pack_info || !pack_buf || size<=0 )
55     {
56         log_error("Invalid input arguments\n");
57         return -1;
58     }
59
60     ptm = &pack_info->sample_time;
bffa2b 61     snprintf(strtime, sizeof(strtime), "%04d-%02d-%02d %02d:%02d:%02d",
29b331 62             ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday,
GW 63             ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
64
65     memset(pack_buf, 0, size);
66     snprintf(pack_buf, size, "%s|%s|%.3f", pack_info->devid, strtime, pack_info->temper);
67
68     return strlen(pack_buf);
69 }
70
71 int packet_json_pack(pack_info_t *pack_info, char *pack_buf, int size)
72 {
73     char              strtime[TIME_LEN] = {'\0'};
74     struct tm        *ptm;
75
76     if( !pack_info || !pack_buf || size<=0 )
77     {
78         log_error("Invalid input arguments\n");
79         return -1;
80     }
81
82     ptm = &pack_info->sample_time;
83     snprintf(strtime, sizeof(strtime), "%04d-%02d-%2d %02d:%02d:%02d",
84             ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday,
85             ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
86
87     memset(pack_buf, 0, size);
88     snprintf(pack_buf, size, "{\"devid\":\"%s\", \"time\":\"%s\",\"temperature\":\"%.3f\"}",
89             pack_info->devid, strtime, pack_info->temper);
90
91     return strlen(pack_buf);
92 }
93