之前傳輸的數據都是測試數據,那我們這次試着調試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
}