public void Write(GXDLMSObject obj, object target, int index, List<object> UpdatedObjects)
        {
            object value;
            GXReplyData reply = new GXReplyData();
            for (int it = 1; it != (obj as IGXDLMSBase).GetAttributeCount() + 1; ++it)
            {
                reply.Clear();
                if (obj.GetDirty(it, out value))
                {
                    //Read DLMS data type if not known.
                    DataType type = obj.GetDataType(it);
                    if (type == DataType.None)
                    {
                        byte[] data = client.Read(obj, it)[0];
                        ReadDataBlock(data, "Write object type " + obj.ObjectType, reply);
                        type = reply.DataType;
                        if (type == DataType.None)
                        {
                            throw new Exception("Failed to write value. Data type not set.");
                        }
                        obj.SetDataType(it, type);
                    }
                    try
                    {
                        foreach (byte[] tmp in client.Write(obj.Name, value, type, obj.ObjectType, it))
                        {
                            ReadDataBlock(tmp, "Write object", reply);
                        }
                        obj.ClearDirty(it);
                        //Read data once again to make sure it is updated.
                        byte[] data = client.Read(obj, it)[0];
                        ReadDataBlock(data, "Read object " + obj.ObjectType, reply);

                        value = reply.Value;
                        if (value is byte[] && (type = obj.GetUIDataType(it)) != DataType.None)
                        {
                            value = GXDLMSClient.ChangeType((byte[])value, type);
                        }
                        client.UpdateValue(obj, it, value);
                    }
                    catch (GXDLMSException ex)
                    {
                        if (ex.ErrorCode == 3)
                        {
                            throw new Exception("Read/Write Failed.");
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
            }
        }
        void InitializeIEC()
        {
            GXManufacturer manufacturer = this.parent.Manufacturers.FindByIdentification(parent.Manufacturer);
            if (manufacturer == null)
            {
                throw new Exception("Unknown manufacturer " + parent.Manufacturer);
            }
            GXSerial serial = media as GXSerial;
            byte Terminator = (byte)0x0A;
            media.Open();
            //Query device information.
            if (media != null && parent.StartProtocol == StartProtocolType.IEC)
            {
                string data = "/?!\r\n";
                if (this.parent.HDLCAddressing == HDLCAddressType.SerialNumber)
                {
                    data = "/?" + this.parent.PhysicalAddress + "!\r\n";
                }
                GXLogWriter.WriteLog("HDLC sending:" + data);
                ReceiveParameters<string> p = new ReceiveParameters<string>()
                {
                    AllData = false,
                    Eop = Terminator,
                    WaitTime = parent.WaitTime * 1000
                };
                lock (media.Synchronous)
                {
                    media.Send(data, null);
                    if (!media.Receive(p))
                    {
                        //Try to move away from mode E.
                        try
                        {
                            GXReplyData reply = new GXReplyData();
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1, reply);
                        }
                        catch (Exception)
                        {
                        }
                        data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                        media.Send(data, null);
                        p.Count = 1;
                        media.Receive(p);
                        data = "Failed to receive reply from the device in given time.";
                        GXLogWriter.WriteLog(data);
                        throw new Exception(data);
                    }
                    //If echo is used.
                    if (p.Reply == data)
                    {
                        p.Reply = null;
                        if (!media.Receive(p))
                        {
                            //Try to move away from mode E.
                            GXReplyData reply = new GXReplyData();
                            this.ReadDLMSPacket(this.DisconnectRequest(), 1, reply);
                            if (serial != null)
                            {
                                data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                                media.Send(data, null);
                                p.Count = 1;
                                if (!media.Receive(p))
                                {
                                }
                                serial.DtrEnable = serial.RtsEnable = false;
                                serial.BaudRate = 9600;
                                serial.DtrEnable = serial.RtsEnable = true;
                                data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                                media.Send(data, null);
                                p.Count = 1;
                                media.Receive(p);
                            }

                            data = "Failed to receive reply from the device in given time.";
                            GXLogWriter.WriteLog(data);
                            throw new Exception(data);
                        }
                    }
                }
                GXLogWriter.WriteLog("HDLC received: " + p.Reply);
                if (p.Reply[0] != '/')
                {
                    p.WaitTime = 100;
                    media.Receive(p);
                    throw new Exception("Invalid responce.");
                }
                string manufactureID = p.Reply.Substring(1, 3);
                UpdateManufactureSettings(manufactureID);
                char baudrate = p.Reply[4];
                int BaudRate = 0;
                switch (baudrate)
                {
                    case '0':
                        BaudRate = 300;
                        break;
                    case '1':
                        BaudRate = 600;
                        break;
                    case '2':
                        BaudRate = 1200;
                        break;
                    case '3':
                        BaudRate = 2400;
                        break;
                    case '4':
                        BaudRate = 4800;
                        break;
                    case '5':
                        BaudRate = 9600;
                        break;
                    case '6':
                        BaudRate = 19200;
                        break;
                    default:
                        throw new Exception("Unknown baud rate.");
                }
                if (parent.MaximumBaudRate != 0)
                {
                    BaudRate = parent.MaximumBaudRate;
                    GXLogWriter.WriteLog("Maximum BaudRate is set to : " + BaudRate.ToString());
                }
                GXLogWriter.WriteLog("BaudRate is : " + BaudRate.ToString());
                //Send ACK
                //Send Protocol control character
                byte controlCharacter = (byte)'2';// "2" HDLC protocol procedure (Mode E)
                //Send Baud rate character
                //Mode control character
                byte ModeControlCharacter = (byte)'2';//"2" //(HDLC protocol procedure) (Binary mode)
                //Set mode E.
                byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
                GXLogWriter.WriteLog("Moving to mode E.", arr);
                lock (media.Synchronous)
                {
                    media.Send(arr, null);
                    System.Threading.Thread.Sleep(500);
                    serial.BaudRate = BaudRate;
                    p.Reply = null;
                    p.WaitTime = 100;
                    //Note! All meters do not echo this.
                    media.Receive(p);
                    if (p.Reply != null)
                    {
                        GXLogWriter.WriteLog("Received: " + p.Reply);
                    }
                    serial.Close();
                    serial.DataBits = 8;
                    serial.Parity = Parity.None;
                    serial.StopBits = StopBits.One;
                    serial.Open();
                }
            }
        }
 /// <summary>
 /// Read DLMS Data from the device.
 /// </summary>
 /// <remarks>
 /// If access is denied return null.
 /// </remarks>
 /// <param name="data">Data to send.</param>
 /// <returns>Received data.</returns>
 public void ReadDLMSPacket(byte[] data, int tryCount, GXReplyData reply)
 {
     if (data == null)
     {
         return;
     }
     object eop = (byte)0x7E;
     //In network connection terminator is not used.
     if (client.InterfaceType == InterfaceType.WRAPPER && media is GXNet && !parent.UseRemoteSerial)
     {
         eop = null;
     }
     int pos = 0;
     bool succeeded = false;
     ReceiveParameters<byte[]> p = new ReceiveParameters<byte[]>()
     {
         AllData = false,
         Eop = eop,
         Count = 5,
         WaitTime = parent.WaitTime * 1000,
     };
     lock (media.Synchronous)
     {
         if (data != null)
         {
             media.Send(data, null);
         }
         while (!succeeded && pos != 3)
         {
             succeeded = media.Receive(p);
             if (!succeeded)
             {
                 //Try to read again...
                 if (++pos != tryCount)
                 {
                     //If Eop is not set read one byte at time.
                     if (p.Eop == null)
                     {
                         p.Count = 1;
                     }
                     System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                     media.Send(data, null);
                     continue;
                 }
                 string err = "Failed to receive reply from the device in given time.";
                 GXLogWriter.WriteLog(err, p.Reply);
                 throw new Exception(err);
             }
         }
         try
         {
             //Loop until whole COSEM packet is received.
             while (!client.GetData(p.Reply, reply))
             {
                 //If Eop is not set read one byte at time.
                 if (p.Eop == null)
                 {
                     p.Count = 1;
                 }
                 if (!media.Receive(p))
                 {
                     //Try to read again...
                     if (++pos != tryCount)
                     {
                         System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                         continue;
                     }
                     string err = "Failed to receive reply from the device in given time.";
                     GXLogWriter.WriteLog(err, p.Reply);
                     throw new Exception(err);
                 }
             }
         }
         catch (Exception ex)
         {
             GXLogWriter.WriteLog("Received data", p.Reply);
             throw ex;
         }
     }
     GXLogWriter.WriteLog("Received data", p.Reply);
     if (reply.Error != 0)
     {
         if (reply.Error == (int)ErrorCode.Rejected)
         {
             Thread.Sleep(1000);
             ReadDLMSPacket(data, tryCount, reply);
         }
         else
         {
             throw new GXDLMSException(reply.Error);
         }
     }
 }
 public void KeepAlive()
 {
     GXReplyData reply = new GXReplyData();
     byte[] data = client.GetKeepAlive();
     GXLogWriter.WriteLog("Send Keep Alive", data);
     ReadDLMSPacket(data, reply);
 }
 /// <summary>
 /// Read object.
 /// </summary>
 /// <param name="InitialValues"></param>
 /// <param name="obj"></param>
 /// <param name="attribute"></param>
 public void Read(object sender, GXDLMSObject obj, int attribute)
 {
     GXReplyData reply = new GXReplyData();
     foreach (int it in (obj as IGXDLMSBase).GetAttributeIndexToRead())
     {
         reply.Clear();
         if (obj is GXDLMSProfileGeneric && it == 2)
         {
             if (OnBeforeRead != null)
             {
                 OnBeforeRead(obj, it);
             }
             try
             {
                 CurrentProfileGeneric = obj as GXDLMSProfileGeneric;
                 OnDataReceived += new GXDLMSCommunicator.DataReceivedEventHandler(this.OnProfileGenericDataReceived);
                 if (CurrentProfileGeneric.AccessSelector == AccessRange.Range ||
                     CurrentProfileGeneric.AccessSelector == AccessRange.Last)
                 {
                     byte[][] tmp = client.ReadRowsByRange(CurrentProfileGeneric, Convert.ToDateTime(CurrentProfileGeneric.From), Convert.ToDateTime(CurrentProfileGeneric.To));
                     ReadDataBlock(tmp[0], "Reading profile generic data", 1, reply);
                 }
                 else if (CurrentProfileGeneric.AccessSelector == AccessRange.Entry)
                 {
                     byte[][] tmp = client.ReadRowsByEntry(CurrentProfileGeneric, Convert.ToInt32(CurrentProfileGeneric.From), Convert.ToInt32(CurrentProfileGeneric.To));
                     ReadDataBlock(tmp[0], "Reading profile generic data " + CurrentProfileGeneric.Name, 1, reply);
                 }
                 else //Read all.
                 {
                     byte[] tmp = client.Read(CurrentProfileGeneric, 2)[0];
                     ReadDataBlock(tmp, "Reading profile generic data " + CurrentProfileGeneric.Name, 1, reply);
                 }
             }
             finally
             {
                 if (OnAfterRead != null)
                 {
                     OnAfterRead(obj, it);
                 }
                 OnDataReceived -= new GXDLMSCommunicator.DataReceivedEventHandler(OnProfileGenericDataReceived);
             }
             continue;
         }
         else
         {
             if (OnBeforeRead != null)
             {
                 OnBeforeRead(obj, it);
             }
             byte[] data = client.Read(obj.Name, obj.ObjectType, it)[0];
             try
             {
                 ReadDataBlock(data, "Read object type " + obj.ObjectType + " index: " + it, reply);
             }
             catch (GXDLMSException ex)
             {
                 if (ex.ErrorCode == 3 ||  //If read is denied.
                     ex.ErrorCode == 4 || // Undefined object.
                     ex.ErrorCode == 13) //Actaris returns access violation error.
                 {
                     obj.SetAccess(it, AccessMode.NoAccess);
                     continue;
                 }
                 else
                 {
                     throw ex;
                 }
             }
             if (obj is IGXDLMSBase)
             {
                 object value = reply.Value;
                 DataType type;
                 if (value is byte[] && (type = obj.GetUIDataType(it)) != DataType.None)
                 {
                     value = GXDLMSClient.ChangeType((byte[])value, type);
                 }
                 client.UpdateValue(obj, it, value);
             }
             if (OnAfterRead != null)
             {
                 OnAfterRead(obj, it);
             }
             obj.SetLastReadTime(it, DateTime.Now);
             //If only selected attribute is read.
             if (attribute != 0)
             {
                 break;
             }
         }
     }
 }
Beispiel #6
0
 ///<summary>
 /// Removes the HDLC frame from the packet, and returns COSEM data only.
 ///</summary>
 ///<param name="reply">
 /// The received data from the device.
 ///</param>
 ///<param name="data">
 /// Information from the received data.
 ///</param>
 ///<returns>
 /// Is frame complete.
 ///</returns>
 public bool GetData(GXByteBuffer reply, GXReplyData data)
 {
     return(GXDLMS.GetData(Settings, reply, data));
 }
 public void GetProfileGenericColumns(GXDLMSProfileGeneric item)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Read(item, 3), "Get profile generic columns...", reply);
     client.UpdateValue(item, 3, reply.Value);
 }
 /// <summary>
 /// Read Association View from the meter.
 /// </summary>
 public GXDLMSObjectCollection GetAssociationView()
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Client.GetObjectsRequest(), reply);
     return Client.ParseObjects(reply.Data, true);
 }
 /// <summary>
 /// Read DLMS Data from the device.
 /// </summary>
 /// <param name="data">Data to send.</param>
 /// <returns>Received data.</returns>
 public void ReadDLMSPacket(byte[] data, GXReplyData reply)
 {
     if (data == null)
     {
         return;
     }
     reply.Error = 0;
     object eop = (byte)0x7E;
     //In network connection terminator is not used.
     if (Client.InterfaceType == InterfaceType.WRAPPER && Media is GXNet)
     {
         eop = null;
     }
     int pos = 0;
     bool succeeded = false;
     ReceiveParameters<byte[]> p = new ReceiveParameters<byte[]>()
     {
         Eop = eop,
         Count = 5,
         WaitTime = WaitTime,
     };
     lock (Media.Synchronous)
     {
         while (!succeeded && pos != 3)
         {
             WriteTrace("<- " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(data, true));
             Media.Send(data, null);
             succeeded = Media.Receive(p);
             if (!succeeded)
             {
                 //If Eop is not set read one byte at time.
                 if (p.Eop == null)
                 {
                     p.Count = 1;
                 }
                 //Try to read again...
                 if (++pos != 3)
                 {
                     System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                     continue;
                 }
                 throw new Exception("Failed to receive reply from the device in given time.");
             }
         }
         try
         {
             //Loop until whole COSEM packet is received.
             while (!Client.GetData(p.Reply, reply))
             {
                 //If Eop is not set read one byte at time.
                 if (p.Eop == null)
                 {
                     p.Count = 1;
                 }
                 while (!Media.Receive(p))
                 {
                     //If echo.
                     if (p.Reply.Length == data.Length)
                     {
                         Media.Send(data, null);
                     }
                     //Try to read again...
                     if (++pos != 3)
                     {
                         System.Diagnostics.Debug.WriteLine("Data send failed. Try to resend " + pos.ToString() + "/3");
                         continue;
                     }
                     throw new Exception("Failed to receive reply from the device in given time.");
                 }
             }
         }
         catch (Exception ex)
         {
             WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(p.Reply, true));
             throw ex;
         }
     }
     WriteTrace("-> " + DateTime.Now.ToLongTimeString() + "\t" + GXCommon.ToHex(p.Reply, true));
     if (reply.Error != 0)
     {
         if (reply.Error == (short)ErrorCode.Rejected)
         {
             Thread.Sleep(1000);
             ReadDLMSPacket(data, reply);
         }
         else
         {
             throw new GXDLMSException(reply.Error);
         }
     }
 }
 /// <summary>
 /// Read Profile Generic Columns by entry.
 /// </summary>
 public object[] ReadRowsByEntry(GXDLMSProfileGeneric it, int index, int count)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Client.ReadRowsByEntry(it, index, count), reply);
     return (object[])Client.UpdateValue(it, 2, reply.Value);
 }
 /// <summary>
 /// Read Profile Generic Columns by range.
 /// </summary>
 public object[] ReadRowsByRange(GXDLMSProfileGeneric it, DateTime start, DateTime end)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Client.ReadRowsByRange(it, start, end), reply);
     return (object[])Client.UpdateValue(it, 2, reply.Value);
 }
 /// <summary>
 /// Method attribute value.
 /// </summary>
 public void Method(GXDLMSObject it, int attributeIndex, object value, DataType type)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Client.Method(it, attributeIndex, value, type), reply);
 }
 /// <summary>
 /// Write attribute value.
 /// </summary>
 public void Write(GXDLMSObject it, int attributeIndex)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Client.Write(it, attributeIndex), reply);
 }
 /// <summary>
 /// Read list of attributes.
 /// </summary>
 public void ReadList(List<KeyValuePair<GXDLMSObject, int>> list)
 {
     byte[][] data = Client.ReadList(list);
     GXReplyData reply = new GXReplyData();
     List<object> values = new List<object>();
     foreach (byte[] it in data)
     {
         ReadDataBlock(it, reply);
         if (reply.Value is object[])
         {
             values.AddRange((object[])reply.Value);
         }
         else if (reply.Value != null)
         {
             //Value is null if data is send multiple frames.
             values.Add(reply.Value);
         }
         reply.Clear();
     }
     if (values.Count != list.Count)
     {
         throw new Exception("Invalid reply. Read items count do not match.");
     }
     Client.UpdateValues(list, values);
 }
 void ReadDataBlock(byte[][] data, string text, GXReplyData reply)
 {
     foreach (byte[] it in data)
     {
         reply.Clear();
         ReadDataBlock(it, text, reply);
     }
 }
        public void UpdateImage(GXDLMSImageTransfer target, byte[] data, string Identification)
        {
            GXReplyData reply = new GXReplyData();
            //Check that image transfer ia enabled.
            ReadDataBlock(Client.Read(target, 5), reply);
            Client.UpdateValue(target, 5, reply);
            if (!target.ImageTransferEnabled)
            {
                throw new Exception("Image transfer is not enabled");
            }

            //Step 1: The client gets the ImageBlockSize.
            reply.Clear();
            ReadDataBlock(Client.Read(target, 2), reply);
            Client.UpdateValue(target, 2, reply);

            // Step 2: The client initiates the Image transfer process.
            reply.Clear();
            ReadDataBlock(target.ImageTransferInitiate(Client, Identification, data.Length), reply);
            // Step 3: The client transfers ImageBlocks.
            reply.Clear();
            int ImageBlockCount;
            ReadDataBlock(target.ImageBlockTransfer(Client, data, out ImageBlockCount), reply);
            //Step 4: The client checks the completeness of the Image in
            //each server individually and transfers any ImageBlocks not (yet) transferred;
            reply.Clear();
            Client.UpdateValue(target, 2, reply);

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

            //Get list to imaages to activate.
            reply.Clear();
            ReadDataBlock(Client.Read(target, 7), reply);
            Client.UpdateValue(target, 7, reply);
            bool bFound = false;
            foreach (GXDLMSImageActivateInfo it in target.ImageActivateInfo)
            {
                if (it.Identification == Identification)
                {
                    bFound = true;
                    break;
                }
            }

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

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

            //Step 7: Activate image.
            reply.Clear();
            ReadDataBlock(target.ImageActivate(Client), reply);
        }
 /// <summary>
 /// Read attribute value.
 /// </summary>
 public object Read(GXDLMSObject it, int attributeIndex)
 {
     GXReplyData reply = new GXReplyData();
     if (!ReadDataBlock(Client.Read(it, attributeIndex), reply))
     {
         reply.Clear();
         Thread.Sleep(1000);
         if (!ReadDataBlock(Client.Read(it, attributeIndex), reply))
         {
             if (reply.Error != 0)
             {
                 throw new GXDLMSException(reply.Error);
             }
         }
     }
     //Update data type.
     if (it.GetDataType(attributeIndex) == DataType.None)
     {
         it.SetDataType(attributeIndex, reply.DataType);
     }
     return Client.UpdateValue(it, attributeIndex, reply.Value);
 }
 public bool ReadDataBlock(byte[][] data, GXReplyData reply)
 {
     foreach (byte[] it in data)
     {
         reply.Clear();
         ReadDataBlock(it, reply);
     }
     return true;
 }
 public GXDLMSObjectCollection GetObjects()
 {
     GXLogWriter.WriteLog("--- Collecting objects. ---");
     GXReplyData reply = new GXReplyData(){Peek = false};
     try
     {
         ReadDataBlock(client.GetObjectsRequest(), "Collecting objects", 3, reply);
     }
     catch (Exception Ex)
     {
         throw new Exception("GetObjects failed. " + Ex.Message);
     }
     GXDLMSObjectCollection objs = client.ParseObjects(reply.Data, true);
     //Update OBIS code description.
     GXDLMSConverter c = new GXDLMSConverter();
     c.UpdateOBISCodeInformation(objs);
     GXLogWriter.WriteLog("--- Collecting " + objs.Count.ToString() + " objects. ---");
     return objs;
 }
 /// <summary>
 /// Read data block from the device.
 /// </summary>
 /// <param name="data">data to send</param>
 /// <param name="text">Progress text.</param>
 /// <param name="multiplier"></param>
 /// <returns>Received data.</returns>
 public void ReadDataBlock(byte[] data, GXReplyData reply)
 {
     ReadDLMSPacket(data, reply);
     while (reply.IsMoreData)
     {
         data = Client.ReceiverReady(reply.MoreData);
         ReadDLMSPacket(data, reply);
         if (!Trace)
         {
             //If data block is read.
             if ((reply.MoreData & RequestTypes.Frame) == 0)
             {
                 Console.Write("+");
             }
             else
             {
                 Console.Write("-");
             }
         }
     }
 }
 public void InitializeConnection()
 {
     if (!string.IsNullOrEmpty(parent.Manufacturer))
     {
         UpdateManufactureSettings(parent.Manufacturer);
     }
     if (media is GXSerial)
     {
         GXLogWriter.WriteLog("Initializing serial connection.");
         InitSerial();
         connectionStartTime = DateTime.Now;
     }
     else if (media is GXNet)
     {
         GXLogWriter.WriteLog("Initializing Network connection.");
         InitNet();
         //Some Electricity meters need some time before first message can be send.
         System.Threading.Thread.Sleep(500);
     }
     else if (media is Gurux.Terminal.GXTerminal)
     {
         GXLogWriter.WriteLog("Initializing Terminal connection.");
         InitTerminal();
     }
     else
     {
         throw new Exception("Unknown media type.");
     }
     try
     {
         GXReplyData reply = new GXReplyData();
         byte[] data;
         data = SNRMRequest();
         if (data != null)
         {
             GXLogWriter.WriteLog("Send SNRM request.", data);
             ReadDLMSPacket(data, 1, reply);
             GXLogWriter.WriteLog("Parsing UA reply.\r\n" + reply.Data.ToString());
             //Has server accepted client.
             ParseUAResponse(reply.Data);
             GXLogWriter.WriteLog("Parsing UA reply succeeded.");
         }
         //Generate AARQ request.
         //Split requests to multiple packets if needed.
         //If password is used all data might not fit to one packet.
         foreach (byte[] it in AARQRequest())
         {
             GXLogWriter.WriteLog("Send AARQ request", it);
             reply.Clear();
             ReadDLMSPacket(it, reply);
         }
         GXLogWriter.WriteLog("Parsing AARE reply\r\n" + reply.Data.ToString());
         try
         {
             //Parse reply.
             ParseAAREResponse(reply.Data);
         }
         catch (Exception Ex)
         {
             reply.Clear();
             ReadDLMSPacket(DisconnectRequest(), 1, reply);
             throw Ex;
         }
         //If authentication is required.
         if (client.IsAuthenticationRequired)
         {
             foreach (byte[] it in client.GetApplicationAssociationRequest())
             {
                 GXLogWriter.WriteLog("Authenticating", it);
                 reply.Clear();
                 ReadDLMSPacket(it, reply);
             }
             client.ParseApplicationAssociationResponse(reply.Data);
         }
     }
     catch (Exception ex)
     {
         if (media is GXSerial && parent.StartProtocol == StartProtocolType.IEC)
         {
             ReceiveParameters<string> p = new ReceiveParameters<string>()
             {
                 Eop = (byte) 0xA,
                 WaitTime = parent.WaitTime * 1000
             };
             lock (media.Synchronous)
             {
                 string data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
                 media.Send(data, null);
                 media.Receive(p);
             }
         }
         throw ex;
     }
     GXLogWriter.WriteLog("Parsing AARE reply succeeded.");
     parent.KeepAliveStart();
 }
        public void Close()
        {
            if (Media != null && Client != null)
            {
                try
                {
                    Console.WriteLine("Disconnecting from the meter.");
                    GXReplyData reply = new GXReplyData();
                    ReadDLMSPacket(Client.DisconnectRequest(), reply);
                    Media.Close();
                }
                catch
                {

                }
                Media = null;
                Client = null;
            }
        }
 public void MethodRequest(GXDLMSObject target, int methodIndex, object data, GXReplyData reply)
 {
     ReadDataBlock(client.Method(target, methodIndex, data, DataType.None), "", reply);
 }
Beispiel #24
0
 ///<summary>
 /// Removes the HDLC frame from the packet, and returns COSEM data only.
 ///</summary>
 ///<param name="reply">
 /// The received data from the device. 
 ///</param>
 ///<param name="data">
 /// Information from the received data. 
 ///</param>
 ///<returns>
 /// Is frame complete.
 ///</returns>
 public bool GetData(GXByteBuffer reply, GXReplyData data)
 {
     return GXDLMS.GetData(Settings, reply, data);
 }
 public void ReadDLMSPacket(byte[] data, GXReplyData reply)
 {
     ReadDLMSPacket(data, 3, reply);
 }
Beispiel #26
0
 ///<summary>
 /// Removes the HDLC frame from the packet, and returns COSEM data only.
 ///</summary>
 ///<param name="reply">
 /// The received data from the device.
 ///</param>
 ///<param name="data">
 /// Information from the received data.
 ///</param>
 ///<returns>
 /// Is frame complete.
 ///</returns>
 public bool GetData(byte[] reply, GXReplyData data)
 {
     return(GXDLMS.GetData(Settings, new GXByteBuffer(reply), data));
 }
 public void ReadValue(GXDLMSObject it, int attributeOrdinal)
 {
     GXReplyData reply = new GXReplyData();
     ReadDataBlock(Read(it, attributeOrdinal), "Read object", reply);
     //If data type is unknown
     if (it.GetDataType(attributeOrdinal) == DataType.None)
     {
         it.SetDataType(attributeOrdinal, reply.DataType);
     }
     client.UpdateValue(it, attributeOrdinal, reply.Value);
 }
Beispiel #28
0
 static void OnAction(object sender, EventArgs e)
 {
     GXButton obj = sender as GXButton;
     try
     {
         GXReplyData reply = new GXReplyData();
         GXDLMSDevice dev = obj.Target.Parent.Tag as GXDLMSDevice;
         dev.Comm.MethodRequest(obj.Target, obj.Index, null, reply);
     }
     catch (Exception ex)
     {
         MessageBox.Show(obj, ex.Message);
     }
 }
 /// <summary>
 /// Read data block from the device.
 /// </summary>
 /// <param name="data">data to send</param>
 /// <param name="text">Progress text.</param>
 /// <param name="multiplier"></param>
 /// <returns>Received data.</returns>
 internal void ReadDataBlock(byte[] data, string text, int multiplier, GXReplyData reply)
 {
     if (parent.InactivityMode == InactivityMode.ReopenActive && media is GXSerial && DateTime.Now.Subtract(connectionStartTime).TotalSeconds > 40)
     {
         parent.Disconnect();
         parent.InitializeConnection();
     }
     GXLogWriter.WriteLog(text, data);
     ReadDLMSPacket(data, reply);
     if (OnDataReceived != null)
     {
         OnDataReceived(this, reply);
     }
     if (reply.IsMoreData)
     {
         if (reply.TotalCount != 1)
         {
             NotifyProgress(text, 1, multiplier * reply.TotalCount);
         }
         while (reply.IsMoreData)
         {
             data = client.ReceiverReady(reply.MoreData);
             if ((reply.MoreData & RequestTypes.Frame) != 0)
             {
                  GXLogWriter.WriteLog("Get next frame: ", data);
             }
             else
             {
                 GXLogWriter.WriteLog("Get Next Data block: ", data);
             }
             ReadDLMSPacket(data, reply);
             if (OnDataReceived != null)
             {
                 OnDataReceived(this, reply);
             }
             if (reply.TotalCount != 1)
             {
                 NotifyProgress(text, reply.Count, multiplier * reply.TotalCount);
             }
         }
     }
 }
        /// <summary>
        /// Handle Information Report.
        /// </summary>
        /// <param name="settings">DLMS settings.</param>
        /// <param name="reply"></param>
        /// <returns></returns>
        public static void HandleInformationReport(GXDLMSSettings settings, GXReplyData reply, List <KeyValuePair <GXDLMSObject, int> > list)
        {
            reply.Time = DateTime.MinValue;
            int len = reply.Data.GetUInt8();

            byte[] tmp = null;
            // If date time is given.
            if (len != 0)
            {
                tmp = new byte[len];
                reply.Data.Get(tmp);
                reply.Time = (GXDateTime)GXDLMSClient.ChangeType(tmp, DataType.DateTime, settings.UseUtc2NormalTime);
            }
            byte type;
            int  count = GXCommon.GetObjectCount(reply.Data);

            if (reply.Xml != null)
            {
                reply.Xml.AppendStartTag(Command.InformationReport);
                if (reply.Time != DateTime.MinValue)
                {
                    reply.Xml.AppendComment(Convert.ToString(reply.Time));
                    if (reply.Xml.OutputType == TranslatorOutputType.SimpleXml)
                    {
                        reply.Xml.AppendLine(TranslatorTags.CurrentTime, null, GXCommon.ToHex(tmp, false));
                    }
                    else
                    {
                        reply.Xml.AppendLine(TranslatorTags.CurrentTime, null,
                                             GXCommon.GeneralizedTime(reply.Time));
                    }
                }
                reply.Xml.AppendStartTag(TranslatorTags.ListOfVariableAccessSpecification, "Qty", reply.Xml.IntegerToHex(count, 2));
            }
            for (int pos = 0; pos != count; ++pos)
            {
                type = reply.Data.GetUInt8();
                if (type == (byte)VariableAccessSpecification.VariableName)
                {
                    int sn = reply.Data.GetUInt16();
                    if (reply.Xml != null)
                    {
                        reply.Xml.AppendLine(
                            (int)Command.WriteRequest << 8
                                | (int)VariableAccessSpecification.VariableName,
                                "Value", reply.Xml.IntegerToHex(sn, 4));
                    }
                    else
                    {
                        GXSNInfo info = FindSNObject(settings.Objects, sn);
                        if (info.Item != null)
                        {
                            list.Add(new KeyValuePair <GXDLMSObject, int>(info.Item, info.Index));
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine(string.Format("Unknown object : {0}.", sn));
                        }
                    }
                }
            }
            if (reply.Xml != null)
            {
                reply.Xml.AppendEndTag(TranslatorTags.ListOfVariableAccessSpecification);
                reply.Xml.AppendStartTag(TranslatorTags.ListOfData, "Qty", reply.Xml.IntegerToHex(count, 2));
            }
            //Get values.
            count = GXCommon.GetObjectCount(reply.Data);
            GXDataInfo di = new GXDataInfo();

            di.xml = reply.Xml;
            for (int pos = 0; pos != count; ++pos)
            {
                di.Clear();
                if (reply.Xml != null)
                {
                    GXCommon.GetData(settings, reply.Data, di);
                }
                else
                {
                    ValueEventArgs v = new ValueEventArgs(list[pos].Key, list[pos].Value, 0, null);
                    v.Value = GXCommon.GetData(settings, reply.Data, di);
                    (list[pos].Key as IGXDLMSBase).SetValue(settings, v);
                }
            }
            if (reply.Xml != null)
            {
                reply.Xml.AppendEndTag(TranslatorTags.ListOfData);
                reply.Xml.AppendEndTag(Command.InformationReport);
            }
        }
 void OnProfileGenericDataReceived(object sender, GXReplyData reply)
 {
     if (reply.Value != null)
     {
         lock (reply)
         {
             client.UpdateValue(CurrentProfileGeneric, 2, reply.Value);
             reply.Value = null;
         }
         if (OnAfterRead != null)
         {
             OnAfterRead(CurrentProfileGeneric, 2);
         }
     }
 }
Beispiel #32
0
 ///<summary>
 /// Removes the HDLC frame from the packet, and returns COSEM data only.
 ///</summary>
 ///<param name="reply">
 /// The received data from the device.
 ///</param>
 ///<param name="data">
 /// Information from the received data.
 ///</param>
 ///<returns>
 /// Is frame complete.
 ///</returns>
 public bool GetData(GXByteBuffer reply, GXReplyData data, GXReplyData notify)
 {
     return(GXDLMS.GetData(Settings, reply, data, notify, null));
 }
 void ReadDataBlock(byte[] data, string text, GXReplyData reply)
 {
     ReadDataBlock(data, text, 1, reply);
 }
 public void InitializeConnection(GXManufacturer man)
 {
     Manufacturer = man;
     UpdateManufactureSettings(man.Identification);
     if (Media is GXSerial)
     {
         Console.WriteLine("Initializing serial connection.");
         InitSerial();
     }
     else if (Media is GXNet)
     {
         Console.WriteLine("Initializing Network connection.");
         InitNet();
         //Some Electricity meters need some time before first message can be send.
         System.Threading.Thread.Sleep(500);
     }
     else
     {
         throw new Exception("Unknown media type.");
     }
     GXReplyData reply = new GXReplyData();
     byte[] data;
     data = Client.SNRMRequest();
     if (data != null)
     {
         if (Trace)
         {
             Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
         }
         ReadDLMSPacket(data, reply);
         if (Trace)
         {
             Console.WriteLine("Parsing UA reply." + reply.ToString());
         }
         //Has server accepted client.
         Client.ParseUAResponse(reply.Data);
         Console.WriteLine("Parsing UA reply succeeded.");
     }
     //Generate AARQ request.
     //Split requests to multiple packets if needed.
     //If password is used all data might not fit to one packet.
     foreach (byte[] it in Client.AARQRequest())
     {
         if (Trace)
         {
             Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
         }
         reply.Clear();
         ReadDLMSPacket(it, reply);
     }
     if (Trace)
     {
         Console.WriteLine("Parsing AARE reply" + reply.ToString());
     }
     //Parse reply.
     Client.ParseAAREResponse(reply.Data);
     reply.Clear();
     //Get challenge Is HSL authentication is used.
     if (Client.IsAuthenticationRequired)
     {
         foreach (byte[] it in Client.GetApplicationAssociationRequest())
         {
             reply.Clear();
             ReadDLMSPacket(it, reply);
         }
         Client.ParseApplicationAssociationResponse(reply.Data);
     }
     Console.WriteLine("Parsing AARE reply succeeded.");
 }