LightHub 4.6.0
Open-source smart home controller firmware
Loading...
Searching...
No Matches
out_Modbus Class Reference

Generic Modbus register channel driver, channel type CH_MBUS = 14. More...

#include <out_modbus.h>

Inheritance diagram for out_Modbus:

Public Member Functions

 out_Modbus ()
 Default constructor; binds nothing until link() is called.
void link (Item *_item)
 Links the channel item and attaches persistent storage.
int Setup () override
 Creates persistent storage, loads the template config and prepares the @S marks.
int Poll (short cause) override
 Sends queued (MB_NEED_SEND) parameter values, then polls the configured register lists and executes mapped actions.
int Stop () override
 Releases the persistent storage.
int getChanType () override
 Returns CH_MBUS (14).
int Ctrl (itemCmd cmd, char *subItem=NULL, bool toExecute=true, bool authorized=false) override
 Queues a command for a template parameter (by subitem name or by suffix id), see class doc.
Public Member Functions inherited from abstractOut
 abstractOut ()
virtual int isActive ()
virtual bool isAllowed (itemCmd cmd)
virtual itemCmd getDefaultOnVal ()
virtual int Status () override
virtual void setStatus (uint8_t status) override
Item * getItem ()
Public Member Functions inherited from abstractCh
 abstractCh ()
virtual ~abstractCh ()

Protected Member Functions

bool getConfig ()
 Загружает и применяет конфигурацию Modbus.
itemCmd findRegister (uint16_t registerNum, uint16_t posInBuffer, uint8_t regType, uint16_t registerFrom, uint16_t registerTo, bool doExecution=true, bool *submitParam=NULL)
 Находит и обрабатывает регистр Modbus, выполняет сопоставление и действия.
void pollModbus (aJsonObject *reg, int regType)
 Опрос Modbus-устройства по списку регистров.
void initLine ()
 Инициализирует линию связи Modbus.
int sendModbus (char *paramName, aJsonObject *outValue)
 Отправляет значение в Modbus-устройство.
int sendItemCmd (aJsonObject *templateParamObj, itemCmd cmd)
 Отправляет команду itemCmd в Modbus по шаблону параметра.
int createLastMeasured (char *name)
 Создаёт поле для хранения последнего измеренного значения по имени параметра.
int createLastMeasured (aJsonObject *execObj)
 Создаёт поле для хранения последнего измеренного значения по JSON-объекту.
aJsonObject * getLastMeasured (char *name)
 Получает объект последнего измеренного значения по имени параметра.
aJsonObject * getLastMeasured (aJsonObject *execObj)
 Получает объект последнего измеренного значения по JSON-объекту.
void setLastMeasured (aJsonObject *execObj, int val)
Protected Member Functions inherited from abstractOut
int pubAction (bool state)
Protected Member Functions inherited from abstractCh
int publishTopic (const char *topic, long value, const char *subtopic=NULL)
int publishTopic (const char *topic, float value, const char *subtopic=NULL)
int publishTopic (const char *topic, const char *value, const char *subtopic=NULL, const char *suffix=NULL)

Protected Attributes

mbPersistent * store
Protected Attributes inherited from abstractOut
Item * item
 Item currently linked to this driver.

Detailed Description

Generic Modbus register channel driver, channel type CH_MBUS = 14.

The channel is described by a template from the global Modbus template table: registers are polled periodically, mapped to item parameters and fired as execution actions, and control commands are written back to the registers. Last sent / last measured values are tracked per parameter in the "@V" / "@S" marks to suppress redundant writes and re-executions.

JSON config (itemArg): [addr, "template", {params}]

  • addr: Modbus unit address;
  • "template": name of a template in the global modbus settings (keys: serial, baud, poll{regs, irs, coils, dins, delay}, par);
  • {params}: per-parameter objects; a template parameter supports reg/ir/coil/din (address), type, id (suffix code), map, def, prefetch.

Register value types: i16, i32, u16, u32, i8h, i8l, u8h, u8l, x10, 100.

Ctrl: the subitem (template parameter name) takes priority, otherwise the suffix code is matched against the "id" of the template parameters (e.g. S_CMD / S_SET or a custom numeric id).

Constructor & Destructor Documentation

◆ out_Modbus()

out_Modbus::out_Modbus ( )
inline

Default constructor; binds nothing until link() is called.

Member Function Documentation

◆ createLastMeasured() [1/2]

int out_Modbus::createLastMeasured ( aJsonObject * execObj)
protected

Создаёт поле для хранения последнего измеренного значения по JSON-объекту.

Parameters
execObjJSON-объект параметра.
Returns
true, если успешно, иначе false.

◆ createLastMeasured() [2/2]

int out_Modbus::createLastMeasured ( char * name)
protected

Создаёт поле для хранения последнего измеренного значения по имени параметра.

Parameters
nameИмя параметра.
Returns
true, если успешно, иначе false.

◆ Ctrl()

int out_Modbus::Ctrl ( itemCmd cmd,
char * subItem = NULL,
bool toExecute = true,
bool authorized = false )
overridevirtual

Queues a command for a template parameter (by subitem name or by suffix id), see class doc.

Control unified Modbus item.

Унифицированное управление Modbus-каналом.

Parameters
cmdКоманда itemCmd.
subItemИмя подэлемента.
toExecuteВыполнять ли команду.
authorizedАвторизовано ли выполнение.
Returns
Результат выполнения.

Implements abstractOut.

◆ findRegister()

itemCmd out_Modbus::findRegister ( uint16_t registerNum,
uint16_t posInBuffer,
uint8_t regType,
uint16_t registerFrom,
uint16_t registerTo,
bool doExecution = true,
bool * submitParam = NULL )
protected

Находит и обрабатывает регистр Modbus, выполняет сопоставление и действия.

Parameters
registerNumНомер регистра.
posInBufferПозиция в буфере ответа.
regTypeТип регистра.
registerFromНачальный регистр диапазона.
registerToКонечный регистр диапазона.
doExecutionВыполнять ли действие.
submitParamФлаг для подавления повторных действий.
Returns
Команда itemCmd с результатом.

◆ getChanType()

int out_Modbus::getChanType ( )
overridevirtual

Returns CH_MBUS (14).

Возвращает тип канала.

Returns
CH_MBUS.

Reimplemented from abstractOut.

◆ getConfig()

bool out_Modbus::getConfig ( )
protected

Загружает и применяет конфигурацию Modbus.

Returns
true, если конфигурация успешно загружена, иначе false.

◆ getLastMeasured() [1/2]

aJsonObject * out_Modbus::getLastMeasured ( aJsonObject * execObj)
protected

Получает объект последнего измеренного значения по JSON-объекту.

Parameters
execObjJSON-объект параметра.
Returns
JSON-объект или NULL.

◆ getLastMeasured() [2/2]

aJsonObject * out_Modbus::getLastMeasured ( char * name)
protected

Получает объект последнего измеренного значения по имени параметра.

Parameters
nameИмя параметра.
Returns
JSON-объект или NULL.

◆ initLine()

void out_Modbus::initLine ( )
protected

Инициализирует линию связи Modbus.

◆ link()

void out_Modbus::link ( Item * _item)
inlinevirtual

Links the channel item and attaches persistent storage.

Reimplemented from abstractOut.

◆ Poll()

int out_Modbus::Poll ( short cause)
overridevirtual

Sends queued (MB_NEED_SEND) parameter values, then polls the configured register lists and executes mapped actions.

Осуществляет опрос и отправку команд Modbus.

Parameters
causeПричина вызова (например, медленный опрос).
Returns
Интервал следующего опроса.

return 1; //relax

Reimplemented from abstractCh.

◆ pollModbus()

void out_Modbus::pollModbus ( aJsonObject * reg,
int regType )
protected

Опрос Modbus-устройства по списку регистров.

Parameters
regJSON-объект с регистрами.
regTypeТип регистра.

◆ sendItemCmd()

int out_Modbus::sendItemCmd ( aJsonObject * templateParamObj,
itemCmd cmd )
protected

Отправляет команду itemCmd в Modbus по шаблону параметра.

Parameters
templateParamObjJSON-объект шаблона параметра.
cmdКоманда itemCmd.
Returns
1 при успехе, 0 при ошибке.

◆ sendModbus()

int out_Modbus::sendModbus ( char * paramName,
aJsonObject * outValue )
protected

Отправляет значение в Modbus-устройство.

Parameters
paramNameИмя параметра.
outValueJSON-объект с отправляемым значением.
Returns
0 при успехе, отрицательное значение при ошибке.

to prevent CORRUPTIOIN if using same buffer

◆ setLastMeasured()

void out_Modbus::setLastMeasured ( aJsonObject * execObj,
int val )
protected

◆ Setup()

int out_Modbus::Setup ( )
overridevirtual

Creates persistent storage, loads the template config and prepares the @S marks.

Инициализирует канал Modbus и загружает конфигурацию.

Returns
1 при успехе, 0 при ошибке.

Reimplemented from abstractOut.

◆ Stop()

int out_Modbus::Stop ( )
overridevirtual

Releases the persistent storage.

Останавливает работу канала Modbus и освобождает ресурсы.

Returns
1 при успехе.

Reimplemented from abstractCh.

Member Data Documentation

◆ store

mbPersistent* out_Modbus::store
protected

The documentation for this class was generated from the following files: