/// <inheritdoc cref="IGXPacketHandler.ExecuteSendCommand"/>
        public void ExecuteSendCommand(object sender, string command, Gurux.Communication.GXPacket packet)
        {
            ulong id = 0;
            if (command == "ReadData")
            {
                GXDLT645Property prop = sender as GXDLT645Property;
                id = prop.DataID;                
            }
            else if (command == "ReadTableRowsCount")
            {				
                if (m_Items == null)
                {
                    m_Items = GXDLT645Property.ReadDataID();
                }
                RowIndex = RowCount = 0;                
                GXDLT645Table table = sender as GXDLT645Table;
				table.ClearRows();
                id = table.DataID;
            }
            else if (command == "ReadTable" || command == "ReadTableNext")
            {                
                GXDLT645Table table = sender as GXDLT645Table;
                ++RowIndex;
                id = table.DataID + RowIndex;
            }
            else
            {
                throw new Exception("ExecuteCommand failed. Unknown command: " + command);
            }
            packet.AppendData(Device.Parser.ReadValue(id));
        }
        /// <inheritdoc cref="IGXPacketHandler.ExecuteParseCommand"/>
		public void ExecuteParseCommand(object sender, string command, Gurux.Communication.GXPacket[] packets)
		{            
            if (command == "ReadDataReply")
            {
                GXDLT645Property prop = sender as GXDLT645Property;
                byte[] data = (byte[])packets[0].ExtractData(typeof(byte[]), 0, -1);
                prop.SetValue(Device.Parser.GetValue(prop.DataID, data, typeof(byte[])), false, PropertyStates.ValueChangedByDevice);                
            }
            else if (command == "ReadTableRowsCountReply")
            {
                GXDLT645Table table = sender as GXDLT645Table;
                byte[] data = (byte[])packets[0].ExtractData(typeof(byte[]), 0, -1);
                data = (byte[])Device.Parser.GetValue(table.DataID, data, typeof(byte[]));
                for (int pos = 0; pos != data.Length; ++pos)
                {
                    byte val = (byte)data[pos];
                    RowCount += (ulong)(val << (8 * pos));                    
                }
            }
            else if (command == "UpdateTable")
            {
                //Rows are already updated.                
            }                
            else
            {
                throw new Exception("ExecuteParseCommand failed. Unknown command: " + command);
            }			
		}
Exemple #3
0
 /// <summary>
 /// Clear states when media is closed.
 /// </summary>
 void GXSerial1_OnMediaStateChange(object sender, Gurux.Common.MediaStateEventArgs e)
 {
     if (e.State == Gurux.Common.MediaState.Closing)
     {
         BreakLed.BackColor = RingLed.BackColor = RingLed.BackColor = RingLed.BackColor = RingLed.BackColor = System.Drawing.Color.Transparent;
     }                    
 }
 /// <summary>
 /// Check are Device ID's same.
 /// </summary>
 /// <param name="send"></param>
 /// <param name="received"></param>
 /// <returns></returns>
 public void IsReplyPacket(object sender, Gurux.Communication.GXReplyPacketEventArgs e)
 {      
     //Get address from data            
     GXClient client = sender as GXClient;
     if (client.MediaType == "Net")
     {
         object SendPackID = e.Send.ExtractData(typeof(System.UInt16), 0, 1);
         object ReceivePackID = e.Received.ExtractData(typeof(System.UInt16), 0, 1);
         e.Accept = SendPackID.Equals(ReceivePackID);
         //Remove all data until function code so parsed data looks same as using serial port connection.
         if (e.Accept)
         {
             e.Received.RemoveData(0, 7);
         }
     }
     else
     {
         object SendSlaveAdd, ReceiveSlaveAdd;
         byte SendFunc, ReceiveFunc;
         SendSlaveAdd = e.Send.Bop;
         ReceiveSlaveAdd = e.Received.Bop;
         //Get function from data
         SendFunc = (byte) e.Send.ExtractData(typeof(System.Byte), 0, 1);
         ReceiveFunc = (byte) e.Received.ExtractData(typeof(System.Byte), 0, 1);
         //If meter notifies error.
         if ((ReceiveFunc & 0x80) != 0 && (ReceiveFunc & 0x7F) == SendFunc)
         {
             throw new Exception("Unexpected response received.");
         }
         //Are Slave Address and functions same...
         e.Accept = SendSlaveAdd.Equals(ReceiveSlaveAdd) && SendFunc.Equals(ReceiveFunc);
     }
 }
 public OBISCodesForm(GXManufacturerCollection manufacturers, string selectedManufacturer, Gurux.DLMS.ObjectType Interface, string ln)
 {
     InitializeComponent();
     ManufacturersList_SizeChanged(null, null);
     NewBtn.Enabled = manufacturers.Count != 0;
     EditBtn.Enabled = RemoveBtn.Enabled = false;
     bool bSelected = false;
     //Add manufacturers
     foreach (GXManufacturer it in manufacturers)
     {
         if (!it.Removed)
         {
             ListViewItem item = AddManufacturer(it);
             if (it.Identification == selectedManufacturer)
             {
                 bSelected = item.Selected = true;
             }
         }
     }
     //Select first item
     if (!bSelected && ManufacturersList.Items.Count != 0)
     {
         ManufacturersList.Items[0].Selected = true;
     }
     //Add OBIS Codes.
     ManufacturersList_SelectedIndexChanged(null, null);
     //Select OBIS code by Logical name.
     if (ManufacturersList.SelectedItems.Count == 1)
     {
         ShowOBISCOdes(((GXManufacturer)ManufacturersList.SelectedItems[0].Tag).ObisCodes, Interface, ln);
     }
     this.ManufacturersList.SelectedIndexChanged += new System.EventHandler(this.ManufacturersList_SelectedIndexChanged);
 }
        public static void SetChar(Gurux.Serial.GXSerial port, string name, byte value)
        {
            if (port == null)
            {
                throw new NullReferenceException();
            }
            if (port.BaseStream == null)
            {
                throw new InvalidOperationException("Cannot change X chars until after the port has been opened.");
            }

            try
            {
                // Get the base stream and its type which is System.IO.Ports.SerialStream
                object baseStream = port.BaseStream;
                Type baseStreamType = baseStream.GetType();

                // Get the Win32 file handle for the port
                SafeFileHandle portFileHandle = (SafeFileHandle)baseStreamType.GetField("_handle", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(baseStream);

                // Get the value of the private DCB field (a value type)
                FieldInfo dcbFieldInfo = baseStreamType.GetField("dcb", BindingFlags.NonPublic | BindingFlags.Instance);
                object dcbValue = dcbFieldInfo.GetValue(baseStream);

                // The type of dcb is Microsoft.Win32.UnsafeNativeMethods.DCB which is an internal type. We can only access it through reflection.
                Type dcbType = dcbValue.GetType();
                dcbType.GetField(name).SetValue(dcbValue, value);

                // We need to call SetCommState but because dcbValue is a private type, we don't have enough
                //  information to create a p/Invoke declaration for it. We have to do the marshalling manually.

                // Create unmanaged memory to copy DCB into
                IntPtr hGlobal = Marshal.AllocHGlobal(Marshal.SizeOf(dcbValue));
                try
                {
                    // Copy their DCB value to unmanaged memory
                    Marshal.StructureToPtr(dcbValue, hGlobal, false);

                    // Call SetCommState
                    if (!SetCommState(portFileHandle, hGlobal))
                        throw new Win32Exception(Marshal.GetLastWin32Error());

                    // Update the BaseStream.dcb field if SetCommState succeeded
                    dcbFieldInfo.SetValue(baseStream, dcbValue);
                }
                finally
                {
                    if (hGlobal != IntPtr.Zero)
                        Marshal.FreeHGlobal(hGlobal);
                }
            }
            catch (System.Security.SecurityException) { throw; }
            catch (OutOfMemoryException) { throw; }
            catch (Win32Exception) { throw; }
            catch (Exception ex)
            {
                throw new ApplicationException("SetXonXoffChars has failed due to incorrect assumptions about System.IO.Ports.SerialStream which is an internal type.", ex);
            }
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXCommunicatation(Gurux.DLMS.GXDLMS dlms, IGXMedia media, bool initializeIEC, Gurux.DLMS.Authentication authentication, string password)
 {
     m_Parser = dlms;
     Media = media;
     InitializeIEC = initializeIEC;
     m_Parser.Authentication = authentication;
     m_Parser.Password = password;
 }
 /// <summary>
 /// Count Checksum for ASCII.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public void CountChecksum(object sender, Gurux.Communication.GXChecksumEventArgs e)
 {
     byte[] data = e.Packet.ExtractPacket();
     int crc = 0;
     int value;            
     for (int pos = 1; pos != data.Length - 2; pos += 2)
     {
         value = Convert.ToInt32(ASCIIEncoding.ASCII.GetString(data, pos, 2), 16);
         crc = (crc + value) & 0xFF;
     }
     e.Checksum = ModbusPacketHandler.GetValue((byte)-crc, true); 
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXCommunicatation(Gurux.DLMS.GXDLMSClient dlms, IGXMedia media, bool initializeIEC, Gurux.DLMS.Authentication authentication, string password)
 {
     Client = dlms;
     Media = media;
     InitializeIEC = initializeIEC;
     Client.Authentication = authentication;
     Client.Password = ASCIIEncoding.ASCII.GetBytes(password);
     //Delete trace file if exists.
     if (File.Exists("trace.txt"))
     {
         File.Delete("trace.txt");
     }
 }
 public void BeforeSend(object sender, Gurux.Communication.GXPacket packet)
 {
     GXClient client = sender as GXClient;
     if (client.MediaType == "Net")
     {
         if (++PacketID == UInt16.MaxValue)
         {
             PacketID = 1;
         }
         //The Unit Identifier
         packet.InsertData((byte)((GXModbusDevice)client.Owner).Address, 0, 0, 0);
         //Count data size and update it to the packet before send.
         int PackSize = packet.GetSize(PacketParts.Data);
         packet.InsertData((UInt16)PackSize, 0, 0, 0);
         //Protocol ID. (Always 0x0)
         packet.InsertData((UInt16)0, 0, 0, 0); 
         //PacketID
         packet.InsertData(PacketID, 0, 0, 0); 
     }
 }
 public void ExecuteSendCommand(object sender, string command, Gurux.Communication.GXPacket packet)
 {
     GXModbusProperty prop = sender as GXModbusProperty;
     bool ascii = (prop.Device as GXModbusDevice).Ascii;
     UInt16 address = prop.Address;
     byte functionCode = (byte)prop.Function;
     if (command == "ModbusRead")
     {
         packet.AppendData(GetValue(functionCode, ascii));
         packet.AppendData(GetValue(address, ascii));
         packet.AppendData(GetValue((UInt16)1, ascii));
     }
     else if (command == "ModbusWrite")
     {
         switch (functionCode)
         {
             case 1:
                 functionCode = 5;
                 break;
             case 3:
                 functionCode = 6;
                 break;
         }
         WriteFailed = false;
         packet.AppendData(GetValue(functionCode, ascii));
         packet.AppendData(GetValue(address, ascii));
         object value = GetWriteData(prop, functionCode);
         packet.AppendData(GetValue(value, ascii));
     }
     //Read value type if write failed.
     else if (command == "ModbusFailedWrite")
     {
         if (WriteFailed)
         {
             packet.AppendData(GetValue(functionCode, ascii));
             packet.AppendData(GetValue(address, ascii));
             packet.AppendData(GetValue((UInt16)1, ascii));
         }
     }
 }
        /// <summary>
        /// GXServer class factory.
        /// </summary>
        public static GXServer Instance(Gurux.Common.IGXMedia media, GXClient client)
        {
            lock (m_syncRoot)
            {                
                if (m_instances == null)
                {
                    m_instances = new Dictionary<string, GXServer>();
                    Handlers = new Dictionary<IGXEventHandler, object>();
                }
                string name = media.Name;
                if (string.IsNullOrEmpty(name))
                {
                    name = media.MediaType;
                }
                GXServer server;
                if (m_instances.ContainsKey(name))
                {
                    server = m_instances[name];
                    if (server.m_bParseReceivedPacket != client.ParseReceivedPacket)
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientParseReceivedPacketValueIsInvalid);
                    }
					if (!object.Equals(server.m_ReplyPacket.Eop, client.Eop))
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientEopValueIsInvalid);
                    }
                    if (!object.Equals(server.m_ReplyPacket.Bop, client.Bop))
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientBopValueIsInvalid);
                    }
                    if (server.m_ReplyPacket.ByteOrder != client.ByteOrder)
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientByteOrdersAreNotSame);
                    }
                    if (server.m_ReplyPacket.MinimumSize != client.MinimumSize)
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientMinimumSizeValueIsInvalid);
                    }
                    if (!server.m_ReplyPacket.ChecksumSettings.Equals(client.ChecksumSettings))
                    {
                        throw new Exception(Resources.ServerFailedToAcceptNewClientChecksumSettingsAreNotSame);
                    }                    
                    lock (server.Clients.SyncRoot)
                    {
                        server.Clients.Add(client);
                    }
                    return server;
                }                
                server = new GXServer(name);
                server.m_ReplyPacket = client.CreatePacket();
                lock (server.Clients.SyncRoot)
                {
                    server.Clients.Add(client);
                }
                server.m_bParseReceivedPacket = client.ParseReceivedPacket;
                media.OnClientDisconnected += new Gurux.Common.ClientDisconnectedEventHandler(server.OnClientDisconnected);
                media.OnClientConnected += new Gurux.Common.ClientConnectedEventHandler(server.OnClientConnected);
                media.OnError += new Gurux.Common.ErrorEventHandler(server.OnError);
                media.OnMediaStateChange += new Gurux.Common.MediaStateChangeEventHandler(server.OnMediaStateChange);
                media.OnReceived += new Gurux.Common.ReceivedEventHandler(server.OnReceived);
                server.m_Media = media;
                m_instances[name] = server;
                server.m_Sender = new GXServerSender(server);
                server.m_Receiver = new GXServerReceiver(server);                
                server.m_SendThread = new Thread(new ThreadStart(server.m_Sender.Run));
                server.m_SendThread.IsBackground = true;
                server.m_SendThread.Start();
                server.m_ReceiverThread = new Thread(new ThreadStart(server.m_Receiver.Run));
                server.m_ReceiverThread.IsBackground = true;
                server.m_ReceiverThread.Start();
                return server;
            }
        }
 public override void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media)
 {
     GXIEC62056Device dev = (GXIEC62056Device)device;
     ImportSelectionDlg dlg = addinPages[1] as ImportSelectionDlg;
     string deviceSerialNumber = dlg.DeviceSerialNumber;
     int waittime = dev.WaitTime;
     media.Open();
     try
     {
         string data = "/?" + deviceSerialNumber + "!\r\n";
         byte[] reply = IEC62056Parser.Identify(media, data, '\0', waittime);
         if (reply[0] != '/')
         {
             throw new Exception("Invalid reply.");
         }
         char baudRate = (char)reply[4];
         string CModeBauds = "0123456789";
         string BModeBauds = "ABCDEFGHI";
         Protocol mode;
         if (CModeBauds.IndexOf(baudRate) != -1)
         {
             mode = Protocol.ModeC;
         }
         else if (BModeBauds.IndexOf(baudRate) != -1)
         {
             mode = Protocol.ModeB;
         }
         else
         {
             mode = Protocol.ModeA;
             baudRate = '0';
         }
         if (reply[0] != '/')
         {
             throw new Exception("Import failed. Invalid reply.");
         }
         //If mode is not given.
         if (dev.Mode == Protocol.None)
         {
             dev.Mode = mode;
         }
         data = ASCIIEncoding.ASCII.GetString(reply.ToArray());                
         string manufacturer = new string(new char[] { (char)reply[1], (char)reply[2], (char)reply[3] });
         if (dev.Mode == Protocol.ModeA)
         {
             data = (char)0x06 + "0" + baudRate + "0\r\n";
         }
         else
         {
             data = (char)0x06 + "0" + baudRate + "1\r\n";
         }
         //Note this sleep is in standard. Do not remove.
         if (media.MediaType == "Serial")
         {
             System.Threading.Thread.Sleep(200);
         }
         reply = IEC62056Parser.ParseHandshake(media, data, baudRate, waittime);
         string header, frame;                
         IEC62056Parser.GetPacket(new List<byte>(reply), true, out header, out frame);
         System.Diagnostics.Debug.WriteLine(frame);
         if (header == "B0")
         {
             throw new Exception("Connection failed. Meter do not accept connection at the moment.");
         }
         //Password is asked.
         if (header == "P0")
         {
             System.Diagnostics.Debug.WriteLine("Password is asked.");
         }
         //Note this sleep is in standard. Do not remove.
         if (media.MediaType == "Serial")
         {
             System.Threading.Thread.Sleep(200);
         }
         if (dev.Mode == Protocol.ModeA)
         {
             GXCategory defaultCategory = new GXIEC62056ReadoutCategory();
             defaultCategory.Name = "Readout";
             device.Categories.Add(defaultCategory);
         }
         else
         {
             GXCategory defaultCategory = null;
             defaultCategory = new GXIEC62056Category();
             defaultCategory.Name = "Properties";
             device.Categories.Add(defaultCategory);
             foreach (string it in IEC62056Parser.GetGeneralOBISCodes())
             {
                 try
                 {
                     //Note this sleep is in standard. Do not remove.
                     if (media is Gurux.Serial.GXSerial)
                     {
                         System.Threading.Thread.Sleep(200);
                     }
                     if (!it.StartsWith("P."))
                     {
                         string value = IEC62056Parser.ReadValue(media, waittime, it + "()", 2);
                         if (!Convert.ToString(value).StartsWith("ER"))
                         {
                             GXIEC62056Property prop = new GXIEC62056Property();
                             prop.AccessMode = AccessMode.Read;
                             prop.ReadMode = dev.ReadMode;
                             prop.WriteMode = dev.WriteMode;
                             prop.Name = IEC62056Parser.GetDescription(it);
                             prop.Data = it;
                             prop.DataType = IEC62056Parser.GetDataType(it);
                             if (prop.DataType == DataType.DateTime ||
                                 prop.DataType == DataType.Date ||
                                 prop.DataType == DataType.Time)
                             {
                                 prop.ValueType = typeof(DateTime);
                             }
                             defaultCategory.Properties.Add(prop);
                             TraceLine("Property " + prop.Name + " added.");
                         }
                     }
                     else
                     {
                         object[][] rows;
                         //Try to read last hour first.
                         TimeSpan add = new TimeSpan(1, 0, 0);
                         DateTime start = DateTime.Now.Add(-add);
                         string[] columns = null;
                         do
                         {
                             try
                             {
                                 rows = IEC62056Parser.ReadTable(media, waittime, it, start, DateTime.Now, null, 5, 1, out columns);
                             }
                             catch
                             {
                                 //If media is closed.
                                 if (!media.IsOpen)
                                 {
                                     break;
                                 }
                                 rows = new object[0][];
                             }
                             if (rows.Length == 0)
                             {
                                 if (add.TotalHours == 1)
                                 {
                                     //Try to read last day.
                                     add = new TimeSpan(1, 0, 0, 0);
                                     start = DateTime.Now.Add(-add).Date;
                                 }
                                 else if (add.TotalHours == 24)
                                 {
                                     //Try to read last week.
                                     add = new TimeSpan(7, 0, 0, 0);
                                     start = DateTime.Now.Add(-add).Date;
                                 }
                                 else if (add.TotalDays == 7)
                                 {
                                     //Try to read last month.
                                     add = new TimeSpan(31, 0, 0, 0);
                                     start = DateTime.Now.Add(-add).Date;
                                 }
                                 else if (add.TotalDays == 31)
                                 {
                                     //Read all.
                                     add = new TimeSpan(100, 0, 0, 0);
                                     start = DateTime.MinValue;                                            
                                 }
                                 else
                                 {
                                     break;
                                 }
                                 //Note this sleep is in standard. Do not remove.
                                 if (media is Gurux.Serial.GXSerial)
                                 {
                                     System.Threading.Thread.Sleep(200);
                                 }
                             }
                             else
                             {
                                 GXIEC62056Table table = new GXIEC62056Table();
                                 table.Name = IEC62056Parser.GetDescription(it);
                                 table.AccessMode = AccessMode.Read;
                                 table.Data = it;
                                 table.ReadMode = 6;
                                 int index = -1;
                                 foreach (string col in columns)
                                 {
                                     GXIEC62056Property prop = new GXIEC62056Property();
                                     prop.Name = col;
                                     //Mikko prop.Name = IEC62056Parser.GetDescription(col);
                                     prop.Data = col;
                                     prop.ValueType = rows[0][++index].GetType();
                                     table.Columns.Add(prop);
                                 }
                                 device.Tables.Add(table);
                                 TraceLine("Property " + table.Name + " added.");
                                 break;
                             }
                         }
                         while (rows.Length == 0);
                     }
                 }
                 catch (Exception ex)
                 {
                     System.Diagnostics.Debug.WriteLine(ex.Message);                            
                 }
             }
         }
     }
     finally
     {
         if (media.MediaType == "Serial" || media.MediaType == "Terminal")
         {
            IEC62056Parser.Disconnect(media, 2);
         }
         media.Close();
     }            
 }
        void ShowOBISCOdes(GXObisCodeCollection collection, Gurux.DLMS.ObjectType Interface, string selectedLN)
        {
            Items.Clear();
            this.OBISCodesList.Items.Clear();
            if (collection != null)
            {
                List<KeyValuePair<string, GXObisCode>> list = new List<KeyValuePair<string, GXObisCode>>();
                foreach (GXObisCode it in collection)
                {
                    if (!string.IsNullOrEmpty(it.LogicalName))
                    {
                        list.Add(new KeyValuePair<string, GXObisCode>(it.LogicalName, it));
                    }
                }
                try
                {
                    list.Sort(CompareOBISKeys);
                }
                catch
                {
                    //This fails if there is empty key. Remove key.
                }
                bool bSelected = false;
                if (collection != null)
                {
                    foreach (KeyValuePair<string, GXObisCode> it in list)
                    {
                        ListViewItem item = AddItem(it.Value);
                        if (!bSelected && Interface == it.Value.ObjectType && it.Value.LogicalName == selectedLN)
                        {
                            bSelected = item.Selected = true;
                        }
                    }
                }

                bool bEnabled = this.OBISCodesList.Items.Count != 0;
                EditBtn.Enabled = RemoveBtn.Enabled = bEnabled;
                if (!bSelected && bEnabled)
                {
                    this.OBISCodesList.Items[0].Selected = true;
                }
            }
            this.OBISCodesList.Select();
        }
		/// <summary>
		/// Imports properties from the device.
		/// </summary>
		/// <param name="addinPages">Custom pages created by the protocol addin.</param>
		/// <param name="device">The source GXDevice.</param>
		/// <param name="media">A media connection to the device.</param>
		/// <returns>True if everything went fine, otherwise false.</returns>
        public virtual void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media)
		{
			throw new NotImplementedException("ImportFromDevice");
		}
 /// <summary>
 /// Find correct DLMS class by Interface Type from the assembly.
 /// </summary>
 /// <param name="device"></param>
 /// <param name="it"></param>
 /// <returns></returns>
 public static GXDLMSObject ConvertObject2Class(GXDLMSDevice device, Gurux.DLMS.ObjectType objectType, string logicalName)
 {
     GXDLMSObject obj = Gurux.DLMS.GXDLMSClient.CreateObject(objectType);
     if (obj != null)
     {
         GXManufacturer m = device.Manufacturers.FindByIdentification(device.Manufacturer);
         GXObisCode item = m.ObisCodes.FindByLN(obj.ObjectType, logicalName, null);
         obj.LogicalName = logicalName;
         if (item != null)
         {
             obj.Description = item.Description;
         }
     }
     return obj;
 }
Exemple #17
0
 /// <summary> 
 /// Constructor,
 /// </summary> 
 protected GXDLMSObject(Gurux.DLMS.ObjectType objectType, string ln, ushort sn)
 {
     Attributes = new Gurux.DLMS.ManufacturerSettings.GXAttributeCollection();
     MethodAttributes = new Gurux.DLMS.ManufacturerSettings.GXAttributeCollection();
     ObjectType = objectType;
     this.ShortName = sn;
     if (ln != null)
     {
         string[] items = ln.Split('.');
         if (items.Length != 6)
         {
             throw new GXDLMSException("Invalid Logical Name.");
         }                
     }
     this.LogicalName = ln;
 }
 /// <summary>
 /// Create given type of COSEM object.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static GXDLMSObject CreateObject(Gurux.DLMS.ObjectType type)
 {
     return GXDLMS.CreateObject(type);
 }        
 /// <summary>
 /// Client has send data.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void OnReceived(object sender, Gurux.Common.ReceiveEventArgs e)
 {
     try
     {
         lock (this)
         {
             if (trace)
             {
                 Console.WriteLine("<- " + Gurux.Common.GXCommon.ToHex((byte[])e.Data, true));
             }
             reply.Set((byte[])e.Data);
             GetData(reply, data);
             // If all data is received.
             if (data.IsComplete && !data.IsMoreData)
             {
                 try
                 {
                     List<KeyValuePair<GXDLMSObject, int>> list;
                     list = ParsePush((Object[])data.Value);
                     // Print received data.
                     foreach (KeyValuePair<GXDLMSObject, int> it in list)
                     {
                         // Print LN.
                         Console.WriteLine(it.Key.ToString());
                         // Print Value.
                         Console.WriteLine(it.Key.GetValues()[it.Value - 1]);
                     }
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex.Message);
                 }
                 finally
                 {
                     data.Clear();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Exemple #20
0
 public static GXDLMSObject CreateObject(Gurux.DLMS.ObjectType type)
 {
     lock (AvailableObjectTypes)
     {
         //Update objects.
         if (AvailableObjectTypes.Count == 0)
         {
             GetObjectTypes();
         }
         if (AvailableObjectTypes.ContainsKey(type))
         {
             return Activator.CreateInstance(AvailableObjectTypes[type]) as GXDLMSObject;
         }
     }
     GXDLMSObject obj = new GXDLMSObject();
     obj.ObjectType = type;
     return obj;
 }
Exemple #21
0
 /// <summary>
 /// Reserved for internal use.
 /// </summary>
 internal void ParseReplyData(Gurux.DLMS.Internal.ActionType action, byte[] buff, out object value, out DataType type)
 {
     type = DataType.None; 
     if (!UseCache)
     {
         ClearProgress();
     }
     int read, total, index = 0;
     value = GXCommon.GetData(buff, ref index, action, out total, out read, ref type, ref CacheIndex);
     if (UseCache)
     {
         CacheSize = buff.Length;
         //If array.
         if (CacheData != null && CacheData.GetType().IsArray)
         {
             if (value != null)
             {
                 Array oldData = (Array)CacheData;
                 if (value.GetType().IsArray)
                 {
                     Array newData = (Array)value;
                     object[] data = new object[oldData.Length + newData.Length];
                     Array.Copy(oldData, data, oldData.Length);
                     Array.Copy(newData, 0, data, oldData.Length, newData.Length);
                     CacheData = data;
                 }
                 else
                 {
                     object[] data = new object[oldData.Length + 1];
                     Array.Copy(oldData, data, oldData.Length);
                     data[oldData.Length] = value;
                     CacheData = data;
                 }
             }
         }
         else
         {
             CacheData = value;
             CacheType = type;
         }
     }
     else
     {
         CacheData = value;
     }
     ItemCount += read;
     MaxItemCount = total;           
 }
 /// <summary>
 /// Assigns new media, after media settings are changed.
 /// </summary>
 /// <remarks>
 /// The media must be created before calling this method. 
 /// See methods EnumMedias and SelectMedia. 
 /// Active media is implemented with GetCurrentMedia method.
 /// AssignMedia closes the active media and selects a new one. 
 /// The protocol settings do not change, when AssignMedia is called. 
 /// After AssignMedia is called, the media must be opened with MediaOpen method.
 /// The new media is selected with the SelectMedia method.
 /// </remarks>
 /// <param name="media">New media component.</param>
 /// <seealso cref="SelectMedia">SelectMedia</seealso> 
 /// <seealso cref="Properties">Properties</seealso> 
 public void AssignMedia(Gurux.Common.IGXMedia media)
 {
     IGXMediaContainer tmp = media as IGXMediaContainer;
     if (tmp != null)
     {                
         media = (media as IGXMediaContainer).Media;
         media.MediaContainer = tmp;
     }
     CloseServer();
     m_MediaType = "";
     if (media != null)
     {
         if (media != null)
         {
             m_MediaType = media.MediaType;
             m_MediaSettings = media.Settings;
         }
         if (m_MediaSettings != null)
         {
             m_MediaSettings = m_MediaSettings.Replace("\r\n", "");
         }
         NotifyLoad();
         //Notify that media is changed.
         NotifyMediaStateChange(MediaState.Changed);
         m_Server = GXServer.Instance(media, this);
         //If handler is given before server is up.
         if (Handler != null)
         {
             m_Server.AddEventHandler(Handler, Clients);
             Handler = null;
             Clients = null;
         }
         //Notify is media is already open.
         if (media.IsOpen)
         {
             NotifyMediaStateChange(MediaState.Open);
         }
     }
 }
 /// <summary>
 /// Client has close connection.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void OnClientDisconnected(object sender, Gurux.Common.ConnectionEventArgs e)
 {
     Console.WriteLine("Client Disconnected.");
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="tag">Command.</param>
 /// <param name="security"></param>
 /// <param name="frameCounter"></param>
 /// <param name="systemTitle"></param>
 /// <param name="blockCipherKey"></param>
 /// <param name="authenticationKey"></param>
 public AesGcmParameter(
     byte tag,
     Gurux.DLMS.Enums.Security security,
     UInt32 frameCounter,
     byte[] systemTitle,
     byte[] blockCipherKey,
     byte[] authenticationKey)
 {
     Tag = tag;
     Security = security;
     FrameCounter = frameCounter;
     SystemTitle = systemTitle;
     BlockCipherKey = blockCipherKey;
     AuthenticationKey = authenticationKey;
     Type = CountType.Packet;
 }
Exemple #25
0
 /// <summary> 
 /// Constructor,
 /// </summary> 
 protected GXDLMSObject(Gurux.DLMS.ObjectType objectType) 
     : this(objectType, null, 0)
 {
 }
 /// <summary>
 /// Get security enum as integer value.
 /// </summary>
 /// <param name="security">Security level.</param>
 /// <returns>Integer value of security level.</returns>
 private static int GetSecurityValue(Gurux.DLMS.Enums.Security security)
 {
     int value = 0;
     switch (security)
     {
         case Gurux.DLMS.Enums.Security.None:
             value = 0;
             break;
         case Gurux.DLMS.Enums.Security.Authentication:
             value = 1;
             break;
         case Gurux.DLMS.Enums.Security.Encryption:
             value = 2;
             break;
         case Gurux.DLMS.Enums.Security.AuthenticationEncryption:
             value = 3;
             break;
         default:
             throw new InvalidEnumArgumentException();
     }
     return value;
 }
 public GXDLMSCommunicator(GXDLMSDevice parent, Gurux.Common.IGXMedia media)
 {
     this.parent = parent;
     this.media = media;
     client = new GXDLMSSecureClient();
 }
 /// <summary>
 /// Activates and strengthens the security policy.
 /// </summary>
 /// <param name="client">DLMS client that is used to generate action.</param>
 /// <param name="security">New security level.</param>
 /// <returns>Generated action.</returns>
 public byte[][] Activate(GXDLMSClient client, Gurux.DLMS.Enums.Security security)
 {
     return client.Method(this, 1, GetSecurityValue(security), DataType.Enum);
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public GXDLMSDevice(Gurux.Common.IGXMedia media)
 {
     StartProtocol = StartProtocolType.IEC;
     ClientID = 0x10; // Public client (lowest security level).
     PhysicalAddress = 1;
     Password = "";
     Authentication = Authentication.None;
     m_Communicator = new GXDLMSCommunicator(this, media);
     m_Objects = m_Communicator.m_Cosem.Objects;
     m_Objects.Tag = this;
     m_Communicator.OnProgress += new ProgressEventHandler(this.NotifyProgress);
     this.KeepAlive = new System.Timers.Timer();
     this.KeepAlive.Interval = 40000;
     this.KeepAlive.Elapsed += new System.Timers.ElapsedEventHandler(KeepAlive_Elapsed);
     m_Status = DeviceState.Initialized;
     WaitTime = 5;
 }
 /// <summary>
 /// Convert DLMS data type to .Net data type.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static Type GetDataType(Gurux.DLMS.DataType type)
 {
     switch (type)
     {
         case Gurux.DLMS.DataType.None:
             return null;
         case Gurux.DLMS.DataType.Array:
         case Gurux.DLMS.DataType.CompactArray:
         case Gurux.DLMS.DataType.Structure:
             return typeof(object[]);
         case Gurux.DLMS.DataType.BinaryCodedDesimal:
             return typeof(string);
         case Gurux.DLMS.DataType.BitString:
             return typeof(string);
         case Gurux.DLMS.DataType.Boolean:
             return typeof(bool);
         case Gurux.DLMS.DataType.Date:
             return typeof(Date);
         case Gurux.DLMS.DataType.DateTime:
             return typeof(DateTime);
         case Gurux.DLMS.DataType.Float32:
             return typeof(float);
         case Gurux.DLMS.DataType.Float64:
             return typeof(double);
         case Gurux.DLMS.DataType.Int16:
             return typeof(Int16);
         case Gurux.DLMS.DataType.Int32:
             return typeof(Int32);
         case Gurux.DLMS.DataType.Int64:
             return typeof(Int64);
         case Gurux.DLMS.DataType.Int8:
             return typeof(sbyte);
         case Gurux.DLMS.DataType.OctetString:
             return typeof(byte[]);
         case Gurux.DLMS.DataType.String:
             return typeof(string);
         case Gurux.DLMS.DataType.Time:
             return typeof(Time);
         case Gurux.DLMS.DataType.UInt16:
             return typeof(UInt16);
         case Gurux.DLMS.DataType.UInt32:
             return typeof(UInt32);
         case Gurux.DLMS.DataType.UInt64:
             return typeof(UInt64);
         case Gurux.DLMS.DataType.UInt8:
             return typeof(byte);
         default:
         case Gurux.DLMS.DataType.Enum:
             break;
     }
     throw new Exception("Invalid DLMS data type.");
 }