CanRead/BlazorApp/Models/Canopen/Eds/EdsDeviceDecoder.cs
2026-01-23 11:20:08 +07:00

48 lines
1.2 KiB
C#

using BlazorApp.Models.Canopen;
using BlazorApp.Models.Canopen.Eds;
namespace BlazorApp.Models.Canopen.Eds
{
public class EdsDeviceDecoder : ICanopenDeviceDecoder
{
private readonly EdsDevice _device;
public int NodeId => _device.NodeId;
public EdsDeviceDecoder(EdsDevice device)
{
_device = device;
}
public string DecodeTpdo(int pdoIndex, byte[] data, byte length)
{
if (!_device.Tpdos.TryGetValue(pdoIndex, out var tpdo))
return "-";
var results = new List<string>();
foreach (var obj in tpdo.Objects)
{
ulong raw = ReadBits(data, obj.BitOffset, obj.BitLength);
double value = raw * obj.Factor;
results.Add($"{obj.Name}: {value:F2} {obj.Unit}");
}
return string.Join(" | ", results);
}
private static ulong ReadBits(byte[] data, int bitOffset, int bitLength)
{
ulong value = 0;
int byteOffset = bitOffset / 8;
for (int i = 0; i < bitLength / 8; i++)
{
value |= (ulong)data[byteOffset + i] << (8 * i);
}
return value;
}
}
}