Device/Chip/Adapter.pm

filter: Statementstmt 81.4% 44 / 54 Branchbran 40.0% 4 / 10 Conditioncond 33.3% 2 / 6 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 69.2% 9 / 13 Podpod 66.6% 2 / 3 totaltotal 67.7% 61 / 90 CC 9 SCAR 17.3
CC
9
Cov
71%
new_from_description
12.8
make_protocol
2.0
name
1.3
CRAP 5.7
↑ Summary Device/Chip/Base/RegisteredI2C.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2015-2023 -- leonerd@leonerd.org.uk
5  
6 8 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Object::Pad 0.800;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 package Device::Chip::Adapter 0.27;
11 role Device::Chip::Adapter :repr(HASH) :compat(invokable);
12  
13 8 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 8 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 8 require Device::Chip;
20  
21 =encoding UTF-8
22  
23 =head1 NAME
24  
25 C<Device::Chip::Adapter> - an abstraction of a hardware communication device
26  
27 =head1 DESCRIPTION
28  
29 =for highlighter language=perl
30  
31 This package describes an interfaces tha classes can use to implement a driver
32 to provide access to some means of connecting an electronic chip or hardware
33 module to a computer. An instance implementing this interface provides some
34 means to send electrical signals to a connected chip or module, and receive
35 replies back from it; this device is called the I<adapter>. This is provided
36 as a service to some instance of the related interface, L<Device::Chip>.
37  
38 It is suggested that a driver for a particular adapter provides a concrete
39 class named within the C<Device::Chip::Adapter> heirarchy, adding the basic
40 name of the product or means of communication as a suffix; for example the
41 driver for communication device based on the I<FDTI> range of devices would
42 be called:
43  
44 package Device::Chip::Adapter::FTDI;
45  
46 This package provides a base class that such a specific implementation class
47 could use as a superclass, but it is not required to. The important detail is
48 that it provides the interface described by this documentation.
49  
50 =cut
51  
52 =head1 UTILITY CONSTRUCTOR
53  
54 =cut
55  
56 =head2 new_from_description
57  
58 $adapter = Device::Chip::Adapter->new_from_description( $DESC );
59  
60 This utility method is provided to allow end-user programs a convenient way to
61 construct a useable C<Device::Chip::Adapter> instance from a given single
62 string value. This string takes the form of a the main name of the adapter
63 class (minus the leading C<Device::Chip::Adapter::> prefix), optionally
64 followed by a single colon and some comma-separated options. Each option takes
65 the form of a name and value, separated by equals sign. For example:
66  
67 FTDI
68 FTDI:
69 FTDI:product=0x0601
70 BusPirate:serial=/dev/ttyUSB3,baud=57600
71  
72 This utility method splits off the base name from the optional suffix, and
73 splits the options into an even-sized name/value list. It loads the class
74 implied by the base name and invokes a method called C<new_from_description>
75 on it. This is passed the even-sized name/value list obtained by splitting
76 the option string. Any option named without a value will be passed having the
77 value true, as a convenience for options that are simple boolean flags.
78  
79 If the class does not provide the C<new_from_description> method (and of
80 course, simply inheriting the base class one from here does not count), then
81 if there are no other options given, the plain C<new> constructor is invoked
82 instead. If this is not possible because there are user-specified options that
83 must be honoured, then an exception is thrown instead.
84  
85 Note for example that in the case above, the C<product> option would be passed
86 to the C<FTDI> adapter class still as a string value; it is likely that this
87 class would want to implement a C<new_from_description> method to parse that
88 using the C<oct> operator into a plain integer.
89  
90 It is intended that this method is used for creating an adapter that a
91 standalone program can use from a description string specified by the user;
92 likely in a commandline option or environment variable.
93  
94 If I<$DESC> is undefined, a default value is taken from the environment
95 variable C<DEVICE_CHIP_ADAPTER>, if defined. If not, an exception is thrown.
96  
97 =cut
98  
99 4 ▶sub new_from_description ( $, $description = undef )
Subroutine new_from_description: called CC=8 SCAR=25.5
Pod documented
100 4 {
101 4 ▶ defined( $description //= $ENV{DEVICE_CHIP_ADAPTER} ) or
Branch: 1 branch
BranchTrueFalseTotal
defined($description //= $ENV{"DEVICE_CHIP_ADAPTER"}) or croak("Undefined Device::Chip adapter description") 4 0 4
Condition33%1/3
$description //= $ENV{"DEVICE_CHIP_ADAPTER"}
l!l&&r!l&&!r
400
MC/DC0%0/2
$description //= $ENV{"DEVICE_CHIP_ADAPTER"}
$description $ENV{"DEVICE_CHIP_ADAPTER"}
Truth table33%1/3
A //= B
A= $descriptionB= $ENV{"DEVICE_CHIP_ADAPTER"}
ABresult
1X1
011
000
102 croak "Undefined Device::Chip adapter description";
103  
104 4 ▶ my ( $basename, $opts ) = $description =~ m/^([^:]+)(?::(.*))?$/ or
Branch: 1 branch
BranchTrueFalseTotal
() = $description =~ /^([^:]+)(?::(.*))?$/u or croak("Malformed adapter description - $description") 4 0 4
105 croak "Malformed adapter description - $description";
106  
107 # Not a hash, in case the same option is given more than once
108 4 my @opts = Device::Chip->_parse_options( $opts );
109  
110 4 my $class = "Device::Chip::Adapter::$basename";
111 4 ( my $file = "$class.pm" ) =~ s{::}{/}g;
112  
113 4 require $file;
114  
115 4 my $code = $class->can( "new_from_description" );
116 4 ▶ if( $code and $code != \&new_from_description ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($code and $code != \&Device::Chip::Adapter::new_from_description) { } 4 0 4
elsif (not @opts) { } 0 0 0
Condition33%1/3
$code and $code != \&Device::Chip::Adapter::new_from_description
!ll&&!rl&&r
004
MC/DC0%0/2
$code and $code != \&Device::Chip::Adapter::new_from_description
$code $code != \&Device::Chip::Adapter::new_from_description
Truth table33%1/3
A and B
A= $codeB= $code != \&Device::Chip::Adapter::new_from_description
ABresult
0X0
100
111
117 4 return $class->$code( @opts );
118 }
119 elsif( !@opts ) {
120 # Fall back on plain ->new
121 0 return $class->new();
122 }
123  
124 0 croak "$class does not provide a ->new_from_description and we cannot fallback on ->new with options";
125 }
126  
127 =head1 METHODS
128  
129 The following methods documented in an C<await> expression return L<Future>
130 instances.
131  
132 =cut
133  
134 =head2 make_protocol
135  
136 $protocol = await $adapter->make_protocol( $pname );
137  
138 Returns an object that satisfies one of the interfaces documented below in
139 L</PROTOCOLS>, depending on the protocol name given by I<$pname>. This should
140 be one of the following values:
141  
142 GPIO
143 SPI
144 I2C
145 UART
146  
147 It is unspecified what class these objects should belong to. In particular, it
148 is permitted that an adapter could even return itself as the protocol
149 implementation, provided it has the methods to satisfy the interface for that
150 particular protocol. This is especially convenient in the case that the
151 adapter is only capable of one kind of protocol.
152  
153 =cut
154  
155 # A default implementation that uses some reflection to simplify
156 # implementations
157 7 ▶method make_protocol ( $pname )
Subroutine make_protocol: called CC=2 SCAR=7.1
Pod documented
158 {
159 7 ▶ if( my $code = $self->can( "make_protocol_$pname" ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $code = $self->can("make_protocol_$pname")) { } 7 0 7
160 7 return $code->( $self );
161 }
162 else {
163 0 croak "Unrecognised protocol name $pname";
164 }
165 8 }
166  
167 =head2 shutdown
168  
169 $adapter->shutdown;
170  
171 Shuts down the adapter in whatever manner is appropriate at the end of the
172 lifetime of the containing program; or at least, at the point when the program
173 has finished using the connected device.
174  
175 This method is allowed to block; it does not yield a L<Future>. It is suitable
176 to call from a C<DESTROY> method or C<END> block.
177  
178 =cut
179  
180 =head1 PROTOCOLS
181  
182 The following methods are common to all protocol instances:
183  
184 =head2 sleep
185  
186 await $protocol->sleep( $secs );
187  
188 Causes a fixed delay, given in (fractional) seconds. Adapter module authors
189 should attempt to perform this delay concurrently, overlapping IO with other
190 operations where possible.
191  
192 =head2 configure
193  
194 await $protocol->configure( %args );
195  
196 Sets configuration options for the protocol. The actual set of options
197 available will depend on the type of the protocol.
198  
199 Chip drivers should attempt to bundle their changes together into as few
200 C<configure> calls as possible, because adapters may find it most efficient to
201 apply multiple changes in one go.
202  
203 =head2 power
204  
205 await $protocol->power( $on );
206  
207 Switches on or off the power to the actual chip or module, if such ability is
208 provided by the adapter.
209  
210 =head2 list_gpios
211  
212 @pin_names = $protocol->list_gpios;
213  
214 Returns a list of the names of GPIO pins that are available for the chip
215 driver to use. This list would depend on the pins available on the adapter
216 itself, minus any pins that are in use by the protocol itself.
217  
218 Adapters should name GPIO pins in a way that makes sense from the hardware;
219 for example C<MOSI>, C<SDA>, C<DTR>, C<Q0>, etc...
220  
221 =head2 meta_gpios
222  
223 @pin_definitions = $protocol->meta_gpios;
224  
225 Returns a list of definition objects that define the behavior of the GPIO
226 pins. This should be returned in the same order as the L</list_gpios> method.
227  
228 Each returned value will be an instance with the following methods:
229  
230 =over 4
231  
232 =item name
233  
234 $def->name = STR
235  
236 Gives the device's name for that GPIO pin - the name that would be returned
237 by L</list_gpios> and recognised by the other methods.
238  
239 =item dir
240  
241 $def->dir = "r" | "w" | "rw"
242  
243 Gives the data directions that the GPIO pin supports. C<r> for pins that are
244 read-only, C<w> for pins that are write-only, and C<rw> for pins that are
245 bidirectional.
246  
247 =item invert
248  
249 $def->invert = BOOL
250  
251 If true, the hardware itself will invert the sense of reads or writes to this
252 pin - that is, a low voltage on the pin will be represented by a true value in
253 the L</write_gpios> and L</read_gpios> methods, and a high voltage represented
254 by a false value.
255  
256 =back
257  
258 Adapter implementations may wish to use a helper class definition provided
259 by this package by calling L<Device::Chip::Adapter::GPIODefinition> to
260 implement these.
261  
262 $def = GPIODefinition( $name, $dir, $invert );
263  
264 =cut
265  
266 8 ▶use Object::Pad::ClassAttr::Struct 0.05;
Subroutine BEGIN: called CC=1 SCAR=0.0
267  
268 # This used to be Struct::Dumb-driven
269 class Device::Chip::Adapter::_GPIODefinition :Struct(readonly) {
270 0 ▶ field $name;
Subroutine name: not called CC=1 SCAR=2.6
271 0 ▶ field $dir;
Subroutine dir: not called CC=1 SCAR=2.6
272 0 ▶ field $invert;
Subroutine invert: not called CC=1 SCAR=2.6
273 }
274 8 ▶sub GPIODefinition {
Subroutine GPIODefinition: not called CC=1 SCAR=1.2
Pod undocumented
275 0 return Device::Chip::Adapter::_GPIODefinition->new_values( @_ );
276 }
277  
278 =head2 write_gpios
279  
280 await $protocol->write_gpios( \%pin_values );
281  
282 Sets the named GPIO pins as driven outputs, and gives their new values. Any
283 GPIO pins not named are left as they are; either driving outputs at the
284 current state, or high-impedence inputs.
285  
286 Pins are specified as a C<HASH> reference, mapping pin names (as returned by
287 the L</list_gpios> method) to boolean logic levels.
288  
289 =head2 read_gpios
290  
291 \%pin_values = await $protocol->read_gpios( \@pin_names );
292  
293 Sets the named GPIO pins as high-impedence inputs, and reads their current
294 state. Any GPIO pins not named here are left as they are; either driving
295 outputs at the current state, or other inputs.
296  
297 Pins are specified in an C<ARRAY> reference giving the names of pins (as
298 returned by the L</list_gpios> method); read values are given in the returned
299 C<HASH> reference which maps pin names to boolean logic levels.
300  
301 =head2 tris_gpios
302  
303 await $protocol->tris_gpios( \@pin_names );
304  
305 Sets the named GPIO pins as high-impedence inputs ("tristate"). Any GPIO pins
306 not named here are left as they are.
307  
308 This method is similar to L</read_gpios> except that it does not return the
309 current pin values to the caller. Adapter implementations may implement this
310 by simply calling L</read_gpios> or they may have a more efficient variant
311 that does not have to transfer these extra readings back from the adapter
312 hardware.
313  
314 =cut
315  
316 =head1 GPIO PROTOCOL
317  
318 The GPIO protocol adds no new abilities or methods; it is the most basic form
319 of protocol that simply provides access to the generic GPIO pins of the
320 device.
321  
322 =head1 SPI PROTOCOL
323  
324 =head2 Configuration Options
325  
326 The following configuration options are recognised:
327  
328 =over 4
329  
330 =item mode => 0 | 1 | 2 | 3
331  
332 The numbered SPI mode used to communicate with the chip.
333  
334 =item max_bitrate => INT
335  
336 The highest speed, in bits per second, that the chip can accept. The adapter
337 must pick a rate that is no higher than this. Note specifically that not all
338 adapters are able to choose a rate arbitrarily, and so the actually
339 communication may happen at some rate slower than this.
340  
341 =item wordsize => INT
342  
343 The number of bits per word transferred. Many drivers will not be able to
344 accept a number other than 8.
345  
346 For values less than 8, the value should be taken from the least-significant
347 bits of each byte given to the C<readwrite> or C<write> methods.
348  
349 For values greater than 8, use character strings with wide codepoints inside;
350 such as created by the C<chr()> function.
351  
352 =back
353  
354 =head2 readwrite
355  
356 $words_in = await $spi->readwrite( $words_out );
357  
358 Performs a complete SPI transaction; assert the SS pin, synchronously clock
359 the data given by the I<$words_out> out of the MOSI pin of the adapter while
360 simultaneously capturing the data coming in to the MISO pin, then release the
361 SS pin again. The values clocked in are eventually returned as the result of
362 the returned future.
363  
364 =head2 write
365  
366 await $spi->write( $words );
367  
368 A variant of C<readwrite> where the caller does not intend to make use of the
369 data returned by the device, and so the adapter does not need to return it.
370 This may or may not make a material difference to the actual communication
371 with the adapter or device; it could be implemented simply by calling the
372 C<readwrite> method and ignoring the return value.
373  
374 =head2 read
375  
376 $words = await $spi->read( $len );
377  
378 A variant of C<readwrite> where the chip will not care what data is written
379 to it, so the caller does not need to supply it. This may or may not make a
380 material difference to the actual communication with the adapter or device;
381 it could be implemented simply by calling the C<readwrite> method and passing
382 in some constant string of appropriate length.
383  
384 =head2 write_then_read
385  
386 $words_in = await $spi->write_then_read( $words_out, $len_in );
387  
388 Performs a complete SPI transaction; assert the SS pin, synchronously clock
389 the data given by I<$words_out> out of the MOSI pin of the adapter, then clock
390 in more data from the MISO pin, finally releasing the SS pin again. These two
391 operations must be performed within a single assert-and-release SS cycle. It
392 is unspecified what values will be sent out during the read phase; adapters
393 should typically send all-bits-low or all-bits-high, but in general may not
394 allow configuration of what that will be.
395  
396 This differs from the C</readwrite> method in that it works sequentially;
397 sending out words while ignoring the result, then reading in words while
398 sending unspecified data.
399  
400 =head2 assert_ss
401  
402 =head2 release_ss
403  
404 await $spi->assert_ss;
405  
406 await $spi->release_ss;
407  
408 Lower-level access methods to directly assert or release the SS pin of the
409 adapter. These would typically be used in conjunction with L</readwrite_no_ss>
410 or L</write_no_ss>.
411  
412 =head2 readwrite_no_ss
413  
414 =head2 write_no_ss
415  
416 =head2 read_no_ss
417  
418 $words_in = await $spi->readwrite_no_ss( $words_out );
419  
420 await $spi->write_no_ss( $words );
421  
422 $words = await $spi->read_no_ss( $len );
423  
424 Lower-level access methods to directly perform a data transfer across the
425 MOSI/MISO pins of the adapter, without touching the SS pin. A complete SPI
426 transaction can be performed in conjunction with the L</assert_ss> and
427 L</release_ss> methods.
428  
429 $spi->assert_ss
430 ->then( sub {
431 $spi->readwrite_no_ss( $words_out );
432 })
433 ->then( sub {
434 ( $words_in ) = @_;
435 $spi->release_ss->then_done( $words_in );
436 });
437  
438 These methods are provided for situations where it is not possible to know in
439 advance all the data to be sent out in an SPI transaction; where the chip
440 driver code must inspect some of the incoming data before it can determine
441 what else needs to be sent, but when these must all be sent in one SS-asserted
442 transaction.
443  
444 Because they perform multiple independent operations on the underlying
445 adapter, these lower-level methods may be less efficient than using the single
446 higher-level methods of L</readwrite> and L</write>. As such, they should only
447 be used when the combined higher-level method cannot be used.
448  
449 Note that many of these methods can be synthesized from other simpler ones. A
450 convenient abstract base class, L<Device::Chip::ProtocolBase::SPI>, can be
451 used to do this, providing wrappers for some methods implemented using others.
452 This reduces the number of distinct methods that need to be provided.
453 Implementations may still, and are encouraged to, provide "better" versions of
454 those methods if they can be provided more efficiently than simply wrapping
455 others.
456  
457 =cut
458  
459 =head1 I2C PROTOCOL
460  
461 =head2 Configuration Options
462  
463 The following configuration options are recognised:
464  
465 =over 4
466  
467 =item addr => INT
468  
469 The (7-bit) slave address for the chip this protocol is communicating with.
470  
471 =item max_bitrate => INT
472  
473 The highest speed, in bits per second, that the chip can accept. The adapter
474 must pick a rate that is no higher than this. Note specifically that not all
475 adapters are able to choose a rate arbitrarily, and so the actually
476 communication may happen at some rate slower than this.
477  
478 =back
479  
480 =head2 write
481  
482 await $i2c->write( $bytes_out );
483  
484 Performs a complete I²C transaction to send the given bytes to the slave chip.
485 This includes the start condition, sending the addressing byte (which is
486 implied; it should I<not> be included in C<$bytes_out>) and ending in the stop
487 condition.
488  
489 =head2 read
490  
491 $bytes_in = await $i2c->read( $len_in );
492  
493 Performs a complete I²C transaction to receive the given number of bytes back
494 from the slave chip. This includes the start condition, sending the addressing
495 byte and ending in a stop condition.
496  
497 =head2 write_then_read
498  
499 $bytes_in = await $i2c->write_then_read( $bytes_out, $len_in );
500  
501 Performs a complete I²C transaction to first send the given bytes to the slave
502 chip then reads the give number of bytes back, returning them. These two
503 operations must be performed within a single I²C transaction using a repeated
504 start condition.
505  
506 =head2 txn
507  
508 $result = await $i2c->txn( async sub {
509 my ( $helper ) = @_;
510 ...
511 } );
512  
513 Performs a complete custom I²C transaction. Within the code block invoked by
514 the transaction, the C<write>, C<read> and C<write_then_read> methods may be
515 called on the passed C<$helper> instance, but they will B<not> cause stop
516 conditions to be sent on the wire. A stop condition will be sent after the
517 code has finished. The return value from this method will be whatever is
518 returned by the inner code block.
519  
520 This method acts as a mutex lock, ensuring only one transaction can run
521 concurrently. This mutex is also used by the C<read>, C<write> and
522 C<write_then_read> methods (which may optionally be implemented in terms of
523 the C<txn> method internally).
524  
525 =cut
526  
527 =head1 UART PROTOCOL
528  
529 The UART protocol is still subject to ongoing design. In particular, a
530 suitable interface for general-purpose spurious read notifications ha yet to
531 be designed. The current API is suitable for transmit-only, or
532 request/response interfaces where the PC side is in control of communications
533 and knows exactly when, and how many bytes long, data will be received.
534  
535 =head2 Configuration Options
536  
537 =over 4
538  
539 =item baudrate => INT
540  
541 The communication bitrate, in bits per second. Most adapters ought to be able
542 to accept the common ones such as 9600, 19200 or 38400.
543  
544 =item bits => INT
545  
546 The number of bits per character. Usually 8, though some adapters may be able
547 to offer smaller values.
548  
549 =item parity => "n" | "o" | "e"
550  
551 Disables parity generation/checking (when C<n>), or enables it for odd
552 (when C<o>) or even (when C<e>).
553  
554 =item stop => 1 | 2
555  
556 The size of the stop state, in bits. Either 1 or 2.
557  
558 =back
559  
560 =head2 write
561  
562 await $uart->write( $bytes );
563  
564 Transmits the given bytes over the UART TX line.
565  
566 =head2 read
567  
568 $bytes = await $uart->read( $len );
569  
570 Receives the given number of bytes from the UART RX line. The returned future
571 will not complete until the requested number of bytes are available.
572  
573 This API is suitable for PC-first request/response style interfaces, but will
574 not be sufficient for chip-first notifications or other use-cases. A suitable
575 API shape for more generic scenarios is still a matter of ongoing design
576 investigation.
577  
578 =head1 AUTHOR
579  
580 Paul Evans <leonerd@leonerd.org.uk>
581  
582 =cut
583  
584 8 0x55AA;
↑ Summary Device/Chip/Base/RegisteredI2C.pm »