Skip to content

Make receiving messages event driven #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,28 @@ mqtt.connect
Publish message to topic.

```ruby
while !mqtt.connected do
ESP32::System.delay(100)
end
mqtt.publish("topic", 'message')
```

Subscribe to topic and get message.
Subscribe to one or more topics to receive messages. Received messages are event driven. For each message, the main mruby task pauses temporarily, allowing the block given for the receiving topic to run.

```ruby
mqtt.subscribe("topic")
topic, message = mqtt.get
mqtt.subscribe("topic1") do |message|
puts "Received from topic1: #{message}"
end

mqtt.on_message_from("topic2") do |message|
puts "New message from topic2: #{message}"
end
mqtt.subscribe("topic2")

loop do
# Do whatever in your main loop.
ESP32::System.delay(1000)
end
```

Disconnect.
Expand Down
53 changes: 52 additions & 1 deletion mrblib/mrb_esp32_mqtt.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,58 @@
module ESP32
module MQTT
class Client
attr_accessor :ca, :cert, :key
attr_accessor :ca, :cert, :key, :connected

def initialize(host, port)
self._initialize(host, port)

@connected = false
@connect_callbacks = []
@message_callbacks = {}

self.set_connected_handler do
@connected = true
@connect_callbacks.each { |cb| cb.call }
@connect_callbacks = []
end

self.set_disconnected_handler do
@connected = false
end

self.set_unsubscribed_handler do |topic|
@message_callbacks[topic] = nil
end

# C calls this block with every received message.
self.set_data_handler do |topic, message|
@message_callbacks[topic].call(message) if @message_callbacks[topic]
end
end

def subscribe(topic, &block)
@message_callbacks[topic] = block if block

# Take semaphore

if @connected
self._subscribe(topic)
else
self.on_connect do
self._subscribe(topic)
end
end

# Release semaphore
end

def on_connect(&block)
@connect_callbacks << block
end

def on_message_from(topic, &block)
@message_callbacks[topic] = block
end
end
end
end
Loading