using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using Modbus.Device; //for modbus master using System.Net; //for tcp client using System.Net.Sockets; using System.Threading; namespace ReConnect { class Program { [DllImport("WININET", CharSet = CharSet.Auto)] static extern bool InternetGetConnectedState(ref InternetConnectionState lpdwFlags, int dwReserved); enum InternetConnectionState : int { INTERNET_CONNECTION_MODEM = 0x1, INTERNET_CONNECTION_LAN = 0x2, INTERNET_CONNECTION_PROXY = 0x4, INTERNET_RAS_INSTALLED = 0x10, INTERNET_CONNECTION_OFFLINE = 0x20, INTERNET_CONNECTION_CONFIGURED = 0x40 } private static TcpClient tcpClient; private static ModbusIpMaster master; static void Main(string[] args) { // connect to Modbus TCP Server bool NetworkIsOk = Connect(); // read the input register 0~9 (30001~30010) of the device slave ID 1. //document->Modbus.Device.Namespace->ModbusMaster Class->ReadInputRegisters Method byte slaveID = 1; ushort startAddress = 0; ushort numOfPoints = 10; while (true) { try { if (NetworkIsOk) { ushort[] register = master.ReadInputRegisters(slaveID, startAddress, numOfPoints); for (int index = 0; index < register.Length; index++) Console.WriteLine(string.Format("register[{0}] = {1}", index, register[index])); } else { NetworkIsOk = Connect(); Console.WriteLine("Network:" + NetworkIsOk.ToString()); } } catch (Exception ex) { Console.WriteLine(ex.Message); Thread.Sleep(10000); NetworkIsOk = false; } Thread.Sleep(1000); } } private static bool Connect() { string ipAddress = "192.168.1.100"; int tcpPort = 502; if (master != null) master.Dispose(); if (tcpClient != null) tcpClient.Close(); if (CheckInternet()) { try { tcpClient = new TcpClient(ipAddress, tcpPort); // create Modbus TCP Master by the tcp client //document->Modbus.Device.Namespace->ModbusIpMaster Class->Create Method master = ModbusIpMaster.CreateIp(tcpClient); return true; } catch (Exception ex) { Console.WriteLine(ex.StackTrace + "==>" + ex.Message); return false; } } return false; } private static bool CheckInternet() { //http://msdn.microsoft.com/en-us/library/windows/desktop/aa384702(v=vs.85).aspx InternetConnectionState flag = InternetConnectionState.INTERNET_CONNECTION_LAN; return InternetGetConnectedState(ref flag, 0); } } }