mqtt esp8266
Dependencies: X_NUCLEO_IKS01A3
PMK2021_MQTT_ESP8266_IKS01A3
main.cpp
- Committer:
- nenad
- Date:
- 2020-04-30
- Revision:
- 0:75fa10a22545
- Child:
- 1:276a09a95334
File content as of revision 0:75fa10a22545:
/* mbed Microcontroller Library
* Copyright (c) 2019 ARM Limited
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
#include "EthernetInterface.h"
#include "platform/mbed_thread.h"
#include <MQTTClientMbedOs.h>
// Blinking rate in milliseconds
#define BLINKING_RATE_MS 500
// Initialise the digital pin LED1 as an output
DigitalOut led(LED1);
Serial pc(USBTX,USBRX);
InterruptIn button(USER_BUTTON);
int arrivedcount = 0;
TCPSocket socket;
MQTTClient client(&socket);
MQTT::Message message;
int button_pressed=0;
float version = 0.6;
char* topic = "mbed-sample-pub";
char* topic_sub = "mbed-sample-sub";
void messageArrived(MQTT::MessageData& md)
{
MQTT::Message &message = md.message;
pc.printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
pc.printf("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
++arrivedcount;
}
void buttonFunction() {
button_pressed=1;
}
int main()
{
button.rise(&buttonFunction); // attach the address of the flip function to the rising edge
const char* hostname = "broker.mqttdashboard.com";
int port = 1883;
// Network interface
EthernetInterface net;
// Bring up the ethernet interface
printf("Ethernet socket example\n");
net.connect();
// Show the network address
const char *ip = net.get_ip_address();
pc.printf("IP address is: %s\n", ip ? ip : "No IP");
//client = MQTTClient::(&socket);
socket.open(&net);
socket.connect(hostname, port);
int rc=0;
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 3;
data.clientID.cstring = "mbed-sample";
//data.username.cstring = "testuser";
//data.password.cstring = "testpassword";
if ((rc = client.connect(data)) != 0)
pc.printf("rc from MQTT connect is %d\r\n", rc);
if ((rc = client.subscribe(topic_sub, MQTT::QOS2, messageArrived)) != 0)
pc.printf("rc from MQTT subscribe is %d\r\n", rc);
while (true) {
led = !led;
thread_sleep_for(BLINKING_RATE_MS);
if (button_pressed==1) {
button_pressed=0;
pc.printf("sace publish\r\n");
// QoS 0
char buf[100];
sprintf(buf, "Hello World! QoS 0 message from app version %f\r\n", version);
message.qos = MQTT::QOS0;
message.retained = false;
message.dup = false;
message.payload = (void*)buf;
message.payloadlen = strlen(buf)+1;
client.publish(topic, message);
//pc.printf("sace jild\r\n");
//client.yield(1000);
//pc.printf("izjildovo\r\n");
}
pc.printf("sace jild\r\n");
client.yield(1000);
pc.printf("izjildovo\r\n");
}
}