import * as amqp from 'amqplib'; import { logger, RABBITMQ_URI } from '../app'; import { Beat } from '../models/beat/beat.model.'; import { Phone } from '../models/phone/phone.model'; interface IBeat { token: string, gpsLocation: Array, battery: number, timestamp: number } export class RabbitMQ { connection: amqp.Connection | null = null; channel: amqp.Channel | null = null; async init() { this.connection = await amqp.connect(RABBITMQ_URI); this.channel = await this.connection.createChannel(); this.channel.consume('tracker', async (income) => { if (income === undefined || income === null) return; const msg: IBeat = JSON.parse(income.content.toString()) as IBeat // Get phone const phone = await Phone.findOne({ androidId: msg.token }); if (phone == undefined) { logger.info(`Received beat from unknown device with id ${msg.token}`); return; } logger.info(`New beat from ${phone.displayName} with ${msg.gpsLocation[2]}, ${msg.gpsLocation[3]}m height and accuracy and ${msg.battery}% battery`); const newBeat = await Beat.create({ phone: phone._id, // [latitude, longitude, altitude] coordinate: [msg.gpsLocation[0], msg.gpsLocation[1], msg.gpsLocation[2]], accuracy: msg.gpsLocation[3], speed: msg.gpsLocation[4], battery: msg.battery, createdAt: msg.timestamp }); this.channel!.publish('amq.topic', '.', Buffer.from(JSON.stringify(newBeat.toJSON()))); }, { noAck: true }); } async publish(queueName = 'tracker', data: any) { if (this.connection == undefined) await this.init() this.channel?.sendToQueue(queueName, Buffer.from(data)); } }