Popular Post kurtykurtyboy Posted June 21, 2023 Popular Post Share Posted June 21, 2023 Here is something that I have been wanting in AutoIt for years but sadly no one had created it yet. Well, I decided to hunker down and do something about it! I present to you, MbTCP - a Modbus TCP/IP UDF. What is Modbus? Modbus is a communications protocol commonly used to communicate with various types of PLC's, sensors, SCADA systems, and many other industrial applications. Modbus TCP is the ethernet variant (as opposed to Modbus RTU which uses a serial connection). This UDF takes care of all the behind-the-scenes legwork and makes it easy to get right to the data. No need to worry about which function codes to use or how to format the data. Modbus typically works on discrete coils and inputs (think BOOL) or 16-bit registers (think INT). However, some devices support 32-bit signed and unsigned integers and 32-bit floating point numbers. This is possible by reading or writing 2 consecutive 16-bit registers and formatting them on both ends. The UDF will take care of all that as well (although maybe not in the most sophisticated ways...😏 ). Because there is no standard for working with 32-bit numbers, it is necessary to have the option to enable or disable big-endianness. Similarly, not all devices start counting at register 1. Some of them actually start at register 0. The UDF allows you to define these parameters when creating the connection to the device. Available data types for input and holding registers are INT16, UINT16, INT32, UINT32, and FLOAT32. Function List: ; _MbTcp_Connect ......................: Open a connection to a remote device ; _MbTcp_ReadCoils ....................: Read 1 or more output coils (function code 1) ; _MbTcp_ReadDiscreteInputs ...........: Read 1 or more discrete inputs (function code 2) ; _MbTcp_ReadHoldingRegisters .........: Read 1 or more holding registers (function code 3) ; _MbTcp_ReadInputRegisters ...........: Read 1 or more input registers (function code 4) ; _MbTcp_WriteCoils ...................: Write 1 or more output coils (function code 5 and 15) ; _MbTcp_WriteRegisters ...............: Write 1 or more holding registers (function code 6 and 16) ; _MbTcp_Disconnect ...................: Close the connection to a device ; _MbTcp_DisconnectAll ................: Close the connection to all connected devices To get started, follow these easy steps: Create a new connection to the device using _MbTcp_Connect Call any of the available read or write functions That's it. The program will automatically clean up any connections that are left open on exit. You may also manually disconnect from any device if needed. The most basic example of use. Connect to a device and read one holding register starting at register 2. #include "MbTcp.au3" ;connect to device at IP 127.0.0.1 Local $iConnection1 = _MbTcp_Connect("127.0.0.1") If @error Then MsgBox(16, "Error", "Failed to connect to the Modbus device at 127.0.0.1." & @CRLF & "Error Code: " & @error) Exit Else ConsoleWrite("Successfully connected to device at 127.0.0.1" & @CRLF) EndIf ;read 1 holding register Local $iReadData = _MbTcp_ReadHoldingRegisters($iConnection1, 2, 1) If @error Then MsgBox(16, "Error", "Failed to read the Modbus value." & @CRLF & "Error Code: " & @error) Else ConsoleWrite("Value: " & $iReadData & @CRLF) EndIf The next example shows how we can format the data to return an unsigned integer instead of the default signed integer. Spoiler #include "MbTcp.au3" ;connect to device at IP 127.0.0.1 Local $iConnection1 = _MbTcp_Connect("127.0.0.1") If @error Then MsgBox(16, "Error", "Failed to connect to the Modbus device at 127.0.0.1." & @CRLF & "Error Code: " & @error) Exit Else ConsoleWrite("Successfully connected to device at 127.0.0.1" & @CRLF) EndIf ;read 1 holding register Local $iReadData = _MbTcp_ReadHoldingRegisters($iConnection1, 2, 1, "UINT16") If @error Then MsgBox(16, "Error", "Failed to read the Modbus value." & @CRLF & "Error Code: " & @error) Else ConsoleWrite("Value: " & $iReadData & @CRLF) EndIf In the following example, we connect to a device that uses big-endian word order and starts at register 0 instead of 1. Then we read and write a group of registers. Spoiler First we create the connection. Then we read 5 holding registers. Then we write to the first 2 holding registers. Then we read the 5 registers again and marvel at the changed values. expandcollapse popup#include "MbTcp.au3" ;connect to device at IP 127.0.0.1 Local $iFirstRef = 0 ; First address is 0 instead of 1 Local $iBigEndian = True ; Slave operates on big-endian 32-bit numbers Local $iConnection1 = _MbTcp_Connect("127.0.0.1", $iFirstRef, $iBigEndian) If @error Then MsgBox(16, "Error", "Failed to connect to the Modbus device at 127.0.0.1." & @CRLF & "Error Code: " & @error) Exit Else ConsoleWrite("Successfully connected to device at 127.0.0.1" & @CRLF) EndIf ;read 5 holding registers Local $register = 0 Local $count = 5 Local $aReadData = _MbTcp_ReadHoldingRegisters($iConnection1, $register, $count) If @error Then MsgBox(16, "Error", "Failed to read the Modbus value." & @CRLF & "Error Code: " & @error) Else ConsoleWrite("Read Data Before:" & @CRLF) For $value In $aReadData ConsoleWrite("Value: " & $value & @CRLF) Next EndIf ConsoleWrite(@CRLF) ;write 2 holding registers ConsoleWrite("Writing Data..." & @CRLF) $register = 0 $count = 2 Local $aWriteData[10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Local $iReturn = _MbTcp_WriteHoldingRegisters($iConnection1, $register, $count, $aWriteData) If @error Then MsgBox(16, "Error", "Failed to write the Modbus value." & @CRLF & "Error Code: " & @error) EndIf ConsoleWrite(@CRLF) ;read 5 holding registers again Local $register = 0 Local $count = 5 Local $aReadData = _MbTcp_ReadHoldingRegisters($iConnection1, $register, $count) If @error Then MsgBox(16, "Error", "Failed to read the Modbus value." & @CRLF & "Error Code: " & @error) Else ConsoleWrite("Read Data After:" & @CRLF) For $value In $aReadData ConsoleWrite("Value: " & $value & @CRLF) Next EndIf ConsoleWrite(@CRLF) ;disconnect from the device (optional) - this will be cleaned up automatically if not performed here _MbTcp_Disconnect($iConnection1) I may add more examples here if needed. There are a number of Modbus simulators out there if you want to test locally on your computer. But I really like a tool named Mod_RSsim link. Let me know if you find any issues. I know I will probably end up needing to add a timeout option. MbTcp_20230620.zip Gianni, argumentum, marcoauto and 2 others 4 1 Link to comment Share on other sites More sharing options...
funkey Posted June 21, 2023 Share Posted June 21, 2023 I have at least one Modbus TCP UDF for over 10 years... 😝😅 Programming today is a race between software engineers striving tobuild bigger and better idiot-proof programs, and the Universetrying to produce bigger and better idiots.So far, the Universe is winning. Link to comment Share on other sites More sharing options...
kurtykurtyboy Posted June 23, 2023 Author Share Posted June 23, 2023 @funkey don't tell me you've been holding out on us for over 10 years! Think of all the people who could benefit from it... At least 5 people - maybe 6! 😁 Link to comment Share on other sites More sharing options...
funkey Posted June 23, 2023 Share Posted June 23, 2023 Sorry.... I have once made two different version of native implementation of Modbus TCP and I also used two different libraries for this task. This is long time ago. Here are two links that originated from my work: modbus - Projekte - AutoIt.de - Das deutschsprachige Forum. ModBus & libmodbus.dll - Funktion "0x10" (modbus_write_registers) integrieren - Hilfe & Unterstützung - AutoIt.de - Das deutschsprachige Forum. BR funkey Programming today is a race between software engineers striving tobuild bigger and better idiot-proof programs, and the Universetrying to produce bigger and better idiots.So far, the Universe is winning. Link to comment Share on other sites More sharing options...
mLipok Posted June 23, 2023 Share Posted June 23, 2023 Interestning: Some articles about: https://www.shemeck.pl/artykuly/71_protokol-modbus-tcp-ip-co-to-jest.html https://ntronic.pl/modbus-tcp/ Signature beginning:* Please remember: "AutoIt"..... * Wondering who uses AutoIt and what it can be used for ? * Forum Rules ** ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Code * for other useful stuff click the following button: Spoiler Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API * ErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 * My contribution to others projects or UDF based on others projects: * _sql.au3 UDF * POP3.au3 UDF * RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF * SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane * Useful links: * Forum Rules * Forum etiquette * Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * Wiki: * Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX IE Related: * How to use IE.au3 UDF with AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler * IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related: * How to get reference to PDF object embeded in IE * IE on Windows 11 * I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions * EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *I also encourage you to check awesome @trancexx code: * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuff * OnHungApp handler * Avoid "AutoIt Error" message box in unknown errors * HTML editor * winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/ "Homo sum; humani nil a me alienum puto" - Publius Terentius Afer"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming" , be and \\//_. Anticipating Errors : "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty." Signature last update: 2023-04-24 Link to comment Share on other sites More sharing options...
kurtykurtyboy Posted June 23, 2023 Author Share Posted June 23, 2023 Nice! I wish I would have seen that sooner. I guess Google doesn't show me the non-english results. Maybe I should start expanding my horizons.. 🤔 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now