From b187785d94c344c477808eaf9bf54101a88058a9 Mon Sep 17 00:00:00 2001
From: Martin Teichmann <martin.teichmann@gmail.com>
Date: Fri, 10 Feb 2023 11:58:56 +0000
Subject: [PATCH] move index datagram to the end of packet

not done for FastEtherCat yet, so it doesn't work
---
 ebpfcat/ethercat.py | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

diff --git a/ebpfcat/ethercat.py b/ebpfcat/ethercat.py
index 4b703e2..de406b9 100644
--- a/ebpfcat/ethercat.py
+++ b/ebpfcat/ethercat.py
@@ -193,10 +193,12 @@ class Packet:
     ETHERNET_HEADER = 14
     DATAGRAM_HEADER = 10
     DATAGRAM_TAIL = 2
+    PACKET_HEADER = 2
+    PACKET_TAIL = 12
 
     def __init__(self):
         self.data = []
-        self.size = 14
+        self.size = self.PACKET_HEADER
 
     def append(self, cmd, data, idx, *address):
         """Append a datagram to the packet
@@ -220,13 +222,15 @@ class Packet:
         An implicit empty datagram is added at the beginning of the packet
         that may be used as an identifier for the packet.
         """
-        ret = [pack("<HBBiHHH", self.size | 0x1000, 0, 0, index, 1 << 15, 0, 0)]
+        FOLLOW = 0x8000
+        ret = [pack("<H", (self.size + self.PACKET_TAIL) | 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) | ((i < len(self.data)) << 15), 0))
+                            len(data) | FOLLOW, 0))
             ret.append(data)
             ret.append(b"\0\0")
+        ret.append(pack("<BBiHHH", 0, 0, index, 0, 0, 0))
         return b''.join(ret)
 
     def __str__(self):
@@ -362,7 +366,7 @@ class EtherCat(Protocol):
         p = Packet()
         p.append(ECCmd.APRD, b"\0\0", 0, 0, 0x10)
         ret = await self.roundtrip_packet(p)
-        no, = unpack("<h", ret[16:18])  # number of terminals
+        no, = unpack("<h", ret[4:6])  # number of terminals
         return no
 
     async def find_free_address(self):
@@ -382,7 +386,9 @@ class EtherCat(Protocol):
 
     def datagram_received(self, data, addr):
         """distribute received packets to the recipients"""
-        index, = unpack("<I", data[4:8])
+        length, = unpack("<H", data[:2])
+        length &= 0x7ff
+        index, = unpack("<I", data[length-10 : length-6])
         self.wait_futures[index].set_result(data)
 
 
-- 
GitLab