This example shows how to use the KaCanOpen Core library. It starts the node via NMT, gets and sets values via SDO and determines device type and device name.
#include <chrono>
#include <vector>
#include <iostream>
#include "core.h"
int main() {
const uint8_t node_id = 2;
const std::string busname = "slcan0";
const std::string baudrate = "500K";
const uint16_t index = 0x6200;
const uint8_t subindex = 0x01;
const std::vector<uint8_t> data { 0x7F };
std::cout << "This is an example which shows the usage of the Core library." << std::endl;
bool found_node = false;
std::cout << "Registering a callback which is called when a device is detected via NMT..." << std::endl;
std::cout << "Device says it's alive! ID = " << (unsigned) new_node_id << std::endl;
if (new_node_id == node_id) {
found_node = true;
}
});
std::cout << "Starting Core (connect to the driver and start the receiver thread)..." << std::endl;
if (!core.
start(busname, baudrate)) {
std::cout << "Starting core failed." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Asking all devices to reset. You don't need to do that, but it makes"
<< " sure all slaves are in a reproducible state." << std::endl;
std::cout << "Giving the devices one second time to respond..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
if (!found_node) {
std::cout << "Node with ID " << (unsigned) node_id << " has not been found."<< std::endl;
return EXIT_FAILURE;
}
std::cout << "Asking the device to start up..." << std::endl;
std::cout << "Giving the devices one second time to boot up..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Writing to a dictionary entry (CANopen speech: \"download\")..." << std::endl;
core.
sdo.
download(node_id, index, subindex, data.size(), data);
std::cout << "Reading the device type (\"upload\" 0x1000)... Little-endian!" << std::endl;
std::vector<uint8_t> device_type = core.
sdo.
upload(node_id,0x1000,0x0);
for (uint8_t device_type_byte : device_type) {
std::cout << " byte 0x" << std::hex << (unsigned) device_type_byte << std::endl;
}
std::cout << "Reading the device name (\"upload\" 0x1008 - usually using segmented transfer)..." << std::endl;
std::vector<uint8_t> device_name = core.
sdo.
upload(node_id,0x1008,0x0);
std::string result(reinterpret_cast<char const*>(device_name.data()), device_name.size());
std::cout << " " << result << std::endl;
std::cout << "Finished." << std::endl;
return EXIT_SUCCESS;
}