### Sample IO-16 Port State B4J

TinkerForge RED Brick example to get or set the state of a TinkerForge IO-16 Bricklet Port using the openHAB REST API.
Brick Setup:
RED Brick > Master Brick > IO-16 Bricklet > Port A0 > LED 3.3v.
B4J Layout
The layout file contains
TextFields tfOHServerURL, tfOHIO16PortItem
ToggleButton tbtnSetIO16PortState, Button btnGetIO16PortState
TextArea taRequestResult
Label lblIO16PortState.
B4J Code
`Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private tfOHServerURL As TextField
Private tfOHIO16PortItem As TextField
Private tbtnSetIO16PortState As ToggleButton
Private btnGetIO16PortState As Button
Private taRequestResult As TextArea
Private lblIO16PortState As Label
End Sub`
`Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
MainForm.RootPane.LoadLayout("Main")
MainForm.SetFormStyle("UTILITY")
MainForm.Title = "B4J HowTo openHAB REST-API IO-16"
MainForm.Show
AppInit
End Sub`
`Sub AppInit
'Set the openHAB server URL and the Switch Item
tfOHServerURL.Text = "http://192.168.0.30:8080"
tfOHIO16PortItem.Text = "outa0"
'Get the port state
btnGetIO16PortState_Action
End Sub`
`Sub MainForm_CloseRequest (EventData As Event)
MainForm.Close
End Sub`
'Set the state of an IO16 Port
'Used is HTTP Post request
`Sub tbtnSetIO16PortState_SelectedChange(Selected As Boolean)
Dim job As HttpJob
Dim state As String = "ON"
'Init the job
job.Initialize("setio16portstate", Me)
If Not(Selected ) Then state = "OFF"
job.PostString($"${tfOHServerURL.text}/rest/items/${tfOHIO16PortItem.text}/"$, state)
job.GetRequest.SetHeader("Content-Type", "text/plain")
taRequestResult.Text = $"Job Started${CRLF}${tfOHServerURL.text}/rest/items/${tfOHIO16PortItem.text}/${state}${CRLF}"$
End Sub`
'Get the state of a switch
'Example URL: http://192.168.0.30:8080/rest/items/outa0/state
`Sub btnGetIO16PortState_Action
Dim job As HttpJob
'Init the job
job.Initialize("getio16portstate", Me)
'HTTP GET IO-16 Port State
job.Download($"${tfOHServerURL.text}/rest/items/${tfOHIO16PortItem.text}/state"$)
job.GetRequest.SetHeader("Content-Type", "text/plain")
taRequestResult.Text = $"Job Started${CRLF}${tfOHServerURL.text}/rest/items/${tfOHIO16PortItem.text}/state${CRLF}"$
End Sub`
`Sub JobDone (job As HttpJob)
Dim sb As StringBuilder
sb.Initialize
sb.Append($"Job Done${CRLF}JobName = ${job.JobName}, Success = ${job.Success}${CRLF}"$)
If job.Success = True Then
sb.Append($"${job.GetString}${CRLF}"$)
fx.Clipboard.SetString(job.GetString)
If job.JobName.EqualsIgnoreCase("getio16portstate") Then
lblIO16PortState.Text = job.GetString
End If
If job.JobName.EqualsIgnoreCase("setio16portstate") Then
btnGetIO16PortState_Action
End If
Else
sb.Append($"Request Error:${CRLF}${job.ErrorMessage}"$)
End If
taRequestResult.Text = taRequestResult.Text & sb.ToString
job.Release
End Sub`

Changed: 2018-06-07 09:26, Category: TinkerForge openHAB, File: T6C267M1994.htm, ID: 1994