public void UpdateManufactureSettings(string id) { if (Manufacturer != null && string.Compare(Manufacturer.Identification, id, true) != 0) { throw new Exception(string.Format("Manufacturer type does not match. Manufacturer is {0} and it should be {1}.", id, Manufacturer.Identification)); } if (this.Media is GXNet && Manufacturer.UseIEC47) { Client.InterfaceType = InterfaceType.WRAPPER; } else { Client.InterfaceType = InterfaceType.HDLC; } Client.UseLogicalNameReferencing = Manufacturer.UseLogicalNameReferencing; //If network media is used check is manufacturer supporting IEC 62056-47 GXServerAddress server = Manufacturer.GetServer(HDLCAddressing); Client.ClientAddress = Manufacturer.GetAuthentication(Client.Authentication).ClientAddress; if (HDLCAddressing == HDLCAddressType.SerialNumber) { Client.ServerAddress = GXDLMSClient.GetServerAddress(server.PhysicalAddress, server.Formula); } else { Client.ServerAddress = GXDLMSClient.GetServerAddress(server.LogicalAddress, server.PhysicalAddress); } }
static void Main(string[] args) { //Create Network media component and start listen events. //4059 is Official DLMS port. try { GXDLMSClient cl = new GXDLMSClient(false, 16, GXDLMSClient.GetServerAddress(123), Authentication.None, null, InterfaceType.HDLC); /////////////////////////////////////////////////////////////////////// //Create Gurux DLMS server component for Short Name and start listen events. GXDLMSServerSN SNServer = new GXDLMSServerSN(); SNServer.Initialize(4060); Console.WriteLine("Short Name DLMS Server in port 4060."); /////////////////////////////////////////////////////////////////////// //Create Gurux DLMS server component for Short Name and start listen events. GXDLMSServerLN LNServer = new GXDLMSServerLN(); LNServer.Initialize(4061); Console.WriteLine("Logical Name DLMS Server in port 4061."); /////////////////////////////////////////////////////////////////////// //Create Gurux DLMS server component for Short Name and start listen events. GXDLMSServerSN_47 SN_47Server = new GXDLMSServerSN_47(); SN_47Server.Initialize(4062); Console.WriteLine("Short Name DLMS Server with IEC 62056-47 in port 4062."); /////////////////////////////////////////////////////////////////////// //Create Gurux DLMS server component for Short Name and start listen events. GXDLMSServerLN_47 LN_47Server = new GXDLMSServerLN_47(); LN_47Server.Initialize(4063); Console.WriteLine("Logical Name DLMS Server with IEC 62056-47 in port 4063."); while (Console.ReadKey().Key != ConsoleKey.Enter) { ; } Console.WriteLine("Closing servers."); //Close servers. SNServer.Close(); LNServer.Close(); SN_47Server.Close(); LN_47Server.Close(); Console.WriteLine("Servers closed."); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static int GetParameters(string[] args, Settings settings) { string[] tmp; List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:iIt:a:wP:g:S:C:n:v:o:T:A:B:D:d:l:F:"); GXNet net = null; foreach (GXCmdParameter it in parameters) { switch (it.Tag) { case 'w': settings.client.InterfaceType = InterfaceType.WRAPPER; break; case 'r': if (string.Compare(it.Value, "sn", true) == 0) { settings.client.UseLogicalNameReferencing = false; } else if (string.Compare(it.Value, "ln", true) == 0) { settings.client.UseLogicalNameReferencing = true; } else { throw new ArgumentException("Invalid reference option."); } break; case 'h': //Host address. if (settings.media == null) { settings.media = new GXNet(); } net = settings.media as GXNet; net.HostName = it.Value; break; case 't': //Trace. try { settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value); } catch (Exception) { throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)"); } break; case 'p': //Port. if (settings.media == null) { settings.media = new GXNet(); } net = settings.media as GXNet; net.Port = int.Parse(it.Value); break; case 'P': //Password settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value); break; case 'i': //IEC. settings.iec = true; break; case 'I': //AutoIncreaseInvokeID. settings.client.AutoIncreaseInvokeID = true; break; case 'v': settings.invocationCounter = it.Value.Trim(); Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter); break; case 'g': //Get (read) selected objects. foreach (string o in it.Value.Split(new char[] { ';', ',' })) { tmp = o.Split(new char[] { ':' }); if (tmp.Length != 2) { throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index."); } settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim()))); } break; case 'S': //Serial Port settings.media = new GXSerial(); GXSerial serial = settings.media as GXSerial; tmp = it.Value.Split(':'); serial.PortName = tmp[0]; if (tmp.Length > 1) { serial.BaudRate = int.Parse(tmp[1]); serial.DataBits = int.Parse(tmp[2].Substring(0, 1)); serial.Parity = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2)); serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1)); } else { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; } break; case 'a': try { if (string.Compare("None", it.Value, true) == 0) { settings.client.Authentication = Authentication.None; } else if (string.Compare("Low", it.Value, true) == 0) { settings.client.Authentication = Authentication.Low; } else if (string.Compare("High", it.Value, true) == 0) { settings.client.Authentication = Authentication.High; } else if (string.Compare("HighMd5", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighMD5; } else if (string.Compare("HighSha1", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighSHA1; } else if (string.Compare("HighSha256", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighSHA256; } else if (string.Compare("HighGMac", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighGMAC; } else { throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)"); } } catch (Exception) { throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)"); } break; case 'C': try { settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value)); } catch (Exception) { throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)"); } break; case 'T': settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value); break; case 'A': settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value); break; case 'B': settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value); break; case 'D': settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value); break; case 'F': settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim()); break; case 'o': settings.outputFile = it.Value; break; case 'd': try { settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value); if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia) { settings.client.UseUtc2NormalTime = true; } } catch (Exception) { throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)"); } break; case 'c': settings.client.ClientAddress = int.Parse(it.Value); break; case 's': if (settings.client.ServerAddress != 1) { settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value)); } else { settings.client.ServerAddress = int.Parse(it.Value); } break; case 'l': settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress); break; case 'n': settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value)); break; case '?': switch (it.Tag) { case 'c': throw new ArgumentException("Missing mandatory client option."); case 's': throw new ArgumentException("Missing mandatory server option."); case 'h': throw new ArgumentException("Missing mandatory host name option."); case 'p': throw new ArgumentException("Missing mandatory port option."); case 'r': throw new ArgumentException("Missing mandatory reference option."); case 'a': throw new ArgumentException("Missing mandatory authentication option."); case 'S': throw new ArgumentException("Missing mandatory Serial port option."); case 't': throw new ArgumentException("Missing mandatory trace option."); case 'g': throw new ArgumentException("Missing mandatory OBIS code option."); case 'C': throw new ArgumentException("Missing mandatory Ciphering option."); case 'v': throw new ArgumentException("Missing mandatory invocation counter logical name option."); case 'T': throw new ArgumentException("Missing mandatory system title option."); case 'A': throw new ArgumentException("Missing mandatory authentication key option."); case 'B': throw new ArgumentException("Missing mandatory block cipher key option."); case 'D': throw new ArgumentException("Missing mandatory dedicated key option."); case 'F': throw new ArgumentException("Missing mandatory frame counter option."); case 'd': throw new ArgumentException("Missing mandatory DLMS standard option."); default: ShowHelp(); return(1); } default: ShowHelp(); return(1); } } if (settings.media == null) { ShowHelp(); return(1); } return(0); }
public static int GetParameters(string[] args, Settings settings) { string[] tmp; List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:i:It:a:P:g:S:C:n:v:o:T:A:B:D:d:l:F:K:k:m:"); GXNet net = null; foreach (GXCmdParameter it in parameters) { switch (it.Tag) { case 'r': if (string.Compare(it.Value, "sn", true) == 0) { settings.client.UseLogicalNameReferencing = false; } else if (string.Compare(it.Value, "ln", true) == 0) { settings.client.UseLogicalNameReferencing = true; } else { throw new ArgumentException("Invalid reference option."); } break; case 'h': //Host address. if (settings.media == null) { settings.media = new GXNet(); } net = settings.media as GXNet; net.HostName = it.Value; break; case 't': //Trace. try { settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value); } catch (Exception) { throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)"); } break; case 'p': //Port. if (settings.media == null) { settings.media = new GXNet(); } net = settings.media as GXNet; net.Port = int.Parse(it.Value); break; case 'P': //Password settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value); break; case 'i': try { settings.client.InterfaceType = (InterfaceType)Enum.Parse(typeof(InterfaceType), it.Value); settings.client.Plc.Reset(); } catch (Exception) { throw new ArgumentException("Invalid interface type option. (HDLC, WRAPPER, HdlcWithModeE, Plc, PlcHdlc)"); } break; case 'I': //AutoIncreaseInvokeID. settings.client.AutoIncreaseInvokeID = true; break; case 'v': settings.invocationCounter = it.Value.Trim(); Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter); break; case 'g': //Get (read) selected objects. foreach (string o in it.Value.Split(new char[] { ';', ',' })) { tmp = o.Split(new char[] { ':' }); if (tmp.Length != 2) { throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index."); } settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim()))); } break; case 'S': //Serial Port settings.media = new GXSerial(); GXSerial serial = settings.media as GXSerial; tmp = it.Value.Split(':'); serial.PortName = tmp[0]; if (tmp.Length > 1) { serial.BaudRate = int.Parse(tmp[1]); serial.DataBits = int.Parse(tmp[2].Substring(0, 1)); serial.Parity = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2)); serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1)); } else { if (settings.client.InterfaceType == InterfaceType.HdlcWithModeE) { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = Parity.Even; serial.StopBits = StopBits.One; } else { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; } } break; case 'a': try { if (string.Compare("None", it.Value, true) == 0) { settings.client.Authentication = Authentication.None; } else if (string.Compare("Low", it.Value, true) == 0) { settings.client.Authentication = Authentication.Low; } else if (string.Compare("High", it.Value, true) == 0) { settings.client.Authentication = Authentication.High; } else if (string.Compare("HighMd5", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighMD5; } else if (string.Compare("HighSha1", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighSHA1; } else if (string.Compare("HighSha256", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighSHA256; } else if (string.Compare("HighGMac", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighGMAC; } else if (string.Compare("HighECDSA", it.Value, true) == 0) { settings.client.Authentication = Authentication.HighECDSA; } else { throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)"); } } catch (Exception) { throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)"); } break; case 'C': try { settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value)); } catch (Exception) { throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)"); } break; case 'T': settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value); break; case 'A': settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value); break; case 'B': settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value); break; case 'D': settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value); break; case 'F': settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim()); break; case 'K': GXPkcs8 cert1 = GXPkcs8.Load(it.Value); settings.client.Ciphering.SigningKeyPair = new KeyValuePair <GXPrivateKey, GXPublicKey>(cert1.PrivateKey, cert1.PublicKey); Console.WriteLine("Client Private key: " + GXDLMSTranslator.ToHex(cert1.PrivateKey.RawValue)); Console.WriteLine("Client Public key: " + GXDLMSTranslator.ToHex(cert1.PublicKey.RawValue)); break; case 'k': GXx509Certificate cert = GXx509Certificate.Load(it.Value); if ((cert.KeyUsage & ASN.Enums.KeyUsage.DigitalSignature) == 0) { throw new Exception("This certificate is not used for digital signature."); } settings.client.Ciphering.PublicKeys.Add(new KeyValuePair <CertificateType, GXx509Certificate>(CertificateType.DigitalSignature, cert)); string[] sn = cert.Subject.Split('='); if (sn.Length != 2) { throw new ArgumentOutOfRangeException("Invalid public key subject."); } settings.client.Ciphering.SystemTitle = GXDLMSTranslator.HexToBytes(sn[1]); Console.WriteLine("Server Public key: " + GXDLMSTranslator.ToHex(cert.PublicKey.RawValue)); break; case 'o': settings.outputFile = it.Value; break; case 'd': try { settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value); if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia) { settings.client.UseUtc2NormalTime = true; } } catch (Exception) { throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)"); } break; case 'c': settings.client.ClientAddress = int.Parse(it.Value); break; case 's': if (settings.client.ServerAddress != 1) { settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value)); } else { settings.client.ServerAddress = int.Parse(it.Value); } break; case 'l': settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress); break; case 'n': settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value)); break; case 'm': settings.client.Plc.MacDestinationAddress = UInt16.Parse(it.Value); break; case '?': switch (it.Tag) { case 'c': throw new ArgumentException("Missing mandatory client option."); case 's': throw new ArgumentException("Missing mandatory server option."); case 'h': throw new ArgumentException("Missing mandatory host name option."); case 'p': throw new ArgumentException("Missing mandatory port option."); case 'r': throw new ArgumentException("Missing mandatory reference option."); case 'a': throw new ArgumentException("Missing mandatory authentication option."); case 'S': throw new ArgumentException("Missing mandatory Serial port option."); case 't': throw new ArgumentException("Missing mandatory trace option."); case 'g': throw new ArgumentException("Missing mandatory OBIS code option."); case 'C': throw new ArgumentException("Missing mandatory Ciphering option."); case 'v': throw new ArgumentException("Missing mandatory invocation counter logical name option."); case 'T': throw new ArgumentException("Missing mandatory system title option."); case 'A': throw new ArgumentException("Missing mandatory authentication key option."); case 'B': throw new ArgumentException("Missing mandatory block cipher key option."); case 'D': throw new ArgumentException("Missing mandatory dedicated key option."); case 'F': throw new ArgumentException("Missing mandatory frame counter option."); case 'd': throw new ArgumentException("Missing mandatory DLMS standard option."); case 'K': throw new ArgumentException("Missing mandatory private key file option."); case 'k': throw new ArgumentException("Missing mandatory public key file option."); case 'l': throw new ArgumentException("Missing mandatory logical server address option."); case 'm': throw new ArgumentException("Missing mandatory MAC destination address option."); default: ShowHelp(); return(1); } default: ShowHelp(); return(1); } } if (settings.media == null) { ShowHelp(); return(1); } return(0); }
private async void DoWork() { //Give some time DB server to start up. Thread.Sleep(1000); GetNextTaskResponse ret = null; System.Net.Http.HttpResponseMessage response; _logger.LogInformation("Reader Service is started."); while (!_cancellationToken.IsCancellationRequested) { try { using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask())) { Helpers.CheckStatus(response); ret = await response.Content.ReadAsAsync <GetNextTaskResponse>(); } if (ret.Tasks != null) { int pos = 0; GXDevice dev; GXDLMSSecureClient cl; using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices() { Ids = new[] { ret.Tasks[0].Object.DeviceId } })) { Helpers.CheckStatus(response); ListDevicesResponse r = await response.Content.ReadAsAsync <ListDevicesResponse>(); if (r.Devices == null || r.Devices.Length == 0) { continue; } dev = r.Devices[0]; } IGXMedia media; if (string.Compare(dev.MediaType, typeof(GXNet).FullName, true) == 0) { media = new GXNet(); } else if (string.Compare(dev.MediaType, typeof(GXSerial).FullName, true) == 0) { media = new GXSerial(); } else if (string.Compare(dev.MediaType, typeof(GXTerminal).FullName, true) == 0) { media = new GXTerminal(); } else { Type type = Type.GetType(dev.MediaType); if (type == null) { string ns = ""; pos = dev.MediaType.LastIndexOf('.'); if (pos != -1) { ns = dev.MediaType.Substring(0, pos); } foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.GetName().Name == ns) { if (assembly.GetType(dev.MediaType, false, true) != null) { type = assembly.GetType(dev.MediaType); } } } } if (type == null) { throw new Exception("Invalid media type: " + dev.MediaType); } media = (IGXMedia)Activator.CreateInstance(type); } if (media == null) { throw new Exception("Unknown media type '" + dev.MediaType + "'."); } media.Settings = dev.MediaSettings; int deviceAddress; if (dev.HDLCAddressing == ManufacturerSettings.HDLCAddressType.SerialNumber) { deviceAddress = GXDLMSClient.GetServerAddressFromSerialNumber(dev.PhysicalAddress, dev.LogicalAddress); } else { if (dev.LogicalAddress != 0 && (dev.InterfaceType == InterfaceType.HDLC || dev.InterfaceType == InterfaceType.HdlcWithModeE)) { deviceAddress = GXDLMSClient.GetServerAddress(dev.LogicalAddress, dev.PhysicalAddress); } else { deviceAddress = dev.PhysicalAddress; } } TraceLevel trace = _traceLevel; if (dev.TraceLevel > trace) { trace = dev.TraceLevel; } UInt64 devId = 0; if (dev.TraceLevel != TraceLevel.Off) { devId = dev.Id; } GXDLMSReader reader; //Read frame counter from the meter. if (dev.Security != 0) { cl = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, 16, deviceAddress, Authentication.None, null, (InterfaceType)dev.InterfaceType); reader = new GXDLMSReader(cl, media, _logger, trace, dev.WaitTime, dev.ResendCount, devId); media.Open(); reader.InitializeConnection(); //Read Innovation counter. GXDLMSData d = new GXDLMSData(dev.FrameCounter); reader.Read(d, 2); dev.InvocationCounter = 1 + Convert.ToUInt32(d.Value); reader.Disconnect(); media.Close(); } cl = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, deviceAddress, (Authentication)dev.Authentication, dev.Password, (InterfaceType)dev.InterfaceType); if (dev.HexPassword != null && dev.HexPassword.Length != 0) { cl.Password = dev.HexPassword; } cl.UseUtc2NormalTime = dev.UtcTimeZone; cl.Standard = dev.Standard; cl.Ciphering.SystemTitle = GXCommon.HexToBytes(dev.ClientSystemTitle); if (cl.Ciphering.SystemTitle != null && cl.Ciphering.SystemTitle.Length == 0) { cl.Ciphering.SystemTitle = null; } cl.Ciphering.BlockCipherKey = GXCommon.HexToBytes(dev.BlockCipherKey); if (cl.Ciphering.BlockCipherKey != null && cl.Ciphering.BlockCipherKey.Length == 0) { cl.Ciphering.BlockCipherKey = null; } cl.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey); if (cl.Ciphering.AuthenticationKey != null && cl.Ciphering.AuthenticationKey.Length == 0) { cl.Ciphering.AuthenticationKey = null; } cl.ServerSystemTitle = GXCommon.HexToBytes(dev.DeviceSystemTitle); if (cl.ServerSystemTitle != null && cl.ServerSystemTitle.Length == 0) { cl.ServerSystemTitle = null; } cl.Ciphering.InvocationCounter = dev.InvocationCounter; cl.Ciphering.Security = dev.Security; reader = new GXDLMSReader(cl, media, _logger, trace, dev.WaitTime, dev.ResendCount, devId); media.Open(); reader.InitializeConnection(); pos = 0; int count = ret.Tasks.Length; foreach (GXTask task in ret.Tasks) { ++pos; try { GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType); obj.Version = task.Object.Version; obj.LogicalName = task.Object.LogicalName; obj.ShortName = task.Object.ShortName; if (task.TaskType == TaskType.Write) { if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2) { cl.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow)); } else { cl.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data)); } reader.Write(obj, task.Index); } else if (task.TaskType == TaskType.Action) { reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None); } else if (task.TaskType == TaskType.Read) { //Reading the meter. if (task.Object.Attributes[0].DataType != 0) { obj.SetDataType(task.Index, (DataType)task.Object.Attributes[0].DataType); } if (task.Object.Attributes[0].UIDataType != 0) { obj.SetUIDataType(task.Index, (DataType)task.Object.Attributes[0].UIDataType); } Reader.Read(_logger, client, reader, task, obj); if (task.Object.Attributes[0].DataType == 0) { task.Object.Attributes[0].DataType = (int)obj.GetDataType(task.Index); if (task.Object.Attributes[0].UIDataType == 0) { task.Object.Attributes[0].UIDataType = (int)obj.GetUIDataType(task.Index); } UpdateDatatype u = new UpdateDatatype() { Items = new GXAttribute[] { task.Object.Attributes[0] } }; response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/Object/UpdateDatatype", u).Result; Helpers.CheckStatus(response); } } } catch (Exception ex) { task.Result = ex.Message; AddError error = new AddError(); error.Error = new GXError() { DeviceId = dev.Id, Error = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message }; _logger.LogError(error.Error.Error); using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error)) { Helpers.CheckStatus(response); await response.Content.ReadAsAsync <AddErrorResponse>(); } } task.End = DateTime.Now; //Close connection after last task is executed. //This must done because there might be new task to execute. if (count == pos) { try { reader.Close(); } catch (Exception ex) { task.Result = ex.Message; AddError error = new AddError(); error.Error = new GXError() { DeviceId = dev.Id, Error = "Failed to close the connection. " + ex.Message }; _logger.LogError(error.Error.Error); using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error)) { Helpers.CheckStatus(response); await response.Content.ReadAsAsync <AddErrorResponse>(); } } } //Update execution time. response = client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady() { Tasks = new GXTask[] { task } }).Result; Helpers.CheckStatus(response); } } else { try { using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/WaitChange", new WaitChange() { Change = TargetType.Tasks, Time = lastUpdated, WaitTime = _waitTime })) { Helpers.CheckStatus(response); { WaitChangeResponse r = await response.Content.ReadAsAsync <WaitChangeResponse>(); if (r.Time > lastUpdated) { lastUpdated = r.Time; } } } } catch (Exception) { if (!_cancellationToken.IsCancellationRequested) { break; } _cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(10)); } } } catch (Exception ex) { //If app is closing. if (_cancellationToken.IsCancellationRequested) { break; } if (ret == null) { _logger.LogError("Failed to connect to the DB server."); } else { AddError error = new AddError(); error.Error = new GXError() { DeviceId = ret.Tasks[0].Object.DeviceId, Error = "Failed to " + ret.Tasks[0].TaskType + " " + ret.Tasks[0].Object.LogicalName + ":" + ret.Tasks[0].Index + ". " + ex.Message }; using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error)) { if (ret.Tasks != null) { DateTime now = DateTime.Now; foreach (GXTask it in ret.Tasks) { it.Result = ex.Message; it.End = now; } response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady() { Tasks = ret.Tasks }); } } } _logger.LogError(ex.Message); } } }
private void OKBtn_Click(object sender, EventArgs e) { try { //Check security settings. if ((Security)SecurityCB.SelectedItem != Security.None || ((GXAuthentication)AuthenticationCB.SelectedItem).Type == Authentication.HighGMAC) { if (SystemTitleTB.Text.Trim().Length == 0) { throw new ArgumentException("Invalid system title."); } if (AuthenticationKeyTB.Text.Trim().Length == 0) { throw new ArgumentException("Invalid authentication key."); } if (BlockCipherKeyTB.Text.Trim().Length == 0) { throw new ArgumentException("Invalid block cipher key."); } } GXServerAddress server = (GXServerAddress)ServerAddressTypeCB.SelectedItem; if (server.HDLCAddress == HDLCAddressType.SerialNumber && PhysicalServerAddressTB.Value == 0) { throw new Exception("Invalid Serial Number."); } GXManufacturer man = (GXManufacturer)ManufacturerCB.SelectedItem; Target.client.Authentication = ((GXAuthentication)this.AuthenticationCB.SelectedItem).Type; if (Target.client.Authentication != Authentication.None) { if (PasswordAsciiCb.Checked) { Target.client.Password = ASCIIEncoding.ASCII.GetBytes(PasswordTB.Text); } else { Target.client.Password = GXDLMSTranslator.HexToBytes(this.PasswordTB.Text); } } else { Target.client.Password = null; } Target.media = SelectedMedia; if (SelectedMedia is GXSerial) { if (this.SerialPortCB.Text.Length == 0) { throw new Exception("Invalid serial port."); } ((GXSerial)SelectedMedia).PortName = this.SerialPortCB.Text; } else if (SelectedMedia is GXNet) { if (this.HostNameTB.Text.Length == 0) { throw new Exception("Invalid host name."); } ((GXNet)SelectedMedia).HostName = this.HostNameTB.Text; int port; if (!Int32.TryParse(this.PortTB.Text, out port)) { throw new Exception("Invalid port number."); } ((GXNet)SelectedMedia).Port = port; ((GXNet)SelectedMedia).Protocol = (NetworkType)NetProtocolCB.SelectedItem; } Properties.Settings.Default.Media = SelectedMedia.MediaType; Properties.Settings.Default.MediaSettings = SelectedMedia.Settings; Properties.Settings.Default.SelectedManufacturer = man.Identification; Properties.Settings.Default.WaitTime = Convert.ToInt32(WaitTimeTB.Value); Target.WaitTime = Properties.Settings.Default.WaitTime * 1000; GXAuthentication authentication = (GXAuthentication)AuthenticationCB.SelectedItem; HDLCAddressType HDLCAddressing = ((GXServerAddress)ServerAddressTypeCB.SelectedItem).HDLCAddress; Properties.Settings.Default.HDLCAddressing = (int)HDLCAddressing; Properties.Settings.Default.ClientAddress = Target.client.ClientAddress = Convert.ToInt32(ClientAddTB.Value); if (HDLCAddressing == HDLCAddressType.SerialNumber) { int address = Convert.ToInt32(PhysicalServerAddressTB.Value); Properties.Settings.Default.PhysicalServerAddress = address; Target.client.ServerAddress = GXDLMSClient.GetServerAddress(address); } else if (HDLCAddressing == HDLCAddressType.Default) { Properties.Settings.Default.PhysicalServerAddress = Convert.ToInt32(PhysicalServerAddressTB.Value); Properties.Settings.Default.LogicalServerAddress = Convert.ToInt32(LogicalServerAddressTB.Value); Target.client.ServerAddress = GXDLMSClient.GetServerAddress(Properties.Settings.Default.LogicalServerAddress, Properties.Settings.Default.PhysicalServerAddress); } Target.client.UseLogicalNameReferencing = this.UseLNCB.Checked; Target.iec = (StartProtocolType)this.StartProtocolCB.SelectedItem == StartProtocolType.IEC; Target.client.Ciphering.Security = (Security)SecurityCB.SelectedItem; Target.client.Ciphering.SystemTitle = GetAsHex(SystemTitleTB.Text, SystemTitleAsciiCb.Checked); Target.client.Ciphering.BlockCipherKey = GetAsHex(BlockCipherKeyTB.Text, BlockCipherKeyAsciiCb.Checked); Target.client.Ciphering.AuthenticationKey = GetAsHex(AuthenticationKeyTB.Text, AuthenticationKeyAsciiCb.Checked); Target.client.Ciphering.InvocationCounter = UInt32.Parse(InvocationCounterTB.Text); Target.client.CtoSChallenge = GXCommon.HexToBytes(ChallengeTB.Text); if (man.UseIEC47) { Target.client.InterfaceType = InterfaceType.WRAPPER; } UpdateConformance(); Properties.Settings.Default.Save(); } catch (Exception Ex) { this.DialogResult = DialogResult.None; MessageBox.Show(this, Ex.Message, Properties.Resources.CTT, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void UpdateSettings() { client.Authentication = this.parent.Authentication; client.InterfaceType = parent.InterfaceType; if (!string.IsNullOrEmpty(this.parent.Password)) { client.Password = CryptHelper.Decrypt(this.parent.Password, Password.Key); } else if (this.parent.HexPassword != null) { client.Password = CryptHelper.Decrypt(this.parent.HexPassword, Password.Key); } client.UseLogicalNameReferencing = this.parent.UseLogicalNameReferencing; client.UtcTimeZone = parent.UtcTimeZone; //If network media is used check is manufacturer supporting IEC 62056-47 if (client.InterfaceType == InterfaceType.WRAPPER && parent.UseRemoteSerial) { client.InterfaceType = InterfaceType.HDLC; } client.ClientAddress = parent.ClientAddress; if (parent.HDLCAddressing != HDLCAddressType.SerialNumber) { if (client.InterfaceType == InterfaceType.WRAPPER) { client.ServerAddress = Convert.ToInt32(parent.PhysicalAddress); } else { client.ServerAddress = GXDLMSClient.GetServerAddress(parent.LogicalAddress, Convert.ToInt32(parent.PhysicalAddress), parent.ServerAddressSize); client.ServerAddressSize = parent.ServerAddressSize; } } client.Ciphering.Security = parent.Security; if (parent.SystemTitle != null && parent.BlockCipherKey != null && parent.AuthenticationKey != null) { client.Ciphering.SystemTitle = GXCommon.HexToBytes(parent.SystemTitle); client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(parent.BlockCipherKey); client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(parent.AuthenticationKey); client.Ciphering.InvocationCounter = parent.InvocationCounter; } else { client.Ciphering.SystemTitle = null; client.Ciphering.BlockCipherKey = null; client.Ciphering.AuthenticationKey = null; client.Ciphering.InvocationCounter = 0; } if (!string.IsNullOrEmpty(parent.Challenge)) { client.CtoSChallenge = GXCommon.HexToBytes(parent.Challenge); } else { client.CtoSChallenge = null; } if (!string.IsNullOrEmpty(parent.DedicatedKey)) { client.Ciphering.DedicatedKey = GXCommon.HexToBytes(parent.DedicatedKey); } else { client.Ciphering.DedicatedKey = null; } client.Limits.WindowSizeRX = parent.WindowSizeRX; client.Limits.WindowSizeTX = parent.WindowSizeTX; client.Limits.UseFrameSize = parent.UseFrameSize; client.Limits.MaxInfoRX = parent.MaxInfoRX; client.Limits.MaxInfoTX = parent.MaxInfoTX; client.MaxReceivePDUSize = parent.PduSize; client.UserId = parent.UserId; client.Priority = parent.Priority; client.ServiceClass = parent.ServiceClass; if (parent.PreEstablished) { client.ServerSystemTitle = GXCommon.HexToBytes(parent.ServerSystemTitle); } }
public void UpdateManufactureSettings(string id) { if (!string.IsNullOrEmpty(this.parent.Manufacturer) && string.Compare(this.parent.Manufacturer, id, true) != 0) { throw new Exception(string.Format("Manufacturer type does not match. Manufacturer is {0} and it should be {1}.", id, this.parent.Manufacturer)); } GXManufacturer manufacturer = this.parent.Manufacturers.FindByIdentification(id); if (manufacturer == null) { throw new Exception("Unknown manufacturer " + id); } this.parent.Manufacturer = manufacturer.Identification; client.Authentication = this.parent.Authentication; client.InterfaceType = InterfaceType.HDLC; if (!string.IsNullOrEmpty(this.parent.Password)) { client.Password = CryptHelper.Decrypt(this.parent.Password, Password.Key); } else if (this.parent.HexPassword != null) { client.Password = CryptHelper.Decrypt(this.parent.HexPassword, Password.Key); } client.UseLogicalNameReferencing = this.parent.UseLogicalNameReferencing; client.UtcTimeZone = parent.UtcTimeZone; //Show media verbose. if (this.parent.Verbose && media.Trace != System.Diagnostics.TraceLevel.Verbose) { media.Trace = System.Diagnostics.TraceLevel.Verbose; media.OnTrace += new TraceEventHandler(Media_OnTrace); } else if (!this.parent.Verbose && media.Trace == System.Diagnostics.TraceLevel.Verbose) { media.Trace = System.Diagnostics.TraceLevel.Off; media.OnTrace -= new TraceEventHandler(Media_OnTrace); } //If network media is used check is manufacturer supporting IEC 62056-47 if (parent.UseWrapper && !parent.UseRemoteSerial && this.media is GXNet) { client.InterfaceType = InterfaceType.WRAPPER; } client.ClientAddress = parent.ClientAddress; if (parent.HDLCAddressing == HDLCAddressType.SerialNumber) { string formula = null; GXServerAddress server = manufacturer.GetServer(parent.HDLCAddressing); if (server != null) { formula = server.Formula; } client.ServerAddress = GXDLMSClient.GetServerAddress(Convert.ToInt32(parent.PhysicalAddress), formula); client.ServerAddressSize = 4; } else { if (client.InterfaceType == InterfaceType.WRAPPER) { client.ServerAddress = Convert.ToInt32(parent.PhysicalAddress); } else { client.ServerAddress = GXDLMSClient.GetServerAddress(parent.LogicalAddress, Convert.ToInt32(parent.PhysicalAddress)); GXServerAddress server = manufacturer.GetServer(parent.HDLCAddressing); if (server != null) { client.ServerAddressSize = (byte)server.Size; } } } client.Ciphering.Security = parent.Security; if (parent.SystemTitle != null && parent.BlockCipherKey != null && parent.AuthenticationKey != null) { client.Ciphering.SystemTitle = GXCommon.HexToBytes(parent.SystemTitle); client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(parent.BlockCipherKey); client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(parent.AuthenticationKey); client.Ciphering.InvocationCounter = parent.InvocationCounter; } else { client.Ciphering.SystemTitle = null; client.Ciphering.BlockCipherKey = null; client.Ciphering.AuthenticationKey = null; client.Ciphering.InvocationCounter = 0; } if (!string.IsNullOrEmpty(parent.Challenge)) { client.CtoSChallenge = GXCommon.HexToBytes(parent.Challenge); } else { client.CtoSChallenge = null; } }
public string GetCommandLineParameters() { StringBuilder sb = new StringBuilder(); if (communicator.media is GXNet n) { if (n.HostName == null) { n.Settings = MediaSettings; } sb.Append("-h " + n.HostName); sb.Append(" -p " + n.Port); } if (communicator.media is GXSerial s) { if (s.PortName == null) { s.Settings = MediaSettings; } sb.Append("-S " + s.PortName); sb.Append(":" + s.BaudRate); sb.Append(":" + s.DataBits); sb.Append(s.Parity); sb.Append(s.StopBits); } if (!UseLogicalNameReferencing) { sb.Append(" -r sn"); } if (InterfaceType != InterfaceType.HDLC) { sb.Append(" -i" + InterfaceType.ToString()); } if (ClientAddress != 16) { sb.Append(" -c " + ClientAddress); } if (HDLCAddressing == HDLCAddressType.Default) { if (PhysicalAddress != 1 && LogicalAddress != 0) { if (InterfaceType == InterfaceType.HDLC || InterfaceType == InterfaceType.HdlcWithModeE || InterfaceType == InterfaceType.PlcHdlc) { sb.Append(" -s " + GXDLMSClient.GetServerAddress(LogicalAddress, Convert.ToInt32(PhysicalAddress))); } else { sb.Append(" -s " + communicator.client.ServerAddress); } } } else if (HDLCAddressing == HDLCAddressType.SerialNumber) { if (PhysicalAddress != 1) { sb.Append(" -n " + PhysicalAddress); } } if (Authentication != Authentication.None) { sb.Append(" -a " + Authentication); if (!string.IsNullOrEmpty(Password)) { string pw = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Password, GXDLMSDirector.Password.Key)); if (!string.IsNullOrEmpty(pw)) { sb.Append(" -P " + pw); } } if (HexPassword != null && HexPassword.Length != 0) { sb.Append(" -P 0x" + ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(HexPassword, GXDLMSDirector.Password.Key))); } } if (Security != Security.None) { sb.Append(" -C " + Security); } if (SecuritySuite != SecuritySuite.Suite0) { sb.Append(" -V " + SecuritySuite); } if (Signing != Signing.None) { sb.Append(" -K " + Signing); } if (Authentication == Authentication.HighSHA256 || Authentication == Authentication.HighECDSA || Security != Security.None) { if (!string.IsNullOrEmpty(SystemTitle)) { sb.Append(" -T " + SystemTitle); } if (!string.IsNullOrEmpty(ServerSystemTitle)) { sb.Append(" -M " + ServerSystemTitle); } if (Security != Security.None) { if (!string.IsNullOrEmpty(AuthenticationKey)) { sb.Append(" -A " + AuthenticationKey); } if (!string.IsNullOrEmpty(BlockCipherKey)) { sb.Append(" -B " + BlockCipherKey); } if (!string.IsNullOrEmpty(DedicatedKey)) { sb.Append(" -D " + DedicatedKey); } } if (!string.IsNullOrEmpty(FrameCounter)) { sb.Append(" -v " + FrameCounter); } } if (Standard != Standard.DLMS) { sb.Append(" -d " + Standard); } if (InterfaceType == InterfaceType.HDLC || InterfaceType == InterfaceType.HdlcWithModeE) { if (GbtWindowSize != 1) { sb.Append(" -W " + GbtWindowSize); } if (WindowSizeRX != 128) { sb.Append(" -w " + WindowSizeRX); } if (MaxInfoTX != 1) { sb.Append(" -f " + MaxInfoRX); } } sb.Append(" -t Verbose"); return(sb.ToString()); }