/// <summary> /// Creates a new telegram for a modbus request or response. /// All data except the function code specific user data is written into the given buffer. /// </summary> /// <param name="addr">Device address. 0 = Breadcast, 1..247 are valid device addresses.</param> /// <param name="fkt">Function code. <see cref="ModbusFunctionCode"/></param> /// <param name="dataLength">Number of bytes for function code sspecific user data.</param> /// <param name="buffer">Buffer to write data into. The buffer must be at least MaxTelegramLength - MaxDataLength + dataLength bytes long.</param> /// <param name="telegramLength">Returns the total length of the telegram in bytes.</param> /// <param name="dataPos">Returns the offset of the function code specific user data in buffer.</param> /// <param name="isResponse">true if this is a response telegram; false if this is a request telegram.</param> /// <param name="telegramContext"> /// If isResponse == false, this parameter returns the interface implementation specific data which must be passed to the ParseTelegram method of the received response. /// If isResponse == true, this parameter must be called with the telegramContext parameter returned by ParseTelegram of the request telegram.</param> public void CreateTelegram(byte addr, byte fkt, short dataLength, byte[] buffer, out short telegramLength, out short dataPos, bool isResponse, ref object telegramContext) { telegramLength = (short)(8 + dataLength); if (isResponse) { // in a response we insert the given telegramContext as transaction id if (telegramContext is ushort) { ModbusUtils.InsertUShort(buffer, 0, (ushort)telegramContext); } else { ModbusUtils.InsertUShort(buffer, 0, 0); } } else { // insert new transaction id into request telegramContext = _NextTransactionId; if (_NextTransactionId == 0xffff) { ModbusUtils.InsertUShort(buffer, 0, 0xffff); _NextTransactionId = 0; } else { ModbusUtils.InsertUShort(buffer, 0, _NextTransactionId++); } } ModbusUtils.InsertUShort(buffer, 2, 0); ModbusUtils.InsertUShort(buffer, 4, (ushort)(telegramLength - 6)); buffer[6] = addr; buffer[7] = fkt; dataPos = 8; }