Пример #1
0
        public List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > Refresh(GXDLMSProfileGeneric item, GXDLMSCommunicator comm)
        {
            GXReplyData reply = new GXReplyData();

            if (item.LogicalName.CompareTo("0.0.99.1.2.255") == 0) // LoadProfile1EndOfRecordingData
            {
                List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > items = new List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> >();
                //Read profile generic columns.
                comm.GetProfileGenericColumns(item);
                byte[] data = comm.Read(item, 2);
                comm.ReadDataBlock(data, "Get profile generic columns...", 1, reply);
                object[]     values = (object[])reply.Value;
                Array        info   = values[0] as Array;
                GXDLMSObject obj    = new GXDLMSData();
                obj.Description = "DateTime";
                obj.SetUIDataType(1, DataType.DateTime);
                items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(1, 0)));
                obj             = new GXDLMSData();
                obj.Description = "Status";
                items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(2, 0)));
                //Two last items contains Start and end date.
                int cnt = 4;
                for (int pos = 0; pos < info.Length - 2; pos += 2)
                {
                    obj             = new GXDLMSData();
                    obj.LogicalName = Convert.ToString(GXDLMSClient.ChangeType((byte[])info.GetValue(pos), DataType.OctetString));
                    object scalerUnit = info.GetValue(pos + 1);
                    obj.Description = "";
                    items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(++cnt, 0)));
                }
                LastDateTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])info.GetValue(info.Length - 1), DataType.DateTime);
                return(items);
            }
            return(null);
        }
Пример #2
0
        /// <summary>
        /// Update simulated values for the meter instance.
        /// </summary>
        /// <param name="items">Simulated COSEM objects.</param>
        void UpdateValues(GXDLMSObjectCollection items)
        {
            //Update COSEM Logical Device Name
            GXDLMSData d = items.FindByLN(ObjectType.Data, "0.0.42.0.0.255") as GXDLMSData;

            if (d != null && d.Value is string v)
            {
                d.Value = string.Format("{0}{1}", v.Substring(0, 3), serialNumber.ToString("D13"));
            }

            //Update Meter serial number.
            d = items.FindByLN(ObjectType.Data, "0.0.96.1.0.255") as GXDLMSData;
            if (d != null && d.Value is string v2)
            {
                string tmp = "";
                foreach (char it in v2)
                {
                    //Append chars.
                    if (it < 0x30 || it > 0x39)
                    {
                        tmp += it;
                    }
                    else
                    {
                        break;
                    }
                }
                d.Value = tmp + serialNumber.ToString("D" + Convert.ToString(v2.Length - tmp.Length));
            }
        }
Пример #3
0
 public List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > Refresh(GXDLMSProfileGeneric item, GXDLMSCommunicator comm)
 {
     if (item.LogicalName.CompareTo("0.0.99.1.2.255") == 0) // LoadProfile1EndOfRecordingData
     {
         List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > items = new List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> >();
         //Read profile generic columns.
         object       value   = comm.GetProfileGenericColumns(item.Name);
         byte[]       data    = comm.Read("0.0.99.128.1.255", ObjectType.ProfileGeneric, 2);
         byte[]       allData = comm.ReadDataBlock(data, "Get profile generic columns...", 1);
         object[]     values  = (object[])comm.m_Cosem.GetValue(allData);
         Array        info    = values[0] as Array;
         GXDLMSObject obj     = new GXDLMSData();
         obj.Description = "DateTime";
         obj.SetUIDataType(1, DataType.DateTime);
         items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(1, 0)));
         obj             = new GXDLMSData();
         obj.Description = "Status";
         items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(2, 0)));
         //Two last items contains Start and end date.
         int cnt = 4;
         for (int pos = 0; pos < info.Length - 2; pos += 2)
         {
             obj             = new GXDLMSData();
             obj.LogicalName = GXHelpers.ConvertFromDLMS(info.GetValue(pos), DataType.OctetString, DataType.OctetString, false).ToString();
             object scalerUnit = info.GetValue(pos + 1);
             obj.Description = "";
             items.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(++cnt, 0)));
         }
         LastDateTime = ((GXDateTime)GXDLMS.Common.GXHelpers.ConvertFromDLMS(info.GetValue(info.Length - 1), DataType.OctetString, DataType.DateTime, true)).Value;
         return(items);
     }
     return(null);
 }
Пример #4
0
 void OnShowDialog(GXActionArgs arg)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new ShowUserDialogEventHandler(OnShowDialog), arg).AsyncWaitHandle.WaitOne();
     }
     else
     {
         if (ProfileGenericView.SelectedCells.Count == 1)
         {
             DataGridViewRow row = ProfileGenericView.Rows[ProfileGenericView.SelectedCells[0].RowIndex];
             if (arg.Index == -1)
             {
                 //Add to the white list.
                 string data = "<Array Qty=\"01\" ><Structure Qty=\"04\" ><OctetString Value=\"" + row.Cells[2].Value + "\" /><UInt8 Value=\"63\" /><UInt16 Value=\"0004\" /><UInt8 Value=\"5\" /></Structure></Array>";
                 arg.Action = ActionType.Write;
                 arg.Index  = 2;
                 GXDLMSData d = new GXDLMSData("0.0.94.39.48.255");
                 d.SetDataType(2, DataType.Array);
                 d.Value    = GXDLMSTranslator.XmlToValue(data);
                 arg.Target = d;
             }
             else if (arg.Index == -2)
             {
                 //Add to the black list.
                 string data = "<Array Qty=\"01\" ><OctetString Value=\"" + row.Cells[2].Value + "\" /></Array>";
                 arg.Action = ActionType.Write;
                 arg.Index  = 2;
                 arg.Value  = GXDLMSTranslator.XmlToValue(data);
                 arg.Target = new GXDLMSData("0.0.94.39.47.255");
                 arg.Target.SetDataType(2, DataType.Array);
             }
             else if (arg.Index == -3)
             {
                 //Remove from the white or black list.
                 //Add to the white list.
                 long   unixTime = GXDateTime.ToUnixTime(DateTime.Parse(Convert.ToString(row.Cells[4].Value)));
                 string data     = "<Structure Qty=\"02\" ><OctetString Value=\"" + row.Cells[0].Value + "\" /><UInt32 Value=\"" + unixTime + "\" /></Structure>";
                 arg.Value = GXDLMSTranslator.XmlToValue(data);
                 ProfileGenericView.Rows.Remove(row);
             }
         }
         else
         {
             GXHelpers.ShowMessageBox(this, Properties.Resources.ProfileGenericDeviceAmountWarning, "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
             arg.Handled = true;
         }
     }
 }
Пример #5
0
 public void PreAction(GXActionArgs arg)
 {
     //Edit object in association view.
     if (arg.Action == ActionType.Action && arg.Index == -1)
     {
         if (arg.Tag == null)
         {
             OnShowDialog(null, arg);
         }
         else
         {
             GXDLMSAssociationLogicalName target = Target as GXDLMSAssociationLogicalName;
             arg.Value = target.AddObject(arg.Client, arg.Tag as GXDLMSObject);
             arg.Tag   = null;
         }
     }
     //Add object to association view.
     else if (arg.Index == 3)
     {
         GXDLMSObject it = new GXDLMSData();
         OnShowDialog(it, arg);
     }
     else if (arg.Index == 4)
     {
         // Remove object from association view.
         OnShowDialog(null, arg);
     }
     //Add user to user list.
     else if (arg.Index == 5)
     {
         OnShowDialog(true, arg);
     }
     else if (arg.Index == 6)
     {
         // Remove user from user list.
         OnShowDialog(false, arg);
     }
     if ((arg.Action == ActionType.Write && arg.Index == 7) ||
         arg.Action == ActionType.Action && arg.Index == 2)
     {
         OnUpdatePassword(arg);
     }
     else if (arg.Action == ActionType.Write && arg.Index == 2)
     {
         //Skip write invoke.
         arg.Handled = true;
     }
 }
Пример #6
0
        void Init()
        {
            Media.OnReceived           += new Gurux.Common.ReceivedEventHandler(OnReceived);
            Media.OnClientConnected    += new Gurux.Common.ClientConnectedEventHandler(OnClientConnected);
            Media.OnClientDisconnected += new Gurux.Common.ClientDisconnectedEventHandler(OnClientDisconnected);
            Media.OnError += new Gurux.Common.ErrorEventHandler(OnError);
            Media.Open();
            ///////////////////////////////////////////////////////////////////////
            //Add Logical Device Name. 123456 is meter serial number.
            GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255");

            ldn.Value = "Gurux123456";
            //Value is get as Octet String.
            ldn.SetDataType(2, DataType.OctetString);
            ldn.SetUIDataType(2, DataType.String);
            Items.Add(ldn);
            //Add firmware version.
            GXDLMSData fw = new GXDLMSData("1.0.0.2.0.255");

            fw.Value = "Gurux FW 0.0.1";
            Items.Add(fw);
            //Add Last average.
            GXDLMSRegister r = new GXDLMSRegister("1.1.21.25.0.255");

            //Set access right. Client can't change average value.
            Items.Add(r);
            //Add default clock. Clock's Logical Name is 0.0.1.0.0.255.
            GXDLMSClock clock = new GXDLMSClock();

            clock.Begin     = new GXDateTime(-1, 9, 1, -1, -1, -1, -1);
            clock.End       = new GXDateTime(-1, 3, 1, -1, -1, -1, -1);
            clock.Deviation = 0;
            Items.Add(clock);
            //Add Tcp Udp setup. Default Logical Name is 0.0.25.0.0.255.
            GXDLMSTcpUdpSetup tcp = new GXDLMSTcpUdpSetup();

            Items.Add(tcp);
            ///////////////////////////////////////////////////////////////////////
            //Add Load profile.
            GXDLMSProfileGeneric pg = new GXDLMSProfileGeneric("1.0.99.1.0.255");

            //Set capture period to 60 second.
            pg.CapturePeriod = 60;
            //Maximum row count.
            pg.ProfileEntries = 100000;
            pg.SortMethod     = SortMethod.FiFo;
            pg.SortObject     = clock;
            //Add columns.
            //Set saved attribute index.
            pg.CaptureObjects.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(clock, new GXDLMSCaptureObject(2, 0)));
            //Set saved attribute index.
            pg.CaptureObjects.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(r, new GXDLMSCaptureObject(2, 0)));
            Items.Add(pg);
            //Add initial rows.
            //Generate Profile Generic data file
            lock (FileLock)
            {
                using (var writer = File.CreateText(GetdataFile()))
                {
                    //Create 10 000 rows for profile generic file.
                    //In example profile generic we have two columns.
                    //Date time and integer value.
                    int      rowCount = 10000;
                    DateTime dt       = DateTime.Now;
                    //Reset minutes and seconds to Zero.
                    dt = dt.AddSeconds(-dt.Second);
                    dt = dt.AddMinutes(-dt.Minute);
                    dt = dt.AddHours(-(rowCount - 1));
                    StringBuilder sb = new StringBuilder();
                    for (int pos = 0; pos != rowCount; ++pos)
                    {
                        sb.Append(dt.ToString(CultureInfo.InvariantCulture));
                        sb.Append(';');
                        sb.AppendLine(Convert.ToString(pos + 1));
                        dt = dt.AddHours(1);
                    }
                    sb.Length -= 2;
                    writer.Write(sb.ToString());
                }
            }
            ///////////////////////////////////////////////////////////////////////
            //Add Auto connect object.
            GXDLMSAutoConnect ac = new GXDLMSAutoConnect();

            ac.Mode            = AutoConnectMode.AutoDiallingAllowedAnytime;
            ac.Repetitions     = 10;
            ac.RepetitionDelay = 60;
            //Calling is allowed between 1am to 6am.
            ac.CallingWindow.Add(new KeyValuePair <GXDateTime, GXDateTime>(new GXDateTime(-1, -1, -1, 1, 0, 0, -1), new GXDateTime(-1, -1, -1, 6, 0, 0, -1)));
            ac.Destinations = new string[] { "www.gurux.org" };
            Items.Add(ac);
            ///////////////////////////////////////////////////////////////////////
            //Add Activity Calendar object.
            GXDLMSActivityCalendar activity = new GXDLMSActivityCalendar();

            activity.CalendarNameActive      = "Active";
            activity.SeasonProfileActive     = new GXDLMSSeasonProfile[] { new GXDLMSSeasonProfile("Summer time", new GXDateTime(-1, 3, 31, -1, -1, -1, -1), "") };
            activity.WeekProfileTableActive  = new GXDLMSWeekProfile[] { new GXDLMSWeekProfile("Monday", 1, 1, 1, 1, 1, 1, 1) };
            activity.DayProfileTableActive   = new GXDLMSDayProfile[] { new GXDLMSDayProfile(1, new GXDLMSDayProfileAction[] { new GXDLMSDayProfileAction(new GXTime(DateTime.Now), "0.1.10.1.101.255", 1) }) };
            activity.CalendarNamePassive     = "Passive";
            activity.SeasonProfilePassive    = new GXDLMSSeasonProfile[] { new GXDLMSSeasonProfile("Winter time", new GXDateTime(-1, 10, 30, -1, -1, -1, -1), "") };
            activity.WeekProfileTablePassive = new GXDLMSWeekProfile[] { new GXDLMSWeekProfile("Tuesday", 1, 1, 1, 1, 1, 1, 1) };
            activity.DayProfileTablePassive  = new GXDLMSDayProfile[] { new GXDLMSDayProfile(1, new GXDLMSDayProfileAction[] { new GXDLMSDayProfileAction(new GXTime(DateTime.Now), "0.1.10.1.101.255", 1) }) };
            activity.Time = new GXDateTime(DateTime.Now);
            Items.Add(activity);
            ///////////////////////////////////////////////////////////////////////
            //Add Optical Port Setup object.
            GXDLMSIECOpticalPortSetup optical = new GXDLMSIECOpticalPortSetup();

            optical.DefaultMode      = OpticalProtocolMode.Default;
            optical.ProposedBaudrate = BaudRate.Baudrate9600;
            optical.DefaultBaudrate  = BaudRate.Baudrate300;
            optical.ResponseTime     = LocalPortResponseTime.ms200;
            optical.DeviceAddress    = "Gurux";
            optical.Password1        = "Gurux1";
            optical.Password2        = "Gurux2";
            optical.Password5        = "Gurux5";
            Items.Add(optical);
            ///////////////////////////////////////////////////////////////////////
            //Add Demand Register object.
            GXDLMSDemandRegister dr = new GXDLMSDemandRegister();

            dr.LogicalName         = "0.0.1.0.0.255";
            dr.CurrentAverageValue = (uint)10;
            dr.LastAverageValue    = (uint)20;
            dr.Status           = (byte)1;
            dr.StartTimeCurrent = dr.CaptureTime = new GXDateTime(DateTime.Now);
            dr.Period           = 10;
            dr.NumberOfPeriods  = 1;
            Items.Add(dr);
            ///////////////////////////////////////////////////////////////////////
            //Add Register Monitor object.
            GXDLMSRegisterMonitor rm = new GXDLMSRegisterMonitor();

            rm.LogicalName = "0.0.1.0.0.255";
            rm.Thresholds  = new object[] { (int)0x1234, (int)0x5678 };
            GXDLMSActionSet set = new GXDLMSActionSet();

            set.ActionDown.LogicalName    = rm.LogicalName;
            set.ActionDown.ScriptSelector = 1;
            set.ActionUp.LogicalName      = rm.LogicalName;
            set.ActionUp.ScriptSelector   = 2;
            rm.Actions = new GXDLMSActionSet[] {
                set
            };
            rm.MonitoredValue.Update(r, 2);
            Items.Add(rm);
            ///////////////////////////////////////////////////////////////////////
            //Add Activate test mode Script table object.
            GXDLMSScriptTable st = new GXDLMSScriptTable("0.1.10.1.101.255");
            GXDLMSScript      s  = new GXDLMSScript();

            s.Id = 1;
            GXDLMSScriptAction a = new GXDLMSScriptAction();

            a.Target = null;

            s.Actions.Add(a);
            st.Scripts.Add(s);
            Items.Add(st);
            ///////////////////////////////////////////////////////////////////////
            //Add action schedule object.
            GXDLMSActionSchedule actionS = new GXDLMSActionSchedule();

            actionS.Target = st;
            actionS.ExecutedScriptSelector = 1;
            actionS.Type          = SingleActionScheduleType.SingleActionScheduleType1;
            actionS.ExecutionTime = new GXDateTime[] { new GXDateTime(DateTime.Now) };
            Items.Add(actionS);
            ///////////////////////////////////////////////////////////////////////
            //Add SAP Assignment object.
            GXDLMSSapAssignment sap = new GXDLMSSapAssignment();

            sap.SapAssignmentList.Add(new KeyValuePair <UInt16, string>(1, "Gurux"));
            sap.SapAssignmentList.Add(new KeyValuePair <UInt16, string>(16, "Gurux-2"));
            Items.Add(sap);
            ///////////////////////////////////////////////////////////////////////
            //Add Auto Answer object.
            GXDLMSAutoAnswer aa = new GXDLMSAutoAnswer();

            aa.Mode = AutoAnswerMode.Connected;
            aa.ListeningWindow.Add(new KeyValuePair <GXDateTime, GXDateTime>(new GXDateTime(-1, -1, -1, 6, -1, -1, -1), new GXDateTime(-1, -1, -1, 8, -1, -1, -1)));
            aa.Status        = AutoAnswerStatus.Inactive;
            aa.NumberOfCalls = 0;
            aa.NumberOfRingsInListeningWindow  = 1;
            aa.NumberOfRingsOutListeningWindow = 2;
            Items.Add(aa);
            ///////////////////////////////////////////////////////////////////////
            //Add Modem Configuration object.
            GXDLMSModemConfiguration mc = new GXDLMSModemConfiguration();

            mc.CommunicationSpeed = BaudRate.Baudrate57600;
            GXDLMSModemInitialisation init = new GXDLMSModemInitialisation();

            init.Request             = "AT";
            init.Response            = "OK";
            init.Delay               = 0;
            mc.InitialisationStrings = new GXDLMSModemInitialisation[] { init };
            Items.Add(mc);

            ///////////////////////////////////////////////////////////////////////
            //Add Mac Address Setup object.
            GXDLMSMacAddressSetup mac = new GXDLMSMacAddressSetup();

            mac.MacAddress = "00:11:22:33:44:55:66";
            Items.Add(mac);

            ///////////////////////////////////////////////////////////////////////
            //Add Image transfer object.
            GXDLMSImageTransfer i = new GXDLMSImageTransfer();

            Items.Add(i);
            ///////////////////////////////////////////////////////////////////////
            //Add IP4 Setup object.
            GXDLMSIp4Setup ip4 = new GXDLMSIp4Setup();
            //Get local IP address.
            var host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip4.IPAddress = ip.ToString();
                }
            }
            Items.Add(ip4);

            //Add Push Setup. (On Connectivity)
            GXDLMSPushSetup push = new GXDLMSPushSetup("0.0.25.9.0.255");

            //Send Push messages to this address as default.
            push.Destination = ip4.IPAddress + ":7000";
            Items.Add(push);
            //Add push object itself. This is needed to tell structure of data to the Push listener.
            push.PushObjectList.Add(new KeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(push, new GXDLMSCaptureObject(2, 0)));
            //Add logical device name.
            push.PushObjectList.Add(new KeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(ldn, new GXDLMSCaptureObject(2, 0)));
            //Add .0.0.25.1.0.255 Ch. 0 IPv4 setup IP address.
            push.PushObjectList.Add(new KeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(ip4, new GXDLMSCaptureObject(3, 0)));

            Items.Add(new GXDLMSSpecialDaysTable());
            //Add  S-FSK objects
            Items.Add(new GXDLMSSFSKPhyMacSetUp());
            Items.Add(new GXDLMSSFSKActiveInitiator());
            Items.Add(new GXDLMSSFSKMacCounters());
            Items.Add(new GXDLMSSFSKMacSynchronizationTimeouts());
            ///Add G3-PLC objects.
            Items.Add(new GXDLMSG3Plc6LoWPan());
            Items.Add(new GXDLMSG3PlcMacLayerCounters());
            Items.Add(new GXDLMSG3PlcMacSetup());
            //Add security setup object
            Items.Add(new GXDLMSSecuritySetup());

            ///////////////////////////////////////////////////////////////////////
            //Server must initialize after all objects are added.
            Initialize();
        }
Пример #7
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();
                    }
                }
            }
        }
Пример #8
0
 public void UpdateColumns(GXDLMSProfileGeneric item, GXManufacturer man)
 {
     if (Comm.parentForm.InvokeRequired)
     {
         try
         {
             Comm.parentForm.Invoke(new UpdateColumnsEventHandler(UpdateColumns), item, man);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         return;
     }
     try
     {
         item.Buffer.Clear();
         item.CaptureObjects.Clear();
         List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > cols = null;
         List <DataColumn> columns = new List <DataColumn>();
         try
         {
             Comm.GetProfileGenericColumns(item);
             if (Standard == Standard.Italy && item.CaptureObjects.Count == 0)
             {
                 cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName, 0);
                 GXDLMSConverter c = new GXDLMSConverter(Standard);
                 foreach (var it in cols)
                 {
                     c.UpdateOBISCodeInformation(it.Key);
                 }
                 item.CaptureObjects.AddRange(cols);
             }
         }
         catch (GXDLMSException ex)
         {
             if (Standard == Standard.Italy)
             {
                 GXDLMSData obj  = Comm.client.Objects.FindByLN(ObjectType.Data, "0.0.96.1.3.255") as GXDLMSData;
                 int        type = 0;
                 if (obj != null)
                 {
                     if (obj.Value == null)
                     {
                         try
                         {
                             Comm.ReadValue(obj, 2);
                             type = Convert.ToInt16(obj.Value);
                         }
                         catch (Exception)
                         {
                             type = 0;
                         }
                     }
                     else
                     {
                         type = Convert.ToInt16(obj.Value);
                     }
                 }
                 cols = GetColumns(Comm.client.Objects, Comm.client.CustomObisCodes, item.LogicalName, type);
                 item.CaptureObjects.Clear();
                 GXDLMSConverter c = new GXDLMSConverter(Standard);
                 foreach (var it in cols)
                 {
                     c.UpdateOBISCodeInformation(it.Key);
                 }
                 item.CaptureObjects.AddRange(cols);
             }
             if (cols == null || cols.Count == 0)
             {
                 throw ex;
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #9
0
        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);
                }
            }
        }
Пример #10
0
 /// <summary>
 /// Read Invocation counter (frame counter) from the meter and update it.
 /// </summary>
 private void UpdateFrameCounter()
 {
     //Read frame counter if GeneralProtection is used.
     if (!string.IsNullOrEmpty(InvocationCounter) && Client.Ciphering != null && Client.Ciphering.Security != (byte)Security.None)
     {
         InitializeOpticalHead();
         byte[]      data;
         GXReplyData reply = new GXReplyData();
         Client.ProposedConformance |= Conformance.GeneralProtection;
         int            add       = Client.ClientAddress;
         Authentication auth      = Client.Authentication;
         Security       security  = Client.Ciphering.Security;
         byte[]         challenge = Client.CtoSChallenge;
         try
         {
             Client.ClientAddress      = 16;
             Client.Authentication     = Authentication.None;
             Client.Ciphering.Security = (byte)Security.None;
             data = Client.SNRMRequest();
             if (data != null)
             {
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
                 }
                 ReadDataBlock(data, reply);
                 if (Trace == TraceLevel.Verbose)
                 {
                     Console.WriteLine("Parsing UA reply." + reply.ToString());
                 }
                 //Has server accepted client.
                 Client.ParseUAResponse(reply.Data);
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Parsing UA reply succeeded.");
                 }
             }
             //Generate AARQ request.
             //Split requests to multiple packets if needed.
             //If password is used all data might not fit to one packet.
             foreach (byte[] it in Client.AARQRequest())
             {
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
                 }
                 reply.Clear();
                 ReadDataBlock(it, reply);
             }
             if (Trace > TraceLevel.Info)
             {
                 Console.WriteLine("Parsing AARE reply" + reply.ToString());
             }
             try
             {
                 //Parse reply.
                 Client.ParseAAREResponse(reply.Data);
                 reply.Clear();
                 GXDLMSData d = new GXDLMSData(InvocationCounter);
                 Read(d, 2);
                 Client.Ciphering.InvocationCounter = 1 + Convert.ToUInt32(d.Value);
                 Console.WriteLine("Invocation counter: " + Convert.ToString(Client.Ciphering.InvocationCounter));
                 reply.Clear();
                 Disconnect();
             }
             catch (Exception Ex)
             {
                 Disconnect();
                 throw Ex;
             }
         }
         finally
         {
             Client.ClientAddress      = add;
             Client.Authentication     = auth;
             Client.Ciphering.Security = security;
             Client.CtoSChallenge      = challenge;
         }
     }
 }
Пример #11
0
        void Init()
        {
            Media.OnReceived           += new Gurux.Common.ReceivedEventHandler(OnReceived);
            Media.OnClientConnected    += new Gurux.Common.ClientConnectedEventHandler(OnClientConnected);
            Media.OnClientDisconnected += new Gurux.Common.ClientDisconnectedEventHandler(OnClientDisconnected);
            Media.OnError += new Gurux.Common.ErrorEventHandler(OnError);
            Media.Open();
            ///////////////////////////////////////////////////////////////////////
            //Add Logical Device Name. 123456 is meter serial number.
            GXDLMSData d = new GXDLMSData("0.0.42.0.0.255");

            d.Value = "Gurux123456";
            //Set access right. Client can't change Device name.
            d.SetAccess(2, AccessMode.ReadWrite);
            //Value is get as Octet String.
            d.SetDataType(2, DataType.OctetString);
            d.SetUIDataType(2, DataType.String);
            Items.Add(d);
            //Add Last average.
            GXDLMSRegister r = new GXDLMSRegister("1.1.21.25.0.255");

            //Set access right. Client can't change average value.
            r.SetAccess(2, AccessMode.Read);
            Items.Add(r);
            //Add default clock. Clock's Logical Name is 0.0.1.0.0.255.
            GXDLMSClock clock = new GXDLMSClock();

            clock.Begin     = new GXDateTime(-1, 9, 1, -1, -1, -1, -1);
            clock.End       = new GXDateTime(-1, 3, 1, -1, -1, -1, -1);
            clock.Deviation = 0;
            Items.Add(clock);
            //Add Tcp Udp setup. Default Logical Name is 0.0.25.0.0.255.
            GXDLMSTcpUdpSetup tcp = new GXDLMSTcpUdpSetup();

            Items.Add(tcp);
            ///////////////////////////////////////////////////////////////////////
            //Add Load profile.
            GXDLMSProfileGeneric pg = new GXDLMSProfileGeneric("1.0.99.1.0.255");

            //Set capture period to 60 second.
            pg.CapturePeriod = 60;
            //Maximum row count.
            pg.ProfileEntries = 100;
            pg.SortMethod     = SortMethod.FiFo;
            pg.SortObject     = clock;
            //Add columns.
            //Set saved attribute index.
            pg.CaptureObjects.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(clock, new GXDLMSCaptureObject(2, 0)));
            //Set saved attribute index.
            pg.CaptureObjects.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(r, new GXDLMSCaptureObject(2, 0)));
            Items.Add(pg);
            //Add initial rows.
            pg.Buffer.Add(new object[] { DateTime.Now, (int)10 });
            ///////////////////////////////////////////////////////////////////////
            //Add Auto connect object.
            GXDLMSAutoConnect ac = new GXDLMSAutoConnect();

            ac.Mode            = AutoConnectMode.AutoDiallingAllowedAnytime;
            ac.Repetitions     = 10;
            ac.RepetitionDelay = 60;
            //Calling is allowed between 1am to 6am.
            ac.CallingWindow.Add(new KeyValuePair <GXDateTime, GXDateTime>(new GXDateTime(-1, -1, -1, 1, 0, 0, -1), new GXDateTime(-1, -1, -1, 6, 0, 0, -1)));
            ac.Destinations = new string[] { "www.gurux.org" };
            Items.Add(ac);

            ///////////////////////////////////////////////////////////////////////
            //Add Activity Calendar object.
            GXDLMSActivityCalendar activity = new GXDLMSActivityCalendar();

            activity.CalendarNameActive      = "Active";
            activity.SeasonProfileActive     = new GXDLMSSeasonProfile[] { new GXDLMSSeasonProfile("Summer time", new GXDateTime(-1, 3, 31, -1, -1, -1, -1), "") };
            activity.WeekProfileTableActive  = new GXDLMSWeekProfile[] { new GXDLMSWeekProfile("Monday", 1, 1, 1, 1, 1, 1, 1) };
            activity.DayProfileTableActive   = new GXDLMSDayProfile[] { new GXDLMSDayProfile(1, new GXDLMSDayProfileAction[] { new GXDLMSDayProfileAction(new GXDateTime(DateTime.Now), "test", 1) }) };
            activity.CalendarNamePassive     = "Passive";
            activity.SeasonProfilePassive    = new GXDLMSSeasonProfile[] { new GXDLMSSeasonProfile("Winter time", new GXDateTime(-1, 10, 30, -1, -1, -1, -1), "") };
            activity.WeekProfileTablePassive = new GXDLMSWeekProfile[] { new GXDLMSWeekProfile("Tuesday", 1, 1, 1, 1, 1, 1, 1) };
            activity.DayProfileTablePassive  = new GXDLMSDayProfile[] { new GXDLMSDayProfile(1, new GXDLMSDayProfileAction[] { new GXDLMSDayProfileAction(new GXDateTime(DateTime.Now), "0.0.1.0.0.255", 1) }) };
            activity.Time = new GXDateTime(DateTime.Now);
            Items.Add(activity);

            ///////////////////////////////////////////////////////////////////////
            //Add Optical Port Setup object.
            GXDLMSIECOpticalPortSetup optical = new GXDLMSIECOpticalPortSetup();

            optical.DefaultMode      = OpticalProtocolMode.Default;
            optical.ProposedBaudrate = BaudRate.Baudrate9600;
            optical.DefaultBaudrate  = BaudRate.Baudrate300;
            optical.ResponseTime     = LocalPortResponseTime.ms200;
            optical.DeviceAddress    = "Gurux";
            optical.Password1        = "Gurux1";
            optical.Password2        = "Gurux2";
            optical.Password5        = "Gurux5";
            Items.Add(optical);

            ///////////////////////////////////////////////////////////////////////
            //Add Demand Register object.
            GXDLMSDemandRegister dr = new GXDLMSDemandRegister();

            dr.LogicalName         = "0.0.1.0.0.255";
            dr.CurrentAverageValue = (uint)10;
            dr.LastAverageValue    = (uint)20;
            dr.Status           = (byte)1;
            dr.StartTimeCurrent = dr.CaptureTime = new GXDateTime(DateTime.Now);
            dr.Period           = 10;
            dr.NumberOfPeriods  = 1;
            Items.Add(dr);

            ///////////////////////////////////////////////////////////////////////
            //Add Register Monitor object.
            GXDLMSRegisterMonitor rm = new GXDLMSRegisterMonitor();

            rm.LogicalName = "0.0.1.0.0.255";
            rm.Thresholds  = new object[] { (int)0x1234, (int)0x5678 };
            GXDLMSActionSet set = new GXDLMSActionSet();

            set.ActionDown.LogicalName    = rm.LogicalName;
            set.ActionDown.ScriptSelector = 1;
            set.ActionUp.LogicalName      = rm.LogicalName;
            set.ActionUp.ScriptSelector   = 2;
            rm.Actions = new GXDLMSActionSet[] { set };
            rm.MonitoredValue.Update(r, 2);
            Items.Add(rm);

            ///////////////////////////////////////////////////////////////////////
            //Add action schedule object.
            GXDLMSActionSchedule actionS = new GXDLMSActionSchedule();

            actionS.LogicalName = "0.0.1.0.0.255";
            actionS.ExecutedScriptLogicalName = "1.2.3.4.5.6";
            actionS.ExecutedScriptSelector    = 1;
            actionS.Type          = SingleActionScheduleType.SingleActionScheduleType1;
            actionS.ExecutionTime = new GXDateTime[] { new GXDateTime(DateTime.Now) };
            Items.Add(actionS);

            ///////////////////////////////////////////////////////////////////////
            //Add SAP Assignment object.
            GXDLMSSapAssignment sap = new GXDLMSSapAssignment();

            sap.SapAssignmentList.Add(new KeyValuePair <UInt16, string>(1, "Gurux"));
            sap.SapAssignmentList.Add(new KeyValuePair <UInt16, string>(16, "Gurux-2"));
            Items.Add(sap);

            ///////////////////////////////////////////////////////////////////////
            //Add Auto Answer object.
            GXDLMSAutoAnswer aa = new GXDLMSAutoAnswer();

            aa.Mode = AutoConnectMode.EmailSending;
            aa.ListeningWindow.Add(new KeyValuePair <GXDateTime, GXDateTime>(new GXDateTime(-1, -1, -1, 6, -1, -1, -1), new GXDateTime(-1, -1, -1, 8, -1, -1, -1)));
            aa.Status        = AutoAnswerStatus.Inactive;
            aa.NumberOfCalls = 0;
            aa.NumberOfRingsInListeningWindow  = 1;
            aa.NumberOfRingsOutListeningWindow = 2;
            Items.Add(aa);

            ///////////////////////////////////////////////////////////////////////
            //Add Modem Configuration object.
            GXDLMSModemConfiguration mc = new GXDLMSModemConfiguration();

            mc.CommunicationSpeed = BaudRate.Baudrate57600;
            GXDLMSModemInitialisation init = new GXDLMSModemInitialisation();

            init.Request             = "AT";
            init.Response            = "OK";
            init.Delay               = 0;
            mc.InitialisationStrings = new GXDLMSModemInitialisation[] { init };
            Items.Add(mc);

            ///////////////////////////////////////////////////////////////////////
            //Add Mac Address Setup object.
            GXDLMSMacAddressSetup mac = new GXDLMSMacAddressSetup();

            mac.MacAddress = "00:11:22:33:44:55:66";
            Items.Add(mac);

            GXDLMSImageTransfer i = new GXDLMSImageTransfer();

            Items.Add(i);
            ///////////////////////////////////////////////////////////////////////
            //Server must initialize after all objects are added.
            Initialize();
        }
 public void PreAction(GXActionArgs arg)
 {
     //Add object to association view.
     if (arg.Index == 3)
     {
         GXDLMSObject it = new GXDLMSData();
         OnShowDialog(it, arg);
     }
     else if (arg.Index == 4)
     {
         // Remove object from association view.
         OnShowDialog(null, arg);
     }
     //Add user to user list.
     else if (arg.Index == 5)
     {
         OnShowDialog(true, arg);
     }
     else if (arg.Index == 6)
     {
         // Remove user from user list.
         OnShowDialog(false, arg);
     }
     if (arg.Action == ActionType.Write && arg.Index == 7)
     {
         DialogResult ret;
         //Update pw.
         ret = GXHelpers.ShowMessageBox(this, Properties.Resources.SetPasswordWarning, "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
         if (ret == DialogResult.Yes)
         {
             byte[] value;
             if (SecretAsciiCb.Checked)
             {
                 value = ASCIIEncoding.ASCII.GetBytes(SecretTB.Text);
             }
             else
             {
                 value = GXDLMSTranslator.HexToBytes(SecretTB.Text);
             }
             GXDLMSAssociationLogicalName target = Target as GXDLMSAssociationLogicalName;
             if (target.AuthenticationMechanismName.MechanismId == Authentication.Low)
             {
                 arg.Index  = 7;
                 arg.Action = ActionType.Write;
             }
             else
             {
                 arg.Action = ActionType.Action;
                 arg.Index  = 2;
             }
             if (arg.Action == ActionType.Write)
             {
                 target.Secret = value;
             }
             else
             {
                 GXByteBuffer bb = new GXByteBuffer();
                 bb.SetUInt8((byte)DataType.OctetString);
                 bb.SetUInt8((byte)value.Length);
                 bb.Set(value);
                 arg.Value = bb.Array();
             }
         }
         arg.Handled = ret != DialogResult.Yes;
     }
     else if (arg.Action == ActionType.Write && arg.Index == 2)
     {
         //Skip write invoke.
         arg.Handled = true;
     }
 }
Пример #13
0
        public void InitializeConnection()
        {
            try
            {
                log("Connection");
                GXReplyData reply = new GXReplyData();
                byte[]      data;
                UpdateSettings();
                //Read frame counter if GeneralProtection is used.
                if (!string.IsNullOrEmpty(parent.FrameCounter) && client.Ciphering != null && client.Ciphering.Security != Security.None)
                {
                    reply.Clear();
                    int            add       = client.ClientAddress;
                    Authentication auth      = client.Authentication;
                    Security       security  = client.Ciphering.Security;
                    byte[]         challenge = client.CtoSChallenge;
                    try
                    {
                        client.ClientAddress      = 16;
                        client.Authentication     = Authentication.None;
                        client.Ciphering.Security = Security.None;

                        data = SNRMRequest();
                        if (data != null)
                        {
                            try
                            {
                                ReadDataBlock(data, "Send SNRM request.", reply);
                            }
                            catch (TimeoutException)
                            {
                                reply.Clear();
                                ReadDataBlock(DisconnectRequest(), "Send Disconnect request.", reply);
                                reply.Clear();
                                ReadDataBlock(data, "Send SNRM request.", reply);
                            }
                            catch (Exception e)
                            {
                                reply.Clear();
                                ReadDataBlock(DisconnectRequest(), "Send Disconnect request.", reply);
                                throw e;
                            }
                            //GXLogWriter.WriteLog("Parsing UA reply succeeded.");
                            //Has server accepted client.
                            ParseUAResponse(reply.Data);
                        }
                        ReadDataBlock(AARQRequest(), "Send AARQ request.", reply);
                        try
                        {
                            //Parse reply.
                            ParseAAREResponse(reply.Data);
                            //GXLogWriter.WriteLog("Parsing AARE reply succeeded.");
                            reply.Clear();
                            GXDLMSData d = new GXDLMSData(parent.FrameCounter);
                            ReadDLMSPacket(Read(d, 2), reply);
                            client.UpdateValue(d, 2, reply.Value);
                            client.Ciphering.InvocationCounter = parent.InvocationCounter = 1 + Convert.ToUInt32(d.Value);
                            reply.Clear();
                            ReadDataBlock(DisconnectRequest(), "Disconnect request", reply);
                        }
                        catch (Exception Ex)
                        {
                            reply.Clear();
                            ReadDataBlock(DisconnectRequest(), "Disconnect request", reply);
                            throw Ex;
                        }
                    }
                    finally
                    {
                        client.ClientAddress      = add;
                        client.Authentication     = auth;
                        client.Ciphering.Security = security;
                        client.CtoSChallenge      = challenge;
                    }
                }
                data = SNRMRequest();
                if (data != null)
                {
                    try
                    {
                        reply.Clear();
                        ReadDataBlock(data, "Send SNRM request.", reply);
                    }
                    catch (TimeoutException)
                    {
                        reply.Clear();
                        ReadDataBlock(DisconnectRequest(), "Send Disconnect request.", reply);
                        reply.Clear();
                        ReadDataBlock(data, "Send SNRM request.", reply);
                    }
                    catch (Exception e)
                    {
                        reply.Clear();
                        ReadDataBlock(DisconnectRequest(), "Send Disconnect request.", reply);
                        throw e;
                    }
                    //GXLogWriter.WriteLog("Parsing UA reply succeeded.");
                    //Has server accepted client.
                    ParseUAResponse(reply.Data);
                }
                if (!parent.PreEstablished)
                {
                    //Generate AARQ request.
                    //Split requests to multiple packets if needed.
                    //If password is used all data might not fit to one packet.
                    reply.Clear();
                    ReadDataBlock(AARQRequest(), "Send AARQ request.", reply);
                    try
                    {
                        //Parse reply.
                        ParseAAREResponse(reply.Data);
                        //GXLogWriter.WriteLog("Parsing AARE reply succeeded.");
                    }
                    catch (Exception Ex)
                    {
                        reply.Clear();
                        ReadDLMSPacket(DisconnectRequest(), reply);
                        throw Ex;
                    }
                    //If authentication is required.
                    if (client.Authentication > Authentication.Low)
                    {
                        reply.Clear();
                        ReadDataBlock(client.GetApplicationAssociationRequest(), "Authenticating.", reply);
                        client.ParseApplicationAssociationResponse(reply.Data);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }