Skip to content

dim-kut/openHAB-SimpleBinary

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

93 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Introduction

This binding for openHAB has ability to connect directly DIY devices (based on Arduino or whatever else). Binding uses serial communication or network communication over implemented TCP server.

Used protocol is easy to implement. Implementation examples for Arduino over serial, STM8, ESP8266 over TCP is part of repository. Arduino IDE library is also available.

Compiled binding is inserted into release branch: https://github.com/docbender/openHAB-SimpleBinary/releases

Binding is working with openHAB 1.8 as well as with openHAB2 in 1.x compatibility mode.

Serial port

It is possible to configure several ports not only one. At one line it is possible to connect several devices (ready for RS422/RS485).

Binding sets the serial port speed according to user configuration. Other parameters are set as follows: 8 data bits, 1 stop bit, without parity and without flow control.

Flow control (especially for RS-485 converters) can be provided through RTS pin. This can be turned on by adding forceRTS parameter in binding port configuration. If it is required inverted function of RTS pin, forceRTSInv parameter should be added in configuration instead forceRTS.

Communication can operate in 2 data read modes - OnScan and OnChange.

TCP server

At binding startup TCP server start listening on user defined port. In basic 256 clients are supported. Every connected client gets actual items states after device ID verification.

Known limitations: max.256 clients(protocol limitation).

Operating modes

Communication can operate it 2 modes reading data from connected devices - OnScan and OnChange. In OnScan mode all data are reading cyclically. In OnChange mode only new data are sent to openHAB. Each device is polled whether has new data and then sends new data to openHAB. One of his modes must be choose in serial port connection. TCP server connection not use any of these modes as default. Because TCP connection is full-duplex, spontaneous states send is preferred and expected.

Supported data types

Binding support openHAB data types listed in the table. Individual item types are converted to simple data types such as byte, word, double word, float, array, rgb. For same types may be converted type defined, others has it strictly defined. Supported data types

Item typeSupported data typeNotes
Numberbyte, word, dword, floatNumbers are represented in signed form. Their maximum value depends on the used type.
Floating point number is represented by float type. Float is stored in 4 bytes formatted according to IEEE 754.
Colorhsb, rgb, rgbwAll color parts are transferred in one double word. Each color component corresponds to one byte. Assignment of bytes depending on the chosen data type is following:

HSB - byte 0 - Hue, 1 - Saturation , 2 - Brightness, 3 - Not used
RGB - byte 0 - Red, 1 - Green, 2 - Blue, 3 - Not used
RGBW - byte 0 - Red, 1 - Green, 2 - Blue, 3 - White
StringarrayArray of bytes. Length of array is specified in square brackets behind type definition (e.g. array[32] defines byte array with length 32 bytes)
Contactbyte0 - off, 1 - on
Switchbyte0 - off, 1 - on
Dimmerbyte
RollershutterwordLower byte for position, upper byte for StopMove/UpDown command - 1-Move,2-Stop,4-Up,8-Down

Binding configuration

In openhab.cfg is binding configured this way:

################################### SimpleBinary Binding ######################################
#
# Select port (ex.: COM1:115200;onscan;forceRTSInv or /dev/ttyUSB1:9600). It is possible defined 
# more ports ex. port1, port2,port145,... Behind semicolon you can specify data pool control (optional).    
# Options for reach slave data are onchange(ask configured devices for new data - default) 
# or onscan(read all data every scan). Option forceRTS or forceRTSInv are for trigger RTS signal
# during data send (useful for RS485 converter). 
# TCP server is defined by tcpserver key. As value server port must be defined.
# 
# serial port configuration
simplebinary:port=COM4:9600;onchange
# TCP server configuration
simplebinary:tcpserver=43243
#refresh - check for new data interval - default 10000ms 
simplebinary:refresh=2000
Configuration parameterDescription
portSerial port definition. Configuration value consist from port name and bitrate (COM1:9600, /dev/ttyS2:57600). Behind semicolon optional parameters can be specified.
Pool control (onchange, onscan)
Enable RTS signal handling (forceRTS or forceRTSInv for signal inversion)
Multiple port can be specified. Must be deviate by number behind key (ex.: port, port1, port123,...)
tcpserverTCP server definition. As value listening port must be specified.
refreshExecution period [ms] between reading cycles. Default 10000ms.

Item configuration

Binding specify item configuration is located as usual in the brackets at the end of the configuration line. It consists of three compulsory and two optional parameters.

Configuration format:

simplebinary="port name:device address:item address:[used data type]:[direction]"
Configuration parameterDescription
port namePort name that is specified in binding configuration in openhab.cfg. For simplebinary:port= port name is port. For simplebinary:port1= port name is port1. For simplebinary:tcpserver= port name is tcpserver.
device addressThe device address is number that device is indicated on the bus (for RS485 and ethernet)
item addressIt is the address under which the data is stored in the target device.
used data typeOptional. Allow define data type. See table Supported data types
directionOptional. Can be I - input, O - output or IO - both (default). It is used only for request data from connected devices. So if all device items are outputs only, there would be no requesting for data from device. It is also good to define data direction for inter-device communication items.

Example of binding configuration:

Dimmer    Item01    "Value[%d]"    { simplebinary="port:1:1" }
Number    Item02    "Value[%d]"    { simplebinary="port:1:3:dword:IO" }
Number    Item03    "Value[%f]"    { simplebinary="port:1:4:float:O" }
Number    Item04    "Value[%f]"    { simplebinary="port:1:14:float:I" }
String    Item05    "Value[%s]"    { simplebinary="port:2:1:array[32]:O" }
Color     TestColor01              { simplebinary="tcpserver:2:2:rgb:O" }

Inter-device communication

Binding support inter-device communication. To configure this another device/binding can be specified separated by comma in item configuration. In examples values from first device are written into openHAB (input-I direction) and same value is immediately written into second device (output-O direction):

Number    Temperature    "Value[%f]"    { simplebinary="port:1:1:float:I", simplebinary="tcpserver:1:1:float:O" }
Number    TemperatureCPU "Value[%f]"    { exec="<[/bin/cat /sys/class/thermal/thermal_zone0/temp:30000:JS(divideTemp.js)]", simplebinary="tcpserver:1:2:float:O" }    

Diagnostic item configuration

Binding itself offers some diagnostic states. There are available statuses for communication port itself and also statuses for connected devices. These statuses can be provided into openHAB if they are properly configured (by use configuration parameter info behind port name or device address).

Port diagnostic info configuration format:

simplebinary="port name:info:port status"

Port statuses:

StatusDescriptionReturned values
stateReturn current port status.0 - Unknown
1 - Listening (opened and ready)
2 - Closed
3 - Not exist
4 - Not available (probably used)
previous_stateReturn previous port statusSame as state
state_change_timeReturn time when status was changedDateTime value

Device diagnostic info configuration format:

simplebinary="port name:device address:info:device status"

Device statuses:

StatusDescriptionReturned values
stateReturn current device status.0 - Unknown
1 - Connected and answering
2 - Not responding / disconnected
3 - Response error (device still wants repeat query - received message had bad CRC)
4 - Data error (device report unknown item address, unknown data, unsupported message or error while saving delivered data)
previous_stateReturn previous device statusSame as state
state_change_timeReturn time when status was changedDateTime value
packet_lostReturn percentage of packet lost (not delivered, bad CRC, ...) within last 5 minutes0-100%

Example of diagnostic item configuration:

Number    PortState            "Port state [%s]"                 { simplebinary="port:info:state" }
Number    PortPreviouState     "Port previous state [%s]"        { simplebinary="port:info:previous_state" }
DateTime  PortStateChangeTime  "Port changed [%1$tA, %1$td.%1$tm.%1$tY %1$tT]"    { simplebinary="port:info:state_change_time" }

Number    Dev01State           "Device 1 state [%s]"             { simplebinary="port:1:info:state" }
Number    Dev01PreviouState    "Device 1 previous state [%s]"    { simplebinary="port:1:info:previous_state" }
DateTime  Dev01StateChangeTime "Device 1 changed [%1$tA, %1$td.%1$tm.%1$tY %1$tT]" { simplebinary="port:1:info:state_change_time" }
Number    Dev01PacketLost      "Device 1 packet lost rate [%s]"  { simplebinary="port:1:info:packet_lost" }

Number    Dev02State           "Device 2 state [%s]"             { simplebinary="port:2:info:state" }
Number    Dev02PreviouState    "Device 2 previous state [%s]"    { simplebinary="port:2:info:previous_state" }
DateTime  Dev02StateChangeTime "Device 2 changed [%1$tA, %1$td.%1$tm.%1$tY %1$tT]" { simplebinary="port:2:info:state_change_time" }
Number    Dev02PacketLost      "Device 2 packet lost rate [%s]"  { simplebinary="port:2:info:packet_lost" }

Protocol

Binding implements master/slave communication model for serial communication. OpenHAB binding is master and connected devices are slaves. Master sends command and waits for response from slave. Answer should arrived in order tens of milliseconds. However bindings has 2000ms timeout to receive answer. Communication protocol itself depends on requested operating mode of the device (OnScan / OnChange). Of course device can support both operating modes.

Network TCP connection use same protocol as serial communication but in producer/consumer communication model. When client is connected, "Hi" message must be send. Then server can verify and register device ID.

Every packet start with device address and is followed by message type. Minimum packet length is 4 bytes. Packets are secured with CRC8 which should be enough for short packets.

###Master query for new data - OnChange mode On this packet master expecting as answer "data" packet or "no data" packet (message type 0xE2).

ByteValueDescription
00xXXDevice slave address
10xD0Message type
20xXXControl byte. Supported values:
0 - standard (data check only)
1 - force all data request
3CRC8
Control byte of this packet can says type of new data retrieve: * _Standard_ (value 0) - only really new data are requested. * _Force all data_ (value 1) - that device should mark all his data as new and send it to master. This message master send when there was connection lost between devices. That because meantime data could be changed, openHAB or device restarted, ....

###Master query for data with specified address - OnScan mode On this packet master expecting as answer "data" packet or "invalid address" packet (message type 0xE4).

ByteValueDescription
00xXXDevice slave address
10xD1Message type
20xXXData address - low byte
30xXXData address - high byte
4CRC8

###Data packet for data type byte This "data" packet could be send by master to write data into slave or by slave as answer for data request. Answer from slave should "done" when everything was right.

ByteValueDescription
00xXXDevice slave address
10xDAMessage type
20xXXData address - low byte
30xXXData address - high byte
40xXXData
5CRC8

###Data packet for data type word This "data" packet could be send by master to write data into slave or by slave as answer for data request. Answer from slave should "done" when everything was right.

ByteValueDescription
00xXXDevice slave address
10xDBMessage type
20xXXData address - low byte
30xXXData address - high byte
40xXXData - low byte
50xXXData - high byte
6CRC8

###Data packet for data type dword This "data" packet could be send by master to write data into slave or by slave as answer for data request. Answer from slave should "done" when everything was right.

ByteValueDescription
00xXXDevice slave address
10xDCMessage type
20xXXData address - low byte
30xXXData address - high byte
40xXXData - 1. byte (lowest)
50xXXData - 2. byte
60xXXData - 3. byte
70xXXData - 4. byte (highest)
8CRC8

###Data packet for type HSB, RGB, RGBW This "data" packet could be send by master to write data into slave or by slave as answer for data request. Answer from slave should "done" when everything was right.

ByteValueDescription
00xXXDevice slave address
10xDDMessage type
20xXXData address - low byte
30xXXData address - high byte
40xXXData - 1. byte (lowest)
50xXXData - 2. byte
60xXXData - 3. byte
70xXXData - 4. byte (highest)
8CRC8

###Data packet for type array This "data" packet could be send by master to write data into slave or by slave as answer for data request. Answer from slave should "done" when everything was right.

ByteValueDescription
00xXXDevice slave address
10xDEMessage type
20xXXData address - low byte
30xXXData address - high byte
40xXXData length - low byte
50xXXData length - high byte
60xXXData
...0xXXData
n-1CRC8

###Acknowledge packet - Done Answer from slave that data write from master was accepted.

ByteValueDescription
00xXXDevice slave address
10xE0Message type
20x00
3CRC8

###Error packet - Repeat Answer that received packet had wrong CRC. On this packet master react by sending last packet again (max. 3 time).

ByteValueDescription
00xXXDevice slave address
10xE1Message type
20xXXHere is expected CRC8 calculated by slave (master logged it for comparison).
3CRC8

###Acknowledge packet - No new data Slave react with this packet on query for new data in OnChange mode in case that there's no data to send.

ByteValueDescription
00xXXDevice slave address
10xE2Message type
20x00
3CRC8

###Error packet - Unknown data Slave react with this packet if received message had unknown/unsupported type.

ByteValueDescription
00xXXDevice slave address
10xE3Message type
20x00
3CRC8

###Error packet - Unknown address Slave react with this packet if received message had unknown data item address.

ByteValueDescription
00xXXDevice slave address
10xE4Message type
20x00
3CRC8

###Error packet - Error while saving data Slave send this packet when he could not save received data from master.

ByteValueDescription
00xXXDevice slave address
10xE5Message type
20x00
3CRC8

###Hi packet This packet is for connection model producer/consumer (TCP client/server connection). Client sends this packet after he is connected to server.

ByteValueDescription
00xXXDevice address
10xE6Message type
20x00
3CRC8

###Welcome packet This packet is for connection model producer/consumer (TCP client/server connection). Server sends this packet as Hi packet response.

 
ByteValueDescription
00xXXDevice address
10xD2Message type
20xXXAssigned address
3CRC8

###Deny packet This packet is for connection model producer/consumer (TCP client/server connection). Server sends this packet as Hi packet response.

 
ByteValueDescription
00xXXDevice address
10xD3Message type
20x00
3CRC8

###Want all data This packet is sent by device to tell that he want's all his data. In master/slave configuration it could be send as response for new data request (0xD0). Note: all data are normally sent when device is connected.

ByteValueDescription
00xXXDevice address
10xE7Message type
20x00
3CRC8

##Implementation The extent of implementation depends on the required features and data types (see chapter Protocol).

At first device should check if message is correctly received (CRC check). Secondly device should check if message is for him by compare message address and his own assigned address. If the address is different device must not respond! Otherwise device must response in corresponding way (see chapter Protocol).

##Implementation example Implementation example for Arduino can be found in Arduino library repo folder.

It consists of two main classes. Class simpleBinary which contains protocol implementation itself and class itemData which provides item data storage and handling with item.


Class simpleBinary - public methods
simpleBinary(int uartAddress, int size)
Constructor.
Parameters: uartAddress - device address at communication line, size - number of exchanged items
voidinitItem(int indexAndAddress, itemType type, void (*pFce)(itemData*))
Initilize item.
Parameters: indexAndAddress - item index in configuration array and also item address used during communication, type - item data type, last parameter is pointer to function that is executed on data receive(NULL for no action).
voidprocessSerial()
Process data received by UART.
boolcheckAddress(int address)
Check if address exist in items array.
Parameters: address - item address used during communication
voidreadData(int address)
Read data on given address and send it to master.
Parameters: address - item address used during communication
boolsaveByte(int address, char* data)
Save byte from given data pointer to addresed item. Return false if target is not expected data type.
Parameters: address - item address used during communication, data - pointer to data to save.
boolsaveWord(int address, char* data)
Save word from given data pointer to addresed item. Return false if target is not expected data type.
Parameters: address - item address used during communication, data - pointer to data to save.
boolsaveDword(int address, char* data)
Save double word from given data pointer to addresed item. Return false if target is not expected data type.
Parameters: address - item address used during communication, data - pointer to data to save.
boolsaveArray(int address, char *pData, int len)
Save byte array from given data pointer to addresed item. Return false if target is not expected data type.
Parameters: address - item address used during communication, pData - pointer to data to save, len - array length (byte count)
intsize()
Return items count.
voidenableRTS(int pinNumber)
Enable RTS handling. RTS pin is passed as parameter.
voidsetSendDelay(unsigned int delayms)
Sets delay between receive and transmit message (in ms). Good for communication line stabilization.

Class itemData - public methods
itemData()
Constructor.
itemData(int address, itemType type, void (*pFce)(itemData*) )
Constructor with item initialization .
Parameters: address - item address used during communication, type - item data type, last parameter is pointer to function that is executed on data receive(NULL for no action).
itemData(int address, itemType type, int size, void (*pFce)(itemData*) )
Constructor with item initialization for arrays.
Parameters: address - item address used during communication, type - item data type, size - data size in bytes, last parameter is pointer to function that is executed on data receive(NULL for no action).
voidinit(int address, itemType type, void (*pFce)(itemData*))
Item initialization .
Parameters: address - item address used during communication, type - item data type, last parameter is pointer to function that is executed on data receive(NULL for no action).
boolsaveByte(char* data)
Save byte from given data pointer. Return false if target is not expected data type.
Parameters: data - pointer to data to save.
boolsaveWord(char* data)
Save word from given data pointer. Return false if target is not expected data type.
Parameters: data - pointer to data to save.
boolsaveDword(char* data)
Save double word from given data pointer. Return false if target is not expected data type.
Parameters: data - pointer to data to save/td>
boolsaveArray(char *pData, int len)
Save array from given data pointer. Return false if target is not expected data type.
Parameters: data - pointer to data to save, len - array length (byte count)
voidsave(int value)
Save int value.
Parameters: value - value to save
voidsave(float value)
Save float value.
Parameters: value - value to save
intgetAddress()
Return item address.
voidsetNewData()
Set item "new data" flag.
boolhasNewData()
Check if item has "new data" flag set.
char*getData()
Return item data.
char*readNewData()
Return item data and reset "new data" flag.
itemTypegetType()
Return item data type.
intgetDataLength()
Return length of data.
voidexecuteAction()
Execute action connected at item initialization.

###CRC8 calculation implementation

char CRC8::evalCRC(char *data, int length)
{
   int crc = 0;
   int i, j;

   for(j=0; j < length; j++)
   {
      crc ^= (data[j] << 8);
	
      for(i=0;i<8;i++)
      {
         if((crc & 0x8000) != 0)
            crc ^= (0x1070 << 3);
	
         crc <<= 1;
      }
   }	
   return (char)(crc >> 8);
}

About

Serial / TCP binding for openHAB

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C 59.6%
  • C++ 22.4%
  • Java 16.9%
  • Other 1.1%