@sedge-hq/mqtt 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/mqtt.ts +13 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sedge-hq/mqtt",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "MQTT for sedge: wake it when a message arrives on a topic, from a sensor, a home hub or a device.",
5
5
  "keywords": [
6
6
  "iot",
package/src/mqtt.ts CHANGED
@@ -7,8 +7,11 @@ const KEEP = 20_000;
7
7
  const clip = (text: string) =>
8
8
  text.length > KEEP ? `${text.slice(0, KEEP)}\n… (${text.length - KEEP} more characters)` : text;
9
9
 
10
- /** A payload as the agent reads it: JSON laid out, text as it is, binary only by its size. */
11
- export const readable = (payload: Uint8Array): string => {
10
+ /**
11
+ * A payload as data: JSON as its value (so `payload.moisture < 30` and `payload > 30` work), text
12
+ * as it is, binary only by its size. Anything very long is cut, as text.
13
+ */
14
+ export const decode = (payload: Uint8Array): unknown => {
12
15
  let text: string;
13
16
  try {
14
17
  text = new TextDecoder('utf-8', { fatal: true }).decode(payload);
@@ -16,21 +19,19 @@ export const readable = (payload: Uint8Array): string => {
16
19
  return `(${payload.length} bytes of binary)`;
17
20
  }
18
21
  if (text.includes('\u0000')) return `(${payload.length} bytes of binary)`;
22
+ if (text.length > KEEP) return clip(text);
19
23
  try {
20
- const value: unknown = JSON.parse(text);
21
- if (typeof value === 'object' && value !== null)
22
- return clip(JSON.stringify(value, null, 2));
24
+ return JSON.parse(text) as unknown;
23
25
  } catch {
24
- // Not JSON: plain text.
26
+ return text;
25
27
  }
26
- return clip(text);
27
28
  };
28
29
 
29
- /** One event per message: the topic, then what was sent. */
30
- export const happening = (topic: string, payload: Uint8Array): Happening => {
31
- const body = readable(payload);
32
- return { text: body.includes('\n') ? `${topic}\n${body}` : `${topic}: ${body}` };
33
- };
30
+ /** One event per message, with its topic and payload as details the agent and conditions read. */
31
+ export const happening = (topic: string, payload: Uint8Array): Happening => ({
32
+ text: `Message on ${topic}`,
33
+ details: { topic, payload: decode(payload) },
34
+ });
34
35
 
35
36
  /** A sensor, a home hub, a device: anything that publishes to an MQTT broker. */
36
37
  export default defineSignal({