private void Form1_Load(object sender, EventArgs e) { try { gxTerminal1 = new GXTerminal(); gxTerminal1.Settings = GXTerminalSample.Properties.Settings.Default.MediaSetting; gxTerminal1.Trace = TraceLevel.Verbose; gxTerminal1.OnTrace += new TraceEventHandler(gxTerminal1_OnTrace); gxTerminal1.OnError += new ErrorEventHandler(gxTerminal1_OnError); gxTerminal1.OnReceived += new ReceivedEventHandler(gxTerminal1_OnReceived); gxTerminal1.OnMediaStateChange += new MediaStateChangeEventHandler(gxTerminal1_OnMediaStateChange); PropertiesBtn.Enabled = true; if (gxTerminal1.IsOpen) { gxTerminal1_OnMediaStateChange(this, new MediaStateEventArgs(MediaState.Open)); } else { gxTerminal1_OnMediaStateChange(this, new MediaStateEventArgs(MediaState.Closed)); } } catch (Exception Ex) { MessageBox.Show(Ex.Message); } }
private void PortNameCB_SelectedIndexChanged(object sender, EventArgs e) { if (BaudRatePanel.Enabled) { this.BaudRateCB.Items.Clear(); BaudRateCB.DropDownStyle = ComboBoxStyle.DropDownList; //User can't change values when connection is open. if (Target.IsOpen) { BaudRateCB.Items.Add(Target.BaudRate); this.BaudRateCB.SelectedItem = 0; } else { foreach (int it in GXTerminal.GetAvailableBaudRates(PortNameCB.Text)) { if (it == 0) { BaudRateCB.DropDownStyle = ComboBoxStyle.DropDown; } else { this.BaudRateCB.Items.Add(it); } } this.BaudRateCB.SelectedItem = Target.BaudRate; } } }
private async void DoWork(object ínfo) { //Give some time DB server to start up. Thread.Sleep(1000); GetNextTaskResponse ret = null; System.Net.Http.HttpResponseMessage response; //Don't wait reply. It might that DB server is not up yet. if (ínfo != null) { using (response = await client.PostAsJsonAsync(Startup.ServerAddress + "/api/reader/AddReader", new AddReader() { Reader = ínfo as GXReaderInfo })) { Helpers.CheckStatus(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; GXDLMSReader reader; //Read frame counter from the meter. if (dev.Security != 0) { cl = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, 16, dev.PhysicalAddress, Authentication.None, null, (InterfaceType)dev.InterfaceType); reader = new GXDLMSReader(cl, media, _logger); 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, dev.PhysicalAddress, (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 = (Security)dev.Security; reader = new GXDLMSReader(cl, media, _logger); 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.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, media, 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 ex) { 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); } } }
public ReceiveThread(GXTerminal parent) { Closing = new ManualResetEvent(false); m_Parent = parent; }
/// <summary> /// Constructor. /// </summary> public Settings(GXTerminal target) { InitializeComponent(); Target = target; }
public DevicePropertiesForm(GXManufacturerCollection manufacturers, GXDLMSDevice dev) { try { InitializeComponent(); SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication, Security.Encryption, Security.AuthenticationEncryption }); NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp }); this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged); NetworkSettingsGB.Width = this.Width - NetworkSettingsGB.Left; SerialSettingsGB.Bounds = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds; ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed; Manufacturers = manufacturers; //OK button is not enabled if there are no manufacturers. if (Manufacturers.Count == 0) { OKBtn.Enabled = false; } //Show supported services tab only when they are read. if (dev == null || dev.Comm.client.SNSettings == null && dev.Comm.client.LNSettings == null) { DeviceTab.TabPages.Remove(SupportedServicesTab); } else { object settings = null; if (dev.Comm.client.UseLogicalNameReferencing) { settings = dev.Comm.client.LNSettings; } else { settings = dev.Comm.client.SNSettings; } if (settings != null) { SupportedServicesGrid.SelectedObject = settings; foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(settings)) { ReadOnlyAttribute att = (ReadOnlyAttribute)it.Attributes[typeof(ReadOnlyAttribute)]; if (att != null) { FieldInfo[] f = att.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); f[0].SetValue(att, true); } } } } Device = dev; StartProtocolCB.Items.Add(StartProtocolType.IEC); StartProtocolCB.Items.Add(StartProtocolType.DLMS); int pos = 0; foreach (GXManufacturer it in Manufacturers) { int index = this.ManufacturerCB.Items.Add(it); if (it.Name == GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer) { pos = index; } } if (Device == null) { Device = new GXDLMSDevice(null); //Select first manufacturer. if (Manufacturers.Count != 0) { ManufacturerCB.SelectedIndex = pos; } } else { foreach (GXManufacturer it in this.ManufacturerCB.Items) { if (string.Compare(it.Identification, Device.Manufacturer, true) == 0) { this.ManufacturerCB.SelectedItem = it; break; } } this.VerboseModeCB.Checked = dev.Verbose; this.NameTB.Text = dev.Name; SelectedMedia = dev.Media; UseRemoteSerialCB.Checked = Device.UseRemoteSerial; StartProtocolCB.SelectedItem = Device.StartProtocol; PhysicalServerAddressTB.Value = Convert.ToDecimal(Device.PhysicalAddress); LogicalServerAddressTB.Value = Convert.ToDecimal(Device.LogicalAddress); this.ClientAddTB.Value = Convert.ToDecimal(Convert.ToUInt32(Device.ClientAddress)); WaitTimeTB.Value = Device.WaitTime; SecurityCB.SelectedItem = dev.Security; SystemTitleTB.Text = dev.SystemTitle; BlockCipherKeyTB.Text = dev.BlockCipherKey; AuthenticationKeyTB.Text = dev.AuthenticationKey; UseUtcTimeZone.Checked = Device.UtcTimeZone; } ManufacturerCB.DrawMode = MediasCB.DrawMode = DrawMode.OwnerDrawFixed; Gurux.Net.GXNet net = new Gurux.Net.GXNet(); //Initialize network settings. if (SelectedMedia is GXNet) { this.MediasCB.Items.Add(SelectedMedia); net.Protocol = Gurux.Net.NetworkType.Tcp; this.HostNameTB.Text = ((GXNet)SelectedMedia).HostName; this.PortTB.Text = ((GXNet)SelectedMedia).Port.ToString(); NetProtocolCB.SelectedItem = ((GXNet)SelectedMedia).Protocol; } else { NetProtocolCB.SelectedItem = net.Protocol = Gurux.Net.NetworkType.Tcp; this.MediasCB.Items.Add(net); } //Set maximum baud rate. GXSerial serial = new GXSerial(); foreach (int it in serial.GetAvailableBaudRates("")) { if (it != 0) { MaximumBaudRateCB.Items.Add(it); } } if (Device.MaximumBaudRate == 0) { UseMaximumBaudRateCB.Checked = false; UseMaximumBaudRateCB_CheckedChanged(null, null); } else { UseMaximumBaudRateCB.Checked = true; this.MaximumBaudRateCB.SelectedItem = Device.MaximumBaudRate; } if (SelectedMedia is GXSerial) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.SerialPortCB.SelectedItem = ((GXSerial)SelectedMedia).PortName; } } else { //Initialize serial settings. string[] ports = GXSerial.GetPortNames(); this.SerialPortCB.Items.AddRange(ports); if (ports.Length != 0) { serial.PortName = ports[0]; } if (((GXManufacturer)ManufacturerCB.SelectedItem).StartProtocol == StartProtocolType.DLMS) { serial.BaudRate = 9600; serial.DataBits = 8; serial.Parity = Parity.None; serial.StopBits = StopBits.One; } else { serial.BaudRate = 300; serial.DataBits = 7; serial.Parity = Parity.Even; serial.StopBits = StopBits.One; } this.MediasCB.Items.Add(serial); } if (SelectedMedia is Gurux.Terminal.GXTerminal) { this.MediasCB.Items.Add(SelectedMedia); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { this.TerminalPortCB.SelectedItem = ((Gurux.Terminal.GXTerminal)SelectedMedia).PortName; } this.TerminalPhoneNumberTB.Text = ((Gurux.Terminal.GXTerminal)SelectedMedia).PhoneNumber; } else { //Initialize terminal settings. Gurux.Terminal.GXTerminal termial = new Gurux.Terminal.GXTerminal(); string[] ports = GXTerminal.GetPortNames(); this.TerminalPortCB.Items.AddRange(ports); if (ports.Length != 0) { termial.PortName = ports[0]; } termial.BaudRate = 9600; termial.DataBits = 8; termial.Parity = Parity.None; termial.StopBits = StopBits.One; this.TerminalPhoneNumberTB.Text = termial.PhoneNumber; //termial.InitializeCommands = "AT+CBST=71,0,1\r\n"; this.MediasCB.Items.Add(termial); } //Select first media if medis is not selected. if (SelectedMedia == null) { SelectedMedia = (Gurux.Common.IGXMedia) this.MediasCB.Items[0]; } this.MediasCB.SelectedItem = SelectedMedia; if (!string.IsNullOrEmpty(Device.Password)) { this.PasswordTB.Text = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Device.Password, Password.Key)); } if (dev != null) { this.UseLNCB.Checked = dev.UseLogicalNameReferencing; } this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged); bool bConnected = Device.Media != null && Device.Media.IsOpen; SerialPortCB.Enabled = AdvancedBtn.Enabled = ManufacturerCB.Enabled = MediasCB.Enabled = AuthenticationCB.Enabled = UseRemoteSerialCB.Enabled = OKBtn.Enabled = !bConnected; HostNameTB.ReadOnly = PortTB.ReadOnly = PasswordTB.ReadOnly = WaitTimeTB.ReadOnly = PhysicalServerAddressTB.ReadOnly = NameTB.ReadOnly = bConnected; } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
void IGXPropertyPage.Initialize() { //Update texts. this.Text = Gurux.Terminal.Properties.Resources.SettingsTxt; this.NumberLbl.Text = Gurux.Terminal.Properties.Resources.PhoneNumberTxt; this.PortNameLbl.Text = Gurux.Terminal.Properties.Resources.PortNameTxt; this.BaudRateLbl.Text = Gurux.Terminal.Properties.Resources.BaudRateTxt; this.DataBitsLbl.Text = Gurux.Terminal.Properties.Resources.DataBitsTxt; this.ParityLbl.Text = Gurux.Terminal.Properties.Resources.ParityTxt; this.StopBitsLbl.Text = Gurux.Terminal.Properties.Resources.StopBitsTxt; this.NumberTB.Text = Target.PhoneNumber; this.ServerCB.Checked = Target.Server; NumberPanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.PhoneNumber) != 0; //Server is disabled because it is not work correctly yet. //ServerPanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.Server) != 0; ServerPanel.Enabled = false; //Hide controls which user do not want to show. PortNamePanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.PortName) != 0; if (PortNamePanel.Enabled) { if (Target.AvailablePorts != null) { PortNameCB.Items.AddRange(Target.AvailablePorts); } else { PortNameCB.Items.AddRange(GXTerminal.GetPortNames()); } if (this.PortNameCB.Items.Contains(Target.PortName)) { this.PortNameCB.SelectedItem = Target.PortName; } else { this.PortNameCB.SelectedIndex = 0; } } BaudRatePanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.BaudRate) != 0; if (BaudRatePanel.Enabled) { PortNameCB_SelectedIndexChanged(null, null); this.BaudRateCB.SelectedItem = Target.BaudRate; } DataBitsPanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.DataBits) != 0; if (DataBitsPanel.Enabled) { this.DataBitsCB.Items.Add(7); this.DataBitsCB.Items.Add(8); this.DataBitsCB.SelectedItem = Target.DataBits; } ParityPanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.Parity) != 0; if (ParityPanel.Enabled) { this.ParityCB.Items.Add(System.IO.Ports.Parity.None); this.ParityCB.Items.Add(System.IO.Ports.Parity.Odd); this.ParityCB.Items.Add(System.IO.Ports.Parity.Even); this.ParityCB.Items.Add(System.IO.Ports.Parity.Mark); this.ParityCB.Items.Add(System.IO.Ports.Parity.Space); this.ParityCB.SelectedItem = Target.Parity; } StopBitsPanel.Enabled = (Target.ConfigurableSettings & AvailableMediaSettings.StopBits) != 0; if (StopBitsPanel.Enabled) { this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.None); this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.One); this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.OnePointFive); this.StopBitsCB.Items.Add(System.IO.Ports.StopBits.Two); this.StopBitsCB.SelectedItem = Target.StopBits; } Dirty = false; }