void OnAsyncStateChange(object sender, GXAsyncWork work, object[] parameters, AsyncState state, string text) { if (InvokeRequired) { BeginInvoke(new AsyncStateChangeEventHandler(OnAsyncStateChange), sender, work, parameters, state, text); } else { if (state != AsyncState.Start) { media.Close(); BeginInvoke(new ResetProgressEventHandler(OnResetProgress), 0, true); } } }
/// <summary> /// Close connection to the meter. /// </summary> public void Close() { if (Media != null && Client != null) { try { if (Trace > TraceLevel.Info) { Console.WriteLine("Disconnecting from the meter."); } GXReplyData reply = new GXReplyData(); try { ReadDataBlock(Client.ReleaseRequest(), reply); } catch (Exception) { //All meters don't support release. } reply.Clear(); ReadDLMSPacket(Client.DisconnectRequest(), reply); Media.Close(); } catch { } Media = null; Client = null; } }
public void Close() { if (Media != null && Client != null) { try { Console.WriteLine("Disconnecting from the meter."); GXReplyData reply = new GXReplyData(); ReadDLMSPacket(Client.DisconnectRequest(), reply); Media.Close(); } catch { } Media = null; Client = null; } }
void OnAsyncStateChange(object sender, GXAsyncWork work, object[] parameters, AsyncState state, string text) { if (InvokeRequired) { BeginInvoke(new AsyncStateChangeEventHandler(OnAsyncStateChange), sender, work, parameters, state, text); } else { if (state != AsyncState.Start) { RegisterMnu.Enabled = true; media.Close(); BeginInvoke(new ResetProgressEventHandler(OnResetProgress), 0, true); } else { RegisterMnu.Enabled = false; } MetersView_SelectedIndexChanged(null, null); } }
public void Disconnect() { if (media != null && media.IsOpen) { try { GXReplyData reply = new GXReplyData(); try { //Release is call only for secured connections. //Add meters are not supporting Release and it's causing problems. if (client.Ciphering.Security != Security.None) { ReadDataBlock(ReleaseRequest(), "Release request", reply); } } catch (Exception) { //All meters don't support release. } reply.Clear(); ReadDataBlock(DisconnectRequest(), "Disconnect request", reply); } finally { if (media != null) { media.Close(); //Restore old settings. if (media is GXSerial) { media.Settings = parent.StartMediaSettings; } } } } }
public void Close() { if (Media != null && m_Parser != null) { try { Console.WriteLine("Disconnecting from the meter."); ReadDLMSPacket(m_Parser.DisconnectRequest()); Media.Close(); } catch { } Media = null; m_Parser = null; } }
/// <summary> /// Close connection to the meter. /// </summary> public void Close() { if (Media != null && Client != null) { try { if (Trace > TraceLevel.Info) { Console.WriteLine("Disconnecting from the meter."); } GXReplyData reply = new GXReplyData(); try { //Release is call only for secured connections. //All meters are not supporting Release and it's causing problems. if (Client.InterfaceType == InterfaceType.WRAPPER || (Client.InterfaceType == InterfaceType.HDLC && Client.Ciphering.Security != (byte)Security.None)) { ReadDataBlock(Client.ReleaseRequest(), reply); } } catch (Exception ex) { //All meters don't support Release. Console.WriteLine("Release failed. " + ex.Message); } reply.Clear(); ReadDLMSPacket(Client.DisconnectRequest(), reply); Media.Close(); } catch { } Media = null; Client = null; } }
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); } } }
/// <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"); } } }
/// <summary> /// Initialize optical head. /// </summary> void InitializeOpticalHead() { if (!UseOpticalHead) { 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); 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); 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); } } 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); } }