之前传输的数据都是测试数据,那我们这次试着调试led
用自己的文件经行led的控制
最后可以用驱动+app的形式经行硬件的控制,我比较懒,先直接改文件吧
看看我们有什么硬件可以玩的
驱动已经注册好led的class类了,那就玩led
进行写值操作
控制led 灯的量灭
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
int main(){
FILE *fp;
fp = fopen("/sys/class/leds/led2/brightness", "w");
fprintf(fp,"255");
fclose(fp);
return 0;
}
报错:
-/bin/sh: ./chulai: not found
因为编译器太老了,编出来的东西无法识别,所以更改编译器
进行读值的操作
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
/* Attempt to read in 10 characters */
int main(){
char *strBuf=(char*)malloc(40);
FILE *fp = fopen("/sys/class/leds/led2/brightness","r");
fgets(strBuf, sizeof(strBuf),fp);
//numread = fread(fp, sizeof(strBuf),strBuf);
//strcpy(strBuf,fp);
printf("%s\n", strBuf);
fclose(fp);
free(strBuf);
return 0;
}
}
导入MQTT主函数
数据上报
那就直接把传入的值改掉就好了
char *strBuf=(char*)malloc(40);
FILE *fp = fopen("/sys/class/leds/led2/brightness","r");
fgets(strBuf, sizeof(strBuf),fp);
char buf[1000];
char * A="Battery";
char * B="lowBatteryAlarm";
char * C= "111";
char * D="batteryLevel";
char * E= "111";
sprintf(buf,"{\"services\":[{\"service_id\":\"%s\",\"properties\":{\"%s\":\"%s\",\"%s\":\"%s\"}}]}\0",A,B,C,D,E);
int ret = mqtt_connect();
if (ret != 0) {
printf("connect failed, result %d\n", ret);
}
time_sleep(3000);
//subscribe
char *cmd_topic = combine_strings(3, "$oc/devices/", username, "/sys/commands/#");
ret = mqtt_subscribe(cmd_topic);
free(cmd_topic);
cmd_topic = NULL;
if (ret < 0) {
printf("subscribe topic error, result %d\n", ret);
}
time_sleep(1000);
//publish data
char *payload=buf;
char *report_topic = combine_strings(3, "$oc/devices/", username, "/sys/properties/report");
ret = mqtt_publish(report_topic, payload);
free(report_topic);
report_topic = NULL;
if (ret < 0) {
printf("publish data error, result %d\n", ret);
}
while(1) {
time_sleep(1000);
}
return 0;
现在就能进行硬件上面数值的读取
数据下发
在iot上控制led的亮灭
int mqtt_message_arrive(void *context, char *topicName, int topicLen, MQTTAsync_message *message) {
// 当为73是关灯,为75是开灯
int str_len = strlen(message->payload);
int led_off = 73;
int led_on = 75;
printf( "mqtt_message_arrive() success, the topic is %s, the payload is %s \n", topicName, message->payload);
printf("the str_len is %d \n",str_len);
if(str_len == led_off){
FILE *fp;
fp = fopen("/sys/class/leds/led2/brightness", "w");
fprintf(fp,"0");
fclose(fp);
}
else
{
FILE *fp;
fp = fopen("/sys/class/leds/led2/brightness", "w");
fprintf(fp,"255");
fclose(fp);
}
return 1; //can not return 0 here, otherwise the message won't update or something wrong would happen
}