import * as log from './log'
import * as config from './config'
import * as gpio from 'onoff'
import * as Mqtt from 'mqtt'


const LED1 = new gpio.Gpio(16, 'out')
const LED2 = new gpio.Gpio(26, 'out')


log.info("PiAlive starting")
LED1.writeSync(0)
LED2.writeSync(0)


let heartbeatTimer = setInterval(() => {
  LED1.writeSync(1)
  setTimeout(() => {
    LED1.writeSync(0)
  }, 100)
}, config.dict.heartbeatInterval)



let mqttClient = Mqtt.connect(config.dict.brokerUrl)
mqttClient.on('offline', () => { log.warn("MQTT client is offline") })
mqttClient.on('reconnect', () => { log.warn("MQTT client is reconnecting") })
mqttClient.on('close', () => { log.warn("MQTT connection closed") })

mqttClient.on('connect', () => {
  log.info("MQTT broker connected")
  mqttClient.subscribe(config.dict.topic)
  log.info(`Subscribed to ${config.dict.topic}`)
})

let msgCnt = 0
mqttClient.on('message', (topic : string, messageBuf : Buffer) => {
  msgCnt++;
  if (config.dict.verbose) {
    let message = messageBuf.toString('UTF-8')
    log.info(`Message received ${msgCnt}, topic ${topic}, payload ${message}`)
  }

  LED2.writeSync(1)
  setTimeout(() => {
    LED2.writeSync(0)
  }, 100)
})




log.info("PiAlive running")
