Exemplo n.º 1
0
 private void ScanMnu_Click(object sender, EventArgs e)
 {
     try
     {
         if (media.IsOpen)
         {
             media.Close();
         }
         else
         {
             if (media is GXSerial serial)
             {
                 //Return default settings.
                 if (Settings.Default.HdlcAddressUseOpticalProbe)
                 {
                     serial.BaudRate = 300;
                     serial.DataBits = 7;
                     serial.Parity   = Parity.Even;
                     serial.StopBits = StopBits.One;
                 }
             }
             media.Open();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 2
0
 private void DiscoverMnu_Click(object sender, EventArgs e)
 {
     try
     {
         if (media.IsOpen)
         {
             ScanWork.Cancel();
             media.Close();
         }
         else
         {
             ClearMnu_Click(null, null);
             media.Open();
             ScanWork = new GXAsyncWork(this, OnAsyncStateChange, DiscoverMeters, OnError, null, new object[] { sender });
             ScanWork.Start();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 3
0
 private void ScanMnu_Click(object sender, EventArgs e)
 {
     try
     {
         if (media.IsOpen)
         {
             media.Close();
         }
         else
         {
             media.Open();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 4
0
        private void StartWithIec()
        {
            //Query device information.
            GXSerial serial = Media as GXSerial;

            if (serial == null)
            {
                return;
            }
            if (UseIec)
            {
                serial.BaudRate = 300;
                serial.DataBits = 7;
                serial.Parity   = System.IO.Ports.Parity.Even;
                serial.StopBits = System.IO.Ports.StopBits.One;
            }
            else
            {
                serial.BaudRate = 9600;
                serial.DataBits = 8;
                serial.Parity   = System.IO.Ports.Parity.None;
                serial.StopBits = System.IO.Ports.StopBits.One;
            }

            byte   Terminator = (byte)0x0A;
            string data       = "/?!\r\n";

            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("IEC sending:" + data);
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                Eop      = Terminator,
                WaitTime = WaitTime
            };

            lock (Media.Synchronous)
            {
                WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(data), true));
                Media.Send(data, null);
                if (!Media.Receive(p))
                {
                    //Try to move away from mode E.
                    try
                    {
                        GXReplyData reply = new GXReplyData();
                        ReadDLMSPacket(Client.DisconnectRequest(), reply);
                    }
                    catch (Exception)
                    {
                    }
                    data = (char)0x01 + "B0" + (char)0x03;
                    Media.Send(data, null);
                    p.Count = 1;
                    if (!Media.Receive(p))
                    {
                    }
                    data = "Failed to receive reply from the device in given time.";
                    Console.WriteLine(data);
                    throw new Exception(data);
                }
                WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        GXReplyData reply = new GXReplyData();
                        ReadDLMSPacket(Client.DisconnectRequest(), reply);
                        if (serial != null)
                        {
                            data = (char)0x01 + "B0" + (char)0x03;
                            Media.Send(data, null);
                            p.Count = 1;
                            Media.Receive(p);
                            serial.BaudRate = 9600;
                            data            = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                            Media.Send(data, null);
                            p.Count = 1;
                            Media.Receive(p);
                        }

                        data = "Failed to receive reply from the device in given time.";
                        Console.WriteLine(data);
                        throw new Exception(data);
                    }
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                }
            }
            Console.WriteLine("IEC received: " + p.Reply);
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                Media.Receive(p);
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate      = 0;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            Console.WriteLine("BaudRate is : " + BaudRate.ToString());
            //Send ACK
            //Send Protocol control character
            byte controlCharacter = (byte)'2';     // "2" HDLC protocol procedure (Mode E)
                                                   //Send Baudrate character
                                                   //Mode control character
            byte ModeControlCharacter = (byte)'2'; //"2" //(HDLC protocol procedure) (Binary mode)

            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            Console.WriteLine("Moving to mode E.", arr);
            lock (Media.Synchronous)
            {
                WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(arr, true));
                Media.Send(arr, null);
                p.Reply = null;

                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                Media.Receive(p);
                if (p.Reply != null)
                {
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                    Console.WriteLine("Received: " + p.Reply);
                }
                if (serial != null)
                {
                    Media.Close();
                    serial.BaudRate = BaudRate;
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                    Media.Open();
                    //Some meters need this sleep. Do not remove.
                    Thread.Sleep(1000);
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initialize optical head.
        /// </summary>
        void InitializeOpticalHead()
        {
            if (Client.InterfaceType != InterfaceType.HdlcWithModeE)
            {
                return;
            }
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            Media.Open();
            //Some meters need a little break.
            Thread.Sleep(1000);
            //Query device information.
            string data = "/?!\r\n";

            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("IEC Sending:" + data);
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                AllData  = false,
                Eop      = Terminator,
                WaitTime = WaitTime * 1000
            };

            lock (Media.Synchronous)
            {
                Media.Send(data, null);
                if (!Media.Receive(p))
                {
                    //Try to move away from mode E.
                    try
                    {
                        Disconnect();
                    }
                    catch (Exception)
                    {
                    }
                    DiscIEC();
                    string str = "Failed to receive reply from the device in given time.";
                    if (Trace > TraceLevel.Info)
                    {
                        Console.WriteLine(str);
                    }
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        throw new Exception(str);
                    }
                }
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        GXReplyData reply = new GXReplyData();
                        Disconnect();
                        if (serial != null)
                        {
                            DiscIEC();
                            serial.DtrEnable = serial.RtsEnable = false;
                            serial.BaudRate  = 9600;
                            serial.DtrEnable = serial.RtsEnable = true;
                            DiscIEC();
                        }
                        data = "Failed to receive reply from the device in given time.";
                        if (Trace > TraceLevel.Info)
                        {
                            Console.WriteLine(data);
                        }
                        throw new Exception(data);
                    }
                }
            }
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("HDLC received: " + p.Reply);
            }
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                Media.Receive(p);
                DiscIEC();
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate      = 0;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("BaudRate is : " + BaudRate.ToString());
            }
            //Send ACK
            //Send Protocol control character
            // "2" HDLC protocol procedure (Mode E)
            byte controlCharacter = (byte)'2';
            //Send Baud rate character
            //Mode control character
            byte ModeControlCharacter = (byte)'2';

            //"2" //(HDLC protocol procedure) (Binary mode)
            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            if (Trace > TraceLevel.Info)
            {
                Console.WriteLine("Moving to mode E.", arr);
            }
            lock (Media.Synchronous)
            {
                p.Reply = null;
                Media.Send(arr, null);
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(200);
                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                Media.Receive(p);
                if (p.Reply != null)
                {
                    if (Trace > TraceLevel.Info)
                    {
                        Console.WriteLine("Received: " + p.Reply);
                    }
                }
                serial.BaudRate = BaudRate;
                serial.DataBits = 8;
                serial.Parity   = Parity.None;
                serial.StopBits = StopBits.One;
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(800);
            }
        }
Exemplo n.º 6
0
		/// <summary>
		/// Import properties from the device.
		/// </summary>
        /// <param name="addinPages">Addin pages.</param>
        /// <param name="device">The target GXDevice to put imported items.</param>
		/// <param name="media">A media connection to the device.</param>
		/// <returns>True if there were no errors, otherwise false.</returns>
        public override void ImportFromDevice(Control[] addinPages, GXDevice device, IGXMedia media)
		{
            media.Open();
			GXDLMSDevice Device = (GXDLMSDevice)device;            
			int wt = Device.WaitTime;
			GXDLMSClient cosem = null;
            byte[] data, reply = null;            
            IGXManufacturerExtension Extension = null;
			try
			{                
				//Initialize connection.
                cosem = new GXDLMSClient();
                cosem.UseLogicalNameReferencing = Device.UseLogicalNameReferencing;				
                if (Device.Manufacturers == null)
                {
                    Device.Manufacturers = new GXManufacturerCollection();
                    GXManufacturerCollection.ReadManufacturerSettings(Device.Manufacturers);
                }
                GXManufacturer man = Device.Manufacturers.FindByIdentification(Device.Identification);
                if (!string.IsNullOrEmpty(man.Extension))
                {
                    Type t = Type.GetType(man.Extension);
                    Extension = Activator.CreateInstance(t) as IGXManufacturerExtension;
                }

                if (!Device.UseRemoteSerial && media is GXNet) //If media is network.
				{
                    if (Device.SupportNetworkSpecificSettings)
                    {
                        cosem.InterfaceType = Gurux.DLMS.InterfaceType.Net;
                    }
				}
				else if (media is GXSerial) //If media is serial.
				{
                    byte terminator = 0xA;
                    if (Device.StartProtocol == StartProtocolType.IEC)
                    {
                        GXSerial serial = media as GXSerial;
                        serial.Eop = terminator;
                        serial.Eop = terminator;
                        //Init IEC connection. This must done first with serial connections.
                        string str = "/?" + Device.SerialNumber + "!\r\n";
                        ReceiveParameters<string> args = new ReceiveParameters<string>()
                        {
                            Eop = terminator,
                            WaitTime = wt
                        };
                        lock (media.Synchronous)
                        {
                            media.Send(str, null);
                            do
                            {
                                args.Reply = null;                                
                                if (!media.Receive(args))
                                {
                                    throw new Exception("Failed to receive reply from the device in given time.");
                                }
                            }
                            while (str == args.Reply);//Remove echo
                        }
                        string answer = args.Reply.ToString();                        
                        if (answer[0] != '/')
                        {
                            throw new Exception("Invalid responce.");
                        }
                        string manufactureID = answer.Substring(1, 3);
                        char baudrate = answer[4];
                        if (baudrate == ' ')
                        {
                            baudrate = '5';
                        }
                        int baudRate = 0;
                        switch (baudrate)
                        {
                            case '0':
                                baudRate = 300;
                                break;
                            case '1':
                                baudRate = 600;
                                break;
                            case '2':
                                baudRate = 1200;
                                break;
                            case '3':
                                baudRate = 2400;
                                break;
                            case '4':
                                baudRate = 4800;
                                break;
                            case '5':                            
                                baudRate = 9600;
                                break;
                            case '6':
                                baudRate = 19200;
                                break;
                            default:
                                throw new Exception("Unknown baud rate.");
                        }                        
                        //Send ACK
                        //Send Protocol control character
                        byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E)
                        //Send Baudrate character
                        //Mode control character 
                        byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode)
                        //We are not receive anything.
                        data = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 0x0D, 0x0A };                        
                        lock (media.Synchronous)
                        {
                            args.Reply = null;                            
                            media.Send(data, null);                                                       
                            //This is in standard. Do not remove sleep.
                            //Some meters work without it, but some do not.
                            System.Threading.Thread.Sleep(500);
                            serial.BaudRate = baudRate;
                            ReceiveParameters<byte[]> args2 = new ReceiveParameters<byte[]>()
                            {
                                Eop = terminator,
                                WaitTime = 100
                            };
                            //If this fails, just read all data.
                            if (!media.Receive(args2))
                            {
                                //Read buffer.
                                args2.AllData = true;
                                args2.WaitTime = 1;
                                media.Receive(args2);
                            }
                            serial.DataBits = 8;
                            serial.Parity = Parity.None;
                            serial.StopBits = StopBits.One;
                            serial.DiscardInBuffer();
                            serial.DiscardOutBuffer();
                            serial.ResetSynchronousBuffer();
                        }                        
                    }
				}
                media.Eop = (byte) 0x7E;
                cosem.Authentication = (Gurux.DLMS.Authentication)Device.Authentication;
                object clientAdd = null;
                if (cosem.Authentication == Authentication.None)
                {
                    clientAdd = Device.ClientID;
                }
                else if (cosem.Authentication == Authentication.Low)
                {
                    clientAdd = Device.ClientIDLow;
                }
                else if (cosem.Authentication == Authentication.High)
                {
                    clientAdd = Device.ClientIDHigh;
                }
                if (!string.IsNullOrEmpty(Device.Password))
                {
                    cosem.Password = ASCIIEncoding.ASCII.GetBytes(Device.Password);
                }
                else
                {
                    cosem.Password = null;
                }
                //If network media is used check is manufacturer supporting IEC 62056-47
                if (!Device.UseRemoteSerial && media is GXNet && Device.SupportNetworkSpecificSettings)
                {
                    cosem.InterfaceType = InterfaceType.Net;
                    media.Eop = null;
                    cosem.ClientID = Convert.ToUInt16(clientAdd);
                    cosem.ServerID = Convert.ToUInt16(Device.PhysicalAddress);
                }
                else
                {
                    if (Device.HDLCAddressing == HDLCAddressType.Custom)
                    {
                        cosem.ClientID = clientAdd;
                    }
                    else
                    {
                        cosem.ClientID = (byte)(Convert.ToByte(clientAdd) << 1 | 0x1);
                    }
                    if (Device.HDLCAddressing == HDLCAddressType.SerialNumber)
                    {
                        cosem.ServerID = GXManufacturer.CountServerAddress(Device.HDLCAddressing, Device.SNFormula, Convert.ToUInt32(Device.SerialNumber), Device.LogicalAddress);
                    }
                    else
                    {
                        cosem.ServerID = GXManufacturer.CountServerAddress(Device.HDLCAddressing, Device.SNFormula, Device.PhysicalAddress, Device.LogicalAddress);
                    }                    
                }
                byte[] allData = null;
                data = cosem.SNRMRequest();
				//General Network connection don't need SNRMRequest.
				if (data != null)
				{
					Trace("--- Initialize DLMS connection\r\n");
					try
					{
						reply = ReadDLMSPacket(cosem, media, data, wt);
					}
					catch (Exception Ex)
					{
						throw new Exception("DLMS Initialize failed. " + Ex.Message);
					}
					//Has server accepted client.
					cosem.ParseUAResponse(reply);
				}
				Trace("Connecting\r\n");
                media.ResetSynchronousBuffer();
				try
				{                    
                    foreach (byte[] it in cosem.AARQRequest(null))
                    {                        
                        reply = ReadDLMSPacket(cosem, media, it, wt);
                    }
				}
				catch (Exception Ex)
				{
					throw new Exception("DLMS AARQRequest failed. " + Ex.Message);
				}
                cosem.ParseAAREResponse(reply);
                //Now 1/5 or actions is done.
                Progress(1, 5);
                Trace("Read Objects\r\n");
                try
				{
                    allData = ReadDataBlock(cosem, media, cosem.GetObjectsRequest(), wt, 1);
				}
				catch (Exception Ex)
				{
					throw new Exception("DLMS AARQRequest failed. " + Ex.Message);
				}
                Trace("--- Parse Objects ---\r\n");
                GXDLMSObjectCollection objs = cosem.ParseObjects((byte[])allData, true);

			    allData = null;
				//Now we know exact number of read registers. Update progress bar again.
                int max = objs.Count;				                
				Trace("--- Read scalars ---\r\n");
				//Now 2/5 or actions is done.
                Progress(2 * max, 5 * max);
                GXCategory dataItems = new GXCategory();
                dataItems.Name = "Data Items";
                GXCategory registers = new GXCategory();
                registers.Name = "Registers";
                Device.Categories.Add(dataItems);
                Device.Categories.Add(registers);
                int pos = 0;
                foreach (GXDLMSObject it in objs)
                {
                    ++pos;
                    //Skip association views.
                    if (it.ObjectType == ObjectType.AssociationLogicalName ||
                        it.ObjectType == ObjectType.AssociationShortName)
                    {
                        continue;
                    }
                    if (it.ObjectType != ObjectType.ProfileGeneric)
                    {
                        object prop = UpdateData(media, Device, wt, cosem, man, it, dataItems, registers);
                        //Read scaler and unit
                        if (it.ObjectType == ObjectType.Register)
                        {
                            try
                            {
                                data = cosem.Read(it.Name, it.ObjectType, 3)[0];
                                allData = ReadDataBlock(cosem, media, data, wt, 2);
                                cosem.UpdateValue(allData, it, 3);
                                Gurux.DLMS.Objects.GXDLMSRegister item = it as Gurux.DLMS.Objects.GXDLMSRegister;
                                GXDLMSRegister r = prop as GXDLMSRegister;
                                r.Scaler = item.Scaler;
                                r.Unit = item.Unit.ToString();
                            }
                            //Ignore HW error and read next.
                            catch (GXDLMSException)
                            {
                                continue;
                            }
                            catch (Exception Ex)
                            {
                                throw new Exception("DLMS Register Scaler and Unit read failed. " + Ex.Message);
                            }
                        }
                        //Read scaler and unit
                        else if (it.ObjectType == ObjectType.ExtendedRegister)
                        {
                            try
                            {
                                data = cosem.Read(it.Name, it.ObjectType, 3)[0];
                                allData = ReadDataBlock(cosem, media, data, wt, 2);
                                cosem.UpdateValue(allData, it, 3);
                                Gurux.DLMS.Objects.GXDLMSExtendedRegister item = it as Gurux.DLMS.Objects.GXDLMSExtendedRegister;
                                GXDLMSCategory cat = prop as GXDLMSCategory;
                                GXDLMSRegister r = cat.Properties[0] as GXDLMSRegister;
                                r.Scaler = item.Scaler;
                                r.Unit = item.Unit.ToString();
                                cat.Properties[1].SetValue(item.Scaler.ToString() + ", " + item.Unit.ToString(), true, PropertyStates.None);
                            }
                            //Ignore HW error and read next.
                            catch (GXDLMSException)
                            {
                                continue;
                            }
                            catch (Exception Ex)
                            {
                                throw new Exception("DLMS Register Scaler and Unit read failed. " + Ex.Message);
                            }
                        }
                        //Read scaler and unit
                        else if (it.ObjectType == ObjectType.DemandRegister)
                        {
                            try
                            {
                                data = cosem.Read(it.Name, it.ObjectType, 3)[0];
                                allData = ReadDataBlock(cosem, media, data, wt, 2);
                                cosem.UpdateValue(allData, it, 3);
                                Gurux.DLMS.Objects.GXDLMSDemandRegister item = it as Gurux.DLMS.Objects.GXDLMSDemandRegister;
                                GXDLMSCategory cat = prop as GXDLMSCategory;
                                cat.Properties[2].SetValue(item.Scaler.ToString() + ", " + item.Unit.ToString(), true, PropertyStates.None);

                                GXDLMSRegister r = cat.Properties[0] as GXDLMSRegister;
                                r.Scaler = item.Scaler;
                                r.Unit = item.Unit.ToString();
                                r = cat.Properties[1] as GXDLMSRegister;
                                r.Scaler = item.Scaler;
                                r.Unit = item.Unit.ToString();
                            }
                            //Ignore HW error and read next.
                            catch (GXDLMSException)
                            {
                                continue;
                            }
                            catch (Exception Ex)
                            {
                                throw new Exception("DLMS Register Scaler and Unit read failed. " + Ex.Message);
                            }
                        }                        
                    }
                    //Now 3/5 actions is done.
                    double tmp = pos * max; 
                    tmp /= max;
                    tmp += 2 * max;
                    Progress((int) tmp , 5 * max);
                }
                //Now 3/5 actions is done.
                Progress(3 * max, 5 * max);
                Trace("--- Read Generic profiles ---\r\n");
                GXDLMSObjectCollection pg = objs.GetObjects(ObjectType.ProfileGeneric);
                foreach (GXDLMSProfileGeneric it in pg)
                {
                    try
                    {
                        allData = ReadDataBlock(cosem, media, cosem.Read(it.Name, it.ObjectType, 3)[0], wt, 3);
                        cosem.UpdateValue(allData, it, 3);
                        UpdateData(media, Device, wt, cosem, man, it, dataItems, registers);
                    }
                    //Ignore HW error and read next.
                    catch (GXDLMSException)
                    {
                        continue;
                    }
                    catch (Exception Ex)
                    {
                        Trace("DLMS Generic Profile read failed. " + Ex.Message + Environment.NewLine);
                    }
                }
                //Now 4/5 actions is done.
                Progress(4 * max, 5 * max);            

                //Update IEC HDLC interval if found. 
                GXDLMSObjectCollection objects = objs.GetObjects(ObjectType.IecHdlcSetup);
                if (objects.Count != 0)
                {
                    allData = ReadDataBlock(cosem, media, cosem.Read(objects[0].Name, objects[0].ObjectType, 8)[0], wt, 5);
                    //Minus 10 second.
                    Device.Keepalive.Interval = (Convert.ToInt32(cosem.GetValue(allData)) - 10) * 1000;
                }

                //Now all actions are done.
                Progress(max, max);
                Trace("--- Succeeded ---\r\n");
			}
			finally
			{                
                if (cosem != null && media != null)
				{
					Trace("--- Disconnecting ---\r\n");
                    byte[] allData = null;
					if (cosem != null)
					{
						//Network standard don't need this.					
                        if (!(media is GXNet && Device.SupportNetworkSpecificSettings))
						{
							try
							{
								reply = ReadDLMSPacket(cosem, media, cosem.DisconnectRequest(), wt);
								cosem.GetDataFromPacket(reply, ref allData);
							}
							catch (Exception Ex)
							{
								Trace("DisconnectRequest failed. " + Ex.Message);
							}
						}
					}
					if (media != null)
					{
						media.Close();
						media = null;
					}
					Trace("--- Disconnected ---\r\n--- Done---\r\n");					
				}
			}			
		}
Exemplo n.º 7
0
        public override void ImportFromDevice(Control[] addinPages, GXDevice device, IGXMedia media)
        {
            media.Open();
            GXMBusDevice dev = device as GXMBusDevice;
            object data;
            //Handshake
            ShortFrame sf = new ShortFrame();
            sf.AddressField = dev.DeviceAddress;
            sf.ControlField = (byte)CFieldFunctions.SendSlaveInit;
            sf.CountChecksum();
            data = sf.ToByteArray();
            ReceiveParameters<byte[]> recParams = new ReceiveParameters<byte[]>()
            {                
                Count = 1,
                Peek = false,
                WaitTime = device.WaitTime
            };

            lock (media.Synchronous)
            {
                media.Send(data, null);
                if (!media.Receive(recParams))
                {
                    throw new Exception("Failed to receive reply from the device in given time.");
                }
                if (recParams.Reply.Length < 1 || recParams.Reply[0] != 0xE5)
                {
                    throw new Exception("Handshake failed.");
                }

                bool morePacketsAvailable = false;
                byte fcb = 1;

                List<MBusRegister> items = new List<MBusRegister>();
                do
                {
                    sf = new ShortFrame();
                    sf.AddressField = dev.DeviceAddress;
                    if (fcb == 1)
                    {
                        sf.ControlField = (byte)CFieldFunctions.RequestClass2Data;
                    }
                    else
                    {
                        sf.ControlField = (byte)CFieldFunctions.RequestClass2Data | (byte)CFieldRequest.FrameCountBit;
                    }
                    sf.CountChecksum();

                    recParams.AllData = true;
                    recParams.Count = 1;
                    recParams.Eop = (byte)0x16;
                    recParams.Reply = null;    
                    int cnt = 0;
                    //Some meters can't answer right a way.
                    do
                    {
                        media.Send(sf.ToByteArray(), null);
                        if (++cnt == 6)
                        {
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }                        
                    }
                    while (!media.Receive(recParams));
                    while (!VerifyReadReplyCheckSum(recParams.Reply))
                    {
                        recParams.Count = 0;
                        recParams.Reply = null;
                        bool gotData = media.Receive(recParams);
                        if (!gotData)
                        {
                            break;
                        }
                    }
                    morePacketsAvailable = recParams.Reply.Length > 5 && (recParams.Reply[4] & 0x10) != 0;
                    items.AddRange(ParseReadReply(recParams.Reply));
                }
                while (morePacketsAvailable);

                GXMBusCategory defaultCategory = null;
                if ((defaultCategory = (GXMBusCategory)device.Categories.Find("Default")) == null)
                {
                    defaultCategory = new GXMBusCategory();
                    defaultCategory.Name = "Default";
                    device.Categories.Add(defaultCategory);
                }
                for (int pos = 0; pos < items.Count; ++pos)
                {
                    MBusRegister item = items[pos];
                    GXMBusProperty prop = new GXMBusProperty();                    
                    prop.Ordinal = pos;
                    if (item.IsVariableData)
                    {
                        string name = item.MBusType;
                        int len = name.IndexOf('_');
                        if (len != -1)
                        {
                            name = name.Substring(0, len);
                        }
                        name += " " + item.Function.ToString();
                        if (item.Tariff != 0)
                        {
                            name += " Tariff " + item.Tariff.ToString();
                        }
                        prop.Name = name;
                        prop.Unit = item.Unit;
                        prop.DataLength = item.DataLength;
                        item.Mask.Reverse();
                        prop.InfoMask = item.Mask.ToArray();
                        prop.Type = item.Type;                                                
                        if (item.MBusType.ToLower().Contains("date") || item.MBusType.ToLower().Contains("timepoint"))
                        {
                            prop.ValueType = typeof(DateTime);
                        }
                        else
                        {                            
                            prop.ValueType = typeof(string);
                        }                         
                    }
                    else
                    {
                        prop.Name = item.MBusType;
                        prop.Unit = item.Unit;
                        prop.ValueType = typeof(string);
                        prop.DataLength = 4;
                    }                    
                    prop.InfoBytes = item.InformationBytes.Reverse().ToArray();
                    defaultCategory.Properties.Add(prop);
                }
            }
        }
Exemplo n.º 8
0
        void InitializeIEC()
        {
            GXManufacturer manufacturer = this.parent.Manufacturers.FindByIdentification(parent.Manufacturer);

            if (manufacturer == null)
            {
                throw new Exception("Unknown manufacturer " + parent.Manufacturer);
            }
            GXSerial serial     = media as GXSerial;
            byte     Terminator = (byte)0x0A;

            media.Open();
            //Query device information.
            if (serial != null && parent.StartProtocol == StartProtocolType.IEC)
            {
                parent.StartMediaSettings = media.Settings;
                string data = "/?!\r\n";
                if (this.parent.HDLCAddressing == HDLCAddressType.SerialNumber)
                {
                    data = "/?" + this.parent.PhysicalAddress + "!\r\n";
                }
                GXLogWriter.WriteLog("HDLC sending:" + data);
                ReceiveParameters <string> p = new ReceiveParameters <string>()
                {
                    AllData  = false,
                    Eop      = Terminator,
                    WaitTime = parent.WaitTime * 1000
                };
                lock (media.Synchronous)
                {
                    media.Send(data, null);
                    if (!media.Receive(p))
                    {
                        //Try to move away from mode E.
                        try
                        {
                            GXReplyData reply = new GXReplyData();
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1, reply);
                        }
                        catch (Exception)
                        {
                        }
                        DiscIEC();
                        string str = "Failed to receive reply from the device in given time.";
                        GXLogWriter.WriteLog(str);
                        media.Send(data, null);
                        if (!media.Receive(p))
                        {
                            throw new Exception(str);
                        }
                    }
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!media.Receive(p))
                        {
                            //Try to move away from mode E.
                            GXReplyData reply = new GXReplyData();
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1, reply);
                            if (serial != null)
                            {
                                DiscIEC();
                                serial.DtrEnable = serial.RtsEnable = false;
                                serial.BaudRate  = 9600;
                                serial.DtrEnable = serial.RtsEnable = true;
                                DiscIEC();
                            }
                            data = "Failed to receive reply from the device in given time.";
                            GXLogWriter.WriteLog(data);
                            throw new Exception(data);
                        }
                    }
                }
                GXLogWriter.WriteLog("HDLC received: " + p.Reply);
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int  BaudRate = 0;
                switch (baudrate)
                {
                case '0':
                    BaudRate = 300;
                    break;

                case '1':
                    BaudRate = 600;
                    break;

                case '2':
                    BaudRate = 1200;
                    break;

                case '3':
                    BaudRate = 2400;
                    break;

                case '4':
                    BaudRate = 4800;
                    break;

                case '5':
                    BaudRate = 9600;
                    break;

                case '6':
                    BaudRate = 19200;
                    break;

                default:
                    throw new Exception("Unknown baud rate.");
                }
                if (parent.MaximumBaudRate != 0)
                {
                    BaudRate = parent.MaximumBaudRate;
                    baudrate = GetIecBaudRate(BaudRate);
                    GXLogWriter.WriteLog("Maximum BaudRate is set to : " + BaudRate.ToString());
                }
                GXLogWriter.WriteLog("BaudRate is : " + BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                // "2" HDLC protocol procedure (Mode E)
                byte controlCharacter = (byte)'2';
                //Send Baud rate character
                //Mode control character
                byte ModeControlCharacter = (byte)'2';
                //"2" //(HDLC protocol procedure) (Binary mode)
                //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                GXLogWriter.WriteLog("Moving to mode E.", arr);
                lock (media.Synchronous)
                {
                    p.Reply = null;
                    media.Send(arr, null);
                    p.WaitTime = 2000;
                    //Note! All meters do not echo this.
                    media.Receive(p);
                    if (p.Reply != null)
                    {
                        GXLogWriter.WriteLog("Received: " + p.Reply);
                    }
                    media.Close();
                    serial.BaudRate = BaudRate;
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                    media.Open();
                    //Some meters need this sleep. Do not remove.
                    Thread.Sleep(1000);
                }
            }
        }
Exemplo n.º 9
0
        void InitSerial()
        {
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            if (serial != null && InitializeIEC)
            {
                serial.BaudRate = 300;
                serial.DataBits = 7;
                serial.Parity   = Parity.Even;
                serial.StopBits = StopBits.One;
            }
            Media.Open();
            //Query device information.
            if (Media != null && InitializeIEC)
            {
                string data = "/?001!\r\n";
                if (Trace)
                {
                    Console.WriteLine("HDLC sending:" + data);
                }
                ReceiveParameters <string> p = new ReceiveParameters <string>()
                {
                    Eop      = Terminator,
                    WaitTime = WaitTime
                };
                lock (Media.Synchronous)
                {
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        throw new Exception("Failed to receive reply from the device in given time.");
                    }
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!Media.Receive(p))
                        {
                            //Try to move away from mode E.
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                    }
                }
                if (Trace)
                {
                    Console.WriteLine("HDLC received: " + p.Reply);
                }
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    Media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                //UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int  BaudRate = 0;
                switch (baudrate)
                {
                case '0':
                    BaudRate = 300;
                    break;

                case '1':
                    BaudRate = 600;
                    break;

                case '2':
                    BaudRate = 1200;
                    break;

                case '3':
                    BaudRate = 2400;
                    break;

                case '4':
                    BaudRate = 4800;
                    break;

                case '5':
                    BaudRate = 9600;
                    break;

                case '6':
                    BaudRate = 19200;
                    break;

                default:
                    throw new Exception("Unknown baud rate.");
                }
                Console.WriteLine("BaudRate is :", BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E)
                //Send Baudrate character
                //Mode control character
                byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode)
                //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                if (Trace)
                {
                    Console.WriteLine("Moving to mode E", BitConverter.ToString(arr));
                }
                lock (Media.Synchronous)
                {
                    Media.Send(arr, null);
                    p.Reply    = null;
                    p.WaitTime = 500;
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        this.ReadDLMSPacket(m_Parser.DisconnectRequest());
                        throw new Exception("Failed to receive reply from the device in given time.");
                    }
                }
                if (serial != null)
                {
                    serial.BaudRate = BaudRate;
                    serial.DataBits = 8;
                    serial.Parity   = Parity.None;
                    serial.StopBits = StopBits.One;
                }
            }
        }