Mqtt连接mCotton

来自Microduino Wikipedia
跳转至: 导航搜索

HTTPGET


描述

本示例会实现一个用mqtt连接mCotton的例子
需要调用#include <ESP8266.h>头文件。

所用方法

  • wifi.mqttSetServer(MQTTSERVER, MQTT_PORT) 设置mqtt服务器
  • wifi.mqttConnect(ID, USER, PASS) 连接mqtt服务器
  • wifi.getMqttJson() 获取mqtt服务器下发数据
  • wifi.mqttSetDiveceIDToken(ID, PASS) 设置diveceID和Token
  • wifi.mqttSetSubscrib(SUBSCRIBTOPIC) 设置订阅
  • wifi.mqttPublish(PUBLISHTOPIC, jsonData) 发布消息
  • wifi.mqttPublishM(jsonData) 简短方法发布消息

实例

#include <ESP8266.h>
#include <aJSON.h>

#ifdef ESP32
#error "This code is not recommended to run on the ESP32 platform! Please check your Tools->Board setting."
#endif

/**
**CoreUSB UART Port: [Serial1] [D0,D1]
**Core+ UART Port: [Serial1] [D2,D3]
**/
#if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1284P__) || defined (__AVR_ATmega644P__) || defined(__AVR_ATmega128RFA1__)
#define EspSerial Serial1
#define UARTSPEED  115200
#endif

/**
**Core UART Port: [SoftSerial] [D2,D3]
**/
#if defined (__AVR_ATmega168__) || defined (__AVR_ATmega328__) || defined (__AVR_ATmega328P__)
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); /* RX:D2, TX:D3 */

#define EspSerial mySerial
#define UARTSPEED  9600
#endif



#define SSID        "your ssid"
#define PASSWORD    "your password"
#define MQTTSERVER   "mCotton.microduino.cn"
#define ID   "your divice id"
#define USER   "your divice id"
#define PASS   "your divice token"
#define SUBSCRIBTOPIC   "ca/your divice id"
#define SUBSCRIBTOPICP   "cp/your divice id"
#define PUBLISHTOPIC   "dp/your divice id"
#define MQTT_PORT   (1883)

static const uint8_t stateLEDPin=4;

#define INTERVAL_sensor 2000
unsigned long sensorlastTime = millis();

float tempOLED, humiOLED, lightnessOLED, gasOLED;

String mCottenData;
String jsonData;

ESP8266 wifi(&EspSerial);

void setup(void) {
	Serial.begin(115200);

	pinMode(stateLEDPin,OUTPUT);
	digitalWrite(stateLEDPin,LOW);


	while (!Serial); // wait for Leonardo enumeration, others continue immediately
  	Serial.print(F("setup begin\r\n"));
  	delay(100);

  	WifiInit(EspSerial, UARTSPEED);

	Serial.print(F("FW Microduino Version:"));
	Serial.println(wifi.getMVersion().c_str());


//	if (wifi.setUart(57600)) {
//		Serial.print(F("set uart ok\r\n"));
//	} else {
//		Serial.print(F("set uart err\r\n"));
//	}

	if (wifi.setOprToStation()) {
		Serial.print(F("to station ok\r\n"));
	} else {
		Serial.print(F("to station err\r\n"));
	}

//	wifi.setAutoConnect(false);
//	wifi.restart();

	if (wifi.joinAP(SSID, PASSWORD)) {
		wifi.setWiFiconnected(true);
		Serial.print(F("Join AP success\r\n"));
		Serial.print(F("IP:"));
		Serial.println(wifi.getMLocalIP().c_str());
	} else {
		wifi.setWiFiconnected(false);
		Serial.print(F("Join AP failure\r\n"));
		Serial.print(F("Make sure your SSID, PASS correctly!\r\n"));
		while (true) {
			mCottenData = wifi.getMqttJson();
			if (mCottenData != "") {
				mCottenData.trim();
				Serial.println(mCottenData);
			}
		}
	}

	if (wifi.mqttSetServer(MQTTSERVER, MQTT_PORT)) {
		Serial.print(F("mqtt set server ok\r\n"));
	} else {
		Serial.print(F("mqtt set server err\r\n"));
	}
	if (wifi.mqttConnect(ID, USER, PASS)) {
		wifi.setMqttConnected(true);
		digitalWrite(stateLEDPin,HIGH);
		Serial.print(F("mqtt connect ok\r\n"));
	} else {
		wifi.setMqttConnected(false);
		Serial.print(F("mqtt connect err\r\n"));
		while (true) {
			mCottenData = wifi.getMqttJson();
			if (mCottenData != "") {
				mCottenData.trim();
				Serial.println(mCottenData);
			}
		}
	}
	if (wifi.mqttSetDiveceIDToken(ID, PASS)) {
		Serial.print(F("mqtt set device ID Token ok\r\n"));
	} else {
		Serial.print(F("mqtt set device ID Token err\r\n"));
	}
	if (wifi.mqttSetSubscrib(SUBSCRIBTOPIC)) {
		Serial.print(F("mqtt set subscrib ca topic ok\r\n"));
	} else {
		Serial.print(F("mqtt set subscrib ca topic err\r\n"));
	}
	if (wifi.mqttSetSubscrib(SUBSCRIBTOPICP)) {
		Serial.print(F("mqtt set subscrib cp topic ok\r\n"));
	} else {
		Serial.print(F("mqtt set subscrib cp topic err\r\n"));
	}



	jsonData = "{\"Humidity\":66.66}";
	if (wifi.mqttPublish(PUBLISHTOPIC, jsonData)) {
		Serial.print(F("mqtt publish ok\r\n"));
	} else {
		Serial.print(F("mqtt publish err\r\n"));
	}

}

void loop(void) {

	mCottenData = wifi.getMqttJson();

	if (mCottenData != "") {
		mCottenData.trim();

		Serial.println(mCottenData);

		if (mCottenData.equals("WIFI DISCONNECT")) {
			wifi.setWiFiconnected(false);
			wifi.setMqttConnected(false);
			digitalWrite(stateLEDPin,LOW);
		} else if (mCottenData.equals("WIFI Connected")) {
			wifi.setWiFiconnected(true);
		} else if (mCottenData.equals("MQTT: Disconnected")) {
			wifi.setMqttConnected(false);
			digitalWrite(stateLEDPin,LOW);
		} else if (mCottenData.equals("MQTT: Connected")) {
			if (wifi.mqttSetDiveceIDToken(ID, PASS)) {
				Serial.print(F("mqtt set device ID Token ok\r\n"));
			} else {
				Serial.print(F("mqtt set device ID Token err\r\n"));
			}
			if (wifi.mqttSetSubscrib(SUBSCRIBTOPIC)) {
				Serial.print(F("mqtt set subscrib ca topic ok\r\n"));
			} else {
				Serial.print(F("mqtt set subscrib ca topic err\r\n"));
			}
			if (wifi.mqttSetSubscrib(SUBSCRIBTOPICP)) {
				Serial.print(F("mqtt set subscrib cp topic ok\r\n"));
			} else {
				Serial.print(F("mqtt set subscrib cp topic err\r\n"));
			}
			wifi.setMqttConnected(true);
			digitalWrite(stateLEDPin,HIGH);
		}

		if (!wifi.isWiFiconnected()) {
			return;
		}

		if (wifi.isMqttConnected()) {
			if (mCottenData.startsWith("{") && mCottenData.endsWith("}")) {

				uint8_t length = mCottenData.length();
				char buf[length + 1];
				mCottenData.toCharArray(buf, length + 1);

				aJsonObject* root = aJson.parse(buf);
				aJsonObject* state = aJson.getObjectItem(root, "undefined");

				if (strcmp(state->valuestring, "true") == 0) {
					Serial.println(F("ON"));
				}
				if (strcmp(state->valuestring, "false") == 0) {
					Serial.println(F("OFF"));
				}
			}
		}
	}

	if (wifi.isMqttConnected()) {
		if (sensorlastTime > millis())
			sensorlastTime = millis();
		if (millis() - sensorlastTime > INTERVAL_sensor) {

			float temp = map(analogRead(A2), 0, 1023, 0, 255);
			float humi = map(analogRead(A1), 0, 1023, 0, 255);
			float lightness = map(analogRead(A0), 0, 1023, 0, 255);
			tempOLED = temp;
			humiOLED = humi;
			lightnessOLED = lightness;
			jsonData = "{\"Humidity\":";
			jsonData += String(humi);
			jsonData += ",\"Temperature\":";
			jsonData += String(temp);
			jsonData += ",\"Lightness\":";
			jsonData += String(lightness);
			jsonData += "}";


			if (wifi.mqttPublishM(jsonData)) {
				Serial.print(F("mqtt publishM ok\r\n"));
			} else {
				Serial.print(F("mqtt publishM err\r\n"));
			}

			sensorlastTime = millis();

		}
	}

}
send data
  • 程序首先进行WiFi模块的初始化,会返回WiFi模块的版本信息,之后连接路由器,获取自身IP,最后开始通过mqtt协议连接mCotton,连接成功后开始间隔2秒推送数据。每一步都设置了串口返回错误或成功,可以参照串口返回调试程序。

如何使用mCotton


mCotton使用: 1:注册账号,使用网页登录 https://mcotton.microduino.cn/ ,左上角有注册按钮。进入后使用邮箱或手机号或者社交媒体账号登录均可。

login

2:登陆后找到IOT WiFi气象站并点击名称进入。在这里可以看到之前建立好的气象站设备,我们需要以此为模板复制一份己用。

create

3:首先点击页面下方的:相关应用 点击进入。

create step1

4:之后再次拉到页面下方选择关联的设备 新建设备。

create step2

5:拉到下方填入标题与描述,设备类型选择WIFI设备不变。之后点击确定。之后可以在首页看到自己建立好的mCotton设备。

create step3

6:点击进入自己的设备,点击控制菜单,将其中不需要的删掉,只保留LED控制按钮。在保证电池盒打开WiFi程序运行成功的情况下,按下Off按钮,会变为ON并变成蓝色,同时连接在D6的LED灯会被点亮,再按下ON按钮,灯会关闭。达到云端控制LED的目的。

control led

7:之后点击右边的消息,可以看到推送信息。程序中只推送了一个模拟量,连接在A0接口的灰度传感器,用户可以遮挡传感器之后点击页面上的刷新,可以看到数据有变化,之后松开传感器,再次点击刷新,可以看到数据变化。达到信息推送云端的目的。

send data




返回mCookie-WiFi界面