Export translations
Перейти к:
навигация
,
поиск
Параметры
Группа
1-Wire
Allen Bradley DF1
API - Запись нового значения в регистр
API - Получение данных для графика
API - Получение данных для события
API - Получение данных о локальном времени
API - Получение лога регистров
API - Получение текущих значений регистров
API - Список блоков панелей
API - Список графиков
API - Список изображений
API - Список панелей
API - Список регистров
API - Список словарей
API - Список соединений
API - Список трендов
BACnet IP
Broadlink SP3S
Delta DVP
ModBus ASCII
ModBus RTU
Modbus RTU в виде custom protocol
ModBus TCP
Siemens PPI
Siemens S7 Communication
Test
Troubleshooting - Решение типовых проблем при работе в WebHMI
Аварии
Аннотация - функциональные возможности WebHMI
Битовые операции
Быстродействие при обмене данными
ВНИМАНИЕ! ДАННАЯ ВЕРСИЯ ВИКИ УСТАРЕЛА - см. docs.webhmi.com.ua
Внутренние регистры WebHMI
Демо-приложение для Android
Дополнительные СОМ порты
Доступ по ftp
Журнал регистров
Интеграция в другие системы
Использование MultiWan
Исторические графики
Как проверить уровень приема сигнала у 3G модема
Календарь
Назначение и применение
Настройка виртуального UART
Настройка связи с CDC-модемами на примере модема Huawei E3531
Настройка сетевых соединений
Обновление версии прошивки
Описание API
Описание внешних разъемов
Оптимизация производительности
Особенности работы с некоторыми модемами
Отладка сложных скриптов
Первое включение
Перевод на англ 2
Поддерживаемые протоколы
Подключение 3G модем ZTE K3806 Киевстар
Подключение WebHMI к Level2
Подключение внешних устройств
Подключение к Allen-Bradley MicroLogix 1200
Подключение к Kиевстар на примере модема ZTE MF100
Подключение к People.net
Подключение к S7-1200
Подключение к МТС Коннект
Подключение к ОВЕН160
Подключение к ПЛК с Codesys
Подключение к интернету через 3G модем
Полезные программы
Полезные советы
Пользовательские графики и тренды (Аналитика)
Пользовательские протоколы
Построение графиков в Level2
Пример доступа к данным из C/C++
Пример доступа к данным из Excel
Пример протокола ModBus ASCII
Пример протокола ModBus TCP
Примеры подключения к разным устройствам
Просмотр регистров по запросу
Работа с контроллером холодильного оборудования Danfoss AK-CC 550
Работа с регистрами
Рецепты
Сброс настроек
Синхронизация времени
Системные настройки и сервис
Скрипты
События
Соединения
Сравнение карт SD
Тренды
Удалённый сервисный доступ
Формирование отчетов
Функции управления соединениями
Функция Modbus/TCP сервер
Шаблоны дешбордов
Экраны
Язык
aa - Afar
ab - Abkhazian
ace - Achinese
ady - Adyghe
ady-cyrl - адыгабзэ
aeb - Tunisian Arabic
aeb-arab - تونسي
aeb-latn - Tûnsî
af - Afrikaans
ak - Akan
aln - Gheg Albanian
am - Amharic
an - Aragonese
ang - Old English
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - تۆرکجه
ba - Bashkir
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba
bcc - Southern Balochi
bcl - Bikol Central
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bg - Bulgarian
bgn - Western Balochi
bho - Bhojpuri
bi - Bislama
bjn - Banjar
bm - Bambara
bn - Bengali
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
bto - Iriga Bicolano
bug - Buginese
bxr - буряад
ca - Catalan
cbk-zam - Chavacano de Zamboanga
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cr - Cree
crh - Crimean Turkish
crh-cyrl - Crimean Turkish (Cyrillic script)
crh-latn - Crimean Turkish (Latin script)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - डोटेली
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
ff - Fulah
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gag - Gagauz
gan - Gan Chinese
gan-hans - Simplified Gan script
gan-hant - Traditional Gan script
gd - Scottish Gaelic
gl - Galician
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
got - Gothic
grc - Ancient Greek
gsw - Swiss German
gu - Gujarati
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
ht - Haitian Creole
hu - Hungarian
hy - Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kbd - Kabardian
kbd-cyrl - Адыгэбзэ
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - 한국어 (조선)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ku - Kurdish
ku-arab - كوردي (عەرەبی)
ku-latn - Kurdish (Latin script)
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - лакку
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Maori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mo - молдовеняскэ
mr - Marathi
mrj - Western Mari
ms - Malay
mt - Maltese
mus - Creek
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
niu - Niuean
nl - Dutch
nl-informal - Nederlands (informeel)
nn - Norwegian Nynorsk
nov - Novial
nrm - Nouormand
nso - Northern Sotho
nv - Navajo
ny - Nyanja
oc - Occitan
olo - Livvi-Karelian
om - Oromo
or - Oriya
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rm - Romansh
rmy - Romani
rn - Rundi
ro - Romanian
roa-tara - tarandíne
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
sa - Sanskrit
sah - Sakha
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
shi - Tachelhit
shi-latn - Tašlḥiyt
shi-tfng - ⵜⴰⵛⵍⵃⵉⵜ
si - Sinhala
sk - Slovak
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - Serbian (Cyrillic script)
sr-el - Serbian (Latin script)
srn - Sranan Tongo
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
su - Sundanese
sv - Swedish
sw - Swahili
szl - Silesian
ta - Tamil
tcy - Tulu
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tn - Tswana
to - Tongan
tokipona - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - ўзбекча
uz-latn - oʻzbekcha
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
war - Waray
wo - Wolof
wuu - Wu Chinese
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
yi - Yiddish
yo - Yoruba
yue - Cantonese
za - Zhuang
zea - Zeelandic
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - 中文(澳門)
zh-my - 中文(马来西亚)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Экспорт для оффлайнового перевод
Экспорт в родном формате
{{DISPLAYTITLE:Custom Protocols}}<languages/> <languages/> There are a lot of different automation devices with non-standard communication protocols. To solve the problem of data collection from such devices in WebHMI, it is possible to create custom protocols in Lua [https://ru.wikipedia.org/wiki/Lua]. This function is available in WebHMI since version 1.10.0.3420. == About Lua == Lua is a typical procedural programming language. It provides ample opportunities for object-oriented and functional development. Lua was created as a powerful and simple language with all the necessary expressive means. The documentation on the language can be found on the official website [http://www.lua.org/manual/5.1/]. You can easily get acquainted with the syntax on a convenient site [http://tylerneylon.com/a/learn-lua/]. WebHMI uses Lua version 5.1.5. Why Lua? Lua is a language that was specially created for embedding in applications written in C language. It has excellent performance, consumes very few resources and has rich capabilities. == General concept of custom protocols == In WebHMI, the minimum unit of information is the register. In general, data exchange with all devices occurs cyclically - the registers that should be polled in this scan are read one by one. Registers are also written one register at a time. WebHMI allows you to create your own protocol and define the read and write functions for the register. These functions must form a request, send it to the device, take an answer from it, disassemble it and, depending on the result, return the necessary data. == Creating a Protocol == To go to the list of user protocols, click on the button "'''Custom protocols'''" on the page'''Setup->Registers'''.<br/> [[Файл:Custom-protocol-button.png|600px]]<br/> You will be taken to the protocol management page. In this example, we see two demonstration protocols - ModBus TCP Demo and ModBus ASCII Demo:<br/> [[Файл:Custom-protocol-list.png|600px]]<br/> Let's look at the page for editing the ModBus TCP Demo protocol: Followed are settings used for custom protocols: * Title, description * type (TCP/IP or Serial) * default TCP port (only for TCP) * regular expression used for register address validation * An error message that will be displayed when you enter an invalid register address * Code with a custom protocol The regular expression must ensure that the register address is validated on the register editing page (when this protocol is selected). Example:<br/> [[Файл:Custom-protocol-validate.png|600px]]<br/> We also see a convenient code editor. It supports formatting, highlighting and validation of syntax. So it's convenient to write the code <br/> If there is a syntax error in the code, a red X appears in the corresponding line. To see a detailed error message, just point your mouse at it:<br/> [[Файл:Custom-protocol-error.png|600px]]<br/> After creating the protocol, it will appear in the drop-down list of available '''PLC models''' on the page of creating new'''Connections''' and with it you can work as well as with the usual built-in protocol == Necessary functions == WebHMI expects to see three functions in the custom protocol code: * createDevices * readRegister * writeRegister == createDevices == The procedure 'createDevices' is called once at the start of WebHMI and creates named prefixes for register addresses. To better understand this, let's look at an example for ModBUS devices. Let's create register types for the Coils, Discrete Inputs, Holding Registers, Input Registers: <syntaxhighlight lang="lua"> function createDevices () addDevice({name = "C", shift = 0, base = 10, xtraFields = {1, 5}}); addDevice({name = "DI", shift = 0, base = 10, xtraFields = {2, 0}}); addDevice({name = "HR", shift = 0, base = 10, xtraFields = {3, 6, 16}}); addDevice({name = "IR", shift = 0, base = 10, xtraFields = {4, 0}}); end </syntaxhighlight> There are four types of registers. For such a protocol, registers of the form C14, DI4, HR34355, IR145 can be specified in the register address line. The '''addDevice ''' procedure is called for each type of address. It is passed a table with such parameters: * name – String-prefix, it is this part in the address that will determine the further processing of the read / write of this register * shift – this will be added to the value of the register address. I.e. it can be done so that the register with address D30 is converted to (with shift = 1000) D1030, and D33 to D1033, etc. * base – address system. Some devices use addresses in octal or hexadecimal number systems * xtraFields – A set of additional parameters (maximum 5 pieces), will be transferred to the function read / write in xtraFields table. == onScanStart == The '''onScanStart''' procedure is called every time a new scan starts. It can be useful for protocols where one array reads an array of values for several registers. For such protocols, you can cache the result of the query and return values from the cache. You can reset the cache in the onScanStart procedure. onScanStart Available in firmware since version 2.1.3923. == readRegister == The function '''readRegister''' should read the specified register. In case of successful reading, the function '''readRegister '''should return an array of bytes, with length corresponding to the specified data type (1, 2 or 4) or the number. In case of failure, you must return false. Three parameters are passed to it as arguments: * reg - Table (structure) with register parameters * device - Table (structure) with register type parameters (that were defined in createDevices) * unitId – device ID for the bus or other ID. For instance, Slave ID in ModBus RTU or Unit ID in ModBus TCP. There are such attributes in the '''reg''' structure: * internalAddr - Recalculated register address. This number is recalculated from the specified number system with shift added to it. * addr - The original address of the register that the user entered. * dataType – The type of data that the user specified for the register. 0 = Bit, 1 = Byte, 2 = Word, 3 = Double Word, 4 = UnixTime There are such attributes in the '''device''' structure: * shift - The shift value from the corresponding row in createDevices * base - base value from the corresponding row in createDevices * xtraFields – xtraFields value from the corresponing row in createDevices These parameters are passed in order to be able to correctly and fully compose a request according to the protocol. Для передачи запроса устройству используются функции '''sendBytes''' и '''sendString'''. Для чтения ответа - '''readBytes''', '''readString'''. На вход '''sendBytes''' принимает таблицу (массив) байт. Результатом будет true в случае успеха и false в случае ошибки. <br> На вход '''sendString''' принимает строку. Результатом будет true в случае успеха и false в случае ошибки. <br> На вход '''readBytes''' принимает количество байт, которое необходимо прочитать. Результатом будет таблица (массив) байт в случае успеха и false в случае ошибки.<br> На вход '''readString''' принимает количество байт, которое необходимо прочитать. Результатом будет строка в случае успеха и false в случае ошибки.<br> Если необходимо закрыть соединение (например, в случае множественных ошибок), то можно вызвать процедуру '''closeConnection'''. Если необходимо сделать паузу, то можно вызвать функцию '''sleep'''. Ее единственным аргументом должно быть время в микросекундах. Пример: sleep(20000); - произойдет пауза 20 миллисекунд. Для работы с битами можно использовать библиотеку bitop [http://bitop.luajit.org/]. Для отладки и вывода диагностических сообщений можно использовать процедуры ERROR, INFO, DEBUG и TRACE которые доступны и в обычных сценариях Lua [http://wiki.webhmi.com.ua/index.php/Сценарии_LUA]. Что бы лучше понять как это все работает давайте рассмотрим пример функции readRegister для протокола ModBus TCP: <syntaxhighlight lang="lua"> local transId = 0; local errorCount = 0; function readRegister (reg, device, unitId) local request = {}; -- transaction ID transId = transId + 1; request[1] = bit.band(bit.rshift(transId, 8), 255); request[2] = bit.band(transId, 255); -- protocol ID request[3] = 0; request[4] = 0; -- message length request[5] = 0; request[6] = 6; -- unit ID request[7] = unitId; -- function code request[8] = device.xtraFields[1]; -- address of register request[9] = bit.band(bit.rshift(reg.internalAddr, 8), 255); request[10] = bit.band(reg.internalAddr, 255); -- count of registers request[11] = 0; request[12] = 1; if (reg.dataType == 3) then -- double word request[12] = 2; end local res = sendBytes(request); if (res == false) then DEBUG("Can't send bytes"); return false; end local response = {}; -- read MBAP Header response = readBytes(7); if (response == false) then errorCount = errorCount + 1; if (errorCount > 3) then closeConnection(); errorCount = 0; end DEBUG("Can't read MBAP"); return false; end res = #response; if (res ~= 7) then errorCount = errorCount + 1; if (errorCount > 3) then closeConnection(); errorCount = 0; end DEBUG("Can't read MBAP"); return false; end if (response[1] ~= request[1] or response[2] ~= request[2]) then ERROR("Wrong transaction ID. Got #" .. (response[1] * 256 + response[2]) .. " but expected #" .. (request[1] * 256 + request[2])); return false; end if (response[3] ~= request[3] or response[4] ~= request[4]) then ERROR("Wrong protocol"); return false; end if (response[7] ~= request[7]) then ERROR("Wrong UnitID in response"); return false; end local length = response[5] * 256 + response[6]; if (length < 1) then ERROR("Wrong length in response"); return false; end local responsePDU = {}; -- read MBAP Header responsePDU = readBytes(length - 1); if (responsePDU == false) then errorCount = errorCount + 1; if (errorCount > 3) then closeConnection(); errorCount = 0; end DEBUG("Can't read PDU in response"); return false; end res = #responsePDU; if (responsePDU[1] ~= request[8]) then ERROR("Wrong function in response"); return false; end local dataLength = responsePDU[2]; if (dataLength ~= length - 3) then ERROR("Wrong length in PDU"); return false; end local result = {}; if (dataLength >= 1) then for i = 1, dataLength do result[i] = responsePDU[2 + i]; end end return result; end </syntaxhighlight> == writeRegister == The '''writeRegister''' function should write a new value to the specified register. If the record is successful, it should return true. In case of an error, false. Ей передаются все те же параметры, что и для readRegister, а также дополнительно четвертый параметр - новое значение. It has all the same arguments as for readRegister, as well as an additional fourth argument, a new value. The '''writeRegister''' function may use the same methods of reading from and writing bytes to the port. Let's have a look at the example of this function for ModBus TCP protocol: <syntaxhighlight lang="lua"> function writeRegister (reg, device, unitId, newValue) local request = {}; transId = transId + 1; -- transaction ID request[1] = bit.band(bit.rshift(transId, 8), 255); request[2] = bit.band(transId, 255); -- protocol ID request[3] = 0; request[4] = 0; if (reg.dataType == 3) then -- double word -- message length request[5] = 0; request[6] = 11; -- unit ID request[7] = unitId; -- function code request[8] = device.xtraFields[3]; -- address of register request[9] = bit.band(bit.rshift(reg.internalAddr, 8), 255); request[10] = bit.band(reg.internalAddr, 255); -- count of registers request[11] = 0; request[12] = 2; -- bytes with data request[13] = 4; -- value of registers request[14] = bit.band(bit.rshift(newValue, 24), 255); request[15] = bit.band(bit.rshift(newValue, 16), 255); request[16] = bit.band(bit.rshift(newValue, 8), 255); request[17] = bit.band(newValue, 255); local res = sendBytes(request); if (res == false) then DEBUG("Can't send bytes"); return 0; end local response = {}; response = readBytes(7); if (response == false) then DEBUG("Can't read response"); return false; end res = #response; if (res ~= 7) then DEBUG("Wrong response length"); return false; end if (response[1] ~= request[1] or response[2] ~= request[2]) then ERROR("Wrong transaction ID. Got #" .. (response[1] * 256 + response[2]) .. " but expected #" .. (request[1] * 256 + request[2])); return false; end if (response[3] ~= request[3] or response[4] ~= request[4]) then ERROR("Wrong protocol"); return false; end if (response[7] ~= request[7]) then ERROR("Wrong UnitID in response"); return false; end local length = response[5] * 256 + response[6]; if (length < 1) then ERROR("Wrong length in response"); return false; end local responsePDU = {}; responsePDU = readBytes(length - 1); if (responsePDU == false) then DEBUG("Can't read response PDU"); return false; end res = #responsePDU; if (responsePDU[1] ~= request[8]) then ERROR("Wrong function in response"); return false; end if (responsePDU[2] ~= request[9] or responsePDU[3] ~= request[10]) then ERROR("Wrong register address in response"); return false; end if (responsePDU[4] ~= 0 or responsePDU[5] ~= 2) then ERROR("Wrong register count in response"); return false; end else if (device.xtraFields[2] == 0) then ERROR("Can't write these type of registers (" .. device.name .. ")"); return 0; end -- message length request[5] = 0; request[6] = 6; -- unit ID request[7] = unitId; request[8] = device.xtraFields[2]; -- address of register request[9] = bit.band(bit.rshift(reg.internalAddr, 8), 255); request[10] = bit.band(reg.internalAddr, 255); local val = newValue; if (reg.dataType == 0) then if (val > 0) then val = 255*256; else val = 0; end end -- value of registers request[11] = bit.band(bit.rshift(val, 8), 255); request[12] = bit.band(val, 255); local res = sendBytes(request); if (res == false) then DEBUG("Can't send bytes"); return 0; end local response = {}; local requestLen = #request; response = readBytes(requestLen); if (response == false) then DEBUG("Can't read response"); return false; end res = #response; if (res ~= requestLen) then DEBUG("Wrong response length"); return false; end for i = 1,res do if (response[i] ~= request[i]) then DEBUG("Wrong response"); return false; end end end return true; end </syntaxhighlight> == Примеры протоколов == В качестве примера мы реализовали несколько протоколов: *[http://wiki.webhmi.com.ua/index.php/Пример_протокола_ModBus_TCP ModBus TCP] *[http://wiki.webhmi.com.ua/index.php/Пример_протокола_ModBus_ASCII ModBus ASCII]. *[http://wiki.webhmi.com.ua/index.php/Modbus_RTU_%D0%B2_%D0%B2%D0%B8%D0%B4%D0%B5_custom_protocol Пример реализации протокола ModbusRTU]. На странице подключения к [http://wiki.webhmi.com.ua/index.php/%D0%A2%D0%B5%D0%BD%D0%B7%D0%BE%D0%B4200 тензометрическому контроллеру Тензод200] также есть пример пользовательского протокола.
Навигация
Персональные инструменты
русский
Войти
Пространства имён
Служебная страница
Варианты
Просмотры
Ещё
Поиск
Навигация
Заглавная страница
Свежие правки
Случайная статья
Справка
Инструменты
Спецстраницы
Версия для печати