Skip to content

Commit

Permalink
added mqtt sample
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Jun 30, 2023
1 parent 03aecf3 commit c09018d
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 10 deletions.
20 changes: 16 additions & 4 deletions packages/net/src/mqtt.ts
Expand Up @@ -557,16 +557,28 @@ export class MQTTClient {
this.readyState = MQTTState.Connected
}

// Publish a message
/**
* Attempts to publish a message on the MQTT stack
* @param topic topic of the message
* @param message payload as string, object that will be JSON serialized or buffer
* @param qos
* @param retained
* @returns
*/
public async publish(
topic: string,
message?: string | Buffer,
message?: string | object | Buffer,
qos: number = Constants.DefaultQos,
retained: boolean = false
): Promise<boolean> {
const buf = typeof message === "string" ? Buffer.from(message) : message
message = null
if (!(await this.canSend())) return false
const buf: Buffer =
typeof message === "string"
? Buffer.from(message)
: message instanceof Buffer
? message
: Buffer.from(JSON.stringify(message))
message = null
const messageLen = buf ? buf.length : 0
this.trace(`publish: ${topic} ${messageLen}b`)
await this.send(createPublishHeader(topic, messageLen, qos, retained))
Expand Down
10 changes: 7 additions & 3 deletions packages/runtime/src/schedule.ts
Expand Up @@ -2,14 +2,15 @@ import { AsyncVoid } from "@devicescript/core"

/**
* Schedules a handler to be called at a later time. Executes timeout before interval if combined.
* If not specified, default to timeout 20ms and interval 60s.
*
* @param handler function to execute
* @param options options to configure the scheduling
* @returns clear timer function
*/
export function schedule(
handler: () => AsyncVoid,
options: {
options?: {
/**
* Time in milliseconds to wait before the first execution of the handler.
*/
Expand All @@ -30,8 +31,11 @@ export function schedule(

if (!handler) return unsub

let { interval, timeout } = options
if (interval === undefined && timeout === undefined) timeout = 20
let { interval, timeout } = options || {}
if (interval === undefined && timeout === undefined) {
timeout = 20
interval = 60000
}
if (timeout >= 0 && interval >= 0) {
timerId = setTimeout(async () => {
await handler()
Expand Down
23 changes: 23 additions & 0 deletions packages/sampleprj/src/maintemperateshtc3.ts
@@ -0,0 +1,23 @@
import "@dsboard/adafruit_qt_py_c3"
import { deviceIdentifier } from "@devicescript/core"
import { startMQTTClient } from "@devicescript/net"
import { startSHTC3 } from "@devicescript/drivers"
import { schedule } from "@devicescript/runtime"

// mqtt settings
const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})
const topic = `devs/temp/${deviceIdentifier("self")}`
console.log({ topic })

// sensors
const { temperature } = await startSHTC3()
// pushing temperature every minute
schedule(async () => {
const t = await temperature.reading.read()
console.data({ t })
await mqtt.publish(topic, { t })
})
4 changes: 1 addition & 3 deletions website/docs/api/servers/aht20.mdx
Expand Up @@ -13,7 +13,5 @@ Driver for AHT20 temperature/humidity sensor at I2C address `0x38`.
import { startAHT20 } from "@devicescript/drivers"

// highlight-next-line
await startAHT20()
const t = new ds.Temperature()
const h = new ds.Humidity()
const { temperature, humidity } = await startAHT20()
```
41 changes: 41 additions & 0 deletions website/docs/samples/temperature-mqtt.mdx
@@ -0,0 +1,41 @@
---
sidebar_position: 2
---

# Temperature + MQTT

This sample uses an ESP32-C3 board [Adafruit QT Py C3](/devices/esp32/adafruit-qt-py-c3)
and a [SHTC3 sensor](/api/servers/shtc3) to publish a temperature reading to
the [HiveMQ public MQTT broker](https://www.mqtt-dashboard.com/) every minute.

```ts
import "@dsboard/adafruit_qt_py_c3"
import { deviceIdentifier } from "@devicescript/core"
import { startMQTTClient } from "@devicescript/net"
import { startSHTC3 } from "@devicescript/drivers"
import { schedule } from "@devicescript/runtime"

// mqtt settings
const mqtt = await startMQTTClient({
host: "broker.hivemq.com",
proto: "tcp",
port: 1883,
})
const topic = `devs/temp/${deviceIdentifier("self")}`
console.log({ topic })

// sensors
const { temperature } = await startSHTC3()
// pushing temperature every minute
schedule(async () => {
const t = await temperature.reading.read()
console.data({ t })
await mqtt.publish(topic, { t })
})
```

:::warning

This is a public MQTT broker, anyone can listen to the messages.

:::

0 comments on commit c09018d

Please sign in to comment.