Create an SMQ client instance and initiate the connection with the broker.
- string | function URL - A fully qualified HTTP URL or a function.
- table op - Optional connection option(s)
- uid - A universally unique client identifier (uid) must be unique across all clients connecting to the same broker instance. The uid is used by the broker instance to store data related to the client; hence it is important that the uid remain the same when connecting to a broker if durable subscriptions are required. The client Lua stack will create a uid based on the IP address if no uid is specified.
- info - An optional string that may provide information to server code interacting with the broker. This string is also passed into the optional broker's authentication callback function. See the info attribute in the server's peer table for details.
- ping - time in seconds between SMQ ping messages sent to the server. The default value is 120 seconds.
- pong - Max time in seconds to wait for pong responses from the broker. The default value is 10 seconds.
- Any key/value accepted by http:create(op) and http:request(op) such as 'trusted=true'. The option table is passed in to these two functions. The SMQ client is internally using the http client library for connecting to the SMQ broker.
Note: the Lua client is similar to the JavaScript client, but you cannot subscribe or publish before the "onconnect" callback is called. You must re-subscribe to topics should the connection go down.
Example
-- Connect to cluster node2: https://simplemq.com/
local url="https://node2.simplemq.com/smq.lsp"
local op={trusted=true}
local smq=require"smq.client".create(url,op)
-- Run the timer based publish test
local function runTest()
trace"Starting test"
ba.timer(function()
for i = 1, 100 do
smq:publish({count=i}, "mytopic.json")
coroutine.yield(true) -- Wait for the next timer tick
end
trace("Exiting timer coroutine")
end):set(1, true, true)
end
-- Received message for topic 'mytopic.json'
local function onmsg(message)
trace(message.count)
end
-- Wait for connection before subscribing
smq.onconnect=function(tid, rnd, ipaddr)
local op = {
datatype="json",
onmsg=onmsg, -- callback for topic 'mytopic.json'
onack=runTest, -- We start the publish test when subscribed
}
smq:subscribe("mytopic.json", op)
end
function onunload()
trace"Stopping SMQ test"
smq:close()
end
trace"Starting SMQ test"
The following provides a list of methods available in an SMQ
Lua client instance. Most functions do not immediately return a
value, but are instead reporting the return value in optional callback
functions. Only methods that include a description for a return value
are, in fact, returning a value.
- smq:create(topic [,subtopic] [,onack])
-
Create a topic and fetch the topic ID (tid). The SMQ protocol is
optimized and does not directly use a string when publishing, but a
number. The server randomly creates a 32 bit number and persistently
stores the topic name and number. The 'create' method is typically
used prior to publishing a message on a
specific topic if the server logic implements
authorization. Otherwise, the publish method
can be used directly with a topic string since the publish method
takes care of first creating a topic if you publish to a topic unknown
to the client stack.
- string topic - The topic name where you plan on publishing messages.
- string subtopic - Provide the second level topic name if you plan on using this feature.
- function onack(accepted, topic, tid, [subtopic, subtid]) - The callback is called when the broker sends the response message.
- boolean accepted - set to 'true' if the broker accepted the
(create) request, and 'false' if the broker's optional authorization
callback function has denied access.
- string topic - the topic name requested.
- number tid - the unique and persistent 32 bit topic ID (tid) created by the server.
- string subtopic - the sub-topic name requested, or 'undefined' if you did not request a sub-topic.
- number subtid - the unique and persistent 32 bit sub-topic ID (tid) created by the server or 'undefined' if you did not request a sub-topic.
- smq:createsub(subtopic [,onsuback])
-
Create a sub-topic and fetch the subtopic ID. The createsub method
is typically used prior to publishing a message on a specific topic,
and sub-topic, (if) the server logic implements "authorization".
Alternatively, the publish method may be used
directly with topic and sub-topic strings, respectively. The
publish method will manage the sequence and creation of a topic,
then sub-topic, if you publish to a topic and/or sub-topic that is
unknown to the client stack.
- string subtopic - The sub-topic name.
- function onsuback(accepted,subtopic,subtid) - The callback is called when the broker sends the response message.
- boolean accepted - set to 'true' if the broker accepted the
(createsub) request, and 'false' if the broker's optional authorization
callback function has denied access.
- string subtopic - the sub-topic name requested.
- number subtid - the unique and persistent 32 bit sub-topic ID.
- smq:close()
-
Gracefully close the connection. You cannot publish any messages after calling this method.
- smq:gettid()
-
Get the client's ephemeral topic ID. Each client is assigned a
unique topic ID, and this topic ID is included when publishing a
message. All subscribers receiving the message published by a client
can use this (tid) for identification purposes or for sending messages
directly to the "publisher" of the message. See the subscribe onmsg for example code.
- smq:publish(data, topic [,subtopic])
-
Publish messages to a topic and optionally to a sub-topic. Topics
may be topic names (strings), topic IDs (numbers), or ephemeral topic
IDs (numbers). Messages publishing unresolved topic names are
temporarily queued. Pending topic names are resolved by calling create and/or createsub
and result in the message being de-queued and published, (if) create
and/or createsub reports are "accepted" by the server. Once the server
denies a create and/or createsub report request, all messages sent to
(unresolved) topic names are de-queued and silently discarded. You may consider
using create and/or createsub prior to calling "publish" if the server
solution implements topic authorization. Note: max payload size is 0xFFF0.
- string|table data - The data to send; a Lua string can include binary data. A Lua table is converted to JSON.
- string|number topic - A topic name or a topic ID fetched from a previous call to method create.
The topic ID can also be an ephemeral topic ID received in a previous
call to an onmsg callback function. See callback function onmsg's argument ptid for details.
- string|number subtopic - An optional sub-topic name or a sub-topic ID fetched from a previous call to method createsub.
- smq:subscribe(topic [,subtopic] [,settings])
-
Subscribe to a topic and optionally to a sub-topic. You can
subscribe multiple times to the same topic if you use sub-topics.
Subscribing to a topic without providing a sub-topic introduces a
"catch all" for sub-topics that do not correspond to any subscribed sub-topics.
The topic name "self" is interpreted as subscribing to the client's
own Ephemeral Topic ID -- in other words, it means subscribing to the
(tid) returned by method gettid. Subscribing to your own Topic ID makes it possible for other connected clients to send a message directly to this client.
Subscription requests are stored in an internal queue and later
processed if the server connection is not established. Subscription
requests are also stored temporarily if the sub-topic name must be
resolved prior to subscribing.
- string topic - The topic to subscribe to. The topic name 'self' means subscribing to the client's own Ephemeral Topic ID.
- string|number subtopic - An optional sub-topic name or a sub-topic ID fetched via method createsub.
- table settings - 'settings' is a Lua table with the following optional properties:
- datatype - The type of data
that you are expecting to receive on the subscribed topic. If none is
specified, the 'onmsg' callback will receive Lua strings.
The available datatype is:
- json - Evaluates the response first as text and then as JSON
and returns a Lua table. The JSON data is parsed in a strict
manner; any malformed JSON is rejected.
The "onmsg" callback will not be called if the data cannot be converted
to the requested data-type. Instead, the data will be sent to the global onmsg event handler function, if installed.
- onack(accepted, topic, tid [,subtopic, subtid]) -
- boolean accepted - Set to 'true' if the broker accepted the
subscribe request, and 'false' if the broker's optional authorization
callback function denied access.
- string topic - The topic name requested.
- number tid - The unique and persistent 32 bit topic ID (tid) created by the server.
- string subtopic - The sub-topic name requested, or 'undefined' if you did not request a sub-topic.
- number subtid - The unique and persistent 32 bit sub-topic ID created by the server, or 'undefined' if you did not request a sub-topic.
- onmsg(message,ptid,tid,subtid)
- The callback function is called when the client receives data on the
subscribed topic and optional sub-topic. You can install multiple
callbacks for the same topic if you use sub-topics. The callback will
then be called for the correct topic and sub-topic. Sub-topics not
subscribed to will be sent to the callback with no subtopic or to the global onmsg event handler if no callback is provided.
- string|table message - The data received from
the publisher. The message type is controlled by the datatype parameter
in the optional settings. The data will be a string if
you did not specify a datatype or a
table if you specified 'json'.
- number ptid - Publisher ephemeral topic ID. The (ptid)
enables you to send a message directly to the publisher without having
to create dynamically named topics, which is common in a traditional
pub/sub protocol.
- number tid - The topic ID.
- number subtid - The sub-topic ID, or 'undefined' if you did not request a sub-topic when you subscribed to the topic.
- smq:unsubscribe(topic)
-
Requests the server to unsubscribe the client from a topic. All registered onmsg callback functions, including all callbacks for sub-topics, will be removed from the client stack.
- string|number topic - Topic name or topic ID.
- smq:observe(topic,onchange)
-
Requests the broker to provide change notification events when the number
of subscribers to a specific topic changes. See the JavaScript client -> observe for details on using this method.
See the broker's SMQ:observe() documentation for details on using observe()
- string|number topic - Topic name or topic ID.
- function onchange(subscribers, topic) - The callback function is called when the broker sends a change notification event.
- number subscribers - The number of clients subscribed to the topic.
- string|number topic - The topic name requested or the ephemeral topic ID requested to be observed.
- smq:unobserve(topic)
-
Stop receiving change notifications for a topic or ephemeral topic ID.
- string|number topic - Topic name or topic ID.
- smq:tid2topic(tid)
-
Translates topic ID to topic name.
- number tid - Topic ID.
- Returns: string|null - Returns the topic name if the topic name is registered in the client.
- smq:topic2tid(topic)
-
Translates topic name to topic ID.
- string topic - Topic name.
- Returns: number|null - Returns the topic ID if the topic name is registered in the client.
- smq:tid2subtopic(tid)
-
Translates sub-topic ID to sub-topic name.
- number tid - Sub-topic ID.
- Returns: string|null - Returns the sub-topic name if the sub-topic name is registered in the client.
- smq:subtopic2tid(subtopic)
-
Translates sub-topic name to sub-topic ID.
- string subtopic - Sub-topic name.
- Returns: number|null - Returns the sub-topic ID if the sub-topic name is registered in the client.
- SMQ Table Event Handler Functions
-
You can set the following event callback functions on an SMQ instance.
- function smq.onauth(rnd, ipaddr)
-
The onauth function must be set if the server requires
authentication. The event function is called during the SMQ handshaking
phase and just before the client SMQ stack sends the CONNECT event to
the broker.
- number rnd - A random number created by the server that can be used for securing hash based password encryption.
- string ipaddr - The client's IP address as seen by the
server. This address may not be the same as the client's IP address if
the client is behind a NAT router. The client's IP address can be used
by hash based authentication to further strengthen the hash value.
- Returns: the password/token as required by the broker's "authenticate" callback. See smq.create() for details.
- function smq.onconnect(tid, rnd, ipaddr)
-
The onconnect function is called after a successful connection
sequence and if the server accepted the credentials. If the connection
was unsuccessful or if the connection was not accepted by the broker,
the onclose function is called instead.
- number tid - The client's unique topic ID created by the
server. This tid is referred to as the ephemeral tid and is the same
tid returned by method gettid.
- number rnd - The same random number as provided to the onauth function.
- string ipaddr - The same IP address as provided to the onauth function.
- function smq.onmsg(data,ptid,tid,subtid)
-
The onmsg function is called if you subscribe to a topic and do not
provide a callback function when subscribing. The onmsg function is
also called if a "topic" callback function fails to decode the data as
specified in the datatype.
- string data - The raw data provided by the publisher.
- number ptid - Publisher ephemeral topic ID.
- number tid - The topic ID.
- number subtid - The sub-topic ID.
- function smq.onclose(message,canreconnect)
-
The onclose function is called if the connection cannot be
established, the server denied access, the server gracefully closed
the connection, or if the connection unexpectedly closed.
The onclose function can request the SMQ client to attempt to
reconnect. Function onreconnect is called if the re-connect attempt is
successful. The onclose function is called again if the re-connection
attempt is unsuccessful.
- string message - The reason for why the connection was closed.
- boolean canreconnect - If the client can re-connect, for example, by reconnect with new credentials.
- Returns: number|null - If the client can re-connect, the
callback function can return the number of milliseconds the client
should wait until it attempts to reconnect.
- function smq.onreconnect(tid, rnd, ipaddr)
-
The onreconnect function is called if the connection closed, the
onclose function requested the SMQ client to reconnect, and if the
re-connect was successful. Function onconnect is called if you do not provide an onreconnect.
- tid - The new ephemeral topic ID.
- rnd - A new random number.
- ipaddr - The client's IP address. This address may not be
the same as the address received in "onconnect". For example, a mobile
phone that loses wifi signals and switches to a cellular network will
have a new IP address when it reconnects.