Simple mqtt client using the MqttPacket lib to create a connect to the public broker and publish series of message. Done over Ethernet.
Dependencies: C12832_lcd EthernetInterface MQTTPacket mbed-rtos mbed
main.cpp
00001 /******************************************************************************* 00002 * Copyright (c) 2014 IBM Corp. 00003 * 00004 * All rights reserved. This program and the accompanying materials 00005 * are made available under the terms of the Eclipse Public License v1.0 00006 * and Eclipse Distribution License v1.0 which accompany this distribution. 00007 * 00008 * The Eclipse Public License is available at 00009 * http://www.eclipse.org/legal/epl-v10.html 00010 * and the Eclipse Distribution License is available at 00011 * http://www.eclipse.org/org/documents/edl-v10.php. 00012 * 00013 * Contributors: 00014 * Ian Craggs - initial API and implementation and/or initial documentation 00015 *******************************************************************************/ 00016 00017 #include "mbed.h" 00018 #include "EthernetInterface.h" 00019 #include "C12832_lcd.h" 00020 00021 #include "MQTTPacket.h" 00022 00023 DigitalOut myled(LED2); 00024 C12832_LCD lcd; 00025 00026 int publish(char* payload) 00027 { 00028 int rc = 0; 00029 int len = 0; 00030 int payloadlen = strlen(payload); 00031 MQTTString topicString = MQTTString_initializer; 00032 MQTTPacket_connectData data = MQTTPacket_connectData_initializer; 00033 TCPSocketConnection mysock; 00034 unsigned char buf[1024]; 00035 int buflen = sizeof(buf); 00036 00037 data.clientID.cstring = "0x556677448899330000"; 00038 data.keepAliveInterval = 30; 00039 data.cleansession = 1; 00040 data.MQTTVersion = 3; 00041 00042 mysock.connect("m2m.eclipse.org", 1883); 00043 00044 len = MQTTSerialize_connect((unsigned char*)buf, buflen, &data); 00045 00046 topicString.cstring = "base"; 00047 len += MQTTSerialize_publish((unsigned char*)buf + len, buflen - len, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen); 00048 00049 len += MQTTSerialize_disconnect((unsigned char*)buf + len, buflen - len); 00050 00051 rc = 0; 00052 while (rc < len) { 00053 int rc1 = mysock.send((char*)buf, len); 00054 if (rc1 == -1) { 00055 lcd.printf("Send failed\n"); 00056 break; 00057 } else 00058 rc += rc1; 00059 } 00060 if (rc == len) 00061 lcd.printf("Sent: %s \n", payload); 00062 wait(0.2); 00063 00064 return 0; 00065 } 00066 00067 int main() 00068 { 00069 EthernetInterface eth; 00070 eth.init(); //Use DHCP 00071 eth.connect(); 00072 lcd.printf("IP Address is %s\n", eth.getIPAddress()); 00073 00074 myled = 1; 00075 publish("Message 1"); 00076 wait(0.2); 00077 myled = 0; 00078 publish("Message 2"); 00079 wait(0.2); 00080 00081 eth.disconnect(); 00082 }
Generated on Mon Jul 18 2022 05:09:01 by 1.7.2