Count amount of Rx CAN messages

This forum covers issues concerning multiple software products.
Post Reply
kepan13
Posts: 4
Joined: Tue 4. Aug 2020, 16:08

Count amount of Rx CAN messages

Post by kepan13 » Tue 4. Aug 2020, 16:14

Good day,

I am working on sending a configuration via CAN messages, where every message contains some sort of data. What's important is for the user sending the messages. Is knowing the amount of messages sent. I Tried adding a counter inside a CAN_UserRead() function, but when i sent 35 messages, the counter went up over 30 000. Im also using PCANBasic to create some python scripts to send the messages for me.

Is there any way to count the amount of messages sent / received in any good way? I am using a CAN-Router FD.

Regards, kepan13

M.Heidemann
Sales & Support
Sales & Support
Posts: 417
Joined: Fri 20. Sep 2019, 13:31

Re: Count amount of Rx CAN messages

Post by M.Heidemann » Tue 4. Aug 2020, 16:46

Hello kepan13,

You seem to count everything that can be read, including failed messages and status messages.

You only want to increment your counter on valid CAN messages:

Use the TPCANStatus "PCAN_ERROR_OK" to evaluate if the message was sucessfully received.

Also try to exclude message types you do not want to count, such as Status-messages and Error frames:

Code: Select all

PCAN_MESSAGE_ERRFRAME 0x40
PCAN_MESSAGE_STATUS 0x80
So only if your TPCANStatus returns "PCAN_ERROR_OK" upon reading and your message is a valid CAN message you increment your counter.


Please report back to me if this solved your issue.


Best Regards


Marvin

kepan13
Posts: 4
Joined: Tue 4. Aug 2020, 16:08

Re: Count amount of Rx CAN messages

Post by kepan13 » Wed 5. Aug 2020, 10:13

Hello Marvin,

I think it already checks that.

Code: Select all

if ( CAN_UserRead ( TARGET_BUS, &RxMsg) == CAN_ERR_OK){
	if (RxMsg.id == 0x2) {
		/*does something*/
		rxMsgCounter++;
	}
}
When i send 70 messages with id 0x2, the counter goes way too big.

Best regards

Kepan13

M.Heidemann
Sales & Support
Sales & Support
Posts: 417
Joined: Fri 20. Sep 2019, 13:31

Re: Count amount of Rx CAN messages

Post by M.Heidemann » Wed 5. Aug 2020, 11:05

Hello Kepan,

Do you actually have 2 channels available on your interface? Your description suggested that there at least 2 channels involved since you want to count message upon CAN-Read.

You cannot self-receive messages in PCANBasic, so messages sent from the same application and the same channel will not be caught by CAN-Read.

Can you explain your setup a bit more? Right now we do not know which hardware you are using, a PCAN-Router FD cannot be accessed via PCANBasic at all so it seems like you have at least one interface device involved (like a PCAN-USB FD, for example).

Best Regards

Marvin

kepan13
Posts: 4
Joined: Tue 4. Aug 2020, 16:08

Re: Count amount of Rx CAN messages

Post by kepan13 » Wed 5. Aug 2020, 11:12

Hello Marvin,

There are 2 channels available, but I am only using 1 while testing.

My setup is a PCAN-USB FD which is connected to the computer and also a CAN-Router FD.

I found this in another post on this forum

Code: Select all

from PCANBasic import *        ## PCAN-Basic library import
import threading               ## Threading-based Timer library
import win32event              ## Windows Events

# Instanciating the DLL
PCANBasic_Object = PCANBasic()

# Constants - adjust these as required

# Globals
g_pcanHandle = PCAN_NONEBUS
g_Terminated = False
g_readThread = None
g_receiveEventObject = None

def ConfigureChannel(channelToConnect):
    global g_receiveEventObject

    result = PCANBasic_Object.Initialize(channelToConnect, PCAN_BAUD_500K)
    if (result == PCAN_ERROR_OK):
        g_receiveEventObject = win32event.CreateEvent(None, 0, 0, None)
        # Configures the Receive-Event. 
        #
        result = PCANBasic_Object.SetValue(channelToConnect, PCAN_RECEIVE_EVENT, g_receiveEventObject)
        if(result != PCAN_ERROR_OK):
            print("Error configuring RECEIVE EVENT\n")

    return result == PCAN_ERROR_OK

def InitializeSample():    
    global g_Terminated
    global g_readThread
    global g_pcanHandle 

    if (ConfigureChannel(PCAN_USBBUS1)):
        g_pcanHandle = PCAN_USBBUS1
    else:
        if (ConfigureChannel(PCAN_USBBUS2)):
            g_pcanHandle = PCAN_USBBUS2
    
    if (g_pcanHandle == PCAN_NONEBUS):
        return False

    print("Channel " + hex(g_pcanHandle.value) + " initialized")
    g_readThread =  threading.Thread(None, CANReadThreadFunc)
    g_readThread.start()

    return True

def ExitHandler():
    PCANBasic_Object.Uninitialize(PCAN_NONEBUS)
    print("All channels removed\n")


def CANReadThreadFunc():
    global g_Terminated
    global g_pcanHandle
    global g_receiveEventObject

    try:        
        g_Terminated = False
        result = PCAN_ERROR_OK

        print("Starting to read....")
               
        while not g_Terminated:
            if win32event.WaitForSingleObject(g_receiveEventObject, 1000) == win32event.WAIT_OBJECT_0:
                ReadMessages()
            else:
                print ("......Queue empty")  

        PCANBasic_Object.SetValue(g_pcanHandle, PCAN_RECEIVE_EVENT, 0)
    except:
        print ("Error occurred while processing CAN data")  


def ReadMessages():
    global g_pcanHandle

    result = PCANBasic_Object.Read(g_pcanHandle)

    if result[0] == PCAN_ERROR_OK:
        print("message received!")
            
    return result[0]    


def main():
    global g_Terminated
    global g_readThread

    print("PCANBasic-Python test")
    print("startup..\n\n", end = "")

    if (InitializeSample()):
        option = -1
        print("\nHit any key at any moment to finalyse the test...\n\n")        
        input()

        g_Terminated = True
        g_readThread.join()
        ExitHandler()

main()
And I am wondering, maybe i can add another thread, a WriteThread, which would write my messages. And the ReadThread can "catch" them.

How does that sound?

Best regards,
Kepan13

M.Heidemann
Sales & Support
Sales & Support
Posts: 417
Joined: Fri 20. Sep 2019, 13:31

Re: Count amount of Rx CAN messages

Post by M.Heidemann » Wed 5. Aug 2020, 12:03

Hello Kepan,

The aforementioned PCANBasic example application uses a thread for reading using events:

Code: Select all

    ## Thread-Function used for reading PCAN-Basic messages
    ##
    def CANReadThreadFunc(self):
        try:        
            self.m_Terminated = False
        
            # Configures the Receive-Event. 
            #
            stsResult = self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_RECEIVE_EVENT, self.m_ReceiveEvent)
        
            if stsResult != PCAN_ERROR_OK:
                print ("Error: " + self.GetFormatedError(stsResult))                
            else:
                while not self.m_Terminated:
                    if win32event.WaitForSingleObject(self.m_ReceiveEvent, 50) == win32event.WAIT_OBJECT_0:
                        self.ReadMessages()
                
                # Resets the Event-handle configuration
                #
                self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_RECEIVE_EVENT, 0)
        except:
            print ("Error occurred while processing CAN data")        
 
If you prefer to, you can use another thread to write messages, yes.

By CAN-Router FD you are refering to a PCAN-Router FD? Keep in mind that the PCAN-Router FD can be configured using custom firmware, so for your application it might be
important to know what exactly the PCAN-Router FD is doing.

As you want to count transmitted messages, i would suggest to increment the counter on successful transmission of a frame.

My recommendation is to take a look at the example application provided with PCANBasic ("which you'll find in the "Samples" folder") and to check what exactly the "CAN-Router FD" is doing.

Best Regards

Marvin

Post Reply