/// <summary> /// Чтение по 4 функции ReadInput /// </summary> /// <param name="master"></param> /// <param name="reg"></param> /// <returns></returns> public string ReadInputRegisters(ModbusIpMaster master, ushort reg) { return(Convert.ToString(master.ReadInputRegisters(1, reg, 1)[0])); }
private void button1_Click(object sender, EventArgs e) { try { ThreadPool.QueueUserWorkItem((o) => { while (runFlag) { try { var sourceClient = new TcpClient(); sourceClient.Connect(IPAddress.Parse(sourceParams[0]), int.Parse(sourceParams[1])); var sourceMaster = ModbusIpMaster.CreateIp(sourceClient ); var targetClient = new TcpClient(); targetClient.Connect(IPAddress.Parse(targetParams[0]), int.Parse(targetParams[1])); var targetMaster = ModbusIpMaster.CreateIp(targetClient); while (runFlag) { var totalLength = ushort.Parse(sourceParams[3]); ushort startLengthFloat = 0; do { ushort byteCntToSend = totalLength; if (totalLength > MAX_PACKAGE_LENGTH) { byteCntToSend = MAX_PACKAGE_LENGTH; } var readResult = sourceMaster.ReadHoldingRegisters( (ushort)(ushort.Parse(sourceParams[2]) + startLengthFloat), byteCntToSend); targetMaster.WriteMultipleRegisters( (ushort)(ushort.Parse(targetParams[2]) + startLengthFloat), readResult); readByteCnt += readResult.Length; startLengthFloat += (ushort)readResult.Length; totalLength -= (ushort)readResult.Length; try { Invoke(new Action <long>(l => { try { if (l == long.MaxValue) { l = 0; } label1.Text = l.ToString(); lblInfo.Text = string.Empty; } catch { } }), readByteCnt); } catch { } } while (totalLength > 0); Thread.Sleep(100); } } catch (Exception ex) { lblInfo.Text = ex.Message; } Thread.Sleep(30000); } }); button1.Enabled = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void NotWorking() { var ip = "192.168.100.13"; var port = 8081; var client = new TcpClient(); var modbusIpMaster = ModbusIpMaster.CreateIp(client); if (!client.ConnectAsync(ip, port).Wait(1000)) { throw new Exception("Connection error"); } Console.WriteLine("Connected"); client.ReceiveTimeout = WriteReadTimeout; client.SendTimeout = WriteReadTimeout; //modbusIpMaster.Transport.RetryOnOldResponseThreshold = 10; new Task(() => { //modbusIpMaster.WriteSingleRegister(40069, 0); while (true) { try { var index = /*Demand - 40083*/ /*battery state - 40311*/ /* privod z panelov - 40100 */ 40274; var numberOfPoints = 1; //client.GetStream().Write(new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x9C, 0x84, 0x00, 0x01 }, 0, 12); //var buffer2 = new byte[256]; //client.Client.Receive(buffer2); //client.GetStream().Read(buffer2, 0, 255); //Thread.Sleep(5000); //try //{ var buffer = modbusIpMaster.ReadHoldingRegisters((ushort)index, (byte)numberOfPoints); //var buffer2 = modbusIpMaster.ReadHoldingRegisters((ushort)40083, (byte)numberOfPoints); // var task = modbusIpMaster.ReadHoldingRegistersAsync((ushort)index, (byte)numberOfPoints); // task.Wait(); //} //catch (Exception e) //{ // Console.WriteLine(e); // Console.WriteLine(); // Console.WriteLine(); //} //client.GetStream().Write(new byte[] { 0x04, 0x00, 0x00, 0x00, 0x00, 0x10, 0x01, 0x03, (byte)156, (byte)185, 0x00, 0x01 }, 0, 12); //var buffer2 = new byte[256]; //client.Client.Receive(buffer2); //client.GetStream().Read(buffer2, 0, 255); var intBuffer = buffer.Select(b => (short)b); Console.WriteLine(string.Join(",", intBuffer)); //Console.WriteLine(buffer2[0] - buffer[0]); Console.WriteLine(); } catch (IOException ioException) { Console.WriteLine(ioException); Console.WriteLine(); Console.WriteLine(); if (ioException.Message.Contains("transaction ID")) { Console.WriteLine("-----------Reconnecting-----------"); client.Close(); client = new TcpClient(); modbusIpMaster = ModbusIpMaster.CreateIp(client); if (!client.ConnectAsync(ip, port).Wait(1000)) { throw new Exception("Connection error"); } } } catch (Exception e) { Console.WriteLine(e); Console.WriteLine(); Console.WriteLine(); } Thread.Sleep(100); } }).Start(); while (true) { } ; }
protected override void Start() { if (master != null) { master.Dispose(); } if (tcpClient != null) { tcpClient.Close(); tcpClient.Dispose(); tcpClient = null; } if (tcpClient == null) { tcpClient = new TcpClient(new IPEndPoint(IPAddress.Parse(Tcp_PARA.LocalTCP_IP), int.Parse(Tcp_PARA.LocalTCP_Port))); } tcpClient.ReceiveTimeout = 1000; tcpClient.SendTimeout = 1000; tcpClient.SendBufferSize = Tcp_PARA.WriteBufferSize; tcpClient.ReceiveBufferSize = Tcp_PARA.ReadBufferSize; master = ModbusIpMaster.CreateIp(tcpClient); //通用部分设置 master.Transport.ReadTimeout = Tcp_PARA.ReadTimeout; //读取数据超时1000ms master.Transport.WriteTimeout = Tcp_PARA.WriteTimeout; //写入数据超时1000ms master.Transport.Retries = Tcp_PARA.CollectFaultsNumber; //重试次数 master.Transport.WaitToRetryMilliseconds = Tcp_PARA.CollectFaultsInternal; //重试间隔 Thread.Sleep(800); //此处采用多线程技术创建一个实时读取数据的任务 for (int i = 0; i < this.RealDevices.Count; i++) { RealData mRealData = this.RealDevices[i]; //创建一个子任务 Task.Run(() => { while (true && this.ServerIsRun) { if (this.ServerIsSuspend) { continue; } try { Task.Run(() => { //发送获取数据的命令 string error = ""; if (!this.RequestData(mRealData.Device, mRealData, out error, mRealData.Fragment)) { this.DeviceException("ERROR=Modbus_Serial_10001," + error); } }); } catch (Exception e) { this.DeviceException("ERROR=Modbus_Serial_10002," + e.Message); } //更新周期 Thread.Sleep(mRealData.Device.IO_DEVICE_UPDATECYCLE * 1000); } }); } this.CommunctionStartChanged(this.IOServer, this.IOServer.SERVER_IP + " " + this.IOServer.SERVER_NAME + "启动服务"); }
public void Initialize() { try { if (tcpClientComPortConfigInfo != null) { TcpClient client = null; if (string.IsNullOrEmpty(tcpClientComPortConfigInfo.LocalIPAddress)) { client = new TcpClient() { ReceiveTimeout = tcpClientComPortConfigInfo.ReceiveTimeout, SendTimeout = tcpClientComPortConfigInfo.SendTimeout }; } else { client = new TcpClient(new IPEndPoint(IPAddress.Parse(tcpClientComPortConfigInfo.LocalIPAddress), tcpClientComPortConfigInfo.LocalPort)) { ReceiveTimeout = tcpClientComPortConfigInfo.ReceiveTimeout, SendTimeout = tcpClientComPortConfigInfo.SendTimeout }; } client.Connect(tcpClientComPortConfigInfo.RemoteIPAddress, tcpClientComPortConfigInfo.RemotePort); master = ModbusIpMaster.CreateIp(client); connectionStateChangedEventManager.StartMonitor(ConnectionStateChanged, this, client); } if (serialPortComPortConfigInfo != null) { SerialPort port = new SerialPort() { PortName = serialPortComPortConfigInfo.PortName, BaudRate = serialPortComPortConfigInfo.BaudRate, DataBits = serialPortComPortConfigInfo.DataBits, Parity = serialPortComPortConfigInfo.Parity, StopBits = serialPortComPortConfigInfo.StopBits, WriteTimeout = serialPortComPortConfigInfo.SendTimeout, ReadTimeout = serialPortComPortConfigInfo.ReceiveTimeout }; port.Open(); if (plcModbusTransportMode == ModbusTransportMode.Rtu) { master = ModbusSerialMaster.CreateRtu(port); } if (plcModbusTransportMode == ModbusTransportMode.Ascii) { master = ModbusSerialMaster.CreateAscii(port); } connectionStateChangedEventManager.StartMonitor(ConnectionStateChanged, this, port); } } catch (Exception e) { throw new ApplicationException("建立与PLC连接失败,请确认", e); } }
public unsafe void UpdateFHPP() { //Mapping of all FHPP Data to signals. See Manual for more information (https://www.festo.com/net/en-ca_ca/SupportPortal/Downloads/385511/403818/555696g1.pdf) //FHPP IN ModbusIpMaster master = ModbusIpMaster.CreateIp(client); ushort[] FHPP_IN = master.ReadHoldingRegisters(0, 4); DriveEnabled = GetBit(FHPP_IN[0], 8); Ready = GetBit(FHPP_IN[0], 9);; Warning = GetBit(FHPP_IN[0], 10);; Fault = GetBit(FHPP_IN[0], 11);; SupplyVoltagePresent = GetBit(FHPP_IN[0], 12); ControlFCT_HMI = GetBit(FHPP_IN[0], 13); OperationModeB1 = GetBit(FHPP_IN[0], 14); OperationModeB2 = GetBit(FHPP_IN[0], 15); HaltActive = GetBit(FHPP_IN[0], 0); AckStart = GetBit(FHPP_IN[0], 1); MotionComplete = GetBit(FHPP_IN[0], 2); DriveIsMoving = GetBit(FHPP_IN[0], 4); DragError = GetBit(FHPP_IN[0], 5); StandstillControl = GetBit(FHPP_IN[0], 6); DriveIsReferenced = GetBit(FHPP_IN[0], 7); ControlModeB1 = GetBit(FHPP_IN[1], 9); ControlModeB2 = GetBit(FHPP_IN[1], 10); if (!OperationModeB1 && !OperationModeB2) { StateOPM = 0; } else if (OperationModeB1 && !OperationModeB2 && !ControlModeB1 && !ControlModeB2) { StateOPM = 1; } else if (OperationModeB1 && !OperationModeB2 && !ControlModeB1 && ControlModeB2) { StateOPM = 5; } else if (OperationModeB1 && !OperationModeB2 && ControlModeB1 && !ControlModeB2) { StateOPM = 9; } byte[] ActualPositionHigh = BitConverter.GetBytes(FHPP_IN[2]); byte[] ActualPositionLow = BitConverter.GetBytes(FHPP_IN[3]); byte[] ActualPositionInt32 = new byte[4]; ActualPositionInt32[1] = ActualPositionLow[1]; ActualPositionInt32[0] = ActualPositionLow[0]; ActualPositionInt32[3] = ActualPositionHigh[1]; ActualPositionInt32[2] = ActualPositionHigh[0]; ActualPosition = BitConverter.ToInt32(ActualPositionInt32, 0); byte[] ActualByte = BitConverter.GetBytes(FHPP_IN[1]); if (StateOPM == 0) { ActualRecordNumber = ActualByte[1]; RC1 = GetBit(FHPP_IN[1], 8); RCC = GetBit(FHPP_IN[1], 9); FNUM1 = GetBit(FHPP_IN[1], 11); FNUM2 = GetBit(FHPP_IN[1], 12); FUNC = GetBit(FHPP_IN[1], 15); } else if (StateOPM == 5) { ActualForce = ActualByte[0]; } else if (StateOPM == 1) { ActualVelocity = ActualByte[0]; } //FHPP OUT byte[] FHPP_3_Array = new byte[2]; FHPP_OUT[1] = SetValueVelocity; if (OPM == 0) { FHPP_OUT[0] = SetBit(FHPP_OUT[0], 15, false); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 16, false); FHPP_3_Array[1] = RecordNumber; FHPP_OUT[1] = BitConverter.ToUInt16(FHPP_3_Array, 0); } else if (OPM == 1) { FHPP_OUT[0] = SetBit(FHPP_OUT[0], 15, true); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 16, false); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 10, false); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 11, false); FHPP_3_Array[0] = SetValueVelocity; FHPP_3_Array[1] = 0; FHPP_OUT[1] = SetValueVelocity; byte[] SetPositionBytes = BitConverter.GetBytes(SetValuePosition); FHPP_OUT[3] = BitConverter.ToUInt16(SetPositionBytes, 0); FHPP_OUT[2] = BitConverter.ToUInt16(SetPositionBytes, 2); } else if (OPM == 5) { FHPP_OUT[0] = SetBit(FHPP_OUT[0], 15, true); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 16, false); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 10, true); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 11, false); FHPP_OUT[3] = SetValueForce; FHPP_OUT[2] = 0; } else if (OPM == 6) { FHPP_OUT[0] = SetBit(FHPP_OUT[0], 15, true); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 16, false); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 10, false); FHPP_OUT[1] = SetBit(FHPP_OUT[1], 11, true); } FHPP_OUT[0] = SetBit(FHPP_OUT[0], 9, EnableDrive); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 10, Stop); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 11, Brake); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 12, ResetFault); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 14, HMIAccessLocked); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 1, Halt); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 2, StartTask); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 3, StartHoming); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 4, JogPos); FHPP_OUT[0] = SetBit(FHPP_OUT[0], 5, JogNeg); try { master.WriteMultipleRegisters(0, FHPP_OUT); } catch (Modbus.SlaveException e) { System.Console.WriteLine(e.Message); if (e.SlaveExceptionCode == 1) { throw new Modbus.SlaveException("Exception 1 (Illegal Function): The function code received in the query is not an allowable action for the slave. This may be because the function code is only applicable to newer devices, and was not implemented in the unit selected."); } else if (e.SlaveExceptionCode == 2) { throw new Modbus.SlaveException("Exception 2 (Illegal Data Address): The data address received in the query is not an allowable address for the slave. More specifically, the combination of reference number and transfer length is invalid."); } else if (e.SlaveExceptionCode == 3) { throw new Modbus.SlaveException("Exception 3 (Illegal Data Value): A value contained in the query data field is not an allowable value for server (or slave). This indicates a fault in the structure of remainder of a complex request, such as that the implied length is incorrect"); } else if (e.SlaveExceptionCode == 4) { throw new Modbus.SlaveException("Exception 4 (Slave Device Failure): An unrecoverable error occurred while the slave was attempting to perform the requested action."); } } }
// job flash public bool lambaJobIlgiliIsikFlashYak(AutoResetEvent _AREvt, ushort DeviceID, ushort jobState1StatusAnimationID, ushort jobState1StatusColorID, ModbusIpMaster master) { bool sonuc = false; ushort[] sonucRegisterAdim0 = new ushort[7]; ushort[] sonucRegisterAdim1 = new ushort[5]; _AREvt = new AutoResetEvent(false); //start timer1, timer1.Interval = 1000 ms try { /* ushort[] value = new ushort[4]; * value[0] = DeviceID;//device ID * value[1] = 1;//yazma * value[2] = 8701;//reg. start * value[3] = 3;//adet * master.WriteMultipleRegisters(1, 699, value); * * ushort[] value2 = new ushort[3]; * value2[0] = 1;//Job modu * value2[1] = jobState1StatusAnimationID;//FLASH * value2[2] = jobState1StatusColorID;//green * master.WriteMultipleRegisters(1, 703, value2);*/ ushort[] value = new ushort[6]; value[0] = 1; //yazma value[1] = 8701; //reg. start value[2] = 3; //adet value[3] = 1; value[4] = jobState1StatusAnimationID; //adet value[5] = jobState1StatusColorID; //adet master.WriteMultipleRegisters(1, 700, value); master.WriteSingleRegister(1, 699, DeviceID); _AREvt.WaitOne(300); ushort[] value3 = new ushort[4]; value3[0] = DeviceID; //device ID value3[1] = 1; //yazma value3[2] = 6336; //reg. start value3[3] = 1; //adet master.WriteMultipleRegisters(1, 699, value3); ushort[] value4 = new ushort[1]; value4[0] = 1;//yellow master.WriteMultipleRegisters(1, 703, value4); sonuc = true; } catch { sonuc = false; } return(sonuc); }
private void SaveDocsGas(Gas_XmlDoc parametrs) { DateTime time = DateTime.Now; Gas_MongoNode gas_MongoNode = new Gas_MongoNode(); //проверка на тип подключения, если AddressOfRemoteSlave = 0, подключение tcp, если нет, то через дб if (parametrs.AddressOfRemoteSlave != 0) { ModbusIpMaster master = null; TcpClient tcpClient = null; PAC3200_Power A1 = new PAC3200_Power(); // попытка подключения for (int i = 1; i <= 3; i++) { // программа время от времени не читает несколько значений электричества, если создавать // новый tcpClient при подключении, ошибки становятся минимальными. Я так не понял в чем дело tcpClient = new TcpClient(); try { tcpClient.Connect(parametrs.IP, parametrs.port); if (tcpClient.Connected) { //успех master = ModbusIpMaster.CreateIp(tcpClient); master.Transport.Retries = 0; //don't have to do retries master.Transport.ReadTimeout = 1500; A1.Registers = master.ReadHoldingRegisters((byte)parametrs.AddressOfRemoteSlave, (ushort)parametrs.address, (ushort)parametrs.length); Console.WriteLine("попытка конвертации"); A1.intConvertValue(); // конвертация значений //передача данных в экземпляр класса gas_MongoNode.ID = parametrs.id; gas_MongoNode.name = parametrs.name; gas_MongoNode.value = A1.intValue; gas_MongoNode.dateTime = time; break; } } catch { tcpClient.Close(); tcpClient.Dispose(); //неудача string error = "GasTCP: ID = " + parametrs.id + " " + parametrs.IP + " date - " + DateTime.Now.ToString() + " Ошибка подключения TCP"; Console.WriteLine(error); if (parametrs.id != 999) { // 999 это тестовый IP Log.logNodeElictricityTestID(error); Log.logNodeElictricity(error); } } if (i == 2) { return; // если 3 итерации не помогло } } tcpClient.Close(); tcpClient.Dispose(); } else { S7Client s7Client = new S7Client(); float value = 0; byte[] Buffer = new byte[parametrs.length]; for (int i = 0; i <= 2; i++) { s7Client.ConnectTo(parametrs.IP, parametrs.rack, parametrs.slot); if (s7Client.Connected) { s7Client.DBRead(parametrs.DB, parametrs.address, parametrs.length, Buffer); value = S7.GetRealAt(Buffer, 0); //передача данных в экземпляр класса gas_MongoNode.ID = parametrs.id; gas_MongoNode.name = parametrs.name; gas_MongoNode.value = value; gas_MongoNode.dateTime = time; break; } else { string error = "Gas: ID = " + parametrs.id + " " + parametrs.name + " " + time + " " + "не удалось подключиться к адресу " + parametrs.IP; Console.WriteLine(error); Log.logWaterNode(error); return; } } //Console.WriteLine(parametrs.id + " " + parametrs.name + " " + value.ToString() + " " + time); s7Client.Disconnect(); } int month = DateTime.Now.Month; int year = DateTime.Now.Year; string date = new DateTime(year, month, 1).ToShortDateString(); IMongoCollection <Gas_MongoNode> collection = null; try { MongoClient client = new MongoClient("mongodb://localhost"); IMongoDatabase DB = client.GetDatabase("Gas"); collection = DB.GetCollection <Gas_MongoNode>(date); } catch (Exception e) { string error = "Gas: ID = " + gas_MongoNode.ID + " " + parametrs.name + time + " Не удалось подключиться к базе данных " + e.Message; Console.WriteLine(error); Log.logWaterNode(error); return; } try { collection.InsertOne(gas_MongoNode); //collection.InsertOne(post); } catch (Exception e) { string error = "Gas: ID = " + gas_MongoNode.ID + " " + parametrs.name + "Ошибка записи в MongoDB:" + time + " " + e.Message; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(error); Console.ForegroundColor = ConsoleColor.White; Log.logWaterNode(error); return; } Console.WriteLine("Gas: ID = " + gas_MongoNode.ID + " " + gas_MongoNode.name + " " + gas_MongoNode.value + " " + "Запить произведена: " + time); return; }
/// <summary> /// Attempts to connect to data input source. /// </summary> /// <remarks> /// Derived classes should attempt connection to data input source here. Any exceptions thrown /// by this implementation will result in restart of the connection cycle. /// </remarks> protected override void AttemptConnection() { Dictionary <string, string> parameters = Settings; string frameFormat, transport, setting; if (!parameters.TryGetValue("frameFormat", out frameFormat) || string.IsNullOrWhiteSpace(frameFormat)) { throw new ArgumentException("Connection string is missing \"frameFormat\"."); } if (!parameters.TryGetValue("transport", out transport) || string.IsNullOrWhiteSpace(transport)) { throw new ArgumentException("Connection string is missing \"transport\"."); } if (!parameters.TryGetValue("unitID", out setting) || !byte.TryParse(setting, out m_unitID)) { throw new ArgumentException("Connection string is missing \"unitID\" or value is invalid."); } bool useIP = false; bool useRTU = false; switch (frameFormat.ToUpperInvariant()) { case "RTU": useRTU = true; break; case "TCP": useIP = true; break; } if (useIP) { int port; if (!parameters.TryGetValue("port", out setting) || !int.TryParse(setting, out port)) { throw new ArgumentException("Connection string is missing \"port\" or value is invalid."); } if (transport.ToUpperInvariant() == "TCP") { string hostName; if (!parameters.TryGetValue("hostName", out hostName) || string.IsNullOrWhiteSpace(hostName)) { throw new ArgumentException("Connection string is missing \"hostName\"."); } m_tcpClient = new TcpClient(hostName, port); m_modbusConnection = ModbusIpMaster.CreateIp(m_tcpClient); m_pollingTimer.Enabled = true; return; } string interfaceIP; if (!parameters.TryGetValue("interface", out interfaceIP)) { interfaceIP = "0.0.0.0"; } m_udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(interfaceIP), port)); m_modbusConnection = ModbusIpMaster.CreateIp(m_udpClient); m_pollingTimer.Enabled = true; return; } string portName; int baudRate; int dataBits; Parity parity; StopBits stopBits; if (!parameters.TryGetValue("portName", out portName) || string.IsNullOrWhiteSpace(portName)) { throw new ArgumentException("Connection string is missing \"portName\"."); } if (!parameters.TryGetValue("baudRate", out setting) || !int.TryParse(setting, out baudRate)) { throw new ArgumentException("Connection string is missing \"baudRate\" or value is invalid."); } if (!parameters.TryGetValue("dataBits", out setting) || !int.TryParse(setting, out dataBits)) { throw new ArgumentException("Connection string is missing \"dataBits\" or value is invalid."); } if (!parameters.TryGetValue("parity", out setting) || !Enum.TryParse(setting, out parity)) { throw new ArgumentException("Connection string is missing \"parity\" or value is invalid."); } if (!parameters.TryGetValue("stopBits", out setting) || !Enum.TryParse(setting, out stopBits)) { throw new ArgumentException("Connection string is missing \"stopBits\" or value is invalid."); } m_serialClient = new SerialPort(portName, baudRate, parity, dataBits, stopBits); m_modbusConnection = useRTU ? ModbusSerialMaster.CreateRtu(m_serialClient) : ModbusSerialMaster.CreateAscii(m_serialClient); m_pollingTimer.Enabled = true; }
public Dictionary <int, string> GetDataFromSlaves(MasterSettings masterSettings) { ModbusMaster master; var results = new Dictionary <int, string>(); try { var masterSettingsIp = masterSettings as MasterSettingsIp; if (masterSettingsIp != null) { using (var client = new TcpClient( masterSettingsIp.Host, masterSettingsIp.Port) { ReceiveTimeout = masterSettings.Timeout }) { master = ModbusIpMaster.CreateIp(client); results = SendRequests(master, masterSettings); client.Close(); } } else { var masterSettingsCom = masterSettings as MasterSettingsCom; if (masterSettingsCom != null) { using (var port = new SerialPort(masterSettingsCom.PortName) { BaudRate = masterSettingsCom.BaudRate, DataBits = masterSettingsCom.DataBits, Parity = masterSettingsCom.Parity, StopBits = masterSettingsCom.StopBits, ReadTimeout = masterSettingsCom.Timeout }) { port.Open(); master = ModbusSerialMaster.CreateRtu(port); results = SendRequests(master, masterSettings); port.Close(); } } } } catch (SocketException ex) { if (!isConnectionLost) { if (loggerEnabled) { Logger.Write(ex.Message); } else { throw ex; } } isConnectionLost = true; } return(results); }
public static void ModbusTcpMasterReadRegisters_SMA_MPPTs() { string workingDirectory = Directory.GetCurrentDirectory(); string[] ini_lines = new string[1]; try { ini_lines[0] = "IP:192.168.1.170"; } catch (Exception e) { Debug.WriteLine(e.Message + '\n'); return; } List <IpInformation> IP_Information = new List <IpInformation>(); int ipTimeout = DEFAULT_IP_TIMEOUT_SECONDS; int ipPort = DEFAULT_IP_PORT; byte unitID = DEFAULT_UNIT_ID; int mpptCount = DEFAULT_MPPT_COUNT; string historyDir = DEFAULT_HISTORY_DIRECTORY_PATH; foreach (string line in ini_lines) { if (line.Trim().StartsWith("#")) { continue; } Match match; if ((match = regex_get_IP.Match(line)).Success) { string ipString = match.Groups["ip"].Value; if ((match = regex_get_PORT.Match(line)).Success) { ipPort = Convert.ToInt32(match.Groups["port"].Value); } if ((match = regex_get_UNIT_ID.Match(line)).Success) { unitID = Convert.ToByte(match.Groups["unitID"].Value); } if ((match = regex_get_MPPTS.Match(line)).Success) { mpptCount = Convert.ToInt32(match.Groups["MPPTs"].Value); } IP_Information.Add(new IpInformation(ipString, ipPort, unitID, mpptCount)); } else if ((match = regex_get_IP_TIMEOUT.Match(line)).Success) { ipTimeout = Convert.ToInt32(match.Groups["ipTimeout"].Value); } else if ((match = regex_get_HISTORY_DIR.Match(line)).Success) { historyDir = match.Groups["historyDir"].Value; if (historyDir.StartsWith("\"") && historyDir.EndsWith("\"")) { historyDir = historyDir.Substring(1, historyDir.Length - 2); } if (historyDir.EndsWith("\\") || historyDir.EndsWith("/")) { historyDir = historyDir.Substring(0, historyDir.Length - 1); } } } for (; ;) { foreach (IpInformation ipInfo in IP_Information) { using (TcpClient client = new TcpClient()) { try { //Communicate with inverter Debug.WriteLine("\nConnecting to " + ipInfo.IP_Address); IAsyncResult ar = client.BeginConnect(ipInfo.IP_Address, ipInfo.IP_Port, null, null); WaitHandle wh = ar.AsyncWaitHandle; try { if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(ipTimeout), false)) { client.Close(); throw new TimeoutException("Could not connect to " + ipInfo.IP_Address); } } finally { wh.Close(); } ModbusIpMaster master = ModbusIpMaster.CreateIp(client); string line = string.Empty; //******************************************DESIRED PARAMETERS***************************************************** //******************************************Refer to the datasheet************************************************* //******************************************2 MPPTS**************************************************************** //Get local time from computer. const string DATE_TIME_PATTERN = "HH:mm:ss"; DateTime timeNow = DateTime.Now; try { if (timeNow.ToShortTimeString() == "00:00 AM") { Thread.Sleep(60000); } } catch { Debug.WriteLine(""); } string dtComputer = timeNow.ToString(DATE_TIME_PATTERN); line += dtComputer; //Get inverter serial number. const ushort SERIAL_NUMBER_ADR = 30005; const ushort SERIAL_NUMBER_REGISTER_COUNT = 2; // Read SMA serial number registers (U32) ushort[] serialNumberInfo = master.ReadHoldingRegisters(ipInfo.UnitID, SERIAL_NUMBER_ADR, SERIAL_NUMBER_REGISTER_COUNT); // Extract fields from U32 UInt32 serialNumber = ((UInt32)serialNumberInfo[0] << 16) | (UInt32)serialNumberInfo[1]; line += "," + serialNumber; //MPPT count. line += "," + ipInfo.MPPT_Count; if (ipInfo.MPPT_Count > 0) { // Get inverter DC input 1 parameters. const ushort DC_1_ADR = 30769; const ushort DC_1_REGISTER_COUNT = 6; // Read SMA DC 1 registers (3 x S32) ushort[] DC1Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_1_ADR, DC_1_REGISTER_COUNT); // Extract fields from DC 1 Current S32 (FIX3) if (DC1Info[0] == 32768) { DC1Info[0] = 0; } if (DC1Info[2] == 32768) { DC1Info[2] = 0; } if (DC1Info[4] == 32768) { DC1Info[4] = 0; } double DC1_Current = (double)(Int32)(((UInt32)DC1Info[0] << 16) | (UInt32)DC1Info[1]) / 1000; double DC1_Voltage = (double)(Int32)(((UInt32)DC1Info[2] << 16) | (UInt32)DC1Info[3]) / 100; double DC1_Power = (double)(Int32)(((UInt32)DC1Info[4] << 16) | (UInt32)DC1Info[5]); line += "," + DC1_Current + "," + DC1_Voltage + "," + DC1_Power; } // Get inverter DC input 2 parameters. if (ipInfo.MPPT_Count > 1) { const ushort DC_2_ADR = 30957; const ushort DC_2_REGISTER_COUNT = 6; // Read SMA DC 2 registers (3 x S32) ushort[] DC2Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_2_ADR, DC_2_REGISTER_COUNT); // Extract fields from DC 2 Current S32 (FIX3) if (DC2Info[0] == 32768) { DC2Info[0] = 0; } if (DC2Info[2] == 32768) { DC2Info[2] = 0; } if (DC2Info[4] == 32768) { DC2Info[4] = 0; } double DC2_Current = (double)(Int32)(((UInt32)DC2Info[0] << 16) | (UInt32)DC2Info[1]) / 1000; double DC2_Voltage = (double)(Int32)(((UInt32)DC2Info[2] << 16) | (UInt32)DC2Info[3]) / 100; double DC2_Power = (double)(Int32)(((UInt32)DC2Info[4] << 16) | (UInt32)DC2Info[5]); line += "," + DC2_Current + "," + DC2_Voltage + "," + DC2_Power + ","; } if (ipInfo.MPPT_Count > 2) { // Get inverter DC input 3 parameters. const ushort DC_3_ADR = 30963; const ushort DC_3_REGISTER_COUNT = 6; // Read SMA DC 3 registers (3 x S32) ushort[] DC3Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_3_ADR, DC_3_REGISTER_COUNT); // Extract fields from DC 3 Current S32 (FIX3) if (DC3Info[0] == 32768) { DC3Info[0] = 0; } if (DC3Info[2] == 32768) { DC3Info[2] = 0; } if (DC3Info[4] == 32768) { DC3Info[4] = 0; } double DC3_Current = (double)(Int32)(((UInt32)DC3Info[0] << 16) | (UInt32)DC3Info[1]) / 1000; double DC3_Voltage = (double)(Int32)(((UInt32)DC3Info[2] << 16) | (UInt32)DC3Info[3]) / 100; double DC3_Power = (double)(Int32)(((UInt32)DC3Info[4] << 16) | (UInt32)DC3Info[5]); line += "," + DC3_Current + "," + DC3_Voltage + "," + DC3_Power + ","; } if (ipInfo.MPPT_Count > 3) { // Get inverter DC input 4 parameters. const ushort DC_4_ADR = 30963; const ushort DC_4_REGISTER_COUNT = 6; // Read SMA DC 4 registers (3 x S32) ushort[] DC4Info = master.ReadHoldingRegisters(ipInfo.UnitID, DC_4_ADR, DC_4_REGISTER_COUNT); // Extract fields from DC 4 Current S32 (FIX3) if (DC4Info[0] == 32768) { DC4Info[0] = 0; } if (DC4Info[2] == 32768) { DC4Info[2] = 0; } if (DC4Info[4] == 32768) { DC4Info[4] = 0; } double DC4_Current = (double)(Int32)(((UInt32)DC4Info[0] << 16) | (UInt32)DC4Info[1]) / 1000; double DC4_Voltage = (double)(Int32)(((UInt32)DC4Info[2] << 16) | (UInt32)DC4Info[3]) / 100; double DC4_Power = (double)(Int32)(((UInt32)DC4Info[4] << 16) | (UInt32)DC4Info[5]); line += "," + DC4_Current + "," + DC4_Voltage + "," + DC4_Power + ","; } //Get Total Yield //kWh const ushort DC_totalpower_ADR = 30529; const ushort DC_totalpower_REGISTER_COUNT = 2; ushort[] DCtotalpowerInfo = master.ReadHoldingRegisters(ipInfo.UnitID, DC_totalpower_ADR, DC_totalpower_REGISTER_COUNT); if (DCtotalpowerInfo[0] == 32768) { DCtotalpowerInfo[0] = 0; } double totalyield = (double)(Int32)(((UInt32)DCtotalpowerInfo[0] << 16) | (UInt32)DCtotalpowerInfo[1]); line += totalyield + ","; //Get current total power //kWh const ushort DC_currentpower_ADR = 30775; const ushort DC_currentpower_REGISTER_COUNT = 2; ushort[] DCcurrentpowerInfo = master.ReadHoldingRegisters(ipInfo.UnitID, DC_currentpower_ADR, DC_currentpower_REGISTER_COUNT); if (DCcurrentpowerInfo[0] == 32768) { DCcurrentpowerInfo[0] = 0; } double currentyield = (double)(Int32)(((UInt32)DCcurrentpowerInfo[0] << 16) | (UInt32)DCcurrentpowerInfo[1]); line += currentyield + ","; //Get daily power //kWh const ushort DC_dailypower_ADR = 30535; const ushort DC_dailypower_REGISTER_COUNT = 2; ushort[] DCdailypowerInfo = master.ReadHoldingRegisters(ipInfo.UnitID, DC_dailypower_ADR, DC_dailypower_REGISTER_COUNT); if (DCdailypowerInfo[0] == 32768) { DCdailypowerInfo[0] = 0; } double dailyyield = (double)(Int32)(((UInt32)DCdailypowerInfo[0] << 16) | (UInt32)DCdailypowerInfo[1]); line += dailyyield + ","; //Get Inverter condition const ushort DC_condition_ADR = 30201; const ushort DC_condition_REGISTER_COUNT = 2; ushort[] DCconditionInfo = master.ReadHoldingRegisters(ipInfo.UnitID, DC_condition_ADR, DC_condition_REGISTER_COUNT); if (DCconditionInfo[0] == 32768) { DCconditionInfo[0] = 0; } double condition = (double)(Int32)(((UInt32)DCconditionInfo[0] << 16) | (UInt32)DCconditionInfo[1]); line += condition + ","; line += "\n"; //File.AppendAllText(filePath, line); //File.AppendAllText(filePath_1, line); Debug.WriteLine(line); ConnectionString(line); } catch (Exception e) { Debug.WriteLine(e.Message); } finally { if (client != null) { ((IDisposable)client).Dispose(); } } } } Thread.Sleep(300000); //5 minutes sleep } }
public void Paletleme(int maxHight, int reference_x, int reference_y, int paletX, int paletY, int paletZ, int productX, int productY, int productZ, int tolerans) { ushort gripperAdress = 1; //GRİPPER REGISTER ADRESİ ATANMALI !!! ushort[] gripperOffsets = new ushort[3]; //OFFSET DEĞERLERİ ATANMALI !!! ushort gripperControl = 0; TcpClient Client = new TcpClient(); ModbusIpMaster master = ModbusIpMaster.CreateIp(Client); int calculateX, calculateY, calculateZ, AdjustedReferenceX, AdjustedReferenceY, AdjustedReferenceZ, initialX, initialY, initialZ; calculateZ = maxHight / productZ; calculateY = paletY / productY; AdjustedReferenceY = (paletY - calculateY * productY) / 2 + reference_y; calculateX = paletY / productX; AdjustedReferenceX = (paletX - calculateX * productX) / 2 + reference_x; AdjustedReferenceZ = paletZ; initialX = AdjustedReferenceX; initialY = AdjustedReferenceY; initialZ = AdjustedReferenceZ; ushort offsetX, offsetY, offsetZ; Client.Connect("192.168.0.1", 502); for (int k = 0; k < calculateZ; k++) { for (int j = 0; j < calculateY; j++) { for (int i = 0; i < calculateX; i++) { offsetX = (ushort)(AdjustedReferenceX + productX / 2 + i * productX); offsetY = (ushort)(AdjustedReferenceY + productY / 2); offsetZ = (ushort)(AdjustedReferenceZ + productZ); ushort offsetAdress = 2; //OFFSET REGISTER ADRESİ ATANMALI !!! ushort[] offsetValues = new ushort[3]; offsetValues[0] = offsetX; offsetValues[1] = offsetY; offsetValues[2] = offsetZ; while (true) { master.ReadHoldingRegisters(gripperAdress, gripperControl); if (gripperControl == 1) { master.WriteMultipleRegisters(offsetAdress, offsetValues); break; } } while (true) { master.ReadHoldingRegisters(gripperAdress, gripperControl); if (gripperControl == 0) { master.WriteMultipleRegisters(offsetAdress, gripperOffsets); break; } } } AdjustedReferenceX = initialX; AdjustedReferenceY = AdjustedReferenceY + productY; } AdjustedReferenceX = initialX; AdjustedReferenceY = initialY; AdjustedReferenceZ = AdjustedReferenceZ + productZ; } }
public bool Read_pq_kwh(ref ModbusIpMaster master) //tcp使用 { if (master != null) { try { Thread.Sleep(Form1.WaitingTime); //ushort[] data0 = new ushort[28]; data0 = master.ReadInputRegisters(this.slaveID, address_v, 28); v_a = ushortToFloat(data0[0], data0[1]); v_b = ushortToFloat(data0[2], data0[3]); v_c = ushortToFloat(data0[4], data0[5]); v = ushortToFloat(data0[6], data0[7]); vl_ab = ushortToFloat(data0[8], data0[9]); vl_bc = ushortToFloat(data0[10], data0[11]); vl_ca = ushortToFloat(data0[12], data0[13]); vl = ushortToFloat(data0[14], data0[15]); i_a = ushortToFloat(data0[16], data0[17]); i_b = ushortToFloat(data0[18], data0[19]); i_c = ushortToFloat(data0[20], data0[21]); i = ushortToFloat(data0[22], data0[23]); i_n = ushortToFloat(data0[24], data0[25]); f = ushortToFloat(data0[26], data0[27]); Thread.Sleep(Form1.WaitingTime); data = master.ReadInputRegisters(this.slaveID, address_power_a, 24); power_a = ushortToFloat(data[0], data[1]); power_b = ushortToFloat(data[2], data[3]); power_c = ushortToFloat(data[4], data[5]); power_total = ushortToFloat(data[6], data[7]); Q1 = ushortToFloat(data[8], data[9]); Q2 = ushortToFloat(data[10], data[12]); Q3 = ushortToFloat(data[12], data[13]); Q_total = ushortToFloat(data[14], data[15]); s_a = ushortToFloat(data[16], data[17]); s_b = ushortToFloat(data[18], data[19]); s_c = ushortToFloat(data[20], data[21]); s = ushortToFloat(data[22], data[23]); Thread.Sleep(Form1.WaitingTime); data2 = master.ReadInputRegisters(slaveID, address_energy, 18); exp_wh_h = ushortToFloat(data2[0], data2[1]); imp_wh_h = ushortToFloat(data2[2], data2[3]); tot_wh_h = ushortToFloat(data2[4], data2[5]); net_wh_h = ushortToFloat(data2[6], data2[7]); exp_varh_h = ushortToFloat(data2[10], data2[11]); imp_varh_h = ushortToFloat(data2[8], data2[9]); tot_varh_h = ushortToFloat(data2[12], data2[13]); net_varh_h = ushortToFloat(data2[14], data2[15]); vah_h = ushortToFloat(data2[16], data2[17]); Thread.Sleep(Form1.WaitingTime); data3 = master.ReadInputRegisters(slaveID, address_PF, 8); pf_a = ushortToFloat(data3[0], data3[1]); pf_b = ushortToFloat(data3[2], data3[3]); pf_c = ushortToFloat(data3[4], data3[5]); pf = ushortToFloat(data3[6], data3[7]); CommFailureFlag = false; Fault_info = "Communication is normal"; return(true); } catch (Exception e) { CommFailureFlag = true; Fault_info = e.Message; return(false); } } return(false); }
private void FormAutomatic_Load(object sender, EventArgs e) { coilM22 = new bool[1]; lastCoilM22 = new bool[1]; coilM22[0] = false; lastCoilM22[0] = false; // Create Modbus modbusMasterTCP ipAddress = "192.168.1.2"; // textBoxIPAddress.Text; //ipAddress = "127.0.0.1"; // textBoxIPAddress.Text; tcpClient.BeginConnect(ipAddress, tcpPort, null, null); modbusMasterTCP = ModbusIpMaster.CreateIp(tcpClient); timerReadModbus.Enabled = true; // aktifkan mode baca data dari plc // Serial Port Scanner serialPortScanner.PortName = "COM1"; //COM1 try { serialPortScanner.Open(); serialOpen = true; } catch (Exception err) { serialOpen = false; MessageBox.Show(err.ToString()); } if (serialOpen) { thread = new Thread(bacaDataSerial); thread.Start(); threadRun = true; } // Update Current Settings loadCurrentSetting(); // Trigger M8 Kalau 4P int a = textBoxReference.Text.IndexOf('T', 4); if (a == 4) { modbusMasterTCP.WriteSingleCoil(1, 8, true); } else { modbusMasterTCP.WriteSingleCoil(1, 8, false); } totalPass = Int32.Parse(textBoxPass.Text); totalFail = Int32.Parse(textBoxFail.Text); totalQty = Int32.Parse(textBoxTotalQty.Text); // Update ke PLC /* * try * { * modbusMasterTCP.WriteSingleRegister(0, (ushort)totalPass); // MW0 == Pass * modbusMasterTCP.WriteSingleRegister(1, (ushort)totalFail); // MW1 == Fail * } * catch (Exception err) * { * // By Pass * } * */ // }
private static void ChannelUpdaterThreadProc(object obj) { try { ModbusStation self = (ModbusStation)obj; for (; ;) { try { using (TcpClient client = new TcpClient(self.ipAddress, self.tcpPort)) { ModbusIpMaster master = ModbusIpMaster.CreateIp(client); for (; ;) { foreach (ModbusBuffer buf in self.buffers) { ushort startAddress = buf.startAddress; ushort numInputs = buf.numInputs; switch (buf.ModbusDataType) { case ModbusDataType.InputRegister: ushort[] registers = master.ReadInputRegisters(startAddress, numInputs); DateTime dt = DateTime.Now; foreach (ModbusChannelImp ch in buf.channels) { if (ch.Value.GetType() == typeof(int)) { ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(uint)) { ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(float)) { ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } } break; case ModbusDataType.Coil: bool[] inputs = master.ReadCoils(startAddress, numInputs); dt = DateTime.Now; foreach (ModbusChannelImp ch in buf.channels) { if (ch.Value.GetType() == typeof(int)) { int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0; ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(uint)) { uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0); ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(float)) { float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0; ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } } break; case ModbusDataType.Input: inputs = master.ReadInputs(startAddress, numInputs); dt = DateTime.Now; foreach (ModbusChannelImp ch in buf.channels) { if (ch.Value.GetType() == typeof(int)) { int val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0; ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(uint)) { uint val = (uint)(inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0); ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(float)) { float val = inputs[ch.ModbusDataAddress - buf.startAddress] ? 1 : 0; ch.DoUpdate(val, dt, ChannelStatusFlags.Good); } } break; case ModbusDataType.HoldingRegister: registers = master.ReadHoldingRegisters(startAddress, numInputs); dt = DateTime.Now; foreach (ModbusChannelImp ch in buf.channels) { if (ch.Value.GetType() == typeof(int)) { ch.DoUpdate((int)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(uint)) { ch.DoUpdate((uint)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } if (ch.Value.GetType() == typeof(float)) { ch.DoUpdate((float)registers[ch.ModbusDataAddress - buf.startAddress], dt, ChannelStatusFlags.Good); } } break; } } Thread.Sleep(100); } } } catch (Exception e) { if (e is ThreadAbortException) { throw e; } } Thread.Sleep(1000); } } catch (ThreadAbortException) { } }
private bool Connect(bool QuickConnect = false) { ConnectionSetup cs = new ConnectionSetup(); string connection_text = ""; if (QuickConnect == false) { DialogResult dr = cs.ShowDialog(); if (dr != DialogResult.OK) { return(false); } } try { if (cs.IsOverSerialPort) { serialPort = cs.GetSerialPort(); master = null; serialPort.Open(); master = ModbusSerialMaster.CreateRtu(serialPort); connection_text = string.Format("{0} @ {1} Baud", serialPort, serialPort.BaudRate); } else if (cs.IsOverTCP) { master = null; tcpClient = cs.GetTcpClient(); tcpClient.ReceiveTimeout = 1000; master = ModbusIpMaster.CreateIp(tcpClient); connection_text = string.Format("{0}:{1}", cs.TcpAddress, cs.TcpPort); } else { return(false); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } master.Transport.Retries = 0; disconnectToolStripMenuItem.Enabled = true; connectToolStripMenuItem.Enabled = false; quickConnectToolStripMenuItem.Enabled = false; gbModbusSetup.Enabled = false; CurrentSlave = 0; seqThreadPause = false; statusLabel.Text = "Connected to " + connection_text; return(true); }
public ModBusTCPMaster(int device, ModBusDriverParam param) : base(device, param) { this.device.master = true; this.device.tcp = true; }
public async Task Connect(string ip, int port) { ModbusIpMaster master = ModbusIpMaster.CreateIp(client); client.Connect(ip, port); }
public void DisconnectFromClient() { _connected = false; _TcpClient = null; _master = null; }
public void Tomodbus() { this.timerModbus.Stop(); try { int port = Convert.ToInt32(Pub_dtTSetting.Rows[0][4]); //<--- This is your value // define array to keep address Input Register--------------------------------------- int tagB = 0; for (int row = 0; row < Pub_dtTTAGMapping.Rows.Count; row++) { string tagtype = dataGridView1.Rows[row].Cells[6].Value.ToString();//TagType if (tagtype == "B") { tagB++; } } int[][] mosbusAdrInputRegister = new int[tagB][]; for (int index1 = 0; index1 < tagB; index1++) { mosbusAdrInputRegister[index1] = new int[2]; } //----------------------------------------------------------------------------------- //IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { using (TcpClient tcpClient = new TcpClient()) { tcpClient.Connect(ip.ToString(), port); //if port 502 open, server not start throw exception ModbusIpMaster master2Family = ModbusIpMaster.CreateIp(tcpClient); int Count_Boolean = 0; bool[] boolvalueto_inputRegister = new bool[dataGridView1.Rows.Count]; slave2Family.DataStore.InputDiscretes.Clear(); // clear Input Status for manual add for (int row = 0; row < Pub_dtTTAGMapping.Rows.Count; row++) { string Mb_Address = dataGridView1.Rows[row].Cells[2].Value.ToString(); //MB address string Value = dataGridView1.Rows[row].Cells[3].Value.ToString(); //Value string tagtype = dataGridView1.Rows[row].Cells[6].Value.ToString(); //TagType if (tagtype == "F") { string ValueString = dataGridView1.Rows[row].Cells[3].Value.ToString();//Value //Convert float to Hex--------------------------------------------------------------------------------- float strTofloat; bool result = float.TryParse(ValueString, out strTofloat); if (result == true) { byte[] buffer = BitConverter.GetBytes(strTofloat); int intVal = BitConverter.ToInt32(buffer, 0); //if don't have this line then program do like string to hex //https://gregstoll.com/~gregstoll/floattohex/ //http://string-functions.com/string-hex.aspx string hexstring = intVal.ToString("X8"); //separate hex string------------------------------------------------------------------------------------- string hexstrinng_left = hexstring.Substring(0, 4); ushort hexshort_left = Convert.ToUInt16(hexstrinng_left, 16); //like under line string hexstrinng_right = hexstring.Substring(4); ushort hexshort_right = Convert.ToUInt16(hexstrinng_right, 16); //Prepare MbAddress to send--------------------------------------------------------------------------------- int int32Mb_Address = Convert.ToInt32(Mb_Address) - 400000 - 1;//-1 cause modscan32 start index 0 ushort RightShortMbAddress = Convert.ToUInt16(int32Mb_Address); //ushort RightShortMbAddress = (ushort)int32Mb_Address; int LeftMbAddress = int32Mb_Address + 1; ushort LeftShortMbAddress = Convert.ToUInt16(LeftMbAddress); //ushort LeftShortMbAddress = (ushort)LeftMbAddress; //--------------------------------------------------------------------------------------------------------------- master2Family.WriteSingleRegister(RightShortMbAddress, hexshort_right); master2Family.WriteSingleRegister(LeftShortMbAddress, hexshort_left); } //end if result } //end if Tagtype F else if (tagtype == "B") { bool boolvalue = Convert.ToBoolean(Convert.ToInt16(Value)); int int32Mb_Address = Convert.ToInt32(Mb_Address) - 100000 - 1;//-1 cause modscan32 start index 0 master2Family.WriteSingleCoil(Convert.ToUInt16(int32Mb_Address), boolvalue); mosbusAdrInputRegister[Count_Boolean][0] = int32Mb_Address; mosbusAdrInputRegister[Count_Boolean][1] = Convert.ToInt32(Value); ++Count_Boolean; //if (boolvalue == true) //{ // //slave.DataStore.InputDiscretes.Add(true); // slave2Family.DataStore.InputDiscretes.Add(false); //} //else //{ // //slave.DataStore.InputDiscretes.Add(false); // slave2Family.DataStore.InputDiscretes.Add(true); //} } //end else if Tagtype B } //end for loop int getlastaddress = mosbusAdrInputRegister[mosbusAdrInputRegister.Length - 1][0]; int matchIndexInputregister = 0; for (int indexInputRegister = 0; indexInputRegister <= getlastaddress; indexInputRegister++) { if (indexInputRegister == mosbusAdrInputRegister[matchIndexInputregister][0]) { if (mosbusAdrInputRegister[matchIndexInputregister][1] == 1) { //slave.DataStore.InputDiscretes.Add(true); slave2Family.DataStore.InputDiscretes.Add(true); } else { //slave.DataStore.InputDiscretes.Add(false); slave2Family.DataStore.InputDiscretes.Add(false); } matchIndexInputregister++; } else { slave2Family.DataStore.InputDiscretes.Add(false); } } datastore.InputRegisters.Clear(); } } //end if ipv4 } //end foreach } catch (Exception ex) { using (StreamWriter sw = File.AppendText(indebuglogFolderPath + "\\" + filename + ".txt")) { sw.WriteLine("ERROR : " + ex); } } }
/////////////////////////////////////////////////////////////////// public bool lambaDurumDollyBaslangic(AutoResetEvent _AREvt, ushort jobState1StatusAnimationID, ushort jobState1StatusColorID, ModbusIpMaster master) { bool sonuc = false; ushort[] sonucRegisterAdim0 = new ushort[7]; ushort[] sonucRegisterAdim1 = new ushort[5]; _AREvt = new AutoResetEvent(false); try { ushort[] value = new ushort[6]; value[0] = 1; //yazma value[1] = 8701; //reg. start value[2] = 3; //adet value[3] = 0; //adet value[4] = jobState1StatusAnimationID; //adet value[5] = jobState1StatusColorID; //adet master.WriteMultipleRegisters(1, 700, value); master.WriteSingleRegister(1, 699, 4096); /* ushort[] value2 = new ushort[3]; * value2[0] = 0;//wait state * value2[1] = jobState1StatusAnimationID;//job state flash * value2[2] = jobState1StatusColorID;////job state color 1 green * master.WriteMultipleRegisters(1, 703, value2);*/ _AREvt.WaitOne(300); ushort[] value3 = new ushort[4]; value3[0] = 4096; //device ID value3[1] = 1; //yazma value3[2] = 6336; //reg. start value3[3] = 1; //adet master.WriteMultipleRegisters(1, 699, value3); ushort[] value4 = new ushort[1]; value4[0] = 1;//green master.WriteMultipleRegisters(1, 703, value4); sonuc = true; } catch (Exception ex) { sonuc = false; } return(sonuc); }
private void GetAlarmsEvents(ProgressBar progress, ushort FC, ushort quantity, bool getAlarms) { progress.Value = 0; string OmniIP = "10.10.1." + Convert.ToString(FC + 10); TcpClient client = new TcpClient(OmniIP, 502); client.ReceiveTimeout = 500; ModbusIpMaster master = ModbusIpMaster.CreateIp(client); //Create text file string fileName; if (getAlarms) { fileName = "FC" + Convert.ToString(FC) + "_alarms.txt"; } else { fileName = "FC" + Convert.ToString(FC) + "_events.txt"; } TextWriter txt = new StreamWriter(fileName); //Number of events to load master.WriteSingleRegister((byte)1, (ushort)3769, quantity); //Send command to load Events on buffer byte commandByte; if (getAlarms) { commandByte = 0x10; } else { commandByte = 0x80; } //byte[] invCommandBytes = new byte[] { 0, commandNibble, 0, 0 }; RegisterCollection invCommand = new RegisterCollection(new byte[] { 0, commandByte, 0, 0 }); CustomWriteMultipleRegistersRequest reqCommand = new CustomWriteMultipleRegistersRequest(16, 1, 15129, invCommand); master.ExecuteCustomMessage <CustomWriteMultipleRegistersResponse>(reqCommand); //Wait buffer is ready CustomReadHoldingRegistersResponse cmdReg; do { CustomReadHoldingRegistersRequest readCmd = new CustomReadHoldingRegistersRequest(3, 1, 15129, 1); cmdReg = master.ExecuteCustomMessage <CustomReadHoldingRegistersResponse>(readCmd); //Console.WriteLine(Convert.ToString(cmdReg.Data[1])); ----Old command for console version---- } while (cmdReg.Data[1] != 0); //Read buffer int endIndex; int CRIndex; DateTime timeStamp; IFormatProvider dateFormat = new System.Globalization.CultureInfo("en-GB"); for (ushort i = 0; i < 600; i++) { try //send request to Omni for the current package { CustomReadBufferRequest reqBuffer = new CustomReadBufferRequest(65, 1, 9402, i); CustomReadBufferResponse packet = master.ExecuteCustomMessage <CustomReadBufferResponse>(reqBuffer); //stop if find end of file endIndex = packet.StrData.IndexOf(Convert.ToChar(26)); //get index of end of file if exists if (endIndex != -1) //if end of file was found { txt.Write(packet.StrData.Substring(0, endIndex)); break; } //stop if find time before yesterday at 17:00 try { CRIndex = packet.StrData.IndexOf(Convert.ToChar(13));//get index of carriage return to find date if (getAlarms) { timeStamp = Convert.ToDateTime(packet.StrData.Substring(CRIndex + 1, 19), dateFormat); } else { timeStamp = Convert.ToDateTime(packet.StrData.Substring(CRIndex + 10, 18), dateFormat); } if (timeStamp < DateTime.Today.AddDays(-1).AddHours(17)) { txt.Write(packet.StrData.Substring(0, CRIndex)); break; } } catch { } txt.Write(packet.StrData); progress.Increment(1); } catch //if request timeout, omni is refilling buffer { System.Threading.Thread.Sleep(3000); //delay 3s //Restart client connection client.Close(); client = new TcpClient(OmniIP, 502); client.ReceiveTimeout = 500; master = ModbusIpMaster.CreateIp(client); progress.Value = 0; i--;//decrement packet index to reapeat the request } } progress.Value = 63; txt.Close(); client.Close(); }