Esempio n. 1
0
        /// <summary>
        /// Reserved for internal use.
        /// </summary>
        internal void EncodeData(byte[] data, ref int index)
        {
            int tag = data[index++];

            if (tag != 0xBE)
            {
                throw new Exception("Invalid tag.");
            }
            int len = data[index++];

            if (data.Length - index < len)
            {
                throw new Exception("Not enough data.");
            }
            //Excoding the choice for user information
            tag = data[index++];
            if (tag != 0x4)
            {
                throw new Exception("Invalid tag.");
            }
            len = data[index++];
            //Tag for xDLMS-Initate.response
            tag = data[index++];
            bool response = tag == GXCommon.InitialResponce;

            if (response)
            {
                //Optional usage field of the negotiated quality of service component
                tag = data[index++];
                if (tag != 0)//Skip if used.
                {
                    len    = data[index++];
                    index += len;
                }
            }
            else if (tag == GXCommon.InitialRequest)
            {
                //Optional usage field of the negotiated quality of service component
                tag = data[index++];
                if (tag != 0)//Skip if used.
                {
                    len    = data[index++];
                    index += len;
                }
                //Optional usage field of the negotiated quality of service component
                tag = data[index++];
                if (tag != 0)//Skip if used.
                {
                    len    = data[index++];
                    index += len;
                }
                //Optional usage field of the negotiated quality of service component
                tag = data[index++];
                if (tag != 0)//Skip if used.
                {
                    len    = data[index++];
                    index += len;
                }
            }
            else
            {
                throw new Exception("Invalid tag.");
            }
            //Get DLMS version number.
            DLMSVersioNumber = data[index++];
            //Tag for conformance block
            tag = data[index++];
            if (tag != 0x5F)
            {
                throw new Exception("Invalid tag.");
            }
            //Old Way...
            if (data[index] == 0x1F)
            {
                ++index;
            }
            len = data[index++];
            //The number of unused bits in the bit string.
            tag = data[index++];
            Array.Copy(data, index, ConformanceBlock, 0, 3);
            index            += 3;
            MaxReceivePDUSize = GXCommon.GetUInt16(data, ref index);
            if (response)
            {
                //VAA Name
                tag = data[index++];
                tag = data[index++];
            }
        }
Esempio n. 2
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 = (string)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            = (string)tmp[2];
                 it.Modulation         = (Modulation)Convert.ToInt32(tmp[3]);
                 it.TxGain             = Convert.ToSByte(tmp[4]);
                 it.TxRes              = (GainResolution)Convert.ToInt32(tmp[5]);
                 it.TxCoeff            = (string)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;
     }
 }
Esempio n. 3
0
 object IGXDLMSBase.GetValue(int index, int selector, object parameters)
 {
     if (index == 1)
     {
         return(this.LogicalName);
     }
     if (index == 2)
     {
         return(GXDLMSClient.ChangeType(ASCIIEncoding.ASCII.GetBytes(CalendarNameActive), DataType.OctetString));
     }
     if (index == 3)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (SeasonProfileActive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = SeasonProfileActive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSSeasonProfile it in SeasonProfileActive)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add(3);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Name));
                 GXCommon.SetData(data, DataType.OctetString, it.Start);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.WeekName));
             }
         }
         return(data.ToArray());
     }
     if (index == 4)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (WeekProfileTableActive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = WeekProfileTableActive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSWeekProfile it in WeekProfileTableActive)
             {
                 data.Add((byte)DataType.Array);
                 data.Add(8);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Name));
                 GXCommon.SetData(data, DataType.UInt8, it.Monday);
                 GXCommon.SetData(data, DataType.UInt8, it.Tuesday);
                 GXCommon.SetData(data, DataType.UInt8, it.Wednesday);
                 GXCommon.SetData(data, DataType.UInt8, it.Thursday);
                 GXCommon.SetData(data, DataType.UInt8, it.Friday);
                 GXCommon.SetData(data, DataType.UInt8, it.Saturday);
                 GXCommon.SetData(data, DataType.UInt8, it.Sunday);
             }
         }
         return(data.ToArray());
     }
     if (index == 5)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (DayProfileTableActive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = DayProfileTableActive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSDayProfile it in DayProfileTableActive)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add(2);
                 GXCommon.SetData(data, DataType.UInt8, it.DayId);
                 data.Add((byte)DataType.Array);
                 //Add count
                 GXCommon.SetObjectCount(it.DaySchedules.Length, data);
                 foreach (GXDLMSDayProfileAction action in it.DaySchedules)
                 {
                     data.Add((byte)DataType.Structure);
                     data.Add(3);
                     GXCommon.SetData(data, DataType.Time, action.StartTime);
                     GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(action.ScriptLogicalName));
                     GXCommon.SetData(data, DataType.UInt16, action.ScriptSelector);
                 }
             }
         }
         return(data.ToArray());
     }
     if (index == 6)
     {
         return(GXDLMSClient.ChangeType(ASCIIEncoding.ASCII.GetBytes(CalendarNamePassive), DataType.OctetString));
     }
     //
     if (index == 7)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (SeasonProfileActive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = SeasonProfileActive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSSeasonProfile it in SeasonProfileActive)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add(3);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Name));
                 GXCommon.SetData(data, DataType.OctetString, it.Start);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.WeekName));
             }
         }
         return(data.ToArray());
     }
     if (index == 8)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (WeekProfileTableActive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = WeekProfileTableActive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSWeekProfile it in WeekProfileTableActive)
             {
                 data.Add((byte)DataType.Array);
                 data.Add(8);
                 GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Name));
                 GXCommon.SetData(data, DataType.UInt8, it.Monday);
                 GXCommon.SetData(data, DataType.UInt8, it.Tuesday);
                 GXCommon.SetData(data, DataType.UInt8, it.Wednesday);
                 GXCommon.SetData(data, DataType.UInt8, it.Thursday);
                 GXCommon.SetData(data, DataType.UInt8, it.Friday);
                 GXCommon.SetData(data, DataType.UInt8, it.Saturday);
                 GXCommon.SetData(data, DataType.UInt8, it.Sunday);
             }
         }
         return(data.ToArray());
     }
     if (index == 9)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (DayProfileTablePassive == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = DayProfileTablePassive.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (GXDLMSDayProfile it in DayProfileTablePassive)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add(2);
                 GXCommon.SetData(data, DataType.UInt8, it.DayId);
                 data.Add((byte)DataType.Array);
                 //Add count
                 GXCommon.SetObjectCount(it.DaySchedules.Length, data);
                 foreach (GXDLMSDayProfileAction action in it.DaySchedules)
                 {
                     data.Add((byte)DataType.Structure);
                     data.Add(3);
                     GXCommon.SetData(data, DataType.Time, action.StartTime);
                     GXCommon.SetData(data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(action.ScriptLogicalName));
                     GXCommon.SetData(data, DataType.UInt16, action.ScriptSelector);
                 }
             }
         }
         return(data.ToArray());
     }
     if (index == 10)
     {
         return(Time);
     }
     throw new ArgumentException("GetValue failed. Invalid attribute index.");
 }
Esempio n. 4
0
        byte[] GetProfileGenericData(GXDLMSSettings settings, ValueEventArgs e)
        {
            List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > columns = null;

            //If all data is read.
            if (e.Selector == 0 || e.Parameters == null || e.RowEndIndex != 0)
            {
                return(GetData(settings, e, Buffer, columns));
            }
            List <object>   arr   = (List <object>)e.Parameters;
            List <object[]> table = new List <object[]>();

            lock (Buffer)
            {
                if (e.Selector == 1) //Read by range
                {
                    GXDataInfo info = new GXDataInfo();
                    info.Type = DataType.DateTime;
                    DateTime start = ((GXDateTime)GXCommon.GetData(settings, new GXByteBuffer((byte[])arr[1]), info)).Value.LocalDateTime;
                    info.Clear();
                    info.Type = DataType.DateTime;
                    DateTime end = ((GXDateTime)GXCommon.GetData(settings, new GXByteBuffer((byte[])arr[2]), info)).Value.LocalDateTime;
                    if (arr.Count > 3)
                    {
                        columns = GetColumns((List <object>)arr[3]);
                    }
                    foreach (object[] row in Buffer)
                    {
                        DateTime tm = Convert.ToDateTime(row[0]);
                        if (tm >= start && tm <= end)
                        {
                            table.Add(row);
                        }
                    }
                }
                else if (e.Selector == 2)//Read by entry.
                {
                    int start = Convert.ToInt32(arr[0]);
                    if (start == 0)
                    {
                        start = 1;
                    }
                    int count = Convert.ToInt32(arr[1]);
                    if (count == 0)
                    {
                        count = Buffer.Count;
                    }
                    if (start + count > Buffer.Count + 1)
                    {
                        count = Buffer.Count;
                    }

                    int colStart = 1;
                    int colCount = 0;
                    if (arr.Count > 2)
                    {
                        colStart = Convert.ToUInt16(arr[2]);
                    }
                    if (arr.Count > 3)
                    {
                        colCount = Convert.ToUInt16(arr[3]);
                    }
                    else if (colStart != 1)
                    {
                        colCount = CaptureObjects.Count;
                    }
                    if (colStart != 1 || colCount != 0)
                    {
                        columns = new List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> >();
                        for (int pos = 0; pos != colCount; ++pos)
                        {
                            columns.Add(CaptureObjects[colStart + pos - 1]);
                        }
                    }

                    //Get rows.
                    // Starting index is 1.
                    for (int pos = 0; pos < count; ++pos)
                    {
                        if (pos + start - 1 == Buffer.Count)
                        {
                            break;
                        }
                        table.Add(Buffer[start + pos - 1]);
                    }
                }
                else
                {
                    throw new Exception("Invalid selector.");
                }
            }
            return(GetData(settings, e, table, columns));
        }
 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;
     }
 }
Esempio n. 6
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                return(GXCommon.LogicalNameToBytes(LogicalName));

            case 2:
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(4);
                if (ChangedParameter == null || ChangedParameter.Target == null)
                {
                    GXCommon.SetData(settings, data, DataType.UInt16, 0);
                    GXCommon.SetData(settings, data, DataType.OctetString, new byte[] { 0, 0, 0, 0, 0, 0 });
                    GXCommon.SetData(settings, data, DataType.Int8, 1);
                    GXCommon.SetData(settings, data, DataType.None, null);
                }
                else
                {
                    GXCommon.SetData(settings, data, DataType.UInt16, ChangedParameter.Target.ObjectType);
                    GXCommon.SetData(settings, data, DataType.OctetString, GXCommon.LogicalNameToBytes(ChangedParameter.Target.LogicalName));
                    GXCommon.SetData(settings, data, DataType.Int8, ChangedParameter.AttributeIndex);
                    GXCommon.SetData(settings, data, GXDLMSConverter.GetDLMSDataType(ChangedParameter.Value), ChangedParameter.Value);
                }
                return(data.Array());
            }

            case 3:
                return(CaptureTime);

            case 4:
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (Parameters == null)
                {
                    data.SetUInt8(0);
                }
                else
                {
                    data.SetUInt8((byte)Parameters.Count);
                    foreach (GXDLMSTarget it in Parameters)
                    {
                        data.SetUInt8((byte)DataType.Structure);
                        data.SetUInt8((byte)3);
                        GXCommon.SetData(settings, data, DataType.UInt16, it.Target.ObjectType);
                        GXCommon.SetData(settings, data, DataType.OctetString, GXCommon.LogicalNameToBytes(it.Target.LogicalName));
                        GXCommon.SetData(settings, data, DataType.Int8, it.AttributeIndex);
                    }
                }
                return(data.Array());
            }

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
            return(null);
        }
Esempio n. 7
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                LogicalName = GXCommon.ToLogicalName(e.Value);
            }
            else if (e.Index == 2)
            {
                SetBuffer(settings, e);
            }
            else if (e.Index == 3)
            {
                Reset();
                //Clear file
                if (e.Server != null)
                {
                    ValueEventArgs[] list = new ValueEventArgs[] { new ValueEventArgs(this, 1, 0, null) };
                    e.Server.NotifyAction(list);
                    e.Server.NotifyPostAction(list);
                }
                CaptureObjects.Clear();
                if (e.Value != null)
                {
                    SetCaptureObjects(this, settings, CaptureObjects, e.Value as List <object>);
                }
            }
            else if (e.Index == 4)
            {
                //Any write access to one of the attributes will automatically call a reset
                //and this call will propagate to all other profiles capturing this profile.
                if (settings.IsServer)
                {
                    Reset();
                }
                CapturePeriod = Convert.ToInt32(e.Value);
            }
            else if (e.Index == 5)
            {
                //Any write access to one of the attributes will automatically call a reset
                //and this call will propagate to all other profiles capturing this profile.
                if (settings.IsServer)
                {
                    Reset();
                }
                SortMethod = (SortMethod)Convert.ToInt32(e.Value);
            }
            else if (e.Index == 6)
            {
                //Any write access to one of the attributes will automatically call a reset
                //and this call will propagate to all other profiles capturing this profile.
                if (settings.IsServer)
                {
                    Reset();
                }

                if (e.Value is List <object> )
                {
                    List <object> tmp = e.Value as List <object>;
                    if (tmp.Count != 4)
                    {
                        throw new GXDLMSException("Invalid structure format.");
                    }
                    ObjectType type = (ObjectType)Convert.ToInt16(tmp[0]);
                    string     ln   = GXCommon.ToLogicalName((byte[])tmp[1]);
                    SortAttributeIndex = Convert.ToInt16(tmp[2]);
                    SortDataIndex      = Convert.ToInt16(tmp[3]);
                    SortObject         = null;
                    foreach (var it in CaptureObjects)
                    {
                        if (it.Key.ObjectType == type && it.Key.LogicalName == ln)
                        {
                            SortObject = it.Key;
                            break;
                        }
                    }
                    if (SortObject == null)
                    {
                        SortObject             = GXDLMSClient.CreateObject(type);
                        SortObject.LogicalName = ln;
                    }
                }
                else
                {
                    SortObject = null;
                }
            }
            else if (e.Index == 7)
            {
                EntriesInUse = Convert.ToInt32(e.Value);
            }
            else if (e.Index == 8)
            {
                //Any write access to one of the attributes will automatically call a reset
                //and this call will propagate to all other profiles capturing this profile.
                if (settings.IsServer)
                {
                    Reset();
                }
                ProfileEntries = Convert.ToUInt32(e.Value);
            }
            else
            {
                e.Error = ErrorCode.ReadWriteDenied;
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Read DLMS Data from the device.
        /// </summary>
        /// <param name="data">Data to send.</param>
        /// <returns>Received data.</returns>
        public void ReadDLMSPacket(byte[] data, GXReplyData reply)
        {
            if (data == null)
            {
                return;
            }
            reply.Error = 0;
            object eop = (byte)0x7E;

            //In network connection terminator is not used.
            if (Client.InterfaceType == InterfaceType.WRAPPER && Media is GXNet)
            {
                eop = null;
            }
            int  pos       = 0;
            bool succeeded = false;
            ReceiveParameters <byte[]> p = new ReceiveParameters <byte[]>()
            {
                Eop      = eop,
                Count    = 5,
                WaitTime = WaitTime,
            };

            lock (Media.Synchronous)
            {
                while (!succeeded && pos != 3)
                {
                    WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(data, true));
                    Media.Send(data, null);
                    succeeded = Media.Receive(p);
                    if (!succeeded)
                    {
                        //If Eop is not set read one byte at time.
                        if (p.Eop == null)
                        {
                            p.Count = 1;
                        }
                        //Try to read again...
                        if (++pos != 3)
                        {
                            System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                            continue;
                        }
                        throw new Exception("Failed to receive reply from the device in given time.");
                    }
                }
                try
                {
                    //Loop until whole COSEM packet is received.
                    while (!Client.GetData(p.Reply, reply))
                    {
                        //If Eop is not set read one byte at time.
                        if (p.Eop == null)
                        {
                            p.Count = 1;
                        }
                        while (!Media.Receive(p))
                        {
                            //If echo.
                            if (p.Reply.Length == data.Length)
                            {
                                Media.Send(data, null);
                            }
                            //Try to read again...
                            if (++pos != 3)
                            {
                                System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                                continue;
                            }
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(p.Reply, true));
                    throw ex;
                }
            }
            WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(p.Reply, true));
            if (reply.Error != 0)
            {
                if (reply.Error == (short)ErrorCode.Rejected)
                {
                    Thread.Sleep(1000);
                    ReadDLMSPacket(data, reply);
                }
                else
                {
                    throw new GXDLMSException(reply.Error);
                }
            }
        }
Esempio n. 9
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return(this.LogicalName);
     }
     if (e.Index == 2)
     {
         return(PHYReference);
     }
     if (e.Index == 3)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (LCPOptions == null)
         {
             data.SetUInt8(0);
         }
         else
         {
             data.SetUInt8((byte)IPCPOptions.Length);
             foreach (GXDLMSPppSetupLcpOption it in LCPOptions)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)3);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Type);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Length);
                 GXCommon.SetData(settings, data, GXCommon.GetValueType(it.Data), it.Data);
             }
         }
         return(data.Array());
     }
     if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (IPCPOptions == null)
         {
             data.SetUInt8(0);
         }
         else
         {
             data.SetUInt8((byte)IPCPOptions.Length);
             foreach (GXDLMSPppSetupIPCPOption it in IPCPOptions)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)3);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Type);
                 GXCommon.SetData(settings, data, DataType.UInt8, it.Length);
                 GXCommon.SetData(settings, data, GXCommon.GetValueType(it.Data), it.Data);
             }
         }
         return(data.Array());
     }
     else if (e.Index == 5)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8(2);
         GXCommon.SetData(settings, data, DataType.OctetString, UserName);
         GXCommon.SetData(settings, data, DataType.OctetString, Password);
         return(data.Array());
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Esempio n. 10
0
        void InitSerial()
        {
            GXSerial serial     = Media as GXSerial;
            byte     Terminator = (byte)0x0A;

            if (serial != null && InitializeIEC)
            {
                serial.BaudRate = 300;
                serial.DataBits = 7;
                serial.Parity   = Parity.Even;
                serial.StopBits = StopBits.One;
            }
            Media.Open();
            //Query device information.
            if (Media != null && InitializeIEC)
            {
                string data = "/?!\r\n";
                if (Trace)
                {
                    Console.WriteLine("IEC sending:" + data);
                }
                ReceiveParameters <string> p = new ReceiveParameters <string>()
                {
                    Eop      = Terminator,
                    WaitTime = WaitTime
                };
                lock (Media.Synchronous)
                {
                    WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(data), true));
                    Media.Send(data, null);
                    if (!Media.Receive(p))
                    {
                        //Try to move away from mode E.
                        try
                        {
                            GXReplyData reply = new GXReplyData();
                            ReadDLMSPacket(Client.DisconnectRequest(), reply);
                        }
                        catch (Exception)
                        {
                        }
                        data = (char)0x01 + "B0" + (char)0x03;
                        Media.Send(data, null);
                        p.Count = 1;
                        if (!Media.Receive(p))
                        {
                        }
                        data = "Failed to receive reply from the device in given time.";
                        Console.WriteLine(data);
                        throw new Exception(data);
                    }
                    WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!Media.Receive(p))
                        {
                            //Try to move away from mode E.
                            GXReplyData reply = new GXReplyData();
                            ReadDLMSPacket(Client.DisconnectRequest(), reply);
                            if (serial != null)
                            {
                                data = (char)0x01 + "B0" + (char)0x03;
                                Media.Send(data, null);
                                p.Count = 1;
                                Media.Receive(p);
                                serial.BaudRate = 9600;
                                data            = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                                Media.Send(data, null);
                                p.Count = 1;
                                Media.Receive(p);
                            }

                            data = "Failed to receive reply from the device in given time.";
                            Console.WriteLine(data);
                            throw new Exception(data);
                        }
                        WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                    }
                }
                Console.WriteLine("IEC received: " + p.Reply);
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    Media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int  BaudRate = 0;
                switch (baudrate)
                {
                case '0':
                    BaudRate = 300;
                    break;

                case '1':
                    BaudRate = 600;
                    break;

                case '2':
                    BaudRate = 1200;
                    break;

                case '3':
                    BaudRate = 2400;
                    break;

                case '4':
                    BaudRate = 4800;
                    break;

                case '5':
                    BaudRate = 9600;
                    break;

                case '6':
                    BaudRate = 19200;
                    break;

                default:
                    throw new Exception("Unknown baud rate.");
                }
                Console.WriteLine("BaudRate is : " + BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                byte controlCharacter = (byte)'2';     // "2" HDLC protocol procedure (Mode E)
                                                       //Send Baudrate character
                                                       //Mode control character
                byte ModeControlCharacter = (byte)'2'; //"2" //(HDLC protocol procedure) (Binary mode)
                                                       //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                Console.WriteLine("Moving to mode E.", arr);
                lock (Media.Synchronous)
                {
                    WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(arr, true));
                    Media.Send(arr, null);
                    p.Reply = null;

                    p.WaitTime = 2000;
                    //Note! All meters do not echo this.
                    Media.Receive(p);
                    if (p.Reply != null)
                    {
                        WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(p.Reply), true));
                        Console.WriteLine("Received: " + p.Reply);
                    }
                    if (serial != null)
                    {
                        Media.Close();
                        serial.BaudRate = BaudRate;
                        serial.DataBits = 8;
                        serial.Parity   = Parity.None;
                        serial.StopBits = StopBits.One;
                        Media.Open();
                        //Some meters need this sleep. Do not remove.
                        Thread.Sleep(1000);
                    }
                }
            }
        }
Esempio n. 11
0
        public void InitializeConnection(GXManufacturer man)
        {
            Manufacturer = man;
            UpdateManufactureSettings(man.Identification);
            if (Media is GXSerial)
            {
                Console.WriteLine("Initializing serial connection.");
                InitSerial();
            }
            else if (Media is GXNet)
            {
                Console.WriteLine("Initializing Network connection.");
                InitNet();
                //Some Electricity meters need some time before first message can be send.
                System.Threading.Thread.Sleep(500);
            }
            else
            {
                throw new Exception("Unknown media type.");
            }
            GXReplyData reply = new GXReplyData();

            byte[] data;
            data = Client.SNRMRequest();
            if (data != null)
            {
                if (Trace)
                {
                    Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
                }
                ReadDLMSPacket(data, reply);
                if (Trace)
                {
                    Console.WriteLine("Parsing UA reply." + reply.ToString());
                }
                //Has server accepted client.
                Client.ParseUAResponse(reply.Data);
                Console.WriteLine("Parsing UA reply succeeded.");
            }
            //Generate AARQ request.
            //Split requests to multiple packets if needed.
            //If password is used all data might not fit to one packet.
            reply.Clear();
            ReadDataBlock(Client.AARQRequest(), reply);
            try
            {
                //Parse reply.
                Client.ParseAAREResponse(reply.Data);
                reply.Clear();
            }
            catch (Exception Ex)
            {
                reply.Clear();
                ReadDLMSPacket(Client.DisconnectRequest(), reply);
                throw Ex;
            }

            //Get challenge Is HLS authentication is used.
            if (Client.IsAuthenticationRequired)
            {
                foreach (byte[] it in Client.GetApplicationAssociationRequest())
                {
                    reply.Clear();
                    ReadDLMSPacket(it, reply);
                }
                Client.ParseApplicationAssociationResponse(reply.Data);
            }
            Console.WriteLine("Parsing AARE reply succeeded.");
        }
Esempio n. 12
0
 object IGXDLMSBase.GetValue(int index, int selector, object parameters)
 {
     if (index == 1)
     {
         return(this.LogicalName);
     }
     if (index == 2)
     {
         return(PHYReference);
     }
     if (index == 3)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (LCPOptions == null)
         {
             data.Add(0);
         }
         else
         {
             data.Add((byte)IPCPOptions.Length);
             foreach (GXDLMSPppSetupLcpOption it in LCPOptions)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add((byte)3);
                 GXCommon.SetData(data, DataType.UInt8, it.Type);
                 GXCommon.SetData(data, DataType.UInt8, it.Length);
                 GXCommon.SetData(data, GXCommon.GetValueType(it.Data), it.Data);
             }
         }
         return(data.ToArray());
     }
     if (index == 4)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Array);
         if (IPCPOptions == null)
         {
             data.Add(0);
         }
         else
         {
             data.Add((byte)IPCPOptions.Length);
             foreach (GXDLMSPppSetupIPCPOption it in IPCPOptions)
             {
                 data.Add((byte)DataType.Structure);
                 data.Add((byte)3);
                 GXCommon.SetData(data, DataType.UInt8, it.Type);
                 GXCommon.SetData(data, DataType.UInt8, it.Length);
                 GXCommon.SetData(data, GXCommon.GetValueType(it.Data), it.Data);
             }
         }
         return(data.ToArray());
     }
     else if (index == 5)
     {
         List <byte> data = new List <byte>();
         data.Add((byte)DataType.Structure);
         data.Add(2);
         GXCommon.SetData(data, DataType.OctetString, UserName);
         GXCommon.SetData(data, DataType.OctetString, Password);
         return(data.ToArray());
     }
     throw new ArgumentException("GetValue failed. Invalid attribute index.");
 }
Esempio n. 13
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                LogicalName = GXCommon.ToLogicalName(e.Value);
                break;

            case 2:
                AccountStatus = (AccountStatus)((object[])e.Value)[0];
                PaymentMode   = (PaymentMode)((object[])e.Value)[1];
                break;

            case 3:
                CurrentCreditInUse = (byte)e.Value;
                break;

            case 4:
                CurrentCreditStatus = (AccountCreditStatus)Convert.ToByte(e.Value);
                break;

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

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

            case 7:
                ClearanceThreshold = (int)e.Value;
                break;

            case 8:
                AggregatedDebt = (int)e.Value;
                break;

            case 9:
                CreditReferences.Clear();
                if (e.Value != null)
                {
                    foreach (object it in (object[])e.Value)
                    {
                        CreditReferences.Add(GXCommon.ToLogicalName(it));
                    }
                }
                break;

            case 10:
                ChargeReferences.Clear();
                if (e.Value != null)
                {
                    foreach (object it in (object[])e.Value)
                    {
                        ChargeReferences.Add(GXCommon.ToLogicalName(it));
                    }
                }
                break;

            case 11:
                CreditChargeConfigurations.Clear();
                if (e.Value != null)
                {
                    foreach (object[] it in (object[])e.Value)
                    {
                        GXCreditChargeConfiguration item = new GXCreditChargeConfiguration();
                        item.CreditReference         = GXCommon.ToLogicalName(it[0]);
                        item.ChargeReference         = GXCommon.ToLogicalName(it[1]);
                        item.CollectionConfiguration = (CreditCollectionConfiguration)Convert.ToByte(it[2]);
                        CreditChargeConfigurations.Add(item);
                    }
                }
                break;

            case 12:
                TokenGatewayConfigurations.Clear();
                if (e.Value != null)
                {
                    foreach (object[] it in (object[])e.Value)
                    {
                        GXTokenGatewayConfiguration item = new GXTokenGatewayConfiguration();
                        item.CreditReference = GXCommon.ToLogicalName(it[0]);
                        item.TokenProportion = (byte)it[1];
                        TokenGatewayConfigurations.Add(item);
                    }
                }
                break;

            case 13:
                if (e.Value == null)
                {
                    AccountActivationTime = 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)
                    {
                        AccountActivationTime = (GXDateTime)e.Value;
                    }
                }
                break;

            case 14:
                if (e.Value == null)
                {
                    AccountClosureTime = 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)
                    {
                        AccountClosureTime = (GXDateTime)e.Value;
                    }
                }
                break;

            case 15:
                object[] tmp = (object[])e.Value;
                Currency.Name  = (string)tmp[0];
                Currency.Scale = (sbyte)tmp[1];
                Currency.Unit  = (Currency)tmp[2];
                break;

            case 16:
                LowCreditThreshold = (int)e.Value;
                break;

            case 17:
                NextCreditAvailableThreshold = (int)e.Value;
                break;

            case 18:
                MaxProvision = (UInt16)e.Value;
                break;

            case 19:
                MaxProvisionPeriod = (int)e.Value;
                break;

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
        }
Esempio n. 14
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            GXByteBuffer bb;

            switch (e.Index)
            {
            case 1:
                return(GXCommon.LogicalNameToBytes(LogicalName));

            case 2:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Structure);
                bb.SetUInt8(2);
                bb.SetUInt8(DataType.Enum);
                bb.SetUInt8(AccountStatus);
                bb.SetUInt8(DataType.Enum);
                bb.SetUInt8(PaymentMode);
                return(bb.Array());

            case 3:
                return(CurrentCreditInUse);

            case 4:
                return((byte)CurrentCreditStatus);

            case 5:
                return(AvailableCredit);

            case 6:
                return(AmountToClear);

            case 7:
                return(ClearanceThreshold);

            case 8:
                return(AggregatedDebt);

            case 9:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Array);
                if (CreditReferences == null)
                {
                    bb.SetUInt8(0);
                }
                else
                {
                    GXCommon.SetObjectCount(CreditReferences.Count, bb);
                    foreach (string it in CreditReferences)
                    {
                        bb.SetUInt8(DataType.OctetString);
                        bb.SetUInt8(6);
                        bb.Set(GXCommon.LogicalNameToBytes(it));
                    }
                }
                return(bb.Array());

            case 10:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Array);
                if (ChargeReferences == null)
                {
                    bb.SetUInt8(0);
                }
                else
                {
                    GXCommon.SetObjectCount(ChargeReferences.Count, bb);
                    foreach (string it in ChargeReferences)
                    {
                        bb.SetUInt8(DataType.OctetString);
                        bb.SetUInt8(6);
                        bb.Set(GXCommon.LogicalNameToBytes(it));
                    }
                }
                return(bb.Array());

            case 11:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Array);
                if (CreditChargeConfigurations == null)
                {
                    bb.SetUInt8(0);
                }
                else
                {
                    GXCommon.SetObjectCount(CreditChargeConfigurations.Count, bb);
                    foreach (GXCreditChargeConfiguration it in CreditChargeConfigurations)
                    {
                        bb.SetUInt8(DataType.Structure);
                        bb.SetUInt8(3);
                        bb.SetUInt8(DataType.OctetString);
                        bb.SetUInt8(6);
                        bb.Set(GXCommon.LogicalNameToBytes(it.CreditReference));
                        bb.SetUInt8(DataType.OctetString);
                        bb.SetUInt8(6);
                        bb.Set(GXCommon.LogicalNameToBytes(it.ChargeReference));
                        bb.SetUInt8(DataType.BitString);
                        bb.SetUInt8(3);
                        bb.SetUInt8(it.CollectionConfiguration);
                    }
                }
                return(bb.Array());

            case 12:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Array);
                if (TokenGatewayConfigurations == null)
                {
                    bb.SetUInt8(0);
                }
                else
                {
                    GXCommon.SetObjectCount(TokenGatewayConfigurations.Count, bb);
                    foreach (GXTokenGatewayConfiguration it in TokenGatewayConfigurations)
                    {
                        bb.SetUInt8(DataType.Structure);
                        bb.SetUInt8(2);
                        bb.SetUInt8(DataType.OctetString);
                        bb.SetUInt8(6);
                        bb.Set(GXCommon.LogicalNameToBytes(it.CreditReference));
                        bb.SetUInt8(DataType.UInt8);
                        bb.SetUInt8(it.TokenProportion);
                    }
                }
                return(bb.Array());

            case 13:
                return(AccountActivationTime);

            case 14:
                return(AccountClosureTime);

            case 15:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Structure);
                bb.SetUInt8(3);
                GXCommon.SetData(settings, bb, DataType.StringUTF8, Currency.Name);
                GXCommon.SetData(settings, bb, DataType.Int8, Currency.Scale);
                GXCommon.SetData(settings, bb, DataType.Enum, Currency.Unit);
                return(bb.Array());

            case 16:
                return(LowCreditThreshold);

            case 17:
                return(NextCreditAvailableThreshold);

            case 18:
                return(MaxProvision);

            case 19:
                return(MaxProvisionPeriod);

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
            return(null);
        }
Esempio n. 15
0
        public void GetProfileGenerics()
        {
            //Find profile generics register objects and read them.
            foreach (GXDLMSObject it in Client.Objects.GetObjects(ObjectType.ProfileGeneric))
            {
                //If trace is info.
                if (Trace > TraceLevel.Warning)
                {
                    Console.WriteLine("-------- Reading " + it.GetType().Name + " " + it.Name + " " + it.Description);
                }
                long entriesInUse = Convert.ToInt64(Read(it, 7));
                long entries      = Convert.ToInt64(Read(it, 8));
                //If trace is info.
                if (Trace > TraceLevel.Warning)
                {
                    Console.WriteLine("Entries: " + entriesInUse + "/" + entries);
                }
                //If there are no columns or rows.
                if (entriesInUse == 0 || (it as GXDLMSProfileGeneric).CaptureObjects.Count == 0)
                {
                    continue;
                }
                //All meters are not supporting parameterized read.
                if ((Client.NegotiatedConformance & (Gurux.DLMS.Enums.Conformance.ParameterizedAccess | Gurux.DLMS.Enums.Conformance.SelectiveAccess)) != 0)
                {
                    try
                    {
                        //Read first row from Profile Generic.
                        object[] rows = ReadRowsByEntry(it as GXDLMSProfileGeneric, 1, 1);
                        //If trace is info.
                        if (Trace > TraceLevel.Warning)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (object[] row in rows)
                            {
                                foreach (object cell in row)
                                {
                                    if (cell is byte[])
                                    {
                                        sb.Append(GXCommon.ToHex((byte[])cell, true));
                                    }
                                    else
                                    {
                                        sb.Append(Convert.ToString(cell));
                                    }
                                    sb.Append(" | ");
                                }
                                sb.Append("\r\n");
                            }
                            Console.WriteLine(sb.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error! Failed to read first row: " + ex.Message);
                        //Continue reading.
                    }
                }
                //All meters are not supporting parameterized read.
                if ((Client.NegotiatedConformance & (Gurux.DLMS.Enums.Conformance.ParameterizedAccess | Gurux.DLMS.Enums.Conformance.SelectiveAccess)) != 0)
                {
                    try
                    {
                        //Read last day from Profile Generic.

                        object[] rows = ReadRowsByRange(it as GXDLMSProfileGeneric, DateTime.Now.Date, DateTime.MaxValue);
                        //If trace is info.
                        if (Trace > TraceLevel.Warning)
                        {
                            StringBuilder sb = new StringBuilder();
                            foreach (object[] row in rows)
                            {
                                foreach (object cell in row)
                                {
                                    if (cell is byte[])
                                    {
                                        sb.Append(GXCommon.ToHex((byte[])cell, true));
                                    }
                                    else
                                    {
                                        sb.Append(Convert.ToString(cell));
                                    }
                                    sb.Append(" | ");
                                }
                                sb.Append("\r\n");
                            }
                            Console.WriteLine(sb.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error! Failed to read last day: " + ex.Message);
                        //Continue reading.
                    }
                }
            }
        }
 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);
         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.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, 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)
     {
         if (SecuritySetupReference == null)
         {
             return(null);
         }
         return(ASCIIEncoding.ASCII.GetBytes(SecuritySetupReference));
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return(null);
 }
Esempio n. 17
0
        /// <summary>
        /// Read DLMS Data from the device.
        /// </summary>
        /// <param name="data">Data to send.</param>
        /// <returns>Received data.</returns>
        public void ReadDLMSPacket(byte[] data, GXReplyData reply)
        {
            if (data == null && !reply.IsStreaming())
            {
                return;
            }
            GXReplyData notify = new GXReplyData();

            reply.Error = 0;
            object eop = (byte)0x7E;

            //In network connection terminator is not used.
            if (Client.InterfaceType == InterfaceType.WRAPPER)
            {
                eop = null;
            }
            int  pos       = 0;
            bool succeeded = false;
            ReceiveParameters <byte[]> p = new ReceiveParameters <byte[]>()
            {
                Eop      = eop,
                Count    = eop == null ? 8 : 5,
                AllData  = true,
                WaitTime = WaitTime,
            };
            GXByteBuffer rd = new GXByteBuffer();

            lock (Media.Synchronous)
            {
                while (!succeeded && pos != 3)
                {
                    if (!reply.IsStreaming())
                    {
                        WriteTrace("TX:\t" + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(data, true));
                        p.Reply = null;
                        Media.Send(data, null);
                    }
                    succeeded = Media.Receive(p);
                    if (!succeeded)
                    {
                        if (++pos >= RetryCount)
                        {
                            throw new Exception("Failed to receive reply from the device in given time.");
                        }
                        //If Eop is not set read one byte at time.
                        if (p.Eop == null)
                        {
                            p.Count = 1;
                        }
                        //Try to read again...
                        System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                    }
                }
                rd = new GXByteBuffer(p.Reply);
                try
                {
                    pos = 0;
                    //Loop until whole COSEM packet is received.
                    while (!Client.GetData(rd, reply, notify))
                    {
                        p.Reply = null;
                        if (notify.IsComplete && notify.Data.Data != null)
                        {
                            //Handle notify.
                            if (!notify.IsMoreData)
                            {
                                //Show received push message as XML.
                                string           xml;
                                GXDLMSTranslator t = new GXDLMSTranslator(TranslatorOutputType.SimpleXml);
                                t.DataToXml(notify.Data, out xml);
                                Console.WriteLine(xml);
                                notify.Clear();
                                continue;
                            }
                        }
                        if (p.Eop == null)
                        {
                            p.Count = Client.GetFrameSize(rd);
                        }
                        while (!Media.Receive(p))
                        {
                            if (++pos >= RetryCount)
                            {
                                throw new Exception("Failed to receive reply from the device in given time.");
                            }
                            p.Reply = null;
                            Media.Send(data, null);
                            //Try to read again...
                            System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                        }
                        rd.Set(p.Reply);
                    }
                }
                catch (Exception ex)
                {
                    WriteTrace("RX:\t" + DateTime.Now.ToLongTimeString() + "\t" + rd);
                    throw ex;
                }
            }
            WriteTrace("RX:\t" + DateTime.Now.ToLongTimeString() + "\t" + rd);
            if (reply.Error != 0)
            {
                if (reply.Error == (short)ErrorCode.Rejected)
                {
                    Thread.Sleep(1000);
                    ReadDLMSPacket(data, reply);
                }
                else
                {
                    throw new GXDLMSException(reply.Error);
                }
            }
        }
 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, settings.UseUtc2NormalTime).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;
             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.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)
             {
                 AuthenticationMechanismName.JointIsoCtt = 0;
                 ++arr.Position;
                 AuthenticationMechanismName.Country = 0;
                 ++arr.Position;
                 AuthenticationMechanismName.CountryName = 0;
                 ++arr.Position;
                 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 = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString, false).ToString();
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Esempio n. 19
0
        void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            switch (e.Index)
            {
            case 1:
                LogicalName = GXCommon.ToLogicalName(e.Value);
                break;

            case 2:
            {
                ChangedParameter = new GXDLMSTarget();
                List <object> tmp = null;
                if (e.Value is List <object> )
                {
                    tmp = (List <object>)e.Value;
                }
                else if (e.Value is object[])
                {
                    tmp = new List <object>((object[])e.Value);
                }
                if (tmp != null)
                {
                    if (tmp.Count != 4)
                    {
                        throw new GXDLMSException("Invalid structure format.");
                    }
                    ObjectType type = (ObjectType)Convert.ToInt16(tmp[0]);
                    ChangedParameter.Target = settings.Objects.FindByLN(type, (byte[])tmp[1]);
                    if (ChangedParameter.Target == null)
                    {
                        ChangedParameter.Target             = GXDLMSClient.CreateObject(type);
                        ChangedParameter.Target.LogicalName = GXCommon.ToLogicalName((byte[])tmp[1]);
                    }
                    ChangedParameter.AttributeIndex = Convert.ToByte(tmp[2]);
                    ChangedParameter.Value          = tmp[3];
                }

                break;
            }

            case 3:
            {
                if (e.Value == null)
                {
                    CaptureTime = 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)
                    {
                        CaptureTime = (GXDateTime)e.Value;
                    }
                    else if (e.Value is String)
                    {
                        DateTime tm;
                        if (!DateTime.TryParse((String)e.Value, out tm))
                        {
                            CaptureTime = DateTime.ParseExact((String)e.Value, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern, CultureInfo.CurrentUICulture);
                        }
                        else
                        {
                            CaptureTime = tm;
                        }
                    }
                    else
                    {
                        CaptureTime = Convert.ToDateTime(e.Value);
                    }
                }

                break;
            }

            case 4:
            {
                Parameters.Clear();
                if (e.Value != null)
                {
                    foreach (object it in e.Value as IEnumerable <object> )
                    {
                        List <object> tmp;
                        if (it is List <object> )
                        {
                            tmp = (List <object>)it;
                        }
                        else
                        {
                            tmp = new List <object>((object[])it);
                        }
                        if (tmp.Count != 3)
                        {
                            throw new GXDLMSException("Invalid structure format.");
                        }
                        GXDLMSTarget obj  = new GXDLMSTarget();
                        ObjectType   type = (ObjectType)Convert.ToInt16(tmp[0]);
                        obj.Target = settings.Objects.FindByLN(type, (byte[])tmp[1]);
                        if (obj.Target == null)
                        {
                            obj.Target             = GXDLMSClient.CreateObject(type);
                            obj.Target.LogicalName = GXCommon.ToLogicalName((byte[])tmp[1]);
                        }
                        obj.AttributeIndex = Convert.ToByte(tmp[2]);
                        Parameters.Add(obj);
                    }
                }

                break;
            }

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                break;
            }
        }
Esempio n. 20
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);
 }
Esempio n. 21
0
        /// <summary>
        /// Returns buffer data.
        /// </summary>
        /// <param name="settings">DLMS settings.</param>
        /// <param name="e"></param>
        /// <param name="table"></param>
        /// <param name="columns">Columns to get. NULL if not used.</param>
        /// <returns></returns>
        byte[] GetData(GXDLMSSettings settings, ValueEventArgs e, List <object[]> table,
                       List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > columns)
        {
            int pos = 0;
            List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > cols = columns;

            if (columns == null)
            {
                cols = CaptureObjects;
            }
            DataType[] types = new DataType[cols.Count];
            foreach (GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> it in cols)
            {
                types[pos] = it.Key.GetDataType(it.Value.AttributeIndex);
                ++pos;
            }
            UInt16 columnStart = 1, columnEnd = 0;

            if (e.Selector == 2)
            {
                columnStart = (UInt16)((List <object>)e.Parameters)[2];
                columnEnd   = (UInt16)((List <object>)e.Parameters)[3];
            }

            if (columnStart > 1 || columnEnd != 0)
            {
                pos  = 1;
                cols = new List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> >();
                foreach (GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> it in CaptureObjects)
                {
                    if (!(pos < columnStart || pos > columnEnd))
                    {
                        cols.Add(it);
                    }
                    ++pos;
                }
                pos = 0;
            }
            GXByteBuffer data = new GXByteBuffer();

            if (settings.Index == 0)
            {
                data.SetUInt8((byte)DataType.Array);
                if (e.RowEndIndex != 0)
                {
                    GXCommon.SetObjectCount((int)(e.RowEndIndex - e.RowBeginIndex), data);
                }
                else
                {
                    GXCommon.SetObjectCount(table.Count, data);
                }
            }

            foreach (object[] items in table)
            {
                data.SetUInt8((byte)DataType.Structure);
                GXCommon.SetObjectCount(cols.Count, data);
                pos = 0;
                DataType tp;
                foreach (object value in items)
                {
                    if (cols == null || cols.Contains(CaptureObjects[pos]))
                    {
                        tp = types[pos];
                        if (tp == DataType.None)
                        {
                            tp         = GXDLMSConverter.GetDLMSDataType(value);
                            types[pos] = tp;
                        }
                        if (value == null)
                        {
                            tp = DataType.None;
                        }
                        GXCommon.SetData(settings, data, tp, value);
                    }
                    ++pos;
                }
                ++settings.Index;
            }
            if (e.RowEndIndex != 0)
            {
                e.RowBeginIndex += (UInt32)table.Count;
            }
            else
            {
                settings.Index = 0;
            }
            return(data.Array());
        }
Esempio n. 22
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((IEnumerable <object>)e.Value);
         }
         PrefixTable = list.ToArray();
     }
     else if (e.Index == 6)
     {
         RoutingConfiguration.Clear();
         if (e.Value != null)
         {
             foreach (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> arr;
                 if (tmp is List <object> )
                 {
                     arr = (List <object>)tmp;
                 }
                 else
                 {
                     arr = new List <object>((object[])tmp);
                 }
                 GXDLMSRoutingConfiguration it = new GXDLMSRoutingConfiguration();
                 it.NetTraversalTime     = Convert.ToByte(arr[0]);
                 it.RoutingTableEntryTtl = Convert.ToUInt16(arr[1]);
                 it.Kr                     = Convert.ToByte(arr[2]);
                 it.Km                     = Convert.ToByte(arr[3]);
                 it.Kc                     = Convert.ToByte(arr[4]);
                 it.Kq                     = Convert.ToByte(arr[5]);
                 it.Kh                     = Convert.ToByte(arr[6]);
                 it.Krt                    = Convert.ToByte(arr[7]);
                 it.RreqRetries            = Convert.ToByte(arr[8]);
                 it.RreqRerrWait           = Convert.ToByte(arr[9]);
                 it.BlacklistTableEntryTtl = Convert.ToUInt16(arr[10]);
                 it.UnicastRreqGenEnable   = Convert.ToBoolean(arr[11]);
                 it.RlcEnabled             = Convert.ToBoolean(arr[12]);
                 it.AddRevLinkCost         = Convert.ToByte(arr[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 (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> arr;
                 if (tmp is List <object> )
                 {
                     arr = (List <object>)tmp;
                 }
                 else
                 {
                     arr = new List <object>((object[])tmp);
                 }
                 GXDLMSRoutingTable it = new GXDLMSRoutingTable();
                 it.DestinationAddress = Convert.ToUInt16(arr[0]);
                 it.NextHopAddress     = Convert.ToUInt16(arr[1]);
                 it.RouteCost          = Convert.ToUInt16(arr[2]);
                 it.HopCount           = Convert.ToByte(arr[3]);
                 it.WeakLinkCount      = Convert.ToByte(arr[4]);
                 it.ValidTime          = Convert.ToUInt16(arr[5]);
                 RoutingTable.Add(it);
             }
         }
     }
     else if (e.Index == 9)
     {
         ContextInformationTable.Clear();
         if (e.Value != null)
         {
             foreach (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> arr;
                 if (tmp is List <object> )
                 {
                     arr = (List <object>)tmp;
                 }
                 else
                 {
                     arr = new List <object>((object[])tmp);
                 }
                 GXDLMSContextInformationTable it = new GXDLMSContextInformationTable();
                 it.CID           = Convert.ToString(arr[0]);
                 it.Context       = (byte[])arr[2];
                 it.Compression   = Convert.ToBoolean(arr[3]);
                 it.ValidLifetime = Convert.ToUInt16(arr[4]);
                 ContextInformationTable.Add(it);
             }
         }
     }
     else if (e.Index == 10)
     {
         List <GXKeyValuePair <UInt16, UInt16> > list = new List <GXKeyValuePair <UInt16, UInt16> >();
         if (e.Value != null)
         {
             foreach (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> arr;
                 if (tmp is List <object> )
                 {
                     arr = (List <object>)tmp;
                 }
                 else
                 {
                     arr = new List <object>((object[])tmp);
                 }
                 list.Add(new GXKeyValuePair <UInt16, UInt16>(Convert.ToUInt16(arr[0]), Convert.ToUInt16(arr[1])));
             }
         }
         BlacklistTable = list;
     }
     else if (e.Index == 11)
     {
         BroadcastLogTable.Clear();
         if (e.Value != null)
         {
             foreach (object tmp in (IEnumerable <object>)e.Value)
             {
                 List <object> arr;
                 if (tmp is List <object> )
                 {
                     arr = (List <object>)tmp;
                 }
                 else
                 {
                     arr = new List <object>((object[])tmp);
                 }
                 GXDLMSBroadcastLogTable it = new GXDLMSBroadcastLogTable();
                 it.SourceAddress  = Convert.ToUInt16(arr[0]);
                 it.SequenceNumber = Convert.ToByte(arr[1]);
                 it.ValidTime      = Convert.ToUInt16(arr[2]);
                 BroadcastLogTable.Add(it);
             }
         }
     }
     else if (e.Index == 12)
     {
         List <UInt16> list = new List <UInt16>();
         if (e.Value != null)
         {
             foreach (object it in (IEnumerable <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;
     }
 }
 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);
 }
Esempio n. 24
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            object ret;

            switch (e.Index)
            {
            case 1:
                ret = GXCommon.LogicalNameToBytes(LogicalName);
                break;

            case 2:
                ret = (byte)Mode;
                break;

            case 3:
                ret = (byte)Speed;
                break;

            case 4:
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (PrimaryAddresses == null)
                {
                    data.SetUInt8(0);
                }
                else
                {
                    data.SetUInt8((byte)PrimaryAddresses.Length);
                    foreach (byte it in PrimaryAddresses)
                    {
                        data.SetUInt8((byte)DataType.UInt8);
                        data.SetUInt8(it);
                    }
                }
                ret = data.Array();
                break;
            }

            case 5:
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (Tabis == null)
                {
                    data.SetUInt8(0);
                }
                else
                {
                    data.SetUInt8((byte)Tabis.Length);
                    foreach (sbyte it in Tabis)
                    {
                        data.SetUInt8((byte)DataType.Int8);
                        data.SetUInt8((byte)it);
                    }
                }
                ret = data.Array();
                break;
            }

            default:
                e.Error = ErrorCode.ReadWriteDenied;
                ret     = null;
                break;
            }
            return(ret);
        }
Esempio n. 25
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);
 }
Esempio n. 26
0
 /// <summary>
 /// Read Invocation counter (frame counter) from the meter and update it.
 /// </summary>
 private void UpdateFrameCounter()
 {
     //Read frame counter if GeneralProtection is used.
     if (!string.IsNullOrEmpty(InvocationCounter) && Client.Ciphering != null && Client.Ciphering.Security != (byte)Security.None)
     {
         InitializeOpticalHead();
         byte[]      data;
         GXReplyData reply = new GXReplyData();
         Client.ProposedConformance |= Conformance.GeneralProtection;
         int            add       = Client.ClientAddress;
         Authentication auth      = Client.Authentication;
         byte           security  = Client.Ciphering.Security;
         byte[]         challenge = Client.CtoSChallenge;
         try
         {
             Client.ClientAddress      = 16;
             Client.Authentication     = Authentication.None;
             Client.Ciphering.Security = (byte)Security.None;
             data = Client.SNRMRequest();
             if (data != null)
             {
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
                 }
                 ReadDataBlock(data, reply);
                 if (Trace == TraceLevel.Verbose)
                 {
                     Console.WriteLine("Parsing UA reply." + reply.ToString());
                 }
                 //Has server accepted client.
                 Client.ParseUAResponse(reply.Data);
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Parsing UA reply succeeded.");
                 }
             }
             //Generate AARQ request.
             //Split requests to multiple packets if needed.
             //If password is used all data might not fit to one packet.
             foreach (byte[] it in Client.AARQRequest())
             {
                 if (Trace > TraceLevel.Info)
                 {
                     Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
                 }
                 reply.Clear();
                 ReadDataBlock(it, reply);
             }
             if (Trace > TraceLevel.Info)
             {
                 Console.WriteLine("Parsing AARE reply" + reply.ToString());
             }
             try
             {
                 //Parse reply.
                 Client.ParseAAREResponse(reply.Data);
                 reply.Clear();
                 GXDLMSData d = new GXDLMSData(InvocationCounter);
                 Read(d, 2);
                 Client.Ciphering.InvocationCounter = 1 + Convert.ToUInt32(d.Value);
                 Console.WriteLine("Invocation counter: " + Convert.ToString(Client.Ciphering.InvocationCounter));
                 reply.Clear();
                 Disconnect();
             }
             catch (Exception Ex)
             {
                 Disconnect();
                 throw Ex;
             }
         }
         finally
         {
             Client.ClientAddress      = add;
             Client.Authentication     = auth;
             Client.Ciphering.Security = security;
             Client.CtoSChallenge      = challenge;
         }
     }
 }
        private static void SetCaptureObjects(GXDLMSSettings settings, List <GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject> > list, IEnumerable <object> array)
        {
            GXDLMSConverter c = null;

            list.Clear();
            try
            {
                if (array != null)
                {
                    foreach (object tmp in array)
                    {
                        List <object> it;
                        if (tmp is List <object> )
                        {
                            it = (List <object>)tmp;
                        }
                        else
                        {
                            it = new List <object>((object[])tmp);
                        }
                        if (it.Count != 4)
                        {
                            throw new GXDLMSException("Invalid structure format.");
                        }
                        int v = Convert.ToInt16(it[0]);
                        if (Enum.GetName(typeof(ObjectType), v) == null)
                        {
                            list.Clear();
                            return;
                        }
                        ObjectType type           = (ObjectType)v;
                        string     ln             = GXCommon.ToLogicalName((byte[])it[1]);
                        int        attributeIndex = Convert.ToInt16(it[2]);
                        //If profile generic selective access is used.
                        if (attributeIndex < 0)
                        {
                            attributeIndex = 2;
                        }
                        int          dataIndex = Convert.ToInt16(it[3]);
                        GXDLMSObject obj       = null;
                        if (settings != null && settings.Objects != null)
                        {
                            obj = settings.Objects.FindByLN(type, ln);
                        }
                        if (obj == null)
                        {
                            obj = GXDLMSClient.CreateDLMSObject((int)type, null, 0, ln, 0);
                            if (c == null)
                            {
                                c = new GXDLMSConverter();
                            }
                            c.UpdateOBISCodeInformation(obj);
                        }
                        list.Add(new GXKeyValuePair <GXDLMSObject, GXDLMSCaptureObject>(obj, new GXDLMSCaptureObject(attributeIndex, dataIndex)));
                    }
                }
            }
            catch (Exception ex)
            {
                list.Clear();
                throw ex;
            }
        }
Esempio n. 28
0
        /// <summary>
        /// This method is used to update meter firmware.
        /// </summary>
        /// <param name="target"></param>
        public void ImageUpdate(GXDLMSImageTransfer target, byte[] identification, byte[] data)
        {
            //Check that image transfer ia enabled.
            GXReplyData reply = new GXReplyData();

            ReadDataBlock(Client.Read(target, 5), reply);
            Client.UpdateValue(target, 5, reply.Value);
            if (!target.ImageTransferEnabled)
            {
                throw new Exception("Image transfer is not enabled");
            }

            //Step 1: Read image block size.
            ReadDataBlock(Client.Read(target, 2), reply);
            Client.UpdateValue(target, 2, reply.Value);

            // Step 2: Initiate the Image transfer process.
            ReadDataBlock(target.ImageTransferInitiate(Client, identification, data.Length), reply);

            // Step 3: Transfers ImageBlocks.
            int imageBlockCount;

            ReadDataBlock(target.ImageBlockTransfer(Client, data, out imageBlockCount), reply);

            //Step 4: Check the completeness of the Image.
            ReadDataBlock(Client.Read(target, 3), reply);
            Client.UpdateValue(target, 3, reply.Value);

            // Step 5: The Image is verified;
            ReadDataBlock(target.ImageVerify(Client), reply);
            // Step 6: Before activation, the Image is checked;

            //Get list to images to activate.
            ReadDataBlock(Client.Read(target, 7), reply);
            Client.UpdateValue(target, 7, reply.Value);
            bool bFound = false;

            foreach (GXDLMSImageActivateInfo it in target.ImageActivateInfo)
            {
                if (GXCommon.EqualBytes(it.Identification, identification))
                {
                    bFound = true;
                    break;
                }
            }

            //Read image transfer status.
            ReadDataBlock(Client.Read(target, 6), reply);
            Client.UpdateValue(target, 6, reply.Value);
            if (target.ImageTransferStatus != Gurux.DLMS.Objects.Enums.ImageTransferStatus.VerificationSuccessful)
            {
                throw new Exception("Image transfer status is " + target.ImageTransferStatus.ToString());
            }

            if (!bFound)
            {
                throw new Exception("Image not found.");
            }

            //Step 7: Activate image.
            ReadDataBlock(target.ImageActivate(Client), reply);
        }
Esempio n. 29
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            GXByteBuffer bb;

            switch (e.Index)
            {
            case 1:
                return(GXCommon.LogicalNameToBytes(LogicalName));

            case 2:
                if (string.IsNullOrEmpty(Operator))
                {
                    return(null);
                }
                return(ASCIIEncoding.ASCII.GetBytes(Operator));

            case 3:
                return(Status);

            case 4:
                return(CircuitSwitchStatus);

            case 5:
                return(PacketSwitchStatus);

            case 6:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Structure);
                if (Version == 0)
                {
                    bb.SetUInt8(4);
                    GXCommon.SetData(settings, bb, DataType.UInt16, CellInfo.CellId);
                }
                else
                {
                    bb.SetUInt8(7);
                    GXCommon.SetData(settings, bb, DataType.UInt32, CellInfo.CellId);
                }
                GXCommon.SetData(settings, bb, DataType.UInt16, CellInfo.LocationId);
                GXCommon.SetData(settings, bb, DataType.UInt8, CellInfo.SignalQuality);
                GXCommon.SetData(settings, bb, DataType.UInt8, CellInfo.Ber);
                if (Version > 0)
                {
                    GXCommon.SetData(settings, bb, DataType.UInt16, CellInfo.MobileCountryCode);
                    GXCommon.SetData(settings, bb, DataType.UInt16, CellInfo.MobileNetworkCode);
                    GXCommon.SetData(settings, bb, DataType.UInt32, CellInfo.ChannelNumber);
                }
                return(bb.Array());

            case 7:
                bb = new GXByteBuffer();
                bb.SetUInt8(DataType.Array);
                if (AdjacentCells == null)
                {
                    bb.SetUInt8(0);
                }
                else
                {
                    bb.SetUInt8((byte)AdjacentCells.Count);
                }
                foreach (AdjacentCell it in AdjacentCells)
                {
                    bb.SetUInt8(DataType.Structure);
                    bb.SetUInt8(2);
                    GXCommon.SetData(settings, bb, Version == 0 ? DataType.UInt16 : DataType.UInt32, it.CellId);
                    GXCommon.SetData(settings, bb, DataType.UInt8, it.SignalQuality);
                }
                return(bb.Array());

            case 8:
                return(CaptureTime);
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return(null);
        }
Esempio n. 30
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)Convert.ToByte(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:
                if (e.Value is GXDateTime)
                {
                    UnitChargeActivationTime = (GXDateTime)e.Value;
                }
                else if (e.Value is byte[])
                {
                    UnitChargeActivationTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings != null && settings.UseUtc2NormalTime);
                }
                else if (e.Value is string)
                {
                    UnitChargeActivationTime = new GXDateTime((string)e.Value);
                }
                else
                {
                    UnitChargeActivationTime = null;
                }
                break;

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

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

            case 10:
                if (e.Value is GXDateTime)
                {
                    LastCollectionTime = (GXDateTime)e.Value;
                }
                else if (e.Value is DateTime)
                {
                    LastCollectionTime = (DateTime)e.Value;
                }
                else if (e.Value is byte[])
                {
                    LastCollectionTime = (GXDateTime)GXDLMSClient.ChangeType((byte[])e.Value, DataType.DateTime, settings != null && settings.UseUtc2NormalTime);
                }
                else if (e.Value is string)
                {
                    LastCollectionTime = new GXDateTime(e.Value as string);
                }
                else
                {
                    LastCollectionTime = null;
                }
                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;
            }
        }