99e1703db13102d522e4a10a100cab8e472b83f4
[linux-gpio-pinout] / gpio.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use autodie;
5 use Data::Dump qw(dump);
6 use Getopt::Long;
7
8 my $opt_svg = 0;
9 my $opt_alt = 0;
10 my $opt_invert = 0;
11 my $opt_vertical = 0;
12 my $opt_horizontal = 0;
13 my $opt_edge = 0;
14 my $opt_middle = 0;
15 my $opt_zebra = 0;
16 my $opt_lines = 0;
17 my $opt_read = '';
18 my $opt_pins = '';
19 my $opt_color = 0;
20 my $opt_pinmux = 0;
21 GetOptions(
22         'svg!' => \$opt_svg,
23         'alt!' => \$opt_alt,
24         'invert!' => \$opt_invert,
25         'vertical-flip!' => \$opt_vertical,
26         'horizontal-flip!' => \$opt_horizontal,
27         'edge-pins!' => \$opt_edge,
28         'middle-pins!' => \$opt_middle,
29         'zebra!' => \$opt_zebra,
30         'lines!' => \$opt_lines,
31         'read=s' => \$opt_read,
32         'pins=s' => \$opt_pins,
33         'color' => \$opt_color,
34         'pinmux' => \$opt_pinmux,
35 );
36
37 # svg font hints
38 my $font_w = 1.67; # < 2.54, font is not perfect square
39 my $font_b = 2.10; # font baseline position
40
41 $opt_read .= '/' unless $opt_read =~ m/\/$/;
42
43 sub slurp {
44         open(my $fh, '<', $opt_read . shift);
45         local $/ = undef;
46         <$fh>;
47 }
48
49 my $pins;
50 my $include = 0;
51
52 my $model = slurp('/proc/device-tree/model');
53 $model =~ s/\x00$//; # strip kernel NULL
54 warn "# model [$model]";
55 if ( $opt_pins ) {
56         $model = $opt_pins;
57         $model =~ s/^.*\///; # strip dir
58         $model =~ s/\..+$//; # strip extension
59         $include = 1;
60         warn "# $opt_pins model [$model] $include";
61 }
62 warn "# $opt_pins model [$model] $include";
63
64 OPEN_PINS_AGAIN:
65 open(DATA, '<', $opt_pins) if $opt_pins;
66
67 my @lines;
68 my $line_i = 0;
69
70 while(<DATA>) {
71         chomp;
72         if ( m/^#\s(.+)/ ) {
73                 if ( $model =~ m/$1/ ) {
74                         $include = 1;
75                 } else {
76                         $include = 0;
77                 }
78                 warn "MODEL [$1] == [$model] include: $include\n";
79         } elsif ( $include ) {
80                 push @{ $pins->{$1} }, $line_i while ( m/\t\s*(\w+\d+)/g );
81
82                 push @lines, $_;
83
84                 $line_i++;
85         } else {
86                 warn "IGNORE: [$_]\n";
87         }
88 }
89
90 if ( ! $opt_pins && ! $pins ) {
91         my $glob = $model;
92         $glob =~ s/^(\w+).*$/$1/;
93         my @pins = glob "pins/${glob}*";
94         die "pins/${glob} NOT FOUND for this board, please create one and contribute" unless @pins;
95         warn "# possible pins: ",dump( \@pins );
96         $opt_pins = $pins[0];
97         goto OPEN_PINS_AGAIN;
98 }
99
100 die "add pin definition for # $model" unless $pins;
101
102 #warn "# lines ",dump( \@lines );
103 warn "# pins ",dump($pins);
104
105 my $serial_tty;
106 foreach (
107         glob($opt_read . '/sys/devices/platform/soc*/*.serial/tty/tty*'),       # 4.x
108         glob(            '/sys/devices/soc.*/*.uart/tty/tty*')                  # 3.10
109 ) {
110         my @v = split(/\//, $_);
111         $serial_tty->{ $v[-3] } = $v[-1];
112 }
113 warn "# serial_tty = ",dump($serial_tty);
114
115
116 my $pin_function;
117 my $device;
118 my $pin;
119 my $function;
120
121 sub annotate_pin {
122         my ($pin, $note) = @_;
123         if ( $pins->{$pin} ) {
124                 foreach my $line ( @{$pins->{$pin}} ) {
125                         my $t = $lines[$line];
126                         if ( $opt_svg ) {
127                                 $t =~ s/$pin/$note/;
128                         } else {
129                                 $t =~ s/$pin/$pin $note/ || warn "can't find $pin in [$t]";
130                         }
131                         $lines[$line] = $t;
132                         warn "# $line: $lines[$line]\n";
133                 }
134         } else {
135                 warn "IGNORED: pin $pin function $note\n";
136         }
137 }
138
139 open(my $fh, '<', $opt_read . '/sys/kernel/debug/pinctrl/pinctrl-maps');
140 while(<$fh>) {
141         chomp;
142         if ( m/^device (\S+)/ ) {
143                 $device = $1;
144                 if ( my $replace = $serial_tty->{$device} ) {
145                         $device = $replace; # replace serial hex with kernel name
146                 } else {
147                         $device =~ s/^[0-9a-f]*\.//; # remove hex address
148                 }
149         } elsif ( m/^group (\w+\d+)/ ) {
150                 $pin = $1;
151
152         } elsif ( m/^function (\S+)/ ) {
153                 $function = $1;
154         } elsif ( m/^$/ ) {
155                 if ( $device && $pin && $function ) {
156                         push @{ $pin_function->{$pin} }, "$device $function";
157
158                         annotate_pin $pin, "[$device $function]";
159                 } else {
160                         warn "missing one of ",dump( $device, $pin, $function );
161                 }
162
163                 $device = undef;
164                 $pin = undef;
165                 $function = undef;
166
167         }
168 }
169
170 warn "# pin_function = ",dump($pin_function);
171
172
173 # insert kernel gpio info
174 my $linux_gpio_name;
175 open(my $pins_fh, '<', (glob "/sys/kernel/debug/pinctrl/*/pins")[0]);
176 while(<$pins_fh>) {
177         if ( m/^pin (\d+) \(([^\)]+)\)/ ) {
178                 $linux_gpio_name->{$1} = $2;
179         }
180 }
181 warn "# linux_gpio_name = ",dump( $linux_gpio_name );
182
183
184 my $gpio_debug;
185 open(my $gpio_fh, '<', '/sys/kernel/debug/gpio');
186 while(<$gpio_fh>) {
187         if (m/|/ ) {
188                 s/^\s+//;
189                 s/\s+$//;
190                 my @l = split(/\s*[\(\|\)]\s*/, $_);
191                 warn "XXX ", dump( \@l );
192                 if ( $l[0] =~ m/gpio-(\d+)/ ) {
193                         if ( my $pin = $linux_gpio_name->{$1} ) {
194                                 $gpio_debug->{ $pin } = $l[2];
195                                 $l[3] =~ s/\s\s+/ /g;
196                                 annotate_pin $pin, qq{"$l[2]" $l[3]};
197                         } else {
198                                 warn "FIXME can't find $1 in ",dump( $linux_gpio_name );
199                         }
200                 }
201         }
202
203 }
204 warn "# gpio_debug = ",dump( $gpio_debug );
205
206
207
208 my $have_sunxi_pio = `which sunxi-pio`;
209 if ( $have_sunxi_pio ) {
210
211 open(my $pio, '-|', 'sunxi-pio -m print');
212 while(<$pio>) {
213         chomp;
214         s/[<>]+/ /g;
215         my @p = split(/\s+/,$_);
216         warn "# pio ",dump(\@p);
217         # annotate input 0 and output 1 pins
218 #       annotate_pin $p[0], ( $p[1] ? 'O' : 'I' ) . ':' . $p[4] if $p[1] == 0 || $p[1] == 1;
219         my $pin = shift @p;
220         annotate_pin $pin, join(' ',@p) if ! $opt_svg;
221 }
222 close($pio);
223
224 } # have_sunxi_pio
225
226 my $have_raspi_gpio = `which raspi-gpio`;
227 if ( $have_raspi_gpio ) {
228
229 my @gpio_pins;
230
231 open(my $pio, '-|', 'raspi-gpio get');
232 while(<$pio>) {
233         chomp;
234         if ( m/^\s*GPIO (\d+): (.+)/ ) {
235                 my $pin = 'gpio' . $1 * 1; # we need * 1 to strip leading zero
236                 push @gpio_pins, $1;
237                 annotate_pin $pin, $2 if ! $opt_svg;
238         }
239 }
240 close($pio);
241
242 open(my $pio, '-|', 'raspi-gpio funcs '.join(',',@gpio_pins));
243 while(<$pio>) {
244         chomp;
245         s/,\s/ /g;
246         if (m/^(\d+)\s+(.*)/) {
247                 annotate_pin 'gpio'.$1,"($2)" if $opt_alt;
248         }
249 }
250 close($pio);
251
252 } # have_raspi_gpio
253
254
255 my $pinmux;
256 my $pinmux_path = (glob("/sys/kernel/debug/pinctrl/*/pinmux-functions"))[0];
257 if ( $opt_pinmux && -e $pinmux_path ) {
258         open(my $mux, '<', $pinmux_path);
259         while(<$mux>) {
260                 chomp;
261                 if ( m/function: (\w+), groups = \[ (.*) \]/ ) {
262                         my ( $func, $pins ) = ( $1, $2 );
263                         foreach ( split(/\s+/,$pins) ) {
264                                 push @{ $pinmux->{$_} }, $func;
265                         }
266                 } else {
267                         warn "IGNORED [$pinmux_path] [$_]\n";
268                 }
269         }
270
271         foreach my $pin ( keys %$pinmux ) {
272                 if ( exists $pins->{$pin} ) {
273                         annotate_pin $pin, '{' . join(' ', @{$pinmux->{$pin}}) . '}';
274                 } else {
275                         warn "IGNORED mux on $pin\n";
276                 }
277         }
278
279         warn "# pinmux = ",dump( $pinmux );
280 }
281
282
283
284 my @max_len = ( 0,0,0,0 );
285 my @line_parts;
286
287 shift(@lines) while ( ! $lines[0] );    # remove empty at beginning
288 pop(@lines) while ( ! $lines[-1] );     # remove empty at end
289
290 foreach my $line (@lines) {
291         if ( $line =~ m/^#/ ) {
292                 push @line_parts, [ $line ] unless $opt_svg && $line =~ m/^###+/; # SVG doesn't display 3rd level comments
293                 next;
294         }
295         $line =~ s/\[(\w+)\s+(\w+)\] \[\1\s+(\w+)\]/[$1 $2 $3]/g; # compress kernel annotation with same prefix
296         $line =~ s/(\[(?:uart\d*|serial|tty\w+))([^\t]*\]\s[^\t]*(rx|tx)d?)/$1 $3$2/gi;
297         $line =~ s/(\[i2c)([^\t]*\]\s[^\t]*(scl?k?|sda))/$1 $3$2/gi;
298         $line =~ s/(\[spi)([^\t]*\]\s[^\t]*(miso|mosi|s?clk|c[se]\d*))/$1 $3$2/gi;
299         $line =~ s/\s*\([^\)]+\)//g if ! $opt_alt;
300
301         # shorten duplicate kernel device/function
302         $line =~ s/\[serial (\w+) (uart\d+)\]/[$2 $1]/g;
303         $line =~ s/\[(\w+) (\w+) \1(\d+)\]/[$1$3 $2]/g;
304
305         $line =~ s/\[(\w+)\s+([^\]]+)\s+\1\]/[$1 $2]/g; # duplicate
306
307         my @v = split(/\s*\t+\s*/,$line,4);
308         @v = ( $v[2], $v[3], $v[0], $v[1] ) if $opt_horizontal && $v[2];
309
310         push @line_parts, [ @v ];
311         foreach my $i ( 0 .. 3 ) {
312                 next unless exists $v[$i];
313                 next if $v[$i] =~ m/^#/; # don't calculate comments into max length
314                 my $l = length($v[$i]);
315                 $max_len[$i] = $l if $l > $max_len[$i];
316         }
317 }
318
319 warn "# max_len = ",dump( \@max_len );
320 warn "# line_parts = ",dump( \@line_parts );
321
322 #print "$_\n" foreach @lines;
323
324 my $x = 20.00; # mm
325 my $y = 20.00; # mm
326
327 if ( $opt_svg ) {
328         print qq{<?xml version="1.0" encoding="UTF-8" standalone="no"?>
329 <svg
330    xmlns:dc="http://purl.org/dc/elements/1.1/"
331    xmlns:cc="http://creativecommons.org/ns#"
332    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
333    xmlns:svg="http://www.w3.org/2000/svg"
334    xmlns="http://www.w3.org/2000/svg"
335    xmlns:xlink="http://www.w3.org/1999/xlink"
336    id="svg8"
337    version="1.1"
338    viewBox="0 0 210 297"
339    height="297mm"
340    width="210mm">
341
342
343 <g id="layer1">
344
345         }; # svg, insert rest of rect
346
347         print qq{<rect x="0" y="0" width="210" height="297" style="fill:#000000" id="high-contrast"/>} if $opt_invert;
348 }
349
350 my @later;
351
352 my $cols = {    # foreground background
353         txt  => [ '#000000', '#ffffff' ],
354         pins => [ '#ffffff', '#ff00ff' ],
355         vcc  => [ '#ff0000', '#ffff00' ],
356         gnd  => [ '#000000', '#00ffff' ],
357         i2c  => [ '#008800', '#ffcccc' ],
358         serial=>[ '#000088', '#ccffcc' ],
359         spi  => [ '#880000', '#ccccff' ],
360 };
361
362 sub swap_cols {
363         my $swap = shift;
364         die "$swap not found in ",dump($cols) unless $cols->{$swap};
365         my ( $c1, $c2 ) = @{ $cols->{$swap} };
366         $cols->{$swap} = [ $c2, $c1 ];
367 }
368
369 swap_cols 'txt' if $opt_invert;
370         
371
372 sub svg_style {
373         my ($name,$x,$y,$col) = @_;
374
375         return '' unless $opt_color;
376
377         $y -= $font_b; # shift box overlay to right vertical position based on font baseline
378
379         sub rect {
380                 my ($x,$y,$col,$fill) = @_;
381                 print qq{<rect x="$x" y="$y" height="2.54" width="}, $max_len[$col] * $font_w, qq{" style="fill:$fill;stroke:#ffffff;stroke-width:0.10" />\n};
382
383         }
384
385         if ( $name =~ m/^(\d+)$/ ) { # pins
386                 my $pin = $1;
387                 my ( $fg, $bg ) = @{ $cols->{pins} };
388                 if ( $pin == 1 ) {
389                         my $w  = $max_len[$col]*$font_w - 0.1;
390                         my $cx = $x + $w;
391                         my $cy = $y + 2.54;
392                         #print qq{<polygon points="$x,$y $cx,$y $x,$cy $x,$y" stroke="$fg" stroke-width="0.25" fill="$bg" />};
393                         #print qq{<polygon points="$x,$cy $cx,$cy $cx,$y $x,$cy" stroke="$bg" stroke-width="0.25" fill="$fg" />};
394                         print qq{<rect x="$x" y="$y" width="$w" height="2.54" stroke="$fg" stroke-width="0.3" fill="$bg" />};
395                         my ( $fg, $bg ) = @{ $cols->{txt} };
396                         print qq{<rect x="$x" y="$y" width="$w" height="2.54" rx="1" ry="1" stroke="$fg" stroke-width="0.3" fill="$bg" />};
397                 } else {
398                         rect $x,$y,$col,$fg;
399                 }
400                 return qq{ style="fill:$bg"};
401         }
402
403         if ( $name =~ m/(VCC|3V3|3.3V|5v)/i ) {
404                 my ($fg,$bg) = @{ $cols->{vcc} };
405                 rect $x,$y,$col,$bg;
406                 return qq{ style="fill:$fg"};
407         } elsif ( $name =~ m/(G(ND|Round)|VSS|0v)/i ) {
408                 my ($fg,$bg) = @{ $cols->{gnd} };
409                 rect $x,$y,$col,$bg;
410                 return qq{ style="fill:$fg"};
411         } elsif ( $name =~ m/\[(\w+)/ ) { # kernel
412                 my $dev = $1;
413                 my ($fg,$bg) = @{ $cols->{txt} };
414                 $dev = 'serial' if $dev =~ m/^tty/;
415                 ($fg,$bg) = @{ $cols->{$dev} } if exists $cols->{$dev};
416                 rect $x,$y,$col,$bg;
417                 return qq{ style="fill:$fg"};
418         } else {
419                 my ( $fg, $bg ) = @{ $cols->{txt} };
420                 rect $x,$y,$col,$bg;
421                 #return qq{ style="fill:$fg"};
422                 return '';
423         }
424 }
425
426 my $alt_col = 0;
427
428 my @cols_order = ( 0,1,2,3 );
429 my @cols_align = ( '','-','','-' ); # sprintf prefix
430
431 my @cols_shuffle = @cols_order;
432
433 if ( $opt_edge ) {
434         # pins outside on the right
435         @cols_shuffle = ( 0,1,3,2 ) if $opt_edge;
436         @cols_align = ( '-','-','','' );
437 } elsif ( $opt_middle ) {
438         # pins in middle
439         @cols_shuffle = ( 1,0,2,3 );
440         @cols_align = ( '','','-','-' );
441 }
442
443 sub cols_shuffle {
444         my ( $what, $order ) = @_;
445         my $new = [];
446         foreach my $i ( 0 .. $#$what ) {
447                 $new->[$i] = $what->[ $order->[$i] ];
448         }
449         warn "# cols_shuffle what=",dump($what)," order=",dump($order)," new=",dump($new);
450         return @$new;
451 }
452
453 @cols_order = cols_shuffle( \@cols_order, \@cols_shuffle );
454 @max_len    = cols_shuffle( \@max_len,    \@cols_shuffle );
455
456 warn "# cols_order = ",dump( \@cols_order );
457 warn "# cols_align = ",dump( \@cols_align );
458
459 my $fmt = "%$cols_align[0]$max_len[0]s %$cols_align[1]$max_len[1]s %$cols_align[2]$max_len[2]s %$cols_align[3]$max_len[3]s\n";
460
461
462 # cut marks
463 my ($fg,$bg) = @{ $cols->{txt} };
464 my $line_fmt = qq{<line x1="%s" y1="%s" x2="%s" y2="%s" style="stroke:$fg;stroke-width:0.10;fill:$bg" />\n};
465
466 my @cut_marks;
467 sub cut_mark {
468         my ($x,$y) = @_;
469         return unless $opt_svg;
470         push @cut_marks, sprintf($line_fmt, $x-5, $y-$font_b,   $x+5, $y-$font_b);
471         push @cut_marks, sprintf($line_fmt, $x,   $y-$font_b-5, $x,   $y-$font_b+5);
472 }
473 #cut_mark $x, $y;
474 my $max_x = $x;
475 $max_x += $max_len[$_] * $font_w foreach ( 0 .. 3 );
476 #cut_mark $max_x, $y;
477
478 sub line {
479         my ($x,$y,$max_x) = @_;
480         push @cut_marks, sprintf($line_fmt, $x, $y-$font_b, $max_x, $y-$font_b);
481 }
482
483
484 my $last_cut_mark = 0;
485
486 sub connector {
487         my ( $from, $to ) = @_;
488         warn "# connector $from - $to ",dump( $line_parts[$from], $line_parts[$to] );
489         if ( $opt_vertical ) {
490                 foreach my $i ( 0 .. int(($to-$from)/2) ) {
491                         my $t = $line_parts[$from + $i];
492                                 $line_parts[$from + $i] = $line_parts[$to - $i];
493                                                           $line_parts[$to - $i] = $t;
494                 }
495         }
496 }
497
498 my $from;
499 my $to;
500 foreach my $i ( 0 .. $#line_parts ) {
501         next if $line_parts[$i]->[0] =~ m/^###/;
502         if (exists $line_parts[$i]->[1]) {
503                 if (! $from) {
504                         $from = $i;
505                 } else {
506                         $to = $i;
507                 }
508         } elsif ($from && $to) {
509                 connector $from => $to;
510                 $from = $to = undef;
511         }
512 }
513 connector $from => $to if $from && $to;
514
515 foreach my $i ( 0 .. $#line_parts ) {
516 #       $i = $#line_parts - $i if $opt_vertical;
517         my $line = $line_parts[$i];
518
519         if ( $opt_svg ) {
520
521                 # not a minimal two column pin description
522                 if ( ! exists $line->[1] ) {
523                         $last_cut_mark = 1 if $line->[0] =~ m/^##/; # skip comments
524
525                         # before first empty line
526                         if ( $last_cut_mark == 0 ) {
527                                 cut_mark $x, $y;
528                                 cut_mark $max_x, $y;
529                                 $last_cut_mark = 1;
530                                 line $x, $y, $max_x if $opt_lines;
531                                 $y += 15; # make spacing between pinouts
532                         }
533                 } elsif ( $last_cut_mark ) {
534                         # first full line
535                         cut_mark $x, $y;
536                         cut_mark $max_x, $y;
537                         $last_cut_mark = 0;
538                 } else {
539                         #warn "CUTMARK no magic";
540                 }
541
542                 line $x, $y, $max_x if $opt_lines && exists $line->[1];
543
544                 my ($fg,$bg) = @{ $cols->{txt} };
545                 my $tspan = qq{<tspan x="$x" y="$y" style="line-height:2.54;fill:$fg;stroke:none;">\n};
546
547                 my $x_pos = $x;
548                 foreach my $i ( 0 .. $#cols_order ) {
549                         my $order = $cols_order[$i];
550                         next unless $line->[$order];
551
552                         my $text_anchor = 'middle';
553                         my $len = $max_len[$i];
554                         my $x2 = $x_pos + ( $len * $font_w ) / 2;
555                         # is this comment?
556                         if ( $#$line == 0 && $line->[$order] =~ s/^#+s*// ) {
557                                 # comment, center over whole width
558                                 $len = length($line->[$order]);
559                                 $x2 = $x + (($max_x-$x)/2); # middle
560                                 $tspan .= qq{\t<tspan x="$x2" text-anchor="$text_anchor"}.sprintf( '>%' . $cols_align[$i] . $len . 's</tspan>', $line->[0]);
561                         } else {
562                                 $tspan .= qq{\t<tspan x="$x2" text-anchor="$text_anchor"}.svg_style($line->[$order],$x_pos,$y,$i).sprintf( '>%' . $cols_align[$i] . $len . 's</tspan>', $line->[$order]);
563                         }
564                         $x_pos += $len * $font_w;
565                 }
566
567                 $tspan .= qq{\n</tspan>\n};
568                 push @later,sprintf $tspan, @$line;
569                 $y += 2.54;
570
571                 # swap pin colors for line stripe
572                 if ( $opt_zebra ) {
573                         swap_cols $_ foreach qw( pins txt );
574                 } else {
575                         swap_cols 'pins';
576                 }
577
578         } else {
579
580                 if ( $#$line == 0 ) {
581                         print $line->[0], "\n";
582                 } else {
583                         push @$line, '' while ($#$line < 3); # fill-in single row header
584                         printf $fmt, map { $line->[$_] } @cols_order;
585                 }
586
587         }
588 }
589
590 if ( $opt_svg ) {
591         cut_mark $x,$y;
592         cut_mark $max_x,$y;
593         line $x, $y, $max_x if $opt_lines;
594
595         print qq{
596     <text
597        id="text4506"
598        y="$x"
599        x="$y"
600        style="font-size:2.34px;line-height:2.54px;font-family:'Andale Mono';stroke:none"
601        xml:space="preserve">
602
603         }; #svg
604
605         print @later, qq{</text>\n}, @cut_marks, qq{</g>\n</svg>};
606
607 }
608
609 # you can add pin definitions below, but they should go into pins/
610 __DATA__
611