Uses 1103K of libraries. Click here for Pure Java version (4531L/22K).
1 | !7 |
2 | |
3 | lib 1400324 // Eclipse Paho (MQTT) |
4 | |
5 | import org.eclipse.paho.client.mqttv3.*; |
6 | |
7 | cmodule MQTTSpike > DynPrintLog {
|
8 | switchable S topic = "iot_data"; |
9 | S messageText; |
10 | transient MqttClient client; |
11 | |
12 | visual centerAndSouthWithMargins(super, |
13 | dm_textFieldAndSubmit messageText('sendMessage, buttonText := "Send message"));
|
14 | |
15 | start-thread {
|
16 | client = new MqttClient("tcp://localhost:1883", MqttClient.generateClientId());
|
17 | client.setCallback(new MyCallback); |
18 | client.connect(); |
19 | client.subscribe(topic); |
20 | print("Connected & subscribed to " + topic);
|
21 | } |
22 | |
23 | void cleanMeUp_mqtt ctex {
|
24 | if (client != null) {
|
25 | client.disconnect(); |
26 | client.close(); |
27 | } |
28 | } |
29 | |
30 | class MyCallback implements MqttCallback {
|
31 | public void connectionLost(Throwable throwable) enter {
|
32 | print("Connection to MQTT broker lost!");
|
33 | } |
34 | |
35 | public void messageArrived(S s, MqttMessage mqttMessage) enter {
|
36 | print("Message received: "+ fromUtf8(mqttMessage.getPayload()));
|
37 | } |
38 | |
39 | public void deliveryComplete(IMqttDeliveryToken token) enter {
|
40 | print("Delivery complete: " + token);
|
41 | } |
42 | } |
43 | |
44 | void sendMessage ctex {
|
45 | temp enter(); |
46 | new MqttMessage message; |
47 | message.setPayload(toUtf8(messageText)); |
48 | client.publish(topic, message); |
49 | print("Published message: " + messageText);
|
50 | } |
51 | |
52 | // API |
53 | |
54 | void sendMessage(S topic, S text) ctex {
|
55 | new MqttMessage message; |
56 | message.setPayload(toUtf8(text)); |
57 | client.publish(topic, message); |
58 | print("Published message in " + topic + ": " + text);
|
59 | } |
60 | } |
Began life as a copy of #1026859
download show line numbers debug dex old transpilations
Travelled to 7 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt, xrpafgyirdlv
No comments. add comment
| Snippet ID: | #1026860 |
| Snippet name: | MQTT Subscriber & Publisher Spike (also used in Smart Home Demo) |
| Eternal ID of this version: | #1026860/8 |
| Text MD5: | 2dfeff8fc1626a0e2799653bc804be4c |
| Transpilation MD5: | 30103c98fe539d92cb7c25261709000f |
| Author: | stefan |
| Category: | javax / mqtt |
| Type: | JavaX source code (Dynamic Module) |
| Public (visible to everyone): | Yes |
| Archived (hidden from active list): | No |
| Created/modified: | 2020-01-29 23:41:55 |
| Source code size: | 1618 bytes / 60 lines |
| Pitched / IR pitched: | No / No |
| Views / Downloads: | 481 / 1679 |
| Version history: | 7 change(s) |
| Referenced in: | [show references] |