### Publish Example

A Raspberry Pi MQTT publish example for the illuminance (from sensor BH1750).
The B4J non-UI program
• connects to MQTT localhost address and
• publishes, controlled by a timer, the Illuminance (in lux)
• as topic BH1750/Illuminance
'Non-UI application (console / server application)
`Sub Process_Globals
' MQTT - user and password are left blank
Private mqtt As MqttClient
Private mqttuser As String = ""
Private mqttpassword As String = ""
Private mqtttopicilluminance As String = "BH1750/Illuminance"
' Timer to publish topics
Private PublishTimer As Timer
Private PublishTimerInterval As Long = 2000
' Sensor
' Define the BH1750 device. The I2C address used is 0x23 - check out with sudo i2cdetect
Private bh As BH1750
End Sub`
`Sub AppStart (Args() As String)
AppInit
mqtt_Init
StartMessageLoop
End Sub`
`Private Sub AppInit
' Init the BH1750 device with device address 0x23 or 0x5C and bus number 0 (Pi 1) or 1 (Pi 2,3)
If bh.Initialize(0x23, 1) = False Then Return
' Power on and set the measurement mode
bh.PowerOnSetMode(bh.CONTINUOUS_HIGH_RES_MODE_1)
' Init the timer to publish topics in regular intervals
PublishTimer.Initialize("PublishTimer", PublishTimerInterval)
' The timer is started after mqtt successfully connected (see sub mqtt_Connected)
PublishTimer.Enabled = False
End Sub`
`Private Sub PublishTimer_Tick
mqtt_Publish(bh.LightIntensity)
End Sub`
Region MQTT
`Private Sub mqtt_Init
' MQTT Create a unique id
Dim clientId As String = Rnd(0, 999999999) & DateTime.Now
' Init the mqtt as localhost
mqtt.Initialize("mqtt", "tcp://localhost", clientId)
' Set the mqtt connect options
Dim mo As MqttConnectOptions
mo.Initialize(mqttuser, mqttpassword)
mqtt.Connect2(mo)
End Sub`
`Private Sub mqtt_Connected (Success As Boolean)
If Success = False Then
Log($"MQTT Connected Error: ${LastException}"$)
Else
Log($"MQTT Connected: OK"$)
PublishTimer.Enabled = True
' Add any subscriptions
' mqtt.Subscribe("myTopic/#", 0)
End If
End Sub`
`Private Sub mqtt_Disconnected
Log($"MQTT Disconnected."$)
End Sub`
`Private Sub mqtt_MessageArrived (Topic As String, Payload() As Byte)
Dim PayLoadStr As String
PayLoadStr = BytesToString(Payload, 0, Payload.Length, "utf8")
Log($"MQTT MessageArrived: ${Topic}=${PayLoadStr}"$)
Select PayLoadStr
' Case ...
End Select
End Sub`
`Private Sub mqtt_Publish(value As Double)
Dim valuestr As String = NumberFormat(value,0,0)
mqtt.Publish(mqtttopicilluminance, valuestr.GetBytes("UTF8"))
Log($"${DateTime.Time(DateTime.Now)} ${valuestr} lux"$)
End Sub`
End Region

Changed: 2018-03-28 16:03, Category: MQTT, File: T6C221M1628.htm, ID: 1628