- Saved searches
- Use saved searches to filter your results more quickly
- Johannes4Linux/Simple-ModbusTCP-Server
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Modbus TCP Server Docker¶
- Docker¶
- Docker Compose¶
- Configuration¶
- Default configuration¶
- Predefined registers¶
- References¶
- Русские Блоги
- Исходная установка
- Тест и использование
- тест
- использование
- Saved searches
- Use saved searches to filter your results more quickly
- License
- adpuckett87/modbus-client-server
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
An example for a Modbus TCP server written in Python with pyModbusTCP
Johannes4Linux/Simple-ModbusTCP-Server
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This is the file I have used for my video about creating a Modbus TCP server in Python. Here is the link to my video.
The file Simple_ModbusServer.py contains the code for a simple Modbus Server with the following register description:
Holding Register Addr. | Description |
---|---|
0 | Server writes a random value to it every 500 ms |
1 | Server monitors this register for changes. If the value is changed by the client, the server will print out the new value |
To run the script, you need to have pyModbusTCP installed on your machine. To install it, you can use:
sudo pip install pyModbusTCP
About
An example for a Modbus TCP server written in Python with pyModbusTCP
Modbus TCP Server Docker¶
The Modbus TCP Server is a simple Modbus server for debugging and simulation.
Docker¶
docker run --name modbus-server -p 5020:5020 -d oitc/modbus-server docker run --name modbus-server -p 5020:5020 -d -v $PWD/server_config.json:/server_config.json oitc/modbus-server -f /server_config.json
Docker Compose¶
modbus-server: container_name: modbus-server image: oitc/modbus-server restart: always command: -f /server_config.json ports: - 5020:5020 volumes: - ./server.json:/server_config.json:ro
Configuration¶
An example can be found in the GIT repo: abb_coretec_example.json
Default configuration¶
"server": "listenerAddress": "0.0.0.0", "listenerPort": 5020, "tlsParams": "description": "path to certificate and private key to enable tls", "privateKey": null, "certificate": null >, "logging": "format": "%(asctime)-15s %(threadName)-15s %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s", "logLevel": "DEBUG" > >, "registers": "description": "initial values for the register types", "zeroMode": false, "initializeUndefinedRegisters": true, "discreteInput": <>, "coils": <>, "holdingRegister": <>, "inputRegister": <> > >
Predefined registers¶
"server": "listenerAddress": "0.0.0.0", "listenerPort": 5020, "tlsParams": "description": "path to certificate and private key to enable tls", "privateKey": null, "certificate": null >, "logging": "format": "%(asctime)-15s %(threadName)-15s %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s", "logLevel": "DEBUG" > >, "registers": "description": "initial values for the register types", "zeroMode": false, "initializeUndefinedRegisters": true, "discreteInput": <>, "coils": <>, "holdingRegister": "123": "0xAABB", "246": "0x0101" >, "inputRegister": <> > >
References¶
Русские Блоги
В рабочем проекте робот должен выполнять функцию управления питанием. Он поставляется с перезаряжаемыми контактами для контакта с заряженной батареей. Конкретные параметры не показаны. Код должен завершать связь с ПЛК Siemens через беспроводную сеть для управления открытием и закрытием зарядной комнаты. И управляя открытием и закрытием реле в точке зарядки, протокол modbus-tcp , Так что найдите полезную библиотеку с открытым исходным кодом онлайн- libmodbus , Запишите простой процесс использования.
Адрес загрузки:
download Выберите долгосрочную стабильную версию v3.0.6
Эта статья состоит из следующих разделов:
Исходная установка
После загрузки почтового файла в /home В каталоге извлеките:
tar -zxvf libmodbus-3.0.6.tar.gz
вводить libmodbus-3.0.6 Содержание:
cd libmodbus-3.0.6
Скомпилируйте и установите:
make && make install
Тест и использование
тест
modbus_t *mb; uint16_t tab_reg[32]; mb = modbus_new_tcp("127.0.0.1", 1502); modbus_connect(mb); /* Read 5 registers from the address 0 */ modbus_read_registers(mb, 0, 5, tab_reg); modbus_close(mb); modbus_free(mb);
Проверьте связь по протоколу modbus-tcp, код использует локальный адрес обратной связи, порт 1502:
Войдите в каталог тестов, откройте терминал и запустите программу сервера:
./unit-test-server tcp
Откройте другой терминал в каталоге и запустите клиентскую программу:
./unit-test-client tcp
Он напечатает много информации при запуске.
использование
И вам также нужно упростить пример кода и изменить IP-адрес и порт при необходимости:
в libmodbus-3.0.6 Создайте новый каталог mytest в каталоге.
mkdir mytest
Скопируйте необходимые заголовочные файлы в каталог src В:
cp modbus.h modbus-rtu.h modbus-tcp.h ../mytest
Войдите в каталог:
cd myteast
Создайте свой собственный код main.c Следующим образом:
#include #include #include #include #include #include #include const uint16_t UT_INPUT_REGISTERS_ADDRESS = 0x1; const uint16_t UT_BITS_ADDRESS = 0x04; const uint16_t UT_INPUT_REGISTERS_NB = 0xA; const uint16_t UT_INPUT_REGISTERS_TAB[] = 0x000A >; int main(int argc, char const *argv[]) int nb = 0x25; int rc = 0; modbus_t *ctx; uint8_t *tab_rp_bits; tab_rp_bits = (uint8_t *) malloc(nb * sizeof(uint8_t)); memset(tab_rp_bits, 0, nb * sizeof(uint8_t)); ctx = modbus_new_tcp("192.168.1.120", 502); if(ctx == NULL) fprintf(stderr, "Unable to allocate libmodbus context\n"); return -1; > if(modbus_connect(ctx) == -1) fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno)); modbus_free(ctx); return -1; > while(1) rc = modbus_write_bit(ctx, UT_BITS_ADDRESS, 1); if (rc != 1) printf("FAILED (nb points %d)\n", rc); > rc = modbus_read_bits(ctx, UT_BITS_ADDRESS, 1, tab_rp_bits); printf("modbus_read_bits 1 \n modbus_read_bits: \n"); if (rc != 1) printf("FAILED (nb points %d)\n", rc); > printf("tab_rp_bits [0] is %d\n",tab_rp_bits[0]); memset(tab_rp_bits, 0, nb * sizeof(uint8_t)); sleep(1); rc = modbus_write_bit(ctx, UT_BITS_ADDRESS, 0); if (rc != 1) printf("FAILED (nb points %d)\n", rc); > rc = modbus_read_bits(ctx, UT_BITS_ADDRESS, 1, tab_rp_bits); printf("modbus_read_bits 0 \n modbus_read_bits: \n"); if (rc != 1) printf("FAILED (nb points %d)\n", rc); > printf("tab_rp_bits [0] is %d\n",tab_rp_bits[0]); sleep(1); > modbus_close(ctx); modbus_free(ctx); return 0; >
ip 192.168.1.120
порт 502
Функция вышеприведенного кода: управление адресом чтения и записи, который должен быть 0x04 бит coil status Состояние заставляет его постоянно изменяться, и производительность на ПЛК мигает индикатором.
Обобщение:
cc -o main main.c -lmodbus -I ./
Если ссылка не работает, но в ошибке отсутствует файл so, найдите соответствующий файл so и скопируйте его в /usr/local/lib Каталог и запустить ldonfig 。
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
adpuckett87/modbus-client-server
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
- modbus-client is a standalone command line Modbus TCP client
- modbus-server is a Modbus TCP server that uses mysql to store register values
modbus-client ip_address slave_id r reg_type address [num_reg format]
modbus-client ip_address slave_id w reg_type address value [format]
- a — floating point abcd
- b — floating point badc
- c — floating point cdab
- d — floating point dcba
- (s)1 — 16-bit register. Optionally signed. Default.
- (s)3 — 32-bit register. Optionally signed.
- (s)6 — 64-bit register. Optionally signed.
- (s)k — 32-bit Mod10k. Optionally signed.
- (s)l — 48-bit Mod10k. Optionally signed.
- (s)m — 64-bit Mod10k. Optionally signed.
From libmodbus documentation:
chmod +x ./autogen.sh ./autogen.sh ./configure make install
May need to do this depending on distribution
cp src/.libs/libmodbus.so* /usr/lib/ ln -s -f /usr/lib/libmodbus.so.5.1.0 /usr/lib/libmodbus.so.5 ln -s -f /usr/lib/libmodbus.so.5.1.0 /usr/lib/libmodbus.so
gcc modbus-client.c -o modbus-client `pkg-config --libs --cflags libmodbus`
gcc inih/ini.c modbus-server.c -o modbus-server -std=gnu99 `mysql_config --cflags --libs` `pkg-config --libs --cflags libmodbus` cp modbus-server /usr/bin/
Make sure mysql is installed with libmysqlclient-dev
Choose a database and create the following table
CREATE TABLE IF NOT EXISTS `modbusServer` ( `id` int(11) NOT NULL AUTO_INCREMENT, `regType` int(11) NOT NULL, `address` int(11) NOT NULL, `val` int(11) NOT NULL DEFAULT '0', `modifiedCount` int(11) NOT NULL DEFAULT '0', `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY (`regType`), KEY (`address`), UNIQUE KEY (`regType`, `address`) ) ENGINE=InnoDB;
Copy ini to /etc and fill in mysql information. Mysql user should have read/write access
Optionally install modbus-server as a service
Install runit and execute the following commands
mkdir -p /etc/sv/modbus-server/log mkdir /var/log/modbus-server cat > /etc/sv/modbus-server/run &1 EOM cat > /etc/sv/modbus-server/log/run