0

I have a script that reads CAN bus signals and displays them to screen but I need to add a signal counter and frequency.

So I need to count how many times has this $id appeared so far and how many milliseconds ago did was it added to the hash table.

#!/usr/bin/perl -w

use strict;

open my $can_bus, "./receivetest |"
    or die "Couldn't read from CAN bus: $!";

my %last_value;
while (<$can_bus>) {
   if( /^(........:...) (........) (.*)$/ )
   {

        my ($something, $id, $payload) = ($1,$2,$3);
        $last_value{ $id } = $payload;

        system('clear'); #clear screen

        #Print Table
        for my $id (sort keys %last_value) {
            print "$id\t $last_value{ $id }\n";
            }
    }
    else {
        warn "ignore unknown line: ";
        warn $_;
    }
}

This is my code so far.

Jalcock501
  • 389
  • 2
  • 6
  • 18

1 Answers1

1

You can store different values for one $id key if you expand your hash by adding more keys after the $id key. For example:

if (defined $last_value{ $id } ){

    $last_value{ $id }{COUNT} += 1;

    my $time_diff = $now_milli - $last_value{ $id }{TIME};

    $last_value{ $id }{TIME}     = $now_milli;
    $last_value{ $id }{DIFF}     = $time_diff;
    $last_value{ $id }{PAYLOAD}  = $payload;

}else{

    $last_value{ $id }{TIME}     = $now_milli;
    $last_value{ $id }{DIFF}     = "NA";
    $last_value{ $id }{COUNT}    = 1;
    $last_value{ $id }{PAYLOAD}  = $payload;

}

To get current time in milliseconds you can use Time::HiRes qw/gettimeofday/ which is a part of Perl core:

use Time::HiRes qw/gettimeofday/;

my $now_milli = 1000 * gettimeofday();

Finally, to print information stored in the %last_value hash:

foreach my $id (keys %last_value){

    print "ID: ", $id, "\n";

    print "Count: ",          $last_value{$id}{COUNT},   "\n";
    print "Time from last: ", $last_value{$id}{DIFF},    "\n";
    print "Payload: ",        $last_value{$id}{PAYLOAD}, "\n";

}
Sergei
  • 260
  • 3
  • 11