Italian Modbus TCP

Walter95

Member
Licensed User
Ciao a tutti,
Visto le difficoltà a trovare una libreria "già fatta" per quanto riguarda la comunicazione Modbus TCP.
Ho deciso di creare una mia libreria, adattata per le mie esigenze, che magari può essere utile a qualcuno, che magari possa migliorare in questo forum.
Allego la libreria, il progetto della libreria e un progetto di test.

Le funzioni disponibili:
  • FC01 - Lettura Coil
  • FC03 - Lettura Holding
  • FC05 - Scrittura Coil singola
  • FC06 - Scrittura Holding singola
  • FC16 - Scrittura Holding multipla

Come funziona:

Da codice si crea Query per indicare la funzione che si vuole eseguire ciclicamente.
Prima di registrarla in una lista analizza il parametro "Count" (questo perchè ho notato appunto che posso arrivare a chiedere dati fino a una quantità massima di 125)
Adatta la Query ed eventualmente crea tutte quelle necessarie per soddisfare la richiesta iniziale.

Esiste la lista di "Query", in maniera ciclica e avanza solo se il server risponde a quella Query
(La mia idea è stata: "Inutile continuare a fare richieste di lettura, se non riesce a rispondermi")
Ripete il processo

Il tutto in background.

ModbusTCP
Author:
Walter Maniero
Version: 2.20


  • Funzioni/Routine:
    • Initialize(Caller As Object,EventName As String, unitId As Byte)
    • CreateConnection(IPaddress As String, Port As Int, Timeout As Int, ReadTime As Int) As ConnectionParams
      Ritorna appunto un Type ConnectionParams che semplicemente raggruppa le informazioni descritta sopra
    • CreateQuery(Function As Short, StartAddress As Short, Count As Short) As ModbusQuery
      Crea e ritorna la query da aggiungere successivamente in lista
    • AddToQuery(Value As ModbusQuery)
    • AddToQuery2(Value() As ModbusQuery)
    • RemoveFromQuery(Key As Short)
      Ogni query all'interno ha un campo chiamato "Id" e questo campo lo uso per dare un nome alla query
    • ResetQueryList()
      Cancella la lista
    • CreateNewQueryList()
      Se in Runtime cambi la lista, per rendere effettive le modifiche devi chiamare questa sub
    • StartCOM(COM As ConnectionParams)
    • StopCOM()
    • SetCoil(Address As Short, Value As Boolean)
    • SetHold(Address As Short, Value As Short)
    • SetMultipleHold(Address As Short, Value() As Short)
    • GetCoil() As Boolean()
      Coil(65536) As Boolean
    • GetHolds() As Short()
      Holds(65536) As Short
  • Type:
    • ModbusQuery
    • ConnectionParams
  • Eventi:
    • ServiceState(State As Boolean)

Esempio::
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
    Private ModbusClient As ModbusTCP
    Private COMParameters As ConnectionParams
    Private ModbusState As Boolean = False
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    ModbusClient.Initialize(Me,"ModbusClient",1)
    COMParameters.Initialize
    COMParameters = ModbusClient.CreateConnection("192.168.178.42",502,3600,200)
    SetQuery
End Sub

Sub SetQuery()
    Dim Myquery1 As ModbusQuery = ModbusClient.CreateQuery(1,0,100)
    Dim Myquery2 As ModbusQuery = ModbusClient.CreateQuery(3,0,100)
    ModbusClient.AddToQuery(Myquery1)
    ModbusClient.AddToQuery(Myquery2)
End Sub

Sub ModbusClient_ServiceState(State As Boolean)
    ModbusState = State
End Sub

Sub Activity_Resume
    If ModbusState = False Then
        ModbusClient.StartCOM(COMParameters)
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then
        ModbusClient.StopCOM
    End If
End Sub

Sub Button1_Click
    Dim MyCoils() As Boolean = ModbusClient.GetCoil()
    Dim MyHolds() As Short = ModbusClient.GetHolds()
    ModbusClient.SetCoil(0,Not(MyCoils(0)))
    Dim Value(10) As Short
    For i = 0 To Value.Length - 1
        Value(i) = MyHolds(i) + 1
    Next
    ModbusClient.SetMultipleHold(1,Value)
End Sub
 

Attachments

  • ModbusTCP.zip
    158.1 KB · Views: 79
  • ModbusTCP-SourceCode.zip
    16.7 KB · Views: 82
  • ModbusTCP-Example.zip
    10.2 KB · Views: 89

Star-Dust

Expert
Licensed User
Longtime User
Ne so poco di Modbus se non quello che si legge su Wikipedia.
Complimenti per la libreria, hai esordito alla grande, mettila nel forum internazionale.
 

Walter95

Member
Licensed User
Urca, very interessante questa
A che hardware ti vai a collegare?
La uso normalmente su PLC Siemens S7-1200 / S7-1500 oppure ET200SP.
L'ho usata con Codesys tramite PLC IFM e adesso che ho un Pixsys, la provo anche lì.
Durante i test ho usato anche il Server Simulator di EasyModbus (Che secondo me ha le librerie ben fatte per .NET)
 

amorosik

Expert
Licensed User
La uso normalmente su PLC Siemens S7-1200 / S7-1500 oppure ET200SP.
L'ho usata con Codesys tramite PLC IFM e adesso che ho un Pixsys, la provo anche lì.
Durante i test ho usato anche il Server Simulator di EasyModbus (Che secondo me ha le librerie ben fatte per .NET)

"Server Simulator di EasyModbus" e questo, per fare esperimenti, si trova aggratisse?
Durante il debug potrebbe essere molto utile "vedere" i pacchetti grezzi che passano in rete, puoi consigliarci qualcosa per fare questo?
 

Walter95

Member
Licensed User
"Server Simulator di EasyModbus" e questo, per fare esperimenti, si trova aggratisse?
Durante il debug potrebbe essere molto utile "vedere" i pacchetti grezzi che passano in rete, puoi consigliarci qualcosa per fare questo?
Si trova gratis,
Si esegue su windows ed simula un server modbus TCP e permette di vedere il protocollo che riceve e la sua risposta in merito ed è molto basico.
Per "vedere" i dati grezzi, intendi i byte che escono o entrano dall'app o uno sniffing di rete?
Per lo sniffing, uso solitamente wireshark
 

amorosik

Expert
Licensed User
Si trova gratis,
Si esegue su windows ed simula un server modbus TCP e permette di vedere il protocollo che riceve e la sua risposta in merito ed è molto basico.
Per "vedere" i dati grezzi, intendi i byte che escono o entrano dall'app o uno sniffing di rete?
Per lo sniffing, uso solitamente wireshark

Si, intendevo se c'e' qualcosa di "pronto all'uso" per il modbus
Wireshark fa tutto ma non e' banale da utilizzare
 

Walter95

Member
Licensed User
Che io sappia no...
So che esiste una libreria per .Net framework chiamata SharpPCap per poi partire da lì a sviluppare il tuo EXE apposta.
Ma nel caso come il ModbusTCP faccio prima ad usare Wireshark e filtrare chiedendo di mostrare solo il modbus, così vedo solo quelle richieste in lista in tempo reale.
 
Top