File Coverage

blib/lib/Device/Chip/Adapter.pm
Criterion Covered Total %
statement 38 48 79.1
branch 4 10 40.0
condition 2 6 33.3
subroutine 9 13 69.2
pod 2 3 66.6
total 55 80 68.7


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