This commit is contained in:
2026-01-26 07:14:29 +07:00
commit 9fb5e046ce
16 changed files with 4292 additions and 0 deletions

94
app/spawn_example.jl Normal file
View File

@@ -0,0 +1,94 @@
using Revise # remove when this package is completed
using MQTTClient, GeneralUtils
using Base.Threads
# --------------------------------------- code width = 100 --------------------------------------- #
function count_and_listen()
total_count = 0
# MQTT on-message function
function on_message(client::MQTTClient.MQTTClient, message::MQTTClient.MQTTMessage)
msg = String(message.payload)
println("Received MQTT message: $msg")
try
num = parse(Int, msg)
total_count += num
catch e
println("Error parsing message: $e")
end
end
# Connect to MQTT broker
client = MQTTClient.MQTTClient("client-1", "tcp://localhost:1883")
connect(client)
subscribe(client, "topic", on_message)
# Count from 1 to 1,000,000,000
for i in 1:1_000_000_000
total_count += i
end
# Disconnect from MQTT broker
unsubscribe(client, "topic")
disconnect(client)
return total_count
end
# Spawn a process to run count_and_listen function
task = @spawn count_and_listen()
# Get the result
result = fetch(task)
# Stop the spawned task
interrupt(task)
using MQTTClient
broker = "test.mosquitto.org"
#Define the callback for receiving messages.
function on_msg(topic, payload)
info("Received message topic: [", topic, "] payload: [", String(payload), "]")
end
#Instantiate a client and connection.
client, connection = MakeConnection(broker, 1883)
connect(client, connection)
#Set retain to true so we can receive a message from the broker once we subscribe
#to this topic.
publish(client, "jlExample", "Hello World!", retain=true)
#Subscribe to the topic we sent a retained message to.
subscribe(client, "jlExample", on_msg, qos=QOS_1)
#Unsubscribe from the topic
unsubscribe(client, "jlExample")
#Disconnect from the broker. Not strictly needed as the broker will also
#disconnect us if the socket is closed. But this is considered good form
#and needed if you want to resume this session later.
disconnect(client)