#!/usr/bin/env perl
# PODNAME: itm_read_nocolor
# ABSTRACT: Simple ITM Reader (No Color)

use strict;
use warnings;
use AnyEvent;
use AnyEvent::Handle;
use AnyEvent::ITM;

$|=1;

my $file = shift or die qq{usage: $0 filename [command]};
my $buf = '';
my $cv = AE::cv;
my $handle = AnyEvent::ITM->handle($file, sub {
  my ( $handle, $itm ) = @_;
  return unless ref($itm) eq 'ITM::Instrumentation';
  $buf .= $itm->payload;

  # emit complete lines (handles \n and \r\n)
  while ((my $lf = index($buf, "\n")) != -1) {
    my $line = substr($buf, 0, $lf);
    $line =~ s/\r$//;               # strip CR in CRLF
    AnyEvent::ITM::_print_ts('>',$line);
    substr($buf, 0, $lf+1) = '';    # drop emitted + newline
  }
}, $cv);

$cv->cb(sub {
  my $cv = shift;
  AnyEvent::ITM::_print_ts('>',$buf) if length $buf;   # flush trailing partial line
  $buf = '';
  warn $cv->recv;
});

my $cmd;

if (scalar @ARGV > 0) {
  $cmd = AnyEvent::ITM->_run_cmd(@ARGV);
}

warn $cv->recv;

__END__

=pod

=encoding UTF-8

=head1 NAME

itm_read_nocolor - Simple ITM Reader (No Color)

=head1 VERSION

version 0.100

=head1 SYNOPSIS

  itm_read_nocolor openocd.itmlog

or directly run openocd with it:

  itm_read_nocolor openocd.itmlog openocd.itmlog openocd -c "program main.bin verify reset 0x08000000; reset run;"

In the openocd.cfg (for a 72MHz ARM)

  itm ports on
  tpiu config internal openocd.itmlog uart off 72000000

Best is to make a fifo for the exchange (more stable)

  mkfifo openocd.itmlog

=head1 DESCRIPTION

Displays ITM/SWO Debugging data.

=head1 SUPPORT

Repository

  https://github.com/Getty/p5-anyevent-itm
  Pull request and additional contributors are welcome

Issue Tracker

  https://github.com/Getty/p5-anyevent-itm/issues

=for :stopwords cpan testmatrix url bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan

=head1 SUPPORT

=head2 Source Code

The code is open to the world, and available for you to hack on. Please feel free to browse it and play
with it, or whatever. If you want to contribute patches, please send me a diff or prod me to pull
from your repository :)

L<https://github.com/Getty/p5-anyevent-itm>

  git clone https://github.com/Getty/p5-anyevent-itm.git

=head1 AUTHOR

Torsten Raudssus <torsten@raudss.us>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2015 by Torsten Raudssus.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
