void SaveParameters(object target, ulong id, List<GXParameter> parameters, GXDevice DeviceProfiles) { object templateTarget = DeviceProfiles.FindItemByID(id & 0xFFFF); PropertyDescriptorCollection templateProperties = TypeDescriptor.GetProperties(templateTarget); object value, templateValue; foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(target)) { //If value is not stored. DataMemberAttribute dm = it.Attributes[typeof(DataMemberAttribute)] as DataMemberAttribute; if (dm == null) { continue; } ValueAccessAttribute va = it.Attributes[typeof(ValueAccessAttribute)] as ValueAccessAttribute; if (va == null || va.RunTime != ValueAccessType.Edit) { continue; } //Ignore default values. value = it.GetValue(target); templateValue = templateProperties[it.Name].GetValue(templateTarget); if (!object.Equals(templateValue, value)) { parameters.Add(new GXParameter(id, it.Name, value, it.PropertyType)); } } }
public DeviceSettingsForm(GXDeviceManufacturerCollection manufacturers, GXDevice device) { Device = device; Manufacturers = new GXDeviceManufacturerCollection(); InitializeComponent(); AddManufacturers(manufacturers, Manufacturers); SettingsPanel.Dock = PropertyGrid.Dock = PresetList.Dock = CustomDeviceProfile.Dock = DockStyle.Fill; //Device type can not be changed after creation. This is for secure reasons. PresetCB.Enabled = CustomRB.Enabled = PresetList.Enabled = CustomDeviceProfile.Enabled = Device == null; CustomDeviceProfile.Visible = false; if (Device != null) { NameTB.Text = Device.Name; RefreshRateTp.Value = new DateTime(((long)Device.UpdateInterval) * 10000000 + RefreshRateTp.MinDate.Ticks); UpdateResendCnt(Device.ResendCount); UpdateWaitTime(Device.WaitTime); } else { RefreshRateTp.Value = new DateTime(((long)1) * 10000000 + RefreshRateTp.MinDate.Ticks); } //Add disabled actions. m_DisActions = new DisabledAction(Device == null ? DisabledActions.None : Device.DisabledActions); tabControl1.TabPages.Add(m_DisActions.DisabledActionsTB); this.Text = Gurux.DeviceSuite.Properties.Resources.DeviceSettingsTxt; this.GeneralTab.Text = Gurux.DeviceSuite.Properties.Resources.GeneralTxt; //Update helps from the resources. this.helpProvider1.SetHelpString(this.NameTB, Gurux.DeviceSuite.Properties.Resources.DeviceNameHelp); this.helpProvider1.SetHelpString(this.MediaCB, Gurux.DeviceSuite.Properties.Resources.MediaListHelp); this.helpProvider1.SetHelpString(this.RefreshRateTp, Gurux.DeviceSuite.Properties.Resources.RefreshRateHelp); this.helpProvider1.SetHelpString(this.OkBtn, Gurux.DeviceSuite.Properties.Resources.OKHelp); this.helpProvider1.SetHelpString(this.CancelBtn, Gurux.DeviceSuite.Properties.Resources.CancelHelp); }
/// <summary> /// Initializes a new instance of the ImportDlg class. /// </summary> /// <param name="gxAddIn">The currently used protocol addin.</param> /// <param name="gxDevice">The target device.</param> public GXImportDlg(System.Diagnostics.TraceLevel traceLevel, GXProtocolAddIn addIn, GXDevice device, bool fromDataCollector) { try { InitializeComponent(); Bitmap bm = Gurux.DeviceSuite.Properties.Resources.leaf; bm.MakeTransparent(); panel1.BackgroundImage = bm; TraceLevel = traceLevel; GXCommon.Owner = this; Start = new GXImportStartForm(addIn); Trace = new GXImportSearchForm(); Import = new GXImportPropertiesForm(); MediaSettings = new GXImportMediaForm(fromDataCollector); m_GXAddIn = addIn; m_GXDevice = device; UpdateResources(); //default settings m_ProtocolCustomPages.Add(Start); m_ProtocolCustomPages.Add(MediaSettings); m_ProtocolCustomPages.Add(Trace); m_ProtocolCustomPages.Add(Import); addIn.ModifyWizardPages(device, GXPropertyPageType.Import, m_ProtocolCustomPages); m_GXAddIn.OnProgress += new Gurux.Device.Editor.GXProtocolAddIn.ProgressEventHandler(OnProgress); m_GXAddIn.OnTrace += new Gurux.Device.Editor.GXProtocolAddIn.TraceEventHandler(OnTraceEvent); ChangePage(0); } catch (Exception Ex) { GXCommon.ShowError(this, Ex); this.DialogResult = DialogResult.None; } }
internal GXSerializedDevice(GXDevice device, GXDevice DeviceProfiles) { this.ID = device.ID; this.ProtocolName = device.ProtocolName; this.ProfileName = device.ProfileName; this.Profile = device.ProfileGuid; this.Name = device.Name; this.Guid = device.Guid; this.MediaType = device.GXClient.MediaType; this.MediaSettings = device.GXClient.MediaSettings; this.ResendCount = device.ResendCount; this.WaitTime = device.WaitTime; this.UpdateInterval = device.UpdateInterval; List<GXParameter> parameters = new List<GXParameter>(); SaveParameters(device, device.ID, parameters, DeviceProfiles); foreach (GXCategory cat in device.Categories) { SaveParameters(cat, cat.ID, parameters, DeviceProfiles); foreach (GXProperty prop in cat.Properties) { SaveParameters(prop, prop.ID, parameters, DeviceProfiles); } } foreach (GXTable table in device.Tables) { SaveParameters(table, table.ID, parameters, DeviceProfiles); } Parameters = parameters.ToArray(); }
public ImportSettings(GXDevice device) { InitializeComponent(); m_device = device as GXDLMSDevice; PasswordTB.ReadOnly = m_device.Authentication == Gurux.DLMS.Authentication.None; SerialNumberTB.ReadOnly = m_device.HDLCAddressing != HDLCAddressType.SerialNumber; PasswordTB.Text = m_device.Password; SerialNumberTB.Text = m_device.SerialNumber; }
/// <summary> /// Initializes a new instance of the DlmsTypeWizardDlg class. /// </summary> public DlmsTypeWizardDlg(GXDevice device, object target) { Target = target; InitializeComponent(); this.TopLevel = false; this.FormBorderStyle = FormBorderStyle.None; Device = device as GXDLMSDevice; UpdateResources(); }
/// <summary> /// Initializes a new instance of the IEC62056DeviceModeWizardDlg class. /// </summary> public IEC62056DeviceModeWizardDlg(GXDevice device) { InitializeComponent(); typeCb.Items.Add(Protocol.ModeA); typeCb.Items.Add(Protocol.ModeC); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; UpdateResources(); m_Device = (GXIEC62056Device)device; this.TopLevel = false; this.FormBorderStyle = FormBorderStyle.None; }
/// <summary> /// Initializes a new instance of the DlmsWizardPage1Dlg class. /// </summary> public DlmsWizardPage1Dlg(GXDevice device) { InitializeComponent(); UpdateResources(); AddressTypeCB.DrawMode = DrawMode.OwnerDrawFixed; this.TopLevel = false; this.FormBorderStyle = FormBorderStyle.None; m_Device = device as GXDLMSDevice; UpdateManufacturers(); this.authLevelCb.SelectedIndexChanged += new System.EventHandler(this.AuthLevelCb_SelectedIndexChanged); UpdatemanufactureSettings((m_Device).PhysicalAddress == null); this.manufacturerTypeCb.SelectedIndexChanged += new System.EventHandler(this.manufacturerTypeCb_SelectedIndexChanged); this.AddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.AddressTypeCB_SelectedIndexChanged); if (m_Device.PhysicalAddress != null) { UpdateOnlineBtn.Enabled = manufacturerTypeCb.Enabled = false; } }
/// <summary> /// Initialize connection. /// </summary> /// <returns>Returns connected device. Null if connection alreay exists.</returns> GXDevice InitializeConnection(GXSchedule schedule, GXDevice device) { lock (device.SyncRoot) { bool connected = (device.Status & DeviceStates.Connected) != 0; if (!connected) { int pos = -1; do { try { device.Connect(); //Increase count in case connection failed. if ((device.Status & DeviceStates.Connected) == 0) { ++pos; Thread.Sleep(schedule.ConnectionFailWaitTime); } } catch (Exception Ex) { device.NotifyError(schedule, Ex); ++pos; Thread.Sleep(schedule.ConnectionFailWaitTime); } } while ((device.Status & DeviceStates.Connected) == 0 && pos < schedule.ConnectionFailTryCount); if ((device.Status & DeviceStates.Connected) == 0) { throw new Exception(Resources.ConnectionFailed); } return device; } return null; } }
public void Next() { if (IsShown()) { if (NameTB.Text.Trim().Length == 0) { throw new Exception(Gurux.DeviceSuite.Properties.Resources.ErrNameEmptyTxt); } GXProtocolAddIn addIn = Gurux.Device.GXDeviceList.Protocols[ProtocolCB.Text]; Device = GXDevice.CreateDeviceProfiles(addIn, NameTB.Text); if (Device.IsRegistered()) { if (GXCommon.ShowQuestion(Gurux.DeviceSuite.Properties.Resources.OverregisterTxt) != DialogResult.Yes) { throw new Exception(Gurux.DeviceSuite.Properties.Resources.CancelTxt); } } GXCommunicationAttribute att = TypeDescriptor.GetAttributes(Device.AddIn)[typeof(GXCommunicationAttribute)] as GXCommunicationAttribute; if (att != null && att.PacketParserType != null) { Device.GXClient.PacketParser = Activator.CreateInstance(att.PacketParserType) as IGXPacketParser; } } }
/// <summary> /// New custom device type is selected. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CustomDeviceType_SelectedIndexChanged(object sender, EventArgs e) { try { if (CustomDeviceProfile.SelectedItems.Count == 1) { PresetList.SelectedItems.Clear(); GXDeviceProfile type = CustomDeviceProfile.SelectedItems[0] as GXDeviceProfile; if (Device == null || Device.ProtocolName != type.Protocol || Device.DeviceProfile != type.Name) { if (Device != null) { Device.Dispose(); } Device = GXDevice.Create(type.Protocol, type.Name, ""); UpdateMedias(); } } } catch (Exception ex) { GXCommon.ShowError(this, ex); } }
/// <summary> /// New preset device is selected. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PresetList_SelectedIndexChanged(object sender, EventArgs e) { try { if (PresetList.SelectedIndices.Count == 1) { CustomDeviceProfile.SelectedItems.Clear(); GXPublishedDeviceProfile type = PresetList.SelectedItems[0].Tag as GXPublishedDeviceProfile; GXDeviceVersion ver = type.Parent.Parent; GXDeviceModel model = ver.Parent.Parent; GXDeviceManufacturer man = model.Parent.Parent; ; if (Device != null) { Device.Dispose(); } Device = GXDevice.Create(man.Name, model.Name, ver.Name, type.PresetName, ""); UpdateMedias(); } } catch (Exception ex) { GXCommon.ShowError(this, ex); } }
public override void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media) { GXIEC62056Device dev = (GXIEC62056Device)device; ImportSelectionDlg dlg = addinPages[1] as ImportSelectionDlg; string deviceSerialNumber = dlg.DeviceSerialNumber; int waittime = dev.WaitTime; media.Open(); try { string data = "/?" + deviceSerialNumber + "!\r\n"; byte[] reply = IEC62056Parser.Identify(media, data, '\0', waittime); if (reply[0] != '/') { throw new Exception("Invalid reply."); } char baudRate = (char)reply[4]; string CModeBauds = "0123456789"; string BModeBauds = "ABCDEFGHI"; Protocol mode; if (CModeBauds.IndexOf(baudRate) != -1) { mode = Protocol.ModeC; } else if (BModeBauds.IndexOf(baudRate) != -1) { mode = Protocol.ModeB; } else { mode = Protocol.ModeA; baudRate = '0'; } if (reply[0] != '/') { throw new Exception("Import failed. Invalid reply."); } //If mode is not given. if (dev.Mode == Protocol.None) { dev.Mode = mode; } data = ASCIIEncoding.ASCII.GetString(reply.ToArray()); string manufacturer = new string(new char[] { (char)reply[1], (char)reply[2], (char)reply[3] }); if (dev.Mode == Protocol.ModeA) { data = (char)0x06 + "0" + baudRate + "0\r\n"; } else { data = (char)0x06 + "0" + baudRate + "1\r\n"; } //Note this sleep is in standard. Do not remove. if (media.MediaType == "Serial") { System.Threading.Thread.Sleep(200); } reply = IEC62056Parser.ParseHandshake(media, data, baudRate, waittime); string header, frame; IEC62056Parser.GetPacket(new List<byte>(reply), true, out header, out frame); System.Diagnostics.Debug.WriteLine(frame); if (header == "B0") { throw new Exception("Connection failed. Meter do not accept connection at the moment."); } //Password is asked. if (header == "P0") { System.Diagnostics.Debug.WriteLine("Password is asked."); } //Note this sleep is in standard. Do not remove. if (media.MediaType == "Serial") { System.Threading.Thread.Sleep(200); } if (dev.Mode == Protocol.ModeA) { GXCategory defaultCategory = new GXIEC62056ReadoutCategory(); defaultCategory.Name = "Readout"; device.Categories.Add(defaultCategory); } else { GXCategory defaultCategory = null; defaultCategory = new GXIEC62056Category(); defaultCategory.Name = "Properties"; device.Categories.Add(defaultCategory); foreach (string it in IEC62056Parser.GetGeneralOBISCodes()) { try { //Note this sleep is in standard. Do not remove. if (media is Gurux.Serial.GXSerial) { System.Threading.Thread.Sleep(200); } if (!it.StartsWith("P.")) { string value = IEC62056Parser.ReadValue(media, waittime, it + "()", 2); if (!Convert.ToString(value).StartsWith("ER")) { GXIEC62056Property prop = new GXIEC62056Property(); prop.AccessMode = AccessMode.Read; prop.ReadMode = dev.ReadMode; prop.WriteMode = dev.WriteMode; prop.Name = IEC62056Parser.GetDescription(it); prop.Data = it; prop.DataType = IEC62056Parser.GetDataType(it); if (prop.DataType == DataType.DateTime || prop.DataType == DataType.Date || prop.DataType == DataType.Time) { prop.ValueType = typeof(DateTime); } defaultCategory.Properties.Add(prop); TraceLine("Property " + prop.Name + " added."); } } else { object[][] rows; //Try to read last hour first. TimeSpan add = new TimeSpan(1, 0, 0); DateTime start = DateTime.Now.Add(-add); string[] columns = null; do { try { rows = IEC62056Parser.ReadTable(media, waittime, it, start, DateTime.Now, null, 5, 1, out columns); } catch { //If media is closed. if (!media.IsOpen) { break; } rows = new object[0][]; } if (rows.Length == 0) { if (add.TotalHours == 1) { //Try to read last day. add = new TimeSpan(1, 0, 0, 0); start = DateTime.Now.Add(-add).Date; } else if (add.TotalHours == 24) { //Try to read last week. add = new TimeSpan(7, 0, 0, 0); start = DateTime.Now.Add(-add).Date; } else if (add.TotalDays == 7) { //Try to read last month. add = new TimeSpan(31, 0, 0, 0); start = DateTime.Now.Add(-add).Date; } else if (add.TotalDays == 31) { //Read all. add = new TimeSpan(100, 0, 0, 0); start = DateTime.MinValue; } else { break; } //Note this sleep is in standard. Do not remove. if (media is Gurux.Serial.GXSerial) { System.Threading.Thread.Sleep(200); } } else { GXIEC62056Table table = new GXIEC62056Table(); table.Name = IEC62056Parser.GetDescription(it); table.AccessMode = AccessMode.Read; table.Data = it; table.ReadMode = 6; int index = -1; foreach (string col in columns) { GXIEC62056Property prop = new GXIEC62056Property(); prop.Name = col; //Mikko prop.Name = IEC62056Parser.GetDescription(col); prop.Data = col; prop.ValueType = rows[0][++index].GetType(); table.Columns.Add(prop); } device.Tables.Add(table); TraceLine("Property " + table.Name + " added."); break; } } while (rows.Length == 0); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } } } finally { if (media.MediaType == "Serial" || media.MediaType == "Terminal") { IEC62056Parser.Disconnect(media, 2); } media.Close(); } }
/// <summary> /// Export settings. /// </summary> /// <param name="device">A GXDevice that is the source of export.</param> /// <param name="trace">A TextBox to trace the process.</param> /// <returns>True if everything went fine, otherwise false.</returns> public virtual bool Export(GXDevice device, TextBox trace) { throw new NotImplementedException("Export"); }
/// <summary> /// Imports properties from the file. /// </summary> /// <param name="device">A GXDevice that is the target of import.</param> /// <param name="fileNames">An array of file names.</param> /// <returns>True if everything went fine, otherwise false.</returns> public virtual bool ImportFromFile(GXDevice device, List<string> fileNames) { throw new NotImplementedException("ImportFromFile"); }
/// <summary> /// Internal constructor. /// </summary> internal GXKeepalive(GXDevice parent) { Parent = parent; TransactionResets = true; m_Keepalive = new AutoResetEvent(false); }
/// <summary> /// Create new device template. /// </summary> public void NewTemplate() { try { //Ask save settings if device template is dirty. if (Device != null && Device.Dirty) { DialogResult ret = MessageBox.Show(ParentComponent, Gurux.DeviceSuite.Properties.Resources.SaveChangesQuestionTxt, Gurux.DeviceSuite.Properties.Resources.DeviceEditorTxt, MessageBoxButtons.YesNoCancel); if (ret == DialogResult.Cancel) { return; } else if (ret == DialogResult.Yes) { Save(); } } GXWizardDlg dlg = new GXWizardDlg(null, Manufacturers, null); if (dlg.ShowDialog(ParentComponent) == DialogResult.Cancel) { return; } Device = dlg.Target as GXDevice; Device.Save(Device.ProfilePath); Device.Register(); ShowProperties(Device); ParentComponent.CloseMenu.Enabled = true; ParentComponent.ExportMenu.Enabled = !System.Diagnostics.Debugger.IsAttached; ParentComponent.ImportMenu.Enabled = Device.AddIn.ImportFromDeviceEnabled; PropertyTree.SelectedNode = PropertyTree.Nodes[0]; PropertyTree.Focus(); ValidateTasks(); } catch (Exception Ex) { GXCommon.ShowError(ParentComponent, Ex); } finally { this.Cursor = Cursors.Default; } }
public void Initialize() { m_Device = Target as GXDevice; WaitTimeTb.Value = new DateTime(WaitTimeTb.MinDate.Ticks + (m_Device.WaitTime * 10000)); ResendCountTb.Text = m_Device.ResendCount.ToString(); }
public override void InitializeAfterImport(GXDevice device) { if (Gurux.DLMS.ManufacturerSettings.GXManufacturerCollection.IsFirstRun()) { Gurux.DLMS.ManufacturerSettings.GXManufacturerCollection.UpdateManufactureSettings(); } }
public void ShowProperties(GXDevice device) { PropertyTree.Nodes.Clear(); GXProtocolAddIn AddIn = device.AddIn; GXProtocolAddIn.VisibilityItems func = AddIn.ItemVisibility; //Show device properties TreeNode DevNode = PropertyTree.Nodes.Add(device.DeviceProfile); DevNode.SelectedImageIndex = DevNode.ImageIndex = 0; DevNode.Tag = device; ObjectToTreeNode[device] = DevNode; if ((func & GXProtocolAddIn.VisibilityItems.Tables) != 0) { //Add tables TreeNode TablesNode = DevNode.Nodes.Add(Gurux.DeviceSuite.Properties.Resources.TablesTxt); TablesNode.Tag = device.Tables; ObjectToTreeNode[device.Tables] = TablesNode; TablesNode.SelectedImageIndex = TablesNode.ImageIndex = 1; foreach (GXTable table in device.Tables) { TreeNode TableNode = TablesNode.Nodes.Add(table.Name); TableNode.SelectedImageIndex = TableNode.ImageIndex = 2; TableNode.Tag = table; ObjectToTreeNode[table] = TableNode; } } //Add categories if ((func & GXProtocolAddIn.VisibilityItems.Categories) != 0) { TreeNode CatsNode = DevNode.Nodes.Add(Gurux.DeviceSuite.Properties.Resources.CategoriesTxt); CatsNode.Tag = device.Categories; ObjectToTreeNode[device.Categories] = CatsNode; CatsNode.SelectedImageIndex = CatsNode.ImageIndex = 3; foreach (GXCategory cat in device.Categories) { TreeNode CatNode = CatsNode.Nodes.Add(cat.Name); CatNode.SelectedImageIndex = CatNode.ImageIndex = 4; CatNode.Tag = cat; ObjectToTreeNode[cat] = CatNode; //Add properties foreach (GXProperty Prop in cat.Properties) { TreeNode PropNode = CatNode.Nodes.Add(Prop.Name); PropNode.SelectedImageIndex = PropNode.ImageIndex = -1; PropNode.Tag = Prop; ObjectToTreeNode[Prop] = PropNode; } } } //Add notifies if ((func & GXProtocolAddIn.VisibilityItems.Events) != 0) { TreeNode NotifiesNode = DevNode.Nodes.Add(Gurux.DeviceSuite.Properties.Resources.NotifiesTxt); NotifiesNode.SelectedImageIndex = NotifiesNode.ImageIndex = 5; NotifiesNode.Tag = device.Events; ObjectToTreeNode[device.Events] = NotifiesNode; //New way. if ((func & GXProtocolAddIn.VisibilityItems.Tables) != 0) { //Add tables TreeNode TablesNode = NotifiesNode.Nodes.Add(Gurux.DeviceSuite.Properties.Resources.TablesTxt); TablesNode.Tag = device.Events.Tables; ObjectToTreeNode[device.Events.Tables] = TablesNode; TablesNode.SelectedImageIndex = TablesNode.ImageIndex = 1; foreach (GXTable table in device.Events.Tables) { TreeNode TableNode = TablesNode.Nodes.Add(table.Name); TableNode.SelectedImageIndex = TableNode.ImageIndex = 2; TableNode.Tag = table; ObjectToTreeNode[table] = TableNode; } } //Add categories if ((func & GXProtocolAddIn.VisibilityItems.Categories) != 0) { TreeNode CatsNode = NotifiesNode.Nodes.Add(Gurux.DeviceSuite.Properties.Resources.CategoriesTxt); CatsNode.Tag = device.Events.Categories; ObjectToTreeNode[device.Events.Categories] = CatsNode; CatsNode.SelectedImageIndex = CatsNode.ImageIndex = 3; foreach (GXCategory cat in device.Events.Categories) { TreeNode CatNode = CatsNode.Nodes.Add(cat.Name); CatNode.SelectedImageIndex = CatNode.ImageIndex = 4; CatNode.Tag = cat; ObjectToTreeNode[cat] = CatNode; //Add properties foreach (GXProperty Prop in cat.Properties) { TreeNode PropNode = CatNode.Nodes.Add(Prop.Name); PropNode.SelectedImageIndex = PropNode.ImageIndex = -1; PropNode.Tag = Prop; ObjectToTreeNode[Prop] = PropNode; } } } } if (PropertyTree.Nodes.Count > 0) { PropertyTree.Nodes[0].ExpandAll(); } }
void DeviceTransaction(GXSchedule schedule, GXDevice device, bool read) { try { ThreadPool.QueueUserWorkItem(new WaitCallback(SendDataThread), new object[] { this, schedule, device, read }); } catch (Exception Ex) { throw Ex; } }
public override void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media) { media.Eop = device.GXClient.Eop; GXDLT645Device dev = device as GXDLT645Device; dev.Parser.IgnoreFrame = false; Dictionary<ulong, object> items = GXDLT645Property.ReadDataID(); GXCategory cat = device.Categories.Find("Default"); if (cat == null) { cat = new GXCategory("Default"); device.Categories.Add(cat); } media.Open(); int count = 0; foreach (var it in items) { Progress(++count, items.Count); byte[] data = dev.Parser.ReadValue(it.Key); lock (media.Synchronous) { media.Send(data, null); ReceiveParameters<byte[]> p = new ReceiveParameters<byte[]>() { Eop = media.Eop, WaitTime = device.WaitTime }; bool compleate = false; try { while (!(compleate = dev.Parser.IsPacketComplete(it.Key, p.Reply))) { if (!media.Receive<byte[]>(p)) { break; } } } catch (Exception ex) { Trace(ex.Message + Environment.NewLine); } // If data is not received or error has occurred. if (!compleate || dev.Parser.IsError(p.Reply)) { continue; } GXDLT645Data d = it.Value as GXDLT645Data; if (d != null) { Trace(it.Key + " " + d.Name + Environment.NewLine); cat.Properties.Add(new GXDLT645Property(it.Key, d.Name, d.Type, d.Access)); } else { GXDLT645TableTemplate t = it.Value as GXDLT645TableTemplate; Trace(it.Key + " " + t.Name + Environment.NewLine); GXDLT645Table table = new GXDLT645Table(); table.Name = t.Name; table.DataID = it.Key; foreach (GXDLT645Data col in t.Columns) { table.Columns.Add(new GXDLT645Property(it.Key, col.Name, col.Type, col.Access)); } device.Tables.Add(table); } } } }
/// <summary> /// Load device template and connect to the device. /// </summary> /// <param name="path"></param> /// <param name="taskinfo"></param> public void Connect(string path, GXClaimedTask taskinfo) { ExecutedTask = taskinfo; //If already connected. if (Device != null) { UpdateParameters(); if ((Device.Status & DeviceStates.Connected) == 0) { Device.Connect(); } return; } DeviceList = new GXDeviceList(); DeviceList.OnError += new Gurux.Common.ErrorEventHandler(DeviceList_OnError); DeviceList.OnUpdated += new ItemUpdatedEventHandler(DeviceList_OnUpdated); GXDeviceGroup group = new GXDeviceGroup(); DeviceList.DeviceGroups.Add(group); TargetDirectory = path; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(CurrentDomain_TypeResolve); GXDeviceList.Update(path); string filename = Path.Combine(path, taskinfo.Device.ProfileGuid + ".gxp"); Device = GXDevice.Load(filename); Device.ID = taskinfo.Device.Id; group.Devices.Add(Device); Device.Name = taskinfo.Device.Name; //taskinfo.Device.AutoConnect; // ForcePerPropertyRead Device.UpdateInterval = taskinfo.Device.UpdateInterval; Device.WaitTime = taskinfo.Device.WaitTime; Device.ResendCount = taskinfo.Device.ResendCount; Device.DisabledActions = taskinfo.Device.DisabledActions; /* TODO: Device.FailTryCount = taskinfo.Device.FailTryCount; Device.FailWaitTime = taskinfo.Device.FailWaitTime; Device.ConnectionTryCount = taskinfo.Device.ConnectionTryCount; Device.ConnectionFailWaitTime = taskinfo.Device.ConnectionFailWaitTime; */ //Update parameters. UpdateParameters(); //Load medias to this assembly domin. Gurux.Communication.GXClient.GetAvailableMedias(); if (taskinfo.Device.TraceLevel != System.Diagnostics.TraceLevel.Off) { Device.Trace = taskinfo.Device.TraceLevel; Device.OnTrace += new TraceEventHandler(Device_OnTrace); } Exception lastException = null; int pos = -1; Gurux.Common.IGXMedia media = null; foreach (var it in taskinfo.MediaSettings) { try { ++pos; //If media is changed. if (media == null || media.MediaType != taskinfo.MediaSettings[pos].Key) { media = Device.GXClient.SelectMedia(taskinfo.MediaSettings[pos].Key); Device.GXClient.AssignMedia(media); } media.Settings = taskinfo.MediaSettings[pos].Value.Value; lastException = null; Device.Connect(); break; } catch (Exception ex) { //If connection fails try next redundant connectio. lastException = ex; } } if (lastException != null) { throw lastException; } }
/// <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"); } } }
public void CloseFile() { try { Clear(); if (Device != null) { Device.Dispose(); Device = null; } } catch (Exception Ex) { GXCommon.ShowError(ParentComponent, Ex); } }
/// <summary> /// Initialize protocol AddIn in import. /// </summary> public virtual void InitializeAfterImport(GXDevice device) { }
private void LoadDevice(GXDeviceProfile deviceType) { try { if (deviceType == null) { throw new Exception("LoadDevice failed: DeviceType is null"); } this.Cursor = Cursors.WaitCursor; Clear(); Device = GXDevice.Load(deviceType.Path); ShowProperties(Device); ParentComponent.CloseMenu.Enabled = true; ParentComponent.ImportMenu.Enabled = Device.AddIn.ImportFromDeviceEnabled; Device.Dirty = false; ValidateTasks(); } catch (Exception Ex) { GXCommon.ShowError(ParentComponent, Ex); } finally { this.Cursor = Cursors.Default; } }
/// <summary> /// Imports properties from the device. /// </summary> /// <param name="addinPages">Custom pages created by the protocol addin.</param> /// <param name="device">The source GXDevice.</param> /// <param name="media">A media connection to the device.</param> /// <returns>True if everything went fine, otherwise false.</returns> public virtual void ImportFromDevice(Control[] addinPages, GXDevice device, Gurux.Common.IGXMedia media) { throw new NotImplementedException("ImportFromDevice"); }
void IGXWizardPage.Initialize() { MediasCB.Items.Clear(); m_GXDevice = ((IGXWizardPage) this).Target as GXDevice; //Medias must load always or gateway can't find medias. GXMediaTypeCollection types = m_GXDevice.GetAllowedMediaTypes(); if (FromDataCollector) { GuruxAMI.Gateway.GXAmiGateway gw = new GuruxAMI.Gateway.GXAmiGateway(Gurux.DeviceSuite.Properties.Settings.Default.AmiHostName, Gurux.DeviceSuite.Properties.Settings.Default.AmiUserName, Gurux.DeviceSuite.Properties.Settings.Default.AmiPassword, m_GXDevice.GXClient); gw.WaitTime = m_GXDevice.WaitTime; if (!AvailableMedias.ContainsKey(gw.MediaType)) { AvailableMedias.Add(gw.MediaType, gw); } MediasCB.Items.Add(gw.MediaType); } else { foreach (GXMediaType type in types) { MediasCB.Items.Add(type.Name); } } if (m_GXDevice.GXClient.Media == null) { //Find used media. if (Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMedia != null) { string newKey = m_GXDevice.ProtocolName + m_GXDevice.DeviceProfile; newKey = newKey.GetHashCode().ToString(); foreach (string it in Gurux.DeviceSuite.Properties.Settings.Default.EditorSelectedMedia) { string[] tmp = it.Split(new char[] { '=' }); string key = tmp[0]; string value = tmp[1]; if (string.Compare(newKey, key) == 0) { MediasCB.SelectedItem = value; break; } } } if (MediasCB.SelectedIndex == -1 && MediasCB.Items.Count != 0) { MediasCB.SelectedItem = MediasCB.Items[0]; } } else { MediasCB.SelectedItem = m_GXDevice.GXClient.Media.MediaType; } }
private void AddDevicePagesContent(GXDeviceManufacturerCollection manufacturers, GXDevice device, List<Control> pages) { //If new device is created. //If device is modified this is skipped. if (DeviceSettings == null) { pages.Add(new GXWizardStartPage()); DeviceSettings = new GXWizardDeviceSettings(); pages.Add(DeviceSettings); } pages.Add(new GXWizardProtocolSettings()); pages.Add(new GXWizardFinishPage()); }