cJSON模块在Mqtt代理mosquitto中的使用


前言

本文记录了在利用mosquitto动态库的过程中,C语言中使用cJSON模块实现json格式主题消息的传递。

本文测试环境CentOS 7.6。

利用mosquitto的C语言客户端进行编程,通过cJSON或protobuff对消息内容进行格式化传输,并与前端JavaScript进行完全交互系列文章:

第一篇:Mosquitto打开Websockets模块并在Linux下的编译及安装使用

第二篇:cJSON模块在Mqtt代理mosquitto中的使用


一、cJSON是什么?

cJSON是在C语言中,用来创建和解释JSON格式内容或文件的工具库,使用简单方便。

二、使用步骤

1.编译及安装

准备源代码:
git clone https://hub.fastgit.org/DaveGamble/cJSON.git
cd cJSON
mkdir build
cd build
cmake3 …
make
make install
编译成功后,需要在程序中引入头文件及cJSON库。

2.cJSON相关说明

  • cJSON通用结构体,通过cJSON解释或发布的内容均通过此核心结构体进行处理。
/* The cJSON structure: */
typedef struct cJSON {
        struct cJSON *next,*prev;       /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
        struct cJSON *child;            /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
        struct cJSON *parent;   /* parent tracing */
        const char**  vars;
        int type;                                       /* The type of the item, as above. */

        char *decvalstring;   /* decoded string of this item */
        char *valuestring;                      /* The item's string, if type==cJSON_String */
        int valueint;                           /* The item's number, if type==cJSON_Number */
        double valuedouble;                     /* The item's number, if type==cJSON_Number */

        char *string;                           /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
  • 常用的几个函数
char *cJSON_Print(cJSON *item);//将cJSON结构的内容转化成字符串
cJSON *cJSON_Parse(const char *value);//将接收的字符串解释成cJSON结构的内容
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//获取字段key对应的value值
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);//创建数组类型的节点
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);//创建对象类型的节点

3.创建JSON内容并发布到Mqtt代理

  • 嵌套形式的JSON内容
{
	"subject": {
			"content":    {
					"name":"语文",
					"score": 85.3
			}
	},
	"age":   15,
	"class":    "二班",
	"name":  "张三"
}

对应的代码

cJSON * root =  cJSON_CreateObject();
cJSON * item =  cJSON_CreateObject();
cJSON * next =  cJSON_CreateObject();

cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(15));//根节点下添加
cJSON_AddItemToObject(root, "class", cJSON_CreateString("二班"));
cJSON_AddItemToObject(root, "name", cJSON_CreateString("张三"));

cJSON_AddItemToObject(root, "subject", item);//root节点下添加subject节点
cJSON_AddItemToObject(item, "content", next);//subject节点下添加item节点
cJSON_AddItemToObject(next, "name", cJSON_CreateString("语文"));//添加name节点
cJSON_AddItemToObject(next, "score", cJSON_CreateNumber(85.3));//添加name节点

printf("%s\n", cJSON_Print(root));
  • 数组形式的JSON内容
{
	[
		"class":    "二班",
		"name":  "张三",
		"score": 87
	],
	[
		"class":    "三班",
		"name":  "李四",
		"score": 92
	]
}

对应的代码

cJSON *root= cJSON_CreateArray();
cJSON *next = cJSON_CreateObject();
cJSON_AddStringToObject(next , "class", "二班");
cJSON_AddStringToObject(next , "name", "张三");
cJSON_AddNumberToObject(next , "score", 87);
cJSON_AddItemToArray(root, next );

cJSON *next1 = cJSON_CreateObject();
cJSON_AddStringToObject(next1 , "class", "三班");
cJSON_AddStringToObject(next1 , "name", "李四");
cJSON_AddNumberToObject(next1, "score", 92);
cJSON_AddItemToArray(root, next1 );

printf("%s\n", cJSON_Print(root));
  • 通过mosquitto进行发布
char* buff = cJSON_Print(ycitem);
if(NULL != buff)
{
	char strTemp[64];
	sprintf(strTemp,"test/control/senddata");
	mosquitto_publish(mosq,NULL,(char *)strTemp,strlen(buff),buff,0,0);
}
cJSON_Delete(ycitem);
free(buff);

4.解释从Mqtt代理接收到的JSON消息内容

mosquitto订阅消息的回调函数中进行处理.

  • JSON内容如下
{
		"class":    "三班",
		"name":  "李四",
		"score": 92
}
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{	
	char m_class[20],m_name[20];
	m_class[0]='\0';
	m_name[0]='\0';
	if(msg->payloadlen){        
        //parse json here
        char * data=new char[msg->payloadlen+1];
		sprintf(data,(char *)msg->payload);
		printf("######## %s %d payload=%s data=%s \n", msg->topic, msg->qos, (char *)msg->payload,data);
        cJSON* pose=cJSON_Parse(data);
		sprintf(m_class,cJSON_GetObjectItem(pose,"class")->valuestring);
		sprintf(m_name,cJSON_GetObjectItem(pose,"name")->valuestring);
		float m_score=cJSON_GetObjectItem(pose,"score")->valuedouble;
		//得到数据后即可进行自己的逻辑处理
    }else{
        printf("%s (null)\n", msg->topic);
    }

}

总结

本文介绍了在使用mosquitto的过程中,在C语言中利用cJSON这个工具库对JSON格式的内容进行创建或解释,从而实现JSON内容的消息传递。

下一篇介绍在前端JavaScript中利用MQTT.js,通过websockets的方式实现消息的自动推送和发布。

如果您对物联网相关方面技术感兴趣,可进群交流,QQ群:541826239

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小二郎上学堂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值