Skip to content
Thomas T. Jarløv edited this page Aug 8, 2018 · 3 revisions

NimHA currently supports to send test messages via MQTT and creating MQTT templates. The templates can be used with alarm and cronjob module.

Create a template

Go to the MQTT page.

The templates consist of 3 elements.

  • The name which is the identifier in NimHA
  • The topic which is the MQTT topic
  • The message which is the message sent to the topic

Helpers

If you are having multiple devices/Raspberry Pi's, you can make the react on things happening in NimHA by using MQTT.

The example below is a small program, which will start a MJPEG stream, when a MQTT message with the topic door and message startstream is sent.

Compile and run it on the device (requires mosquitto_clients). Checkout the Wiki - Mosquitto and the Wiki - MJPEG page.

import asyncdispatch
import osproc
import strutils
import streams


var ffserver: Process
var ffmpeg: Process
var ffserverActive = false

proc mqttParser(payload: string) {.async.} =
  ## Parse the raw output from Mosquitto sub

  let topicName = payload.split(" ")[0]
  let message   = payload.replace(topicName & " ", "")
  
  case message
  of "startstream":
    if not ffserverActive:
      ffserverActive = true
      ffserver = startProcess("ffserver -f /etc/ffserver.conf", options = {poEvalCommand})
      ffmpeg = startProcess("ffmpeg -r 15 -s 640x480 -f video4linux2 -i /dev/video0 http://127.0.0.1:9090/feed1.ffm", options = {poEvalCommand})
  
  of "stopstream":
    kill(ffserver)
    kill(ffmpeg)
    discard execCmd("pkill ffserver")
    discard execCmd("pkill ffmpeg")
    ffserverActive = false

  else:
    discard



let s_mqttPathSub   = "/usr/bin/mosquitto_sub"
let s_mqttPassword  = "secretPassword"
let s_clientName    = "secretUsername"
let s_mqttIp        = "192.168.1.150"
let s_mqttPort      = "8883"
let s_topic         = "door"

proc mosquittoSub() =
  ## Start Mosquitto sub listening on #

  var mqttProcess = startProcess(s_mqttPathSub & " -v -t " & s_topic & " -u " & s_clientName & " -P " & s_mqttPassword & " -h " & s_mqttIp & " -p " & s_mqttPort, options = {poEvalCommand})

  while running(mqttProcess):
    asyncCheck mqttParser(readLine(outputStream(mqttProcess)))


mosquittoSub()
quit()