Exemplo n.º 1
0
        ///<summary>
        ///Retrieves the string that indicates the level of authentication, if any.
        ///</summary>
        private static void GetAuthenticationString(GXDLMSSettings settings, GXByteBuffer data)
        {
            //If authentication is used.
            if (settings.Authentication != Authentication.None)
            {
                //Add sender ACSE-requirements field component.
                data.SetUInt8((byte)BerType.Context | (byte)PduType.SenderAcseRequirements);
                data.SetUInt8(2);
                data.SetUInt8(BerType.BitString | BerType.OctetString);
                data.SetUInt8(0x80);

                data.SetUInt8((byte)BerType.Context | (byte)PduType.MechanismName);
                //Len
                data.SetUInt8(7);
                // OBJECT IDENTIFIER
                byte[] p = { (byte)0x60, (byte)0x85, (byte)0x74, (byte)0x05, (byte)0x08, (byte)0x02, (byte)settings.Authentication };
                data.Set(p);
                //Add Calling authentication information.
                int len = 0;
                byte[] callingAuthenticationValue = null;
                if (settings.Authentication == Authentication.Low)
                {
                    if (settings.Password != null)
                    {
                        callingAuthenticationValue = settings.Password;
                        len = callingAuthenticationValue.Length;
                    }
                }
                else
                {
                    callingAuthenticationValue = settings.CtoSChallenge;
                    len = callingAuthenticationValue.Length;
                }
                //0xAC
                data.SetUInt8((byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CallingAuthenticationValue);
                //Len
                data.SetUInt8((byte)(2 + len));
                //Add authentication information.
                data.SetUInt8((byte)BerType.Context);
                //Len.
                data.SetUInt8((byte)len);
                if (len != 0)
                {
                    data.Set(callingAuthenticationValue);
                }
            }
        }
Exemplo n.º 2
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         if (e.Value is string)
         {
             LogicalName = e.Value.ToString();
         }
         else
         {
             LogicalName = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
         }
     }
     else if (e.Index == 2)
     {
         ObjectType ot       = (ObjectType)Convert.ToInt16(((object[])e.Value)[0]);
         string     ln       = GXDLMSClient.ChangeType((byte[])((object[])e.Value)[1], DataType.OctetString).ToString();
         int        attIndex = Convert.ToInt32(((object[])e.Value)[2]);
         MonitoredValue          = settings.Objects.FindByLN(ot, ln);
         MonitoredAttributeIndex = attIndex;
     }
     else if (e.Index == 3)
     {
         ThresholdActive = e.Value;
     }
     else if (e.Index == 4)
     {
         ThresholdNormal = e.Value;
     }
     else if (e.Index == 5)
     {
         ThresholdEmergency = e.Value;
     }
     else if (e.Index == 6)
     {
         MinOverThresholdDuration = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 7)
     {
         MinUnderThresholdDuration = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 8)
     {
         object[] tmp = (object[])e.Value;
         EmergencyProfile.ID             = (UInt16)tmp[0];
         EmergencyProfile.ActivationTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])tmp[1], DataType.DateTime);
         EmergencyProfile.Duration       = (UInt32)tmp[2];
     }
     else if (e.Index == 9)
     {
         List <UInt16> list = new List <UInt16>();
         if (e.Value != null)
         {
             foreach (object it in (object[])e.Value)
             {
                 list.Add(Convert.ToUInt16(it));
             }
         }
         EmergencyProfileGroupIDs = list.ToArray();
     }
     else if (e.Index == 10)
     {
         EmergencyProfileActive = Convert.ToBoolean(e.Value);
     }
     else if (e.Index == 11)
     {
         object[] tmp  = (object[])e.Value;
         object[] tmp1 = (object[])tmp[0];
         object[] tmp2 = (object[])tmp[1];
         ActionOverThreshold.LogicalName     = GXDLMSClient.ChangeType((byte[])tmp1[0], DataType.OctetString).ToString();
         ActionOverThreshold.ScriptSelector  = Convert.ToUInt16(tmp1[1]);
         ActionUnderThreshold.LogicalName    = GXDLMSClient.ChangeType((byte[])tmp2[0], DataType.OctetString).ToString();
         ActionUnderThreshold.ScriptSelector = Convert.ToUInt16(tmp2[1]);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
 /// <summary>
 /// Returns Association View.
 /// </summary>
 private GXByteBuffer GetObjects(GXDLMSSettings settings, ValueEventArgs e)
 {
     int cnt = ObjectList.Count;
     GXByteBuffer data = new GXByteBuffer();
     //Add count only for first time.
     if (settings.Index == 0)
     {
         settings.Count = (UInt16)cnt;
         data.SetUInt8((byte)DataType.Array);
         GXCommon.SetObjectCount(cnt, data);
     }
     ushort pos = 0;
     foreach (GXDLMSObject it in ObjectList)
     {
         ++pos;
         if (!(pos <= settings.Index))
         {
             data.SetUInt8((byte)DataType.Structure);
             //Count
             data.SetUInt8((byte)4);
             //base address.
             GXCommon.SetData(settings, data, DataType.Int16, it.ShortName);
             //ClassID
             GXCommon.SetData(settings, data, DataType.UInt16, it.ObjectType);
             //Version
             GXCommon.SetData(settings, data, DataType.UInt8, 0);
             //LN
             GXCommon.SetData(settings, data, DataType.OctetString, it.LogicalName);
             ++settings.Index;
             //If PDU is full.
             if (!e.SkipMaxPduSize && data.Size >= settings.MaxPduSize)
             {
                 break;
             }
         }
     }
     return data;
 }
Exemplo n.º 4
0
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Exemplo n.º 5
0
 ///<summary>
 ///Get data from DLMS frame.
 ///</summary>
 ///<param name="settings">DLMS settings.</param>
 ///<param name="data">Received data.</param>
 ///<param name="info"> Data info.</param>
 ///<returns>Parsed object.</returns>
 ///
 public static object GetData(GXDLMSSettings settings, GXByteBuffer data, GXDataInfo info)
 {
     object value = null;
     int startIndex = data.Position;
     if (data.Position == data.Size)
     {
         info.Complete = false;
         return null;
     }
     info.Complete = true;
     bool knownType = info.Type != DataType.None;
     // Get data type if it is unknown.
     if (!knownType)
     {
         info.Type = (DataType)data.GetUInt8();
     }
     if (info.Type == DataType.None)
     {
         if (info.xml != null)
         {
             info.xml.AppendLine("<" + info.xml.GetDataType(info.Type) + " />");
         }
         return value;
     }
     if (data.Position == data.Size)
     {
         info.Complete = false;
         return null;
     }
     switch (info.Type)
     {
         case DataType.Array:
         case DataType.Structure:
             value = GetArray(data, info, startIndex);
             break;
         case DataType.Boolean:
             value = GetBoolean(data, info);
             break;
         case DataType.BitString:
             value = GetBitString(data, info);
             break;
         case DataType.Int32:
             value = GetInt32(data, info);
             break;
         case DataType.UInt32:
             value = GetUInt32(data, info);
             break;
         case DataType.String:
             value = GetString(data, info, knownType);
             break;
         case DataType.StringUTF8:
             value = GetUtfString(data, info, knownType);
             break;
         case DataType.OctetString:
             value = GetOctetString(data, info, knownType);
             break;
         case DataType.Bcd:
             value = GetBcd(data, info, knownType);
             break;
         case DataType.Int8:
             value = GetInt8(data, info);
             break;
         case DataType.Int16:
             value = GetInt16(data, info);
             break;
         case DataType.UInt8:
             value = GetUInt8(data, info);
             break;
         case DataType.UInt16:
             value = GetUInt16(data, info);
             break;
         case DataType.CompactArray:
             throw new Exception("Invalid data type.");
         case DataType.Int64:
             value = GetInt64(data, info);
             break;
         case DataType.UInt64:
             value = GetUInt64(data, info);
             break;
         case DataType.Enum:
             value = GetEnum(data, info);
             break;
         case DataType.Float32:
             value = Getfloat(data, info);
             break;
         case DataType.Float64:
             value = GetDouble(data, info);
             break;
         case DataType.DateTime:
             value = GetDateTime(settings, data, info);
             break;
         case DataType.Date:
             value = GetDate(data, info);
             break;
         case DataType.Time:
             value = GetTime(data, info);
             break;
         default:
             throw new Exception("Invalid data type.");
     }
     return value;
 }
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                if (e.Value is string)
                {
                    LogicalName = e.Value.ToString();
                }
                else
                {
                    LogicalName = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
                }
            }
            else if (e.Index == 2)
            {
                ObjectList.Clear();
                if (e.Value != null)
                {
                    foreach (Object[] item in (Object[])e.Value)
                    {
                        ObjectType type = (ObjectType)Convert.ToInt32(item[0]);
                        int version = Convert.ToInt32(item[1]);
                        String ln = GXDLMSObject.ToLogicalName((byte[])item[2]);
                        GXDLMSObject obj = null;
                        if (settings.Objects != null)
                        {
                            obj = settings.Objects.FindByLN(type, ln);
                        }
                        if (obj == null)
                        {
                            obj = Gurux.DLMS.GXDLMSClient.CreateObject(type);
                            obj.LogicalName = ln;
                            obj.Version = version;
                        }
                        //Unknown objects are not shown.
                        if (obj is IGXDLMSBase && item[3] != null)
                        {
                            UpdateAccessRights(obj, (Object[])item[3]);
                            ObjectList.Add(obj);
                        }
                    }
                }
            }
            else if (e.Index == 3)
            {
                if (e.Value != null)
                {
                    ClientSAP = Convert.ToByte(((Object[])e.Value)[0]);
                    ServerSAP = Convert.ToUInt16(((Object[])e.Value)[1]);
                }
            }
            else if (e.Index == 4)
            {
                //Value of the object identifier encoded in BER
                if (e.Value is byte[])
                {
                    GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
                    if (arr.GetUInt8(0) == 0x60)
                    {

                        ApplicationContextName.JointIsoCtt = 0;
                        ++arr.Position;
                        ApplicationContextName.Country = 0;
                        ++arr.Position;
                        ApplicationContextName.CountryName = 0;
                        ++arr.Position;
                        ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                        ApplicationContextName.DlmsUA = arr.GetUInt8();
                        ApplicationContextName.ApplicationContext = arr.GetUInt8();
                        ApplicationContextName.ContextId = arr.GetUInt8();
                    }
                    else
                    {
                        //Get Tag and Len.
                        if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.JointIsoCtt = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.Country = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x12)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.CountryName = arr.GetUInt16();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.DlmsUA = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.ApplicationContext = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        ApplicationContextName.ContextId = arr.GetUInt8();
                    }
                }
                else if (e.Value != null)
                {
                    Object[] arr = (Object[])e.Value;
                    ApplicationContextName.JointIsoCtt = Convert.ToByte(arr[0]);
                    ApplicationContextName.Country = Convert.ToByte(arr[1]);
                    ApplicationContextName.CountryName = Convert.ToUInt16(arr[2]);
                    ApplicationContextName.IdentifiedOrganization = Convert.ToByte(arr[3]);
                    ApplicationContextName.DlmsUA = Convert.ToByte(arr[4]);
                    ApplicationContextName.ApplicationContext = Convert.ToByte(arr[5]);
                    ApplicationContextName.ContextId = Convert.ToByte(arr[6]);
                }
            }
            else if (e.Index == 5)
            {
                if (e.Value != null)
                {
                    Object[] arr = (Object[])e.Value;
                    XDLMSContextInfo.Conformance = arr[0].ToString();
                    XDLMSContextInfo.MaxReceivePduSize = Convert.ToUInt16(arr[1]);
                    XDLMSContextInfo.MaxSendPpuSize = Convert.ToUInt16(arr[2]);
                    XDLMSContextInfo.DlmsVersionNumber = Convert.ToByte(arr[3]);
                    XDLMSContextInfo.QualityOfService = Convert.ToSByte(arr[4]);
                    XDLMSContextInfo.CypheringInfo = (byte[])arr[5];
                }
            }
            else if (e.Index == 6)
            {
                //Value of the object identifier encoded in BER
                if (e.Value is byte[])
                {
                    GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
                    if (arr.GetUInt8(0) == 0x60)
                    {
                        AuthenticationMechanismMame.JointIsoCtt = 0;
                        ++arr.Position;
                        AuthenticationMechanismMame.Country = 0;
                        ++arr.Position;
                        AuthenticationMechanismMame.CountryName = 0;
                        ++arr.Position;
                        AuthenticationMechanismMame.IdentifiedOrganization = arr.GetUInt8();
                        AuthenticationMechanismMame.DlmsUA = arr.GetUInt8();
                        AuthenticationMechanismMame.AuthenticationMechanismName = arr.GetUInt8();
                        AuthenticationMechanismMame.MechanismId = (Authentication)arr.GetUInt8();
                    }
                    else
                    {
                        //Get Tag and Len.
                        if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.JointIsoCtt = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.Country = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x12)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.CountryName = arr.GetUInt16();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.IdentifiedOrganization = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.DlmsUA = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.AuthenticationMechanismName = arr.GetUInt8();
                        //Get tag
                        if (arr.GetUInt8() != 0x11)
                        {
                            throw new ArgumentOutOfRangeException();
                        }
                        AuthenticationMechanismMame.MechanismId = (Authentication)arr.GetUInt8();
                    }
                }
                else if (e.Value != null)
                {
                    Object[] arr = (Object[])e.Value;
                    AuthenticationMechanismMame.JointIsoCtt = Convert.ToByte(arr[0]);
                    AuthenticationMechanismMame.Country = Convert.ToByte(arr[1]);
                    AuthenticationMechanismMame.CountryName = Convert.ToUInt16(arr[2]);
                    AuthenticationMechanismMame.IdentifiedOrganization = Convert.ToByte(arr[3]);
                    AuthenticationMechanismMame.DlmsUA = Convert.ToByte(arr[4]);
                    AuthenticationMechanismMame.AuthenticationMechanismName = Convert.ToByte(arr[5]);
                    AuthenticationMechanismMame.MechanismId = (Authentication)Convert.ToByte(arr[6]);
                }
            }
            else if (e.Index == 7)
            {
                Secret = (byte[])e.Value;
            }
            else if (e.Index == 8)
            {
                if (e.Value == null)
                {
                    AssociationStatus = AssociationStatus.NonAssociated;
                }
                else
                {
                    AssociationStatus = (AssociationStatus)Convert.ToInt32(e.Value);
                }
            }
            else if (e.Index == 9)
            {
                SecuritySetupReference = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
            }
            else
            {
                e.Error = ErrorCode.ReadWriteDenied;
            }
        }
Exemplo n.º 7
0
        private static void updatePassword(GXDLMSSettings settings, GXByteBuffer buff, GXDLMSTranslatorStructure xml)
        {
            int len = buff.GetUInt8();
            // Get authentication information.
            if (buff.GetUInt8() != 0x80)
            {
                throw new Exception("Invalid tag.");
            }
            len = buff.GetUInt8();
            if (settings.Authentication == Authentication.Low)
            {
                settings.Password = new byte[len];
                buff.Get(settings.Password);
            }
            else
            {
                settings.CtoSChallenge = new byte[len];
                buff.Get(settings.CtoSChallenge);
            }

            if (xml != null)
            {
                if (xml.OutputType == TranslatorOutputType.SimpleXml)
                {
                    if (settings.Authentication == Authentication.Low)
                    {
                        xml.AppendLine(TranslatorGeneralTags.CallingAuthentication,
                                       "Value",
                                       GXCommon.ToHex(settings.Password, false));
                    }
                    else
                    {
                        xml.AppendLine(TranslatorGeneralTags.CallingAuthentication,
                                       "Value",
                                       GXCommon.ToHex(settings.CtoSChallenge, false));
                    }
                }
                else
                {
                    xml.AppendStartTag(
                        TranslatorGeneralTags.CallingAuthentication);
                    xml.AppendStartTag(TranslatorGeneralTags.CharString);
                    if (settings.Authentication == Authentication.Low)
                    {
                        xml.Append(GXCommon.ToHex(settings.Password, false));
                    }
                    else
                    {
                        xml.Append(
                            GXCommon.ToHex(settings.CtoSChallenge, false));
                    }
                    xml.AppendEndTag(TranslatorGeneralTags.CharString);
                    xml.AppendEndTag(TranslatorGeneralTags.CallingAuthentication);
                }
            }
        }
Exemplo n.º 8
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         ObjectList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 ushort       sn      = (ushort)(Convert.ToInt32(item[0]) & 0xFFFF);
                 ObjectType   type    = (ObjectType)Convert.ToInt32(item[1]);
                 int          version = Convert.ToInt32(item[2]);
                 String       ln      = GXCommon.ToLogicalName((byte[])item[3]);
                 GXDLMSObject obj     = null;
                 if (settings.Objects != null)
                 {
                     obj = settings.Objects.FindBySN(sn);
                 }
                 if (obj == null)
                 {
                     obj = Gurux.DLMS.GXDLMSClient.CreateObject(type);
                     if (obj != null)
                     {
                         obj.LogicalName = ln;
                         obj.ShortName   = sn;
                         obj.Version     = version;
                     }
                 }
                 //Unknown objects are not shown.
                 if (obj is IGXDLMSBase)
                 {
                     ObjectList.Add(obj);
                 }
             }
         }
     }
     else if (e.Index == 3)
     {
         if (e.Value == null)
         {
             foreach (GXDLMSObject it in ObjectList)
             {
                 for (int pos = 1; pos != (it as IGXDLMSBase).GetAttributeCount(); ++pos)
                 {
                     it.SetAccess(pos, AccessMode.NoAccess);
                 }
             }
         }
         else
         {
             UpdateAccessRights((Object[])e.Value);
         }
     }
     else if (e.Index == 4)
     {
         SecuritySetupReference = GXCommon.ToLogicalName(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 9
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                LogicalName = GXCommon.ToLogicalName(e.Value);
                break;

            case 2:
                TotalAmountPaid = (Int32)e.Value;
                break;

            case 3:
                ChargeType = (ChargeType)e.Value;
                break;

            case 4:
                Priority = (byte)e.Value;
                break;

            case 5:
                SetUnitCharge(UnitChargeActive, e.Value);
                break;

            case 6:
                SetUnitCharge(UnitChargePassive, e.Value);
                break;

            case 7:
                UnitChargeActivationTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
                break;

            case 8:
                Period = (UInt32)e.Value;
                break;

            case 9:
                ChargeConfiguration = Convert.ToString(e.Value);
                break;

            case 10:
                LastCollectionTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
                break;

            case 11:
                LastCollectionAmount = (Int32)e.Value;
                break;

            case 12:
                TotalAmountRemaining = (Int32)e.Value;
                break;

            case 13:
                Proportion = (UInt16)e.Value;
                break;

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
        }
Exemplo n.º 10
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         if (e.Value == null)
         {
             Time = new GXDateTime(DateTime.MinValue);
         }
         else
         {
             if (e.Value is byte[])
             {
                 e.Value = GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
             }
             else if (e.Value is string)
             {
                 e.Value = new GXDateTime((string)e.Value);
             }
             if (e.Value is GXDateTime)
             {
                 Time = (GXDateTime)e.Value;
             }
             else if (e.Value is String)
             {
                 DateTime tm;
                 if (!DateTime.TryParse((String)e.Value, out tm))
                 {
                     Time = DateTime.ParseExact((String)e.Value, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern, CultureInfo.CurrentUICulture);
                 }
                 else
                 {
                     Time = tm;
                 }
             }
             else
             {
                 Time = Convert.ToDateTime(e.Value);
             }
         }
     }
     else if (e.Index == 3)
     {
         TimeZone = Convert.ToInt32(e.Value);
     }
     else if (e.Index == 4)
     {
         Status = (ClockStatus)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 5)
     {
         if (e.Value == null)
         {
             Begin = new GXDateTime(DateTime.MinValue);
         }
         else
         {
             if (e.Value is byte[])
             {
                 e.Value = GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
             }
             else if (e.Value is string)
             {
                 e.Value = new GXDateTime((string)e.Value);
             }
             Begin = (GXDateTime)e.Value;
         }
     }
     else if (e.Index == 6)
     {
         if (e.Value == null)
         {
             End = new GXDateTime(DateTime.MinValue);
         }
         else
         {
             if (e.Value is byte[])
             {
                 e.Value = GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
             }
             else if (e.Value is string)
             {
                 e.Value = new GXDateTime((string)e.Value);
             }
             End = (GXDateTime)e.Value;
         }
     }
     else if (e.Index == 7)
     {
         Deviation = Convert.ToInt32(e.Value);
     }
     else if (e.Index == 8)
     {
         Enabled = Convert.ToBoolean(e.Value);
         if (settings.IsServer)
         {
             if (Enabled)
             {
                 Status |= ClockStatus.DaylightSavingActive;
             }
             else
             {
                 Status &= ~ClockStatus.DaylightSavingActive;
             }
         }
     }
     else if (e.Index == 9)
     {
         ClockBase = (ClockBase)Convert.ToInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     //Check reply_to_HLS_authentication
     if (e.Index == 8)
     {
         UInt32 ic = 0;
         byte[] secret;
         if (settings.Authentication == Authentication.HighGMAC)
         {
             secret = settings.SourceSystemTitle;
             GXByteBuffer bb = new GXByteBuffer(e.Parameters as byte[]);
             bb.GetUInt8();
             ic = bb.GetUInt32();
         }
         else if (settings.Authentication == Authentication.HighSHA256)
         {
             GXByteBuffer tmp = new GXByteBuffer();
             tmp.Set(Secret);
             tmp.Set(settings.SourceSystemTitle);
             tmp.Set(settings.Cipher.SystemTitle);
             tmp.Set(settings.StoCChallenge);
             tmp.Set(settings.CtoSChallenge);
             secret = tmp.Array();
         }
         else
         {
             secret = Secret;
         }
         byte[] serverChallenge = GXSecure.Secure(settings, settings.Cipher, ic, settings.StoCChallenge, secret);
         byte[] clientChallenge = (byte[])e.Parameters;
         if (GXCommon.Compare(serverChallenge, clientChallenge))
         {
             if (settings.Authentication == Authentication.HighGMAC)
             {
                 secret = settings.Cipher.SystemTitle;
                 ic     = settings.Cipher.InvocationCounter++;
             }
             else
             {
                 secret = Secret;
             }
             settings.Connected |= ConnectionState.Dlms;
             if (settings.Authentication == Authentication.HighSHA256)
             {
                 GXByteBuffer tmp = new GXByteBuffer();
                 tmp.Set(Secret);
                 tmp.Set(settings.Cipher.SystemTitle);
                 tmp.Set(settings.SourceSystemTitle);
                 tmp.Set(settings.CtoSChallenge);
                 tmp.Set(settings.StoCChallenge);
                 secret = tmp.Array();
             }
             return(GXSecure.Secure(settings, settings.Cipher, ic, settings.CtoSChallenge, secret));
         }
         else
         {
             // If the password does not match.
             settings.Connected &= ~ConnectionState.Dlms;
             return(null);
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
         return(null);
     }
 }
Exemplo n.º 12
0
        byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
        {
            DateTimeOffset tm = this.Time.Value;

            // Resets the value to the default value.
            // The default value is an instance specific constant.
            if (e.Index == 1)
            {
                int minutes = tm.Minute;
                if (minutes < 8)
                {
                    minutes = 0;
                }
                else if (minutes < 23)
                {
                    minutes = 15;
                }
                else if (minutes < 38)
                {
                    minutes = 30;
                }
                else if (minutes < 53)
                {
                    minutes = 45;
                }
                else
                {
                    minutes = 0;
                    tm      = tm.AddHours(1);
                }
                tm = tm.AddMinutes(-tm.Minute + minutes);
                tm = tm.AddSeconds(-tm.Second);
                tm = tm.AddMilliseconds(-tm.Millisecond);
                this.Time.Value = tm;
            }
            // Sets the meter's time to the nearest minute.
            else if (e.Index == 3)
            {
                tm = this.Time.Value;
                int s = tm.Second;
                if (s > 30)
                {
                    tm = tm.AddMinutes(1);
                }
                tm = tm.AddSeconds(-tm.Second);
                tm = tm.AddMilliseconds(-tm.Millisecond);
                this.Time.Value = tm;
            }
            // Presets the time to a new value (preset_time) and defines
            // avalidity_interval within which the new time can be activated.
            else if (e.Index == 5)
            {
                GXDateTime presetTime            = (GXDateTime)GXDLMSClient.ChangeType((byte[])((List <object>)e.Parameters)[0], DataType.DateTime, settings.UseUtc2NormalTime);
                GXDateTime validityIntervalStart = (GXDateTime)GXDLMSClient.ChangeType((byte[])((List <object>)e.Parameters)[1], DataType.DateTime, settings.UseUtc2NormalTime);
                GXDateTime validityIntervalEnd   = (GXDateTime)GXDLMSClient.ChangeType((byte[])((List <object>)e.Parameters)[2], DataType.DateTime, settings.UseUtc2NormalTime);
                this.Time.Value = presetTime.Value;
            }
            // Shifts the time.
            else if (e.Index == 6)
            {
                int shift = Convert.ToInt32(e.Parameters);
                tm = tm.AddSeconds(shift);
                this.Time.Value = tm;
            }
            else
            {
                e.Error = ErrorCode.ReadWriteDenied;
            }
            return(null);
        }
Exemplo n.º 13
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return((byte)Mode);
     }
     if (e.Index == 3)
     {
         return(Repetitions);
     }
     if (e.Index == 4)
     {
         return(RepetitionDelay);
     }
     if (e.Index == 5)
     {
         int          cnt  = CallingWindow.Count;
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         //Add count
         GXCommon.SetObjectCount(cnt, data);
         if (cnt != 0)
         {
             foreach (var it in CallingWindow)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)2);                                           //Count
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Key);   //start_time
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Value); //end_time
             }
         }
         return(data.Array());
     }
     if (e.Index == 6)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (Destinations == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = Destinations.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (string it in Destinations)
             {
                 GXCommon.SetData(settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it)); //destination
             }
         }
         return(data.Array());
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 14
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, int index, int selector, object parameters)
        {
            if (index == 1)
            {
                return(this.LogicalName);
            }
            if (index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                data.SetUInt8((byte)Entries.Count);

                /*
                 * foreach (GXScheduleEntry it in Entries)
                 * {
                 *  data.SetUInt8((byte)DataType.Structure);
                 *  data.SetUInt8(10);
                 *  //Add index.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.Index);
                 *  //Add enable.
                 *  data.SetUInt8((byte)DataType.Boolean);
                 *  data.SetUInt8((byte) (it.Enable ? 1 : 0));
                 *
                 *  //Add logical Name.
                 *  data.SetUInt8((byte)DataType.OctetString);
                 *  data.SetUInt8((byte) it.LogicalName.Length);
                 *  //TODO: data.SetUInt8((byte)it.LogicalName.Length);
                 *
                 *  //Add script selector.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.ScriptSelector);
                 *
                 *  //Add switch time.
                 *  ret = var_setDateTime(&tmp, &se->switchTime);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 *  //Add validity window.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.ValidityWindow);
                 *
                 *  //Add exec week days.
                 *  ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                 *  setObjectCount(se->execWeekdays.size, &value->byteArr);
                 *  ba_addRange(&value->byteArr, se->execWeekdays.data, bit_getByteCount(se->execWeekdays.size));
                 *
                 *  //Add exec spec days.
                 *  ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                 *  setObjectCount(se->execSpecDays.size, &value->byteArr);
                 *  ba_addRange(&value->byteArr, se->execSpecDays.data, bit_getByteCount(se->execSpecDays.size));
                 *
                 *  //Add begin date.
                 *  ret = var_setDateTime(&tmp, &se->beginDate);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 *  //Add end date.
                 *  ret = var_setDateTime(&tmp, &se->endDate);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 * }
                 * */
                return(data.Array());
            }
            throw new ArgumentException("GetValue failed. Invalid attribute index.");
        }
Exemplo n.º 15
0
 /// <summary>
 /// Generate user information.
 /// </summary>
 /// <param name="settings">DLMS settings.</param>
 /// <param name="cipher"></param>
 /// <param name="data">Generated user information.</param>
 static internal void GenerateUserInformation(GXDLMSSettings settings, GXICipher cipher, GXByteBuffer encryptedData, GXByteBuffer data)
 {
     data.SetUInt8((byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.UserInformation);
     if (cipher == null || !cipher.IsCiphered())
     {
         //Length for AARQ user field
         data.SetUInt8(0x10);
         //Coding the choice for user-information (Octet STRING, universal)
         data.SetUInt8(BerType.OctetString);
         //Length
         data.SetUInt8(0x0E);
         GetInitiateRequest(settings, cipher, data);
     }
     else
     {
         if (encryptedData != null && encryptedData.Size != 0)
         {
             //Length for AARQ user field
             data.SetUInt8((byte)(4 + encryptedData.Size));
             //Tag
             data.SetUInt8(BerType.OctetString);
             data.SetUInt8((byte)(2 + encryptedData.Size));
             //Coding the choice for user-information (Octet STRING, universal)
             data.SetUInt8((byte)Command.GloInitiateRequest);
             data.SetUInt8((byte)encryptedData.Size);
             data.Set(encryptedData);
         }
         else
         {
             GXByteBuffer tmp = new GXByteBuffer();
             GetInitiateRequest(settings, cipher, tmp);
             byte[] crypted = cipher.Encrypt((byte)Command.GloInitiateRequest, cipher.SystemTitle, tmp.Array());
             //Length for AARQ user field
             data.SetUInt8((byte)(2 + crypted.Length));
             //Coding the choice for user-information (Octet STRING, universal)
             data.SetUInt8(BerType.OctetString);
             data.SetUInt8((byte)crypted.Length);
             data.Set(crypted);
         }
     }
 }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return(GetObjects(settings, e).Array());
     }
     if (e.Index == 3)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         data.SetUInt8(2);
         data.SetUInt8((byte)DataType.Int8);
         data.SetUInt8(ClientSAP);
         data.SetUInt8((byte)DataType.UInt16);
         data.SetUInt16(ServerSAP);
         return(data.Array());
     }
     if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         data.SetUInt8(0x7);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.JointIsoCtt);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.Country);
         GXCommon.SetData(settings, data, DataType.UInt16, ApplicationContextName.CountryName);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.IdentifiedOrganization);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.DlmsUA);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.ApplicationContext);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.ContextId);
         return(data.Array());
     }
     if (e.Index == 5)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8(6);
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt32((UInt32)XDLMSContextInfo.Conformance);
         GXCommon.SetData(settings, data, DataType.BitString, bb.SubArray(1, 3));
         GXCommon.SetData(settings, data, DataType.UInt16, XDLMSContextInfo.MaxReceivePduSize);
         GXCommon.SetData(settings, data, DataType.UInt16, XDLMSContextInfo.MaxSendPduSize);
         GXCommon.SetData(settings, data, DataType.UInt8, XDLMSContextInfo.DlmsVersionNumber);
         GXCommon.SetData(settings, data, DataType.Int8, XDLMSContextInfo.QualityOfService);
         GXCommon.SetData(settings, data, DataType.OctetString, XDLMSContextInfo.CypheringInfo);
         return(data.Array());
     }
     if (e.Index == 6)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         data.SetUInt8(0x7);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.JointIsoCtt);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.Country);
         GXCommon.SetData(settings, data, DataType.UInt16, AuthenticationMechanismName.CountryName);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.IdentifiedOrganization);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.DlmsUA);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.AuthenticationMechanismName);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismName.MechanismId);
         return(data.Array());
     }
     if (e.Index == 7)
     {
         return(Secret);
     }
     if (e.Index == 8)
     {
         return(AssociationStatus);
     }
     if (e.Index == 9)
     {
         return(GXCommon.LogicalNameToBytes(SecuritySetupReference));
     }
     if (e.Index == 10)
     {
         return(GetUserList(settings, e).Array());
     }
     if (e.Index == 11)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add structure size.
         data.SetUInt8(2);
         GXCommon.SetData(settings, data, DataType.UInt8, CurrentUser.Key);
         GXCommon.SetData(settings, data, DataType.String, CurrentUser.Value);
         return(data.Array());
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 17
0
        /// <summary>
        /// Parse User Information from PDU.
        /// </summary>
        public static void ParseUserInformation(GXDLMSSettings settings, GXICipher cipher, GXByteBuffer data, GXDLMSTranslatorStructure xml)
        {
            byte len = data.GetUInt8();
            GXByteBuffer tmp2 = new GXByteBuffer();
            tmp2.SetUInt8(0);
            if (data.Size - data.Position < len)
            {
                throw new Exception("Not enough data.");
            }
            if (xml != null && xml.OutputType == TranslatorOutputType.StandardXml)
            {
                len = (byte)(data.Size - data.Position);
                xml.AppendLine(Command.InitiateRequest, null, GXCommon
                               .ToHex(data.Data, false, data.Position, len));
                data.Position = data.Position + len;
                return;
            }
            //Excoding the choice for user information
            int tag = data.GetUInt8();
            if (tag != 0x4)
            {
                throw new Exception("Invalid tag.");
            }
            len = data.GetUInt8();
            //Tag for xDLMS-Initate.response
            tag = data.GetUInt8();
            if (tag == (byte)Command.GloInitiateResponse)
            {
                if (xml != null)
                {
                    int cnt = GXCommon.GetObjectCount(data);
                    byte[] tmp = new byte[cnt];
                    data.Get(tmp);
                    //<glo_InitiateResponse>
                    xml.AppendLine(Command.GloInitiateResponse, "Value", GXCommon.ToHex(tmp, false));
                    return;
                }
                --data.Position;
                cipher.Security = cipher.Decrypt(settings.SourceSystemTitle, data);
                tag = data.GetUInt8();
            }
            else if (tag == (byte)Command.GloInitiateRequest)
            {
                if (xml != null)
                {
                    int cnt = GXCommon.GetObjectCount(data);
                    byte[] tmp = new byte[cnt];
                    data.Get(tmp);
                    //<glo_InitiateRequest>
                    xml.AppendLine(Command.GloInitiateRequest, "Value", GXCommon.ToHex(tmp, false));
                    return;
                }
                --data.Position;
                cipher.Security = cipher.Decrypt(settings.SourceSystemTitle, data);
                tag = data.GetUInt8();
            }
            bool response = tag == (byte)Command.InitiateResponse;
            if (response)
            {
                if (xml != null)
                {
                    //<InitiateResponse>
                    xml.AppendStartTag(Command.InitiateResponse);
                }
                //Optional usage field of the negotiated quality of service component
                tag = data.GetUInt8();
                len = 0;
                if (tag != 0)//Skip if used.
                {
                    len = data.GetUInt8();
                    data.Position += len;
                    if (len == 0 && xml != null)
                    {
                        //NegotiatedQualityOfService
                        xml.AppendLine(TranslatorGeneralTags.NegotiatedQualityOfService, "Value", "00");
                    }
                }
            }
            else if (tag == (byte)Command.InitiateRequest)
            {
                if (xml != null)
                {
                    //<InitiateRequest>
                    xml.AppendStartTag(Command.InitiateRequest);
                }
                //Optional usage field of the negotiated quality of service component
                tag = data.GetUInt8();
                //CtoS.
                if (tag != 0)
                {
                    len = data.GetUInt8();
                    settings.CtoSChallenge = new byte[len];
                    data.Get(settings.CtoSChallenge);
                }
                //Optional usage field of the negotiated quality of service component
                tag = data.GetUInt8();
                if (tag != 0)//Skip if used.
                {
                    len = data.GetUInt8();
                    data.Position += len;
                }
                //Optional usage field of the proposed quality of service component
                tag = data.GetUInt8();
                if (tag != 0)//Skip if used.
                {
                    len = data.GetUInt8();
                    data.Position += len;
                }
            }
            else
            {
                throw new Exception("Invalid tag.");
            }
            //Get DLMS version number.
            if (!response)
            {
                if (data.GetUInt8() != 6)
                {
                    throw new Exception("Invalid DLMS version number.");
                }
                //ProposedDlmsVersionNumber
                if (xml != null)
                {
                    xml.AppendLine(TranslatorGeneralTags.ProposedDlmsVersionNumber, "Value", xml.IntegerToHex(settings.DLMSVersion, 2));
                }
            }
            else
            {
                if (data.GetUInt8() != 6)
                {
                    throw new Exception("Invalid DLMS version number.");
                }
                if (xml != null)
                {
                    xml.AppendLine(TranslatorGeneralTags.NegotiatedDlmsVersionNumber, "Value", xml.IntegerToHex(settings.DLMSVersion, 2));
                }
            }

            //Tag for conformance block
            tag = data.GetUInt8();
            if (tag != 0x5F)
            {
                throw new Exception("Invalid tag.");
            }
            //Old Way...
            if (data.GetUInt8(data.Position) == 0x1F)
            {
                data.GetUInt8();
            }
            len = data.GetUInt8();
            //The number of unused bits in the bit string.
            tag = data.GetUInt8();
            if (!response)
            {
                //ProposedConformance
                if (xml != null)
                {
                    xml.AppendStartTag(TranslatorGeneralTags.ProposedConformance);
                }
                data.Get(settings.ConformanceBlock);
                tmp2.Set(settings.ConformanceBlock);
            }
            else
            {
                //NegotiatedConformance
                if (xml != null)
                {
                    xml.AppendStartTag(TranslatorGeneralTags.NegotiatedConformance);
                }
                if (settings.UseLogicalNameReferencing)
                {
                    data.Get(settings.LnSettings.ConformanceBlock);
                    tmp2.Set(settings.LnSettings.ConformanceBlock);
                }
                else
                {
                    data.Get(settings.SnSettings.ConformanceBlock);
                    tmp2.Set(settings.SnSettings.ConformanceBlock);
                }
            }
            if (xml != null)
            {
                GetConformance(tmp2.GetUInt32(), xml);
            }
            if (!response)
            {
                //Proposed max PDU size.
                settings.MaxPduSize = data.GetUInt16();
                if (xml != null)
                {
                    //ProposedConformance closing
                    xml.AppendEndTag(TranslatorGeneralTags.ProposedConformance);
                    //ProposedMaxPduSize
                    xml.AppendLine(TranslatorGeneralTags.ProposedMaxPduSize, "Value", xml.IntegerToHex(settings.MaxPduSize, 4));
                }
                //If client asks too high PDU.
                if (settings.MaxPduSize > settings.MaxServerPDUSize)
                {
                    settings.MaxPduSize = settings.MaxServerPDUSize;
                }
            }
            else
            {
                //Max PDU size.
                settings.MaxPduSize = data.GetUInt16();
                if (xml != null)
                {
                    //NegotiatedConformance closing
                    xml.AppendEndTag(TranslatorGeneralTags.NegotiatedConformance);
                    //NegotiatedMaxPduSize
                    xml.AppendLine(TranslatorGeneralTags.NegotiatedMaxPduSize, "Value", xml.IntegerToHex(settings.MaxPduSize, 4));
                }
            }
            if (response)
            {
                //VAA Name
                tag = data.GetUInt16();
                if (xml != null)
                {
                    xml.AppendLine(TranslatorGeneralTags.VaaName, "Value", xml.IntegerToHex(tag, 4));
                }
                if (tag == 0x0007)
                {
                    // If LN
                    if (!settings.UseLogicalNameReferencing)
                    {
                        throw new ArgumentException("Invalid VAA.");
                    }
                }
                else if (tag == 0xFA00)
                {
                    // If SN
                    if (settings.UseLogicalNameReferencing)
                    {
                        throw new ArgumentException("Invalid VAA.");
                    }
                }
                else
                {
                    // Unknown VAA.
                    throw new ArgumentException("Invalid VAA.");
                }
                if (xml != null)
                {
                    //<InitiateResponse>
                    xml.AppendEndTag(Command.InitiateResponse);
                }
            }
            else if (xml != null)
            {
                //</InitiateRequest>
                xml.AppendEndTag(Command.InitiateRequest);
            }
        }
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         ObjectList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 GXDLMSObject obj = GetObject(settings, item);
                 //Unknown objects are not shown.
                 if (obj is IGXDLMSBase)
                 {
                     ObjectList.Add(obj);
                 }
             }
         }
     }
     else if (e.Index == 3)
     {
         if (e.Value != null)
         {
             ClientSAP = Convert.ToByte(((Object[])e.Value)[0]);
             ServerSAP = Convert.ToUInt16(((Object[])e.Value)[1]);
         }
     }
     else if (e.Index == 4)
     {
         //Value of the object identifier encoded in BER
         if (e.Value is byte[])
         {
             GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
             if (arr.GetUInt8(0) == 0x60)
             {
                 ApplicationContextName.JointIsoCtt            = arr.GetUInt8();
                 ApplicationContextName.Country                = arr.GetUInt8();
                 ApplicationContextName.CountryName            = arr.GetUInt8();
                 ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                 ApplicationContextName.DlmsUA             = arr.GetUInt8();
                 ApplicationContextName.ApplicationContext = arr.GetUInt8();
                 ApplicationContextName.ContextId          = (ApplicationContextName)arr.GetUInt8();
             }
             else
             {
                 //Get Tag and Len.
                 if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.JointIsoCtt = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.Country = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x12)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.CountryName = arr.GetUInt16();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.DlmsUA = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.ApplicationContext = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.ContextId = (ApplicationContextName)arr.GetUInt8();
             }
         }
         else if (e.Value != null)
         {
             Object[] arr = (Object[])e.Value;
             ApplicationContextName.JointIsoCtt            = Convert.ToByte(arr[0]);
             ApplicationContextName.Country                = Convert.ToByte(arr[1]);
             ApplicationContextName.CountryName            = Convert.ToUInt16(arr[2]);
             ApplicationContextName.IdentifiedOrganization = Convert.ToByte(arr[3]);
             ApplicationContextName.DlmsUA             = Convert.ToByte(arr[4]);
             ApplicationContextName.ApplicationContext = Convert.ToByte(arr[5]);
             ApplicationContextName.ContextId          = (ApplicationContextName)Convert.ToByte(arr[6]);
         }
     }
     else if (e.Index == 5)
     {
         if (e.Value != null)
         {
             Object[]     arr = (Object[])e.Value;
             GXByteBuffer bb  = new GXByteBuffer();
             GXCommon.SetBitString(bb, arr[0]);
             bb.SetUInt8(0, 0);
             XDLMSContextInfo.Conformance       = (Conformance)bb.GetUInt32();
             XDLMSContextInfo.MaxReceivePduSize = Convert.ToUInt16(arr[1]);
             XDLMSContextInfo.MaxSendPduSize    = Convert.ToUInt16(arr[2]);
             XDLMSContextInfo.DlmsVersionNumber = Convert.ToByte(arr[3]);
             XDLMSContextInfo.QualityOfService  = Convert.ToSByte(arr[4]);
             XDLMSContextInfo.CypheringInfo     = (byte[])arr[5];
         }
     }
     else if (e.Index == 6)
     {
         //Value of the object identifier encoded in BER
         if (e.Value is byte[])
         {
             GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
             if (arr.GetUInt8(0) == 0x60)
             {
                 AuthenticationMechanismName.JointIsoCtt            = arr.GetUInt8();
                 AuthenticationMechanismName.Country                = arr.GetUInt8();
                 AuthenticationMechanismName.CountryName            = arr.GetUInt8();
                 AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8();
                 AuthenticationMechanismName.DlmsUA = arr.GetUInt8();
                 AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8();
                 AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8();
             }
             else
             {
                 //Get Tag and Len.
                 if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.JointIsoCtt = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.Country = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x12)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.CountryName = arr.GetUInt16();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.DlmsUA = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8();
             }
         }
         else if (e.Value != null)
         {
             Object[] arr = (Object[])e.Value;
             AuthenticationMechanismName.JointIsoCtt            = Convert.ToByte(arr[0]);
             AuthenticationMechanismName.Country                = Convert.ToByte(arr[1]);
             AuthenticationMechanismName.CountryName            = Convert.ToUInt16(arr[2]);
             AuthenticationMechanismName.IdentifiedOrganization = Convert.ToByte(arr[3]);
             AuthenticationMechanismName.DlmsUA = Convert.ToByte(arr[4]);
             AuthenticationMechanismName.AuthenticationMechanismName = Convert.ToByte(arr[5]);
             AuthenticationMechanismName.MechanismId = (Authentication)Convert.ToByte(arr[6]);
         }
     }
     else if (e.Index == 7)
     {
         Secret = (byte[])e.Value;
     }
     else if (e.Index == 8)
     {
         if (e.Value == null)
         {
             AssociationStatus = AssociationStatus.NonAssociated;
         }
         else
         {
             AssociationStatus = (AssociationStatus)Convert.ToInt32(e.Value);
         }
     }
     else if (e.Index == 9)
     {
         SecuritySetupReference = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 10)
     {
         UserList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 UserList.Add(new KeyValuePair <byte, string>(Convert.ToByte(item[0]), Convert.ToString(item[1])));
             }
         }
     }
     else if (e.Index == 11)
     {
         if (e.Value != null)
         {
             Object[] tmp = (Object[])e.Value;
             CurrentUser = new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1]));
         }
         else
         {
             CurrentUser = new KeyValuePair <byte, string>(0, null);
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 19
0
 private static void AppendServerSystemTitleToXml(
     GXDLMSSettings settings, GXDLMSTranslatorStructure xml,
     int tag)
 {
     if (xml != null)
     {
         // RespondingAuthentication
         if (xml.OutputType == TranslatorOutputType.SimpleXml)
         {
             xml.AppendLine(tag, "Value", GXCommon.ToHex(settings.StoCChallenge, false));
         }
         else
         {
             xml.Append(tag, true);
             xml.Append((int)TranslatorGeneralTags.CharString, true);
             xml.Append(GXCommon.ToHex(settings.StoCChallenge, false));
             xml.Append((int)TranslatorGeneralTags.CharString, false);
             xml.Append(tag, false);
             xml.Append("\r\n");
         }
     }
 }
Exemplo n.º 20
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return(ShortAddress);
     }
     if (e.Index == 3)
     {
         return(RcCoord);
     }
     if (e.Index == 4)
     {
         return(PANId);
     }
     if (e.Index == 5)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (KeyTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(KeyTable.Count, bb);
             foreach (GXKeyValuePair <byte, byte[]> it in KeyTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(2);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Key);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Value);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 6)
     {
         return(FrameCounter);
     }
     if (e.Index == 7)
     {
         return(ToneMask);
     }
     if (e.Index == 8)
     {
         return(TmrTtl);
     }
     if (e.Index == 9)
     {
         return(MaxFrameRetries);
     }
     if (e.Index == 10)
     {
         return(NeighbourTableEntryTtl);
     }
     if (e.Index == 11)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (NeighbourTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(NeighbourTable.Length, bb);
             foreach (GXDLMSNeighbourTable it in NeighbourTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(11);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.ShortAddress);
                 GXCommon.SetData(settings, bb, DataType.Boolean, it.Enabled);
                 GXCommon.SetData(settings, bb, DataType.BitString, it.ToneMap);
                 GXCommon.SetData(settings, bb, DataType.Enum, it.Modulation);
                 GXCommon.SetData(settings, bb, DataType.Int8, it.TxGain);
                 GXCommon.SetData(settings, bb, DataType.Enum, it.TxRes);
                 GXCommon.SetData(settings, bb, DataType.BitString, it.TxCoeff);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Lqi);
                 GXCommon.SetData(settings, bb, DataType.Int8, it.PhaseDifferential);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.TMRValidTime);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.NeighbourValidTime);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 12)
     {
         return(HighPriorityWindowSize);
     }
     if (e.Index == 13)
     {
         return(CscmFairnessLimit);
     }
     if (e.Index == 14)
     {
         return(BeaconRandomizationWindowLength);
     }
     if (e.Index == 15)
     {
         return(A);
     }
     if (e.Index == 16)
     {
         return(K);
     }
     if (e.Index == 17)
     {
         return(MinCwAttempts);
     }
     if (e.Index == 18)
     {
         return(CenelecLegacyMode);
     }
     if (e.Index == 19)
     {
         return(FccLegacyMode);
     }
     if (e.Index == 20)
     {
         return(MaxBe);
     }
     if (e.Index == 21)
     {
         return(MaxCsmaBackoffs);
     }
     if (e.Index == 22)
     {
         return(MinBe);
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
 private void GetAccessRights(GXDLMSSettings settings, GXDLMSObject item, GXByteBuffer data)
 {
     data.SetUInt8((byte)DataType.Structure);
     data.SetUInt8((byte)2);
     data.SetUInt8((byte)DataType.Array);
     GXAttributeCollection attributes = item.Attributes;
     int cnt = (item as IGXDLMSBase).GetAttributeCount();
     data.SetUInt8((byte)cnt);
     for (int pos = 0; pos != cnt; ++pos)
     {
         GXDLMSAttributeSettings att = attributes.Find(pos + 1);
         data.SetUInt8((byte)DataType.Structure); //attribute_access_item
         data.SetUInt8((byte)3);
         GXCommon.SetData(settings, data, DataType.Int8, pos + 1);
         //If attribute is not set return read only.
         if (att == null)
         {
             GXCommon.SetData(settings, data, DataType.Enum, AccessMode.Read);
         }
         else
         {
             GXCommon.SetData(settings, data, DataType.Enum, att.Access);
         }
         GXCommon.SetData(settings, data, DataType.None, null);
     }
     data.SetUInt8((byte)DataType.Array);
     attributes = item.MethodAttributes;
     cnt = (item as IGXDLMSBase).GetMethodCount();
     data.SetUInt8((byte)cnt);
     for (int pos = 0; pos != cnt; ++pos)
     {
         GXDLMSAttributeSettings att = attributes.Find(pos + 1);
         data.SetUInt8((byte)DataType.Structure); //attribute_access_item
         data.SetUInt8((byte)2);
         GXCommon.SetData(settings, data, DataType.Int8, pos + 1);
         //If method attribute is not set return no access.
         if (att == null)
         {
             GXCommon.SetData(settings, data, DataType.Enum, MethodAccessMode.NoAccess);
         }
         else
         {
             GXCommon.SetData(settings, data, DataType.Enum, att.MethodAccess);
         }
     }
 }
Exemplo n.º 22
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         ShortAddress = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 3)
     {
         RcCoord = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 4)
     {
         PANId = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 5)
     {
         KeyTable.Clear();
         if (e.Value != null)
         {
             foreach (object v in (object[])e.Value)
             {
                 object[] tmp = (object[])v;
                 KeyTable.Add(new GXKeyValuePair <byte, byte[]>(Convert.ToByte(tmp[0]), (byte[])tmp[1]));
             }
         }
     }
     else if (e.Index == 6)
     {
         FrameCounter = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 7)
     {
         ToneMask = Convert.ToString(e.Value);
     }
     else if (e.Index == 8)
     {
         TmrTtl = Convert.ToByte(e.Value);
     }
     else if (e.Index == 9)
     {
         MaxFrameRetries = Convert.ToByte(e.Value);
     }
     else if (e.Index == 10)
     {
         NeighbourTableEntryTtl = Convert.ToByte(e.Value);
     }
     else if (e.Index == 11)
     {
         List <GXDLMSNeighbourTable> list = new List <GXDLMSNeighbourTable>();
         if (e.Value != null)
         {
             foreach (object v in (object[])e.Value)
             {
                 object[]             tmp = (object[])v;
                 GXDLMSNeighbourTable it  = new GXDLMSNeighbourTable();
                 it.ShortAddress       = Convert.ToUInt16(tmp[0]);
                 it.Enabled            = Convert.ToBoolean(tmp[1]);
                 it.ToneMap            = Convert.ToString(tmp[2]);
                 it.Modulation         = (Modulation)Convert.ToInt32(tmp[3]);
                 it.TxGain             = Convert.ToSByte(tmp[4]);
                 it.TxRes              = (GainResolution)Convert.ToInt32(tmp[5]);
                 it.TxCoeff            = Convert.ToString(tmp[6]);
                 it.Lqi                = Convert.ToByte(tmp[7]);
                 it.PhaseDifferential  = Convert.ToSByte(tmp[8]);
                 it.TMRValidTime       = Convert.ToByte(tmp[9]);
                 it.NeighbourValidTime = Convert.ToByte(tmp[10]);
                 list.Add(it);
             }
         }
         NeighbourTable = list.ToArray();
     }
     else if (e.Index == 12)
     {
         HighPriorityWindowSize = Convert.ToByte(e.Value);
     }
     else if (e.Index == 13)
     {
         CscmFairnessLimit = Convert.ToByte(e.Value);
     }
     else if (e.Index == 14)
     {
         BeaconRandomizationWindowLength = Convert.ToByte(e.Value);
     }
     else if (e.Index == 15)
     {
         A = Convert.ToByte(e.Value);
     }
     else if (e.Index == 16)
     {
         K = Convert.ToByte(e.Value);
     }
     else if (e.Index == 17)
     {
         MinCwAttempts = Convert.ToByte(e.Value);
     }
     else if (e.Index == 18)
     {
         CenelecLegacyMode = Convert.ToByte(e.Value);
     }
     else if (e.Index == 19)
     {
         FccLegacyMode = Convert.ToByte(e.Value);
     }
     else if (e.Index == 20)
     {
         MaxBe = Convert.ToByte(e.Value);
     }
     else if (e.Index == 21)
     {
         MaxCsmaBackoffs = Convert.ToByte(e.Value);
     }
     else if (e.Index == 22)
     {
         MinBe = Convert.ToByte(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 23
0
        ///<summary>
        ///Convert date time to DLMS bytes.
        ///</summary>
        ///<param name="buff">
        ///Byte buffer where data is write.
        ///</param>
        ///<param name="value">
        ///Added value.
        ///</param>
        private static void SetDateTime(GXDLMSSettings settings, GXByteBuffer buff, object value)
        {
            GXDateTime dt;
            if (value is GXDateTime)
            {
                dt = (GXDateTime)value;
            }
            else if (value is DateTime)
            {
                dt = new GXDateTime((DateTime)value);
                dt.Skip = dt.Skip | DateTimeSkips.Ms;
            }
            else if (value is string)
            {
                dt = new GXDateTime(DateTime.Parse((string)value));
                dt.Skip = dt.Skip | DateTimeSkips.Ms;
            }
            else
            {
                throw new Exception("Invalid date format.");
            }
            if (dt.Value.UtcDateTime == DateTime.MinValue)
            {
                dt.Value = DateTime.SpecifyKind(new DateTime(2000, 1, 1).Date, DateTimeKind.Utc);
            }
            else if (dt.Value.UtcDateTime == DateTime.MaxValue)
            {
                dt.Value = DateTime.SpecifyKind(DateTime.Now.AddYears(1).Date, DateTimeKind.Utc);
            }
            DateTimeOffset tm = dt.Value;
            if ((dt.Skip & DateTimeSkips.Year) == 0)
            {
                buff.SetUInt16((ushort)tm.Year);
            }
            else
            {
                buff.SetUInt16(0xFFFF);
            }
            if ((dt.Skip & DateTimeSkips.Month) == 0)
            {
                if (dt.DaylightSavingsBegin)
                {
                    buff.SetUInt8(0xFE);
                }
                else if (dt.DaylightSavingsEnd)
                {
                    buff.SetUInt8(0xFD);
                }
                else
                {
                    buff.SetUInt8((byte)tm.Month);
                }
            }
            else
            {
                buff.SetUInt8(0xFF);
            }
            if ((dt.Skip & DateTimeSkips.Day) == 0)
            {
                buff.SetUInt8((byte)tm.Day);
            }
            else
            {
                buff.SetUInt8(0xFF);
            }
            // Add week day
            if ((dt.Skip & DateTimeSkips.DayOfWeek) != 0)
            {
                buff.SetUInt8(0xFF);
            }
            else
            {
                if (dt.Value.DayOfWeek == DayOfWeek.Sunday)
                {
                    buff.SetUInt8(7);
                }
                else
                {
                    buff.SetUInt8((byte)(dt.Value.DayOfWeek));
                }
            }
            //Add time.
            if ((dt.Skip & DateTimeSkips.Hour) == 0)
            {
                buff.SetUInt8((byte)tm.Hour);
            }
            else
            {
                buff.SetUInt8(0xFF);
            }

            if ((dt.Skip & DateTimeSkips.Minute) == 0)
            {
                buff.SetUInt8((byte)tm.Minute);
            }
            else
            {
                buff.SetUInt8(0xFF);
            }
            if ((dt.Skip & DateTimeSkips.Second) == 0)
            {
                buff.SetUInt8((byte)tm.Second);
            }
            else
            {
                buff.SetUInt8(0xFF);
            }

            if ((dt.Skip & DateTimeSkips.Ms) == 0)
            {
                buff.SetUInt8((byte)(tm.Millisecond / 10));
            }
            else
            {
                buff.SetUInt8((byte)0xFF); //Hundredths of second is not used.
            }
            //Add deviation.
            if ((dt.Skip & DateTimeSkips.Devitation) == 0)
            {
                if (settings != null && settings.UtcTimeZone)
                {
                    buff.SetInt16((Int16)(dt.Value.Offset.TotalMinutes));
                }
                else
                {
                    buff.SetInt16((Int16)(-dt.Value.Offset.TotalMinutes));
                }
            }
            else //deviation not used.
            {
                buff.SetUInt16(0x8000);
            }
            //Add clock_status
            if (dt.Value.LocalDateTime.IsDaylightSavingTime())
            {
                buff.SetUInt8((byte)(dt.Status | ClockStatus.DaylightSavingActive));
            }
            else
            {
                buff.SetUInt8((byte)dt.Status);
            }
        }
Exemplo n.º 24
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return(GXCommon.LogicalNameToBytes(DataLinkLayerReference));
     }
     if (e.Index == 3)
     {
         return(FromAddressString(IPAddress));
     }
     if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (MulticastIPAddress == null)
         {
             //Object count is zero.
             data.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(MulticastIPAddress.Length, data);
             foreach (string it in MulticastIPAddress)
             {
                 GXCommon.SetData(settings, data, DataType.UInt32, FromAddressString(it));
             }
         }
         return(data.Array());
     }
     if (e.Index == 5)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (IPOptions == null)
         {
             //Object count is zero.
             data.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(IPOptions.Length, data);
             foreach (GXDLMSIp4SetupIpOption it in IPOptions)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8(3);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Type);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Length);
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Data);
             }
         }
         return(data.Array());
     }
     if (e.Index == 6)
     {
         //If subnet mask is not given.
         return(FromAddressString(SubnetMask));
     }
     if (e.Index == 7)
     {
         return(FromAddressString(GatewayIPAddress));
     }
     if (e.Index == 8)
     {
         return(this.UseDHCP);
     }
     if (e.Index == 9)
     {
         return(FromAddressString(PrimaryDNSAddress));
     }
     if (e.Index == 10)
     {
         return(FromAddressString(SecondaryDNSAddress));
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 25
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return (byte)Mode;
     }
     if (e.Index == 3)
     {
         int cnt = ListeningWindow.Count;
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         //Add count
         GXCommon.SetObjectCount(cnt, data);
         if (cnt != 0)
         {
             foreach (var it in ListeningWindow)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)2); //Count
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Key); //start_time
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Value); //end_time
             }
         }
         return data.Array();
     }
     if (e.Index == 4)
     {
         return Status;
     }
     if (e.Index == 5)
     {
         return NumberOfCalls;
     }
     if (e.Index == 6)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         GXCommon.SetObjectCount(2, data);
         GXCommon.SetData(settings, data, DataType.UInt8, NumberOfRingsInListeningWindow);
         GXCommon.SetData(settings, data, DataType.UInt8, NumberOfRingsOutListeningWindow);
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Exemplo n.º 26
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         DataLinkLayerReference = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 3)
     {
         IPAddress = ToAddressString(e.Value);
     }
     else if (e.Index == 4)
     {
         List <string> data = new List <string>();
         if (e.Value is Object[])
         {
             if (e.Value is Object[])
             {
                 foreach (object it in (Object[])e.Value)
                 {
                     data.Add(ToAddressString(it));
                 }
             }
             else if (e.Value is UInt16[])
             {
                 //Some meters are returning wrong data here.
                 foreach (UInt16 it in (UInt16[])e.Value)
                 {
                     data.Add(ToAddressString(it));
                 }
             }
         }
         MulticastIPAddress = data.ToArray();
     }
     else if (e.Index == 5)
     {
         List <GXDLMSIp4SetupIpOption> data = new List <GXDLMSIp4SetupIpOption>();
         if (e.Value is Object[])
         {
             foreach (object[] it in (Object[])e.Value)
             {
                 GXDLMSIp4SetupIpOption item = new GXDLMSIp4SetupIpOption();
                 item.Type   = (Ip4SetupIpOptionType)Convert.ToInt32(it[0]);
                 item.Length = Convert.ToByte(it[1]);
                 item.Data   = (byte[])it[2];
                 data.Add(item);
             }
         }
         IPOptions = data.ToArray();
     }
     else if (e.Index == 6)
     {
         SubnetMask = ToAddressString(Convert.ToUInt32(e.Value));
     }
     else if (e.Index == 7)
     {
         GatewayIPAddress = ToAddressString(e.Value);
     }
     else if (e.Index == 8)
     {
         UseDHCP = Convert.ToBoolean(e.Value);
     }
     else if (e.Index == 9)
     {
         PrimaryDNSAddress = ToAddressString(e.Value);
     }
     else if (e.Index == 10)
     {
         SecondaryDNSAddress = ToAddressString(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
    byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
    {
        //Check reply_to_HLS_authentication
        if (e.Index == 8)
        {
            UInt32 ic = 0;
            byte[] secret;
            if (settings.Authentication == Authentication.HighGMAC)
            {
                secret = settings.SourceSystemTitle;
                GXByteBuffer bb = new GXByteBuffer(e.Parameters as byte[]);
                bb.GetUInt8();
                ic = bb.GetUInt32();
            }
            else
            {
                secret = HlsSecret;
            }
            byte[] serverChallenge = GXSecure.Secure(settings, settings.Cipher, ic, settings.StoCChallenge, secret);
            byte[] clientChallenge = (byte[])e.Parameters;
            if (GXCommon.Compare(serverChallenge, clientChallenge))
            {
                if (settings.Authentication == Authentication.HighGMAC)
                {
                    secret = settings.Cipher.SystemTitle;
                    ic = settings.Cipher.FrameCounter;
                }
                else
                {
                    secret = HlsSecret;
                }
                settings.Connected = true;
                return GXSecure.Secure(settings, settings.Cipher, ic, settings.CtoSChallenge, secret);
            }
            else
            {
                // If the password does not match.
                settings.Connected = false;
                return null;
            }

        }
        else
        {
            e.Error = ErrorCode.ReadWriteDenied;
            return null;
        }
    }
Exemplo n.º 28
0
 /// <summary>
 /// Data interface do not have any methods.
 /// </summary>
 /// <param name="index"></param>
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, int index, Object parameters)
 {
     throw new ArgumentException("Invoke failed. Invalid attribute index.");
 }
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         if (e.Value is string)
         {
             LogicalName = e.Value.ToString();
         }
         else
         {
             LogicalName = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
         }
     }
     else if (e.Index == 2)
     {
         ObjectList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 ushort sn = (ushort)(Convert.ToInt32(item[0]) & 0xFFFF);
                 ObjectType type = (ObjectType)Convert.ToInt32(item[1]);
                 int version = Convert.ToInt32(item[2]);
                 String ln = GXDLMSObject.ToLogicalName((byte[])item[3]);
                 GXDLMSObject obj = null;
                 if (settings.Objects != null)
                 {
                     obj = settings.Objects.FindBySN(sn);
                 }
                 if (obj == null)
                 {
                     obj = Gurux.DLMS.GXDLMSClient.CreateObject(type);
                     if (obj != null)
                     {
                         obj.LogicalName = ln;
                         obj.ShortName = sn;
                         obj.Version = version;
                     }
                 }
                 //Unknown objects are not shown.
                 if (obj is IGXDLMSBase)
                 {
                     ObjectList.Add(obj);
                 }
             }
         }
     }
     else if (e.Index == 3)
     {
         if (e.Value == null)
         {
             foreach (GXDLMSObject it in ObjectList)
             {
                 for (int pos = 1; pos != (it as IGXDLMSBase).GetAttributeCount(); ++pos)
                 {
                     it.SetAccess(pos, AccessMode.NoAccess);
                 }
             }
         }
         else
         {
             UpdateAccessRights((Object[])e.Value);
         }
     }
     else if (e.Index == 4)
     {
         if (e.Value is string)
         {
             SecuritySetupReference = e.Value.ToString();
         }
         else
         {
             SecuritySetupReference = GXDLMSClient.ChangeType(e.Value as byte[], DataType.OctetString).ToString();
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 30
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                return(GXCommon.LogicalNameToBytes(LogicalName));
            }
            if (e.Index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                data.SetUInt8((byte)Entries.Count);

                /*TODO:
                 * foreach (GXScheduleEntry it in Entries)
                 * {
                 *  data.SetUInt8((byte)DataType.Structure);
                 *  data.SetUInt8(10);
                 *  //Add index.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.Index);
                 *  //Add enable.
                 *  data.SetUInt8((byte)DataType.Boolean);
                 *  data.SetUInt8((byte) (it.Enable ? 1 : 0));
                 *
                 *  //Add logical Name.
                 *  data.SetUInt8((byte)DataType.OctetString);
                 *  data.SetUInt8((byte) it.LogicalName.Length);
                 *  //TODO: data.SetUInt8((byte)it.LogicalName.Length);
                 *
                 *  //Add script selector.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.ScriptSelector);
                 *
                 *  //Add switch time.
                 *  ret = var_setDateTime(&tmp, &se->switchTime);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 *  //Add validity window.
                 *  data.SetUInt8((byte)DataType.UInt8);
                 *  data.SetUInt8(it.ValidityWindow);
                 *
                 *  //Add exec week days.
                 *  ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                 *  setObjectCount(se->execWeekdays.size, &value->byteArr);
                 *  ba_addRange(&value->byteArr, se->execWeekdays.data, bit_getByteCount(se->execWeekdays.size));
                 *
                 *  //Add exec spec days.
                 *  ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                 *  setObjectCount(se->execSpecDays.size, &value->byteArr);
                 *  ba_addRange(&value->byteArr, se->execSpecDays.data, bit_getByteCount(se->execSpecDays.size));
                 *
                 *  //Add begin date.
                 *  ret = var_setDateTime(&tmp, &se->beginDate);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 *  //Add end date.
                 *  ret = var_setDateTime(&tmp, &se->endDate);
                 *  if (ret != 0)
                 *  {
                 *      var_clear(&tmp);
                 *      break;
                 *  }
                 *  ret = var_getBytes(&tmp, &value->byteArr);
                 *  var_clear(&tmp);
                 *  if (ret != 0)
                 *  {
                 *      break;
                 *  }
                 * }
                 * */
                return(data.Array());
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return(null);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Generate User information initiate request.
        /// </summary>
        /// <param name="settings">DLMS settings.</param>
        /// <param name="cipher"></param>
        /// <param name="data"></param>
        private static void GetInitiateRequest(GXDLMSSettings settings, GXICipher cipher, GXByteBuffer data)
        {
            // Tag for xDLMS-Initiate request
            data.SetUInt8((byte)Command.InitiateRequest);
            // Usage field for dedicated-key component. Not used
            data.SetUInt8(0x00);
            //encoding of the response-allowed component (BOOLEAN DEFAULT TRUE)
            // usage flag (FALSE, default value TRUE conveyed)
            data.SetUInt8(0);

            // Usage field of the proposed-quality-of-service component. Not used
            data.SetUInt8(0x00);
            data.SetUInt8(settings.DLMSVersion);
            // Tag for conformance block
            data.SetUInt8(0x5F);
            data.SetUInt8(0x1F);
            // length of the conformance block
            data.SetUInt8(0x04);
            // encoding the number of unused bits in the bit string
            data.SetUInt8(0x00);
            if (settings.UseLogicalNameReferencing)
            {
                data.Set(settings.LnSettings.ConformanceBlock);
            }
            else
            {
                data.Set(settings.SnSettings.ConformanceBlock);
            }
            data.SetUInt16(settings.MaxPduSize);
        }
Exemplo n.º 32
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return(MaxHops);
     }
     if (e.Index == 3)
     {
         return(WeakLqiValue);
     }
     if (e.Index == 4)
     {
         return(SecurityLevel);
     }
     if (e.Index == 5)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (PrefixTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(PrefixTable.Length, bb);
             foreach (var it in PrefixTable)
             {
                 GXCommon.SetData(settings, bb, GXDLMSConverter.GetDLMSDataType(it), it);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 6)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (RoutingConfiguration == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(RoutingConfiguration.Count, bb);
             foreach (GXDLMSRoutingConfiguration it in RoutingConfiguration)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(14);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.NetTraversalTime);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.RoutingTableEntryTtl);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Kr);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Km);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Kc);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Kq);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Kh);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.Krt);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.RreqRetries);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.RreqRerrWait);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.BlacklistTableEntryTtl);
                 GXCommon.SetData(settings, bb, DataType.Boolean, it.UnicastRreqGenEnable);
                 GXCommon.SetData(settings, bb, DataType.Boolean, it.RlcEnabled);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.AddRevLinkCost);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 7)
     {
         return(BroadcastLogTableEntryTtl);
     }
     if (e.Index == 8)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (RoutingTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(RoutingTable.Count, bb);
             foreach (GXDLMSRoutingTable it in RoutingTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(6);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.DestinationAddress);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.NextHopAddress);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.RouteCost);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.HopCount);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.WeakLinkCount);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.ValidTime);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 9)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (ContextInformationTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(ContextInformationTable.Count, bb);
             foreach (GXDLMSContextInformationTable it in ContextInformationTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(5);
                 GXCommon.SetData(settings, bb, DataType.BitString, it.CID);
                 if (it.Context == null)
                 {
                     GXCommon.SetData(settings, bb, DataType.UInt8, 0);
                 }
                 else
                 {
                     GXCommon.SetData(settings, bb, DataType.UInt8, it.Context.Length);
                 }
                 GXCommon.SetData(settings, bb, DataType.OctetString, it.Context);
                 GXCommon.SetData(settings, bb, DataType.Boolean, it.Compression);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.ValidLifetime);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 10)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (BlacklistTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(BlacklistTable.Count, bb);
             foreach (var it in BlacklistTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(2);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.Key);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.Value);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 11)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (BroadcastLogTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(BroadcastLogTable.Count, bb);
             foreach (GXDLMSBroadcastLogTable it in BroadcastLogTable)
             {
                 bb.SetUInt8((byte)DataType.Structure);
                 bb.SetUInt8(3);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.SourceAddress);
                 GXCommon.SetData(settings, bb, DataType.UInt8, it.SequenceNumber);
                 GXCommon.SetData(settings, bb, DataType.UInt16, it.ValidTime);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 12)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8((byte)DataType.Array);
         if (GroupTable == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(GroupTable.Length, bb);
             foreach (UInt16 it in GroupTable)
             {
                 GXCommon.SetData(settings, bb, DataType.UInt16, it);
             }
         }
         return(bb.Array());
     }
     if (e.Index == 13)
     {
         return(MaxJoinWaitTime);
     }
     if (e.Index == 14)
     {
         return(PathDiscoveryTime);
     }
     if (e.Index == 15)
     {
         return(ActiveKeyIndex);
     }
     if (e.Index == 16)
     {
         return(MetricType);
     }
     if (e.Index == 17)
     {
         return(CoordShortAddress);
     }
     if (e.Index == 18)
     {
         return(DisableDefaultRouting);
     }
     if (e.Index == 19)
     {
         return(DeviceType);
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 33
0
 ///<summary>
 /// Generates Aarq.
 ///</summary>
 static internal void GenerateAarq(GXDLMSSettings settings, GXICipher cipher, GXByteBuffer encryptedData, GXByteBuffer data)
 {
     //AARQ APDU Tag
     data.SetUInt8(BerType.Application | BerType.Constructed);
     //Length is updated later.
     int offset = data.Size;
     data.SetUInt8(0);
     ///////////////////////////////////////////
     // Add Application context name.
     GenerateApplicationContextName(settings, data, cipher);
     GetAuthenticationString(settings, data);
     GenerateUserInformation(settings, cipher, encryptedData, data);
     data.SetUInt8(offset, (byte)(data.Size - offset - 1));
 }
Exemplo n.º 34
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         MaxHops = Convert.ToByte(e.Value);
     }
     else if (e.Index == 3)
     {
         WeakLqiValue = Convert.ToByte(e.Value);
     }
     else if (e.Index == 4)
     {
         SecurityLevel = Convert.ToByte(e.Value);
     }
     else if (e.Index == 5)
     {
         List <object> list = new List <object>();
         if (e.Value != null)
         {
             list.AddRange((List <object>)e.Value);
         }
         PrefixTable = list.ToArray();
     }
     else if (e.Index == 6)
     {
         RoutingConfiguration.Clear();
         if (e.Value != null)
         {
             foreach (List <object> v in (List <object>)e.Value)
             {
                 GXDLMSRoutingConfiguration it = new GXDLMSRoutingConfiguration();
                 it.NetTraversalTime     = Convert.ToByte(v[0]);
                 it.RoutingTableEntryTtl = Convert.ToUInt16(v[1]);
                 it.Kr                     = Convert.ToByte(v[2]);
                 it.Km                     = Convert.ToByte(v[3]);
                 it.Kc                     = Convert.ToByte(v[4]);
                 it.Kq                     = Convert.ToByte(v[5]);
                 it.Kh                     = Convert.ToByte(v[6]);
                 it.Krt                    = Convert.ToByte(v[7]);
                 it.RreqRetries            = Convert.ToByte(v[8]);
                 it.RreqRerrWait           = Convert.ToByte(v[9]);
                 it.BlacklistTableEntryTtl = Convert.ToUInt16(v[10]);
                 it.UnicastRreqGenEnable   = Convert.ToBoolean(v[11]);
                 it.RlcEnabled             = Convert.ToBoolean(v[12]);
                 it.AddRevLinkCost         = Convert.ToByte(v[13]);
                 RoutingConfiguration.Add(it);
             }
         }
     }
     else if (e.Index == 7)
     {
         BroadcastLogTableEntryTtl = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 8)
     {
         RoutingTable.Clear();
         if (e.Value != null)
         {
             foreach (List <object> v in (List <object>)e.Value)
             {
                 GXDLMSRoutingTable it = new GXDLMSRoutingTable();
                 it.DestinationAddress = Convert.ToUInt16(v[0]);
                 it.NextHopAddress     = Convert.ToUInt16(v[1]);
                 it.RouteCost          = Convert.ToUInt16(v[2]);
                 it.HopCount           = Convert.ToByte(v[3]);
                 it.WeakLinkCount      = Convert.ToByte(v[4]);
                 it.ValidTime          = Convert.ToUInt16(v[5]);
                 RoutingTable.Add(it);
             }
         }
     }
     else if (e.Index == 9)
     {
         ContextInformationTable.Clear();
         if (e.Value != null)
         {
             foreach (List <object> v in (List <object>)e.Value)
             {
                 GXDLMSContextInformationTable it = new GXDLMSContextInformationTable();
                 it.CID           = Convert.ToString(v[0]);
                 it.Context       = (byte[])v[2];
                 it.Compression   = Convert.ToBoolean(v[3]);
                 it.ValidLifetime = Convert.ToUInt16(v[4]);
                 ContextInformationTable.Add(it);
             }
         }
     }
     else if (e.Index == 10)
     {
         List <GXKeyValuePair <UInt16, UInt16> > list = new List <GXKeyValuePair <UInt16, UInt16> >();
         if (e.Value != null)
         {
             foreach (List <object> v in (List <object>)e.Value)
             {
                 list.Add(new GXKeyValuePair <UInt16, UInt16>(Convert.ToUInt16(v[0]), Convert.ToUInt16(v[1])));
             }
         }
         BlacklistTable = list;
     }
     else if (e.Index == 11)
     {
         BroadcastLogTable.Clear();
         if (e.Value != null)
         {
             foreach (List <object> v in (List <object>)e.Value)
             {
                 GXDLMSBroadcastLogTable it = new GXDLMSBroadcastLogTable();
                 it.SourceAddress  = Convert.ToUInt16(v[0]);
                 it.SequenceNumber = Convert.ToByte(v[1]);
                 it.ValidTime      = Convert.ToUInt16(v[2]);
                 BroadcastLogTable.Add(it);
             }
         }
     }
     else if (e.Index == 12)
     {
         List <UInt16> list = new List <UInt16>();
         if (e.Value != null)
         {
             foreach (object it in (List <object>)e.Value)
             {
                 list.Add(Convert.ToUInt16(it));
             }
         }
         GroupTable = list.ToArray();
     }
     else if (e.Index == 13)
     {
         MaxJoinWaitTime = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 14)
     {
         PathDiscoveryTime = Convert.ToByte(e.Value);
     }
     else if (e.Index == 15)
     {
         ActiveKeyIndex = Convert.ToByte(e.Value);
     }
     else if (e.Index == 16)
     {
         MetricType = Convert.ToByte(e.Value);
     }
     else if (e.Index == 17)
     {
         CoordShortAddress = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 18)
     {
         DisableDefaultRouting = (bool)e.Value;
     }
     else if (e.Index == 19)
     {
         DeviceType = (DeviceType)Convert.ToInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 35
0
 /// <summary>
 /// Parse application context name.
 /// </summary>
 /// <param name="settings">DLMS settings.</param>
 /// <param name="buff">Received data.</param>
 private static bool ParseApplicationContextName(GXDLMSSettings settings, GXByteBuffer buff, GXDLMSTranslatorStructure xml)
 {
     //Get length.
     int len = buff.GetUInt8();
     if (buff.Size - buff.Position < len)
     {
         throw new Exception("Encoding failed. Not enough data.");
     }
     if (buff.GetUInt8() != 0x6)
     {
         throw new Exception("Encoding failed. Not an Object ID.");
     }
     if (settings.IsServer && settings.Cipher != null)
     {
         settings.Cipher.Security = Gurux.DLMS.Enums.Security.None;
     }
     //Object ID length.
     len = buff.GetUInt8();
     if (xml != null)
     {
         if (buff.Compare(GXCommon.LogicalNameObjectID))
         {
             if (xml.OutputType == TranslatorOutputType.SimpleXml)
             {
                 xml.AppendLine(TranslatorGeneralTags.ApplicationContextName,
                                "Value", "LN");
             }
             else
             {
                 xml.AppendLine(
                     TranslatorGeneralTags.ApplicationContextName,
                     null, "1");
             }
             settings.UseLogicalNameReferencing = true;
         }
         else if (buff.Compare(GXCommon.LogicalNameObjectIdWithCiphering))
         {
             if (xml.OutputType == TranslatorOutputType.SimpleXml)
             {
                 xml.AppendLine(TranslatorGeneralTags.ApplicationContextName,
                                "Value", "LN_WITH_CIPHERING");
             }
             else
             {
                 xml.AppendLine(
                     TranslatorGeneralTags.ApplicationContextName,
                     null, "3");
             }
             settings.UseLogicalNameReferencing = true;
         }
         else if (buff.Compare(GXCommon.ShortNameObjectID))
         {
             if (xml.OutputType == TranslatorOutputType.SimpleXml)
             {
                 xml.AppendLine(TranslatorGeneralTags.ApplicationContextName,
                                "Value", "SN");
             }
             else
             {
                 xml.AppendLine(
                     TranslatorGeneralTags.ApplicationContextName,
                     null, "2");
             }
             settings.UseLogicalNameReferencing = false;
         }
         else if (buff.Compare(GXCommon.ShortNameObjectIdWithCiphering))
         {
             if (xml.OutputType == TranslatorOutputType.SimpleXml)
             {
                 xml.AppendLine(TranslatorGeneralTags.ApplicationContextName,
                                "Value", "SN_WITH_CIPHERING");
             }
             else
             {
                 xml.AppendLine(
                     TranslatorGeneralTags.ApplicationContextName,
                     null, "4");
             }
             settings.UseLogicalNameReferencing = false;
         }
         else
         {
             return false;
         }
         return true;
     }
     if (settings.UseLogicalNameReferencing)
     {
         if (buff.Compare(GXCommon.LogicalNameObjectID))
         {
             return true;
         }
         // If ciphering is used.
         return buff.Compare(GXCommon.LogicalNameObjectIdWithCiphering);
     }
     if (buff.Compare(GXCommon.ShortNameObjectID))
     {
         return true;
     }
     // If ciphering is used.
     return buff.Compare(GXCommon.ShortNameObjectIdWithCiphering);
 }
Exemplo n.º 36
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         if (CalendarNameActive == null)
         {
             return(null);
         }
         if (IsSec())
         {
             return(GXCommon.HexToBytes(CalendarNameActive));
         }
         return(ASCIIEncoding.ASCII.GetBytes(CalendarNameActive));
     }
     if (e.Index == 3)
     {
         e.ByteArray = true;
         bool useOctetString = settings.Standard != Standard.SaudiArabia;
         return(GetSeasonProfile(settings, SeasonProfileActive, useOctetString));
     }
     if (e.Index == 4)
     {
         e.ByteArray = true;
         return(GetWeekProfileTable(settings, WeekProfileTableActive));
     }
     if (e.Index == 5)
     {
         e.ByteArray = true;
         return(GetDayProfileTable(settings, DayProfileTableActive));
     }
     if (e.Index == 6)
     {
         if (CalendarNamePassive == null)
         {
             return(null);
         }
         if (IsSec())
         {
             return(GXCommon.HexToBytes(CalendarNamePassive));
         }
         return(ASCIIEncoding.ASCII.GetBytes(CalendarNamePassive));
     }
     if (e.Index == 7)
     {
         e.ByteArray = true;
         bool useOctetString = settings.Standard != Standard.SaudiArabia;
         return(GetSeasonProfile(settings, SeasonProfilePassive, useOctetString));
     }
     if (e.Index == 8)
     {
         e.ByteArray = true;
         return(GetWeekProfileTable(settings, WeekProfileTablePassive));
     }
     if (e.Index == 9)
     {
         e.ByteArray = true;
         return(GetDayProfileTable(settings, DayProfileTablePassive));
     }
     if (e.Index == 10)
     {
         return(Time);
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 37
0
 private static void UpdateAuthentication(GXDLMSSettings settings,
         GXByteBuffer buff)
 {
     byte len = buff.GetUInt8();
     if (buff.GetUInt8() != 0x60)
     {
         throw new Exception("Invalid tag.");
     }
     if (buff.GetUInt8() != 0x85)
     {
         throw new Exception("Invalid tag.");
     }
     if (buff.GetUInt8() != 0x74)
     {
         throw new Exception("Invalid tag.");
     }
     if (buff.GetUInt8() != 0x05)
     {
         throw new Exception("Invalid tag.");
     }
     if (buff.GetUInt8() != 0x08)
     {
         throw new Exception("Invalid tag.");
     }
     if (buff.GetUInt8() != 0x02)
     {
         throw new Exception("Invalid tag.");
     }
     int tmp = buff.GetUInt8();
     if (tmp < 0 || tmp > 7)
     {
         throw new Exception("Invalid tag.");
     }
     settings.Authentication = (Authentication)tmp;
 }
Exemplo n.º 38
0
 static GXDLMSDayProfile[] SetDayProfileTable(GXDLMSSettings settings, Object value)
 {
     if (value != null)
     {
         List <object> arr, item, it2;
         if (value is List <object> )
         {
             arr = (List <object>)value;
         }
         else
         {
             arr = new List <object>((object[])value);
         }
         List <GXDLMSDayProfile> items = new List <GXDLMSDayProfile>();
         foreach (object tmp in arr)
         {
             if (tmp is List <object> )
             {
                 item = (List <object>)tmp;
             }
             else
             {
                 item = new List <object>((object[])tmp);
             }
             GXDLMSDayProfile it = new GXDLMSDayProfile();
             it.DayId = Convert.ToInt32(item[0]);
             List <GXDLMSDayProfileAction> actions = new List <GXDLMSDayProfileAction>();
             if (item[1] is List <object> )
             {
                 item = (List <object>)item[1];
             }
             else
             {
                 item = new List <object>((object[])item[1]);
             }
             foreach (object tmp2 in item)
             {
                 if (tmp2 is List <object> )
                 {
                     it2 = (List <object>)tmp2;
                 }
                 else
                 {
                     it2 = new List <object>((object[])tmp2);
                 }
                 GXDLMSDayProfileAction ac = new GXDLMSDayProfileAction();
                 if (it2[0] is GXTime)
                 {
                     ac.StartTime = (GXTime)it2[0];
                 }
                 else if (it2[0] is GXDateTime)
                 {
                     ac.StartTime = new GXTime((GXDateTime)it2[0]);
                 }
                 else
                 {
                     ac.StartTime = (GXTime)GXDLMSClient.ChangeType((byte[])it2[0], DataType.Time, settings.UseUtc2NormalTime);
                 }
                 ac.ScriptLogicalName = GXCommon.ToLogicalName(it2[1]);
                 ac.ScriptSelector    = Convert.ToUInt16(it2[2]);
                 actions.Add(ac);
             }
             it.DaySchedules = actions.ToArray();
             items.Add(it);
         }
         return(items.ToArray());
     }
     return(null);
 }
Exemplo n.º 39
0
        ///<summary>
        ///Parse APDU.
        ///</summary>
        static internal SourceDiagnostic ParsePDU(GXDLMSSettings settings, GXICipher cipher,
                GXByteBuffer buff, GXDLMSTranslatorStructure xml)
        {
            // Get AARE tag and length
            int tag = buff.GetUInt8();
            if (settings.IsServer)
            {
                if (tag != ((byte)BerType.Application | (byte)BerType.Constructed | (byte)PduType.ProtocolVersion))
                {
                    throw new Exception("Invalid tag.");
                }
            }
            else
            {
                if (tag != ((byte)BerType.Application | (byte)BerType.Constructed | (byte)PduType.ApplicationContextName))
                {
                    throw new Exception("Invalid tag.");
                }
            }
            int len = buff.GetUInt8();
            int size = buff.Size - buff.Position;
            if (len > size)
            {
                throw new Exception("Not enough data.");
            }
            //Opening tags
            if (xml != null)
            {
                if (settings.IsServer)
                {
                    xml.AppendStartTag(Command.Aarq);
                }
                else
                {
                    xml.AppendStartTag(Command.Aare);
                }
            }
            AssociationResult resultComponent = AssociationResult.Accepted;
            SourceDiagnostic resultDiagnosticValue = SourceDiagnostic.None;
            while (buff.Position < buff.Size)
            {
                tag = buff.GetUInt8();
                switch (tag)
                {
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.ApplicationContextName://0xA1
                        if (!ParseApplicationContextName(settings, buff, xml))
                        {
                            throw new GXDLMSException(AssociationResult.PermanentRejected, SourceDiagnostic.ApplicationContextNameNotSupported);
                        }
                        break;
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CalledApTitle://0xA2
                                                                                                         //Get len.
                        if (buff.GetUInt8() != 3)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        //Choice for result (INTEGER, universal)
                        if (buff.GetUInt8() != (byte)BerType.Integer)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        //Get len.
                        if (buff.GetUInt8() != 1)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        resultComponent = (AssociationResult)buff.GetUInt8();
                        if (xml != null)
                        {
                            xml.AppendLine(TranslatorGeneralTags.AssociationResult, "Value", xml.IntegerToHex((int)resultComponent, 2));
                            xml.AppendStartTag(TranslatorGeneralTags.ResultSourceDiagnostic);
                        }
                        break;
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CalledAeQualifier:////SourceDiagnostic 0xA3
                        len = buff.GetUInt8();
                        // ACSE service user tag.
                        tag = buff.GetUInt8();
                        len = buff.GetUInt8();
                        // Result source diagnostic component.
                        if (buff.GetUInt8() != (byte)BerType.Integer)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        if (buff.GetUInt8() != 1)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        resultDiagnosticValue = (SourceDiagnostic)buff.GetUInt8();
                        if (xml != null)
                        {
                            xml.AppendLine(TranslatorGeneralTags.ACSEServiceUser, "Value", xml.IntegerToHex((int)resultDiagnosticValue, 2));
                            xml.AppendEndTag(TranslatorGeneralTags.ResultSourceDiagnostic);
                        }
                        break;
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CalledApInvocationId:
                        ////Result 0xA4
                        //Get len.
                        if (buff.GetUInt8() != 0xA)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        //Choice for result (Universal, Octetstring type)
                        if (buff.GetUInt8() != (byte)BerType.OctetString)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        //responding-AP-title-field
                        //Get len.
                        len = buff.GetUInt8();
                        settings.SourceSystemTitle = new byte[len];
                        buff.Get(settings.SourceSystemTitle);
                        if (xml != null)
                        {
                            //RespondingAPTitle
                            xml.AppendLine(TranslatorGeneralTags.RespondingAPTitle, "Value", GXCommon.ToHex(settings.SourceSystemTitle, false));
                        }
                        break;
                    //Client Challenge.
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CallingApTitle://0xA6
                        len = buff.GetUInt8();
                        tag = buff.GetUInt8();
                        len = buff.GetUInt8();
                        settings.SourceSystemTitle = new byte[len];
                        buff.Get(settings.SourceSystemTitle);
                        if (xml != null)
                        {
                            //CallingAPTitle
                            xml.AppendLine(TranslatorGeneralTags.CallingAPTitle, "Value", GXCommon.ToHex(settings.SourceSystemTitle, false));
                        }
                        break;
                    //Server Challenge.
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.SenderAcseRequirements://0xAA
                        len = buff.GetUInt8();
                        tag = buff.GetUInt8();
                        len = buff.GetUInt8();
                        settings.StoCChallenge = new byte[len];
                        buff.Get(settings.StoCChallenge);
                        AppendServerSystemTitleToXml(settings, xml, tag);
                        break;
                    case (byte)BerType.Context | (byte)PduType.SenderAcseRequirements:
                    //0x8A
                    case (byte)BerType.Context | (byte)PduType.CallingApInvocationId:
                        //0x88

                        //Get sender ACSE-requirements field component.
                        if (buff.GetUInt8() != 2)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        if (buff.GetUInt8() != (byte)BerType.ObjectDescriptor)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        if (buff.GetUInt8() != 0x80)
                        {
                            throw new Exception("Invalid tag.");
                        }
                        //SenderACSERequirements
                        if (xml != null)
                        {
                            xml.AppendLine(tag, "Value", "1");
                        }
                        break;
                    case (byte)BerType.Context | (byte)PduType.MechanismName://0x8B
                    case (byte)BerType.Context | (byte)PduType.CallingAeInvocationId://0x89
                        UpdateAuthentication(settings, buff);
                        if (xml != null)
                        {
                            if (xml.OutputType == TranslatorOutputType.SimpleXml)
                            {
                                xml.AppendLine(tag, "Value", settings.Authentication.ToString());
                            }
                            else
                            {
                                xml.AppendLine(tag, "Value", ((int)settings.Authentication).ToString());
                            }
                        }
                        break;
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.CallingAuthenticationValue://0xAC
                        updatePassword(settings, buff, xml);
                        break;
                    case (byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.UserInformation:
                        //0xBE
                        if (xml == null && resultComponent != AssociationResult.Accepted && resultDiagnosticValue != SourceDiagnostic.None)
                        {
                            throw new GXDLMSException(resultComponent, resultDiagnosticValue);
                        }
                        ParseUserInformation(settings, cipher, buff, xml);
                        break;
                    default:
                        //Unknown tags.
                        System.Diagnostics.Debug.WriteLine("Unknown tag: " + tag + ".");
                        if (buff.Position < buff.Size)
                        {
                            len = buff.GetUInt8();
                            buff.Position += (UInt16)len;
                        }
                        break;
                }
            }
            //Closing tags
            if (xml != null)
            {
                if (settings.IsServer)
                {
                    xml.AppendEndTag(Command.Aarq);
                }
                else
                {
                    xml.AppendEndTag(Command.Aare);
                }
            }
            return resultDiagnosticValue;
        }
Exemplo n.º 40
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         if (e.Value is byte[] v)
         {
             if (IsSec() || !GXByteBuffer.IsAsciiString(v))
             {
                 CalendarNameActive = GXCommon.ToHex(v, false);
             }
             else
             {
                 CalendarNameActive = ASCIIEncoding.ASCII.GetString(v);
             }
         }
         else
         {
             CalendarNameActive = Convert.ToString(e.Value);
         }
     }
     else if (e.Index == 3)
     {
         SeasonProfileActive = SetSeasonProfile(settings, e.Value);
     }
     else if (e.Index == 4)
     {
         WeekProfileTableActive = SetWeekProfileTable(settings, e.Value);
     }
     else if (e.Index == 5)
     {
         DayProfileTableActive = SetDayProfileTable(settings, e.Value);
     }
     else if (e.Index == 6)
     {
         if (e.Value is byte[] v)
         {
             if (IsSec() || !GXByteBuffer.IsAsciiString(v))
             {
                 CalendarNamePassive = GXCommon.ToHex(v, false);
             }
             else
             {
                 CalendarNamePassive = ASCIIEncoding.ASCII.GetString(v);
             }
         }
         else
         {
             CalendarNamePassive = Convert.ToString(e.Value);
         }
     }
     else if (e.Index == 7)
     {
         SeasonProfilePassive = SetSeasonProfile(settings, e.Value);
     }
     else if (e.Index == 8)
     {
         WeekProfileTablePassive = SetWeekProfileTable(settings, e.Value);
     }
     else if (e.Index == 9)
     {
         DayProfileTablePassive = SetDayProfileTable(settings, e.Value);
     }
     else if (e.Index == 10)
     {
         if (e.Value is byte[])
         {
             Time = (GXDateTime)GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
         }
         else
         {
             Time = new GXDateTime(Convert.ToDateTime(e.Value));
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 41
0
        private static byte[] GetUserInformation(GXDLMSSettings settings, GXICipher cipher)
        {
            GXByteBuffer data = new GXByteBuffer();
            data.SetUInt8(Command.InitiateResponse); // Tag for xDLMS-Initiate response
                                                     // NegotiatedQualityOfService (not used)
            data.SetUInt8(0x1);
            data.SetUInt8(0x00);
            // DLMS Version Number
            data.SetUInt8(06);
            data.SetUInt8(0x5F);
            data.SetUInt8(0x1F);
            data.SetUInt8(0x04);// length of the conformance block
            data.SetUInt8(0x00);// encoding the number of unused bits in the bit string
            if (settings.UseLogicalNameReferencing)
            {
                data.Set(settings.LnSettings.ConformanceBlock);
            }
            else
            {
                data.Set(settings.SnSettings.ConformanceBlock);

            }
            data.SetUInt16(settings.MaxPduSize);
            //VAA Name VAA name (0x0007 for LN referencing and 0xFA00 for SN)
            if (settings.UseLogicalNameReferencing)
            {
                data.SetUInt16(0x0007);
            }
            else
            {
                data.SetUInt16(0xFA00);
            }
            if (cipher != null && cipher.IsCiphered())
            {
                return cipher.Encrypt((byte)Command.GloInitiateResponse, cipher.SystemTitle, data.Array());
            }
            return data.Array();
        }
Exemplo n.º 42
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     if (e.Index == 2)
     {
         return(GXCommon.LogicalNameToBytes(MBusPortReference));
     }
     if (e.Index == 3)
     {
         GXByteBuffer buff = new GXByteBuffer();
         buff.SetUInt8((byte)DataType.Array);
         GXCommon.SetObjectCount(CaptureDefinition.Count, buff);
         foreach (KeyValuePair <string, string> it in CaptureDefinition)
         {
             buff.SetUInt8((byte)DataType.Structure);
             buff.SetUInt8(2);
             GXCommon.SetData(settings, buff, DataType.UInt8, it.Key);
             GXCommon.SetData(settings, buff, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Value));
         }
         return(buff.Array());
     }
     if (e.Index == 4)
     {
         return(CapturePeriod);
     }
     if (e.Index == 5)
     {
         return(PrimaryAddress);
     }
     if (e.Index == 6)
     {
         return(IdentificationNumber);
     }
     if (e.Index == 7)
     {
         return(ManufacturerID);
     }
     if (e.Index == 8)
     {
         return(DataHeaderVersion);
     }
     if (e.Index == 9)
     {
         return(DeviceType);
     }
     if (e.Index == 10)
     {
         return(AccessNumber);
     }
     if (e.Index == 11)
     {
         return(Status);
     }
     if (e.Index == 12)
     {
         return(Alarm);
     }
     if (Version > 0)
     {
         if (e.Index == 13)
         {
             return(Configuration);
         }
         if (e.Index == 14)
         {
             return(EncryptionKeyStatus);
         }
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return GetObjects(settings, e).Array();
     }
     if (e.Index == 3)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         //Add count
         data.SetUInt8(2);
         data.SetUInt8((byte)DataType.UInt8);
         data.SetUInt8(ClientSAP);
         data.SetUInt8((byte)DataType.UInt16);
         data.SetUInt16(ServerSAP);
         return data.Array();
     }
     if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         data.SetUInt8(0x7);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.JointIsoCtt);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.Country);
         GXCommon.SetData(settings, data, DataType.UInt16, ApplicationContextName.CountryName);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.IdentifiedOrganization);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.DlmsUA);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.ApplicationContext);
         GXCommon.SetData(settings, data, DataType.UInt8, ApplicationContextName.ContextId);
         return data.Array();
     }
     if (e.Index == 5)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8(6);
         GXCommon.SetData(settings, data, DataType.BitString, XDLMSContextInfo.Conformance);
         GXCommon.SetData(settings, data, DataType.UInt16, XDLMSContextInfo.MaxReceivePduSize);
         GXCommon.SetData(settings, data, DataType.UInt16, XDLMSContextInfo.MaxSendPpuSize);
         GXCommon.SetData(settings, data, DataType.UInt8, XDLMSContextInfo.DlmsVersionNumber);
         GXCommon.SetData(settings, data, DataType.Int8, XDLMSContextInfo.QualityOfService);
         GXCommon.SetData(settings, data, DataType.OctetString, XDLMSContextInfo.CypheringInfo);
         return data.Array();
     }
     if (e.Index == 6)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         //Add count
         data.SetUInt8(0x7);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.JointIsoCtt);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.Country);
         GXCommon.SetData(settings, data, DataType.UInt16, AuthenticationMechanismMame.CountryName);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.IdentifiedOrganization);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.DlmsUA);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.AuthenticationMechanismName);
         GXCommon.SetData(settings, data, DataType.UInt8, AuthenticationMechanismMame.MechanismId);
         return data.Array();
     }
     if (e.Index == 7)
     {
         return Secret;
     }
     if (e.Index == 8)
     {
         return AssociationStatus;
     }
     if (e.Index == 9)
     {
         if (SecuritySetupReference == null)
         {
             return null;
         }
         return ASCIIEncoding.ASCII.GetBytes(SecuritySetupReference);
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Exemplo n.º 44
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         MBusPortReference = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 3)
     {
         CaptureDefinition.Clear();
         if (e.Value != null)
         {
             foreach (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> it;
                 if (tmp is List <object> )
                 {
                     it = (List <object>)tmp;
                 }
                 else
                 {
                     it = new List <object>((object[])tmp);
                 }
                 CaptureDefinition.Add(new KeyValuePair <string, string>(GXDLMSClient.ChangeType((byte[])it[0], DataType.OctetString, settings.UseUtc2NormalTime).ToString(),
                                                                         GXDLMSClient.ChangeType((byte[])it[1], DataType.OctetString, settings.UseUtc2NormalTime).ToString()));
             }
         }
     }
     else if (e.Index == 4)
     {
         CapturePeriod = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 5)
     {
         PrimaryAddress = Convert.ToByte(e.Value);
     }
     else if (e.Index == 6)
     {
         IdentificationNumber = Convert.ToUInt32(e.Value);
     }
     else if (e.Index == 7)
     {
         ManufacturerID = Convert.ToUInt16(e.Value);
     }
     else if (e.Index == 8)
     {
         DataHeaderVersion = Convert.ToByte(e.Value);
     }
     else if (e.Index == 9)
     {
         DeviceType = Convert.ToByte(e.Value);
     }
     else if (e.Index == 10)
     {
         AccessNumber = Convert.ToByte(e.Value);
     }
     else if (e.Index == 11)
     {
         Status = Convert.ToByte(e.Value);
     }
     else if (e.Index == 12)
     {
         Alarm = Convert.ToByte(e.Value);
     }
     else if (Version > 0)
     {
         if (e.Index == 13)
         {
             Configuration = Convert.ToUInt16(e.Value);
         }
         else if (e.Index == 14)
         {
             EncryptionKeyStatus = (MBusEncryptionKeyStatus)Convert.ToInt32(e.Value);
         }
         else
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 45
0
        ///<summary>
        ///Convert object to DLMS bytes.
        ///</summary>
        ///<param name="settings">DLMS settings.</param>
        ///<param name="buff">Byte buffer where data is write.</param>
        ///<param name="dataType">Data type.</param>
        ///<param name="value">Added Value.</param>
        public static void SetData(GXDLMSSettings settings, GXByteBuffer buff, DataType type, object value)
        {
            if ((type == DataType.Array || type == DataType.Structure) && value is byte[])
            {
                // If byte array is added do not add type.
                buff.Set((byte[])value);
                return;
            }
            buff.SetUInt8((byte)type);
            switch (type)
            {
                case DataType.None:
                    break;
                case DataType.Boolean:
                    if (Convert.ToBoolean(value))
                    {
                        buff.SetUInt8(1);
                    }
                    else
                    {
                        buff.SetUInt8(0);
                    }
                    break;
                case DataType.Int8:
                    buff.SetUInt8((byte)Convert.ToSByte(value));
                    break;
                case DataType.UInt8:
                case DataType.Enum:
                    buff.SetUInt8(Convert.ToByte(value));
                    break;
                case DataType.Int16:
                    if (value is UInt16)
                    {
                        buff.SetUInt16((UInt16)value);
                    }
                    else
                    {
                        buff.SetUInt16((UInt16)(Convert.ToInt16(value) & 0xFFFF));
                    }
                    break;
                case DataType.UInt16:
                    buff.SetUInt16(Convert.ToUInt16(value));
                    break;
                case DataType.Int32:
                    buff.SetUInt32((UInt32)Convert.ToInt32(value));
                    break;
                case DataType.UInt32:

                    buff.SetUInt32(Convert.ToUInt32(value));
                    break;
                case DataType.Int64:
                    buff.SetUInt64((UInt64)Convert.ToInt64(value));
                    break;
                case DataType.UInt64:
                    buff.SetUInt64(Convert.ToUInt64(value));
                    break;
                case DataType.Float32:
                    buff.SetFloat((float)value);
                    break;
                case DataType.Float64:
                    buff.SetDouble((double)value);
                    break;
                case DataType.BitString:
                    SetBitString(buff, value);
                    break;
                case DataType.String:
                    SetString(buff, value);
                    break;
                case DataType.StringUTF8:
                    SetUtcString(buff, value);
                    break;
                case DataType.OctetString:
                    if (value is GXDate)
                    {
                        //Add size
                        buff.SetUInt8(5);
                        SetDate(buff, value);
                    }
                    else if (value is GXTime)
                    {
                        //Add size
                        buff.SetUInt8(4);
                        SetTime(buff, value);
                    }
                    else if (value is GXDateTime || value is DateTime)
                    {
                        //Add size
                        buff.SetUInt8(12);
                        SetDateTime(settings, buff, value);
                    }
                    else
                    {
                        SetOctetString(buff, value);
                    }
                    break;
                case DataType.Array:
                case DataType.Structure:
                    SetArray(settings, buff, value);
                    break;
                case DataType.Bcd:
                    SetBcd(buff, value);
                    break;
                case DataType.CompactArray:
                    throw new Exception("Invalid data type.");
                case DataType.DateTime:
                    SetDateTime(settings, buff, value);
                    break;
                case DataType.Date:
                    SetDate(buff, value);
                    break;
                case DataType.Time:
                    SetTime(buff, value);
                    break;
                default:
                    throw new Exception("Invalid data type.");
            }
        }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(GXCommon.LogicalNameToBytes(LogicalName));
     }
     else if (e.Index == 2)
     {
         return(InitiatorElectricalPhase);
     }
     else if (e.Index == 3)
     {
         return(DeltaElectricalPhase);
     }
     else if (e.Index == 4)
     {
         return(MaxReceivingGain);
     }
     else if (e.Index == 5)
     {
         return(MaxTransmittingGain);
     }
     else if (e.Index == 6)
     {
         return(SearchInitiatorThreshold);
     }
     else if (e.Index == 7)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8(DataType.Structure);
         bb.SetUInt8(2);
         GXCommon.SetData(settings, bb, DataType.UInt32, MarkFrequency);
         GXCommon.SetData(settings, bb, DataType.UInt32, SpaceFrequency);
         return(bb.Array());
     }
     else if (e.Index == 8)
     {
         return(MacAddress);
     }
     else if (e.Index == 9)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8(DataType.Array);
         if (MacGroupAddresses == null)
         {
             bb.SetUInt8(0);
         }
         else
         {
             GXCommon.SetObjectCount(MacGroupAddresses.Length, bb);
             foreach (UInt16 it in MacGroupAddresses)
             {
                 GXCommon.SetData(settings, bb, DataType.UInt16, it);
             }
         }
         return(bb.Array());
     }
     else if (e.Index == 10)
     {
         return(Repeater);
     }
     else if (e.Index == 11)
     {
         return(RepeaterStatus);
     }
     else if (e.Index == 12)
     {
         return(MinDeltaCredit);
     }
     else if (e.Index == 13)
     {
         return(InitiatorMacAddress);
     }
     else if (e.Index == 14)
     {
         return(SynchronizationLocked);
     }
     else if (e.Index == 15)
     {
         return(TransmissionSpeed);
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 47
0
 ///<summary>
 ///Convert Array to DLMS bytes.
 ///</summary>
 ///<param name="buff">
 ///Byte buffer where data is write.
 ///</param>
 ///<param name="value">
 ///Added value.
 ///</param>
 private static void SetArray(GXDLMSSettings settings, GXByteBuffer buff, object value)
 {
     if (value != null)
     {
         object[] arr = (object[])value;
         SetObjectCount(arr.Length, buff);
         foreach (object it in arr)
         {
             SetData(settings, buff, GetValueType(it), it);
         }
     }
     else
     {
         SetObjectCount(0, buff);
     }
 }
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         InitiatorElectricalPhase = (InitiatorElectricalPhase)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 3)
     {
         DeltaElectricalPhase = (DeltaElectricalPhase)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 4)
     {
         MaxReceivingGain = (byte)e.Value;
     }
     else if (e.Index == 5)
     {
         MaxTransmittingGain = (byte)e.Value;
     }
     else if (e.Index == 6)
     {
         SearchInitiatorThreshold = (byte)e.Value;
     }
     else if (e.Index == 7)
     {
         if (e.Value != null)
         {
             List <object> tmp;
             if (e.Value is List <object> )
             {
                 tmp = (List <object>)e.Value;
             }
             else
             {
                 tmp = new List <object>((object[])e.Value);
             }
             MarkFrequency  = (UInt32)tmp[0];
             SpaceFrequency = (UInt32)tmp[1];
         }
         else
         {
             MarkFrequency  = 0;
             SpaceFrequency = 0;
         }
     }
     else if (e.Index == 8)
     {
         MacAddress = (UInt16)e.Value;
     }
     else if (e.Index == 9)
     {
         List <ushort> list = new List <ushort>();
         if (e.Value != null)
         {
             foreach (object it in (IEnumerable <object>)e.Value)
             {
                 list.Add((ushort)it);
             }
         }
         MacGroupAddresses = list.ToArray();
     }
     else if (e.Index == 10)
     {
         Repeater = (Repeater)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 11)
     {
         RepeaterStatus = (bool)e.Value;
     }
     else if (e.Index == 12)
     {
         MinDeltaCredit = (byte)e.Value;
     }
     else if (e.Index == 13)
     {
         InitiatorMacAddress = (UInt16)e.Value;
     }
     else if (e.Index == 14)
     {
         SynchronizationLocked = (bool)e.Value;
     }
     else if (e.Index == 15)
     {
         TransmissionSpeed = (BaudRate)Convert.ToInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 49
0
        ///<summary>
        ///Get date and time from DLMS data.
        ///</summary>
        ///<param name="settings">DLMS settings.</param>
        ///<param name="buff">Received DLMS data.</param>
        ///<param name="info">Data info.</param>
        ///<returns>
        ///Parsed date and time.
        ///</returns>
        private static object GetDateTime(GXDLMSSettings settings, GXByteBuffer buff, GXDataInfo info)
        {
            // If there is not enough data available.
            if (buff.Size - buff.Position < 12)
            {
                //If time.
                if (buff.Size - buff.Position < 5)
                {
                    return GetTime(buff, info);
                }
                //If date.
                else if (buff.Size - buff.Position < 6)
                {
                    return GetDate(buff, info);
                }

                info.Complete = false;
                return null;
            }
            if (info.xml != null)
            {
                info.xml.AppendLine(info.xml.GetDataType(info.Type), "Value", GXCommon.ToHex(buff.Data, false, buff.Position, 12));
            }

            GXDateTime dt = new GXDateTime();
            //Get year.
            int year = buff.GetUInt16();
            if (year == 0xFFFF || year == 0)
            {
                year = DateTime.Now.Year;
                dt.Skip |= DateTimeSkips.Year;
            }
            //Get month
            int month = buff.GetUInt8();
            if (month == 0 || month == 0xFF || month == 0xFE || month == 0xFD)
            {
                month = 1;
                dt.Skip |= DateTimeSkips.Month;
            }
            int day = buff.GetUInt8();
            if (day < 1 || day == 0xFF)
            {
                day = 1;
                dt.Skip |= DateTimeSkips.Day;
            }
            else if (day == 0xFD || day == 0xFE)
            {
                day = DateTime.DaysInMonth(year, month) + (sbyte)day + 2;
            }
            //Skip week day
            if (buff.GetUInt8() == 0xFF)
            {
                dt.Skip |= DateTimeSkips.DayOfWeek;
            }
            //Get time.
            int hours = buff.GetUInt8();
            if (hours == 0xFF)
            {
                hours = 0;
                dt.Skip |= DateTimeSkips.Hour;
            }
            int minutes = buff.GetUInt8();
            if (minutes == 0xFF)
            {
                minutes = 0;
                dt.Skip |= DateTimeSkips.Minute;
            }
            int seconds = buff.GetUInt8();
            if (seconds == 0xFF)
            {
                seconds = 0;
                dt.Skip |= DateTimeSkips.Second;
            }
            int milliseconds = buff.GetUInt8();
            if (milliseconds != 0xFF)
            {
                milliseconds *= 10;
            }
            else
            {
                milliseconds = 0;
                dt.Skip |= DateTimeSkips.Ms;
            }
            int deviation = buff.GetInt16();
            dt.Status = (ClockStatus)buff.GetUInt8();
            if (settings != null && settings.UtcTimeZone)
            {
                deviation = -deviation;
            }
            dt.Deviation = deviation;
            //0x8000 == -32768
            //deviation = -1 if skipped.
            if (deviation != -1 && deviation != -32768 && year != 1 && (dt.Skip & DateTimeSkips.Year) == 0)
            {
                dt.Value = new DateTimeOffset(new DateTime(year, month, day, hours, minutes, seconds, milliseconds),
                                              new TimeSpan(0, -deviation, 0));
            }
            else //Use current time if deviation is not defined.
            {
                dt.Skip |= DateTimeSkips.Devitation;
                DateTime tmp = new DateTime(year, month, day, hours, minutes, seconds, milliseconds, DateTimeKind.Local);
                dt.Value = new DateTimeOffset(tmp, TimeZoneInfo.Local.GetUtcOffset(tmp));
            }
            return dt;
        }
Exemplo n.º 50
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                LogicalName = GXCommon.ToLogicalName(e.Value);
                break;

            case 2:
                DefaultMode = (OpticalProtocolMode)Convert.ToInt32(e.Value);
                break;

            case 3:
                DefaultBaudrate = (BaudRate)Convert.ToInt32(e.Value);
                break;

            case 4:
                ProposedBaudrate = (BaudRate)Convert.ToInt32(e.Value);
                break;

            case 5:
                ResponseTime = (LocalPortResponseTime)Convert.ToInt32(e.Value);
                break;

            case 6:
                if (e.Value is byte[])
                {
                    DeviceAddress = GXDLMSClient.ChangeType((byte[])e.Value, DataType.String, settings.UseUtc2NormalTime).ToString();
                }
                else
                {
                    DeviceAddress = Convert.ToString(e.Value);
                }
                break;

            case 7:
                if (e.Value is byte[])
                {
                    Password1 = GXDLMSClient.ChangeType((byte[])e.Value, DataType.String, settings.UseUtc2NormalTime).ToString();
                }
                else
                {
                    Password1 = Convert.ToString(e.Value);
                }
                break;

            case 8:
                if (e.Value is byte[])
                {
                    Password2 = GXDLMSClient.ChangeType((byte[])e.Value, DataType.String, settings.UseUtc2NormalTime).ToString();
                }
                else
                {
                    Password2 = Convert.ToString(e.Value);
                }
                break;

            case 9:
                if (e.Value is byte[])
                {
                    Password5 = GXDLMSClient.ChangeType((byte[])e.Value, DataType.String, settings.UseUtc2NormalTime).ToString();
                }
                else
                {
                    Password5 = Convert.ToString(e.Value);
                }
                break;

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
        }
Exemplo n.º 51
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         if (e.Value is string)
         {
             LogicalName = e.Value.ToString();
         }
         else
         {
             LogicalName = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
         }
     }
     else if (e.Index == 2)
     {
         Mode = (AutoAnswerMode)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 3)
     {
         ListeningWindow.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 GXDateTime start = (GXDateTime)GXDLMSClient.ChangeType((byte[])item[0], DataType.DateTime);
                 GXDateTime end = (GXDateTime)GXDLMSClient.ChangeType((byte[])item[1], DataType.DateTime);
                 ListeningWindow.Add(new KeyValuePair<GXDateTime, GXDateTime>(start, end));
             }
         }
     }
     else if (e.Index == 4)
     {
         Status = (AutoAnswerStatus)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 5)
     {
         NumberOfCalls = Convert.ToInt32(e.Value);
     }
     else if (e.Index == 6)
     {
         NumberOfRingsInListeningWindow = NumberOfRingsOutListeningWindow = 0;
         if (e.Value != null)
         {
             NumberOfRingsInListeningWindow = Convert.ToInt32(((Object[])e.Value)[0]);
             NumberOfRingsOutListeningWindow = Convert.ToInt32(((Object[])e.Value)[1]);
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemplo n.º 52
0
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Exemplo n.º 53
0
 ///<summary>
 /// Chipher text.
 ///</summary>
 ///<param name="settings">
 ///DLMS settings. 
 ///</param>
 ///<param name="cipher">
 ///Cipher. 
 ///</param>
 ///<param name="ic">
 ///Invocation counter.
 ///</param>
 ///<param name="data">
 ///Text to chipher. 
 ///</param>
 ///<param name="secret">
 ///Secret. 
 ///</param>
 ///<returns>
 ///Chiphered text.
 ///</returns>
 public static byte[] Secure(GXDLMSSettings settings, GXICipher cipher, UInt32 ic, byte[] data, byte[] secret)
 {
     byte[] tmp;
     if (settings.Authentication == Authentication.High)
     {
         int len = secret.Length;
         if (len % 16 != 0)
         {
             len += 16 - (secret.Length % 16);
         }
         byte[] p = new byte[len];
         byte[] s = new byte[16];
         byte[] x = new byte[16];
         int i;
         data.CopyTo(p, 0);
         secret.CopyTo(s, 0);
         for (i = 0; i < p.Length; i += 16)
         {
             Buffer.BlockCopy(p, i, x, 0, 16);
             GXAes128.Encrypt(x, s);
             Buffer.BlockCopy(x, 0, p, i, 16);
         }
         Buffer.BlockCopy(p, 0, x, 0, 16);
         return x;
     }
     // Get server Challenge.
     GXByteBuffer challenge = new GXByteBuffer();
     // Get shared secret
     if (settings.Authentication == Authentication.HighGMAC)
     {
         challenge.Set(data);              
     }
     else
     {
         challenge.Set(data);
         challenge.Set(secret);
     }
     tmp = challenge.Array();
     if (settings.Authentication == Authentication.HighMD5)
     {
         using (MD5 md5Hash = MD5.Create())
         {
             tmp = md5Hash.ComputeHash(tmp);
             return tmp;
         }
     }
     else if (settings.Authentication == Authentication.HighSHA1)
     {
         using (SHA1 sha = new SHA1CryptoServiceProvider())
         {
             tmp = sha.ComputeHash(tmp);
             return tmp;
         }
     }
     else if (settings.Authentication == Authentication.HighGMAC)
     {
         //SC is always Security.Authentication.
         AesGcmParameter p = new AesGcmParameter(0, Security.Authentication, ic,
             secret, cipher.BlockCipherKey, cipher.AuthenticationKey);
         p.Type = CountType.Tag;
         challenge.Clear();
         challenge.SetUInt8((byte)Security.Authentication);
         challenge.SetUInt32(p.FrameCounter);
         challenge.Set(GXDLMSChippering.EncryptAesGcm(p, tmp));
         tmp = challenge.Array();
         return tmp;
     }
     return data;
 }
Exemplo n.º 54
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                LogicalName = GXCommon.ToLogicalName(e.Value);
                break;

            case 2:
                CurrentCreditAmount = (int)e.Value;
                break;

            case 3:
                Type = (CreditType)Convert.ToByte(e.Value);
                break;

            case 4:
                Priority = (byte)e.Value;
                break;

            case 5:
                WarningThreshold = (int)e.Value;
                break;

            case 6:
                Limit = (int)e.Value;
                break;

            case 7:
                CreditConfiguration = (CreditConfiguration)Convert.ToByte(e.Value);
                break;

            case 8:
                Status = (CreditStatus)Convert.ToByte(e.Value);
                break;

            case 9:
                PresetCreditAmount = (int)e.Value;
                break;

            case 10:
                CreditAvailableThreshold = (int)e.Value;
                break;

            case 11:
                if (e.Value == null)
                {
                    Period = new GXDateTime(DateTime.MinValue);
                }
                else
                {
                    if (e.Value is byte[])
                    {
                        e.Value = GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings.UseUtc2NormalTime);
                    }
                    else if (e.Value is string)
                    {
                        e.Value = new GXDateTime((string)e.Value);
                    }
                    if (e.Value is GXDateTime)
                    {
                        Period = (GXDateTime)e.Value;
                    }
                }
                break;

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
        }
 private void GetAccessRights(GXDLMSSettings settings, GXDLMSObject item, GXByteBuffer data)
 {
     data.SetUInt8((byte)DataType.Structure);
     data.SetUInt8((byte)3);
     GXCommon.SetData(settings, data, DataType.UInt16, item.ShortName);
     data.SetUInt8((byte)DataType.Array);
     data.SetUInt8((byte)item.Attributes.Count);
     foreach (GXDLMSAttributeSettings att in item.Attributes)
     {
         data.SetUInt8((byte)DataType.Structure); //attribute_access_item
         data.SetUInt8((byte)3);
         GXCommon.SetData(settings, data, DataType.Int8, att.Index);
         GXCommon.SetData(settings, data, DataType.Enum, att.Access);
         GXCommon.SetData(settings, data, DataType.None, null);
     }
     data.SetUInt8((byte)DataType.Array);
     data.SetUInt8((byte)item.MethodAttributes.Count);
     foreach (GXDLMSAttributeSettings it in item.MethodAttributes)
     {
         data.SetUInt8((byte)DataType.Structure); //attribute_access_item
         data.SetUInt8((byte)2);
         GXCommon.SetData(settings, data, DataType.Int8, it.Index);
         GXCommon.SetData(settings, data, DataType.Enum, it.MethodAccess);
     }
 }
Exemplo n.º 56
0
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     //Check reply_to_HLS_authentication
     if (e.Index == 1)
     {
         UInt32 ic = 0;
         byte[] secret;
         if (settings.Authentication == Authentication.HighGMAC)
         {
             secret = settings.SourceSystemTitle;
             GXByteBuffer bb = new GXByteBuffer(e.Parameters as byte[]);
             bb.GetUInt8();
             ic = bb.GetUInt32();
         }
         else
         {
             secret = Secret;
         }
         byte[] serverChallenge = GXSecure.Secure(settings, settings.Cipher, ic, settings.StoCChallenge, secret);
         byte[] clientChallenge = (byte[])e.Parameters;
         if (serverChallenge != null && clientChallenge != null && GXCommon.Compare(serverChallenge, clientChallenge))
         {
             if (settings.Authentication == Authentication.HighGMAC)
             {
                 secret = settings.Cipher.SystemTitle;
                 ic     = settings.Cipher.InvocationCounter;
             }
             else
             {
                 secret = Secret;
             }
             AssociationStatus = AssociationStatus.Associated;
             return(GXSecure.Secure(settings, settings.Cipher, ic, settings.CtoSChallenge, secret));
         }
         else //If the password does not match.
         {
             AssociationStatus = AssociationStatus.NonAssociated;
             return(null);
         }
     }
     else if (e.Index == 2)
     {
         byte[] tmp = e.Parameters as byte[];
         if (tmp == null || tmp.Length == 0)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             Secret = tmp;
         }
     }
     else if (e.Index == 3)
     {
         //Add COSEM object.
         GXDLMSObject obj = GetObject(settings, e.Parameters as object[]);
         //Unknown objects are not add.
         if (obj is IGXDLMSBase)
         {
             if (ObjectList.FindByLN(obj.ObjectType, obj.LogicalName) == null)
             {
                 ObjectList.Add(obj);
             }
             if (settings.Objects.FindByLN(obj.ObjectType, obj.LogicalName) == null)
             {
                 settings.Objects.Add(obj);
             }
         }
     }
     else if (e.Index == 4)
     {
         //Remove COSEM object.
         GXDLMSObject obj = GetObject(settings, e.Parameters as object[]);
         //Unknown objects are not removed.
         if (obj is IGXDLMSBase)
         {
             GXDLMSObject t = ObjectList.FindByLN(obj.ObjectType, obj.LogicalName);
             if (t != null)
             {
                 ObjectList.Remove(t);
             }
             //Item is not removed from all objects. It might be that use wants remove object only from association view.
         }
     }
     else if (e.Index == 5)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Add(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else if (e.Index == 6)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Remove(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
     return(null);
 }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (ObjectList == null)
     {
         ObjectList = new GXDLMSObjectCollection();
     }
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     else if (e.Index == 2)
     {
         return GetObjects(settings, e).Array();
     }
     else if (e.Index == 3)
     {
         bool lnExists = ObjectList.FindBySN(this.ShortName) != null;
         //Add count
         int cnt = ObjectList.Count;
         if (!lnExists)
         {
             ++cnt;
         }
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         GXCommon.SetObjectCount(cnt, data);
         foreach (GXDLMSObject it in ObjectList)
         {
             GetAccessRights(settings, it, data);
         }
         if (!lnExists)
         {
             GetAccessRights(settings, this, data);
         }
         return data.Array();
     }
     else if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         GXCommon.SetData(settings, data, DataType.OctetString, SecuritySetupReference);
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Exemplo n.º 58
0
 /// <summary>
 /// Code application context name.
 /// </summary>
 /// <param name="settings">DLMS settings.</param>
 /// <param name="data">Byte buffer where data is saved.</param>
 /// <param name="cipher">Is ciphering settings.</param>
 private static void GenerateApplicationContextName(GXDLMSSettings settings, GXByteBuffer data, GXICipher cipher)
 {
     //Application context name tag
     data.SetUInt8(((byte)BerType.Context | (byte)BerType.Constructed | (byte)PduType.ApplicationContextName));
     //Len
     data.SetUInt8(0x09);
     data.SetUInt8(BerType.ObjectIdentifier);
     //Len
     data.SetUInt8(0x07);
     bool ciphered = cipher != null && cipher.IsCiphered();
     if (settings.UseLogicalNameReferencing)
     {
         if (ciphered)
         {
             data.Set(GXCommon.LogicalNameObjectIdWithCiphering);
         }
         else
         {
             data.Set(GXCommon.LogicalNameObjectID);
         }
     }
     else
     {
         if (ciphered)
         {
             data.Set(GXCommon.ShortNameObjectIdWithCiphering);
         }
         else
         {
             data.Set(GXCommon.ShortNameObjectID);
         }
     }
     //Add system title if cipher or GMAC authentication is used..
     if (!settings.IsServer && (ciphered || settings.Authentication == Authentication.HighGMAC))
     {
         if (cipher.SystemTitle == null || cipher.SystemTitle.Length == 0)
         {
             throw new ArgumentNullException("SystemTitle");
         }
         //Add calling-AP-title
         data.SetUInt8(((byte)BerType.Context | (byte)BerType.Constructed | 6));
         //LEN
         data.SetUInt8((byte)(2 + cipher.SystemTitle.Length));
         data.SetUInt8((byte)BerType.OctetString);
         //LEN
         data.SetUInt8((byte)cipher.SystemTitle.Length);
         data.Set(cipher.SystemTitle);
     }
 }
Exemplo n.º 59
0
        /// <summary>
        /// Import server settings and COSEM objects from GXDLMSDirector trace.
        /// </summary>
        /// <param name="server">Server where settings are updated.</param>
        /// <param name="data">GXDLMSDirector trace in byte array.</param>
        public static void Import(GXDLMSServer server, byte[] data)
        {
            GXDLMSTranslator translator = new GXDLMSTranslator(TranslatorOutputType.StandardXml);
            translator.CompletePdu = true;
            translator.PduOnly = true;
            XmlDocument doc = new XmlDocument();
            List<ValueEventArgs> targets = new List<ValueEventArgs>();
            GXDLMSSettings settings = new GXDLMSSettings(true);
            GXByteBuffer pdu = new GXByteBuffer();
            GXByteBuffer bb = new GXByteBuffer(data);
            server.InterfaceType = GXDLMSTranslator.GetDlmsFraming(bb);
            bool lastBlock = true;
            GXByteBuffer val = new DLMS.GXByteBuffer();
            while (translator.FindNextFrame(bb, pdu, server.InterfaceType))
            {
                String xml = translator.MessageToXml(bb);
                if (xml != "")
                {
                    doc.LoadXml(xml);
                    foreach (XmlNode node in doc.ChildNodes[doc.ChildNodes.Count - 1].ChildNodes)
                    {
                        if (node.Name == "x:get-request")
                        {
                            server.UseLogicalNameReferencing = true;
                            GetLN(settings.Objects, targets, node.ChildNodes);
                        }
                        else if (node.Name == "x:readRequest")
                        {
                            List<short> items = GetSN(node.ChildNodes);

                            server.UseLogicalNameReferencing = false;
                            foreach (short it in items)
                            {
                                GXSNInfo i = GXDLMSSNCommandHandler.FindSNObject(settings.Objects, Convert.ToUInt16((it) & 0xFFFF));
                                targets.Add(new ValueEventArgs(i.Item, i.Index, 0, null));
                            }
                        }
                        else if (node.Name == "x:readResponse" ||
                                 node.Name == "x:get-response")
                        {
                            if (targets != null)
                            {
                                List<string> items;
                                if (server.UseLogicalNameReferencing)
                                {
                                    items = GetLNValues(node.ChildNodes);
                                }
                                else
                                {
                                    items = GetSNValues(node.ChildNodes);
                                }

                                int pos = 0;
                                foreach (string it in items)
                                {
                                    if ("read-write-denied".Equals(it) ||
                                            "scope-of-access-violated".Equals(it) ||
                                            "object-unavailable".Equals(it))
                                    {
                                        ValueEventArgs ve = targets[pos];
                                        ve.Target.SetAccess(ve.Index, AccessMode.NoAccess);
                                        continue;
                                    }
                                    try
                                    {
                                        if (server.UseLogicalNameReferencing)
                                        {
                                            lastBlock = IsLastBlock(node.ChildNodes);
                                        }
                                        val.Set(translator.XmlToData(it));
                                        if (lastBlock)
                                        {
                                            if (settings.Objects.Count == 0)
                                            {
                                                GXDLMSClient c = new GXDLMSClient();
                                                c.UseLogicalNameReferencing = server.UseLogicalNameReferencing;
                                                settings.Objects = c.ParseObjects(val, true);
                                                //Update OBIS code description.
                                                GXDLMSConverter converter = new GXDLMSConverter();
                                                converter.UpdateOBISCodeInformation(settings.Objects);
                                            }
                                            else
                                            {
                                                ValueEventArgs ve = targets[pos];
                                                GXDataInfo info = new GXDataInfo();
                                                ve.Value = GXCommon.GetData(server.Settings, val, info);
                                                if (ve.Value is byte[])
                                                {
                                                    DataType tp = ve.Target.GetUIDataType(ve.Index);
                                                    if (tp != DataType.None)
                                                    {
                                                        ve.Value = GXDLMSClient.ChangeType((byte[])ve.Value, tp);
                                                    }
                                                }
                                                ((IGXDLMSBase)ve.Target).SetValue(settings, ve);
                                            }
                                            val.Clear();
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        ValueEventArgs ve = targets[pos];
                                        ve.Target.SetAccess(ve.Index, AccessMode.NoAccess);

                                    }
                                    ++pos;
                                }
                                if (lastBlock)
                                {
                                    targets.Clear();
                                }
                            }

                        }
                    }
                }
            }
            server.Items.Clear();
            server.Items.AddRange(settings.Objects);
        }
Exemplo n.º 60
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                return(this.LogicalName);
            }
            else if (e.Index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(3);
                if (MonitoredValue == null)
                {
                    GXCommon.SetData(settings, data, DataType.Int16, 0);
                    GXCommon.SetData(settings, data, DataType.OctetString, "0.0.0.0.0.0");
                    GXCommon.SetData(settings, data, DataType.UInt8, 0);
                }
                else
                {
                    GXCommon.SetData(settings, data, DataType.Int16, MonitoredValue.ObjectType);
                    GXCommon.SetData(settings, data, DataType.OctetString, MonitoredValue.LogicalName);
                    GXCommon.SetData(settings, data, DataType.UInt8, MonitoredAttributeIndex);
                }
                return(data.Array());
            }
            else if (e.Index == 3)
            {
                return(ThresholdActive);
            }
            else if (e.Index == 4)
            {
                return(ThresholdNormal);
            }
            else if (e.Index == 5)
            {
                return(ThresholdEmergency);
            }
            else if (e.Index == 6)
            {
                return(MinOverThresholdDuration);
            }
            else if (e.Index == 7)
            {
                return(MinUnderThresholdDuration);
            }
            else if (e.Index == 8)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(3);
                GXCommon.SetData(settings, data, DataType.UInt16, EmergencyProfile.ID);
                GXCommon.SetData(settings, data, DataType.OctetString, EmergencyProfile.ActivationTime);
                GXCommon.SetData(settings, data, DataType.UInt32, EmergencyProfile.Duration);
                return(data.Array());
            }
            else if (e.Index == 9)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (EmergencyProfileGroupIDs == null)
                {
                    data.SetUInt8(0);
                }
                else
                {
                    data.SetUInt8((byte)EmergencyProfileGroupIDs.Length);
                    foreach (object it in EmergencyProfileGroupIDs)
                    {
                        GXCommon.SetData(settings, data, DataType.UInt16, it);
                    }
                }

                return(data.Array());
            }
            else if (e.Index == 10)
            {
                return(EmergencyProfileActive);
            }
            else if (e.Index == 11)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                GXCommon.SetData(settings, data, DataType.OctetString, ActionOverThreshold.LogicalName);
                GXCommon.SetData(settings, data, DataType.UInt16, ActionOverThreshold.ScriptSelector);
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                GXCommon.SetData(settings, data, DataType.OctetString, ActionUnderThreshold.LogicalName);
                GXCommon.SetData(settings, data, DataType.UInt16, ActionUnderThreshold.ScriptSelector);
                return(data.Array());
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return(null);
        }