1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | 1x 1x 1x 3x 11x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 2x 11x 2x 1x 5x 5x 12x 12x 12x 12x 12x 12x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 1x 28x 14x 14x 2x 12x 8x 8x 4x 4x 4x 12x 12x 5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 1x | import {PubSubEngine} from 'graphql-subscriptions/dist/pubsub'; import {connect, Client, ClientPublishOptions, ClientSubscribeOptions, Granted} from 'mqtt'; import {each} from 'async'; export interface PubSubMQTTOptions { brokerUrl?: string; client?: Client; connectionListener?: (err: Error) => void; publishOptions?: PublishOptionsResolver; subscribeOptions?: SubscribeOptionsResolver; onMQTTSubscribe?: (id: number, granted: Granted) => void; triggerTransform?: TriggerTransform; parseMessageWithEncoding?: string; } export class MQTTPubSub implements PubSubEngine { constructor(options: PubSubMQTTOptions = {}) { this.triggerTransform = options.triggerTransform || (trigger => trigger as string); Iif (options.client) { this.mqttConnection = options.client; } else { const brokerUrl = options.brokerUrl || 'mqtt://localhost'; this.mqttConnection = connect(brokerUrl); } this.mqttConnection.on('message', this.onMessage.bind(this)); Iif (options.connectionListener) { this.mqttConnection.on('connect', options.connectionListener); this.mqttConnection.on('error', options.connectionListener); } else { this.mqttConnection.on('error', console.error); } this.subscriptionMap = {}; this.subsRefsMap = {}; this.currentSubscriptionId = 0; this.onMQTTSubscribe = options.onMQTTSubscribe || (() => null); this.publishOptionsResolver = options.publishOptions || (() => Promise.resolve({})); this.subscribeOptionsResolver = options.subscribeOptions || (() => Promise.resolve({})); this.parseMessageWithEncoding = options.parseMessageWithEncoding; } public publish(trigger: string, payload: any): boolean { this.publishOptionsResolver(trigger, payload).then(publishOptions => { this.mqttConnection.publish(trigger, JSON.stringify(payload), publishOptions); }); return true; } public subscribe(trigger: string, onMessage: Function, options?: Object): Promise<number> { const triggerName: string = this.triggerTransform(trigger, options); const id = this.currentSubscriptionId++; this.subscriptionMap[id] = [triggerName, onMessage]; let refs = this.subsRefsMap[triggerName]; if (refs && refs.length > 0) { const newRefs = [...refs, id]; this.subsRefsMap[triggerName] = newRefs; return Promise.resolve(id); } else { return new Promise<number>((resolve, reject) => { // 1. Resolve options object this.subscribeOptionsResolver(trigger, options).then(subscriptionOptions => { //I 2. Subscribing using MQTT this.mqttConnection.subscribe(triggerName, {qos: 0, ...subscriptionOptions}, (err, granted) => { if (err) { reject(err); } else { // 3. Saving the new sub id const subscriptionIds = this.subsRefsMap[triggerName] || []; this.subsRefsMap[triggerName] = [...subscriptionIds, id]; // 4. Resolving the subscriptions id to the Subscription Manager resolve(id); // 5. Notify implementor on the subscriptions ack and QoS this.onMQTTSubscribe(id, granted); } }); }).catch(err => reject(err)); }); } } public unsubscribe(subId: number) { const [triggerName = null] = this.subscriptionMap[subId] || []; const refs = this.subsRefsMap[triggerName]; if (!refs) throw new Error(`There is no subscription of id "${subId}"`); let newRefs; if (refs.length === 1) { this.mqttConnection.unsubscribe(triggerName); newRefs = []; } Eelse { const index = refs.indexOf(subId); if (index != -1) { newRefs = [...refs.slice(0, index), ...refs.slice(index + 1)]; } } this.subsRefsMap[triggerName] = newRefs; delete this.subscriptionMap[subId]; } private onMessage(topic: string, message: Buffer) { const subscribers = this.subsRefsMap[topic]; I // Don't work for nothing.. if (!subscribers || !subscribers.length) return; const messageString = message.toString(this.parseMessageWithEncoding); let parsedMessage; try { parsedMessage = JSON.parse(messageString); } catch (e) { parsedMessage = messageString; } each(subscribers, (subId, cb) => { const [triggerName, listener] = this.subscriptionMap[subId]; listener(parsedMessage); cb(); }) } private triggerTransform: TriggerTransform; private onMQTTSubscribe: SubscribeHandler; private subscribeOptionsResolver: SubscribeOptionsResolver; private publishOptionsResolver: PublishOptionsResolver; private mqttConnection: Client; private subscriptionMap: {[subId: number]: [string , Function]}; private subsRefsMap: {[trigger: string]: Array<number>}; private currentSubscriptionId: number; private parseMessageWithEncoding: string; } export type Path = Array<string | number>; export type Trigger = string | Path; export type TriggerTransform = (trigger: Trigger, channelOptions?: Object) => string; export type SubscribeOptionsResolver = (trigger: Trigger, channelOptions?: Object) => Promise<ClientSubscribeOptions>; export type PublishOptionsResolver = (trigger: Trigger, payload: any) => Promise<ClientPublishOptions>; export type SubscribeHandler = (id: number, granted: Granted) => void; |