-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmb.c
74 lines (58 loc) · 1.96 KB
/
mb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @file mb.c
* @author Taka Wang
* @brief modbus common functions
*/
#include "mb.h"
extern int enable_syslog; // syslog flag
/* ==================================================
* public functions
================================================== */
char * set_modbus_success_resp_str_with_data (char *tid, cJSON *json_arr)
{
BEGIN (enable_syslog);
cJSON *resp_root;
resp_root = cJSON_CreateObject ();
cJSON_AddStringToObject (resp_root, "tid", tid);
if (json_arr != NULL)
{
cJSON_AddItemToObject (resp_root, "data", json_arr);
}
cJSON_AddStringToObject (resp_root, "status", "ok");
char * resp_json_str = cJSON_PrintUnformatted (resp_root);
LOG (enable_syslog, "resp: %s", resp_json_str);
// clean up
cJSON_Delete (resp_root);
return resp_json_str;
}
char * set_modbus_success_resp_str (char *tid)
{
return set_modbus_success_resp_str_with_data (tid, NULL);
}
char * set_modbus_fail_resp_str (char *tid, const char *reason)
{
BEGIN (enable_syslog);
ERR (enable_syslog, "Fail: %s", reason);
cJSON *resp_root;
resp_root = cJSON_CreateObject ();
cJSON_AddStringToObject (resp_root, "tid", tid);
cJSON_AddStringToObject (resp_root, "status", reason);
char * resp_json_string = cJSON_PrintUnformatted (resp_root);
LOG(enable_syslog, "resp: %s", resp_json_string);
// clean up
cJSON_Delete (resp_root);
return resp_json_string;
}
char * set_modbus_fail_resp_str_with_errno (char *tid, mbtcp_handle_s *handle, int errnum)
{
BEGIN (enable_syslog);
// [TODO][enhance] reconnect proactively?
// ... if the request interval is very large,
// we should try to reconnect automatically
if (errnum == 104) // Connection reset by peer (i.e, tcp connection timeout)
{
handle->connected = false;
}
ERR (enable_syslog, "%s:%d", modbus_strerror (errnum), errnum);
return set_modbus_fail_resp_str (tid, modbus_strerror (errnum));
}