SetUInt8() private method

Push the given enumeration value as byte into this buffer at the current position, and then increments the position.
private SetUInt8 ( Enum value ) : void
value System.Enum The value to be added.
return void
Esempio n. 1
0
        /// <summary>
        /// Generate write reply.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="results"></param>
        /// <param name="replyData"></param>
        internal static void GenerateWriteResponse(GXDLMSSettings settings, GXByteBuffer results, GXByteBuffer replyData)
        {
            GXByteBuffer bb = new GXByteBuffer((UInt16)(2 * results.Size));
            byte         ret;

            for (int pos = 0; pos != results.Size; ++pos)
            {
                ret = results.GetUInt8(pos);
                // If meter returns error.
                if (ret != 0)
                {
                    bb.SetUInt8(1);
                }
                bb.SetUInt8(ret);
            }
            GXDLMSSNParameters p = new GXDLMSSNParameters(settings, Command.WriteResponse, results.Size, 0xFF, null, bb);

            GXDLMS.GetSNPdu(p, replyData);
        }
Esempio n. 2
0
        public static void HandleGetRequest(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            //Return error if connection is not established.
            if (xml == null && settings.Connected == ConnectionState.None && !settings.CanAccess())
            {
                replyData.Set(GXDLMSServer.GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                                                                         ServiceError.Service, (byte)Service.Unsupported));
                return;
            }
            byte           invokeID = 0;
            GetCommandType type     = GetCommandType.NextDataBlock;

            //If GBT is used data is empty.
            if (data.Size != 0)
            {
                type = (GetCommandType)data.GetUInt8();
                // Get invoke ID and priority.
                invokeID = data.GetUInt8();
                if (xml != null)
                {
                    xml.AppendStartTag(Command.GetRequest);
                    xml.AppendStartTag(Command.GetRequest, type);
                    xml.AppendLine(TranslatorTags.InvokeId, "Value", xml.IntegerToHex(invokeID, 2));
                }
            }
            // GetRequest normal
            if (type == GetCommandType.Normal)
            {
                GetRequestNormal(settings, invokeID, server, data, replyData, xml);
            }
            else if (type == GetCommandType.NextDataBlock)
            {
                // Get request for next data block
                GetRequestNextDataBlock(settings, invokeID, server, data, replyData, xml, false);
            }
            else if (type == GetCommandType.WithList)
            {
                // Get request with a list.
                GetRequestWithList(settings, invokeID, server, data, replyData, xml);
            }
            else
            {
                Debug.WriteLine("HandleGetRequest failed. Invalid command type.");
                settings.ResetBlockIndex();
                GXByteBuffer bb = new GXByteBuffer();
                // Access Error : Device reports a hardware fault.
                bb.SetUInt8((byte)ErrorCode.HardwareFault);
                GXDLMS.GetLNPdu(new GXDLMSLNParameters(settings, invokeID, Command.GetResponse, (byte)type, null, bb, (byte)ErrorCode.Ok), replyData);
            }
            if (xml != null)
            {
                xml.AppendEndTag(Command.GetRequest, type);
                xml.AppendEndTag(Command.GetRequest);
            }
        }
Esempio n. 3
0
        ///<summary>
        ///Generates disconnect request.
        /// </summary>
        ///<returns>
        ///Disconnect request.
        ///</returns>
        private byte[][] GenerateDisconnectRequest()
        {
            GXByteBuffer buff;

            if (this.InterfaceType == InterfaceType.WRAPPER)
            {
                buff = new GXByteBuffer(2);
                buff.SetUInt8(0x63);
                buff.SetUInt8(0x0);
                return(GXDLMS.SplitToWrapperFrames(Settings, buff));
            }
            else
            {
                buff = new GXByteBuffer(22);
                buff.SetUInt8(0x81); // FromatID
                buff.SetUInt8(0x80); // GroupID
                buff.SetUInt8(0);    // Length

                buff.SetUInt8(HDLCInfo.MaxInfoTX);
                buff.SetUInt8(GXCommon.GetSize(Limits.MaxInfoTX));
                buff.Add(Limits.MaxInfoTX);

                buff.SetUInt8(HDLCInfo.MaxInfoRX);
                buff.SetUInt8(GXCommon.GetSize(Limits.MaxInfoRX));
                buff.Add(Limits.MaxInfoRX);

                buff.SetUInt8(HDLCInfo.WindowSizeTX);
                buff.SetUInt8(GXCommon.GetSize(Limits.WindowSizeTX));
                buff.Add(Limits.WindowSizeTX);

                buff.SetUInt8(HDLCInfo.WindowSizeRX);
                buff.SetUInt8(GXCommon.GetSize(Limits.WindowSizeRX));
                buff.Add(Limits.WindowSizeRX);

                int len = buff.Position - 3;
                buff.SetUInt8(2, (byte)len); // Length.
            }
            return(GXDLMS.SplitToHdlcFrames(Settings, (byte)Command.Ua, buff));
        }
Esempio n. 4
0
        /// <summary>
        /// Generates data notification message.
        /// </summary>
        /// <param name="date">Date time. Set To Min or Max if not added</param>
        /// <param name="data">Notification body.</param>
        /// <returns>Generated data notification message(s).</returns>
        public byte[][] GetDataNotificationMessage(DateTime date, byte[] data)
        {
            GXByteBuffer buff = new GXByteBuffer();

            if (date == DateTime.MinValue || date == DateTime.MaxValue)
            {
                buff.SetUInt8(DataType.None);
            }
            else
            {
                GXCommon.SetData(buff, DataType.DateTime, date);
            }
            buff.Set(data);
            return(GXDLMS.SplitPdu(Settings, Command.DataNotification, 0, buff, ErrorCode.Ok, DateTime.MinValue)[0]);
        }
Esempio n. 5
0
        /// <summary>
        /// Generates data notification message.
        /// </summary>
        /// <param name="date">Date time. Set To Min or Max if not added</param>
        /// <param name="objects">List of objects and attribute indexes to notify.</param>
        /// <returns>Generated data notification message(s).</returns>
        public byte[][] GenerateDataNotificationMessage(DateTime date, List <KeyValuePair <GXDLMSObject, int> > objects)
        {
            if (objects == null)
            {
                throw new ArgumentNullException("objects");
            }
            GXByteBuffer buff = new GXByteBuffer();

            if (date == DateTime.MinValue || date == DateTime.MaxValue)
            {
                buff.SetUInt8(DataType.None);
            }
            else
            {
                GXCommon.SetData(buff, DataType.DateTime, date);
            }
            buff.SetUInt8(DataType.Array);
            GXCommon.SetObjectCount(objects.Count, buff);
            foreach (KeyValuePair <GXDLMSObject, int> it in objects)
            {
                AddData(it.Key, it.Value, buff);
            }
            return(GXDLMS.SplitPdu(Settings, Command.DataNotification, 0, buff, ErrorCode.Ok, DateTime.MinValue)[0]);
        }
Esempio n. 6
0
        private byte[] ReportError(Command cmd, ErrorCode error)
        {
            switch (cmd)
            {
            case Command.ReadRequest:
                cmd = Command.ReadResponse;
                break;

            case Command.WriteRequest:
                cmd = Command.WriteResponse;
                break;

            case Command.GetRequest:
                cmd = Command.GetResponse;
                break;

            case Command.SetRequest:
                cmd = Command.SetResponse;
                break;

            case Command.MethodRequest:
                cmd = Command.MethodResponse;
                break;

            default:
                //Return HW error and close connection..
                break;
            }
            if (Settings.UseLogicalNameReferencing)
            {
                GXDLMS.GetLNPdu(new GXDLMSLNParameters(Settings, 0, cmd, 1, null, null, (byte)error), replyData);
            }
            else
            {
                GXByteBuffer bb = new GXByteBuffer();
                bb.SetUInt8(error);
                GXDLMSSNParameters p = new GXDLMSSNParameters(Settings, cmd, 1, (byte)error, null, bb);
                GXDLMS.GetSNPdu(p, replyData);
            }
            if (this.InterfaceType == Enums.InterfaceType.WRAPPER)
            {
                return(GXDLMS.GetWrapperFrame(Settings, replyData));
            }
            else
            {
                return(GXDLMS.GetHdlcFrame(Settings, 0, replyData));
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Generates push setup message.
        /// </summary>
        /// <param name="date"> Date time. Set To Min or Max if not added.</param>
        /// <param name="push">Target Push object.</param>
        /// <returns>Generated data notification message(s).</returns>
        public byte[][] GeneratePushSetupMessages(DateTime date, GXDLMSPushSetup push)
        {
            if (push == null)
            {
                throw new ArgumentNullException("push");
            }
            GXByteBuffer buff = new GXByteBuffer();

            buff.SetUInt8((byte)DataType.Structure);
            GXCommon.SetObjectCount(push.PushObjectList.Count, buff);
            foreach (KeyValuePair <GXDLMSObject, GXDLMSCaptureObject> it in push.PushObjectList)
            {
                AddData(it.Key, it.Value.AttributeIndex, buff);
            }
            return(GenerateDataNotificationMessages(date, buff));
        }
        /// <summary>
        /// Sends Event Notification Request.
        /// </summary>
        /// <param name="time">Send time.</param>
        /// <param name="item">COSEM object and attribute index to report.</param>
        /// <returns>Report request as byte array.</returns>
        public byte[][] GenerateEventNotification(DateTime time, KeyValuePair <GXDLMSObject, int> item)
        {
            GXByteBuffer buff = new GXByteBuffer();

            byte[][] reply;
            if (UseLogicalNameReferencing)
            {
                buff.SetUInt16((ushort)item.Key.ObjectType);
                buff.Set(GXCommon.LogicalNameToBytes(item.Key.LogicalName));
                buff.SetUInt8((byte)item.Value);
                AddData(item.Key, item.Value, buff);
                GXDLMSLNParameters p = new GXDLMSLNParameters(null, Settings, 0, Command.EventNotification, 0, null, buff, 0xff, Command.None);
                p.time = time;
                reply  = GXDLMS.GetLnMessages(p);
            }
            else
            {
                throw new Exception("Use GenerateInformationReport when Short Name referencing is used.");
            }
            return(reply);
        }
Esempio n. 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="p"></param>
        /// <param name="reply"></param>
        internal static void GetSNPdu(GXDLMSSNParameters p, GXByteBuffer reply)
        {
            bool ciphering = p.settings.Cipher != null && p.settings.Cipher.Security != Gurux.DLMS.Enums.Security.None;
            if (!ciphering && p.settings.InterfaceType == InterfaceType.HDLC)
            {
                if (p.settings.IsServer)
                {
                    reply.Set(GXCommon.LLCReplyBytes);
                }
                else if (reply.Size == 0)
                {
                    reply.Set(GXCommon.LLCSendBytes);
                }
            }
            int cnt = 0, cipherSize = 0;
            if (ciphering)
            {
                cipherSize = CipheringHeaderSize;
                /*
                if (p.settings.Cipher.Security == Security.Encryption)
                {
                    cipherSize = 7;
                }
                else if (p.settings.Cipher.Security == Security.Authentication)
                {
                    cipherSize = 19;
                }
                else if (p.settings.Cipher.Security == Security.AuthenticationEncryption)
                {
                    cipherSize = 7;
                }
                 * */
            }
            if (p.data != null)
            {
                cnt = p.data.Size - p.data.Position;
            }
            // Add command.
            if (p.command != Command.Aarq && p.command != Command.Aare)
            {
                reply.SetUInt8((byte)p.command);
                if (p.count != 0xFF)
                {
                    GXCommon.SetObjectCount(p.count, reply);
                }
                if (p.requestType != 0xFF)
                {
                    reply.SetUInt8(p.requestType);
                }
                reply.Set(p.attributeDescriptor);

                if (!p.multipleBlocks)
                {
                    p.multipleBlocks = reply.Size + cipherSize + cnt > p.settings.MaxPduSize;
                    //If reply data is not fit to one PDU.
                    if (p.multipleBlocks)
                    {
                        //Remove command.
                        GXByteBuffer tmp = new GXByteBuffer();
                        int offset = 1;
                        if (!ciphering && p.settings.InterfaceType == InterfaceType.HDLC)
                        {
                            offset = 4;
                        }
                        tmp.Set(reply.Data, offset, reply.Size - offset);
                        reply.Size = 0;
                        if (!ciphering && p.settings.InterfaceType == InterfaceType.HDLC)
                        {
                            if (p.settings.IsServer)
                            {
                                reply.Set(GXCommon.LLCReplyBytes);
                            }
                            else if (reply.Size == 0)
                            {
                                reply.Set(GXCommon.LLCSendBytes);
                            }
                        }
                        if (p.command == Command.WriteRequest)
                        {
                            p.requestType = (byte)VariableAccessSpecification.WriteDataBlockAccess;
                        }
                        else if (p.command == Command.ReadRequest)
                        {
                            p.requestType = (byte)VariableAccessSpecification.ReadDataBlockAccess;
                        }
                        else if (p.command == Command.ReadResponse)
                        {
                            p.requestType = (byte)SingleReadResponse.DataBlockResult;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid command.");
                        }
                        reply.SetUInt8((byte)p.command);
                        //Set object count.
                        reply.SetUInt8(1);
                        if (p.requestType != 0xFF)
                        {
                            reply.SetUInt8(p.requestType);
                        }
                        cnt = GXDLMS.AppendMultipleSNBlocks(p, tmp, reply);
                    }
                }
                else
                {
                    cnt = GXDLMS.AppendMultipleSNBlocks(p, null, reply);
                }
            }
            // Add data.
            reply.Set(p.data, cnt);
            //Af all data is transfered.
            if (p.data != null && p.data.Position == p.data.Size)
            {
                p.settings.Index = p.settings.Count = 0;
            }
            // If Ciphering is used.
            if (ciphering && p.command != Command.Aarq && p.command != Command.Aare)
            {
                byte[] tmp = p.settings.Cipher.Encrypt((byte)GetGloMessage(p.command), p.settings.Cipher.SystemTitle, reply.Array());
                System.Diagnostics.Debug.Assert(!(p.settings.MaxPduSize < tmp.Length));
                reply.Size = 0;
                if (p.settings.InterfaceType == InterfaceType.HDLC)
                {
                    if (p.settings.IsServer)
                    {
                        reply.Set(GXCommon.LLCReplyBytes);
                    }
                    else if (reply.Size == 0)
                    {
                        reply.Set(GXCommon.LLCSendBytes);
                    }
                }
                reply.Set(tmp);
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Convert HDLC address to bytes.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="size">Address size in bytes.</param>
 /// <returns></returns>
 private static byte[] GetHdlcAddressBytes(int value, byte size)
 {
     Object tmp = GetHhlcAddress(value, size);
     GXByteBuffer bb = new GXByteBuffer();
     if (tmp is byte)
     {
         bb.SetUInt8((byte)tmp);
     }
     else if (tmp is UInt16)
     {
         bb.SetUInt16((UInt16)tmp);
     }
     else if (tmp is UInt32)
     {
         bb.SetUInt32((UInt32)tmp);
     }
     else
     {
         throw new ArgumentException("Invalid address type.");
     }
     return bb.Array();
 }
Esempio n. 11
0
 /// <summary>
 /// Generates data notification message.
 /// </summary>
 /// <param name="time">Date time. Set To Min or Max if not added</param>
 /// <param name="objects">List of objects and attribute indexes to notify.</param>
 /// <returns>Generated data notification message(s).</returns>
 public byte[][] GenerateDataNotificationMessages(DateTime time, List<KeyValuePair<GXDLMSObject, int>> objects)
 {
     if (objects == null)
     {
         throw new ArgumentNullException("objects");
     }
     GXByteBuffer buff = new GXByteBuffer();
     buff.SetUInt8(DataType.Structure);
     GXCommon.SetObjectCount(objects.Count, buff);
     foreach (KeyValuePair<GXDLMSObject, int> it in objects)
     {
         AddData(it.Key, it.Value, buff);
     }
     byte[][] reply;
     if (UseLogicalNameReferencing)
     {
         GXDLMSLNParameters p = new GXDLMSLNParameters(Settings, Command.DataNotification, 0, null, buff, 0xff);
         p.time = time;
         reply = GXDLMS.GetLnMessages(p);
     }
     else
     {
         GXDLMSSNParameters p = new GXDLMSSNParameters(Settings, Command.DataNotification, 1, 0, buff, null);
         reply = GXDLMS.GetSnMessages(p);
     }
     return reply;
 }
Esempio n. 12
0
 /// <summary>
 /// Removes X.509 v3 certificate from the server using serial number.
 /// </summary>
 /// <param name="client">DLMS client that is used to generate action.</param>
 /// <param name="serialNumber">Serial number.</param>
 /// <param name="issuer">Issuer.</param>
 /// <returns>Generated action.</returns>
 public byte[][] RemoveCertificateBySerial(GXDLMSClient client, byte[] serialNumber, byte[] issuer)
 {
     GXByteBuffer bb = new GXByteBuffer();
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(2);
     //Add enum
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(1);
     //Add certificate_identification_by_entity
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(2);
     //serialNumber
     GXCommon.SetData(client.Settings, bb, DataType.OctetString, serialNumber);
     //issuer
     GXCommon.SetData(client.Settings, bb, DataType.OctetString, issuer);
     return client.Method(this, 8, bb.Array(), DataType.OctetString);
 }
Esempio n. 13
0
 /// <summary>
 /// Agree on one or more symmetric keys using the key agreement algorithm.
 /// </summary>
 /// <param name="client"> DLMS client that is used to generate action.</param>
 /// <param name="list"> List of keys.</param>
 /// <returns>Generated action.</returns>
 public byte[][] keyAgreement(GXDLMSClient client, List<KeyValuePair<GlobalKeyType, byte[]>> list)
 {
     if (list == null || list.Count == 0)
     {
         throw new ArgumentException("Invalid list. It is empty.");
     }
     GXByteBuffer bb = new GXByteBuffer();
     bb.SetUInt8(DataType.Array);
     bb.SetUInt8((byte)list.Count);
     foreach (KeyValuePair<GlobalKeyType, byte[]> it in list)
     {
         bb.SetUInt8(DataType.Structure);
         bb.SetUInt8(2);
         GXCommon.SetData(client.Settings, bb, DataType.Enum, it.Key);
         GXCommon.SetData(client.Settings, bb, DataType.OctetString, it.Value);
     }
     return client.Method(this, 3, bb.Array(), DataType.Array);
 }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return (byte)Mode;
     }
     if (e.Index == 3)
     {
         return (byte)Speed;
     }
     if (e.Index == 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);
             }
         }
         return data.Array();
     }
     if (e.Index == 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.UInt8);
                 data.SetUInt8((byte)it);
             }
         }
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 15
0
        ///<summary>
        /// Handle write request.
        ///</summary>
        public static void HandleWriteRequest(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data,
                                              GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            //Return error if connection is not established.
            if (xml == null && !settings.Connected)
            {
                replyData.Add(GXDLMSServer.GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                                                                         ServiceError.Service, (byte)Service.Unsupported));
                return;
            }
            short  type;
            object value;
            // Get object count.
            List <GXSNInfo> targets = new List <GXSNInfo>();
            int             cnt     = GXCommon.GetObjectCount(data);

            if (xml != null)
            {
                xml.AppendStartTag(Command.WriteRequest);
                xml.AppendStartTag(
                    TranslatorTags.ListOfVariableAccessSpecification, "Qty",
                    xml.IntegerToHex(cnt, 2));
                if (xml.OutputType == TranslatorOutputType.StandardXml)
                {
                    xml.AppendStartTag(
                        TranslatorTags.VariableAccessSpecification);
                }
            }
            GXByteBuffer results = new GXByteBuffer((ushort)cnt);

            for (int pos = 0; pos != cnt; ++pos)
            {
                type = data.GetUInt8();
                if (type == (byte)VariableAccessSpecification.VariableName)
                {
                    int sn = data.GetUInt16();
                    if (xml != null)
                    {
                        xml.AppendLine(
                            (int)Command.WriteRequest << 8
                                | (int)VariableAccessSpecification.VariableName,
                                "Value", xml.IntegerToHex(sn, 4));
                    }
                    else
                    {
                        GXSNInfo info = FindSNObject(server, sn);
                        targets.Add(info);
                        // If target is unknown.
                        if (info == null)
                        {
                            // Device reports a undefined object.
                            results.SetUInt8(ErrorCode.UndefinedObject);
                        }
                        else
                        {
                            results.SetUInt8(ErrorCode.Ok);
                        }
                    }
                }
                else if (type == (byte)VariableAccessSpecification.WriteDataBlockAccess)
                {
                    HandleReadDataBlockAccess(settings, server, Command.WriteResponse, data, cnt, replyData, xml);
                    if (xml == null)
                    {
                        return;
                    }
                }
                else
                {
                    // Device reports a HW error.
                    results.SetUInt8(ErrorCode.HardwareFault);
                }
            }

            if (xml != null)
            {
                if (xml.OutputType == TranslatorOutputType.StandardXml)
                {
                    xml.AppendEndTag(TranslatorTags.VariableAccessSpecification);
                }
                xml.AppendEndTag(
                    TranslatorTags.ListOfVariableAccessSpecification);
            }
            // Get data count.
            cnt = GXCommon.GetObjectCount(data);
            GXDataInfo di = new GXDataInfo();

            di.xml = xml;
            if (xml != null)
            {
                xml.AppendStartTag(TranslatorTags.ListOfData, "Qty", xml.IntegerToHex(cnt, 2));
            }
            for (int pos = 0; pos != cnt; ++pos)
            {
                di.Clear();
                if (xml != null)
                {
                    if (xml.OutputType == TranslatorOutputType.StandardXml)
                    {
                        xml.AppendStartTag(Command.WriteRequest,
                                           SingleReadResponse.Data);
                    }
                    value = GXCommon.GetData(settings, data, di);
                    if (!di.Complete)
                    {
                        value = GXCommon.ToHex(data.Data, false,
                                               data.Position, data.Size - data.Position);
                        xml.AppendLine(
                            GXDLMS.DATA_TYPE_OFFSET + (int)di.Type,
                            "Value", value.ToString());
                    }
                    if (xml.OutputType == TranslatorOutputType.StandardXml)
                    {
                        xml.AppendEndTag(Command.WriteRequest, SingleReadResponse.Data);
                    }
                    GXCommon.GetData(settings, data, di);
                }
                else if (results.GetUInt8(pos) == 0)
                {
                    // If object has found.
                    GXSNInfo target = targets[pos];
                    value = GXCommon.GetData(settings, data, di);
                    if (value is byte[])
                    {
                        DataType dt = target.Item.GetDataType(target.Index);
                        if (dt != DataType.None && dt != DataType.OctetString)
                        {
                            value = GXDLMSClient.ChangeType((byte[])value, dt, settings.UseUtc2NormalTime);
                        }
                    }
                    ValueEventArgs e  = new ValueEventArgs(server, target.Item, target.Index, 0, null);
                    AccessMode     am = server.NotifyGetAttributeAccess(e);
                    // If write is denied.
                    if (am != AccessMode.Write && am != AccessMode.ReadWrite)
                    {
                        results.SetUInt8((byte)pos, (byte)ErrorCode.ReadWriteDenied);
                    }
                    else
                    {
                        e.Value = value;
                        server.NotifyWrite(new ValueEventArgs[] { e });
                        if (e.Error != 0)
                        {
                            results.SetUInt8((byte)pos, (byte)e.Error);
                        }
                        else if (!e.Handled)
                        {
                            (target.Item as IGXDLMSBase).SetValue(settings, e);
                            server.NotifyPostWrite(new ValueEventArgs[] { e });
                        }
                    }
                }
            }
            if (xml != null)
            {
                xml.AppendEndTag(TranslatorTags.ListOfData);
                xml.AppendEndTag(Command.WriteRequest);
                return;
            }
            GenerateWriteResponse(settings, results, replyData);
        }
Esempio n. 16
0
        private byte[][] HandleGetRequest()
        {
            ErrorCode    error = ErrorCode.Ok;
            GXByteBuffer data  = Reply.Data;
            GXByteBuffer bb    = new GXByteBuffer();
            short        type;
            int          index      = 0;
            object       parameters = null;

            // Get type.
            type = data.GetUInt8();
            // Get invoke ID and priority.
            data.GetUInt8();
            // GetRequest normal
            if (type == 1)
            {
                Settings.ResetBlockIndex();
                ServerReply.Index = 0;
                parameters        = null;
                // CI
                ObjectType ci = (ObjectType)data.GetUInt16();
                byte[]     ln = new byte[6];
                data.Get(ln);
                // Attribute Id
                int          attributeIndex = data.GetUInt8();
                GXDLMSObject obj            = Settings.Objects.FindByLN(ci, GXDLMSObject.ToLogicalName(ln));
                if (obj == null)
                {
                    obj = FindObject(ci, 0, GXDLMSObject.ToLogicalName(ln));
                }
                if (obj == null)
                {
                    // "Access Error : Device reports a undefined object."
                    error = ErrorCode.UndefinedObject;
                }
                else
                {
                    // AccessSelection
                    int selection = data.GetUInt8();
                    int selector  = 0;
                    if (selection != 0)
                    {
                        selector = data.GetUInt8();
                        GXDataInfo info = new GXDataInfo();
                        parameters = GXCommon.GetData(data, info);
                    }

                    ValueEventArgs e = new ValueEventArgs(obj, attributeIndex, 0, parameters);
                    Read(e);
                    object value;
                    if (e.Handled)
                    {
                        value = e.Value;
                    }
                    else
                    {
                        value = (obj as IGXDLMSBase).GetValue(Settings, attributeIndex, selector, parameters);
                    }
                    GXDLMS.AppedData(obj, attributeIndex, bb, value);
                }
                ServerReply.ReplyMessages = GXDLMS.SplitPdu(Settings, Command.GetResponse, 1, bb, error, DateTime.MinValue);
            }
            else if (type == 2)
            {
                // Get request for next data block
                // Get block index.
                index = (int)data.GetUInt32();
                if (index != Settings.BlockIndex + 1)
                {
                    Debug.WriteLine("handleGetRequest failed. Invalid block number. " + Settings.BlockIndex + "/" + index);
                    ServerReply.ReplyMessages = GXDLMS.SplitPdu(Settings, Command.GetResponse, 1, bb,
                                                                ErrorCode.DataBlockNumberInvalid, DateTime.MinValue);
                    index             = 0;
                    ServerReply.Index = index;
                }
                else
                {
                    Settings.IncreaseBlockIndex();
                    index             = ServerReply.Index + 1;
                    ServerReply.Index = index;
                }
            }
            else if (type == 3)
            {
                // Get request with a list.
                int cnt = GXCommon.GetObjectCount(data);
                GXCommon.SetObjectCount(cnt, bb);
                for (int pos = 0; pos != cnt; ++pos)
                {
                    ObjectType ci = (ObjectType)data.GetUInt16();
                    byte[]     ln = new byte[6];
                    data.Get(ln);
                    short attributeIndex = data.GetUInt8();

                    GXDLMSObject obj = Settings.Objects.FindByLN(ci, GXDLMSObject.ToLogicalName(ln));
                    if (obj == null)
                    {
                        obj = FindObject(ci, 0, GXDLMSObject.ToLogicalName(ln));
                    }
                    if (obj == null)
                    {
                        // "Access Error : Device reports a undefined object."
                        error = ErrorCode.UndefinedObject;
                    }
                    else
                    {
                        // AccessSelection
                        int selection = data.GetUInt8();
                        int selector  = 0;
                        if (selection != 0)
                        {
                            selector = data.GetUInt8();
                            GXDataInfo info = new GXDataInfo();
                            parameters = GXCommon.GetData(data, info);
                        }
                        try
                        {
                            ValueEventArgs e = new ValueEventArgs(obj, attributeIndex, 0, parameters);
                            Read(e);
                            object value;
                            if (e.Handled)
                            {
                                value = e.Value;
                            }
                            else
                            {
                                value = (obj as IGXDLMSBase).GetValue(Settings, attributeIndex, selector, parameters);
                            }
                            bb.SetUInt8(ErrorCode.Ok);
                            GXDLMS.AppedData(obj, attributeIndex, bb, value);
                        }
                        catch (Exception)
                        {
                            bb.SetUInt8(1);
                            bb.SetUInt8(ErrorCode.HardwareFault);
                        }
                    }
                }
                ServerReply.ReplyMessages = GXDLMS.SplitPdu(Settings, Command.GetResponse, 3, bb, error, DateTime.MinValue);
            }
            else
            {
                Debug.WriteLine("handleGetRequest failed. Invalid command type.");
                Settings.ResetBlockIndex();
                // Access Error : Device reports a hardware fault.
                ServerReply.ReplyMessages = GXDLMS.SplitPdu(Settings, Command.GetResponse, 1, bb, ErrorCode.HardwareFault, DateTime.MinValue);
            }
            ServerReply.Index = index;
            return(ServerReply.ReplyMessages[index]);
        }
        ///<summary>
        /// Handle action request.
        ///</summary>
        ///<param name="Reply">
        /// Received data from the client.
        ///</param>
        ///<returns>
        ///Reply.
        ///</returns>
        public static void HandleMethodRequest(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXDLMSConnectionEventArgs connectionInfo, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            ErrorCode error = ErrorCode.Ok;
            GXByteBuffer bb = new GXByteBuffer();
            // Get type.
            ActionRequestType type = (ActionRequestType)data.GetUInt8();
            // Get invoke ID and priority.
            byte invokeId = data.GetUInt8();
            // CI
            ObjectType ci = (ObjectType)data.GetUInt16();
            byte[] ln = new byte[6];
            data.Get(ln);
            // Attribute Id
            byte id = data.GetUInt8();
            // Get parameters.
            object parameters = null;
            byte selection = data.GetUInt8();
            if (xml != null)
            {
                xml.AppendStartTag(Command.MethodRequest);
                if (type == ActionRequestType.Normal)
                {
                    xml.AppendStartTag(Command.MethodRequest, ActionRequestType.Normal);
                    xml.AppendLine(TranslatorTags.InvokeId, "Value", xml.IntegerToHex(invokeId, 2));
                    AppendMethodDescriptor(xml, (int)ci, ln, id);
                    if (selection != 0)
                    {
                        //MethodInvocationParameters
                        xml.AppendStartTag(TranslatorTags.MethodInvocationParameters);
                        GXDataInfo di = new GXDataInfo();
                        di.xml = xml;
                        GXCommon.GetData(settings, data, di);
                        xml.AppendEndTag(TranslatorTags.MethodInvocationParameters);
                    }
                    xml.AppendEndTag(Command.MethodRequest, ActionRequestType.Normal);
                }
                xml.AppendEndTag(Command.MethodRequest);
                return;
            }
            if (selection != 0)
            {
                GXDataInfo info = new GXDataInfo();
                parameters = GXCommon.GetData(settings, data, info);
            }

            GXDLMSObject obj = settings.Objects.FindByLN(ci, GXDLMSObject.ToLogicalName(ln));
            if (!settings.Connected && (ci != ObjectType.AssociationLogicalName || id != 1))
            {
                replyData.Set(GXDLMSServer.GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                              ServiceError.Service, (byte)Service.Unsupported));
                return;
            }

            if (obj == null)
            {
                obj = server.NotifyFindObject(ci, 0, GXDLMSObject.ToLogicalName(ln));
            }
            if (obj == null)
            {
                // Device reports a undefined object.
                error = ErrorCode.UndefinedObject;
            }
            else
            {
                if (obj.GetMethodAccess(id) == MethodAccessMode.NoAccess)
                {
                    error = ErrorCode.ReadWriteDenied;
                }
                else
                {
                    ValueEventArgs e = new ValueEventArgs(settings, obj, id, 0, parameters);
                    server.NotifyAction(new ValueEventArgs[] { e });
                    byte[] actionReply;
                    if (e.Handled)
                    {
                        actionReply = (byte[])e.Value;
                    }
                    else
                    {
                        actionReply = (obj as IGXDLMSBase).Invoke(settings, e);
                    }
                    //Set default action reply if not given.
                    if (actionReply != null && e.Error == 0)
                    {
                        //Add return parameters
                        bb.SetUInt8(1);
                        //Add parameters error code.
                        bb.SetUInt8(0);
                        GXCommon.SetData(settings, bb, GXCommon.GetValueType(actionReply), actionReply);
                    }
                    else
                    {
                        error = e.Error;
                        //Add return parameters
                        bb.SetUInt8(0);
                    }
                }
            }

            GXDLMSLNParameters p = new GXDLMSLNParameters(settings, Command.MethodResponse, 1, null, bb, (byte)error);
            GXDLMS.GetLNPdu(p, replyData);
            //If High level authentication fails.
            if (!settings.Connected && obj is GXDLMSAssociationLogicalName && id == 1)
            {
                server.NotifyInvalidConnection(connectionInfo);
            }
        }
Esempio n. 18
0
        ///<summary>
        ///Parse SNRM Request. If server do not accept client empty byte array is returned.
        /// </summary>
        ///<returns>
        ///Returns returned UA packet.
        ///</returns>
        private byte[][] HandleSnrmRequest()
        {
            GXByteBuffer bb = new GXByteBuffer(25);

            bb.SetUInt8(0x81); // FromatID
            bb.SetUInt8(0x80); // GroupID
            bb.SetUInt8(0);    // Length
            bb.SetUInt8(HDLCInfo.MaxInfoTX);
            bb.SetUInt8(GXCommon.GetSize(Limits.MaxInfoTX));
            bb.Add(Limits.MaxInfoTX);
            bb.SetUInt8(HDLCInfo.MaxInfoRX);
            bb.SetUInt8(GXCommon.GetSize(Limits.MaxInfoRX));
            bb.Add(Limits.MaxInfoRX);
            bb.SetUInt8(HDLCInfo.WindowSizeTX);
            bb.SetUInt8(GXCommon.GetSize(Limits.WindowSizeTX));
            bb.Add(Limits.WindowSizeTX);
            bb.SetUInt8(HDLCInfo.WindowSizeRX);
            bb.SetUInt8(GXCommon.GetSize(Limits.WindowSizeRX));
            bb.Add(Limits.WindowSizeRX);
            bb.SetUInt8(2, (byte)(bb.Size - 3));
            return(GXDLMS.SplitToHdlcFrames(Settings, (byte)Command.Ua, bb));
        }
Esempio n. 19
0
        ///<summary>
        /// Handle write request.
        ///</summary>
        ///<param name="Reply">
        /// Received data from the client.
        /// </param>
        ///<returns>
        /// Reply.
        ///</returns>
        private byte[][] HandleWriteRequest()
        {
            GXByteBuffer data = Reply.Data;
            short        type;
            object       value;
            // Get object count.
            IList <GXSNInfo> targets = new List <GXSNInfo>();
            int          cnt         = GXCommon.GetObjectCount(data);
            GXByteBuffer results     = new GXByteBuffer((ushort)cnt);

            for (int pos = 0; pos != cnt; ++pos)
            {
                type = data.GetUInt8();
                if (type == 2)
                {
                    int      sn   = data.GetUInt16();
                    GXSNInfo info = FindSNObject(sn);
                    targets.Add(info);
                    // If target is unknown.
                    if (info == null)
                    {
                        // Device reports a undefined object.
                        results.SetUInt8(ErrorCode.UndefinedObject);
                    }
                    else
                    {
                        results.SetUInt8(ErrorCode.Ok);
                    }
                }
                else
                {
                    // Device reports a HW error.
                    results.SetUInt8(ErrorCode.HardwareFault);
                }
            }
            // Get data count.
            cnt = GXCommon.GetObjectCount(data);
            GXDataInfo di = new GXDataInfo();

            for (int pos = 0; pos != cnt; ++pos)
            {
                if (results.GetUInt8(pos) == 0)
                {
                    // If object has found.
                    GXSNInfo target = targets[pos];
                    value = GXCommon.GetData(data, di);
                    if (value is byte[])
                    {
                        DataType dt = target.Item.GetDataType(target.Index);
                        if (dt != DataType.None && dt != DataType.OctetString)
                        {
                            value = GXDLMSClient.ChangeType((byte[])value, dt);
                        }
                    }
                    di.Clear();
                    AccessMode am = target.Item.GetAccess(target.Index);
                    // If write is denied.
                    if (am != AccessMode.Write && am != AccessMode.ReadWrite)
                    {
                        results.SetUInt8((byte)pos, (byte)ErrorCode.ReadWriteDenied);
                    }
                    else
                    {
                        ValueEventArgs e = new ValueEventArgs(target.Item, target.Index, 0, null);
                        e.Value = value;
                        Write(e);
                        if (!e.Handled)
                        {
                            (target.Item as IGXDLMSBase).SetValue(Settings, target.Index, value);
                        }
                    }
                }
            }
            GXByteBuffer bb = new GXByteBuffer((UInt16)(2 * cnt + 2));

            GXCommon.SetObjectCount(cnt, bb);
            byte ret;

            for (int pos = 0; pos != cnt; ++pos)
            {
                ret = results.GetUInt8(pos);
                // If meter returns error.
                if (ret != 0)
                {
                    bb.SetUInt8(1);
                }
                bb.SetUInt8(ret);
            }
            return(GXDLMS.SplitPdu(Settings, Command.WriteResponse, 1, bb, ErrorCode.Ok, DateTime.MinValue)[0]);
        }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8(DataType.Structure);
         bb.SetUInt8(3);
         GXCommon.SetData(settings, bb, DataType.OctetString, SystemTitle);
         GXCommon.SetData(settings, bb, DataType.UInt16, MacAddress);
         GXCommon.SetData(settings, bb, DataType.UInt8, LSapSelector);
         return bb.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 21
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                return this.LogicalName;
            }
            if (e.Index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                //LN
                if (Target != null)
                {
                    GXCommon.SetData(settings, data, DataType.OctetString, Target.LogicalName);
                }
                else
                {
#pragma warning disable CS0618
                    GXCommon.SetData(settings, data, DataType.OctetString, ExecutedScriptLogicalName);
#pragma warning restore CS0618
                }
                GXCommon.SetData(settings, data, DataType.UInt16, ExecutedScriptSelector);
                return data.Array();
            }
            if (e.Index == 3)
            {
                return this.Type;
            }
            if (e.Index == 4)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (ExecutionTime == null)
                {
                    GXCommon.SetObjectCount(0, data);
                }
                else
                {
                    GXCommon.SetObjectCount(ExecutionTime.Length, data);
                    foreach (GXDateTime it in ExecutionTime)
                    {
                        data.SetUInt8((byte)DataType.Structure);
                        //Count
                        data.SetUInt8((byte)2);
                        //Time
                        GXCommon.SetData(settings, data, DataType.OctetString, new GXTime(it));
                        //Date
                        GXCommon.SetData(settings, data, DataType.OctetString, new GXDate(it));
                    }
                }
                return data.Array();
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return null;
        }
Esempio n. 22
0
        ///
        ///<summary>Handle read request.
        /// </summary>
        ///<returns> Reply to the client. </returns>
        ///
        private byte[][] HandleReadRequest()
        {
            GXByteBuffer data = Reply.Data;
            short        type;
            object       value = null;
            GXByteBuffer bb    = new GXByteBuffer();
            int          cnt   = GXCommon.GetObjectCount(data);

            GXCommon.SetObjectCount(cnt, bb);
            GXSNInfo info;

            for (int pos = 0; pos != cnt; ++pos)
            {
                type = data.GetUInt8();
                // GetRequest normal
                if (type == 2)
                {
                    int sn = data.GetUInt16();
                    info = FindSNObject(sn);
                    if (!info.IsAction)
                    {
                        ValueEventArgs e = new ValueEventArgs(info.Item, info.Index, 0, null);
                        Read(e);
                        if (e.Handled)
                        {
                            value = e.Value;
                        }
                        else
                        {
                            value = (info.Item as IGXDLMSBase).GetValue(Settings, info.Index, 0, null);
                        }
                        // Set status.
                        bb.SetUInt8(0);
                        GXDLMS.AppedData(info.Item, info.Index, bb, value);
                    }
                    else
                    {
                        ValueEventArgs e = new ValueEventArgs(info.Item, info.Index, 0, null);
                        Action(e);
                        if (e.Handled)
                        {
                            value = e.Value;
                        }
                        else
                        {
                            value = ((IGXDLMSBase)info.Item).Invoke(Settings, info.Index, null);
                        }
                        // Set status.
                        bb.SetUInt8(0);
                        // Add value
                        bb.SetUInt8(GXCommon.GetValueType(value));
                        bb.Add(value);
                    }
                }
                else if (type == 2)
                {
                    // Get request for next data block
                    throw new System.ArgumentException("TODO: Invalid Command.");
                }
                else if (type == 4)
                {
                    // Parameterised access.
                    int        sn         = data.GetUInt16();
                    int        selector   = data.GetUInt8();
                    GXDataInfo di         = new GXDataInfo();
                    object     parameters = GXCommon.GetData(data, di);
                    info = FindSNObject(sn);
                    if (!info.IsAction)
                    {
                        ValueEventArgs e = new ValueEventArgs(info.Item, info.Index, 0, parameters);
                        Read(e);
                        if (e.Handled)
                        {
                            value = e.Value;
                        }
                        else
                        {
                            value = (info.Item as IGXDLMSBase).GetValue(Settings, info.Index, selector, parameters);
                        }
                        // Set status.
                        bb.SetUInt8(0);
                        GXDLMS.AppedData(info.Item, info.Index, bb, value);
                    }
                    else
                    {
                        ValueEventArgs e = new ValueEventArgs(info.Item, info.Index, 0, parameters);
                        e.Value = parameters;
                        Action(e);
                        if (e.Handled)
                        {
                            value = e.Value;
                        }
                        else
                        {
                            value = ((IGXDLMSBase)info.Item).Invoke(Settings, info.Index, parameters);
                        }
                        // Add value
                        bb.Add(value);
                    }
                }
                else
                {
                    throw new System.ArgumentException("Invalid Command.");
                }
            }
            return(GXDLMS.SplitPdu(Settings, Command.ReadResponse, 1, bb,
                                   ErrorCode.Ok, DateTime.MinValue)[0]);
        }
Esempio n. 23
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return Value;
     }
     if (e.Index == 3)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8(2);
         GXCommon.SetData(settings, data, DataType.Int8, scaler);
         GXCommon.SetData(settings, data, DataType.Enum, Unit);
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 24
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                return this.LogicalName;
            }
            else if (e.Index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(3);
                if (MonitoredValue == null)
                {
                    GXCommon.SetData(settings, data, DataType.Int16, 0);
                    GXCommon.SetData(settings, data, DataType.OctetString, "0.0.0.0.0.0");
                    GXCommon.SetData(settings, data, DataType.UInt8, 0);
                }
                else
                {
                    GXCommon.SetData(settings, data, DataType.Int16, MonitoredValue.ObjectType);
                    GXCommon.SetData(settings, data, DataType.OctetString, MonitoredValue.LogicalName);
                    GXCommon.SetData(settings, data, DataType.UInt8, MonitoredAttributeIndex);

                }
                return data.Array();
            }
            else if (e.Index == 3)
            {
                return ThresholdActive;
            }
            else if (e.Index == 4)
            {
                return ThresholdNormal;
            }
            else if (e.Index == 5)
            {
                return ThresholdEmergency;
            }
            else if (e.Index == 6)
            {
                return MinOverThresholdDuration;
            }
            else if (e.Index == 7)
            {
                return MinUnderThresholdDuration;
            }
            else if (e.Index == 8)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(3);
                GXCommon.SetData(settings, data, DataType.UInt16, EmergencyProfile.ID);
                GXCommon.SetData(settings, data, DataType.OctetString, EmergencyProfile.ActivationTime);
                GXCommon.SetData(settings, data, DataType.UInt32, EmergencyProfile.Duration);
                return data.Array();
            }
            else if (e.Index == 9)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                if (EmergencyProfileGroupIDs == null)
                {
                    data.SetUInt8(0);
                }
                else
                {
                    data.SetUInt8((byte)EmergencyProfileGroupIDs.Length);
                    foreach (object it in EmergencyProfileGroupIDs)
                    {
                        GXCommon.SetData(settings, data, DataType.UInt16, it);
                    }
                }

                return data.Array();
            }
            else if (e.Index == 10)
            {
                return EmergencyProfileActive;
            }
            else if (e.Index == 11)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                GXCommon.SetData(settings, data, DataType.OctetString, ActionOverThreshold.LogicalName);
                GXCommon.SetData(settings, data, DataType.UInt16, ActionOverThreshold.ScriptSelector);
                data.SetUInt8((byte)DataType.Structure);
                data.SetUInt8(2);
                GXCommon.SetData(settings, data, DataType.OctetString, ActionUnderThreshold.LogicalName);
                GXCommon.SetData(settings, data, DataType.UInt16, ActionUnderThreshold.ScriptSelector);
                return data.Array();
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return null;
        }
        public static void HandleGetRequest(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            //Return error if connection is not established.
            if (xml == null && !settings.Connected)
            {
                replyData.Set(GXDLMSServer.GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                              ServiceError.Service, (byte)Service.Unsupported));
                return;
            }

            GetCommandType type = (GetCommandType)data.GetUInt8();
            // Get invoke ID and priority.
            byte invokeID = data.GetUInt8();
            if (xml != null)
            {
                xml.AppendStartTag(Command.GetRequest);
                xml.AppendStartTag(Command.GetRequest, type);
                xml.AppendLine(TranslatorTags.InvokeId, "Value", xml.IntegerToHex(invokeID, 2));
            }

            // GetRequest normal
            if (type == GetCommandType.Normal)
            {
                GetRequestNormal(settings, server, data, replyData, xml);
            }
            else if (type == GetCommandType.NextDataBlock)
            {
                // Get request for next data block
                GetRequestNextDataBlock(settings, server, data, replyData, xml);
            }
            else if (type == GetCommandType.WithList)
            {
                // Get request with a list.
                GetRequestWithList(settings, server, data, replyData, xml);
            }
            else
            {
                Debug.WriteLine("HandleGetRequest failed. Invalid command type.");
                settings.ResetBlockIndex();
                GXByteBuffer bb = new GXByteBuffer();
                // Access Error : Device reports a hardware fault.
                bb.SetUInt8((byte)ErrorCode.HardwareFault);
                GXDLMS.GetLNPdu(new GXDLMSLNParameters(settings, Command.GetResponse, (byte)type, null, bb, (byte)ErrorCode.Ok), replyData);
            }
            if (xml != null)
            {
                xml.AppendEndTag(Command.GetRequest, type);
                xml.AppendEndTag(Command.GetRequest);
            }
        }
Esempio n. 26
0
        object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
        {
            if (e.Index == 1)
            {
                return this.LogicalName;
            }
            if (e.Index == 2)
            {
                GXByteBuffer data = new GXByteBuffer();
                data.SetUInt8((byte)DataType.Array);
                data.SetUInt8((byte)Entries.Count);
                /*
                foreach (GXScheduleEntry it in Entries)
                {
                    data.SetUInt8((byte)DataType.Structure);
                    data.SetUInt8(10);
                    //Add index.
                    data.SetUInt8((byte)DataType.UInt8);
                    data.SetUInt8(it.Index);
                    //Add enable.
                    data.SetUInt8((byte)DataType.Boolean);
                    data.SetUInt8((byte) (it.Enable ? 1 : 0));

                    //Add logical Name.
                    data.SetUInt8((byte)DataType.OctetString);
                    data.SetUInt8((byte) it.LogicalName.Length);
                    //TODO: data.SetUInt8((byte)it.LogicalName.Length);

                    //Add script selector.
                    data.SetUInt8((byte)DataType.UInt8);
                    data.SetUInt8(it.ScriptSelector);

                    //Add switch time.
                    ret = var_setDateTime(&tmp, &se->switchTime);
                    if (ret != 0)
                    {
                        var_clear(&tmp);
                        break;
                    }
                    ret = var_getBytes(&tmp, &value->byteArr);
                    var_clear(&tmp);
                    if (ret != 0)
                    {
                        break;
                    }
                    //Add validity window.
                    data.SetUInt8((byte)DataType.UInt8);
                    data.SetUInt8(it.ValidityWindow);

                    //Add exec week days.
                    ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                    setObjectCount(se->execWeekdays.size, &value->byteArr);
                    ba_addRange(&value->byteArr, se->execWeekdays.data, bit_getByteCount(se->execWeekdays.size));

                    //Add exec spec days.
                    ba_setUInt8(&value->byteArr, DLMS_DATA_TYPE_BIT_STRING);
                    setObjectCount(se->execSpecDays.size, &value->byteArr);
                    ba_addRange(&value->byteArr, se->execSpecDays.data, bit_getByteCount(se->execSpecDays.size));

                    //Add begin date.
                    ret = var_setDateTime(&tmp, &se->beginDate);
                    if (ret != 0)
                    {
                        var_clear(&tmp);
                        break;
                    }
                    ret = var_getBytes(&tmp, &value->byteArr);
                    var_clear(&tmp);
                    if (ret != 0)
                    {
                        break;
                    }
                    //Add end date.
                    ret = var_setDateTime(&tmp, &se->endDate);
                    if (ret != 0)
                    {
                        var_clear(&tmp);
                        break;
                    }
                    ret = var_getBytes(&tmp, &value->byteArr);
                    var_clear(&tmp);
                    if (ret != 0)
                    {
                        break;
                    }
                }
                 * */
                return data.Array();
            }
            e.Error = ErrorCode.ReadWriteDenied;
            return null;
        }
Esempio n. 27
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         int cnt = 0;
         if (SapAssignmentList != null)
         {
             cnt = SapAssignmentList.Count;
         }
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         //Add count
         GXCommon.SetObjectCount(cnt, data);
         if (cnt != 0)
         {
             foreach (var it in SapAssignmentList)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)2); //Count
                 GXCommon.SetData(settings, data, DataType.UInt16, it.Key);
                 GXCommon.SetData(settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Value));
             }
         }
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 28
0
 public byte[][] ImageTransferInitiate(GXDLMSClient client, string imageIdentifier, long imageSize)
 {
     if (ImageBlockSize == 0)
     {
         throw new Exception("Invalid image block size");
     }
     GXByteBuffer data = new GXByteBuffer();
     data.SetUInt8((byte)DataType.Structure);
     data.SetUInt8((byte)2);
     GXCommon.SetData(client.Settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(imageIdentifier));
     GXCommon.SetData(client.Settings, data, DataType.UInt32, imageSize);
     return client.Method(this, 1, data.Array(), DataType.Array);
 }
Esempio n. 29
0
 /// <summary>
 /// Removes X.509 v3 certificate from the server using entity.
 /// </summary>
 /// <param name="client">DLMS client that is used to generate action.</param>
 /// <param name="entity">Certificate entity type.</param>
 /// <param name="type">Certificate type.</param>
 /// <param name="systemTitle">System title.</param>
 /// <returns>Generated action.</returns>
 public byte[][] RemoveCertificateByEntity(GXDLMSClient client, CertificateEntity entity, CertificateType type, byte[] systemTitle)
 {
     GXByteBuffer bb = new GXByteBuffer();
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(2);
     //Add enum
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(0);
     //Add certificate_identification_by_entity
     bb.SetUInt8(DataType.Structure);
     bb.SetUInt8(3);
     //Add certificate_entity
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(entity);
     //Add certificate_type
     bb.SetUInt8(DataType.Enum);
     bb.SetUInt8(type);
     //system_title
     GXCommon.SetData(client.Settings, bb, DataType.OctetString, systemTitle);
     return client.Method(this, 8, bb.Array(), DataType.OctetString);
 }
Esempio n. 30
0
 public byte[][] ImageBlockTransfer(GXDLMSClient client, byte[] imageBlockValue, out int ImageBlockCount)
 {
     ImageBlockCount = (int)(imageBlockValue.Length / ImageBlockSize);
     if (imageBlockValue.Length % ImageBlockSize != 0)
     {
         ++ImageBlockCount;
     }
     List<byte[]> packets = new List<byte[]>();
     for (int pos = 0; pos != ImageBlockCount; ++pos)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8((byte)2);
         GXCommon.SetData(client.Settings, data, DataType.UInt32, pos);
         byte[] tmp;
         int bytes = (int)(imageBlockValue.Length - ((pos + 1) * ImageBlockSize));
         //If last packet
         if (bytes < 0)
         {
             bytes = (int)(imageBlockValue.Length - (pos * ImageBlockSize));
             tmp = new byte[bytes];
             Array.Copy(imageBlockValue, pos * ImageBlockSize, tmp, 0, bytes);
         }
         else
         {
             tmp = new byte[ImageBlockSize];
             Array.Copy(imageBlockValue, (pos * ImageBlockSize), tmp, 0, ImageBlockSize);
         }
         GXCommon.SetData(client.Settings, data, DataType.OctetString, tmp);
         packets.AddRange(client.Method(this, 2, data.Array(), DataType.Array));
     }
     return packets.ToArray();
 }
Esempio n. 31
0
 /// <summary>
 /// Get sertificates as byte buffer.
 /// </summary>
 /// <returns></returns>
 private byte[] GetSertificates()
 {
     GXByteBuffer bb = new GXByteBuffer();
     bb.SetUInt8((byte)DataType.Array);
     GXCommon.SetObjectCount(Certificates.Count, bb);
     foreach (GXDLMSCertificateInfo it in Certificates)
     {
         bb.SetUInt8((byte)DataType.Structure);
         GXCommon.SetObjectCount(6, bb);
         bb.SetUInt8((byte)DataType.Enum);
         bb.SetUInt8((byte)it.Entity);
         bb.SetUInt8((byte)DataType.Enum);
         bb.SetUInt8((byte)it.Type);
         GXCommon.AddString(it.SerialNumber, bb);
         GXCommon.AddString(it.Issuer, bb);
         GXCommon.AddString(it.Subject, bb);
         GXCommon.AddString(it.SubjectAltName, bb);
     }
     return bb.Array();
 }
Esempio n. 32
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return ImageBlockSize;
     }
     if (e.Index == 3)
     {
         return ImageTransferredBlocksStatus;
     }
     if (e.Index == 4)
     {
         return ImageFirstNotTransferredBlockNumber;
     }
     if (e.Index == 5)
     {
         return ImageTransferEnabled;
     }
     if (e.Index == 6)
     {
         return ImageTransferStatus;
     }
     if (e.Index == 7)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (ImageActivateInfo == null)
         {
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             GXCommon.SetObjectCount(ImageActivateInfo.Length, data);
             foreach (GXDLMSImageActivateInfo it in ImageActivateInfo)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8(3);
                 GXCommon.SetData(settings, data, DataType.UInt32, it.Size);
                 GXCommon.SetData(settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(Convert.ToString(it.Identification)));
                 if (it.Signature == null || it.Signature.Length == 0)
                 {
                     GXCommon.SetData(settings, data, DataType.OctetString, null);
                 }
                 else
                 {
                     GXCommon.SetData(settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it.Signature));
                 }
             }
         }
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 33
0
 /// <summary>
 /// Generates push setup message.
 /// </summary>
 /// <param name="date"> Date time. Set To Min or Max if not added.</param>
 /// <param name="push">Target Push object.</param>
 /// <returns>Generated data notification message(s).</returns>
 public byte[][] GeneratePushSetupMessages(DateTime date, GXDLMSPushSetup push)
 {
     if (push == null)
     {
         throw new ArgumentNullException("push");
     }
     GXByteBuffer buff = new GXByteBuffer();
     buff.SetUInt8((byte)DataType.Structure);
     GXCommon.SetObjectCount(push.PushObjectList.Count, buff);
     foreach (KeyValuePair<GXDLMSObject, GXDLMSCaptureObject> it in push.PushObjectList)
     {
         AddData(it.Key, it.Value.AttributeIndex, buff);
     }
     return GenerateDataNotificationMessages(date, buff);
 }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.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. 35
0
 ///<summary>
 ///Parse SNRM Request. If server do not accept client empty byte array is returned.
 /// </summary>
 ///<returns>
 ///Returns returned UA packet.
 ///</returns>
 private void HandleSnrmRequest()
 {
     Reset(true);
     replyData.SetUInt8(0x81); // FromatID
     replyData.SetUInt8(0x80); // GroupID
     replyData.SetUInt8(0);    // Length
     replyData.SetUInt8(HDLCInfo.MaxInfoTX);
     replyData.SetUInt8(GXCommon.GetSize(Limits.MaxInfoTX));
     replyData.Add(Limits.MaxInfoTX);
     replyData.SetUInt8(HDLCInfo.MaxInfoRX);
     replyData.SetUInt8(GXCommon.GetSize(Limits.MaxInfoRX));
     replyData.Add(Limits.MaxInfoRX);
     replyData.SetUInt8(HDLCInfo.WindowSizeTX);
     replyData.SetUInt8(GXCommon.GetSize(Limits.WindowSizeTX));
     replyData.Add(Limits.WindowSizeTX);
     replyData.SetUInt8(HDLCInfo.WindowSizeRX);
     replyData.SetUInt8(GXCommon.GetSize(Limits.WindowSizeRX));
     replyData.Add(Limits.WindowSizeRX);
     replyData.SetUInt8(2, (byte)(replyData.Size - 3));
 }
Esempio n. 36
0
        /// <summary>
        /// Handle read Block in blocks.
        /// </summary>
        /// <param name="data">Received data.</param>
        private static void HandleReadBlockNumberAccess(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            UInt16 blockNumber = data.GetUInt16();

            if (xml != null)
            {
                xml.AppendStartTag(Command.ReadRequest, VariableAccessSpecification.BlockNumberAccess);
                xml.AppendLine("<BlockNumber Value=\"" + xml.IntegerToHex(blockNumber, 4) + "\" />");
                xml.AppendEndTag(Command.ReadRequest, VariableAccessSpecification.BlockNumberAccess);
                return;
            }

            if (blockNumber != settings.BlockIndex)
            {
                GXByteBuffer bb = new GXByteBuffer();
                Debug.WriteLine("handleReadRequest failed. Invalid block number. " + settings.BlockIndex + "/" + blockNumber);
                bb.SetUInt8(ErrorCode.DataBlockNumberInvalid);
                GXDLMS.GetSNPdu(new GXDLMSSNParameters(settings, Command.ReadResponse, 1, (byte)SingleReadResponse.DataAccessError, bb, null), replyData);
                settings.ResetBlockIndex();
                return;
            }
            if (settings.Index != settings.Count && server.transaction.data.Size < settings.MaxPduSize)
            {
                List <ValueEventArgs> reads   = new List <ValueEventArgs>();
                List <ValueEventArgs> actions = new List <ValueEventArgs>();
                foreach (ValueEventArgs it in server.transaction.targets)
                {
                    if (it.action)
                    {
                        actions.Add(it);
                    }
                    else
                    {
                        reads.Add(it);
                    }
                }
                if (reads.Count != 0)
                {
                    server.NotifyRead(reads.ToArray());
                }

                if (actions.Count != 0)
                {
                    server.NotifyAction(actions.ToArray());
                }
                GetReadData(settings, server.transaction.targets, server.transaction.data);
                if (reads.Count != 0)
                {
                    server.NotifyPostRead(reads.ToArray());
                }

                if (actions.Count != 0)
                {
                    server.NotifyPostAction(actions.ToArray());
                }
            }
            settings.IncreaseBlockIndex();
            GXDLMSSNParameters p = new GXDLMSSNParameters(settings, Command.ReadResponse, 1,
                                                          (byte)SingleReadResponse.DataBlockResult, null, server.transaction.data);

            p.multipleBlocks = true;
            GXDLMS.GetSNPdu(p, replyData);
            //If all data is sent.
            if (server.transaction.data.Size == server.transaction.data.Position)
            {
                server.transaction = null;
                settings.ResetBlockIndex();
            }
            else
            {
                server.transaction.data.Trim();
            }
        }
Esempio n. 37
0
 static int AppendMultipleSNBlocks(GXDLMSSNParameters p, GXByteBuffer header, GXByteBuffer reply)
 {
     bool ciphering = p.settings.Cipher != null && p.settings.Cipher.Security != Gurux.DLMS.Enums.Security.None;
     int hSize = reply.Size + 3;
     if (header != null)
     {
         hSize += header.Size;
     }
     //Add LLC bytes.
     if (p.command == Command.WriteRequest ||
             p.command == Command.ReadRequest)
     {
         hSize += 1 + GXCommon.GetObjectCountSizeInBytes(p.count);
     }
     int maxSize = p.settings.MaxPduSize - hSize;
     if (ciphering)
     {
         maxSize -= CipheringHeaderSize;
         if (p.settings.InterfaceType == InterfaceType.HDLC)
         {
             maxSize -= 3;
         }
     }
     maxSize -= GXCommon.GetObjectCountSizeInBytes(maxSize);
     if (p.data.Size - p.data.Position > maxSize)
     {
         //More blocks.
         reply.SetUInt8(0);
     }
     else
     {
         //Last block.
         reply.SetUInt8(1);
         maxSize = p.data.Size - p.data.Position;
     }
     //Add block index.
     reply.SetUInt16(p.blockIndex);
     if (p.command == Command.WriteRequest)
     {
         ++p.blockIndex;
         GXCommon.SetObjectCount(p.count, reply);
         reply.SetUInt8(DataType.OctetString);
     }
     if (p.command == Command.ReadRequest)
     {
         ++p.blockIndex;
     }
     if (header != null)
     {
         GXCommon.SetObjectCount(maxSize + header.Size, reply);
         reply.Set(header);
     }
     else
     {
         GXCommon.SetObjectCount(maxSize, reply);
     }
     return maxSize;
 }
Esempio n. 38
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return (byte)Mode;
     }
     if (e.Index == 3)
     {
         return Repetitions;
     }
     if (e.Index == 4)
     {
         return RepetitionDelay;
     }
     if (e.Index == 5)
     {
         int cnt = CallingWindow.Count;
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         //Add count
         GXCommon.SetObjectCount(cnt, data);
         if (cnt != 0)
         {
             foreach (var it in CallingWindow)
             {
                 data.SetUInt8((byte)DataType.Structure);
                 data.SetUInt8((byte)2); //Count
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Key); //start_time
                 GXCommon.SetData(settings, data, DataType.OctetString, it.Value); //end_time
             }
         }
         return data.Array();
     }
     if (e.Index == 6)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (Destinations == null)
         {
             //Add count
             GXCommon.SetObjectCount(0, data);
         }
         else
         {
             int cnt = Destinations.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             foreach (string it in Destinations)
             {
                 GXCommon.SetData(settings, data, DataType.OctetString, ASCIIEncoding.ASCII.GetBytes(it)); //destination
             }
         }
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 39
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. 40
0
        ///<summary>
        /// Handle action request.
        ///</summary>
        public static void HandleMethodRequest(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXDLMSConnectionEventArgs connectionInfo, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            ErrorCode    error = ErrorCode.Ok;
            GXByteBuffer bb    = new GXByteBuffer();
            // Get type.
            ActionRequestType type = (ActionRequestType)data.GetUInt8();
            // Get invoke ID and priority.
            byte invokeId = data.GetUInt8();

            settings.UpdateInvokeId(invokeId);
            // CI
            ObjectType ci = (ObjectType)data.GetUInt16();

            byte[] ln = new byte[6];
            data.Get(ln);
            // Attribute Id
            byte id = data.GetUInt8();
            // Get parameters.
            object parameters = null;
            byte   selection  = data.GetUInt8();

            if (xml != null)
            {
                xml.AppendStartTag(Command.MethodRequest);
                if (type == ActionRequestType.Normal)
                {
                    xml.AppendStartTag(Command.MethodRequest, ActionRequestType.Normal);
                    xml.AppendLine(TranslatorTags.InvokeId, "Value", xml.IntegerToHex(invokeId, 2));
                    AppendMethodDescriptor(xml, (int)ci, ln, id);
                    if (selection != 0)
                    {
                        //MethodInvocationParameters
                        xml.AppendStartTag(TranslatorTags.MethodInvocationParameters);
                        GXDataInfo di = new GXDataInfo();
                        di.xml = xml;
                        GXCommon.GetData(settings, data, di);
                        xml.AppendEndTag(TranslatorTags.MethodInvocationParameters);
                    }
                    xml.AppendEndTag(Command.MethodRequest, ActionRequestType.Normal);
                }
                xml.AppendEndTag(Command.MethodRequest);
                return;
            }
            if (selection != 0)
            {
                GXDataInfo info = new GXDataInfo();
                parameters = GXCommon.GetData(settings, data, info);
            }

            GXDLMSObject obj = settings.Objects.FindByLN(ci, GXCommon.ToLogicalName(ln));

            if (settings.Connected == ConnectionState.None && !settings.CanAccess() && (ci != ObjectType.AssociationLogicalName || id != 1))
            {
                replyData.Set(GXDLMSServer.GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                                                                         ServiceError.Service, (byte)Service.Unsupported));
                return;
            }

            if (obj == null)
            {
                obj = server.NotifyFindObject(ci, 0, GXCommon.ToLogicalName(ln));
            }
            if (obj == null)
            {
                // Device reports a undefined object.
                error = ErrorCode.UndefinedObject;
            }
            else
            {
                ValueEventArgs e = new ValueEventArgs(server, obj, id, 0, parameters);
                e.InvokeId = invokeId;
                if (server.NotifyGetMethodAccess(e) == MethodAccessMode.NoAccess)
                {
                    error = ErrorCode.ReadWriteDenied;
                }
                else
                {
                    server.NotifyAction(new ValueEventArgs[] { e });
                    byte[] actionReply;
                    if (e.Handled)
                    {
                        actionReply = (byte[])e.Value;
                    }
                    else
                    {
                        actionReply = (obj as IGXDLMSBase).Invoke(settings, e);
                        server.NotifyPostAction(new ValueEventArgs[] { e });
                    }
                    //Set default action reply if not given.
                    if (actionReply != null && e.Error == 0)
                    {
                        //Add return parameters
                        bb.SetUInt8(1);
                        //Add parameters error code.
                        bb.SetUInt8(0);
                        GXCommon.SetData(settings, bb, GXDLMSConverter.GetDLMSDataType(actionReply), actionReply);
                    }
                    else
                    {
                        error = e.Error;
                        //Add return parameters
                        bb.SetUInt8(0);
                    }
                }
                invokeId = (byte)e.InvokeId;
            }

            GXDLMSLNParameters p = new GXDLMSLNParameters(null, settings, invokeId, Command.MethodResponse, 1, null, bb, (byte)error);

            GXDLMS.GetLNPdu(p, replyData);
            //If High level authentication fails.
            if (obj is GXDLMSAssociationLogicalName && id == 1)
            {
                if ((obj as GXDLMSAssociationLogicalName).AssociationStatus == Objects.Enums.AssociationStatus.Associated)
                {
                    server.NotifyConnected(connectionInfo);
                    settings.Connected |= ConnectionState.Dlms;
                }
                else
                {
                    server.NotifyInvalidConnection(connectionInfo);
                    settings.Connected &= ~ConnectionState.Dlms;
                }
            }
        }
Esempio n. 41
0
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         return this.CurrentAverageValue;
     }
     if (e.Index == 3)
     {
         return this.LastAverageValue;
     }
     if (e.Index == 4)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Structure);
         data.SetUInt8(2);
         GXCommon.SetData(settings, data, DataType.Int8, _scaler);
         GXCommon.SetData(settings, data, DataType.Enum, Unit);
         return data.Array();
     }
     if (e.Index == 5)
     {
         return this.Status;
     }
     if (e.Index == 6)
     {
         return CaptureTime;
     }
     if (e.Index == 7)
     {
         return StartTimeCurrent;
     }
     if (e.Index == 8)
     {
         return Period;
     }
     if (e.Index == 9)
     {
         return NumberOfPeriods;
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 42
0
        /// <summary>
        /// Get next logical name PDU.
        /// </summary>
        /// <param name="p">LN parameters.</param>
        /// <param name="reply">Generated message.</param>
        internal static void GetLNPdu(GXDLMSLNParameters p, GXByteBuffer reply)
        {
            bool ciphering = p.settings.Cipher != null && p.settings.Cipher.Security != Gurux.DLMS.Enums.Security.None;
            int len = 0;
            if (!ciphering && p.settings.InterfaceType == InterfaceType.HDLC)
            {
                AddLLCBytes(p.settings, reply);
            }
            if (p.command == Command.Aarq)
            {
                reply.Set(p.attributeDescriptor);
            }
            else
            {
                if (p.settings.LnSettings.GeneralBlockTransfer)
                {
                    reply.SetUInt8((byte)Command.GeneralBlockTransfer);
                    MultipleBlocks(p, reply, ciphering);
                    // Is last block
                    if (!p.lastBlock)
                    {
                        reply.SetUInt8(0);
                    }
                    else
                    {
                        reply.SetUInt8(0x80);
                    }
                    // Set block number sent.
                    reply.SetUInt8(0);
                    // Set block number acknowledged
                    reply.SetUInt8((byte)p.blockIndex);
                    ++p.blockIndex;
                    // Add APU tag.
                    reply.SetUInt8(0);
                    // Add Addl fields
                    reply.SetUInt8(0);
                }
                // Add command.
                reply.SetUInt8((byte)p.command);

                if (p.command == Command.DataNotification ||
                        p.command == Command.AccessRequest ||
                        p.command == Command.AccessResponse)
                {
                    // Add Long-Invoke-Id-And-Priority
                    reply.SetUInt32(GetLongInvokeIDPriority(p.settings));
                    // Add date time.
                    if (p.time == null || p.time.Value.DateTime == DateTime.MinValue || p.time.Value.DateTime == DateTime.MaxValue ||
                            p.time.Value.LocalDateTime == DateTime.MinValue || p.time.Value.LocalDateTime == DateTime.MaxValue)
                    {
                        reply.SetUInt8(DataType.None);
                    }
                    else
                    {
                        // Data is send in octet string. Remove data type.
                        int pos = reply.Size;
                        GXCommon.SetData(p.settings, reply, DataType.OctetString, p.time);
                        reply.Move(pos + 1, pos, reply.Size - pos - 1);
                    }
                }
                else
                {
                    //Get request size can be bigger than PDU size.
                    if (p.command != Command.GetRequest &&
                            p.data != null && p.data.Size != 0)
                    {
                        MultipleBlocks(p, reply, ciphering);
                    }
                    //Change Request type if Set request and multiple blocks is needed.
                    if (p.command == Command.SetRequest)
                    {
                        if (p.multipleBlocks)
                        {
                            if (p.requestType == 1)
                            {
                                p.requestType = 2;
                            }
                            else if (p.requestType == 2)
                            {
                                p.requestType = 3;
                            }
                        }
                    }
                    //Change request type If get response and multiple blocks is needed.
                    if (p.command == Command.GetResponse)
                    {
                        if (p.multipleBlocks)
                        {
                            if (p.requestType == 1)
                            {
                                p.requestType = 2;
                            }
                        }
                    }
                    reply.SetUInt8(p.requestType);
                    // Add Invoke Id And Priority.
                    reply.SetUInt8(GetInvokeIDPriority(p.settings));
                }

                //Add attribute descriptor.
                reply.Set(p.attributeDescriptor);
                if (p.command != Command.DataNotification && !p.settings.LnSettings.GeneralBlockTransfer)
                {
                    //If multiple blocks.
                    if (p.multipleBlocks)
                    {
                        // Is last block.
                        if (p.lastBlock)
                        {
                            reply.SetUInt8(1);
                            p.settings.Count = p.settings.Index = 0;
                        }
                        else
                        {
                            reply.SetUInt8(0);
                        }
                        // Block index.
                        reply.SetUInt32(p.blockIndex);
                        ++p.blockIndex;
                        //Add status if reply.
                        if (p.status != 0xFF)
                        {
                            if (p.status != 0 && p.command == Command.GetResponse)
                            {
                                reply.SetUInt8(1);
                            }
                            reply.SetUInt8(p.status);
                        }
                        //Block size.
                        if (p.data != null)
                        {
                            len = p.data.Size - p.data.Position;
                        }
                        else
                        {
                            len = 0;
                        }
                        int totalLength = len + reply.Size;
                        if (ciphering)
                        {
                            totalLength += CipheringHeaderSize;
                        }

                        if (totalLength > p.settings.MaxPduSize)
                        {
                            len = p.settings.MaxPduSize - reply.Size - p.data.Position;
                            if (ciphering)
                            {
                                len -= CipheringHeaderSize;
                            }
                            len -= GXCommon.GetObjectCountSizeInBytes(len);
                        }
                        GXCommon.SetObjectCount(len, reply);
                        reply.Set(p.data, len);
                    }
                }
                //Add data that fits to one block.
                if (len == 0)
                {
                    //Add status if reply.
                    if (p.status != 0xFF)
                    {
                        if (p.status != 0 && p.command == Command.GetResponse)
                        {
                            reply.SetUInt8(1);
                        }
                        reply.SetUInt8(p.status);
                    }
                    if (p.data != null && p.data.Size != 0)
                    {
                        len = p.data.Size - p.data.Position;
                        //Get request size can be bigger than PDU size.
                        if (p.command != Command.GetRequest && len + reply.Size > p.settings.MaxPduSize)
                        {
                            len = p.settings.MaxPduSize - reply.Size;
                        }
                        reply.Set(p.data, len);
                    }
                }
                if (ciphering)
                {
                    byte[] tmp = p.settings.Cipher.Encrypt((byte)GetGloMessage(p.command),
                                                           p.settings.Cipher.SystemTitle, reply.Array());
                    reply.Size = 0;
                    if (p.settings.InterfaceType == InterfaceType.HDLC)
                    {
                        AddLLCBytes(p.settings, reply);
                    }
                    if (p.command == Command.DataNotification)
                    {
                        // Add command.
                        reply.SetUInt8(tmp[0]);
                        // Add system title.
                        GXCommon.SetObjectCount(
                            p.settings.Cipher.SystemTitle.Length,
                            reply);
                        reply.Set(p.settings.Cipher.SystemTitle);
                        // Add data.
                        reply.Set(tmp, 1, tmp.Length - 1);
                    }
                    else
                    {
                        reply.Set(tmp);
                    }
                }
            }
        }
Esempio n. 43
0
 /// <summary>
 /// Handles release reuest.
 /// </summary>
 /// <param name="data">Received data.</param>
 /// <param name="connectionInfo">Connection info.</param>
 private void HandleReleaseRequest(GXByteBuffer data, GXDLMSConnectionEventArgs connectionInfo)
 {
     //Return error if connection is not established.
     if (!Settings.Connected && !Settings.IsAuthenticationRequired && !Settings.AllowAnonymousAccess)
     {
         replyData.Add(GenerateConfirmedServiceError(ConfirmedServiceError.InitiateError,
                                                     ServiceError.Service, (byte)Service.Unsupported));
         return;
     }
     if (Settings.InterfaceType == InterfaceType.HDLC)
     {
         replyData.Set(0, GXCommon.LLCReplyBytes);
     }
     replyData.SetUInt8(0x63);
     //LEN.
     replyData.SetUInt8(0x03);
     replyData.SetUInt8(0x80);
     replyData.SetUInt8(0x01);
     replyData.SetUInt8(0x00);
 }
        /// <summary>
        /// Handle get request with list command.
        /// </summary>
        /// <param name="data">Received data.</param>
        private static void GetRequestWithList(GXDLMSSettings settings, GXDLMSServer server, GXByteBuffer data, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            ValueEventArgs e;
            GXByteBuffer bb = new GXByteBuffer();
            int pos;
            int cnt = GXCommon.GetObjectCount(data);
            GXCommon.SetObjectCount(cnt, bb);
            List<ValueEventArgs> list = new List<ValueEventArgs>();
            if (xml != null)
            {
                xml.AppendStartTag(TranslatorTags.AttributeDescriptorList, "Qty", xml.IntegerToHex(cnt, 2));
            }
            try
            {
                for (pos = 0; pos != cnt; ++pos)
                {
                    ObjectType ci = (ObjectType)data.GetUInt16();
                    byte[] ln = new byte[6];
                    data.Get(ln);
                    short attributeIndex = data.GetUInt8();
                    // AccessSelection
                    int selection = data.GetUInt8();
                    int selector = 0;
                    object parameters = null;
                    if (selection != 0)
                    {
                        selector = data.GetUInt8();
                        GXDataInfo info = new GXDataInfo();
                        parameters = GXCommon.GetData(settings, data, info);
                    }
                    if (xml != null)
                    {
                        xml.AppendStartTag(TranslatorTags.AttributeDescriptorWithSelection);
                        xml.AppendStartTag(TranslatorTags.AttributeDescriptor);
                        xml.AppendLine(TranslatorTags.ClassId, "Value", xml.IntegerToHex((int)ci, 4));
                        xml.AppendLine(TranslatorTags.InstanceId, "Value", GXCommon.ToHex(ln, false));
                        xml.AppendLine(TranslatorTags.AttributeId, "Value", xml.IntegerToHex(attributeIndex, 2));
                        xml.AppendEndTag(TranslatorTags.AttributeDescriptor);
                        xml.AppendEndTag(TranslatorTags.AttributeDescriptorWithSelection);
                    }
                    else
                    {
                        GXDLMSObject obj = settings.Objects.FindByLN(ci, GXDLMSObject.ToLogicalName(ln));
                        if (obj == null)
                        {
                            obj = server.NotifyFindObject(ci, 0, GXDLMSObject.ToLogicalName(ln));
                        }
                        if (obj == null)
                        {
                            // "Access Error : Device reports a undefined object."
                            e = new ValueEventArgs(settings, obj, attributeIndex, 0, 0);
                            e.Error = ErrorCode.UndefinedObject;
                            list.Add(e);
                        }
                        else
                        {
                            if (obj.GetAccess(attributeIndex) == AccessMode.NoAccess)
                            {
                                //Read Write denied.
                                ValueEventArgs arg = new ValueEventArgs(settings, obj, attributeIndex, 0, null);
                                arg.Error = ErrorCode.ReadWriteDenied;
                                list.Add(arg);
                            }
                            else
                            {
                                ValueEventArgs arg = new ValueEventArgs(settings, obj, attributeIndex, selector, parameters);
                                list.Add(arg);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (xml == null)
                {
                    throw ex;
                }
            }
            if (xml != null)
            {
                xml.AppendEndTag(TranslatorTags.AttributeDescriptorList);
                return;
            }

            server.NotifyRead(list.ToArray());
            object value;
            pos = 0;
            foreach (ValueEventArgs it in list)
            {
                try
                {
                    if (it.Handled)
                    {
                        value = it.Value;
                    }
                    else
                    {
                        value = (it.Target as IGXDLMSBase).GetValue(settings, it);
                    }
                    bb.SetUInt8(it.Error);
                    GXDLMS.AppendData(settings, it.Target, it.Index, bb, value);
                }
                catch (Exception)
                {
                    bb.SetUInt8((byte)ErrorCode.HardwareFault);
                }
                if (settings.Index != settings.Count)
                {
                    server.transaction = new GXDLMSLongTransaction(list.ToArray(), Command.GetRequest, null);
                }
                ++pos;
            }
            GXDLMSLNParameters p = new GXDLMSLNParameters(settings, Command.GetResponse, 3, null, bb, 0xFF);
            GXDLMS.GetLNPdu(p, replyData);
        }
Esempio n. 45
0
        private static void HandleReadDataBlockAccess(
            GXDLMSSettings settings, GXDLMSServer server,
            Command command, GXByteBuffer data, int cnt, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            GXByteBuffer bb          = new GXByteBuffer();
            byte         lastBlock   = data.GetUInt8();
            UInt16       blockNumber = data.GetUInt16();

            if (xml != null)
            {
                if (command == Command.WriteResponse)
                {
                    xml.AppendStartTag(TranslatorTags.WriteDataBlockAccess);
                }
                else
                {
                    xml.AppendStartTag(TranslatorTags.ReadDataBlockAccess);
                }
                xml.AppendLine("<LastBlock Value=\"" + xml.IntegerToHex(lastBlock, 2) + "\" />");
                xml.AppendLine("<BlockNumber Value=\"" + xml.IntegerToHex(blockNumber, 4) + "\" />");
                if (command == Command.WriteResponse)
                {
                    xml.AppendEndTag(TranslatorTags.WriteDataBlockAccess);
                }
                else
                {
                    xml.AppendEndTag(TranslatorTags.ReadDataBlockAccess);
                }
                return;
            }
            if (blockNumber != settings.BlockIndex)
            {
                Debug.WriteLine("handleReadRequest failed. Invalid block number. " + settings.BlockIndex + "/" + blockNumber);
                bb.SetUInt8(ErrorCode.DataBlockNumberInvalid);
                GXDLMS.GetSNPdu(new GXDLMSSNParameters(settings, command, 1, (byte)SingleReadResponse.DataAccessError, bb, null), replyData);
                settings.ResetBlockIndex();
                return;
            }
            int  count = 1;
            byte type  = (byte)DataType.OctetString;

            if (command == Command.WriteResponse)
            {
                count = GXCommon.GetObjectCount(data);
                type  = data.GetUInt8();
            }
            int size     = GXCommon.GetObjectCount(data);
            int realSize = data.Size - data.Position;

            if (count != 1 || type != (byte)DataType.OctetString || size != realSize)
            {
                Debug.WriteLine("handleGetRequest failed. Invalid block size.");
                bb.SetUInt8(ErrorCode.DataBlockUnavailable);
                GXDLMS.GetSNPdu(new GXDLMSSNParameters(settings, command, cnt, (byte)SingleReadResponse.DataAccessError, bb, null), replyData);
                settings.ResetBlockIndex();
                return;
            }
            if (server.transaction == null)
            {
                server.transaction = new GXDLMSLongTransaction(null, command, data);
            }
            else
            {
                server.transaction.data.Set(data);
            }
            if (lastBlock == 0)
            {
                bb.SetUInt16(blockNumber);
                settings.IncreaseBlockIndex();
                if (command == Command.ReadResponse)
                {
                    type = (byte)SingleReadResponse.BlockNumber;
                }
                else
                {
                    type = (byte)SingleWriteResponse.BlockNumber;
                }
                GXDLMS.GetSNPdu(new GXDLMSSNParameters(settings, command, cnt, type, null, bb), replyData);
                return;
            }
            else
            {
                if (server.transaction != null)
                {
                    data.Size = 0;
                    data.Set(server.transaction.data);
                    server.transaction = null;
                }
                if (command == Command.ReadResponse)
                {
                    HandleReadRequest(settings, server, data, replyData, xml);
                }
                else
                {
                    HandleWriteRequest(settings, server, data, replyData, xml);
                }
                settings.ResetBlockIndex();
            }
        }
Esempio n. 46
0
        ///<summary>
        ///Parse AARQ request that client send and returns AARE request.
        /// </summary>
        ///<returns>
        ///Reply to the client.
        ///</returns>
        private void HandleAarqRequest(GXByteBuffer data, GXDLMSConnectionEventArgs connectionInfo)
        {
            GXByteBuffer      error  = null;
            AssociationResult result = AssociationResult.Accepted;

            Settings.CtoSChallenge = null;
            if (!Settings.UseCustomChallenge)
            {
                Settings.StoCChallenge = null;
            }
            // Reset settings for wrapper.
            if (Settings.InterfaceType == InterfaceType.WRAPPER)
            {
                Reset(true);
            }
            SourceDiagnostic diagnostic = SourceDiagnostic.NoReasonGiven;

            try
            {
                diagnostic = GXAPDU.ParsePDU(Settings, Settings.Cipher, data, null);
                if (diagnostic != SourceDiagnostic.None)
                {
                    result     = AssociationResult.PermanentRejected;
                    diagnostic = SourceDiagnostic.ApplicationContextNameNotSupported;
                    InvalidConnection(connectionInfo);
                }
                else
                {
                    diagnostic = ValidateAuthentication(Settings.Authentication, Settings.Password);
                    if (diagnostic != SourceDiagnostic.None)
                    {
                        result = AssociationResult.PermanentRejected;
                        InvalidConnection(connectionInfo);
                    }
                    else if (Settings.Authentication > Authentication.Low)
                    {
                        // If High authentication is used.
                        if (!Settings.UseCustomChallenge)
                        {
                            Settings.StoCChallenge = GXSecure.GenerateChallenge(Settings.Authentication);
                        }
                        result     = AssociationResult.Accepted;
                        diagnostic = SourceDiagnostic.AuthenticationRequired;
                    }
                    else
                    {
                        Connected(connectionInfo);
                        Settings.Connected = true;
                    }
                }
                Settings.IsAuthenticationRequired = diagnostic == SourceDiagnostic.AuthenticationRequired;
            }
            catch (GXDLMSConfirmedServiceError e)
            {
                result     = AssociationResult.PermanentRejected;
                diagnostic = SourceDiagnostic.NoReasonGiven;
                error      = new GXByteBuffer();
                error.SetUInt8(0xE);
                error.SetUInt8(e.ConfirmedServiceError);
                error.SetUInt8(e.ServiceError);
                error.SetUInt8(e.ServiceErrorValue);
            }
            if (Settings.InterfaceType == Enums.InterfaceType.HDLC)
            {
                replyData.Set(GXCommon.LLCReplyBytes);
            }
            // Generate AARE packet.
            GXAPDU.GenerateAARE(Settings, replyData, result, diagnostic, Settings.Cipher, error, null);
        }
 object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         return this.LogicalName;
     }
     if (e.Index == 2)
     {
         GXByteBuffer data = new GXByteBuffer();
         data.SetUInt8((byte)DataType.Array);
         if (Entries == null)
         {
             data.SetUInt8(0);
         }
         else
         {
             int cnt = Entries.Length;
             //Add count
             GXCommon.SetObjectCount(cnt, data);
             if (cnt != 0)
             {
                 foreach (GXDLMSSpecialDay it in Entries)
                 {
                     data.SetUInt8((byte)DataType.Structure);
                     data.SetUInt8((byte)3); //Count
                     GXCommon.SetData(settings, data, DataType.UInt16, it.Index);
                     GXCommon.SetData(settings, data, DataType.OctetString, it.Date);
                     GXCommon.SetData(settings, data, DataType.UInt8, it.DayId);
                 }
             }
         }
         return data.Array();
     }
     e.Error = ErrorCode.ReadWriteDenied;
     return null;
 }
Esempio n. 48
0
 private byte[] ReportError(Command cmd, ErrorCode error)
 {
     switch (cmd)
     {
         case Command.ReadRequest:
             cmd = Command.ReadResponse;
             break;
         case Command.WriteRequest:
             cmd = Command.WriteResponse;
             break;
         case Command.GetRequest:
             cmd = Command.GetResponse;
             break;
         case Command.SetRequest:
             cmd = Command.SetResponse;
             break;
         case Command.MethodRequest:
             cmd = Command.MethodResponse;
             break;
         default:
             //Return HW error and close connection..
             break;
     }
     if (Settings.UseLogicalNameReferencing)
     {
         GXDLMS.GetLNPdu(new GXDLMSLNParameters(Settings, cmd, 1, null, null, (byte)error), replyData);
     }
     else
     {
         GXByteBuffer bb = new GXByteBuffer();
         bb.SetUInt8(error);
         GXDLMSSNParameters p = new GXDLMSSNParameters(Settings, cmd, 1, (byte)error, null, bb);
         GXDLMS.GetSNPdu(p, replyData);
     }
     if (this.InterfaceType == Enums.InterfaceType.WRAPPER)
     {
         return GXDLMS.GetWrapperFrame(Settings, replyData);
     }
     else
     {
         return GXDLMS.GetHdlcFrame(Settings, 0, replyData);
     }
 }
Esempio n. 49
0
        /// <summary>
        /// Handle get request with list command.
        /// </summary>
        /// <param name="data">Received data.</param>
        private static void GetRequestWithList(GXDLMSSettings settings, byte invokeID, GXDLMSServer server, GXByteBuffer data, GXByteBuffer replyData, GXDLMSTranslatorStructure xml)
        {
            ValueEventArgs e;
            GXByteBuffer   bb = new GXByteBuffer();
            int            pos;
            int            cnt = GXCommon.GetObjectCount(data);

            GXCommon.SetObjectCount(cnt, bb);
            List <ValueEventArgs> list = new List <ValueEventArgs>();

            if (xml != null)
            {
                xml.AppendStartTag(TranslatorTags.AttributeDescriptorList, "Qty", xml.IntegerToHex(cnt, 2));
            }
            try
            {
                for (pos = 0; pos != cnt; ++pos)
                {
                    ObjectType ci = (ObjectType)data.GetUInt16();
                    byte[]     ln = new byte[6];
                    data.Get(ln);
                    short attributeIndex = data.GetUInt8();
                    // AccessSelection
                    int    selection  = data.GetUInt8();
                    int    selector   = 0;
                    object parameters = null;
                    if (selection != 0)
                    {
                        selector = data.GetUInt8();
                        GXDataInfo info = new GXDataInfo();
                        parameters = GXCommon.GetData(settings, data, info);
                    }
                    if (xml != null)
                    {
                        xml.AppendStartTag(TranslatorTags.AttributeDescriptorWithSelection);
                        xml.AppendStartTag(TranslatorTags.AttributeDescriptor);
                        xml.AppendComment(ci.ToString());
                        xml.AppendLine(TranslatorTags.ClassId, "Value", xml.IntegerToHex((int)ci, 4));
                        xml.AppendComment(GXCommon.ToLogicalName(ln));
                        xml.AppendLine(TranslatorTags.InstanceId, "Value", GXCommon.ToHex(ln, false));
                        xml.AppendLine(TranslatorTags.AttributeId, "Value", xml.IntegerToHex(attributeIndex, 2));
                        xml.AppendEndTag(TranslatorTags.AttributeDescriptor);
                        xml.AppendEndTag(TranslatorTags.AttributeDescriptorWithSelection);
                    }
                    else
                    {
                        GXDLMSObject obj = settings.Objects.FindByLN(ci, GXCommon.ToLogicalName(ln));
                        if (obj == null)
                        {
                            obj = server.NotifyFindObject(ci, 0, GXCommon.ToLogicalName(ln));
                        }
                        if (obj == null)
                        {
                            // "Access Error : Device reports a undefined object."
                            e       = new ValueEventArgs(server, obj, attributeIndex, 0, 0);
                            e.Error = ErrorCode.UndefinedObject;
                            list.Add(e);
                        }
                        else
                        {
                            ValueEventArgs arg = new ValueEventArgs(server, obj, attributeIndex, selector, parameters);
                            arg.InvokeId = invokeID;
                            if (server.NotifyGetAttributeAccess(arg) == AccessMode.NoAccess)
                            {
                                //Read Write denied.
                                arg.Error = ErrorCode.ReadWriteDenied;
                                list.Add(arg);
                            }
                            else
                            {
                                list.Add(arg);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (xml == null)
                {
                    throw ex;
                }
            }
            if (xml != null)
            {
                xml.AppendEndTag(TranslatorTags.AttributeDescriptorList);
                return;
            }

            server.NotifyRead(list.ToArray());
            object value;

            pos = 0;
            foreach (ValueEventArgs it in list)
            {
                try
                {
                    if (it.Handled)
                    {
                        value = it.Value;
                    }
                    else
                    {
                        value = (it.Target as IGXDLMSBase).GetValue(settings, it);
                    }
                    bb.SetUInt8(it.Error);
                    if (it.ByteArray)
                    {
                        bb.Set((byte[])value);
                    }
                    else
                    {
                        GXDLMS.AppendData(settings, it.Target, it.Index, bb, value);
                    }
                    invokeID = (byte)it.InvokeId;
                }
                catch (Exception)
                {
                    bb.SetUInt8((byte)ErrorCode.HardwareFault);
                }
                if (settings.Index != settings.Count)
                {
                    server.transaction = new GXDLMSLongTransaction(list.ToArray(), Command.GetRequest, null);
                }
                ++pos;
            }
            server.NotifyPostRead(list.ToArray());
            GXDLMSLNParameters p = new GXDLMSLNParameters(null, settings, invokeID, Command.GetResponse, 3, null, bb, 0xFF);

            GXDLMS.GetLNPdu(p, replyData);
        }
Esempio n. 50
0
        /// <summary>
        /// Get HDLC frame for data.
        /// </summary>
        /// <param name="settings">DLMS settings.</param>
        /// <param name="frame">Frame ID. If zero new is generated.</param>
        /// <param name="data">Data to add.</param>
        /// <returns>HDLC frames.</returns>
        internal static byte[] GetHdlcFrame(GXDLMSSettings settings, byte frame, GXByteBuffer data)
        {
            GXByteBuffer bb = new GXByteBuffer();
            int frameSize, len = 0;
            byte[] primaryAddress, secondaryAddress;
            if (settings.IsServer)
            {
                primaryAddress = GetHdlcAddressBytes(settings.ClientAddress, 0);
                secondaryAddress = GetHdlcAddressBytes(settings.ServerAddress, settings.ServerAddressSize);
            }
            else
            {
                primaryAddress = GetHdlcAddressBytes(settings.ServerAddress, settings.ServerAddressSize);
                secondaryAddress = GetHdlcAddressBytes(settings.ClientAddress, 0);
            }
            // Add BOP
            bb.SetUInt8(GXCommon.HDLCFrameStartEnd);
            frameSize = Convert.ToInt32(settings.Limits.MaxInfoTX);
            // If no data
            if (data == null || data.Size == 0)
            {
                bb.SetUInt8(0xA0);
            }
            else if (data.Size - data.Position <= frameSize)
            {
                // Is last packet.
                bb.SetUInt8(0xA0);
                len = data.Size - data.Position;
            }
            else
            {
                // More data to left.
                bb.SetUInt8(0xA8);
                len = frameSize;
            }
            //Frame len.
            if (len == 0)
            {
                bb.SetUInt8((byte)(5 + primaryAddress.Length + secondaryAddress.Length + len));
            }
            else
            {
                bb.SetUInt8((byte)(7 + primaryAddress.Length + secondaryAddress.Length + len));
            }
            // Add primary address.
            bb.Set(primaryAddress);
            // Add secondary address.
            bb.Set(secondaryAddress);

            //Add frame ID.
            if (frame == 0)
            {
                frame = settings.NextSend();
            }
            bb.SetUInt8(frame);
            // Add header CRC.
            UInt16 crc = GXFCS16.CountFCS16(bb.Data, 1, bb.Size - 1);
            bb.SetUInt16(crc);
            if (len != 0)
            {
                //Add data.
                bb.Set(data, len);
                // Add data CRC.
                crc = GXFCS16.CountFCS16(bb.Data, 1, bb.Size - 1);
                bb.SetUInt16(crc);
            }
            // Add EOP
            bb.SetUInt8(GXCommon.HDLCFrameStartEnd);
            if (data != null)
            {
                //Remove sent data in server side.
                if (settings.IsServer)
                {
                    if (data.Size == data.Position)
                    {
                        data.Clear();
                    }
                    else
                    {
                        data.Move(data.Position, 0, data.Size - data.Position);
                        data.Position = 0;
                    }
                }
            }
            return bb.Array();
        }