private void createTestDevicesToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         GXDeviceTemplate[] templates = ami.templates;
         GXDeviceTemplate   target    = null;
         if (TemplatesView.SelectedItems.Count == 1)
         {
             target = (GXDeviceTemplate)TemplatesView.SelectedItems[0].Tag;
         }
         TestDevicesDlg dlg = new TestDevicesDlg(target, templates);
         if (dlg.ShowDialog(panel1.Parent) == DialogResult.OK)
         {
             GXDevice dev = new GXDevice();
             GXDevice.Copy(dev, dlg.target);
             dev.TemplateId   = dlg.target.Id;
             dev.Manufacturer = dlg.target.Name;
             ami.AddTestDevices(dev, dlg.Index, dlg.Count);
             MessageBox.Show(panel1.Parent, "Test devices added.", "GXDLMSDirector", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(panel1.Parent, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #2
0
 /// <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;
 }
Beispiel #3
0
        public static async void AddDevice(GXDevice dev)
        {
            UpdateDevice gw = new UpdateDevice();

            gw.Device = dev;
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.PostAsJsonAsync(ServerAddress + "/api/device/UpdateDevice", gw))
                {
                    Helpers.CheckStatus(response);
                    UpdateDeviceResponse r = await response.Content.ReadAsAsync <UpdateDeviceResponse>();

                    dev.Id = r.DeviceId;
                }
            }
        }
        private void Readout(object sender, GXPacket packet)
        {
            GXDevice dev = null;

            if (sender is GXDevice)
            {
                dev = sender as GXDevice;
            }
            else if (sender is GXTable)
            {
                dev = (sender as GXTable).Device;
            }
            else if (sender is GXCategory)
            {
                dev = (sender as GXCategory).Device;
            }
            else if (sender is GXProperty)
            {
                dev = (sender as GXProperty).Device;
            }
            else
            {
                throw new Exception("Readout failed. Unknown sender: " + sender.ToString());
            }

            /* TODO: Readout
             *          List<byte> readoutBytes = Handshake(sender, packet, true);
             *          List<Parser.IECDataObject> items = Parser.IEC62056Parser.ParseReadout(readoutBytes);
             * foreach (Parser.IECDataObject it in items)
             * {
             *  if (!it.Address.Contains("*"))
             *  {
             *      List<object> results = new List<object>();
             *      dev.FindByPropertyValue("OBISCode", it.Address, results);
             *      if (results.Count > 0)
             *      {
             *          GXProperty prop = results[0] as GXProperty;
             *          prop.ReadTime = DateTime.Now;
             *          prop.SetValue(it.Value, false, PropertyStates.ValueChangedByDevice);
             *      }
             *  }
             * }
             * */
        }
 private void TemplatesAdd_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect      = false;
         dlg.InitialDirectory = Directory.GetCurrentDirectory();
         dlg.Filter           = Properties.Resources.FilterTxt;
         dlg.DefaultExt       = ".gdr";
         dlg.ValidateNames    = true;
         if (dlg.ShowDialog(panel1.Parent) == DialogResult.OK)
         {
             if (File.Exists(dlg.FileName))
             {
                 List <GXDLMSDevice> devices;
                 using (XmlReader reader = XmlReader.Create(dlg.FileName))
                 {
                     List <Type> types = new List <Type>(Gurux.DLMS.GXDLMSClient.GetObjectTypes());
                     types.Add(typeof(GXDLMSAttributeSettings));
                     types.Add(typeof(GXDLMSAttribute));
                     //Version is added to namespace.
                     XmlSerializer x = new XmlSerializer(typeof(List <GXDLMSDevice>), null, types.ToArray(), null, "Gurux1");
                     if (!x.CanDeserialize(reader))
                     {
                         x = new XmlSerializer(typeof(List <GXDLMSDevice>), types.ToArray());
                     }
                     devices = (List <GXDLMSDevice>)x.Deserialize(reader);
                     reader.Close();
                 }
                 GXDeviceTemplate        m         = new GXDeviceTemplate();
                 List <GXDeviceTemplate> templates = new List <GXDeviceTemplate>();
                 foreach (GXDLMSDevice it in devices)
                 {
                     GXDeviceTemplate t = new GXDeviceTemplate();
                     GXDevice.Copy(t, it);
                     if (!string.IsNullOrEmpty(it.Password))
                     {
                         t.Password = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(it.Password, Password.Key));
                     }
                     else if (it.HexPassword != null)
                     {
                         t.Password = GXDLMSTranslator.ToHex(CryptHelper.Decrypt(it.HexPassword, Password.Key));
                     }
                     List <GXObjectTemplate> list = new List <GXObjectTemplate>();
                     foreach (GXDLMSObject value in it.Objects)
                     {
                         string[]         names = ((IGXDLMSBase)value).GetNames();
                         GXObjectTemplate obj   = new GXObjectTemplate();
                         obj.LogicalName = value.LogicalName;
                         obj.ObjectType  = (int)value.ObjectType;
                         obj.Name        = value.Description;
                         obj.Version     = value.Version;
                         obj.ShortName   = value.ShortName;
                         list.Add(obj);
                         for (int pos = 2; pos <= ((IGXDLMSBase)value).GetAttributeCount(); ++pos)
                         {
                             GXAttributeTemplate a = new GXAttributeTemplate();
                             a.Index       = pos;
                             a.AccessLevel = (int)value.GetAccess(pos);
                             a.DataType    = (int)((IGXDLMSBase)value).GetDataType(pos);
                             a.UIDataType  = (int)((GXDLMSObject)value).GetUIDataType(pos);
                             if (value.GetStatic(pos))
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             //Profile generic capture object read is not allowed.
                             if (value is GXDLMSProfileGeneric && pos == 3)
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             obj.Attributes.Add(a);
                         }
                         t.Objects = list;
                     }
                     templates.Add(t);
                 }
                 DBDevicePropertiesForm dlg2 = new DBDevicePropertiesForm(templates.ToArray(), m);
                 if (dlg2.ShowDialog(panel1.Parent) == DialogResult.OK)
                 {
                     {
                         ami.AddDeviceTemplates(new GXDLMSMeterBase[] { m });
                         ListViewItem li = TemplatesView.Items.Add(m.Name);
                         li.Tag      = m;
                         li.Selected = true;
                     }
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(panel1.Parent, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #6
0
        /// <summary>
        /// Read data from the meter.
        /// </summary>
        private static void ReadMeter(object parameter)
        {
            GXDLMSReader reader = null;

            System.Net.Http.HttpClient httpClient = Helpers.client;
            using (GXNet media = (GXNet)parameter)
            {
                try
                {
                    var config = new ConfigurationBuilder()
                                 .SetBasePath(Directory.GetCurrentDirectory())
                                 .AddJsonFile("appsettings.json", optional: true)
                                 .Build();
                    ListenerOptions        listener = config.GetSection("Listener").Get <ListenerOptions>();
                    GXDLMSObjectCollection objects  = new GXDLMSObjectCollection();
                    GXDLMSSecureClient     client   = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface);
                    reader = new GXDLMSReader(client, media, _logger);
                    GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");
                    ldn.SetUIDataType(2, DataType.String);
                    reader.InitializeConnection();
                    reader.Read(ldn, 2);
                    Console.WriteLine("Meter connected: " + ldn.Value);
                    //Find device.
                    GXDevice            dev  = null;
                    ListDevicesResponse devs = null;
                    {
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                        {
                            Name = (string)ldn.Value
                        }).Result)
                        {
                            Helpers.CheckStatus(response);
                            devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                        }
                        //If device is unknown.
                        if (devs.Devices.Length == 0)
                        {
                            if (listener.DefaultDeviceTemplate == 0)
                            {
                                string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value;
                                Console.WriteLine(str);
                                AddSystemError info = new AddSystemError();
                                info.Error = new GXSystemError()
                                {
                                    Error = str
                                };
                                using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                                {
                                    Helpers.CheckStatus(response);
                                }
                                return;
                            }
                            ListDeviceTemplates lt = new ListDeviceTemplates()
                            {
                                Ids = new UInt64[] { listener.DefaultDeviceTemplate }
                            };
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result)
                            {
                                Helpers.CheckStatus(response);
                                ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result;
                                if (ret.Devices.Length != 1)
                                {
                                    throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate);
                                }
                                dev = new GXDevice();
                                GXDevice.Copy(dev, ret.Devices[0]);
                                dev.Name         = Convert.ToString(ldn.Value);
                                dev.TemplateId   = listener.DefaultDeviceTemplate;
                                dev.Manufacturer = ret.Devices[0].Name;
                            }
                            dev.Dynamic = true;
                            UpdateDevice update = new UpdateDevice();
                            update.Device = dev;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result)
                            {
                                Helpers.CheckStatus(response);
                                UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result;
                                dev.Id = r.DeviceId;
                            }
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices()
                            {
                                Ids = new UInt64[] { dev.Id }
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result;
                            }
                        }
                        else if (devs.Devices.Length != 1)
                        {
                            throw new Exception("There are multiple devices with same name: " + ldn.Value);
                        }
                        else
                        {
                            dev = devs.Devices[0];
                            if (dev.Security != Security.None)
                            {
                                Console.WriteLine("Reading frame counter.");
                                GXDLMSData fc = new GXDLMSData(listener.InvocationCounter);
                                reader.Read(fc, 2);
                                dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value);
                                Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value);
                                Console.WriteLine("Frame counter: " + dev.FrameCounter);
                            }
                            GetNextTaskResponse ret;
                            using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask()
                            {
                                Listener = true, DeviceId = dev.Id
                            }).Result)
                            {
                                Helpers.CheckStatus(response);
                                ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result;
                            }
                            if (ret.Tasks == null || ret.Tasks.Length == 0)
                            {
                                Console.WriteLine("No tasks to execute");
                            }
                            else
                            {
                                Console.WriteLine("Task count: " + ret.Tasks.Length);
                                if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None)
                                {
                                    reader.Release();
                                    reader.Disconnect();
                                    client             = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress, (Authentication)dev.Authentication, dev.Password, dev.InterfaceType);
                                    client.UtcTimeZone = dev.UtcTimeZone;
                                    client.Standard    = (Standard)dev.Standard;
                                    if (dev.Conformance != 0)
                                    {
                                        client.ProposedConformance = (Conformance)dev.Conformance;
                                    }
                                    client.Priority                    = dev.Priority;
                                    client.ServiceClass                = dev.ServiceClass;
                                    client.Ciphering.SystemTitle       = GXCommon.HexToBytes(dev.ClientSystemTitle);
                                    client.Ciphering.BlockCipherKey    = GXCommon.HexToBytes(dev.BlockCipherKey);
                                    client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey);
                                    client.ServerSystemTitle           = GXCommon.HexToBytes(dev.DeviceSystemTitle);
                                    client.Ciphering.InvocationCounter = dev.InvocationCounter;
                                    client.Ciphering.Security          = (Security)dev.Security;
                                    reader = new GXDLMSReader(client, media, _logger);
                                    reader.InitializeConnection();
                                }
                                List <GXValue> values = new List <GXValue>();
                                foreach (GXTask task in ret.Tasks)
                                {
                                    GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType);
                                    obj.LogicalName = task.Object.LogicalName;
                                    try
                                    {
                                        if (task.TaskType == TaskType.Write)
                                        {
                                            if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2)
                                            {
                                                client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow));
                                            }
                                            else
                                            {
                                                client.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)
                                        {
                                            Reader.Reader.Read(null, httpClient, reader, task, media, obj);
                                        }
                                    }
                                    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
                                        };
                                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result)
                                        {
                                            Helpers.CheckStatus(response);
                                            response.Content.ReadAsAsync <AddErrorResponse>();
                                        }
                                    }
                                    using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady()
                                    {
                                        Tasks = new GXTask[] { task }
                                    }).Result)
                                    {
                                        Helpers.CheckStatus(response);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        AddSystemError info = new AddSystemError();
                        info.Error = new GXSystemError()
                        {
                            Error = ex.Message
                        };
                        using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result)
                        {
                            Helpers.CheckStatus(response);
                        }
                    }
                    catch (Exception ex2)
                    {
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                }
            }
        }
		/// <summary>
		/// Constructor. Initializes the dialog and populates the tree.
		/// </summary>
		public GXDataIOSourceDialog(GXDataIOSource dataIOSource, GXDataIOSourceAttribute sourceAttributes, GXDevice device)
        {
            InitializeComponent();
			PopulateTree(dataIOSource, sourceAttributes, device);
        }
		private static void CreateDeviceNode(GXDevice device, object target, long UsedDataSources, out TreeNode deviceNode, ref TreeNode selNode)
		{
			deviceNode = new TreeNode(GXDeviceList.DeviceProfiles.Find(device.ProfileGuid).Name, 0, 0);
			deviceNode.Tag = device;
			if (target == device)
			{
				selNode = deviceNode;
			}

			if ((UsedDataSources & (long)GXDataIOSourceType.Category) != 0 ||
				(UsedDataSources & (long)GXDataIOSourceType.Property) != 0)
			{
				foreach (GXCategory cat in device.Categories)
				{
					TreeNode catNode = new TreeNode(cat.DisplayName, 1, 1);
					catNode.Tag = cat;
					if (target == cat)
					{
						selNode = catNode;
					}

					if ((UsedDataSources & (long)GXDataIOSourceType.Category) != 0 ||
						cat.Properties.Count != 0)
					{
						deviceNode.Nodes.Add(catNode);
					}
					if ((UsedDataSources & (long)GXDataIOSourceType.Property) != 0)
					{
						foreach (GXProperty prop in cat.Properties)
						{
							TreeNode propNode = new TreeNode(prop.DisplayName, 3, 3);
							propNode.Tag = prop;
							catNode.Nodes.Add(propNode);
							if (target == prop)
							{
								selNode = propNode;
							}
						}
					}
				}
			}
			if ((UsedDataSources & (long)GXDataIOSourceType.Table) != 0)
			{
				foreach (GXTable table in device.Tables)
				{
					TreeNode tableNode = new TreeNode(table.DisplayName, 2, 2);
					tableNode.Tag = table;
					if (target == table)
					{
						selNode = tableNode;
					}
					deviceNode.Nodes.Add(tableNode);
				}
			}
		}
Beispiel #9
0
		/// <summary>
        /// Exports a device from GXDeviceEditor to a .gxz file. 
		/// </summary>
		/// <param name="device">exported device.</param>
		/// <param name="path">Path to the file, where to export.</param>
        public static void Export(GXDevice device, string path)
        {
            device.Save(path, false);
            List<string> filenames = new List<string>();
            filenames.Add(device.ProfilePath);
            string DevFolder = System.IO.Path.GetDirectoryName(device.ProfilePath);
            if (!Directory.Exists(DevFolder))
            {
                Directory.CreateDirectory(DevFolder);
            }

            using (ZipOutputStream s = new ZipOutputStream(File.Create(path)))
            {
                s.SetLevel(9); // 0 - store only to 9 - means best compression
                //Save device files
                foreach (string file in filenames)
                {
                    using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, buffer.Length);
                        FileInfo fi = new FileInfo(file);
                        ZipEntry entry = new ZipEntry(fi.Name);
                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                }

                //Save Dll file
                string DLLFile = device.m_AddIn.GetType().Assembly.Location;
                FileStream DLLFS = File.OpenRead(DLLFile);
                byte[] DLLBuffer = new byte[DLLFS.Length];
                DLLFS.Read(DLLBuffer, 0, DLLBuffer.Length);
                FileInfo fi2 = new FileInfo(DLLFile);
                ZipEntry DLLEntry = new ZipEntry(fi2.Name);
                s.PutNextEntry(DLLEntry);
                s.Write(DLLBuffer, 0, DLLBuffer.Length);
                //////////////////////////////////
                //Add referenced assemblies from the same directory
                // Create an Application Domain:
                string pathToDll = typeof(GXZip).Assembly.CodeBase;
                AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = pathToDll };
                System.AppDomain td = AppDomain.CreateDomain("AddInReferencesDomain", null, domainSetup);
                try
                {
                    GXProxyClass pc = (GXProxyClass)(td.CreateInstanceFromAndUnwrap(pathToDll, typeof(GXProxyClass).FullName));
                    path = string.Empty;
                    List<string> medias = new List<string>();
                    pc.FindAddInReferences(DLLFile);

                    foreach (string asmPath in pc.Assemblies)
                    {
                        Assembly asm = Assembly.LoadFile(asmPath);
                        //Save Dll file
                        DLLFile = asm.Location;
                        DLLFS = File.OpenRead(DLLFile);
                        DLLBuffer = new byte[DLLFS.Length];
                        DLLFS.Read(DLLBuffer, 0, DLLBuffer.Length);
                        fi2 = new FileInfo(DLLFile);
                        DLLEntry = new ZipEntry(fi2.Name);
                        s.PutNextEntry(DLLEntry);
                        s.Write(DLLBuffer, 0, DLLBuffer.Length);
                    }
                }
                finally
                {
                    System.AppDomain.Unload(td);
                }                
            }
        }
		public PropertyDlg(GXDevice GXDevice1, GXProperty GXProperty1, bool Edit)
		{
			m_GXProperty1 = GXProperty1;
			m_GXDevice1 = GXDevice1;
			m_edit = Edit;
			m_Types = CreateTypeTable();
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			PropertyDlgBase DlgBase = new PropertyDlgBase();
			DlgBase.SortTabOrder(GeneralGB);
			DlgBase.SortTabOrder(Common2Tab);
		}
Beispiel #11
0
        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();
            }
        }
            public List <object[]> Import(string path, string target, out byte[] data, out string assemblyName, out string addInType)
            {
                data            = null;
                TargetDirectory = target;
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
                GXDeviceProfile type = GXZip.Import(null, path, target);

                GXDeviceList.Update(target);
                string filename = Path.Combine(target, type.DeviceGuid + ".gxp");

                using (FileStream s = File.OpenRead(filename))
                {
                    long size = s.Length;
                    size = 0;
                }
                GXDevice device = GXDevice.Load(filename);

                addInType    = device.AddIn.ToString();
                assemblyName = device.AddIn.GetType().Assembly.FullName;
                GXAmiDeviceProfile dt = new GXAmiDeviceProfile();

                dt.Guid           = device.Guid;
                dt.Protocol       = device.ProtocolName;
                dt.Profile        = device.DeviceProfile;
                dt.PresetName     = device.PresetName;
                dt.Manufacturer   = device.Manufacturer;
                dt.Model          = device.Model;
                dt.Version        = device.Version;
                dt.UpdateInterval = device.UpdateInterval;
                dt.WaitTime       = device.WaitTime;
                dt.ResendCount    = device.ResendCount;
                dt.Added          = DateTime.Now.ToUniversalTime();
                List <GXAmiMediaType> list   = new List <GXAmiMediaType>();
                List <string>         medias = new List <string>(Gurux.Communication.GXClient.GetAvailableMedias());

                foreach (GXMediaType it in device.AllowedMediaTypes)
                {
                    GXAmiMediaType mt = new GXAmiMediaType();
                    mt.Name = it.Name;
                    //If default media settings are not given, ask them from the parser.
                    if (string.IsNullOrEmpty(it.DefaultMediaSettings) && medias.Contains(it.Name))
                    {
                        Gurux.Common.IGXMedia m = device.GXClient.SelectMedia(it.Name);
                        mt.Settings = m.Settings;
                    }
                    else
                    {
                        mt.Settings = it.DefaultMediaSettings;
                    }
                    list.Add(mt);
                }
                dt.AllowedMediaTypes = list.ToArray();
                List <object[]> items = new List <object[]>();

                items.Add(new object[] { dt, dt });
                ImportParameters(device, device.ID, dt, items);
                foreach (GXCategory cat in device.Categories)
                {
                    GXAmiCategoryTemplate ct = new GXAmiCategoryTemplate();
                    items.Add(new object[] { dt, ct });
                    ct.Name = cat.Name;
                    ct.Id   = cat.ID;
                    ImportParameters(cat, cat.ID, ct, items);
                    foreach (GXProperty prop in cat.Properties)
                    {
                        GXAmiPropertyTemplate pt = new GXAmiPropertyTemplate();
                        pt.Id       = prop.ID;
                        pt.ParentID = cat.ID;
                        pt.Name     = prop.Name;
                        pt.Unit     = prop.Unit;
                        if (prop.ValueType != null)
                        {
                            pt.TypeAsString = prop.ValueType.ToString();
                        }
                        pt.AccessMode = prop.AccessMode;
                        items.Add(new object[] { dt, pt });
                        ImportParameters(prop, prop.ID, pt, items);
                    }
                }

                foreach (GXTable table in device.Tables)
                {
                    GXAmiDataTableTemplate tt = new GXAmiDataTableTemplate();
                    items.Add(new object[] { dt, tt });
                    tt.Name = table.Name;
                    tt.Id   = table.ID;
                    ImportParameters(table, table.ID, tt, items);
                    foreach (GXProperty prop in table.Columns)
                    {
                        GXAmiPropertyTemplate pt = new GXAmiPropertyTemplate();
                        pt.Id       = prop.ID;
                        pt.ParentID = table.ID;
                        pt.Name     = prop.Name;
                        pt.Unit     = prop.Unit;
                        if (prop.ValueType != null)
                        {
                            pt.TypeAsString = prop.ValueType.ToString();
                        }
                        pt.AccessMode = prop.AccessMode;
                        items.Add(new object[] { dt, pt });
                        ImportParameters(prop, prop.ID, pt, items);
                    }
                }
                return(items);
            }