Commit 44036e7a authored by chen.weican's avatar chen.weican
parents c7a249a9 a0816f3c
#include <stdio.h> #include <stdio.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdint.h> #include <stdint.h>
#include <fcntl.h> #include <fcntl.h>
#include <errno.h> #include <errno.h>
#include <unistd.h> #include <unistd.h>
#include "com_api.h" #include "com_api.h"
#define CCU_TCP_PORT 16565 #define CCU_TCP_PORT 16565
#define BUFFER_SIZE 1024 #define BUFFER_SIZE 1024
#define MAX_LISTEN_NUM 10 #define MAX_LISTEN_NUM 10
#define MAX_IP_LEN 16 #define MAX_IP_LEN 16
#define DEVICE_CODE_LEN 33 #define DEVICE_CODE_LEN 33
typedef struct{ typedef struct{
char deviceCode[DEVICE_CODE_LEN]; char deviceCode[DEVICE_CODE_LEN];
char ip[MAX_IP_LEN]; char ip[MAX_IP_LEN];
int sock; int sock;
int isConnect; int isConnect;
}kk_tcp_ctrl_t; }kk_tcp_ctrl_t;
static kk_tcp_ctrl_t g_tcp_ctrl[MAX_LISTEN_NUM]; static kk_tcp_ctrl_t g_tcp_ctrl[MAX_LISTEN_NUM];
static struct ev_loop *g_loop = NULL; static struct ev_loop *g_loop = NULL;
static pthread_t g_pTh = NULL; static pthread_t g_pTh = NULL;
static int g_init = 0; static int g_init = 0;
static ipc_cb* g_cb = NULL; static ipc_cb* g_cb = NULL;
static struct ev_io w_accept; static struct ev_io w_accept;
// Save/Load the gateway list // Save/Load the gateway list
void kk_gw_list_save(void) void kk_gw_list_save(void)
{ {
FILE *fp; FILE *fp;
uint8_t i; uint8_t i;
uint8_t j; uint8_t j;
int len = MAX_LISTEN_NUM * sizeof(kk_tcp_ctrl_t); int len = MAX_LISTEN_NUM * sizeof(kk_tcp_ctrl_t);
// Save device table // Save device table
fp = fopen("gwlist.txt", "w"); fp = fopen("gwlist.txt", "w");
fwrite(g_tcp_ctrl,len,1,fp); fwrite(g_tcp_ctrl,len,1,fp);
fclose(fp); fclose(fp);
} }
void kk_gw_list_load(void) void kk_gw_list_load(void)
{ {
uint16_t i; uint16_t i;
FILE *fp; FILE *fp;
int readLen = MAX_LISTEN_NUM * sizeof(kk_tcp_ctrl_t); int readLen = MAX_LISTEN_NUM * sizeof(kk_tcp_ctrl_t);
int retLen = 0; int retLen = 0;
fp = fopen("gwlist.txt", "r"); fp = fopen("gwlist.txt", "r");
if (!fp) { if (!fp) {
printf("open gatewaylist.txt failed! \n"); printf("open gatewaylist.txt failed! \n");
goto error1; goto error1;
} }
char buf[1024] = {0}; char buf[1024] = {0};
retLen = fread(g_tcp_ctrl, readLen, 1, fp); retLen = fread(g_tcp_ctrl, readLen, 1, fp);
printf("read gatewaylist.txt retLen= %d, readLen=%d ! \n", retLen,readLen); printf("read gatewaylist.txt retLen= %d, readLen=%d ! \n", retLen,readLen);
if (retLen != readLen ){ if (retLen != readLen ){
printf("read gatewaylist.txt failed! \n"); printf("read gatewaylist.txt failed! \n");
} }
fclose(fp); fclose(fp);
// Set the rest of the device table to null. // Set the rest of the device table to null.
error1: error1:
for (i=0; i < MAX_LISTEN_NUM; i++) { for (i=0; i < MAX_LISTEN_NUM; i++) {
printf("deviceCode ip sock [%s] [%s] [%d] \n",g_tcp_ctrl[i].deviceCode, printf("deviceCode ip sock [%s] [%s] [%d] \n",g_tcp_ctrl[i].deviceCode,
g_tcp_ctrl[i].ip==NULL?"":g_tcp_ctrl[i].ip, g_tcp_ctrl[i].sock); g_tcp_ctrl[i].ip==NULL?"":g_tcp_ctrl[i].ip, g_tcp_ctrl[i].sock);
g_tcp_ctrl[i].sock = -1; g_tcp_ctrl[i].sock = -1;
} }
} }
static int get_idx_by_ip(char ip[MAX_IP_LEN]){ static int get_idx_by_ip(char ip[MAX_IP_LEN]){
int i = 0; int i = 0;
if (ip == NULL || strlen(ip) == 0){ if (ip == NULL || strlen(ip) == 0){
return -1; return -1;
} }
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){ if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){
return i; return i;
} }
} }
return -1; return -1;
} }
static int get_sock_by_deviceCode(char deviceCode[DEVICE_CODE_LEN]){ static int get_sock_by_deviceCode(char deviceCode[DEVICE_CODE_LEN]){
int i = 0; int i = 0;
if (deviceCode == NULL || strlen(deviceCode) == 0){ if (deviceCode == NULL || strlen(deviceCode) == 0){
return -1; return -1;
} }
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(deviceCode, g_tcp_ctrl[i].deviceCode) == 0){ if(strcmp(deviceCode, g_tcp_ctrl[i].deviceCode) == 0){
return g_tcp_ctrl[i].sock; return g_tcp_ctrl[i].sock;
} }
} }
return -1; return -1;
} }
static kk_tcp_ctrl_t* get_channel_by_ip(char ip[MAX_IP_LEN]){ static kk_tcp_ctrl_t* get_channel_by_ip(char ip[MAX_IP_LEN]){
int i = 0; int i = 0;
if (ip == NULL || strlen(ip) == 0){ if (ip == NULL || strlen(ip) == 0){
return NULL; return NULL;
} }
printf("[%s] ip=%s \n", __FUNCTION__,ip); printf("[%s] ip=%s \n", __FUNCTION__,ip);
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){ if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){
printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, ip, g_tcp_ctrl[i].sock); printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, ip, g_tcp_ctrl[i].sock);
return &g_tcp_ctrl[i]; return &g_tcp_ctrl[i];
} }
} }
return NULL; return NULL;
} }
static int set_status_by_ip(char ip[MAX_IP_LEN], int status){ static int set_status_by_ip(char ip[MAX_IP_LEN], int status){
int i = 0; int i = 0;
if (ip == NULL || strlen(ip) == 0){ if (ip == NULL || strlen(ip) == 0){
return -1; return -1;
} }
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){ if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){
g_tcp_ctrl[i].isConnect = status; g_tcp_ctrl[i].isConnect = status;
return 0; return 0;
} }
} }
return -1; return -1;
} }
static int reset_by_sock(int sock){ static int reset_by_sock(int sock){
int i = 0; int i = 0;
if (sock < 0){ if (sock < 0){
return -1; return -1;
} }
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(sock == g_tcp_ctrl[i].sock){ if(sock == g_tcp_ctrl[i].sock){
g_tcp_ctrl[i].isConnect = 0; g_tcp_ctrl[i].isConnect = 0;
g_tcp_ctrl[i].isConnect = -1; g_tcp_ctrl[i].isConnect = -1;
return 0; return 0;
} }
} }
return -1; return -1;
} }
static int set_sock_by_ip(char ip[MAX_IP_LEN], int sock){ static int set_sock_by_ip(char ip[MAX_IP_LEN], int sock){
int i = 0; int i = 0;
if (ip == NULL || strlen(ip) == 0){ if (ip == NULL || strlen(ip) == 0){
return -1; return -1;
} }
printf("[%s] ip=%s \n", __FUNCTION__,ip); printf("[%s] ip=%s \n", __FUNCTION__,ip);
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){ if(strcmp(ip, g_tcp_ctrl[i].ip) == 0){
g_tcp_ctrl[i].sock = sock; g_tcp_ctrl[i].sock = sock;
printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, ip, g_tcp_ctrl[i].sock); printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, ip, g_tcp_ctrl[i].sock);
return 0; return 0;
} }
} }
return -1; return -1;
} }
int kk_is_tcp_channel(char devCode[DEVICE_CODE_LEN]){ int kk_is_tcp_channel(char devCode[DEVICE_CODE_LEN]){
int i = 0; int i = 0;
if (devCode == NULL || strlen(devCode) == 0){ if (devCode == NULL || strlen(devCode) == 0){
return -1; return -1;
} }
//printf("[%s] devCode=%s \n", __FUNCTION__,devCode); //printf("[%s] devCode=%s \n", __FUNCTION__,devCode);
for(;i < MAX_LISTEN_NUM; i++){ for(;i < MAX_LISTEN_NUM; i++){
if(strcmp(devCode, g_tcp_ctrl[i].deviceCode) == 0){ if(strcmp(devCode, g_tcp_ctrl[i].deviceCode) == 0){
printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, devCode, g_tcp_ctrl[i].sock); printf("[%s] idx=%d ip=%s sock=%d\n", __FUNCTION__,i, devCode, g_tcp_ctrl[i].sock);
return i; return i;
} }
} }
return -1; return -1;
} }
int kk_set_tcp_channel(char devCode[DEVICE_CODE_LEN], char ip[MAX_IP_LEN]){ int kk_set_tcp_channel_by_idx(int idx, char devCode[DEVICE_CODE_LEN], char ip[MAX_IP_LEN]){
int i = 0;
int isEmptyIdx = -1; int i = 0;
if (devCode == NULL || strlen(devCode) == 0 || ip == NULL || strlen(ip) == 0){ if(idx >= MAX_LISTEN_NUM){
printf("paramenter error \n"); printf("kk_set_tcp_channel_by_idx idx[] need less than %d \n", idx, MAX_LISTEN_NUM);
return -1; return - 1;
} }
for(;i < MAX_LISTEN_NUM; i++){ if (devCode == NULL || strlen(devCode) == 0 || ip == NULL || strlen(ip) == 0){
return -1;
if(strcmp(devCode, g_tcp_ctrl[i].deviceCode) == 0){ }
strncpy(g_tcp_ctrl[i].ip, ip, strlen(ip)); //printf("[%s] devCode=%s \n", __FUNCTION__,devCode);
printf("find and replace it [%d][%s][%s] \n",i, g_tcp_ctrl[i].ip, devCode); memcpy(g_tcp_ctrl[idx].deviceCode, devCode, strlen(devCode));
kk_gw_list_save(); memcpy(g_tcp_ctrl[idx].ip, ip, strlen(ip));
break;
} return 0;
}
if (strlen(g_tcp_ctrl[i].deviceCode) == 0 && isEmptyIdx == -1){
isEmptyIdx = i;
} int kk_set_tcp_channel(char devCode[DEVICE_CODE_LEN], char ip[MAX_IP_LEN]){
} int i = 0;
int isEmptyIdx = -1;
if (i < MAX_LISTEN_NUM){
return 0; if (devCode == NULL || strlen(devCode) == 0 || ip == NULL || strlen(ip) == 0){
} printf("paramenter error \n");
return -1;
if (isEmptyIdx != -1){ }
strncpy(g_tcp_ctrl[isEmptyIdx].ip, ip, strlen(ip)); for(;i < MAX_LISTEN_NUM; i++){
strncpy(g_tcp_ctrl[isEmptyIdx].deviceCode, devCode, strlen(devCode));
printf("idx deviceCode ip[%d][%s][%s]",isEmptyIdx, g_tcp_ctrl[isEmptyIdx].deviceCode, g_tcp_ctrl[isEmptyIdx].ip); if(strcmp(devCode, g_tcp_ctrl[i].deviceCode) == 0){
kk_gw_list_save(); strncpy(g_tcp_ctrl[i].ip, ip, strlen(ip));
return 0; printf("find and replace it [%d][%s][%s] \n",i, g_tcp_ctrl[i].ip, devCode);
} //kk_gw_list_save();
break;
return -1; }
} if (strlen(g_tcp_ctrl[i].deviceCode) == 0 && isEmptyIdx == -1){
isEmptyIdx = i;
}
}
/*初始化服务端*/ if (i < MAX_LISTEN_NUM){
static int server_socket_init(int *sd, char *ipaddr, uint16_t port) return 0;
{ }
//创建socket
int sock = socket(AF_INET, SOCK_STREAM, 0); if (isEmptyIdx != -1){
if (-1 == sock){
printf("error socket \n"); strncpy(g_tcp_ctrl[isEmptyIdx].ip, ip, strlen(ip));
goto err1; strncpy(g_tcp_ctrl[isEmptyIdx].deviceCode, devCode, strlen(devCode));
} printf("idx deviceCode ip[%d][%s][%s]",isEmptyIdx, g_tcp_ctrl[isEmptyIdx].deviceCode, g_tcp_ctrl[isEmptyIdx].ip);
//设置立即释放端口并可以再次使用 //kk_gw_list_save();
int reuse = 1; return 0;
if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))){ }
printf("error setsockopt \n");
goto err2; return -1;
}
//设置为非阻塞 }
if (-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)){
printf("================== fcntl \n");
goto err2;
}
struct sockaddr_in addr; /*初始化服务端*/
memset(&addr, 0 , sizeof(addr)); static int server_socket_init(int *sd, char *ipaddr, uint16_t port)
addr.sin_family = AF_INET; {
addr.sin_port = htons(port); //创建socket
if (NULL == ipaddr) { int sock = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_addr.s_addr = htonl(INADDR_ANY); if (-1 == sock){
} else { printf("error socket \n");
addr.sin_addr.s_addr = inet_addr(ipaddr); goto err1;
} }
//绑定监听 //设置立即释放端口并可以再次使用
if (-1 == bind(sock, (struct sockaddr *)&addr, sizeof(addr))){ int reuse = 1;
printf("error bind \n"); if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))){
goto err2; printf("error setsockopt \n");
} goto err2;
if (-1 == listen(sock, MAX_LISTEN_NUM)){ }
printf("error listen \n"); //设置为非阻塞
goto err2; if (-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)){
} printf("================== fcntl \n");
*sd = sock; goto err2;
return 0; }
err2: struct sockaddr_in addr;
close(sock); memset(&addr, 0 , sizeof(addr));
err1: addr.sin_family = AF_INET;
return -1; addr.sin_port = htons(port);
} if (NULL == ipaddr) {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
/*读回调*/ } else {
static void read_cb(struct ev_loop *loop, struct ev_io *watcher, int revents) addr.sin_addr.s_addr = inet_addr(ipaddr);
{ }
printf("================== read_cb \n"); //绑定监听
char buffer[BUFFER_SIZE] = {0}; if (-1 == bind(sock, (struct sockaddr *)&addr, sizeof(addr))){
if (EV_ERROR & revents) { printf("error bind \n");
printf("read got invalid event...\r\n"); goto err2;
return; }
} if (-1 == listen(sock, MAX_LISTEN_NUM)){
int res = 0; printf("error listen \n");
kk_tcp_ctrl_t* tcp_ctrl = (kk_tcp_ctrl_t*)watcher->data; goto err2;
int32_t bytes = read(watcher->fd, buffer, sizeof(buffer)); }
if (-1 == bytes) { *sd = sock;
//tcp Error return 0;
if (EINTR != errno && EAGAIN != errno) { err2:
res = 1; close(sock);
} err1:
} else if (0 == bytes) { return -1;
//tcp Close }
res = 2;
} /*读回调*/
if (0 != res) { static void read_cb(struct ev_loop *loop, struct ev_io *watcher, int revents)
//关闭事件循环并释放watcher {
printf("TCP CLOSE\r\n"); printf("================== read_cb \n");
reset_by_sock(watcher->fd); char buffer[BUFFER_SIZE] = {0};
ev_io_stop(loop,watcher); if (EV_ERROR & revents) {
free(watcher); printf("read got invalid event...\r\n");
} else { return;
//intf("READ:\r\n %s\r\n", buffer); }
printf("read_cb deviceCode ip sock [%s][%s][%d]",tcp_ctrl->deviceCode,tcp_ctrl->ip, tcp_ctrl->sock); int res = 0;
if (g_cb != NULL){ kk_tcp_ctrl_t* tcp_ctrl = (kk_tcp_ctrl_t*)watcher->data;
g_cb(buffer,bytes,tcp_ctrl->deviceCode); int32_t bytes = read(watcher->fd, buffer, sizeof(buffer));
} if (-1 == bytes) {
} //tcp Error
} if (EINTR != errno && EAGAIN != errno) {
res = 1;
}
/*accept回调函数*/ } else if (0 == bytes) {
static void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents) //tcp Close
{ res = 2;
printf("================== accept_cb \n"); }
struct sockaddr_in client_addr; if (0 != res) {
socklen_t client_len = sizeof(client_addr); //关闭事件循环并释放watcher
if (EV_ERROR & revents) { printf("TCP CLOSE\r\n");
printf("accept got invalid event...\r\n"); reset_by_sock(watcher->fd);
return; ev_io_stop(loop,watcher);
} free(watcher);
//accept连接 } else {
int sock = accept(watcher->fd, (struct sockaddr *)&client_addr, &client_len); //intf("READ:\r\n %s\r\n", buffer);
if (-1 == sock) { printf("read_cb deviceCode ip sock [%s][%s][%d]",tcp_ctrl->deviceCode,tcp_ctrl->ip, tcp_ctrl->sock);
return; if (g_cb != NULL){
} g_cb(buffer,bytes,tcp_ctrl->deviceCode);
//设置非阻塞 }
if(-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)) { }
close(sock); }
return;
}
/*accept回调函数*/
if(set_sock_by_ip(inet_ntoa(client_addr.sin_addr),sock) < 0){ static void accept_cb(struct ev_loop *loop, struct ev_io *watcher, int revents)
//ip无效,reject it {
printf("This ip[%s][%u] is invaild, reject it! \r\n", inet_ntoa(client_addr.sin_addr), client_addr.sin_port); printf("================== accept_cb \n");
close(sock); struct sockaddr_in client_addr;
return; socklen_t client_len = sizeof(client_addr);
} if (EV_ERROR & revents) {
printf("Successfully connected with client: %s:%u\r\n", \ printf("accept got invalid event...\r\n");
inet_ntoa(client_addr.sin_addr), client_addr.sin_port); return;
}
//加入事件循环 //accept连接
struct ev_io *w_client = (struct ev_io*) malloc (sizeof(struct ev_io)); int sock = accept(watcher->fd, (struct sockaddr *)&client_addr, &client_len);
if (w_client == NULL){ if (-1 == sock) {
printf("malloc w_client failed \r\n"); return;
return; }
} //设置非阻塞
if(-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)) {
w_client->data = get_channel_by_ip(inet_ntoa(client_addr.sin_addr)); close(sock);
ev_io_init(w_client, read_cb, sock, EV_READ); return;
ev_io_start(loop, w_client); }
}
if(set_sock_by_ip(inet_ntoa(client_addr.sin_addr),sock) < 0){
//ip无效,reject it
printf("This ip[%s][%u] is invaild, reject it! \r\n", inet_ntoa(client_addr.sin_addr), client_addr.sin_port);
close(sock);
/*int run() return;
{ }
int sd; printf("Successfully connected with client: %s:%u\r\n", \
struct ev_io w_accept; inet_ntoa(client_addr.sin_addr), client_addr.sin_port);
g_loop = ev_loop_new(EVBACKEND_EPOLL);
if (NULL == g_loop) { //加入事件循环
printf("loop create failed\r\n"); struct ev_io *w_client = (struct ev_io*) malloc (sizeof(struct ev_io));
return -1; if (w_client == NULL){
} printf("malloc w_client failed \r\n");
if (server_socket_init(&sd, NULL, CCU_TCP_PORT) < 0) { return;
printf("server init failed\r\n"); }
return -1;
} w_client->data = get_channel_by_ip(inet_ntoa(client_addr.sin_addr));
ev_io_init(&w_accept, accept_cb, sd, EV_READ); ev_io_init(w_client, read_cb, sock, EV_READ);
ev_io_start(g_loop, &w_accept); ev_io_start(loop, w_client);
ev_run(g_loop, 0); }
return 0;
}*/
static void loop_tcp_thread(void *arg){
printf("loop_tcp_thread start!\r\n"); /*int run()
int sd; {
int sd;
g_loop = ev_loop_new(EVBACKEND_EPOLL); struct ev_io w_accept;
if (NULL == g_loop) { g_loop = ev_loop_new(EVBACKEND_EPOLL);
printf("loop create failed\r\n"); if (NULL == g_loop) {
return -1; printf("loop create failed\r\n");
} return -1;
if (server_socket_init(&sd, NULL, CCU_TCP_PORT) < 0) { }
printf("server init failed\r\n"); if (server_socket_init(&sd, NULL, CCU_TCP_PORT) < 0) {
return -1; printf("server init failed\r\n");
} return -1;
ev_io_init(&w_accept, accept_cb, sd, EV_READ); }
ev_io_start(g_loop, &w_accept); ev_io_init(&w_accept, accept_cb, sd, EV_READ);
ev_run (g_loop, 0); ev_io_start(g_loop, &w_accept);
close(sd); ev_run(g_loop, 0);
printf("loop_tcp_thread================== end \n"); return 0;
}*/
}
static void loop_tcp_thread(void *arg){
printf("loop_tcp_thread start!\r\n");
int kk_tcp_channel_ser_send(char* data, int len, char chalMark[DEVICE_CODE_LEN]){ int sd;
int ret = 0;
if (data != NULL){ g_loop = ev_loop_new(EVBACKEND_EPOLL);
int sd = get_sock_by_deviceCode(chalMark); if (NULL == g_loop) {
if (sd > -1){ printf("loop create failed\r\n");
ret = write(sd, data, len); return -1;
if (ret < 0){ }
printf("[%s] write failed!!!! \n",__FUNCTION__); if (server_socket_init(&sd, NULL, CCU_TCP_PORT) < 0) {
} printf("server init failed\r\n");
} return -1;
}
} ev_io_init(&w_accept, accept_cb, sd, EV_READ);
} ev_io_start(g_loop, &w_accept);
ev_run (g_loop, 0);
close(sd);
int kk_TCP_channel_init(ipc_cb cb) printf("loop_tcp_thread================== end \n");
{
int i = 0; }
int sd;
if (g_init == 1){ int kk_tcp_channel_ser_send(char* data, int len, char chalMark[DEVICE_CODE_LEN]){
printf("kk_TCP_channel_init has been inited \n"); int ret = 0;
return -1; if (data != NULL){
} int sd = get_sock_by_deviceCode(chalMark);
g_init = 1; if (sd > -1){
memset(g_tcp_ctrl, 0, sizeof(kk_tcp_ctrl_t)*MAX_LISTEN_NUM); ret = write(sd, data, len);
kk_gw_list_load(); if (ret < 0){
printf("[%s] write failed!!!! \n",__FUNCTION__);
}
if (g_pTh ==NULL && 0 != pthread_create(&g_pTh, NULL, loop_tcp_thread, NULL)) { }
printf("create pthread failed\r\n");
return -1; }
}; }
g_cb = cb;
return 0; int kk_TCP_channel_init(ipc_cb cb)
{
int i = 0;
} int sd;
if (g_init == 1){
int kk_TCP_channel_deinit(ipc_type type) printf("kk_TCP_channel_init has been inited \n");
{ return -1;
int i = 0; }
g_init = 1;
for(i = 0; i < MAX_LISTEN_NUM; i++){ //memset(g_tcp_ctrl, 0, sizeof(kk_tcp_ctrl_t)*MAX_LISTEN_NUM);
if(g_tcp_ctrl[i].sock > -1){ //kk_gw_list_load();
//close(g_tcp_ctrl[i].sock); for(i = 0; i < MAX_LISTEN_NUM; i++){
} g_tcp_ctrl[i].sock = -1;
} }
ev_io_stop(g_loop, &w_accept); if (g_pTh ==NULL && 0 != pthread_create(&g_pTh, NULL, loop_tcp_thread, NULL)) {
ev_break(g_loop,EVBREAK_ALL); printf("create pthread failed\r\n");
pthread_exit(g_pTh); return -1;
ev_loop_destroy(g_loop); };
g_loop = NULL; g_cb = cb;
g_pTh = NULL;
g_init = 0; return 0;
return 0; }
}
int kk_TCP_channel_deinit(ipc_type type)
{
int i = 0;
void *_MutexCreate(void)
{ for(i = 0; i < MAX_LISTEN_NUM; i++){
int err_num; if(g_tcp_ctrl[i].sock > -1){
pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); //close(g_tcp_ctrl[i].sock);
if (NULL == mutex) { }
return NULL; }
}
ev_io_stop(g_loop, &w_accept);
if (0 != (err_num = pthread_mutex_init(mutex, NULL))) { ev_break(g_loop,EVBREAK_ALL);
printf("create mutex failed"); pthread_exit(g_pTh);
free(mutex); ev_loop_destroy(g_loop);
return NULL; g_loop = NULL;
} g_pTh = NULL;
g_init = 0;
return mutex;
}
return 0;
void _MutexDestroy(void *mutex)
{ }
int err_num;
if (!mutex) {
printf("mutex want to destroy is NULL!"); void *_MutexCreate(void)
return; {
} int err_num;
if (0 != (err_num = pthread_mutex_destroy((pthread_mutex_t *)mutex))) { pthread_mutex_t *mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
printf("destroy mutex failed"); if (NULL == mutex) {
} return NULL;
}
free(mutex);
} if (0 != (err_num = pthread_mutex_init(mutex, NULL))) {
printf("create mutex failed");
void _MutexLock(void *mutex) free(mutex);
{ return NULL;
int err_num; }
if (0 != (err_num = pthread_mutex_lock((pthread_mutex_t *)mutex))) {
printf("lock mutex failed: - '%s' (%d)", strerror(err_num), err_num); return mutex;
} }
}
void _MutexDestroy(void *mutex)
void _MutexUnlock(void *mutex) {
{ int err_num;
int err_num;
if (0 != (err_num = pthread_mutex_unlock((pthread_mutex_t *)mutex))) { if (!mutex) {
printf("unlock mutex failed - '%s' (%d)", strerror(err_num), err_num); printf("mutex want to destroy is NULL!");
} return;
} }
if (0 != (err_num = pthread_mutex_destroy((pthread_mutex_t *)mutex))) {
printf("destroy mutex failed");
//client }
/*初始化服务端*/
typedef struct { free(mutex);
void *mutex; }
int sd;
int isConnect; void _MutexLock(void *mutex)
char ip[MAX_IP_LEN]; {
int port; int err_num;
ipc_cb* cb; if (0 != (err_num = pthread_mutex_lock((pthread_mutex_t *)mutex))) {
} kk_tcp_client_t; printf("lock mutex failed: - '%s' (%d)", strerror(err_num), err_num);
}
static kk_tcp_client_t g_client_ctrl = {NULL, -1, 0,{0},0, NULL}; }
static int _init_client(){ void _MutexUnlock(void *mutex)
memset(&g_client_ctrl, 0 ,sizeof(kk_tcp_client_t)); {
/* Create Mutex */ int err_num;
if (0 != (err_num = pthread_mutex_unlock((pthread_mutex_t *)mutex))) {
g_client_ctrl.mutex = _MutexCreate(); printf("unlock mutex failed - '%s' (%d)", strerror(err_num), err_num);
if (g_client_ctrl.mutex == NULL) { }
return -1; }
}
g_client_ctrl.sd = -1;
//client
} /*初始化服务端*/
typedef struct {
void *mutex;
static int client_socket_init(int *sd, char *ipaddr, uint16_t port) int sd;
{ int isConnect;
//创建socket char ip[MAX_IP_LEN];
int sock = socket(AF_INET, SOCK_STREAM, 0); int port;
if (-1 == sock){ ipc_cb* cb;
printf("error socket \n"); } kk_tcp_client_t;
goto err1;
} static kk_tcp_client_t g_client_ctrl = {NULL, -1, 0,{0},0, NULL};
//设置立即释放端口并可以再次使用
int reuse = 1; static int _init_client(){
if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))){ memset(&g_client_ctrl, 0 ,sizeof(kk_tcp_client_t));
printf("error setsockopt \n"); /* Create Mutex */
goto err2;
} g_client_ctrl.mutex = _MutexCreate();
//设置为非阻塞 if (g_client_ctrl.mutex == NULL) {
if (-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)){ return -1;
printf("================== fcntl \n"); }
goto err2; g_client_ctrl.sd = -1;
}
struct sockaddr_in addr; }
memset(&addr, 0 , sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port); static int client_socket_init(int *sd, char *ipaddr, uint16_t port)
if (NULL == ipaddr) { {
addr.sin_addr.s_addr = htonl(INADDR_ANY); //创建socket
} else { int sock = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_addr.s_addr = inet_addr(ipaddr); if (-1 == sock){
} printf("error socket \n");
//连接 goto err1;
int retry = 0; }
for(;retry < 10; retry++){ //设置立即释放端口并可以再次使用
if(-1 != connect(sock, (struct sockaddr *)&addr, sizeof(addr))){ int reuse = 1;
break; if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))){
} printf("error setsockopt \n");
printf("==================connect retry=%d \n", retry); goto err2;
sleep(1); }
} //设置为非阻塞
if (retry >= 10){ if (-1 == fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK)){
printf("==================connect failed \n"); printf("================== fcntl \n");
goto err2; goto err2;
} }
struct sockaddr_in addr;
printf("==================[%s] ok sock=%d \n", __FUNCTION__, sock); memset(&addr, 0 , sizeof(addr));
*sd = sock; addr.sin_family = AF_INET;
return 0; addr.sin_port = htons(port);
err2: if (NULL == ipaddr) {
close(sock); addr.sin_addr.s_addr = htonl(INADDR_ANY);
err1: } else {
return -1; addr.sin_addr.s_addr = inet_addr(ipaddr);
} }
//连接
static void loop_tcp_client_thread(void *arg){ int retry = 0;
printf("loop_tcp_client_thread start!\r\n"); for(;retry < 10; retry++){
char buf[1024]= {0}; if(-1 != connect(sock, (struct sockaddr *)&addr, sizeof(addr))){
int ret = 0; break;
while(1){ }
if(-1 == client_socket_init(&g_client_ctrl.sd,g_client_ctrl.ip, g_client_ctrl.port)){ printf("==================connect retry=%d \n", retry);
printf("connect failed \n"); sleep(1);
sleep(1); }
continue; if (retry >= 10){
} printf("==================connect failed \n");
g_client_ctrl.isConnect = 1; goto err2;
while(g_client_ctrl.isConnect){ }
_MutexLock(g_client_ctrl.mutex);
ret = read(g_client_ctrl.sd, buf, sizeof(buf)); printf("==================[%s] ok sock=%d \n", __FUNCTION__, sock);
_MutexUnlock(g_client_ctrl.mutex); *sd = sock;
if(-1== ret){ return 0;
//printf("=================read error \n"); err2:
//break ; close(sock);
}else if(ret > 0){ err1:
printf("buf = %s\n",buf); return -1;
if (g_client_ctrl.cb != NULL){ }
g_client_ctrl.cb(buf,ret,"");
} static void loop_tcp_client_thread(void *arg){
} printf("loop_tcp_client_thread start!\r\n");
char buf[1024]= {0};
usleep(100000); int ret = 0;
while(1){
} if(-1 == client_socket_init(&g_client_ctrl.sd,g_client_ctrl.ip, g_client_ctrl.port)){
printf("network error, try connect again! \n"); printf("connect failed \n");
close(g_client_ctrl.sd); sleep(1);
} continue;
printf("loop_tcp_client_thread================== end \n"); }
g_client_ctrl.isConnect = 1;
} while(g_client_ctrl.isConnect){
_MutexLock(g_client_ctrl.mutex);
ret = read(g_client_ctrl.sd, buf, sizeof(buf));
int kk_tcp_client_send(char* data, int len){ _MutexUnlock(g_client_ctrl.mutex);
int ret = 0; if(-1== ret){
int cnt = 0; //printf("=================read error \n");
if ( data != NULL){ //break ;
while(g_client_ctrl.sd == -1 && cnt < 5){ }else if(ret > 0){
printf("[%s] tcp don't connect, sleep 1s !!!! \n",__FUNCTION__); printf("buf = %s\n",buf);
sleep(1); if (g_client_ctrl.cb != NULL){
cnt++; g_client_ctrl.cb(buf,ret,"");
} }
if (g_client_ctrl.sd < 0){ }
printf("[%s] The tcp socket created fialid !!!! \n",__FUNCTION__);
return -1; usleep(100000);
}
_MutexLock(g_client_ctrl.mutex); }
ret = write(g_client_ctrl.sd, data, len); printf("network error, try connect again! \n");
_MutexUnlock(g_client_ctrl.mutex); close(g_client_ctrl.sd);
if (ret < 0){ }
printf("[%s] write failed ret=%d, reconnect !!!! \n",__FUNCTION__, ret); printf("loop_tcp_client_thread================== end \n");
g_client_ctrl.isConnect = 0;
ret = -1; }
}
}
return ret; int kk_tcp_client_send(char* data, int len){
} int ret = 0;
int kk_tcp_client_init(char ip[MAX_IP_LEN], int port, ipc_cb cb) int cnt = 0;
{ if ( data != NULL){
//kk_tcp_client_deinit(); while(g_client_ctrl.sd == -1 && cnt < 5){
_init_client(); printf("[%s] tcp don't connect, sleep 1s !!!! \n",__FUNCTION__);
g_client_ctrl.port = port; sleep(1);
memcpy(g_client_ctrl.ip, ip, strlen(ip)); cnt++;
if (g_pTh ==NULL && 0 != pthread_create(&g_pTh, NULL, loop_tcp_client_thread, NULL)) { }
printf("create pthread failed\r\n"); if (g_client_ctrl.sd < 0){
return -1; printf("[%s] The tcp socket created fialid !!!! \n",__FUNCTION__);
}; return -1;
g_client_ctrl.cb = cb; }
} _MutexLock(g_client_ctrl.mutex);
ret = write(g_client_ctrl.sd, data, len);
kk_tcp_client_deinit(){ _MutexUnlock(g_client_ctrl.mutex);
if (g_client_ctrl.sd > -1){ if (ret < 0){
close(g_client_ctrl.sd); printf("[%s] write failed ret=%d, reconnect !!!! \n",__FUNCTION__, ret);
} g_client_ctrl.isConnect = 0;
_MutexDestroy(g_client_ctrl.mutex); ret = -1;
} }
}
return ret;
}
int kk_tcp_client_init(char ip[MAX_IP_LEN], int port, ipc_cb cb)
{
//kk_tcp_client_deinit();
_init_client();
g_client_ctrl.port = port;
memcpy(g_client_ctrl.ip, ip, strlen(ip));
if (g_pTh ==NULL && 0 != pthread_create(&g_pTh, NULL, loop_tcp_client_thread, NULL)) {
printf("create pthread failed\r\n");
return -1;
};
g_client_ctrl.cb = cb;
}
kk_tcp_client_deinit(){
if (g_client_ctrl.sd > -1){
close(g_client_ctrl.sd);
}
_MutexDestroy(g_client_ctrl.mutex);
}
LIBA_TARGET := libkk_hal.a LIBSO_TARGET := libkk_hal.so
\ No newline at end of file \ No newline at end of file
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include "sqlite3.h" #include "sqlite3.h"
#include "kk_log.h" #include "kk_log.h"
#include "kk_dm_mng.h" #include "kk_dm_mng.h"
#include "kk_property_db.h"
#define KK_PROPERTIES_DB_FILE "kk_properties.db" #define KK_PROPERTIES_DB_FILE "kk_properties.db"
...@@ -185,6 +186,93 @@ int kk_property_db_update_value(const char *deviceCode,const char *identifier,co ...@@ -185,6 +186,93 @@ int kk_property_db_update_value(const char *deviceCode,const char *identifier,co
return SUCCESS_RETURN; return SUCCESS_RETURN;
} }
int kk_property_db_get_value(const char *deviceCode,const char *identifier,void* value)
{
char *sqlCmd = NULL;
int rc = 0;
char *zErrMsg = 0;
sqlite3_stmt *stmt;
char *valueStr = NULL;
int valueType = 0;
kk_property_db_ctx_t *ctx = _kk_property_db_get_ctx();
_kk_property_db_lock();
sqlCmd = sqlite3_mprintf("select * from PropertiesInfo WHERE deviceCode= '%s' and identifier = '%s'",deviceCode,identifier);
DEBUG_PRINT("kk_property_db_get_value sqlCmd:%s\n",sqlCmd);
sqlite3_prepare_v2(ctx->pDb, sqlCmd, strlen(sqlCmd), &stmt, NULL);
while(sqlite3_step(stmt) == SQLITE_ROW){
valueStr = sqlite3_column_text(stmt, DB_VALUE);
valueType = sqlite3_column_int(stmt, DB_VALUETYPE);
if(valueType == KK_TSL_DATA_TYPE_INT||
valueType == KK_TSL_DATA_TYPE_ENUM||
valueType == KK_TSL_DATA_TYPE_BOOL){
int value_int = atoi(valueStr);
*(int*)value = value_int;
}
else if(valueType == KK_TSL_DATA_TYPE_FLOAT){
float value_float = atoi(valueStr);
*(float*)value = value_float;
}
else if(valueType == KK_TSL_DATA_TYPE_DOUBLE){
double value_double = atoi(valueStr);
*(double*)value = value_double;
}
else{
memcpy(value,valueStr, strlen(valueStr));
}
}
sqlite3_free(sqlCmd);
_kk_property_db_unlock();
sqlite3_finalize(stmt);
return SUCCESS_RETURN;
}
int kk_property_db_get_rawdata(const char *identifier,const int dev_type, kk_prop_raw_struct_t* raw, int count)
{
char *sqlCmd = NULL;
int rc = 0;
char *zErrMsg = 0;
sqlite3_stmt *stmt;
char *valueStr = NULL;
char *devcode = NULL;
int valueType = 0;
int idx = 0;
kk_prop_raw_struct_t *curData = NULL;
kk_property_db_ctx_t *ctx = _kk_property_db_get_ctx();
_kk_property_db_lock();
sqlCmd = sqlite3_mprintf("select * from PropertiesInfo WHERE devType= '%d' and identifier = '%s'",dev_type,identifier);
DEBUG_PRINT("kk_property_db_get_gw_value sqlCmd:%s\n",sqlCmd);
sqlite3_prepare_v2(ctx->pDb, sqlCmd, strlen(sqlCmd), &stmt, NULL);
curData = raw;
while(sqlite3_step(stmt) == SQLITE_ROW && idx < count){
devcode = sqlite3_column_text(stmt, DB_DEVICECODE);
valueStr = sqlite3_column_text(stmt, DB_VALUE);
valueType = sqlite3_column_int(stmt, DB_VALUETYPE);
memcpy(curData->deviceCode,devcode, strlen(devcode));
memcpy(curData->raw,valueStr, strlen(valueStr));
curData->type = valueType;
curData++;
idx++;
}
sqlite3_free(sqlCmd);
_kk_property_db_unlock();
sqlite3_finalize(stmt);
return SUCCESS_RETURN;
}
int kk_property_db_update(const char *deviceCode) int kk_property_db_update(const char *deviceCode)
{ {
int res = 0; int res = 0;
...@@ -285,6 +373,7 @@ int kk_property_sync_values(const char *deviceCode) ...@@ -285,6 +373,7 @@ int kk_property_sync_values(const char *deviceCode)
} }
sqlite3_free(sqlCmd);
_kk_property_db_unlock(); _kk_property_db_unlock();
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
......
#ifndef _KK_PROPERTY_DB_H_ #ifndef _KK_PROPERTY_DB_H_
#define _KK_PROPERTY_DB_H_ #define _KK_PROPERTY_DB_H_
#include "kk_tsl_common.h" #include "kk_tsl_common.h"
int kk_property_db_init(void); typedef struct{
int type;
#endif char deviceCode[DEVICE_CODE_MAXLEN];
char raw[60];
}kk_prop_raw_struct_t;
int kk_property_db_init(void);
#endif
#include<stdio.h> #include<stdio.h>
#include"com_api.h" #include"com_api.h"
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <stdio.h> #include <stdio.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <unistd.h> #include <unistd.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/shm.h> #include <sys/shm.h>
#include "cJSON.h" #include "cJSON.h"
#include "kk_product.h" #include "kk_product.h"
#include "kk_tsl_common.h" #include "kk_tsl_common.h"
#include "kk_tsl_api.h" #include "kk_tsl_api.h"
#include "kk_dm_api.h" #include "kk_dm_api.h"
#include "kk_dm_msg.h" #include "kk_dm_msg.h"
#include "kk_dm_mng.h" #include "kk_dm_mng.h"
#include "kk_log.h" #include "kk_log.h"
#include "kk_dm_queue.h" #include "kk_dm_queue.h"
#include "kk_property_db.h"
char * g_filerToPlatTable[] =
{ char * g_filerToPlatTable[] =
{KK_REGISTER_TOPIC_REPLY}, {
{KK_ADD_TOPIC_REPLY}, {KK_REGISTER_TOPIC_REPLY},
{KK_LOGIN_TOPIC_REPLY}, {KK_ADD_TOPIC_REPLY},
{KK_THING_OTA_DEVICE_UPGRADE}, {KK_LOGIN_TOPIC_REPLY},
{KK_THING_CLOUDSTATE_MSG}, {KK_THING_OTA_DEVICE_UPGRADE},
{KK_THING_CLOUDSTATE_MSG},
};
static int _kk_filter_to_plat(const char* msgtype) };
{ static int _kk_filter_to_plat(const char* msgtype)
int i = 0,num = 0; {
num = sizeof(g_filerToPlatTable)/sizeof(char *); int i = 0,num = 0;
num = sizeof(g_filerToPlatTable)/sizeof(char *);
for(i =0; i < num; i++){
if(strstr(msgtype,g_filerToPlatTable[i])) for(i =0; i < num; i++){
{ if(strstr(msgtype,g_filerToPlatTable[i]))
return 1; {
} return 1;
} }
return 0; }
} return 0;
}
void kk_sendData2gw(void* data, int len, char* chalMark){
if (chalMark== NULL || strlen(chalMark) == 0){ void kk_sendData2gw(void* data, int len, char* chalMark){
ERROR_PRINT(" chalMark is null"); if (chalMark== NULL || strlen(chalMark) == 0){
return; ERROR_PRINT(" chalMark is null");
} return;
}
if (kk_is_tcp_channel(chalMark) > -1){
kk_tcp_channel_ser_send(data, len, chalMark); if (kk_is_tcp_channel(chalMark) > -1){
}else{ kk_tcp_channel_ser_send(data, len, chalMark);
kk_ipc_send_ex(IPC_MID2PLAT, data, len, chalMark); }else{
} kk_ipc_send_ex(IPC_MID2PLAT, data, len, chalMark);
}
}
void mid_cb(void* data, int len){ }
if (data != NULL){ void mid_cb(void* data, int len){
if (data != NULL){
char *out;
cJSON *json; char *out;
cJSON *info_root,*info,*type; cJSON *json;
cJSON*payload; cJSON *info_root,*info,*type;
cJSON*deviceCode; cJSON*payload;
int res; cJSON*deviceCode;
void* buf = malloc(len); int res;
memcpy(buf, data, len); void* buf = malloc(len);
res = dm_queue_msg_insert((void *)buf); memcpy(buf, data, len);
if (res != SUCCESS_RETURN) { res = dm_queue_msg_insert((void *)buf);
free(buf); if (res != SUCCESS_RETURN) {
//return FAIL_RETURN; free(buf);
} //return FAIL_RETURN;
}
json=cJSON_Parse(data);
if (!json) { json=cJSON_Parse(data);
printf("Error before: [%s]\n","cJSON_Parse"); if (!json) {
} printf("Error before: [%s]\n","cJSON_Parse");
else }
{ else
info_root = cJSON_GetObjectItem(json, MSG_INFO_STR); {
deviceCode = cJSON_GetObjectItem(info_root, MSG_DEVICE_CODE_STR); info_root = cJSON_GetObjectItem(json, MSG_INFO_STR);
type = cJSON_GetObjectItem(info_root, MSG_TYPE_STR); deviceCode = cJSON_GetObjectItem(info_root, MSG_DEVICE_CODE_STR);
if(_kk_filter_to_plat(type->valuestring)){ type = cJSON_GetObjectItem(info_root, MSG_TYPE_STR);
cJSON_Delete(json); if(_kk_filter_to_plat(type->valuestring)){
cJSON_Delete(info); cJSON_Delete(json);
return; cJSON_Delete(info);
} return;
}
int devType = 0;
dm_mgr_get_devicetype_by_devicecode(deviceCode->valuestring,&devType); int devType = 0;
if(devType == KK_DM_DEVICE_GATEWAY){ dm_mgr_get_devicetype_by_devicecode(deviceCode->valuestring,&devType);
kk_sendData2gw(data, strlen(data), deviceCode->valuestring);//send to gw itself if(devType == KK_DM_DEVICE_GATEWAY){
}else if(devType == KK_DM_DEVICE_SUBDEV){ kk_sendData2gw(data, strlen(data), deviceCode->valuestring);//send to gw itself
dm_mgr_dev_node_t *gw_node = NULL; }else if(devType == KK_DM_DEVICE_SUBDEV){
res = dm_mgr_get_device_by_devicecode(deviceCode->valuestring,&gw_node); dm_mgr_dev_node_t *gw_node = NULL;
if (res != SUCCESS_RETURN) { res = dm_mgr_get_device_by_devicecode(deviceCode->valuestring,&gw_node);
ERROR_PRINT("res:%d\n",res); if (res != SUCCESS_RETURN) {
cJSON_Delete(json); ERROR_PRINT("res:%d\n",res);
cJSON_Delete(info); cJSON_Delete(json);
return; cJSON_Delete(info);
} return;
kk_sendData2gw(data, strlen(data), gw_node->fatherDeviceCode);//send to sub device }
} kk_sendData2gw(data, strlen(data), gw_node->fatherDeviceCode);//send to sub device
else{ }
ERROR_PRINT("wrong type\n"); else{
} ERROR_PRINT("wrong type\n");
cJSON_Delete(json); }
cJSON_Delete(info); cJSON_Delete(json);
cJSON_Delete(info);
}
} }
} }
}
void mid2p_cb(void* data, int len, char* chalMark){
if (data != NULL){ void mid2p_cb(void* data, int len, char* chalMark){
//printf("mid2plat_cb: %s RECEIVED \r\n", data); if (data != NULL){
int res = 0; //printf("mid2plat_cb: %s RECEIVED \r\n", data);
void* buf = NULL; int res = 0;
dm_queue_msg_t *queue_msg = NULL; void* buf = NULL;
queue_msg = malloc(sizeof(dm_queue_msg_t)); dm_queue_msg_t *queue_msg = NULL;
if (queue_msg == NULL){ queue_msg = malloc(sizeof(dm_queue_msg_t));
ERROR_PRINT("mid2p_cb malloc queue_msg failed "); if (queue_msg == NULL){
return; ERROR_PRINT("mid2p_cb malloc queue_msg failed ");
} return;
buf = malloc(len); }
if (buf == NULL){ buf = malloc(len);
ERROR_PRINT("mid2p_cb malloc buf failed "); if (buf == NULL){
return; ERROR_PRINT("mid2p_cb malloc buf failed ");
} return;
}
memcpy(buf, data, len);
queue_msg->data = buf; memcpy(buf, data, len);
memset(queue_msg->chalMark, 0, sizeof(queue_msg->chalMark)); queue_msg->data = buf;
if(chalMark != NULL){ memset(queue_msg->chalMark, 0, sizeof(queue_msg->chalMark));
memcpy(queue_msg->chalMark, chalMark, sizeof(chalMark)); if(chalMark != NULL){
} memcpy(queue_msg->chalMark, chalMark, sizeof(chalMark));
res = dm_queue_msg_insert2((void *)queue_msg); }
if (res != SUCCESS_RETURN) { res = dm_queue_msg_insert2((void *)queue_msg);
free(queue_msg); if (res != SUCCESS_RETURN) {
free(buf); free(queue_msg);
return ; free(buf);
} return ;
}
//kk_ipc_send(IPC_MID2APP, data, len);
} //kk_ipc_send(IPC_MID2APP, data, len);
} }
}
void gw2mid_cb(void* data, int len, char* chalMark){
if (data != NULL){ void gw2mid_cb(void* data, int len, char* chalMark){
printf("gw2mid_cb chalMark=%s, data: %s RECEIVED \r\n", chalMark, data); if (data != NULL){
mid2p_cb(data,len,chalMark); printf("gw2mid_cb chalMark=%s, data: %s RECEIVED \r\n", chalMark, data);
} mid2p_cb(data,len,chalMark);
} }
}
void kk_platMsg_handle(void* data, char* chalMark){
void kk_platMsg_handle(void* data, char* chalMark){
char *out;
int res = 0; char *out;
cJSON *json; int res = 0;
cJSON *info; cJSON *json;
cJSON *info_dcode; cJSON *info;
cJSON *params; cJSON *info_dcode;
cJSON *jsonPay; cJSON *params;
cJSON *msgType; cJSON *jsonPay;
cJSON *proCode; cJSON *msgType;
cJSON *devCode; cJSON *proCode;
cJSON *mac; cJSON *devCode;
cJSON *payload; cJSON *mac;
cJSON *payload;
json=cJSON_Parse(data);
if (!json) { json=cJSON_Parse(data);
WARNING_PRINT("Error before: [%s]\n","cJSON_Parse"); if (!json) {
} WARNING_PRINT("Error before: [%s]\n","cJSON_Parse");
else{ }
info = cJSON_GetObjectItem(json, "info"); else{
payload = cJSON_GetObjectItem(json, "payload"); info = cJSON_GetObjectItem(json, "info");
if (info == NULL || payload == NULL){ payload = cJSON_GetObjectItem(json, "payload");
ERROR_PRINT("info or payload params is error\n"); if (info == NULL || payload == NULL){
goto error; ERROR_PRINT("info or payload params is error\n");
} goto error;
}
msgType = cJSON_GetObjectItem(info, "msgType");
info_dcode = cJSON_GetObjectItem(info, "deviceCode"); msgType = cJSON_GetObjectItem(info, "msgType");
info_dcode = cJSON_GetObjectItem(info, "deviceCode");
jsonPay = cJSON_GetObjectItem(payload, "params");
jsonPay = cJSON_GetObjectItem(payload, "params");
if (msgType == NULL || info_dcode == NULL || jsonPay == NULL){
ERROR_PRINT("msgType info_dcode or jsonPay params are error\n"); if (msgType == NULL || info_dcode == NULL || jsonPay == NULL){
goto error; ERROR_PRINT("msgType info_dcode or jsonPay params are error\n");
} goto error;
}
dm_mgr_update_timestamp_by_devicecode(info_dcode->valuestring,HAL_UptimeMs());
dm_mgr_update_timestamp_by_devicecode(info_dcode->valuestring,HAL_UptimeMs());
if (strcmp(msgType->valuestring, "/thing/topo/add")==0){
proCode = cJSON_GetObjectItem(jsonPay, "productCode"); if (strcmp(msgType->valuestring, "/thing/topo/add")==0){
devCode = cJSON_GetObjectItem(jsonPay, "deviceCode"); proCode = cJSON_GetObjectItem(jsonPay, "productCode");
mac = cJSON_GetObjectItem(jsonPay, "mac"); devCode = cJSON_GetObjectItem(jsonPay, "deviceCode");
if (proCode == NULL || devCode == NULL || mac == NULL){ mac = cJSON_GetObjectItem(jsonPay, "mac");
ERROR_PRINT("productCode, deviceCode mac params are error\n"); if (proCode == NULL || devCode == NULL || mac == NULL){
goto error; ERROR_PRINT("productCode, deviceCode mac params are error\n");
} goto error;
INFO_PRINT("deviceCode productCode mac: [%s][%s] [%s] \n",devCode->valuestring, proCode->valuestring, mac->valuestring); }
//判断网关还是子设备 INFO_PRINT("deviceCode productCode mac: [%s][%s] [%s] \n",devCode->valuestring, proCode->valuestring, mac->valuestring);
if (strcmp(info_dcode->valuestring, devCode->valuestring) == 0){ //判断网关还是子设备
char ccu_deviceCode[DEVICE_CODE_MAXLEN] = {0}; if (strcmp(info_dcode->valuestring, devCode->valuestring) == 0){
HAL_GetDevice_Code(ccu_deviceCode); char ccu_deviceCode[DEVICE_CODE_MAXLEN] = {0};
kk_mid_subdev_add(KK_DM_DEVICE_GATEWAY,proCode->valuestring,devCode->valuestring, mac->valuestring,ccu_deviceCode); HAL_GetDevice_Code(ccu_deviceCode);
}else{ kk_mid_subdev_add(KK_DM_DEVICE_GATEWAY,proCode->valuestring,devCode->valuestring, mac->valuestring,ccu_deviceCode);
kk_mid_subdev_add(KK_DM_DEVICE_SUBDEV,proCode->valuestring,devCode->valuestring, mac->valuestring,info_dcode->valuestring); }else{
} kk_mid_subdev_add(KK_DM_DEVICE_SUBDEV,proCode->valuestring,devCode->valuestring, mac->valuestring,info_dcode->valuestring);
}
}else if (strstr(msgType->valuestring, "property/post") != NULL){
INFO_PRINT("save property and send to cloud \n"); }else if (strstr(msgType->valuestring, "property/post") != NULL){
char* outstr = cJSON_Print(payload); INFO_PRINT("save property and send to cloud \n");
kk_tsl_property_set_by_devicecode(info_dcode->valuestring, outstr, strlen(outstr)+1); char* outstr = cJSON_Print(payload);
kk_property_db_update(info_dcode->valuestring); kk_tsl_property_set_by_devicecode(info_dcode->valuestring, outstr, strlen(outstr)+1);
free(outstr); kk_property_db_update(info_dcode->valuestring);
free(outstr);
}else if(strstr(msgType->valuestring, "/thing/topo/delete") != NULL){
INFO_PRINT("kk_platMsg_handle data: handle delete\n"); }else if(strstr(msgType->valuestring, "/thing/topo/delete") != NULL){
devCode = cJSON_GetObjectItem(jsonPay, "deviceCode"); INFO_PRINT("kk_platMsg_handle data: handle delete\n");
kk_ipc_send(IPC_MID2APP,data,strlen(data)); devCode = cJSON_GetObjectItem(jsonPay, "deviceCode");
dm_mgr_subdev_delete(devCode->valuestring); kk_ipc_send(IPC_MID2APP,data,strlen(data));
dm_mgr_subdev_delete(devCode->valuestring);
}else{
INFO_PRINT("kk_platMsg_handle data: don't handle it [%s]\n",data); }else{
INFO_PRINT("kk_platMsg_handle data: don't handle it [%s]\n",data);
//kk_tsl_service_property_set(topic->valuestring, payload->valuestring, strlen(payload->valuestring), NULL);
} //kk_tsl_service_property_set(topic->valuestring, payload->valuestring, strlen(payload->valuestring), NULL);
error: }
cJSON_Delete(json); error:
} cJSON_Delete(json);
} }
}
void kk_platMsg_dispatch(void)
{ void kk_platMsg_dispatch(void)
int count = 0; {
void *data = NULL; int count = 0;
void *data = NULL;
while (CONFIG_DISPATCH_QUEUE_MAXLEN == 0 || count++ < CONFIG_DISPATCH_QUEUE_MAXLEN) {
while (CONFIG_DISPATCH_QUEUE_MAXLEN == 0 || count++ < CONFIG_DISPATCH_QUEUE_MAXLEN) {
if (dm_queue_msg_next2(&data) == SUCCESS_RETURN) {
dm_queue_msg_t *msg = (dm_queue_msg_t *)data; if (dm_queue_msg_next2(&data) == SUCCESS_RETURN) {
INFO_PRINT("kk_handle_platMsg_dispatch get call \n"); dm_queue_msg_t *msg = (dm_queue_msg_t *)data;
if (kk_platMsg_handle) { INFO_PRINT("kk_handle_platMsg_dispatch get call \n");
kk_platMsg_handle(msg->data,msg->chalMark); if (kk_platMsg_handle) {
} kk_platMsg_handle(msg->data,msg->chalMark);
}
if (msg->data != NULL){
free(msg->data); if (msg->data != NULL){
} free(msg->data);
free(data); }
data = NULL; free(data);
} else { data = NULL;
break; } else {
} break;
} }
} }
}
time_t getSysTime(){
time_t t; time_t getSysTime(){
t = time(NULL); time_t t;
return t; t = time(NULL);
return t;
}
}
typedef struct {
int auto_add_subdev; typedef struct {
int master_devid; int auto_add_subdev;
int cloud_connected; int master_devid;
int master_initialized; int cloud_connected;
int subdev_index; int master_initialized;
int permit_join; int subdev_index;
void *g_mid_dispatch_thread; int permit_join;
void *g_ota_dispatch_thread; void *g_mid_dispatch_thread;
void *g_ccuProChg_dispatch_thread; void *g_ota_dispatch_thread;
void *g_udp_dispatch_thread; void *g_ccuProChg_dispatch_thread;
int g_mid_dispatch_thread_running; void *g_udp_dispatch_thread;
int g_ota_dispatch_thread_running; int g_mid_dispatch_thread_running;
int g_ccuProChg_dispatch_thread_running; int g_ota_dispatch_thread_running;
int g_udp_dispatch_thread_running; int g_ccuProChg_dispatch_thread_running;
} mid_ctx_t; int g_udp_dispatch_thread_running;
#define MID_YIELD_TIMEOUT_MS (200) } mid_ctx_t;
#define MID_YIELD_TIMEOUT_MS (200)
static mid_ctx_t g_mid_ctx;
static mid_ctx_t g_mid_ctx;
static mid_ctx_t *kk_mid_get_ctx(void)
{ static mid_ctx_t *kk_mid_get_ctx(void)
return &g_mid_ctx; {
} return &g_mid_ctx;
}
extern void IOT_Linkkit_Yield(int timeout_ms);
void *mid_dispatch_yield(void *args) extern void IOT_Linkkit_Yield(int timeout_ms);
{ void *mid_dispatch_yield(void *args)
mid_ctx_t *mid_ctx = kk_mid_get_ctx(); {
mid_ctx_t *mid_ctx = kk_mid_get_ctx();
while (mid_ctx->g_mid_dispatch_thread_running) {
IOT_Linkkit_Yield(MID_YIELD_TIMEOUT_MS); while (mid_ctx->g_mid_dispatch_thread_running) {
} IOT_Linkkit_Yield(MID_YIELD_TIMEOUT_MS);
}
return NULL;
} return NULL;
}
void *ota_dispatch_yield(void *args)
{ void *ota_dispatch_yield(void *args)
mid_ctx_t *mid_ctx = kk_mid_get_ctx(); {
mid_ctx_t *mid_ctx = kk_mid_get_ctx();
while (mid_ctx->g_ota_dispatch_thread_running) {
dm_ota_yield(MID_YIELD_TIMEOUT_MS); while (mid_ctx->g_ota_dispatch_thread_running) {
} dm_ota_yield(MID_YIELD_TIMEOUT_MS);
}
return NULL;
} return NULL;
}
#define UDP_LAN_PORT 25556
#define UDP_LAN_PORT_HOST 25555 #define UDP_LAN_PORT 25556
#define test_ #define UDP_LAN_PORT_HOST 25555
void *udp_dispatch_yield(void *args){ #define test_
void *udp_dispatch_yield(void *args){
INFO_PRINT("udp_dispatch_yield udp thread create\n");
// 绑定地址 INFO_PRINT("udp_dispatch_yield udp thread create\n");
struct sockaddr_in addrto;
bzero(&addrto, sizeof(struct sockaddr_in)); // 绑定地址
addrto.sin_family = AF_INET; struct sockaddr_in addrto;
addrto.sin_addr.s_addr = htonl(INADDR_ANY); bzero(&addrto, sizeof(struct sockaddr_in));
addrto.sin_port = htons(UDP_LAN_PORT); addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = htonl(INADDR_ANY);
// 发送地址 addrto.sin_port = htons(UDP_LAN_PORT);
struct sockaddr_in addrto_host;
bzero(&addrto_host, sizeof(struct sockaddr_in)); // 发送地址
addrto_host.sin_family = AF_INET; struct sockaddr_in addrto_host;
addrto_host.sin_addr.s_addr = htonl(INADDR_ANY); bzero(&addrto_host, sizeof(struct sockaddr_in));
//addrto_host.sin_port = htons(UDP_LAN_PORT); addrto_host.sin_family = AF_INET;
addrto_host.sin_addr.s_addr = htonl(INADDR_ANY);
// 接收到的广播地址 //addrto_host.sin_port = htons(UDP_LAN_PORT);
struct sockaddr_in from;
bzero(&from, sizeof(struct sockaddr_in)); // 接收到的广播地址
struct sockaddr_in from;
bzero(&from, sizeof(struct sockaddr_in));
int sock = -1;
int sock_host = -1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) int sock = -1;
{ int sock_host = -1;
ERROR_PRINT("socket error\n"); if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
} {
ERROR_PRINT("socket error\n");
if ((sock_host = socket(AF_INET, SOCK_DGRAM, 0)) == -1) }
{
ERROR_PRINT("socket error\n"); if ((sock_host = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
} {
ERROR_PRINT("socket error\n");
if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1) }
{
ERROR_PRINT("bind error...\n"); if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)
} {
ERROR_PRINT("bind error...\n");
socklen_t len = sizeof(struct sockaddr_in); }
cJSON* json = NULL;
cJSON* info = NULL; socklen_t len = sizeof(struct sockaddr_in);
cJSON* payload = NULL; cJSON* json = NULL;
cJSON* infoObj = NULL; cJSON* info = NULL;
cJSON* payloadObj = NULL; cJSON* payload = NULL;
cJSON* msgtype = NULL; cJSON* infoObj = NULL;
cJSON* proCode = NULL; cJSON* payloadObj = NULL;
cJSON* devCode = NULL; cJSON* msgtype = NULL;
cJSON* params = NULL; cJSON* proCode = NULL;
cJSON* macstr = NULL; cJSON* devCode = NULL;
char szOut[128] = {0}; cJSON* params = NULL;
char szDec[1024] = {0}; cJSON* macstr = NULL;
char host_ip[32] = {0}; char szOut[128] = {0};
char mac[32] = {0}; char szDec[1024] = {0};
char device_code[DEVICE_CODE_LEN] = {0}; char host_ip[32] = {0};
int devId = 0; char mac[32] = {0};
char device_code[DEVICE_CODE_LEN] = {0};
kk_TCP_channel_init(gw2mid_cb); int devId = 0;
kk_prop_raw_struct_t ipList[10] = {0};
while(1) int idx = 0;
{
kk_property_db_get_rawdata("IPAddress",4, ipList, sizeof(ipList));
for(; idx < 10; idx++){
//从广播地址接受消息 DEBUG_PRINT("ipList[%d][%s][%s] \n", idx, ipList[idx].deviceCode, ipList[idx].raw);
memset(szDec, 0 , sizeof(szDec)); if (strlen(ipList[idx].deviceCode)>0 && strlen(ipList[idx].raw)>0){
int size=recvfrom(sock, szDec, sizeof(szDec), 0, (struct sockaddr*)&from,(socklen_t*)&len); kk_set_tcp_channel_by_idx(idx, ipList[idx].deviceCode, ipList[idx].raw);
if(size<=0) }
{ }
WARNING_PRINT("read error....\n"); kk_TCP_channel_init(gw2mid_cb);
}
else while(1)
{ {
DEBUG_PRINT("lan recmsg: %s\n", szDec);
//DEBUG_PRINT("udp client ip:%s ,port is :%d htons(UDP_LAN_PORT)=%d \n",inet_ntoa(from.sin_addr),from.sin_port, htons(UDP_LAN_PORT)); //从广播地址接受消息
#ifdef test_ memset(szDec, 0 , sizeof(szDec));
//"search_kk_ccu|deviceCode=1122334455667788;protocol=tcp" int size=recvfrom(sock, szDec, sizeof(szDec), 0, (struct sockaddr*)&from,(socklen_t*)&len);
if(strstr(szDec, "search_kk_ccu|") != NULL){ if(size<=0)
{
char* getConnet = szDec + strlen("search_kk_ccu|"); WARNING_PRINT("read error....\n");
char* tmp = NULL; }
char* endIdx = NULL; else
int itemLen = 0; {
int itemConnetLen = 0;
char gwDevCode[DEVICE_CODE_LEN] = {0}; DEBUG_PRINT("lan recmsg: %s\n", szDec);
char proto[10] = {0}; //DEBUG_PRINT("udp client ip:%s ,port is :%d htons(UDP_LAN_PORT)=%d \n",inet_ntoa(from.sin_addr),from.sin_port, htons(UDP_LAN_PORT));
#ifdef test_
//"search_kk_ccu|deviceCode=1122334455667788;protocol=tcp"
tmp = strstr(getConnet, "deviceCode="); if(strstr(szDec, "search_kk_ccu|") != NULL){
itemLen = strlen("deviceCode=");
if (tmp != NULL){ char* getConnet = szDec + strlen("search_kk_ccu|");
endIdx = strstr(tmp, ";"); char* tmp = NULL;
if(endIdx == NULL){ char* endIdx = NULL;
itemConnetLen = strlen(tmp) - itemLen; int itemLen = 0;
}else{ int itemConnetLen = 0;
itemConnetLen = endIdx - tmp - itemLen; char gwDevCode[DEVICE_CODE_LEN] = {0};
} char proto[10] = {0};
memcpy(gwDevCode, tmp + itemLen,itemConnetLen);
}
tmp = strstr(getConnet, "deviceCode=");
tmp = strstr(getConnet, "protocol="); itemLen = strlen("deviceCode=");
itemLen = strlen("protocol="); if (tmp != NULL){
if (tmp != NULL){ endIdx = strstr(tmp, ";");
endIdx = strstr(tmp, ";"); if(endIdx == NULL){
if(endIdx == NULL){ itemConnetLen = strlen(tmp) - itemLen;
itemConnetLen = strlen(tmp) - itemLen; }else{
}else{ itemConnetLen = endIdx - tmp - itemLen;
itemConnetLen = endIdx - tmp - itemLen; }
} memcpy(gwDevCode, tmp + itemLen,itemConnetLen);
memcpy(proto, tmp + itemLen,itemConnetLen); }
}
tmp = strstr(getConnet, "protocol=");
DEBUG_PRINT("gwDevCode =%s proto=%s \n",gwDevCode,proto); itemLen = strlen("protocol=");
if(strcmp(proto,"tcp") == 0){ if (tmp != NULL){
// endIdx = strstr(tmp, ";");
if(endIdx == NULL){
kk_set_tcp_channel(gwDevCode,inet_ntoa(from.sin_addr)); itemConnetLen = strlen(tmp) - itemLen;
} }else{
itemConnetLen = endIdx - tmp - itemLen;
memset(host_ip, 0, sizeof(host_ip)); }
memset(mac, 0, sizeof(mac)); memcpy(proto, tmp + itemLen,itemConnetLen);
memset(szOut, 0, sizeof(szOut)); }
HAL_Get_IP(host_ip,"ens33");
HAL_GetDevice_Code(device_code); DEBUG_PRINT("gwDevCode =%s proto=%s \n",gwDevCode,proto);
if(strcmp(proto,"tcp") == 0){
sprintf(szOut,"search_kk_ccu_ack|deviceCode=%s;ip=%s;port=%d",device_code,host_ip,16565); //
DEBUG_PRINT("szOut:%s\n",szOut);
DEBUG_PRINT("udp client ip:%s ,port is :%d \n",inet_ntoa(from.sin_addr),from.sin_port); kk_set_tcp_channel(gwDevCode,inet_ntoa(from.sin_addr));
//sendto(sock, szOut, strlen(szOut), 0, (struct sockaddr*)&from,len); }
addrto_host.sin_addr.s_addr = inet_addr(inet_ntoa(from.sin_addr)); memset(host_ip, 0, sizeof(host_ip));
addrto_host.sin_port = htons(UDP_LAN_PORT_HOST); memset(mac, 0, sizeof(mac));
//addrto_host.sin_port = from.sin_port; memset(szOut, 0, sizeof(szOut));
//if(strcmp(host_ip,inet_ntoa(from.sin_addr)) == 0) HAL_Get_IP(host_ip,"ens33");
//{ HAL_GetDevice_Code(device_code);
sendto(sock_host, szOut, strlen(szOut), 0, (struct sockaddr*)&addrto_host,sizeof(addrto_host));
//} sprintf(szOut,"search_kk_ccu_ack|deviceCode=%s;ip=%s;port=%d",device_code,host_ip,16565);
//else DEBUG_PRINT("szOut:%s\n",szOut);
//{ DEBUG_PRINT("udp client ip:%s ,port is :%d \n",inet_ntoa(from.sin_addr),from.sin_port);
// DEBUG_PRINT("udp client is not local ip , refused send ack to it\n"); //sendto(sock, szOut, strlen(szOut), 0, (struct sockaddr*)&from,len);
//}
} addrto_host.sin_addr.s_addr = inet_addr(inet_ntoa(from.sin_addr));
#else addrto_host.sin_port = htons(UDP_LAN_PORT_HOST);
json=cJSON_Parse(szDec); //addrto_host.sin_port = from.sin_port;
if (!json) { //if(strcmp(host_ip,inet_ntoa(from.sin_addr)) == 0)
ERROR_PRINT("Error before: [%s]\n","cJSON_Parse"); //{
} sendto(sock_host, szOut, strlen(szOut), 0, (struct sockaddr*)&addrto_host,sizeof(addrto_host));
else //}
{ //else
//{
infoObj = cJSON_GetObjectItem(json, "info"); // DEBUG_PRINT("udp client is not local ip , refused send ack to it\n");
payloadObj = cJSON_GetObjectItem(json, "payload"); //}
}
if (infoObj != NULL && payloadObj != NULL){ #else
json=cJSON_Parse(szDec);
msgtype = cJSON_GetObjectItem(infoObj, "msgtype"); if (!json) {
if (msgtype == NULL || strstr(msgtype->valuestring, "/thing/topo/add") == NULL){ ERROR_PRINT("Error before: [%s]\n","cJSON_Parse");
ERROR_PRINT("msgtype parameter is error \n"); }
cJSON_Delete(json); else
continue; {
}
infoObj = cJSON_GetObjectItem(json, "info");
proCode = cJSON_GetObjectItem(infoObj, "productCode"); payloadObj = cJSON_GetObjectItem(json, "payload");
devCode = cJSON_GetObjectItem(infoObj, "deviceCode");
params = cJSON_GetObjectItem(payloadObj, "params"); if (infoObj != NULL && payloadObj != NULL){
if (proCode == NULL || devCode == NULL || params == NULL){
ERROR_PRINT("productType productCode deviceCode params parameters are error \n"); msgtype = cJSON_GetObjectItem(infoObj, "msgtype");
cJSON_Delete(json); if (msgtype == NULL || strstr(msgtype->valuestring, "/thing/topo/add") == NULL){
continue; ERROR_PRINT("msgtype parameter is error \n");
} cJSON_Delete(json);
continue;
macstr = cJSON_GetObjectItem(params, "mac"); }
if (macstr == NULL){ proCode = cJSON_GetObjectItem(infoObj, "productCode");
ERROR_PRINT("mac parameter is error \n"); devCode = cJSON_GetObjectItem(infoObj, "deviceCode");
cJSON_Delete(json); params = cJSON_GetObjectItem(payloadObj, "params");
continue; if (proCode == NULL || devCode == NULL || params == NULL){
} ERROR_PRINT("productType productCode deviceCode params parameters are error \n");
cJSON_Delete(json);
INFO_PRINT(" productCode deviceCode mac: [%s][%s][%s] \n", proCode->valuestring, continue;
devCode->valuestring, macstr->valuestring); }
char device_code[DEVICE_CODE_LEN] = {0};
HAL_GetDevice_Code(device_code); macstr = cJSON_GetObjectItem(params, "mac");
int res = kk_mid_subdev_add(KK_DM_DEVICE_GATEWAY, proCode->valuestring, devCode->valuestring,macstr->valuestring, device_code);
if (res != SUCCESS_RETURN) { if (macstr == NULL){
WARNING_PRINT("dm_mgr_gw_create error"); ERROR_PRINT("mac parameter is error \n");
} cJSON_Delete(json);
continue;
//kk_ipc_send(IPC_MID2APP, szDec, size); }
memset(host_ip, 0, sizeof(host_ip)); INFO_PRINT(" productCode deviceCode mac: [%s][%s][%s] \n", proCode->valuestring,
memset(mac, 0, sizeof(mac)); devCode->valuestring, macstr->valuestring);
memset(szOut, 0, sizeof(szOut)); char device_code[DEVICE_CODE_LEN] = {0};
HAL_Get_IP(host_ip,"ens33"); HAL_GetDevice_Code(device_code);
HAL_Get_mac(mac); int res = kk_mid_subdev_add(KK_DM_DEVICE_GATEWAY, proCode->valuestring, devCode->valuestring,macstr->valuestring, device_code);
if (res != SUCCESS_RETURN) {
sprintf(szOut,"/thing/topo/add_reply|mac=%s;ip=%s",mac,host_ip); WARNING_PRINT("dm_mgr_gw_create error");
DEBUG_PRINT("szOut:%s\n",szOut); }
DEBUG_PRINT("udp client ip:%s ,port is :%d \n",inet_ntoa(from.sin_addr),from.sin_port);
//sendto(sock, szOut, strlen(szOut), 0, (struct sockaddr*)&from,len); //kk_ipc_send(IPC_MID2APP, szDec, size);
addrto_host.sin_addr.s_addr = inet_addr(inet_ntoa(from.sin_addr)); memset(host_ip, 0, sizeof(host_ip));
addrto_host.sin_port = htons(UDP_LAN_PORT_HOST); memset(mac, 0, sizeof(mac));
//addrto_host.sin_port = from.sin_port; memset(szOut, 0, sizeof(szOut));
if(strcmp(host_ip,inet_ntoa(from.sin_addr)) == 0) HAL_Get_IP(host_ip,"ens33");
{ HAL_Get_mac(mac);
sendto(sock_host, szOut, strlen(szOut), 0, (struct sockaddr*)&addrto_host,sizeof(addrto_host));
} sprintf(szOut,"/thing/topo/add_reply|mac=%s;ip=%s",mac,host_ip);
else DEBUG_PRINT("szOut:%s\n",szOut);
{ DEBUG_PRINT("udp client ip:%s ,port is :%d \n",inet_ntoa(from.sin_addr),from.sin_port);
DEBUG_PRINT("udp client is not local ip , refused send ack to it\n"); //sendto(sock, szOut, strlen(szOut), 0, (struct sockaddr*)&from,len);
}
addrto_host.sin_addr.s_addr = inet_addr(inet_ntoa(from.sin_addr));
}else{ addrto_host.sin_port = htons(UDP_LAN_PORT_HOST);
INFO_PRINT("error format json: [%s]\n",szDec); //addrto_host.sin_port = from.sin_port;
if(strcmp(host_ip,inet_ntoa(from.sin_addr)) == 0)
} {
sendto(sock_host, szOut, strlen(szOut), 0, (struct sockaddr*)&addrto_host,sizeof(addrto_host));
cJSON_Delete(json); }
else
} {
#endif DEBUG_PRINT("udp client is not local ip , refused send ack to it\n");
}
}
usleep(100000); }else{
} INFO_PRINT("error format json: [%s]\n",szDec);
}
close(sock);
close(sock_host); cJSON_Delete(json);
}
void *ccu_property_monitor(void *args) }
{ #endif
mid_ctx_t *mid_ctx = kk_mid_get_ctx();
char s_IP[NETWORK_ADDR_LEN]; }
char *s_IP_TSL = NULL; usleep(100000);
int res = 0; }
int needReport = 0;
int time_second = 60;
close(sock);
while (mid_ctx->g_ccuProChg_dispatch_thread_running) { close(sock_host);
if(kk_get_cloud_recv_status() == 0){ }
iotx_dm_ccu_cloud_check(); void *ccu_property_monitor(void *args)
sleep(10); {
continue; mid_ctx_t *mid_ctx = kk_mid_get_ctx();
} char s_IP[NETWORK_ADDR_LEN];
//dm_ota_yield(MID_YIELD_TIMEOUT_MS); char *s_IP_TSL = NULL;
HAL_Get_IP(s_IP,NULL); int res = 0;
res = kk_tsl_get_value(kk_tsl_get_property_value,0,KK_TSL_CCU_WANIP_IDENTIFIER,NULL,&s_IP_TSL); int needReport = 0;
if(res != SUCCESS_RETURN){ int time_second = 60;
ERROR_PRINT("kk_tsl_get_value Failed\n");
} while (mid_ctx->g_ccuProChg_dispatch_thread_running) {
else{ if(kk_get_cloud_recv_status() == 0){
if(strcmp(s_IP,s_IP_TSL)){ iotx_dm_ccu_cloud_check();
kk_tsl_set_value(kk_tsl_set_property_value,0,KK_TSL_CCU_WANIP_IDENTIFIER,NULL,s_IP); sleep(10);
INFO_PRINT("current ip:%s,before ip:%s\n",s_IP,s_IP_TSL); continue;
kk_property_db_update("CCU_66666"); }
needReport = 1; //dm_ota_yield(MID_YIELD_TIMEOUT_MS);
} HAL_Get_IP(s_IP,NULL);
} res = kk_tsl_get_value(kk_tsl_get_property_value,0,KK_TSL_CCU_WANIP_IDENTIFIER,NULL,&s_IP_TSL);
if(needReport&&(kk_get_cloudstatus() == 1)){ if(res != SUCCESS_RETURN){
needReport = 0; ERROR_PRINT("kk_tsl_get_value Failed\n");
kk_tsl_post_property(0,NULL); }
} else{
sleep(time_second); if(strcmp(s_IP,s_IP_TSL)){
} kk_tsl_set_value(kk_tsl_set_property_value,0,KK_TSL_CCU_WANIP_IDENTIFIER,NULL,s_IP);
return NULL; INFO_PRINT("current ip:%s,before ip:%s\n",s_IP,s_IP_TSL);
} kk_property_db_update("CCU_66666");
needReport = 1;
}
}
static int kk_set_product_info(void) if(needReport&&(kk_get_cloudstatus() == 1)){
{ needReport = 0;
HAL_SetProduct_Type(PRODUCT_TPYE); kk_tsl_post_property(0,NULL);
HAL_SetProduct_Code(PRODUCT_CODE); }
return 0; sleep(time_second);
} }
return NULL;
int main(const int argc, const char **argv) }
{
int res = 0;
char *tsl_str; static int kk_set_product_info(void)
int i; {
kk_tsl_t *dev_shadow[30] = {NULL}; HAL_SetProduct_Type(PRODUCT_TPYE);
mid_ctx_t *mid_ctx = kk_mid_get_ctx(); HAL_SetProduct_Code(PRODUCT_CODE);
return 0;
kk_zlog_init("midware"); }
memset(mid_ctx, 0, sizeof(mid_ctx_t));
int main(const int argc, const char **argv)
kk_set_product_info(); {
kk_tsl_api_init();
kk_ipc_init(IPC_MID2APP, mid_cb, NULL, NULL); int res = 0;
kk_ipc_init(IPC_MID2PLAT, mid2p_cb, NULL, "*"); char *tsl_str;
int i;
kk_init_dmproc(); kk_tsl_t *dev_shadow[30] = {NULL};
kk_subDb_init(); mid_ctx_t *mid_ctx = kk_mid_get_ctx();
kk_heartbeat_init();
mid_ctx->g_mid_dispatch_thread_running = 1; kk_zlog_init("midware");
res = pthread_create(&mid_ctx->g_mid_dispatch_thread, NULL, mid_dispatch_yield, NULL); memset(mid_ctx, 0, sizeof(mid_ctx_t));
if (res < 0) {
ERROR_PRINT("HAL_ThreadCreate mid Failed\n"); kk_set_product_info();
//IOT_Linkkit_Close(mid_ctx->master_devid); kk_tsl_api_init();
return -1; kk_ipc_init(IPC_MID2APP, mid_cb, NULL, NULL);
} kk_ipc_init(IPC_MID2PLAT, mid2p_cb, NULL, "*");
mid_ctx->g_ota_dispatch_thread_running = 1;
res = pthread_create(&mid_ctx->g_ota_dispatch_thread, NULL, ota_dispatch_yield, NULL); kk_init_dmproc();
if (res < 0) { kk_subDb_init();
ERROR_PRINT("HAL_ThreadCreate ota Failed\n"); kk_heartbeat_init();
//IOT_Linkkit_Close(mid_ctx->master_devid); mid_ctx->g_mid_dispatch_thread_running = 1;
return -1; res = pthread_create(&mid_ctx->g_mid_dispatch_thread, NULL, mid_dispatch_yield, NULL);
} if (res < 0) {
ERROR_PRINT("HAL_ThreadCreate mid Failed\n");
// recv gateway add cmd and ack to gateway //IOT_Linkkit_Close(mid_ctx->master_devid);
res = pthread_create(&mid_ctx->g_udp_dispatch_thread, NULL, udp_dispatch_yield, NULL); return -1;
if (res < 0) { }
ERROR_PRINT("HAL_ThreadCreate udp Failed\n"); mid_ctx->g_ota_dispatch_thread_running = 1;
//IOT_Linkkit_Close(mid_ctx->master_devid); res = pthread_create(&mid_ctx->g_ota_dispatch_thread, NULL, ota_dispatch_yield, NULL);
return -1; if (res < 0) {
} ERROR_PRINT("HAL_ThreadCreate ota Failed\n");
//IOT_Linkkit_Close(mid_ctx->master_devid);
mid_ctx->g_ccuProChg_dispatch_thread_running = 1; return -1;
res = pthread_create(&mid_ctx->g_ccuProChg_dispatch_thread, NULL, ccu_property_monitor, NULL); }
if (res < 0) {
ERROR_PRINT("HAL_ThreadCreate Failed\n"); // recv gateway add cmd and ack to gateway
return -1; res = pthread_create(&mid_ctx->g_udp_dispatch_thread, NULL, udp_dispatch_yield, NULL);
} if (res < 0) {
ERROR_PRINT("HAL_ThreadCreate udp Failed\n");
int ct = 0; //IOT_Linkkit_Close(mid_ctx->master_devid);
for (;;) { return -1;
usleep(200000); }
kk_platMsg_dispatch();
/*if (ct == 0){ mid_ctx->g_ccuProChg_dispatch_thread_running = 1;
ct =1; res = pthread_create(&mid_ctx->g_ccuProChg_dispatch_thread, NULL, ccu_property_monitor, NULL);
void* buf = "{\ if (res < 0) {
\"info\": {\ ERROR_PRINT("HAL_ThreadCreate Failed\n");
\"msgtype\": \"/thing/topo/add\",\ return -1;
\"productType\": \"gw\",\ }
\"productCode\": \"2\",\
\"deviceCode\": \"1122334455667788\"\ int ct = 0;
},\ for (;;) {
\"payload\": {\ usleep(200000);
\"msgId\": \"1\",\ kk_platMsg_dispatch();
\"version\": \"1.0\",\ /*if (ct == 0){
\"params\": {\ ct =1;
\"deviceCode\": \"588E81FFFED3834A\",\ void* buf = "{\
\"productCode\": \"24\",\ \"info\": {\
\"mac\": \"588E81FFFED3834A\"\ \"msgtype\": \"/thing/topo/add\",\
}\ \"productType\": \"gw\",\
}\ \"productCode\": \"2\",\
}"; \"deviceCode\": \"1122334455667788\"\
},\
kk_platMsg_handle(buf, "1122334455667788"); \"payload\": {\
//kk_set_tsl_by_productKey("a1OYuSallan","model.json"); \"msgId\": \"1\",\
//kk_mid_subdev_add("a1OYuSallan","allanWno8yDdsjCX15iq","","aabbccddeeff1122"); \"version\": \"1.0\",\
}*/ \"params\": {\
\"deviceCode\": \"588E81FFFED3834A\",\
} \"productCode\": \"24\",\
} \"mac\": \"588E81FFFED3834A\"\
}\
}\
}";
kk_platMsg_handle(buf, "1122334455667788");
//kk_set_tsl_by_productKey("a1OYuSallan","model.json");
//kk_mid_subdev_add("a1OYuSallan","allanWno8yDdsjCX15iq","","aabbccddeeff1122");
}*/
}
}
# This file was generated by Simplicity Studio from the following template: # This file was generated by Simplicity Studio from the following template:
# app/esf_common/template/unix/Makefile # app/esf_common/template/unix/Makefile
# Please do not edit it directly. # Please do not edit it directly.
# This Makefile defines how to build a unix host application connected to an # This Makefile defines how to build a unix host application connected to an
# Ember NCP EZSP device. This also works for Windows machines running # Ember NCP EZSP device. This also works for Windows machines running
# Cygwin. # Cygwin.
# Variables # Variables
# If using a different compiler than GCC, you can create a makefile # If using a different compiler than GCC, you can create a makefile
# that overrides the following variables. # that overrides the following variables.
# COMPILER - Compiler binary path # COMPILER - Compiler binary path
# LINKER - Linker binary path # LINKER - Linker binary path
# ARCHIVE - Optional archive tool, only necessary for building a library. # ARCHIVE - Optional archive tool, only necessary for building a library.
# Must also set GENERATE_LIBRARY := 1 in your makefile. # Must also set GENERATE_LIBRARY := 1 in your makefile.
# COMPILER_INCLUDES - Any additional compiler includes each prefixed with -I # COMPILER_INCLUDES - Any additional compiler includes each prefixed with -I
# COMPILER_DEFINES - Any additional compiler defines each prefixed with -D # COMPILER_DEFINES - Any additional compiler defines each prefixed with -D
# COMPILER_FLAGS - The set of compiler flags (not including dependencies) # COMPILER_FLAGS - The set of compiler flags (not including dependencies)
# LINKER_FLAGS - The set of linker flags # LINKER_FLAGS - The set of linker flags
# ARCHIVE_FLAGS - The set of archive tool flags. # ARCHIVE_FLAGS - The set of archive tool flags.
# DEPENDENCY_FLAGS - The set of dependency generation flags used to generate # DEPENDENCY_FLAGS - The set of dependency generation flags used to generate
# dependencies at the same time compilation is executed. # dependencies at the same time compilation is executed.
# DEPENDENCY_POST_PROCESS - An optional post processing step for massaging # DEPENDENCY_POST_PROCESS - An optional post processing step for massaging
# generated dependencies. Only necessary when using a compiler on the # generated dependencies. Only necessary when using a compiler on the
# non-native platform (e.g. Windows compiler on Linux) # non-native platform (e.g. Windows compiler on Linux)
# PLATFORM_HEADER_FILE - The header file defining the basic int8u, int32u, # PLATFORM_HEADER_FILE - The header file defining the basic int8u, int32u,
# and other typedefs and platform elements. # and other typedefs and platform elements.
# ARCHIVE_EXTENSION - The file extension for archives if not using the standard # ARCHIVE_EXTENSION - The file extension for archives if not using the standard
# .a file extension. # .a file extension.
# #
# Then pass the makefile to this one on the command line with: # Then pass the makefile to this one on the command line with:
# "make -C app/builder/Z3GatewayHost INCLUDE_MAKEFILE=my-custom.mak" # "make -C app/builder/Z3GatewayHost INCLUDE_MAKEFILE=my-custom.mak"
# or # or
# "cd app/builder/Z3GatewayHost; make INCLUDE_MAKEFILE=my-custom.mak" # "cd app/builder/Z3GatewayHost; make INCLUDE_MAKEFILE=my-custom.mak"
# #
ifdef INCLUDE_MAKEFILE ifdef INCLUDE_MAKEFILE
include $(INCLUDE_MAKEFILE) include $(INCLUDE_MAKEFILE)
endif endif
COMPILER ?= gcc COMPILER ?= gcc
LINKER ?= gcc LINKER ?= gcc
ARCHIVE ?= ar ARCHIVE ?= ar
STD ?= gnu99 STD ?= gnu99
ARCHIVE_EXTENSION ?= .a ARCHIVE_EXTENSION ?= .a
CC = $(COMPILER) CC = $(COMPILER)
LD = $(LINKER) LD = $(LINKER)
SHELL = /bin/sh SHELL = /bin/sh
ifneq ($(CURDIR),$(shell dirname '$(abspath $(lastword $(MAKEFILE_LIST)))')) ifneq ($(CURDIR),$(shell dirname '$(abspath $(lastword $(MAKEFILE_LIST)))'))
$(error This makefile should only be invoked under its current directory ($(shell dirname '$(abspath $(lastword $(MAKEFILE_LIST)))'))) $(error This makefile should only be invoked under its current directory ($(shell dirname '$(abspath $(lastword $(MAKEFILE_LIST)))')))
endif endif
COMPILER_INCLUDES ?= COMPILER_INCLUDES ?=
INCLUDES= \ INCLUDES= \
$(COMPILER_INCLUDES) \ $(COMPILER_INCLUDES) \
-I./../../.. \ -I./../../.. \
-I./../../../protocol/zigbee/app/framework \ -I./../../../protocol/zigbee/app/framework \
-I./../../../protocol/zigbee/app/framework/../.. \ -I./../../../protocol/zigbee/app/framework/../.. \
-I./../../../protocol/zigbee/app/framework/../../stack \ -I./../../../protocol/zigbee/app/framework/../../stack \
-I./../../../protocol/zigbee/app/framework/../util \ -I./../../../protocol/zigbee/app/framework/../util \
-I./../../../protocol/zigbee/app/framework/../util/common \ -I./../../../protocol/zigbee/app/framework/../util/common \
-I./../../../protocol/zigbee/app/framework/../util/ezsp \ -I./../../../protocol/zigbee/app/framework/../util/ezsp \
-I./../../../protocol/zigbee/app/framework/../util/serial \ -I./../../../protocol/zigbee/app/framework/../util/serial \
-I./../../../protocol/zigbee/app/framework/../util/zigbee-framework \ -I./../../../protocol/zigbee/app/framework/../util/zigbee-framework \
-I./../../../protocol/zigbee/app/framework/cli \ -I./../../../protocol/zigbee/app/framework/cli \
-I./../../../protocol/zigbee/app/framework/include \ -I./../../../protocol/zigbee/app/framework/include \
-I./../../../protocol/zigbee/app/framework/security \ -I./../../../protocol/zigbee/app/framework/security \
-I./../../../protocol/zigbee/app/framework/plugin/network-creator \ -I./../../../protocol/zigbee/app/framework/plugin/network-creator \
-I./../../../protocol/zigbee/app/framework/plugin/network-creator-security\ -I./../../../protocol/zigbee/app/framework/plugin/network-creator-security\
-I./../../../protocol/zigbee/app/framework/util \ -I./../../../protocol/zigbee/app/framework/util \
-I./../../../app/builder/Z3GatewayHost \ -I./../../../app/builder/Z3GatewayHost \
-I./../../../platform/base/hal \ -I./../../../platform/base/hal \
-I./../../../platform/base/hal/plugin \ -I./../../../platform/base/hal/plugin \
-I./../../../platform/base/hal/.. \ -I./../../../platform/base/hal/.. \
-I./../../../platform/base/hal/micro/generic \ -I./../../../platform/base/hal/micro/generic \
-I./../../../platform/base/hal/micro/unix/host \ -I./../../../platform/base/hal/micro/unix/host \
-I../../../platform/base/hal/micro/unix/host/board \ -I../../../platform/base/hal/micro/unix/host/board \
-I./rpc_api/inc -I./rpc_api/inc
\ \
APP_BUILDER_OUTPUT_DIRECTORY=. APP_BUILDER_OUTPUT_DIRECTORY=.
APP_BUILDER_CONFIG_HEADER=$(APP_BUILDER_OUTPUT_DIRECTORY)/Z3GatewayHost.h APP_BUILDER_CONFIG_HEADER=$(APP_BUILDER_OUTPUT_DIRECTORY)/Z3GatewayHost.h
APP_BUILDER_STORAGE_FILE=$(APP_BUILDER_OUTPUT_DIRECTORY)/Z3GatewayHost_endpoint_config.h APP_BUILDER_STORAGE_FILE=$(APP_BUILDER_OUTPUT_DIRECTORY)/Z3GatewayHost_endpoint_config.h
PLATFORM_HEADER_FILE ?= \"../../../platform/base/hal/micro/unix/compiler/gcc.h\" PLATFORM_HEADER_FILE ?= \"../../../platform/base/hal/micro/unix/compiler/gcc.h\"
DEFINES = \ DEFINES = \
$(COMPILER_DEFINES) \ $(COMPILER_DEFINES) \
-DUNIX \ -DUNIX \
-DUNIX_HOST \ -DUNIX_HOST \
-DPHY_NULL \ -DPHY_NULL \
-DCONFIGURATION_HEADER=\"../../../protocol/zigbee/app/framework/util/config.h\" \ -DCONFIGURATION_HEADER=\"../../../protocol/zigbee/app/framework/util/config.h\" \
-DEZSP_HOST \ -DEZSP_HOST \
-DGATEWAY_APP \ -DGATEWAY_APP \
-DZA_GENERATED_HEADER=\"$(APP_BUILDER_CONFIG_HEADER)\" \ -DZA_GENERATED_HEADER=\"$(APP_BUILDER_CONFIG_HEADER)\" \
-DATTRIBUTE_STORAGE_CONFIGURATION=\"$(APP_BUILDER_STORAGE_FILE)\" \ -DATTRIBUTE_STORAGE_CONFIGURATION=\"$(APP_BUILDER_STORAGE_FILE)\" \
-DPLATFORM_HEADER=$(PLATFORM_HEADER_FILE) \ -DPLATFORM_HEADER=$(PLATFORM_HEADER_FILE) \
-DBOARD_HOST \ -DBOARD_HOST \
-DBOARD_HEADER=\"app/builder/Z3GatewayHost/Z3GatewayHost_board.h\" \ -DBOARD_HEADER=\"app/builder/Z3GatewayHost/Z3GatewayHost_board.h\" \
-DEM_AF_TEST_HARNESS_CODE \ -DEM_AF_TEST_HARNESS_CODE \
-DEM_AF_LINK_M \ -DEM_AF_LINK_M \
-DEM_AF_LINK_PTHREAD \ -DEM_AF_LINK_PTHREAD \
-DEMBER_AF_API_EMBER_TYPES=\"stack/include/ember-types.h\" \ -DEMBER_AF_API_EMBER_TYPES=\"stack/include/ember-types.h\" \
-DEMBER_AF_API_DEBUG_PRINT=\"app/framework/util/print.h\" \ -DEMBER_AF_API_DEBUG_PRINT=\"app/framework/util/print.h\" \
-DEMBER_AF_API_AF_HEADER=\"app/framework/include/af.h\" \ -DEMBER_AF_API_AF_HEADER=\"app/framework/include/af.h\" \
-DEMBER_AF_API_AF_SECURITY_HEADER=\"app/framework/security/af-security.h\" \ -DEMBER_AF_API_AF_SECURITY_HEADER=\"app/framework/security/af-security.h\" \
-DEMBER_STACK_ZIGBEE \ -DEMBER_STACK_ZIGBEE \
-DEZSP_ASH \ -DEZSP_ASH \
COMPILER_FLAGS ?= \ COMPILER_FLAGS ?= \
-Wall \ -Wall \
-ggdb \ -ggdb \
-O0 \ -O0 \
-std=$(STD) -std=$(STD)
APPLICATION_FILES= \ APPLICATION_FILES= \
../../../app/builder/Z3GatewayHost/afv2-bookkeeping.c \ ../../../app/builder/Z3GatewayHost/afv2-bookkeeping.c \
../../../app/builder/Z3GatewayHost/call-command-handler.c \ ../../../app/builder/Z3GatewayHost/call-command-handler.c \
../../../app/builder/Z3GatewayHost/callback-stub.c \ ../../../app/builder/Z3GatewayHost/callback-stub.c \
../../../app/builder/Z3GatewayHost/stack-handler-stub.c \ ../../../app/builder/Z3GatewayHost/stack-handler-stub.c \
../../../app/builder/Z3GatewayHost/cli.c \ ../../../app/builder/Z3GatewayHost/cli.c \
../../../app/builder/Z3GatewayHost/Z3GatewayHost_callbacks.c \ ../../../app/builder/Z3GatewayHost/Z3GatewayHost_callbacks.c \
../../../protocol/zigbee/app/framework/cli/core-cli.c \ ../../../protocol/zigbee/app/framework/cli/core-cli.c \
../../../protocol/zigbee/app/framework/cli/network-cli.c \ ../../../protocol/zigbee/app/framework/cli/network-cli.c \
../../../protocol/zigbee/app/framework/cli/option-cli.c \ ../../../protocol/zigbee/app/framework/cli/option-cli.c \
../../../protocol/zigbee/app/framework/cli/plugin-cli.c \ ../../../protocol/zigbee/app/framework/cli/plugin-cli.c \
../../../protocol/zigbee/app/framework/cli/security-cli.c \ ../../../protocol/zigbee/app/framework/cli/security-cli.c \
../../../protocol/zigbee/app/framework/cli/zcl-cli.c \ ../../../protocol/zigbee/app/framework/cli/zcl-cli.c \
../../../protocol/zigbee/app/framework/cli/zdo-cli.c \ ../../../protocol/zigbee/app/framework/cli/zdo-cli.c \
../../../protocol/zigbee/app/framework/security/af-node.c \ ../../../protocol/zigbee/app/framework/security/af-node.c \
../../../protocol/zigbee/app/framework/security/af-security-common.c \ ../../../protocol/zigbee/app/framework/security/af-security-common.c \
../../../protocol/zigbee/app/framework/security/af-trust-center.c \ ../../../protocol/zigbee/app/framework/security/af-trust-center.c \
../../../protocol/zigbee/app/framework/security/crypto-state.c \ ../../../protocol/zigbee/app/framework/security/crypto-state.c \
../../../protocol/zigbee/app/framework/util/af-event.c \ ../../../protocol/zigbee/app/framework/util/af-event.c \
../../../protocol/zigbee/app/framework/util/af-main-common.c \ ../../../protocol/zigbee/app/framework/util/af-main-common.c \
../../../protocol/zigbee/app/framework/util/af-main-host.c \ ../../../protocol/zigbee/app/framework/util/af-main-host.c \
../../../protocol/zigbee/app/framework/util/attribute-size.c \ ../../../protocol/zigbee/app/framework/util/attribute-size.c \
../../../protocol/zigbee/app/framework/util/attribute-storage.c \ ../../../protocol/zigbee/app/framework/util/attribute-storage.c \
../../../protocol/zigbee/app/framework/util/attribute-table.c \ ../../../protocol/zigbee/app/framework/util/attribute-table.c \
../../../protocol/zigbee/app/framework/util/client-api.c \ ../../../protocol/zigbee/app/framework/util/client-api.c \
../../../protocol/zigbee/app/framework/util/message.c \ ../../../protocol/zigbee/app/framework/util/message.c \
../../../protocol/zigbee/app/framework/util/multi-network.c \ ../../../protocol/zigbee/app/framework/util/multi-network.c \
../../../protocol/zigbee/app/framework/util/print.c \ ../../../protocol/zigbee/app/framework/util/print.c \
../../../protocol/zigbee/app/framework/util/print-formatter.c \ ../../../protocol/zigbee/app/framework/util/print-formatter.c \
../../../protocol/zigbee/app/framework/util/process-cluster-message.c \ ../../../protocol/zigbee/app/framework/util/process-cluster-message.c \
../../../protocol/zigbee/app/framework/util/process-global-message.c \ ../../../protocol/zigbee/app/framework/util/process-global-message.c \
../../../protocol/zigbee/app/framework/util/service-discovery-common.c \ ../../../protocol/zigbee/app/framework/util/service-discovery-common.c \
../../../protocol/zigbee/app/framework/util/service-discovery-host.c \ ../../../protocol/zigbee/app/framework/util/service-discovery-host.c \
../../../protocol/zigbee/app/framework/util/time-util.c \ ../../../protocol/zigbee/app/framework/util/time-util.c \
../../../protocol/zigbee/app/framework/util/util.c \ ../../../protocol/zigbee/app/framework/util/util.c \
../../../protocol/zigbee/app/framework/../util/common/library.c \ ../../../protocol/zigbee/app/framework/../util/common/library.c \
../../../protocol/zigbee/app/framework/../util/serial/command-interpreter2.c \ ../../../protocol/zigbee/app/framework/../util/serial/command-interpreter2.c \
../../../protocol/zigbee/app/framework/../util/zigbee-framework/zigbee-device-common.c \ ../../../protocol/zigbee/app/framework/../util/zigbee-framework/zigbee-device-common.c \
../../../protocol/zigbee/app/framework/../util/zigbee-framework/zigbee-device-host.c \ ../../../protocol/zigbee/app/framework/../util/zigbee-framework/zigbee-device-host.c \
../../../protocol/zigbee/app/framework/../../stack/framework/event-control.c \ ../../../protocol/zigbee/app/framework/../../stack/framework/event-control.c \
../../../platform/base/hal/micro/generic/led-stub.c \ ../../../platform/base/hal/micro/generic/led-stub.c \
../../../platform/base/hal/micro/generic/mem-util.c \ ../../../platform/base/hal/micro/generic/mem-util.c \
../../../platform/base/hal/plugin/antenna-stub/antenna-stub.c \ ../../../platform/base/hal/plugin/antenna-stub/antenna-stub.c \
../../../platform/base/hal/plugin/buzzer-stub/buzzer-stub.c \ ../../../platform/base/hal/plugin/buzzer-stub/buzzer-stub.c \
../../../protocol/zigbee/app/framework/plugin/address-table/address-table.c \ ../../../protocol/zigbee/app/framework/plugin/address-table/address-table.c \
../../../protocol/zigbee/app/framework/plugin/address-table/address-table-cli.c \ ../../../protocol/zigbee/app/framework/plugin/address-table/address-table-cli.c \
../../../protocol/zigbee/app/framework/plugin/basic/basic.c \ ../../../protocol/zigbee/app/framework/plugin/basic/basic.c \
../../../protocol/zigbee/app/framework/plugin/button-joining/button-joining.c \ ../../../protocol/zigbee/app/framework/plugin/button-joining/button-joining.c \
../../../protocol/zigbee/app/framework/plugin/button-joining/button-joining-cli.c \ ../../../protocol/zigbee/app/framework/plugin/button-joining/button-joining-cli.c \
../../../util/third_party/cjson/cJSON.c \ ../../../util/third_party/cjson/cJSON.c \
../../../util/third_party/cjson/cJSON_Utils.c \ ../../../util/third_party/cjson/cJSON_Utils.c \
../../../protocol/zigbee/app/framework/plugin/color-control-server/color-control-server.c \ ../../../protocol/zigbee/app/framework/plugin/color-control-server/color-control-server.c \
../../../protocol/zigbee/app/framework/plugin/command-relay/command-relay.c \ ../../../protocol/zigbee/app/framework/plugin/command-relay/command-relay.c \
../../../protocol/zigbee/app/framework/plugin/command-relay/command-relay-cli.c \ ../../../protocol/zigbee/app/framework/plugin/command-relay/command-relay-cli.c \
../../../protocol/zigbee/app/framework/plugin/concentrator/concentrator-support.c \ ../../../protocol/zigbee/app/framework/plugin/concentrator/concentrator-support.c \
../../../protocol/zigbee/app/framework/plugin/concentrator/concentrator-support-cli.c \ ../../../protocol/zigbee/app/framework/plugin/concentrator/concentrator-support-cli.c \
../../../protocol/zigbee/app/framework/plugin/concentrator/source-route-common.c \ ../../../protocol/zigbee/app/framework/plugin/concentrator/source-route-common.c \
../../../protocol/zigbee/app/framework/plugin/concentrator/source-route-host.c \ ../../../protocol/zigbee/app/framework/plugin/concentrator/source-route-host.c \
../../../protocol/zigbee/app/framework/plugin/counters/counters-cli.c \ ../../../protocol/zigbee/app/framework/plugin/counters/counters-cli.c \
../../../protocol/zigbee/app/framework/plugin/counters/counters-ota-host.c \ ../../../protocol/zigbee/app/framework/plugin/counters/counters-ota-host.c \
../../../protocol/zigbee/app/framework/plugin/counters/counters-host.c \ ../../../protocol/zigbee/app/framework/plugin/counters/counters-host.c \
../../../protocol/zigbee/app/framework/plugin/device-table/device-table.c \ ../../../protocol/zigbee/app/framework/plugin/device-table/device-table.c \
../../../protocol/zigbee/app/framework/plugin/device-table/device-table-cli.c \ ../../../protocol/zigbee/app/framework/plugin/device-table/device-table-cli.c \
../../../protocol/zigbee/app/framework/plugin/device-table/device-table-discovery.c \ ../../../protocol/zigbee/app/framework/plugin/device-table/device-table-discovery.c \
../../../protocol/zigbee/app/framework/plugin/device-table/device-table-tracking.c \ ../../../protocol/zigbee/app/framework/plugin/device-table/device-table-tracking.c \
../../../protocol/zigbee/app/framework/plugin/ezmode-commissioning/ez-mode.c \ ../../../protocol/zigbee/app/framework/plugin/ezmode-commissioning/ez-mode.c \
../../../protocol/zigbee/app/framework/plugin/ezmode-commissioning/ez-mode-cli.c \ ../../../protocol/zigbee/app/framework/plugin/ezmode-commissioning/ez-mode-cli.c \
../../../protocol/zigbee/app/util/ezsp/ezsp-callbacks.c \ ../../../protocol/zigbee/app/util/ezsp/ezsp-callbacks.c \
../../../protocol/zigbee/app/util/ezsp/ezsp-enum-decode.c \ ../../../protocol/zigbee/app/util/ezsp/ezsp-enum-decode.c \
../../../protocol/zigbee/app/util/ezsp/ezsp-frame-utilities.c \ ../../../protocol/zigbee/app/util/ezsp/ezsp-frame-utilities.c \
../../../protocol/zigbee/app/util/ezsp/ezsp.c \ ../../../protocol/zigbee/app/util/ezsp/ezsp.c \
../../../protocol/zigbee/app/ezsp-host/ezsp-host-io.c \ ../../../protocol/zigbee/app/ezsp-host/ezsp-host-io.c \
../../../protocol/zigbee/app/ezsp-host/ezsp-host-queues.c \ ../../../protocol/zigbee/app/ezsp-host/ezsp-host-queues.c \
../../../protocol/zigbee/app/ezsp-host/ezsp-host-ui.c \ ../../../protocol/zigbee/app/ezsp-host/ezsp-host-ui.c \
../../../protocol/zigbee/app/util/ezsp/serial-interface-uart.c \ ../../../protocol/zigbee/app/util/ezsp/serial-interface-uart.c \
../../../protocol/zigbee/app/ezsp-host/ash/ash-host-ui.c \ ../../../protocol/zigbee/app/ezsp-host/ash/ash-host-ui.c \
../../../protocol/zigbee/app/ezsp-host/ash/ash-host.c \ ../../../protocol/zigbee/app/ezsp-host/ash/ash-host.c \
../../../platform/base/hal/micro/generic/ash-common.c \ ../../../platform/base/hal/micro/generic/ash-common.c \
../../../protocol/zigbee/app/framework/plugin-host/file-descriptor-dispatch/file-descriptor-dispatch.c \ ../../../protocol/zigbee/app/framework/plugin-host/file-descriptor-dispatch/file-descriptor-dispatch.c \
../../../protocol/zigbee/app/framework/plugin/form-and-join/form-and-join-afv2.c \ ../../../protocol/zigbee/app/framework/plugin/form-and-join/form-and-join-afv2.c \
../../../protocol/zigbee/app/util/common/form-and-join.c \ ../../../protocol/zigbee/app/util/common/form-and-join.c \
../../../protocol/zigbee/app/util/common/form-and-join-host-adapter.c \ ../../../protocol/zigbee/app/util/common/form-and-join-host-adapter.c \
../../../protocol/zigbee/app/framework/plugin-host/gateway/gateway-support.c \ ../../../protocol/zigbee/app/framework/plugin-host/gateway/gateway-support.c \
../../../protocol/zigbee/app/framework/plugin-host/gateway/backchannel-support.c \ ../../../protocol/zigbee/app/framework/plugin-host/gateway/backchannel-support.c \
../../../protocol/zigbee/app/framework/plugin-host/gateway/gateway-support-cli.c \ ../../../protocol/zigbee/app/framework/plugin-host/gateway/gateway-support-cli.c \
../../../protocol/zigbee/app/framework/plugin/green-power-client/green-power-client.c \ ../../../protocol/zigbee/app/framework/plugin/green-power-client/green-power-client.c \
../../../protocol/zigbee/app/framework/plugin/green-power-client/green-power-client-cli.c \ ../../../protocol/zigbee/app/framework/plugin/green-power-client/green-power-client-cli.c \
../../../protocol/zigbee/app/framework/plugin/green-power-common/green-power-common.c \ ../../../protocol/zigbee/app/framework/plugin/green-power-common/green-power-common.c \
../../../protocol/zigbee/stack/gp/gp-util.c \ ../../../protocol/zigbee/stack/gp/gp-util.c \
../../../protocol/zigbee/app/framework/plugin/heartbeat/heartbeat.c \ ../../../protocol/zigbee/app/framework/plugin/heartbeat/heartbeat.c \
../../../protocol/zigbee/app/framework/plugin/ias-zone-client/ias-zone-client.c \ ../../../protocol/zigbee/app/framework/plugin/ias-zone-client/ias-zone-client.c \
../../../protocol/zigbee/app/framework/plugin/ias-zone-client/ias-zone-client-cli.c \ ../../../protocol/zigbee/app/framework/plugin/ias-zone-client/ias-zone-client-cli.c \
../../../protocol/zigbee/app/framework/plugin/identify/identify.c \ ../../../protocol/zigbee/app/framework/plugin/identify/identify.c \
../../../protocol/zigbee/app/framework/plugin/identify/identify-cli.c \ ../../../protocol/zigbee/app/framework/plugin/identify/identify-cli.c \
../../../protocol/zigbee/app/framework/plugin/identify-feedback/identify-feedback.c \ ../../../protocol/zigbee/app/framework/plugin/identify-feedback/identify-feedback.c \
../../../protocol/zigbee/app/framework/plugin/level-control/level-control.c \ ../../../protocol/zigbee/app/framework/plugin/level-control/level-control.c \
../../../util/plugin/plugin-common/linked-list/linked-list.c \ ../../../util/plugin/plugin-common/linked-list/linked-list.c \
../../../protocol/zigbee/app/framework/plugin-host/ncp-configuration/ncp-configuration.c \ ../../../protocol/zigbee/app/framework/plugin-host/ncp-configuration/ncp-configuration.c \
../../../protocol/zigbee/app/framework/plugin/network-creator/network-creator.c \ ../../../protocol/zigbee/app/framework/plugin/network-creator/network-creator.c \
../../../protocol/zigbee/app/framework/plugin/network-creator/network-creator-cli.c \ ../../../protocol/zigbee/app/framework/plugin/network-creator/network-creator-cli.c \
../../../protocol/zigbee/app/framework/plugin/network-creator-security/network-creator-security.c \ ../../../protocol/zigbee/app/framework/plugin/network-creator-security/network-creator-security.c \
../../../protocol/zigbee/app/framework/plugin/network-creator-security/network-creator-security-cli.c \ ../../../protocol/zigbee/app/framework/plugin/network-creator-security/network-creator-security-cli.c \
../../../protocol/zigbee/app/framework/plugin/network-find/network-find.c \ ../../../protocol/zigbee/app/framework/plugin/network-find/network-find.c \
../../../protocol/zigbee/app/framework/plugin/network-find/network-find-cli.c \ ../../../protocol/zigbee/app/framework/plugin/network-find/network-find-cli.c \
../../../protocol/zigbee/app/framework/plugin/on-off/on-off.c \ ../../../protocol/zigbee/app/framework/plugin/on-off/on-off.c \
../../../protocol/zigbee/app/framework/plugin/ota-common/ota-common.c \ ../../../protocol/zigbee/app/framework/plugin/ota-common/ota-common.c \
../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server.c \ ../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server.c \
../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-page-request.c \ ../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-page-request.c \
../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-cli.c \ ../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-cli.c \
../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-dynamic-block-period.c \ ../../../protocol/zigbee/app/framework/plugin/ota-server/ota-server-dynamic-block-period.c \
../../../protocol/zigbee/app/framework/plugin/ota-server-policy/ota-server-policy.c \ ../../../protocol/zigbee/app/framework/plugin/ota-server-policy/ota-server-policy.c \
../../../protocol/zigbee/app/framework/plugin/ota-storage-common/ota-storage-common.c \ ../../../protocol/zigbee/app/framework/plugin/ota-storage-common/ota-storage-common.c \
../../../protocol/zigbee/app/framework/plugin/ota-storage-common/ota-storage-common-cli.c \ ../../../protocol/zigbee/app/framework/plugin/ota-storage-common/ota-storage-common-cli.c \
../../../protocol/zigbee/app/framework/plugin/ota-storage-posix-filesystem/ota-storage-linux.c \ ../../../protocol/zigbee/app/framework/plugin/ota-storage-posix-filesystem/ota-storage-linux.c \
../../../protocol/zigbee/app/framework/plugin/permit-join-manager/permit-join-manager.c \ ../../../protocol/zigbee/app/framework/plugin/permit-join-manager/permit-join-manager.c \
../../../protocol/zigbee/app/framework/plugin/poll-control-client/poll-control-client.c \ ../../../protocol/zigbee/app/framework/plugin/poll-control-client/poll-control-client.c \
../../../protocol/zigbee/app/framework/plugin/poll-control-client/poll-control-client-cli.c \ ../../../protocol/zigbee/app/framework/plugin/poll-control-client/poll-control-client-cli.c \
../../../protocol/zigbee/app/framework/plugin/reporting/reporting.c \ ../../../protocol/zigbee/app/framework/plugin/reporting/reporting.c \
../../../protocol/zigbee/app/framework/plugin/reporting/reporting-cli.c \ ../../../protocol/zigbee/app/framework/plugin/reporting/reporting-cli.c \
../../../protocol/zigbee/app/framework/plugin/reporting/reporting-default-configuration.c \ ../../../protocol/zigbee/app/framework/plugin/reporting/reporting-default-configuration.c \
../../../protocol/zigbee/app/framework/plugin/scan-dispatch/scan-dispatch.c \ ../../../protocol/zigbee/app/framework/plugin/scan-dispatch/scan-dispatch.c \
../../../protocol/zigbee/app/util/ezsp/secure-ezsp-stub.c \ ../../../protocol/zigbee/app/util/ezsp/secure-ezsp-stub.c \
../../../protocol/zigbee/app/framework/plugin-host/security-support/security-support.c \ ../../../protocol/zigbee/app/framework/plugin-host/security-support/security-support.c \
../../../protocol/zigbee/tool/random/random-linux.c \ ../../../protocol/zigbee/tool/random/random-linux.c \
../../../protocol/zigbee/app/framework/plugin/simple-main/simple-main.c \ ../../../protocol/zigbee/app/framework/plugin/simple-main/simple-main.c \
../../../protocol/zigbee/app/framework/plugin/simple-metering-client/simple-metering-client.c \ ../../../protocol/zigbee/app/framework/plugin/simple-metering-client/simple-metering-client.c \
../../../protocol/zigbee/app/framework/plugin/simple-metering-client/simple-metering-client-cli.c \ ../../../protocol/zigbee/app/framework/plugin/simple-metering-client/simple-metering-client-cli.c \
../../../protocol/zigbee/app/framework/plugin/stack-diagnostics/stack-diagnostics.c \ ../../../protocol/zigbee/app/framework/plugin/stack-diagnostics/stack-diagnostics.c \
../../../protocol/zigbee/app/framework/plugin/test-harness/test-harness.c \ ../../../protocol/zigbee/app/framework/plugin/test-harness/test-harness.c \
../../../protocol/zigbee/app/framework/plugin/test-harness/read-write-attributes.c \ ../../../protocol/zigbee/app/framework/plugin/test-harness/read-write-attributes.c \
../../../protocol/zigbee/app/framework/plugin/test-harness/test-harness-host.c \ ../../../protocol/zigbee/app/framework/plugin/test-harness/test-harness-host.c \
../../../protocol/zigbee/app/framework/plugin/time-server/time-server.c \ ../../../protocol/zigbee/app/framework/plugin/time-server/time-server.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-cli.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-cli.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-cli-posix.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-cli-posix.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-posix.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-backup/trust-center-backup-posix.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-broadcast/trust-center-nwk-key-update-broadcast.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-broadcast/trust-center-nwk-key-update-broadcast.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-periodic/trust-center-nwk-key-update-periodic.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-periodic/trust-center-nwk-key-update-periodic.c \
../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-unicast/trust-center-nwk-key-update-unicast.c \ ../../../protocol/zigbee/app/framework/plugin/trust-center-nwk-key-update-unicast/trust-center-nwk-key-update-unicast.c \
../../../platform/base/hal/micro/generic/crc.c \ ../../../platform/base/hal/micro/generic/crc.c \
../../../platform/base/hal/micro/generic/endian.c \ ../../../platform/base/hal/micro/generic/endian.c \
../../../platform/base/hal/micro/generic/random.c \ ../../../platform/base/hal/micro/generic/random.c \
../../../platform/base/hal/micro/generic/system-timer.c \ ../../../platform/base/hal/micro/generic/system-timer.c \
../../../platform/base/hal/micro/unix/host/micro.c \ ../../../platform/base/hal/micro/unix/host/micro.c \
../../../platform/base/hal/micro/unix/host/token-def-unix.c \ ../../../platform/base/hal/micro/unix/host/token-def-unix.c \
../../../platform/base/hal/micro/unix/host/token.c \ ../../../platform/base/hal/micro/unix/host/token.c \
../../../platform/base/hal/plugin/serial/ember-printf-convert.c \ ../../../platform/base/hal/plugin/serial/ember-printf-convert.c \
../../../protocol/zigbee/app/util/serial/linux-serial.c \ ../../../protocol/zigbee/app/util/serial/linux-serial.c \
./jsonrpc/jsonrpc-c.c\ ./jsonrpc/jsonrpc-c.c\
./jsonrpc/rpccJSON.c\ ./jsonrpc/rpccJSON.c\
./yjq_ezsp.c\ ./yjq_ezsp.c\
./kk_test.c\ ./kk_test.c\
./kk_sub_tsl.c\ ./kk_sub_tsl.c\
./kk_tsl_zigbee_map.c\ ./kk_tsl_zigbee_map.c\
./rpc_api/src/rpc_common.c\ ./rpc_api/src/rpc_common.c\
./rpc_api/src/rpc_onoff.c\ ./rpc_api/src/rpc_onoff.c\
./rpc_api/src/rpc_global_cmd.c\ ./rpc_api/src/rpc_global_cmd.c\
./rpc_api/src/rpc_interface_parse.c\ ./rpc_api/src/rpc_interface_parse.c\
./rpc_api/src/color_control/rpc_colorControl.c\ ./rpc_api/src/color_control/rpc_colorControl.c\
./rpc_api/src/rpc_network_operate.c\ ./rpc_api/src/rpc_network_operate.c\
LIBRARIES = \ LIBRARIES = \
\ \
OUTPUT_DIR=$(APP_BUILDER_OUTPUT_DIRECTORY)/build OUTPUT_DIR=$(APP_BUILDER_OUTPUT_DIRECTORY)/build
OUTPUT_DIR_CREATED= $(OUTPUT_DIR)/created OUTPUT_DIR_CREATED= $(OUTPUT_DIR)/created
EXE_DIR=$(OUTPUT_DIR)/exe EXE_DIR=$(OUTPUT_DIR)/exe
# Build a list of object files from the source file list, but all objects # Build a list of object files from the source file list, but all objects
# live in the $(OUTPUT_DIR) above. The list of object files # live in the $(OUTPUT_DIR) above. The list of object files
# created assumes that the file part of the filepath is unique # created assumes that the file part of the filepath is unique
# (i.e. the bar.c of foo/bar.c is unique across all sub-directories included). # (i.e. the bar.c of foo/bar.c is unique across all sub-directories included).
APPLICATION_OBJECTS= $(shell echo $(APPLICATION_FILES) | xargs -n1 echo | sed -e 's^.*/\(.*\)\.c^$(OUTPUT_DIR)/\1\.o^') APPLICATION_OBJECTS= $(shell echo $(APPLICATION_FILES) | xargs -n1 echo | sed -e 's^.*/\(.*\)\.c^$(OUTPUT_DIR)/\1\.o^')
ifdef GENERATE_LIBRARY ifdef GENERATE_LIBRARY
TARGET_FILE= $(EXE_DIR)/Z3GatewayHost$(ARCHIVE_EXTENSION) TARGET_FILE= $(EXE_DIR)/Z3GatewayHost$(ARCHIVE_EXTENSION)
else else
TARGET_FILE= $(EXE_DIR)/Z3GatewayHost TARGET_FILE= $(EXE_DIR)/Z3GatewayHost
endif endif
# -MMD and -MF generates Makefile dependencies while at the same time compiling. # -MMD and -MF generates Makefile dependencies while at the same time compiling.
# -MP notes to add a dummy 'build' rule for each header file. This # -MP notes to add a dummy 'build' rule for each header file. This
# prevent a problem where a removed header file will generate an error because a # prevent a problem where a removed header file will generate an error because a
# dependency references it but it can't be found anymore. # dependency references it but it can't be found anymore.
DEPENDENCY_FLAGS ?= -MMD -MP -MF $(@D)/$(@F:.o=.d) DEPENDENCY_FLAGS ?= -MMD -MP -MF $(@D)/$(@F:.o=.d)
# Dependency post process is a way to massage generated dependencies. # Dependency post process is a way to massage generated dependencies.
# This is necessary for example when using Make under Cygwin but compiling # This is necessary for example when using Make under Cygwin but compiling
# using a native Windows compiler that generates native Windows paths # using a native Windows compiler that generates native Windows paths
# that Cygwin will choke on. Or if compiling on Linux using Wine to run a # that Cygwin will choke on. Or if compiling on Linux using Wine to run a
# Windows compiler, a similar problem can occur. # Windows compiler, a similar problem can occur.
DEPENDENCY_POST_PROCESS ?= DEPENDENCY_POST_PROCESS ?=
CPPFLAGS= $(INCLUDES) $(DEFINES) $(COMPILER_FLAGS) $(DEPENDENCY_FLAGS) CPPFLAGS= $(INCLUDES) $(DEFINES) $(COMPILER_FLAGS) $(DEPENDENCY_FLAGS)
LINKER_FLAGS ?= LINKER_FLAGS ?=
ifdef NO_READLINE ifdef NO_READLINE
CPPFLAGS += -DNO_READLINE CPPFLAGS += -DNO_READLINE
else else
LINKER_FLAGS += \ LINKER_FLAGS += \
-lreadline \ -lreadline \
-lncurses -lncurses
endif endif
# Conditionally include the math library if EM_AF_LINK_M is defined. # Conditionally include the math library if EM_AF_LINK_M is defined.
ifeq ($(findstring -DEM_AF_LINK_M,$(DEFINES)),-DEM_AF_LINK_M) ifeq ($(findstring -DEM_AF_LINK_M,$(DEFINES)),-DEM_AF_LINK_M)
LINKER_FLAGS += \ LINKER_FLAGS += \
-lm -lm
endif endif
# Conditionally include the POSIX threads library if EM_AF_LINK_PTHREAD is # Conditionally include the POSIX threads library if EM_AF_LINK_PTHREAD is
# defined. # defined.
ifeq ($(findstring -DEM_AF_LINK_PTHREAD,$(DEFINES)),-DEM_AF_LINK_PTHREAD) ifeq ($(findstring -DEM_AF_LINK_PTHREAD,$(DEFINES)),-DEM_AF_LINK_PTHREAD)
LINKER_FLAGS += \ LINKER_FLAGS += \
-lpthread -lpthread
endif endif
ARCHIVE_FLAGS ?= rus ARCHIVE_FLAGS ?= rus
# Rules # Rules
.PHONY: all .PHONY: all
all: $(TARGET_FILE) all: $(TARGET_FILE)
ifneq ($(MAKECMDGOALS),clean) ifneq ($(MAKECMDGOALS),clean)
-include $(APPLICATION_OBJECTS:.o=.d) -include $(APPLICATION_OBJECTS:.o=.d)
endif endif
ifdef GENERATE_LIBRARY ifdef GENERATE_LIBRARY
$(TARGET_FILE): $(APPLICATION_OBJECTS) $(LIBRARIES) $(TARGET_FILE): $(APPLICATION_OBJECTS) $(LIBRARIES)
$(ARCHIVE) $(ARCHIVE_FLAGS) $(TARGET_FILE) $^ $(ARCHIVE) $(ARCHIVE_FLAGS) $(TARGET_FILE) $^
@echo -e '\n$@ build success' @echo -e '\n$@ build success'
else else
$(TARGET_FILE): $(APPLICATION_OBJECTS) $(LIBRARIES) $(TARGET_FILE): $(APPLICATION_OBJECTS) $(LIBRARIES)
$(LD) $^ $(LINKER_FLAGS) -lm -L. -lapi_com -lnanomsg -lanl -pthread -lev -ltinfo -o $(TARGET_FILE) $(LD) $^ $(LINKER_FLAGS) -lm -L. -lapi_com -lnanomsg -lkk_hal -lanl -pthread -lev -ltinfo -o $(TARGET_FILE)
@echo -e '\n$@ build success' @echo -e '\n$@ build success'
endif endif
.PHONY: clean .PHONY: clean
clean: clean:
rm -rf $(OUTPUT_DIR) rm -rf $(OUTPUT_DIR)
$(OUTPUT_DIR_CREATED): $(OUTPUT_DIR_CREATED):
mkdir -p $(OUTPUT_DIR) mkdir -p $(OUTPUT_DIR)
mkdir -p $(EXE_DIR) mkdir -p $(EXE_DIR)
touch $(OUTPUT_DIR_CREATED) touch $(OUTPUT_DIR_CREATED)
# To facilitate generating all output files in a single output directory, we # To facilitate generating all output files in a single output directory, we
# must create separate .o and .d rules for all the different sub-directories # must create separate .o and .d rules for all the different sub-directories
# used by the source files. # used by the source files.
# If additional directories are added that are not already in the # If additional directories are added that are not already in the
# $(APPLICATION_FILES) above, new rules will have to be created below. # $(APPLICATION_FILES) above, new rules will have to be created below.
# Object File rules # Object File rules
define make-deps define make-deps
$(OUTPUT_DIR)/$(notdir $(1:%.c=%.o)): $1 | $(OUTPUT_DIR_CREATED) $(OUTPUT_DIR)/$(notdir $(1:%.c=%.o)): $1 | $(OUTPUT_DIR_CREATED)
endef endef
$(foreach d, $(APPLICATION_FILES), $(eval $(call make-deps,$d))) $(foreach d, $(APPLICATION_FILES), $(eval $(call make-deps,$d)))
%.o : %.o :
$(CC) $(CPPFLAGS) -c $< -o $(OUTPUT_DIR)/$(@F) $(CC) $(CPPFLAGS) -c $< -o $(OUTPUT_DIR)/$(@F)
$(DEPENDENCY_POST_PROCESS) $(DEPENDENCY_POST_PROCESS)
# Dependency rules # Dependency rules
# No explicit rules. Dependencies are generated as part of the compile step. # No explicit rules. Dependencies are generated as part of the compile step.
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <errno.h> #include <errno.h>
#include <string.h> #include <string.h>
#include <sys/types.h> #include <sys/types.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <netdb.h> #include <netdb.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <signal.h> #include <signal.h>
#include <time.h> #include <time.h>
#include <fcntl.h> #include <fcntl.h>
#include "RPC_API.h" #include "RPC_API.h"
#include "./rpc_api/inc/rpc_interface_parse.h" #include "./rpc_api/inc/rpc_interface_parse.h"
#include "rpc_network_operate.h" #include "rpc_network_operate.h"
#include "rpc_global_cmd.h" #include "rpc_global_cmd.h"
#include "rpc_colorControl.h" #include "rpc_colorControl.h"
#include "rpc_onoff.h" #include "rpc_onoff.h"
#include "kk_test.h" #include "kk_test.h"
//#include "kk_log.h" //#include "kk_log.h"
static struct jrpc_server my_server; static struct jrpc_server my_server;
cJSON * test_func(jrpc_context * ctx, cJSON * params, cJSON *id); cJSON * test_func(jrpc_context * ctx, cJSON * params, cJSON *id);
typedef cJSON(*rpc_function)(jrpc_context * ctx, cJSON * params, cJSON *id); typedef cJSON(*rpc_function)(jrpc_context * ctx, cJSON * params, cJSON *id);
typedef struct{ typedef struct{
rpc_function func; rpc_function func;
char * name; char * name;
}rpc_table_s; }rpc_table_s;
rpc_table_s rpc_table[]={ rpc_table_s rpc_table[]={
{test_func,"test_func"}, {test_func,"test_func"},
RPC_KK_TEST_FUNCTION_TABLE, RPC_KK_TEST_FUNCTION_TABLE,
RPC_NETWORK_FUNCTION_TABLE, RPC_NETWORK_FUNCTION_TABLE,
RPC_COMMON_FUNCTION_TABLE, RPC_COMMON_FUNCTION_TABLE,
RPC_GLOBAL_COMMAND_FUNCTION_TABLE, RPC_GLOBAL_COMMAND_FUNCTION_TABLE,
RPC_COLOR_CONTROL_COMMAND_FUNCTION_TABLE, RPC_COLOR_CONTROL_COMMAND_FUNCTION_TABLE,
RPC_OnOff_COMMAND_FUNCTION_TABLE, RPC_OnOff_COMMAND_FUNCTION_TABLE,
}; };
void rpcInterfaceParse(void) void rpcInterfaceParse(void)
{ {
emberAfAppPrint( "Thread rpc Interface Parse create\n" ); emberAfAppPrint( "Thread rpc Interface Parse create\n" );
jrpc_server_init(&my_server, PORT); jrpc_server_init(&my_server, PORT);
emberAfAppPrint("sizeof(rpc_table)=%d,sizeof(rpc_table_s)=%d,%d\n",sizeof(rpc_table),sizeof(rpc_table_s),sizeof(rpc_table)/sizeof(rpc_table_s)); emberAfAppPrint("sizeof(rpc_table)=%d,sizeof(rpc_table_s)=%d,%d\n",sizeof(rpc_table),sizeof(rpc_table_s),sizeof(rpc_table)/sizeof(rpc_table_s));
for(int i=0;i<sizeof(rpc_table)/sizeof(rpc_table_s);i++){ for(int i=0;i<sizeof(rpc_table)/sizeof(rpc_table_s);i++){
emberAfAppPrint("i=%d,%s\r\n",i,rpc_table[i].name); emberAfAppPrint("i=%d,%s\r\n",i,rpc_table[i].name);
jrpc_register_procedure(&my_server, rpc_table[i].func, rpc_table[i].name, NULL ); jrpc_register_procedure(&my_server, rpc_table[i].func, rpc_table[i].name, NULL );
} }
jrpc_server_run(&my_server); jrpc_server_run(&my_server);
jrpc_server_destroy(&my_server); jrpc_server_destroy(&my_server);
} }
cJSON * test_func(jrpc_context * ctx, cJSON * params, cJSON *id) { cJSON * test_func(jrpc_context * ctx, cJSON * params, cJSON *id) {
cJSON * item1 = rpc_cJSON_CreateObject(); cJSON * item1 = rpc_cJSON_CreateObject();
cJSON * item2 = rpc_cJSON_CreateObject(); cJSON * item2 = rpc_cJSON_CreateObject();
rpc_cJSON_AddNullToObject(item1,"Null"); rpc_cJSON_AddNullToObject(item1,"Null");
rpc_cJSON_AddTrueToObject(item1,"True"); rpc_cJSON_AddTrueToObject(item1,"True");
rpc_cJSON_AddFalseToObject(item1,"False"); rpc_cJSON_AddFalseToObject(item1,"False");
rpc_cJSON_AddNumberToObject(item1, "Number",12345); rpc_cJSON_AddNumberToObject(item1, "Number",12345);
rpc_cJSON_AddStringToObject(item1, "String","hello world!"); rpc_cJSON_AddStringToObject(item1, "String","hello world!");
rpc_cJSON_AddNullToObject(item2,"1"); rpc_cJSON_AddNullToObject(item2,"1");
rpc_cJSON_AddTrueToObject(item2,"2"); rpc_cJSON_AddTrueToObject(item2,"2");
rpc_cJSON_AddFalseToObject(item2,"3"); rpc_cJSON_AddFalseToObject(item2,"3");
rpc_cJSON_AddNumberToObject(item2, "4",12345); rpc_cJSON_AddNumberToObject(item2, "4",12345);
rpc_cJSON_AddStringToObject(item2, "5","hello world!"); rpc_cJSON_AddStringToObject(item2, "5","hello world!");
rpc_cJSON_AddItemToObject(item1,"hhhhhh",item2); rpc_cJSON_AddItemToObject(item1,"hhhhhh",item2);
return item1; return item1;
} }
static int send_result_resp(cJSON * result, static int send_result_resp(cJSON * result,
cJSON * id) { cJSON * id) {
int return_value = 0; int return_value = 0;
cJSON *info_root = rpc_cJSON_CreateObject(); cJSON *info_root = rpc_cJSON_CreateObject();
if(info_root){ if(info_root){
rpc_cJSON_AddStringToObject(info_root, "msgType", ""); rpc_cJSON_AddStringToObject(info_root, "msgType", "");
rpc_cJSON_AddStringToObject(info_root, "productType", ""); rpc_cJSON_AddStringToObject(info_root, "productType", "");
rpc_cJSON_AddStringToObject(info_root, "productCode", ""); rpc_cJSON_AddStringToObject(info_root, "productCode", "");
rpc_cJSON_AddStringToObject(info_root, "deviceCode", ""); rpc_cJSON_AddStringToObject(info_root, "deviceCode", "");
} }
cJSON *payload_root = rpc_cJSON_CreateObject(); cJSON *payload_root = rpc_cJSON_CreateObject();
if(payload_root){ if(payload_root){
rpc_cJSON_AddItemToObject(payload_root, "msgId", id); rpc_cJSON_AddItemToObject(payload_root, "msgId", id);
rpc_cJSON_AddItemToObject(payload_root, "code", result); rpc_cJSON_AddItemToObject(payload_root, "code", result);
rpc_cJSON_AddStringToObject(payload_root, "data", "{}"); rpc_cJSON_AddStringToObject(payload_root, "data", "{}");
} }
cJSON *result_root = rpc_cJSON_CreateObject(); cJSON *result_root = rpc_cJSON_CreateObject();
if(result_root){ if(result_root){
rpc_cJSON_AddItemToObject(result_root, "info", info_root); rpc_cJSON_AddItemToObject(result_root, "info", info_root);
rpc_cJSON_AddItemToObject(result_root, "payload", payload_root); rpc_cJSON_AddItemToObject(result_root, "payload", payload_root);
} }
char * str_result = rpc_cJSON_Print(result_root); char * str_result = rpc_cJSON_Print(result_root);
printf("send json:\n%s\n",str_result); printf("send json:\n%s\n",str_result);
return_value = kk_sendData2CCU(str_result, strlen(str_result)+1); return_value = kk_sendData2CCU(str_result, strlen(str_result)+1);
free(str_result); free(str_result);
rpc_cJSON_Delete(result_root); rpc_cJSON_Delete(result_root);
return return_value; return return_value;
} }
static int send_error_resp(int code, char* message, static int send_error_resp(int code, char* message,
cJSON * id) { cJSON * id) {
int return_value = 0; int return_value = 0;
cJSON *edata; cJSON *edata;
cJSON *info_root = rpc_cJSON_CreateObject(); cJSON *info_root = rpc_cJSON_CreateObject();
if(info_root){ if(info_root){
rpc_cJSON_AddStringToObject(info_root, "msgType", ""); rpc_cJSON_AddStringToObject(info_root, "msgType", "");
rpc_cJSON_AddStringToObject(info_root, "productType", ""); rpc_cJSON_AddStringToObject(info_root, "productType", "");
rpc_cJSON_AddStringToObject(info_root, "productCode", ""); rpc_cJSON_AddStringToObject(info_root, "productCode", "");
rpc_cJSON_AddStringToObject(info_root, "deviceCode", ""); rpc_cJSON_AddStringToObject(info_root, "deviceCode", "");
} }
cJSON *payload_root = rpc_cJSON_CreateObject(); cJSON *payload_root = rpc_cJSON_CreateObject();
if(payload_root){ if(payload_root){
rpc_cJSON_AddItemToObject(payload_root, "msgId", id); rpc_cJSON_AddItemToObject(payload_root, "msgId", id);
rpc_cJSON_AddNumberToObject(payload_root, "code", code); rpc_cJSON_AddNumberToObject(payload_root, "code", code);
edata = rpc_cJSON_CreateObject(); edata = rpc_cJSON_CreateObject();
if(edata){ if(edata){
rpc_cJSON_AddStringToObject(edata, "message", message); rpc_cJSON_AddStringToObject(edata, "message", message);
} }
rpc_cJSON_AddItemToObject(payload_root, "data", edata); rpc_cJSON_AddItemToObject(payload_root, "data", edata);
} }
cJSON *result_root = rpc_cJSON_CreateObject(); cJSON *result_root = rpc_cJSON_CreateObject();
if(result_root){ if(result_root){
rpc_cJSON_AddItemToObject(result_root, "info", info_root); rpc_cJSON_AddItemToObject(result_root, "info", info_root);
rpc_cJSON_AddItemToObject(result_root, "payload", payload_root); rpc_cJSON_AddItemToObject(result_root, "payload", payload_root);
} }
char * str_result = rpc_cJSON_Print(result_root); char * str_result = rpc_cJSON_Print(result_root);
//printf("alla=========== :%d\n", strlen(str_result)+1); //printf("alla=========== :%d\n", strlen(str_result)+1);
return_value = kk_sendData2CCU(str_result, strlen(str_result)+1); return_value = kk_sendData2CCU(str_result, strlen(str_result)+1);
printf("send_error_resp:\n%s\n", str_result); printf("send_error_resp:\n%s\n", str_result);
free(str_result); free(str_result);
rpc_cJSON_Delete(result_root); rpc_cJSON_Delete(result_root);
free(message); free(message);
return return_value; return return_value;
} }
static int invoke_procedure(struct jrpc_server *server, static int invoke_procedure(struct jrpc_server *server,
char *name, cJSON *params, cJSON *id,cJSON *mac) { char *name, cJSON *params, cJSON *id,cJSON *mac) {
cJSON *returned = NULL; cJSON *returned = NULL;
int procedure_found = 0; int procedure_found = 0;
jrpc_context ctx; jrpc_context ctx;
ctx.error_code = 0; ctx.error_code = 0;
ctx.error_message = NULL; ctx.error_message = NULL;
int i = server->procedure_count; int i = server->procedure_count;
while (i--) { while (i--) {
if (!strcmp(server->procedures[i].name, name)) { if (!strcmp(server->procedures[i].name, name)) {
procedure_found = 1; procedure_found = 1;
ctx.data = server->procedures[i].data; ctx.data = server->procedures[i].data;
returned = server->procedures[i].function(&ctx, params, id,mac); returned = server->procedures[i].function(&ctx, params, id,mac);
break; break;
} }
} }
if (!procedure_found) if (!procedure_found)
return send_error_resp(JRPC_METHOD_NOT_FOUND, return send_error_resp(JRPC_METHOD_NOT_FOUND,
strdup("Method not found."), id); strdup("Method not found."), id);
else { else {
if (ctx.error_code) if (ctx.error_code)
return send_error_resp(ctx.error_code, ctx.error_message, id); return send_error_resp(ctx.error_code, ctx.error_message, id);
else else
return send_result_resp(returned, id); return send_result_resp(returned, id);
} }
} }
static int eval_request(struct jrpc_server *server, cJSON *root) { static int eval_request(struct jrpc_server *server, cJSON *root) {
cJSON *params, *id,*mac,*info,*msgType,*payload; cJSON *params, *id,*mac,*info,*msgType,*payload;
info = rpc_cJSON_GetObjectItem(root, "info"); info = rpc_cJSON_GetObjectItem(root, "info");
if(info != NULL){ if(info != NULL){
msgType = rpc_cJSON_GetObjectItem(info, "msgType"); msgType = rpc_cJSON_GetObjectItem(info, "msgType");
mac = rpc_cJSON_GetObjectItem(info, "deviceCode"); mac = rpc_cJSON_GetObjectItem(info, "deviceCode");
} }
payload = rpc_cJSON_GetObjectItem(root, "payload"); payload = rpc_cJSON_GetObjectItem(root, "payload");
if(payload != NULL){ if(payload != NULL){
params = rpc_cJSON_GetObjectItem(payload, "params"); params = rpc_cJSON_GetObjectItem(payload, "params");
id = rpc_cJSON_GetObjectItem(payload, "msgId"); id = rpc_cJSON_GetObjectItem(payload, "msgId");
} }
if(id != NULL && params != NULL && msgType != NULL && mac != NULL){ if(id != NULL && params != NULL && msgType != NULL && mac != NULL){
cJSON * id_copy = NULL; cJSON * id_copy = NULL;
id_copy = (id->type == cJSON_String) ? rpc_cJSON_CreateString(id->valuestring) : \ id_copy = (id->type == cJSON_String) ? rpc_cJSON_CreateString(id->valuestring) : \
rpc_cJSON_CreateNumber(id->valueint); rpc_cJSON_CreateNumber(id->valueint);
return invoke_procedure(server, msgType->valuestring, return invoke_procedure(server, msgType->valuestring,
params, id_copy,mac); params, id_copy,mac);
} }
send_error_resp(JRPC_INVALID_REQUEST, send_error_resp(JRPC_INVALID_REQUEST,
strdup("The JSON sent is not a valid Request object."), NULL); strdup("The JSON sent is not a valid Request object."), NULL);
return -1; return -1;
} }
void _cb(void* data){ void _cb(void* data){
if (data != NULL){ if (data != NULL){
//printf("plat2mid_cb: %s RECEIVED \r\n", data); //printf("plat2mid_cb: %s RECEIVED \r\n", data);
cJSON *root; cJSON *root;
char *end_ptr = NULL; char *end_ptr = NULL;
if ((root = rpc_cJSON_Parse_Stream(data, &end_ptr)) != NULL) { if ((root = rpc_cJSON_Parse_Stream(data, &end_ptr)) != NULL) {
if (1) { if (1) {
char * str_result = rpc_cJSON_Print(root); char * str_result = rpc_cJSON_Print(root);
printf("Valid JSON Received:\n%s\n", str_result); printf("Valid JSON Received:\n%s\n", str_result);
free(str_result); free(str_result);
} }
if (root->type == cJSON_Object) { if (root->type == cJSON_Object) {
eval_request(&my_server, root); eval_request(&my_server, root);
} }
//shift processed request, discarding it //shift processed request, discarding it
rpc_cJSON_Delete(root); rpc_cJSON_Delete(root);
} else { } else {
if (1) { if (1) {
printf("INVALID JSON Received:\n---\n%s\n---\n", printf("INVALID JSON Received:\n---\n%s\n---\n",
data); data);
} }
send_error_resp(JRPC_PARSE_ERROR, send_error_resp(JRPC_PARSE_ERROR,
strdup( strdup(
"Parse error. Invalid JSON was received by the server."), "Parse error. Invalid JSON was received by the server."),
NULL); NULL);
} }
} }
} }
int _init_param(struct jrpc_server *server) { int _init_param(struct jrpc_server *server) {
memset(server, 0, sizeof(struct jrpc_server)); memset(server, 0, sizeof(struct jrpc_server));
//kk_zlog_init("paltform"); //kk_zlog_init("paltform");
printf("getenv\r\n"); printf("getenv\r\n");
char * debug_level_env = getenv("HOME"); char * debug_level_env = getenv("HOME");
printf("getenv(JRPC_DEBUG):%s\n", server->debug_level); printf("getenv(JRPC_DEBUG):%s\n", server->debug_level);
if (debug_level_env == NULL) if (debug_level_env == NULL)
server->debug_level = 0; server->debug_level = 0;
else { else {
server->debug_level = strtol(debug_level_env, NULL, 10); server->debug_level = strtol(debug_level_env, NULL, 10);
printf("JSONRPC-C Debug level %d\n", server->debug_level); printf("JSONRPC-C Debug level %d\n", server->debug_level);
} }
server->debug_level = 1; server->debug_level = 1;
return 0; return 0;
} }
char g_mac[19] = {0}; char g_mac[19] = {0};
char* kk_get_gw_mac(){ char* kk_get_gw_mac(){
int cnt = 0; int cnt = 0;
EmberEUI64 eui64; EmberEUI64 eui64;
emberAfGetEui64(eui64); emberAfGetEui64(eui64);
while(eui64[0] ==0 && eui64[1] ==0 && eui64[2] == 0 && cnt++ < 3){ while(eui64[0] ==0 && eui64[1] ==0 && eui64[2] == 0 && cnt++ < 3){
sleep(1); sleep(1);
} }
if (eui64[0] ==0 && eui64[1] ==0 && eui64[2] == 0){ if (eui64[0] ==0 && eui64[1] ==0 && eui64[2] == 0){
printf("get gw mac error !!! \n"); printf("get gw mac error !!! \n");
return NULL; return NULL;
} }
rpc_eui64ToString(eui64,g_mac); rpc_eui64ToString(eui64,g_mac);
return g_mac; return g_mac;
} }
int search_ccu(char devcode[33], char ip[16], int* port){ int search_ccu(char devcode[33], char ip[16], int* port){
char sendCmdFmt[] = "search_kk_ccu|deviceCode=%s;protocol=%s"; char sendCmdFmt[] = "search_kk_ccu|deviceCode=%s;protocol=%s";
char sendMessage[128] = {0}; char sendMessage[128] = {0};
char revMessage[128] = {0}; char revMessage[128] = {0};
int sock; int sock;
int sk_recv; int sk_recv;
int iSendbytes; int iSendbytes;
int iOptval = 1; int iOptval = 1;
int flag; int flag;
int iAddrLength; int iAddrLength;
int recvLen = 0; int recvLen = 0;
struct sockaddr_in Addrto; struct sockaddr_in Addrto;
struct sockaddr_in AddrRev; struct sockaddr_in AddrRev;
char* macString = kk_get_gw_mac(); char* macString = kk_get_gw_mac();
if (macString == NULL){ if (macString == NULL){
printf("[%s] get mac fail\n",__FUNCTION__); printf("[%s] get mac fail\n",__FUNCTION__);
return -1; return -1;
} }
sprintf(sendMessage,sendCmdFmt,macString/*GW_DEVICE_CODE*/,GW2CCU_PROTOCOL); sprintf(sendMessage,sendCmdFmt,macString/*GW_DEVICE_CODE*/,GW2CCU_PROTOCOL);
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{ {
printf("[%s] socket fail\n",__FUNCTION__); printf("[%s] socket fail\n",__FUNCTION__);
return -1; return -1;
} }
if ((sk_recv = socket(AF_INET, SOCK_DGRAM, 0)) == -1) if ((sk_recv = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{ {
printf("[%s] socket sk_recv fail\n",__FUNCTION__); printf("[%s] socket sk_recv fail\n",__FUNCTION__);
close(sock); close(sock);
return -1; return -1;
} }
if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &iOptval, sizeof(int)) < 0) if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &iOptval, sizeof(int)) < 0)
{ {
printf("[%s] setsockopt failed\n",__FUNCTION__); printf("[%s] setsockopt failed\n",__FUNCTION__);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1; return -1;
} }
if (setsockopt(sk_recv, SOL_SOCKET, SO_REUSEADDR, &iOptval, sizeof(int)) < 0) if (setsockopt(sk_recv, SOL_SOCKET, SO_REUSEADDR, &iOptval, sizeof(int)) < 0)
{ {
printf("[%s] setsockopt failed\n",__FUNCTION__); printf("[%s] setsockopt failed\n",__FUNCTION__);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1; return -1;
} }
flag = fcntl(sk_recv, F_GETFL, 0); flag = fcntl(sk_recv, F_GETFL, 0);
if (flag < 0) if (flag < 0)
{ {
printf("[%s] fcntl failed.\n",__FUNCTION__); printf("[%s] fcntl failed.\n",__FUNCTION__);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1;; return -1;;
} }
flag |= O_NONBLOCK; flag |= O_NONBLOCK;
if (fcntl(sk_recv, F_SETFL, flag) < 0) if (fcntl(sk_recv, F_SETFL, flag) < 0)
{ {
printf("[%s] fcntl failed.\n",__FUNCTION__); printf("[%s] fcntl failed.\n",__FUNCTION__);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1; return -1;
} }
memset(&Addrto, 0, sizeof(struct sockaddr_in)); memset(&Addrto, 0, sizeof(struct sockaddr_in));
Addrto.sin_family = AF_INET; Addrto.sin_family = AF_INET;
Addrto.sin_addr.s_addr = inet_addr("255.255.255.255"); Addrto.sin_addr.s_addr = inet_addr("255.255.255.255");
Addrto.sin_port = htons(25556); Addrto.sin_port = htons(25556);
memset(&AddrRev, 0, sizeof(struct sockaddr_in)); memset(&AddrRev, 0, sizeof(struct sockaddr_in));
AddrRev.sin_family = AF_INET; AddrRev.sin_family = AF_INET;
AddrRev.sin_addr.s_addr = INADDR_ANY; AddrRev.sin_addr.s_addr = INADDR_ANY;
AddrRev.sin_port = htons(25555); AddrRev.sin_port = htons(25555);
iAddrLength = sizeof(struct sockaddr); iAddrLength = sizeof(struct sockaddr);
if (bind(sk_recv, (struct sockaddr *)&AddrRev, sizeof(AddrRev)) == -1) if (bind(sk_recv, (struct sockaddr *)&AddrRev, sizeof(AddrRev)) == -1)
{ {
printf("[%s] bind failed!\n",__FUNCTION__); printf("[%s] bind failed!\n",__FUNCTION__);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1; return -1;
} }
while (1) while (1)
{ {
if ((iSendbytes = sendto(sock, sendMessage, strlen(sendMessage)+1, 0, (struct sockaddr*)&Addrto, sizeof(struct sockaddr))) == -1) if ((iSendbytes = sendto(sock, sendMessage, strlen(sendMessage)+1, 0, (struct sockaddr*)&Addrto, sizeof(struct sockaddr))) == -1)
{ {
printf("[%s] sendto fail, errno=%d\n", __FUNCTION__,errno); printf("[%s] sendto fail, errno=%d\n", __FUNCTION__,errno);
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return -1; return -1;
} }
sleep(1); sleep(1);
recvLen = recvfrom(sk_recv, revMessage, sizeof(revMessage), 0, (struct sockaddr *)&AddrRev, &iAddrLength); recvLen = recvfrom(sk_recv, revMessage, sizeof(revMessage), 0, (struct sockaddr *)&AddrRev, &iAddrLength);
if (recvLen > 0){ if (recvLen > 0){
printf("[%s] recv:%s\n", __FUNCTION__, revMessage); printf("[%s] recv:%s\n", __FUNCTION__, revMessage);
//"search_kk_ccu_ack|deviceCode=CCU_66666;ip=192.168.36.128;port=16565" //"search_kk_ccu_ack|deviceCode=CCU_66666;ip=192.168.36.128;port=16565"
if (strstr(revMessage, "search_kk_ccu_ack|") != NULL){ if (strstr(revMessage, "search_kk_ccu_ack|") != NULL){
char* ackConnet = revMessage + strlen("search_kk_ccu_ack|"); char* ackConnet = revMessage + strlen("search_kk_ccu_ack|");
char* tmp = NULL; char* tmp = NULL;
char* endIdx = NULL; char* endIdx = NULL;
int itemLen = 0; int itemLen = 0;
int itemConnetLen = 0; int itemConnetLen = 0;
tmp = strstr(ackConnet, "deviceCode="); tmp = strstr(ackConnet, "deviceCode=");
itemLen = strlen("deviceCode="); itemLen = strlen("deviceCode=");
if (tmp != NULL){ if (tmp != NULL){
endIdx = strstr(tmp, ";"); endIdx = strstr(tmp, ";");
if(endIdx == NULL){ if(endIdx == NULL){
itemConnetLen = strlen(tmp) - itemLen; itemConnetLen = strlen(tmp) - itemLen;
}else{ }else{
itemConnetLen = endIdx - tmp - itemLen; itemConnetLen = endIdx - tmp - itemLen;
} }
memcpy(devcode, tmp + itemLen,itemConnetLen); memcpy(devcode, tmp + itemLen,itemConnetLen);
} }
tmp = strstr(ackConnet, "ip="); tmp = strstr(ackConnet, "ip=");
itemLen = strlen("ip="); itemLen = strlen("ip=");
if (tmp != NULL){ if (tmp != NULL){
endIdx = strstr(tmp, ";"); endIdx = strstr(tmp, ";");
if(endIdx == NULL){ if(endIdx == NULL){
itemConnetLen = strlen(tmp) - itemLen; itemConnetLen = strlen(tmp) - itemLen;
}else{ }else{
itemConnetLen = endIdx - tmp - itemLen; itemConnetLen = endIdx - tmp - itemLen;
} }
memcpy(ip, tmp + itemLen,itemConnetLen); memcpy(ip, tmp + itemLen,itemConnetLen);
} }
tmp = strstr(ackConnet, "port="); tmp = strstr(ackConnet, "port=");
itemLen = strlen("port="); itemLen = strlen("port=");
if (tmp != NULL){ if (tmp != NULL){
endIdx = strstr(tmp, ";"); endIdx = strstr(tmp, ";");
if(endIdx == NULL){ if(endIdx == NULL){
itemConnetLen = strlen(tmp) - itemLen; itemConnetLen = strlen(tmp) - itemLen;
}else{ }else{
itemConnetLen = endIdx - tmp - itemLen; itemConnetLen = endIdx - tmp - itemLen;
} }
char portstr[20] = {0}; char portstr[20] = {0};
memcpy(portstr, tmp + itemLen,itemConnetLen); memcpy(portstr, tmp + itemLen,itemConnetLen);
*port = atoi(portstr); *port = atoi(portstr);
} }
//memcpy(ip, inet_ntoa(AddrRev.sin_addr), strlen(inet_ntoa(AddrRev.sin_addr))); //memcpy(ip, inet_ntoa(AddrRev.sin_addr), strlen(inet_ntoa(AddrRev.sin_addr)));
printf(" recv deviceCode:%s ip:%s port:%d \n", devcode, ip, *port); printf(" recv deviceCode:%s ip:%s port:%d \n", devcode, ip, *port);
break; break;
} }
} }
} }
close(sock); close(sock);
close(sk_recv); close(sk_recv);
return 0; return 0;
} }
#define GW_PRODUCT_CODE "2" #define GW_PRODUCT_CODE "2"
#define GW_MAC GW_DEVICE_CODE #define GW_MAC GW_DEVICE_CODE
void* _msg_topo_add(){ void* _msg_topo_add(){
char msgFmt[] = "{\"info\":{\"msgtype\":\"/thing/topo/add\",\"productCode\":\"%s\",\"deviceCode\":\"%s\"},\ char msgFmt[] = "{\"info\":{\"msgtype\":\"/thing/topo/add\",\"productCode\":\"%s\",\"deviceCode\":\"%s\"},\
\"payload\":{\"msgId\":\"%d\",\"version\":\"1.0\",\"params\":{\"deviceCode\":\"%s\",\"productCode\":\"%s\",\"mac\":\"%s\"}}}"; \"payload\":{\"msgId\":\"%d\",\"version\":\"1.0\",\"params\":{\"deviceCode\":\"%s\",\"productCode\":\"%s\",\"mac\":\"%s\"}}}";
char msg[520] = {0}; char msg[520] = {0};
char* macString = kk_get_gw_mac(); char* macString = kk_get_gw_mac();
if (macString == NULL){ if (macString == NULL){
printf("[%s] get mac fail\n",__FUNCTION__); printf("[%s] get mac fail\n",__FUNCTION__);
return NULL; return NULL;
} }
sprintf(msg, msgFmt, GW_PRODUCT_CODE, macString, 1, macString/*GW_DEVICE_CODE*/, GW_PRODUCT_CODE,macString); sprintf(msg, msgFmt, GW_PRODUCT_CODE, macString, 1, macString/*GW_DEVICE_CODE*/, GW_PRODUCT_CODE,macString);
cJSON* msgObj = cJSON_Parse(msg); cJSON* msgObj = cJSON_Parse(msg);
char* outbuf = cJSON_Print(msgObj); char* outbuf = cJSON_Print(msgObj);
cJSON_Delete(msgObj); cJSON_Delete(msgObj);
return outbuf; return outbuf;
} }
void* _msg_event_property_post(char ip[16], int port){ void* _msg_event_property_post(char ip[16], int port){
char msgFmt[] = "{\"info\":{\"msgtype\":\"/thing/event/property/post\",\"productCode\":\"%s\",\"deviceCode\":\"%s\"},\ char msgFmt[] = "{\"info\":{\"msgtype\":\"/thing/event/property/post\",\"productCode\":\"%s\",\"deviceCode\":\"%s\"},\
\"payload\":{\"msgId\":\"%d\",\"version\":\"1.0\",\"params\":{\"NetChannelState\":%d,\"WhiteListState\":%d,\ \"payload\":{\"msgId\":\"%d\",\"version\":\"1.0\",\"params\":{\"NetChannelState\":%d,\"WhiteListState\":%d,\
\"OnlineDetectionState\":%d,\"SN\":\"%s\",\"IPAddress\":\"%s\",\"MACAddress\":\"%s\",\"Port\":%d},\ \"OnlineDetectionState\":%d,\"SN\":\"%s\",\"IPAddress\":\"%s\",\"MACAddress\":\"%s\",\"Port\":%d},\
\"time\":1524448722000,\"method\":\"thing.event.property.post\"}\ \"time\":1524448722000,\"method\":\"thing.event.property.post\"}\
}"; }";
char msg[620] = {0}; char msg[620] = {0};
char* macString = kk_get_gw_mac(); char* macString = kk_get_gw_mac();
if (macString == NULL){ if (macString == NULL){
printf("[%s] get mac fail\n",__FUNCTION__); printf("[%s] get mac fail\n",__FUNCTION__);
return NULL; return NULL;
} }
sprintf(msg, msgFmt, GW_PRODUCT_CODE, macString/*GW_DEVICE_CODE*/, sprintf(msg, msgFmt, GW_PRODUCT_CODE, macString/*GW_DEVICE_CODE*/,
1, 0, 0, 0, "12345", ip,macString, port); 1, 0, 0, 0, "12345", ip,macString, port);
cJSON* msgObj = cJSON_Parse(msg); cJSON* msgObj = cJSON_Parse(msg);
char* outbuf = cJSON_Print(msgObj); char* outbuf = cJSON_Print(msgObj);
cJSON_Delete(msgObj); cJSON_Delete(msgObj);
return outbuf; return outbuf;
} }
void ipcHandle(void) void ipcHandle(void)
{ {
char deviceCode[33] = {0}; char deviceCode[33] = {0};
char ip[16] = {0}; char ip[16] = {0};
int port = 0; int port = 0;
emberAfAppPrint( "Thread rpc Interface Parse create\n" ); emberAfAppPrint( "Thread rpc Interface Parse create\n" );
search_ccu(deviceCode, ip, &port); search_ccu(deviceCode, ip, &port);
char* macString = kk_get_gw_mac(); char* macString = kk_get_gw_mac();
if (macString == NULL){ if (macString == NULL){
printf("[%s] get mac fail, exit pthread !!!!!!!!!!!!!!!!!\n",__FUNCTION__); printf("[%s] get mac fail, exit pthread !!!!!!!!!!!!!!!!!\n",__FUNCTION__);
return; return;
} }
_init_param(&my_server); _init_param(&my_server);
if(strcmp(GW2CCU_PROTOCOL, "tcp") == 0){ if(strcmp(GW2CCU_PROTOCOL, "tcp") == 0){
kk_tcp_client_init(ip, port, _cb); kk_tcp_client_init(ip, port, _cb);
}else{ }else{
kk_ipc_init(IPC_PLAT2MID, _cb, macString/*GW_DEVICE_CODE*/, ip); kk_ipc_init(IPC_PLAT2MID, _cb, macString/*GW_DEVICE_CODE*/, ip);
} }
emberAfAppPrint("sizeof(rpc_table)=%d,sizeof(rpc_table_s)=%d,%d\n",sizeof(rpc_table),sizeof(rpc_table_s),sizeof(rpc_table)/sizeof(rpc_table_s)); emberAfAppPrint("sizeof(rpc_table)=%d,sizeof(rpc_table_s)=%d,%d\n",sizeof(rpc_table),sizeof(rpc_table_s),sizeof(rpc_table)/sizeof(rpc_table_s));
for(int i=0;i<sizeof(rpc_table)/sizeof(rpc_table_s);i++){ for(int i=0;i<sizeof(rpc_table)/sizeof(rpc_table_s);i++){
emberAfAppPrint("i=%d,%s\r\n",i,rpc_table[i].name); emberAfAppPrint("i=%d,%s\r\n",i,rpc_table[i].name);
jrpc_register_procedure(&my_server, rpc_table[i].func, rpc_table[i].name, NULL ); jrpc_register_procedure(&my_server, rpc_table[i].func, rpc_table[i].name, NULL );
} }
//send add gw to ccu //send add gw to ccu
char* outbuf = _msg_topo_add(); char* outbuf = _msg_topo_add();
if (outbuf == NULL){ if (outbuf == NULL){
printf("[%s] topo add msg failed, exit\n",__FUNCTION__); printf("[%s] topo add msg failed, exit\n",__FUNCTION__);
return; return;
} }
if (strcmp(GW2CCU_PROTOCOL, "tcp") != 0){ if (strcmp(GW2CCU_PROTOCOL, "tcp") != 0){
printf("check nanomsg is connect(%d) \n", kk_ipc_isconnect(IPC_PLAT2MID)); printf("check nanomsg is connect(%d) \n", kk_ipc_isconnect(IPC_PLAT2MID));
} }
kk_sendData2CCU(outbuf, strlen(outbuf)); kk_sendData2CCU(outbuf, strlen(outbuf));
free(outbuf); free(outbuf);
int cnt = 0; int cnt = 0;
//handle procidure //handle procidure
while(1){ while(1){
// //
usleep(20000); usleep(20000);
cnt++; cnt++;
if (cnt == 2){ if (cnt == 2){
sleep(1); sleep(1);
char* postmsg = _msg_event_property_post(ip,port); char gwIp[17] = {0};
if (outbuf == NULL){ HAL_Get_IP(gwIp,NULL);
char* postmsg = _msg_event_property_post(gwIp,port);
printf("[%s] property_post msg failed\n",__FUNCTION__); if (outbuf == NULL){
continue;
} printf("[%s] property_post msg failed\n",__FUNCTION__);
kk_sendData2CCU(postmsg, strlen(postmsg)); continue;
free(postmsg); }
} kk_sendData2CCU(postmsg, strlen(postmsg));
free(postmsg);
}
}
//jrpc_server_run(&my_server);
//jrpc_server_destroy(&my_server); }
//jrpc_server_run(&my_server);
} //jrpc_server_destroy(&my_server);
}
int jrpc_send_msg(cJSON * msgJson) {
int return_value = 0;
int jrpc_send_msg(cJSON * msgJson) {
char * str_result = rpc_cJSON_Print(msgJson); int return_value = 0;
emberAfAppPrintln("send json:\n%s\n",str_result); char * str_result = rpc_cJSON_Print(msgJson);
emberAfAppPrintln("send json:\n%s\n",str_result);
return_value = kk_sendData2CCU(str_result, strlen(str_result)+1);
free(str_result);
return return_value; return_value = kk_sendData2CCU(str_result, strlen(str_result)+1);
} free(str_result);
return return_value;
#define ATTRIBUTE_BUFFER_ATTRIBUTEID_ID 1 }
#define ATTRIBUTE_BUFFER_REPORT_DATA_TYPE 2
#define ATTRIBUTE_BUFFER_REPORT_DATA_VALUE 3 #define ATTRIBUTE_BUFFER_ATTRIBUTEID_ID 1
#define ATTRIBUTE_BUFFER_REPORT_DATA_TYPE 2
// Attribute reading buffer location definitions #define ATTRIBUTE_BUFFER_REPORT_DATA_VALUE 3
#define ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS 0
#define ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS 1 // Attribute reading buffer location definitions
#define ATTRIBUTE_BUFFER_SUCCESS_CODE 2 #define ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS 0
#define ATTRIBUTE_BUFFER_DATA_TYPE 3 #define ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS 1
#define ATTRIBUTE_BUFFER_DATA_START 4 #define ATTRIBUTE_BUFFER_SUCCESS_CODE 2
#define ATTRIBUTE_BUFFER_DATA_TYPE 3
static void rpc_send_message(cJSON *data,char *method) #define ATTRIBUTE_BUFFER_DATA_START 4
{
cJSON *item = rpc_cJSON_CreateObject(); static void rpc_send_message(cJSON *data,char *method)
rpc_cJSON_AddStringToObject(item, "jsonrpc", "2.0"); {
rpc_cJSON_AddStringToObject(item, "method",method); cJSON *item = rpc_cJSON_CreateObject();
rpc_cJSON_AddItemToObject(item, "params", data); rpc_cJSON_AddStringToObject(item, "jsonrpc", "2.0");
rpc_cJSON_AddStringToObject(item, "method",method);
char* p = rpc_cJSON_Print(item); rpc_cJSON_AddItemToObject(item, "params", data);
emberAfAppPrintln("send send json:\n%s\n",p);
free(p); char* p = rpc_cJSON_Print(item);
emberAfAppPrintln("send send json:\n%s\n",p);
jrpc_send_msg(item); free(p);
} jrpc_send_msg(item);
void rpc_read_attribute_response(cJSON *data)
{ }
rpc_send_message(data,"read_attribute_response"); void rpc_read_attribute_response(cJSON *data)
} {
rpc_send_message(data,"read_attribute_response");
void rpc_report_attribute(cJSON *data) }
{
rpc_send_message(data,"report_attribute"); void rpc_report_attribute(cJSON *data)
} {
void rpc_report_devices(cJSON *data) rpc_send_message(data,"report_attribute");
{ }
rpc_send_message(data,"report_devices"); void rpc_report_devices(cJSON *data)
} {
void rpc_control_devices(cJSON *data,char *method) rpc_send_message(data,"report_devices");
{ }
rpc_send_message(data,method); void rpc_control_devices(cJSON *data,char *method)
} {
rpc_send_message(data,method);
}
bool rpc_ReportAttributesCallback(EmberAfClusterId clusterId,
uint8_t * buffer,
uint16_t bufLen) bool rpc_ReportAttributesCallback(EmberAfClusterId clusterId,
{ uint8_t * buffer,
EmberEUI64 nodeEui64; uint16_t bufLen)
EmberAfAttributeId attributeId; {
EmberNodeId nodeId = emberAfCurrentCommand()->source; EmberEUI64 nodeEui64;
uint8_t ep = emberAfCurrentCommand()->apsFrame->sourceEndpoint; EmberAfAttributeId attributeId;
emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64); EmberNodeId nodeId = emberAfCurrentCommand()->source;
uint8_t * bufferTemp; uint8_t ep = emberAfCurrentCommand()->apsFrame->sourceEndpoint;
uint8_t * bufferPtr = buffer; emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64);
uint8_t i, bufferSize,typeSize; uint8_t * bufferTemp;
uint8_t * bufferPtr = buffer;
uint8_t dataLen,dataType; uint8_t i, bufferSize,typeSize;
uint8_t *dataPtr;
uint8_t dataLen,dataType;
kk_print_debug("\n********************report callback**********************\n"); uint8_t *dataPtr;
emberAfAppPrint("[ ");
emberAfAppPrintBuffer(buffer,bufLen,true); kk_print_debug("\n********************report callback**********************\n");
emberAfAppPrint("]\n"); emberAfAppPrint("[ ");
emberAfAppPrintBuffer(buffer,bufLen,true);
if (bufLen == 0) { emberAfAppPrint("]\n");
emberAfAppPrintln("Report attributes callback: zero length buffer");
return false; if (bufLen == 0) {
} emberAfAppPrintln("Report attributes callback: zero length buffer");
return false;
kk_print_debug("\nmac:"); }
emberAfPrintBigEndianEui64(nodeEui64);
emberAfAppPrintln(",EP=%d,cluster=0x%04X\n",ep,clusterId); kk_print_debug("\nmac:");
emberAfPrintBigEndianEui64(nodeEui64);
emberAfAppPrintln(",EP=%d,cluster=0x%04X\n",ep,clusterId);
for (i = 0; i < bufLen - 3; ) {
dataType = bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE];
if(emberAfIsStringAttributeType(dataType)){ for (i = 0; i < bufLen - 3; ) {
dataLen = bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_VALUE ]; dataType = bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE];
typeSize = 1; if(emberAfIsStringAttributeType(dataType)){
}else if(emberAfIsLongStringAttributeType(dataType)){ dataLen = bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_VALUE ];
dataLen = HIGH_LOW_TO_INT(bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE + 2], typeSize = 1;
bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE + 1]); }else if(emberAfIsLongStringAttributeType(dataType)){
typeSize = 2; dataLen = HIGH_LOW_TO_INT(bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE + 2],
}else { bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE + 1]);
typeSize = 0; typeSize = 2;
dataLen = emberAfGetDataSize( }else {
bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]); typeSize = 0;
} dataLen = emberAfGetDataSize(
dataPtr = &bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_VALUE]; bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]);
}
bufferSize = ATTRIBUTE_BUFFER_REPORT_DATA_VALUE + dataLen + typeSize; dataPtr = &bufferPtr[ATTRIBUTE_BUFFER_REPORT_DATA_VALUE];
bufferTemp = (uint8_t*)malloc(bufferSize);
memcpy(bufferTemp, bufferPtr, bufferSize); bufferSize = ATTRIBUTE_BUFFER_REPORT_DATA_VALUE + dataLen + typeSize;
bufferTemp = (uint8_t*)malloc(bufferSize);
bufferPtr +=bufferSize; memcpy(bufferTemp, bufferPtr, bufferSize);
i +=bufferSize;
bufferPtr +=bufferSize;
emberAfAppPrintln("i=%d,bufferSize=%d\n",i,bufferSize); i +=bufferSize;
emberAfAppPrintln("Reported attribute: 0x%02X%02X, Type: %02X", emberAfAppPrintln("i=%d,bufferSize=%d\n",i,bufferSize);
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS], emberAfAppPrintln("Reported attribute: 0x%02X%02X, Type: %02X",
bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]); bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS],
bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]);
attributeId = HIGH_LOW_TO_INT(bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS]);
emberAfAppPrintln("attributeId=0x%x",attributeId);
attributeId = HIGH_LOW_TO_INT(bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS]);
if(emberAfDeviceTableGetEui64FromNodeId(nodeId,nodeEui64)){ emberAfAppPrintln("attributeId=0x%x",attributeId);
emberAfAppPrintln("nodeId=0x%x",nodeId);
kk_dispatch_report_attribute(nodeEui64,ep,clusterId,attributeId,dataType,dataLen,dataPtr); if(emberAfDeviceTableGetEui64FromNodeId(nodeId,nodeEui64)){
} emberAfAppPrintln("nodeId=0x%x",nodeId);
kk_dispatch_report_attribute(nodeEui64,ep,clusterId,attributeId,dataType,dataLen,dataPtr);
}
free(bufferTemp);
}
free(bufferTemp);
return false; }
}
return false;
bool rpc_ReadAttributesResponseCallback(EmberAfClusterId clusterId, }
uint8_t *buffer,
uint16_t bufLen) bool rpc_ReadAttributesResponseCallback(EmberAfClusterId clusterId,
{ uint8_t *buffer,
EmberEUI64 nodeEui64; uint16_t bufLen)
EmberNodeId nodeId = emberAfCurrentCommand()->source; {
uint8_t ep = emberAfCurrentCommand()->apsFrame->sourceEndpoint; EmberEUI64 nodeEui64;
emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64); EmberNodeId nodeId = emberAfCurrentCommand()->source;
uint8_t * bufferTemp; uint8_t ep = emberAfCurrentCommand()->apsFrame->sourceEndpoint;
uint8_t * bufferPtr = buffer; emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64);
uint8_t i, bufferSize,typeSize; uint8_t * bufferTemp;
uint8_t cnt=1; uint8_t * bufferPtr = buffer;
uint8_t Status; uint8_t i, bufferSize,typeSize;
kk_print_debug("\n********************read attributes response callback**********************\n"); uint8_t cnt=1;
emberAfAppPrint("[ "); uint8_t Status;
emberAfAppPrintBuffer(buffer,bufLen,true); kk_print_debug("\n********************read attributes response callback**********************\n");
emberAfAppPrint("]\n"); emberAfAppPrint("[ ");
emberAfAppPrintBuffer(buffer,bufLen,true);
if (bufLen == 0) { emberAfAppPrint("]\n");
emberAfAppPrintln("read attributes response callback: zero length buffer");
return false; if (bufLen == 0) {
} emberAfAppPrintln("read attributes response callback: zero length buffer");
return false;
kk_print_debug("\nmac:"); }
emberAfPrintBigEndianEui64(nodeEui64);
emberAfAppPrintln(",EP=%d,cluster=0x%04X\n",ep,clusterId); kk_print_debug("\nmac:");
emberAfPrintBigEndianEui64(nodeEui64);
cJSON *item = rpc_cJSON_CreateObject(); emberAfAppPrintln(",EP=%d,cluster=0x%04X\n",ep,clusterId);
cJSON *array_attr = rpc_cJSON_CreateObject();
cJSON *item = rpc_cJSON_CreateObject();
rpc_cJSON_AddMACToObject(item,nodeEui64); cJSON *array_attr = rpc_cJSON_CreateObject();
rpc_cJSON_AddNodeToObject(item,nodeId);
rpc_cJSON_AddEndpointToObject(item,ep); rpc_cJSON_AddMACToObject(item,nodeEui64);
rpc_cJSON_AddClusterToObject(item,clusterId); rpc_cJSON_AddNodeToObject(item,nodeId);
rpc_cJSON_AddEndpointToObject(item,ep);
array_attr = rpc_cJSON_CreateArray(); rpc_cJSON_AddClusterToObject(item,clusterId);
rpc_cJSON_AddItemToObject(item,"attributes",array_attr);
array_attr = rpc_cJSON_CreateArray();
cJSON *item_attr = rpc_cJSON_CreateObject(); rpc_cJSON_AddItemToObject(item,"attributes",array_attr);
rpc_cJSON_AddItemToArray(array_attr,item_attr);
cJSON *item_attr = rpc_cJSON_CreateObject();
//todo:check rpc_cJSON_AddItemToArray(array_attr,item_attr);
for (i = 0; i < bufLen; ) {
Status = bufferPtr[2]; //todo:check
for (i = 0; i < bufLen; ) {
if(Status == EMBER_ZCL_STATUS_SUCCESS){ Status = bufferPtr[2];
if(emberAfIsStringAttributeType(bufferPtr[3])){
bufferSize = bufferPtr[4]; if(Status == EMBER_ZCL_STATUS_SUCCESS){
typeSize = 1; if(emberAfIsStringAttributeType(bufferPtr[3])){
}else if(emberAfIsLongStringAttributeType(bufferPtr[3])){ bufferSize = bufferPtr[4];
bufferSize = HIGH_LOW_TO_INT(bufferPtr[5], bufferPtr[4]); typeSize = 1;
typeSize = 2; }else if(emberAfIsLongStringAttributeType(bufferPtr[3])){
}else { bufferSize = HIGH_LOW_TO_INT(bufferPtr[5], bufferPtr[4]);
typeSize = 0; typeSize = 2;
bufferSize = emberAfGetDataSize( }else {
bufferPtr[3]); typeSize = 0;
} bufferSize = emberAfGetDataSize(
bufferSize = bufferSize + 4 + typeSize; bufferPtr[3]);
bufferTemp = (uint8_t*)malloc(bufferSize); }
memcpy(bufferTemp, bufferPtr, bufferSize); bufferSize = bufferSize + 4 + typeSize;
bufferTemp = (uint8_t*)malloc(bufferSize);
bufferPtr = bufferPtr + bufferSize; memcpy(bufferTemp, bufferPtr, bufferSize);
emberAfAppPrintln("i=%d,bufferSize=%d\n",i,bufferSize); bufferPtr = bufferPtr + bufferSize;
emberAfAppPrintln("Read attribute Response: 0x%02X%02X, Type: %02X", emberAfAppPrintln("i=%d,bufferSize=%d\n",i,bufferSize);
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS], emberAfAppPrintln("Read attribute Response: 0x%02X%02X, Type: %02X",
bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]); bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],
bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS],
bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE]);
rpc_cJSON_AddStatusToObject(item_attr,Status);
EmberAfAttributeId attributeId = HIGH_LOW_TO_INT(bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS]);
rpc_cJSON_AddAttributeToObject(item_attr,attributeId); rpc_cJSON_AddStatusToObject(item_attr,Status);
EmberAfAttributeId attributeId = HIGH_LOW_TO_INT(bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_HIGH_BITS],bufferTemp[ATTRIBUTE_BUFFER_ATTRIBUTEID_LOW_BITS]);
rpc_cJSON_AddDataTypeToObject(item_attr,bufferTemp[3]); rpc_cJSON_AddAttributeToObject(item_attr,attributeId);
int dataLen = bufferSize-4-typeSize; rpc_cJSON_AddDataTypeToObject(item_attr,bufferTemp[3]);
rpc_cJSON_AddLengthToObject(item_attr,dataLen);
uint8_t *dataPtr = &bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE+1+1+typeSize]; int dataLen = bufferSize-4-typeSize;
rpc_cJSON_AddDataToObject(item_attr,dataPtr,dataLen); rpc_cJSON_AddLengthToObject(item_attr,dataLen);
uint8_t *dataPtr = &bufferTemp[ATTRIBUTE_BUFFER_REPORT_DATA_TYPE+1+1+typeSize];
//rpc_read_response_process_callback(nodeId,ep,clusterId,attributeId,bufferPtr[3],dataLen,dataPtr); rpc_cJSON_AddDataToObject(item_attr,dataPtr,dataLen);
free(bufferTemp); //rpc_read_response_process_callback(nodeId,ep,clusterId,attributeId,bufferPtr[3],dataLen,dataPtr);
}else{
rpc_cJSON_AddStatusToObject(item_attr,Status); free(bufferTemp);
bufferSize += 2; }else{
emberAfAppPrintln("Status=%d\n",Status); rpc_cJSON_AddStatusToObject(item_attr,Status);
} bufferSize += 2;
i = i + bufferSize; emberAfAppPrintln("Status=%d\n",Status);
} }
i = i + bufferSize;
rpc_read_attribute_response(item); }
return false; rpc_read_attribute_response(item);
}
return false;
}
static cJSON* rpc_reportDeviceState(char *state,EmberEUI64 eui64)
{
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 }; static cJSON* rpc_reportDeviceState(char *state,EmberEUI64 eui64)
cJSON* stateJSON; {
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 };
rpc_eui64ToString(eui64, euiString); cJSON* stateJSON;
stateJSON = rpc_cJSON_CreateObject(); rpc_eui64ToString(eui64, euiString);
rpc_cJSON_AddStringToObject(stateJSON, "mac", euiString);
rpc_cJSON_AddStringToObject(stateJSON, "status", state); stateJSON = rpc_cJSON_CreateObject();
return stateJSON; rpc_cJSON_AddStringToObject(stateJSON, "mac", euiString);
} rpc_cJSON_AddStringToObject(stateJSON, "status", state);
return stateJSON;
void rpc_reportDeviceStateChange(EmberEUI64 eui64,uint8_t state) }
{
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 }; void rpc_reportDeviceStateChange(EmberEUI64 eui64,uint8_t state)
cJSON* stateChangeJson; {
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 };
rpc_eui64ToString(eui64, euiString); cJSON* stateChangeJson;
stateChangeJson = rpc_cJSON_CreateObject(); rpc_eui64ToString(eui64, euiString);
rpc_cJSON_AddStringToObject(stateChangeJson, "mac", euiString);
rpc_cJSON_AddNumberToObject(stateChangeJson, "deviceState", state); stateChangeJson = rpc_cJSON_CreateObject();
rpc_printfJSON("devicestatechange",stateChangeJson); rpc_cJSON_AddStringToObject(stateChangeJson, "mac", euiString);
} rpc_cJSON_AddNumberToObject(stateChangeJson, "deviceState", state);
rpc_printfJSON("devicestatechange",stateChangeJson);
void emberAfPluginDeviceTableStateChangeCallback(EmberNodeId nodeId, }
uint8_t state)
{ void emberAfPluginDeviceTableStateChangeCallback(EmberNodeId nodeId,
EmberEUI64 nodeEui64; uint8_t state)
emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64); {
rpc_reportDeviceStateChange(nodeEui64, state); EmberEUI64 nodeEui64;
} emberAfDeviceTableGetEui64FromNodeId(nodeId, nodeEui64);
rpc_reportDeviceStateChange(nodeEui64, state);
}
void emberAfPluginDeviceTableRejoinDeviceCallback(EmberEUI64 nodeEui64)
{
uint16_t deviceTableIndex = emberAfDeviceTableGetFirstIndexFromEui64(nodeEui64); void emberAfPluginDeviceTableRejoinDeviceCallback(EmberEUI64 nodeEui64)
if(deviceTableIndex == EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_INDEX){ {
return ; uint16_t deviceTableIndex = emberAfDeviceTableGetFirstIndexFromEui64(nodeEui64);
} if(deviceTableIndex == EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_INDEX){
return ;
EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer(); }
cJSON* nodeJson = rpc_reportDeviceState("rejoin",deviceTable[deviceTableIndex].eui64); EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer();
rpc_printfJSON("rejoin",nodeJson);
//rpc_send_message(nodeJson,"device rejoin"); cJSON* nodeJson = rpc_reportDeviceState("rejoin",deviceTable[deviceTableIndex].eui64);
kk_rpc_reportDevices(deviceTable[deviceTableIndex].eui64); rpc_printfJSON("rejoin",nodeJson);
} //rpc_send_message(nodeJson,"device rejoin");
kk_rpc_reportDevices(deviceTable[deviceTableIndex].eui64);
void emberAfPluginDeviceTableDeviceLeftCallback(EmberEUI64 nodeEui64) }
{
uint16_t deviceTableIndex = emberAfDeviceTableGetFirstIndexFromEui64(nodeEui64); void emberAfPluginDeviceTableDeviceLeftCallback(EmberEUI64 nodeEui64)
{
if(deviceTableIndex == EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_INDEX){ uint16_t deviceTableIndex = emberAfDeviceTableGetFirstIndexFromEui64(nodeEui64);
return ;
} if(deviceTableIndex == EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_INDEX){
EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer(); return ;
}
cJSON* nodeJson = rpc_reportDeviceState("left",deviceTable[deviceTableIndex].eui64); EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer();
rpc_printfJSON("left",nodeJson);
//rpc_send_message(nodeJson,"device left"); cJSON* nodeJson = rpc_reportDeviceState("left",deviceTable[deviceTableIndex].eui64);
rpc_printfJSON("left",nodeJson);
kk_rpc_reportLeftDevices(deviceTable[deviceTableIndex].eui64); //rpc_send_message(nodeJson,"device left");
}
kk_rpc_reportLeftDevices(deviceTable[deviceTableIndex].eui64);
static cJSON* rpc_buildDeviceEndpoint(EmberEUI64 eui64, uint8_t endpoint) }
{
cJSON* deviceEndpointObj; static cJSON* rpc_buildDeviceEndpoint(EmberEUI64 eui64, uint8_t endpoint)
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 }; {
deviceEndpointObj = rpc_cJSON_CreateObject(); cJSON* deviceEndpointObj;
char euiString[RPC_EUI64_STRING_LENGTH] = { 0 };
rpc_eui64ToString(eui64, euiString); deviceEndpointObj = rpc_cJSON_CreateObject();
rpc_cJSON_AddStringToObject(deviceEndpointObj, "mac", euiString);
rpc_cJSON_AddNumberToObject(deviceEndpointObj, "ep", endpoint); rpc_eui64ToString(eui64, euiString);
return deviceEndpointObj; rpc_cJSON_AddStringToObject(deviceEndpointObj, "mac", euiString);
} rpc_cJSON_AddNumberToObject(deviceEndpointObj, "ep", endpoint);
return deviceEndpointObj;
static cJSON* rpc_buildDeviceEndpointWithClusterInfo( }
EmberEUI64 eui64,
uint8_t endpoint, static cJSON* rpc_buildDeviceEndpointWithClusterInfo(
uint16_t *clusterIds, EmberEUI64 eui64,
uint8_t clusterOutStartPosition) uint8_t endpoint,
{ uint16_t *clusterIds,
cJSON* deviceEndpointObj; uint8_t clusterOutStartPosition)
cJSON* clusterInfoArray; {
cJSON* clusterInfoItem; cJSON* deviceEndpointObj;
uint16_t clusterIdIndex; cJSON* clusterInfoArray;
char clusterIdString[RPC_CLUSTERID_STRING_LENGTH] = { 0 }; cJSON* clusterInfoItem;
uint16_t clusterIdIndex;
clusterInfoArray = rpc_cJSON_CreateArray(); char clusterIdString[RPC_CLUSTERID_STRING_LENGTH] = { 0 };
deviceEndpointObj = rpc_buildDeviceEndpoint(eui64, endpoint);
clusterInfoArray = rpc_cJSON_CreateArray();
for (clusterIdIndex = 0; deviceEndpointObj = rpc_buildDeviceEndpoint(eui64, endpoint);
clusterIdIndex < EMBER_AF_PLUGIN_DEVICE_TABLE_CLUSTER_SIZE;
clusterIdIndex++) { for (clusterIdIndex = 0;
clusterInfoItem = rpc_cJSON_CreateObject(); clusterIdIndex < EMBER_AF_PLUGIN_DEVICE_TABLE_CLUSTER_SIZE;
if (clusterIds[clusterIdIndex] != ZCL_NULL_CLUSTER_ID) { clusterIdIndex++) {
sprintf(clusterIdString, "0x%04X", clusterIds[clusterIdIndex]); clusterInfoItem = rpc_cJSON_CreateObject();
rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterId", clusterIdString); if (clusterIds[clusterIdIndex] != ZCL_NULL_CLUSTER_ID) {
if (clusterIdIndex < clusterOutStartPosition) { sprintf(clusterIdString, "0x%04X", clusterIds[clusterIdIndex]);
rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterType", "In"); rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterId", clusterIdString);
} else { if (clusterIdIndex < clusterOutStartPosition) {
rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterType", "Out"); rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterType", "In");
} } else {
rpc_cJSON_AddItemToArray(clusterInfoArray, clusterInfoItem); rpc_cJSON_AddStringToObject(clusterInfoItem, "clusterType", "Out");
clusterInfoItem = NULL; }
} else { rpc_cJSON_AddItemToArray(clusterInfoArray, clusterInfoItem);
rpc_cJSON_Delete(clusterInfoItem); clusterInfoItem = NULL;
clusterInfoItem = NULL; } else {
break; rpc_cJSON_Delete(clusterInfoItem);
} clusterInfoItem = NULL;
} break;
rpc_cJSON_AddItemToObject(deviceEndpointObj, "clusterInfo", clusterInfoArray); }
return deviceEndpointObj; }
} rpc_cJSON_AddItemToObject(deviceEndpointObj, "clusterInfo", clusterInfoArray);
return deviceEndpointObj;
static cJSON* buildNodeJson(uint16_t nodeIndex) }
{
cJSON* nodeJson; static cJSON* buildNodeJson(uint16_t nodeIndex)
cJSON* deviceEndpoint; {
char nodeIdString[RPC_NODEID_STRING_LENGTH] = { 0 }; cJSON* nodeJson;
char* deviceTypeString; cJSON* deviceEndpoint;
char nodeIdString[RPC_NODEID_STRING_LENGTH] = { 0 };
EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer(); char* deviceTypeString;
nodeJson = rpc_cJSON_CreateObject(); EmberAfPluginDeviceTableEntry *deviceTable = emberAfDeviceTablePointer();
rpc_nodeIdToString(deviceTable[nodeIndex].nodeId, nodeIdString);
rpc_cJSON_AddStringToObject(nodeJson, "nodeId", nodeIdString); nodeJson = rpc_cJSON_CreateObject();
rpc_cJSON_AddNumberToObject(nodeJson, rpc_nodeIdToString(deviceTable[nodeIndex].nodeId, nodeIdString);
"deviceState", rpc_cJSON_AddStringToObject(nodeJson, "nodeId", nodeIdString);
deviceTable[nodeIndex].state); rpc_cJSON_AddNumberToObject(nodeJson,
deviceTypeString = rpc_createTwoByteHexString(deviceTable[nodeIndex].deviceId); "deviceState",
rpc_cJSON_AddStringToObject(nodeJson, "deviceType", deviceTypeString); deviceTable[nodeIndex].state);
free(deviceTypeString); deviceTypeString = rpc_createTwoByteHexString(deviceTable[nodeIndex].deviceId);
rpc_cJSON_AddStringToObject(nodeJson, "deviceType", deviceTypeString);
deviceEndpoint = rpc_buildDeviceEndpointWithClusterInfo( free(deviceTypeString);
deviceTable[nodeIndex].eui64,
deviceTable[nodeIndex].endpoint, deviceEndpoint = rpc_buildDeviceEndpointWithClusterInfo(
deviceTable[nodeIndex].clusterIds, deviceTable[nodeIndex].eui64,
deviceTable[nodeIndex].clusterOutStartPosition); deviceTable[nodeIndex].endpoint,
rpc_cJSON_AddItemToObject(nodeJson, "deviceEndpoint", deviceEndpoint); deviceTable[nodeIndex].clusterIds,
return nodeJson; deviceTable[nodeIndex].clusterOutStartPosition);
} rpc_cJSON_AddItemToObject(nodeJson, "deviceEndpoint", deviceEndpoint);
return nodeJson;
}
void rpc_reportDevices(void)
{
uint16_t nodeIndex; void rpc_reportDevices(void)
cJSON* nodeJson; {
cJSON* devicesJson; uint16_t nodeIndex;
cJSON* devicesJsonNodeArray; cJSON* nodeJson;
cJSON* devicesJson;
devicesJson = rpc_cJSON_CreateObject(); cJSON* devicesJsonNodeArray;
devicesJsonNodeArray = rpc_cJSON_CreateArray();
rpc_cJSON_AddItemToObject(devicesJson, "devices", devicesJsonNodeArray); devicesJson = rpc_cJSON_CreateObject();
devicesJsonNodeArray = rpc_cJSON_CreateArray();
for (nodeIndex = 0; rpc_cJSON_AddItemToObject(devicesJson, "devices", devicesJsonNodeArray);
nodeIndex < EMBER_AF_PLUGIN_DEVICE_TABLE_DEVICE_TABLE_SIZE;
nodeIndex++) { for (nodeIndex = 0;
if (emberAfDeviceTableGetNodeIdFromIndex(nodeIndex) nodeIndex < EMBER_AF_PLUGIN_DEVICE_TABLE_DEVICE_TABLE_SIZE;
!= EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID) { nodeIndex++) {
nodeJson = buildNodeJson(nodeIndex); if (emberAfDeviceTableGetNodeIdFromIndex(nodeIndex)
rpc_cJSON_AddItemToArray(devicesJsonNodeArray, nodeJson); != EMBER_AF_PLUGIN_DEVICE_TABLE_NULL_NODE_ID) {
break; nodeJson = buildNodeJson(nodeIndex);
} rpc_cJSON_AddItemToArray(devicesJsonNodeArray, nodeJson);
} break;
rpc_report_devices(devicesJson); }
} }
rpc_report_devices(devicesJson);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment