Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use select to reduce CPU usage. #361

Open
wants to merge 2 commits into
base: ros2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion dynamixel_sdk/src/dynamixel_sdk/port_handler_linux.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,41 @@ int PortHandlerLinux::getBytesAvailable()

int PortHandlerLinux::readPort(uint8_t *packet, int length)
{
return read(socket_fd_, packet, length);
if (packet_timeout_ != 0)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(socket_fd_, &readfds);
struct timeval timeout;
timeout.tv_sec = 0;
// packet_timeout_ is in milliseconds
timeout.tv_usec = packet_timeout_ * 1000;
int select_ret = ::select(socket_fd_ + 1, &readfds, nullptr, nullptr, &timeout);
if (select_ret < 0)
{
// Some kind of error happened; just return 0
return 0;
}
else if (select_ret == 0)
{
// timeout happened; return 0
return 0;
}
else
{
if (!FD_ISSET(socket_fd_, &readfds))
{
// We didn't see the file descriptor we expected; just return 0
return 0;
}

return read(socket_fd_, packet, length);
}
}
else
{
return read(socket_fd_, packet, length);
}
}

int PortHandlerLinux::writePort(uint8_t *packet, int length)
Expand Down
7 changes: 6 additions & 1 deletion dynamixel_sdk/src/dynamixel_sdk/protocol1_packet_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -441,8 +441,13 @@ int Protocol1PacketHandler::readTxRx(PortHandler *port, uint8_t id, uint16_t add
uint8_t txpacket[8] = {0};
uint8_t *rxpacket = (uint8_t *)malloc(RXPACKET_MAX_LEN);//(length+6);

if (id >= BROADCAST_ID)
if (rxpacket == NULL)
return result;

if (id >= BROADCAST_ID) {
free(rxpacket);
return COMM_NOT_AVAILABLE;
}

txpacket[PKT_ID] = id;
txpacket[PKT_LENGTH] = 4;
Expand Down
4 changes: 3 additions & 1 deletion dynamixel_sdk/src/dynamixel_sdk/protocol2_packet_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -712,8 +712,10 @@ int Protocol2PacketHandler::readTxRx(PortHandler *port, uint8_t id, uint16_t add
if (rxpacket == NULL)
return result;

if (id >= BROADCAST_ID)
if (id >= BROADCAST_ID) {
free(rxpacket);
return COMM_NOT_AVAILABLE;
}

txpacket[PKT_ID] = id;
txpacket[PKT_LENGTH_L] = 7;
Expand Down