Motion Master
Loading...
Searching...
No Matches
soem.h
Go to the documentation of this file.
1#pragma once
2
3#include <chrono>
4#include <cstdint>
5#include <functional>
6#include <map>
7#include <memory>
8#include <mutex>
9#include <sstream>
10#include <string>
11#include <type_traits>
12#include <unordered_map>
13#include <utility>
14#include <variant>
15#include <vector>
16
17#include <tl/expected.hpp>
18
19#include "base.h"
20#include "ethercat.h"
21#include "loguru.h"
22
23namespace mm::comm::soem {
24
25// 3-second SDO read/write timeout — long enough for devices with slower mailbox implementations.
26inline constexpr int kSdoTimeoutUs = 3'000'000;
27
28// 10-second FoE read/write timeout — covers large firmware files over slow links.
29inline constexpr int kFoeTimeoutUs = 10'000'000;
30
42std::map<std::string, std::string> mapMacAddressesToInterfaces();
43
59inline std::string uiConfigWithDefaultPdoMapping = R"(
60{
61 "pdoMapping": {
62 "rx": {
63 "0x1600": [
64 "0x60400010",
65 "0x60600008",
66 "0x60710010",
67 "0x607a0020",
68 "0x60ff0020",
69 "0x60b20010",
70 "0x27010020"
71 ],
72 "0x1601": [
73 "0x60fe0120",
74 "0x60fe0220"
75 ],
76 "0x1602": [
77 "0x27030020",
78 "0x60b10020",
79 "0x20120120"
80 ]
81 },
82 "tx": {
83 "0x1a00": [
84 "0x60410010",
85 "0x60610008",
86 "0x60640020",
87 "0x606c0020",
88 "0x60770010",
89 "0x60f40020",
90 "0x21110220",
91 "0x21130220"
92 ],
93 "0x1a01": [
94 "0x24010010",
95 "0x24020010",
96 "0x24030010",
97 "0x24040010",
98 "0x27020020"
99 ],
100 "0x1a02": [
101 "0x60fd0020"
102 ],
103 "0x1a03": [
104 "0x27040020",
105 "0x20f00020",
106 "0x60fc0020",
107 "0x606b0020",
108 "0x60740010",
109 "0x60790020"
110 ]
111 }
112 }
113})";
114
139int setPdoMappingFromUiConfig(ecx_contextt* context, uint16 slave);
140
158void checkPdoMapping(ecx_contextt* context, uint16 slave);
159
173uint16_t getSlaveState(ecx_contextt* context, uint16_t slave);
174
194std::string convertSlaveStateToString(int state);
195
218void updateMailboxSyncManagersOnNextState(ecx_contextt* context, uint16_t slave,
219 int targetState);
220
236void configureDetectedSmmModule(ecx_contextt* context, uint16_t slave);
237
275void transitionSlaves(ecx_contextt* context,
276 const std::vector<uint16_t>& positions,
277 uint16_t requiredState, uint16_t targetState,
278 const char* targetName,
279 std::chrono::steady_clock::duration timeout,
280 std::chrono::steady_clock::duration resendInterval =
281 std::chrono::seconds(2),
282 std::function<void()> tick = nullptr,
283 std::function<bool()> shouldAbort = nullptr);
284
297bool setSlaveState(ecx_contextt* context, uint16_t slave, uint16_t targetState,
298 std::chrono::steady_clock::duration timeout =
299 std::chrono::seconds(5));
300
334std::vector<uint8_t> readSii(ecx_contextt* context, uint16 position);
335
347mm::comm::base::PdoMappings readPdoMappings(ecx_contextt* context,
348 uint16_t slave);
349
365 const std::vector<mm::comm::base::PdoMappingEntry>& entries);
366
378void logIoMap(uint8_t* ioMap, size_t totalBytes);
379
394struct Fieldbus {
395 ecx_contextt context;
396 std::string iface;
397 uint8 group;
399
400 /* Used by the context */
401 uint8 map[4096];
402 ecx_portt port;
403 ec_slavet slavelist[EC_MAXSLAVE];
405 ec_groupt grouplist[EC_MAXGROUP];
406 uint8 esibuf[EC_MAXEEPBUF];
407 uint32 esimap[EC_MAXEEPBITMAP];
408 ec_eringt elist;
409 ec_idxstackT idxstack;
410 boolean ecaterror;
411 int64 DCtime;
412 ec_SMcommtypet SMcommtype[EC_MAX_MAPT];
413 ec_PDOassignt PDOassign[EC_MAX_MAPT];
414 ec_PDOdesct PDOdesc[EC_MAX_MAPT];
415 ec_eepromSMt eepSM;
416 ec_eepromFMMUt eepFMMU;
417};
418
433 uint16_t readLength;
434
441 uint16_t readOffset;
442
454
461 uint16_t writeLength;
462
469 uint16_t writeOffset;
470};
471
473 supportedProtocols, writeLength, writeOffset)
474
475
482struct SlaveInfoSyncManager {
491 uint32_t flags;
492
499 uint16_t length;
500
506 uint16_t startAddress;
507
518 uint8_t type;
519};
520
521NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SlaveInfoSyncManager, flags, length,
522 startAddress, type)
523
524
531struct SlaveInfoFmmu {
537 uint8_t active;
538
545 uint8_t logicalEndBit;
546
553 uint8_t logicalStartBit;
554
560 uint32_t logicalStartAddress;
561
567 uint16_t logicalLength;
568
575 uint8_t physicalStartBit;
576
582 uint16_t physicalStartAddress;
583
590 uint8_t type;
591};
592
593NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SlaveInfoFmmu, active, logicalEndBit,
594 logicalStartBit, logicalStartAddress,
595 logicalLength, physicalStartBit,
596 physicalStartAddress, type)
597
598
604struct SlaveInfo {
611 uint16_t alStatusCode;
612
619 uint16_t aliasAddress;
620
626 std::vector<SlaveInfoFmmu> fmmus;
627
634 SlaveInfoMailbox mailbox;
635
643 uint32_t productCode;
644
650 uint32_t position;
651
659 uint32_t revisionNumber;
660
667 std::vector<SlaveInfoSyncManager> syncManagers;
668
674 std::string name;
675
684 uint32_t vendorId;
685};
686
687NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SlaveInfo, alStatusCode, aliasAddress, fmmus,
688 mailbox, productCode, position,
689 revisionNumber, syncManagers, name, vendorId)
690
691
703SlaveInfo getSlaveInfo(ecx_contextt* context, uint16 position);
704
721void logSlaveInfo(ecx_contextt* context, uint16 position);
722
740void initFieldbus(std::unique_ptr<Fieldbus>& fieldbus,
741 const std::string& iface);
742
747class Slave {
748 public:
759 explicit Slave(ecx_contextt& context, uint16_t position);
760
769 uint16_t position() const;
770
779 uint32_t vendorId() const;
780
789 uint32_t productCode() const;
790
799 uint32_t revisionNumber() const;
800
806 int getState() const;
807
827 bool setState(int targetState, int timeoutMs = 0, int intervalMs = 100);
828
850 tl::expected<void, std::string> loadParameters(bool readValues = false);
851
864 void logParameters() const;
865
882
899
906 void clearParameters();
907
916 std::unordered_map<mm::comm::base::Parameter::Address,
919
932 mm::comm::base::Parameter& findParameter(uint16_t index, uint8_t subindex);
933
961 template <typename T = std::vector<uint8_t>>
962 T upload(uint16_t index, uint8_t subindex, bool refresh = true) {
963 // Lock the mailbox mutex to ensure thread safety
964 std::lock_guard<std::mutex> lock(mailboxMutex_);
965
966 // Check if the device is in a valid state for uploading
967 auto state = context_.slavelist[position_].state;
968 if (state == EC_STATE_INIT || state == EC_STATE_BOOT) {
969 throw std::runtime_error(
970 "To upload object dictionary entries, the device must be in the (2) "
971 "PRE-OPERATIONAL, (4) SAFE-OPERATIONAL, or (8) OPERATIONAL state. "
972 "The current state is " +
973 convertSlaveStateToString(state) + ".");
974 }
975
976 // Find the previously loaded parameter
977 auto& parameter = findParameter(index, subindex);
978
979 // Refresh data if needed (SDO read)
980 if (refresh) {
981 const std::unique_ptr<std::uint8_t[]> data =
982 std::make_unique<std::uint8_t[]>(parameter.byteLength);
983 auto wkc = ecx_SDOread(&context_, position_, parameter.index,
984 parameter.subindex, false, &parameter.byteLength,
985 data.get(), kSdoTimeoutUs);
986 if (wkc <= 0) {
987 LOG_F(ERROR, "Device %d: SDO read failed for %#04x:%02x! WKC: %d",
988 position_, parameter.index, parameter.subindex, wkc);
989 auto id = mm::comm::base::makeParameterId(parameter.index,
990 parameter.subindex);
991 throw std::runtime_error("Device " + std::to_string(position_) +
992 ": SDO read failed for " + id +
993 "! WKC: " + std::to_string(wkc));
994 } else {
995 std::vector<uint8_t> receivedData(data.get(),
996 data.get() + parameter.byteLength);
997 if (!parameter.trySetValue(receivedData)) {
998 LOG_F(ERROR,
999 "Device %d: Failed to set the value of parameter %#04x:%02x!",
1000 position_, parameter.index, parameter.subindex);
1001 }
1002 }
1003 }
1004
1005 // Return the appropriate type
1006 if constexpr (std::is_same_v<T, std::vector<uint8_t>>) {
1007 return parameter.data; // parameter.data should be std::vector<uint8_t>
1008 } else {
1009 // Otherwise, try to get the value as the requested type T
1010 auto value = parameter.getValue();
1011 if (auto ptr = std::get_if<T>(&value)) {
1012 return *ptr;
1013 } else {
1014 throw std::bad_variant_access(); // Type mismatch
1015 }
1016 }
1017 }
1018
1043 template <typename T = std::vector<uint8_t>>
1044 bool download(uint16_t index, uint8_t subindex, const T& value) {
1045 std::lock_guard<std::mutex> lock(mailboxMutex_);
1046
1047 // Check if device is in valid state for download
1048 auto state = context_.slavelist[position_].state;
1049 if (state == EC_STATE_INIT || state == EC_STATE_BOOT) {
1050 throw std::runtime_error(
1051 "To download object dictionary entries, the device must be in the "
1052 "(2) PRE-OPERATIONAL, (4) SAFE-OPERATIONAL, or (8) OPERATIONAL "
1053 "state. The current state is " +
1054 convertSlaveStateToString(state) + ".");
1055 }
1056
1057 auto& parameter = findParameter(index, subindex);
1058
1059 // Convert value to raw byte data
1060 std::vector<uint8_t> data;
1061 if constexpr (std::is_same_v<T, std::vector<uint8_t>>) {
1062 data = value;
1063 } else {
1064 // Set the value in the parameter model
1065 if (!parameter.trySetValue(value)) {
1066 LOG_F(ERROR,
1067 "Device %d: Failed to set the value of parameter %#04x:%02x!",
1068 position_, parameter.index, parameter.subindex);
1069 return false;
1070 }
1071 data = parameter.data; // Use the parameter's byte representation
1072 }
1073
1074 // Check if data size matches the expected parameter size
1075 if (data.size() != parameter.byteLength) {
1076 LOG_F(ERROR, "Data size mismatch: expected %d, got %zu",
1077 parameter.byteLength, data.size());
1078 throw std::runtime_error("Data size does not match the parameter size!");
1079 }
1080
1081 // Perform the SDO write
1082 auto wkc = ecx_SDOwrite(&context_, position_, parameter.index,
1083 parameter.subindex, false, parameter.byteLength,
1084 data.data(), kSdoTimeoutUs);
1085
1086 // Check write result
1087 if (wkc <= 0) {
1088 LOG_F(ERROR, "Device %d: SDO write failed for %#04x:%02x! WKC: %d",
1089 position_, parameter.index, parameter.subindex, wkc);
1090 return false;
1091 }
1092
1093 return true;
1094 }
1095
1105
1114 void updatePdoMappings();
1115
1127 void logPdoMappings() const;
1128
1134 mm::comm::base::PdoMappings& getPdoMappings();
1135
1158 void updateOutputs();
1159
1181 void updateParametersFromInputs();
1182
1208 tl::expected<std::vector<uint8_t>, std::string> readFile(
1209 const std::string& filename,
1210 size_t maxFileSize = 1 * 1024 * 1024, // 1 MB default max file size
1211 int retries = 5,
1212 std::chrono::steady_clock::duration retryWait =
1213 std::chrono::milliseconds(100));
1214
1228 tl::expected<std::vector<std::uint8_t>, std::string> readSdo(
1229 uint16_t index, uint8_t subindex);
1230
1244 tl::expected<ec_ODlistt, std::string> readODList(
1245 int retries = 5, std::chrono::steady_clock::duration retryWait =
1246 std::chrono::milliseconds(100));
1247
1266 tl::expected<void, std::string> readODDescription(
1267 uint16_t item, ec_ODlistt& odList, int retries = 5,
1268 std::chrono::steady_clock::duration retryWait =
1269 std::chrono::milliseconds(100));
1270
1287 tl::expected<ec_OElistt, std::string> readOE(
1288 uint16_t item, ec_ODlistt& odList, int retries = 5,
1289 std::chrono::steady_clock::duration retryWait =
1290 std::chrono::milliseconds(100));
1291
1292 private:
1293 ecx_contextt& context_;
1294 const uint16_t position_;
1297 std::mutex mailboxMutex_;
1298 std::unordered_map<mm::comm::base::Parameter::Address,
1300 parametersMap_;
1303 pdoMappings_;
1304};
1305
1306class Master {
1307 public:
1314 explicit Master();
1315
1326 explicit Master(const std::string& iface);
1327
1379 void init(const std::string& iface);
1380
1391 void deinit();
1392
1399 ~Master();
1400
1410 Fieldbus& getFieldbus() const;
1411
1420 std::string getInterfaceName() const;
1421
1430 size_t getIoMapSize() const;
1431
1494 tl::expected<int, std::string> initSlaves();
1495
1507 const std::vector<std::unique_ptr<Slave>>& slaves() const;
1508
1518 inline int expectedWkc() const {
1519 return fieldbus_->context.grouplist[fieldbus_->group].outputsWKC * 2 +
1520 fieldbus_->context.grouplist[fieldbus_->group].inputsWKC;
1521 }
1522
1532 int roundtrip();
1533
1563
1574 bool start();
1575
1576 private:
1590 std::unique_ptr<Fieldbus> fieldbus_;
1591
1603 std::vector<std::unique_ptr<Slave>> slaves_;
1604};
1605}; // namespace mm::comm::soem
Represents a device parameter identified by index and subindex.
Definition base.h:533
std::pair< uint16_t, uint8_t > Address
Alias for a pair of uint16_t and uint8_t representing a parameter address.
Definition base.h:543
int roundtrip()
Performs a complete send/receive process data cycle on the fieldbus.
Definition soem.cc:1416
Master()
Default constructor for the Master class.
Definition soem.cc:1337
const std::vector< std::unique_ptr< Slave > > & slaves() const
Returns a reference to the list of slaves.
Definition soem.cc:1412
tl::expected< int, std::string > initSlaves()
Initializes the slave devices on the EtherCAT network.
Definition soem.cc:1389
void exchangeProcessDataAndUpdateParameters()
Exchanges process data with slaves and updates parameters based on the response.
Definition soem.cc:1421
size_t getIoMapSize() const
Returns the total size of the I/O map for the current group.
Definition soem.cc:1384
Fieldbus & getFieldbus() const
Returns a reference to the Fieldbus instance.
Definition soem.cc:1380
void init(const std::string &iface)
Initializes the fieldbus using the specified network interface.
Definition soem.cc:1344
std::string getInterfaceName() const
Retrieves the interface name used by the fieldbus.
Definition soem.cc:1382
void deinit()
Deinitializes the fieldbus and releases associated resources.
Definition soem.cc:1362
bool start()
Initializes and starts the fieldbus master.
Definition soem.cc:1444
~Master()
Destructor for the Master class.
Definition soem.cc:1378
int expectedWkc() const
Calculates the expected working counter (WKC) for the current fieldbus group.
Definition soem.h:1518
uint32_t productCode() const
Gets the Product Code of the slave device.
Definition soem.cc:838
uint32_t vendorId() const
Gets the Vendor ID of the slave device.
Definition soem.cc:834
std::unordered_map< mm::comm::base::Parameter::Address, mm::comm::base::Parameter > & parametersMap()
Returns a reference to the internal parameters map.
Definition soem.cc:1131
mm::comm::base::Parameter & findParameter(uint16_t index, uint8_t subindex)
Finds and returns a reference to a Parameter in the parameters map.
Definition soem.cc:1135
uint32_t revisionNumber() const
Gets the Revision Number of the slave device.
Definition soem.cc:842
T upload(uint16_t index, uint8_t subindex, bool refresh=true)
Uploads a parameter value from the device's object dictionary.
Definition soem.h:962
tl::expected< void, std::string > loadParameters(bool readValues=false)
Loads the parameters (object dictionary entries) from the EtherCAT slave device.
Definition soem.cc:943
void clearParameters()
Clears all loaded object dictionary parameters.
Definition soem.cc:1127
void logTxPdoMappedParameters()
Logs all mapped TxPDO parameters with their current values.
Definition soem.cc:1112
Slave(ecx_contextt &context, uint16_t position)
Constructs a Slave object with a given context and position.
Definition soem.cc:829
void logRxPdoMappedParameters()
Logs all mapped RxPDO parameters with their current values.
Definition soem.cc:1097
bool setState(int targetState, int timeoutMs=0, int intervalMs=100)
Attempts to set the slave to the specified EtherCAT state and optionally waits until it is reached.
Definition soem.cc:848
void logParameters() const
Logs all loaded object dictionary parameters.
Definition soem.cc:1091
int getState() const
Reads the current state of the slave directly from the device.
Definition soem.cc:846
uint16_t position() const
Gets the position of the slave.
Definition soem.cc:832
bool download(uint16_t index, uint8_t subindex, const T &value)
Downloads a value to the specified object dictionary entry via SDO.
Definition soem.h:1044
uint8_t type
Definition co_dictionary.h:1
const char ** name
Definition co_dictionary.h:7
uint8_t * value
Definition co_dictionary.h:9
uint16_t index
Definition co_dictionary.h:0
std::string makeParameterId(int index, int subindex)
Formats the given index and subindex into a parameter identifier string.
Definition base.h:1654
Definition soem.cc:40
mm::comm::base::PdoMappings readPdoMappings(ecx_contextt *context, uint16_t slave)
Read and parse all mapped PDO entries for a given slave.
Definition soem.cc:736
uint16_t getSlaveState(ecx_contextt *context, uint16_t slave)
Reads the current state of a specific EtherCAT slave directly from the device via an FPRD datagram.
Definition soem.cc:426
constexpr int kFoeTimeoutUs
Definition soem.h:29
void logPdoMappingEntries(const std::vector< mm::comm::base::PdoMappingEntry > &entries)
Logs PDO mapping entries grouped by PDO index.
Definition soem.cc:798
std::string convertSlaveStateToString(int state)
Converts a numeric EtherCAT state value into a human-readable string.
Definition soem.cc:441
constexpr int kSdoTimeoutUs
Definition soem.h:26
void transitionSlaves(ecx_contextt *context, const std::vector< uint16_t > &positions, uint16_t requiredState, uint16_t targetState, const char *targetName, std::chrono::steady_clock::duration timeout, std::chrono::steady_clock::duration resendInterval, std::function< void()> tick, std::function< bool()> shouldAbort)
Transitions multiple EtherCAT slaves to a target state using a single-threaded fire-then-poll pattern...
Definition soem.cc:470
std::string uiConfigWithDefaultPdoMapping
Default UI configuration used for PDO mapping.
Definition soem.h:59
void initFieldbus(std::unique_ptr< Fieldbus > &fieldbus, const std::string &iface)
Initializes a Fieldbus instance for EtherCAT communication.
Definition soem.cc:1304
void updateMailboxSyncManagersOnNextState(ecx_contextt *context, uint16_t slave, int targetState)
Updates the mailbox and sync manager (SM) configurations for an EtherCAT slave when transitioning to ...
Definition soem.cc:571
void logIoMap(uint8_t *ioMap, size_t totalBytes)
Logs the I/O map as a formatted hexadecimal string.
Definition soem.cc:819
void checkPdoMapping(ecx_contextt *context, uint16 slave)
Diagnoses and prints the PDO mapping for a given slave.
Definition soem.cc:344
void configureDetectedSmmModule(ecx_contextt *context, uint16_t slave)
Reads the detected SMM module ID from the slave device and configures the module identification objec...
Definition soem.cc:663
std::map< std::string, std::string > mapMacAddressesToInterfaces()
Maps MAC addresses to their corresponding network interface names.
Definition soem.cc:42
int setPdoMappingFromUiConfig(ecx_contextt *context, uint16 slave)
Sets PDO mapping for a specified EtherCAT slave using UI configuration.
Definition soem.cc:221
uint16 position
Definition soem.h:703
void logSlaveInfo(ecx_contextt *context, uint16 position)
Logs detailed information about a specific EtherCAT slave in JSON format.
Definition soem.cc:215
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(SlaveInfoMailbox, readLength, readOffset, supportedProtocols, writeLength, writeOffset) struct SlaveInfoSyncManager
Information about a slave's Sync Manager (SM) configuration.
Definition soem.h:472
SlaveInfo getSlaveInfo(ecx_contextt *context, uint16 position)
Definition soem.cc:163
std::vector< uint8_t > readSii(ecx_contextt *context, uint16 position)
Read the complete Slave Information Interface (SII) EEPROM from an EtherCAT slave device.
Definition soem.cc:693
bool setSlaveState(ecx_contextt *context, uint16_t slave, uint16_t targetState, std::chrono::steady_clock::duration timeout)
Transitions a single EtherCAT slave to targetState.
Definition soem.cc:563
Specialization of std::hash for std::pair<uint16_t, uint8_t>.
Definition util.h:612
Represents the mapped PDO entries for a slave device.
Definition base.h:175
Structure representing the Fieldbus configuration and context for EtherCAT communication.
Definition soem.h:394
boolean ecaterror
Definition soem.h:410
ec_idxstackT idxstack
Definition soem.h:409
ec_eepromFMMUt eepFMMU
Definition soem.h:416
ec_groupt grouplist[EC_MAXGROUP]
Definition soem.h:405
std::string iface
Definition soem.h:396
uint8 group
Definition soem.h:397
int slavecount
Definition soem.h:404
uint8 esibuf[EC_MAXEEPBUF]
Definition soem.h:406
uint32 esimap[EC_MAXEEPBITMAP]
Definition soem.h:407
int64 DCtime
Definition soem.h:411
ec_eepromSMt eepSM
Definition soem.h:415
ec_PDOassignt PDOassign[EC_MAX_MAPT]
Definition soem.h:413
uint8 map[4096]
Definition soem.h:401
ecx_contextt context
Definition soem.h:395
int roundtripTime
Definition soem.h:398
ec_PDOdesct PDOdesc[EC_MAX_MAPT]
Definition soem.h:414
ecx_portt port
Definition soem.h:402
ec_slavet slavelist[EC_MAXSLAVE]
Definition soem.h:403
ec_SMcommtypet SMcommtype[EC_MAX_MAPT]
Definition soem.h:412
ec_eringt elist
Definition soem.h:408
Information about a slave's mailbox configuration.
Definition soem.h:426
uint16_t writeOffset
Offset of the mailbox write area within the slave's memory.
Definition soem.h:469
uint16_t supportedProtocols
Supported mailbox protocols as a bitmask.
Definition soem.h:453
uint16_t readOffset
Offset of the mailbox read area within the slave's memory.
Definition soem.h:441
uint16_t readLength
Length of the mailbox read area (in bytes).
Definition soem.h:433
uint16_t writeLength
Length of the mailbox write area (in bytes).
Definition soem.h:461