ot-gateway 0.8.0 → 0.9.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.
@@ -51787,7 +51787,12 @@ var MqttSettings = Schema_exports.Struct({
51787
51787
  clientId: Schema_exports.optionalKey(ConnectString),
51788
51788
  username: Schema_exports.optionalKey(ConnectString),
51789
51789
  /** Name of the environment variable holding the password. Never inline secrets. */
51790
- passwordEnv: Schema_exports.optionalKey(Schema_exports.String)
51790
+ passwordEnv: Schema_exports.optionalKey(Schema_exports.String),
51791
+ /**
51792
+ * The MQTT spoken: `auto` dials with MQTT 5 and falls back to 3.1.1 for a
51793
+ * broker that refuses it; `5` or `3.1.1` speak only that.
51794
+ */
51795
+ version: Schema_exports.Literals(["auto", "5", "3.1.1"]).pipe(Schema_exports.withDecodingDefaultKey(Effect_exports.succeed("auto")))
51791
51796
  });
51792
51797
  var loopbackIpv4 = new RegExp(`^127(\\.${octet}){3}$`);
51793
51798
  var isLoopbackHost = (hostname3) => {
@@ -58109,14 +58114,20 @@ var makeFrameReader = (maximumPacketSize = Number.POSITIVE_INFINITY) => {
58109
58114
  };
58110
58115
  var encodeConnect = (connect2) => {
58111
58116
  const flags = (connect2.username === void 0 ? 0 : 128) | (connect2.password === void 0 ? 0 : 64) | (connect2.will?.retain === true ? 32 : 0) | (connect2.will?.qos ?? 0) << 3 | (connect2.will === void 0 ? 0 : 4) | (connect2.cleanStart ? 2 : 0);
58112
- const body = new Writer2().string("MQTT").byte(5).byte(flags).u16(connect2.keepAliveSeconds).bytes(
58113
- encodeProperties((w) => {
58114
- w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58115
- if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58116
- })
58117
- ).string(connect2.clientId);
58117
+ const v5 = (connect2.protocolVersion ?? 5) === 5;
58118
+ const body = new Writer2().string("MQTT").byte(v5 ? 5 : 4).byte(flags).u16(connect2.keepAliveSeconds);
58119
+ if (v5) {
58120
+ body.bytes(
58121
+ encodeProperties((w) => {
58122
+ w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58123
+ if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58124
+ })
58125
+ );
58126
+ }
58127
+ body.string(connect2.clientId);
58118
58128
  if (connect2.will !== void 0) {
58119
- body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1))).string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58129
+ if (v5) body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1)));
58130
+ body.string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58120
58131
  }
58121
58132
  if (connect2.username !== void 0) body.string(connect2.username);
58122
58133
  if (connect2.password !== void 0) body.binary(encoder9.encode(connect2.password));
@@ -58125,16 +58136,17 @@ var encodeConnect = (connect2) => {
58125
58136
  var decodeConnect = (body) => decodeWith2(body, (r) => {
58126
58137
  const protocol = r.string();
58127
58138
  const level = r.byte();
58128
- if (protocol !== "MQTT" || level !== 5) {
58139
+ if (protocol !== "MQTT" || level !== 5 && level !== 4) {
58129
58140
  throw new MqttCodecError({ message: `unsupported protocol ${protocol} level ${level}` });
58130
58141
  }
58142
+ const v5 = level === 5;
58131
58143
  const flags = r.byte();
58132
58144
  const keepAliveSeconds = r.u16();
58133
- const properties = r.properties();
58145
+ const properties = v5 ? r.properties() : /* @__PURE__ */ new Map();
58134
58146
  const clientId = r.string();
58135
58147
  let will;
58136
58148
  if ((flags & 4) !== 0) {
58137
- r.properties();
58149
+ if (v5) r.properties();
58138
58150
  const topic = r.string();
58139
58151
  const payload = decoder4.decode(r.binary());
58140
58152
  will = { topic, payload, qos: flags >> 3 & 1 ? 1 : 0, retain: (flags & 32) !== 0 };
@@ -58144,6 +58156,7 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58144
58156
  const expiry = properties.get(Property.SessionExpiryInterval);
58145
58157
  const maximumPacketSize = properties.get(Property.MaximumPacketSize);
58146
58158
  return {
58159
+ protocolVersion: v5 ? 5 : 4,
58147
58160
  clientId,
58148
58161
  keepAliveSeconds,
58149
58162
  cleanStart: (flags & 2) !== 0,
@@ -58154,26 +58167,39 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58154
58167
  ...will === void 0 ? {} : { will }
58155
58168
  };
58156
58169
  });
58157
- var decodeConnack = (body) => decodeWith2(body, (r) => ({
58158
- sessionPresent: (r.byte() & 1) !== 0,
58159
- reasonCode: r.byte(),
58160
- properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map()
58161
- }));
58162
- var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map()) => packet(
58163
- PacketType.CONNACK,
58164
- 0,
58165
- new Writer2().byte(0).byte(reasonCode).bytes(
58166
- encodeProperties((w) => {
58167
- for (const [id2, value4] of properties) {
58168
- w.byte(id2);
58169
- const kind = propertyKinds[id2];
58170
- if (kind === "u16") w.u16(value4);
58171
- else if (kind === "u32") w.u32(value4);
58172
- else w.byte(value4);
58173
- }
58174
- })
58175
- ).toBytes()
58176
- );
58170
+ var returnCodeReasons = { 1: 132, 2: 133, 3: 136, 4: 134, 5: 135 };
58171
+ var reasonReturnCodes = { 132: 1, 133: 2, 136: 3, 134: 4, 135: 5 };
58172
+ var decodeConnack = (body, version2 = 5) => decodeWith2(body, (r) => {
58173
+ const sessionPresent = (r.byte() & 1) !== 0;
58174
+ const code = r.byte();
58175
+ if (version2 === 4) {
58176
+ return { sessionPresent, reasonCode: code === 0 ? 0 : returnCodeReasons[code] ?? 128, properties: /* @__PURE__ */ new Map() };
58177
+ }
58178
+ return { sessionPresent, reasonCode: code, properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map() };
58179
+ });
58180
+ var refusesProtocolLevel = (connack) => connack.reasonCode === 132 || connack.reasonCode === 1;
58181
+ var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map(), version2 = 5) => {
58182
+ if (version2 === 4) {
58183
+ const returnCode = reasonCode === 0 ? 0 : reasonReturnCodes[reasonCode] ?? 3;
58184
+ return packet(PacketType.CONNACK, 0, Uint8Array.of(0, returnCode));
58185
+ }
58186
+ return packet(
58187
+ PacketType.CONNACK,
58188
+ 0,
58189
+ new Writer2().byte(0).byte(reasonCode).bytes(
58190
+ encodeProperties((w) => {
58191
+ for (const [id2, value4] of properties) {
58192
+ w.byte(id2);
58193
+ const kind = propertyKinds[id2];
58194
+ if (kind === "u16") w.u16(value4);
58195
+ else if (kind === "u32") w.u32(value4);
58196
+ else w.byte(value4);
58197
+ }
58198
+ })
58199
+ ).toBytes()
58200
+ );
58201
+ };
58202
+ var encodeUnsupportedLevelConnack = () => packet(PacketType.CONNACK, 0, Uint8Array.of(0, 1));
58177
58203
  var connackReasonName = (code) => ({
58178
58204
  128: "unspecified error",
58179
58205
  129: "malformed packet",
@@ -58190,9 +58216,13 @@ var connackReasonName = (code) => ({
58190
58216
  151: "quota exceeded",
58191
58217
  159: "connection rate exceeded"
58192
58218
  })[code] ?? `reason code 0x${code.toString(16)}`;
58193
- var encodePublish = (publish2) => {
58219
+ var encodePublish = (publish2, version2 = 5) => {
58194
58220
  const body = new Writer2().string(publish2.topic);
58195
58221
  if (publish2.qos > 0) body.u16(publish2.packetId ?? 0);
58222
+ if (version2 === 4) {
58223
+ body.bytes(publish2.payload);
58224
+ return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58225
+ }
58196
58226
  body.bytes(
58197
58227
  encodeProperties((w) => {
58198
58228
  w.byte(Property.PayloadFormatIndicator).byte(1);
@@ -58205,12 +58235,12 @@ var encodePublish = (publish2) => {
58205
58235
  ).bytes(publish2.payload);
58206
58236
  return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58207
58237
  };
58208
- var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58238
+ var decodePublish = (flags, body, version2 = 5) => decodeWith2(body, (r) => {
58209
58239
  const qos = flags >> 1 & 3;
58210
58240
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58211
58241
  const topic = r.string();
58212
58242
  const packetId = qos > 0 ? r.u16() : void 0;
58213
- const properties = r.properties();
58243
+ const properties = version2 === 5 ? r.properties() : /* @__PURE__ */ new Map();
58214
58244
  const expiry = properties.get(Property.MessageExpiryInterval);
58215
58245
  const responseTopic = properties.get(Property.ResponseTopic);
58216
58246
  const correlationData = properties.get(Property.CorrelationData);
@@ -58227,29 +58257,34 @@ var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58227
58257
  });
58228
58258
  var pubackRefusesMessage = (reasonCode) => reasonCode === 135 || reasonCode === 144 || reasonCode === 149 || reasonCode === 153;
58229
58259
  var decodePuback = (body) => decodeWith2(body, (r) => ({ packetId: r.u16(), reasonCode: r.remaining > 0 ? r.byte() : 0 }));
58230
- var encodePuback = (packetId, reasonCode = 0) => packet(
58260
+ var encodePuback = (packetId, reasonCode = 0, version2 = 5) => version2 === 4 ? packet(PacketType.PUBACK, 0, new Writer2().u16(packetId).toBytes()) : packet(
58231
58261
  PacketType.PUBACK,
58232
58262
  0,
58233
58263
  new Writer2().u16(packetId).byte(reasonCode).bytes(encodeProperties(() => {
58234
58264
  })).toBytes()
58235
58265
  );
58236
- var encodeSubscribe = (subscribe2) => {
58237
- const body = new Writer2().u16(subscribe2.packetId).bytes(encodeProperties(() => {
58266
+ var encodeSubscribe = (subscribe2, version2 = 5) => {
58267
+ const body = new Writer2().u16(subscribe2.packetId);
58268
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58238
58269
  }));
58239
58270
  for (const { filter: filter14, qos, retainAsPublished, noLocal } of subscribe2.subscriptions) {
58240
- body.string(filter14).byte(qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0));
58271
+ const options3 = version2 === 5 ? qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0) : qos;
58272
+ body.string(filter14).byte(options3);
58241
58273
  }
58242
58274
  return packet(PacketType.SUBSCRIBE, 2, body.toBytes());
58243
58275
  };
58244
- var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58276
+ var decodeSubscribe = (body, version2 = 5) => decodeWith2(body, (r) => {
58245
58277
  const packetId = r.u16();
58246
- r.properties();
58278
+ if (version2 === 5) r.properties();
58247
58279
  const subscriptions = [];
58248
58280
  while (r.remaining > 0) {
58249
58281
  const filter14 = r.string();
58250
58282
  const options3 = r.byte();
58251
58283
  const qos = options3 & 3;
58252
58284
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58285
+ if (version2 === 4 && (options3 & 252) !== 0) {
58286
+ throw new MqttCodecError({ message: "reserved bits set in a subscription's options" });
58287
+ }
58253
58288
  subscriptions.push({
58254
58289
  filter: filter14,
58255
58290
  qos: qos === 1 ? 1 : 0,
@@ -58260,15 +58295,16 @@ var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58260
58295
  if (subscriptions.length === 0) throw new MqttCodecError({ message: "SUBSCRIBE without a topic filter" });
58261
58296
  return { packetId, subscriptions };
58262
58297
  });
58263
- var encodeSuback = (suback) => packet(
58264
- PacketType.SUBACK,
58265
- 0,
58266
- new Writer2().u16(suback.packetId).bytes(encodeProperties(() => {
58267
- })).bytes(Uint8Array.from(suback.reasonCodes)).toBytes()
58268
- );
58269
- var decodeSuback = (body) => decodeWith2(body, (r) => {
58298
+ var encodeSuback = (suback, version2 = 5) => {
58299
+ const body = new Writer2().u16(suback.packetId);
58300
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58301
+ }));
58302
+ const codes3 = version2 === 5 ? suback.reasonCodes : suback.reasonCodes.map((code) => code >= 128 ? 128 : code);
58303
+ return packet(PacketType.SUBACK, 0, body.bytes(Uint8Array.from(codes3)).toBytes());
58304
+ };
58305
+ var decodeSuback = (body, version2 = 5) => decodeWith2(body, (r) => {
58270
58306
  const packetId = r.u16();
58271
- r.properties();
58307
+ if (version2 === 5) r.properties();
58272
58308
  return { packetId, reasonCodes: [...r.rest()] };
58273
58309
  });
58274
58310
  var topicMatches = (filter14, topic) => {
@@ -58285,7 +58321,7 @@ var topicMatches = (filter14, topic) => {
58285
58321
  };
58286
58322
  var encodePingreq = () => Uint8Array.of(PacketType.PINGREQ << 4, 0);
58287
58323
  var encodePingresp = () => Uint8Array.of(PacketType.PINGRESP << 4, 0);
58288
- var encodeDisconnect = (reasonCode = 0) => reasonCode === 0 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58324
+ var encodeDisconnect = (reasonCode = 0, version2 = 5) => reasonCode === 0 || version2 === 4 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58289
58325
  var decodeDisconnect = (body) => decodeWith2(body, (r) => {
58290
58326
  const reasonCode = r.remaining > 0 ? r.byte() : 0;
58291
58327
  const reason = r.remaining > 0 ? r.properties().get(Property.ReasonString) : void 0;
@@ -58302,6 +58338,8 @@ var MqttRejected = class extends Schema_exports.TaggedError()("MqttRejected", {
58302
58338
  message: Schema_exports.String
58303
58339
  }) {
58304
58340
  };
58341
+ var MqttDowngrade = class extends Schema_exports.TaggedError()("MqttDowngrade", {}) {
58342
+ };
58305
58343
  var MqttPublishError = class extends Schema_exports.TaggedError()("MqttPublishError", {
58306
58344
  topic: Schema_exports.String,
58307
58345
  reason: Schema_exports.Literals(["unavailable", "rejected"]),
@@ -58334,7 +58372,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58334
58372
  const maxDelay = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(options3.reconnectDelay?.max ?? "15 seconds"));
58335
58373
  const connected = yield* Latch_exports.make(false);
58336
58374
  const firstDialDone = yield* Latch_exports.make(false);
58375
+ const firstDial = Deferred_exports.makeUnsafe();
58337
58376
  let session;
58377
+ let version2 = options3.protocolVersion === "3.1.1" ? 4 : 5;
58378
+ let lastTurn = Deferred_exports.makeUnsafe();
58379
+ Deferred_exports.doneUnsafe(lastTurn, Effect_exports.void);
58338
58380
  const runSession = (onConnected) => Effect_exports.scoped(
58339
58381
  Effect_exports.gen(function* () {
58340
58382
  const { pull } = yield* socket.reader;
@@ -58352,10 +58394,13 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58352
58394
  ),
58353
58395
  Deferred_exports.await(closed)
58354
58396
  );
58355
- const protocolError = (reasonCode, message) => write2(encodeDisconnect(reasonCode)).pipe(
58356
- Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58357
- Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58358
- Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58397
+ const protocolError = (reasonCode, message) => (
58398
+ // 3.1.1 has no reason to send, and its DISCONNECT discards the will: there, only close (3.1.1 §4.8).
58399
+ (version2 === 4 ? Effect_exports.void : write2(encodeDisconnect(reasonCode))).pipe(
58400
+ Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58401
+ Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58402
+ Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58403
+ )
58359
58404
  );
58360
58405
  const frames = makeFrameReader(maximumPacketSize);
58361
58406
  const nextPacket = Effect_exports.gen(function* () {
@@ -58381,8 +58426,10 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58381
58426
  (error2) => Effect_exports.fail(new MqttConnectionError({ message: describeSocketError(error2) }))
58382
58427
  )
58383
58428
  );
58429
+ const dialedWith = version2;
58384
58430
  yield* write2(
58385
58431
  encodeConnect({
58432
+ protocolVersion: dialedWith,
58386
58433
  clientId: options3.clientId,
58387
58434
  keepAliveSeconds,
58388
58435
  cleanStart: true,
@@ -58398,7 +58445,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58398
58445
  if (packet2.type !== PacketType.CONNACK) {
58399
58446
  return yield* new MqttConnectionError({ message: `expected CONNACK, got packet type ${packet2.type}` });
58400
58447
  }
58401
- const decoded = decodeConnack(packet2.body);
58448
+ const decoded = decodeConnack(packet2.body, dialedWith);
58402
58449
  if (Result_exports.isFailure(decoded)) {
58403
58450
  return yield* new MqttConnectionError({ message: `unreadable CONNACK: ${decoded.failure.message}` });
58404
58451
  }
@@ -58409,6 +58456,16 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58409
58456
  orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "no CONNACK in time" }))
58410
58457
  })
58411
58458
  );
58459
+ if (dialedWith === 5 && refusesProtocolLevel(connack)) {
58460
+ if (options3.protocolVersion === "5") {
58461
+ return yield* new MqttRejected({
58462
+ reasonCode: 132,
58463
+ message: "broker refused the connection: it does not speak MQTT 5 (set mqtt.version to 3.1.1 or auto)"
58464
+ });
58465
+ }
58466
+ version2 = 4;
58467
+ return yield* new MqttDowngrade();
58468
+ }
58412
58469
  if (connack.reasonCode >= 128) {
58413
58470
  return yield* new MqttRejected({
58414
58471
  reasonCode: connack.reasonCode,
@@ -58422,11 +58479,23 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58422
58479
  if (props.get(Property.MaximumPacketSize) === 0) {
58423
58480
  return yield* protocolError(130, "broker sent Maximum Packet Size 0 in CONNACK, a protocol error");
58424
58481
  }
58482
+ const receiveMaximum = Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3);
58483
+ const announcedPacketSize = props.get(Property.MaximumPacketSize);
58484
+ const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58425
58485
  const current = {
58486
+ version: dialedWith,
58487
+ info: {
58488
+ protocolVersion: dialedWith === 5 ? "5" : "3.1.1",
58489
+ receiveMaximum,
58490
+ maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58491
+ retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58492
+ ...typeof announcedPacketSize === "number" ? { maximumPacketSize: announcedPacketSize } : {},
58493
+ keepAliveSeconds: effectiveKeepAlive
58494
+ },
58426
58495
  write: write2,
58427
58496
  inflight: /* @__PURE__ */ new Map(),
58428
58497
  // Receive Maximum bounds unacknowledged QoS 1 publishes (§3.2.2.3.3).
58429
- inflightLimit: yield* Semaphore_exports.make(Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3)),
58498
+ inflightLimit: yield* Semaphore_exports.make(receiveMaximum),
58430
58499
  maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58431
58500
  retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58432
58501
  maximumPacketSize: numberProperty(props, Property.MaximumPacketSize, Number.POSITIVE_INFINITY),
@@ -58435,7 +58504,6 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58435
58504
  pubackTimeouts: 0,
58436
58505
  droppedForSilence: false
58437
58506
  };
58438
- const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58439
58507
  const pingSeconds = effectiveKeepAlive > 0 ? effectiveKeepAlive : keepAliveSeconds;
58440
58508
  yield* Effect_exports.addFinalizer(
58441
58509
  (exit3) => Effect_exports.gen(function* () {
@@ -58468,6 +58536,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58468
58536
  yield* Effect_exports.logInfo("connected to MQTT broker").pipe(
58469
58537
  Effect_exports.annotateLogs({
58470
58538
  keepAlive: effectiveKeepAlive,
58539
+ ...dialedWith === 4 ? { mqtt: "3.1.1" } : {},
58471
58540
  ...failedBefore > 0 ? { failedDials: failedBefore } : {}
58472
58541
  })
58473
58542
  );
@@ -58476,7 +58545,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58476
58545
  if (subscriptions.length > 0) {
58477
58546
  const packetId = current.nextPacketId;
58478
58547
  current.nextPacketId = packetId % 65535 + 1;
58479
- yield* write2(encodeSubscribe({ packetId, subscriptions }));
58548
+ yield* write2(encodeSubscribe({ packetId, subscriptions }, dialedWith));
58480
58549
  }
58481
58550
  let lastReceived = yield* monotonicMillis;
58482
58551
  const readLoop2 = Effect_exports.gen(function* () {
@@ -58499,12 +58568,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58499
58568
  return yield* new MqttConnectionError({ message: `broker disconnected: ${reason}` });
58500
58569
  }
58501
58570
  case PacketType.PUBLISH: {
58502
- const publish3 = decodePublish(packet2.flags, packet2.body);
58571
+ const publish3 = decodePublish(packet2.flags, packet2.body, dialedWith);
58503
58572
  if (Result_exports.isFailure(publish3)) {
58504
58573
  return yield* protocolError(129, `unreadable PUBLISH: ${publish3.failure.message}`);
58505
58574
  }
58506
58575
  const { topic, payload, retain, packetId, messageExpirySeconds, responseTopic, correlationData } = publish3.success;
58507
- if (packetId !== void 0) yield* write2(encodePuback(packetId));
58576
+ if (packetId !== void 0) yield* write2(encodePuback(packetId, 0, dialedWith));
58508
58577
  if (options3.onMessage !== void 0) {
58509
58578
  yield* options3.onMessage({
58510
58579
  topic,
@@ -58518,10 +58587,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58518
58587
  break;
58519
58588
  }
58520
58589
  case PacketType.SUBACK: {
58521
- const suback = decodeSuback(packet2.body);
58590
+ const suback = decodeSuback(packet2.body, dialedWith);
58522
58591
  const refused = Result_exports.isSuccess(suback) ? subscriptions.filter((_, index2) => (suback.success.reasonCodes[index2] ?? 128) >= 128) : subscriptions;
58523
58592
  if (refused.length > 0) {
58524
- yield* Effect_exports.logError("MQTT broker refused a subscription, commands on it will not arrive").pipe(
58593
+ yield* Effect_exports.logError(
58594
+ "MQTT broker refused a subscription; nothing published on it will arrive"
58595
+ ).pipe(
58525
58596
  Effect_exports.annotateLogs({ filters: refused.map((subscription) => subscription.filter).join(", ") })
58526
58597
  );
58527
58598
  }
@@ -58568,15 +58639,21 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58568
58639
  });
58569
58640
  while (true) {
58570
58641
  let connectedAt;
58571
- yield* runSession((at) => {
58642
+ const outcome = yield* runSession((at) => {
58572
58643
  connectedAt = at;
58644
+ Deferred_exports.doneUnsafe(firstDial, Effect_exports.void);
58573
58645
  unreachable = void 0;
58574
58646
  const dials = failedDials;
58575
58647
  failedDials = 0;
58576
58648
  return dials;
58577
58649
  }).pipe(
58578
58650
  Effect_exports.catchTags({
58579
- MqttRejected: (error2) => countConnect3("rejected").pipe(
58651
+ MqttDowngrade: () => Effect_exports.as(
58652
+ Effect_exports.logInfo("MQTT broker does not speak MQTT 5, connecting with MQTT 3.1.1"),
58653
+ "redial"
58654
+ ),
58655
+ MqttRejected: (error2) => Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58656
+ Effect_exports.andThen(countConnect3("rejected")),
58580
58657
  Effect_exports.andThen(
58581
58658
  dialFailed(
58582
58659
  `rejected ${error2.reasonCode}`,
@@ -58586,7 +58663,8 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58586
58663
  )
58587
58664
  )
58588
58665
  ),
58589
- MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : countConnect3("failed").pipe(
58666
+ MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58667
+ Effect_exports.andThen(countConnect3("failed")),
58590
58668
  Effect_exports.andThen(
58591
58669
  dialFailed(
58592
58670
  "unreachable",
@@ -58598,6 +58676,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58598
58676
  )
58599
58677
  })
58600
58678
  );
58679
+ if (outcome === "redial") continue;
58601
58680
  yield* Latch_exports.open(firstDialDone);
58602
58681
  const heldFor = connectedAt === void 0 ? 0 : (yield* monotonicMillis) - connectedAt;
58603
58682
  failures = heldFor >= stableConnectionMs ? 0 : failures + 1;
@@ -58609,16 +58688,26 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58609
58688
  let sent = false;
58610
58689
  let blameless = false;
58611
58690
  let used;
58691
+ const previousTurn = lastTurn;
58692
+ const turn = Deferred_exports.makeUnsafe();
58693
+ lastTurn = turn;
58694
+ const passTurn = Effect_exports.sync(() => Deferred_exports.doneUnsafe(turn, Effect_exports.void));
58612
58695
  return Effect_exports.gen(function* () {
58613
58696
  const rejected3 = (message) => new MqttPublishError({ topic, reason: "rejected", message });
58614
58697
  const problem = topicProblem(topic);
58615
58698
  if (problem !== void 0) return yield* rejected3(problem);
58616
- yield* (options3.waitForConnection === false ? firstDialDone : connected).await.pipe(
58617
- Effect_exports.timeoutOrElse({
58618
- duration: publishTimeout,
58619
- orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "not connected to the broker" }))
58620
- })
58621
- );
58699
+ const notConnected = () => new MqttConnectionError({ message: "not connected to the broker" });
58700
+ const withinPublishTimeout = Effect_exports.timeoutOrElse({
58701
+ duration: publishTimeout,
58702
+ orElse: () => Effect_exports.fail(notConnected())
58703
+ });
58704
+ if (options3.waitForConnection === false) {
58705
+ yield* firstDialDone.await.pipe(withinPublishTimeout);
58706
+ if (session === void 0) return yield* notConnected();
58707
+ yield* Deferred_exports.await(previousTurn).pipe(withinPublishTimeout);
58708
+ } else {
58709
+ yield* Deferred_exports.await(previousTurn).pipe(Effect_exports.andThen(connected.await), withinPublishTimeout);
58710
+ }
58622
58711
  const current = session;
58623
58712
  if (current === void 0) return yield* new MqttConnectionError({ message: "not connected to the broker" });
58624
58713
  used = current;
@@ -58630,11 +58719,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58630
58719
  const bytes3 = encoder10.encode(payload);
58631
58720
  const correlation = publishOptions.correlationData === void 0 ? {} : { correlationData: publishOptions.correlationData };
58632
58721
  if (qos === 0) {
58633
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation });
58722
+ const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation }, current.version);
58634
58723
  if (packet2.length > current.maximumPacketSize) {
58635
58724
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58636
58725
  }
58637
- return yield* current.write(packet2);
58726
+ return yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58638
58727
  }
58639
58728
  const reasonCode = yield* Semaphore_exports.withPermit(
58640
58729
  current.inflightLimit,
@@ -58642,14 +58731,17 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58642
58731
  let packetId = current.nextPacketId;
58643
58732
  while (current.inflight.has(packetId)) packetId = packetId % 65535 + 1;
58644
58733
  current.nextPacketId = packetId % 65535 + 1;
58645
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 1, retain, packetId, ...correlation });
58734
+ const packet2 = encodePublish(
58735
+ { topic, payload: bytes3, qos: 1, retain, packetId, ...correlation },
58736
+ current.version
58737
+ );
58646
58738
  if (packet2.length > current.maximumPacketSize) {
58647
58739
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58648
58740
  }
58649
58741
  const acked = yield* Deferred_exports.make();
58650
58742
  current.inflight.set(packetId, acked);
58651
58743
  return yield* Effect_exports.gen(function* () {
58652
- yield* current.write(packet2);
58744
+ yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58653
58745
  sent = true;
58654
58746
  return yield* Deferred_exports.await(acked);
58655
58747
  }).pipe(Effect_exports.ensuring(Effect_exports.sync(() => current.inflight.delete(packetId))));
@@ -58678,6 +58770,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58678
58770
  return yield* new MqttPublishError({ topic, reason: "unavailable", message });
58679
58771
  }
58680
58772
  }).pipe(
58773
+ Effect_exports.ensuring(passTurn),
58681
58774
  Effect_exports.catchTag(
58682
58775
  "MqttConnectionError",
58683
58776
  (error2) => Effect_exports.fail(
@@ -58691,7 +58784,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58691
58784
  )
58692
58785
  );
58693
58786
  });
58694
- const client = { publish: publish2, isConnected: Effect_exports.sync(() => session !== void 0) };
58787
+ const client = {
58788
+ publish: publish2,
58789
+ isConnected: Effect_exports.sync(() => session !== void 0),
58790
+ connection: Effect_exports.sync(() => session?.info),
58791
+ firstDial: Deferred_exports.await(firstDial)
58792
+ };
58695
58793
  yield* Effect_exports.forkScoped(connectionLoop);
58696
58794
  return client;
58697
58795
  });
@@ -58789,6 +58887,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58789
58887
  const client = yield* makeMqttClient(socket, {
58790
58888
  ...clientOptions,
58791
58889
  clientId: settings.clientId ?? `ot-gateway-${hostname()}`,
58890
+ protocolVersion: settings.version,
58792
58891
  ...settings.username === void 0 ? {} : { username: settings.username },
58793
58892
  ...password === void 0 ? {} : { password },
58794
58893
  ...health === void 0 ? {} : { will: { topic: health.topic, payload: offlinePayload("connection-lost"), qos: 1, retain: true } },
@@ -58833,6 +58932,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58833
58932
 
58834
58933
  // ../../packages/mqtt/src/TestBroker.ts
58835
58934
  var makeBrokerControl = () => ({
58935
+ speaksMqtt5: true,
58836
58936
  connackReason: 0,
58837
58937
  connackProperties: /* @__PURE__ */ new Map(),
58838
58938
  ackPublishes: true,
@@ -58860,15 +58960,18 @@ var deliver = (subscriber, message, onSubscribe) => {
58860
58960
  if (packetId !== void 0) subscriber.nextPacketId = packetId % 65535 + 1;
58861
58961
  Queue_exports.offerUnsafe(
58862
58962
  subscriber.outgoing,
58863
- encodePublish({
58864
- topic: message.topic,
58865
- payload: encoder11.encode(message.payload),
58866
- qos,
58867
- retain,
58868
- ...packetId === void 0 ? {} : { packetId },
58869
- ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
58870
- ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
58871
- })
58963
+ encodePublish(
58964
+ {
58965
+ topic: message.topic,
58966
+ payload: encoder11.encode(message.payload),
58967
+ qos,
58968
+ retain,
58969
+ ...packetId === void 0 ? {} : { packetId },
58970
+ ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
58971
+ ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
58972
+ },
58973
+ subscriber.version
58974
+ )
58872
58975
  );
58873
58976
  };
58874
58977
  var accept = (control, message) => {
@@ -58892,6 +58995,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58892
58995
  let will;
58893
58996
  const subscriber = {
58894
58997
  clientId: void 0,
58998
+ version: 5,
58895
58999
  subscriptions: [],
58896
59000
  outgoing: yield* Queue_exports.unbounded(),
58897
59001
  nextPacketId: 1
@@ -58916,10 +59020,16 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58916
59020
  switch (split4.type) {
58917
59021
  case PacketType.CONNECT: {
58918
59022
  const connect2 = decodeConnect(split4.body);
59023
+ const unsupported3 = Result_exports.isFailure(connect2) ? connect2.failure.message.startsWith("unsupported protocol") : false;
59024
+ if (unsupported3 || Result_exports.isSuccess(connect2) && connect2.success.protocolVersion === 5 && !control.speaksMqtt5) {
59025
+ yield* writer.write(encodeUnsupportedLevelConnack());
59026
+ return;
59027
+ }
58919
59028
  if (Result_exports.isFailure(connect2)) return;
58920
59029
  const { password, ...rest } = connect2.success;
58921
59030
  control.connects.push({ ...rest, hasPassword: password !== void 0 });
58922
- yield* writer.write(encodeConnack(control.connackReason, control.connackProperties));
59031
+ subscriber.version = connect2.success.protocolVersion ?? 5;
59032
+ yield* writer.write(encodeConnack(control.connackReason, control.connackProperties, subscriber.version));
58923
59033
  if (control.connackReason >= 128) return;
58924
59034
  clientId = connect2.success.clientId;
58925
59035
  subscriber.clientId = clientId;
@@ -58928,7 +59038,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58928
59038
  break;
58929
59039
  }
58930
59040
  case PacketType.PUBLISH: {
58931
- const publish2 = decodePublish(split4.flags, split4.body);
59041
+ const publish2 = decodePublish(split4.flags, split4.body, subscriber.version);
58932
59042
  if (Result_exports.isFailure(publish2) || clientId === void 0) return;
58933
59043
  const { topic, qos, retain, packetId, responseTopic, correlationData } = publish2.success;
58934
59044
  const payload = decoder5.decode(publish2.success.payload);
@@ -58945,19 +59055,22 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58945
59055
  });
58946
59056
  }
58947
59057
  if (qos === 1 && packetId !== void 0 && control.ackPublishes) {
58948
- yield* writer.write(encodePuback(packetId, reasonCode));
59058
+ yield* writer.write(encodePuback(packetId, reasonCode, subscriber.version));
58949
59059
  }
58950
59060
  break;
58951
59061
  }
58952
59062
  case PacketType.SUBSCRIBE: {
58953
- const subscribe2 = decodeSubscribe(split4.body);
59063
+ const subscribe2 = decodeSubscribe(split4.body, subscriber.version);
58954
59064
  if (Result_exports.isFailure(subscribe2) || clientId === void 0) return;
58955
59065
  subscriber.subscriptions.push(...subscribe2.success.subscriptions);
58956
59066
  yield* writer.write(
58957
- encodeSuback({
58958
- packetId: subscribe2.success.packetId,
58959
- reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
58960
- })
59067
+ encodeSuback(
59068
+ {
59069
+ packetId: subscribe2.success.packetId,
59070
+ reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
59071
+ },
59072
+ subscriber.version
59073
+ )
58961
59074
  );
58962
59075
  const fresh2 = { ...subscriber, subscriptions: [...subscribe2.success.subscriptions] };
58963
59076
  for (const message of control.retainedMessages.values()) deliver(fresh2, message, true);
@@ -58984,7 +59097,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58984
59097
  split4 = frames.next();
58985
59098
  }
58986
59099
  if (split4._tag === "TooLarge") {
58987
- yield* writer.write(encodeDisconnect(149));
59100
+ if (subscriber.version === 5) yield* writer.write(encodeDisconnect(149));
58988
59101
  return;
58989
59102
  }
58990
59103
  if (split4._tag === "Invalid") return;
@@ -59143,7 +59256,8 @@ var demoConfig = (example, directory, options3) => {
59143
59256
  ...options3.public === void 0 ? {} : {
59144
59257
  mqtt: {
59145
59258
  url: `mqtt://${options3.public.broker.host}:${options3.public.broker.port}`,
59146
- clientId: `ot-gateway-${site}`
59259
+ clientId: `ot-gateway-${site}`,
59260
+ version: "auto"
59147
59261
  }
59148
59262
  },
59149
59263
  ...buffer4 === void 0 ? {} : { buffer: { ...buffer4, path: `${directory}/buffer.sqlite` } },
@@ -59306,13 +59420,22 @@ var describeConfigured = (client, configured, address) => Effect_exports.gen(fun
59306
59420
  );
59307
59421
  return missing2 === 0 ? [] : [{ device, described, configured }];
59308
59422
  }).pipe(skipOnFailure(configured.deviceInstance));
59309
- var discoverDrafts = (config, network) => Effect_exports.gen(function* () {
59423
+ var DiscoverError = class extends Schema_exports.TaggedError()("DiscoverError", { message: Schema_exports.String }) {
59424
+ };
59425
+ var discoverDrafts = (config, network, options3 = {}) => Effect_exports.gen(function* () {
59426
+ const target = options3.address === void 0 ? void 0 : parseDeviceAddress(options3.address);
59427
+ if (target !== void 0 && Result_exports.isFailure(target)) {
59428
+ return yield* new DiscoverError({ message: `--address takes ip or ip:port: ${target.failure}` });
59429
+ }
59310
59430
  const client = yield* makeBacnetNetwork(config.bacnet, network);
59311
- yield* Console_exports.error(`Who-Is to ${config.bacnet.broadcastAddress}, listening for ${LISTEN}\u2026`);
59312
- const devices = yield* client.discover({ within: LISTEN });
59431
+ yield* Console_exports.error(`Who-Is to ${options3.address ?? config.bacnet.broadcastAddress}, listening for ${LISTEN}\u2026`);
59432
+ const devices = yield* client.discover({
59433
+ within: LISTEN,
59434
+ ...target === void 0 ? {} : { target: { address: target.success } }
59435
+ });
59313
59436
  if (devices.length === 0) {
59314
59437
  yield* Console_exports.error(
59315
- "No device answered. Set bacnet.broadcastAddress to this subnet's broadcast (e.g. 192.168.1.255), check that UDP 47808 is not taken by another BACnet program on this machine, and that devices on other subnets have a BBMD."
59438
+ options3.address === void 0 ? "No device answered. Set bacnet.broadcastAddress to this subnet's broadcast (e.g. 192.168.1.255), check that UDP 47808 is not taken by another BACnet program on this machine, and that devices on other subnets have a BBMD. With a device's address from a device list: discover --address ip[:port]." : `No device answered at ${options3.address}. Check the address and port, that BACnet/IP is on for the device, and that no firewall drops UDP to it or from it.`
59316
59439
  );
59317
59440
  }
59318
59441
  if (devices.length >= MAX_DEVICES) {
@@ -59345,7 +59468,10 @@ var discoverDrafts = (config, network) => Effect_exports.gen(function* () {
59345
59468
  const existing = config.devices.map((device) => device.id);
59346
59469
  return draftDevices(described.flat(), existing);
59347
59470
  }).pipe(Effect_exports.scoped);
59348
- var discover = (config, network) => Effect_exports.flatMap(discoverDrafts(config, network), (devices) => Console_exports.log(JSON.stringify({ devices }, null, 2)));
59471
+ var discover = (config, network, options3 = {}) => Effect_exports.flatMap(
59472
+ discoverDrafts(config, network, options3),
59473
+ (devices) => Console_exports.log(JSON.stringify({ devices }, null, 2))
59474
+ );
59349
59475
  var pointColumn = (point) => slugify(point.name) === point.id && !/^[=+\-@\t\r]/.test(point.name) ? point.name : point.id;
59350
59476
  var draftPointsList = (drafts) => {
59351
59477
  const header = ["device", "point", "unit", "device_instance", "address", "object_type", "object_instance"];
@@ -59362,13 +59488,13 @@ var draftPointsList = (drafts) => {
59362
59488
  );
59363
59489
  return toCsv([header, ...rows]);
59364
59490
  };
59365
- var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (config, path, network) {
59491
+ var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (config, path, network, options3 = {}) {
59366
59492
  const fs = yield* FileSystem_exports.FileSystem;
59367
59493
  if (yield* fs.exists(path)) {
59368
59494
  return yield* Console_exports.error(`${path} exists; give another file name, or move it away first. Nothing was written.`);
59369
59495
  }
59370
59496
  const configured = new Set(config.devices.map((device) => device.id));
59371
- const drafts = yield* discoverDrafts(config, network);
59497
+ const drafts = yield* discoverDrafts(config, network, options3);
59372
59498
  const fresh2 = drafts.filter((draft) => !configured.has(draft.id));
59373
59499
  if (fresh2.length < drafts.length) {
59374
59500
  yield* Console_exports.error(
@@ -59376,6 +59502,7 @@ var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (
59376
59502
  );
59377
59503
  }
59378
59504
  const points2 = fresh2.reduce((total, draft) => total + draft.points.length, 0);
59505
+ if (points2 === 0) return yield* Console_exports.error(`no points to list; ${path} was not written.`);
59379
59506
  yield* fs.writeFileString(path, draftPointsList(fresh2), { flag: "wx" });
59380
59507
  yield* Console_exports.error(
59381
59508
  `wrote ${points2} point(s) of ${fresh2.length} device(s) to ${path}. Delete the rows you do not need, then: ot-gateway import ${path}`
@@ -60239,9 +60366,22 @@ ${error2.message}`
60239
60366
  import { fileURLToPath as fileURLToPath4 } from "node:url";
60240
60367
  var composeTemplatePath = fileURLToPath4(new URL("../../../packaging/compose.yaml", import.meta.url));
60241
60368
  var folderConfigName = "ot-gateway.json";
60242
- var envFileText = (passwordEnv) => `# The MQTT broker password. Docker Compose and ot-gateway read this file; keep it out of git.
60243
- ${passwordEnv}=
60244
- `;
60369
+ var envFileText = (passwordEnv) => [
60370
+ "# Secrets and settings for this gateway, kept out of ot-gateway.json. Docker Compose and ot-gateway read",
60371
+ "# this file; keep it yours alone (chmod 600) and out of git.",
60372
+ ...passwordEnv === void 0 ? [] : ["", "# The MQTT broker password.", `${passwordEnv}=`],
60373
+ "",
60374
+ "# Telemetry: uncomment and fill in to send traces, metrics and logs over OTLP (observability/README.md).",
60375
+ "# OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.example.com/otlp",
60376
+ "# OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic%20<token>",
60377
+ "# OTEL_TRACES_EXPORTER=otlp",
60378
+ "# OTEL_METRICS_EXPORTER=otlp",
60379
+ "# OTEL_LOGS_EXPORTER=otlp",
60380
+ "# OTEL_RESOURCE_ATTRIBUTES=deployment.environment=production",
60381
+ "# OTEL_TRACES_SAMPLER=traceidratio",
60382
+ "# OTEL_TRACES_SAMPLER_ARG=0.1",
60383
+ ""
60384
+ ].join("\n");
60245
60385
  var writeFolderFiles = Effect_exports.fn("writeFolderFiles")(function* (configPath2, config, options3 = {}) {
60246
60386
  const fs = yield* FileSystem_exports.FileSystem;
60247
60387
  const path = yield* Path_exports.Path;
@@ -60257,8 +60397,7 @@ var writeFolderFiles = Effect_exports.fn("writeFolderFiles")(function* (configPa
60257
60397
  if (noCompose === void 0) {
60258
60398
  yield* create(path.join(folder, "compose.yaml"), yield* fs.readFileString(composeTemplatePath), 420);
60259
60399
  }
60260
- const passwordEnv = config.mqtt.passwordEnv;
60261
- if (passwordEnv !== void 0) yield* create(path.join(folder, "ot-gateway.env"), envFileText(passwordEnv), 384);
60400
+ yield* create(path.join(folder, "ot-gateway.env"), envFileText(config.mqtt.passwordEnv), 384);
60262
60401
  return { written, kept, noCompose };
60263
60402
  });
60264
60403
 
@@ -60471,8 +60610,13 @@ var nextSteps = (path, config, folder = { written: [], kept: [] }) => {
60471
60610
  const folderPath = dirname3(path);
60472
60611
  const name = basename(path);
60473
60612
  const argument = name === folderConfigName ? "" : ` ${name}`;
60613
+ const devices = config.devices.length > 0 ? [] : [
60614
+ ["ot-gateway points template > points.csv", "start a points list (or discover --points-list for BACnet)"],
60615
+ [`ot-gateway import points.csv${argument}`, "add its devices to the config"]
60616
+ ];
60474
60617
  const commands2 = [
60475
60618
  ...folderPath === "." ? [] : [[`cd ${folderPath}`, "the gateway's folder"]],
60619
+ ...devices,
60476
60620
  ...compose5 ? [
60477
60621
  ["docker compose up -d", "start it in Docker, restarted after a crash or a reboot"],
60478
60622
  ["ot-gateway status", `one line per device (status page on http://127.0.0.1:${port2})`]
@@ -60486,7 +60630,6 @@ var nextSteps = (path, config, folder = { written: [], kept: [] }) => {
60486
60630
  ...folder.kept.map((file3) => `kept ${file3} as it is`),
60487
60631
  ...folder.noCompose === void 0 ? [] : [`no compose.yaml: ${folder.noCompose}`],
60488
60632
  ...password,
60489
- ...config.devices.length === 0 ? [" add your devices under devices (docs/configuration.md)"] : [],
60490
60633
  "next:",
60491
60634
  ...commands2.map(([command, what]) => ` ${command.padEnd(width3)}${what}`)
60492
60635
  ].join("\n");
@@ -71358,6 +71501,104 @@ var statusReport = Effect_exports.fn("statusReport")(function* (url, options3 =
71358
71501
  yield* Console_exports.log(options3.json === true ? JSON.stringify(status3, null, 2) : formatStatus(status3));
71359
71502
  });
71360
71503
 
71504
+ // src/Broker.ts
71505
+ var DIAL_TIMEOUT = "15 seconds";
71506
+ var ROUND_TRIP_TIMEOUT = "5 seconds";
71507
+ var BrokerCommandError = class extends Schema_exports.TaggedError()("BrokerCommandError", {
71508
+ message: Schema_exports.String
71509
+ }) {
71510
+ };
71511
+ var randomSuffix = Effect_exports.map(Random_exports.nextIntBetween(0, 16777215), (value4) => value4.toString(16).padStart(6, "0"));
71512
+ var brokerClient = Effect_exports.fn("brokerClient")(function* (settings, role, options3 = {}) {
71513
+ const address = yield* parseBrokerUrl(settings.url);
71514
+ const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
71515
+ const openTimeout2 = "10 seconds";
71516
+ const socket = address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
71517
+ return yield* makeMqttClient(socket, {
71518
+ ...options3,
71519
+ clientId: `ot-gateway-${role}-${yield* randomSuffix}`,
71520
+ protocolVersion: settings.version,
71521
+ ...settings.username === void 0 ? {} : { username: settings.username },
71522
+ ...password === void 0 ? {} : { password }
71523
+ });
71524
+ });
71525
+ var firstDialOf = (client, url) => client.firstDial.pipe(
71526
+ Effect_exports.timeoutOrElse({
71527
+ duration: DIAL_TIMEOUT,
71528
+ orElse: () => Effect_exports.fail(new MqttConnectionError({ message: `no answer within ${DIAL_TIMEOUT}` }))
71529
+ }),
71530
+ Effect_exports.mapError((error2) => new BrokerCommandError({ message: `could not connect to ${url}: ${error2.message}` }))
71531
+ );
71532
+ var brokerWarnings = (info2, roundTripMs, topic) => [
71533
+ ...info2.protocolVersion === "3.1.1" ? [
71534
+ "MQTT 3.1.1: the broker announces no limits, commands get no correlation data and messages no expiry (docs/configuration.md, mqtt.version)"
71535
+ ] : [],
71536
+ ...info2.retainAvailable ? [] : ["the broker keeps no retained messages: $meta and health reach only clients connected at the time"],
71537
+ ...info2.maximumQoS === 0 ? ["the broker allows QoS 0 only: nothing confirms that a message arrived, so the buffer cannot help"] : [],
71538
+ ...roundTripMs === void 0 ? [
71539
+ `a message to ${topic} did not come back within ${ROUND_TRIP_TIMEOUT}: the broker's ACL may not let this user publish or subscribe there`
71540
+ ] : []
71541
+ ];
71542
+ var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
71543
+ const topic = `${config.site}/${config.building}/$gateway/${config.id}/check/${yield* randomSuffix}`;
71544
+ const payload = "ot-gateway broker check";
71545
+ const received = yield* Deferred_exports.make();
71546
+ const client = yield* brokerClient(config.mqtt, "check", {
71547
+ subscriptions: [{ filter: topic, qos: 1 }],
71548
+ onMessage: (message) => message.topic === topic ? Effect_exports.flatMap(
71549
+ Effect_exports.clockWith((clock) => clock.currentTimeMillis),
71550
+ (now2) => Deferred_exports.succeed(received, now2)
71551
+ ).pipe(Effect_exports.asVoid) : Effect_exports.void
71552
+ });
71553
+ yield* firstDialOf(client, config.mqtt.url);
71554
+ const info2 = yield* client.connection;
71555
+ if (info2 === void 0) {
71556
+ return yield* new BrokerCommandError({ message: `connected to ${config.mqtt.url}, then lost the connection` });
71557
+ }
71558
+ const sentAt = yield* Effect_exports.clockWith((clock) => clock.currentTimeMillis);
71559
+ yield* client.publish(topic, payload, { qos: 1 }).pipe(
71560
+ Effect_exports.mapError(
71561
+ (error2) => new BrokerCommandError({ message: `${config.mqtt.url} did not take a message: ${error2.message}` })
71562
+ )
71563
+ );
71564
+ const arrivedAt = yield* Deferred_exports.await(received).pipe(Effect_exports.timeoutOption(ROUND_TRIP_TIMEOUT));
71565
+ const roundTripMs = Option_exports.match(arrivedAt, {
71566
+ onNone: () => void 0,
71567
+ onSome: (at) => Math.max(0, at - sentAt)
71568
+ });
71569
+ const report = {
71570
+ ok: true,
71571
+ broker: config.mqtt.url,
71572
+ ...info2,
71573
+ ...roundTripMs === void 0 ? {} : { roundTripMs },
71574
+ roundTripTopic: topic,
71575
+ warnings: brokerWarnings(info2, roundTripMs, topic)
71576
+ };
71577
+ return report;
71578
+ }, Effect_exports.scoped);
71579
+ var sizeText = (bytes3) => bytes3 >= 1024 * 1024 ? `${Math.round(bytes3 / 1024 / 1024)} MiB` : bytes3 >= 1024 ? `${Math.round(bytes3 / 1024)} KiB` : `${bytes3} B`;
71580
+ var formatBrokerReport = (report) => [
71581
+ `${report.broker}: connected with MQTT ${report.protocolVersion}`,
71582
+ ` allows QoS ${report.maximumQoS}, ${report.retainAvailable ? "retained messages" : "NO retained messages"}, ${report.receiveMaximum} in flight, ${report.maximumPacketSize === void 0 ? "packets of any size" : `packets up to ${sizeText(report.maximumPacketSize)}`}, keep-alive ${report.keepAliveSeconds} s`,
71583
+ report.roundTripMs === void 0 ? ` round trip: NO ANSWER within ${ROUND_TRIP_TIMEOUT}` : ` round trip: ${report.roundTripMs} ms (QoS 1, through ${report.roundTripTopic})`,
71584
+ ...report.warnings.map((warning) => ` warning: ${warning}`)
71585
+ ].join("\n");
71586
+ var publishOnce = Effect_exports.fn("publishOnce")(function* (config, topic, payload, options3) {
71587
+ const client = yield* brokerClient(config.mqtt, "publish");
71588
+ yield* firstDialOf(client, config.mqtt.url);
71589
+ yield* client.publish(topic, payload, { qos: options3.qos, retain: options3.retain }).pipe(Effect_exports.mapError((error2) => new BrokerCommandError({ message: `${topic}: ${error2.message}` })));
71590
+ return {
71591
+ ok: true,
71592
+ broker: config.mqtt.url,
71593
+ topic,
71594
+ bytes: new TextEncoder().encode(payload).length,
71595
+ qos: options3.qos,
71596
+ retain: options3.retain,
71597
+ cleared: options3.retain && payload === ""
71598
+ };
71599
+ }, Effect_exports.scoped);
71600
+ var formatPublished = (result4) => result4.cleared ? `cleared the retained message on ${result4.topic}` : `published ${result4.bytes} byte(s) to ${result4.topic} (QoS ${result4.qos}${result4.retain ? ", retained" : ""})`;
71601
+
71361
71602
  // src/Watch.ts
71362
71603
  var MAX_PAYLOAD = 300;
71363
71604
  var watchFilter = (config) => `${config.site}/${config.building}/#`;
@@ -71369,22 +71610,17 @@ var formatMessage2 = (message, at) => {
71369
71610
  return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
71370
71611
  };
71371
71612
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71372
- const address = yield* parseBrokerUrl(config.mqtt.url);
71373
- const password = config.mqtt.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(config.mqtt.passwordEnv);
71374
71613
  const filter14 = options3.topic ?? watchFilter(config);
71375
- const openTimeout2 = "10 seconds";
71376
- const socket = address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
71377
- const suffix = (yield* Random_exports.nextIntBetween(0, 16777215)).toString(16).padStart(6, "0");
71378
- yield* makeMqttClient(socket, {
71379
- clientId: `ot-gateway-watch-${suffix}`,
71380
- ...config.mqtt.username === void 0 ? {} : { username: config.mqtt.username },
71381
- ...password === void 0 ? {} : { password },
71614
+ yield* brokerClient(config.mqtt, "watch", {
71382
71615
  subscriptions: [{ filter: filter14, qos: 0, retainAsPublished: true }],
71383
- onConnect: () => Console_exports.error(`watching ${filter14} on ${config.mqtt.url} (Ctrl-C to stop)`),
71616
+ onConnect: () => Console_exports.error(
71617
+ `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
71618
+ ),
71384
71619
  onMessage: (message) => Console_exports.log(formatMessage2(message, /* @__PURE__ */ new Date()))
71385
71620
  });
71386
71621
  yield* Console_exports.error(`connecting to ${config.mqtt.url}\u2026`);
71387
- return yield* Effect_exports.never;
71622
+ if (options3.seconds === void 0) return yield* Effect_exports.never;
71623
+ yield* Effect_exports.sleep(Duration_exports.seconds(options3.seconds));
71388
71624
  }, Effect_exports.scoped);
71389
71625
 
71390
71626
  // ../../node_modules/.pnpm/@effect+sql-sqlite-node@4.1.2_effect@4.1.2/node_modules/@effect/sql-sqlite-node/dist/SqliteClient.js
@@ -72533,6 +72769,47 @@ var keepRunning = Effect_exports.fn("keepRunning")(function* (name, task, delay3
72533
72769
  }
72534
72770
  });
72535
72771
 
72772
+ // src/StaleMeta.ts
72773
+ var MAX_PENDING = 1024;
72774
+ var metaSubscriptions = (config) => config.devices.map((device) => ({
72775
+ filter: `${config.site}/${config.building}/${device.id}/+/$meta`,
72776
+ qos: 0
72777
+ }));
72778
+ var staleMetaTopic = (config, message) => {
72779
+ if (!message.retain || message.payload === "") return void 0;
72780
+ const parts2 = message.topic.split("/");
72781
+ if (parts2.length !== 5 || parts2[0] !== config.site || parts2[1] !== config.building || parts2[4] !== "$meta") {
72782
+ return void 0;
72783
+ }
72784
+ const device = config.devices.find((candidate) => candidate.id === parts2[2]);
72785
+ if (device === void 0) return void 0;
72786
+ return device.points.some((point) => point.id === parts2[3]) ? void 0 : message.topic;
72787
+ };
72788
+ var makeStaleMetaCleaner = Effect_exports.fn("makeStaleMetaCleaner")(function* (config) {
72789
+ const pending = yield* Queue_exports.dropping(MAX_PENDING);
72790
+ const clear5 = Effect_exports.fn("clearStaleMeta")(function* (topic) {
72791
+ const publisher = yield* Publisher;
72792
+ yield* publisher.publish(topic, "", { retain: true }).pipe(
72793
+ Effect_exports.andThen(Effect_exports.logInfo("cleared the retained metadata of a point no longer in the config")),
72794
+ Effect_exports.catchTag(
72795
+ "PublishError",
72796
+ (error2) => Effect_exports.logWarning("could not clear the retained metadata of a point no longer in the config").pipe(
72797
+ Effect_exports.annotateLogs({ error: error2.message })
72798
+ )
72799
+ ),
72800
+ Effect_exports.annotateLogs({ topic })
72801
+ );
72802
+ });
72803
+ return {
72804
+ subscriptions: metaSubscriptions(config),
72805
+ onMessage: (message) => {
72806
+ const topic = staleMetaTopic(config, message);
72807
+ return topic === void 0 ? Effect_exports.void : Queue_exports.offer(pending, topic).pipe(Effect_exports.asVoid);
72808
+ },
72809
+ run: Effect_exports.forever(Effect_exports.flatMap(Queue_exports.take(pending), clear5))
72810
+ };
72811
+ });
72812
+
72536
72813
  // src/Host.ts
72537
72814
  import { statfs } from "node:fs/promises";
72538
72815
  import { dirname as dirname4, resolve as resolve7 } from "node:path";
@@ -74112,6 +74389,7 @@ var defaultWebRoot = fileURLToPath5(new URL("../../web/out", import.meta.url));
74112
74389
  var makeStatusState = (config, health, since, host) => {
74113
74390
  const prefix = `${config.site}/${config.building}/`;
74114
74391
  const payloads = /* @__PURE__ */ new Map();
74392
+ const reads = /* @__PURE__ */ new Map();
74115
74393
  const latest = /* @__PURE__ */ new Map();
74116
74394
  const droppedTopics = /* @__PURE__ */ new Set();
74117
74395
  const commands2 = [];
@@ -74119,6 +74397,10 @@ var makeStatusState = (config, health, since, host) => {
74119
74397
  return {
74120
74398
  recordPublish: (topic, payload, message) => {
74121
74399
  if (!topic.startsWith(prefix)) return;
74400
+ if (message.retained && payload === "") {
74401
+ latest.delete(topic);
74402
+ return;
74403
+ }
74122
74404
  const previous = latest.get(topic);
74123
74405
  if (previous !== void 0 || latest.size < MAX_TOPICS) {
74124
74406
  latest.set(topic, { payload, retained: message.retained, at: message.at, count: (previous?.count ?? 0) + 1 });
@@ -74128,6 +74410,11 @@ var makeStatusState = (config, health, since, host) => {
74128
74410
  if (slash <= 0 || rest.indexOf("/", slash + 1) !== -1) return;
74129
74411
  payloads.set(rest, payload);
74130
74412
  },
74413
+ reads: {
74414
+ record: (device, point, value4, ts) => {
74415
+ reads.set(`${device}/${point}`, { value: value4, ts });
74416
+ }
74417
+ },
74131
74418
  recordCommand: (at, command, outcome) => {
74132
74419
  commands2.unshift({
74133
74420
  at,
@@ -74156,9 +74443,9 @@ var makeStatusState = (config, health, since, host) => {
74156
74443
  ...state.reason === void 0 ? {} : { reason: state.reason },
74157
74444
  ...state.lastSuccess === void 0 ? {} : { lastSuccess: state.lastSuccess },
74158
74445
  points: device.points.map((point) => {
74159
- const payload = payloads.get(`${device.id}/${point.id}`);
74160
- const decoded = payload === void 0 ? Option_exports.none() : decodeValue2(payload);
74161
- const last2 = Option_exports.getOrUndefined(decoded);
74446
+ const key5 = `${device.id}/${point.id}`;
74447
+ const payload = payloads.get(key5);
74448
+ const last2 = reads.get(key5) ?? Option_exports.getOrUndefined(payload === void 0 ? Option_exports.none() : decodeValue2(payload));
74162
74449
  return {
74163
74450
  id: point.id,
74164
74451
  name: point.name,
@@ -74396,7 +74683,7 @@ var makeStore2 = (sql) => {
74396
74683
  };
74397
74684
 
74398
74685
  // ../../packages/history/src/History.ts
74399
- var MAX_PENDING = 2e4;
74686
+ var MAX_PENDING2 = 2e4;
74400
74687
  var DEFAULT_BUCKETS = 300;
74401
74688
  var MAX_BUCKETS = 2e3;
74402
74689
  var HOUR_MS = 36e5;
@@ -74479,9 +74766,9 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74479
74766
  let dropped = 0;
74480
74767
  let failing = false;
74481
74768
  const keepAtMost = (rows) => {
74482
- if (rows.length <= MAX_PENDING) return rows;
74483
- dropped += rows.length - MAX_PENDING;
74484
- return rows.slice(rows.length - MAX_PENDING);
74769
+ if (rows.length <= MAX_PENDING2) return rows;
74770
+ dropped += rows.length - MAX_PENDING2;
74771
+ return rows.slice(rows.length - MAX_PENDING2);
74485
74772
  };
74486
74773
  const flush2 = Effect_exports.gen(function* () {
74487
74774
  if (dropped > 0) {
@@ -74531,7 +74818,7 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74531
74818
  sink: {
74532
74819
  record: (device, point, value4, ts) => {
74533
74820
  pending.push({ device, point, ts, value: typeof value4 === "boolean" ? value4 ? 1 : 0 : value4 });
74534
- if (pending.length > MAX_PENDING + MAX_PENDING / 10) pending = keepAtMost(pending);
74821
+ if (pending.length > MAX_PENDING2 + MAX_PENDING2 / 10) pending = keepAtMost(pending);
74535
74822
  }
74536
74823
  },
74537
74824
  series: (query3) => Effect_exports.gen(function* () {
@@ -75876,7 +76163,7 @@ var openBacnet = Effect_exports.fn("openBacnet")(function* (config, health, endp
75876
76163
  );
75877
76164
  yield* Deferred_exports.succeed(endpoint4, client);
75878
76165
  });
75879
- var runOne = (config, device, sampleRatio, health, bacnet, network, drivers, modbusLinks, history) => {
76166
+ var runOne = (config, device, sampleRatio, health, bacnet, network, drivers, modbusLinks, reads) => {
75880
76167
  const run10 = (driver) => Effect_exports.andThen(drivers.register(driver), runDevice(ctx, driver));
75881
76168
  const ctx = {
75882
76169
  site: config.site,
@@ -75886,7 +76173,7 @@ var runOne = (config, device, sampleRatio, health, bacnet, network, drivers, mod
75886
76173
  ...device.publish === void 0 ? {} : { publish: device.publish },
75887
76174
  traceSampleRatio: sampleRatio,
75888
76175
  health,
75889
- ...history === void 0 ? {} : { history: history.sink }
76176
+ ...reads === void 0 ? {} : { history: reads }
75890
76177
  };
75891
76178
  switch (device.protocol) {
75892
76179
  case "simulator":
@@ -75914,9 +76201,11 @@ var runOne = (config, device, sampleRatio, health, bacnet, network, drivers, mod
75914
76201
  }
75915
76202
  }
75916
76203
  };
75917
- var runDevices = Effect_exports.fn("runGateway")(function* (config, health, network, commands2, status3, host) {
76204
+ var runDevices = Effect_exports.fn("runGateway")(function* (config, health, network, commands2, status3, host, staleMeta) {
75918
76205
  const sampleRatio = yield* traceSampleRatio;
75919
76206
  const history = config.history === void 0 ? void 0 : yield* openHistory(config.history);
76207
+ const sinks = [history?.sink, status3?.reads].filter((sink) => sink !== void 0);
76208
+ const reads = sinks.length === 0 ? void 0 : { record: (device, point, value4, ts) => sinks.forEach((sink) => sink.record(device, point, value4, ts)) };
75920
76209
  yield* Effect_exports.log(`OT Gateway starting: ${config.site}/${config.building}, ${config.devices.length} device(s)`).pipe(
75921
76210
  Effect_exports.annotateLogs({ traceSampleRatio: sampleRatio, health: health.topic })
75922
76211
  );
@@ -75941,42 +76230,36 @@ var runDevices = Effect_exports.fn("runGateway")(function* (config, health, netw
75941
76230
  ...config.devices.map(
75942
76231
  (device) => superviseDevice(
75943
76232
  Effect_exports.suspend(
75944
- () => runOne(
75945
- config,
75946
- device,
75947
- sampleRatio,
75948
- health.registry,
75949
- bacnet,
75950
- network,
75951
- commands2.drivers,
75952
- modbusLinks,
75953
- history
75954
- )
76233
+ () => runOne(config, device, sampleRatio, health.registry, bacnet, network, commands2.drivers, modbusLinks, reads)
75955
76234
  ),
75956
76235
  { deviceId: device.id, health: health.registry }
75957
76236
  )
75958
76237
  ),
75959
76238
  ...host === void 0 ? [] : [keepRunning("host monitor", host.run)],
76239
+ keepRunning("stale metadata", staleMeta.run),
75960
76240
  // A command at a time per device, each with its own deadline; devices do not wait for each other.
75961
76241
  ...commands2.routing === void 0 ? [] : [keepRunning("command guard", commands2.routing.run)]
75962
76242
  ],
75963
76243
  { concurrency: "unbounded", discard: true }
75964
76244
  );
75965
76245
  });
75966
- var northbound = (config, health, options3, routing, status3) => {
76246
+ var northbound = (config, health, options3, routing, status3, staleMeta) => {
76247
+ const commandSubscriptions = routing === void 0 ? [] : [
76248
+ {
76249
+ filter: commandFilter(config.site, config.building),
76250
+ qos: 1,
76251
+ retainAsPublished: true,
76252
+ noLocal: true
76253
+ }
76254
+ ];
75967
76255
  const mqtt = MqttPublisher(config.mqtt, {
75968
76256
  health: { topic: health.topic, online: health.online },
75969
76257
  // With a buffer, a value that cannot go out now is stored, so waiting for the broker would only stall reads.
75970
76258
  waitForConnection: config.buffer === void 0,
75971
76259
  ...options3.network === void 0 ? {} : { network: options3.network },
75972
- ...routing === void 0 ? {} : {
75973
- // Retain As Published, so a command published retained is seen as such even live, and refused.
75974
- // No Local, so nothing the gateway publishes itself is ever taken for a command.
75975
- subscriptions: [
75976
- { filter: commandFilter(config.site, config.building), qos: 1, retainAsPublished: true, noLocal: true }
75977
- ],
75978
- onMessage: routing.onMessage
75979
- }
76260
+ subscriptions: [...commandSubscriptions, ...staleMeta.subscriptions],
76261
+ // A `$meta` topic is never a command topic (`.../$set`), so each message has one taker.
76262
+ onMessage: (message) => message.topic.endsWith("/$meta") ? staleMeta.onMessage(message) : routing === void 0 ? Effect_exports.void : routing.onMessage(message)
75980
76263
  });
75981
76264
  const publisher = config.buffer === void 0 ? mqtt : BufferedPublisher(config.buffer, options3.buffer).pipe(Layer_exports.provide(mqtt));
75982
76265
  const onAccepted = options3.onAccepted;
@@ -76031,11 +76314,12 @@ var runGateway = Effect_exports.fn("Gateway")(function* (config, options3 = {})
76031
76314
  drivers,
76032
76315
  routing: writable ? yield* makeCommandRouting(config, guard.handle) : void 0
76033
76316
  };
76034
- return yield* runDevices(config, health, options3.network, commands2, status3, host).pipe(
76317
+ const staleMeta = yield* makeStaleMetaCleaner(config);
76318
+ return yield* runDevices(config, health, options3.network, commands2, status3, host, staleMeta).pipe(
76035
76319
  // The BACnet/IP socket closes before the broker connection does.
76036
76320
  Effect_exports.scoped,
76037
76321
  // Inside the metric attributes, so the broker connection's metrics carry site and building too.
76038
- Effect_exports.provide(northbound(config, health, options3, commands2.routing, status3)),
76322
+ Effect_exports.provide(northbound(config, health, options3, commands2.routing, status3, staleMeta)),
76039
76323
  withMetricAttributes({ site: config.site, building: config.building })
76040
76324
  );
76041
76325
  });
@@ -76148,20 +76432,30 @@ var discoverCommand = Command_exports.make(
76148
76432
  Flag_exports.withDescription("Write the devices found as a points list (CSV) to this file, to trim and import"),
76149
76433
  Flag_exports.optional
76150
76434
  ),
76435
+ address: Flag_exports.String("address").pipe(
76436
+ Flag_exports.withDescription(
76437
+ "Ask only the device at this ip or ip:port, instead of a broadcast: one on another subnet or another port"
76438
+ ),
76439
+ Flag_exports.optional
76440
+ ),
76151
76441
  json: jsonFlag
76152
76442
  },
76153
76443
  // The draft is JSON already; --json makes a failure JSON too.
76154
- ({ config, pointsList, json: json3 }) => Effect_exports.flatMap(
76155
- loadConfig(config),
76156
- (decoded) => Option_exports.isSome(pointsList) ? discoverToPointsList(decoded, pointsList.value) : discover(decoded)
76157
- ).pipe(jsonFailure(json3, { path: config }))
76444
+ ({ config, pointsList, address, json: json3 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76445
+ const options3 = { address: Option_exports.getOrUndefined(address) };
76446
+ return Option_exports.isSome(pointsList) ? discoverToPointsList(decoded, pointsList.value, void 0, options3) : discover(decoded, void 0, options3);
76447
+ }).pipe(jsonFailure(json3, { path: config }))
76158
76448
  ).pipe(
76159
76449
  Command_exports.withDescription(
76160
76450
  "Find BACnet devices through the config's bacnet settings and print a draft of their devices entries, read-only"
76161
76451
  ),
76162
76452
  Command_exports.withExamples([
76163
76453
  { command: "ot-gateway discover", description: "Print the draft as JSON, in the config's shape" },
76164
- { command: "ot-gateway discover --points-list points.csv", description: "Write it as a points list to trim" }
76454
+ { command: "ot-gateway discover --points-list points.csv", description: "Write it as a points list to trim" },
76455
+ {
76456
+ command: "ot-gateway discover --address 10.20.3.40:47809",
76457
+ description: "Ask one device whose address a device list gives"
76458
+ }
76165
76459
  ])
76166
76460
  );
76167
76461
  var demo = Command_exports.make(
@@ -76394,14 +76688,85 @@ var watchCommand = Command_exports.make(
76394
76688
  topic: Flag_exports.String("topic").pipe(
76395
76689
  Flag_exports.withDescription("A topic filter instead of site/building/# (# for everything on the broker)"),
76396
76690
  Flag_exports.optional
76691
+ ),
76692
+ seconds: Flag_exports.Int("seconds").pipe(
76693
+ Flag_exports.withDescription("Stop after this many seconds instead of at Ctrl-C, for scripts and agents"),
76694
+ Flag_exports.filter(
76695
+ (seconds3) => seconds3 >= 1,
76696
+ (seconds3) => `--seconds takes 1 or more, not ${seconds3}`
76697
+ ),
76698
+ Flag_exports.optional
76397
76699
  )
76398
76700
  },
76399
- ({ config, topic }) => Effect_exports.flatMap(loadConfig(config), (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic) }))
76701
+ ({ config, topic, seconds: seconds3 }) => Effect_exports.flatMap(
76702
+ loadConfig(config),
76703
+ (decoded) => watch3(decoded, { topic: Option_exports.getOrUndefined(topic), seconds: Option_exports.getOrUndefined(seconds3) })
76704
+ )
76400
76705
  ).pipe(
76401
76706
  Command_exports.withDescription("Print what arrives at the config's broker under its site and building, as it arrives"),
76402
76707
  Command_exports.withExamples([
76403
76708
  { command: "ot-gateway watch", description: "Watch the broker in ot-gateway.json" },
76404
- { command: "ot-gateway watch --topic 'my-site/main/ahu-1/#'", description: "Only one device" }
76709
+ { command: "ot-gateway watch --topic 'my-site/main/ahu-1/#'", description: "Only one device" },
76710
+ { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" }
76711
+ ])
76712
+ );
76713
+ var brokerCommand = Command_exports.make(
76714
+ "broker",
76715
+ { config: configPath, json: jsonFlag },
76716
+ ({ config, json: json3 }) => loadConfig(config).pipe(
76717
+ Effect_exports.flatMap(checkBroker),
76718
+ Effect_exports.flatMap((report) => json3 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76719
+ jsonFailure(json3, { path: config })
76720
+ )
76721
+ ).pipe(
76722
+ Command_exports.withDescription(
76723
+ "Connect to the config's broker: the MQTT it speaks (5 or 3.1.1), what it allows, and a message there and back"
76724
+ ),
76725
+ Command_exports.withExamples([
76726
+ { command: "ot-gateway broker", description: "Check the broker in ot-gateway.json" },
76727
+ { command: "ot-gateway broker /etc/ot-gateway/gateway.json --json", description: "Another config, as JSON" }
76728
+ ])
76729
+ );
76730
+ var publishCommand = Command_exports.make(
76731
+ "publish",
76732
+ {
76733
+ topic: Argument_exports.String("topic").pipe(Argument_exports.withDescription("The topic, without wildcards")),
76734
+ payload: Argument_exports.String("payload").pipe(
76735
+ Argument_exports.withDescription("The message; empty when left out"),
76736
+ Argument_exports.withDefault("")
76737
+ ),
76738
+ config: Flag_exports.String("config").pipe(
76739
+ Flag_exports.withDescription("Path of the gateway's JSON config"),
76740
+ Flag_exports.withDefault("ot-gateway.json")
76741
+ ),
76742
+ retain: Flag_exports.Boolean("retain").pipe(
76743
+ Flag_exports.withDescription(
76744
+ "Ask the broker to keep it for later subscribers; an empty retained message clears the topic"
76745
+ ),
76746
+ Flag_exports.withDefault(false)
76747
+ ),
76748
+ qos: Flag_exports.ChoiceWithValue("qos", [
76749
+ ["0", 0],
76750
+ ["1", 1]
76751
+ ]).pipe(
76752
+ Flag_exports.withDescription("0 sends and forgets, 1 waits until the broker confirmed it"),
76753
+ Flag_exports.withDefault(1)
76754
+ ),
76755
+ json: jsonFlag
76756
+ },
76757
+ ({ topic, payload, config, retain, qos, json: json3 }) => loadConfig(config).pipe(
76758
+ Effect_exports.flatMap((decoded) => publishOnce(decoded, topic, payload, { retain, qos })),
76759
+ Effect_exports.flatMap((result4) => json3 ? printJson(result4) : Console_exports.log(formatPublished(result4))),
76760
+ jsonFailure(json3, { topic })
76761
+ )
76762
+ ).pipe(
76763
+ Command_exports.withDescription("Send one message to the config's broker, as the gateway's user"),
76764
+ Command_exports.withExamples([
76765
+ { command: "ot-gateway publish my-site/main/test hello", description: "A message, QoS 1" },
76766
+ {
76767
+ command: "ot-gateway publish 'my-site/main/old-device/temp/$meta' --retain",
76768
+ description: "Clear a retained message the broker keeps for a device that is gone"
76769
+ }
76405
76770
  ])
76406
76771
  );
76407
76772
  var status2 = Command_exports.make(
@@ -76424,6 +76789,7 @@ var rootDescription = [
76424
76789
  " import <list> --dry-run --json check a points list, row by row",
76425
76790
  " init <folder> --dry-run --json the folder init would write (with --site, --broker, --points <list>)",
76426
76791
  " check --json every mistake in a config, with its path",
76792
+ " broker --json the broker: MQTT version, limits, a round trip",
76427
76793
  " status --json the running gateway, device by device"
76428
76794
  ].join("\n");
76429
76795
  var cli = Command_exports.make("ot-gateway").pipe(
@@ -76438,6 +76804,8 @@ var cli = Command_exports.make("ot-gateway").pipe(
76438
76804
  points,
76439
76805
  profiles,
76440
76806
  watchCommand,
76807
+ brokerCommand,
76808
+ publishCommand,
76441
76809
  status2
76442
76810
  ])
76443
76811
  );
@@ -76451,6 +76819,8 @@ var subcommands = /* @__PURE__ */ new Set([
76451
76819
  "points",
76452
76820
  "profiles",
76453
76821
  "watch",
76822
+ "broker",
76823
+ "publish",
76454
76824
  "status"
76455
76825
  ]);
76456
76826
  var toCliArgs = (argv) => {
@@ -76501,6 +76871,8 @@ var reportFailure = (cause) => {
76501
76871
  return Effect_exports.logError(error2.success.message);
76502
76872
  };
76503
76873
  loadEnvFile();
76874
+ var extraEnvFile = process.env["OT_GATEWAY_ENV_FILE"];
76875
+ if (extraEnvFile !== void 0 && extraEnvFile !== "") loadEnvFile(extraEnvFile);
76504
76876
  var program = runCli(process.argv.slice(2));
76505
76877
  program.pipe(
76506
76878
  Effect_exports.tapCause(reportFailure),