From 1f8c3067f7da75aaa388d95c9cbc5457063194b7 Mon Sep 17 00:00:00 2001
From: Martin Teichmann <martin.teichmann@gmail.com>
Date: Fri, 10 Feb 2023 19:36:16 +0000
Subject: [PATCH] fix length indicator in packet

this is now following what Twincat does, as checked with tcpdump
---
 ebpfcat/ethercat.py | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/ebpfcat/ethercat.py b/ebpfcat/ethercat.py
index de406b9..f84d73e 100644
--- a/ebpfcat/ethercat.py
+++ b/ebpfcat/ethercat.py
@@ -223,14 +223,16 @@ class Packet:
         that may be used as an identifier for the packet.
         """
         FOLLOW = 0x8000
-        ret = [pack("<H", (self.size + self.PACKET_TAIL) | 0x1000)]
+        ret = [pack("<H", (self.size + self.PACKET_TAIL - self.PACKET_HEADER) | 0x1000)]
         for i, (cmd, data, *dgram) in enumerate(self.data, start=1):
             ret.append(pack("<BBhHHH" if len(dgram) == 3 else "<BBiHH",
                             cmd.value, *dgram,
                             len(data) | FOLLOW, 0))
             ret.append(data)
             ret.append(b"\0\0")
-        ret.append(pack("<BBiHHH", 0, 0, index, 0, 0, 0))
+        ret.append(pack("<BBiHHH", ECCmd.NOP.value, 0, index, 0, 0, 0))
+        if self.size < 34:
+            ret.append(b"\0" * (34 - self.size))
         return b''.join(ret)
 
     def __str__(self):
@@ -286,7 +288,8 @@ class EtherCat(Protocol):
             *dgram, future = await self.send_queue.get()
             lastsize = packet.size
             packet.append(*dgram)
-            dgrams.append((lastsize + 10, packet.size - 2, future))
+            dgrams.append((lastsize + Packet.DATAGRAM_HEADER,
+                           packet.size - Packet.DATAGRAM_TAIL, future))
             if packet.full() or self.send_queue.empty():
                 data = await self.roundtrip_packet(packet)
                 for start, stop, future in dgrams:
@@ -388,7 +391,7 @@ class EtherCat(Protocol):
         """distribute received packets to the recipients"""
         length, = unpack("<H", data[:2])
         length &= 0x7ff
-        index, = unpack("<I", data[length-10 : length-6])
+        index, = unpack("<I", data[length-8 : length-4])
         self.wait_futures[index].set_result(data)
 
 
-- 
GitLab