WiringPi.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« WiringPi/Meta.pm ↑ Summary WiringPi/Core.pm »
1 package RPi::WiringPi;
2  
3 74 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 74 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # Method resolution order: this class tree uses Perl's default depth-first
7 # MRO. The effective search order from this class is:
8 #
9 # RPi::WiringPi -> Core -> WiringPi::API -> Exporter -> Meta -> Util
10 # -> RPi::SysInfo
11 #
12 # WiringPi::API (reached through Core, which lists it first) is searched
13 # BEFORE Meta and Util, even though both are direct parents below. Do NOT
14 # define a method in Meta/Util/RPi::SysInfo whose name spans two branches
15 # (e.g. a Util sub named after a WiringPi::API sub) without revisiting the
16 # MRO -- depth-first search would silently dispatch to the WiringPi::API
17 # version. A symbol table audit (2026-06-11) found no meaningful
18 # cross-branch collisions: only identical RPi::Const/Carp imports, XS
19 # bootstrap glue, and new() (WiringPi::API vs RPi::SysInfo), which is
20 # shadowed by this class's own new() for all callers.
21 #
22 # Switching to `use mro 'c3'` is NOT a drop-in change: the current parent
23 # ordering is C3-inconsistent (Util lists Exporter before WiringPi::API,
24 # which itself inherits Exporter; Core lists WiringPi::API before Util,
25 # its own subclass) and Perl dies with "Inconsistent hierarchy". @ISA in
26 # Util.pm, Core.pm and this file would need reordering first.
27 74 ▶use parent 'RPi::WiringPi::Core';
Subroutine BEGIN: called CC=1 SCAR=0.0
28 use parent 'RPi::WiringPi::Util';
29 use parent 'RPi::WiringPi::Meta';
30  
31 use Carp qw(croak confess);
32 use Data::Dumper;
33 use RPi::Const qw(:all);
34 use Scalar::Util qw(weaken);
35  
36 our $VERSION = '3.1802';
37  
38 # class variables
39  
40 my %sig_handlers;
41 my %prev_sig;
42 my $signal_debug = 0;
43  
44 # Weak registry of live, registered objects (keyed by uuid) so the END block
45 # below can clean up anything the user never explicitly cleanup()'d while the
46 # IPC::Shareable segment is still alive — before global destruction tears it
47 # down. The strong refs in %sig_handlers keep these objects alive until exit.
48  
49 my %objects;
50  
51 # Core
52  
53 sub new {
54 my ($self, %args) = @_;
55 $self = bless {%args}, $self;
56  
57 if (! $ENV{NO_BOARD}){
58 if (defined $ENV{RPI_PIN_MODE}){
59 # This checks if another application has already run a setup
60 # routine. Must be a defined check: RPI_MODE_WPI is 0, which is
61 # falsy, and a truthy test would silently re-init WPI mode to GPIO
62 $self->pin_scheme($ENV{RPI_PIN_MODE});
63 }
64 else {
65 # We default to gpio mode
66  
67 if (! defined $self->{setup}) {
68 $self->SUPER::setup_gpio();
69 $self->pin_scheme(RPI_MODE_GPIO);
70 }
71 else {
72 if ($self->_setup =~ /^w/i) {
73 $self->SUPER::setup();
74 $self->pin_scheme(RPI_MODE_WPI);
75 }
76 elsif ($self->_setup =~ /^g/i) {
77 $self->SUPER::setup_gpio();
78 $self->pin_scheme(RPI_MODE_GPIO);
79 }
80 elsif ($self->_setup =~ /^n/i) {
81 # 'none': deliberately skip the C library setup call; the
82 # pin scheme stays uninitialized (the test suite uses this)
83 $self->pin_scheme(RPI_MODE_UNINIT);
84 }
85 else {
86 croak "unrecognized 'setup' param value '" . $self->_setup .
87 "'; valid values are 'wiringpi', 'gpio' or 'none'\n";
88 }
89 }
90 }
91  
92 # Set the env var so we can catch multiple setup calls properly
93 $ENV{RPI_PIN_MODE} = $self->pin_scheme;
94 }
95  
96 $self->{proc} = $$;
97  
98 $self->_fatal_exit($args{fatal_exit});
99  
100 $self->{shm_key} //= 'rpiw';
101 $self->meta($self->{shm_key});
102  
103 if ($self->_rpi_register) {
104 # Register all objects for collision detection and safety shutdown
105  
106 $self->_meta_txn(sub {
107 my $meta = $self->meta_fetch;
108  
109 while (! defined $self->{uuid}) {
110 my $uuid = $self->checksum;
111 next if exists $meta->{objects}{$uuid};
112 $self->{uuid} = $uuid;
113 }
114  
115 $meta->{objects}{$self->uuid} = {
116 proc => $self->{proc},
117 label => $self->{label}
118 };
119  
120 $meta->{object_count}++;
121  
122 $self->meta_store($meta);
123 });
124  
125 $self->_generate_signal_handlers;
126  
127 # Track for END-time cleanup (weak, so we never extend the object's
128 # life ourselves — %sig_handlers already holds it until exit).
129  
130 $objects{$self->uuid} = $self;
131 weaken $objects{$self->uuid};
132 }
133  
134 return $self;
135 }
136 sub adc {
137 my ($self, %args) = @_;
138  
139 if (defined $args{model} && $args{model} eq 'MCP3008'){
140 require RPi::ADC::MCP3008;
141 RPi::ADC::MCP3008->import;
142  
143 my $pin = $self->pin($args{channel}, "MCP3008 ADC CS");
144  
145 return RPi::ADC::MCP3008->new($pin->num);
146 }
147 else {
148 # ADSxxxx ADCs don't require any pins
149 require RPi::ADC::ADS;
150 RPi::ADC::ADS->import;
151 return RPi::ADC::ADS->new(%args);
152 }
153 }
154 sub bmp {
155 require RPi::BMP180;
156 RPi::BMP180->import;
157 return RPi::BMP180->new($_[1]);
158 }
159 sub dac {
160 my ($self, %args) = @_;
161  
162 $self->pin($args{cs}, 'MCP4922 DAC CS');
163 $self->pin($args{shdn}, 'MCP4922 DAC Shutdown') if defined $args{shdn};
164  
165 $args{model} = 'MCP4922' if ! defined $args{model};
166  
167 require RPi::DAC::MCP4922;
168 RPi::DAC::MCP4922->import;
169  
170 return RPi::DAC::MCP4922->new(%args);
171 }
172 sub dpot {
173 my ($self, $cs, $channel) = @_;
174 $self->pin($cs, 'MCP4XXXX Digital Potentiometer CS');
175 require RPi::DigiPot::MCP4XXXX;
176 RPi::DigiPot::MCP4XXXX->import;
177 return RPi::DigiPot::MCP4XXXX->new($cs, $channel);
178 }
179 sub eeprom {
180 my ($self, %args) = @_;
181 require RPi::EEPROM::AT24C32;
182 RPi::EEPROM::AT24C32->import;
183 return RPi::EEPROM::AT24C32->new(%args);
184 }
185 sub expander {
186 my ($self, $addr, $expander) = @_;
187  
188 if (! defined $expander || $expander eq 'MCP23017'){
189 $addr = 0x20 if ! defined $addr;
190 require RPi::GPIOExpander::MCP23017;
191 RPi::GPIOExpander::MCP23017->import;
192 return RPi::GPIOExpander::MCP23017->new($addr);
193 }
194  
195 croak "expander() type '$expander' is unrecognized; only 'MCP23017' is " .
196 "currently supported\n";
197 }
198 sub gps {
199 my ($self, %args) = @_;
200 require GPSD::Parse;
201 GPSD::Parse->import;
202 return GPSD::Parse->new(%args);
203 }
204 sub hcsr04 {
205 my ($self, $t, $e) = @_;
206 $self->pin($t, "HCSR04 Ultrasonic Distance Sensor Trigger");
207 $self->pin($e, "HCSR04 Ultrasonic Distance Sensor Echo");
208 require RPi::HCSR04;
209 RPi::HCSR04->import;
210 return RPi::HCSR04->new($t, $e);
211 }
212 sub hygrometer {
213 my ($self, $pin) = @_;
214 $self->pin($pin, "DHT11 Hygrometer Signal");
215 require RPi::DHT11;
216 RPi::DHT11->import;
217 return RPi::DHT11->new($pin);
218 }
219 sub i2c {
220 my ($self, $addr, $i2c_device) = @_;
221 require RPi::I2C;
222 RPi::I2C->import;
223 return RPi::I2C->new($addr, $i2c_device);
224 }
225 sub lcd {
226 my ($self, %args) = @_;
227  
228 # Pre-register all pins so we can clean them up= accordingly upon cleanup
229  
230 for (qw(rs strb d0 d1 d2 d3 d4 d5 d6 d7)){
231 if (! exists $args{$_} || $args{$_} !~ /^\d+$/){
232 die "lcd() requires pin configuration within a hash\n";
233 }
234 next if $args{$_} == 0;
235 $self->pin($args{$_}, "LCD $_");
236 }
237  
238 require RPi::LCD;
239 RPi::LCD->import;
240 my $lcd = RPi::LCD->new;
241 $lcd->init(%args);
242 return $lcd;
243 }
244 sub oled {
245 my ($self, $model, $i2c_addr, $display_splash_page) = @_;
246  
247 $model //= '128x64';
248 $i2c_addr //= 0x3C;
249  
250 my %models = (
251 '128x64' => 1,
252 '128x32' => 1,
253 '96x16' => 1,
254 );
255  
256 if (! exists $models{$model}){
257 die "oled() requires one of the following models sent in: " .
258 "128x64, 128x32 or 96x16\n";
259 }
260  
261 if ($model eq '128x64'){
262 require RPi::OLED::SSD1306::128_64;
263 RPi::OLED::SSD1306::128_64->import;
264 return RPi::OLED::SSD1306::128_64->new($i2c_addr, $display_splash_page);
265 }
266  
267 # The remaining whitelisted sizes don't have a driver class yet; dying
268 # beats silently handing the caller undef
269  
270 die "oled() model '$model' is not yet implemented; only 128x64 is " .
271 "currently supported\n";
272 }
273 sub pin {
274 my ($self, $pin_num, $comment) = @_;
275  
276 require RPi::Pin;
277 RPi::Pin->import;
278  
279 my $gpio = $self->pin_to_gpio($pin_num);
280  
281 if ($self->_rpi_register && $self->_rpi_register_pins) {
282 # Both object and pin registration is enabled
283  
284 if (grep {$gpio == $_} @{$self->registered_pins}) {
285 croak "\npin $pin_num is already in use... can't create second object\n";
286 }
287 }
288  
289 my $pin = RPi::Pin->new($pin_num, $comment);
290  
291 if ($self->_rpi_register && $self->_rpi_register_pins) {
292 # Register the pin
293 $self->register_pin($pin);
294 }
295  
296 return $pin;
297 }
298 sub rtc {
299 my ($self, $rtc_addr) = @_;
300 require RPi::RTC::DS3231;
301 RPi::RTC::DS3231->import;
302 return RPi::RTC::DS3231->new($rtc_addr);
303 }
304 sub serial {
305 my ($self, $device, $baud) = @_;
306 require RPi::Serial;
307 RPi::Serial->import;
308 return RPi::Serial->new($device, $baud);
309 }
310 sub servo {
311 my ($self, $pin_num, %config) = @_;
312  
313 if ($> != 0) {
314 die "\n\nAt this time, servo() requires PWM functionality, and PWM " .
315 "requires your script to be run as the 'root' user (sudo)\n\n";
316 }
317  
318 my $servo = $self->pin($pin_num, "Servo PWM");
319  
320 $config{clock} = exists $config{clock} ? $config{clock} : 192;
321 $config{range} = exists $config{range} ? $config{range} : 2000;
322  
323 $self->_pwm_in_use(1);
324  
325 $servo->mode(PWM_OUT);
326  
327 $self->pwm_mode(PWM_MODE_MS);
328 $self->pwm_clock($config{clock});
329 $self->pwm_range($config{range});
330  
331 return $servo;
332 }
333 sub shift_register {
334 my ($self, $base, $num_pins, $data, $clk, $latch) = @_;
335  
336 my @pin_nums;
337 my @pin_comments = (
338 'Shift Register Data',
339 'Shift Register Clock',
340 'Shift Register Latch',
341 );
342 my $pin_count = 0;
343  
344 for ($data, $clk, $latch){
345 my $pin = $self->pin($_, $pin_comments[$pin_count]);
346 push @pin_nums, $pin->num;
347 $pin_count++;
348 }
349 $self->shift_reg_setup($base, $num_pins, @pin_nums);
350 }
351 sub spi {
352 my ($self, $chan, $speed) = @_;
353 require RPi::SPI;
354 RPi::SPI->import;
355 my $spi = RPi::SPI->new($chan, $speed);
356 return $spi;
357 }
358 sub stepper_motor {
359 my ($self, %args) = @_;
360  
361 require RPi::StepperMotor;
362 RPi::StepperMotor->import;
363  
364 if (! exists $args{pins}) {
365 die "steppermotor() requires an arrayref of pins sent in\n";
366 }
367  
368 my @pin_comments = (
369 'Stepper IN1',
370 'Stepper IN2',
371 'Stepper IN3',
372 'Stepper IN4'
373 );
374 my $pin_count = 0;
375  
376 if (! exists $args{expander}) {
377 for (@{$args{pins}}) {
378 $self->pin($_, $pin_comments[$pin_count]);
379 $pin_count++;
380 }
381 }
382  
383 return RPi::StepperMotor->new(%args);
384 }
385  
386 # Interrupts
387  
388 sub auto_dispatch_interrupts {
389 my ($self, $enable, $signal) = @_;
390 return WiringPi::API::auto_dispatch_interrupts($enable, $signal);
391 }
392 sub background_interrupts {
393 my ($self, @specs) = @_;
394 return WiringPi::API::background_interrupts(@specs);
395 }
396 sub dispatch_interrupts {
397 my ($self) = @_;
398 return WiringPi::API::dispatch_interrupts();
399 }
400 sub interrupt_buffer {
401 my ($self, $bytes) = @_;
402 return WiringPi::API::interrupt_buffer($bytes);
403 }
404 sub interrupt_dropped {
405 my ($self) = @_;
406 return WiringPi::API::interrupt_dropped();
407 }
408 sub last_interrupt {
409 my ($self) = @_;
410 return WiringPi::API::last_interrupt();
411 }
412 sub run_interrupt_loop {
413 my ($self, $timeout_ms, $max) = @_;
414 return WiringPi::API::run_interrupt_loop($timeout_ms, $max);
415 }
416 sub stop_interrupt_loop {
417 my ($self) = @_;
418 return WiringPi::API::stop_interrupt_loop();
419 }
420 sub stop_interrupts {
421 my ($self) = @_;
422 return WiringPi::API::stop_interrupts();
423 }
424 sub wait_interrupts {
425 my ($self, $timeout_ms) = @_;
426 return WiringPi::API::wait_interrupts($timeout_ms);
427 }
428  
429 # Threads
430  
431 sub worker {
432 my ($self, $body, $opts) = @_;
433  
434 # Track the returned handle on the object so cleanup()/DESTROY can reap it
435  
436 my $handle = WiringPi::API::worker($body, $opts);
437 push @{ $self->{workers} }, $handle;
438 return $handle;
439 }
440  
441 # Private
442  
443 sub _class_signal_handler {
444 # The process-global INT/TERM handler. Cleans up every live object, chains
445 # to any handler the caller had installed before us, then honours fatal_exit
446  
447 my ($signal, @args) = @_;
448  
449 # During global destruction the object graph is torn down in an arbitrary
450 # order; dispatching per-object handlers here would call methods on
451 # already-freed objects. Bail out — END-time cleanup has already run.
452  
453 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
454  
455 # Reset every live object's hardware first (the safety guarantee).
456  
457 for (keys %{ $sig_handlers{$signal} }){
458 &{ $sig_handlers{$signal}->{$_} }(@args);
459 }
460  
461 # Chain to a handler the caller installed before we took over, so we don't
462 # silently swallow their signal handling.
463  
464 if (ref $prev_sig{$signal} eq 'CODE'){
465 $prev_sig{$signal}->(@args);
466 }
467  
468 # fatal_exit (default true): once cleanup is done, terminate with the
469 # signal's default disposition so the exit status is correct (and END still
470 # runs). The setting is per-object: if ANY live object was created with
471 # fatal_exit => 0, the process is allowed to carry on
472  
473 my $fatal = 1;
474  
475 for my $uuid (keys %objects) {
476 my $obj = $objects{$uuid} or next;
477 $fatal = 0 if ! $obj->{fatal_exit};
478 }
479  
480 if ($fatal) {
481 $SIG{$signal} = 'DEFAULT';
482 kill $signal, $$;
483 }
484 }
485 sub _cleanup_handler {
486 # Per-object signal cleanup. The terminate/continue decision lives in
487 # _class_signal_handler (after all objects are cleaned), not here.
488  
489 my ($self, $sig) = @_;
490  
491 if ($signal_debug) {
492 print "running '$sig' handler for: " . $self->uuid .
493 " with fatal_exit = " . $self->_fatal_exit . "\n";
494 }
495  
496 delete $sig_handlers{$sig}{$self->uuid};
497 $self->cleanup;
498 }
499 sub _fatal_exit {
500 my ($self, $fatal) = @_;
501  
502 # Strictly per-object; _class_signal_handler honours a fatal_exit => 0
503 # from any live object instead of a process-global last-writer-wins
504  
505 $self->{fatal_exit} = $fatal if defined $fatal;
506 $self->{fatal_exit} = 1 if ! defined $self->{fatal_exit};
507  
508 return $self->{fatal_exit};
509 }
510 sub _generate_signal_handlers {
511 my $self = shift;
512  
513 if (! %sig_handlers){
514 # Install our INT/TERM handlers once. We deliberately do NOT trap
515 # $SIG{__DIE__}: resetting the hardware on a crash or normal exit is
516 # already handled by the END block and DESTROY, so trapping every die
517 # would only risk tearing things down on a caught, handled exception.
518 # Preserve any handler the caller already set so we can chain to it.
519  
520 for my $sig (qw(INT TERM)){
521 # Preserve whatever disposition was in place (a CODE ref, a sub
522 # name, 'IGNORE'/'DEFAULT', or undef) so it can be restored once
523 # the last object is cleaned up. Only CODE refs are chained
524 # mid-signal in _class_signal_handler
525  
526 $prev_sig{$sig} = $SIG{$sig};
527 $SIG{$sig} = sub { _class_signal_handler($sig, @_) };
528 }
529 }
530  
531 $sig_handlers{'INT'}{$self->uuid} = sub {
532 $self->_cleanup_handler('INT')
533 };
534  
535 $sig_handlers{'TERM'}{$self->uuid} = sub {
536 $self->_cleanup_handler('TERM')
537 };
538 }
539 sub _release_signal_handlers {
540 # Drops this object's per-signal cleanup entries (releasing the strong
541 # closure that keeps the object alive). When the last object for a signal
542 # is gone, restore the handler that was in place before we took over,
543 # including non-CODE dispositions ('IGNORE', 'DEFAULT', sub names)
544  
545 my ($self) = @_;
546  
547 for my $sig (qw(INT TERM)){
548 delete $sig_handlers{$sig}{$self->uuid};
549  
550 if (! keys %{ $sig_handlers{$sig} }){
551 $SIG{$sig} = defined $prev_sig{$sig} ? $prev_sig{$sig} : 'DEFAULT';
552 delete $sig_handlers{$sig};
553 delete $prev_sig{$sig};
554 }
555 }
556 }
557 sub _setup {
558 return $_[0]->{setup};
559 }
560 sub _signal_handlers {
561 return \%sig_handlers;
562 }
563  
564 sub DESTROY {
565 my ($self) = @_;
566  
567 # At global destruction the IPC::Shareable segment may already be gone, so
568 # cleanup() can't run reliably; the END block has already reaped any live
569 # objects. Skip here to avoid noisy teardown warnings.
570  
571 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
572  
573 $self->cleanup if ! $self->{clean};
574 }
575 END {
576 # Reap any object that was never explicitly cleaned. Running here (END
577 # phase) keeps the shared-memory segment intact, so cleanup() actually
578 # resets the pins and unregisters the object, and leaves DESTROY nothing
579 # to do at global destruction — avoiding "during global destruction"
580 # warnings from operating on a half-torn-down segment.
581  
582 for my $uuid (keys %objects) {
583 my $obj = $objects{$uuid} or next;
584 next if $obj->{clean};
585 eval { $obj->cleanup; 1 };
586 }
587 }
588  
589 sub _vim{};
590  
591 1;
592 __END__
« WiringPi/Meta.pm ↑ Summary WiringPi/Core.pm »