https://github.com/RozenAstrayChen/MQTT-IDW01M1

Dependencies:   MQTT NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed

Files at this revision

API Documentation at this revision

Comitter:
rozendhyan@gmail.com
Date:
Tue Oct 31 18:41:30 2017 +0800
Child:
1:2ee9e5685a1e
Commit message:
My commit message

Changed in this revision

.gitignore Show annotated file Show diff for this revision Revisions of this file
.hgignore Show annotated file Show diff for this revision Revisions of this file
.mbed Show annotated file Show diff for this revision Revisions of this file
BME280/BME280.hpp Show annotated file Show diff for this revision Revisions of this file
MQTT.lib Show annotated file Show diff for this revision Revisions of this file
NetworkSocketAPI.lib Show annotated file Show diff for this revision Revisions of this file
README.md Show annotated file Show diff for this revision Revisions of this file
X_NUCLEO_IDW01M1v2.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
mbed_settings.py Show annotated file Show diff for this revision Revisions of this file
mbed_settings.pyc Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.gitignore	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,7 @@
+# dir
+BUILD/
+mbed/
+MQTT/
+NetworkSocketAPI/
+X_NUCLEO_IDW01M1v2/
+.hg/
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.hgignore	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,7 @@
+# dir
+BUILD/
+mbed/
+MQTT/
+NetworkSocketAPI/
+X_NUCLEO_IDW01M1v2/
+.git/
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.mbed	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,3 @@
+ROOT=.
+TARGET=NUCLEO_F401RE
+TOOLCHAIN=GCC_ARM
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/BME280/BME280.hpp	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,74 @@
+#include "mbed.h"
+
+#ifndef BME280_HPP
+#define BME280_HPP
+
+#define BME280_size 14
+
+Serial sensor(PA_11,PA_12);
+Serial pc(USBTX,USBRX);
+int AT[3] = {0xA5,0x52,0xF7};
+class BME280{
+public:
+    void judgement_data(char buf[]);
+    int Temp_read();
+
+private:
+    void receive();
+    void send_AT();
+    char buf[BME280_size];
+    int Lux,Temp,Preesure,Hum,Height;
+
+};
+void BME280::judgement_data(char buf[]){
+    int i=0;
+    if(buf[i++]== 0x5A){
+        //pc.printf("first_step\n");
+        if(buf[i++]== 0x5A){
+            //pc.printf("second_step\n");
+           //i++;//go to data type
+            if(buf[i] == 0x15){
+                //pc.printf("Lux type\n");
+                i++;//04
+                Lux = ((buf[i+1]<<24) | (buf[i+2]<<16) | (buf[i+3]<<8) | buf[i+4])/100;
+                //Lux = (0x00<<24) | (0x00<<16) | (0xFE<<8) | 0x40;//test
+                //pc.printf("Lux = %d\n", Lux);
+            }else if(buf[i] == 0x45){
+                //pc.printf("temp type\n");
+                i++;//0A
+                Temp = ((buf[i+1]<<8)|(buf[i+2]))/100;
+                Preesure = ((buf[i+3]<<24)|(buf[i+4]<<16)|(buf[i+5]<<8)|(buf[i+6]))/100;
+                Hum = ((buf[i+7]<<8)|(buf[i+8]))/100;
+                Height = ((buf[i+9]<<8)|(buf[i+10]));
+                //pc.printf("Temp = %d\n", Temp);
+                //pc.printf("Preesure = %d\n", Preesure);
+                //pc.printf("Hum = %d\n", Hum);
+                //pc.printf("Height = %d\n", Height);
+            }
+        }
+    }
+}
+void BME280::receive(){
+    for(int i=0;i<BME280_size;i++){
+        buf[i] = sensor.getc();  
+        //pc.putc(buf[i]);
+    }
+    
+}
+void BME280::send_AT(){
+    for(int i=0;i<3;i++){
+        sensor.putc(AT[i]);
+        //pc.putc(AT[i]);
+    }
+}
+int BME280::Temp_read(){
+    send_AT();
+    //wait(0.2);
+    receive();
+    //wait(0.2);
+    judgement_data(this->buf);
+    
+    return Temp;
+}
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MQTT.lib	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/MQTT/#66826ea709ea
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/NetworkSocketAPI.lib	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,1 @@
+http://mbed.org/teams/NetworkSocketAPI/code/NetworkSocketAPI/#ea3a618e0818
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README.md	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,47 @@
+# MQTT-IDW01M1
+This project is testing MQTT on mbed
+- device
+	- NUCLEO_F401RE
+	- IDW01M1(WiFi board)
+- MQTT cloud
+	- Node-Red(local,in my RaspberryPi)
+- Toolchain
+	- ARM_GCC
+- Tools
+	- mbed cli
+	- MQTTlens
+
+## compile
+First you need dowload mbed lib
+```
+mbed deploy
+```
+Setting toolchain and target
+```
+mbed toolcahin $(yourtoolchain)
+mbed target $(your target)
+``` 
+compile
+```
+mbed compile
+```
+
+
+## MQTT step
+### connect to your AP
+### connect to your host
+### MQTT connect
+### Subscribe
+### Publish
+
+## MQTT function
+- Subscribe
+- Publish
+
+## MQTT variables
+- QOS
+
+
+## Reference material
+- [X-NUCLEO-IDW01M1 Wi-Fi expansion board](https://os.mbed.com/components/X-NUCLEO-IDW01M1/)
+- [IDW01M1_Cloud_IBM](https://os.mbed.com/teams/ST/code/IDW01M1_Cloud_IBM/)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/X_NUCLEO_IDW01M1v2.lib	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/X_NUCLEO_IDW01M1v2/#0368732b5b9d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,195 @@
+#include "mbed.h"
+#include "BME280.hpp"
+#include "SpwfInterface.h"
+#include "TCPSocket.h"
+#include "MQTTClient.h"
+#include "MQTTWiFi.h"
+
+// MQTT use
+#define MQTT_MAX_PACKET_SIZE 250
+#define MQTT_MAX_PAYLOAD_SIZE 300
+//Configuration value needed to connect Red-node
+#define BROKER_URL "192.168.0.10";
+#define MQTT_PORT 1883
+//MQTT use Topic 
+#define TOPIC "temp"
+
+
+//Wifi network
+#define SSID "megu megu fire"
+#define PASSW "66666667"
+
+DigitalOut myled(LED1);
+BME280 bmpSensor;
+
+int connack_rc = 0;    // MQTT connack return code
+const char * ip_addr = "";
+char *host_addr = "";
+bool netConnecting = false;
+int connectTimeout = 1000;
+bool mqttConnecting = false;
+bool netConnected = false;
+bool connected = false;
+int retryAttempt = 0;
+char subscription_url[MQTT_MAX_PAYLOAD_SIZE];
+
+MQTT::Message message;
+MQTTString TopicName={TOPIC};
+MQTT::MessageData MsgData(TopicName, message);
+
+
+void subscribe_cb(MQTT::MessageData & msgMQTT) {
+    char msg[MQTT_MAX_PAYLOAD_SIZE];
+    msg[0]='\0';
+    strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen);
+    printf ("--->>> subscribe_cb msg: %s\n\r", msg);
+}
+int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
+{
+    char* pubTopic = TOPIC;    
+    return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb);
+}
+
+
+int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
+    const char* host = BROKER_URL;
+
+    char hostname[strlen(host) + 1];
+    sprintf(hostname,"%s", host);
+
+    SpwfSAInterface& WiFi = ipstack->getWiFi();
+
+    //Network Debug statements
+    LOG("=====================================\n\r");
+    LOG("Connecting WiFi.\n\r");
+    LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address());
+    LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address());
+    LOG("Server Hostname: %s port: %d\n\r", hostname, MQTT_PORT);
+    LOG("Topic: %s\n\r", TOPIC);
+    //need subscrie
+    LOG("=====================================\n\r");
+    netConnecting = true;
+    ipstack->open(&ipstack->getWiFi());
+    int rc = ipstack->connect(hostname,MQTT_PORT,connectTimeout);
+     if (rc != 0)
+    {
+        WARN("IP Stack connect returned: %d\n", rc);    
+        return rc;
+    }
+    printf ("--->TCP Connected\n\r");
+    netConnected = true;
+    netConnecting = false;
+
+    //MQTT Connect
+    mqttConnecting = true;
+    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+    data.MQTTVersion = 4;
+    data.struct_version =0;
+
+    if((rc = client->connect(data)) == 0){
+    	connected = true;
+    	printf("--->MQTT Connected\n\r");
+#ifdef SUBSCRIBE
+        if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",TOPIC);
+#endif 
+    }else {
+        WARN("MQTT connect returned %d\n", rc);        
+    }
+    if (rc >= 0)
+        connack_rc = rc;
+        mqttConnecting = false;
+        return rc;
+   
+}
+int getConnTimeout(int attemptNumber)
+{  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
+   // after 20 attempts, retry every 10 minutes
+    return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
+}
+void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
+{
+    connected = false;
+           
+    while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
+    {    
+        /*if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
+            printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc);        
+            return; // don't reattempt to connect if credentials are wrong
+        } */
+        int timeout = getConnTimeout(++retryAttempt);
+        WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
+        
+        // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
+        //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)        
+        // this works - reset the system when the retry count gets to a threshold
+        if (retryAttempt == 5)
+            NVIC_SystemReset();
+        else
+            wait(timeout);
+    }
+}
+int publish (MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
+	
+    
+	MQTT::Message message;
+	int data = bmpSensor.Temp_read();
+	char *pubTopic = TOPIC;
+	char buf[MQTT_MAX_PAYLOAD_SIZE];
+
+
+	printf("Temp = %d\n", data);
+	sprintf(buf,"%d",data);
+	message.qos = MQTT::QOS0;
+	message.retained = false;
+    message.dup = false;
+    message.payload = (void*)buf;
+    message.payloadlen = strlen(buf);
+
+    printf("Publishing %s\n\r", buf);
+    return client->publish(pubTopic, message);
+}
+
+int main(int argc, char const *argv[])
+{
+	myled =0;
+	/* code */
+	const char *ssid = SSID;
+	const char *seckey = PASSW;
+	//use SpwfSAInterface connect AP
+	SpwfSAInterface spwf(D8,D2, false);
+
+	printf("\r\nX-NUCLEO-IDW01M1 mbed \n");
+	printf("\r\nconnecting to AP\n");
+	//connect to Wifi
+	MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2);
+	//check wifi has got ip_address
+	if(ipstack.getWiFi().get_ip_address() == 0){
+		printf("Connect WiFi is failed!\nPlease check your ssid and passwd is correct");
+		return 0;
+	}
+	printf("ip: %s\n",ipstack.getWiFi().get_ip_address() );
+
+	MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
+	attemptConnect(&client, &ipstack);
+
+	myled=1;         
+   int count = 0;    
+//    tyeld.start();    
+    while (true)
+    {
+        if (++count == 100)
+        {               // Publish a message every second
+            if (publish(&client, &ipstack) != 0) { 
+                myled=0;
+                attemptConnect(&client, &ipstack);   // if we have lost the connection                
+            } else myled=1;
+            count = 0;
+        }        
+//        int start = tyeld.read_ms();
+        client.yield(10);  // allow the MQTT client to receive messages
+//        printf ("tyeld: %d\n\r",tyeld.read_ms()-start);
+
+    }
+	
+	return 0;
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,1 @@
+https://mbed.org/users/mbed_official/code/mbed/builds/4eea097334d6
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed_settings.py	Tue Oct 31 18:41:30 2017 +0800
@@ -0,0 +1,45 @@
+"""
+mbed SDK
+Copyright (c) 2016 ARM Limited
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+from os.path import join, abspath, dirname
+
+#ROOT = abspath(join(dirname(__file__), "."))
+
+##############################################################################
+# Build System Settings
+##############################################################################
+#BUILD_DIR = abspath(join(ROOT, "build"))
+
+# ARM
+#ARM_PATH = "C:/Program Files/ARM"
+
+# GCC ARM
+#GCC_ARM_PATH = ""
+
+# GCC CodeRed
+#GCC_CR_PATH = "C:/code_red/RedSuite_4.2.0_349/redsuite/Tools/bin"
+
+# IAR
+#IAR_PATH = "C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm"
+
+# Goanna static analyser. Please overload it in private_settings.py
+#GOANNA_PATH = "c:/Program Files (x86)/RedLizards/Goanna Central 3.2.3/bin"
+
+#BUILD_OPTIONS = []
+
+# mbed.org username
+#MBED_ORG_USER = ""
Binary file mbed_settings.pyc has changed