![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Ethernet mqtt server
PMK2021_MQTT_ETHERNET_SERVER
main.cpp
- Committer:
- nenad
- Date:
- 2021-05-07
- Revision:
- 4:5b78021768e2
- Parent:
- 1:276a09a95334
File content as of revision 4:5b78021768e2:
#include "mbed.h" #include "EthernetInterface.h" #include "platform/mbed_thread.h" #include <MQTTClientMbedOs.h> // Blinking rate in milliseconds #define BLINKING_RATE_MS 500 DigitalOut led(LED1); int arrivedcount = 0; TCPSocket socket; MQTTClient client(&socket); MQTT::Message message; char* topic_pub = "PMK-server-topic-pub"; char* topic_sub = "PMK-client-temperature"; const char *sec2str(nsapi_security_t sec) { switch (sec) { case NSAPI_SECURITY_NONE: return "None"; case NSAPI_SECURITY_WEP: return "WEP"; case NSAPI_SECURITY_WPA: return "WPA"; case NSAPI_SECURITY_WPA2: return "WPA2"; case NSAPI_SECURITY_WPA_WPA2: return "WPA/WPA2"; case NSAPI_SECURITY_UNKNOWN: default: return "Unknown"; } } void messageArrived(MQTT::MessageData& md) { MQTT::Message &message = md.message; printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id); printf("Payload %.*s\r\n", message.payloadlen, (char*)message.payload); ++arrivedcount; } int main() { printf("PMK2021 Ethernet MQTT example\r\n"); const char* hostname = "broker.mqttdashboard.com"; int port = 1883; // Network interface EthernetInterface net; // Bring up the ethernet interface net.connect(); // Show the network address const char *ip = net.get_ip_address(); printf("IP address is: %s\r\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 = "PMK-server"; //data.username.cstring = "testuser"; //data.password.cstring = "testpassword"; if ((rc = client.connect(data)) != 0) printf("rc from MQTT connect is %d\r\n", rc); if ((rc = client.subscribe(topic_sub, MQTT::QOS2, messageArrived)) != 0) printf("rc from MQTT subscribe is %d\r\n", rc); while (true) { led = !led; thread_sleep_for(BLINKING_RATE_MS); printf("Server Yielding "); client.yield(1000); printf(" -> Yielded\r\n"); } }