From 008aaf45860ce2b64e4444e872db2a4d07e1df5a Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Thu, 11 Jan 2018 07:10:01 +0100 Subject: [PATCH 001/114] Update README.md --- README.md | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 17b4ea9..a11fa68 100644 --- a/README.md +++ b/README.md @@ -34,24 +34,15 @@ Supports Function Codes: Modbus TCP, Modbus UDP and Modbus RTU client/server library -Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - -You are free to: - -Share — copy and redistribute the material in any medium or format -The licensor cannot revoke these freedoms as long as you follow the license terms. -Under the following terms: - -Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. -NonCommercial — You may not use the material for commercial purposes. -NoDerivatives — If you remix, transform, or build upon the material, you may not distribute the modified material. -No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits.You are free to: - -Share — copy and redistribute the material in any medium or format -The licensor cannot revoke these freedoms as long as you follow the license terms. -Under the following terms: - -Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. -NonCommercial — You may not use the material for commercial purposes. -NoDerivatives — If you remix, transform, or build upon the material, you may not distribute the modified material. -No additional restrictions — You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . From f355dd2f9798d4dfdf5327501bea7f75ec5ad8e5 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Thu, 11 Jan 2018 07:13:22 +0100 Subject: [PATCH 002/114] Update README.md --- README.md | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a11fa68..5470d01 100644 --- a/README.md +++ b/README.md @@ -34,15 +34,18 @@ Supports Function Codes: Modbus TCP, Modbus UDP and Modbus RTU client/server library - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . + + This file is part of the EasyModbus library. + + EasyModbus is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + EasyModbus is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Foobar. If not, see . From 22e233b3d9d780eefd1ed93e84ce119d25fb7ab3 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Thu, 11 Jan 2018 08:02:24 +0100 Subject: [PATCH 003/114] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5470d01..792555b 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Only a few lines of codes are needed to read or write data from or to a PLC. Additional Software tools e.g. Modbus Server Simulator, makes software development fast and easy. -Download Library (*.DLL) and tools: Download EasyModbusTCP/UDP/RTU .NET +Download Library (*.DLL) from NuGet or from: Download EasyModbusTCP/UDP/RTU .NET From 43b4a9c28879016ba19624fd317400dece2f25b2 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Thu, 11 Jan 2018 08:04:19 +0100 Subject: [PATCH 004/114] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 792555b..f7f701f 100644 --- a/README.md +++ b/README.md @@ -48,4 +48,4 @@ Modbus TCP, Modbus UDP and Modbus RTU client/server library GNU General Public License for more details. You should have received a copy of the GNU General Public License - along with Foobar. If not, see . + along with EasyModbus. If not, see . From ff28895e7d16c207a253708326a3b74aa213d64b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Tue, 27 Mar 2018 19:25:10 +0200 Subject: [PATCH 005/114] Changed eventhandlers --- EasyModbus/ModbusClient.cs | 144 +++++++++++++-------------- EasyModbus/ModbusServer.cs | 44 ++++---- EasyModbusAdvancedClient/MainForm.cs | 20 ++-- EasyModbusClientExample/MainForm.cs | 6 +- ServerApplication/Program.cs | 2 +- 5 files changed, 108 insertions(+), 108 deletions(-) diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 5e307c9..6fe7d04 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -70,14 +70,14 @@ public enum RegisterOrder { LowHigh = 0, HighLow = 1 }; public int MqttBrokerPort { get; set; } = 1883; - public delegate void ReceiveDataChanged(object sender); - public event ReceiveDataChanged receiveDataChanged; + public delegate void ReceiveDataChangedHandler(object sender); + public event ReceiveDataChangedHandler ReceiveDataChanged; - public delegate void SendDataChanged(object sender); - public event SendDataChanged sendDataChanged; + public delegate void SendDataChangedHandler(object sender); + public event SendDataChangedHandler SendDataChanged; - public delegate void ConnectedChanged(object sender); - public event ConnectedChanged connectedChanged; + public delegate void ConnectedChangedHandler(object sender); + public event ConnectedChangedHandler ConnectedChanged; NetworkStream stream; @@ -154,10 +154,10 @@ public void Connect() } - if (connectedChanged != null) + if (ConnectedChanged != null) try { - connectedChanged(this); + ConnectedChanged(this); } catch { @@ -187,10 +187,10 @@ public void Connect() tcpClient = new TcpClient(); connected = true; } - if (connectedChanged != null) + if (ConnectedChanged != null) try { - connectedChanged(this); + ConnectedChanged(this); } catch { @@ -226,8 +226,8 @@ public void Connect(string ipAddress, int port) connected = true; } - if (connectedChanged != null) - connectedChanged(this); + if (ConnectedChanged != null) + ConnectedChanged(this); } /// @@ -839,10 +839,10 @@ private void DataReceivedHandler(object sender, dataReceived = true; receiveActive = false; serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { - receiveDataChanged(this); + ReceiveDataChanged(this); } @@ -975,11 +975,11 @@ public bool[] ReadDiscreteInputs(int startingAddress, int quantity) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -1022,20 +1022,20 @@ public bool[] ReadDiscreteInputs(int startingAddress, int quantity) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -1210,11 +1210,11 @@ public bool[] ReadCoils(int startingAddress, int quantity) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -1256,21 +1256,21 @@ public bool[] ReadCoils(int startingAddress, int quantity) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send MocbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -1437,11 +1437,11 @@ public int[] ReadHoldingRegisters(int startingAddress, int quantity) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -1484,21 +1484,21 @@ public int[] ReadHoldingRegisters(int startingAddress, int quantity) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[256]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -1676,11 +1676,11 @@ public int[] ReadInputRegisters(int startingAddress, int quantity) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -1723,20 +1723,20 @@ public int[] ReadInputRegisters(int startingAddress, int quantity) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -1876,11 +1876,11 @@ public void WriteSingleCoil(int startingAddress, bool value) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -1919,21 +1919,21 @@ public void WriteSingleCoil(int startingAddress, bool value) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -2051,11 +2051,11 @@ public void WriteSingleRegister(int startingAddress, int value) Array.Copy(data, 6, debugData, 0, 8); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[8]; Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -2096,21 +2096,21 @@ public void WriteSingleRegister(int startingAddress, int value) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -2247,11 +2247,11 @@ public void WriteMultipleCoils(int startingAddress, bool[] values) Array.Copy(data, 6, debugData, 0, data.Length - 6); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length - 6]; Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -2292,21 +2292,21 @@ public void WriteMultipleCoils(int startingAddress, bool[] values) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -2432,11 +2432,11 @@ public void WriteMultipleRegisters(int startingAddress, int[] values) Array.Copy(data, 6, debugData, 0, data.Length - 6); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length - 6]; Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; @@ -2477,20 +2477,20 @@ public void WriteMultipleRegisters(int startingAddress, int[] values) Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -2636,11 +2636,11 @@ public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRea Array.Copy(data, 6, debugData, 0, data.Length - 6); if (debug) StoreLogData.Instance.Store("Send Serial-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length - 6]; Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); + SendDataChanged(this); } data = new byte[2100]; readBuffer = new byte[256]; @@ -2680,21 +2680,21 @@ public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRea Array.Copy(data, 0, debugData, 0, data.Length-2); if (debug) StoreLogData.Instance.Store("Send ModbusTCP-Data: "+BitConverter.ToString(debugData) ,System.DateTime.Now); } - if (sendDataChanged != null) + if (SendDataChanged != null) { sendData = new byte[data.Length-2]; Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); + SendDataChanged(this); } data = new Byte[2100]; int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) + if (ReceiveDataChanged != null) { receiveData = new byte[NumberOfBytes]; Array.Copy(data, 0, receiveData, 0, NumberOfBytes); if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); - receiveDataChanged(this); + ReceiveDataChanged(this); } } } @@ -2744,8 +2744,8 @@ public void Disconnect() { if (serialport.IsOpen & !this.receiveActive) serialport.Close(); - if (connectedChanged != null) - connectedChanged(this); + if (ConnectedChanged != null) + ConnectedChanged(this); return; } if (stream != null) @@ -2753,8 +2753,8 @@ public void Disconnect() if (tcpClient != null) tcpClient.Close(); connected = false; - if (connectedChanged != null) - connectedChanged(this); + if (ConnectedChanged != null) + ConnectedChanged(this); } diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index c898d7d..a61b73c 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -322,17 +322,17 @@ public ModbusServer() } #region events - public delegate void CoilsChanged(int coil, int numberOfCoils); - public event CoilsChanged coilsChanged; + public delegate void CoilsChangedHandler(int coil, int numberOfCoils); + public event CoilsChangedHandler CoilsChanged; - public delegate void HoldingRegistersChanged(int register, int numberOfRegisters); - public event HoldingRegistersChanged holdingRegistersChanged; + public delegate void HoldingRegistersChangedHandler(int register, int numberOfRegisters); + public event HoldingRegistersChangedHandler HoldingRegistersChanged; - public delegate void NumberOfConnectedClientsChanged(); - public event NumberOfConnectedClientsChanged numberOfConnectedClientsChanged; + public delegate void NumberOfConnectedClientsChangedHandler(); + public event NumberOfConnectedClientsChangedHandler NumberOfConnectedClientsChanged; - public delegate void LogDataChanged(); - public event LogDataChanged logDataChanged; + public delegate void LogDataChangedHandler(); + public event LogDataChangedHandler LogDataChanged; #endregion public void Listen() @@ -481,8 +481,8 @@ private void DataReceivedHandler(object sender, private void numberOfClientsChanged() { numberOfConnections = tcpHandler.NumberOfConnectedClients; - if (numberOfConnectedClientsChanged != null) - numberOfConnectedClientsChanged(); + if (NumberOfConnectedClientsChanged != null) + NumberOfConnectedClientsChanged(); } #endregion @@ -646,8 +646,8 @@ private void ProcessReceivedData(object networkConnectionParameter) //this.sendAnswer(); this.CreateLogData(receiveDataThread, sendDataThread); - if (logDataChanged != null) - logDataChanged(); + if (LogDataChanged != null) + LogDataChanged(); } } #endregion @@ -1386,8 +1386,8 @@ private void WriteSingleCoil(ModbusProtocol receiveData, ModbusProtocol sendData } } catch (Exception) { } - if (coilsChanged != null) - coilsChanged(receiveData.startingAdress+1, 1); + if (CoilsChanged != null) + CoilsChanged(receiveData.startingAdress+1, 1); } } @@ -1509,8 +1509,8 @@ private void WriteSingleRegister(ModbusProtocol receiveData, ModbusProtocol send } } catch (Exception) { } - if (holdingRegistersChanged != null) - holdingRegistersChanged(receiveData.startingAdress+1, 1); + if (HoldingRegistersChanged != null) + HoldingRegistersChanged(receiveData.startingAdress+1, 1); } } @@ -1649,8 +1649,8 @@ private void WriteMultipleCoils(ModbusProtocol receiveData, ModbusProtocol sendD } } catch (Exception) { } - if (coilsChanged != null) - coilsChanged(receiveData.startingAdress+1, receiveData.quantity); + if (CoilsChanged != null) + CoilsChanged(receiveData.startingAdress+1, receiveData.quantity); } } @@ -1773,8 +1773,8 @@ private void WriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtocol s } } catch (Exception) { } - if (holdingRegistersChanged != null) - holdingRegistersChanged(receiveData.startingAdress+1, receiveData.quantity); + if (HoldingRegistersChanged != null) + HoldingRegistersChanged(receiveData.startingAdress+1, receiveData.quantity); } } @@ -1904,8 +1904,8 @@ private void ReadWriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtoc } } catch (Exception) { } - if (holdingRegistersChanged != null) - holdingRegistersChanged(receiveData.startingAddressWrite+1, receiveData.quantityWrite); + if (HoldingRegistersChanged != null) + HoldingRegistersChanged(receiveData.startingAddressWrite+1, receiveData.quantityWrite); } } diff --git a/EasyModbusAdvancedClient/MainForm.cs b/EasyModbusAdvancedClient/MainForm.cs index 277a4f3..73187de 100644 --- a/EasyModbusAdvancedClient/MainForm.cs +++ b/EasyModbusAdvancedClient/MainForm.cs @@ -567,8 +567,8 @@ void StartSingleJobToolStripMenuItemClick(object sender, EventArgs e) getValuesThreadObject.connectionProperty.timer = new System.Threading.Timer(GetValuesThread, getValuesThreadObject , easyModbusManager.connectionPropertiesList[treeView1.SelectedNode.Parent.Index].CycleTime, easyModbusManager.connectionPropertiesList[treeView1.SelectedNode.Parent.Index].CycleTime); else getValuesThreadObject.connectionProperty.timer.Change(easyModbusManager.connectionPropertiesList[treeView1.SelectedNode.Parent.Index].CycleTime, easyModbusManager.connectionPropertiesList[treeView1.SelectedNode.Parent.Index].CycleTime); - getValuesThreadObject.connectionProperty.modbusClient.receiveDataChanged -= new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateTextBoxReceive); - getValuesThreadObject.connectionProperty.modbusClient.sendDataChanged -= new EasyModbus.ModbusClient.SendDataChanged(UpdateTextBoxSend); + getValuesThreadObject.connectionProperty.modbusClient.ReceiveDataChanged -= new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateTextBoxReceive); + getValuesThreadObject.connectionProperty.modbusClient.SendDataChanged -= new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateTextBoxSend); } @@ -605,8 +605,8 @@ void StartAllJobsToolStripMenuItemClick(object sender, EventArgs e) { foreach(ConnectionProperties connectionProperty in easyModbusManager.connectionPropertiesList) { - connectionProperty.modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateTextBoxReceive); - connectionProperty.modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateTextBoxSend); + connectionProperty.modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateTextBoxReceive); + connectionProperty.modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateTextBoxSend); GetValuesThreadObject getValuesThreadObject = new GetValuesThreadObject(); getValuesThreadObject.connectionProperty = connectionProperty; if (connectionProperty.timer == null) @@ -640,8 +640,8 @@ void StopAllJobsToolStripMenuItemClick(object sender, EventArgs e) { foreach(ConnectionProperties connectionProperty in easyModbusManager.connectionPropertiesList) { - connectionProperty.modbusClient.receiveDataChanged -= new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateTextBoxReceive); - connectionProperty.modbusClient.sendDataChanged -= new EasyModbus.ModbusClient.SendDataChanged(UpdateTextBoxSend); + connectionProperty.modbusClient.ReceiveDataChanged -= new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateTextBoxReceive); + connectionProperty.modbusClient.SendDataChanged -= new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateTextBoxSend); connectionProperty.timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); connectionProperty.modbusClient.Disconnect(); } @@ -663,16 +663,16 @@ private void stopCurrentJobToolStripMenuItem_Click(object sender, EventArgs e) indexJobToStop = treeView1.SelectedNode.Index; easyModbusManager.connectionPropertiesList[indexJobToStop].timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.Disconnect(); - easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateTextBoxReceive); - easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateTextBoxSend); + easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateTextBoxReceive); + easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateTextBoxSend); } if (treeView1.SelectedNode.Level == 2) { indexJobToStop = treeView1.SelectedNode.Parent.Index; easyModbusManager.connectionPropertiesList[indexJobToStop].timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.Disconnect(); - easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateTextBoxReceive); - easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateTextBoxSend); + easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateTextBoxReceive); + easyModbusManager.connectionPropertiesList[indexJobToStop].modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateTextBoxSend); } UpdateNodesConnectedStatus(); diff --git a/EasyModbusClientExample/MainForm.cs b/EasyModbusClientExample/MainForm.cs index 841c57f..169ff4e 100644 --- a/EasyModbusClientExample/MainForm.cs +++ b/EasyModbusClientExample/MainForm.cs @@ -24,9 +24,9 @@ public MainForm() InitializeComponent(); modbusClient = new EasyModbus.ModbusClient(); - modbusClient.receiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChanged(UpdateReceiveData); - modbusClient.sendDataChanged += new EasyModbus.ModbusClient.SendDataChanged(UpdateSendData); - modbusClient.connectedChanged += new EasyModbus.ModbusClient.ConnectedChanged(UpdateConnectedChanged); + modbusClient.ReceiveDataChanged += new EasyModbus.ModbusClient.ReceiveDataChangedHandler(UpdateReceiveData); + modbusClient.SendDataChanged += new EasyModbus.ModbusClient.SendDataChangedHandler(UpdateSendData); + modbusClient.ConnectedChanged += new EasyModbus.ModbusClient.ConnectedChangedHandler(UpdateConnectedChanged); // modbusClient.LogFileFilename = "logFiletxt.txt"; //modbusClient.Baudrate = 9600; diff --git a/ServerApplication/Program.cs b/ServerApplication/Program.cs index 6c0de7e..4b32d79 100644 --- a/ServerApplication/Program.cs +++ b/ServerApplication/Program.cs @@ -22,7 +22,7 @@ public void startServer() modbusServer.MqttRootTopic = "examplemodbusserver"; modbusServer.MqttBrokerAddress = "www.mqtt-dashboard.com"; modbusServer.Listen(); - modbusServer.holdingRegistersChanged += new EasyModbus.ModbusServer.HoldingRegistersChanged(holdingRegistersChanged); + modbusServer.HoldingRegistersChanged += new EasyModbus.ModbusServer.HoldingRegistersChangedHandler(holdingRegistersChanged); Console.ReadKey(); modbusServer.StopListening(); From efa021a2b4ec2aadaa7b255454ad299dadae6112 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Tue, 27 Mar 2018 19:34:24 +0200 Subject: [PATCH 006/114] Event Handler changed --- EasyModbusServerSimulator/MainForm.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/EasyModbusServerSimulator/MainForm.cs b/EasyModbusServerSimulator/MainForm.cs index b0c166d..75f0635 100644 --- a/EasyModbusServerSimulator/MainForm.cs +++ b/EasyModbusServerSimulator/MainForm.cs @@ -34,10 +34,10 @@ public MainForm() easyModbusTCPServer.Listen(); - easyModbusTCPServer.coilsChanged += new ModbusServer.CoilsChanged(CoilsChanged); - easyModbusTCPServer.holdingRegistersChanged += new ModbusServer.HoldingRegistersChanged(HoldingRegistersChanged); - easyModbusTCPServer.numberOfConnectedClientsChanged += new ModbusServer.NumberOfConnectedClientsChanged(NumberOfConnectionsChanged); - easyModbusTCPServer.logDataChanged += new ModbusServer.LogDataChanged(LogDataChanged); + easyModbusTCPServer.CoilsChanged += new ModbusServer.CoilsChangedHandler(CoilsChanged); + easyModbusTCPServer.HoldingRegistersChanged += new ModbusServer.HoldingRegistersChangedHandler(HoldingRegistersChanged); + easyModbusTCPServer.NumberOfConnectedClientsChanged += new ModbusServer.NumberOfConnectedClientsChangedHandler(NumberOfConnectionsChanged); + easyModbusTCPServer.LogDataChanged += new ModbusServer.LogDataChangedHandler(LogDataChanged); } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) From 22b5fa6a8d08d0c699b6289576956338aab9f09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Tue, 27 Mar 2018 19:48:47 +0200 Subject: [PATCH 007/114] Version Update 5.0 --- ConsoleApplicationMqqt/Properties/AssemblyInfo.cs | 2 +- EasyModbus/ModbusClient.cs | 2 +- EasyModbus/Properties/AssemblyInfo.cs | 2 +- EasyModbusAdvancedClient/Properties/AssemblyInfo.cs | 2 +- EasyModbusClientExample/Properties/AssemblyInfo.cs | 2 +- EasyModbusServerSimulator/Properties/AssemblyInfo.cs | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs b/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs index e9638e3..0ee6b27 100644 --- a/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs +++ b/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs @@ -10,7 +10,7 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplicationMqqt")] -[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyCopyright("Copyright…–––––––––––– © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 6fe7d04..86c5476 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -724,7 +724,7 @@ public static UInt16 calculateCRC(byte[] data, UInt16 numberOfBytes, int startBy private bool receiveActive = false; private byte[] readBuffer = new byte[256]; private int bytesToRead = 0; - private int actualPositionToRead = 0; + private int akjjjctualPositionToRead = 0; DateTime dateTimeLastRead; /* private void DataReceivedHandler(object sender, diff --git a/EasyModbus/Properties/AssemblyInfo.cs b/EasyModbus/Properties/AssemblyInfo.cs index de0d356..8483345 100644 --- a/EasyModbus/Properties/AssemblyInfo.cs +++ b/EasyModbus/Properties/AssemblyInfo.cs @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("4.4.1")] +[assembly: AssemblyVersion("5.0.0")] diff --git a/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs b/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs index e3ab5f9..9b018fc 100644 --- a/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs +++ b/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("4.4")] +[assembly: AssemblyVersion("5.0.0")] diff --git a/EasyModbusClientExample/Properties/AssemblyInfo.cs b/EasyModbusClientExample/Properties/AssemblyInfo.cs index dc7f894..9b080c3 100644 --- a/EasyModbusClientExample/Properties/AssemblyInfo.cs +++ b/EasyModbusClientExample/Properties/AssemblyInfo.cs @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("4.4.1")] +[assembly: AssemblyVersion("5.0.0")] diff --git a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs index 289b875..0f0bc64 100644 --- a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs +++ b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs @@ -24,4 +24,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion ("4.4.1")] +[assembly: AssemblyVersion ("5.0.0")] From b03915bede7dd7ddcb016713b23de91d9720c674 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Thu, 20 Sep 2018 18:47:27 +0200 Subject: [PATCH 008/114] MQTT feature Removed --- EasyModbus.sln | 152 +---- EasyModbus/EasyModbus.csproj | 124 ---- EasyModbus/EasyModbus2Mqtt.cs | 547 ------------------ EasyModbus/ModbusClient.cs | 198 +------ EasyModbus/ModbusServer.cs | 203 +------ .../EasyModbusAdvancedClient.csproj | 126 ---- .../Properties/AssemblyInfo.cs | 4 +- .../EasyModbusClientExample.csproj | 126 ---- .../Properties/AssemblyInfo.cs | 4 +- .../EasyModbusServerSimulator.csproj | 126 ---- EasyModbusServerSimulator/Info.Designer.cs | 2 +- .../MainForm.Designer.cs | 45 +- EasyModbusServerSimulator/MainForm.cs | 28 - .../Properties/AssemblyInfo.cs | 4 +- ServerApplication/Program.cs | 2 - 15 files changed, 15 insertions(+), 1676 deletions(-) delete mode 100644 EasyModbus/EasyModbus2Mqtt.cs diff --git a/EasyModbus.sln b/EasyModbus.sln index 7a222e3..0193508 100644 --- a/EasyModbus.sln +++ b/EasyModbus.sln @@ -13,12 +13,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusAdvancedClient", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerApplication", "ServerApplication\ServerApplication.csproj", "{F737B6B0-3B35-4CC9-9134-EFF5F37B8C1F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTT", "MQTT\MQTT\MQTT.csproj", "{613A173A-77E1-46A1-9668-93A67BD558D5}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "M2Mqtt.Net", "paho.mqtt.m2mqtt-master\M2Mqtt\M2Mqtt.Net.csproj", "{A11AEF5A-B246-4FE8-8330-06DB73CC8074}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplicationMqqt", "ConsoleApplicationMqqt\ConsoleApplicationMqqt.csproj", "{F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyModbusTCPCore", "EasyModbusTCPCore\EasyModbusTCPCore.csproj", "{22675733-2164-4AE8-A8C2-F23182073913}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusClient_IOTCoreExample", "EasyModbusClient_IOTCoreExample\EasyModbusClient_IOTCoreExample.csproj", "{9AC81F46-F110-46F3-B884-6665D8A05267}" @@ -291,150 +285,6 @@ Global {F737B6B0-3B35-4CC9-9134-EFF5F37B8C1F}.Release|x64.Build.0 = Release|Any CPU {F737B6B0-3B35-4CC9-9134-EFF5F37B8C1F}.Release|x86.ActiveCfg = Release|Any CPU {F737B6B0-3B35-4CC9-9134-EFF5F37B8C1F}.Release|x86.Build.0 = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|ARM.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|ARM.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|x64.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|x64.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|x86.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|x86.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|Any CPU.Build.0 = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|ARM.ActiveCfg = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|ARM.Build.0 = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|x64.ActiveCfg = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|x64.Build.0 = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|x86.ActiveCfg = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|x86.Build.0 = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|ARM.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|ARM.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|x64.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|x64.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|x86.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|x86.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|Any CPU.Build.0 = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|ARM.ActiveCfg = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|ARM.Build.0 = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|x64.ActiveCfg = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|x64.Build.0 = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|x86.ActiveCfg = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|x86.Build.0 = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|ARM.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|ARM.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|x64.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|x64.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|x86.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Debug|x86.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|ARM.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|x64.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial|x86.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|x64.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial1|x86.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|x64.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial2|x86.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|x64.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.DebugCommercial3|x86.Build.0 = Debug|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|Any CPU.Build.0 = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|ARM.ActiveCfg = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|ARM.Build.0 = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|x64.ActiveCfg = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|x64.Build.0 = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|x86.ActiveCfg = Release|Any CPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D}.Release|x86.Build.0 = Release|Any CPU {22675733-2164-4AE8-A8C2-F23182073913}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {22675733-2164-4AE8-A8C2-F23182073913}.Debug|Any CPU.Build.0 = Debug|Any CPU {22675733-2164-4AE8-A8C2-F23182073913}.Debug|ARM.ActiveCfg = Debug|Any CPU @@ -559,7 +409,7 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - VisualSVNWorkingCopyRoot = . SolutionGuid = {7628B1C9-8DDB-4DBD-A71D-D369A4A166DE} + VisualSVNWorkingCopyRoot = . EndGlobalSection EndGlobal diff --git a/EasyModbus/EasyModbus.csproj b/EasyModbus/EasyModbus.csproj index f320753..41db91d 100644 --- a/EasyModbus/EasyModbus.csproj +++ b/EasyModbus/EasyModbus.csproj @@ -67,131 +67,7 @@ - - M2Mqtt\Exceptions\MqttClientException.cs - - - M2Mqtt\Exceptions\MqttCommunicationException.cs - - - M2Mqtt\Exceptions\MqttConnectionException.cs - - - M2Mqtt\Exceptions\MqttTimeoutException.cs - - - M2Mqtt\IMqttNetworkChannel.cs - - - M2Mqtt\Internal\InternalEvent.cs - - - M2Mqtt\Internal\MsgInternalEvent.cs - - - M2Mqtt\Internal\MsgPublishedInternalEvent.cs - - - M2Mqtt\Messages\MqttMsgBase.cs - - - M2Mqtt\Messages\MqttMsgConnack.cs - - - M2Mqtt\Messages\MqttMsgConnect.cs - - - M2Mqtt\Messages\MqttMsgConnectEventArgs.cs - - - M2Mqtt\Messages\MqttMsgContext.cs - - - M2Mqtt\Messages\MqttMsgDisconnect.cs - - - M2Mqtt\Messages\MqttMsgPingReq.cs - - - M2Mqtt\Messages\MqttMsgPingResp.cs - - - M2Mqtt\Messages\MqttMsgPuback.cs - - - M2Mqtt\Messages\MqttMsgPubcomp.cs - - - M2Mqtt\Messages\MqttMsgPublish.cs - - - M2Mqtt\Messages\MqttMsgPublishedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPublishEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPubrec.cs - - - M2Mqtt\Messages\MqttMsgPubrel.cs - - - M2Mqtt\Messages\MqttMsgSuback.cs - - - M2Mqtt\Messages\MqttMsgSubscribe.cs - - - M2Mqtt\Messages\MqttMsgSubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgSubscribeEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsuback.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribe.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribeEventArgs.cs - - - M2Mqtt\MqttClient.cs - - - M2Mqtt\MqttSecurity.cs - - - M2Mqtt\MqttSettings.cs - - - M2Mqtt\Net\Fx.cs - - - M2Mqtt\Net\MqttNetworkChannel.cs - - - M2Mqtt\Session\MqttBrokerSession.cs - - - M2Mqtt\Session\MqttClientSession.cs - - - M2Mqtt\Session\MqttSession.cs - - - M2Mqtt\Utility\QueueExtension.cs - - - M2Mqtt\Utility\Trace.cs - - diff --git a/EasyModbus/EasyModbus2Mqtt.cs b/EasyModbus/EasyModbus2Mqtt.cs deleted file mode 100644 index f912278..0000000 --- a/EasyModbus/EasyModbus2Mqtt.cs +++ /dev/null @@ -1,547 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using uPLibrary.Networking.M2Mqtt.Messages; -using System.IO.Ports; -using System.Diagnostics; - -namespace EasyModbus -{ - - public class EasyModbus2Mqtt - { - private ModbusClient modbusClient = new ModbusClient(); - List readOrders = new List(); - string mqttBrokerAddress = "www.mqtt-dashboard.com"; - int mqttBrokerPort = 1883; - string mqttRootTopic = "easymodbusclient"; - uPLibrary.Networking.M2Mqtt.MqttClient mqttClient; - public bool AutomaticReconnect { get; set; } = true; - public string MqttUserName { get; set; } - public string MqttPassword { get; set; } - public bool RetainMessages { get; set; } - - - public EasyModbus2Mqtt() - { - - } - - public void AddReadOrder(ReadOrder readOrder) - { - if (readOrder.FunctionCode == 0) - throw new ArgumentOutOfRangeException("FunctionCode must be initialized"); - if (readOrder.Quantity == 0) - throw new ArgumentOutOfRangeException("Quantity cannot be 0"); - if (readOrder.Topic != null) - if (readOrder.Topic.Length != readOrder.Quantity) - throw new ArgumentOutOfRangeException("Size of the Topic array must mach with quantity"); - if (readOrder.Retain != null) - if (readOrder.Retain.Length != readOrder.Quantity) - throw new ArgumentOutOfRangeException("Size of the Retain array must mach with quantity"); - if (readOrder.Hysteresis != null) - if (readOrder.Hysteresis.Length != readOrder.Quantity) - throw new ArgumentOutOfRangeException("Size of the Hysteresis array must mach with quantity"); - if (readOrder.Scale != null) - if (readOrder.Scale.Length != readOrder.Quantity) - throw new ArgumentOutOfRangeException("Size of the Scale array must mach with quantity"); - if (readOrder.Retain != null) - if (readOrder.Retain.Length != readOrder.Quantity) - throw new ArgumentOutOfRangeException("Size of the Retain array must mach with quantity"); - if (readOrder.CylceTime == 0) - readOrder.CylceTime = 500; - if (readOrder.Topic == null) - { - readOrder.Topic = new string[readOrder.Quantity]; - for (int i = 0; i < readOrder.Quantity; i++) - { - if (readOrder.FunctionCode == FunctionCode.ReadCoils) - { - readOrder.Topic[i] = mqttRootTopic+"/coils/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) - { - readOrder.Topic[i] = mqttRootTopic+"/discreteinputs/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) - { - readOrder.Topic[i] = mqttRootTopic+"/holdingregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) - { - readOrder.Topic[i] = mqttRootTopic+"/inputregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - } - } - readOrder.oldvalue = new object[readOrder.Quantity]; - readOrders.Add(readOrder); - } - - public void AddReadOrder(FunctionCode functionCode, int quantity, int startingAddress, int cycleTime) - { - ReadOrder readOrder = new ReadOrder(); - readOrder.CylceTime = cycleTime; - readOrder.FunctionCode = functionCode; - readOrder.Quantity = quantity; - readOrder.StartingAddress = startingAddress; - readOrder.Topic = new string[quantity]; - readOrder.Retain = new bool[quantity]; - readOrder.oldvalue = new object[quantity]; - for (int i = 0; i < quantity; i++) - { - if (functionCode == FunctionCode.ReadCoils) - { - readOrder.Topic[i] = mqttRootTopic+ "/coils/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadDiscreteInputs) - { - readOrder.Topic[i] = mqttRootTopic + "/discreteinputs/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadHoldingRegisters) - { - readOrder.Topic[i] = mqttRootTopic + "/holdingregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadInputRegisters) - { - readOrder.Topic[i] = mqttRootTopic + "/inputregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - } - readOrders.Add(readOrder); - } - - public void AddReadOrder(FunctionCode functionCode, int quantity, int startingAddress, int cycleTime, string[] topic) - { - ReadOrder readOrder = new ReadOrder(); - readOrder.FunctionCode = functionCode; - readOrder.Quantity = quantity; - readOrder.StartingAddress = startingAddress; - readOrder.CylceTime = cycleTime; - readOrder.Topic = topic; - readOrder.Retain = new bool[quantity]; - this.AddReadOrder(readOrder); - } - - public void start() - { - - this.shouldStop = false; - if (mqttBrokerAddress == null) - throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized"); - mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress,mqttBrokerPort,false,null,null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); - - string clientID = new Guid().ToString(); - try - { - if (MqttUserName == null || MqttPassword == null) - mqttClient.Connect(clientID); - else - mqttClient.Connect(clientID, MqttUserName, MqttPassword); - if (!modbusClient.Connected) - modbusClient.Connect(); - } - catch (Exception exc) - { - if (!this.AutomaticReconnect) - throw exc; - } - for (int i = 0; i < readOrders.Count; i++) - { - readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData)); - readOrders[i].thread.Start(readOrders[i]); - } - } - - string MqttBrokerAddressPublish = ""; - public void publish(string[] topic, string[] payload, string mqttBrokerAddress) - { - if (mqttClient != null) - if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected) - mqttClient.Disconnect(); - if (topic.Length != payload.Length) - throw new ArgumentOutOfRangeException("Array topic and payload must be the same size"); - mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); - string clientID = Guid.NewGuid().ToString(); - if (!mqttClient.IsConnected) - { - if (MqttUserName == null || MqttPassword == null) - mqttClient.Connect(clientID); - else - mqttClient.Connect(clientID, MqttUserName, MqttPassword); - } - - for (int i = 0; i < payload.Length; i++) - mqttClient.Publish(topic[i], Encoding.UTF8.GetBytes(payload[i]), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages); - - } - - public void publish(string topic, string payload, string mqttBrokerAddress) - { - if (mqttClient != null) - if (!mqttBrokerAddress.Equals(this.MqttBrokerAddressPublish) & mqttClient.IsConnected) - mqttClient.Disconnect(); - mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); - string clientID = Guid.NewGuid().ToString(); - if (!mqttClient.IsConnected) - { - if (MqttUserName == null || MqttPassword == null) - mqttClient.Connect(clientID); - else - mqttClient.Connect(clientID, MqttUserName, MqttPassword); - } - - if (payload != null) - mqttClient.Publish(topic, Encoding.UTF8.GetBytes(payload), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, RetainMessages); - else - mqttClient.Publish(topic, new byte[0], 0, RetainMessages); - } - - public void Disconnect() - { - mqttClient.Disconnect(); - } - - - public void stop() - { - modbusClient.Disconnect(); - mqttClient.Disconnect(); - this.shouldStop = true; - } - - private volatile bool shouldStop; - private object lockProcessData = new object(); - private void ProcessData(object param) - { - while (!shouldStop) - { - try - { - if (!mqttClient.IsConnected) - { - mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress, mqttBrokerPort, false, null, null, uPLibrary.Networking.M2Mqtt.MqttSslProtocols.None); - string clientID = Guid.NewGuid().ToString(); - if (MqttUserName == null || MqttPassword == null) - mqttClient.Connect(clientID); - else - mqttClient.Connect(clientID, MqttUserName, MqttPassword); - } - } - catch (Exception exc) - { - if (!this.AutomaticReconnect) - throw exc; - } - ReadOrder readOrder = (ReadOrder)param; - lock (lockProcessData) - { - try - { - if (readOrder.FunctionCode == FunctionCode.ReadCoils) - { - bool[] value = modbusClient.ReadCoils(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - else if ((bool)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - - } - if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) - { - bool[] value = modbusClient.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - else if ((bool)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - } - if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) - { - int[] value = modbusClient.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1; - if (readOrder.oldvalue[i] == null) - { - mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale) + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true)) - { - mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - } - } - - if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) - { - int[] value = modbusClient.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - float scale = readOrder.Scale != null ? (readOrder.Scale[i] == 0) ? 1 : readOrder.Scale[i] : 1; - if (readOrder.oldvalue[i] == null) - { - mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - else if (((int)readOrder.oldvalue[i] != value[i]) && (readOrder.Hysteresis != null ? ((value[i] < (int)readOrder.oldvalue[i] - (int)readOrder.Hysteresis[i]) | (value[i] > (int)readOrder.oldvalue[i] + (int)readOrder.Hysteresis[i])) : true)) - { - mqttClient.Publish(readOrder.Topic[i], (readOrder.Unit == null ? Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString()) : Encoding.UTF8.GetBytes(((float)value[i] * scale).ToString() + " " + readOrder.Unit[i])), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, (readOrder.Retain != null) ? readOrder.Retain[i] : false); - readOrder.oldvalue[i] = value[i]; - } - } - } - } - catch (Exception exc) - { - modbusClient.Disconnect(); - Thread.Sleep(2000); - if (!AutomaticReconnect) - throw exc; - Debug.WriteLine(exc.StackTrace); - - if (!modbusClient.Connected) - { - try - { - - modbusClient.Connect(); - } - catch (Exception) { } - } - } - } - System.Threading.Thread.Sleep(readOrder.CylceTime); - } - } - - - public string MqttBrokerAddress - { - get - { - return this.mqttBrokerAddress; - } - set - { - this.mqttBrokerAddress = value; - } - } - - public int MqttBrokerPort - { - get - { - return this.mqttBrokerPort; - } - set - { - this.mqttBrokerPort = value; - } - } - - public string MqttRootTopic - { - get - { - return this.mqttRootTopic; - } - set - { - this.mqttRootTopic = value; - } - } - - public string IPAddress - { - get - { - return modbusClient.IPAddress; - } - set - { - modbusClient.IPAddress = value; - } - } - - public string ModbusIPAddress - { - get - { - return modbusClient.IPAddress; - } - set - { - modbusClient.IPAddress = value; - } - } - - public int Port - { - get - { - return modbusClient.Port; - } - set - { - modbusClient.Port = value; - } - } - - public int ModbusPort - { - get - { - return modbusClient.Port; - } - set - { - modbusClient.Port = value; - } - } - - /// - /// Gets or Sets the Unit identifier in case of serial connection (Default = 0) - /// - public byte UnitIdentifier - { - get - { - return modbusClient.UnitIdentifier; - } - set - { - modbusClient.UnitIdentifier = value; - } - } - - - /// - /// Gets or Sets the Baudrate for serial connection (Default = 9600) - /// - public int Baudrate - { - get - { - return modbusClient.Baudrate; - } - set - { - modbusClient.Baudrate = value; - } - } - - /// - /// Gets or Sets the of Parity in case of serial connection - /// - public Parity Parity - { - get - { - if (modbusClient.SerialPort != null) - return modbusClient.Parity; - else - return Parity.Even; - } - set - { - if (modbusClient.SerialPort != null) - modbusClient.Parity = value; - } - } - - - /// - /// Gets or Sets the number of stopbits in case of serial connection - /// - public StopBits StopBits - { - get - { - if (modbusClient.SerialPort != null) - return modbusClient.StopBits; - else - return StopBits.One; - } - set - { - if (modbusClient.SerialPort != null) - modbusClient.StopBits = value; - } - } - - /// - /// Gets or Sets the connection Timeout in case of ModbusTCP connection - /// - public int ConnectionTimeout - { - get - { - return modbusClient.ConnectionTimeout; - } - set - { - modbusClient.ConnectionTimeout = value; - } - } - - /// - /// Gets or Sets the serial Port - /// - public string SerialPort - { - get - { - - return modbusClient.SerialPort; - } - set - { - this.SerialPort = value; - } - } - - } - - public class ReadOrder - { - public FunctionCode FunctionCode; //Function Code to execute - public int CylceTime = 500; //Polling intervall in ms - public int StartingAddress; //First Modbus Register to Read (0-based) - public int Quantity; - public string[] Topic; //Symbolnames can by replaced, by default we Push to the topic e.g. for Coils: /modbusclient/coils/1 - public int[] Hysteresis; //Values for 16-Bit Registers will be published of the dieffreence is greater than Hysteresis - public string[] Unit; //Unit for Analog Values (Holding Registers and Input Registers) - public float[] Scale; //Scale for Analog Values (Holding Registers and Input Registers) - public bool[] Retain; //Retain last Value in Broker - internal System.Threading.Thread thread; - internal object[] oldvalue; - } - - public enum FunctionCode - { - ReadDiscreteInputs = 2, - ReadCoils = 1, - ReadHoldingRegisters = 3, - ReadInputRegisters = 4 - } - -} diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 86c5476..8926af1 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -55,20 +55,8 @@ public enum RegisterOrder { LowHigh = 0, HighLow = 1 }; private Parity parity = Parity.Even; private StopBits stopBits = StopBits.One; private bool connected = false; - private bool[] mqttCoilsOldValues; - private bool[] mqttDiscreteInputsOldValues; - private int[] mqttInputRegistersOldValues; - private int[] mqttHoldingRegistersOldValues; - private EasyModbus2Mqtt easyModbus2Mqtt; - private bool mqttRetainMessages; public int NumberOfRetries { get; set; } = 3; private int countRetries = 0; - string mqttRootTopic = "easymodbusclient"; - public string MqttUserName { get; set; } - public string MqttPassword { get; set; } - public bool MqttPushOnChange { get; set; } = true; - - public int MqttBrokerPort { get; set; } = 1883; public delegate void ReceiveDataChangedHandler(object sender); public event ReceiveDataChangedHandler ReceiveDataChanged; @@ -865,45 +853,6 @@ public static bool DetectValidModbusFrame(byte[] readBuffer, int length) return true; } - /// - /// Read Discrete Inputs from Server device (FC2) and publishes the values to a MQTT-Broker. - /// The Topic will be easymodbusclient/discreteinputs/'address' e.g. easymodbusclient/discreteinputs/0 for address "0". - /// Note that the Address that will be publishes is "0"-Based. The Root topic can be changed using the Parameter - /// By default we are using the Standard-Port 1883. This Port can be changed using the Property "MqttBrokerPort" - /// A Username and Passowrd can be provided using the Properties "MqttUserName" and "MqttPassword" - /// 'MqttRootTopic' Default is 'easymodbusclient' - /// - /// First discrete input to read - /// Number of discrete Inputs to read - /// Broker address the values will be published to - /// Boolean Array which contains the discrete Inputs - public bool[] ReadDiscreteInputs(int startingAddress, int quantity, string mqttBrokerAddress) - { - bool[] returnValue = this.ReadDiscreteInputs(startingAddress, quantity); - List topic = new List(); - List payload = new List(); - if (MqttPushOnChange && mqttDiscreteInputsOldValues == null) - mqttDiscreteInputsOldValues = new bool[65535]; - for (int i = 0; i < returnValue.Length; i++) - { - if (mqttDiscreteInputsOldValues == null ? true : (mqttDiscreteInputsOldValues[i] != returnValue[i])) - { - topic.Add(mqttRootTopic + "/discreteinputs/" + (i + startingAddress).ToString()); - payload.Add(returnValue[i].ToString()); - mqttDiscreteInputsOldValues[i] = returnValue[i]; - } - - } - if (easyModbus2Mqtt == null) - easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerPort = this.MqttBrokerPort; - easyModbus2Mqtt.MqttUserName = this.MqttUserName; - easyModbus2Mqtt.MqttPassword = this.MqttPassword; - easyModbus2Mqtt.RetainMessages = this.mqttRetainMessages; - easyModbus2Mqtt.publish(topic.ToArray(), payload.ToArray(), mqttBrokerAddress); - - return returnValue; - } /// @@ -1101,46 +1050,6 @@ public bool[] ReadDiscreteInputs(int startingAddress, int quantity) return (response); } - /// - /// Read coils from Server device (FC1) and publishes the values to a MQTT-Broker. - /// The Topic will be easymodbusclient/coils/'address' e.g. easymodbusclient/coils/0 for address "0". - /// Note that the Address that will be publishes is "0"-Based. The Root topic can be changed using the Parameter - /// 'MqttRootTopic' Default is 'easymodbusclient' - /// By default we are using the Standard-Port 1883. This Port can be changed using the Property "MqttBrokerPort" - /// A Username and Passowrd can be provided using the Properties "MqttUserName" and "MqttPassword" - /// - /// First coil to read - /// Number of coils to read - /// Broker address 8the values will be published to - /// Boolean Array which contains the coild - public bool[] ReadCoils(int startingAddress, int quantity, string mqttBrokerAddress) - { - - bool[] returnValue = this.ReadCoils(startingAddress, quantity); - List topic = new List(); - List payload = new List(); - if (MqttPushOnChange && mqttCoilsOldValues == null) - mqttCoilsOldValues = new bool[65535]; - for (int i = 0; i < returnValue.Length; i++) - { - if (mqttCoilsOldValues == null ? true : (mqttCoilsOldValues[i] != returnValue[i])) - { - topic.Add(mqttRootTopic + "/coils/" + (i + startingAddress).ToString()); - payload.Add(returnValue[i].ToString()); - mqttCoilsOldValues[i] = returnValue[i]; - } - } - if (easyModbus2Mqtt == null) - easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerPort = this.MqttBrokerPort; - easyModbus2Mqtt.MqttUserName = this.MqttUserName; - easyModbus2Mqtt.MqttPassword = this.MqttPassword; - easyModbus2Mqtt.RetainMessages = this.mqttRetainMessages; - easyModbus2Mqtt.publish(topic.ToArray(), payload.ToArray(), mqttBrokerAddress); - - - return returnValue; - } /// /// Read Coils from Server device (FC1). @@ -1336,43 +1245,6 @@ public bool[] ReadCoils(int startingAddress, int quantity) return (response); } - /// - /// Read Holding Registers from Server device (FC3) and publishes the values to a MQTT-Broker. - /// The Topic will be easymodbusclient/holdingregisters/'address' e.g. easymodbusclient/holdingregisters/0 for address "0". - /// Note that the Address that will be publishes is "0"-Based. The Root topic can be changed using the Parameter - /// 'MqttRootTopic' Default is 'easymodbusclient' - /// By default we are using the Standard-Port 1883. This Port can be changed using the Property "MqttBrokerPort" - /// A Username and Passowrd can be provided using the Properties "MqttUserName" and "MqttPassword" - /// - /// First Holding Register to read - /// Number of Holding Registers to read - /// Broker address the values will be published to - /// Boolean Array which contains the Holding Registers - public int[] ReadHoldingRegisters(int startingAddress, int quantity, string mqttBrokerAddress) - { - int[] returnValue = this.ReadHoldingRegisters(startingAddress, quantity); - List topic = new List(); - List payload = new List(); - if (MqttPushOnChange && mqttHoldingRegistersOldValues == null) - mqttHoldingRegistersOldValues = new int[65535]; - for (int i = 0; i < returnValue.Length; i++) - { - if (mqttHoldingRegistersOldValues == null ? true : (mqttHoldingRegistersOldValues[i] != returnValue[i])) - { - topic.Add(mqttRootTopic + "/holdingregisters/" + (i + startingAddress).ToString()); - payload.Add(returnValue[i].ToString()); - mqttHoldingRegistersOldValues[i] = returnValue[i]; - } - } - if (easyModbus2Mqtt == null) - easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerPort = this.MqttBrokerPort; - easyModbus2Mqtt.MqttUserName = this.MqttUserName; - easyModbus2Mqtt.MqttPassword = this.MqttPassword; - easyModbus2Mqtt.RetainMessages = this.mqttRetainMessages; - easyModbus2Mqtt.publish(topic.ToArray(), payload.ToArray(), mqttBrokerAddress); - return returnValue; - } /// /// Read Holding Registers from Master device (FC3). @@ -1572,43 +1444,7 @@ public int[] ReadHoldingRegisters(int startingAddress, int quantity) return (response); } - /// - /// Read Input Registers from Server device (FC4) and publishes the values to a MQTT-Broker. - /// The Topic will be easymodbusclient/inputregisters/'address' e.g. easymodbusclient/inputregisters/0 for address "0". - /// Note that the Address that will be publishes is "0"-Based. The Root topic can be changed using the Parameter - /// 'MqttRootTopic' Default is 'easymodbusclient' - /// By default we are using the Standard-Port 1883. This Port can be changed using the Property "MqttBrokerPort" - /// A Username and Passowrd can be provided using the Properties "MqttUserName" and "MqttPassword" - /// - /// First Input Register to read - /// Number of Input Registers to read - /// Broker address 8the values will be published to - /// Boolean Array which contains the Input Registers - public int[] ReadInputRegisters(int startingAddress, int quantity, string mqttBrokerAddress) - { - int[] returnValue = this.ReadInputRegisters(startingAddress, quantity); - List topic = new List(); - List payload = new List(); - if (MqttPushOnChange && mqttInputRegistersOldValues == null) - mqttInputRegistersOldValues = new int[65535]; - for (int i = 0; i < returnValue.Length; i++) - { - if (mqttInputRegistersOldValues == null ? true : (mqttInputRegistersOldValues[i] != returnValue[i])) - { - topic.Add(mqttRootTopic + "/inputregisters/" + (i + startingAddress).ToString()); - payload.Add(returnValue[i].ToString()); - mqttInputRegistersOldValues[i] = returnValue[i]; - } - } - if (easyModbus2Mqtt == null) - easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerPort = this.MqttBrokerPort; - easyModbus2Mqtt.MqttUserName = this.MqttUserName; - easyModbus2Mqtt.MqttPassword = this.MqttPassword; - easyModbus2Mqtt.RetainMessages = this.mqttRetainMessages; - easyModbus2Mqtt.publish(topic.ToArray(), payload.ToArray(), mqttBrokerAddress); - return returnValue; - } + /// /// Read Input Registers from Master device (FC4). @@ -2589,7 +2425,7 @@ public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRea int[] response; this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); + this.length = BitConverter.GetBytes((int)11 + values.Length * 2); this.functionCode = 0x17; startingAddressReadLocal = BitConverter.GetBytes(startingAddressRead); quantityReadLocal = BitConverter.GetBytes(quantityRead); @@ -3001,35 +2837,5 @@ public string LogFileFilename } } - /// - /// Gets or Sets the Mqtt Root Topic - /// - public string MqttRootTopic - { - get - { - return this.mqttRootTopic; - } - set - { - this.mqttRootTopic = value; - } - } - - /// - /// Disables or Enables to Retain the Messages in the Broker - default is false (Enabled) - /// - public bool MqttRetainMessages - { - get - { - return this.mqttRetainMessages; - } - set - { - this.mqttRetainMessages = value; - } - } - } } diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index a61b73c..57d7871 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -303,21 +303,16 @@ public class ModbusServer public bool PortChanged { get; set; } object lockCoils = new object(); object lockHoldingRegisters = new object(); - internal object lockMQTT = new object(); private volatile bool shouldStop; - internal EasyModbus2Mqtt easyModbus2Mqtt = new EasyModbus2Mqtt(); public ModbusServer() { - easyModbus2Mqtt.MqttRootTopic = "easymodbusserver"; - easyModbus2Mqtt.RetainMessages = true; holdingRegisters = new HoldingRegisters(this); inputRegisters = new InputRegisters(this); coils = new Coils(this); discreteInputs = new DiscreteInputs(this); - easyModbus2Mqtt.MqttBrokerAddress = null; } @@ -2006,12 +2001,6 @@ private void CreateLogData(ModbusProtocol receiveData, ModbusProtocol sendData) } - public void DeleteRetainedMessages(string topic) - { - if (MqttBrokerAddress != null) - easyModbus2Mqtt.publish(topic, null, MqttBrokerAddress); - - } public int NumberOfConnections @@ -2154,105 +2143,12 @@ public string LogFileFilename } } - /// - /// Gets or Sets the Mqtt Broker Address - /// - public string MqttBrokerAddress - { - get - { - return easyModbus2Mqtt.MqttBrokerAddress; - } - set - { - easyModbus2Mqtt.MqttBrokerAddress = value; - - - - } - } - - /// - /// Gets or Sets the Mqtt Root Topic - Standard is "easymodbusserver" - /// - public string MqttRootTopic - { - get - { - return easyModbus2Mqtt.MqttRootTopic; - } - set - { - easyModbus2Mqtt.MqttRootTopic = value; - } - } - - /// - /// Gets or Sets the Username for the MQTT-Broker (if nessesary) default is "null" - /// - public string MqttUserName - { - get - { - return easyModbus2Mqtt.MqttUserName; - } - set - { - easyModbus2Mqtt.MqttUserName = value; - } - } - /// - /// Gets or Sets the Password for the MQTT-Broker (if nessesary) default is "null" - /// - public string MqttPassword - { - get - { - return easyModbus2Mqtt.MqttPassword; - } - set - { - easyModbus2Mqtt.MqttPassword = value; - } - } - /// - /// Disables or Enables to Retain the Messages in the Broker - default is TRUE (Enabled) - /// - public bool MqttRetainMessages - { - get - { - return easyModbus2Mqtt.RetainMessages; - } - set - { - easyModbus2Mqtt.RetainMessages = value; - } - } - - /// - /// Gets or Sets the MQTT Broker Port (Standard is 1883) - /// - public int MqttBrokerPort - { - get - { - return easyModbus2Mqtt.MqttBrokerPort; - } - set - { - easyModbus2Mqtt.MqttBrokerPort = value; - } - } - - } public class HoldingRegisters { public Int16[] localArray = new Int16[65535]; - private Int16[] mqttHoldingRegistersOldValues = new Int16[65535]; ModbusServer modbusServer; public HoldingRegisters(EasyModbus.ModbusServer modbusServer) @@ -2266,30 +2162,7 @@ public Int16 this[int x] set { this.localArray[x] = value; - if (modbusServer.MqttBrokerAddress != null) - if (localArray[x] != mqttHoldingRegistersOldValues[x]) - { - - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.DoWork); - Thread thread = new Thread(pts); - thread.Start(x); - } - mqttHoldingRegistersOldValues[x] = localArray[x]; - } - } - - private void DoWork(Object parameter) - { - lock (modbusServer.lockMQTT) - { - //ToSend contains the Array elements to publish - int toSend = (int) parameter; - try - { - modbusServer.easyModbus2Mqtt.publish(modbusServer.MqttRootTopic + "/holdingregisters" + toSend, localArray[toSend].ToString(), modbusServer.MqttBrokerAddress); - } - catch (Exception) { } - Thread.Sleep(100); + } } } @@ -2297,7 +2170,6 @@ private void DoWork(Object parameter) public class InputRegisters { public Int16[] localArray = new Int16[65535]; - private Int16[] mqttInputRegistersOldValues = new Int16[65535]; ModbusServer modbusServer; public InputRegisters(EasyModbus.ModbusServer modbusServer) @@ -2311,30 +2183,7 @@ public Int16 this[int x] set { this.localArray[x] = value; - if (modbusServer.MqttBrokerAddress != null) - if (localArray[x] != mqttInputRegistersOldValues[x]) - { - mqttInputRegistersOldValues[x] = localArray[x]; - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.DoWork); - Thread thread = new Thread(pts); - thread.Start(x); - } - } - } - private void DoWork(Object parameter) - { - lock (modbusServer.lockMQTT) - { - //ToSend contains the Array elements to publish - int toSend = (int)parameter; - try - { - modbusServer.easyModbus2Mqtt.publish(modbusServer.MqttRootTopic + "/inputregisters" + toSend, localArray[toSend].ToString(), modbusServer.MqttBrokerAddress); - } - catch (Exception) { } - - Thread.Sleep(100); } } } @@ -2342,7 +2191,6 @@ private void DoWork(Object parameter) public class Coils { public bool[] localArray = new bool[65535]; - private bool[] mqttCoilsOldValues = new bool[65535]; ModbusServer modbusServer; public Coils(EasyModbus.ModbusServer modbusServer) @@ -2356,30 +2204,7 @@ public bool this[int x] set { this.localArray[x] = value; - if (modbusServer.MqttBrokerAddress != null) - if (localArray[x] != mqttCoilsOldValues[x]) - { - mqttCoilsOldValues[x] = localArray[x]; - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.DoWork); - Thread thread = new Thread(pts); - thread.Start(x); - } - } - } - - private void DoWork(Object parameter) - { - lock (modbusServer.lockMQTT) - { - //ToSend contains the Array elements to publish - int toSend = (int)parameter; - try - { - modbusServer.easyModbus2Mqtt.publish(modbusServer.MqttRootTopic + "/coils" + toSend, localArray[toSend].ToString(), modbusServer.MqttBrokerAddress); - } - catch (Exception) { } - - Thread.Sleep(100); + } } } @@ -2387,7 +2212,6 @@ private void DoWork(Object parameter) public class DiscreteInputs { public bool[] localArray = new bool[65535]; - private bool[] mqttDiscreteInputsOldValues = new bool[65535]; ModbusServer modbusServer; public DiscreteInputs(EasyModbus.ModbusServer modbusServer) @@ -2401,30 +2225,11 @@ public bool this[int x] set { this.localArray[x] = value; - if (modbusServer.MqttBrokerAddress != null) - if (localArray[x] != mqttDiscreteInputsOldValues[x]) - { - mqttDiscreteInputsOldValues[x] = localArray[x]; - ParameterizedThreadStart pts = new ParameterizedThreadStart(this.DoWork); - Thread thread = new Thread(pts); - thread.Start(x); - } + } } - private void DoWork(Object parameter) - { - lock (modbusServer.lockMQTT) - { - //ToSend contains the Array elements to publish - int toSend = (int)parameter; - try - { - modbusServer.easyModbus2Mqtt.publish(modbusServer.MqttRootTopic + "/discreteinputs" + toSend, localArray[toSend].ToString(), modbusServer.MqttBrokerAddress); - } - catch (Exception) { } - Thread.Sleep(100); - } + } } } diff --git a/EasyModbusAdvancedClient/EasyModbusAdvancedClient.csproj b/EasyModbusAdvancedClient/EasyModbusAdvancedClient.csproj index 5a1192c..77592b0 100644 --- a/EasyModbusAdvancedClient/EasyModbusAdvancedClient.csproj +++ b/EasyModbusAdvancedClient/EasyModbusAdvancedClient.csproj @@ -65,9 +65,6 @@ - - EasyModbus2Mqtt.cs - Exceptions\Exceptions.cs @@ -80,129 +77,6 @@ StoreLogData.cs - - M2Mqtt\Exceptions\MqttClientException.cs - - - M2Mqtt\Exceptions\MqttCommunicationException.cs - - - M2Mqtt\Exceptions\MqttConnectionException.cs - - - M2Mqtt\Exceptions\MqttTimeoutException.cs - - - M2Mqtt\IMqttNetworkChannel.cs - - - M2Mqtt\Internal\InternalEvent.cs - - - M2Mqtt\Internal\MsgInternalEvent.cs - - - M2Mqtt\Internal\MsgPublishedInternalEvent.cs - - - M2Mqtt\Messages\MqttMsgBase.cs - - - M2Mqtt\Messages\MqttMsgConnack.cs - - - M2Mqtt\Messages\MqttMsgConnect.cs - - - M2Mqtt\Messages\MqttMsgConnectEventArgs.cs - - - M2Mqtt\Messages\MqttMsgContext.cs - - - M2Mqtt\Messages\MqttMsgDisconnect.cs - - - M2Mqtt\Messages\MqttMsgPingReq.cs - - - M2Mqtt\Messages\MqttMsgPingResp.cs - - - M2Mqtt\Messages\MqttMsgPuback.cs - - - M2Mqtt\Messages\MqttMsgPubcomp.cs - - - M2Mqtt\Messages\MqttMsgPublish.cs - - - M2Mqtt\Messages\MqttMsgPublishedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPublishEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPubrec.cs - - - M2Mqtt\Messages\MqttMsgPubrel.cs - - - M2Mqtt\Messages\MqttMsgSuback.cs - - - M2Mqtt\Messages\MqttMsgSubscribe.cs - - - M2Mqtt\Messages\MqttMsgSubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgSubscribeEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsuback.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribe.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribeEventArgs.cs - - - M2Mqtt\MqttClient.cs - - - M2Mqtt\MqttSecurity.cs - - - M2Mqtt\MqttSettings.cs - - - M2Mqtt\Net\Fx.cs - - - M2Mqtt\Net\MqttNetworkChannel.cs - - - M2Mqtt\Session\MqttBrokerSession.cs - - - M2Mqtt\Session\MqttClientSession.cs - - - M2Mqtt\Session\MqttSession.cs - - - M2Mqtt\Utility\QueueExtension.cs - - - M2Mqtt\Utility\Trace.cs - Form diff --git a/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs b/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs index 9b018fc..4fae2f9 100644 --- a/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs +++ b/EasyModbusAdvancedClient/Properties/AssemblyInfo.cs @@ -14,7 +14,7 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stefan Rossmann Engineering Solutions")] [assembly: AssemblyProduct("EasyModbusAdvancedClient")] -[assembly: AssemblyCopyright("Copyright 2017")] +[assembly: AssemblyCopyright("Copyright 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("5.0.0")] +[assembly: AssemblyVersion("5.1.0")] diff --git a/EasyModbusClientExample/EasyModbusClientExample.csproj b/EasyModbusClientExample/EasyModbusClientExample.csproj index d2517f6..16d52ef 100644 --- a/EasyModbusClientExample/EasyModbusClientExample.csproj +++ b/EasyModbusClientExample/EasyModbusClientExample.csproj @@ -68,9 +68,6 @@ - - EasyModbus2Mqtt.cs - Exceptions\Exceptions.cs @@ -83,129 +80,6 @@ StoreLogData.cs - - M2Mqtt\Exceptions\MqttClientException.cs - - - M2Mqtt\Exceptions\MqttCommunicationException.cs - - - M2Mqtt\Exceptions\MqttConnectionException.cs - - - M2Mqtt\Exceptions\MqttTimeoutException.cs - - - M2Mqtt\IMqttNetworkChannel.cs - - - M2Mqtt\Internal\InternalEvent.cs - - - M2Mqtt\Internal\MsgInternalEvent.cs - - - M2Mqtt\Internal\MsgPublishedInternalEvent.cs - - - M2Mqtt\Messages\MqttMsgBase.cs - - - M2Mqtt\Messages\MqttMsgConnack.cs - - - M2Mqtt\Messages\MqttMsgConnect.cs - - - M2Mqtt\Messages\MqttMsgConnectEventArgs.cs - - - M2Mqtt\Messages\MqttMsgContext.cs - - - M2Mqtt\Messages\MqttMsgDisconnect.cs - - - M2Mqtt\Messages\MqttMsgPingReq.cs - - - M2Mqtt\Messages\MqttMsgPingResp.cs - - - M2Mqtt\Messages\MqttMsgPuback.cs - - - M2Mqtt\Messages\MqttMsgPubcomp.cs - - - M2Mqtt\Messages\MqttMsgPublish.cs - - - M2Mqtt\Messages\MqttMsgPublishedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPublishEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPubrec.cs - - - M2Mqtt\Messages\MqttMsgPubrel.cs - - - M2Mqtt\Messages\MqttMsgSuback.cs - - - M2Mqtt\Messages\MqttMsgSubscribe.cs - - - M2Mqtt\Messages\MqttMsgSubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgSubscribeEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsuback.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribe.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribeEventArgs.cs - - - M2Mqtt\MqttClient.cs - - - M2Mqtt\MqttSecurity.cs - - - M2Mqtt\MqttSettings.cs - - - M2Mqtt\Net\Fx.cs - - - M2Mqtt\Net\MqttNetworkChannel.cs - - - M2Mqtt\Session\MqttBrokerSession.cs - - - M2Mqtt\Session\MqttClientSession.cs - - - M2Mqtt\Session\MqttSession.cs - - - M2Mqtt\Utility\QueueExtension.cs - - - M2Mqtt\Utility\Trace.cs - Form diff --git a/EasyModbusClientExample/Properties/AssemblyInfo.cs b/EasyModbusClientExample/Properties/AssemblyInfo.cs index 9b080c3..ae9a9bf 100644 --- a/EasyModbusClientExample/Properties/AssemblyInfo.cs +++ b/EasyModbusClientExample/Properties/AssemblyInfo.cs @@ -14,7 +14,7 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stefan Rossmann Engineering Solutions")] [assembly: AssemblyProduct("EasyModbusClientExample")] -[assembly: AssemblyCopyright("Copyright 2017")] +[assembly: AssemblyCopyright("Copyright 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("5.0.0")] +[assembly: AssemblyVersion("5.1.0")] diff --git a/EasyModbusServerSimulator/EasyModbusServerSimulator.csproj b/EasyModbusServerSimulator/EasyModbusServerSimulator.csproj index be8c5a1..ea85d85 100644 --- a/EasyModbusServerSimulator/EasyModbusServerSimulator.csproj +++ b/EasyModbusServerSimulator/EasyModbusServerSimulator.csproj @@ -87,9 +87,6 @@ - - EasyModbus2Mqtt.cs - Exceptions\Exceptions.cs @@ -102,129 +99,6 @@ StoreLogData.cs - - M2Mqtt\Exceptions\MqttClientException.cs - - - M2Mqtt\Exceptions\MqttCommunicationException.cs - - - M2Mqtt\Exceptions\MqttConnectionException.cs - - - M2Mqtt\Exceptions\MqttTimeoutException.cs - - - M2Mqtt\IMqttNetworkChannel.cs - - - M2Mqtt\Internal\InternalEvent.cs - - - M2Mqtt\Internal\MsgInternalEvent.cs - - - M2Mqtt\Internal\MsgPublishedInternalEvent.cs - - - M2Mqtt\Messages\MqttMsgBase.cs - - - M2Mqtt\Messages\MqttMsgConnack.cs - - - M2Mqtt\Messages\MqttMsgConnect.cs - - - M2Mqtt\Messages\MqttMsgConnectEventArgs.cs - - - M2Mqtt\Messages\MqttMsgContext.cs - - - M2Mqtt\Messages\MqttMsgDisconnect.cs - - - M2Mqtt\Messages\MqttMsgPingReq.cs - - - M2Mqtt\Messages\MqttMsgPingResp.cs - - - M2Mqtt\Messages\MqttMsgPuback.cs - - - M2Mqtt\Messages\MqttMsgPubcomp.cs - - - M2Mqtt\Messages\MqttMsgPublish.cs - - - M2Mqtt\Messages\MqttMsgPublishedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPublishEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPubrec.cs - - - M2Mqtt\Messages\MqttMsgPubrel.cs - - - M2Mqtt\Messages\MqttMsgSuback.cs - - - M2Mqtt\Messages\MqttMsgSubscribe.cs - - - M2Mqtt\Messages\MqttMsgSubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgSubscribeEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsuback.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribe.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribeEventArgs.cs - - - M2Mqtt\MqttClient.cs - - - M2Mqtt\MqttSecurity.cs - - - M2Mqtt\MqttSettings.cs - - - M2Mqtt\Net\Fx.cs - - - M2Mqtt\Net\MqttNetworkChannel.cs - - - M2Mqtt\Session\MqttBrokerSession.cs - - - M2Mqtt\Session\MqttClientSession.cs - - - M2Mqtt\Session\MqttSession.cs - - - M2Mqtt\Utility\QueueExtension.cs - - - M2Mqtt\Utility\Trace.cs - Form diff --git a/EasyModbusServerSimulator/Info.Designer.cs b/EasyModbusServerSimulator/Info.Designer.cs index 2142799..0ba8034 100644 --- a/EasyModbusServerSimulator/Info.Designer.cs +++ b/EasyModbusServerSimulator/Info.Designer.cs @@ -73,7 +73,7 @@ private void InitializeComponent() this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(158, 13); this.label1.TabIndex = 15; - this.label1.Text = "(c) Rossmann-Engineering 2016"; + this.label1.Text = "(c) Rossmann-Engineering 2018"; this.label1.Click += new System.EventHandler(this.label1_Click); // // linkLabel2 diff --git a/EasyModbusServerSimulator/MainForm.Designer.cs b/EasyModbusServerSimulator/MainForm.Designer.cs index 8797938..839f621 100644 --- a/EasyModbusServerSimulator/MainForm.Designer.cs +++ b/EasyModbusServerSimulator/MainForm.Designer.cs @@ -87,9 +87,6 @@ private void InitializeComponent() this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.setupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.infoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.cbEnableWebView = new System.Windows.Forms.CheckBox(); - this.linkLabel2 = new System.Windows.Forms.LinkLabel(); - this.label6 = new System.Windows.Forms.Label(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); @@ -673,48 +670,11 @@ private void InitializeComponent() this.infoToolStripMenuItem.Text = "Info"; this.infoToolStripMenuItem.Click += new System.EventHandler(this.infoToolStripMenuItem_Click); // - // cbEnableWebView - // - this.cbEnableWebView.AutoSize = true; - this.cbEnableWebView.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.cbEnableWebView.Location = new System.Drawing.Point(335, 337); - this.cbEnableWebView.Name = "cbEnableWebView"; - this.cbEnableWebView.Size = new System.Drawing.Size(149, 20); - this.cbEnableWebView.TabIndex = 25; - this.cbEnableWebView.Text = "Enable Web View"; - this.cbEnableWebView.UseVisualStyleBackColor = true; - this.cbEnableWebView.CheckedChanged += new System.EventHandler(this.cbEnableWebView_CheckedChanged); - // - // linkLabel2 - // - this.linkLabel2.AutoSize = true; - this.linkLabel2.Location = new System.Drawing.Point(116, 547); - this.linkLabel2.Name = "linkLabel2"; - this.linkLabel2.Size = new System.Drawing.Size(55, 13); - this.linkLabel2.TabIndex = 26; - this.linkLabel2.TabStop = true; - this.linkLabel2.Text = "linkLabel2"; - this.linkLabel2.Visible = false; - this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked); - // - // label6 - // - this.label6.AutoSize = true; - this.label6.Location = new System.Drawing.Point(15, 547); - this.label6.Name = "label6"; - this.label6.Size = new System.Drawing.Size(95, 13); - this.label6.TabIndex = 27; - this.label6.Text = "Webview-address:"; - this.label6.Visible = false; - // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(897, 570); - this.Controls.Add(this.label6); - this.Controls.Add(this.linkLabel2); - this.Controls.Add(this.cbEnableWebView); this.Controls.Add(this.panel1); this.Controls.Add(this.checkBox10); this.Controls.Add(this.btnProperties); @@ -762,7 +722,7 @@ private void InitializeComponent() ((System.ComponentModel.ISupportInitialize)(this.form1BindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.easyModbusTCPServerBindingSource)).EndInit(); this.panel1.ResumeLayout(false); - // ((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit(); + //((System.ComponentModel.ISupportInitialize)(this.performanceCounter1)).EndInit(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); @@ -823,9 +783,6 @@ private void InitializeComponent() private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem setupToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem infoToolStripMenuItem; - private System.Windows.Forms.CheckBox cbEnableWebView; - private System.Windows.Forms.LinkLabel linkLabel2; - private System.Windows.Forms.Label label6; } } diff --git a/EasyModbusServerSimulator/MainForm.cs b/EasyModbusServerSimulator/MainForm.cs index 75f0635..78f6dc5 100644 --- a/EasyModbusServerSimulator/MainForm.cs +++ b/EasyModbusServerSimulator/MainForm.cs @@ -663,34 +663,6 @@ private void setupToolStripMenuItem_Click(object sender, EventArgs e) propertryForm.SettingsChangedEvent += new PropertyForm.settingsChangedEvent(SettingsChanged); propertryForm.Show(); } - int topic = 0; - private void cbEnableWebView_CheckedChanged(object sender, EventArgs e) - { - Random rnd = new Random(); - topic = rnd.Next(0, 99999); - easyModbusTCPServer.MqttRootTopic = "easymodbusserver/"+ topic; - if (cbEnableWebView.Checked) - { - easyModbusTCPServer.DeleteRetainedMessages(easyModbusTCPServer.MqttRootTopic); - easyModbusTCPServer.MqttBrokerAddress = "www.mqtt-dashboard.com"; - linkLabel2.Text = "http://www.easymodbustcp.net/webview/easymodbuswebview.html ?topic=" + topic; - linkLabel2.Visible = true; - label6.Visible = true; - - - } - - else - { - easyModbusTCPServer.MqttBrokerAddress = null; - linkLabel2.Visible = false; - label6.Visible = false; - } - } - private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - System.Diagnostics.Process.Start("http://www.easymodbustcp.net/webview/easymodbuswebview.html ?topic=" + topic); - } } } diff --git a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs index 0f0bc64..4620cdc 100644 --- a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs +++ b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs @@ -12,7 +12,7 @@ [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Stefan Rossmann Engineering Solutions")] [assembly: AssemblyProduct ("EasyModbusServerSimulator")] -[assembly: AssemblyCopyright ("Copyright 2017")] +[assembly: AssemblyCopyright ("Copyright 2018")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // This sets the default COM visibility of types in the assembly to invisible. @@ -24,4 +24,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion ("5.0.0")] +[assembly: AssemblyVersion ("5.1.0")] diff --git a/ServerApplication/Program.cs b/ServerApplication/Program.cs index 4b32d79..ca0c5bb 100644 --- a/ServerApplication/Program.cs +++ b/ServerApplication/Program.cs @@ -19,8 +19,6 @@ static void Main(string[] args) public void startServer() { EasyModbus.ModbusServer modbusServer = new EasyModbus.ModbusServer(); - modbusServer.MqttRootTopic = "examplemodbusserver"; - modbusServer.MqttBrokerAddress = "www.mqtt-dashboard.com"; modbusServer.Listen(); modbusServer.HoldingRegistersChanged += new EasyModbus.ModbusServer.HoldingRegistersChangedHandler(holdingRegistersChanged); Console.ReadKey(); From ac7f111b63de72f1a04e4a26775fedcb7f4af7bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Thu, 20 Sep 2018 18:59:24 +0200 Subject: [PATCH 009/114] MQTT removed --- EasyModbusTCPCore/ModbusServer.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/EasyModbusTCPCore/ModbusServer.cs b/EasyModbusTCPCore/ModbusServer.cs index 891435d..bd61a4b 100644 --- a/EasyModbusTCPCore/ModbusServer.cs +++ b/EasyModbusTCPCore/ModbusServer.cs @@ -254,7 +254,6 @@ public class ModbusServer public bool PortChanged { get; set; } object lockCoils = new object(); object lockHoldingRegisters = new object(); - internal object lockMQTT = new object(); private volatile bool shouldStop; @@ -1667,7 +1666,6 @@ public string LogFileFilename public class HoldingRegisters { public Int16[] localArray = new Int16[65535]; - private Int16[] mqttHoldingRegistersOldValues = new Int16[65535]; ModbusServer modbusServer; public HoldingRegisters(EasyModbus.ModbusServer modbusServer) @@ -1689,7 +1687,6 @@ public Int16 this[int x] public class InputRegisters { public Int16[] localArray = new Int16[65535]; - private Int16[] mqttInputRegistersOldValues = new Int16[65535]; ModbusServer modbusServer; public InputRegisters(EasyModbus.ModbusServer modbusServer) @@ -1712,7 +1709,6 @@ public Int16 this[int x] public class Coils { public bool[] localArray = new bool[65535]; - private bool[] mqttCoilsOldValues = new bool[65535]; ModbusServer modbusServer; public Coils(EasyModbus.ModbusServer modbusServer) @@ -1735,7 +1731,6 @@ public bool this[int x] public class DiscreteInputs { public bool[] localArray = new bool[65535]; - private bool[] mqttDiscreteInputsOldValues = new bool[65535]; ModbusServer modbusServer; public DiscreteInputs(EasyModbus.ModbusServer modbusServer) From c56fa7b435ccf05e61cf5b5eb173438454ee0d1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Ro=C3=9Fmann?= Date: Thu, 20 Sep 2018 22:10:15 +0200 Subject: [PATCH 010/114] MQTT --- ConsoleApplicationMqqt/App.config | 6 - .../ConsoleApplicationMqqt.csproj | 93 - ConsoleApplicationMqqt/Program.cs | 35 - .../Properties/AssemblyInfo.cs | 36 - MQTT/MQTT.sln | 22 - MQTT/MQTT/App.config | 6 - MQTT/MQTT/MQTT.csproj | 195 -- MQTT/MQTT/Program.cs | 24 - MQTT/MQTT/Properties/AssemblyInfo.cs | 36 - paho.mqtt.m2mqtt-master/.DS_Store | Bin 6148 -> 0 bytes paho.mqtt.m2mqtt-master/.gitignore | 196 -- paho.mqtt.m2mqtt-master/CONTRIBUTING.md | 87 - .../ConsoleApplication1/App.config | 6 - .../ConsoleApplication1/EasyModbus2Mqtt.cs | 226 -- .../ConsoleApplication1/Mqtt.csproj | 70 - .../ConsoleApplication1/Program.cs | 24 - .../Properties/AssemblyInfo.cs | 36 - paho.mqtt.m2mqtt-master/LICENSE | 204 -- paho.mqtt.m2mqtt-master/M2Mqtt.nuspec | 31 - paho.mqtt.m2mqtt-master/M2Mqtt.sln | 28 - .../M2Mqtt/Exceptions/MqttClientException.cs | 132 - .../Exceptions/MqttCommunicationException.cs | 42 - .../Exceptions/MqttConnectionException.cs | 31 - .../M2Mqtt/Exceptions/MqttTimeoutException.cs | 27 - .../M2Mqtt/IMqttNetworkChannel.cs | 69 - .../M2Mqtt/Internal/InternalEvent.cs | 25 - .../M2Mqtt/Internal/MsgInternalEvent.cs | 51 - .../Internal/MsgPublishedInternalEvent.cs | 53 - .../M2Mqtt/M2Mqtt.Mono.csproj | 80 - .../M2Mqtt/M2Mqtt.Net.csproj | 97 - .../M2Mqtt/M2Mqtt.NetCf35.csproj | 115 - .../M2Mqtt/M2Mqtt.NetCf39.csproj | 96 - .../M2Mqtt/M2Mqtt.NetMf42.csproj | 84 - .../M2Mqtt/M2Mqtt.NetMf43.csproj | 84 - .../M2Mqtt/M2Mqtt.WinRT.csproj | 97 - .../M2Mqtt/Messages/MqttMsgBase.cs | 275 -- .../M2Mqtt/Messages/MqttMsgConnack.cs | 191 -- .../M2Mqtt/Messages/MqttMsgConnect.cs | 582 ---- .../Messages/MqttMsgConnectEventArgs.cs | 44 - .../M2Mqtt/Messages/MqttMsgContext.cs | 159 - .../M2Mqtt/Messages/MqttMsgDisconnect.cs | 86 - .../M2Mqtt/Messages/MqttMsgPingReq.cs | 86 - .../M2Mqtt/Messages/MqttMsgPingResp.cs | 87 - .../M2Mqtt/Messages/MqttMsgPuback.cs | 125 - .../M2Mqtt/Messages/MqttMsgPubcomp.cs | 125 - .../M2Mqtt/Messages/MqttMsgPublish.cs | 277 -- .../Messages/MqttMsgPublishEventArgs.cs | 111 - .../Messages/MqttMsgPublishedEventArgs.cs | 78 - .../M2Mqtt/Messages/MqttMsgPubrec.cs | 125 - .../M2Mqtt/Messages/MqttMsgPubrel.cs | 142 - .../M2Mqtt/Messages/MqttMsgSuback.cs | 162 - .../M2Mqtt/Messages/MqttMsgSubscribe.cs | 272 -- .../Messages/MqttMsgSubscribeEventArgs.cs | 81 - .../Messages/MqttMsgSubscribedEventArgs.cs | 68 - .../M2Mqtt/Messages/MqttMsgUnsuback.cs | 126 - .../M2Mqtt/Messages/MqttMsgUnsubscribe.cs | 239 -- .../Messages/MqttMsgUnsubscribeEventArgs.cs | 68 - .../Messages/MqttMsgUnsubscribedEventArgs.cs | 55 - paho.mqtt.m2mqtt-master/M2Mqtt/MqttClient.cs | 2631 ----------------- .../M2Mqtt/MqttSecurity.cs | 30 - .../M2Mqtt/MqttSettings.cs | 104 - paho.mqtt.m2mqtt-master/M2Mqtt/Net/Fx.cs | 36 - .../M2Mqtt/Net/MqttNetworkChannel.cs | 470 --- .../M2Mqtt/Properties/AssemblyInfo.cs | 44 - .../M2Mqtt/Session/MqttBrokerSession.cs | 65 - .../M2Mqtt/Session/MqttClientSession.cs | 33 - .../M2Mqtt/Session/MqttSession.cs | 63 - .../M2Mqtt/Utility/QueueExtension.cs | 50 - .../M2Mqtt/Utility/Trace.cs | 86 - paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Fx.cs | 36 - .../M2Mqtt/WinRT/Hashtable.cs | 27 - .../M2Mqtt/WinRT/MqttNetworkChannel.cs | 179 -- paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Queue.cs | 27 - paho.mqtt.m2mqtt-master/M2MqttVS2008.sln | 20 - paho.mqtt.m2mqtt-master/README.md | 106 - paho.mqtt.m2mqtt-master/about.html | 28 - paho.mqtt.m2mqtt-master/build.cmd | 6 - paho.mqtt.m2mqtt-master/deleteme.txt | 0 paho.mqtt.m2mqtt-master/edl-v10 | 15 - paho.mqtt.m2mqtt-master/epl-v10 | 70 - .../images/M2Mqtt_Short_Logo.png | Bin 2951 -> 0 bytes paho.mqtt.m2mqtt-master/notice.html | 108 - 82 files changed, 10242 deletions(-) delete mode 100644 ConsoleApplicationMqqt/App.config delete mode 100644 ConsoleApplicationMqqt/ConsoleApplicationMqqt.csproj delete mode 100644 ConsoleApplicationMqqt/Program.cs delete mode 100644 ConsoleApplicationMqqt/Properties/AssemblyInfo.cs delete mode 100644 MQTT/MQTT.sln delete mode 100644 MQTT/MQTT/App.config delete mode 100644 MQTT/MQTT/MQTT.csproj delete mode 100644 MQTT/MQTT/Program.cs delete mode 100644 MQTT/MQTT/Properties/AssemblyInfo.cs delete mode 100644 paho.mqtt.m2mqtt-master/.DS_Store delete mode 100644 paho.mqtt.m2mqtt-master/.gitignore delete mode 100644 paho.mqtt.m2mqtt-master/CONTRIBUTING.md delete mode 100644 paho.mqtt.m2mqtt-master/ConsoleApplication1/App.config delete mode 100644 paho.mqtt.m2mqtt-master/ConsoleApplication1/EasyModbus2Mqtt.cs delete mode 100644 paho.mqtt.m2mqtt-master/ConsoleApplication1/Mqtt.csproj delete mode 100644 paho.mqtt.m2mqtt-master/ConsoleApplication1/Program.cs delete mode 100644 paho.mqtt.m2mqtt-master/ConsoleApplication1/Properties/AssemblyInfo.cs delete mode 100644 paho.mqtt.m2mqtt-master/LICENSE delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt.nuspec delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt.sln delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttClientException.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttCommunicationException.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttConnectionException.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttTimeoutException.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/IMqttNetworkChannel.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Internal/InternalEvent.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgInternalEvent.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgPublishedInternalEvent.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Mono.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Net.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf35.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf39.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf42.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf43.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.WinRT.csproj delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgBase.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnack.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnect.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnectEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgContext.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgDisconnect.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingReq.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingResp.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPuback.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubcomp.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublish.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishedEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrec.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrel.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSuback.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribe.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribeEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribedEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsuback.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribe.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribeEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribedEventArgs.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/MqttClient.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/MqttSecurity.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/MqttSettings.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Net/Fx.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Net/MqttNetworkChannel.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Properties/AssemblyInfo.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttBrokerSession.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttClientSession.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttSession.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Utility/QueueExtension.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/Utility/Trace.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Fx.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Hashtable.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/MqttNetworkChannel.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Queue.cs delete mode 100644 paho.mqtt.m2mqtt-master/M2MqttVS2008.sln delete mode 100644 paho.mqtt.m2mqtt-master/README.md delete mode 100644 paho.mqtt.m2mqtt-master/about.html delete mode 100644 paho.mqtt.m2mqtt-master/build.cmd delete mode 100644 paho.mqtt.m2mqtt-master/deleteme.txt delete mode 100644 paho.mqtt.m2mqtt-master/edl-v10 delete mode 100644 paho.mqtt.m2mqtt-master/epl-v10 delete mode 100644 paho.mqtt.m2mqtt-master/images/M2Mqtt_Short_Logo.png delete mode 100644 paho.mqtt.m2mqtt-master/notice.html diff --git a/ConsoleApplicationMqqt/App.config b/ConsoleApplicationMqqt/App.config deleted file mode 100644 index 88fa402..0000000 --- a/ConsoleApplicationMqqt/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/ConsoleApplicationMqqt/ConsoleApplicationMqqt.csproj b/ConsoleApplicationMqqt/ConsoleApplicationMqqt.csproj deleted file mode 100644 index debb5f6..0000000 --- a/ConsoleApplicationMqqt/ConsoleApplicationMqqt.csproj +++ /dev/null @@ -1,93 +0,0 @@ - - - - - Debug - AnyCPU - {F4A2D947-EAF7-4F1C-BDEA-8217BD96DB9D} - Exe - Properties - ConsoleApplicationMqqt - ConsoleApplicationMqqt - v4.5.2 - 512 - true - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - - - - - {7657fc4a-aedf-4f17-b3e9-0d0dfb1ce23b} - EasyModbus - - - - - False - Microsoft .NET Framework 4.5.2 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - - - - - \ No newline at end of file diff --git a/ConsoleApplicationMqqt/Program.cs b/ConsoleApplicationMqqt/Program.cs deleted file mode 100644 index 5133396..0000000 --- a/ConsoleApplicationMqqt/Program.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ConsoleApplicationMqqt -{ - class Program - { - static void Main(string[] args) - { - EasyModbus.EasyModbus2Mqtt easyModbus2Mqtt= new EasyModbus.EasyModbus2Mqtt(); - //easyModbus2Mqtt.AutomaticReconnect = false; - easyModbus2Mqtt.MqttUserName = "sr555"; - easyModbus2Mqtt.MqttPassword = "Ironsink51"; - easyModbus2Mqtt.MqttBrokerPort = 18972; - //easyModbus2Mqtt.MqttBrokerAddress = "broker.hivemq.com"; - //easyModbus2Mqtt.MqttBrokerAddress = "192.168.178.101"; - easyModbus2Mqtt.MqttBrokerAddress = "m21.cloudmqtt.com"; - easyModbus2Mqtt.ModbusIPAddress = "127.0.0.1"; - easyModbus2Mqtt.AddReadOrder(EasyModbus.FunctionCode.ReadCoils, 2, 0, 200, new string[] { "easymodbusclient/customtopic1", "easymodbusclient/customtopic2" }); - easyModbus2Mqtt.AddReadOrder(EasyModbus.FunctionCode.ReadInputRegisters, 2, 0, 200); - EasyModbus.ReadOrder readOrder = new EasyModbus.ReadOrder(); - readOrder.Hysteresis = new int[10] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; - readOrder.Unit = new string[10] {"°C", "°C", "°C", "°C", "°C", "°C", "°C", "°C", "°C", "°C"}; - readOrder.Scale = new float[10] { 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f }; - readOrder.Quantity = 10; - readOrder.StartingAddress = 10; - readOrder.FunctionCode = EasyModbus.FunctionCode.ReadHoldingRegisters; - easyModbus2Mqtt.AddReadOrder(readOrder); - easyModbus2Mqtt.start(); - } - } -} diff --git a/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs b/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs deleted file mode 100644 index 0ee6b27..0000000 --- a/ConsoleApplicationMqqt/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ConsoleApplicationMqqt")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ConsoleApplicationMqqt")] -[assembly: AssemblyCopyright("Copyright…–––––––––––– © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("f4a2d947-eaf7-4f1c-bdea-8217bd96db9d")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MQTT/MQTT.sln b/MQTT/MQTT.sln deleted file mode 100644 index 173842d..0000000 --- a/MQTT/MQTT.sln +++ /dev/null @@ -1,22 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTT", "MQTT\MQTT.csproj", "{613A173A-77E1-46A1-9668-93A67BD558D5}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {613A173A-77E1-46A1-9668-93A67BD558D5}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/MQTT/MQTT/App.config b/MQTT/MQTT/App.config deleted file mode 100644 index 88fa402..0000000 --- a/MQTT/MQTT/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/MQTT/MQTT/MQTT.csproj b/MQTT/MQTT/MQTT.csproj deleted file mode 100644 index 8c8576d..0000000 --- a/MQTT/MQTT/MQTT.csproj +++ /dev/null @@ -1,195 +0,0 @@ - - - - - Debug - AnyCPU - {613A173A-77E1-46A1-9668-93A67BD558D5} - Exe - Properties - ConsoleApplication1 - ConsoleApplication1 - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - TRACE;DEBUG;SSL - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - EasyModbus2Mqtt.cs - - - Exceptions\Exceptions.cs - - - ModbusClient.cs - - - StoreLogData.cs - - - M2Mqtt\Exceptions\MqttClientException.cs - - - M2Mqtt\Exceptions\MqttCommunicationException.cs - - - M2Mqtt\Exceptions\MqttConnectionException.cs - - - M2Mqtt\Exceptions\MqttTimeoutException.cs - - - M2Mqtt\IMqttNetworkChannel.cs - - - M2Mqtt\Internal\InternalEvent.cs - - - M2Mqtt\Internal\MsgInternalEvent.cs - - - M2Mqtt\Internal\MsgPublishedInternalEvent.cs - - - M2Mqtt\Messages\MqttMsgBase.cs - - - M2Mqtt\Messages\MqttMsgConnack.cs - - - M2Mqtt\Messages\MqttMsgConnect.cs - - - M2Mqtt\Messages\MqttMsgConnectEventArgs.cs - - - M2Mqtt\Messages\MqttMsgContext.cs - - - M2Mqtt\Messages\MqttMsgDisconnect.cs - - - M2Mqtt\Messages\MqttMsgPingReq.cs - - - M2Mqtt\Messages\MqttMsgPingResp.cs - - - M2Mqtt\Messages\MqttMsgPuback.cs - - - M2Mqtt\Messages\MqttMsgPubcomp.cs - - - M2Mqtt\Messages\MqttMsgPublish.cs - - - M2Mqtt\Messages\MqttMsgPublishedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPublishEventArgs.cs - - - M2Mqtt\Messages\MqttMsgPubrec.cs - - - M2Mqtt\Messages\MqttMsgPubrel.cs - - - M2Mqtt\Messages\MqttMsgSuback.cs - - - M2Mqtt\Messages\MqttMsgSubscribe.cs - - - M2Mqtt\Messages\MqttMsgSubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgSubscribeEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsuback.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribe.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribedEventArgs.cs - - - M2Mqtt\Messages\MqttMsgUnsubscribeEventArgs.cs - - - M2Mqtt\MqttClient.cs - - - M2Mqtt\MqttSecurity.cs - - - M2Mqtt\MqttSettings.cs - - - M2Mqtt\Net\Fx.cs - - - M2Mqtt\Net\MqttNetworkChannel.cs - - - M2Mqtt\Session\MqttBrokerSession.cs - - - M2Mqtt\Session\MqttClientSession.cs - - - M2Mqtt\Session\MqttSession.cs - - - M2Mqtt\Utility\QueueExtension.cs - - - M2Mqtt\Utility\Trace.cs - - - - - - - - - - \ No newline at end of file diff --git a/MQTT/MQTT/Program.cs b/MQTT/MQTT/Program.cs deleted file mode 100644 index 6a5b0b6..0000000 --- a/MQTT/MQTT/Program.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EasyModbus; - -namespace Mqtt -{ - class Program - { - static void Main(string[] args) - { - EasyModbus2Mqtt easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerAddress = "www.mqtt-dashboard.com"; - easyModbus2Mqtt.IPAddress = "127.0.0.1"; - easyModbus2Mqtt.AddReadOrder(FunctionCode.ReadCoils, 10, 0, 500); - easyModbus2Mqtt.AddReadOrder(FunctionCode.ReadHoldingRegisters, 10, 0, 500); - easyModbus2Mqtt.start(); - - - } - } -} diff --git a/MQTT/MQTT/Properties/AssemblyInfo.cs b/MQTT/MQTT/Properties/AssemblyInfo.cs deleted file mode 100644 index 95c464d..0000000 --- a/MQTT/MQTT/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("MQTT")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("MQTT")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("613a173a-77e1-46a1-9668-93a67bd558d5")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/paho.mqtt.m2mqtt-master/.DS_Store b/paho.mqtt.m2mqtt-master/.DS_Store deleted file mode 100644 index 2a937ed64b3579f58753d2f20fe64f3fdbf855ef..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%We}f6g^I(v`q@llI1Mf6t!8g9Fj~?Bpy;*SR%+n5R_z6WrA4FXY`}^fPO&# z1J1RrYV1kX9YW~d$UYwX9^biV#^V@(>2IfJKo`IPi(s?OYKO_Vl$tes&r_nYa};=i zZz!o+uPGpFw~a3tBgd92_kR737Wrhn$j2O)kHb03^WWCk0uIU8V$O9w zC1=7FKaCi_BE~TWc#n6u!Uaa?;{#hGUcV;4#x@rb`-pL7j5gyv&gefQtH4hbVN`P) z@%HICCGP}3aE8;+yYXp<_xeHayU4r6{Fl`3D`RZJnfJa&zWaE?YzN4g@g=g*+p2q0 zQMZM+=&@Wg$0$RHu2tVBRbQ&I;&a(x&3l@JQLLs_W;Cn+({Ncm+$i|;gjE&Cu6YCC>I@DSfPz6E-_S|Jx_W$hR^M6RvD^)-h z_^%W&&Ee&+&y@V$T1!s$+JxmZi@git.eclipse.org:29418/paho/org.eclipse.paho.mqtt.m2mqtt -- https://@git.eclipse.org/r/paho/org.eclipse.paho.mqtt.m2mqtt - -A [web browsable repository](http://git.eclipse.org/c/paho/org.eclipse.paho.mqtt.m2mqtt.git) is available. - -Contributing a patch --------------------- - -The Paho repositories are accessed through Gerrit, the code review -project, which makes it possible for anybody to clone the repository, make -changes and push them back for review and eventual acceptance into the project. - -To do this, you must follow a few steps. The first of these are described at - -- [Contributing via git](https://wiki.eclipse.org/Development_Resources/Contributing_via_Git) - -* Sign the Eclipse CLA -* Use a valid commit record, including a signed-off-by entry. - -There are further details at - -- [Handling Git Contributions](https://wiki.eclipse.org/Development_Resources/Handling_Git_Contributions) - -Once the patch is pushed back to Gerrit, the project committers will be -informed and they will undertake a review of the code. The patch may need -modifying for some reason. In order to make amending commits more -straightforward, the steps at -https://git.eclipse.org/r/Documentation/cmd-hook-commit-msg.html should be -followed. This automatically inserts a "Change-Id" entry to your commit message -which allows you to amend commits and have Gerrit track them as the same -change. - -What happens next depends on the content of the patch. If it is 100% authored -by the contributor and is less than 1000 lines (and meets the needs of the -project), then it can be committed to the main repository. If not, more steps -are required. These are detailed in the -[legal process poster](http://www.eclipse.org/legal/EclipseLegalProcessPoster.pdf). - - -Developer resources: --------------------- - -Information regarding source code management, builds, coding standards, and more. - -- [https://projects.eclipse.org/projects/iot.paho/developer](https://projects.eclipse.org/projects/iot.paho/developer) - -Contributor License Agreement: ------------------------------- - -Before your contribution can be accepted by the project, you need to create and electronically sign the Eclipse Foundation [Contributor License Agreement (CLA)](http://www.eclipse.org/legal/CLA.php). - -Contact: --------- - -Contact the project developers via the project's development -[mailing list](https://dev.eclipse.org/mailman/listinfo/paho-dev). - -Search for bugs: ----------------- - -This project uses [Bugzilla](https://bugs.eclipse.org/bugs/buglist.cgi?product=Paho) to track ongoing development and issues. - -Create a new bug: ------------------ - -Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! - -- [Create new Paho bug](https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Paho) diff --git a/paho.mqtt.m2mqtt-master/ConsoleApplication1/App.config b/paho.mqtt.m2mqtt-master/ConsoleApplication1/App.config deleted file mode 100644 index 88fa402..0000000 --- a/paho.mqtt.m2mqtt-master/ConsoleApplication1/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/ConsoleApplication1/EasyModbus2Mqtt.cs b/paho.mqtt.m2mqtt-master/ConsoleApplication1/EasyModbus2Mqtt.cs deleted file mode 100644 index ad210f0..0000000 --- a/paho.mqtt.m2mqtt-master/ConsoleApplication1/EasyModbus2Mqtt.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using uPLibrary.Networking.M2Mqtt.Messages; - -namespace Mqtt -{ - - class EasyModbus2Mqtt : EasyModbus.ModbusClient - { - List readOrders = new List(); - string mqttBrokerAddress; - string mqttRootTopic = "easymodbusclient"; - uPLibrary.Networking.M2Mqtt.MqttClient mqttClient; - - public EasyModbus2Mqtt() - { - } - - public void AddReadOrder(ReadOrder readOrder) - { - if (readOrder.FunctionCode == 0) - throw new ArgumentOutOfRangeException("FunctionCode must be initialized"); - if (readOrder.Quantity == 0) - throw new ArgumentOutOfRangeException("Quantity cannot be 0"); - if (readOrder.CylceTime == 0) - readOrder.CylceTime = 500; - if (readOrder.Topic == null) - { - readOrder.Topic = new string[readOrder.Quantity]; - for (int i = 0; i < readOrder.Quantity; i++) - { - if (readOrder.FunctionCode == FunctionCode.ReadCoils) - { - readOrder.Topic[i] = mqttRootTopic+"/coils/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) - { - readOrder.Topic[i] = mqttRootTopic+"/discreteinputs/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) - { - readOrder.Topic[i] = mqttRootTopic+"/holdingregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) - { - readOrder.Topic[i] = mqttRootTopic+"/inputregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - } - } - readOrders.Add(readOrder); - } - - public void AddReadOrder(FunctionCode functionCode, int quantity, int startingAddress, int cycleTime) - { - ReadOrder readOrder = new ReadOrder(); - readOrder.CylceTime = cycleTime; - readOrder.FunctionCode = functionCode; - readOrder.Quantity = quantity; - readOrder.StartingAddress = startingAddress; - readOrder.Topic = new string[quantity]; - readOrder.oldvalue = new object[quantity]; - for (int i = 0; i < quantity; i++) - { - if (functionCode == FunctionCode.ReadCoils) - { - readOrder.Topic[i] = mqttRootTopic+ "/coils/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadDiscreteInputs) - { - readOrder.Topic[i] = mqttRootTopic + "/discreteinputs/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadHoldingRegisters) - { - readOrder.Topic[i] = mqttRootTopic + "/holdingregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - if (functionCode == FunctionCode.ReadInputRegisters) - { - readOrder.Topic[i] = mqttRootTopic + "/inputregisters/" + (i + readOrder.StartingAddress).ToString(); - - } - } - readOrders.Add(readOrder); - } - - public void start() - { - this.shouldStop = false; - if (mqttBrokerAddress == null) - throw new ArgumentOutOfRangeException("Mqtt Broker Address not initialized"); - if (!this.Connected) - this.Connect(); - mqttClient = new uPLibrary.Networking.M2Mqtt.MqttClient(mqttBrokerAddress); - string clientID = new Guid().ToString(); - mqttClient.Connect(clientID); - for (int i = 0; i < readOrders.Count; i++) - { - readOrders[i].thread = new System.Threading.Thread(new ParameterizedThreadStart(ProcessData)); - readOrders[i].thread.Start(readOrders[i]); - } - } - - public void stop() - { - this.Disconnect(); - mqttClient.Disconnect(); - this.shouldStop = true; - } - - private volatile bool shouldStop; - private void ProcessData(object param) - { - while (!shouldStop) - { - ReadOrder readOrder = (ReadOrder)param; - if (readOrder.FunctionCode == FunctionCode.ReadCoils) - { - bool[] value = this.ReadCoils(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()) , MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - else if ((bool)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - readOrder.oldvalue[i] = value[i]; - } - - } - if (readOrder.FunctionCode == FunctionCode.ReadDiscreteInputs) - { - bool[] value = this.ReadDiscreteInputs(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - else if ((bool)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - readOrder.oldvalue[i] = value[i]; - } - } - if (readOrder.FunctionCode == FunctionCode.ReadHoldingRegisters) - { - int[] value = this.ReadHoldingRegisters(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - else if ((int)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - readOrder.oldvalue[i] = value[i]; - } - } - - if (readOrder.FunctionCode == FunctionCode.ReadInputRegisters) - { - int[] value = this.ReadInputRegisters(readOrder.StartingAddress, readOrder.Quantity); - for (int i = 0; i < value.Length; i++) - { - if (readOrder.oldvalue[i] == null) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - else if ((int)readOrder.oldvalue[i] != value[i]) - mqttClient.Publish(readOrder.Topic[i], Encoding.UTF8.GetBytes(value[i].ToString()), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - readOrder.oldvalue[i] = value[i]; - } - } - System.Threading.Thread.Sleep(readOrder.CylceTime); - } - } - - - public string MqttBrokerAddress - { - get - { - return this.mqttBrokerAddress; - } - set - { - this.mqttBrokerAddress = value; - } - } - - public string MqttRootTopic - { - get - { - return this.mqttRootTopic; - } - set - { - this.mqttRootTopic = value; - } - } - - } - - public class ReadOrder - { - public FunctionCode FunctionCode; //Function Code to execute - public int CylceTime = 500; //Polling intervall in ms - public int StartingAddress; //First Modbus Register to Read (0-based) - public int Quantity; - public string[] Topic; //Symbolnames can by replaced, by default we Push to the topic e.g. for Coils: /modbusclient/coils/1 - internal System.Threading.Thread thread; - internal object[] oldvalue; - } - - public enum FunctionCode - { - ReadDiscreteInputs = 2, - ReadCoils = 1, - ReadHoldingRegisters = 3, - ReadInputRegisters = 4 - } - -} diff --git a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Mqtt.csproj b/paho.mqtt.m2mqtt-master/ConsoleApplication1/Mqtt.csproj deleted file mode 100644 index ad584b4..0000000 --- a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Mqtt.csproj +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Debug - AnyCPU - {A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90} - Exe - Properties - ConsoleApplication1 - ConsoleApplication1 - v4.5.2 - 512 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\..\..\..\..\Downloads\EasyModbusLibrary for .NET (DLL)\EasyModbus.dll - - - - - - - - - - - - - - - - - - - - - {a11aef5a-b246-4fe8-8330-06db73cc8074} - M2Mqtt.Net - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Program.cs b/paho.mqtt.m2mqtt-master/ConsoleApplication1/Program.cs deleted file mode 100644 index 6a5b0b6..0000000 --- a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Program.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using EasyModbus; - -namespace Mqtt -{ - class Program - { - static void Main(string[] args) - { - EasyModbus2Mqtt easyModbus2Mqtt = new EasyModbus2Mqtt(); - easyModbus2Mqtt.MqttBrokerAddress = "www.mqtt-dashboard.com"; - easyModbus2Mqtt.IPAddress = "127.0.0.1"; - easyModbus2Mqtt.AddReadOrder(FunctionCode.ReadCoils, 10, 0, 500); - easyModbus2Mqtt.AddReadOrder(FunctionCode.ReadHoldingRegisters, 10, 0, 500); - easyModbus2Mqtt.start(); - - - } - } -} diff --git a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Properties/AssemblyInfo.cs b/paho.mqtt.m2mqtt-master/ConsoleApplication1/Properties/AssemblyInfo.cs deleted file mode 100644 index 34ae283..0000000 --- a/paho.mqtt.m2mqtt-master/ConsoleApplication1/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ConsoleApplication1")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ConsoleApplication1")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("a4cbee7d-43e9-4897-a68c-c2d1a52bac90")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/paho.mqtt.m2mqtt-master/LICENSE b/paho.mqtt.m2mqtt-master/LICENSE deleted file mode 100644 index 3260e4f..0000000 --- a/paho.mqtt.m2mqtt-master/LICENSE +++ /dev/null @@ -1,204 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC -LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM -CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and -b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' - from a Contributor if it was added to the Program by such Contributor - itself or anyone acting on such Contributor's behalf. Contributions do not - include additions to the Program which: (i) are separate modules of - software distributed in conjunction with the Program under their own - license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are -necessarily infringed by the use or sale of its Contribution alone or when -combined with the Program. - -"Program" means the Contributions distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, -including all Contributors. - -2. GRANT OF RIGHTS - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly - perform, distribute and sublicense the Contribution of such Contributor, - if any, and such derivative works, in source code and object code form. - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under - Licensed Patents to make, use, sell, offer to sell, import and otherwise - transfer the Contribution of such Contributor, if any, in source code and - object code form. This patent license shall apply to the combination of - the Contribution and the Program if, at the time the Contribution is - added by the Contributor, such addition of the Contribution causes such - combination to be covered by the Licensed Patents. The patent license - shall not apply to any other combinations which include the Contribution. - No hardware per se is licensed hereunder. - c) Recipient understands that although each Contributor grants the licenses - to its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other - intellectual property rights of any other entity. Each Contributor - disclaims any liability to Recipient for claims brought by any other - entity based on infringement of intellectual property rights or - otherwise. As a condition to exercising the rights and licenses granted - hereunder, each Recipient hereby assumes sole responsibility to secure - any other intellectual property rights needed, if any. For example, if a - third party patent license is required to allow Recipient to distribute - the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - d) Each Contributor represents that to its knowledge it has sufficient - copyright rights in its Contribution, if any, to grant the copyright - license set forth in this Agreement. - -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under -its own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - b) its license agreement: - i) effectively disclaims on behalf of all Contributors all warranties - and conditions, express and implied, including warranties or - conditions of title and non-infringement, and implied warranties or - conditions of merchantability and fitness for a particular purpose; - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and - consequential damages, such as lost profits; - iii) states that any provisions which differ from this Agreement are - offered by that Contributor alone and not by any other party; and - iv) states that source code for the Program is available from such - Contributor, and informs licensees how to obtain it in a reasonable - manner on or through a medium customarily used for software exchange. - -When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - b) a copy of this Agreement must be included with each copy of the Program. - Contributors may not remove or alter any copyright notices contained - within the Program. - -Each Contributor must identify itself as the originator of its Contribution, -if -any, in a manner that reasonably allows subsequent Recipients to identify the -originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with -respect to end users, business partners and the like. While this license is -intended to facilitate the commercial use of the Program, the Contributor who -includes the Program in a commercial product offering should do so in a manner -which does not create potential liability for other Contributors. Therefore, -if a Contributor includes the Program in a commercial product offering, such -Contributor ("Commercial Contributor") hereby agrees to defend and indemnify -every other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits and -other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such Commercial -Contributor in connection with its distribution of the Program in a commercial -product offering. The obligations in this section do not apply to any claims -or Losses relating to any actual or alleged intellectual property -infringement. In order to qualify, an Indemnified Contributor must: -a) promptly notify the Commercial Contributor in writing of such claim, and -b) allow the Commercial Contributor to control, and cooperate with the -Commercial Contributor in, the defense and any related settlement -negotiations. The Indemnified Contributor may participate in any such claim at -its own expense. - -For example, a Contributor might include the Program in a commercial product -offering, Product X. That Contributor is then a Commercial Contributor. If -that Commercial Contributor then makes performance claims, or offers -warranties related to Product X, those performance claims and warranties are -such Commercial Contributor's responsibility alone. Under this section, the -Commercial Contributor would have to defend claims against the other -Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, -NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each -Recipient is solely responsible for determining the appropriateness of using -and distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to the -risks and costs of program errors, compliance with applicable laws, damage to -or loss of data, programs or equipment, and unavailability or interruption of -operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY -CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION -LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of the -remainder of the terms of this Agreement, and without further action by the -parties hereto, such provision shall be reformed to the minimum extent -necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Program itself -(excluding combinations of the Program with other software or hardware) -infringes such Recipient's patent(s), then such Recipient's rights granted -under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to -comply with any of the material terms or conditions of this Agreement and does -not cure such failure in a reasonable period of time after becoming aware of -such noncompliance. If all Recipient's rights under this Agreement terminate, -Recipient agrees to cease use and distribution of the Program as soon as -reasonably practicable. However, Recipient's obligations under this Agreement -and any licenses granted by Recipient relating to the Program shall continue -and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in -order to avoid inconsistency the Agreement is copyrighted and may only be -modified in the following manner. The Agreement Steward reserves the right to -publish new versions (including revisions) of this Agreement from time to -time. No one other than the Agreement Steward has the right to modify this -Agreement. The Eclipse Foundation is the initial Agreement Steward. The -Eclipse Foundation may assign the responsibility to serve as the Agreement -Steward to a suitable separate entity. Each new version of the Agreement will -be given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version of the -Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly -stated in Sections 2(a) and 2(b) above, Recipient receives no rights or -licenses to the intellectual property of any Contributor under this Agreement, -whether expressly, by implication, estoppel or otherwise. All rights in the -Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the -intellectual property laws of the United States of America. No party to this -Agreement will bring a legal action under this Agreement more than one year -after the cause of action arose. Each party waives its rights to a jury trial in -any resulting litigation. - diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt.nuspec b/paho.mqtt.m2mqtt-master/M2Mqtt.nuspec deleted file mode 100644 index f078b02..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt.nuspec +++ /dev/null @@ -1,31 +0,0 @@ - - - - M2Mqtt - 4.3.0.0 - M2Mqtt - MQTT Client Library for .Net and WinRT - Paolo Patierno - Paolo Patierno - https://github.com/ppatierno/m2mqtt/blob/master/LICENSE - https://github.com/ppatierno/m2mqtt - https://raw.githubusercontent.com/ppatierno/m2mqtt/master/images/M2Mqtt_Short_Logo.png - false - M2Mqtt is a MQTT client available for all .Net platform (.Net Framework, .Net Compact Framework and .Net Micro Framework) and WinRT platform (Windows 8.1 and Windows Phone 8.1) for M2M communication. - M2Mqtt is a MQTT client available for all .Net platform (.Net Framework, .Net Compact Framework and .Net Micro Framework) and WinRT platform (Windows 8.1 and Windows Phone 8.1) for M2M communication. - Added SSL/TLS client authentication - Paolo Patierno Copyright 2015 - m2m mqtt queue messaging internetofthings iot cloud netmf embedded micro netduino micro-framework hardware winrt windows8 windows8.1 windowsphone windowsphone8.1 gadgeteer - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt.sln b/paho.mqtt.m2mqtt-master/M2Mqtt.sln deleted file mode 100644 index d975c3f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.25420.1 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "M2Mqtt.Net", "M2Mqtt\M2Mqtt.Net.csproj", "{A11AEF5A-B246-4FE8-8330-06DB73CC8074}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mqtt", "ConsoleApplication1\Mqtt.csproj", "{A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A11AEF5A-B246-4FE8-8330-06DB73CC8074}.Release|Any CPU.Build.0 = Release|Any CPU - {A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A4CBEE7D-43E9-4897-A68C-C2D1A52BAC90}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttClientException.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttClientException.cs deleted file mode 100644 index cd8303f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttClientException.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; - -namespace uPLibrary.Networking.M2Mqtt.Exceptions -{ - /// - /// MQTT client exception - /// - public class MqttClientException : Exception - { - /// - /// Constructor - /// - /// Error code - public MqttClientException(MqttClientErrorCode errorCode) - { - this.errorCode = errorCode; - } - - // error code - private MqttClientErrorCode errorCode; - - /// - /// Error code - /// - public MqttClientErrorCode ErrorCode - { - get { return this.errorCode; } - set { this.errorCode = value; } - } - } - - /// - /// MQTT client erroro code - /// - public enum MqttClientErrorCode - { - /// - /// Will error (topic, message or QoS level) - /// - WillWrong = 1, - - /// - /// Keep alive period too large - /// - KeepAliveWrong, - - /// - /// Topic contains wildcards - /// - TopicWildcard, - - /// - /// Topic length wrong - /// - TopicLength, - - /// - /// QoS level not allowed - /// - QosNotAllowed, - - /// - /// Topics list empty for subscribe - /// - TopicsEmpty, - - /// - /// Qos levels list empty for subscribe - /// - QosLevelsEmpty, - - /// - /// Topics / Qos Levels not match in subscribe - /// - TopicsQosLevelsNotMatch, - - /// - /// Wrong message from broker - /// - WrongBrokerMessage, - - /// - /// Wrong Message Id - /// - WrongMessageId, - - /// - /// Inflight queue is full - /// - InflightQueueFull, - - // [v3.1.1] - /// - /// Invalid flag bits received - /// - InvalidFlagBits, - - // [v3.1.1] - /// - /// Invalid connect flags received - /// - InvalidConnectFlags, - - // [v3.1.1] - /// - /// Invalid client id - /// - InvalidClientId, - - // [v3.1.1] - /// - /// Invalid protocol name - /// - InvalidProtocolName - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttCommunicationException.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttCommunicationException.cs deleted file mode 100644 index 6b916cc..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttCommunicationException.cs +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; - -namespace uPLibrary.Networking.M2Mqtt.Exceptions -{ - /// - /// Exception due to error communication with broker on socket - /// - public class MqttCommunicationException : Exception - { - /// - /// Default constructor - /// - public MqttCommunicationException() - { - } - - /// - /// Constructor - /// - /// Inner Exception - public MqttCommunicationException(Exception e) - : base(String.Empty, e) - { - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttConnectionException.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttConnectionException.cs deleted file mode 100644 index 3203c7e..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttConnectionException.cs +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; - -namespace uPLibrary.Networking.M2Mqtt.Exceptions -{ - /// - /// Connection to the broker exception - /// - public class MqttConnectionException : Exception - { - public MqttConnectionException(string message, Exception innerException) - : base(message, innerException) - { - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttTimeoutException.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttTimeoutException.cs deleted file mode 100644 index b15e69e..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Exceptions/MqttTimeoutException.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; - -namespace uPLibrary.Networking.M2Mqtt.Exceptions -{ - /// - /// Timeout on receiving from broker exception - /// - public class MqttTimeoutException : Exception - { - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/IMqttNetworkChannel.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/IMqttNetworkChannel.cs deleted file mode 100644 index f4ff90f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/IMqttNetworkChannel.cs +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Text; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Interface for channel under MQTT library - /// - public interface IMqttNetworkChannel - { - /// - /// Data available on channel - /// - bool DataAvailable { get; } - - /// - /// Receive data from the network channel - /// - /// Data buffer for receiving data - /// Number of bytes received - int Receive(byte[] buffer); - - /// - /// Receive data from the network channel with a specified timeout - /// - /// Data buffer for receiving data - /// Timeout on receiving (in milliseconds) - /// Number of bytes received - int Receive(byte[] buffer, int timeout); - - /// - /// Send data on the network channel to the broker - /// - /// Data buffer to send - /// Number of byte sent - int Send(byte[] buffer); - - /// - /// Close the network channel - /// - void Close(); - - /// - /// Connect to remote server - /// - void Connect(); - - /// - /// Accept client connection - /// - void Accept(); - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/InternalEvent.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/InternalEvent.cs deleted file mode 100644 index 7f298c7..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/InternalEvent.cs +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -namespace uPLibrary.Networking.M2Mqtt.Internal -{ - /// - /// Generic internal event for dispatching - /// - public abstract class InternalEvent - { - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgInternalEvent.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgInternalEvent.cs deleted file mode 100644 index 8cf46a4..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgInternalEvent.cs +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Messages; - -namespace uPLibrary.Networking.M2Mqtt.Internal -{ - /// - /// Internal event with a message - /// - public class MsgInternalEvent : InternalEvent - { - #region Properties ... - - /// - /// Related message - /// - public MqttMsgBase Message - { - get { return this.msg; } - set { this.msg = value; } - } - - #endregion - - // related message - protected MqttMsgBase msg; - - /// - /// Constructor - /// - /// Related message - public MsgInternalEvent(MqttMsgBase msg) - { - this.msg = msg; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgPublishedInternalEvent.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgPublishedInternalEvent.cs deleted file mode 100644 index 5a7f182..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Internal/MsgPublishedInternalEvent.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Messages; - -namespace uPLibrary.Networking.M2Mqtt.Internal -{ - /// - /// Internal event for a published message - /// - public class MsgPublishedInternalEvent : MsgInternalEvent - { - #region Properties... - - /// - /// Message published (or failed due to retries) - /// - public bool IsPublished - { - get { return this.isPublished; } - internal set { this.isPublished = value; } - } - - #endregion - - // published flag - bool isPublished; - - /// - /// Constructor - /// - /// Message published - /// Publish flag - public MsgPublishedInternalEvent(MqttMsgBase msg, bool isPublished) - : base(msg) - { - this.isPublished = isPublished; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Mono.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Mono.csproj deleted file mode 100644 index eac5f12..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Mono.csproj +++ /dev/null @@ -1,80 +0,0 @@ - - - - Debug - AnyCPU - 10.0.0 - 2.0 - {9B706DEC-4CE7-4764-BDBE-8A5F855E5857} - Library - uPLibrary.Networking.M2Mqtt - M2Mqtt.Mono - - - true - full - false - ..\bin\Debug\M2Mqtt.Mono - DEBUG;SSL - prompt - 4 - false - - - none - false - ..\bin\Release\M2Mqtt.Mono - prompt - 4 - false - SSL - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Net.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Net.csproj deleted file mode 100644 index 1008ea6..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.Net.csproj +++ /dev/null @@ -1,97 +0,0 @@ - - - - Debug - AnyCPU - 8.0.30703 - 2.0 - {A11AEF5A-B246-4FE8-8330-06DB73CC8074} - Library - Properties - uPLibrary.Networking.M2Mqtt - M2Mqtt.Net - v4.0 - 512 - - - - true - full - false - ..\bin\Debug\M2Mqtt.Net - TRACE;DEBUG;SSL - prompt - 4 - false - - - pdbonly - true - ..\bin\Release\M2Mqtt.Net - TRACE;SSL - prompt - 4 - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf35.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf35.csproj deleted file mode 100644 index a032243..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf35.csproj +++ /dev/null @@ -1,115 +0,0 @@ - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {194FEA1B-E67F-4FC0-AC47-CD71F7F060CC} - Library - Properties - uPLibrary.Networking.M2Mqtt - M2Mqtt.NetCf35 - {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - WindowsCE - E2BECB1F-8C8C-41ba-B736-9BE7D946A398 - 5.0 - M2MqttNetCf35 - v3.5 - Windows CE - - - - - true - full - false - ..\bin\Debug\M2Mqtt.NetCf35\ - TRACE;DEBUG;WindowsCE,COMPACT_FRAMEWORK - true - true - prompt - 512 - 4 - Off - - - pdbonly - true - ..\bin\Release\M2Mqtt.NetCf35\ - TRACE;WindowsCE,COMPACT_FRAMEWORK - true - true - prompt - 512 - 4 - Off - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf39.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf39.csproj deleted file mode 100644 index f2a15c8..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetCf39.csproj +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Debug - AnyCPU - {BB9B7FF4-6502-41AF-8851-5060B67645E8} - {6AFDAB0D-95EF-424D-8A49-099ECD40B0FF};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - uPLibrary.Networking.M2Mqtt - M2Mqtt.NetCf39 - WindowsEmbeddedCompact - v3.9 - v8.0 - 512 - - - true - full - false - ..\bin\Debug\M2Mqtt.NetCf39\ - TRACE;DEBUG;COMPACT_FRAMEWORK - prompt - 4 - ManagedMinimumRules.ruleset - - - pdbonly - true - ..\bin\Release\M2Mqtt.NetCf39\ - TRACE;COMPACT_FRAMEWORK - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf42.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf42.csproj deleted file mode 100644 index d94e20b..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf42.csproj +++ /dev/null @@ -1,84 +0,0 @@ - - - - M2Mqtt.NetMf - Library - uPLibrary.Networking.M2Mqtt - {b69e3092-b931-443c-abe7-7e7b65f2a37f};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 9.0.21022 - 2.0 - {F733523A-F14E-4F5A-9E7C-085CA80F52B1} - v4.2 - $(MSBuildExtensionsPath32)\Microsoft\.NET Micro Framework\ - - - true - full - false - ..\bin\Debug\M2Mqtt.NetMf42\ - DEBUG;TRACE,MF_FRAMEWORK_VERSION_V4_2,SSL - prompt - 4 - - - pdbonly - true - ..\bin\Release\M2Mqtt.NetMf42\ - TRACE,MF_FRAMEWORK_VERSION_V4_2,SSL - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf43.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf43.csproj deleted file mode 100644 index c45764c..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.NetMf43.csproj +++ /dev/null @@ -1,84 +0,0 @@ - - - - M2Mqtt.NetMf - Library - uPLibrary.Networking.M2Mqtt - {b69e3092-b931-443c-abe7-7e7b65f2a37f};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 9.0.21022 - 2.0 - {6A6D540B-8554-4FFD-8884-8BEFCCD9AD41} - v4.3 - $(MSBuildExtensionsPath32)\Microsoft\.NET Micro Framework\ - - - true - full - false - ..\bin\Debug\M2Mqtt.NetMf43\ - DEBUG;TRACE,MF_FRAMEWORK_VERSION_V4_3,SSL - prompt - 4 - - - pdbonly - true - ..\bin\Release\M2Mqtt.NetMf43\ - TRACE,MF_FRAMEWORK_VERSION_V4_3,SSL - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.WinRT.csproj b/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.WinRT.csproj deleted file mode 100644 index f9dc853..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/M2Mqtt.WinRT.csproj +++ /dev/null @@ -1,97 +0,0 @@ - - - - - 12.0 - Debug - AnyCPU - {0238F0E3-A02B-428D-8A3F-410D8F15BB50} - Library - Properties - uPLibrary.Networking.M2Mqtt - M2Mqtt.WinRT - en-US - 512 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Profile32 - v4.6 - - - true - full - false - ..\bin\Debug\M2Mqtt.WinRT\ - TRACE;DEBUG;WINDOWS_APP,WINDOWS_PHONE_APP,SSL - prompt - 4 - - - pdbonly - true - ..\bin\Release\M2Mqtt.WinRT\ - TRACE;WINDOWS_APP,WINDOWS_PHONE_APP,SSL - prompt - 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgBase.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgBase.cs deleted file mode 100644 index 870fe5f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgBase.cs +++ /dev/null @@ -1,275 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Text; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Base class for all MQTT messages - /// - public abstract class MqttMsgBase - { - #region Constants... - - // mask, offset and size for fixed header fields - internal const byte MSG_TYPE_MASK = 0xF0; - internal const byte MSG_TYPE_OFFSET = 0x04; - internal const byte MSG_TYPE_SIZE = 0x04; - internal const byte MSG_FLAG_BITS_MASK = 0x0F; // [v3.1.1] - internal const byte MSG_FLAG_BITS_OFFSET = 0x00; // [v3.1.1] - internal const byte MSG_FLAG_BITS_SIZE = 0x04; // [v3.1.1] - internal const byte DUP_FLAG_MASK = 0x08; - internal const byte DUP_FLAG_OFFSET = 0x03; - internal const byte DUP_FLAG_SIZE = 0x01; - internal const byte QOS_LEVEL_MASK = 0x06; - internal const byte QOS_LEVEL_OFFSET = 0x01; - internal const byte QOS_LEVEL_SIZE = 0x02; - internal const byte RETAIN_FLAG_MASK = 0x01; - internal const byte RETAIN_FLAG_OFFSET = 0x00; - internal const byte RETAIN_FLAG_SIZE = 0x01; - - // MQTT message types - internal const byte MQTT_MSG_CONNECT_TYPE = 0x01; - internal const byte MQTT_MSG_CONNACK_TYPE = 0x02; - internal const byte MQTT_MSG_PUBLISH_TYPE = 0x03; - internal const byte MQTT_MSG_PUBACK_TYPE = 0x04; - internal const byte MQTT_MSG_PUBREC_TYPE = 0x05; - internal const byte MQTT_MSG_PUBREL_TYPE = 0x06; - internal const byte MQTT_MSG_PUBCOMP_TYPE = 0x07; - internal const byte MQTT_MSG_SUBSCRIBE_TYPE = 0x08; - internal const byte MQTT_MSG_SUBACK_TYPE = 0x09; - internal const byte MQTT_MSG_UNSUBSCRIBE_TYPE = 0x0A; - internal const byte MQTT_MSG_UNSUBACK_TYPE = 0x0B; - internal const byte MQTT_MSG_PINGREQ_TYPE = 0x0C; - internal const byte MQTT_MSG_PINGRESP_TYPE = 0x0D; - internal const byte MQTT_MSG_DISCONNECT_TYPE = 0x0E; - - // [v3.1.1] MQTT flag bits - internal const byte MQTT_MSG_CONNECT_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_CONNACK_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_PUBLISH_FLAG_BITS = 0x00; // just defined as 0x00 but depends on publish props (dup, qos, retain) - internal const byte MQTT_MSG_PUBACK_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_PUBREC_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_PUBREL_FLAG_BITS = 0x02; - internal const byte MQTT_MSG_PUBCOMP_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_SUBSCRIBE_FLAG_BITS = 0x02; - internal const byte MQTT_MSG_SUBACK_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_UNSUBSCRIBE_FLAG_BITS = 0x02; - internal const byte MQTT_MSG_UNSUBACK_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_PINGREQ_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_PINGRESP_FLAG_BITS = 0x00; - internal const byte MQTT_MSG_DISCONNECT_FLAG_BITS = 0x00; - - // QOS levels - public const byte QOS_LEVEL_AT_MOST_ONCE = 0x00; - public const byte QOS_LEVEL_AT_LEAST_ONCE = 0x01; - public const byte QOS_LEVEL_EXACTLY_ONCE = 0x02; - - // SUBSCRIBE QoS level granted failure [v3.1.1] - public const byte QOS_LEVEL_GRANTED_FAILURE = 0x80; - - internal const ushort MAX_TOPIC_LENGTH = 65535; - internal const ushort MIN_TOPIC_LENGTH = 1; - internal const byte MESSAGE_ID_SIZE = 2; - - #endregion - - #region Properties... - - /// - /// Message type - /// - public byte Type - { - get { return this.type; } - set { this.type = value; } - } - - /// - /// Duplicate message flag - /// - public bool DupFlag - { - get { return this.dupFlag; } - set { this.dupFlag = value; } - } - - /// - /// Quality of Service level - /// - public byte QosLevel - { - get { return this.qosLevel; } - set { this.qosLevel = value; } - } - - /// - /// Retain message flag - /// - public bool Retain - { - get { return this.retain; } - set { this.retain = value; } - } - - /// - /// Message identifier for the message - /// - public ushort MessageId - { - get { return this.messageId; } - set { this.messageId = value; } - } - - #endregion - - // message type - protected byte type; - // duplicate delivery - protected bool dupFlag; - // quality of service level - protected byte qosLevel; - // retain flag - protected bool retain; - // message identifier - protected ushort messageId; - - /// - /// Returns message bytes rapresentation - /// - /// Protocol version - /// Bytes rapresentation - public abstract byte[] GetBytes(byte protocolVersion); - - /// - /// Encode remaining length and insert it into message buffer - /// - /// Remaining length value to encode - /// Message buffer for inserting encoded value - /// Index from which insert encoded value into buffer - /// Index updated - protected int encodeRemainingLength(int remainingLength, byte[] buffer, int index) - { - int digit = 0; - do - { - digit = remainingLength % 128; - remainingLength /= 128; - if (remainingLength > 0) - digit = digit | 0x80; - buffer[index++] = (byte)digit; - } while (remainingLength > 0); - return index; - } - - /// - /// Decode remaining length reading bytes from socket - /// - /// Channel from reading bytes - /// Decoded remaining length - protected static int decodeRemainingLength(IMqttNetworkChannel channel) - { - int multiplier = 1; - int value = 0; - int digit = 0; - byte[] nextByte = new byte[1]; - do - { - // next digit from stream - channel.Receive(nextByte); - digit = nextByte[0]; - value += ((digit & 127) * multiplier); - multiplier *= 128; - } while ((digit & 128) != 0); - return value; - } - -#if TRACE - /// - /// Returns a string representation of the message for tracing - /// - /// Message name - /// Message fields name - /// Message fields value - /// String representation of the message - protected string GetTraceString(string name, object[] fieldNames, object[] fieldValues) - { - StringBuilder sb = new StringBuilder(); - sb.Append(name); - - if ((fieldNames != null) && (fieldValues != null)) - { - sb.Append("("); - bool addComma = false; - for (int i = 0; i < fieldValues.Length; i++) - { - if (fieldValues[i] != null) - { - if (addComma) - { - sb.Append(","); - } - - sb.Append(fieldNames[i]); - sb.Append(":"); - sb.Append(GetStringObject(fieldValues[i])); - addComma = true; - } - } - sb.Append(")"); - } - - return sb.ToString(); - } - - object GetStringObject(object value) - { - byte[] binary = value as byte[]; - if (binary != null) - { - string hexChars = "0123456789ABCDEF"; - StringBuilder sb = new StringBuilder(binary.Length * 2); - for (int i = 0; i < binary.Length; ++i) - { - sb.Append(hexChars[binary[i] >> 4]); - sb.Append(hexChars[binary[i] & 0x0F]); - } - - return sb.ToString(); - } - - object[] list = value as object[]; - if (list != null) - { - StringBuilder sb = new StringBuilder(); - sb.Append('['); - for (int i = 0; i < list.Length; ++i) - { - if (i > 0) sb.Append(','); - sb.Append(list[i]); - } - sb.Append(']'); - - return sb.ToString(); - } - - return value; - } -#endif - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnack.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnack.cs deleted file mode 100644 index ae5a342..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnack.cs +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for CONNACK message from broker to client - /// - public class MqttMsgConnack : MqttMsgBase - { - #region Constants... - - // return codes for CONNACK message - public const byte CONN_ACCEPTED = 0x00; - public const byte CONN_REFUSED_PROT_VERS = 0x01; - public const byte CONN_REFUSED_IDENT_REJECTED = 0x02; - public const byte CONN_REFUSED_SERVER_UNAVAILABLE = 0x03; - public const byte CONN_REFUSED_USERNAME_PASSWORD = 0x04; - public const byte CONN_REFUSED_NOT_AUTHORIZED = 0x05; - - private const byte TOPIC_NAME_COMP_RESP_BYTE_OFFSET = 0; - private const byte TOPIC_NAME_COMP_RESP_BYTE_SIZE = 1; - // [v3.1.1] connect acknowledge flags replace "old" topic name compression respone (not used in 3.1) - private const byte CONN_ACK_FLAGS_BYTE_OFFSET = 0; - private const byte CONN_ACK_FLAGS_BYTE_SIZE = 1; - // [v3.1.1] session present flag - private const byte SESSION_PRESENT_FLAG_MASK = 0x01; - private const byte SESSION_PRESENT_FLAG_OFFSET = 0x00; - private const byte SESSION_PRESENT_FLAG_SIZE = 0x01; - private const byte CONN_RETURN_CODE_BYTE_OFFSET = 1; - private const byte CONN_RETURN_CODE_BYTE_SIZE = 1; - - #endregion - - #region Properties... - - // [v3.1.1] session present flag - /// - /// Session present flag - /// - public bool SessionPresent - { - get { return this.sessionPresent; } - set { this.sessionPresent = value; } - } - - /// - /// Return Code - /// - public byte ReturnCode - { - get { return this.returnCode; } - set { this.returnCode = value; } - } - - #endregion - - // [v3.1.1] session present flag - private bool sessionPresent; - - // return code for CONNACK message - private byte returnCode; - - /// - /// Constructor - /// - public MqttMsgConnack() - { - this.type = MQTT_MSG_CONNACK_TYPE; - } - - /// - /// Parse bytes for a CONNACK message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// CONNACK message instance - public static MqttMsgConnack Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - MqttMsgConnack msg = new MqttMsgConnack(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_CONNACK_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] ... set session present flag ... - msg.sessionPresent = (buffer[CONN_ACK_FLAGS_BYTE_OFFSET] & SESSION_PRESENT_FLAG_MASK) != 0x00; - } - // ...and set return code from broker - msg.returnCode = buffer[CONN_RETURN_CODE_BYTE_OFFSET]; - - return msg; - } - - public override byte[] GetBytes(byte ProtocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - if (ProtocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - // flags byte and connect return code - varHeaderSize += (CONN_ACK_FLAGS_BYTE_SIZE + CONN_RETURN_CODE_BYTE_SIZE); - else - // topic name compression response and connect return code - varHeaderSize += (TOPIC_NAME_COMP_RESP_BYTE_SIZE + CONN_RETURN_CODE_BYTE_SIZE); - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (ProtocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_CONNACK_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_CONNACK_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (byte)(MQTT_MSG_CONNACK_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - if (ProtocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - // [v3.1.1] session present flag - buffer[index++] = this.sessionPresent ? (byte)(1 << SESSION_PRESENT_FLAG_OFFSET) : (byte)0x00; - else - // topic name compression response (reserved values. not used); - buffer[index++] = 0x00; - - // connect return code - buffer[index++] = this.returnCode; - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "CONNACK", - new object[] { "returnCode" }, - new object[] { this.returnCode }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnect.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnect.cs deleted file mode 100644 index 382cf83..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnect.cs +++ /dev/null @@ -1,582 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Text; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for CONNECT message from client to broker - /// - public class MqttMsgConnect : MqttMsgBase - { - #region Constants... - - // protocol name supported - internal const string PROTOCOL_NAME_V3_1 = "MQIsdp"; - internal const string PROTOCOL_NAME_V3_1_1 = "MQTT"; // [v.3.1.1] - - // max length for client id (removed in 3.1.1) - internal const int CLIENT_ID_MAX_LENGTH = 23; - - // variable header fields - internal const byte PROTOCOL_NAME_LEN_SIZE = 2; - internal const byte PROTOCOL_NAME_V3_1_SIZE = 6; - internal const byte PROTOCOL_NAME_V3_1_1_SIZE = 4; // [v.3.1.1] - internal const byte PROTOCOL_VERSION_SIZE = 1; - internal const byte CONNECT_FLAGS_SIZE = 1; - internal const byte KEEP_ALIVE_TIME_SIZE = 2; - - internal const byte PROTOCOL_VERSION_V3_1 = 0x03; - internal const byte PROTOCOL_VERSION_V3_1_1 = 0x04; // [v.3.1.1] - internal const ushort KEEP_ALIVE_PERIOD_DEFAULT = 60; // seconds - internal const ushort MAX_KEEP_ALIVE = 65535; // 16 bit - - // connect flags - internal const byte USERNAME_FLAG_MASK = 0x80; - internal const byte USERNAME_FLAG_OFFSET = 0x07; - internal const byte USERNAME_FLAG_SIZE = 0x01; - internal const byte PASSWORD_FLAG_MASK = 0x40; - internal const byte PASSWORD_FLAG_OFFSET = 0x06; - internal const byte PASSWORD_FLAG_SIZE = 0x01; - internal const byte WILL_RETAIN_FLAG_MASK = 0x20; - internal const byte WILL_RETAIN_FLAG_OFFSET = 0x05; - internal const byte WILL_RETAIN_FLAG_SIZE = 0x01; - internal const byte WILL_QOS_FLAG_MASK = 0x18; - internal const byte WILL_QOS_FLAG_OFFSET = 0x03; - internal const byte WILL_QOS_FLAG_SIZE = 0x02; - internal const byte WILL_FLAG_MASK = 0x04; - internal const byte WILL_FLAG_OFFSET = 0x02; - internal const byte WILL_FLAG_SIZE = 0x01; - internal const byte CLEAN_SESSION_FLAG_MASK = 0x02; - internal const byte CLEAN_SESSION_FLAG_OFFSET = 0x01; - internal const byte CLEAN_SESSION_FLAG_SIZE = 0x01; - // [v.3.1.1] lsb (reserved) must be now 0 - internal const byte RESERVED_FLAG_MASK = 0x01; - internal const byte RESERVED_FLAG_OFFSET = 0x00; - internal const byte RESERVED_FLAG_SIZE = 0x01; - - #endregion - - #region Properties... - - /// - /// Protocol name - /// - public string ProtocolName - { - get { return this.protocolName; } - set { this.protocolName = value; } - } - - /// - /// Protocol version - /// - public byte ProtocolVersion - { - get { return this.protocolVersion; } - set { this.protocolVersion = value; } - } - - /// - /// Client identifier - /// - public string ClientId - { - get { return this.clientId; } - set { this.clientId = value; } - } - - /// - /// Will retain flag - /// - public bool WillRetain - { - get { return this.willRetain; } - set { this.willRetain = value; } - } - - /// - /// Will QOS level - /// - public byte WillQosLevel - { - get { return this.willQosLevel; } - set { this.willQosLevel = value; } - } - - /// - /// Will flag - /// - public bool WillFlag - { - get { return this.willFlag; } - set { this.willFlag = value; } - } - - /// - /// Will topic - /// - public string WillTopic - { - get { return this.willTopic; } - set { this.willTopic = value; } - } - - /// - /// Will message - /// - public string WillMessage - { - get { return this.willMessage; } - set { this.willMessage = value; } - } - - /// - /// Username - /// - public string Username - { - get { return this.username; } - set { this.username = value; } - } - - /// - /// Password - /// - public string Password - { - get { return this.password; } - set { this.password = value; } - } - - /// - /// Clean session flag - /// - public bool CleanSession - { - get { return this.cleanSession; } - set { this.cleanSession = value; } - } - - /// - /// Keep alive period - /// - public ushort KeepAlivePeriod - { - get { return this.keepAlivePeriod; } - set { this.keepAlivePeriod = value; } - } - - #endregion - - // protocol name - private string protocolName; - // protocol version - private byte protocolVersion; - // client identifier - private string clientId; - // will retain flag - protected bool willRetain; - // will quality of service level - protected byte willQosLevel; - // will flag - private bool willFlag; - // will topic - private string willTopic; - // will message - private string willMessage; - // username - private string username; - // password - private string password; - // clean session flag - private bool cleanSession; - // keep alive period (in sec) - private ushort keepAlivePeriod; - - /// - /// Constructor - /// - public MqttMsgConnect() - { - this.type = MQTT_MSG_CONNECT_TYPE; - } - - /// - /// Constructor - /// - /// Client identifier - public MqttMsgConnect(string clientId) : - this(clientId, null, null, false, QOS_LEVEL_AT_LEAST_ONCE, false, null, null, true, KEEP_ALIVE_PERIOD_DEFAULT, PROTOCOL_VERSION_V3_1_1) - { - } - - /// - /// Constructor - /// - /// Client identifier - /// Username - /// Password - /// Will retain flag - /// Will QOS level - /// Will flag - /// Will topic - /// Will message - /// Clean sessione flag - /// Keep alive period - /// Protocol version - public MqttMsgConnect(string clientId, - string username, - string password, - bool willRetain, - byte willQosLevel, - bool willFlag, - string willTopic, - string willMessage, - bool cleanSession, - ushort keepAlivePeriod, - byte protocolVersion - ) - { - this.type = MQTT_MSG_CONNECT_TYPE; - - this.clientId = clientId; - this.username = username; - this.password = password; - this.willRetain = willRetain; - this.willQosLevel = willQosLevel; - this.willFlag = willFlag; - this.willTopic = willTopic; - this.willMessage = willMessage; - this.cleanSession = cleanSession; - this.keepAlivePeriod = keepAlivePeriod; - // [v.3.1.1] added new protocol name and version - this.protocolVersion = protocolVersion; - this.protocolName = (this.protocolVersion == PROTOCOL_VERSION_V3_1_1) ? PROTOCOL_NAME_V3_1_1 : PROTOCOL_NAME_V3_1; - } - - /// - /// Parse bytes for a CONNECT message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// CONNECT message instance - public static MqttMsgConnect Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - int protNameUtf8Length; - byte[] protNameUtf8; - bool isUsernameFlag; - bool isPasswordFlag; - int clientIdUtf8Length; - byte[] clientIdUtf8; - int willTopicUtf8Length; - byte[] willTopicUtf8; - int willMessageUtf8Length; - byte[] willMessageUtf8; - int usernameUtf8Length; - byte[] usernameUtf8; - int passwordUtf8Length; - byte[] passwordUtf8; - MqttMsgConnect msg = new MqttMsgConnect(); - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // protocol name - protNameUtf8Length = ((buffer[index++] << 8) & 0xFF00); - protNameUtf8Length |= buffer[index++]; - protNameUtf8 = new byte[protNameUtf8Length]; - Array.Copy(buffer, index, protNameUtf8, 0, protNameUtf8Length); - index += protNameUtf8Length; - msg.protocolName = new String(Encoding.UTF8.GetChars(protNameUtf8)); - - // [v3.1.1] wrong protocol name - if (!msg.protocolName.Equals(PROTOCOL_NAME_V3_1) && !msg.protocolName.Equals(PROTOCOL_NAME_V3_1_1)) - throw new MqttClientException(MqttClientErrorCode.InvalidProtocolName); - - // protocol version - msg.protocolVersion = buffer[index]; - index += PROTOCOL_VERSION_SIZE; - - // connect flags - // [v3.1.1] check lsb (reserved) must be 0 - if ((msg.protocolVersion == PROTOCOL_VERSION_V3_1_1) && - ((buffer[index] & RESERVED_FLAG_MASK) != 0x00)) - throw new MqttClientException(MqttClientErrorCode.InvalidConnectFlags); - - isUsernameFlag = (buffer[index] & USERNAME_FLAG_MASK) != 0x00; - isPasswordFlag = (buffer[index] & PASSWORD_FLAG_MASK) != 0x00; - msg.willRetain = (buffer[index] & WILL_RETAIN_FLAG_MASK) != 0x00; - msg.willQosLevel = (byte)((buffer[index] & WILL_QOS_FLAG_MASK) >> WILL_QOS_FLAG_OFFSET); - msg.willFlag = (buffer[index] & WILL_FLAG_MASK) != 0x00; - msg.cleanSession = (buffer[index] & CLEAN_SESSION_FLAG_MASK) != 0x00; - index += CONNECT_FLAGS_SIZE; - - // keep alive timer - msg.keepAlivePeriod = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.keepAlivePeriod |= buffer[index++]; - - // client identifier [v3.1.1] it may be zero bytes long (empty string) - clientIdUtf8Length = ((buffer[index++] << 8) & 0xFF00); - clientIdUtf8Length |= buffer[index++]; - clientIdUtf8 = new byte[clientIdUtf8Length]; - Array.Copy(buffer, index, clientIdUtf8, 0, clientIdUtf8Length); - index += clientIdUtf8Length; - msg.clientId = new String(Encoding.UTF8.GetChars(clientIdUtf8)); - // [v3.1.1] if client identifier is zero bytes long, clean session must be true - if ((msg.protocolVersion == PROTOCOL_VERSION_V3_1_1) && (clientIdUtf8Length == 0) && (!msg.cleanSession)) - throw new MqttClientException(MqttClientErrorCode.InvalidClientId); - - // will topic and will message - if (msg.willFlag) - { - willTopicUtf8Length = ((buffer[index++] << 8) & 0xFF00); - willTopicUtf8Length |= buffer[index++]; - willTopicUtf8 = new byte[willTopicUtf8Length]; - Array.Copy(buffer, index, willTopicUtf8, 0, willTopicUtf8Length); - index += willTopicUtf8Length; - msg.willTopic = new String(Encoding.UTF8.GetChars(willTopicUtf8)); - - willMessageUtf8Length = ((buffer[index++] << 8) & 0xFF00); - willMessageUtf8Length |= buffer[index++]; - willMessageUtf8 = new byte[willMessageUtf8Length]; - Array.Copy(buffer, index, willMessageUtf8, 0, willMessageUtf8Length); - index += willMessageUtf8Length; - msg.willMessage = new String(Encoding.UTF8.GetChars(willMessageUtf8)); - } - - // username - if (isUsernameFlag) - { - usernameUtf8Length = ((buffer[index++] << 8) & 0xFF00); - usernameUtf8Length |= buffer[index++]; - usernameUtf8 = new byte[usernameUtf8Length]; - Array.Copy(buffer, index, usernameUtf8, 0, usernameUtf8Length); - index += usernameUtf8Length; - msg.username = new String(Encoding.UTF8.GetChars(usernameUtf8)); - } - - // password - if (isPasswordFlag) - { - passwordUtf8Length = ((buffer[index++] << 8) & 0xFF00); - passwordUtf8Length |= buffer[index++]; - passwordUtf8 = new byte[passwordUtf8Length]; - Array.Copy(buffer, index, passwordUtf8, 0, passwordUtf8Length); - index += passwordUtf8Length; - msg.password = new String(Encoding.UTF8.GetChars(passwordUtf8)); - } - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - byte[] clientIdUtf8 = Encoding.UTF8.GetBytes(this.clientId); - byte[] willTopicUtf8 = (this.willFlag && (this.willTopic != null)) ? Encoding.UTF8.GetBytes(this.willTopic) : null; - byte[] willMessageUtf8 = (this.willFlag && (this.willMessage != null)) ? Encoding.UTF8.GetBytes(this.willMessage) : null; - byte[] usernameUtf8 = ((this.username != null) && (this.username.Length > 0)) ? Encoding.UTF8.GetBytes(this.username) : null; - byte[] passwordUtf8 = ((this.password != null) && (this.password.Length > 0)) ? Encoding.UTF8.GetBytes(this.password) : null; - - // [v3.1.1] - if (this.protocolVersion == PROTOCOL_VERSION_V3_1_1) - { - // will flag set, will topic and will message MUST be present - if (this.willFlag && ((this.willQosLevel >= 0x03) || - (willTopicUtf8 == null) || (willMessageUtf8 == null) || - ((willTopicUtf8 != null) && (willTopicUtf8.Length == 0)) || - ((willMessageUtf8 != null) && (willMessageUtf8.Length == 0)))) - throw new MqttClientException(MqttClientErrorCode.WillWrong); - // willflag not set, retain must be 0 and will topic and message MUST NOT be present - else if (!this.willFlag && ((this.willRetain) || - (willTopicUtf8 != null) || (willMessageUtf8 != null) || - ((willTopicUtf8 != null) && (willTopicUtf8.Length != 0)) || - ((willMessageUtf8 != null) && (willMessageUtf8.Length != 0)))) - throw new MqttClientException(MqttClientErrorCode.WillWrong); - } - - if (this.keepAlivePeriod > MAX_KEEP_ALIVE) - throw new MqttClientException(MqttClientErrorCode.KeepAliveWrong); - - // check on will QoS Level - if ((this.willQosLevel < MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE) || - (this.willQosLevel > MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE)) - throw new MqttClientException(MqttClientErrorCode.WillWrong); - - // protocol name field size - // MQTT version 3.1 - if (this.protocolVersion == PROTOCOL_VERSION_V3_1) - { - varHeaderSize += (PROTOCOL_NAME_LEN_SIZE + PROTOCOL_NAME_V3_1_SIZE); - } - // MQTT version 3.1.1 - else - { - varHeaderSize += (PROTOCOL_NAME_LEN_SIZE + PROTOCOL_NAME_V3_1_1_SIZE); - } - // protocol level field size - varHeaderSize += PROTOCOL_VERSION_SIZE; - // connect flags field size - varHeaderSize += CONNECT_FLAGS_SIZE; - // keep alive timer field size - varHeaderSize += KEEP_ALIVE_TIME_SIZE; - - // client identifier field size - payloadSize += clientIdUtf8.Length + 2; - // will topic field size - payloadSize += (willTopicUtf8 != null) ? (willTopicUtf8.Length + 2) : 0; - // will message field size - payloadSize += (willMessageUtf8 != null) ? (willMessageUtf8.Length + 2) : 0; - // username field size - payloadSize += (usernameUtf8 != null) ? (usernameUtf8.Length + 2) : 0; - // password field size - payloadSize += (passwordUtf8 != null) ? (passwordUtf8.Length + 2) : 0; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - buffer[index++] = (MQTT_MSG_CONNECT_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_CONNECT_FLAG_BITS; // [v.3.1.1] - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // protocol name - buffer[index++] = 0; // MSB protocol name size - // MQTT version 3.1 - if (this.protocolVersion == PROTOCOL_VERSION_V3_1) - { - buffer[index++] = PROTOCOL_NAME_V3_1_SIZE; // LSB protocol name size - Array.Copy(Encoding.UTF8.GetBytes(PROTOCOL_NAME_V3_1), 0, buffer, index, PROTOCOL_NAME_V3_1_SIZE); - index += PROTOCOL_NAME_V3_1_SIZE; - // protocol version - buffer[index++] = PROTOCOL_VERSION_V3_1; - } - // MQTT version 3.1.1 - else - { - buffer[index++] = PROTOCOL_NAME_V3_1_1_SIZE; // LSB protocol name size - Array.Copy(Encoding.UTF8.GetBytes(PROTOCOL_NAME_V3_1_1), 0, buffer, index, PROTOCOL_NAME_V3_1_1_SIZE); - index += PROTOCOL_NAME_V3_1_1_SIZE; - // protocol version - buffer[index++] = PROTOCOL_VERSION_V3_1_1; - } - - // connect flags - byte connectFlags = 0x00; - connectFlags |= (usernameUtf8 != null) ? (byte)(1 << USERNAME_FLAG_OFFSET) : (byte)0x00; - connectFlags |= (passwordUtf8 != null) ? (byte)(1 << PASSWORD_FLAG_OFFSET) : (byte)0x00; - connectFlags |= (this.willRetain) ? (byte)(1 << WILL_RETAIN_FLAG_OFFSET) : (byte)0x00; - // only if will flag is set, we have to use will QoS level (otherwise is MUST be 0) - if (this.willFlag) - connectFlags |= (byte)(this.willQosLevel << WILL_QOS_FLAG_OFFSET); - connectFlags |= (this.willFlag) ? (byte)(1 << WILL_FLAG_OFFSET) : (byte)0x00; - connectFlags |= (this.cleanSession) ? (byte)(1 << CLEAN_SESSION_FLAG_OFFSET) : (byte)0x00; - buffer[index++] = connectFlags; - - // keep alive period - buffer[index++] = (byte)((this.keepAlivePeriod >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.keepAlivePeriod & 0x00FF); // LSB - - // client identifier - buffer[index++] = (byte)((clientIdUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(clientIdUtf8.Length & 0x00FF); // LSB - Array.Copy(clientIdUtf8, 0, buffer, index, clientIdUtf8.Length); - index += clientIdUtf8.Length; - - // will topic - if (this.willFlag && (willTopicUtf8 != null)) - { - buffer[index++] = (byte)((willTopicUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(willTopicUtf8.Length & 0x00FF); // LSB - Array.Copy(willTopicUtf8, 0, buffer, index, willTopicUtf8.Length); - index += willTopicUtf8.Length; - } - - // will message - if (this.willFlag && (willMessageUtf8 != null)) - { - buffer[index++] = (byte)((willMessageUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(willMessageUtf8.Length & 0x00FF); // LSB - Array.Copy(willMessageUtf8, 0, buffer, index, willMessageUtf8.Length); - index += willMessageUtf8.Length; - } - - // username - if (usernameUtf8 != null) - { - buffer[index++] = (byte)((usernameUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(usernameUtf8.Length & 0x00FF); // LSB - Array.Copy(usernameUtf8, 0, buffer, index, usernameUtf8.Length); - index += usernameUtf8.Length; - } - - // password - if (passwordUtf8 != null) - { - buffer[index++] = (byte)((passwordUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(passwordUtf8.Length & 0x00FF); // LSB - Array.Copy(passwordUtf8, 0, buffer, index, passwordUtf8.Length); - index += passwordUtf8.Length; - } - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "CONNECT", - new object[] { "protocolName", "protocolVersion", "clientId", "willFlag", "willRetain", "willQosLevel", "willTopic", "willMessage", "username", "password", "cleanSession", "keepAlivePeriod" }, - new object[] { this.protocolName, this.protocolVersion, this.clientId, this.willFlag, this.willRetain, this.willQosLevel, this.willTopic, this.willMessage, this.username, this.password, this.cleanSession, this.keepAlivePeriod }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnectEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnectEventArgs.cs deleted file mode 100644 index ce0b3fe..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgConnectEventArgs.cs +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for CONNECT message received from client - /// - public class MqttMsgConnectEventArgs : EventArgs - { - /// - /// Message received from client - /// - public MqttMsgConnect Message { get; private set; } - - /// - /// Constructor - /// - /// CONNECT message received from client - public MqttMsgConnectEventArgs(MqttMsgConnect connect) - { - this.Message = connect; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgContext.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgContext.cs deleted file mode 100644 index a2850d7..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgContext.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Text; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Context for MQTT message - /// - public class MqttMsgContext - { - /// - /// MQTT message - /// - public MqttMsgBase Message { get; set; } - - /// - /// MQTT message state - /// - public MqttMsgState State { get; set; } - - /// - /// Flow of the message - /// - public MqttMsgFlow Flow { get; set; } - - /// - /// Timestamp in ticks (for retry) - /// - public int Timestamp { get; set; } - - /// - /// Attempt (for retry) - /// - public int Attempt { get; set; } - - /// - /// Unique key - /// - public string Key - { - get { return this.Flow + "_" + this.Message.MessageId; } - } - } - - /// - /// Flow of the message - /// - public enum MqttMsgFlow - { - /// - /// To publish to subscribers - /// - ToPublish, - - /// - /// To acknowledge to publisher - /// - ToAcknowledge - } - - /// - /// MQTT message state - /// - public enum MqttMsgState - { - /// - /// QOS = 0, Message queued - /// - QueuedQos0, - - /// - /// QOS = 1, Message queued - /// - QueuedQos1, - - /// - /// QOS = 2, Message queued - /// - QueuedQos2, - - /// - /// QOS = 1, PUBLISH sent, wait for PUBACK - /// - WaitForPuback, - - /// - /// QOS = 2, PUBLISH sent, wait for PUBREC - /// - WaitForPubrec, - - /// - /// QOS = 2, PUBREC sent, wait for PUBREL - /// - WaitForPubrel, - - /// - /// QOS = 2, PUBREL sent, wait for PUBCOMP - /// - WaitForPubcomp, - - /// - /// QOS = 2, start first phase handshake send PUBREC - /// - SendPubrec, - - /// - /// QOS = 2, start second phase handshake send PUBREL - /// - SendPubrel, - - /// - /// QOS = 2, end second phase handshake send PUBCOMP - /// - SendPubcomp, - - /// - /// QOS = 1, PUBLISH received, send PUBACK - /// - SendPuback, - - // [v3.1.1] SUBSCRIBE isn't "officially" QOS = 1 - /// - /// Send SUBSCRIBE message - /// - SendSubscribe, - - // [v3.1.1] UNSUBSCRIBE isn't "officially" QOS = 1 - /// - /// Send UNSUBSCRIBE message - /// - SendUnsubscribe, - - /// - /// (QOS = 1), SUBSCRIBE sent, wait for SUBACK - /// - WaitForSuback, - - /// - /// (QOS = 1), UNSUBSCRIBE sent, wait for UNSUBACK - /// - WaitForUnsuback - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgDisconnect.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgDisconnect.cs deleted file mode 100644 index d918473..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgDisconnect.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for DISCONNECT message from client to broker - /// - public class MqttMsgDisconnect : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgDisconnect() - { - this.type = MQTT_MSG_DISCONNECT_TYPE; - } - - /// - /// Parse bytes for a DISCONNECT message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// DISCONNECT message instance - public static MqttMsgDisconnect Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - MqttMsgDisconnect msg = new MqttMsgDisconnect(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_DISCONNECT_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - // NOTE : remainingLength must be 0 - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - byte[] buffer = new byte[2]; - int index = 0; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_DISCONNECT_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_DISCONNECT_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_DISCONNECT_TYPE << MSG_TYPE_OFFSET); - buffer[index++] = 0x00; - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "DISCONNECT", - null, - null); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingReq.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingReq.cs deleted file mode 100644 index b46bdb6..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingReq.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PINGREQ message from client to broker - /// - public class MqttMsgPingReq : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPingReq() - { - this.type = MQTT_MSG_PINGREQ_TYPE; - } - - public override byte[] GetBytes(byte protocolVersion) - { - byte[] buffer = new byte[2]; - int index = 0; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PINGREQ_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PINGREQ_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_PINGREQ_TYPE << MSG_TYPE_OFFSET); - buffer[index++] = 0x00; - - return buffer; - } - - /// - /// Parse bytes for a PINGREQ message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PINGREQ message instance - public static MqttMsgPingReq Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - MqttMsgPingReq msg = new MqttMsgPingReq(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PINGREQ_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // already know remaininglength is zero (MQTT specification), - // so it isn't necessary to read other data from socket - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PINGREQ", - null, - null); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingResp.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingResp.cs deleted file mode 100644 index 2b028b9..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPingResp.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PINGRESP message from client to broker - /// - public class MqttMsgPingResp : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPingResp() - { - this.type = MQTT_MSG_PINGRESP_TYPE; - } - - /// - /// Parse bytes for a PINGRESP message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PINGRESP message instance - public static MqttMsgPingResp Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - MqttMsgPingResp msg = new MqttMsgPingResp(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PINGRESP_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // already know remaininglength is zero (MQTT specification), - // so it isn't necessary to read other data from socket - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - byte[] buffer = new byte[2]; - int index = 0; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PINGRESP_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PINGRESP_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_PINGRESP_TYPE << MSG_TYPE_OFFSET); - buffer[index++] = 0x00; - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PINGRESP", - null, - null); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPuback.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPuback.cs deleted file mode 100644 index e00e37f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPuback.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PUBACK message from broker to client - /// - public class MqttMsgPuback : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPuback() - { - this.type = MQTT_MSG_PUBACK_TYPE; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PUBACK_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PUBACK_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_PUBACK_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // get message identifier - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - return buffer; - } - - /// - /// Parse bytes for a PUBACK message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PUBACK message instance - public static MqttMsgPuback Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgPuback msg = new MqttMsgPuback(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PUBACK_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PUBACK", - new object[] { "messageId" }, - new object[] { this.messageId }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubcomp.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubcomp.cs deleted file mode 100644 index eeabd3b..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubcomp.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PUBCOMP message from broker to client - /// - public class MqttMsgPubcomp : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPubcomp() - { - this.type = MQTT_MSG_PUBCOMP_TYPE; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PUBCOMP_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PUBCOMP_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_PUBCOMP_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // get message identifier - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - return buffer; - } - - /// - /// Parse bytes for a PUBCOMP message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PUBCOMP message instance - public static MqttMsgPubcomp Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgPubcomp msg = new MqttMsgPubcomp(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PUBCOMP_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PUBCOMP", - new object[] { "messageId" }, - new object[] { this.messageId }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublish.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublish.cs deleted file mode 100644 index 6bbf207..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublish.cs +++ /dev/null @@ -1,277 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Text; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PUBLISH message from client to broker - /// - public class MqttMsgPublish : MqttMsgBase - { - #region Properties... - - /// - /// Message topic - /// - public string Topic - { - get { return this.topic; } - set { this.topic = value; } - } - - /// - /// Message data - /// - public byte[] Message - { - get { return this.message; } - set { this.message = value; } - } - - #endregion - - // message topic - private string topic; - // message data - private byte[] message; - - /// - /// Constructor - /// - public MqttMsgPublish() - { - this.type = MQTT_MSG_PUBLISH_TYPE; - } - - /// - /// Constructor - /// - /// Message topic - /// Message data - public MqttMsgPublish(string topic, byte[] message) : - this(topic, message, false, QOS_LEVEL_AT_MOST_ONCE, false) - { - } - - /// - /// Constructor - /// - /// Message topic - /// Message data - /// Duplicate flag - /// Quality of Service level - /// Retain flag - public MqttMsgPublish(string topic, - byte[] message, - bool dupFlag, - byte qosLevel, - bool retain) : base() - { - this.type = MQTT_MSG_PUBLISH_TYPE; - - this.topic = topic; - this.message = message; - this.dupFlag = dupFlag; - this.qosLevel = qosLevel; - this.retain = retain; - this.messageId = 0; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // topic can't contain wildcards - if ((this.topic.IndexOf('#') != -1) || (this.topic.IndexOf('+') != -1)) - throw new MqttClientException(MqttClientErrorCode.TopicWildcard); - - // check topic length - if ((this.topic.Length < MIN_TOPIC_LENGTH) || (this.topic.Length > MAX_TOPIC_LENGTH)) - throw new MqttClientException(MqttClientErrorCode.TopicLength); - - // check wrong QoS level (both bits can't be set 1) - if (this.qosLevel > QOS_LEVEL_EXACTLY_ONCE) - throw new MqttClientException(MqttClientErrorCode.QosNotAllowed); - - byte[] topicUtf8 = Encoding.UTF8.GetBytes(this.topic); - - // topic name - varHeaderSize += topicUtf8.Length + 2; - - // message id is valid only with QOS level 1 or QOS level 2 - if ((this.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || - (this.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) - { - varHeaderSize += MESSAGE_ID_SIZE; - } - - // check on message with zero length - if (this.message != null) - // message data - payloadSize += this.message.Length; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - buffer[index] = (byte)((MQTT_MSG_PUBLISH_TYPE << MSG_TYPE_OFFSET) | - (this.qosLevel << QOS_LEVEL_OFFSET)); - buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; - buffer[index] |= this.retain ? (byte)(1 << RETAIN_FLAG_OFFSET) : (byte)0x00; - index++; - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // topic name - buffer[index++] = (byte)((topicUtf8.Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(topicUtf8.Length & 0x00FF); // LSB - Array.Copy(topicUtf8, 0, buffer, index, topicUtf8.Length); - index += topicUtf8.Length; - - // message id is valid only with QOS level 1 or QOS level 2 - if ((this.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || - (this.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) - { - // check message identifier assigned - if (this.messageId == 0) - throw new MqttClientException(MqttClientErrorCode.WrongMessageId); - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - } - - // check on message with zero length - if (this.message != null) - { - // message data - Array.Copy(this.message, 0, buffer, index, this.message.Length); - index += this.message.Length; - } - - return buffer; - } - - /// - /// Parse bytes for a PUBLISH message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PUBLISH message instance - public static MqttMsgPublish Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - byte[] topicUtf8; - int topicUtf8Length; - MqttMsgPublish msg = new MqttMsgPublish(); - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - int received = channel.Receive(buffer); - - // topic name - topicUtf8Length = ((buffer[index++] << 8) & 0xFF00); - topicUtf8Length |= buffer[index++]; - topicUtf8 = new byte[topicUtf8Length]; - Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length); - index += topicUtf8Length; - msg.topic = new String(Encoding.UTF8.GetChars(topicUtf8)); - - // read QoS level from fixed header - msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); - // check wrong QoS level (both bits can't be set 1) - if (msg.qosLevel > QOS_LEVEL_EXACTLY_ONCE) - throw new MqttClientException(MqttClientErrorCode.QosNotAllowed); - // read DUP flag from fixed header - msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); - // read retain flag from fixed header - msg.retain = (((fixedHeaderFirstByte & RETAIN_FLAG_MASK) >> RETAIN_FLAG_OFFSET) == 0x01); - - // message id is valid only with QOS level 1 or QOS level 2 - if ((msg.qosLevel == QOS_LEVEL_AT_LEAST_ONCE) || - (msg.qosLevel == QOS_LEVEL_EXACTLY_ONCE)) - { - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - } - - // get payload with message data - int messageSize = remainingLength - index; - int remaining = messageSize; - int messageOffset = 0; - msg.message = new byte[messageSize]; - - // BUG FIX 26/07/2013 : receiving large payload - - // copy first part of payload data received - Array.Copy(buffer, index, msg.message, messageOffset, received - index); - remaining -= (received - index); - messageOffset += (received - index); - - // if payload isn't finished - while (remaining > 0) - { - // receive other payload data - received = channel.Receive(buffer); - Array.Copy(buffer, 0, msg.message, messageOffset, received); - remaining -= received; - messageOffset += received; - } - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PUBLISH", - new object[] { "messageId", "topic", "message" }, - new object[] { this.messageId, this.topic, this.message }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishEventArgs.cs deleted file mode 100644 index efb2333..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishEventArgs.cs +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for PUBLISH message received from broker - /// - public class MqttMsgPublishEventArgs : EventArgs - { - #region Properties... - - /// - /// Message topic - /// - public string Topic - { - get { return this.topic; } - internal set { this.topic = value; } - } - - /// - /// Message data - /// - public byte[] Message - { - get { return this.message; } - internal set { this.message = value; } - } - - /// - /// Duplicate message flag - /// - public bool DupFlag - { - get { return this.dupFlag; } - set { this.dupFlag = value; } - } - - /// - /// Quality of Service level - /// - public byte QosLevel - { - get { return this.qosLevel; } - internal set { this.qosLevel = value; } - } - - /// - /// Retain message flag - /// - public bool Retain - { - get { return this.retain; } - internal set { this.retain = value; } - } - - #endregion - - // message topic - private string topic; - // message data - private byte[] message; - // duplicate delivery - private bool dupFlag; - // quality of service level - private byte qosLevel; - // retain flag - private bool retain; - - /// - /// Constructor - /// - /// Message topic - /// Message data - /// Duplicate delivery flag - /// Quality of Service level - /// Retain flag - public MqttMsgPublishEventArgs(string topic, - byte[] message, - bool dupFlag, - byte qosLevel, - bool retain) - { - this.topic = topic; - this.message = message; - this.dupFlag = dupFlag; - this.qosLevel = qosLevel; - this.retain = retain; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishedEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishedEventArgs.cs deleted file mode 100644 index e507c38..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPublishedEventArgs.cs +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for published message - /// - public class MqttMsgPublishedEventArgs : EventArgs - { - #region Properties... - - /// - /// Message identifier - /// - public ushort MessageId - { - get { return this.messageId; } - internal set { this.messageId = value; } - } - - /// - /// Message published (or failed due to retries) - /// - public bool IsPublished - { - get { return this.isPublished; } - internal set { this.isPublished = value; } - } - - #endregion - - // message identifier - ushort messageId; - - // published flag - bool isPublished; - - /// - /// Constructor (published message) - /// - /// Message identifier published - public MqttMsgPublishedEventArgs(ushort messageId) - : this(messageId, true) - { - } - - /// - /// Constructor - /// - /// Message identifier - /// Publish flag - public MqttMsgPublishedEventArgs(ushort messageId, bool isPublished) - { - this.messageId = messageId; - this.isPublished = isPublished; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrec.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrec.cs deleted file mode 100644 index 1855bf9..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrec.cs +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PUBREC message from broker to client - /// - public class MqttMsgPubrec : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPubrec() - { - this.type = MQTT_MSG_PUBREC_TYPE; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PUBREC_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PUBREC_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (MQTT_MSG_PUBREC_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // get message identifier - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - return buffer; - } - - /// - /// Parse bytes for a PUBREC message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PUBREC message instance - public static MqttMsgPubrec Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgPubrec msg = new MqttMsgPubrec(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PUBREC_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PUBREC", - new object[] { "messageId" }, - new object[] { this.messageId }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrel.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrel.cs deleted file mode 100644 index e43ca91..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgPubrel.cs +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for PUBREL message from client top broker - /// - public class MqttMsgPubrel : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgPubrel() - { - this.type = MQTT_MSG_PUBREL_TYPE; - // PUBREL message use QoS Level 1 (not "officially" in 3.1.1) - this.qosLevel = QOS_LEVEL_AT_LEAST_ONCE; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_PUBREL_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PUBREL_FLAG_BITS; // [v.3.1.1] - else - { - buffer[index] = (byte)((MQTT_MSG_PUBREL_TYPE << MSG_TYPE_OFFSET) | - (this.qosLevel << QOS_LEVEL_OFFSET)); - buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; - index++; - } - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // get next message identifier - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - return buffer; - } - - /// - /// Parse bytes for a PUBREL message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// PUBREL message instance - public static MqttMsgPubrel Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgPubrel msg = new MqttMsgPubrel(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PUBREL_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1) - { - // only 3.1.0 - - // read QoS level from fixed header (would be QoS Level 1) - msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); - // read DUP flag from fixed header - msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); - } - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - return msg; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "PUBREL", - new object[] { "messageId" }, - new object[] { this.messageId }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSuback.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSuback.cs deleted file mode 100644 index 6ecfd0d..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSuback.cs +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for SUBACK message from broker to client - /// - public class MqttMsgSuback : MqttMsgBase - { - #region Properties... - - /// - /// List of granted QOS Levels - /// - public byte[] GrantedQoSLevels - { - get { return this.grantedQosLevels; } - set { this.grantedQosLevels = value; } - } - - #endregion - - // granted QOS levels - byte[] grantedQosLevels; - - /// - /// Constructor - /// - public MqttMsgSuback() - { - this.type = MQTT_MSG_SUBACK_TYPE; - } - - /// - /// Parse bytes for a SUBACK message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// SUBACK message instance - public static MqttMsgSuback Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgSuback msg = new MqttMsgSuback(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_SUBACK_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - // payload contains QoS levels granted - msg.grantedQosLevels = new byte[remainingLength - MESSAGE_ID_SIZE]; - int qosIdx = 0; - do - { - msg.grantedQosLevels[qosIdx++] = buffer[index++]; - } while (index < remainingLength); - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - int grantedQosIdx = 0; - for (grantedQosIdx = 0; grantedQosIdx < this.grantedQosLevels.Length; grantedQosIdx++) - { - payloadSize++; - } - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_SUBACK_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_SUBACK_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (byte)(MQTT_MSG_SUBACK_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // message id - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - // payload contains QoS levels granted - for (grantedQosIdx = 0; grantedQosIdx < this.grantedQosLevels.Length; grantedQosIdx++) - { - buffer[index++] = this.grantedQosLevels[grantedQosIdx]; - } - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "SUBACK", - new object[] { "messageId", "grantedQosLevels" }, - new object[] { this.messageId, this.grantedQosLevels }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribe.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribe.cs deleted file mode 100644 index 0e3927e..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribe.cs +++ /dev/null @@ -1,272 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -// if NOT .Net Micro Framework -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System.Collections.Generic; -#endif -using System.Collections; -using System.Text; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for SUBSCRIBE message from client to broker - /// - public class MqttMsgSubscribe : MqttMsgBase - { - #region Properties... - - /// - /// List of topics to subscribe - /// - public string[] Topics - { - get { return this.topics; } - set { this.topics = value; } - } - - /// - /// List of QOS Levels related to topics - /// - public byte[] QoSLevels - { - get { return this.qosLevels; } - set { this.qosLevels = value; } - } - - #endregion - - // topics to subscribe - string[] topics; - // QOS levels related to topics - byte[] qosLevels; - - /// - /// Constructor - /// - public MqttMsgSubscribe() - { - this.type = MQTT_MSG_SUBSCRIBE_TYPE; - } - - /// - /// Constructor - /// - /// List of topics to subscribe - /// List of QOS Levels related to topics - public MqttMsgSubscribe(string[] topics, byte[] qosLevels) - { - this.type = MQTT_MSG_SUBSCRIBE_TYPE; - - this.topics = topics; - this.qosLevels = qosLevels; - - // SUBSCRIBE message uses QoS Level 1 (not "officially" in 3.1.1) - this.qosLevel = QOS_LEVEL_AT_LEAST_ONCE; - } - - /// - /// Parse bytes for a SUBSCRIBE message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// SUBSCRIBE message instance - public static MqttMsgSubscribe Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - byte[] topicUtf8; - int topicUtf8Length; - MqttMsgSubscribe msg = new MqttMsgSubscribe(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_SUBSCRIBE_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - int received = channel.Receive(buffer); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1) - { - // only 3.1.0 - - // read QoS level from fixed header - msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); - // read DUP flag from fixed header - msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); - // retain flag not used - msg.retain = false; - } - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - // payload contains topics and QoS levels - // NOTE : before, I don't know how many topics will be in the payload (so use List) - -// if .Net Micro Framework -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - IList tmpTopics = new ArrayList(); - IList tmpQosLevels = new ArrayList(); -// else other frameworks (.Net, .Net Compact, Mono, Windows Phone) -#else - IList tmpTopics = new List(); - IList tmpQosLevels = new List(); -#endif - do - { - // topic name - topicUtf8Length = ((buffer[index++] << 8) & 0xFF00); - topicUtf8Length |= buffer[index++]; - topicUtf8 = new byte[topicUtf8Length]; - Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length); - index += topicUtf8Length; - tmpTopics.Add(new String(Encoding.UTF8.GetChars(topicUtf8))); - - // QoS level - tmpQosLevels.Add(buffer[index++]); - - } while (index < remainingLength); - - // copy from list to array - msg.topics = new string[tmpTopics.Count]; - msg.qosLevels = new byte[tmpQosLevels.Count]; - for (int i = 0; i < tmpTopics.Count; i++) - { - msg.topics[i] = (string)tmpTopics[i]; - msg.qosLevels[i] = (byte)tmpQosLevels[i]; - } - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // topics list empty - if ((this.topics == null) || (this.topics.Length == 0)) - throw new MqttClientException(MqttClientErrorCode.TopicsEmpty); - - // qos levels list empty - if ((this.qosLevels == null) || (this.qosLevels.Length == 0)) - throw new MqttClientException(MqttClientErrorCode.QosLevelsEmpty); - - // topics and qos levels lists length don't match - if (this.topics.Length != this.qosLevels.Length) - throw new MqttClientException(MqttClientErrorCode.TopicsQosLevelsNotMatch); - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - int topicIdx = 0; - byte[][] topicsUtf8 = new byte[this.topics.Length][]; - - for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) - { - // check topic length - if ((this.topics[topicIdx].Length < MIN_TOPIC_LENGTH) || (this.topics[topicIdx].Length > MAX_TOPIC_LENGTH)) - throw new MqttClientException(MqttClientErrorCode.TopicLength); - - topicsUtf8[topicIdx] = Encoding.UTF8.GetBytes(this.topics[topicIdx]); - payloadSize += 2; // topic size (MSB, LSB) - payloadSize += topicsUtf8[topicIdx].Length; - payloadSize++; // byte for QoS - } - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_SUBSCRIBE_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_SUBSCRIBE_FLAG_BITS; // [v.3.1.1] - else - { - buffer[index] = (byte)((MQTT_MSG_SUBSCRIBE_TYPE << MSG_TYPE_OFFSET) | - (this.qosLevel << QOS_LEVEL_OFFSET)); - buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; - index++; - } - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // check message identifier assigned (SUBSCRIBE uses QoS Level 1, so message id is mandatory) - if (this.messageId == 0) - throw new MqttClientException(MqttClientErrorCode.WrongMessageId); - buffer[index++] = (byte)((messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(messageId & 0x00FF); // LSB - - topicIdx = 0; - for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) - { - // topic name - buffer[index++] = (byte)((topicsUtf8[topicIdx].Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(topicsUtf8[topicIdx].Length & 0x00FF); // LSB - Array.Copy(topicsUtf8[topicIdx], 0, buffer, index, topicsUtf8[topicIdx].Length); - index += topicsUtf8[topicIdx].Length; - - // requested QoS - buffer[index++] = this.qosLevels[topicIdx]; - } - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "SUBSCRIBE", - new object[] { "messageId", "topics", "qosLevels" }, - new object[] { this.messageId, this.topics, this.qosLevels }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribeEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribeEventArgs.cs deleted file mode 100644 index 91c85f9..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribeEventArgs.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for subscribe request on topics - /// - public class MqttMsgSubscribeEventArgs : EventArgs - { - #region Properties... - - /// - /// Message identifier - /// - public ushort MessageId - { - get { return this.messageId; } - internal set { this.messageId = value; } - } - - /// - /// Topics requested to subscribe - /// - public string[] Topics - { - get { return this.topics; } - internal set { this.topics = value; } - } - - /// - /// List of QOS Levels requested - /// - public byte[] QoSLevels - { - get { return this.qosLevels; } - internal set { this.qosLevels = value; } - } - - #endregion - - // message identifier - ushort messageId; - // topics requested to subscribe - string[] topics; - // QoS levels requested - byte[] qosLevels; - - /// - /// Constructor - /// - /// Message identifier for subscribe topics request - /// Topics requested to subscribe - /// List of QOS Levels requested - public MqttMsgSubscribeEventArgs(ushort messageId, string[] topics, byte[] qosLevels) - { - this.messageId = messageId; - this.topics = topics; - this.qosLevels = qosLevels; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribedEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribedEventArgs.cs deleted file mode 100644 index 58bbb22..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgSubscribedEventArgs.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for subscribed topics - /// - public class MqttMsgSubscribedEventArgs : EventArgs - { - #region Properties... - - /// - /// Message identifier - /// - public ushort MessageId - { - get { return this.messageId; } - internal set { this.messageId = value; } - } - - /// - /// List of granted QOS Levels - /// - public byte[] GrantedQoSLevels - { - get { return this.grantedQosLevels; } - internal set { this.grantedQosLevels = value; } - } - - #endregion - - // message identifier - ushort messageId; - // granted QOS levels - byte[] grantedQosLevels; - - /// - /// Constructor - /// - /// Message identifier for subscribed topics - /// List of granted QOS Levels - public MqttMsgSubscribedEventArgs(ushort messageId, byte[] grantedQosLevels) - { - this.messageId = messageId; - this.grantedQosLevels = grantedQosLevels; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsuback.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsuback.cs deleted file mode 100644 index 8e49a06..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsuback.cs +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for UNSUBACK message from broker to client - /// - public class MqttMsgUnsuback : MqttMsgBase - { - /// - /// Constructor - /// - public MqttMsgUnsuback() - { - this.type = MQTT_MSG_UNSUBACK_TYPE; - } - - /// - /// Parse bytes for a UNSUBACK message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// UNSUBACK message instance - public static MqttMsgUnsuback Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - MqttMsgUnsuback msg = new MqttMsgUnsuback(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_UNSUBACK_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - channel.Receive(buffer); - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_UNSUBACK_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_UNSUBACK_FLAG_BITS; // [v.3.1.1] - else - buffer[index++] = (byte)(MQTT_MSG_UNSUBACK_TYPE << MSG_TYPE_OFFSET); - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // message id - buffer[index++] = (byte)((this.messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(this.messageId & 0x00FF); // LSB - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "UNSUBACK", - new object[] { "messageId" }, - new object[] { this.messageId }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribe.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribe.cs deleted file mode 100644 index e485133..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribe.cs +++ /dev/null @@ -1,239 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -// if NOT .Net Micro Framework -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System.Collections.Generic; -#endif -using System.Collections; -using System.Text; -using uPLibrary.Networking.M2Mqtt.Exceptions; - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Class for UNSUBSCRIBE message from client to broker - /// - public class MqttMsgUnsubscribe : MqttMsgBase - { - #region Properties... - - /// - /// List of topics to unsubscribe - /// - public string[] Topics - { - get { return this.topics; } - set { this.topics = value; } - } - - #endregion - - // topics to unsubscribe - string[] topics; - - /// - /// Constructor - /// - public MqttMsgUnsubscribe() - { - this.type = MQTT_MSG_UNSUBSCRIBE_TYPE; - } - - /// - /// Constructor - /// - /// List of topics to unsubscribe - public MqttMsgUnsubscribe(string[] topics) - { - this.type = MQTT_MSG_UNSUBSCRIBE_TYPE; - - this.topics = topics; - - // UNSUBSCRIBE message uses QoS Level 1 (not "officially" in 3.1.1) - this.qosLevel = QOS_LEVEL_AT_LEAST_ONCE; - } - - /// - /// Parse bytes for a UNSUBSCRIBE message - /// - /// First fixed header byte - /// Protocol Version - /// Channel connected to the broker - /// UNSUBSCRIBE message instance - public static MqttMsgUnsubscribe Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel) - { - byte[] buffer; - int index = 0; - byte[] topicUtf8; - int topicUtf8Length; - MqttMsgUnsubscribe msg = new MqttMsgUnsubscribe(); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - { - // [v3.1.1] check flag bits - if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_UNSUBSCRIBE_FLAG_BITS) - throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits); - } - - // get remaining length and allocate buffer - int remainingLength = MqttMsgBase.decodeRemainingLength(channel); - buffer = new byte[remainingLength]; - - // read bytes from socket... - int received = channel.Receive(buffer); - - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1) - { - // only 3.1.0 - - // read QoS level from fixed header - msg.qosLevel = (byte)((fixedHeaderFirstByte & QOS_LEVEL_MASK) >> QOS_LEVEL_OFFSET); - // read DUP flag from fixed header - msg.dupFlag = (((fixedHeaderFirstByte & DUP_FLAG_MASK) >> DUP_FLAG_OFFSET) == 0x01); - // retain flag not used - msg.retain = false; - } - - // message id - msg.messageId = (ushort)((buffer[index++] << 8) & 0xFF00); - msg.messageId |= (buffer[index++]); - - // payload contains topics - // NOTE : before, I don't know how many topics will be in the payload (so use List) - -// if .Net Micro Framework -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - IList tmpTopics = new ArrayList(); -// else other frameworks (.Net, .Net Compact, Mono, Windows Phone) -#else - IList tmpTopics = new List(); -#endif - do - { - // topic name - topicUtf8Length = ((buffer[index++] << 8) & 0xFF00); - topicUtf8Length |= buffer[index++]; - topicUtf8 = new byte[topicUtf8Length]; - Array.Copy(buffer, index, topicUtf8, 0, topicUtf8Length); - index += topicUtf8Length; - tmpTopics.Add(new String(Encoding.UTF8.GetChars(topicUtf8))); - } while (index < remainingLength); - - // copy from list to array - msg.topics = new string[tmpTopics.Count]; - for (int i = 0; i < tmpTopics.Count; i++) - { - msg.topics[i] = (string)tmpTopics[i]; - } - - return msg; - } - - public override byte[] GetBytes(byte protocolVersion) - { - int fixedHeaderSize = 0; - int varHeaderSize = 0; - int payloadSize = 0; - int remainingLength = 0; - byte[] buffer; - int index = 0; - - // topics list empty - if ((this.topics == null) || (this.topics.Length == 0)) - throw new MqttClientException(MqttClientErrorCode.TopicsEmpty); - - // message identifier - varHeaderSize += MESSAGE_ID_SIZE; - - int topicIdx = 0; - byte[][] topicsUtf8 = new byte[this.topics.Length][]; - - for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) - { - // check topic length - if ((this.topics[topicIdx].Length < MIN_TOPIC_LENGTH) || (this.topics[topicIdx].Length > MAX_TOPIC_LENGTH)) - throw new MqttClientException(MqttClientErrorCode.TopicLength); - - topicsUtf8[topicIdx] = Encoding.UTF8.GetBytes(this.topics[topicIdx]); - payloadSize += 2; // topic size (MSB, LSB) - payloadSize += topicsUtf8[topicIdx].Length; - } - - remainingLength += (varHeaderSize + payloadSize); - - // first byte of fixed header - fixedHeaderSize = 1; - - int temp = remainingLength; - // increase fixed header size based on remaining length - // (each remaining length byte can encode until 128) - do - { - fixedHeaderSize++; - temp = temp / 128; - } while (temp > 0); - - // allocate buffer for message - buffer = new byte[fixedHeaderSize + varHeaderSize + payloadSize]; - - // first fixed header byte - if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1) - buffer[index++] = (MQTT_MSG_UNSUBSCRIBE_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_UNSUBSCRIBE_FLAG_BITS; // [v.3.1.1] - else - { - buffer[index] = (byte)((MQTT_MSG_UNSUBSCRIBE_TYPE << MSG_TYPE_OFFSET) | - (this.qosLevel << QOS_LEVEL_OFFSET)); - buffer[index] |= this.dupFlag ? (byte)(1 << DUP_FLAG_OFFSET) : (byte)0x00; - index++; - } - - // encode remaining length - index = this.encodeRemainingLength(remainingLength, buffer, index); - - // check message identifier assigned - if (this.messageId == 0) - throw new MqttClientException(MqttClientErrorCode.WrongMessageId); - buffer[index++] = (byte)((messageId >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(messageId & 0x00FF); // LSB - - topicIdx = 0; - for (topicIdx = 0; topicIdx < this.topics.Length; topicIdx++) - { - // topic name - buffer[index++] = (byte)((topicsUtf8[topicIdx].Length >> 8) & 0x00FF); // MSB - buffer[index++] = (byte)(topicsUtf8[topicIdx].Length & 0x00FF); // LSB - Array.Copy(topicsUtf8[topicIdx], 0, buffer, index, topicsUtf8[topicIdx].Length); - index += topicsUtf8[topicIdx].Length; - } - - return buffer; - } - - public override string ToString() - { -#if TRACE - return this.GetTraceString( - "UNSUBSCRIBE", - new object[] { "messageId", "topics" }, - new object[] { this.messageId, this.topics }); -#else - return base.ToString(); -#endif - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribeEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribeEventArgs.cs deleted file mode 100644 index e158783..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribeEventArgs.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for unsubscribe request on topics - /// - public class MqttMsgUnsubscribeEventArgs : EventArgs - { - #region Properties... - - /// - /// Message identifier - /// - public ushort MessageId - { - get { return this.messageId; } - internal set { this.messageId = value; } - } - - /// - /// Topics requested to subscribe - /// - public string[] Topics - { - get { return this.topics; } - internal set { this.topics = value; } - } - - #endregion - - // message identifier - ushort messageId; - // topics requested to unsubscribe - string[] topics; - - /// - /// Constructor - /// - /// Message identifier for subscribed topics - /// Topics requested to subscribe - public MqttMsgUnsubscribeEventArgs(ushort messageId, string[] topics) - { - this.messageId = messageId; - this.topics = topics; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribedEventArgs.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribedEventArgs.cs deleted file mode 100644 index e65c383..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Messages/MqttMsgUnsubscribedEventArgs.cs +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) -using System; -#else -using Microsoft.SPOT; -#endif - -namespace uPLibrary.Networking.M2Mqtt.Messages -{ - /// - /// Event Args class for unsubscribed topic - /// - public class MqttMsgUnsubscribedEventArgs : EventArgs - { - #region Properties... - - /// - /// Message identifier - /// - public ushort MessageId - { - get { return this.messageId; } - internal set { this.messageId = value; } - } - - #endregion - - // message identifier - ushort messageId; - - /// - /// Constructor - /// - /// Message identifier for unsubscribed topic - public MqttMsgUnsubscribedEventArgs(ushort messageId) - { - this.messageId = messageId; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttClient.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/MqttClient.cs deleted file mode 100644 index 40745b5..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttClient.cs +++ /dev/null @@ -1,2631 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Net; -#if !(WINDOWS_APP || WINDOWS_PHONE_APP) -using System.Net.Sockets; -using System.Security.Cryptography.X509Certificates; -#endif -using System.Threading; -using uPLibrary.Networking.M2Mqtt.Exceptions; -using uPLibrary.Networking.M2Mqtt.Messages; -using uPLibrary.Networking.M2Mqtt.Session; -using uPLibrary.Networking.M2Mqtt.Utility; -using uPLibrary.Networking.M2Mqtt.Internal; -// if .Net Micro Framework -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) -using Microsoft.SPOT; -#if SSL -using Microsoft.SPOT.Net.Security; -#endif -// else other frameworks (.Net, .Net Compact, Mono, Windows Phone) -#else -using System.Collections.Generic; -#if (SSL && !(WINDOWS_APP || WINDOWS_PHONE_APP)) -using System.Security.Authentication; -using System.Net.Security; -#endif -#endif - -#if (WINDOWS_APP || WINDOWS_PHONE_APP) -using Windows.Networking.Sockets; -#endif - -using System.Collections; - -// alias needed due to Microsoft.SPOT.Trace in .Net Micro Framework -// (it's ambiguos with uPLibrary.Networking.M2Mqtt.Utility.Trace) -using MqttUtility = uPLibrary.Networking.M2Mqtt.Utility; -using System.IO; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// MQTT Client - /// - public class MqttClient - { -#if BROKER - #region Constants ... - - // thread names - private const string RECEIVE_THREAD_NAME = "ReceiveThread"; - private const string RECEIVE_EVENT_THREAD_NAME = "DispatchEventThread"; - private const string PROCESS_INFLIGHT_THREAD_NAME = "ProcessInflightThread"; - private const string KEEP_ALIVE_THREAD = "KeepAliveThread"; - - #endregion -#endif - - /// - /// Delagate that defines event handler for PUBLISH message received - /// - public delegate void MqttMsgPublishEventHandler(object sender, MqttMsgPublishEventArgs e); - - /// - /// Delegate that defines event handler for published message - /// - public delegate void MqttMsgPublishedEventHandler(object sender, MqttMsgPublishedEventArgs e); - - /// - /// Delagate that defines event handler for subscribed topic - /// - public delegate void MqttMsgSubscribedEventHandler(object sender, MqttMsgSubscribedEventArgs e); - - /// - /// Delagate that defines event handler for unsubscribed topic - /// - public delegate void MqttMsgUnsubscribedEventHandler(object sender, MqttMsgUnsubscribedEventArgs e); - -#if BROKER - /// - /// Delagate that defines event handler for SUBSCRIBE message received - /// - public delegate void MqttMsgSubscribeEventHandler(object sender, MqttMsgSubscribeEventArgs e); - - /// - /// Delagate that defines event handler for UNSUBSCRIBE message received - /// - public delegate void MqttMsgUnsubscribeEventHandler(object sender, MqttMsgUnsubscribeEventArgs e); - - /// - /// Delagate that defines event handler for CONNECT message received - /// - public delegate void MqttMsgConnectEventHandler(object sender, MqttMsgConnectEventArgs e); - - /// - /// Delegate that defines event handler for client disconnection (DISCONNECT message or not) - /// - public delegate void MqttMsgDisconnectEventHandler(object sender, EventArgs e); -#endif - - /// - /// Delegate that defines event handler for cliet/peer disconnection - /// - public delegate void ConnectionClosedEventHandler(object sender, EventArgs e); - - // broker hostname (or ip address) and port - private string brokerHostName; - private int brokerPort; - - // running status of threads - private bool isRunning; - // event for raising received message event - private AutoResetEvent receiveEventWaitHandle; - - // event for starting process inflight queue asynchronously - private AutoResetEvent inflightWaitHandle; - - // event for signaling synchronous receive - AutoResetEvent syncEndReceiving; - // message received - MqttMsgBase msgReceived; - - // exeption thrown during receiving - Exception exReceiving; - - // keep alive period (in ms) - private int keepAlivePeriod; - // events for signaling on keep alive thread - private AutoResetEvent keepAliveEvent; - private AutoResetEvent keepAliveEventEnd; - // last communication time in ticks - private int lastCommTime; - - // event for PUBLISH message received - public event MqttMsgPublishEventHandler MqttMsgPublishReceived; - // event for published message - public event MqttMsgPublishedEventHandler MqttMsgPublished; - // event for subscribed topic - public event MqttMsgSubscribedEventHandler MqttMsgSubscribed; - // event for unsubscribed topic - public event MqttMsgUnsubscribedEventHandler MqttMsgUnsubscribed; -#if BROKER - // event for SUBSCRIBE message received - public event MqttMsgSubscribeEventHandler MqttMsgSubscribeReceived; - // event for USUBSCRIBE message received - public event MqttMsgUnsubscribeEventHandler MqttMsgUnsubscribeReceived; - // event for CONNECT message received - public event MqttMsgConnectEventHandler MqttMsgConnected; - // event for DISCONNECT message received - public event MqttMsgDisconnectEventHandler MqttMsgDisconnected; -#endif - - // event for peer/client disconnection - public event ConnectionClosedEventHandler ConnectionClosed; - - // channel to communicate over the network - private IMqttNetworkChannel channel; - - // inflight messages queue - private Queue inflightQueue; - // internal queue for received messages about inflight messages - private Queue internalQueue; - // internal queue for dispatching events - private Queue eventQueue; - // session - private MqttClientSession session; - - // reference to avoid access to singleton via property - private MqttSettings settings; - - // current message identifier generated - private ushort messageIdCounter = 0; - - // connection is closing due to peer - private bool isConnectionClosing; - - /// - /// Connection status between client and broker - /// - public bool IsConnected { get; private set; } - - /// - /// Client identifier - /// - public string ClientId { get; private set; } - - /// - /// Clean session flag - /// - public bool CleanSession { get; private set; } - - /// - /// Will flag - /// - public bool WillFlag { get; private set; } - - /// - /// Will QOS level - /// - public byte WillQosLevel { get; private set; } - - /// - /// Will topic - /// - public string WillTopic { get; private set; } - - /// - /// Will message - /// - public string WillMessage { get; private set; } - - /// - /// MQTT protocol version - /// - public MqttProtocolVersion ProtocolVersion { get; set; } - -#if BROKER - /// - /// MQTT Client Session - /// - public MqttClientSession Session - { - get { return this.session; } - set { this.session = value; } - } -#endif - - /// - /// MQTT client settings - /// - public MqttSettings Settings - { - get { return this.settings; } - } - -#if !(WINDOWS_APP || WINDOWS_PHONE_APP) - /// - /// Constructor - /// - /// Broker IP address - [Obsolete("Use this ctor MqttClient(string brokerHostName) insted")] - public MqttClient(IPAddress brokerIpAddress) : - this(brokerIpAddress, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, null, null, MqttSslProtocols.None) - { - } - - /// - /// Constructor - /// - /// Broker IP address - /// Broker port - /// Using secure connection - /// CA certificate for secure connection - /// Client certificate - /// SSL/TLS protocol version - [Obsolete("Use this ctor MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert) insted")] - public MqttClient(IPAddress brokerIpAddress, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol) - { -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol, null, null); -#else - this.Init(brokerIpAddress.ToString(), brokerPort, secure, caCert, clientCert, sslProtocol); -#endif - } -#endif - - /// - /// Constructor - /// - /// Broker Host Name or IP Address - public MqttClient(string brokerHostName) : -#if !(WINDOWS_APP || WINDOWS_PHONE_APP) - this(brokerHostName, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, null, null, MqttSslProtocols.None) -#else - this(brokerHostName, MqttSettings.MQTT_BROKER_DEFAULT_PORT, false, MqttSslProtocols.None) -#endif - { - } - - /// - /// Constructor - /// - /// Broker Host Name or IP Address - /// Broker port - /// Using secure connection - /// SSL/TLS protocol version -#if !(WINDOWS_APP || WINDOWS_PHONE_APP) - /// CA certificate for secure connection - /// Client certificate - public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol) -#else - public MqttClient(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol) -#endif - { -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP) - this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, null, null); -#elif (WINDOWS_APP || WINDOWS_PHONE_APP) - this.Init(brokerHostName, brokerPort, secure, sslProtocol); -#else - this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol); -#endif - } - - -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP) - - /// - /// Constructor - /// - /// Broker Host Name or IP Address - /// Broker port - /// Using secure connection - /// CA certificate for secure connection - /// Client certificate - /// SSL/TLS protocol version - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback) - : this(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, null) - { - } - - /// - /// Constructor - /// - /// Broker Host Name or IP Address - /// Broker port - /// Using secure connection - /// SSL/TLS protocol version - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication - public MqttClient(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) - : this(brokerHostName, brokerPort, secure, null, null, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback) - { - } - - /// - /// Constructor - /// - /// Broker Host Name or IP Address - /// Broker port - /// Using secure connection - /// CA certificate for secure connection - /// Client certificate - /// SSL/TLS protocol version - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication - public MqttClient(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) - { - this.Init(brokerHostName, brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback); - } -#endif - -#if BROKER - /// - /// Constructor - /// - /// Network channel for communication - public MqttClient(IMqttNetworkChannel channel) - { - // set default MQTT protocol version (default is 3.1.1) - this.ProtocolVersion = MqttProtocolVersion.Version_3_1_1; - - this.channel = channel; - - // reference to MQTT settings - this.settings = MqttSettings.Instance; - - // client not connected yet (CONNACK not send from client), some default values - this.IsConnected = false; - this.ClientId = null; - this.CleanSession = true; - - this.keepAliveEvent = new AutoResetEvent(false); - - // queue for handling inflight messages (publishing and acknowledge) - this.inflightWaitHandle = new AutoResetEvent(false); - this.inflightQueue = new Queue(); - - // queue for received message - this.receiveEventWaitHandle = new AutoResetEvent(false); - this.eventQueue = new Queue(); - this.internalQueue = new Queue(); - - // session - this.session = null; - } -#endif - - /// - /// MqttClient initialization - /// - /// Broker Host Name or IP Address - /// Broker port - /// >Using secure connection - /// CA certificate for secure connection - /// Client certificate - /// SSL/TLS protocol version -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP) - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication - private void Init(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) -#elif (WINDOWS_APP || WINDOWS_PHONE_APP) - private void Init(string brokerHostName, int brokerPort, bool secure, MqttSslProtocols sslProtocol) -#else - private void Init(string brokerHostName, int brokerPort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol) -#endif - { - // set default MQTT protocol version (default is 3.1.1) - this.ProtocolVersion = MqttProtocolVersion.Version_3_1_1; -#if !SSL - // check security parameters - if (secure) - throw new ArgumentException("Library compiled without SSL support"); -#endif - - this.brokerHostName = brokerHostName; - this.brokerPort = brokerPort; - - // reference to MQTT settings - this.settings = MqttSettings.Instance; - // set settings port based on secure connection or not - if (!secure) - this.settings.Port = this.brokerPort; - else - this.settings.SslPort = this.brokerPort; - - this.syncEndReceiving = new AutoResetEvent(false); - this.keepAliveEvent = new AutoResetEvent(false); - - // queue for handling inflight messages (publishing and acknowledge) - this.inflightWaitHandle = new AutoResetEvent(false); - this.inflightQueue = new Queue(); - - // queue for received message - this.receiveEventWaitHandle = new AutoResetEvent(false); - this.eventQueue = new Queue(); - this.internalQueue = new Queue(); - - // session - this.session = null; - - // create network channel -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP) - this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, caCert, clientCert, sslProtocol, userCertificateValidationCallback, userCertificateSelectionCallback); -#elif (WINDOWS_APP || WINDOWS_PHONE_APP) - this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, sslProtocol); -#else - this.channel = new MqttNetworkChannel(this.brokerHostName, this.brokerPort, secure, caCert, clientCert, sslProtocol); -#endif - } - - /// - /// Connect to broker - /// - /// Client identifier - /// Return code of CONNACK message from broker - public byte Connect(string clientId) - { - return this.Connect(clientId, null, null, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, true, MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT); - } - - /// - /// Connect to broker - /// - /// Client identifier - /// Username - /// Password - /// Return code of CONNACK message from broker - public byte Connect(string clientId, - string username, - string password) - { - return this.Connect(clientId, username, password, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, true, MqttMsgConnect.KEEP_ALIVE_PERIOD_DEFAULT); - } - - /// - /// Connect to broker - /// - /// Client identifier - /// Username - /// Password - /// Clean sessione flag - /// Keep alive period - /// Return code of CONNACK message from broker - public byte Connect(string clientId, - string username, - string password, - bool cleanSession, - ushort keepAlivePeriod) - { - return this.Connect(clientId, username, password, false, MqttMsgConnect.QOS_LEVEL_AT_MOST_ONCE, false, null, null, cleanSession, keepAlivePeriod); - } - - /// - /// Connect to broker - /// - /// Client identifier - /// Username - /// Password - /// Will retain flag - /// Will QOS level - /// Will flag - /// Will topic - /// Will message - /// Clean sessione flag - /// Keep alive period - /// Return code of CONNACK message from broker - public byte Connect(string clientId, - string username, - string password, - bool willRetain, - byte willQosLevel, - bool willFlag, - string willTopic, - string willMessage, - bool cleanSession, - ushort keepAlivePeriod) - { - // create CONNECT message - MqttMsgConnect connect = new MqttMsgConnect(clientId, - username, - password, - willRetain, - willQosLevel, - willFlag, - willTopic, - willMessage, - cleanSession, - keepAlivePeriod, - (byte)this.ProtocolVersion); - - try - { - // connect to the broker - this.channel.Connect(); - } - catch (Exception ex) - { - throw new MqttConnectionException("Exception connecting to the broker", ex); - } - - this.lastCommTime = 0; - this.isRunning = true; - this.isConnectionClosing = false; - // start thread for receiving messages from broker - Fx.StartThread(this.ReceiveThread); - - MqttMsgConnack connack = (MqttMsgConnack)this.SendReceive(connect); - // if connection accepted, start keep alive timer and - if (connack.ReturnCode == MqttMsgConnack.CONN_ACCEPTED) - { - // set all client properties - this.ClientId = clientId; - this.CleanSession = cleanSession; - this.WillFlag = willFlag; - this.WillTopic = willTopic; - this.WillMessage = willMessage; - this.WillQosLevel = willQosLevel; - - this.keepAlivePeriod = keepAlivePeriod * 1000; // convert in ms - - // restore previous session - this.RestoreSession(); - - // keep alive period equals zero means turning off keep alive mechanism - if (this.keepAlivePeriod != 0) - { - // start thread for sending keep alive message to the broker - Fx.StartThread(this.KeepAliveThread); - } - - // start thread for raising received message event from broker - Fx.StartThread(this.DispatchEventThread); - - // start thread for handling inflight messages queue to broker asynchronously (publish and acknowledge) - Fx.StartThread(this.ProcessInflightThread); - - this.IsConnected = true; - } - return connack.ReturnCode; - } - - /// - /// Disconnect from broker - /// - public void Disconnect() - { - MqttMsgDisconnect disconnect = new MqttMsgDisconnect(); - this.Send(disconnect); - - // close client - this.OnConnectionClosing(); - } - -#if BROKER - /// - /// Open client communication - /// - public void Open() - { - this.isRunning = true; - - // start thread for receiving messages from client - Fx.StartThread(this.ReceiveThread); - - // start thread for raising received message event from client - Fx.StartThread(this.DispatchEventThread); - - // start thread for handling inflight messages queue to client asynchronously (publish and acknowledge) - Fx.StartThread(this.ProcessInflightThread); - } -#endif - - /// - /// Close client - /// -#if BROKER - public void Close() -#else - private void Close() -#endif - { - // stop receiving thread - this.isRunning = false; - - // wait end receive event thread - if (this.receiveEventWaitHandle != null) - this.receiveEventWaitHandle.Set(); - - // wait end process inflight thread - if (this.inflightWaitHandle != null) - this.inflightWaitHandle.Set(); - -#if BROKER - // unlock keep alive thread - this.keepAliveEvent.Set(); -#else - // unlock keep alive thread and wait - this.keepAliveEvent.Set(); - - if (this.keepAliveEventEnd != null) - this.keepAliveEventEnd.WaitOne(); -#endif - - // clear all queues - this.inflightQueue.Clear(); - this.internalQueue.Clear(); - this.eventQueue.Clear(); - - // close network channel - this.channel.Close(); - - this.IsConnected = false; - } - - /// - /// Execute ping to broker for keep alive - /// - /// PINGRESP message from broker - private MqttMsgPingResp Ping() - { - MqttMsgPingReq pingreq = new MqttMsgPingReq(); - try - { - // broker must send PINGRESP within timeout equal to keep alive period - return (MqttMsgPingResp)this.SendReceive(pingreq, this.keepAlivePeriod); - } - catch (Exception e) - { -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString()); -#endif - - // client must close connection - this.OnConnectionClosing(); - return null; - } - } - -#if BROKER - /// - /// Send CONNACK message to the client (connection accepted or not) - /// - /// CONNECT message with all client information - /// Return code for CONNACK message - /// If not null, client id assigned by broker - /// Session present on the broker - public void Connack(MqttMsgConnect connect, byte returnCode, string clientId, bool sessionPresent) - { - this.lastCommTime = 0; - - // create CONNACK message and ... - MqttMsgConnack connack = new MqttMsgConnack(); - connack.ReturnCode = returnCode; - // [v3.1.1] session present flag - if (this.ProtocolVersion == MqttProtocolVersion.Version_3_1_1) - connack.SessionPresent = sessionPresent; - // ... send it to the client - this.Send(connack); - - // connection accepted, start keep alive thread checking - if (connack.ReturnCode == MqttMsgConnack.CONN_ACCEPTED) - { - // [v3.1.1] if client id isn't null, the CONNECT message has a cliend id with zero bytes length - // and broker assigned a unique identifier to the client - this.ClientId = (clientId == null) ? connect.ClientId : clientId; - this.CleanSession = connect.CleanSession; - this.WillFlag = connect.WillFlag; - this.WillTopic = connect.WillTopic; - this.WillMessage = connect.WillMessage; - this.WillQosLevel = connect.WillQosLevel; - - this.keepAlivePeriod = connect.KeepAlivePeriod * 1000; // convert in ms - // broker has a tolerance of 1.5 specified keep alive period - this.keepAlivePeriod += (this.keepAlivePeriod / 2); - - // start thread for checking keep alive period timeout - Fx.StartThread(this.KeepAliveThread); - - this.isConnectionClosing = false; - this.IsConnected = true; - } - // connection refused, close TCP/IP channel - else - { - this.Close(); - } - } - - /// - /// Send SUBACK message to the client - /// - /// Message Id for the SUBSCRIBE message that is being acknowledged - /// Granted QoS Levels - public void Suback(ushort messageId, byte[] grantedQosLevels) - { - MqttMsgSuback suback = new MqttMsgSuback(); - suback.MessageId = messageId; - suback.GrantedQoSLevels = grantedQosLevels; - - this.Send(suback); - } - - /// - /// Send UNSUBACK message to the client - /// - /// Message Id for the UNSUBSCRIBE message that is being acknowledged - public void Unsuback(ushort messageId) - { - MqttMsgUnsuback unsuback = new MqttMsgUnsuback(); - unsuback.MessageId = messageId; - - this.Send(unsuback); - } -#endif - - /// - /// Subscribe for message topics - /// - /// List of topics to subscribe - /// QOS levels related to topics - /// Message Id related to SUBSCRIBE message - public ushort Subscribe(string[] topics, byte[] qosLevels) - { - MqttMsgSubscribe subscribe = - new MqttMsgSubscribe(topics, qosLevels); - subscribe.MessageId = this.GetMessageId(); - - // enqueue subscribe request into the inflight queue - this.EnqueueInflight(subscribe, MqttMsgFlow.ToPublish); - - return subscribe.MessageId; - } - - /// - /// Unsubscribe for message topics - /// - /// List of topics to unsubscribe - /// Message Id in UNSUBACK message from broker - public ushort Unsubscribe(string[] topics) - { - MqttMsgUnsubscribe unsubscribe = - new MqttMsgUnsubscribe(topics); - unsubscribe.MessageId = this.GetMessageId(); - - // enqueue unsubscribe request into the inflight queue - this.EnqueueInflight(unsubscribe, MqttMsgFlow.ToPublish); - - return unsubscribe.MessageId; - } - - /// - /// Publish a message asynchronously (QoS Level 0 and not retained) - /// - /// Message topic - /// Message data (payload) - /// Message Id related to PUBLISH message - public ushort Publish(string topic, byte[] message) - { - return this.Publish(topic, message, MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, false); - } - - /// - /// Publish a message asynchronously - /// - /// Message topic - /// Message data (payload) - /// QoS Level - /// Retain flag - /// Message Id related to PUBLISH message - public ushort Publish(string topic, byte[] message, byte qosLevel, bool retain) - { - MqttMsgPublish publish = - new MqttMsgPublish(topic, message, false, qosLevel, retain); - publish.MessageId = this.GetMessageId(); - - // enqueue message to publish into the inflight queue - bool enqueue = this.EnqueueInflight(publish, MqttMsgFlow.ToPublish); - - // message enqueued - if (enqueue) - return publish.MessageId; - // infligh queue full, message not enqueued - else - throw new MqttClientException(MqttClientErrorCode.InflightQueueFull); - } - - /// - /// Wrapper method for raising events - /// - /// Internal event - private void OnInternalEvent(InternalEvent internalEvent) - { - lock (this.eventQueue) - { - this.eventQueue.Enqueue(internalEvent); - } - - this.receiveEventWaitHandle.Set(); - } - - /// - /// Wrapper method for raising closing connection event - /// - private void OnConnectionClosing() - { - if (!this.isConnectionClosing) - { - this.isConnectionClosing = true; - this.receiveEventWaitHandle.Set(); - } - } - - /// - /// Wrapper method for raising PUBLISH message received event - /// - /// PUBLISH message received - private void OnMqttMsgPublishReceived(MqttMsgPublish publish) - { - if (this.MqttMsgPublishReceived != null) - { - this.MqttMsgPublishReceived(this, - new MqttMsgPublishEventArgs(publish.Topic, publish.Message, publish.DupFlag, publish.QosLevel, publish.Retain)); - } - } - - /// - /// Wrapper method for raising published message event - /// - /// Message identifier for published message - /// Publish flag - private void OnMqttMsgPublished(ushort messageId, bool isPublished) - { - if (this.MqttMsgPublished != null) - { - this.MqttMsgPublished(this, - new MqttMsgPublishedEventArgs(messageId, isPublished)); - } - } - - /// - /// Wrapper method for raising subscribed topic event - /// - /// SUBACK message received - private void OnMqttMsgSubscribed(MqttMsgSuback suback) - { - if (this.MqttMsgSubscribed != null) - { - this.MqttMsgSubscribed(this, - new MqttMsgSubscribedEventArgs(suback.MessageId, suback.GrantedQoSLevels)); - } - } - - /// - /// Wrapper method for raising unsubscribed topic event - /// - /// Message identifier for unsubscribed topic - private void OnMqttMsgUnsubscribed(ushort messageId) - { - if (this.MqttMsgUnsubscribed != null) - { - this.MqttMsgUnsubscribed(this, - new MqttMsgUnsubscribedEventArgs(messageId)); - } - } - -#if BROKER - /// - /// Wrapper method for raising SUBSCRIBE message event - /// - /// Message identifier for subscribe topics request - /// Topics requested to subscribe - /// List of QOS Levels requested - private void OnMqttMsgSubscribeReceived(ushort messageId, string[] topics, byte[] qosLevels) - { - if (this.MqttMsgSubscribeReceived != null) - { - this.MqttMsgSubscribeReceived(this, - new MqttMsgSubscribeEventArgs(messageId, topics, qosLevels)); - } - } - - /// - /// Wrapper method for raising UNSUBSCRIBE message event - /// - /// Message identifier for unsubscribe topics request - /// Topics requested to unsubscribe - private void OnMqttMsgUnsubscribeReceived(ushort messageId, string[] topics) - { - if (this.MqttMsgUnsubscribeReceived != null) - { - this.MqttMsgUnsubscribeReceived(this, - new MqttMsgUnsubscribeEventArgs(messageId, topics)); - } - } - - /// - /// Wrapper method for raising CONNECT message event - /// - private void OnMqttMsgConnected(MqttMsgConnect connect) - { - if (this.MqttMsgConnected != null) - { - this.ProtocolVersion = (MqttProtocolVersion)connect.ProtocolVersion; - this.MqttMsgConnected(this, new MqttMsgConnectEventArgs(connect)); - } - } - - /// - /// Wrapper method for raising DISCONNECT message event - /// - private void OnMqttMsgDisconnected() - { - if (this.MqttMsgDisconnected != null) - { - this.MqttMsgDisconnected(this, EventArgs.Empty); - } - } -#endif - - /// - /// Wrapper method for peer/client disconnection - /// - private void OnConnectionClosed() - { - if (this.ConnectionClosed != null) - { - this.ConnectionClosed(this, EventArgs.Empty); - } - } - - /// - /// Send a message - /// - /// Message bytes - private void Send(byte[] msgBytes) - { - try - { - // send message - this.channel.Send(msgBytes); - -#if !BROKER - // update last message sent ticks - this.lastCommTime = Environment.TickCount; -#endif - } - catch (Exception e) - { -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString()); -#endif - - throw new MqttCommunicationException(e); - } - } - - /// - /// Send a message - /// - /// Message - private void Send(MqttMsgBase msg) - { -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "SEND {0}", msg); -#endif - this.Send(msg.GetBytes((byte)this.ProtocolVersion)); - } - - /// - /// Send a message to the broker and wait answer - /// - /// Message bytes - /// MQTT message response - private MqttMsgBase SendReceive(byte[] msgBytes) - { - return this.SendReceive(msgBytes, MqttSettings.MQTT_DEFAULT_TIMEOUT); - } - - /// - /// Send a message to the broker and wait answer - /// - /// Message bytes - /// Timeout for receiving answer - /// MQTT message response - private MqttMsgBase SendReceive(byte[] msgBytes, int timeout) - { - // reset handle before sending - this.syncEndReceiving.Reset(); - try - { - // send message - this.channel.Send(msgBytes); - - // update last message sent ticks - this.lastCommTime = Environment.TickCount; - } - catch (Exception e) - { -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK || WINDOWS_APP || WINDOWS_PHONE_APP) - if (typeof(SocketException) == e.GetType()) - { - // connection reset by broker - if (((SocketException)e).SocketErrorCode == SocketError.ConnectionReset) - this.IsConnected = false; - } -#endif -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString()); -#endif - - throw new MqttCommunicationException(e); - } - -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - // wait for answer from broker - if (this.syncEndReceiving.WaitOne(timeout, false)) -#else - // wait for answer from broker - if (this.syncEndReceiving.WaitOne(timeout)) -#endif - { - // message received without exception - if (this.exReceiving == null) - return this.msgReceived; - // receiving thread catched exception - else - throw this.exReceiving; - } - else - { - // throw timeout exception - throw new MqttCommunicationException(); - } - } - - /// - /// Send a message to the broker and wait answer - /// - /// Message - /// MQTT message response - private MqttMsgBase SendReceive(MqttMsgBase msg) - { - return this.SendReceive(msg, MqttSettings.MQTT_DEFAULT_TIMEOUT); - } - - /// - /// Send a message to the broker and wait answer - /// - /// Message - /// Timeout for receiving answer - /// MQTT message response - private MqttMsgBase SendReceive(MqttMsgBase msg, int timeout) - { -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "SEND {0}", msg); -#endif - return this.SendReceive(msg.GetBytes((byte)this.ProtocolVersion), timeout); - } - - /// - /// Enqueue a message into the inflight queue - /// - /// Message to enqueue - /// Message flow (publish, acknowledge) - /// Message enqueued or not - private bool EnqueueInflight(MqttMsgBase msg, MqttMsgFlow flow) - { - // enqueue is needed (or not) - bool enqueue = true; - - // if it is a PUBLISH message with QoS Level 2 - if ((msg.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE)) - { - lock (this.inflightQueue) - { - // if it is a PUBLISH message already received (it is in the inflight queue), the publisher - // re-sent it because it didn't received the PUBREC. In this case, we have to re-send PUBREC - - // NOTE : I need to find on message id and flow because the broker could be publish/received - // to/from client and message id could be the same (one tracked by broker and the other by client) - MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToAcknowledge); - MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find); - - // the PUBLISH message is alredy in the inflight queue, we don't need to re-enqueue but we need - // to change state to re-send PUBREC - if (msgCtx != null) - { - msgCtx.State = MqttMsgState.QueuedQos2; - msgCtx.Flow = MqttMsgFlow.ToAcknowledge; - enqueue = false; - } - } - } - - if (enqueue) - { - // set a default state - MqttMsgState state = MqttMsgState.QueuedQos0; - - // based on QoS level, the messages flow between broker and client changes - switch (msg.QosLevel) - { - // QoS Level 0 - case MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE: - - state = MqttMsgState.QueuedQos0; - break; - - // QoS Level 1 - case MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE: - - state = MqttMsgState.QueuedQos1; - break; - - // QoS Level 2 - case MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE: - - state = MqttMsgState.QueuedQos2; - break; - } - - // [v3.1.1] SUBSCRIBE and UNSUBSCRIBE aren't "officially" QOS = 1 - // so QueuedQos1 state isn't valid for them - if (msg.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE) - state = MqttMsgState.SendSubscribe; - else if (msg.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE) - state = MqttMsgState.SendUnsubscribe; - - // queue message context - MqttMsgContext msgContext = new MqttMsgContext() - { - Message = msg, - State = state, - Flow = flow, - Attempt = 0 - }; - - lock (this.inflightQueue) - { - // check number of messages inside inflight queue - enqueue = (this.inflightQueue.Count < this.settings.InflightQueueSize); - - if (enqueue) - { - // enqueue message and unlock send thread - this.inflightQueue.Enqueue(msgContext); - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "enqueued {0}", msg); -#endif - - // PUBLISH message - if (msg.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) - { - // to publish and QoS level 1 or 2 - if ((msgContext.Flow == MqttMsgFlow.ToPublish) && - ((msg.QosLevel == MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE) || - (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE))) - { - if (this.session != null) - this.session.InflightMessages.Add(msgContext.Key, msgContext); - } - // to acknowledge and QoS level 2 - else if ((msgContext.Flow == MqttMsgFlow.ToAcknowledge) && - (msg.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE)) - { - if (this.session != null) - this.session.InflightMessages.Add(msgContext.Key, msgContext); - } - } - } - } - } - - this.inflightWaitHandle.Set(); - - return enqueue; - } - - /// - /// Enqueue a message into the internal queue - /// - /// Message to enqueue - private void EnqueueInternal(MqttMsgBase msg) - { - // enqueue is needed (or not) - bool enqueue = true; - - // if it is a PUBREL message (for QoS Level 2) - if (msg.Type == MqttMsgBase.MQTT_MSG_PUBREL_TYPE) - { - lock (this.inflightQueue) - { - // if it is a PUBREL but the corresponding PUBLISH isn't in the inflight queue, - // it means that we processed PUBLISH message and received PUBREL and we sent PUBCOMP - // but publisher didn't receive PUBCOMP so it re-sent PUBREL. We need only to re-send PUBCOMP. - - // NOTE : I need to find on message id and flow because the broker could be publish/received - // to/from client and message id could be the same (one tracked by broker and the other by client) - MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToAcknowledge); - MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find); - - // the PUBLISH message isn't in the inflight queue, it was already processed so - // we need to re-send PUBCOMP only - if (msgCtx == null) - { - MqttMsgPubcomp pubcomp = new MqttMsgPubcomp(); - pubcomp.MessageId = msg.MessageId; - - this.Send(pubcomp); - - enqueue = false; - } - } - } - // if it is a PUBCOMP message (for QoS Level 2) - else if (msg.Type == MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE) - { - lock (this.inflightQueue) - { - // if it is a PUBCOMP but the corresponding PUBLISH isn't in the inflight queue, - // it means that we sent PUBLISH message, sent PUBREL (after receiving PUBREC) and already received PUBCOMP - // but publisher didn't receive PUBREL so it re-sent PUBCOMP. We need only to ignore this PUBCOMP. - - // NOTE : I need to find on message id and flow because the broker could be publish/received - // to/from client and message id could be the same (one tracked by broker and the other by client) - MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToPublish); - MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find); - - // the PUBLISH message isn't in the inflight queue, it was already sent so we need to ignore this PUBCOMP - if (msgCtx == null) - { - enqueue = false; - } - } - } - // if it is a PUBREC message (for QoS Level 2) - else if (msg.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE) - { - lock (this.inflightQueue) - { - // if it is a PUBREC but the corresponding PUBLISH isn't in the inflight queue, - // it means that we sent PUBLISH message more times (retries) but broker didn't send PUBREC in time - // the publish is failed and we need only to ignore this PUBREC. - - // NOTE : I need to find on message id and flow because the broker could be publish/received - // to/from client and message id could be the same (one tracked by broker and the other by client) - MqttMsgContextFinder msgCtxFinder = new MqttMsgContextFinder(msg.MessageId, MqttMsgFlow.ToPublish); - MqttMsgContext msgCtx = (MqttMsgContext)this.inflightQueue.Get(msgCtxFinder.Find); - - // the PUBLISH message isn't in the inflight queue, it was already sent so we need to ignore this PUBREC - if (msgCtx == null) - { - enqueue = false; - } - } - } - - if (enqueue) - { - lock (this.internalQueue) - { - this.internalQueue.Enqueue(msg); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "enqueued {0}", msg); -#endif - this.inflightWaitHandle.Set(); - } - } - } - - /// - /// Thread for receiving messages - /// - private void ReceiveThread() - { - int readBytes = 0; - byte[] fixedHeaderFirstByte = new byte[1]; - byte msgType; - - while (this.isRunning) - { - try - { - // read first byte (fixed header) - readBytes = this.channel.Receive(fixedHeaderFirstByte); - - if (readBytes > 0) - { -#if BROKER - // update last message received ticks - this.lastCommTime = Environment.TickCount; -#endif - - // extract message type from received byte - msgType = (byte)((fixedHeaderFirstByte[0] & MqttMsgBase.MSG_TYPE_MASK) >> MqttMsgBase.MSG_TYPE_OFFSET); - - switch (msgType) - { - // CONNECT message received - case MqttMsgBase.MQTT_MSG_CONNECT_TYPE: - -#if BROKER - MqttMsgConnect connect = MqttMsgConnect.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - Trace.WriteLine(TraceLevel.Frame, "RECV {0}", connect); -#endif - - // raise message received event - this.OnInternalEvent(new MsgInternalEvent(connect)); - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // CONNACK message received - case MqttMsgBase.MQTT_MSG_CONNACK_TYPE: - -#if BROKER - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#else - this.msgReceived = MqttMsgConnack.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived); -#endif - this.syncEndReceiving.Set(); - break; -#endif - - // PINGREQ message received - case MqttMsgBase.MQTT_MSG_PINGREQ_TYPE: - -#if BROKER - this.msgReceived = MqttMsgPingReq.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived); -#endif - - MqttMsgPingResp pingresp = new MqttMsgPingResp(); - this.Send(pingresp); - - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // PINGRESP message received - case MqttMsgBase.MQTT_MSG_PINGRESP_TYPE: - -#if BROKER - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#else - this.msgReceived = MqttMsgPingResp.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", this.msgReceived); -#endif - this.syncEndReceiving.Set(); - break; -#endif - - // SUBSCRIBE message received - case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE: - -#if BROKER - MqttMsgSubscribe subscribe = MqttMsgSubscribe.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - Trace.WriteLine(TraceLevel.Frame, "RECV {0}", subscribe); -#endif - - // raise message received event - this.OnInternalEvent(new MsgInternalEvent(subscribe)); - - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // SUBACK message received - case MqttMsgBase.MQTT_MSG_SUBACK_TYPE: - -#if BROKER - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#else - // enqueue SUBACK message received (for QoS Level 1) into the internal queue - MqttMsgSuback suback = MqttMsgSuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", suback); -#endif - - // enqueue SUBACK message into the internal queue - this.EnqueueInternal(suback); - - break; -#endif - - // PUBLISH message received - case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE: - - MqttMsgPublish publish = MqttMsgPublish.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", publish); -#endif - - // enqueue PUBLISH message to acknowledge into the inflight queue - this.EnqueueInflight(publish, MqttMsgFlow.ToAcknowledge); - - break; - - // PUBACK message received - case MqttMsgBase.MQTT_MSG_PUBACK_TYPE: - - // enqueue PUBACK message received (for QoS Level 1) into the internal queue - MqttMsgPuback puback = MqttMsgPuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", puback); -#endif - - // enqueue PUBACK message into the internal queue - this.EnqueueInternal(puback); - - break; - - // PUBREC message received - case MqttMsgBase.MQTT_MSG_PUBREC_TYPE: - - // enqueue PUBREC message received (for QoS Level 2) into the internal queue - MqttMsgPubrec pubrec = MqttMsgPubrec.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubrec); -#endif - - // enqueue PUBREC message into the internal queue - this.EnqueueInternal(pubrec); - - break; - - // PUBREL message received - case MqttMsgBase.MQTT_MSG_PUBREL_TYPE: - - // enqueue PUBREL message received (for QoS Level 2) into the internal queue - MqttMsgPubrel pubrel = MqttMsgPubrel.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubrel); -#endif - - // enqueue PUBREL message into the internal queue - this.EnqueueInternal(pubrel); - - break; - - // PUBCOMP message received - case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE: - - // enqueue PUBCOMP message received (for QoS Level 2) into the internal queue - MqttMsgPubcomp pubcomp = MqttMsgPubcomp.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", pubcomp); -#endif - - // enqueue PUBCOMP message into the internal queue - this.EnqueueInternal(pubcomp); - - break; - - // UNSUBSCRIBE message received - case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE: - -#if BROKER - MqttMsgUnsubscribe unsubscribe = MqttMsgUnsubscribe.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - Trace.WriteLine(TraceLevel.Frame, "RECV {0}", unsubscribe); -#endif - - // raise message received event - this.OnInternalEvent(new MsgInternalEvent(unsubscribe)); - - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // UNSUBACK message received - case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE: - -#if BROKER - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#else - // enqueue UNSUBACK message received (for QoS Level 1) into the internal queue - MqttMsgUnsuback unsuback = MqttMsgUnsuback.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Frame, "RECV {0}", unsuback); -#endif - - // enqueue UNSUBACK message into the internal queue - this.EnqueueInternal(unsuback); - - break; -#endif - - // DISCONNECT message received - case MqttMsgDisconnect.MQTT_MSG_DISCONNECT_TYPE: - -#if BROKER - MqttMsgDisconnect disconnect = MqttMsgDisconnect.Parse(fixedHeaderFirstByte[0], (byte)this.ProtocolVersion, this.channel); -#if TRACE - Trace.WriteLine(TraceLevel.Frame, "RECV {0}", disconnect); -#endif - - // raise message received event - this.OnInternalEvent(new MsgInternalEvent(disconnect)); - - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - default: - - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); - } - - this.exReceiving = null; - } - // zero bytes read, peer gracefully closed socket - else - { - // wake up thread that will notify connection is closing - this.OnConnectionClosing(); - } - } - catch (Exception e) - { -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString()); -#endif - this.exReceiving = new MqttCommunicationException(e); - - bool close = false; - if (e.GetType() == typeof(MqttClientException)) - { - // [v3.1.1] scenarios the receiver MUST close the network connection - MqttClientException ex = e as MqttClientException; - close = ((ex.ErrorCode == MqttClientErrorCode.InvalidFlagBits) || - (ex.ErrorCode == MqttClientErrorCode.InvalidProtocolName) || - (ex.ErrorCode == MqttClientErrorCode.InvalidConnectFlags)); - } -#if !(WINDOWS_APP || WINDOWS_PHONE_APP) - else if ((e.GetType() == typeof(IOException)) || (e.GetType() == typeof(SocketException)) || - ((e.InnerException != null) && (e.InnerException.GetType() == typeof(SocketException)))) // added for SSL/TLS incoming connection that use SslStream that wraps SocketException - { - close = true; - } -#endif - - if (close) - { - // wake up thread that will notify connection is closing - this.OnConnectionClosing(); - } - } - } - } - - /// - /// Thread for handling keep alive message - /// - private void KeepAliveThread() - { - int delta = 0; - int wait = this.keepAlivePeriod; - - // create event to signal that current thread is end - this.keepAliveEventEnd = new AutoResetEvent(false); - - while (this.isRunning) - { -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - // waiting... - this.keepAliveEvent.WaitOne(wait, false); -#else - // waiting... - this.keepAliveEvent.WaitOne(wait); -#endif - - if (this.isRunning) - { - delta = Environment.TickCount - this.lastCommTime; - - // if timeout exceeded ... - if (delta >= this.keepAlivePeriod) - { -#if BROKER - // client must close connection - this.OnConnectionClosing(); -#else - // ... send keep alive - this.Ping(); - wait = this.keepAlivePeriod; -#endif - } - else - { - // update waiting time - wait = this.keepAlivePeriod - delta; - } - } - } - - // signal thread end - this.keepAliveEventEnd.Set(); - } - - /// - /// Thread for raising event - /// - private void DispatchEventThread() - { - while (this.isRunning) - { -#if BROKER - if ((this.eventQueue.Count == 0) && !this.isConnectionClosing) - { - // broker need to receive the first message (CONNECT) - // within a reasonable amount of time after TCP/IP connection - if (!this.IsConnected) - { - // wait on receiving message from client with a connection timeout - if (!this.receiveEventWaitHandle.WaitOne(this.settings.TimeoutOnConnection)) - { - // client must close connection - this.Close(); - - // client raw disconnection - this.OnConnectionClosed(); - } - } - else - { - // wait on receiving message from client - this.receiveEventWaitHandle.WaitOne(); - } - } -#else - if ((this.eventQueue.Count == 0) && !this.isConnectionClosing) - // wait on receiving message from client - this.receiveEventWaitHandle.WaitOne(); -#endif - - // check if it is running or we are closing client - if (this.isRunning) - { - // get event from queue - InternalEvent internalEvent = null; - lock (this.eventQueue) - { - if (this.eventQueue.Count > 0) - internalEvent = (InternalEvent)this.eventQueue.Dequeue(); - } - - // it's an event with a message inside - if (internalEvent != null) - { - MqttMsgBase msg = ((MsgInternalEvent)internalEvent).Message; - - if (msg != null) - { - switch (msg.Type) - { - // CONNECT message received - case MqttMsgBase.MQTT_MSG_CONNECT_TYPE: - -#if BROKER - // raise connected client event (CONNECT message received) - this.OnMqttMsgConnected((MqttMsgConnect)msg); - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // SUBSCRIBE message received - case MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE: - -#if BROKER - MqttMsgSubscribe subscribe = (MqttMsgSubscribe)msg; - // raise subscribe topic event (SUBSCRIBE message received) - this.OnMqttMsgSubscribeReceived(subscribe.MessageId, subscribe.Topics, subscribe.QoSLevels); - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // SUBACK message received - case MqttMsgBase.MQTT_MSG_SUBACK_TYPE: - - // raise subscribed topic event (SUBACK message received) - this.OnMqttMsgSubscribed((MqttMsgSuback)msg); - break; - - // PUBLISH message received - case MqttMsgBase.MQTT_MSG_PUBLISH_TYPE: - - // PUBLISH message received in a published internal event, no publish succeeded - if (internalEvent.GetType() == typeof(MsgPublishedInternalEvent)) - this.OnMqttMsgPublished(msg.MessageId, false); - else - // raise PUBLISH message received event - this.OnMqttMsgPublishReceived((MqttMsgPublish)msg); - break; - - // PUBACK message received - case MqttMsgBase.MQTT_MSG_PUBACK_TYPE: - - // raise published message event - // (PUBACK received for QoS Level 1) - this.OnMqttMsgPublished(msg.MessageId, true); - break; - - // PUBREL message received - case MqttMsgBase.MQTT_MSG_PUBREL_TYPE: - - // raise message received event - // (PUBREL received for QoS Level 2) - this.OnMqttMsgPublishReceived((MqttMsgPublish)msg); - break; - - // PUBCOMP message received - case MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE: - - // raise published message event - // (PUBCOMP received for QoS Level 2) - this.OnMqttMsgPublished(msg.MessageId, true); - break; - - // UNSUBSCRIBE message received from client - case MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE: - -#if BROKER - MqttMsgUnsubscribe unsubscribe = (MqttMsgUnsubscribe)msg; - // raise unsubscribe topic event (UNSUBSCRIBE message received) - this.OnMqttMsgUnsubscribeReceived(unsubscribe.MessageId, unsubscribe.Topics); - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - - // UNSUBACK message received - case MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE: - - // raise unsubscribed topic event - this.OnMqttMsgUnsubscribed(msg.MessageId); - break; - - // DISCONNECT message received from client - case MqttMsgDisconnect.MQTT_MSG_DISCONNECT_TYPE: - -#if BROKER - // raise disconnected client event (DISCONNECT message received) - this.OnMqttMsgDisconnected(); - break; -#else - throw new MqttClientException(MqttClientErrorCode.WrongBrokerMessage); -#endif - } - } - } - - // all events for received messages dispatched, check if there is closing connection - if ((this.eventQueue.Count == 0) && this.isConnectionClosing) - { - // client must close connection - this.Close(); - - // client raw disconnection - this.OnConnectionClosed(); - } - } - } - } - - /// - /// Process inflight messages queue - /// - private void ProcessInflightThread() - { - MqttMsgContext msgContext = null; - MqttMsgBase msgInflight = null; - MqttMsgBase msgReceived = null; - InternalEvent internalEvent = null; - bool acknowledge = false; - int timeout = Timeout.Infinite; - int delta; - bool msgReceivedProcessed = false; - - try - { - while (this.isRunning) - { -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - // wait on message queueud to inflight - this.inflightWaitHandle.WaitOne(timeout, false); -#else - // wait on message queueud to inflight - this.inflightWaitHandle.WaitOne(timeout); -#endif - - // it could be unblocked because Close() method is joining - if (this.isRunning) - { - lock (this.inflightQueue) - { - // message received and peeked from internal queue is processed - // NOTE : it has the corresponding message in inflight queue based on messageId - // (ex. a PUBREC for a PUBLISH, a SUBACK for a SUBSCRIBE, ...) - // if it's orphan we need to remove from internal queue - msgReceivedProcessed = false; - acknowledge = false; - msgReceived = null; - - // set timeout tu MaxValue instead of Infinte (-1) to perform - // compare with calcultad current msgTimeout - timeout = Int32.MaxValue; - - // a message inflight could be re-enqueued but we have to - // analyze it only just one time for cycle - int count = this.inflightQueue.Count; - // process all inflight queued messages - while (count > 0) - { - count--; - acknowledge = false; - msgReceived = null; - - // check to be sure that client isn't closing and all queues are now empty ! - if (!this.isRunning) - break; - - // dequeue message context from queue - msgContext = (MqttMsgContext)this.inflightQueue.Dequeue(); - - // get inflight message - msgInflight = (MqttMsgBase)msgContext.Message; - - switch (msgContext.State) - { - case MqttMsgState.QueuedQos0: - - // QoS 0, PUBLISH message to send to broker, no state change, no acknowledge - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - this.Send(msgInflight); - } - // QoS 0, no need acknowledge - else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge) - { - internalEvent = new MsgInternalEvent(msgInflight); - // notify published message from broker (no need acknowledged) - this.OnInternalEvent(internalEvent); - } - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight); -#endif - break; - - case MqttMsgState.QueuedQos1: - // [v3.1.1] SUBSCRIBE and UNSIBSCRIBE aren't "officially" QOS = 1 - case MqttMsgState.SendSubscribe: - case MqttMsgState.SendUnsubscribe: - - // QoS 1, PUBLISH or SUBSCRIBE/UNSUBSCRIBE message to send to broker, state change to wait PUBACK or SUBACK/UNSUBACK - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - msgContext.Timestamp = Environment.TickCount; - msgContext.Attempt++; - - if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) - { - // PUBLISH message to send, wait for PUBACK - msgContext.State = MqttMsgState.WaitForPuback; - // retry ? set dup flag [v3.1.1] only for PUBLISH message - if (msgContext.Attempt > 1) - msgInflight.DupFlag = true; - } - else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE) - // SUBSCRIBE message to send, wait for SUBACK - msgContext.State = MqttMsgState.WaitForSuback; - else if (msgInflight.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE) - // UNSUBSCRIBE message to send, wait for UNSUBACK - msgContext.State = MqttMsgState.WaitForUnsuback; - - this.Send(msgInflight); - - // update timeout : minimum between delay (based on current message sent) or current timeout - timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout; - - // re-enqueue message (I have to re-analyze for receiving PUBACK, SUBACK or UNSUBACK) - this.inflightQueue.Enqueue(msgContext); - } - // QoS 1, PUBLISH message received from broker to acknowledge, send PUBACK - else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge) - { - MqttMsgPuback puback = new MqttMsgPuback(); - puback.MessageId = msgInflight.MessageId; - - this.Send(puback); - - internalEvent = new MsgInternalEvent(msgInflight); - // notify published message from broker and acknowledged - this.OnInternalEvent(internalEvent); - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight); -#endif - } - break; - - case MqttMsgState.QueuedQos2: - - // QoS 2, PUBLISH message to send to broker, state change to wait PUBREC - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - msgContext.Timestamp = Environment.TickCount; - msgContext.Attempt++; - msgContext.State = MqttMsgState.WaitForPubrec; - // retry ? set dup flag - if (msgContext.Attempt > 1) - msgInflight.DupFlag = true; - - this.Send(msgInflight); - - // update timeout : minimum between delay (based on current message sent) or current timeout - timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout; - - // re-enqueue message (I have to re-analyze for receiving PUBREC) - this.inflightQueue.Enqueue(msgContext); - } - // QoS 2, PUBLISH message received from broker to acknowledge, send PUBREC, state change to wait PUBREL - else if (msgContext.Flow == MqttMsgFlow.ToAcknowledge) - { - MqttMsgPubrec pubrec = new MqttMsgPubrec(); - pubrec.MessageId = msgInflight.MessageId; - - msgContext.State = MqttMsgState.WaitForPubrel; - - this.Send(pubrec); - - // re-enqueue message (I have to re-analyze for receiving PUBREL) - this.inflightQueue.Enqueue(msgContext); - } - break; - - case MqttMsgState.WaitForPuback: - case MqttMsgState.WaitForSuback: - case MqttMsgState.WaitForUnsuback: - - // QoS 1, waiting for PUBACK of a PUBLISH message sent or - // waiting for SUBACK of a SUBSCRIBE message sent or - // waiting for UNSUBACK of a UNSUBSCRIBE message sent or - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - acknowledge = false; - lock (this.internalQueue) - { - if (this.internalQueue.Count > 0) - msgReceived = (MqttMsgBase)this.internalQueue.Peek(); - } - - // it is a PUBACK message or a SUBACK/UNSUBACK message - if (msgReceived != null) - { - // PUBACK message or SUBACK/UNSUBACK message for the current message - if (((msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && (msgReceived.MessageId == msgInflight.MessageId)) || - ((msgReceived.Type == MqttMsgBase.MQTT_MSG_SUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_SUBSCRIBE_TYPE) && (msgReceived.MessageId == msgInflight.MessageId)) || - ((msgReceived.Type == MqttMsgBase.MQTT_MSG_UNSUBACK_TYPE) && (msgInflight.Type == MqttMsgBase.MQTT_MSG_UNSUBSCRIBE_TYPE) && (msgReceived.MessageId == msgInflight.MessageId))) - { - lock (this.internalQueue) - { - // received message processed - this.internalQueue.Dequeue(); - acknowledge = true; - msgReceivedProcessed = true; -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived); -#endif - } - - // if PUBACK received, confirm published with flag - if (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBACK_TYPE) - internalEvent = new MsgPublishedInternalEvent(msgReceived, true); - else - internalEvent = new MsgInternalEvent(msgReceived); - - // notify received acknowledge from broker of a published message or subscribe/unsubscribe message - this.OnInternalEvent(internalEvent); - - // PUBACK received for PUBLISH message with QoS Level 1, remove from session state - if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight); -#endif - } - } - - // current message not acknowledged, no PUBACK or SUBACK/UNSUBACK or not equal messageid - if (!acknowledge) - { - delta = Environment.TickCount - msgContext.Timestamp; - // check timeout for receiving PUBACK since PUBLISH was sent or - // for receiving SUBACK since SUBSCRIBE was sent or - // for receiving UNSUBACK since UNSUBSCRIBE was sent - if (delta >= this.settings.DelayOnRetry) - { - // max retry not reached, resend - if (msgContext.Attempt < this.settings.AttemptsOnRetry) - { - msgContext.State = MqttMsgState.QueuedQos1; - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - - // update timeout (0 -> reanalyze queue immediately) - timeout = 0; - } - else - { - // if PUBACK for a PUBLISH message not received after retries, raise event for not published - if (msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) - { - // PUBACK not received in time, PUBLISH retries failed, need to remove from session inflight messages too - if ((this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - - internalEvent = new MsgPublishedInternalEvent(msgInflight, false); - - // notify not received acknowledge from broker and message not published - this.OnInternalEvent(internalEvent); - } - // NOTE : not raise events for SUBACK or UNSUBACK not received - // for the user no event raised means subscribe/unsubscribe failed - } - } - else - { - // re-enqueue message (I have to re-analyze for receiving PUBACK, SUBACK or UNSUBACK) - this.inflightQueue.Enqueue(msgContext); - - // update timeout - int msgTimeout = (this.settings.DelayOnRetry - delta); - timeout = (msgTimeout < timeout) ? msgTimeout : timeout; - } - } - } - break; - - case MqttMsgState.WaitForPubrec: - - // QoS 2, waiting for PUBREC of a PUBLISH message sent - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - acknowledge = false; - lock (this.internalQueue) - { - if (this.internalQueue.Count > 0) - msgReceived = (MqttMsgBase)this.internalQueue.Peek(); - } - - // it is a PUBREC message - if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE)) - { - // PUBREC message for the current PUBLISH message, send PUBREL, wait for PUBCOMP - if (msgReceived.MessageId == msgInflight.MessageId) - { - lock (this.internalQueue) - { - // received message processed - this.internalQueue.Dequeue(); - acknowledge = true; - msgReceivedProcessed = true; -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived); -#endif - } - - MqttMsgPubrel pubrel = new MqttMsgPubrel(); - pubrel.MessageId = msgInflight.MessageId; - - msgContext.State = MqttMsgState.WaitForPubcomp; - msgContext.Timestamp = Environment.TickCount; - msgContext.Attempt = 1; - - this.Send(pubrel); - - // update timeout : minimum between delay (based on current message sent) or current timeout - timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout; - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - } - } - - // current message not acknowledged - if (!acknowledge) - { - delta = Environment.TickCount - msgContext.Timestamp; - // check timeout for receiving PUBREC since PUBLISH was sent - if (delta >= this.settings.DelayOnRetry) - { - // max retry not reached, resend - if (msgContext.Attempt < this.settings.AttemptsOnRetry) - { - msgContext.State = MqttMsgState.QueuedQos2; - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - - // update timeout (0 -> reanalyze queue immediately) - timeout = 0; - } - else - { - // PUBREC not received in time, PUBLISH retries failed, need to remove from session inflight messages too - if ((this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - - // if PUBREC for a PUBLISH message not received after retries, raise event for not published - internalEvent = new MsgPublishedInternalEvent(msgInflight, false); - // notify not received acknowledge from broker and message not published - this.OnInternalEvent(internalEvent); - } - } - else - { - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - - // update timeout - int msgTimeout = (this.settings.DelayOnRetry - delta); - timeout = (msgTimeout < timeout) ? msgTimeout : timeout; - } - } - } - break; - - case MqttMsgState.WaitForPubrel: - - // QoS 2, waiting for PUBREL of a PUBREC message sent - if (msgContext.Flow == MqttMsgFlow.ToAcknowledge) - { - lock (this.internalQueue) - { - if (this.internalQueue.Count > 0) - msgReceived = (MqttMsgBase)this.internalQueue.Peek(); - } - - // it is a PUBREL message - if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREL_TYPE)) - { - // PUBREL message for the current message, send PUBCOMP - if (msgReceived.MessageId == msgInflight.MessageId) - { - lock (this.internalQueue) - { - // received message processed - this.internalQueue.Dequeue(); - msgReceivedProcessed = true; -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived); -#endif - } - - MqttMsgPubcomp pubcomp = new MqttMsgPubcomp(); - pubcomp.MessageId = msgInflight.MessageId; - - this.Send(pubcomp); - - internalEvent = new MsgInternalEvent(msgInflight); - // notify published message from broker and acknowledged - this.OnInternalEvent(internalEvent); - - // PUBREL received (and PUBCOMP sent) for PUBLISH message with QoS Level 2, remove from session state - if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight); -#endif - } - else - { - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - } - } - else - { - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - } - } - break; - - case MqttMsgState.WaitForPubcomp: - - // QoS 2, waiting for PUBCOMP of a PUBREL message sent - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - acknowledge = false; - lock (this.internalQueue) - { - if (this.internalQueue.Count > 0) - msgReceived = (MqttMsgBase)this.internalQueue.Peek(); - } - - // it is a PUBCOMP message - if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBCOMP_TYPE)) - { - // PUBCOMP message for the current message - if (msgReceived.MessageId == msgInflight.MessageId) - { - lock (this.internalQueue) - { - // received message processed - this.internalQueue.Dequeue(); - acknowledge = true; - msgReceivedProcessed = true; -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived); -#endif - } - - internalEvent = new MsgPublishedInternalEvent(msgReceived, true); - // notify received acknowledge from broker of a published message - this.OnInternalEvent(internalEvent); - - // PUBCOMP received for PUBLISH message with QoS Level 2, remove from session state - if ((msgInflight.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "processed {0}", msgInflight); -#endif - } - } - // it is a PUBREC message - else if ((msgReceived != null) && (msgReceived.Type == MqttMsgBase.MQTT_MSG_PUBREC_TYPE)) - { - // another PUBREC message for the current message due to a retransmitted PUBLISH - // I'm in waiting for PUBCOMP, so I can discard this PUBREC - if (msgReceived.MessageId == msgInflight.MessageId) - { - lock (this.internalQueue) - { - // received message processed - this.internalQueue.Dequeue(); - acknowledge = true; - msgReceivedProcessed = true; -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0}", msgReceived); -#endif - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - } - } - } - - // current message not acknowledged - if (!acknowledge) - { - delta = Environment.TickCount - msgContext.Timestamp; - // check timeout for receiving PUBCOMP since PUBREL was sent - if (delta >= this.settings.DelayOnRetry) - { - // max retry not reached, resend - if (msgContext.Attempt < this.settings.AttemptsOnRetry) - { - msgContext.State = MqttMsgState.SendPubrel; - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - - // update timeout (0 -> reanalyze queue immediately) - timeout = 0; - } - else - { - // PUBCOMP not received, PUBREL retries failed, need to remove from session inflight messages too - if ((this.session != null) && -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - (this.session.InflightMessages.Contains(msgContext.Key))) -#else - (this.session.InflightMessages.ContainsKey(msgContext.Key))) -#endif - { - this.session.InflightMessages.Remove(msgContext.Key); - } - - // if PUBCOMP for a PUBLISH message not received after retries, raise event for not published - internalEvent = new MsgPublishedInternalEvent(msgInflight, false); - // notify not received acknowledge from broker and message not published - this.OnInternalEvent(internalEvent); - } - } - else - { - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - - // update timeout - int msgTimeout = (this.settings.DelayOnRetry - delta); - timeout = (msgTimeout < timeout) ? msgTimeout : timeout; - } - } - } - break; - - case MqttMsgState.SendPubrec: - - // TODO : impossible ? --> QueuedQos2 ToAcknowledge - break; - - case MqttMsgState.SendPubrel: - - // QoS 2, PUBREL message to send to broker, state change to wait PUBCOMP - if (msgContext.Flow == MqttMsgFlow.ToPublish) - { - MqttMsgPubrel pubrel = new MqttMsgPubrel(); - pubrel.MessageId = msgInflight.MessageId; - - msgContext.State = MqttMsgState.WaitForPubcomp; - msgContext.Timestamp = Environment.TickCount; - msgContext.Attempt++; - // retry ? set dup flag [v3.1.1] no needed - if (this.ProtocolVersion == MqttProtocolVersion.Version_3_1) - { - if (msgContext.Attempt > 1) - pubrel.DupFlag = true; - } - - this.Send(pubrel); - - // update timeout : minimum between delay (based on current message sent) or current timeout - timeout = (this.settings.DelayOnRetry < timeout) ? this.settings.DelayOnRetry : timeout; - - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - } - break; - - case MqttMsgState.SendPubcomp: - // TODO : impossible ? - break; - case MqttMsgState.SendPuback: - // TODO : impossible ? --> QueuedQos1 ToAcknowledge - break; - default: - break; - } - } - - // if calculated timeout is MaxValue, it means that must be Infinite (-1) - if (timeout == Int32.MaxValue) - timeout = Timeout.Infinite; - - // if message received is orphan, no corresponding message in inflight queue - // based on messageId, we need to remove from the queue - if ((msgReceived != null) && !msgReceivedProcessed) - { - this.internalQueue.Dequeue(); -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Queuing, "dequeued {0} orphan", msgReceived); -#endif - } - } - } - } - } - catch (MqttCommunicationException e) - { - // possible exception on Send, I need to re-enqueue not sent message - if (msgContext != null) - // re-enqueue message - this.inflightQueue.Enqueue(msgContext); - -#if TRACE - MqttUtility.Trace.WriteLine(TraceLevel.Error, "Exception occurred: {0}", e.ToString()); -#endif - - // raise disconnection client event - this.OnConnectionClosing(); - } - } - - /// - /// Restore session - /// - private void RestoreSession() - { - // if not clean session - if (!this.CleanSession) - { - // there is a previous session - if (this.session != null) - { - lock (this.inflightQueue) - { - foreach (MqttMsgContext msgContext in this.session.InflightMessages.Values) - { - this.inflightQueue.Enqueue(msgContext); - - // if it is a PUBLISH message to publish - if ((msgContext.Message.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (msgContext.Flow == MqttMsgFlow.ToPublish)) - { - // it's QoS 1 and we haven't received PUBACK - if ((msgContext.Message.QosLevel == MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE) && - (msgContext.State == MqttMsgState.WaitForPuback)) - { - // we haven't received PUBACK, we need to resend PUBLISH message - msgContext.State = MqttMsgState.QueuedQos1; - } - // it's QoS 2 - else if (msgContext.Message.QosLevel == MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE) - { - // we haven't received PUBREC, we need to resend PUBLISH message - if (msgContext.State == MqttMsgState.WaitForPubrec) - { - msgContext.State = MqttMsgState.QueuedQos2; - } - // we haven't received PUBCOMP, we need to resend PUBREL for it - else if (msgContext.State == MqttMsgState.WaitForPubcomp) - { - msgContext.State = MqttMsgState.SendPubrel; - } - } - } - } - } - - // unlock process inflight queue - this.inflightWaitHandle.Set(); - } - else - { - // create new session - this.session = new MqttClientSession(this.ClientId); - } - } - // clean any previous session - else - { - if (this.session != null) - this.session.Clear(); - } - } - -#if BROKER - - /// - /// Load a given session - /// - /// MQTT Client session to load - public void LoadSession(MqttClientSession session) - { - // if not clean session - if (!this.CleanSession) - { - // set the session ... - this.session = session; - // ... and restore it - this.RestoreSession(); - } - } -#endif - - /// - /// Generate the next message identifier - /// - /// Message identifier - private ushort GetMessageId() - { - // if 0 or max UInt16, it becomes 1 (first valid messageId) - this.messageIdCounter = ((this.messageIdCounter % UInt16.MaxValue) != 0) ? (ushort)(this.messageIdCounter + 1) : (ushort)1; - return this.messageIdCounter; - } - - /// - /// Finder class for PUBLISH message inside a queue - /// - internal class MqttMsgContextFinder - { - // PUBLISH message id - internal ushort MessageId { get; set; } - // message flow into inflight queue - internal MqttMsgFlow Flow { get; set; } - - /// - /// Constructor - /// - /// Message Id - /// Message flow inside inflight queue - internal MqttMsgContextFinder(ushort messageId, MqttMsgFlow flow) - { - this.MessageId = messageId; - this.Flow = flow; - } - - internal bool Find(object item) - { - MqttMsgContext msgCtx = (MqttMsgContext)item; - return ((msgCtx.Message.Type == MqttMsgBase.MQTT_MSG_PUBLISH_TYPE) && - (msgCtx.Message.MessageId == this.MessageId) && - msgCtx.Flow == this.Flow); - - } - } - } - - /// - /// MQTT protocol version - /// - public enum MqttProtocolVersion - { - Version_3_1 = MqttMsgConnect.PROTOCOL_VERSION_V3_1, - Version_3_1_1 = MqttMsgConnect.PROTOCOL_VERSION_V3_1_1 - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSecurity.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSecurity.cs deleted file mode 100644 index b19f108..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSecurity.cs +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Supported SSL/TLS protocol versions - /// - public enum MqttSslProtocols - { - None, - SSLv3, - TLSv1_0, - TLSv1_1, - TLSv1_2 - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSettings.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSettings.cs deleted file mode 100644 index 994f622..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/MqttSettings.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Settings class for the MQTT broker - /// - public class MqttSettings - { - // default port for MQTT protocol - public const int MQTT_BROKER_DEFAULT_PORT = 1883; - public const int MQTT_BROKER_DEFAULT_SSL_PORT = 8883; - // default timeout on receiving from client - public const int MQTT_DEFAULT_TIMEOUT = 30000; - // max publish, subscribe and unsubscribe retry for QoS Level 1 or 2 - public const int MQTT_ATTEMPTS_RETRY = 3; - // delay for retry publish, subscribe and unsubscribe for QoS Level 1 or 2 - public const int MQTT_DELAY_RETRY = 10000; - // broker need to receive the first message (CONNECT) - // within a reasonable amount of time after TCP/IP connection - public const int MQTT_CONNECT_TIMEOUT = 30000; - // default inflight queue size - public const int MQTT_MAX_INFLIGHT_QUEUE_SIZE = int.MaxValue; - - /// - /// Listening connection port - /// - public int Port { get; internal set; } - - /// - /// Listening connection SSL port - /// - public int SslPort { get; internal set; } - - /// - /// Timeout on client connection (before receiving CONNECT message) - /// - public int TimeoutOnConnection { get; internal set; } - - /// - /// Timeout on receiving - /// - public int TimeoutOnReceiving { get; internal set; } - - /// - /// Attempts on retry - /// - public int AttemptsOnRetry { get; internal set; } - - /// - /// Delay on retry - /// - public int DelayOnRetry { get; internal set; } - - /// - /// Inflight queue size - /// - public int InflightQueueSize { get; set; } - - /// - /// Singleton instance of settings - /// - public static MqttSettings Instance - { - get - { - if (instance == null) - instance = new MqttSettings(); - return instance; - } - } - - // singleton instance - private static MqttSettings instance; - - /// - /// Constructor - /// - private MqttSettings() - { - this.Port = MQTT_BROKER_DEFAULT_PORT; - this.SslPort = MQTT_BROKER_DEFAULT_SSL_PORT; - this.TimeoutOnReceiving = MQTT_DEFAULT_TIMEOUT; - this.AttemptsOnRetry = MQTT_ATTEMPTS_RETRY; - this.DelayOnRetry = MQTT_DELAY_RETRY; - this.TimeoutOnConnection = MQTT_CONNECT_TIMEOUT; - this.InflightQueueSize = MQTT_MAX_INFLIGHT_QUEUE_SIZE; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Net/Fx.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Net/Fx.cs deleted file mode 100644 index 3fcc505..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Net/Fx.cs +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Threading; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Support methods fos specific framework - /// - public class Fx - { - public static void StartThread(ThreadStart threadStart) - { - new Thread(threadStart).Start(); - } - - public static void SleepThread(int millisecondsTimeout) - { - Thread.Sleep(millisecondsTimeout); - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Net/MqttNetworkChannel.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Net/MqttNetworkChannel.cs deleted file mode 100644 index 17cfda7..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Net/MqttNetworkChannel.cs +++ /dev/null @@ -1,470 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if SSL -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) -using Microsoft.SPOT.Net.Security; -#else -using System.Net.Security; -using System.Security.Authentication; -#endif -#endif -using System.Net.Sockets; -using System.Net; -using System.Security.Cryptography.X509Certificates; -using System; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Channel to communicate over the network - /// - public class MqttNetworkChannel : IMqttNetworkChannel - { -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - private readonly RemoteCertificateValidationCallback userCertificateValidationCallback; - private readonly LocalCertificateSelectionCallback userCertificateSelectionCallback; -#endif - // remote host information - private string remoteHostName; - private IPAddress remoteIpAddress; - private int remotePort; - - // socket for communication - private Socket socket; - // using SSL - private bool secure; - - // CA certificate (on client) - private X509Certificate caCert; - // Server certificate (on broker) - private X509Certificate serverCert; - // client certificate (on client) - private X509Certificate clientCert; - - // SSL/TLS protocol version - private MqttSslProtocols sslProtocol; - - /// - /// Remote host name - /// - public string RemoteHostName { get { return this.remoteHostName; } } - - /// - /// Remote IP address - /// - public IPAddress RemoteIpAddress { get { return this.remoteIpAddress; } } - - /// - /// Remote port - /// - public int RemotePort { get { return this.remotePort; } } - -#if SSL - // SSL stream - private SslStream sslStream; -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) - private NetworkStream netStream; -#endif -#endif - - /// - /// Data available on the channel - /// - public bool DataAvailable - { - get - { -#if SSL -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - if (secure) - return this.sslStream.DataAvailable; - else - return (this.socket.Available > 0); -#else - if (secure) - return this.netStream.DataAvailable; - else - return (this.socket.Available > 0); -#endif -#else - return (this.socket.Available > 0); -#endif - } - } - - /// - /// Constructor - /// - /// Socket opened with the client - public MqttNetworkChannel(Socket socket) -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - : this(socket, false, null, MqttSslProtocols.None, null, null) -#else - : this(socket, false, null, MqttSslProtocols.None) -#endif - { - - } - - /// - /// Constructor - /// - /// Socket opened with the client - /// Secure connection (SSL/TLS) - /// Server X509 certificate for secure connection - /// SSL/TLS protocol version -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication - public MqttNetworkChannel(Socket socket, bool secure, X509Certificate serverCert, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) -#else - public MqttNetworkChannel(Socket socket, bool secure, X509Certificate serverCert, MqttSslProtocols sslProtocol) -#endif - { - this.socket = socket; - this.secure = secure; - this.serverCert = serverCert; - this.sslProtocol = sslProtocol; -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - this.userCertificateValidationCallback = userCertificateValidationCallback; - this.userCertificateSelectionCallback = userCertificateSelectionCallback; -#endif - } - - /// - /// Constructor - /// - /// Remote Host name - /// Remote port - public MqttNetworkChannel(string remoteHostName, int remotePort) -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - : this(remoteHostName, remotePort, false, null, null, MqttSslProtocols.None, null, null) -#else - : this(remoteHostName, remotePort, false, null, null, MqttSslProtocols.None) -#endif - { - } - - /// - /// Constructor - /// - /// Remote Host name - /// Remote port - /// Using SSL - /// CA certificate - /// Client certificate - /// SSL/TLS protocol version -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - /// A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party - /// A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication - public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol, - RemoteCertificateValidationCallback userCertificateValidationCallback, - LocalCertificateSelectionCallback userCertificateSelectionCallback) -#else - public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol) -#endif - { - IPAddress remoteIpAddress = null; - try - { - // check if remoteHostName is a valid IP address and get it - remoteIpAddress = IPAddress.Parse(remoteHostName); - } - catch - { - } - - // in this case the parameter remoteHostName isn't a valid IP address - if (remoteIpAddress == null) - { - IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName); - if ((hostEntry != null) && (hostEntry.AddressList.Length > 0)) - { - // check for the first address not null - // it seems that with .Net Micro Framework, the IPV6 addresses aren't supported and return "null" - int i = 0; - while (hostEntry.AddressList[i] == null) i++; - remoteIpAddress = hostEntry.AddressList[i]; - } - else - { - throw new Exception("No address found for the remote host name"); - } - } - - this.remoteHostName = remoteHostName; - this.remoteIpAddress = remoteIpAddress; - this.remotePort = remotePort; - this.secure = secure; - this.caCert = caCert; - this.clientCert = clientCert; - this.sslProtocol = sslProtocol; -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK) - this.userCertificateValidationCallback = userCertificateValidationCallback; - this.userCertificateSelectionCallback = userCertificateSelectionCallback; -#endif - } - - /// - /// Connect to remote server - /// - public void Connect() - { - this.socket = new Socket(this.remoteIpAddress.GetAddressFamily(), SocketType.Stream, ProtocolType.Tcp); - // try connection to the broker - this.socket.Connect(new IPEndPoint(this.remoteIpAddress, this.remotePort)); - -#if SSL - // secure channel requested - if (secure) - { - // create SSL stream -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - this.sslStream = new SslStream(this.socket); -#else - this.netStream = new NetworkStream(this.socket); - this.sslStream = new SslStream(this.netStream, false, this.userCertificateValidationCallback, this.userCertificateSelectionCallback); -#endif - - // server authentication (SSL/TLS handshake) -#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - this.sslStream.AuthenticateAsClient(this.remoteHostName, - this.clientCert, - new X509Certificate[] { this.caCert }, - SslVerification.CertificateRequired, - MqttSslUtility.ToSslPlatformEnum(this.sslProtocol)); -#else - X509CertificateCollection clientCertificates = null; - // check if there is a client certificate to add to the collection, otherwise it's null (as empty) - if (this.clientCert != null) - clientCertificates = new X509CertificateCollection(new X509Certificate[] { this.clientCert }); - - this.sslStream.AuthenticateAsClient(this.remoteHostName, - clientCertificates, - MqttSslUtility.ToSslPlatformEnum(this.sslProtocol), - false); - -#endif - } -#endif - } - - /// - /// Send data on the network channel - /// - /// Data buffer to send - /// Number of byte sent - public int Send(byte[] buffer) - { -#if SSL - if (this.secure) - { - this.sslStream.Write(buffer, 0, buffer.Length); - this.sslStream.Flush(); - return buffer.Length; - } - else - return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None); -#else - return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None); -#endif - } - - /// - /// Receive data from the network - /// - /// Data buffer for receiving data - /// Number of bytes received - public int Receive(byte[] buffer) - { -#if SSL - if (this.secure) - { - // read all data needed (until fill buffer) - int idx = 0, read = 0; - while (idx < buffer.Length) - { - // fixed scenario with socket closed gracefully by peer/broker and - // Read return 0. Avoid infinite loop. - read = this.sslStream.Read(buffer, idx, buffer.Length - idx); - if (read == 0) - return 0; - idx += read; - } - return buffer.Length; - } - else - { - // read all data needed (until fill buffer) - int idx = 0, read = 0; - while (idx < buffer.Length) - { - // fixed scenario with socket closed gracefully by peer/broker and - // Read return 0. Avoid infinite loop. - read = this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None); - if (read == 0) - return 0; - idx += read; - } - return buffer.Length; - } -#else - // read all data needed (until fill buffer) - int idx = 0, read = 0; - while (idx < buffer.Length) - { - // fixed scenario with socket closed gracefully by peer/broker and - // Read return 0. Avoid infinite loop. - read = this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None); - if (read == 0) - return 0; - idx += read; - } - return buffer.Length; -#endif - } - - /// - /// Receive data from the network channel with a specified timeout - /// - /// Data buffer for receiving data - /// Timeout on receiving (in milliseconds) - /// Number of bytes received - public int Receive(byte[] buffer, int timeout) - { - // check data availability (timeout is in microseconds) - if (this.socket.Poll(timeout * 1000, SelectMode.SelectRead)) - { - return this.Receive(buffer); - } - else - { - return 0; - } - } - - /// - /// Close the network channel - /// - public void Close() - { -#if SSL - if (this.secure) - { -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) - this.netStream.Close(); -#endif - this.sslStream.Close(); - } - this.socket.Close(); -#else - this.socket.Close(); -#endif - } - - /// - /// Accept connection from a remote client - /// - public void Accept() - { -#if SSL - // secure channel requested - if (secure) - { -#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - - this.netStream = new NetworkStream(this.socket); - this.sslStream = new SslStream(this.netStream, false, this.userCertificateValidationCallback, this.userCertificateSelectionCallback); - - this.sslStream.AuthenticateAsServer(this.serverCert, false, MqttSslUtility.ToSslPlatformEnum(this.sslProtocol), false); -#endif - } - - return; -#else - return; -#endif - } - } - - /// - /// IPAddress Utility class - /// - public static class IPAddressUtility - { - /// - /// Return AddressFamily for the IP address - /// - /// IP address to check - /// Address family - public static AddressFamily GetAddressFamily(this IPAddress ipAddress) - { -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3) - return ipAddress.AddressFamily; -#else - return (ipAddress.ToString().IndexOf(':') != -1) ? - AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; -#endif - } - } - - /// - /// MQTT SSL utility class - /// - public static class MqttSslUtility - { -#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3 && !COMPACT_FRAMEWORK) - public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol) - { - switch (mqttSslProtocol) - { - case MqttSslProtocols.None: - return SslProtocols.None; - case MqttSslProtocols.SSLv3: - return SslProtocols.Ssl3; - case MqttSslProtocols.TLSv1_0: - return SslProtocols.Tls; - case MqttSslProtocols.TLSv1_1: - //return SslProtocols.Tls11; - case MqttSslProtocols.TLSv1_2: - //return SslProtocols.Tls12; - default: - throw new ArgumentException("SSL/TLS protocol version not supported"); - } - } -#elif (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3) - public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol) - { - switch (mqttSslProtocol) - { - case MqttSslProtocols.None: - return SslProtocols.None; - case MqttSslProtocols.SSLv3: - return SslProtocols.SSLv3; - case MqttSslProtocols.TLSv1_0: - return SslProtocols.TLSv1; - case MqttSslProtocols.TLSv1_1: - case MqttSslProtocols.TLSv1_2: - default: - throw new ArgumentException("SSL/TLS protocol version not supported"); - } - } -#endif - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Properties/AssemblyInfo.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Properties/AssemblyInfo.cs deleted file mode 100644 index 2d21558..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("M2Mqtt")] -[assembly: AssemblyDescription("MQTT Client Library for M2M communication")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Paolo Patierno")] -[assembly: AssemblyProduct("M2Mqtt")] -[assembly: AssemblyCopyright("Copyright © Paolo Patierno 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -[assembly: AssemblyVersion("4.3.0.0")] -// to avoid compilation error (AssemblyFileVersionAttribute doesn't exist) under .Net CF 3.5 -#if !WindowsCE -[assembly: AssemblyFileVersion("4.3.0.0")] -#endif \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttBrokerSession.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttBrokerSession.cs deleted file mode 100644 index 859213c..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttBrokerSession.cs +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -#if BROKER -using System.Collections; -using System.Collections.Generic; -using uPLibrary.Networking.M2Mqtt.Managers; -using uPLibrary.Networking.M2Mqtt.Messages; - -namespace uPLibrary.Networking.M2Mqtt.Session -{ - /// - /// MQTT Broker Session - /// - public class MqttBrokerSession : MqttSession - { - /// - /// Client related to the subscription - /// - public MqttClient Client { get; set; } - - /// - /// Subscriptions for the client session - /// - public List Subscriptions; - - /// - /// Outgoing messages to publish - /// - public Queue OutgoingMessages; - - /// - /// Constructor - /// - public MqttBrokerSession() - : base() - { - this.Client = null; - this.Subscriptions = new List(); - this.OutgoingMessages = new Queue(); - } - - public override void Clear() - { - base.Clear(); - this.Client = null; - this.Subscriptions.Clear(); - this.OutgoingMessages.Clear(); - } - } -} -#endif \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttClientSession.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttClientSession.cs deleted file mode 100644 index 7613880..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttClientSession.cs +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -namespace uPLibrary.Networking.M2Mqtt.Session -{ - /// - /// MQTT Client Session - /// - public class MqttClientSession : MqttSession - { - /// - /// Constructor - /// - /// Client Id to create session - public MqttClientSession(string clientId) - : base(clientId) - { - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttSession.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttSession.cs deleted file mode 100644 index 712a854..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Session/MqttSession.cs +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Collections; - -namespace uPLibrary.Networking.M2Mqtt.Session -{ - /// - /// MQTT Session base class - /// - public abstract class MqttSession - { - /// - /// Client Id - /// - public string ClientId { get; set; } - - /// - /// Messages inflight during session - /// - public Hashtable InflightMessages { get; set; } - - /// - /// Constructor - /// - public MqttSession() - : this(null) - { - } - - /// - /// Constructor - /// - /// Client Id to create session - public MqttSession(string clientId) - { - this.ClientId = clientId; - this.InflightMessages = new Hashtable(); - } - - /// - /// Clean session - /// - public virtual void Clear() - { - this.ClientId = null; - this.InflightMessages.Clear(); - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/QueueExtension.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/QueueExtension.cs deleted file mode 100644 index f8caa5d..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/QueueExtension.cs +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Collections; - -namespace uPLibrary.Networking.M2Mqtt.Utility -{ - /// - /// Extension class for a Queue - /// - internal static class QueueExtension - { - /// - /// Predicate for searching inside a queue - /// - /// Item of the queue - /// Result of predicate - internal delegate bool QueuePredicate(object item); - - /// - /// Get (without removing) an item from queue based on predicate - /// - /// Queue in which to search - /// Predicate to verify to get item - /// Item matches the predicate - internal static object Get(this Queue queue, QueuePredicate predicate) - { - foreach (var item in queue) - { - if (predicate(item)) - return item; - } - return null; - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/Trace.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/Trace.cs deleted file mode 100644 index c299ebe..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/Utility/Trace.cs +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Diagnostics; - -namespace uPLibrary.Networking.M2Mqtt.Utility -{ - /// - /// Tracing levels - /// - public enum TraceLevel - { - Error = 0x01, - Warning = 0x02, - Information = 0x04, - Verbose = 0x0F, - Frame = 0x10, - Queuing = 0x20 - } - - // delegate for writing trace - public delegate void WriteTrace(string format, params object[] args); - - /// - /// Tracing class - /// - public static class Trace - { - public static TraceLevel TraceLevel; - public static WriteTrace TraceListener; - - [Conditional("DEBUG")] - public static void Debug(string format, params object[] args) - { - if (TraceListener != null) - { - TraceListener(format, args); - } - } - - public static void WriteLine(TraceLevel level, string format) - { - if (TraceListener != null && (level & TraceLevel) > 0) - { - TraceListener(format); - } - } - - public static void WriteLine(TraceLevel level, string format, object arg1) - { - if (TraceListener != null && (level & TraceLevel) > 0) - { - TraceListener(format, arg1); - } - } - - public static void WriteLine(TraceLevel level, string format, object arg1, object arg2) - { - if (TraceListener != null && (level & TraceLevel) > 0) - { - TraceListener(format, arg1, arg2); - } - } - - public static void WriteLine(TraceLevel level, string format, object arg1, object arg2, object arg3) - { - if (TraceListener != null && (level & TraceLevel) > 0) - { - TraceListener(format, arg1, arg2, arg3); - } - } - } -} \ No newline at end of file diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Fx.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Fx.cs deleted file mode 100644 index 6d62d28..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Fx.cs +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Threading; -using System.Threading.Tasks; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Support methods fos specific framework - /// - public class Fx - { - - public delegate void ThreadStart(); - public static void StartThread(ThreadStart threadStart) - { - Task.Factory.StartNew(o => ((ThreadStart)o)(), threadStart); - } - - public static void SleepThread(int millisecondsTimeout) { Task.Delay(millisecondsTimeout).RunSynchronously(); } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Hashtable.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Hashtable.cs deleted file mode 100644 index a42532b..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Hashtable.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Collections.Generic; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Wrapper Hashtable class for generic Dictionary (the only available in WinRT) - /// - public class Hashtable : Dictionary - { - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/MqttNetworkChannel.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/MqttNetworkChannel.cs deleted file mode 100644 index 305992c..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/MqttNetworkChannel.cs +++ /dev/null @@ -1,179 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Networking; -using Windows.Networking.Sockets; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Storage.Streams; -using System.Threading; - -namespace uPLibrary.Networking.M2Mqtt -{ - public class MqttNetworkChannel : IMqttNetworkChannel - { - // stream socket for communication - private StreamSocket socket; - - // remote host information - private HostName remoteHostName; - private int remotePort; - - // using SSL - private bool secure; - - // SSL/TLS protocol version - private MqttSslProtocols sslProtocol; - - /// - /// Constructor - /// - /// Socket opened with the client - public MqttNetworkChannel(StreamSocket socket) - { - this.socket = socket; - this.sslProtocol = MqttSslProtocols.None; - } - - /// - /// Constructor - /// - /// Remote Host name - /// Remote port - /// Using SSL - /// SSL/TLS protocol version - public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, MqttSslProtocols sslProtocol) - { - this.remoteHostName = new HostName(remoteHostName); - this.remotePort = remotePort; - this.secure = secure; - this.sslProtocol = sslProtocol; - - if (secure && (sslProtocol == MqttSslProtocols.None)) - throw new ArgumentException("For secure connection, an SSL/TLS protocol version is needed"); - } - - public bool DataAvailable - { - get { return true; } - } - - public int Receive(byte[] buffer) - { - IBuffer result; - - // read all data needed (until fill buffer) - int idx = 0; - while (idx < buffer.Length) - { - // fixed scenario with socket closed gracefully by peer/broker and - // Read return 0. Avoid infinite loop. - - // read is executed synchronously - result = this.socket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None).AsTask().Result; - if (result.Length == 0) - return 0; - idx += (int)result.Length; - } - return buffer.Length; - } - - public int Receive(byte[] buffer, int timeout) - { - CancellationTokenSource cts = new CancellationTokenSource(timeout); - - try - { - IBuffer result; - - // read all data needed (until fill buffer) - int idx = 0; - while (idx < buffer.Length) - { - // fixed scenario with socket closed gracefully by peer/broker and - // Read return 0. Avoid infinite loop. - - // read is executed synchronously - result = this.socket.InputStream.ReadAsync(buffer.AsBuffer(), (uint)buffer.Length, InputStreamOptions.None).AsTask(cts.Token).Result; - if (result.Length == 0) - return 0; - idx += (int)result.Length; - } - return buffer.Length; - } - catch (TaskCanceledException) - { - return 0; - } - } - - public int Send(byte[] buffer) - { - // send is executed synchronously - return (int)this.socket.OutputStream.WriteAsync(buffer.AsBuffer()).AsTask().Result; - } - - public void Close() - { - this.socket.Dispose(); - } - - public void Connect() - { - this.socket = new StreamSocket(); - - // connection is executed synchronously - this.socket.ConnectAsync(this.remoteHostName, - this.remotePort.ToString(), - MqttSslUtility.ToSslPlatformEnum(this.sslProtocol)).AsTask().Wait(); - } - - public void Accept() - { - // TODO : SSL support with StreamSocket / StreamSocketListener seems to be NOT supported - return; - } - } - - /// - /// MQTT SSL utility class - /// - public static class MqttSslUtility - { - public static SocketProtectionLevel ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol) - { - switch (mqttSslProtocol) - { - case MqttSslProtocols.None: - return SocketProtectionLevel.PlainSocket; - case MqttSslProtocols.SSLv3: - return SocketProtectionLevel.SslAllowNullEncryption; - case MqttSslProtocols.TLSv1_0: - return SocketProtectionLevel.Tls10; - case MqttSslProtocols.TLSv1_1: - return SocketProtectionLevel.Tls11; - case MqttSslProtocols.TLSv1_2: - return SocketProtectionLevel.Tls12; - default: - throw new ArgumentException("SSL/TLS protocol version not supported"); - } - } - } -} diff --git a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Queue.cs b/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Queue.cs deleted file mode 100644 index bc6728f..0000000 --- a/paho.mqtt.m2mqtt-master/M2Mqtt/WinRT/Queue.cs +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (c) 2013, 2014 Paolo Patierno - -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -and Eclipse Distribution License v1.0 which accompany this distribution. - -The Eclipse Public License is available at - http://www.eclipse.org/legal/epl-v10.html -and the Eclipse Distribution License is available at - http://www.eclipse.org/org/documents/edl-v10.php. - -Contributors: - Paolo Patierno - initial API and implementation and/or initial documentation -*/ - -using System.Collections.Generic; - -namespace uPLibrary.Networking.M2Mqtt -{ - /// - /// Wrapper Queue class for generic Queue (the only available in WinRT) - /// - public class Queue : Queue - { - } -} diff --git a/paho.mqtt.m2mqtt-master/M2MqttVS2008.sln b/paho.mqtt.m2mqtt-master/M2MqttVS2008.sln deleted file mode 100644 index b412b81..0000000 --- a/paho.mqtt.m2mqtt-master/M2MqttVS2008.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual Studio 2008 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "M2Mqtt.NetCf35", "M2Mqtt\M2Mqtt.NetCf35.csproj", "{194FEA1B-E67F-4FC0-AC47-CD71F7F060CC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {194FEA1B-E67F-4FC0-AC47-CD71F7F060CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {194FEA1B-E67F-4FC0-AC47-CD71F7F060CC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {194FEA1B-E67F-4FC0-AC47-CD71F7F060CC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {194FEA1B-E67F-4FC0-AC47-CD71F7F060CC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/paho.mqtt.m2mqtt-master/README.md b/paho.mqtt.m2mqtt-master/README.md deleted file mode 100644 index dfa7b77..0000000 --- a/paho.mqtt.m2mqtt-master/README.md +++ /dev/null @@ -1,106 +0,0 @@ -# M2Mqtt - -![](images/M2Mqtt_Short_Logo.png) - -MQTT Client Library for .Net and WinRT - -*Project Description* - -M2Mqtt is a MQTT client available for all .Net platforms (.Net Framework, .Net Compact Framework and .Net Micro Framework) and WinRT platforms (Windows 8.1, Windows Phone 8.1 and Windows 10) for Internet of Things and M2M communication. - -MQTT, short for Message Queue Telemetry Transport, is a light weight messaging protocol that enables embedded devices with limited resources to perform asynchronous communication on a constrained network. - -MQTT protocol is based on publish/subscribe pattern so that a client can subscribe to one or more topics and receive messages that other clients publish on these topics. - -This sample is a library contains an MQTT client that you can use to connect to any MQTT broker. It is developed in C# language and works on all the following .Net platforms : - -* .Net Framework (up to 4.5) -* .Net Compact Framework 3.5 & 3.9 (for Windows Embedded Compact 7 / 2013) -* .Net Micro Framework 4.2 & 4.3 -* Mono (for Linux O.S.) - -There is also the support for WinRT platforms : - -* Windows 8.1 -* Windows Phone 8.1 -* Windows 10 - -It can be used on Windows O.S, Windows Embedded Compact 7 / 2013 and Linux O.S. (thanks to Mono Project). - -The project has an official website here : https://m2mqtt.wordpress.com/ - -The binaries for all platforms are also available as package from Nuget web site https://www.nuget.org/packages/M2Mqtt/ - -For all information about MQTT protocol, please visit official web site http://mqtt.org/. - -Follow the project on Twitter [@m2mqtt](https://twitter.com/M2Mqtt) and [Facebook](https://www.facebook.com/m2mqtt). - -*Building the source code* - -The library is available for the following solution and project files : - -* M2Mqtt.sln : solution for Visual Studio that contains projects file for .Net Framework, .Net Compact Framework 3.9, .Net Micro Framework 4.2, .Net Micro Framework 4.3 and WinRT (a portable class library) for Windows 8.1, Window Phone 8.1 and Windows 10 applications -* M2MqttVS2008.sln : solution for Visual Studio 2008 that contains project file for .Net Compact Framework 3.5; - -To build sample based on .Net Micro Framework (4.2 and 4.3) you need to download .Net Micro Framework SDK from the official CodePlex web site : https://netmf.codeplex.com/ - -To build sample based on .Net Compact Framework 3.9 you need to download Application Builder for Windows Embedded Compact 2013 from here : http://www.microsoft.com/en-us/download/details.aspx?id=38819 - -*SSL/TLS support* - -For SSL/TLS feature, the definition of the symbol "SSL" is needed before compile the project. -On the repository, this symbol is already defined and all assemblies (needed for SSL/TLS) are referenced (for Debug and Release configuration). -If you want to disable SSL/TLS feature, so that you can reduce memory occupation, you can delete "SSL" symbol and remove all assemblies referenced for SSL/TLS. -However, you can leave the default project configuration and set "secure" parameter to false and "cacert" to null for MqttClient constructor (these are already default if you don't specify any values). - -ATTENTION : .Net Micro Framework supports up to TLSV1 - -*Example* - -The M2Mqtt library provides a main class MqttClient that represents the MQTT client to connect to a broker. You can connect to the broker providing its IP address or host name and optionally some parameters related to MQTT protocol. - -After connecting to the broker you can use Publish() method to publish a message to a topic and Subscribe() method to subscribe to a topic and receive message published on it. The MqttClient class is events based so that you receive an event when a message is published to a topic you subscribed to. You can receive event when a message publishing is complete, you have subscribed or unsubscribed to a topic. - -Following an example of client subscriber to a topic : - -``` -... - -// create client instance -MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); - -// register to message received -client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; - -string clientId = Guid.NewGuid().ToString(); -client.Connect(clientId); - -// subscribe to the topic "/home/temperature" with QoS 2 -client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); - -... - -static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) -{ -// handle message received -} -``` - -Following an example of client publisher to a topic : - -``` -... - -// create client instance -MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS)); - -string clientId = Guid.NewGuid().ToString(); -client.Connect(clientId); - -string strValue = Convert.ToString(value); - -// publish a message on "/home/temperature" topic with QoS 2 -client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false); - -... -``` diff --git a/paho.mqtt.m2mqtt-master/about.html b/paho.mqtt.m2mqtt-master/about.html deleted file mode 100644 index 6555a44..0000000 --- a/paho.mqtt.m2mqtt-master/about.html +++ /dev/null @@ -1,28 +0,0 @@ - - - -About - - -

About This Content

- -

December 9, 2013

-

License

- -

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). -A copy of the EPL is available at -http://www.eclipse.org/legal/epl-v10.html -and a copy of the EDL is available at -http://www.eclipse.org/org/documents/edl-v10.php. -For purposes of the EPL, "Program" will mean the Content.

- -

If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party ("Redistributor") and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at http://www.eclipse.org.

- - diff --git a/paho.mqtt.m2mqtt-master/build.cmd b/paho.mqtt.m2mqtt-master/build.cmd deleted file mode 100644 index 5a60879..0000000 --- a/paho.mqtt.m2mqtt-master/build.cmd +++ /dev/null @@ -1,6 +0,0 @@ - -MSBuild.exe M2Mqtt.sln /p:Configuration=Release - -IF NOT EXIST ".\Build\Packages" MKDIR ".\Build\Packages" - -.\Tools\NuGet\NuGet.exe pack M2Mqtt.nuspec -OutputDirectory ".\Build\Packages" diff --git a/paho.mqtt.m2mqtt-master/deleteme.txt b/paho.mqtt.m2mqtt-master/deleteme.txt deleted file mode 100644 index e69de29..0000000 diff --git a/paho.mqtt.m2mqtt-master/edl-v10 b/paho.mqtt.m2mqtt-master/edl-v10 deleted file mode 100644 index cf989f1..0000000 --- a/paho.mqtt.m2mqtt-master/edl-v10 +++ /dev/null @@ -1,15 +0,0 @@ - -Eclipse Distribution License - v 1.0 - -Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/paho.mqtt.m2mqtt-master/epl-v10 b/paho.mqtt.m2mqtt-master/epl-v10 deleted file mode 100644 index 79e486c..0000000 --- a/paho.mqtt.m2mqtt-master/epl-v10 +++ /dev/null @@ -1,70 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: -i) changes to the Program, and -ii) additions to the Program; -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS - -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: - -a) it complies with the terms and conditions of this Agreement; and -b) its license agreement: -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and -b) a copy of this Agreement must be included with each copy of the Program. -Contributors may not remove or alter any copyright notices contained within the Program. - -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. diff --git a/paho.mqtt.m2mqtt-master/images/M2Mqtt_Short_Logo.png b/paho.mqtt.m2mqtt-master/images/M2Mqtt_Short_Logo.png deleted file mode 100644 index e5e04e10581867d385ca5098acd7bfd08ac55b11..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2951 zcmV;23wZR2P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D3mi#AK~#8N?OlCr z8)q30EvO(qHYUXQDDgQ-hxh{xC_`mJ1g18=v(u!YIR1*yb{wCbG+EQGYwpf*-LH)@ zbp^x}Hd<{GADV_lC6Hj+Uqu=pe{Abkv5tX28bg!V7oyOC+KnF1^WIafiO-GCzBjqM z+)w(+O6jnA0ChG&*Y=?KLQc{1VMjuV*5cu89ri^o3J!=$QX~+jJ#BR4X*oDAyzw3 zjMcwDxAY8903kj3Eg>~|1_J+|p0R18C%4P!&CLSw^$N|ud$Kczkg8k+o)ywl_l7c+ zEp)5S0X2OK1oELmbp9X8@L>?(uu&YW8xUXvL|K;kXw`u0jS`4g9=^*MAKZ_BKbeo! zrj@O8*O3|5p-&VyU~LblC!aw9FxdDCe;Y!wygXBr?DM_(StC5Q6Rw*&-JP6_(e3Rc zE6#luf_DmokF_0xY87z1gw|qU%R+JBo__j9L>2@;Th>W;z1ZwI91v+A@pz$X5NoGZ; z{bIO(*Y#Aa6+t*LaT9dDFJeb+6+j-uz6b{Zp~S=QK8fh^I4T5&?ffceQK9B#W>5FCC_Y(HSYMDV&5E`u{S7V99 z4m~9ZvJ7cU7PUhZV_OI%m4oQ8RUq6#&k2G?ZXm6 zQuz%(K@_%fi+xl$V{SmnkH8fhD>Q0ny4JXSZ&{CeTYp*Rqu$JP6R>9nI zwH$(iAh$w#c^PZ7)jc|)SypWynQ9r}@Kam_ffNOTTndd&EIRJ9ain+yy!U!IJ!O5J z1=|t?(^6K_?Gf95ROR~X@0KO~6{lMX6C|qNM`l_EILt*53?il~GP4Lmvh)pn-|9Lm+7<*4 zL1ZQEXJl_#z=-G!cKBBJYL{5nyreIXiIxEl^JyX3X#@I!= z%kKBU=U(J-5|Zs4irNc`@__CAb#U09g5YOiV)j$A*#LNNFYfMHUE3+mQJ(%VnX(0N z*nfiHh^Y{*T^buu`^e@Z;3_PnwAXknnIO%|ppB6^TL6dsCkWfuj;P1UUIU=-xSLn& zV54f$Y8mVnrt*6AJIQI z4)X(=v^h?*b*OC(b*~0E?0rG7cCrcHHO@joDtU~@niZ0@j%e+zc4p>F0SAA%I^Fd8FAl6x_<*?N&6j-ZCa!`37x-K zh^akft|NfM-WCLhxw51lq5-d7S#dzcLTE0+#S3Y5RvA+wWDOt zF@VF~666Zf=A5HR>)3TY^ex<$*Vz}IMXUcz4c3?4v$qRy*qee}3vxs|!n<``Yh>36 zz+rz0l8NXa#oW$oc^z9FF7M}t>s-DK2psm8ATSzR;I+JtWUV8jYh=!GfW!U~1h;H) z>z3E@I(v3d(qA4Qy7T>H(s6*p{t-lus1Ng;ci^lXpEDtITmTOHLlE|bn3&%=Eg-U0 z0a5=Wnd1g<*dKzxB=J#R%j-xSB*>EXk}T<`VgB)WD=ZHkc^scVp(3^faM=5TWJRqX z*Q@ZfqE#@RBKA#ar&Z339E0nsww|H_hrKTdw2t5MT3+vjtUt5a=YYfB76kXuc`mPa z!ZjyIy{op=Qm5d4uZb|{V0^19Pp1A?eOW=>i-??(Dski4kg!jAiMT3+WtUkd^wt9$XAqpciw zD}60UE}|dzQo2I=yoFr*fgLw85X5B+1aTPyL0m?k3!;5*SNyp7ox2_(me=l~Iw7h2 zWm9o4`(a_nn4dNJ3VV#+5#@_yW)bkmBR46k^|cnf2|f$+kZN2RI&?B8YA3uxEN>xF z-AaD91R+tX^<;LQ3?<7aoTQMRJkjj;ZG} - - - - -Eclipse Foundation Software User Agreement - - - -

Eclipse Foundation Software User Agreement

-

February 1, 2011

- -

Usage Of Content

- -

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS - (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND - CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE - OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR - NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND - CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

- -

Applicable Licenses

- -

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 - ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. - For purposes of the EPL, "Program" will mean the Content.

- -

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code - repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

- -
    -
  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • -
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • -
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins - and/or Fragments associated with that Feature.
  • -
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
  • -
- -

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and -Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module -including, but not limited to the following locations:

- -
    -
  • The top-level (root) directory
  • -
  • Plug-in and Fragment directories
  • -
  • Inside Plug-ins and Fragments packaged as JARs
  • -
  • Sub-directories of the directory named "src" of certain Plug-ins
  • -
  • Feature directories
  • -
- -

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the -installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or -inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. -Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in -that directory.

- -

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE -OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

- - - -

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please -contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

- - -

Use of Provisioning Technology

- -

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse - Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or - other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to - install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html - ("Specification").

- -

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the - applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology - in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the - Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

- -
    -
  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology - on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based - product.
  2. -
  3. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be - accessed and copied to the Target Machine.
  4. -
  5. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable - Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target - Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern - the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such - indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
  6. -
- -

Cryptography

- -

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to - another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, - possession, or use, and re-export of encryption software, to see if this is permitted.

- -

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

- - From 3e7052c4a0886f2fcbf82e789a39463188da3a87 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Fri, 21 Sep 2018 01:36:02 +0200 Subject: [PATCH 011/114] V5.5 --- EasyModbus/ModbusClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 8926af1..564de30 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Stefan Roßmann. + * Copyright (c) 2018 Stefan Roßmann. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by From 7f2a4f30c1149abe41521b3f91ebe40230d95483 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Fri, 21 Sep 2018 01:56:01 +0200 Subject: [PATCH 012/114] V5.5 --- EasyModbus/ModbusServer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index 57d7871..81351e8 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017 Stefan Roßmann. + * Copyright (c) 2018 Stefan Roßmann. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by From 20397019ee1989f02b13c7196aa340aede7941d4 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Fri, 21 Sep 2018 01:57:50 +0200 Subject: [PATCH 013/114] V5.5 --- EasyModbusTCPCore/ModbusClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EasyModbusTCPCore/ModbusClient.cs b/EasyModbusTCPCore/ModbusClient.cs index 0a13e5a..b71766f 100644 --- a/EasyModbusTCPCore/ModbusClient.cs +++ b/EasyModbusTCPCore/ModbusClient.cs @@ -14,7 +14,7 @@ namespace EasyModbus { /// - /// Implements a ModbusClient. + /// Implements a ModbusClient /// public partial class ModbusClient { From d6a3e6d5c6cc2140a09c28f2834091216cb89b30 Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Fri, 21 Sep 2018 02:01:29 +0200 Subject: [PATCH 014/114] V5.5 --- EasyModbus/Properties/AssemblyInfo.cs | 2 +- EasyModbusClientExample/Properties/AssemblyInfo.cs | 2 +- EasyModbusServerSimulator/Properties/AssemblyInfo.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/EasyModbus/Properties/AssemblyInfo.cs b/EasyModbus/Properties/AssemblyInfo.cs index 8483345..6c9dff7 100644 --- a/EasyModbus/Properties/AssemblyInfo.cs +++ b/EasyModbus/Properties/AssemblyInfo.cs @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("5.0.0")] +[assembly: AssemblyVersion("5.5.0")] diff --git a/EasyModbusClientExample/Properties/AssemblyInfo.cs b/EasyModbusClientExample/Properties/AssemblyInfo.cs index ae9a9bf..7c39ca9 100644 --- a/EasyModbusClientExample/Properties/AssemblyInfo.cs +++ b/EasyModbusClientExample/Properties/AssemblyInfo.cs @@ -28,4 +28,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("5.1.0")] +[assembly: AssemblyVersion("5.5.0")] diff --git a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs index 4620cdc..d986739 100644 --- a/EasyModbusServerSimulator/Properties/AssemblyInfo.cs +++ b/EasyModbusServerSimulator/Properties/AssemblyInfo.cs @@ -24,4 +24,4 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion ("5.1.0")] +[assembly: AssemblyVersion ("5.5.0")] From 3f5842a9dc1591e545a8c2a02cf8ee80f168df0b Mon Sep 17 00:00:00 2001 From: rossmann-engineering Date: Fri, 21 Sep 2018 07:36:18 +0200 Subject: [PATCH 015/114] V5.5 --- EasyModbus/ModbusClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 564de30..7f180ef 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -3,7 +3,7 @@ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. + * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of From 160386b26b67d2611dc345f2bbcad53ec797fb4e Mon Sep 17 00:00:00 2001 From: Ryan O'Kelley Date: Tue, 3 Mar 2020 12:25:28 -0500 Subject: [PATCH 016/114] Don't reset countRetries to prevent endless loop --- EasyModbus/ModbusClient.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 7f180ef..21b17a4 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1730,7 +1730,6 @@ public void WriteSingleCoil(int startingAddress, bool value) data = new byte[2100]; Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); receivedUnitIdentifier = data[6]; - countRetries = 0; } } From 28318fcc25ea3a0bb2d9413bce4ffb50bf9aecd5 Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Wed, 29 Apr 2020 07:26:49 +0200 Subject: [PATCH 017/114] Updated License Information --- EasyModbus/Exceptions/Exceptions.cs | 18 +- EasyModbus/ModbusClient-PC017.cs | 1816 -------------------------- EasyModbus/ModbusClient.cs | 4 +- EasyModbus/ModbusServer.cs | 2 +- EasyModbusClientExample/MainForm.cs | 16 +- EasyModbusClientExample/Program.cs | 18 +- EasyModbusServerSimulator/Program.cs | 16 +- 7 files changed, 58 insertions(+), 1832 deletions(-) delete mode 100644 EasyModbus/ModbusClient-PC017.cs diff --git a/EasyModbus/Exceptions/Exceptions.cs b/EasyModbus/Exceptions/Exceptions.cs index 2dc7e10..4213be5 100644 --- a/EasyModbus/Exceptions/Exceptions.cs +++ b/EasyModbus/Exceptions/Exceptions.cs @@ -1,8 +1,18 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: iMac - * Date: 09.07.2016 - * Time: 12:36 + * Copyright (c) 2018-2020 Stefan Roßmann. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * http://www.rossmann-engineering.de */ using System; using System.Runtime.Serialization; diff --git a/EasyModbus/ModbusClient-PC017.cs b/EasyModbus/ModbusClient-PC017.cs deleted file mode 100644 index 73faae8..0000000 --- a/EasyModbus/ModbusClient-PC017.cs +++ /dev/null @@ -1,1816 +0,0 @@ -/* - * Erstellt mit SharpDevelop. - * http://www.rossmann-engineering.de - * Datum: 16.06.2011 - * Zeit: 21:35 - */ -using System; -using System.Net.Sockets; -using System.Net; -using System.IO.Ports; -using System.Reflection; - -namespace EasyModbus -{ - /// - /// Implements a ModbusClient. - /// - public partial class ModbusClient - { - public enum RegisterOrder { LowHigh = 0, HighLow = 1 }; - private TcpClient tcpClient; - private string ipAddress = "127.0.0.1"; - private int port = 502; - private uint transactionIdentifierInternal = 0; - private byte [] transactionIdentifier = new byte[2]; - private byte [] protocolIdentifier = new byte[2]; - private byte[] crc = new byte[2]; - private byte [] length = new byte[2]; - private byte unitIdentifier = 0x01; - private byte functionCode; - private byte [] startingAddress = new byte[2]; - private byte [] quantity = new byte[2]; - private bool udpFlag = false; - private int portOut; - private int baudRate = 9600; - private int connectTimeout = 1000; - public byte[] receiveData; - public byte[] sendData; - private SerialPort serialport; - private Parity parity = Parity.Even; - private StopBits stopBits = StopBits.One; - - public delegate void ReceiveDataChanged(object sender); - public event ReceiveDataChanged receiveDataChanged; - - public delegate void SendDataChanged(object sender); - public event SendDataChanged sendDataChanged; - - NetworkStream stream; - - /// - /// Constructor which determines the Master ip-address and the Master Port. - /// - /// IP-Address of the Master device - /// Listening port of the Master device (should be 502) - public ModbusClient(string ipAddress, int port) - { - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); - this.ipAddress = ipAddress; - this.port = port; - } - - /// - /// Constructor which determines the Serial-Port - /// - /// Serial-Port Name e.G. "COM1" - public ModbusClient(string serialPort) - { - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); - this.serialport = new SerialPort(); - serialport.PortName = serialPort; - serialport.BaudRate = baudRate; - serialport.Parity = parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = connectTimeout; - serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - - - } - - /// - /// Parameterless constructor - /// - public ModbusClient() - { - Console.WriteLine("EasyModbus Client Library Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); - Console.WriteLine("Copyright (c) Stefan Rossmann Engineering Solutions"); - Console.WriteLine(); - } - - /// - /// Establish connection to Master device in case of Modbus TCP. Opens COM-Port in case of Modbus RTU - /// - public void Connect() - { - if (serialport != null) - { - if (!serialport.IsOpen) - { - serialport.BaudRate = baudRate; - serialport.Parity = parity; - serialport.StopBits = stopBits; - serialport.WriteTimeout = 10000; - serialport.ReadTimeout = connectTimeout; - serialport.Open(); - - - } - return; - } - if (!udpFlag) - { - tcpClient = new TcpClient(ipAddress, port); - stream = tcpClient.GetStream(); - stream.ReadTimeout = connectTimeout; - } - else - tcpClient = new TcpClient(); - } - - /// - /// Establish connection to Master device in case of Modbus TCP. - /// - public void Connect(string ipAddress, int port) - { - if (!udpFlag) - { - this.ipAddress = ipAddress; - this.port = port; - tcpClient = new TcpClient(ipAddress, port); - stream = tcpClient.GetStream(); - stream.ReadTimeout = connectTimeout; - } - else - tcpClient = new TcpClient(); - } - - /// - /// Converts two ModbusRegisters to Float - Example: EasyModbus.ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(19,2)) - /// - /// Two Register values received from Modbus - /// Connected float value - public static float ConvertRegistersToFloat(int[] registers) - { - if (registers.Length != 2) - throw new ArgumentException("Input Array length invalid"); - int highRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] floatBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToSingle(floatBytes, 0); - } - - /// - /// Converts two ModbusRegisters to Float, Registers can by swapped - /// - /// Two Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connected float value - public static float ConvertRegistersToFloat(int[] registers, RegisterOrder registerOrder) - { - int [] swappedRegisters = {registers[0],registers[1]}; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] {registers[1],registers[0]}; - return ConvertRegistersToFloat(swappedRegisters); - } - - /// - /// Converts two ModbusRegisters to Double - /// - /// Two Register values received from Modbus - /// Connected double value - public static Int32 ConvertRegistersToDouble(int[] registers) - { - if (registers.Length != 2) - throw new ArgumentException("Input Array length invalid"); - int highRegister = registers[1]; - int lowRegister = registers[0]; - byte[] highRegisterBytes = BitConverter.GetBytes(highRegister); - byte[] lowRegisterBytes = BitConverter.GetBytes(lowRegister); - byte[] doubleBytes = { - lowRegisterBytes[0], - lowRegisterBytes[1], - highRegisterBytes[0], - highRegisterBytes[1] - }; - return BitConverter.ToInt32(doubleBytes, 0); - } - - /// - /// Converts two ModbusRegisters to Double - Registers can be swapped - /// - /// Two Register values received from Modbus - /// Desired Word Order (Low Register first or High Register first - /// Connecteds double value - public static Int32 ConvertRegistersToDouble(int[] registers, RegisterOrder registerOrder) - { - int[] swappedRegisters = { registers[0], registers[1] }; - if (registerOrder == RegisterOrder.HighLow) - swappedRegisters = new int[] { registers[1], registers[0] }; - return ConvertRegistersToDouble(swappedRegisters); - } - - /// - /// Converts float to two ModbusRegisters - Example: modbusClient.WriteMultipleRegisters(24, EasyModbus.ModbusClient.ConvertFloatToTwoRegisters((float)1.22)); - /// - /// Float value which has to be converted into two registers - /// Register values - public static int[] ConvertFloatToTwoRegisters(float floatValue) - { - byte[] floatBytes = BitConverter.GetBytes(floatValue); - byte[] highRegisterBytes = - { - floatBytes[2], - floatBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - floatBytes[0], - floatBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts float to two ModbusRegisters Registers - Registers can be swapped - /// - /// Float value which has to be converted into two registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertFloatToTwoRegisters(float floatValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertFloatToTwoRegisters(floatValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new Int32[] { registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Converts 32 Bit Value to two ModbusRegisters - /// - /// Double value which has to be converted into two registers - /// Register values - public static int[] ConvertDoubleToTwoRegisters(Int32 doubleValue) - { - byte[] doubleBytes = BitConverter.GetBytes(doubleValue); - byte[] highRegisterBytes = - { - doubleBytes[2], - doubleBytes[3], - 0, - 0 - }; - byte[] lowRegisterBytes = - { - - doubleBytes[0], - doubleBytes[1], - 0, - 0 - }; - int[] returnValue = - { - BitConverter.ToInt32(lowRegisterBytes,0), - BitConverter.ToInt32(highRegisterBytes,0) - }; - return returnValue; - } - - /// - /// Converts 32 Bit Value to two ModbusRegisters Registers - Registers can be swapped - /// - /// Double value which has to be converted into two registers - /// Desired Word Order (Low Register first or High Register first - /// Register values - public static int[] ConvertDoubleToTwoRegisters(Int32 doubleValue, RegisterOrder registerOrder) - { - int[] registerValues = ConvertDoubleToTwoRegisters(doubleValue); - int[] returnValue = registerValues; - if (registerOrder == RegisterOrder.HighLow) - returnValue = new Int32[] { registerValues[1], registerValues[0] }; - return returnValue; - } - - /// - /// Calculates the CRC16 for Modbus-RTU - /// - /// Byte buffer to send - /// Number of bytes to calculate CRC - /// First byte in buffer to start calculating CRC - public static UInt16 calculateCRC(byte[] data, UInt16 numberOfBytes, int startByte) - { - byte[] auchCRCHi = { - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, - 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, - 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, - 0x40 - }; - - byte[] auchCRCLo = { - 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, - 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, - 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, - 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, - 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, - 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, - 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, - 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, - 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, - 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, - 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, - 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, - 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91, - 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, - 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, - 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, - 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, - 0x40 - }; - UInt16 usDataLen = numberOfBytes; - byte uchCRCHi = 0xFF ; - byte uchCRCLo = 0xFF ; - int i = 0; - int uIndex ; - while (usDataLen>0) - { - usDataLen--; - uIndex = uchCRCLo ^ data[i+startByte]; - uchCRCLo = (byte) (uchCRCHi ^ auchCRCHi[uIndex]) ; - uchCRCHi = auchCRCLo[uIndex] ; - i++; - } - return (UInt16)((UInt16)uchCRCHi << 8 | uchCRCLo); - } - - private bool dataReceived = false; - private bool receiveActive = false; - private byte[] readBuffer = new byte[256]; - private int bytesToRead = 0; - private void DataReceivedHandler(object sender, - SerialDataReceivedEventArgs e) - { - - - while (receiveActive | dataReceived) - System.Threading.Thread.Sleep(10); - receiveActive = true; - - long ticksWait = TimeSpan.TicksPerMillisecond * 2000;//((40*10000000) / this.baudRate); - - - SerialPort sp = (SerialPort)sender; - if (bytesToRead == 0) - { - sp.DiscardInBuffer(); - receiveActive = false; - return; - } - readBuffer = new byte[256]; - int numbytes=0; - int actualPositionToRead = 0; - bool modbusFrameValid = false;; - DateTime dateTimeLastRead = DateTime.Now; - do{ - - dateTimeLastRead = DateTime.Now; - while ((sp.BytesToRead) == 0) - { - System.Threading.Thread.Sleep(1); - if ((DateTime.Now.Ticks - dateTimeLastRead.Ticks) > ticksWait) - break; - } - numbytes=sp.BytesToRead ; - - - byte[] rxbytearray = new byte[numbytes]; - sp.Read(rxbytearray, 0, numbytes); - - Array.Copy(rxbytearray,0, readBuffer,actualPositionToRead, rxbytearray.Length); - - actualPositionToRead = actualPositionToRead + rxbytearray.Length; - - - - if (DetectValidModbusFrame(readBuffer, actualPositionToRead)) - { - modbusFrameValid = true; - break; - } - if (bytesToRead < actualPositionToRead) break; - } - while ((DateTime.Now.Ticks - dateTimeLastRead.Ticks) < ticksWait) ; - if (!modbusFrameValid) - { - receiveActive = false; - return; - } - bytesToRead = 0; - //10.000 Ticks in 1 ms - dataReceived = true; - receiveActive = false; - sp.DiscardInBuffer(); - receiveData = new byte[actualPositionToRead]; - Array.Copy(readBuffer, 0, receiveData, 0, actualPositionToRead); - if (receiveDataChanged != null) - { - - receiveDataChanged(this); - - } - } - - public static bool DetectValidModbusFrame(byte[] readBuffer, int length) - { - // minimum length 6 bytes - if (length < 6) - return false; - //SlaveID correct - if ((readBuffer[0] < 1) | (readBuffer[0] > 247)) - return false; - //CRC correct? - byte[] crc = new byte[2]; - crc = BitConverter.GetBytes(calculateCRC(readBuffer, (ushort)(length-2), 0)); - if (crc[0] != readBuffer[length-2] | crc[1] != readBuffer[length-1]) - return false; - return true; - } - - - /// - /// Read Discrete Inputs from Master device (FC2). - /// - /// First discrete input to be read - /// Number of discrete Inputs to be read - /// Boolean Array which contains the discrete Inputs - public bool[] ReadDiscreteInputs(int startingAddress, int quantity) - { - transactionIdentifierInternal ++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport==null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - if (startingAddress > 65535 | quantity >2000) - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 2000"); - bool[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x02; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[] - { - this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - - if (serialport != null) - { - dataReceived = false; - if (quantity % 8 == 0) - bytesToRead = 5 + quantity / 8; - else - bytesToRead = 6 + quantity / 8; - serialport.Write(data, 6, 8); - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x82 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x82 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x82 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x82 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8] + 9] | crc[1] != data[data[8] + 10]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - response = new bool[quantity]; - for (int i = 0; i < quantity; i++) - { - int intData = data[9+i/8]; - int mask = Convert.ToInt32(Math.Pow(2, (i%8))); - response[i] = Convert.ToBoolean((intData & mask)/mask); - } - return (response); - } - - /// - /// Read Coils from Master device (FC1). - /// - /// First coil to be read - /// Numer of coils to be read - /// Boolean Array which contains the coils - public bool[] ReadCoils(int startingAddress, int quantity) - { - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - if (startingAddress > 65535 | quantity >2000) - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 2000"); - bool[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x01; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ - this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - if (quantity % 8 == 0) - bytesToRead = 5 + quantity/8; - else - bytesToRead = 6 + quantity/8; - serialport.Write(data, 6, 8); - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x81 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x81 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x81 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x81 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - response = new bool[quantity]; - for (int i = 0; i < quantity; i++) - { - int intData = data[9+i/8]; - int mask = Convert.ToInt32(Math.Pow(2, (i%8))); - response[i] = Convert.ToBoolean((intData & mask)/mask); - } - return (response); - } - - /// - /// Read Holding Registers from Master device (FC3). - /// - /// First holding register to be read - /// Number of holding registers to be read - /// Int Array which contains the holding registers - public int[] ReadHoldingRegisters(int startingAddress, int quantity) - { - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - if (startingAddress > 65535 | quantity >125) - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 125"); - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x03; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2 * quantity; - serialport.Write(data, 6, 8); - - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[256]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x83 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x83 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x83 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x83 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10])& dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - response = new int[quantity]; - for (int i = 0; i < quantity; i++) - { - byte lowByte; - byte highByte; - highByte = data[9+i*2]; - lowByte = data[9+i*2+1]; - - data[9+i*2] = lowByte; - data[9+i*2+1] = highByte; - - response[i] = BitConverter.ToInt16(data,(9+i*2)); - } - return (response); - } - - /// - /// Read Input Registers from Master device (FC4). - /// - /// First input register to be read - /// Number of input registers to be read - /// Int Array which contains the input registers - public int[] ReadInputRegisters(int startingAddress, int quantity) - { - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - if (startingAddress > 65535 | quantity >125) - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 125"); - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int) 0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x04; - this.startingAddress = BitConverter.GetBytes(startingAddress); - this.quantity = BitConverter.GetBytes(quantity); - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - this.quantity[1], - this.quantity[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2 * quantity; - serialport.Write(data, 6, 8); - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x84 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x84 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x84 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x84 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data[8]+3), 6)); - if ((crc[0] != data[data[8]+9] | crc[1] != data[data[8]+10]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - response = new int[quantity]; - for (int i = 0; i < quantity; i++) - { - byte lowByte; - byte highByte; - highByte = data[9+i*2]; - lowByte = data[9+i*2+1]; - - data[9+i*2] = lowByte; - data[9+i*2+1] = highByte; - - response[i] = BitConverter.ToInt16(data,(9+i*2)); - } - return (response); - } - - - /// - /// Write single Coil to Master device (FC5). - /// - /// Coil to be written - /// Coil Value to be written - public void WriteSingleCoil(int startingAddress, bool value) - { - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - byte[] coilValue = new byte[2]; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x05; - this.startingAddress = BitConverter.GetBytes(startingAddress); - if (value == true) - { - coilValue = BitConverter.GetBytes((int)0xFF00); - } - else - { - coilValue = BitConverter.GetBytes((int)0x0000); - } - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - coilValue[1], - coilValue[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - serialport.Write(data, 6, 8); - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length - 2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length - 2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x85 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x85 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x85 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x85 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - } - - - /// - /// Write single Register to Master device (FC6). - /// - /// Register to be written - /// Register Value to be written - public void WriteSingleRegister(int startingAddress, int value) - { - transactionIdentifierInternal++; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - byte[] registerValue = new byte[2]; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x06; - this.startingAddress = BitConverter.GetBytes(startingAddress); - registerValue = BitConverter.GetBytes((int)value); - - Byte[] data = new byte[]{ this.transactionIdentifier[1], - this.transactionIdentifier[0], - this.protocolIdentifier[1], - this.protocolIdentifier[0], - this.length[1], - this.length[0], - this.unitIdentifier, - this.functionCode, - this.startingAddress[1], - this.startingAddress[0], - registerValue[1], - registerValue[0], - this.crc[0], - this.crc[1] - }; - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - data[12] = crc[0]; - data[13] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - serialport.Write(data, 6, 8); - if (sendDataChanged != null) - { - sendData = new byte[8]; - Array.Copy(data, 6, sendData, 0, 8); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length - 2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length - 2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x86 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x86 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x86 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x86 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - } - - /// - /// Write multiple coils to Master device (FC15). - /// - /// First coil to be written - /// Coil Values to be written - public void WriteMultipleCoils(int startingAddress, bool[] values) - { - transactionIdentifierInternal++; - byte byteCount = (byte)(values.Length/8+1); - byte[] quantityOfOutputs = BitConverter.GetBytes((int)values.Length); - byte singleCoilValue = 0; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)(7+(values.Length/8+1))); - this.functionCode = 0x0F; - this.startingAddress = BitConverter.GetBytes(startingAddress); - - Byte[] data = new byte[14 +2 + values.Length/8]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = this.startingAddress[1]; - data[9] = this.startingAddress[0]; - data[10] = quantityOfOutputs[1]; - data[11] = quantityOfOutputs[0]; - data[12] = byteCount; - for (int i = 0; i < values.Length; i++) - { - if ((i % 8) == 0) - singleCoilValue = 0; - byte CoilValue; - if (values[i] == true) - CoilValue = 1; - else - CoilValue = 0; - - - singleCoilValue = (byte)((int)CoilValue<<(i%8) | (int)singleCoilValue); - - data[13 + (i / 8)] = singleCoilValue; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - serialport.Write(data, 6, data.Length - 6); - if (sendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x8F & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x8F & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x8F & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x8F & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) & dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - } - - /// - /// Write multiple registers to Master device (FC16). - /// - /// First register to be written - /// register Values to be written - public void WriteMultipleRegisters(int startingAddress, int[] values) - { - transactionIdentifierInternal++; - byte byteCount = (byte)(values.Length * 2); - byte[] quantityOfOutputs = BitConverter.GetBytes((int)values.Length); - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)(7+values.Length*2)); - this.functionCode = 0x10; - this.startingAddress = BitConverter.GetBytes(startingAddress); - - Byte[] data = new byte[13+2 + values.Length*2]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = this.startingAddress[1]; - data[9] = this.startingAddress[0]; - data[10] = quantityOfOutputs[1]; - data[11] = quantityOfOutputs[0]; - data[12] = byteCount; - for (int i = 0; i < values.Length; i++) - { - byte[] singleRegisterValue = BitConverter.GetBytes((int)values[i]); - data[13 + i*2] = singleRegisterValue[1]; - data[14 + i*2] = singleRegisterValue[0]; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 8; - serialport.Write(data, 6, data.Length - 6); - if (sendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x90 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x90 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x90 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x90 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - if (serialport != null) - { - crc = BitConverter.GetBytes(calculateCRC(data, 6, 6)); - if ((crc[0] != data[12] | crc[1] != data[13]) &dataReceived) - throw new EasyModbus.Exceptions.CRCCheckFailedException("Response CRC check failed"); - else if (!dataReceived) - throw new TimeoutException("No Response from Modbus Slave"); - } - } - - /// - /// Read/Write Multiple Registers (FC23). - /// - /// First input register to read - /// Number of input registers to read - /// First input register to write - /// Values to write - /// Int Array which contains the Holding registers - public int[] ReadWriteMultipleRegisters(int startingAddressRead, int quantityRead, int startingAddressWrite, int[] values) - { - transactionIdentifierInternal++; - byte [] startingAddressReadLocal = new byte[2]; - byte [] quantityReadLocal = new byte[2]; - byte[] startingAddressWriteLocal = new byte[2]; - byte[] quantityWriteLocal = new byte[2]; - byte writeByteCountLocal = 0; - if (serialport != null) - if (!serialport.IsOpen) - throw new EasyModbus.Exceptions.SerialPortNotOpenedException("serial port not opened"); - if (tcpClient == null & !udpFlag & serialport == null) - throw new EasyModbus.Exceptions.ConnectionException("connection error"); - if (startingAddressRead > 65535 | quantityRead > 125 | startingAddressWrite > 65535 | values.Length > 121) - throw new ArgumentException("Starting address must be 0 - 65535; quantity must be 0 - 125"); - int[] response; - this.transactionIdentifier = BitConverter.GetBytes((uint)transactionIdentifierInternal); - this.protocolIdentifier = BitConverter.GetBytes((int)0x0000); - this.length = BitConverter.GetBytes((int)0x0006); - this.functionCode = 0x17; - startingAddressReadLocal = BitConverter.GetBytes(startingAddressRead); - quantityReadLocal = BitConverter.GetBytes(quantityRead); - startingAddressWriteLocal = BitConverter.GetBytes(startingAddressWrite); - quantityWriteLocal = BitConverter.GetBytes(values.Length); - writeByteCountLocal = Convert.ToByte(values.Length * 2); - Byte[] data = new byte[17 +2+ values.Length*2]; - data[0] = this.transactionIdentifier[1]; - data[1] = this.transactionIdentifier[0]; - data[2] = this.protocolIdentifier[1]; - data[3] = this.protocolIdentifier[0]; - data[4] = this.length[1]; - data[5] = this.length[0]; - data[6] = this.unitIdentifier; - data[7] = this.functionCode; - data[8] = startingAddressReadLocal[1]; - data[9] = startingAddressReadLocal[0]; - data[10] = quantityReadLocal[1]; - data[11] = quantityReadLocal[0]; - data[12] = startingAddressWriteLocal[1]; - data[13] = startingAddressWriteLocal[0]; - data[14] = quantityWriteLocal[1]; - data[15] = quantityWriteLocal[0]; - data[16] = writeByteCountLocal; - - for (int i = 0; i < values.Length; i++) - { - byte[] singleRegisterValue = BitConverter.GetBytes((int)values[i]); - data[17 + i*2] = singleRegisterValue[1]; - data[18 + i*2] = singleRegisterValue[0]; - } - crc = BitConverter.GetBytes(calculateCRC(data, (ushort)(data.Length - 8), 6)); - data[data.Length - 2] = crc[0]; - data[data.Length - 1] = crc[1]; - if (serialport != null) - { - dataReceived = false; - bytesToRead = 5 + 2*quantityRead; - serialport.Write(data, 6, data.Length - 6); - if (sendDataChanged != null) - { - sendData = new byte[data.Length - 6]; - Array.Copy(data, 6, sendData, 0, data.Length - 6); - sendDataChanged(this); - } - DateTime dateTimeSend = DateTime.Now; - byte receivedUnitIdentifier = 0xFF; - while (receivedUnitIdentifier != this.unitIdentifier & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - { - while (dataReceived == false & !((DateTime.Now.Ticks - dateTimeSend.Ticks) > TimeSpan.TicksPerMillisecond * this.connectTimeout)) - System.Threading.Thread.Sleep(1); - data = new byte[2100]; - Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); - receivedUnitIdentifier = data[6]; - } - if (receivedUnitIdentifier != this.unitIdentifier) - data = new byte[2100]; - } - else if (tcpClient.Client.Connected | udpFlag) - { - if (udpFlag) - { - UdpClient udpClient = new UdpClient(); - IPEndPoint endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), port); - udpClient.Send(data, data.Length-2, endPoint); - portOut = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; - udpClient.Client.ReceiveTimeout = 5000; - endPoint = new IPEndPoint(System.Net.IPAddress.Parse(ipAddress), portOut); - data = udpClient.Receive(ref endPoint); - } - else - { - stream.Write(data, 0, data.Length-2); - if (sendDataChanged != null) - { - sendData = new byte[data.Length-2]; - Array.Copy(data, 0, sendData, 0, data.Length-2); - sendDataChanged(this); - } - data = new Byte[2100]; - int NumberOfBytes = stream.Read(data, 0, data.Length); - if (receiveDataChanged != null) - { - receiveData = new byte[NumberOfBytes]; - Array.Copy(data, 0, receiveData, 0, NumberOfBytes); - receiveDataChanged(this); - } - } - } - if (data[7] == 0x97 & data[8] == 0x01) - throw new EasyModbus.Exceptions.FunctionCodeNotSupportedException("Function code not supported by master"); - if (data[7] == 0x97 & data[8] == 0x02) - throw new EasyModbus.Exceptions.StartingAddressInvalidException("Starting address invalid or starting address + quantity invalid"); - if (data[7] == 0x97 & data[8] == 0x03) - throw new EasyModbus.Exceptions.QuantityInvalidException("quantity invalid"); - if (data[7] == 0x97 & data[8] == 0x04) - throw new EasyModbus.Exceptions.ModbusException("error reading"); - response = new int[quantityRead]; - for (int i = 0; i < quantityRead; i++) - { - byte lowByte; - byte highByte; - highByte = data[9 + i * 2]; - lowByte = data[9 + i * 2 + 1]; - - data[9 + i * 2] = lowByte; - data[9 + i * 2 + 1] = highByte; - - response[i] = BitConverter.ToInt16(data, (9 + i * 2)); - } - return (response); - } - - /// - /// Close connection to Master Device. - /// - public void Disconnect() - { - if (serialport != null) - { - if (serialport.IsOpen) - { - System.Threading.Thread CloseDown = new System.Threading.Thread(new System.Threading.ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang - CloseDown.Start(); //close port in new thread to avoid hang - } - - return; - } - if (stream != null) - stream.Close(); - if (tcpClient != null) - tcpClient.Close(); - } - - /// - /// Close Serial connection in a sepereta Thread - /// - private void CloseSerialOnExit() - { - serialport.Close(); - } - - /// - /// Destructor - Close connection to Master Device. - /// - ~ ModbusClient() - { - if (serialport != null) - { - if (serialport.IsOpen) - serialport.Close(); - return; - } - if (tcpClient != null & !udpFlag) - { - stream.Close(); - tcpClient.Close(); - } - } - - /// - /// Returns "TRUE" if Client is connected to Server and "FALSE" if not. In case of Modbus RTU returns if COM-Port is opened - /// - public bool Connected - { - get - { - if (serialport != null) - { - return (serialport.IsOpen); - } - - if (udpFlag & tcpClient != null) - return true; - if (tcpClient == null) - return false; - else - return tcpClient.Connected; - - } - } - - public bool Available(int timeout) - { - // Ping's the local machine. - System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping(); - IPAddress address = System.Net.IPAddress.Parse(ipAddress); - - // Create a buffer of 32 bytes of data to be transmitted. - string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - byte[] buffer = System.Text.Encoding.ASCII.GetBytes(data); - - // Wait 10 seconds for a reply. - System.Net.NetworkInformation.PingReply reply = pingSender.Send(address, timeout, buffer); - - if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) - return true; - else - return false; - } - - /// - /// Gets or Sets the IP-Address of the Server. - /// - public string IPAddress - { - get - { - return ipAddress; - } - set - { - ipAddress = value; - } - } - - /// - /// Gets or Sets the Port were the Modbus-TCP Server is reachable (Standard is 502). - /// - public int Port - { - get - { - return port; - } - set - { - port = value; - } - } - - /// - /// Gets or Sets the UDP-Flag to activate Modbus UDP. - /// - public bool UDPFlag - { - get - { - return udpFlag; - } - set - { - udpFlag = value; - } - } - - /// - /// Gets or Sets the Unit identifier in case of serial connection (Default = 0) - /// - public byte UnitIdentifier - { - get - { - return unitIdentifier; - } - set - { - unitIdentifier = value; - } - } - - - /// - /// Gets or Sets the Baudrate for serial connection (Default = 9600) - /// - public int Baudrate - { - get - { - return baudRate; - } - set - { - baudRate = value; - } - } - - /// - /// Gets or Sets the of Parity in case of serial connection - /// - public Parity Parity - { - get - { - if (serialport != null) - return parity; - else - return Parity.Even; - } - set - { - if (serialport != null) - parity = value; - } - } - - - /// - /// Gets or Sets the number of stopbits in case of serial connection - /// - public StopBits StopBits - { - get - { - if (serialport != null) - return stopBits; - else - return StopBits.One; - } - set - { - if (serialport != null) - stopBits = value; - } - } - - /// - /// Gets or Sets the connection Timeout in case of ModbusTCP connection - /// - public int ConnectionTimeout - { - get - { - return connectTimeout; - } - set - { - connectTimeout = value; - } - } - } -} diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 7f180ef..5abae31 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Stefan Roßmann. + * Copyright (c) 2018-2020 Stefan Roßmann. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -13,8 +13,6 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * http://www.rossmann-engineering.de - * Datum: 16.06.2011 - * Zeit: 21:35 */ using System; using System.Net.Sockets; diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index 81351e8..d46d5d3 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018 Stefan Roßmann. + * Copyright (c) 2018-2020 Stefan Roßmann. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by diff --git a/EasyModbusClientExample/MainForm.cs b/EasyModbusClientExample/MainForm.cs index 169ff4e..3ed25cf 100644 --- a/EasyModbusClientExample/MainForm.cs +++ b/EasyModbusClientExample/MainForm.cs @@ -1,6 +1,18 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * www.rossmann-engineering.de + * Copyright (c) 2018-2020 Stefan Roßmann. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * http://www.rossmann-engineering.de */ using System; using System.Collections.Generic; diff --git a/EasyModbusClientExample/Program.cs b/EasyModbusClientExample/Program.cs index e16beb1..5e2fc08 100644 --- a/EasyModbusClientExample/Program.cs +++ b/EasyModbusClientExample/Program.cs @@ -1,8 +1,18 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 13.02.2015 - * Time: 11:09 + * Copyright (c) 2018-2020 Stefan Roßmann. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * http://www.rossmann-engineering.de */ using System; using System.Windows.Forms; diff --git a/EasyModbusServerSimulator/Program.cs b/EasyModbusServerSimulator/Program.cs index 3283099..925b6be 100644 --- a/EasyModbusServerSimulator/Program.cs +++ b/EasyModbusServerSimulator/Program.cs @@ -1,6 +1,18 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: www.rossmann-engineering.de + * Copyright (c) 2018-2020 Stefan Roßmann. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * http://www.rossmann-engineering.de */ using System; using System.Windows.Forms; From 7afed948fabecef93fde0c1fe1c62a64f6ef534e Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Sat, 20 Jun 2020 10:27:34 +0200 Subject: [PATCH 018/114] Changed license to MIT --- EasyModbus/Exceptions/Exceptions.cs | 37 +++++++++++-------- EasyModbus/ModbusClient.cs | 35 +++++++++++------- EasyModbus/ModbusServer.cs | 37 +++++++++++-------- EasyModbus/StoreLogData.cs | 26 ++++++++++++- EasyModbusAdvancedClient/AddConnectionForm.cs | 27 +++++++++++--- .../AddFunctionCodeForm.cs | 27 +++++++++++--- EasyModbusAdvancedClient/EasyModbusManager.cs | 27 +++++++++++--- EasyModbusAdvancedClient/MainForm.cs | 27 +++++++++++--- EasyModbusAdvancedClient/Program.cs | 27 +++++++++++--- EasyModbusClientExample/MainForm.cs | 37 +++++++++++-------- EasyModbusClientExample/Program.cs | 37 +++++++++++-------- EasyModbusServerSimulator/Program.cs | 37 +++++++++++-------- EasyModbusTCPCore/Exceptions/Exceptions.cs | 27 +++++++++++--- EasyModbusTCPCore/ModbusClient.cs | 27 +++++++++++--- EasyModbusTCPCore/ModbusServer.cs | 25 +++++++++++-- 15 files changed, 332 insertions(+), 128 deletions(-) diff --git a/EasyModbus/Exceptions/Exceptions.cs b/EasyModbus/Exceptions/Exceptions.cs index 4213be5..8d1db4f 100644 --- a/EasyModbus/Exceptions/Exceptions.cs +++ b/EasyModbus/Exceptions/Exceptions.cs @@ -1,19 +1,26 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Runtime.Serialization; diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index 5abae31..9e47854 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1,18 +1,25 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Net.Sockets; diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index d46d5d3..19012c8 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -1,19 +1,26 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Collections.Generic; diff --git a/EasyModbus/StoreLogData.cs b/EasyModbus/StoreLogData.cs index 569178c..3345038 100644 --- a/EasyModbus/StoreLogData.cs +++ b/EasyModbus/StoreLogData.cs @@ -1,4 +1,28 @@ -using System; +/* +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +using System; using System.Collections.Generic; using System.Text; diff --git a/EasyModbusAdvancedClient/AddConnectionForm.cs b/EasyModbusAdvancedClient/AddConnectionForm.cs index fa93a7c..6b74d1e 100644 --- a/EasyModbusAdvancedClient/AddConnectionForm.cs +++ b/EasyModbusAdvancedClient/AddConnectionForm.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 25.11.2015 - * Time: 07:35 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Drawing; using System.ComponentModel; diff --git a/EasyModbusAdvancedClient/AddFunctionCodeForm.cs b/EasyModbusAdvancedClient/AddFunctionCodeForm.cs index 3028805..64d7283 100644 --- a/EasyModbusAdvancedClient/AddFunctionCodeForm.cs +++ b/EasyModbusAdvancedClient/AddFunctionCodeForm.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 26.11.2015 - * Time: 06:55 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Drawing; using System.Windows.Forms; diff --git a/EasyModbusAdvancedClient/EasyModbusManager.cs b/EasyModbusAdvancedClient/EasyModbusManager.cs index cbac3bf..f0d8d01 100644 --- a/EasyModbusAdvancedClient/EasyModbusManager.cs +++ b/EasyModbusAdvancedClient/EasyModbusManager.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 25.11.2015 - * Time: 12:44 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Collections.Generic; using System.Drawing; diff --git a/EasyModbusAdvancedClient/MainForm.cs b/EasyModbusAdvancedClient/MainForm.cs index 73187de..2f26e74 100644 --- a/EasyModbusAdvancedClient/MainForm.cs +++ b/EasyModbusAdvancedClient/MainForm.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 25.11.2015 - * Time: 06:50 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Collections.Generic; using System.Drawing; diff --git a/EasyModbusAdvancedClient/Program.cs b/EasyModbusAdvancedClient/Program.cs index 100884e..b7b3982 100644 --- a/EasyModbusAdvancedClient/Program.cs +++ b/EasyModbusAdvancedClient/Program.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: srossmann - * Date: 25.11.2015 - * Time: 06:50 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Windows.Forms; diff --git a/EasyModbusClientExample/MainForm.cs b/EasyModbusClientExample/MainForm.cs index 3ed25cf..d374705 100644 --- a/EasyModbusClientExample/MainForm.cs +++ b/EasyModbusClientExample/MainForm.cs @@ -1,19 +1,26 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Collections.Generic; using System.Drawing; diff --git a/EasyModbusClientExample/Program.cs b/EasyModbusClientExample/Program.cs index 5e2fc08..da22046 100644 --- a/EasyModbusClientExample/Program.cs +++ b/EasyModbusClientExample/Program.cs @@ -1,19 +1,26 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Windows.Forms; diff --git a/EasyModbusServerSimulator/Program.cs b/EasyModbusServerSimulator/Program.cs index 925b6be..c57be66 100644 --- a/EasyModbusServerSimulator/Program.cs +++ b/EasyModbusServerSimulator/Program.cs @@ -1,19 +1,26 @@ /* - * Copyright (c) 2018-2020 Stefan Roßmann. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3. - * - * This program is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Windows.Forms; using EasyModbus; diff --git a/EasyModbusTCPCore/Exceptions/Exceptions.cs b/EasyModbusTCPCore/Exceptions/Exceptions.cs index fc25570..7db677e 100644 --- a/EasyModbusTCPCore/Exceptions/Exceptions.cs +++ b/EasyModbusTCPCore/Exceptions/Exceptions.cs @@ -1,9 +1,26 @@ /* - * Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0) - * User: iMac - * Date: 09.07.2016 - * Time: 12:36 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; namespace EasyModbus.Exceptions diff --git a/EasyModbusTCPCore/ModbusClient.cs b/EasyModbusTCPCore/ModbusClient.cs index b71766f..1e94ea5 100644 --- a/EasyModbusTCPCore/ModbusClient.cs +++ b/EasyModbusTCPCore/ModbusClient.cs @@ -1,9 +1,26 @@ /* - * GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - * http://www.rossmann-engineering.de - * Datum: 16.06.2011 - * Zeit: 21:35 - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Net.Sockets; using System.Net; diff --git a/EasyModbusTCPCore/ModbusServer.cs b/EasyModbusTCPCore/ModbusServer.cs index bd61a4b..12102be 100644 --- a/EasyModbusTCPCore/ModbusServer.cs +++ b/EasyModbusTCPCore/ModbusServer.cs @@ -1,7 +1,26 @@ /* - * GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - * http://www.rossmann-engineering.de - */ +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ using System; using System.Collections.Generic; From a5aa8729802d1ee45bf303d8ad6ed2706e086aa9 Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Sat, 20 Jun 2020 10:33:08 +0200 Subject: [PATCH 019/114] Changed license to MIT --- README.md | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index f7f701f..d1a2c60 100644 --- a/README.md +++ b/README.md @@ -35,17 +35,26 @@ Supports Function Codes: Modbus TCP, Modbus UDP and Modbus RTU client/server library - This file is part of the EasyModbus library. - - EasyModbus is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - EasyModbus is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with EasyModbus. If not, see . +/* +Copyright (c) 2018-2020 Rossmann-Engineering +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software +and associated documentation files (the "Software"), +to deal in the Software without restriction, +including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission +notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE +OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ From f1290b343b5b815d0991aec21d4c14e94c6e0e18 Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Sat, 20 Jun 2020 10:34:11 +0200 Subject: [PATCH 020/114] Changed license to MIT --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index d1a2c60..f6454d1 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,6 @@ Supports Function Codes: Modbus TCP, Modbus UDP and Modbus RTU client/server library -/* Copyright (c) 2018-2020 Rossmann-Engineering Permission is hereby granted, free of charge, to any person obtaining a copy of this software @@ -57,4 +56,3 @@ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ From 7e3674cd9547b614bc66f9a1332e778291681f10 Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Mon, 22 Jun 2020 18:53:29 +0200 Subject: [PATCH 021/114] Write Single Coil issue --- EasyModbus.sln | 56 ++++++++++++++++++++++++++++++++++++-- EasyModbus/ModbusClient.cs | 8 +++++- 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/EasyModbus.sln b/EasyModbus.sln index 0193508..a5b3acb 100644 --- a/EasyModbus.sln +++ b/EasyModbus.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2010 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29503.13 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbus", "EasyModbus\EasyModbus.csproj", "{7657FC4A-AEDF-4F17-B3E9-0D0DFB1CE23B}" EndProject @@ -17,6 +17,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyModbusTCPCore", "EasyMo EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyModbusClient_IOTCoreExample", "EasyModbusClient_IOTCoreExample\EasyModbusClient_IOTCoreExample.csproj", "{9AC81F46-F110-46F3-B884-6665D8A05267}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApplication1", "ConsoleApplication1\ConsoleApplication1.csproj", "{AA208FA1-1496-4BBC-97D1-9F628EB4197A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -404,12 +406,60 @@ Global {9AC81F46-F110-46F3-B884-6665D8A05267}.Release|x86.ActiveCfg = Release|x86 {9AC81F46-F110-46F3-B884-6665D8A05267}.Release|x86.Build.0 = Release|x86 {9AC81F46-F110-46F3-B884-6665D8A05267}.Release|x86.Deploy.0 = Release|x86 + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|ARM.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|ARM.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|x64.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|x64.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|x86.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Debug|x86.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|Any CPU.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|Any CPU.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|ARM.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|ARM.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|x64.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|x64.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|x86.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial|x86.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|Any CPU.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|Any CPU.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|ARM.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|ARM.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|x64.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|x64.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|x86.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial1|x86.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|Any CPU.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|Any CPU.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|ARM.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|ARM.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|x64.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|x64.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|x86.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial2|x86.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|Any CPU.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|Any CPU.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|ARM.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|ARM.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|x64.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|x64.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|x86.ActiveCfg = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.DebugCommercial3|x86.Build.0 = Debug|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|Any CPU.Build.0 = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|ARM.ActiveCfg = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|ARM.Build.0 = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|x64.ActiveCfg = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|x64.Build.0 = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|x86.ActiveCfg = Release|Any CPU + {AA208FA1-1496-4BBC-97D1-9F628EB4197A}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {7628B1C9-8DDB-4DBD-A71D-D369A4A166DE} VisualSVNWorkingCopyRoot = . + SolutionGuid = {7628B1C9-8DDB-4DBD-A71D-D369A4A166DE} EndGlobalSection EndGlobal diff --git a/EasyModbus/ModbusClient.cs b/EasyModbus/ModbusClient.cs index bcecf85..c1e8f38 100644 --- a/EasyModbus/ModbusClient.cs +++ b/EasyModbus/ModbusClient.cs @@ -1579,6 +1579,7 @@ public int[] ReadInputRegisters(int startingAddress, int quantity) if (debug) StoreLogData.Instance.Store("Receive ModbusTCP-Data: " + BitConverter.ToString(receiveData), System.DateTime.Now); ReceiveDataChanged(this); } + } } if (data[7] == 0x84 & data[8] == 0x01) @@ -1736,7 +1737,12 @@ public void WriteSingleCoil(int startingAddress, bool value) Array.Copy(readBuffer, 0, data, 6, readBuffer.Length); receivedUnitIdentifier = data[6]; } - + + if (receivedUnitIdentifier != this.unitIdentifier) + data = new byte[2100]; + else + countRetries = 0; + } else if (tcpClient.Client.Connected | udpFlag) { From 39c3034e0ec64afcfb85b0deb259554dcf516908 Mon Sep 17 00:00:00 2001 From: Darren Rook Date: Sun, 11 Oct 2020 20:33:44 -0500 Subject: [PATCH 022/114] When creating TCP and UDP servers, you can specify which network interface to use. Added new event delegates to ModbusServer class that pass a reference to the server to the event. --- EasyModbus/ModbusServer.cs | 71 +++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 13 deletions(-) diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index 19012c8..2ef1247 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -85,7 +85,7 @@ internal class TCPHandler public event NumberOfClientsChanged numberOfClientsChanged; TcpListener server = null; - + private List tcpClientLastRequestList = new List(); @@ -93,19 +93,32 @@ internal class TCPHandler public string ipAddress = null; + /// When making a server TCP listen socket, will listen to this IP address. + public IPAddress LocalIPAddress { + get { return localIPAddress; } + } + private IPAddress localIPAddress = IPAddress.Any; + + /// + /// Listen to all network interfaces. + /// + /// TCP port to listen public TCPHandler(int port) { - IPAddress localAddr = IPAddress.Any; - server = new TcpListener(localAddr, port); + server = new TcpListener(LocalIPAddress, port); server.Start(); server.BeginAcceptTcpClient(AcceptTcpClientCallback, null); } - public TCPHandler(string ipAddress, int port) + /// + /// Listen to a specific network interface. + /// + /// IP address of network interface to listen + /// TCP port to listen + public TCPHandler(IPAddress localIPAddress, int port) { - this.ipAddress = ipAddress; - IPAddress localAddr = IPAddress.Any; - server = new TcpListener(localAddr, port); + this.localIPAddress = localIPAddress; + server = new TcpListener(LocalIPAddress, port); server.Start(); server.BeginAcceptTcpClient(AcceptTcpClientCallback, null); } @@ -311,8 +324,17 @@ public class ModbusServer object lockCoils = new object(); object lockHoldingRegisters = new object(); private volatile bool shouldStop; - + private IPAddress localIPAddress = IPAddress.Any; + + /// + /// When creating a TCP or UDP socket, the local IP address to attach to. + /// + public IPAddress LocalIPAddress + { + get { return localIPAddress; } + set { if (listenerThread == null) localIPAddress = value; } + } public ModbusServer() { @@ -326,15 +348,23 @@ public ModbusServer() #region events public delegate void CoilsChangedHandler(int coil, int numberOfCoils); public event CoilsChangedHandler CoilsChanged; + public delegate void CoilsChangedWithServerHandler(ModbusServer server, int coil, int numberOfCoils); + public event CoilsChangedWithServerHandler CoilsChangedWithServer; public delegate void HoldingRegistersChangedHandler(int register, int numberOfRegisters); public event HoldingRegistersChangedHandler HoldingRegistersChanged; + public delegate void HoldingRegistersChangedWithServerHandler(ModbusServer server, int register, int numberOfRegisters); + public event HoldingRegistersChangedWithServerHandler HoldingRegistersChangedWithServer; public delegate void NumberOfConnectedClientsChangedHandler(); public event NumberOfConnectedClientsChangedHandler NumberOfConnectedClientsChanged; + public delegate void NumberOfConnectedClientsChangedWithServerHandler(ModbusServer server); + public event NumberOfConnectedClientsChangedWithServerHandler NumberOfConnectedClientsChangedWithServer; public delegate void LogDataChangedHandler(); public event LogDataChangedHandler LogDataChanged; + public delegate void LogDataChangedWithServerHandler(ModbusServer server); + public event LogDataChangedWithServerHandler LogDataChangedWithServer; #endregion public void Listen() @@ -379,9 +409,9 @@ private void ListenerThread() udpClient.Close(); } catch (Exception) { } - } - tcpHandler = new TCPHandler(port); - if (debug) StoreLogData.Instance.Store("EasyModbus Server listing for incomming data at Port " + port, System.DateTime.Now); + } + tcpHandler = new TCPHandler(LocalIPAddress, port); + if (debug) StoreLogData.Instance.Store($"EasyModbus Server listing for incomming data at Port {port}, local IP {LocalIPAddress}", System.DateTime.Now); tcpHandler.dataChanged += new TCPHandler.DataChanged(ProcessReceivedData); tcpHandler.numberOfClientsChanged += new TCPHandler.NumberOfClientsChanged(numberOfClientsChanged); } @@ -408,8 +438,9 @@ private void ListenerThread() { if (udpClient == null | PortChanged) { - udpClient = new UdpClient(port); - if (debug) StoreLogData.Instance.Store("EasyModbus Server listing for incomming data at Port " + port, System.DateTime.Now); + IPEndPoint localEndoint = new IPEndPoint(LocalIPAddress, port); + udpClient = new UdpClient(localEndoint); + if (debug) StoreLogData.Instance.Store($"EasyModbus Server listing for incomming data at Port {port}, local IP {LocalIPAddress}", System.DateTime.Now); udpClient.Client.ReceiveTimeout = 1000; iPEndPoint = new IPEndPoint(IPAddress.Any, port); PortChanged = false; @@ -485,6 +516,8 @@ private void numberOfClientsChanged() numberOfConnections = tcpHandler.NumberOfConnectedClients; if (NumberOfConnectedClientsChanged != null) NumberOfConnectedClientsChanged(); + if (NumberOfConnectedClientsChangedWithServer != null) + NumberOfConnectedClientsChangedWithServer(this); } #endregion @@ -650,6 +683,8 @@ private void ProcessReceivedData(object networkConnectionParameter) if (LogDataChanged != null) LogDataChanged(); + if (LogDataChangedWithServer != null) + LogDataChangedWithServer(this); } } #endregion @@ -1390,6 +1425,8 @@ private void WriteSingleCoil(ModbusProtocol receiveData, ModbusProtocol sendData catch (Exception) { } if (CoilsChanged != null) CoilsChanged(receiveData.startingAdress+1, 1); + if (CoilsChangedWithServer != null) + CoilsChangedWithServer(this, receiveData.startingAdress + 1, 1); } } @@ -1513,6 +1550,8 @@ private void WriteSingleRegister(ModbusProtocol receiveData, ModbusProtocol send catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAdress+1, 1); + if (HoldingRegistersChangedWithServer != null) + HoldingRegistersChangedWithServer(this, receiveData.startingAdress + 1, 1); } } @@ -1653,6 +1692,8 @@ private void WriteMultipleCoils(ModbusProtocol receiveData, ModbusProtocol sendD catch (Exception) { } if (CoilsChanged != null) CoilsChanged(receiveData.startingAdress+1, receiveData.quantity); + if (CoilsChangedWithServer != null) + CoilsChangedWithServer(this, receiveData.startingAdress + 1, receiveData.quantity); } } @@ -1777,6 +1818,8 @@ private void WriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtocol s catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAdress+1, receiveData.quantity); + if (HoldingRegistersChangedWithServer != null) + HoldingRegistersChangedWithServer(this, receiveData.startingAdress + 1, receiveData.quantity); } } @@ -1908,6 +1951,8 @@ private void ReadWriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtoc catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAddressWrite+1, receiveData.quantityWrite); + if (HoldingRegistersChangedWithServer != null) + HoldingRegistersChangedWithServer(this, receiveData.startingAddressWrite + 1, receiveData.quantityWrite); } } From 4e7d1ff293e96a275c18a5046645369baf9e72cf Mon Sep 17 00:00:00 2001 From: Darren Rook Date: Tue, 20 Oct 2020 20:34:33 -0500 Subject: [PATCH 023/114] Removed the new delegates --- EasyModbus/ModbusServer.cs | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/EasyModbus/ModbusServer.cs b/EasyModbus/ModbusServer.cs index 2ef1247..13374cd 100644 --- a/EasyModbus/ModbusServer.cs +++ b/EasyModbus/ModbusServer.cs @@ -348,23 +348,15 @@ public ModbusServer() #region events public delegate void CoilsChangedHandler(int coil, int numberOfCoils); public event CoilsChangedHandler CoilsChanged; - public delegate void CoilsChangedWithServerHandler(ModbusServer server, int coil, int numberOfCoils); - public event CoilsChangedWithServerHandler CoilsChangedWithServer; public delegate void HoldingRegistersChangedHandler(int register, int numberOfRegisters); public event HoldingRegistersChangedHandler HoldingRegistersChanged; - public delegate void HoldingRegistersChangedWithServerHandler(ModbusServer server, int register, int numberOfRegisters); - public event HoldingRegistersChangedWithServerHandler HoldingRegistersChangedWithServer; public delegate void NumberOfConnectedClientsChangedHandler(); public event NumberOfConnectedClientsChangedHandler NumberOfConnectedClientsChanged; - public delegate void NumberOfConnectedClientsChangedWithServerHandler(ModbusServer server); - public event NumberOfConnectedClientsChangedWithServerHandler NumberOfConnectedClientsChangedWithServer; public delegate void LogDataChangedHandler(); public event LogDataChangedHandler LogDataChanged; - public delegate void LogDataChangedWithServerHandler(ModbusServer server); - public event LogDataChangedWithServerHandler LogDataChangedWithServer; #endregion public void Listen() @@ -516,8 +508,6 @@ private void numberOfClientsChanged() numberOfConnections = tcpHandler.NumberOfConnectedClients; if (NumberOfConnectedClientsChanged != null) NumberOfConnectedClientsChanged(); - if (NumberOfConnectedClientsChangedWithServer != null) - NumberOfConnectedClientsChangedWithServer(this); } #endregion @@ -683,8 +673,6 @@ private void ProcessReceivedData(object networkConnectionParameter) if (LogDataChanged != null) LogDataChanged(); - if (LogDataChangedWithServer != null) - LogDataChangedWithServer(this); } } #endregion @@ -1425,8 +1413,6 @@ private void WriteSingleCoil(ModbusProtocol receiveData, ModbusProtocol sendData catch (Exception) { } if (CoilsChanged != null) CoilsChanged(receiveData.startingAdress+1, 1); - if (CoilsChangedWithServer != null) - CoilsChangedWithServer(this, receiveData.startingAdress + 1, 1); } } @@ -1550,8 +1536,6 @@ private void WriteSingleRegister(ModbusProtocol receiveData, ModbusProtocol send catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAdress+1, 1); - if (HoldingRegistersChangedWithServer != null) - HoldingRegistersChangedWithServer(this, receiveData.startingAdress + 1, 1); } } @@ -1692,8 +1676,6 @@ private void WriteMultipleCoils(ModbusProtocol receiveData, ModbusProtocol sendD catch (Exception) { } if (CoilsChanged != null) CoilsChanged(receiveData.startingAdress+1, receiveData.quantity); - if (CoilsChangedWithServer != null) - CoilsChangedWithServer(this, receiveData.startingAdress + 1, receiveData.quantity); } } @@ -1818,8 +1800,6 @@ private void WriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtocol s catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAdress+1, receiveData.quantity); - if (HoldingRegistersChangedWithServer != null) - HoldingRegistersChangedWithServer(this, receiveData.startingAdress + 1, receiveData.quantity); } } @@ -1951,8 +1931,6 @@ private void ReadWriteMultipleRegisters(ModbusProtocol receiveData, ModbusProtoc catch (Exception) { } if (HoldingRegistersChanged != null) HoldingRegistersChanged(receiveData.startingAddressWrite+1, receiveData.quantityWrite); - if (HoldingRegistersChangedWithServer != null) - HoldingRegistersChangedWithServer(this, receiveData.startingAddressWrite + 1, receiveData.quantityWrite); } } From fb5998bc330590ce12710aaf3a9cd23814f98e22 Mon Sep 17 00:00:00 2001 From: Stefan Rossmann Date: Wed, 30 Dec 2020 19:43:20 +0100 Subject: [PATCH 024/114] Alpha Version of .NET5 integration and complete redesign --- ConsoleAppStd/ConsoleAppStd.csproj | 12 + ConsoleAppStd/Program.cs | 22 + .../ConsoleApplication1.csproj | 9 +- ConsoleApplication1/Program.cs | 58 -- EasyModbus.sln | 321 ++++------- ...yModbus.csproj => EasyModbus_Net40.csproj} | 0 EasyModbus/Properties/AssemblyInfo.cs | 2 +- EasyModbusStd/EasyModbus.StoreLogData.cs | 120 +++++ EasyModbusStd/EasyModbus_V5.0.csproj | 17 + EasyModbusStd/Exceptions/Exceptions.cs | 211 ++++++++ .../EasyModbus.ModbusClient.Core.cs | 330 ++++++++++++ .../EasyModbus.ModbusClient.Helpers.cs | 508 ++++++++++++++++++ .../EasyModbus.ModbusClient.Protocol.cs | 157 ++++++ README.md | 10 +- ServerApplication/ServerApplication.csproj | 6 - 15 files changed, 1485 insertions(+), 298 deletions(-) create mode 100644 ConsoleAppStd/ConsoleAppStd.csproj create mode 100644 ConsoleAppStd/Program.cs rename EasyModbus/{EasyModbus.csproj => EasyModbus_Net40.csproj} (100%) create mode 100644 EasyModbusStd/EasyModbus.StoreLogData.cs create mode 100644 EasyModbusStd/EasyModbus_V5.0.csproj create mode 100644 EasyModbusStd/Exceptions/Exceptions.cs create mode 100644 EasyModbusStd/ModbusClient/EasyModbus.ModbusClient.Core.cs create mode 100644 EasyModbusStd/ModbusClient/EasyModbus.ModbusClient.Helpers.cs create mode 100644 EasyModbusStd/ModbusClient/EasyModbus.ModbusClient.Protocol.cs diff --git a/ConsoleAppStd/ConsoleAppStd.csproj b/ConsoleAppStd/ConsoleAppStd.csproj new file mode 100644 index 0000000..2714a59 --- /dev/null +++ b/ConsoleAppStd/ConsoleAppStd.csproj @@ -0,0 +1,12 @@ + + + + Exe + net5.0 + + + + + + + diff --git a/ConsoleAppStd/Program.cs b/ConsoleAppStd/Program.cs new file mode 100644 index 0000000..423e386 --- /dev/null +++ b/ConsoleAppStd/Program.cs @@ -0,0 +1,22 @@ +using System; + +namespace ConsoleAppStd +{ + class Program + { + + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + + EasyModbus.ModbusClient modbusClient = new EasyModbus.ModbusClient(); + modbusClient.Connect("127.0.0.1", 502); + bool[] response = modbusClient.ReadDiscreteInputs(0, 2); + + modbusClient.Disconnect(); + Console.WriteLine("Value of Discrete Input #1: " + response[0].ToString()); + Console.WriteLine("Value of Discrete Input #2: " + response[1].ToString()); + Console.ReadKey(); + } + } +} diff --git a/ConsoleApplication1/ConsoleApplication1.csproj b/ConsoleApplication1/ConsoleApplication1.csproj index 186a0e3..93e21e3 100644 --- a/ConsoleApplication1/ConsoleApplication1.csproj +++ b/ConsoleApplication1/ConsoleApplication1.csproj @@ -33,9 +33,6 @@ 4 - - ..\packages\EasyModbusTCP.4.5.1\lib\EasyModbus.dll - @@ -53,6 +50,12 @@ + + + {723f8a8c-55aa-44ea-b595-db10dfd24e74} + EasyModbusStd + + - \ No newline at end of file diff --git a/ConsoleApplication1/Program.cs b/ConsoleApplication1/Program.cs deleted file mode 100644 index 9ced3ae..0000000 --- a/ConsoleApplication1/Program.cs +++ /dev/null @@ -1,22 +0,0 @@ - using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System; -using System.Net.Sockets; -using System.Net; -using System.IO.Ports; -using System.Reflection; -namespace ConsoleApplication1 -{ - class Program - { - static void Main(string[] args) - { - - Console.ReadKey(); - } - } -} - \ No newline at end of file diff --git a/ConsoleApplication1/Properties/AssemblyInfo.cs b/ConsoleApplication1/Properties/AssemblyInfo.cs deleted file mode 100644 index 97e457c..0000000 --- a/ConsoleApplication1/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("ConsoleApplication1")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ConsoleApplication1")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("aa208fa1-1496-4bbc-97d1-9f628eb4197a")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ConsoleApplication1/packages.config b/ConsoleApplication1/packages.config deleted file mode 100644 index 9b07e13..0000000 --- a/ConsoleApplication1/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/EasyModbusClient_IOTCoreExample/App.xaml b/EasyModbusClient_IOTCoreExample/App.xaml deleted file mode 100644 index 4ecb99a..0000000 --- a/EasyModbusClient_IOTCoreExample/App.xaml +++ /dev/null @@ -1,8 +0,0 @@ - - - diff --git a/EasyModbusClient_IOTCoreExample/App.xaml.cs b/EasyModbusClient_IOTCoreExample/App.xaml.cs deleted file mode 100644 index 506165f..0000000 --- a/EasyModbusClient_IOTCoreExample/App.xaml.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -namespace EasyModbusClient_IOTCoreExample -{ - /// - /// Stellt das anwendungsspezifische Verhalten bereit, um die Standardanwendungsklasse zu ergänzen. - /// - sealed partial class App : Application - { - /// - /// Initialisiert das Singletonanwendungsobjekt. Dies ist die erste Zeile von erstelltem Code - /// und daher das logische Äquivalent von main() bzw. WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Wird aufgerufen, wenn die Anwendung durch den Endbenutzer normal gestartet wird. Weitere Einstiegspunkte - /// werden z. B. verwendet, wenn die Anwendung gestartet wird, um eine bestimmte Datei zu öffnen. - /// - /// Details über Startanforderung und -prozess. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - Frame rootFrame = Window.Current.Content as Frame; - - // App-Initialisierung nicht wiederholen, wenn das Fenster bereits Inhalte enthält. - // Nur sicherstellen, dass das Fenster aktiv ist. - if (rootFrame == null) - { - // Frame erstellen, der als Navigationskontext fungiert und zum Parameter der ersten Seite navigieren - rootFrame = new Frame(); - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Zustand von zuvor angehaltener Anwendung laden - } - - // Den Frame im aktuellen Fenster platzieren - Window.Current.Content = rootFrame; - } - - if (e.PrelaunchActivated == false) - { - if (rootFrame.Content == null) - { - // Wenn der Navigationsstapel nicht wiederhergestellt wird, zur ersten Seite navigieren - // und die neue Seite konfigurieren, indem die erforderlichen Informationen als Navigationsparameter - // übergeben werden - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Sicherstellen, dass das aktuelle Fenster aktiv ist - Window.Current.Activate(); - } - } - - /// - /// Wird aufgerufen, wenn die Navigation auf eine bestimmte Seite fehlschlägt - /// - /// Der Rahmen, bei dem die Navigation fehlgeschlagen ist - /// Details über den Navigationsfehler - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Wird aufgerufen, wenn die Ausführung der Anwendung angehalten wird. Der Anwendungszustand wird gespeichert, - /// ohne zu wissen, ob die Anwendung beendet oder fortgesetzt wird und die Speicherinhalte dabei - /// unbeschädigt bleiben. - /// - /// Die Quelle der Anhalteanforderung. - /// Details zur Anhalteanforderung. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Anwendungszustand speichern und alle Hintergrundaktivitäten beenden - deferral.Complete(); - } - } -} diff --git a/EasyModbusClient_IOTCoreExample/Assets/LockScreenLogo.scale-200.png b/EasyModbusClient_IOTCoreExample/Assets/LockScreenLogo.scale-200.png deleted file mode 100644 index 735f57adb5dfc01886d137b4e493d7e97cf13af3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1430 zcmaJ>TTC2P7~aKltDttVHYH6u8Io4i*}3fO&d$gd*bA_<3j~&e7%8(eXJLfhS!M@! zKrliY>>6yT4+Kr95$!DoD(Qn-5TP|{V_KS`k~E6(LGS@#`v$hQo&^^BKsw3HIsZBT z_y6C2n`lK@apunKojRQ^(_P}Mgewt$(^BBKCTZ;*xa?J3wQ7~@S0lUvbcLeq1Bg4o zH-bvQi|wt~L7q$~a-gDFP!{&TQfc3fX*6=uHv* zT&1&U(-)L%Xp^djI2?~eBF2cxC@YOP$+9d?P&h?lPy-9M2UT9fg5jKm1t$m#iWE{M zIf%q9@;fyT?0UP>tcw-bLkz;s2LlKl2qeP0w zECS7Ate+Awk|KQ+DOk;fl}Xsy4o^CY=pwq%QAAKKl628_yNPsK>?A>%D8fQG6IgdJ ztnxttBz#NI_a@fk7SU`WtrpsfZsNs9^0(2a z@C3#YO3>k~w7?2hipBf{#b6`}Xw1hlG$yi?;1dDs7k~xDAw@jiI*+tc;t2Lflg&bM)0!Y;0_@=w%`LW^8DsYpS#-bLOklX9r?Ei}TScw|4DbpW%+7 zFgAI)f51s}{y-eWb|vrU-Ya!GuYKP)J7z#*V_k^Xo>4!1Yqj*m)x&0L^tg3GJbVAJ zJ-Pl$R=NAabouV=^z_t;^K*0AvFs!vYU>_<|I^#c?>>CR<(T?=%{;U=aI*SbZADLH z&(f2wz_Y0??Tf|g;?|1Znw6}6U43Q#qNRwv1vp9uFn1)V#*4p&%$mP9x&15^OaBiDS(XppT|z^>;B{PLVEbS3IFYV yGvCsSX*m diff --git a/EasyModbusClient_IOTCoreExample/Assets/SplashScreen.scale-200.png b/EasyModbusClient_IOTCoreExample/Assets/SplashScreen.scale-200.png deleted file mode 100644 index 023e7f1feda78d5100569825acedfd213a0d84e9..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 7700 zcmeHLYj~4Yw%(;oxoEH#Kxq-eR|+VkP17b#Vk;?4QwkI+A{L04G+#<<(x#Un1#+h5>eArRq zTw$)ZvTWW_Y?bDho0nPVTh08+s`sp!j74rJTTtXIDww0SILedFv?sZ?yb@@}GN;#8 znk_b~Q(A0YR#uV4ef!osoV1M3;vQ8N$O|fStfgf$S5;ddUNv`tWtGjM;koG#N;7M< zP*84lnx(bn_KF&9Z5Ai$)#Cs3a|$OFw>WKCT$of*L7_CqQEinflT|W{JT+aKp-E0v zsxmYg)1(T>DROm+LN1eQw8}KCTp=C!$H7`PU!t9_Hw@TsTI2`udRZv*!a5`#A9hK6Y95L(CDUX&_@QxKV z_feX{UhA#ZWlvgpL$#w^D#lq`_A4AzDqd|Zv6y9PX&DNcN|l}_D^{q@GG&H^Pg583 z8FI6N8^H7b5WjGp;urW)d7F+_lcp%KsLX0viCmE(OHH+=%ZfD_=`voUuoUxFO^L;- z;!;2{g-YiiO6m4bs89OuF9!p{FGtH-f%8<2gY!h9s)4ciN%{Kh1+`}{^}M~+TDH9N z^Z5PlgVXMC&2&k*Hw^Lb9gny#ro$MOIxIt{+r)EA10$VR3 zanN8D{TUkl+v0CQ_>ZoHP<M-x#8@8ZiT#$Kh`(uRaX1g$Bg|qy$<#7 zSSAi{Nb8Y=lvNVeio+UGLCAtoLBfL`iOv`)yoJMDJBN>4IH@(l7YRF;61@>qq1iM9 zr@b#OC~SAxSle?5Pp8Z78{VO0YFr1x7kZU64Z23eLf2T2#6J_t;-E}DkB?NufZ0Ug zi?J&byXeaB-uTNVhuiM!UVQw}bZrJ3GtAETYp->!{q#zfN7D3AS9@Q7*V^85jGx#R z(QxYV(wW#F0XF9^^s>>H8pPlVJ>)3Oz z&_X8Sf@~?cH_O*cgi$U#`v`RRfv#y3m(ZpKk^5uLup+lVs$~}FZU$r_+}#hl%?g5m z-u-}-666ssp-xWQak~>PPy$mRc|~?pVSs1_@mBEXpPVfLF6(Ktf1S* zPPh@QZ=tFMs?LM2(5P3L2;l_6XX6s&cYsP1ip#eg0`ZEP0HGYh{UmS@o`MihLLvkU zgyAG0G`b1|qjxxh1(ODKFE%AP}Dq=3vK$P7TXP4GrM1kQ72!GUVMDl`rDC&2;TA}*nF z8$nQD&6ys_nc1*E7$*1S@R8$ymy(sQV}imGSedB@{!QR5P&N_H=-^o!?LsWs+2|mH z-e=)T^SvI)=_JIm7}j4;@*Z17=(#}m=~YF~z~CLI+vdAGlJDcdF$TM?CVI1%LhUrN zaa6DJ=Yh$)$k&Oz{-~8yw^GM^8prYxSxo zvI4k#ibryMa%%*8oI-5m61Koa_A_xg=(fwp0aBX{;X4Q;NXUhtaoJDo1>TqhWtn=_ zd5~chq#&6~c%8JZK#t_&J(9EVUU&upYeIovLt1>vaHe}UUq>#RGQj!EN#5+0@T`(@ z^g~>*c`VGRiSt;!$_4+0hk^I!@O3``5=sZ8IwlxWW7km1B&_t&E*u0_9UBa#VqwY* zz>nxv?FAsVnRaD(Bui=6i==BFUw0k4n$>`umU`F2l?7CYTD^)c2X+d9X&ddS9|gj? zM?knGkGCX&W8offw8aLC2$D{PjC3nVZwd4k?eZH8*mZ)U@3Qk8RDFOz_#WUA#vnzy zyP>KrCfKwSXea7}jgJjBc}PGY+4#6%lbZyjhy`5sZd_Vy6Wz;ixa?czkN}J9It1K6 zY!eu>|AwF^fwZlLAYyQI*lM@^>O>Iu6Vf6i>Q$?v!SeUS<{>UYMwz$*%Aq?w^`j{h z!$GZbhu=^D{&ET8;))LL%ZBDZkQqRd2;u~!d9bHGmLRhLDctNgYyjsuvoSZ#iVdoB z2!f--UUA#U;<{je#?cYt^{PIyKa%hW>}uepWMyAI{{Zo7?2>?$c9;whJae%oN|I-kpTQSx_C$Z&;f zi2i)qmEn=y4U0uvk)$m;zKfjPK@oc?I`}1Jzl$Q~aoKBd3kt7L#7gyt|A_qgz6ai< z=X%D1i!d2h?rHR^R8SUj&G||dkC?DT>{o#Yau<@uqVT{Xef&XG}5*E4aPk{}~ zplx&XhaV)&1EfI3Em;Bw#O5SV^c;{twb-1Rw)+=0!e_BLbd7tYmXCH0wrlOSS+~`7He8Iqx0{CN+DVit9;*6L~JAN zD&cyT)2?h}xnYmL?^)<7YyzZ3$FHU^Eg;DLqAV{#wv#Wj7S`Jdl1pX&{3(uZ?!uh} zDc$ZTNV*7le_W6}Hju~GMTxZQ1aWCeUc%!jv3MHAzt>Y-nQK%zfT*3ebDQA5b?iGn; zBjv3B+GhLTexd_(CzZDP4|#n5^~scvB6#Pk%Ho!kQ>yYw((Dv{6=$g3jT1!u6gORW zx5#`7Wy-ZHRa~IxGHdrp(bm%lf>2%J660nj$fCqN(epv@y!l9s7@k6EvxS{AMP>WY zX4$@F8^kayphIx-RGO$+LYl9YdoI5d|4#q9##`_F5Xnx`&GPzp2fB{-{P@ATw=X@~ z_|&^UMWAKD;jjBKTK(~o?cUFRK8EX=6>cXpfzg4ZpMB>*w_^8GSiT-Jp|xBOnzM+j z*09-@-~qJ(eqWq5@R4i^u4^{McCP(!3}C|v_WsTR*bIUxN(Nx`u##3B4{sE`Z`v8w zAwIG`?1~PkID~W{uDzmqH98Pew_1(;x2%8r^vY{)_&J2K)cN{W+h5+g)ZcjP&Ci#O zgy|8K@4kyMfwilHd&6TDlhb%++Pk!>9HRld6HT7gwyZGrxS$}CsD6`>6!!2K1@Mjf z(P0WYB7V_OFZyeWrbOFb>O54BNXf~K&?}3=^v;v_wT{DKr?jN^DtN&DXwX%u?s*c6`%8>WFz z7}YW^tp0bp^NriE)AB6M2l<7rn7fzePtR*omOevpfm9n?}2V*+0iW;S)C zhg`NAjL?D=W#k*$aR{>pGf~lD-rVtD;5jW1_*Jn1j1=es@Kcx4ySM_bwcQCT=d+DV z>Sz~L=Hj@(X%31nK$mWI@7d>}ORB`K(p=+`UD)+99YUGQc7y^bHZ1F(8|tL0 zdK*DT0kSXG_{BKTpP2*2PecdKV9;dq$^ZZDP;Nyq1kp-&GI5eAyZsK!e3V zK@rPy*{(`KIfo+lc878mDKk^V#`VT05}64kBtk%DgwLrOvLMj5-;*GNKv6c6pzMuL z6EP%ob|_0IW}lLRXCP2!9wWhEw3LA7iF#1O1mIZ@Z=6&bz41F;@S_GvYAG-#CW3z{ zP3+6vHhvP&A3$##Vo9$dT^#MoGg^|MDm=Bt1d2RRwSZ<;ZHICpLBv5Xs!D?BH^(9_ z7`H=N&^v|Z-%mP}wNzG{aiFCsRgwzwq!N6obW9+7(R; z(SZ=23`|`>qil!LMGG{_Heq!BD>(Y-zV9wD)}hz25JA37YR%39;kI4y9pgtcUass6 zP24}ZY$vvYeI`zy&)A_X#nY3017ap*0&jx|mVwyGhg3;!keU53a}Uhm3BZI$N$6Se zLWlAmy1S0xKJm4G_U@sN_Tm=`$xWJSEwKU98rZ&)1R^*$$1vA3oG#&*%SMxY_~oGP zP&PFJatFLM-Ps%84IV-+Ow)T{C7cqUAvauy4C z(FRz&?6$Rypj{xO!`y=*J5o4@U8Q-(y5(*=YoKeZ+-1YdljXxkA#B)zo=FeQH#?Le zycNUmEEHWO9a=X^pb#&cOq7-`7UA87#|S22)<7RUtZo|(zibX=w;K3qur9vy#`MNV z6UUcf9ZwEnKCCp+OoBnF@OdbvH)ANXO0o~Pi9l8=x3))}L<#vO0-~O4!~--Ket?d} zJaqsj<@CD1%S2cTW%rOP{Vto%0sGW~1RMa_j^)5nil0Yw- z0EE#bP+l4#P^%PQ+N*oxu1Zq05xZ!bXfYTg>9c{(Iw*lnjR^>kz%lAN^zFce7rppy zY8zA~3GD=A6d*hze&l4D_wA~+O!56)BZTe_rEu}Ezi<4!kG|W#amBZ5{&XS2@6R~H z{9o^y*BkH4$~yX9U&@CgbOzX1bn9xqF|zh$Dh0Y5y*E0e90*$!ObrHY3Ok0`2=O~r zCuke6KrP9KOf?V(YDsM<6pX2nVoN%M$LT^q#FmtaF?1^27F*IcNX~XRB(|hCFvdcc zc)$=S-)acdk$g4?_>jRqxpI6M3vHZk?0c^3=byamYDNf;uB{3NlKW5IhnOS3DNkMV z?tK8?kJ}pmvp%&&eTVOVjHP`q34hN1@!aK}H(K!vI`~gf|Gv+FNEQD5Yd<~yX7k_l h&G-K)@HZb3BABY{)U1?^%I#E6`MGoTtustd{~yM6srvu` diff --git a/EasyModbusClient_IOTCoreExample/Assets/Square150x150Logo.scale-200.png b/EasyModbusClient_IOTCoreExample/Assets/Square150x150Logo.scale-200.png deleted file mode 100644 index af49fec1a5484db1d52a7f9b5ec90a27c7030186..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2937 zcma)84OCO-8BSud5)jwMLRVKgX(S?$n?Ld|vrsm<$CF7)&zTbyy1FE5bU`Q17MRv`9ue$;R(@8kR;#vJ*IM0>cJIAOte!d7oRgdH zd%ySjdB6L9=gX^A6)VzH7p2l@v~3zJAMw|DFy#^)F@@F*`mqUn=Il>l)8_+ab;nOW{%+iPx z+s{Eu|&pIs)Z7{La9~?xKfyl z#43?gjEL15d4WbOZo#SiP%>DB^+BcnJ=7dHEe;r#G=tuw|ka z%q@}##Uh7;tc%L_64m(kHtw74ty%BJMb)_1)#S0j`)F8_1jF7vScpsnH=0V19bO8y zR`0SjIdCUo&=>JwMQF8KHA<{ODHTiQh}0^@5QRmCA?gOH6_H3K^-_sNB^RrdNuK-R zOO*vOrKCVvDwgUck`kF(E7j{I#iiN;b*ZdCt4m@HPA`EuEqGGf4%!K<;(=I=&Vyrw z%TwcWtxa}8mCZ%Cyf&ActJ6_$ox5z6-D!0-dvnRx6t7y3d+h6QYpKWO;8OdnvERo7 zuEf>ih5`wqY)~o@OeVt-wM?Q!>QzdGRj!bz6fzYrfw$hZfAKzr2-M+D+R>}~oT574c;_3zquHcElqKIsryILt3g8n3jcMb+j?i?-L3FpZJ z2WRVBRdDPc+G5aaYg#5hpE+6nQ|(VSoxT3|biF;BUq#==-27Xi=gihDPYP$7?=9cP zYKE$jeQ|3~_L0VG-(F~2ZPyD0=k{J4Q~h(t__{-mz_w8{JDY9{`1ouzz!Vr5!ECdE z6U~O1k8c}24V7~zzXWTV-Pe4)y}wQJS&q%H5`Fo_f_JvIU489aCX$;P`u#!I-=^4ijC2{&9!O&h>mi?9oYD=GC#%)6{GzN6nQYw+Fal50!#x^asjBBR50i`+mho*ttoqV)ubM2KD9S~k7+FR4>{29?6 z{!l6kDdyTN0YJ9LgkPWeXm|gyi@zM3?0@{&pXT12w|78&W-q!RRF)&iLCEZVH<|fR zN0fr2^t8H(>L?>K#>^+jWROLral(Qy-xoBq1U7A&DV||wClb)Otd9?(gZ|8znMF}D zf<1haWz^s0qgecz;RFGt0C-B4g`jNGHsFU+;{<%t65v^sjk^h$lmWn#B0#_)9ij&d z-~lc`A)YYExi^7sBuPM^Y|wA2g*5?`K?#7tzELQYNxGo$UB$4J8RJp1k(8Jj+~hMT zlN~>M@KTTh^--8y3PK_NZ@AC!{PT=CziBzGd+wTJ^@icH!Bd}%)g8V)%K?|c&WTUk zy}qv1C%(fjRoZ4ozC3{O%@5?)XzH35zHns$pgU*Q?fj4v?fp1Qbm+j;3l;9jam9Da zXVcKjPlQ73x78QPu|Ffm6x?`~e3oD=gl=4kYK?={kD5j~QCXU)`HSdduNNENzA*2$ zOm3PzF!lN5e*06-f1Uot67wY#{o-S1!KZ7E=!~7ynnk9_iJR#kFoNbAOT#^2Gd17F zMmvU6>lndZQGd|ax9kUoXXO+$N?|j@6qpsF&_j7YXvwo_C{JpmLw5&#e6k>atv%es z5)7r*Wvv_JkUpT}M!_o!nVlEk1Zbl=a*2hQ*<|%*K1Glj^FcF`6kTzGQ3lz~2tCc@ z&x|tj;aH&1&9HwcJBcT`;{?a+pnej;M1HO(6Z{#J!cZA04hnFl;NXA+&`=7bjW_^o zfC40u3LMG?NdPtwGl>Tq6u}*QG)}-y;)lu-_>ee3kibW(69n0$0Zy!}9rQz%*v1iO zT9_H>99yIrSPYVy6^);rR}7Yo=J_T@hi+qhTZXnVWyf;JDYm5#eYLTxr*?kiNn!+Y zQ+LUkBafNJ#rH#C(?d5^;gw9o#%daEI{mA*LHPIHPU`#|H$hD zwm>0&+kahQ)E#%~k>&5@&#Vg82H?s%71=)(soi@174pi9--2{w{1$}Sz4zGn3Du&x bht0Iza^2ykEt4(epJ78uh5nDlX8(TxzDYwP diff --git a/EasyModbusClient_IOTCoreExample/Assets/Square44x44Logo.scale-200.png b/EasyModbusClient_IOTCoreExample/Assets/Square44x44Logo.scale-200.png deleted file mode 100644 index ce342a2ec8a61291ba76c54604aea7e9d20af11b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1647 zcmaJ?eM}Q)7(e+G1Q(|`V9JhTI2>MkceK4;p;PR&$Pi?ejk3YQ_3o`S&|W_dsOZ8# zWPTt69g`t$ab`0cj-Y0yiBSOqmd)tG7G(}M5aP0_%&9TijB#&)I{zSE^4@#z^FF`l z`8{8`o%wlL(UI|y2!cdsuVamHH~H86F!*-15em4)NqUpCQM5?aoC_eCf@lV4wvF2a zjDQn1JBL69f&@2M3rvzJcfE!eZ8FZUBlFlC5RD)it33{mF9#B82AiyQE%w)`vlwa> zv{<1sm&kSKK$&%2jSFn7$t&P%%6Ue>R=EAnG8N7fqynWG8L3p!4801a;8{+nliO(qd(jNJ_?+9W3#hLIDLoT6~3fx9=`CC-D}-AMrpEO7HK zt3$GicGPc?GmDjy7K2P@La;eu4!$zWCZ`ym{Z$b zu-O6RM&K4JT|BIZB`E-gxqG%FzanI#+2FFmqHqXG7yxWB=w55RGOM)$xMb(>kSNR z2w=1AZi%z=AmG~yea~XaXJR!v7vLn(RUnELfiB1|6D84ICOS}^Zo2AdN}<&*h}G_u z{xZ!(%>tLT3J3<5XhWy-tg+6)0nmUUENLW8TWA{R6bgVd3X;anYFZ^IRis*_P-C-r z;i>%1^eL3UI2-{w8nuFFcs0e~7J{O2k^~Ce%+Ly4U?|=!0LH=t6()xi<^I-rs+9sF z*q{E-CxZbGPeu#a;XJwE;9S1?#R&uns>^0G3p`hEUF*v`M?@h%T%J%RChmD|EVydq zmHWh*_=S%emRC*mhxaVLzT@>Z2SX0u9v*DIJ@WC^kLVdlGV6LpK$KIrlJqc zpJ921)+3JJdTx|<`G&kXpKkjGJv=76R`yYIQ{#c-`%+`#V(7}Q;&@6U8!Td1`d;?N z_9mnI#?AA}4J!r)LN4!E-@H5eXauuB7TOawS>Y|{-P?NNx-lq+z1W-+y(;39P&&LP zL{N80?&=C*qKmdA^moMZRuPcD!B<*mq$ch=0Cnlitw#txRWhb3%TQvPqjkC`F69G4b! ze7z9MZ#+;_#l?H37UqUhDFb^l&s2{oM$3I0o^Q!yx;;V)QmCMo)Tb_ui|mit8MS?U zm##6$sZZ1$@|s%?l@>4Z<*Q}sRBSKMhb4I{e5LdEhsHIHTe8Bod5c>6QtT>$XgUBz z6MK`kO$=jmt@FqggOhJ5j~e@ygRbG;<{Vu)*+nn9aQeo0;$#j;|MS=S$&L?BeV25z xs3B`@=#`5TF{^6(A1rvdY@|-RtQ|iS5{tyX+wH?;n8E)G$kykv-D^wh{{!TZT%7;_ diff --git a/EasyModbusClient_IOTCoreExample/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/EasyModbusClient_IOTCoreExample/Assets/Square44x44Logo.targetsize-24_altform-unplated.png deleted file mode 100644 index f6c02ce97e0a802b85f6021e822c89f8bf57d5cd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1255 zcmaJ>TWs4@7*5+{G#S+&C!qC#> zf>5N3P6jO*Cz>ug*(_DmW=)kea&m$gZ^+nyiF`;j%w@}y8)>p*SH}C`m?DXeieF2U zyQHecc_L%Gh!7GMt+hG06y;+|p4>m~}PjA}rKViGiEnn7G0ZO<>G|7q;2?NwGCM3s?eued6%hd$B+ z*kQJ{#~$S=DFE(%=E+UkmlEI*%3llUf~8Ja9YU1Vui0IbGBkW_gHB%Rd&!!ioX zs40O?i9I{};kle7GMvE7(rk`la=gTI)47=>%?q@^iL-nUo3}h4S}N-KHn8t5mVP8w z&bSErwp+37 zNJJ8?a|{r5Q3R0Z5s-LB1WHOwYC@7pCHWND#cL1cZ?{kJ368_*(UDWUDyb<}0y@o# zfMF016iMWPCb6obAxT$JlB6(2DrlXDTB&!0`!m??4F(qWMhjVZo?JXQmz`1*58Z=& zcDmB|S-E@j?BoFGix0flckqdS4jsPNzhfWyWIM98GxcLs89C(~dw%$_t;JjX-SD}E zfiGV;{8Q%8r}w9x>EEigW81>`kvnU@pK)4+xk9@+bNj9L!AAZ@SZ@q|)&BmY3+HZx zul~BeG4|}-;L%cHViQGQX?^zFfO0&#cHwel=d`lH9sJ-@Sl@n*(8J2>%Ac`IxyY?Q z{=GhWvC#gu-~Ia7*n{=+;qM?Ul_wy1+u7ho;=`>EwP^g~R@{unBds`!#@}tluZQpS zm)M~nYEifJWJGx?_6DcTy>#uh%>!H9=hb^(v`=m3F1{L>db=<5_tm+_&knAQ2EU$s Mu9UqpbNZeC0BbUo^Z)<= diff --git a/EasyModbusClient_IOTCoreExample/Assets/StoreLogo.png b/EasyModbusClient_IOTCoreExample/Assets/StoreLogo.png deleted file mode 100644 index 7385b56c0e4d3c6b0efe3324aa1194157d837826..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1451 zcmaJ>eN5D57_Z|bH;{0+1#mbl)eTU3{h)Wf7EZV?;HD@XL@{B`Ui%(2aMxQ~xdXSv z5nzWi(LW)U2=Vc-cY@s7nPt{i0hc6!7xN4NNHI#EQl>YNBy8l4%x9gr_W-j zEZMQmmTIy(>;lblRfh`dIyTgc9W5d!VP$L4(kKrN1c5G~(O_#xG zAJCNTstD^5SeXFB+&$h=ToJP2H>xr$iqPs-#O*;4(!Fjw25-!gEb*)mU}=)J;Iu>w zxK(5XoD0wrPSKQ~rbL^Cw6O_03*l*}i=ydbu7adJ6y;%@tjFeXIXT+ms30pmbOP%Q zX}S;+LBh8Tea~TSkHzvX6$rYb)+n&{kSbIqh|c7hmlxmwSiq5iVhU#iEQ<>a18|O^Sln-8t&+t`*{qBWo5M?wFM(JuimAOb5!K#D}XbslM@#1ZVz_;!9U zpfEpLAOz=0g@bd6Xj_ILi-x^!M}73h^o@}hM$1jflTs|Yuj9AL@A3<-?MV4!^4q`e z)fO@A;{9K^?W?DbnesnPr6kK>$zaKo&;FhFd(GYFCIU^T+OIMb%Tqo+P%oq(IdX7S zf6+HLO?7o0m+p>~Tp5UrXWh!UH!wZ5kv!E`_w)PTpI(#Iw{AS`gH4^b(bm^ZCq^FZ zY9DD7bH}rq9mg88+KgA$Zp!iWncuU2n1AuIa@=sWvUR-s`Qb{R*kk(SPU^`$6BXz8 zn#7yaFOIK%qGxyi`dYtm#&qqox0$h=pNi#u=M8zUG@bpiZ=3sT=1}Trr}39cC)H|v zbL?W)=&s4zrh)7>L(|cc%$1#!zfL?HjpeP%T+x_a+jZ16b^iKOHxFEX$7d|8${H-* zIrOJ5w&i$>*D>AKaIoYg`;{L@jM((Kt?$N$5OnuPqVvq**Nm}(f0wwOF%iX_Pba;V z;m@wxX&NcV3?<1+u?A{y_DIj7#m3Af1rCE)o`D&Y3}0%7E;iX1yMDiS)sh0wKi!36 zL!Wmq?P^Ku&rK~HJd97KkLTRl>ScGFYZNlYytWnhmuu|)L&ND8_PmkayQb{HOY640 bno1(wj@u8DCVuFR|31B*4ek@pZJqxCDDe1x diff --git a/EasyModbusClient_IOTCoreExample/Assets/Wide310x150Logo.scale-200.png b/EasyModbusClient_IOTCoreExample/Assets/Wide310x150Logo.scale-200.png deleted file mode 100644 index 288995b397fdbef1fb7e85afd71445d5de1952c5..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3204 zcmbVPeQXow8NYmBd90>}0NP?GhXW~VaeThm=a0tV#EwJMI!)6M3}|c4_Bl3=Kd>G0 z(GHx1wl<7(tP?FsOQkTilSo*iIvF%uArExJ73~P zSv1xEy!U(Wd4A9D`FQV@W3@F^qJ@PEF$@z`Z!*BbFsS(^?B zyiAzJ+q})bkgiQHWqEb*jJD-coHYr1^iocg)l!Qa{Xqs-l~6J}p-|##ZHYofskQ3$ zI0;xzXyhazBeXhIsg5A=%ufo@f)1yy&ScKS0;HF^!r_2UE^lpZEom(+@duma3awTv zCrCL-%D_SvYWIcdHkmI}#50(fkUi)Qgx!80ju>g1za^}ff>JI8Z@^-iCiaCgg@TgF z+vtE?Q9{VQUX&MW9SYYmGcxA14%N2@7FwBTD4N<(2{nWgV8$e3?-F=L^&FrtWn~(U_Q~~^uYiyeY6-KoTnfh9AWz@ zIKje0)u!_Lw)E}G!#kEfwKVdNt(UAf9*f>tEL_(=xco-T%jTi@7YlC3hs2ik%Le0H ztj}RTeCF(5mwvi3_56>-yB?l;J>-1%!9~=fs|QcNG3J~a@JCu`4SB460s0ZO+##4fFUSGLcj_ja^fL4&BKALfb#$6$O?>P@qx2Agl^x0i&ugt zsy5Pyu=()`7HRMG3IB7F1@`_ z+-!J%#i6e^U$e#+C%Q>_qVRzWRsG^W_n+@OcX@vzI&z;mzHNb!GQ?LWA(wtpqHqTM z1OFw_{Zn?fD)p)`c`kOgv{de=v@suGRqY{N^U7gI1VF3*F=obwaXI6ob5__Yn zVTguS!%(NI09J8x#AO_aW!9W7k*UvB;IWDFC3srwftr{kHj%g)fvnAm;&h_dnl~

MY- zf+K}sCe8qU6Ujs`3ua{U0Of$R_gVQBuUA za0v=mu#vIOqiiAZOr&h*$WyOw&k-xr$;G4Ixa!#TJNr>95(h>l%)PUy4p+^SgR(uR zta%k*?ny-+nAr8spEk1fo{J4i!b^Fia`N{_F6@zidA2ZTTrjl#^5Z-2KfB@Cu}l9s z(*|Z2jc?p~vn2f)3y9i*7zJV1L{$?|&q)4oaT;uXi6>1GkRXVTOzAz(RHEmr=eFIi z`}<>-Q?K0GN8!IYxeP1XKXO+jsJbp~o^);Bc;%b7Flpe7;1`Ny@3r7ZR;?R)aJt8C ziNlEC<@3f_lIV4TwV}&e;D!Ee5_|e#g0LUh=5vmYWYm7&2h*M>QPKvGh9-)wfMMW3 z8J9b%1k7dzPzO0_NGQy92BZ^FR6R~6;^6?lqO;-QUP4BY%cG%3vEhbm#>4vIhPBh3 z-+pZGjh$x%Hp{?=FHsMp0&wNPlj00us{&`1ZOZTqs8%4X&xH=UDr*xyBW(Zp&Em94 zf)ZSfn#yg0N)>!1kWdkqJ^S*z0FF5|fj&qcE#Na|%OY0$uO>!&hP+1ywfD_WXk@4J(?MBftK7>$Nvqh@tDuarN%PrTLQ2Uzysx>UV=V zk^RrDSvdQ?0;=hY67EgII-f4`t=+i*yS=Y~!XlqIy_4x&%+OdfbKOFPXS2X5%4R{N z$SQMX^AK6(fA - - - - Debug - x86 - {9AC81F46-F110-46F3-B884-6665D8A05267} - AppContainerExe - Properties - EasyModbusClient_IOTCoreExample - EasyModbusClient_IOTCoreExample - de-DE - UAP - 10.0.16299.0 - 10.0.16299.0 - 14 - 512 - {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - true - EasyModbusClient_IOTCoreExample_TemporaryKey.pfx - - - true - bin\x86\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x86 - false - prompt - true - - - bin\x86\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x86 - false - prompt - true - true - - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - ARM - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - ARM - false - prompt - true - true - - - true - bin\x64\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - ;2008 - full - x64 - false - prompt - true - - - bin\x64\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - true - ;2008 - pdbonly - x64 - false - prompt - true - true - - - PackageReference - - - - App.xaml - - - MainPage.xaml - - - - - - Designer - - - - - - - - - - - - - - - MSBuild:Compile - Designer - - - MSBuild:Compile - Designer - - - - - 5.4.0 - - - 1.0.0 - - - - - Windows Desktop Extensions for the UWP - - - Windows IoT Extensions for the UWP - - - - - - - 14.0 - - - - \ No newline at end of file diff --git a/EasyModbusClient_IOTCoreExample/MainPage.xaml b/EasyModbusClient_IOTCoreExample/MainPage.xaml deleted file mode 100644 index a246428..0000000 --- a/EasyModbusClient_IOTCoreExample/MainPage.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - -