1- import { connect } from "mqtt" // import connect from mqtt
1+ import { MqttClient , connect } from "mqtt" // import connect from mqtt
22import { serverTelemetry } from "./azure/appinsights"
33import { registerMessageSink } from "./messages"
44import { getSecret } from "./secrets"
55import { defaultPartition , getDevice } from "./storage"
66import { sendJSON } from "./apidevices"
77import { DeviceId } from "./schema"
88
9+ let client : MqttClient
10+ let serverUrl : string
11+
12+ export function mqttTopicPrefix ( deviceid : DeviceId ) {
13+ return client ? `devs/${ deviceid . rowKey } ` : undefined
14+ }
15+
16+ export function mqttServer ( ) {
17+ return serverUrl
18+ }
19+
920export async function setup ( ) {
10- const connStr = await getSecret (
21+ serverUrl = await getSecret (
1122 "mqttConnectionString" ,
12- "DEVS_MQTT_CONNECTION_STRING_SECRET " ,
13- "DEVS_MQTT_CONNETION_STRING "
23+ "DEVS_MQTT_SERVER_SECRET " ,
24+ "DEVS_MQTT_SERVER "
1425 )
15- if ( ! connStr ) {
26+ if ( ! serverUrl ) {
1627 console . log ( "no MQTT connection string secret, skipping registration" )
1728 return
1829 }
1930
20- console . log ( "registering MQTT broker" )
31+ console . log ( ` MQTT server: ${ serverUrl } ` )
2132 const telemetry = serverTelemetry ( )
22- const client = connect ( connStr ) // create a client
33+ client = connect ( serverUrl ) // create a client
2334
2435 // device to mqtt
2536 registerMessageSink ( {
@@ -28,7 +39,7 @@ export async function setup() {
2839 ingest : async ( topic , message , device ) => {
2940 if ( ! client . connected ) return
3041
31- const mqTopic = `devs/from/ ${ device . dev . rowKey } /${ topic } `
42+ const mqTopic = `${ mqttTopicPrefix ( device . dev ) } /from /${ topic } `
3243 client . publish (
3344 mqTopic ,
3445 Buffer . from ( JSON . stringify ( message ) , "utf-8" ) ,
@@ -46,18 +57,18 @@ export async function setup() {
4657 // dispatch messages to devices
4758 client . on ( "connect" , ( ) => {
4859 // devs/deviceid/json/topic
49- client . subscribe ( "devs/to/+ /#" , err => {
60+ client . subscribe ( "devs/+/to /#" , err => {
5061 if ( err ) {
5162 console . error ( err )
5263 telemetry ?. trackException ( { exception : err } )
5364 } else {
54- console . log ( `mqtt: subscribe to 'devs/to/+ /#'` )
65+ console . log ( `mqtt: subscribe to 'devs/+/to /#'` )
5566 }
5667 } )
5768 } )
5869 client . on ( "message" , async function ( topic , message ) {
5970 const { deviceId, msgTopic } =
60- / ^ d e v s \/ t o \/ (?< deviceId > .+ ?) \/ (?< msgTopic > .+ ) $ / . exec ( topic )
71+ / ^ d e v s \/ (?< deviceId > .+ ?) \/ t o \/ (?< msgTopic > .+ ) $ / . exec ( topic )
6172 ?. groups || { }
6273 if ( ! deviceId || ! msgTopic ) return // unknown topic
6374 const did : DeviceId = {
0 commit comments