STM32+W5500+MQTT+Android實(shí)現(xiàn)遠(yuǎn)程數(shù)據(jù)采集及控制
下面我們看下主函數(shù)的代碼,思路也比較清晰:
int main(void)
{
static char meassage[200];
int rc;
char *led;
char led_value;
float temperature,humidity,light,pressure;
srand(0);
//配置LED燈引腳
LED_Config();
//初始化配置網(wǎng)絡(luò)
network_init();
while(1){
memset(meassage,0,sizeof(meassage));
//訂閱消息
rc = mqtt_subscrib(“pyboard_led”,meassage);
printf(“rc = %d”,rc);
if(rc >= 0){
printf(“meassage = %s”,meassage);
//解析JSON格式字符串并點(diǎn)亮相應(yīng)的LED燈
cJSON *root = cJSON_Parse(meassage);
if(root != NULL){
led = cJSON_GetObjectItem(root,”led”)->valuestring;
printf(“led = %s”,led);
led_value = cJSON_GetObjectItem(root,”value”)->valueint;
if(!strcmp(led,”red”)){
if(led_value){
LED_On(LED_RED);
}else{
LED_Off(LED_RED);
}
}else if(!strcmp(led,”green”)){
if(led_value){
LED_On(LED_GREEN);
}else{
LED_Off(LED_GREEN);
}
}else if(!strcmp(led,”blue”)){
if(led_value){
LED_On(LED_BLUE);
}else{
LED_Off(LED_BLUE);
}
}else if(!strcmp(led,”yellow”)){
if(led_value){
LED_On(LED_YELLOW);
printf(“Yellow On”);
}else{
LED_Off(LED_YELLOW);
printf(“Yellow Off”);
}
}
// 釋放內(nèi)存空間
cJSON_Delete(root);
}else{
printf(“Error before: [%s]”,cJSON_GetErrorPtr());
}
}
delay_ms(500);
//獲取傳感器測(cè)量數(shù)據(jù),該示例使用隨機(jī)數(shù)
temperature = rand()P;
humidity = rand()0;
light = rand()00;
pressure = rand()00;
//將數(shù)據(jù)合成為JSON格式數(shù)據(jù)
sprintf(meassage,”{”temperature”:%.1f,”humidity”:%.1f,”light”:%.1f,”pressure”:%.1f}”,temperature,humidity,light,pressure);
//將數(shù)據(jù)發(fā)送出去
mqtt_publish(“pyboard_value”,meassage);
}
}
完整工程代碼可在后面的附件下載。
2 手機(jī)端代碼實(shí)現(xiàn)
手機(jī)端我們也使用官方提供的Java庫(kù)Java client and utilities,下載地址:
http://www.eclipse.org/paho/
將jar文件添加到工程中即可,程序界面如下所示:
上面4個(gè)條目分別顯示STM32單片機(jī)通過W5500發(fā)送到服務(wù)器端的傳感器測(cè)量數(shù)據(jù);
下面4個(gè)圖片分別控制板子上的4個(gè)LED燈;
消息發(fā)送我們采用線程的方式發(fā)送,接收采用回調(diào)函數(shù)方式接收消息。
2.1 實(shí)現(xiàn)消息發(fā)送
發(fā)送消息的代碼如下所示:
class PublishThread extends Thread {
String topic;
MqttMessage message;
int qos = 0;
MemoryPersistence persistence = new MemoryPersistence();
PublishThread(String topic,String message){
this.topic = topic;
this.message = new MqttMessage(message.getBytes());
}
public void sendMessage(String topic,String message){
this.topic = topic;
this.message = new MqttMessage(message.getBytes());
run();
}
@Override
public void run() {
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setKeepAliveInterval(1);
System.out.println(“Connecting to broker: ” + broker);
sampleClient.connect(connOpts);
System.out.println(“Connected”);
System.out.println(“Publishing message: ” + message.toString());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println(“Message published”);
sampleClient.disconnect();
System.out.println(“Disconnected”);
}catch(MqttException me) {
System.out.println(“reason “+me.getReasonCode());
System.out.println(“msg “+me.getMessage());
System.out.println(“loc “+me.getLocalizedMessage());
System.out.println(“cause “+me.getCause());
System.out.println(“excep “+me);
me.printStackTrace();
}
}
}
2.2 實(shí)現(xiàn)消息接收
接收消息的代碼如下所示:
class SubscribeThread extends Thread{
final String topic;
MemoryPersistence persistence = new MemoryPersistence();
SubscribeThread(String topic){
this.topic = topic;
}
@Override
public void run(){
try {
final MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
final MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println(“Connecting to broker: ” + broker);
connOpts.setKeepAliveInterval(5);
sampleClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
System.out.println(“connectionLost”);
try {
sampleClient.connect(connOpts);
sampleClient.subscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println(“messageArrived:”+mqttMessage.toString());
System.out.println(topic);
System.out.println(mqttMessage.toString());
try {
JSONTokener jsonParser = new JSONTokener(mqttMessage.toString());
JSONObject person = (JSONObject) jsonParser.nextValue();
temperature = person.getDouble(“temperature”);
humidity = person.getDouble(“humidity”);
light = person.getDouble(“light”);
pressure = person.getDouble(“pressure”);
System.out.println(“temperature = ” + temperature);
System.out.println(“humidity = ” + humidity);
runOnUiThread(new Runnable() {
@Override
public void run() {
temperatureTextView.setText(String.format(“%.1f”, temperature));
humidityTextView.setText(String.format(“%.1f”, humidity));
lightTextView.setText(String.format(“%.1f”, light));
pressureTextView.setText(String.format(“%.1f”, pressure));
}
});
} catch (JSONException ex) {
ex.printStackTrace();
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println(“deliveryComplete”);
}
});
sampleClient.connect(connOpts);
sampleClient.subscribe(topic);
} catch(MqttException me) {
System.out.println(“reason “+me.getReasonCode());
System.out.println(“msg “+me.getMessage());
System.out.println(“loc “+me.getLocalizedMessage());
System.out.println(“cause “+me.getCause());
System.out.println(“excep “+me);
me.printStackTrace();
}
}
}
3 實(shí)測(cè)效果
1,單片機(jī)端定時(shí)更新傳感器數(shù)據(jù),手機(jī)端也會(huì)同步更新;
2,手機(jī)端點(diǎn)擊4個(gè)LED控制的按鈕,板子上也會(huì)點(diǎn)亮或者熄滅對(duì)應(yīng)的LED;
4 源碼下載
4.1 STM32端源碼下載
4.2 手機(jī)端源碼下載
4.3 手機(jī)端apk下載
評(píng)論