#include "canbus.h" #define DEFAULT_GAP 200 /* ms */ #define MODE_RANDOM 0 #define MODE_INCREMENT 1 #define MODE_FIX 2 #define LOG( X ) m_pLog->Log( "canBus", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "canBus", this, _LOG_ERROR, X ) canBus::canBus():transportSerial(){ m_pLog = basicLogCollection::getInstance(); m_bConnected = false; m_bInitComplete = false; m_bFulDuplexCAN = false; m_bLoopbackDisabled = true;//false; m_bExtendedFrame = false; m_lPollTimeout = 0; m_sDevice = NULL; m_iNodeID = 0; /* bitrate switch implies CAN FD */ m_bBitrateSwitch = false; if(m_bBitrateSwitch) { m_bFulDuplexCAN = true; }; }; canBus::canBus(CSTR Device, int NodeID, int FilterID=0 ):transportSerial(){ m_pLog = basicLogCollection::getInstance(); m_bConnected = false; m_bInitComplete = false; setNodeID( NodeID ); m_bFilterID = false; setFilterID( FilterID ); m_sDevice = (CSTR) malloc( strlen(Device)+1); strcpy( m_sDevice, Device ); m_bFulDuplexCAN = false; m_bLoopbackDisabled = false; m_bExtendedFrame = false; m_lPollTimeout = 0; /* bitrate switch implies CAN FD */ m_bBitrateSwitch = false; if(m_bBitrateSwitch) { m_bFulDuplexCAN = true; }; m_bInitComplete = HW_init(); if( m_bInitComplete ) { #ifdef DEBUG char MsgBuffer[CLOG]; sprintf( MsgBuffer,"Init %s [0x%X] OK", m_sDevice, m_iNodeID ); LOG( MsgBuffer ); LOG("Starting"); #endif init(); }; }; canBus::~canBus(){ LOG("Destructor"); if( close( m_iInFID ) == -1) { switch( errno ) { case EBADF: LOG_ERROR( "Error Close In[FD is not a valid descriptor]!" ); break; case EINVAL: LOG_ERROR( "Error Close In[An invalid value was specified in how]!" ); break; case ENOTCONN: LOG_ERROR( "Error Close In[The specified socket is not connected]!" ); break; case ENOTSOCK: LOG_ERROR( "Error Close In[FD is a file, not a socket]!" ); break; default: { char Buffer[128]; sprintf( Buffer, "Error(%d) Close In[Unexpected]!", errno ); LOG_ERROR( Buffer ); }; }; }; if( close( m_iOutFID ) == -1) { switch( errno ) { case EBADF: LOG_ERROR( "Error Close Out[FD is not a valid descriptor]!" ); break; case EINVAL: LOG_ERROR( "Error Close Out[An invalid value was specified in how]!" ); break; case ENOTCONN: LOG_ERROR( "Error Close Out[The specified socket is not connected]!" ); break; case ENOTSOCK: LOG_ERROR( "Error Close Out[FD is a file, not a socket]!" ); break; default: { char Buffer[128]; sprintf( Buffer, "Error(%d) Close Out[Unexpected]!", errno ); LOG_ERROR( Buffer ); }; }; }; //waitThreadEnd( true ); LOG("Destructor Done"); }; bool canBus::setFilterID( int ID ){ if( ID > 0 ){ LOG("SET Filter ID"); m_sFilterID.can_id = ID; m_sFilterID.can_mask = 0x07FF; m_bFilterID = true; }; return m_bFilterID; }; bool canBus::setNodeID( int ID ){ if( ID > 0 ) { LOG("SET Node ID"); m_iNodeID = ID; return true; }; return false; }; bool canBus::HW_init(){ char mBuffer[CLOG]; if (strlen( m_sDevice ) >= IFNAMSIZ) { sprintf( mBuffer, "Name of CAN device '%s' is too long!", m_sDevice ); LOG_ERROR( mBuffer ); return false; } if(( m_iOutFID = socket( PF_CAN, SOCK_RAW, CAN_RAW )) < 0) { LOG_ERROR("Error while opening socket(OUT)"); return false; }; strncpy(ifr.ifr_name, m_sDevice, IFNAMSIZ - 1); ifr.ifr_name[IFNAMSIZ - 1] = '\0'; ifr.ifr_ifindex = if_nametoindex(ifr.ifr_name); if (!ifr.ifr_ifindex) { LOG_ERROR("if_nametoindex"); return false; }; if( ioctl( m_iOutFID, SIOCGIFINDEX, &ifr ) < 0) { LOG_ERROR("SIOCGIFINDEX"); return false; } addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; sprintf( mBuffer,"%s at index %d as Output", m_sDevice, ifr.ifr_ifindex); LOG( mBuffer ); /* disable default receive filter on this RAW socket */ /* This is obsolete as we do not read from the socket at all, but for */ /* this reason we can remove the receive list in the Kernel to save a */ /* little (really a very little!) CPU usage. */ setsockopt( m_iOutFID, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0); if( m_bLoopbackDisabled ){ int loopback = 0; setsockopt( m_iOutFID, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback) ); }; if( m_bFulDuplexCAN ){ int enable_canfd = 1; /* check if the frame fits into the CAN netdevice */ if( ioctl( m_iOutFID, SIOCGIFMTU, &ifr ) < 0){ LOG_ERROR("SIOCGIFMTU"); return false; }; if( ifr.ifr_mtu != CANFD_MTU ){ LOG_ERROR("CAN interface is not CAN FD capable - sorry."); return false; }; /* interface is ok - try to switch the socket into CAN FD mode */ if( setsockopt( m_iOutFID, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable_canfd, sizeof(enable_canfd))){ LOG_ERROR("error when enabling CAN FD support"); return false; }; } else{ int canfd_on = 1; /* try to switch the socket into CAN FD mode */ setsockopt( m_iOutFID, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)); }; if( bind( m_iOutFID, (struct sockaddr *)&addr, sizeof(addr)) < 0 ){ LOG_ERROR("Error in socket(OUT) bind"); return false; } if( m_lPollTimeout ){ m_sFDs.fd = m_iOutFID; m_sFDs.events = POLLOUT; } /*Receiver Part*/ if(( m_iInFID = socket( PF_CAN, SOCK_RAW, CAN_RAW ))<0){ LOG_ERROR("Error while opening socket(IN)"); return false; }; strncpy(ifr.ifr_name, m_sDevice, IFNAMSIZ - 1); ifr.ifr_name[IFNAMSIZ - 1] = '\0'; ifr.ifr_ifindex = if_nametoindex(ifr.ifr_name); if (!ifr.ifr_ifindex) { LOG_ERROR("if_nametoindex"); return false; }; if( ioctl( m_iInFID, SIOCGIFINDEX, &ifr ) < 0) { LOG_ERROR("SIOCGIFINDEX"); return false; } addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; sprintf( mBuffer,"%s at index %d as Input", m_sDevice, ifr.ifr_ifindex); LOG( mBuffer ); { /* try to switch the socket into CAN FD mode */ int canfd_on = 1; setsockopt( m_iInFID, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on)); } if( m_bFilterID ){ setsockopt( m_iInFID, SOL_CAN_RAW, CAN_RAW_FILTER, &m_sFilterID, sizeof(struct can_filter)); }; if( bind( m_iInFID, (struct sockaddr *)&addr, sizeof(addr)) < 0 ){ LOG_ERROR("Error in socket(IN) bind"); return false; } return true; }; int canBus::sendBlock( unsigned char *Data, int DataSize ){ struct canfd_frame frame; int mtu, maxdlen; LOG("SendBlock"); memset( &frame, 0, sizeof( canfd_frame )); if( m_bFulDuplexCAN ){ mtu = CANFD_MTU; maxdlen = CANFD_MAX_DLEN; if( m_bBitrateSwitch ) frame.flags |= CANFD_BRS; if( DataSize > CAN_MAX_DLEN ) DataSize = CAN_MAX_DLEN; /* ensure discrete CAN FD length values 0..8, 12, 16, 20, 24, 32, 64 */ DataSize = can_dlc2len(can_len2dlc(DataSize)); } else { mtu = CAN_MTU; maxdlen = CAN_MAX_DLEN; /* sanitize CAN 2.0 frame length */ if( DataSize > 8 ){ DataSize = 8; }; }; frame.len = DataSize; //frame.can_dlc = can_len2dlc( DataSize ); for(int index= 0; index < DataSize; index++) { frame.data[index] = Data[index]; }; /* set unused payload data to zero like the CAN driver does it on rx */ //if (frame.len < maxdlen) memset(&frame.data[frame.len], 0, maxdlen - frame.len); frame.can_id = m_iNodeID; if (m_bExtendedFrame ) { frame.can_id &= CAN_EFF_MASK; frame.can_id |= CAN_EFF_FLAG; } else frame.can_id &= CAN_SFF_MASK; //if( rtr_frame && !m_bFulDuplexCAN ) // frame.can_id |= CAN_RTR_FLAG; int RetVal; do{ RetVal = write( m_iOutFID, &frame, mtu ); if ( RetVal < 0) { if( errno != ENOBUFS ){ LOG_ERROR("Error write to Socket"); return -1; }; /*if( !m_lPollTimeout ){ LOG_ERROR("Error write to Socket"); return -1; } if( m_lPollTimeout ){ // wait for the write socket (with timeout) if( poll( &m_sFDs, 1, m_lPollTimeout ) < 0 ){ LOG_ERROR("Error Poll"); return -1; }; };*/ } else if( RetVal < mtu ){ LOG_ERROR("write: incomplete CAN frame"); return -1; }; } while( ( RetVal < 0 ) && (errno == EINTR || errno == EWOULDBLOCK ) ); #ifdef _DEBUG_SERIAL_COMMUNICATION_ char MsgBuffer[CLOG]; sprintf( MsgBuffer, "Sent %d[%d] byte(s) of %d", RetVal, mtu, DataSize ); LOG( MsgBuffer ); #endif return RetVal; }; int canBus::recptBlock( unsigned char *Buffer, int *BufferLength ){ struct iovec iov; struct msghdr msg; struct cmsghdr *cmsg; char ctrlmsg[ CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32)) ]; struct can_filter *rfilter; can_err_mask_t err_mask; struct canfd_frame frame; int RetVal, maxdlen; /* these settings are static and can be held out of the hot path */ iov.iov_base = &frame; msg.msg_name = &addr; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = &ctrlmsg; /* these settings may be modified by recvmsg() */ iov.iov_len = sizeof( canfd_frame ); msg.msg_namelen = sizeof( sockaddr_can ); msg.msg_controllen = sizeof(ctrlmsg); msg.msg_flags = 0; do{ //LOG("<[|]>"); RetVal = recvmsg( m_iInFID, &msg, MSG_DONTWAIT );//0 ); if( RetVal < 0){ if ( errno == ENETDOWN) { LOG_ERROR( "interface down" ); return -1; }; }; if( RetVal > 0 ) { if( (size_t)RetVal == CAN_MTU ) maxdlen = CAN_MAX_DLEN; else if ((size_t)RetVal == CANFD_MTU ) maxdlen = CANFD_MAX_DLEN; else { LOG_ERROR( "read: incomplete CAN frame"); return -1; }; } SLEEP(1); //LOG("<[-]>"); } while (RetVal < 0 && errno == EINTR ); #ifdef _DEBUG_SERIAL_COMMUNICATION_ if( RetVal > -1 ){ LOG("ReceivedBlock"); char MsgBuffer[CLOG]; if( RetVal > 1 || RetVal == 0 ) { sprintf( MsgBuffer, "Received %d bytes", RetVal ); } else { sprintf( MsgBuffer, "Received 1 byte"); }; LOG( MsgBuffer ); }; #endif if( RetVal > 0) { *BufferLength = frame.len; for(int index = 0; index < frame.len; index++ ) { Buffer[index] = frame.data[index]; }; RetVal = *BufferLength; return RetVal; }; *BufferLength = 0; if( RetVal == -1) return 0; if( RetVal == 0 ){ errno = 0; return 0; }; /* r < -1, should never happen. */ //errno = EIO; return 0; }; #undef LOG #undef LOG_ERROR /* int main(void) { int s; int nbytes; struct sockaddr_can addr; struct can_frame frame; struct ifreq ifr; const char *ifname = "vcan0"; if((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) { perror("Error while opening socket"); return -1; } strcpy(ifr.ifr_name, ifname); ioctl(s, SIOCGIFINDEX, &ifr); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; printf("%s at index %d\n", ifname, ifr.ifr_ifindex); if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("Error in socket bind"); return -2; } frame.can_id = 0x123; frame.can_dlc = 2; frame.data[0] = 0x11; frame.data[1] = 0x22; nbytes = write(s, &frame, sizeof(struct can_frame)); printf("Wrote %d bytes\n", nbytes); return 0; } */