pigpio.py
Go to the documentation of this file.
00001 """
00002 pigpio is a Python module for the Raspberry which talks to
00003 the pigpio daemon to allow control of the general purpose
00004 input outputs (GPIO).
00005 
00006 [http://abyz.me.uk/rpi/pigpio/python.html]
00007 
00008 *Features*
00009 
00010 o the pigpio Python module can run on Windows, Macs, or Linux
00011 
00012 o controls one or more Pi's
00013 
00014 o hardware timed PWM on any of GPIO 0-31
00015 
00016 o hardware timed servo pulses on any of GPIO 0-31
00017 
00018 o callbacks when any of GPIO 0-31 change state
00019 
00020 o creating and transmitting precisely timed waveforms
00021 
00022 o reading/writing GPIO and setting their modes
00023 
00024 o wrappers for I2C, SPI, and serial links
00025 
00026 o creating and running scripts on the pigpio daemon
00027 
00028 *GPIO*
00029 
00030 ALL GPIO are identified by their Broadcom number.
00031 
00032 *Notes*
00033 
00034 Transmitted waveforms are accurate to a microsecond.
00035 
00036 Callback level changes are time-stamped and will be
00037 accurate to within a few microseconds.
00038 
00039 *Settings*
00040 
00041 A number of settings are determined when the pigpio daemon is started.
00042 
00043 o the sample rate (1, 2, 4, 5, 8, or 10 us, default 5 us).
00044 
00045 o the set of GPIO which may be updated (generally written to).  The
00046   default set is those available on the Pi board revision.
00047 
00048 o the available PWM frequencies (see [*set_PWM_frequency*]).
00049 
00050 *Exceptions*
00051 
00052 By default a fatal exception is raised if you pass an invalid
00053 argument to a pigpio function.
00054 
00055 If you wish to handle the returned status yourself you should set
00056 pigpio.exceptions to False.
00057 
00058 You may prefer to check the returned status in only a few parts
00059 of your code.  In that case do the following:
00060 
00061 ...
00062 pigpio.exceptions = False
00063 
00064 # Code where you want to test the error status.
00065 
00066 pigpio.exceptions = True
00067 ...
00068 
00069 *Usage*
00070 
00071 This module uses the services of the C pigpio library.  pigpio
00072 must be running on the Pi(s) whose GPIO are to be manipulated.
00073 
00074 The normal way to start pigpio is as a daemon (during system
00075 start).
00076 
00077 sudo pigpiod
00078 
00079 Your Python program must import pigpio and create one or more
00080 instances of the pigpio.pi class.  This class gives access to
00081 a specified Pi's GPIO.
00082 
00083 ...
00084 pi1 = pigpio.pi()       # pi1 accesses the local Pi's GPIO
00085 pi2 = pigpio.pi('tom')  # pi2 accesses tom's GPIO
00086 pi3 = pigpio.pi('dick') # pi3 accesses dick's GPIO
00087 
00088 pi1.write(4, 0) # set local Pi's GPIO 4 low
00089 pi2.write(4, 1) # set tom's GPIO 4 to high
00090 pi3.read(4)     # get level of dick's GPIO 4
00091 ...
00092 
00093 The later example code snippets assume that pi is an instance of
00094 the pigpio.pi class.
00095 
00096 OVERVIEW
00097 
00098 Essential
00099 
00100 pigpio.pi                 Initialise Pi connection
00101 stop                      Stop a Pi connection
00102 
00103 Beginner
00104 
00105 set_mode                  Set a GPIO mode
00106 get_mode                  Get a GPIO mode
00107 set_pull_up_down          Set/clear GPIO pull up/down resistor
00108 
00109 read                      Read a GPIO
00110 write                     Write a GPIO
00111 
00112 set_PWM_dutycycle         Start/stop PWM pulses on a GPIO
00113 get_PWM_dutycycle         Get PWM dutycycle set on a GPIO
00114 
00115 set_servo_pulsewidth      Start/Stop servo pulses on a GPIO
00116 get_servo_pulsewidth      Get servo pulsewidth set on a GPIO
00117 
00118 callback                  Create GPIO level change callback
00119 wait_for_edge             Wait for GPIO level change
00120 
00121 Intermediate
00122 
00123 gpio_trigger              Send a trigger pulse to a GPIO
00124 
00125 set_watchdog              Set a watchdog on a GPIO
00126 
00127 set_PWM_range             Configure PWM range of a GPIO
00128 get_PWM_range             Get configured PWM range of a GPIO
00129 
00130 set_PWM_frequency         Set PWM frequency of a GPIO
00131 get_PWM_frequency         Get PWM frequency of a GPIO
00132 
00133 read_bank_1               Read all bank 1 GPIO
00134 read_bank_2               Read all bank 2 GPIO
00135 
00136 clear_bank_1              Clear selected GPIO in bank 1
00137 clear_bank_2              Clear selected GPIO in bank 2
00138 
00139 set_bank_1                Set selected GPIO in bank 1
00140 set_bank_2                Set selected GPIO in bank 2
00141 
00142 Advanced
00143 
00144 get_PWM_real_range        Get underlying PWM range for a GPIO
00145 
00146 notify_open               Request a notification handle
00147 notify_begin              Start notifications for selected GPIO
00148 notify_pause              Pause notifications
00149 notify_close              Close a notification
00150 
00151 bb_serial_read_open       Open a GPIO for bit bang serial reads
00152 bb_serial_read            Read bit bang serial data from  a GPIO
00153 bb_serial_read_close      Close a GPIO for bit bang serial reads
00154 bb_serial_invert          Invert serial logic (1 invert, 0 normal)
00155 
00156 hardware_clock            Start hardware clock on supported GPIO
00157 hardware_PWM              Start hardware PWM on supported GPIO
00158 
00159 set_glitch_filter         Set a glitch filter on a GPIO
00160 set_noise_filter          Set a noise filter on a GPIO
00161 
00162 get_pad_strength          Gets a pads drive strength
00163 set_pad_strength          Sets a pads drive strength
00164 
00165 shell                     Executes a shell command
00166 
00167 Scripts
00168 
00169 store_script              Store a script
00170 run_script                Run a stored script
00171 update_script             Set a scripts parameters
00172 script_status             Get script status and parameters
00173 stop_script               Stop a running script
00174 delete_script             Delete a stored script
00175 
00176 Waves
00177 
00178 wave_clear                Deletes all waveforms
00179 
00180 wave_add_new              Starts a new waveform
00181 wave_add_generic          Adds a series of pulses to the waveform
00182 wave_add_serial           Adds serial data to the waveform
00183 
00184 wave_create               Creates a waveform from added data
00185 wave_delete               Deletes a waveform
00186 
00187 wave_send_once            Transmits a waveform once
00188 wave_send_repeat          Transmits a waveform repeatedly
00189 wave_send_using_mode      Transmits a waveform in the chosen mode
00190 
00191 wave_chain                Transmits a chain of waveforms
00192 
00193 wave_tx_at                Returns the current transmitting waveform
00194 wave_tx_busy              Checks to see if a waveform has ended
00195 wave_tx_stop              Aborts the current waveform
00196 
00197 wave_get_micros           Length in microseconds of the current waveform
00198 wave_get_max_micros       Absolute maximum allowed micros
00199 wave_get_pulses           Length in pulses of the current waveform
00200 wave_get_max_pulses       Absolute maximum allowed pulses
00201 wave_get_cbs              Length in cbs of the current waveform
00202 wave_get_max_cbs          Absolute maximum allowed cbs
00203 
00204 I2C
00205 
00206 i2c_open                  Opens an I2C device
00207 i2c_close                 Closes an I2C device
00208 
00209 i2c_write_quick           SMBus write quick
00210 i2c_write_byte            SMBus write byte
00211 i2c_read_byte             SMBus read byte
00212 i2c_write_byte_data       SMBus write byte data
00213 i2c_write_word_data       SMBus write word data
00214 i2c_read_byte_data        SMBus read byte data
00215 i2c_read_word_data        SMBus read word data
00216 i2c_process_call          SMBus process call
00217 i2c_write_block_data      SMBus write block data
00218 i2c_read_block_data       SMBus read block data
00219 i2c_block_process_call    SMBus block process call
00220 
00221 i2c_read_i2c_block_data   SMBus read I2C block data
00222 i2c_write_i2c_block_data  SMBus write I2C block data
00223 
00224 i2c_read_device           Reads the raw I2C device
00225 i2c_write_device          Writes the raw I2C device
00226 
00227 i2c_zip                   Performs multiple I2C transactions
00228 
00229 bb_i2c_open               Opens GPIO for bit banging I2C
00230 bb_i2c_close              Closes GPIO for bit banging I2C
00231 bb_i2c_zip                Performs multiple bit banged I2C transactions
00232 
00233 SPI
00234 
00235 spi_open                  Opens a SPI device
00236 spi_close                 Closes a SPI device
00237 
00238 spi_read                  Reads bytes from a SPI device
00239 spi_write                 Writes bytes to a SPI device
00240 spi_xfer                  Transfers bytes with a SPI device
00241 
00242 bb_spi_open               Opens GPIO for bit banging SPI
00243 bb_spi_close              Closes GPIO for bit banging SPI
00244 bb_spi_xfer               Transfers bytes with bit banging SPI
00245 
00246 I2C/SPI_Slave
00247 
00248 bsc_xfer                  I2C/SPI as slave transfer
00249 bsc_i2c                   I2C as slave transfer
00250 
00251 Serial
00252 
00253 serial_open               Opens a serial device
00254 serial_close              Closes a serial device
00255 
00256 serial_read               Reads bytes from a serial device
00257 serial_read_byte          Reads a byte from a serial device
00258 
00259 serial_write              Writes bytes to a serial device
00260 serial_write_byte         Writes a byte to a serial device
00261 
00262 serial_data_available     Returns number of bytes ready to be read
00263 
00264 Files
00265 
00266 file_open                 Opens a file
00267 file_close                Closes a file
00268 file_read                 Reads bytes from a file
00269 file_write                Writes bytes to a file
00270 file_seek                 Seeks to a position within a file
00271 file_list                 List files which match a pattern
00272 
00273 Events
00274 
00275 event_callback            Sets a callback for an event
00276 event_trigger             Triggers an event
00277 wait_for_event            Wait for an event
00278 
00279 Custom
00280 
00281 custom_1                  User custom function 1
00282 custom_2                  User custom function 2
00283 
00284 Utility
00285 
00286 get_current_tick          Get current tick (microseconds)
00287 
00288 get_hardware_revision     Get hardware revision
00289 get_pigpio_version        Get the pigpio version
00290 
00291 pigpio.error_text         Gets error text from error number
00292 pigpio.tickDiff           Returns difference between two ticks
00293 """
00294 
00295 import sys
00296 import socket
00297 import struct
00298 import time
00299 import threading
00300 import os
00301 import atexit
00302 
00303 VERSION = "1.41"
00304 
00305 exceptions = True
00306 
00307 # GPIO levels
00308 
00309 OFF   = 0
00310 LOW   = 0
00311 CLEAR = 0
00312 
00313 ON   = 1
00314 HIGH = 1
00315 SET  = 1
00316 
00317 TIMEOUT = 2
00318 
00319 # GPIO edges
00320 
00321 RISING_EDGE  = 0
00322 FALLING_EDGE = 1
00323 EITHER_EDGE  = 2
00324 
00325 # GPIO modes
00326 
00327 INPUT  = 0
00328 OUTPUT = 1
00329 ALT0   = 4
00330 ALT1   = 5
00331 ALT2   = 6
00332 ALT3   = 7
00333 ALT4   = 3
00334 ALT5   = 2
00335 
00336 # GPIO Pull Up Down
00337 
00338 PUD_OFF  = 0
00339 PUD_DOWN = 1
00340 PUD_UP   = 2
00341 
00342 # script run status
00343 
00344 PI_SCRIPT_INITING=0
00345 PI_SCRIPT_HALTED =1
00346 PI_SCRIPT_RUNNING=2
00347 PI_SCRIPT_WAITING=3
00348 PI_SCRIPT_FAILED =4
00349 
00350 # notification flags
00351 
00352 NTFY_FLAGS_EVENT = (1 << 7)
00353 NTFY_FLAGS_ALIVE = (1 << 6)
00354 NTFY_FLAGS_WDOG  = (1 << 5)
00355 NTFY_FLAGS_GPIO  = 31
00356 
00357 # wave modes
00358 
00359 WAVE_MODE_ONE_SHOT     =0
00360 WAVE_MODE_REPEAT       =1
00361 WAVE_MODE_ONE_SHOT_SYNC=2
00362 WAVE_MODE_REPEAT_SYNC  =3
00363 
00364 WAVE_NOT_FOUND = 9998 # Transmitted wave not found.
00365 NO_TX_WAVE     = 9999 # No wave being transmitted.
00366 
00367 FILE_READ=1
00368 FILE_WRITE=2
00369 FILE_RW=3
00370 
00371 FILE_APPEND=4
00372 FILE_CREATE=8
00373 FILE_TRUNC=16
00374 
00375 FROM_START=0
00376 FROM_CURRENT=1
00377 FROM_END=2
00378 
00379 SPI_MODE_0 = 0
00380 SPI_MODE_1 = 1
00381 SPI_MODE_2 = 2
00382 SPI_MODE_3 = 3
00383 
00384 SPI_CPHA = 1 << 0
00385 SPI_CPOL = 1 << 1
00386 
00387 SPI_CS_HIGH_ACTIVE  = 1 << 2
00388 
00389 SPI_TX_LSBFIRST = 1 << 14
00390 SPI_RX_LSBFIRST = 1 << 15
00391 
00392 EVENT_BSC = 31
00393 
00394 _SOCK_CMD_LEN = 16
00395 
00396 # pigpio command numbers
00397 
00398 _PI_CMD_MODES= 0
00399 _PI_CMD_MODEG= 1
00400 _PI_CMD_PUD=   2
00401 _PI_CMD_READ=  3
00402 _PI_CMD_WRITE= 4
00403 _PI_CMD_PWM=   5
00404 _PI_CMD_PRS=   6
00405 _PI_CMD_PFS=   7
00406 _PI_CMD_SERVO= 8
00407 _PI_CMD_WDOG=  9
00408 _PI_CMD_BR1=  10
00409 _PI_CMD_BR2=  11
00410 _PI_CMD_BC1=  12
00411 _PI_CMD_BC2=  13
00412 _PI_CMD_BS1=  14
00413 _PI_CMD_BS2=  15
00414 _PI_CMD_TICK= 16
00415 _PI_CMD_HWVER=17
00416 
00417 _PI_CMD_NO=   18
00418 _PI_CMD_NB=   19
00419 _PI_CMD_NP=   20
00420 _PI_CMD_NC=   21
00421 
00422 _PI_CMD_PRG=  22
00423 _PI_CMD_PFG=  23
00424 _PI_CMD_PRRG= 24
00425 _PI_CMD_HELP= 25
00426 _PI_CMD_PIGPV=26
00427 
00428 _PI_CMD_WVCLR=27
00429 _PI_CMD_WVAG= 28
00430 _PI_CMD_WVAS= 29
00431 _PI_CMD_WVGO= 30
00432 _PI_CMD_WVGOR=31
00433 _PI_CMD_WVBSY=32
00434 _PI_CMD_WVHLT=33
00435 _PI_CMD_WVSM= 34
00436 _PI_CMD_WVSP= 35
00437 _PI_CMD_WVSC= 36
00438 
00439 _PI_CMD_TRIG= 37
00440 
00441 _PI_CMD_PROC= 38
00442 _PI_CMD_PROCD=39
00443 _PI_CMD_PROCR=40
00444 _PI_CMD_PROCS=41
00445 
00446 _PI_CMD_SLRO= 42
00447 _PI_CMD_SLR=  43
00448 _PI_CMD_SLRC= 44
00449 
00450 _PI_CMD_PROCP=45
00451 _PI_CMD_MICRO=46
00452 _PI_CMD_MILLI=47
00453 _PI_CMD_PARSE=48
00454 
00455 _PI_CMD_WVCRE=49
00456 _PI_CMD_WVDEL=50
00457 _PI_CMD_WVTX =51
00458 _PI_CMD_WVTXR=52
00459 _PI_CMD_WVNEW=53
00460 
00461 _PI_CMD_I2CO =54
00462 _PI_CMD_I2CC =55
00463 _PI_CMD_I2CRD=56
00464 _PI_CMD_I2CWD=57
00465 _PI_CMD_I2CWQ=58
00466 _PI_CMD_I2CRS=59
00467 _PI_CMD_I2CWS=60
00468 _PI_CMD_I2CRB=61
00469 _PI_CMD_I2CWB=62
00470 _PI_CMD_I2CRW=63
00471 _PI_CMD_I2CWW=64
00472 _PI_CMD_I2CRK=65
00473 _PI_CMD_I2CWK=66
00474 _PI_CMD_I2CRI=67
00475 _PI_CMD_I2CWI=68
00476 _PI_CMD_I2CPC=69
00477 _PI_CMD_I2CPK=70
00478 
00479 _PI_CMD_SPIO =71
00480 _PI_CMD_SPIC =72
00481 _PI_CMD_SPIR =73
00482 _PI_CMD_SPIW =74
00483 _PI_CMD_SPIX =75
00484 
00485 _PI_CMD_SERO =76
00486 _PI_CMD_SERC =77
00487 _PI_CMD_SERRB=78
00488 _PI_CMD_SERWB=79
00489 _PI_CMD_SERR =80
00490 _PI_CMD_SERW =81
00491 _PI_CMD_SERDA=82
00492 
00493 _PI_CMD_GDC  =83
00494 _PI_CMD_GPW  =84
00495 
00496 _PI_CMD_HC   =85
00497 _PI_CMD_HP   =86
00498 
00499 _PI_CMD_CF1  =87
00500 _PI_CMD_CF2  =88
00501 
00502 _PI_CMD_NOIB =99
00503 
00504 _PI_CMD_BI2CC=89
00505 _PI_CMD_BI2CO=90
00506 _PI_CMD_BI2CZ=91
00507 
00508 _PI_CMD_I2CZ =92
00509 
00510 _PI_CMD_WVCHA=93
00511 
00512 _PI_CMD_SLRI =94
00513 
00514 _PI_CMD_CGI  =95
00515 _PI_CMD_CSI  =96
00516 
00517 _PI_CMD_FG   =97
00518 _PI_CMD_FN   =98
00519 
00520 _PI_CMD_WVTXM=100
00521 _PI_CMD_WVTAT=101
00522 
00523 _PI_CMD_PADS =102
00524 _PI_CMD_PADG =103
00525 
00526 _PI_CMD_FO   =104
00527 _PI_CMD_FC   =105
00528 _PI_CMD_FR   =106
00529 _PI_CMD_FW   =107
00530 _PI_CMD_FS   =108
00531 _PI_CMD_FL   =109
00532 _PI_CMD_SHELL=110
00533 
00534 _PI_CMD_BSPIC=111
00535 _PI_CMD_BSPIO=112
00536 _PI_CMD_BSPIX=113
00537 
00538 _PI_CMD_BSCX =114
00539 
00540 _PI_CMD_EVM  =115
00541 _PI_CMD_EVT  =116
00542 
00543 _PI_CMD_PROCU=117
00544 
00545 # pigpio error numbers
00546 
00547 _PI_INIT_FAILED     =-1
00548 PI_BAD_USER_GPIO    =-2
00549 PI_BAD_GPIO         =-3
00550 PI_BAD_MODE         =-4
00551 PI_BAD_LEVEL        =-5
00552 PI_BAD_PUD          =-6
00553 PI_BAD_PULSEWIDTH   =-7
00554 PI_BAD_DUTYCYCLE    =-8
00555 _PI_BAD_TIMER       =-9
00556 _PI_BAD_MS          =-10
00557 _PI_BAD_TIMETYPE    =-11
00558 _PI_BAD_SECONDS     =-12
00559 _PI_BAD_MICROS      =-13
00560 _PI_TIMER_FAILED    =-14
00561 PI_BAD_WDOG_TIMEOUT =-15
00562 _PI_NO_ALERT_FUNC   =-16
00563 _PI_BAD_CLK_PERIPH  =-17
00564 _PI_BAD_CLK_SOURCE  =-18
00565 _PI_BAD_CLK_MICROS  =-19
00566 _PI_BAD_BUF_MILLIS  =-20
00567 PI_BAD_DUTYRANGE    =-21
00568 _PI_BAD_SIGNUM      =-22
00569 _PI_BAD_PATHNAME    =-23
00570 PI_NO_HANDLE        =-24
00571 PI_BAD_HANDLE       =-25
00572 _PI_BAD_IF_FLAGS    =-26
00573 _PI_BAD_CHANNEL     =-27
00574 _PI_BAD_PRIM_CHANNEL=-27
00575 _PI_BAD_SOCKET_PORT =-28
00576 _PI_BAD_FIFO_COMMAND=-29
00577 _PI_BAD_SECO_CHANNEL=-30
00578 _PI_NOT_INITIALISED =-31
00579 _PI_INITIALISED     =-32
00580 _PI_BAD_WAVE_MODE   =-33
00581 _PI_BAD_CFG_INTERNAL=-34
00582 PI_BAD_WAVE_BAUD    =-35
00583 PI_TOO_MANY_PULSES  =-36
00584 PI_TOO_MANY_CHARS   =-37
00585 PI_NOT_SERIAL_GPIO  =-38
00586 _PI_BAD_SERIAL_STRUC=-39
00587 _PI_BAD_SERIAL_BUF  =-40
00588 PI_NOT_PERMITTED    =-41
00589 PI_SOME_PERMITTED   =-42
00590 PI_BAD_WVSC_COMMND  =-43
00591 PI_BAD_WVSM_COMMND  =-44
00592 PI_BAD_WVSP_COMMND  =-45
00593 PI_BAD_PULSELEN     =-46
00594 PI_BAD_SCRIPT       =-47
00595 PI_BAD_SCRIPT_ID    =-48
00596 PI_BAD_SER_OFFSET   =-49
00597 PI_GPIO_IN_USE      =-50
00598 PI_BAD_SERIAL_COUNT =-51
00599 PI_BAD_PARAM_NUM    =-52
00600 PI_DUP_TAG          =-53
00601 PI_TOO_MANY_TAGS    =-54
00602 PI_BAD_SCRIPT_CMD   =-55
00603 PI_BAD_VAR_NUM      =-56
00604 PI_NO_SCRIPT_ROOM   =-57
00605 PI_NO_MEMORY        =-58
00606 PI_SOCK_READ_FAILED =-59
00607 PI_SOCK_WRIT_FAILED =-60
00608 PI_TOO_MANY_PARAM   =-61
00609 PI_SCRIPT_NOT_READY =-62
00610 PI_BAD_TAG          =-63
00611 PI_BAD_MICS_DELAY   =-64
00612 PI_BAD_MILS_DELAY   =-65
00613 PI_BAD_WAVE_ID      =-66
00614 PI_TOO_MANY_CBS     =-67
00615 PI_TOO_MANY_OOL     =-68
00616 PI_EMPTY_WAVEFORM   =-69
00617 PI_NO_WAVEFORM_ID   =-70
00618 PI_I2C_OPEN_FAILED  =-71
00619 PI_SER_OPEN_FAILED  =-72
00620 PI_SPI_OPEN_FAILED  =-73
00621 PI_BAD_I2C_BUS      =-74
00622 PI_BAD_I2C_ADDR     =-75
00623 PI_BAD_SPI_CHANNEL  =-76
00624 PI_BAD_FLAGS        =-77
00625 PI_BAD_SPI_SPEED    =-78
00626 PI_BAD_SER_DEVICE   =-79
00627 PI_BAD_SER_SPEED    =-80
00628 PI_BAD_PARAM        =-81
00629 PI_I2C_WRITE_FAILED =-82
00630 PI_I2C_READ_FAILED  =-83
00631 PI_BAD_SPI_COUNT    =-84
00632 PI_SER_WRITE_FAILED =-85
00633 PI_SER_READ_FAILED  =-86
00634 PI_SER_READ_NO_DATA =-87
00635 PI_UNKNOWN_COMMAND  =-88
00636 PI_SPI_XFER_FAILED  =-89
00637 _PI_BAD_POINTER     =-90
00638 PI_NO_AUX_SPI       =-91
00639 PI_NOT_PWM_GPIO     =-92
00640 PI_NOT_SERVO_GPIO   =-93
00641 PI_NOT_HCLK_GPIO    =-94
00642 PI_NOT_HPWM_GPIO    =-95
00643 PI_BAD_HPWM_FREQ    =-96
00644 PI_BAD_HPWM_DUTY    =-97
00645 PI_BAD_HCLK_FREQ    =-98
00646 PI_BAD_HCLK_PASS    =-99
00647 PI_HPWM_ILLEGAL     =-100
00648 PI_BAD_DATABITS     =-101
00649 PI_BAD_STOPBITS     =-102
00650 PI_MSG_TOOBIG       =-103
00651 PI_BAD_MALLOC_MODE  =-104
00652 _PI_TOO_MANY_SEGS   =-105
00653 _PI_BAD_I2C_SEG     =-106
00654 PI_BAD_SMBUS_CMD    =-107
00655 PI_NOT_I2C_GPIO     =-108
00656 PI_BAD_I2C_WLEN     =-109
00657 PI_BAD_I2C_RLEN     =-110
00658 PI_BAD_I2C_CMD      =-111
00659 PI_BAD_I2C_BAUD     =-112
00660 PI_CHAIN_LOOP_CNT   =-113
00661 PI_BAD_CHAIN_LOOP   =-114
00662 PI_CHAIN_COUNTER    =-115
00663 PI_BAD_CHAIN_CMD    =-116
00664 PI_BAD_CHAIN_DELAY  =-117
00665 PI_CHAIN_NESTING    =-118
00666 PI_CHAIN_TOO_BIG    =-119
00667 PI_DEPRECATED       =-120
00668 PI_BAD_SER_INVERT   =-121
00669 _PI_BAD_EDGE        =-122
00670 _PI_BAD_ISR_INIT    =-123
00671 PI_BAD_FOREVER      =-124
00672 PI_BAD_FILTER       =-125
00673 PI_BAD_PAD          =-126
00674 PI_BAD_STRENGTH     =-127
00675 PI_FIL_OPEN_FAILED  =-128
00676 PI_BAD_FILE_MODE    =-129
00677 PI_BAD_FILE_FLAG    =-130
00678 PI_BAD_FILE_READ    =-131
00679 PI_BAD_FILE_WRITE   =-132
00680 PI_FILE_NOT_ROPEN   =-133
00681 PI_FILE_NOT_WOPEN   =-134
00682 PI_BAD_FILE_SEEK    =-135
00683 PI_NO_FILE_MATCH    =-136
00684 PI_NO_FILE_ACCESS   =-137
00685 PI_FILE_IS_A_DIR    =-138
00686 PI_BAD_SHELL_STATUS =-139
00687 PI_BAD_SCRIPT_NAME  =-140
00688 PI_BAD_SPI_BAUD     =-141
00689 PI_NOT_SPI_GPIO     =-142
00690 PI_BAD_EVENT_ID     =-143
00691 PI_CMD_INTERRUPTED  =-144
00692 
00693 # pigpio error text
00694 
00695 _errors=[
00696    [_PI_INIT_FAILED      , "pigpio initialisation failed"],
00697    [PI_BAD_USER_GPIO     , "GPIO not 0-31"],
00698    [PI_BAD_GPIO          , "GPIO not 0-53"],
00699    [PI_BAD_MODE          , "mode not 0-7"],
00700    [PI_BAD_LEVEL         , "level not 0-1"],
00701    [PI_BAD_PUD           , "pud not 0-2"],
00702    [PI_BAD_PULSEWIDTH    , "pulsewidth not 0 or 500-2500"],
00703    [PI_BAD_DUTYCYCLE     , "dutycycle not 0-range (default 255)"],
00704    [_PI_BAD_TIMER        , "timer not 0-9"],
00705    [_PI_BAD_MS           , "ms not 10-60000"],
00706    [_PI_BAD_TIMETYPE     , "timetype not 0-1"],
00707    [_PI_BAD_SECONDS      , "seconds < 0"],
00708    [_PI_BAD_MICROS       , "micros not 0-999999"],
00709    [_PI_TIMER_FAILED     , "gpioSetTimerFunc failed"],
00710    [PI_BAD_WDOG_TIMEOUT  , "timeout not 0-60000"],
00711    [_PI_NO_ALERT_FUNC    , "DEPRECATED"],
00712    [_PI_BAD_CLK_PERIPH   , "clock peripheral not 0-1"],
00713    [_PI_BAD_CLK_SOURCE   , "DEPRECATED"],
00714    [_PI_BAD_CLK_MICROS   , "clock micros not 1, 2, 4, 5, 8, or 10"],
00715    [_PI_BAD_BUF_MILLIS   , "buf millis not 100-10000"],
00716    [PI_BAD_DUTYRANGE     , "dutycycle range not 25-40000"],
00717    [_PI_BAD_SIGNUM       , "signum not 0-63"],
00718    [_PI_BAD_PATHNAME     , "can't open pathname"],
00719    [PI_NO_HANDLE         , "no handle available"],
00720    [PI_BAD_HANDLE        , "unknown handle"],
00721    [_PI_BAD_IF_FLAGS     , "ifFlags > 4"],
00722    [_PI_BAD_CHANNEL      , "DMA channel not 0-14"],
00723    [_PI_BAD_SOCKET_PORT  , "socket port not 1024-30000"],
00724    [_PI_BAD_FIFO_COMMAND , "unknown fifo command"],
00725    [_PI_BAD_SECO_CHANNEL , "DMA secondary channel not 0-14"],
00726    [_PI_NOT_INITIALISED  , "function called before gpioInitialise"],
00727    [_PI_INITIALISED      , "function called after gpioInitialise"],
00728    [_PI_BAD_WAVE_MODE    , "waveform mode not 0-1"],
00729    [_PI_BAD_CFG_INTERNAL , "bad parameter in gpioCfgInternals call"],
00730    [PI_BAD_WAVE_BAUD     , "baud rate not 50-250000(RX)/1000000(TX)"],
00731    [PI_TOO_MANY_PULSES   , "waveform has too many pulses"],
00732    [PI_TOO_MANY_CHARS    , "waveform has too many chars"],
00733    [PI_NOT_SERIAL_GPIO   , "no bit bang serial read in progress on GPIO"],
00734    [PI_NOT_PERMITTED     , "no permission to update GPIO"],
00735    [PI_SOME_PERMITTED    , "no permission to update one or more GPIO"],
00736    [PI_BAD_WVSC_COMMND   , "bad WVSC subcommand"],
00737    [PI_BAD_WVSM_COMMND   , "bad WVSM subcommand"],
00738    [PI_BAD_WVSP_COMMND   , "bad WVSP subcommand"],
00739    [PI_BAD_PULSELEN      , "trigger pulse length not 1-100"],
00740    [PI_BAD_SCRIPT        , "invalid script"],
00741    [PI_BAD_SCRIPT_ID     , "unknown script id"],
00742    [PI_BAD_SER_OFFSET    , "add serial data offset > 30 minute"],
00743    [PI_GPIO_IN_USE       , "GPIO already in use"],
00744    [PI_BAD_SERIAL_COUNT  , "must read at least a byte at a time"],
00745    [PI_BAD_PARAM_NUM     , "script parameter id not 0-9"],
00746    [PI_DUP_TAG           , "script has duplicate tag"],
00747    [PI_TOO_MANY_TAGS     , "script has too many tags"],
00748    [PI_BAD_SCRIPT_CMD    , "illegal script command"],
00749    [PI_BAD_VAR_NUM       , "script variable id not 0-149"],
00750    [PI_NO_SCRIPT_ROOM    , "no more room for scripts"],
00751    [PI_NO_MEMORY         , "can't allocate temporary memory"],
00752    [PI_SOCK_READ_FAILED  , "socket read failed"],
00753    [PI_SOCK_WRIT_FAILED  , "socket write failed"],
00754    [PI_TOO_MANY_PARAM    , "too many script parameters (> 10)"],
00755    [PI_SCRIPT_NOT_READY  , "script initialising"],
00756    [PI_BAD_TAG           , "script has unresolved tag"],
00757    [PI_BAD_MICS_DELAY    , "bad MICS delay (too large)"],
00758    [PI_BAD_MILS_DELAY    , "bad MILS delay (too large)"],
00759    [PI_BAD_WAVE_ID       , "non existent wave id"],
00760    [PI_TOO_MANY_CBS      , "No more CBs for waveform"],
00761    [PI_TOO_MANY_OOL      , "No more OOL for waveform"],
00762    [PI_EMPTY_WAVEFORM    , "attempt to create an empty waveform"],
00763    [PI_NO_WAVEFORM_ID    , "No more waveform ids"],
00764    [PI_I2C_OPEN_FAILED   , "can't open I2C device"],
00765    [PI_SER_OPEN_FAILED   , "can't open serial device"],
00766    [PI_SPI_OPEN_FAILED   , "can't open SPI device"],
00767    [PI_BAD_I2C_BUS       , "bad I2C bus"],
00768    [PI_BAD_I2C_ADDR      , "bad I2C address"],
00769    [PI_BAD_SPI_CHANNEL   , "bad SPI channel"],
00770    [PI_BAD_FLAGS         , "bad i2c/spi/ser open flags"],
00771    [PI_BAD_SPI_SPEED     , "bad SPI speed"],
00772    [PI_BAD_SER_DEVICE    , "bad serial device name"],
00773    [PI_BAD_SER_SPEED     , "bad serial baud rate"],
00774    [PI_BAD_PARAM         , "bad i2c/spi/ser parameter"],
00775    [PI_I2C_WRITE_FAILED  , "I2C write failed"],
00776    [PI_I2C_READ_FAILED   , "I2C read failed"],
00777    [PI_BAD_SPI_COUNT     , "bad SPI count"],
00778    [PI_SER_WRITE_FAILED  , "ser write failed"],
00779    [PI_SER_READ_FAILED   , "ser read failed"],
00780    [PI_SER_READ_NO_DATA  , "ser read no data available"],
00781    [PI_UNKNOWN_COMMAND   , "unknown command"],
00782    [PI_SPI_XFER_FAILED   , "SPI xfer/read/write failed"],
00783    [_PI_BAD_POINTER      , "bad (NULL) pointer"],
00784    [PI_NO_AUX_SPI        , "no auxiliary SPI on Pi A or B"],
00785    [PI_NOT_PWM_GPIO      , "GPIO is not in use for PWM"],
00786    [PI_NOT_SERVO_GPIO    , "GPIO is not in use for servo pulses"],
00787    [PI_NOT_HCLK_GPIO     , "GPIO has no hardware clock"],
00788    [PI_NOT_HPWM_GPIO     , "GPIO has no hardware PWM"],
00789    [PI_BAD_HPWM_FREQ     , "hardware PWM frequency not 1-125M"],
00790    [PI_BAD_HPWM_DUTY     , "hardware PWM dutycycle not 0-1M"],
00791    [PI_BAD_HCLK_FREQ     , "hardware clock frequency not 4689-250M"],
00792    [PI_BAD_HCLK_PASS     , "need password to use hardware clock 1"],
00793    [PI_HPWM_ILLEGAL      , "illegal, PWM in use for main clock"],
00794    [PI_BAD_DATABITS      , "serial data bits not 1-32"],
00795    [PI_BAD_STOPBITS      , "serial (half) stop bits not 2-8"],
00796    [PI_MSG_TOOBIG        , "socket/pipe message too big"],
00797    [PI_BAD_MALLOC_MODE   , "bad memory allocation mode"],
00798    [_PI_TOO_MANY_SEGS    , "too many I2C transaction segments"],
00799    [_PI_BAD_I2C_SEG      , "an I2C transaction segment failed"],
00800    [PI_BAD_SMBUS_CMD     , "SMBus command not supported"],
00801    [PI_NOT_I2C_GPIO      , "no bit bang I2C in progress on GPIO"],
00802    [PI_BAD_I2C_WLEN      , "bad I2C write length"],
00803    [PI_BAD_I2C_RLEN      , "bad I2C read length"],
00804    [PI_BAD_I2C_CMD       , "bad I2C command"],
00805    [PI_BAD_I2C_BAUD      , "bad I2C baud rate, not 50-500k"],
00806    [PI_CHAIN_LOOP_CNT    , "bad chain loop count"],
00807    [PI_BAD_CHAIN_LOOP    , "empty chain loop"],
00808    [PI_CHAIN_COUNTER     , "too many chain counters"],
00809    [PI_BAD_CHAIN_CMD     , "bad chain command"],
00810    [PI_BAD_CHAIN_DELAY   , "bad chain delay micros"],
00811    [PI_CHAIN_NESTING     , "chain counters nested too deeply"],
00812    [PI_CHAIN_TOO_BIG     , "chain is too long"],
00813    [PI_DEPRECATED        , "deprecated function removed"],
00814    [PI_BAD_SER_INVERT    , "bit bang serial invert not 0 or 1"],
00815    [_PI_BAD_EDGE         , "bad ISR edge value, not 0-2"],
00816    [_PI_BAD_ISR_INIT     , "bad ISR initialisation"],
00817    [PI_BAD_FOREVER       , "loop forever must be last chain command"],
00818    [PI_BAD_FILTER        , "bad filter parameter"],
00819    [PI_BAD_PAD           , "bad pad number"],
00820    [PI_BAD_STRENGTH      , "bad pad drive strength"],
00821    [PI_FIL_OPEN_FAILED   , "file open failed"],
00822    [PI_BAD_FILE_MODE     , "bad file mode"],
00823    [PI_BAD_FILE_FLAG     , "bad file flag"],
00824    [PI_BAD_FILE_READ     , "bad file read"],
00825    [PI_BAD_FILE_WRITE    , "bad file write"],
00826    [PI_FILE_NOT_ROPEN    , "file not open for read"],
00827    [PI_FILE_NOT_WOPEN    , "file not open for write"],
00828    [PI_BAD_FILE_SEEK     , "bad file seek"],
00829    [PI_NO_FILE_MATCH     , "no files match pattern"],
00830    [PI_NO_FILE_ACCESS    , "no permission to access file"],
00831    [PI_FILE_IS_A_DIR     , "file is a directory"],
00832    [PI_BAD_SHELL_STATUS  , "bad shell return status"],
00833    [PI_BAD_SCRIPT_NAME   , "bad script name"],
00834    [PI_BAD_SPI_BAUD      , "bad SPI baud rate, not 50-500k"],
00835    [PI_NOT_SPI_GPIO      , "no bit bang SPI in progress on GPIO"],
00836    [PI_BAD_EVENT_ID      , "bad event id"],
00837    [PI_CMD_INTERRUPTED   , "pigpio command interrupted"],
00838 ]
00839 
00840 _except_a = "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n{}"
00841 
00842 _except_z = "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
00843 
00844 _except_1 = """
00845 Did you start the pigpio daemon? E.g. sudo pigpiod
00846 
00847 Did you specify the correct Pi host/port in the environment
00848 variables PIGPIO_ADDR/PIGPIO_PORT?
00849 E.g. export PIGPIO_ADDR=soft, export PIGPIO_PORT=8888
00850 
00851 Did you specify the correct Pi host/port in the
00852 pigpio.pi() function? E.g. pigpio.pi('soft', 8888)"""
00853 
00854 _except_2 = """
00855 Do you have permission to access the pigpio daemon?
00856 Perhaps it was started with sudo pigpiod -nlocalhost"""
00857 
00858 _except_3 = """
00859 Can't create callback thread.
00860 Perhaps too many simultaneous pigpio connections."""
00861 
00862 class _socklock:
00863    """
00864    A class to store socket and lock.
00865    """
00866    def __init__(self):
00867       self.s = None
00868       self.l = threading.Lock()
00869 
00870 class error(Exception):
00871    """pigpio module exception"""
00872    def __init__(self, value):
00873       self.value = value
00874    def __str__(self):
00875       return repr(self.value)
00876 
00877 class pulse:
00878    """
00879    A class to store pulse information.
00880    """
00881 
00882    def __init__(self, gpio_on, gpio_off, delay):
00883       """
00884       Initialises a pulse.
00885 
00886        gpio_on:= the GPIO to switch on at the start of the pulse.
00887       gpio_off:= the GPIO to switch off at the start of the pulse.
00888          delay:= the delay in microseconds before the next pulse.
00889 
00890       """
00891       self.gpio_on = gpio_on
00892       self.gpio_off = gpio_off
00893       self.delay = delay
00894 
00895 def error_text(errnum):
00896    """
00897    Returns a text description of a pigpio error.
00898 
00899    errnum:= <0, the error number
00900 
00901    ...
00902    print(pigpio.error_text(-5))
00903    level not 0-1
00904    ...
00905    """
00906    for e in _errors:
00907       if e[0] == errnum:
00908          return e[1]
00909    return "unknown error ({})".format(errnum)
00910 
00911 def tickDiff(t1, t2):
00912    """
00913    Returns the microsecond difference between two ticks.
00914 
00915    t1:= the earlier tick
00916    t2:= the later tick
00917 
00918    ...
00919    print(pigpio.tickDiff(4294967272, 12))
00920    36
00921    ...
00922    """
00923    tDiff = t2 - t1
00924    if tDiff < 0:
00925       tDiff += (1 << 32)
00926    return tDiff
00927 
00928 # A couple of hacks to cope with different string handling
00929 # between various Python versions
00930 # 3 != 2.7.8 != 2.7.3
00931 
00932 if sys.hexversion < 0x03000000:
00933    def _b(x):
00934       return x
00935 else:
00936    def _b(x):
00937       return x.encode('latin-1')
00938 
00939 if sys.hexversion < 0x02070800:
00940    def _str(x):
00941       return buffer(x)
00942 else:
00943    def _str(x):
00944       return x
00945 
00946 def u2i(uint32):
00947    """
00948    Converts a 32 bit unsigned number to signed.
00949 
00950    uint32:= an unsigned 32 bit number
00951 
00952    ...
00953    print(u2i(4294967272))
00954    -24
00955    print(u2i(37))
00956    37
00957    ...
00958    """
00959    mask = (2 ** 32) - 1
00960    if uint32 & (1 << 31):
00961       v = uint32 | ~mask
00962    else:
00963       v = uint32 & mask
00964    return v
00965 
00966 def _u2i(uint32):
00967    """
00968    Converts a 32 bit unsigned number to signed.  If the number
00969    is negative it indicates an error.  On error a pigpio
00970    exception will be raised if exceptions is True.
00971    """
00972    v = u2i(uint32)
00973    if v < 0:
00974       if exceptions:
00975          raise error(error_text(v))
00976    return v
00977 
00978 def _pigpio_command(sl, cmd, p1, p2):
00979    """
00980    Runs a pigpio socket command.
00981 
00982     sl:= command socket and lock.
00983    cmd:= the command to be executed.
00984     p1:= command parameter 1 (if applicable).
00985     p2:= command parameter 2 (if applicable).
00986    """
00987    res = PI_CMD_INTERRUPTED
00988    with sl.l:
00989       sl.s.send(struct.pack('IIII', cmd, p1, p2, 0))
00990       dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
00991    return res
00992 
00993 def _pigpio_command_nolock(sl, cmd, p1, p2):
00994    """
00995    Runs a pigpio socket command.
00996 
00997     sl:= command socket and lock.
00998    cmd:= the command to be executed.
00999     p1:= command parameter 1 (if applicable).
01000     p2:= command parameter 2 (if applicable).
01001    """
01002    res = PI_CMD_INTERRUPTED
01003    sl.s.send(struct.pack('IIII', cmd, p1, p2, 0))
01004    dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
01005    return res
01006 
01007 def _pigpio_command_ext(sl, cmd, p1, p2, p3, extents):
01008    """
01009    Runs an extended pigpio socket command.
01010 
01011         sl:= command socket and lock.
01012        cmd:= the command to be executed.
01013         p1:= command parameter 1 (if applicable).
01014         p2:= command parameter 2 (if applicable).
01015         p3:= total size in bytes of following extents
01016    extents:= additional data blocks
01017    """
01018    ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
01019    for x in extents:
01020       if type(x) == type(""):
01021          ext.extend(_b(x))
01022       else:
01023          ext.extend(x)
01024    res = PI_CMD_INTERRUPTED
01025    with sl.l:
01026       sl.s.sendall(ext)
01027       dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
01028    return res
01029 
01030 def _pigpio_command_ext_nolock(sl, cmd, p1, p2, p3, extents):
01031    """
01032    Runs an extended pigpio socket command.
01033 
01034         sl:= command socket and lock.
01035        cmd:= the command to be executed.
01036         p1:= command parameter 1 (if applicable).
01037         p2:= command parameter 2 (if applicable).
01038         p3:= total size in bytes of following extents
01039    extents:= additional data blocks
01040    """
01041    res = PI_CMD_INTERRUPTED
01042    ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
01043    for x in extents:
01044       if type(x) == type(""):
01045          ext.extend(_b(x))
01046       else:
01047          ext.extend(x)
01048    sl.s.sendall(ext)
01049    dummy, res = struct.unpack('12sI', sl.s.recv(_SOCK_CMD_LEN))
01050    return res
01051 
01052 class _event_ADT:
01053    """
01054    An ADT class to hold event callback information.
01055    """
01056 
01057    def __init__(self, event, func):
01058       """
01059       Initialises an event callback ADT.
01060 
01061       event:= the event id.
01062        func:= a user function taking one argument, the event id.
01063       """
01064       self.event = event
01065       self.func = func
01066       self.bit = 1<<event
01067 
01068 class _callback_ADT:
01069    """An ADT class to hold callback information."""
01070 
01071    def __init__(self, gpio, edge, func):
01072       """
01073       Initialises a callback ADT.
01074 
01075       gpio:= Broadcom GPIO number.
01076       edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
01077       func:= a user function taking three arguments (GPIO, level, tick).
01078       """
01079       self.gpio = gpio
01080       self.edge = edge
01081       self.func = func
01082       self.bit = 1<<gpio
01083 
01084 class _callback_thread(threading.Thread):
01085    """A class to encapsulate pigpio notification callbacks."""
01086    def __init__(self, control, host, port):
01087       """Initialises notifications."""
01088       threading.Thread.__init__(self)
01089       self.control = control
01090       self.sl = _socklock()
01091       self.go = False
01092       self.daemon = True
01093       self.monitor = 0
01094       self.event_bits = 0
01095       self.callbacks = []
01096       self.events = []
01097       self.sl.s = socket.create_connection((host, port), None)
01098       self.lastLevel = _pigpio_command(self.sl,  _PI_CMD_BR1, 0, 0)
01099       self.handle = _u2i(_pigpio_command(self.sl, _PI_CMD_NOIB, 0, 0))
01100       self.go = True
01101       self.start()
01102 
01103    def stop(self):
01104       """Stops notifications."""
01105       if self.go:
01106          self.go = False
01107          self.sl.s.send(struct.pack('IIII', _PI_CMD_NC, self.handle, 0, 0))
01108 
01109    def append(self, callb):
01110       """Adds a callback to the notification thread."""
01111       self.callbacks.append(callb)
01112       self.monitor = self.monitor | callb.bit
01113       _pigpio_command(self.control, _PI_CMD_NB, self.handle, self.monitor)
01114 
01115    def remove(self, callb):
01116       """Removes a callback from the notification thread."""
01117       if callb in self.callbacks:
01118          self.callbacks.remove(callb)
01119          newMonitor = 0
01120          for c in self.callbacks:
01121             newMonitor |= c.bit
01122          if newMonitor != self.monitor:
01123             self.monitor = newMonitor
01124             _pigpio_command(
01125                self.control, _PI_CMD_NB, self.handle, self.monitor)
01126 
01127    def append_event(self, callb):
01128       """
01129       Adds an event callback to the notification thread.
01130       """
01131       self.events.append(callb)
01132       self.event_bits = self.event_bits | callb.bit
01133       _pigpio_command(self.control, _PI_CMD_EVM, self.handle, self.event_bits)
01134 
01135    def remove_event(self, callb):
01136       """
01137       Removes an event callback from the notification thread.
01138       """
01139       if callb in self.events:
01140          self.events.remove(callb)
01141          new_event_bits = 0
01142          for c in self.events:
01143             new_event_bits |= c.bit
01144          if new_event_bits != self.event_bits:
01145             self.event_bits = new_event_bits
01146             _pigpio_command(
01147                self.control, _PI_CMD_EVM, self.handle, self.event_bits)
01148 
01149    def run(self):
01150       """Runs the notification thread."""
01151 
01152       lastLevel = self.lastLevel
01153 
01154       RECV_SIZ = 4096
01155       MSG_SIZ = 12
01156 
01157       buf = bytes()
01158       while self.go:
01159 
01160          buf += self.sl.s.recv(RECV_SIZ)
01161          offset = 0
01162 
01163          while self.go and (len(buf) - offset) >= MSG_SIZ:
01164             msgbuf = buf[offset:offset + MSG_SIZ]
01165             offset += MSG_SIZ
01166             seq, flags, tick, level = (struct.unpack('HHII', msgbuf))
01167 
01168             if flags == 0:
01169                changed = level ^ lastLevel
01170                lastLevel = level
01171                for cb in self.callbacks:
01172                   if cb.bit & changed:
01173                      newLevel = 0
01174                      if cb.bit & level:
01175                         newLevel = 1
01176                      if (cb.edge ^ newLevel):
01177                          cb.func(cb.gpio, newLevel, tick)
01178             else:
01179                if flags & NTFY_FLAGS_WDOG:
01180                   gpio = flags & NTFY_FLAGS_GPIO
01181                   for cb in self.callbacks:
01182                      if cb.gpio == gpio:
01183                         cb.func(gpio, TIMEOUT, tick)
01184                elif flags & NTFY_FLAGS_EVENT:
01185                   event = flags & NTFY_FLAGS_GPIO
01186                   for cb in self.events:
01187                      if cb.event == event:
01188                         cb.func(event, tick)
01189          buf = buf[offset:]
01190 
01191       self.sl.s.close()
01192 
01193 class _callback:
01194    """A class to provide GPIO level change callbacks."""
01195 
01196    def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None):
01197       """
01198       Initialise a callback and adds it to the notification thread.
01199       """
01200       self._notify = notify
01201       self.count=0
01202       self._reset = False
01203       if func is None:
01204          func=self._tally
01205       self.callb = _callback_ADT(user_gpio, edge, func)
01206       self._notify.append(self.callb)
01207 
01208    def cancel(self):
01209       """Cancels a callback by removing it from the notification thread."""
01210       self._notify.remove(self.callb)
01211 
01212    def _tally(self, user_gpio, level, tick):
01213       """Increment the callback called count."""
01214       if self._reset:
01215          self._reset = False
01216          self.count = 0
01217       self.count += 1
01218 
01219    def tally(self):
01220       """
01221       Provides a count of how many times the default tally
01222       callback has triggered.
01223 
01224       The count will be zero if the user has supplied their own
01225       callback function.
01226       """
01227       return self.count
01228 
01229    def reset_tally(self):
01230       """
01231       Resets the tally count to zero.
01232       """
01233       self._reset = True
01234       self.count = 0
01235 
01236 class _event:
01237    """A class to provide event callbacks."""
01238 
01239    def __init__(self, notify, event, func=None):
01240       """
01241       Initialise an event and adds it to the notification thread.
01242       """
01243       self._notify = notify
01244       self.count=0
01245       self._reset = False
01246       if func is None:
01247          func=self._tally
01248       self.callb = _event_ADT(event, func)
01249       self._notify.append_event(self.callb)
01250 
01251    def cancel(self):
01252       """
01253       Cancels a event callback by removing it from the
01254       notification thread.
01255       """
01256       self._notify.remove_event(self.callb)
01257 
01258    def _tally(self, event, tick):
01259       """Increment the event callback called count."""
01260       if self._reset:
01261          self._reset = False
01262          self.count = 0
01263       self.count += 1
01264 
01265    def tally(self):
01266       """
01267       Provides a count of how many times the default tally
01268       callback has triggered.
01269 
01270       The count will be zero if the user has supplied their own
01271       callback function.
01272       """
01273       return self.count
01274 
01275    def reset_tally(self):
01276       """
01277       Resets the tally count to zero.
01278       """
01279       self._reset = True
01280       self.count = 0
01281 
01282 class _wait_for_edge:
01283    """Encapsulates waiting for GPIO edges."""
01284 
01285    def __init__(self, notify, gpio, edge, timeout):
01286       """Initialises a wait_for_edge."""
01287       self._notify = notify
01288       self.callb = _callback_ADT(gpio, edge, self.func)
01289       self.trigger = False
01290       self._notify.append(self.callb)
01291       self.start = time.time()
01292       while (self.trigger == False) and ((time.time()-self.start) < timeout):
01293          time.sleep(0.05)
01294       self._notify.remove(self.callb)
01295 
01296    def func(self, gpio, level, tick):
01297       """Sets wait_for_edge triggered."""
01298       self.trigger = True
01299 
01300 class _wait_for_event:
01301    """Encapsulates waiting for an event."""
01302 
01303    def __init__(self, notify, event, timeout):
01304       """Initialises wait_for_event."""
01305       self._notify = notify
01306       self.callb = _event_ADT(event, self.func)
01307       self.trigger = False
01308       self._notify.append_event(self.callb)
01309       self.start = time.time()
01310       while (self.trigger == False) and ((time.time()-self.start) < timeout):
01311          time.sleep(0.05)
01312       self._notify.remove_event(self.callb)
01313 
01314    def func(self, event, tick):
01315       """Sets wait_for_event triggered."""
01316       self.trigger = True
01317 
01318 class pi():
01319 
01320    def _rxbuf(self, count):
01321       """Returns count bytes from the command socket."""
01322       ext = bytearray(self.sl.s.recv(count))
01323       while len(ext) < count:
01324          ext.extend(self.sl.s.recv(count - len(ext)))
01325       return ext
01326 
01327    def set_mode(self, gpio, mode):
01328       """
01329       Sets the GPIO mode.
01330 
01331       gpio:= 0-53.
01332       mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.
01333 
01334       ...
01335       pi.set_mode( 4, pigpio.INPUT)  # GPIO  4 as input
01336       pi.set_mode(17, pigpio.OUTPUT) # GPIO 17 as output
01337       pi.set_mode(24, pigpio.ALT2)   # GPIO 24 as ALT2
01338       ...
01339       """
01340       return _u2i(_pigpio_command(self.sl, _PI_CMD_MODES, gpio, mode))
01341 
01342    def get_mode(self, gpio):
01343       """
01344       Returns the GPIO mode.
01345 
01346       gpio:= 0-53.
01347 
01348       Returns a value as follows
01349 
01350       . .
01351       0 = INPUT
01352       1 = OUTPUT
01353       2 = ALT5
01354       3 = ALT4
01355       4 = ALT0
01356       5 = ALT1
01357       6 = ALT2
01358       7 = ALT3
01359       . .
01360 
01361       ...
01362       print(pi.get_mode(0))
01363       4
01364       ...
01365       """
01366       return _u2i(_pigpio_command(self.sl, _PI_CMD_MODEG, gpio, 0))
01367 
01368    def set_pull_up_down(self, gpio, pud):
01369       """
01370       Sets or clears the internal GPIO pull-up/down resistor.
01371 
01372       gpio:= 0-53.
01373        pud:= PUD_UP, PUD_DOWN, PUD_OFF.
01374 
01375       ...
01376       pi.set_pull_up_down(17, pigpio.PUD_OFF)
01377       pi.set_pull_up_down(23, pigpio.PUD_UP)
01378       pi.set_pull_up_down(24, pigpio.PUD_DOWN)
01379       ...
01380       """
01381       return _u2i(_pigpio_command(self.sl, _PI_CMD_PUD, gpio, pud))
01382 
01383    def read(self, gpio):
01384       """
01385       Returns the GPIO level.
01386 
01387       gpio:= 0-53.
01388 
01389       ...
01390       pi.set_mode(23, pigpio.INPUT)
01391 
01392       pi.set_pull_up_down(23, pigpio.PUD_DOWN)
01393       print(pi.read(23))
01394       0
01395 
01396       pi.set_pull_up_down(23, pigpio.PUD_UP)
01397       print(pi.read(23))
01398       1
01399       ...
01400       """
01401       return _u2i(_pigpio_command(self.sl, _PI_CMD_READ, gpio, 0))
01402 
01403    def write(self, gpio, level):
01404       """
01405       Sets the GPIO level.
01406 
01407        GPIO:= 0-53.
01408       level:= 0, 1.
01409 
01410       If PWM or servo pulses are active on the GPIO they are
01411       switched off.
01412 
01413       ...
01414       pi.set_mode(17, pigpio.OUTPUT)
01415 
01416       pi.write(17,0)
01417       print(pi.read(17))
01418       0
01419 
01420       pi.write(17,1)
01421       print(pi.read(17))
01422       1
01423       ...
01424       """
01425       return _u2i(_pigpio_command(self.sl, _PI_CMD_WRITE, gpio, level))
01426 
01427    def set_PWM_dutycycle(self, user_gpio, dutycycle):
01428       """
01429       Starts (non-zero dutycycle) or stops (0) PWM pulses on the GPIO.
01430 
01431       user_gpio:= 0-31.
01432       dutycycle:= 0-range (range defaults to 255).
01433 
01434       The [*set_PWM_range*] function can change the default range of 255.
01435 
01436       ...
01437       pi.set_PWM_dutycycle(4,   0) # PWM off
01438       pi.set_PWM_dutycycle(4,  64) # PWM 1/4 on
01439       pi.set_PWM_dutycycle(4, 128) # PWM 1/2 on
01440       pi.set_PWM_dutycycle(4, 192) # PWM 3/4 on
01441       pi.set_PWM_dutycycle(4, 255) # PWM full on
01442       ...
01443       """
01444       return _u2i(_pigpio_command(
01445          self.sl, _PI_CMD_PWM, user_gpio, int(dutycycle)))
01446 
01447    def get_PWM_dutycycle(self, user_gpio):
01448       """
01449       Returns the PWM dutycycle being used on the GPIO.
01450 
01451       user_gpio:= 0-31.
01452 
01453       Returns the PWM dutycycle.
01454 
01455 
01456       For normal PWM the dutycycle will be out of the defined range
01457       for the GPIO (see [*get_PWM_range*]).
01458 
01459       If a hardware clock is active on the GPIO the reported
01460       dutycycle will be 500000 (500k) out of 1000000 (1M).
01461 
01462       If hardware PWM is active on the GPIO the reported dutycycle
01463       will be out of a 1000000 (1M).
01464 
01465       ...
01466       pi.set_PWM_dutycycle(4, 25)
01467       print(pi.get_PWM_dutycycle(4))
01468       25
01469 
01470       pi.set_PWM_dutycycle(4, 203)
01471       print(pi.get_PWM_dutycycle(4))
01472       203
01473       ...
01474       """
01475       return _u2i(_pigpio_command(self.sl, _PI_CMD_GDC, user_gpio, 0))
01476 
01477    def set_PWM_range(self, user_gpio, range_):
01478       """
01479       Sets the range of PWM values to be used on the GPIO.
01480 
01481       user_gpio:= 0-31.
01482          range_:= 25-40000.
01483 
01484       ...
01485       pi.set_PWM_range(9, 100)  # now  25 1/4,   50 1/2,   75 3/4 on
01486       pi.set_PWM_range(9, 500)  # now 125 1/4,  250 1/2,  375 3/4 on
01487       pi.set_PWM_range(9, 3000) # now 750 1/4, 1500 1/2, 2250 3/4 on
01488       ...
01489       """
01490       return _u2i(_pigpio_command(self.sl, _PI_CMD_PRS, user_gpio, range_))
01491 
01492    def get_PWM_range(self, user_gpio):
01493       """
01494       Returns the range of PWM values being used on the GPIO.
01495 
01496       user_gpio:= 0-31.
01497 
01498       If a hardware clock or hardware PWM is active on the GPIO
01499       the reported range will be 1000000 (1M).
01500 
01501       ...
01502       pi.set_PWM_range(9, 500)
01503       print(pi.get_PWM_range(9))
01504       500
01505       ...
01506       """
01507       return _u2i(_pigpio_command(self.sl, _PI_CMD_PRG, user_gpio, 0))
01508 
01509    def get_PWM_real_range(self, user_gpio):
01510       """
01511       Returns the real (underlying) range of PWM values being
01512       used on the GPIO.
01513 
01514       user_gpio:= 0-31.
01515 
01516       If a hardware clock is active on the GPIO the reported
01517       real range will be 1000000 (1M).
01518 
01519       If hardware PWM is active on the GPIO the reported real range
01520       will be approximately 250M divided by the set PWM frequency.
01521 
01522       ...
01523       pi.set_PWM_frequency(4, 800)
01524       print(pi.get_PWM_real_range(4))
01525       250
01526       ...
01527       """
01528       return _u2i(_pigpio_command(self.sl, _PI_CMD_PRRG, user_gpio, 0))
01529 
01530    def set_PWM_frequency(self, user_gpio, frequency):
01531       """
01532       Sets the frequency (in Hz) of the PWM to be used on the GPIO.
01533 
01534       user_gpio:= 0-31.
01535       frequency:= >=0 Hz
01536 
01537       Returns the numerically closest frequency if OK, otherwise
01538       PI_BAD_USER_GPIO or PI_NOT_PERMITTED.
01539 
01540       If PWM is currently active on the GPIO it will be switched
01541       off and then back on at the new frequency.
01542 
01543       Each GPIO can be independently set to one of 18 different
01544       PWM frequencies.
01545 
01546       The selectable frequencies depend upon the sample rate which
01547       may be 1, 2, 4, 5, 8, or 10 microseconds (default 5).  The
01548       sample rate is set when the pigpio daemon is started.
01549 
01550       The frequencies for each sample rate are:
01551 
01552       . .
01553                              Hertz
01554 
01555              1: 40000 20000 10000 8000 5000 4000 2500 2000 1600
01556                  1250  1000   800  500  400  250  200  100   50
01557 
01558              2: 20000 10000  5000 4000 2500 2000 1250 1000  800
01559                   625   500   400  250  200  125  100   50   25
01560 
01561              4: 10000  5000  2500 2000 1250 1000  625  500  400
01562                   313   250   200  125  100   63   50   25   13
01563       sample
01564        rate
01565        (us)  5:  8000  4000  2000 1600 1000  800  500  400  320
01566                   250   200   160  100   80   50   40   20   10
01567 
01568              8:  5000  2500  1250 1000  625  500  313  250  200
01569                   156   125   100   63   50   31   25   13    6
01570 
01571             10:  4000  2000  1000  800  500  400  250  200  160
01572                   125   100    80   50   40   25   20   10    5
01573       . .
01574 
01575       ...
01576       pi.set_PWM_frequency(4,0)
01577       print(pi.get_PWM_frequency(4))
01578       10
01579 
01580       pi.set_PWM_frequency(4,100000)
01581       print(pi.get_PWM_frequency(4))
01582       8000
01583       ...
01584       """
01585       return _u2i(
01586          _pigpio_command(self.sl, _PI_CMD_PFS, user_gpio, frequency))
01587 
01588    def get_PWM_frequency(self, user_gpio):
01589       """
01590       Returns the frequency of PWM being used on the GPIO.
01591 
01592       user_gpio:= 0-31.
01593 
01594       Returns the frequency (in Hz) used for the GPIO.
01595 
01596       For normal PWM the frequency will be that defined for the GPIO
01597       by [*set_PWM_frequency*].
01598 
01599       If a hardware clock is active on the GPIO the reported frequency
01600       will be that set by [*hardware_clock*].
01601 
01602       If hardware PWM is active on the GPIO the reported frequency
01603       will be that set by [*hardware_PWM*].
01604 
01605       ...
01606       pi.set_PWM_frequency(4,0)
01607       print(pi.get_PWM_frequency(4))
01608       10
01609 
01610       pi.set_PWM_frequency(4, 800)
01611       print(pi.get_PWM_frequency(4))
01612       800
01613       ...
01614       """
01615       return _u2i(_pigpio_command(self.sl, _PI_CMD_PFG, user_gpio, 0))
01616 
01617    def set_servo_pulsewidth(self, user_gpio, pulsewidth):
01618       """
01619       Starts (500-2500) or stops (0) servo pulses on the GPIO.
01620 
01621        user_gpio:= 0-31.
01622       pulsewidth:= 0 (off),
01623                    500 (most anti-clockwise) - 2500 (most clockwise).
01624 
01625       The selected pulsewidth will continue to be transmitted until
01626       changed by a subsequent call to set_servo_pulsewidth.
01627 
01628       The pulsewidths supported by servos varies and should probably
01629       be determined by experiment. A value of 1500 should always be
01630       safe and represents the mid-point of rotation.
01631 
01632       You can DAMAGE a servo if you command it to move beyond its
01633       limits.
01634 
01635       ...
01636       pi.set_servo_pulsewidth(17, 0)    # off
01637       pi.set_servo_pulsewidth(17, 1000) # safe anti-clockwise
01638       pi.set_servo_pulsewidth(17, 1500) # centre
01639       pi.set_servo_pulsewidth(17, 2000) # safe clockwise
01640       ...
01641    """
01642       return _u2i(_pigpio_command(
01643          self.sl, _PI_CMD_SERVO, user_gpio, int(pulsewidth)))
01644 
01645    def get_servo_pulsewidth(self, user_gpio):
01646       """
01647       Returns the servo pulsewidth being used on the GPIO.
01648 
01649       user_gpio:= 0-31.
01650 
01651       Returns the servo pulsewidth.
01652 
01653       ...
01654       pi.set_servo_pulsewidth(4, 525)
01655       print(pi.get_servo_pulsewidth(4))
01656       525
01657 
01658       pi.set_servo_pulsewidth(4, 2130)
01659       print(pi.get_servo_pulsewidth(4))
01660       2130
01661       ...
01662       """
01663       return _u2i(_pigpio_command(self.sl, _PI_CMD_GPW, user_gpio, 0))
01664 
01665    def notify_open(self):
01666       """
01667       Returns a notification handle (>=0).
01668 
01669       A notification is a method for being notified of GPIO state
01670       changes via a pipe.
01671 
01672       Pipes are only accessible from the local machine so this
01673       function serves no purpose if you are using Python from a
01674       remote machine.  The in-built (socket) notifications
01675       provided by [*callback*] should be used instead.
01676 
01677       Notifications for handle x will be available at the pipe
01678       named /dev/pigpiox (where x is the handle number).
01679 
01680       E.g. if the function returns 15 then the notifications must be
01681       read from /dev/pigpio15.
01682 
01683       Notifications have the following structure:
01684 
01685       . .
01686       H seqno
01687       H flags
01688       I tick
01689       I level
01690       . .
01691 
01692       seqno: starts at 0 each time the handle is opened and then
01693       increments by one for each report.
01694 
01695       flags: three flags are defined, PI_NTFY_FLAGS_WDOG,
01696       PI_NTFY_FLAGS_ALIVE, and PI_NTFY_FLAGS_EVENT.
01697 
01698       If bit 5 is set (PI_NTFY_FLAGS_WDOG) then bits 0-4 of the
01699       flags indicate a GPIO which has had a watchdog timeout.
01700 
01701       If bit 6 is set (PI_NTFY_FLAGS_ALIVE) this indicates a keep
01702       alive signal on the pipe/socket and is sent once a minute
01703       in the absence of other notification activity.
01704 
01705       If bit 7 is set (PI_NTFY_FLAGS_EVENT) then bits 0-4 of the
01706       flags indicate an event which has been triggered.
01707 
01708 
01709       tick: the number of microseconds since system boot.  It wraps
01710       around after 1h12m.
01711 
01712       level: indicates the level of each GPIO.  If bit 1<<x is set
01713       then GPIO x is high.
01714 
01715       ...
01716       h = pi.notify_open()
01717       if h >= 0:
01718          pi.notify_begin(h, 1234)
01719       ...
01720       """
01721       return _u2i(_pigpio_command(self.sl, _PI_CMD_NO, 0, 0))
01722 
01723    def notify_begin(self, handle, bits):
01724       """
01725       Starts notifications on a handle.
01726 
01727       handle:= >=0 (as returned by a prior call to [*notify_open*])
01728         bits:= a 32 bit mask indicating the GPIO to be notified.
01729 
01730       The notification sends state changes for each GPIO whose
01731       corresponding bit in bits is set.
01732 
01733       The following code starts notifications for GPIO 1, 4,
01734       6, 7, and 10 (1234 = 0x04D2 = 0b0000010011010010).
01735 
01736       ...
01737       h = pi.notify_open()
01738       if h >= 0:
01739          pi.notify_begin(h, 1234)
01740       ...
01741       """
01742       return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, bits))
01743 
01744    def notify_pause(self, handle):
01745       """
01746       Pauses notifications on a handle.
01747 
01748       handle:= >=0 (as returned by a prior call to [*notify_open*])
01749 
01750       Notifications for the handle are suspended until
01751       [*notify_begin*] is called again.
01752 
01753       ...
01754       h = pi.notify_open()
01755       if h >= 0:
01756          pi.notify_begin(h, 1234)
01757          ...
01758          pi.notify_pause(h)
01759          ...
01760          pi.notify_begin(h, 1234)
01761          ...
01762       ...
01763       """
01764       return _u2i(_pigpio_command(self.sl, _PI_CMD_NB, handle, 0))
01765 
01766    def notify_close(self, handle):
01767       """
01768       Stops notifications on a handle and releases the handle for reuse.
01769 
01770       handle:= >=0 (as returned by a prior call to [*notify_open*])
01771 
01772       ...
01773       h = pi.notify_open()
01774       if h >= 0:
01775          pi.notify_begin(h, 1234)
01776          ...
01777          pi.notify_close(h)
01778          ...
01779       ...
01780       """
01781       return _u2i(_pigpio_command(self.sl, _PI_CMD_NC, handle, 0))
01782 
01783    def set_watchdog(self, user_gpio, wdog_timeout):
01784       """
01785       Sets a watchdog timeout for a GPIO.
01786 
01787          user_gpio:= 0-31.
01788       wdog_timeout:= 0-60000.
01789 
01790       The watchdog is nominally in milliseconds.
01791 
01792       Only one watchdog may be registered per GPIO.
01793 
01794       The watchdog may be cancelled by setting timeout to 0.
01795 
01796       Once a watchdog has been started callbacks for the GPIO
01797       will be triggered every timeout interval after the last
01798       GPIO activity.
01799 
01800       The callback will receive the special level TIMEOUT.
01801 
01802       ...
01803       pi.set_watchdog(23, 1000) # 1000 ms watchdog on GPIO 23
01804       pi.set_watchdog(23, 0)    # cancel watchdog on GPIO 23
01805       ...
01806       """
01807       return _u2i(_pigpio_command(
01808          self.sl, _PI_CMD_WDOG, user_gpio, int(wdog_timeout)))
01809 
01810    def read_bank_1(self):
01811       """
01812       Returns the levels of the bank 1 GPIO (GPIO 0-31).
01813 
01814       The returned 32 bit integer has a bit set if the corresponding
01815       GPIO is high.  GPIO n has bit value (1<<n).
01816 
01817       ...
01818       print(bin(pi.read_bank_1()))
01819       0b10010100000011100100001001111
01820       ...
01821       """
01822       return _pigpio_command(self.sl, _PI_CMD_BR1, 0, 0)
01823 
01824    def read_bank_2(self):
01825       """
01826       Returns the levels of the bank 2 GPIO (GPIO 32-53).
01827 
01828       The returned 32 bit integer has a bit set if the corresponding
01829       GPIO is high.  GPIO n has bit value (1<<(n-32)).
01830 
01831       ...
01832       print(bin(pi.read_bank_2()))
01833       0b1111110000000000000000
01834       ...
01835       """
01836       return _pigpio_command(self.sl, _PI_CMD_BR2, 0, 0)
01837 
01838    def clear_bank_1(self, bits):
01839       """
01840       Clears GPIO 0-31 if the corresponding bit in bits is set.
01841 
01842       bits:= a 32 bit mask with 1 set if the corresponding GPIO is
01843              to be cleared.
01844 
01845       A returned status of PI_SOME_PERMITTED indicates that the user
01846       is not allowed to write to one or more of the GPIO.
01847 
01848       ...
01849       pi.clear_bank_1(int("111110010000",2))
01850       ...
01851       """
01852       return _u2i(_pigpio_command(self.sl, _PI_CMD_BC1, bits, 0))
01853 
01854    def clear_bank_2(self, bits):
01855       """
01856       Clears GPIO 32-53 if the corresponding bit (0-21) in bits is set.
01857 
01858       bits:= a 32 bit mask with 1 set if the corresponding GPIO is
01859              to be cleared.
01860 
01861       A returned status of PI_SOME_PERMITTED indicates that the user
01862       is not allowed to write to one or more of the GPIO.
01863 
01864       ...
01865       pi.clear_bank_2(0x1010)
01866       ...
01867       """
01868       return _u2i(_pigpio_command(self.sl, _PI_CMD_BC2, bits, 0))
01869 
01870    def set_bank_1(self, bits):
01871       """
01872       Sets GPIO 0-31 if the corresponding bit in bits is set.
01873 
01874       bits:= a 32 bit mask with 1 set if the corresponding GPIO is
01875              to be set.
01876 
01877       A returned status of PI_SOME_PERMITTED indicates that the user
01878       is not allowed to write to one or more of the GPIO.
01879 
01880       ...
01881       pi.set_bank_1(int("111110010000",2))
01882       ...
01883       """
01884       return _u2i(_pigpio_command(self.sl, _PI_CMD_BS1, bits, 0))
01885 
01886    def set_bank_2(self, bits):
01887       """
01888       Sets GPIO 32-53 if the corresponding bit (0-21) in bits is set.
01889 
01890       bits:= a 32 bit mask with 1 set if the corresponding GPIO is
01891              to be set.
01892 
01893       A returned status of PI_SOME_PERMITTED indicates that the user
01894       is not allowed to write to one or more of the GPIO.
01895 
01896       ...
01897       pi.set_bank_2(0x303)
01898       ...
01899       """
01900       return _u2i(_pigpio_command(self.sl, _PI_CMD_BS2, bits, 0))
01901 
01902    def hardware_clock(self, gpio, clkfreq):
01903       """
01904       Starts a hardware clock on a GPIO at the specified frequency.
01905       Frequencies above 30MHz are unlikely to work.
01906 
01907          gpio:= see description
01908       clkfreq:= 0 (off) or 4689-250000000 (250M)
01909 
01910 
01911       Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
01912       PI_NOT_HCLK_GPIO, PI_BAD_HCLK_FREQ,or PI_BAD_HCLK_PASS.
01913 
01914       The same clock is available on multiple GPIO.  The latest
01915       frequency setting will be used by all GPIO which share a clock.
01916 
01917       The GPIO must be one of the following:
01918 
01919       . .
01920       4   clock 0  All models
01921       5   clock 1  All models but A and B (reserved for system use)
01922       6   clock 2  All models but A and B
01923       20  clock 0  All models but A and B
01924       21  clock 1  All models but A and Rev.2 B (reserved for system use)
01925 
01926       32  clock 0  Compute module only
01927       34  clock 0  Compute module only
01928       42  clock 1  Compute module only (reserved for system use)
01929       43  clock 2  Compute module only
01930       44  clock 1  Compute module only (reserved for system use)
01931       . .
01932 
01933       Access to clock 1 is protected by a password as its use will
01934       likely crash the Pi.  The password is given by or'ing 0x5A000000
01935       with the GPIO number.
01936 
01937       ...
01938       pi.hardware_clock(4, 5000) # 5 KHz clock on GPIO 4
01939 
01940       pi.hardware_clock(4, 40000000) # 40 MHz clock on GPIO 4
01941       ...
01942       """
01943       return _u2i(_pigpio_command(self.sl, _PI_CMD_HC, gpio, clkfreq))
01944 
01945    def hardware_PWM(self, gpio, PWMfreq, PWMduty):
01946       """
01947       Starts hardware PWM on a GPIO at the specified frequency
01948       and dutycycle. Frequencies above 30MHz are unlikely to work.
01949 
01950       NOTE: Any waveform started by [*wave_send_once*],
01951       [*wave_send_repeat*], or [*wave_chain*] will be cancelled.
01952 
01953       This function is only valid if the pigpio main clock is PCM.
01954       The main clock defaults to PCM but may be overridden when the
01955       pigpio daemon is started (option -t).
01956 
01957          gpio:= see descripton
01958       PWMfreq:= 0 (off) or 1-125000000 (125M).
01959       PWMduty:= 0 (off) to 1000000 (1M)(fully on).
01960 
01961       Returns 0 if OK, otherwise PI_NOT_PERMITTED, PI_BAD_GPIO,
01962       PI_NOT_HPWM_GPIO, PI_BAD_HPWM_DUTY, PI_BAD_HPWM_FREQ.
01963 
01964       The same PWM channel is available on multiple GPIO.
01965       The latest frequency and dutycycle setting will be used
01966       by all GPIO which share a PWM channel.
01967 
01968       The GPIO must be one of the following:
01969 
01970       . .
01971       12  PWM channel 0  All models but A and B
01972       13  PWM channel 1  All models but A and B
01973       18  PWM channel 0  All models
01974       19  PWM channel 1  All models but A and B
01975 
01976       40  PWM channel 0  Compute module only
01977       41  PWM channel 1  Compute module only
01978       45  PWM channel 1  Compute module only
01979       52  PWM channel 0  Compute module only
01980       53  PWM channel 1  Compute module only
01981       . .
01982 
01983       The actual number of steps beween off and fully on is the
01984       integral part of 250 million divided by PWMfreq.
01985 
01986       The actual frequency set is 250 million / steps.
01987 
01988       There will only be a million steps for a PWMfreq of 250.
01989       Lower frequencies will have more steps and higher
01990       frequencies will have fewer steps.  PWMduty is
01991       automatically scaled to take this into account.
01992 
01993       ...
01994       pi.hardware_PWM(18, 800, 250000) # 800Hz 25% dutycycle
01995 
01996       pi.hardware_PWM(18, 2000, 750000) # 2000Hz 75% dutycycle
01997       ...
01998       """
01999       # pigpio message format
02000 
02001       # I p1 gpio
02002       # I p2 PWMfreq
02003       # I p3 4
02004       ## extension ##
02005       # I PWMdutycycle
02006       extents = [struct.pack("I", PWMduty)]
02007       return _u2i(_pigpio_command_ext(
02008          self.sl, _PI_CMD_HP, gpio, PWMfreq, 4, extents))
02009 
02010 
02011    def get_current_tick(self):
02012       """
02013       Returns the current system tick.
02014 
02015       Tick is the number of microseconds since system boot.  As an
02016       unsigned 32 bit quantity tick wraps around approximately
02017       every 71.6 minutes.
02018 
02019       ...
02020       t1 = pi.get_current_tick()
02021       time.sleep(1)
02022       t2 = pi.get_current_tick()
02023       ...
02024       """
02025       return _pigpio_command(self.sl, _PI_CMD_TICK, 0, 0)
02026 
02027    def get_hardware_revision(self):
02028       """
02029       Returns the Pi's hardware revision number.
02030 
02031       The hardware revision is the last few characters on the
02032       Revision line of /proc/cpuinfo.
02033 
02034       The revision number can be used to determine the assignment
02035       of GPIO to pins (see [*gpio*]).
02036 
02037       There are at least three types of board.
02038 
02039       Type 1 boards have hardware revision numbers of 2 and 3.
02040 
02041       Type 2 boards have hardware revision numbers of 4, 5, 6, and 15.
02042 
02043       Type 3 boards have hardware revision numbers of 16 or greater.
02044 
02045       If the hardware revision can not be found or is not a valid
02046       hexadecimal number the function returns 0.
02047 
02048       ...
02049       print(pi.get_hardware_revision())
02050       2
02051       ...
02052       """
02053       return _pigpio_command(self.sl, _PI_CMD_HWVER, 0, 0)
02054 
02055    def get_pigpio_version(self):
02056       """
02057       Returns the pigpio software version.
02058 
02059       ...
02060       v = pi.get_pigpio_version()
02061       ...
02062       """
02063       return _pigpio_command(self.sl, _PI_CMD_PIGPV, 0, 0)
02064 
02065    def wave_clear(self):
02066       """
02067       Clears all waveforms and any data added by calls to the
02068       [*wave_add_**] functions.
02069 
02070       ...
02071       pi.wave_clear()
02072       ...
02073       """
02074       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCLR, 0, 0))
02075 
02076    def wave_add_new(self):
02077       """
02078       Starts a new empty waveform.
02079 
02080       You would not normally need to call this function as it is
02081       automatically called after a waveform is created with the
02082       [*wave_create*] function.
02083 
02084       ...
02085       pi.wave_add_new()
02086       ...
02087       """
02088       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVNEW, 0, 0))
02089 
02090    def wave_add_generic(self, pulses):
02091       """
02092       Adds a list of pulses to the current waveform.
02093 
02094       pulses:= list of pulses to add to the waveform.
02095 
02096       Returns the new total number of pulses in the current waveform.
02097 
02098       The pulses are interleaved in time order within the existing
02099       waveform (if any).
02100 
02101       Merging allows the waveform to be built in parts, that is the
02102       settings for GPIO#1 can be added, and then GPIO#2 etc.
02103 
02104       If the added waveform is intended to start after or within
02105       the existing waveform then the first pulse should consist
02106       solely of a delay.
02107 
02108       ...
02109       G1=4
02110       G2=24
02111 
02112       pi.set_mode(G1, pigpio.OUTPUT)
02113       pi.set_mode(G2, pigpio.OUTPUT)
02114 
02115       flash_500=[] # flash every 500 ms
02116       flash_100=[] # flash every 100 ms
02117 
02118       #                              ON     OFF  DELAY
02119 
02120       flash_500.append(pigpio.pulse(1<<G1, 1<<G2, 500000))
02121       flash_500.append(pigpio.pulse(1<<G2, 1<<G1, 500000))
02122 
02123       flash_100.append(pigpio.pulse(1<<G1, 1<<G2, 100000))
02124       flash_100.append(pigpio.pulse(1<<G2, 1<<G1, 100000))
02125 
02126       pi.wave_clear() # clear any existing waveforms
02127 
02128       pi.wave_add_generic(flash_500) # 500 ms flashes
02129       f500 = pi.wave_create() # create and save id
02130 
02131       pi.wave_add_generic(flash_100) # 100 ms flashes
02132       f100 = pi.wave_create() # create and save id
02133 
02134       pi.wave_send_repeat(f500)
02135 
02136       time.sleep(4)
02137 
02138       pi.wave_send_repeat(f100)
02139 
02140       time.sleep(4)
02141 
02142       pi.wave_send_repeat(f500)
02143 
02144       time.sleep(4)
02145 
02146       pi.wave_tx_stop() # stop waveform
02147 
02148       pi.wave_clear() # clear all waveforms
02149       ...
02150       """
02151       # pigpio message format
02152 
02153       # I p1 0
02154       # I p2 0
02155       # I p3 pulses * 12
02156       ## extension ##
02157       # III on/off/delay * pulses
02158       if len(pulses):
02159          ext = bytearray()
02160          for p in pulses:
02161             ext.extend(struct.pack("III", p.gpio_on, p.gpio_off, p.delay))
02162          extents = [ext]
02163          return _u2i(_pigpio_command_ext(
02164             self.sl, _PI_CMD_WVAG, 0, 0, len(pulses)*12, extents))
02165       else:
02166          return 0
02167 
02168    def wave_add_serial(
02169       self, user_gpio, baud, data, offset=0, bb_bits=8, bb_stop=2):
02170       """
02171       Adds a waveform representing serial data to the existing
02172       waveform (if any).  The serial data starts [*offset*]
02173       microseconds from the start of the waveform.
02174 
02175       user_gpio:= GPIO to transmit data.  You must set the GPIO mode
02176                   to output.
02177            baud:= 50-1000000 bits per second.
02178            data:= the bytes to write.
02179          offset:= number of microseconds from the start of the
02180                   waveform, default 0.
02181         bb_bits:= number of data bits, default 8.
02182         bb_stop:= number of stop half bits, default 2.
02183 
02184       Returns the new total number of pulses in the current waveform.
02185 
02186       The serial data is formatted as one start bit, [*bb_bits*]
02187       data bits, and [*bb_stop*]/2 stop bits.
02188 
02189       It is legal to add serial data streams with different baud
02190       rates to the same waveform.
02191 
02192       The bytes required for each character depend upon [*bb_bits*].
02193 
02194       For [*bb_bits*] 1-8 there will be one byte per character. 
02195       For [*bb_bits*] 9-16 there will be two bytes per character. 
02196       For [*bb_bits*] 17-32 there will be four bytes per character.
02197 
02198       ...
02199       pi.wave_add_serial(4, 300, 'Hello world')
02200 
02201       pi.wave_add_serial(4, 300, b"Hello world")
02202 
02203       pi.wave_add_serial(4, 300, b'\\x23\\x01\\x00\\x45')
02204 
02205       pi.wave_add_serial(17, 38400, [23, 128, 234], 5000)
02206       ...
02207       """
02208       # pigpio message format
02209 
02210       # I p1 gpio
02211       # I p2 baud
02212       # I p3 len+12
02213       ## extension ##
02214       # I bb_bits
02215       # I bb_stop
02216       # I offset
02217       # s len data bytes
02218       if len(data):
02219          extents = [struct.pack("III", bb_bits, bb_stop, offset), data]
02220          return _u2i(_pigpio_command_ext(
02221             self.sl, _PI_CMD_WVAS, user_gpio, baud, len(data)+12, extents))
02222       else:
02223          return 0
02224 
02225    def wave_create(self):
02226       """
02227       Creates a waveform from the data provided by the prior calls
02228       to the [*wave_add_**] functions.
02229 
02230       Returns a wave id (>=0) if OK,  otherwise PI_EMPTY_WAVEFORM,
02231       PI_TOO_MANY_CBS, PI_TOO_MANY_OOL, or PI_NO_WAVEFORM_ID.
02232 
02233       The data provided by the [*wave_add_**] functions is consumed by
02234       this function.
02235 
02236       As many waveforms may be created as there is space available.
02237       The wave id is passed to [*wave_send_**] to specify the waveform
02238       to transmit.
02239 
02240       Normal usage would be
02241 
02242       Step 1. [*wave_clear*] to clear all waveforms and added data.
02243 
02244       Step 2. [*wave_add_**] calls to supply the waveform data.
02245 
02246       Step 3. [*wave_create*] to create the waveform and get a unique id
02247 
02248       Repeat steps 2 and 3 as needed.
02249 
02250       Step 4. [*wave_send_**] with the id of the waveform to transmit.
02251 
02252       A waveform comprises one or more pulses.
02253 
02254       A pulse specifies
02255 
02256       1) the GPIO to be switched on at the start of the pulse. 
02257       2) the GPIO to be switched off at the start of the pulse. 
02258       3) the delay in microseconds before the next pulse.
02259 
02260       Any or all the fields can be zero.  It doesn't make any sense
02261       to set all the fields to zero (the pulse will be ignored).
02262 
02263       When a waveform is started each pulse is executed in order with
02264       the specified delay between the pulse and the next.
02265 
02266       ...
02267       wid = pi.wave_create()
02268       ...
02269       """
02270       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVCRE, 0, 0))
02271 
02272    def wave_delete(self, wave_id):
02273       """
02274       This function deletes the waveform with id wave_id.
02275 
02276       wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
02277 
02278       Wave ids are allocated in order, 0, 1, 2, etc.
02279 
02280       The wave is flagged for deletion.  The resources used by the wave
02281       will only be reused when either of the following apply.
02282 
02283       - all waves with higher numbered wave ids have been deleted or have
02284       been flagged for deletion.
02285 
02286       - a new wave is created which uses exactly the same resources as
02287       the current wave (see the C source for gpioWaveCreate for details).
02288 
02289       ...
02290       pi.wave_delete(6) # delete waveform with id 6
02291 
02292       pi.wave_delete(0) # delete waveform with id 0
02293       ...
02294       """
02295       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVDEL, wave_id, 0))
02296 
02297    def wave_tx_start(self): # DEPRECATED
02298       """
02299       This function is deprecated and has been removed.
02300 
02301       Use [*wave_create*]/[*wave_send_**] instead.
02302       """
02303       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGO, 0, 0))
02304 
02305    def wave_tx_repeat(self): # DEPRECATED
02306       """
02307       This function is deprecated and has beeen removed.
02308 
02309       Use [*wave_create*]/[*wave_send_**] instead.
02310       """
02311       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVGOR, 0, 0))
02312 
02313    def wave_send_once(self, wave_id):
02314       """
02315       Transmits the waveform with id wave_id.  The waveform is sent
02316       once.
02317 
02318       NOTE: Any hardware PWM started by [*hardware_PWM*] will
02319       be cancelled.
02320 
02321       wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
02322 
02323       Returns the number of DMA control blocks used in the waveform.
02324 
02325       ...
02326       cbs = pi.wave_send_once(wid)
02327       ...
02328       """
02329       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTX, wave_id, 0))
02330 
02331    def wave_send_repeat(self, wave_id):
02332       """
02333       Transmits the waveform with id wave_id.  The waveform repeats
02334       until wave_tx_stop is called or another call to [*wave_send_**]
02335       is made.
02336 
02337       NOTE: Any hardware PWM started by [*hardware_PWM*] will
02338       be cancelled.
02339 
02340       wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
02341 
02342       Returns the number of DMA control blocks used in the waveform.
02343 
02344       ...
02345       cbs = pi.wave_send_repeat(wid)
02346       ...
02347       """
02348       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXR, wave_id, 0))
02349 
02350    def wave_send_using_mode(self, wave_id, mode):
02351       """
02352       Transmits the waveform with id wave_id using mode mode.
02353 
02354       wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
02355          mode:= WAVE_MODE_ONE_SHOT, WAVE_MODE_REPEAT,
02356                 WAVE_MODE_ONE_SHOT_SYNC, or WAVE_MODE_REPEAT_SYNC.
02357 
02358       WAVE_MODE_ONE_SHOT: same as [*wave_send_once*].
02359 
02360       WAVE_MODE_REPEAT same as [*wave_send_repeat*].
02361 
02362       WAVE_MODE_ONE_SHOT_SYNC same as [*wave_send_once*] but tries
02363       to sync with the previous waveform.
02364 
02365       WAVE_MODE_REPEAT_SYNC same as [*wave_send_repeat*] but tries
02366       to sync with the previous waveform.
02367 
02368       WARNING: bad things may happen if you delete the previous
02369       waveform before it has been synced to the new waveform.
02370 
02371       NOTE: Any hardware PWM started by [*hardware_PWM*] will
02372       be cancelled.
02373 
02374       wave_id:= >=0 (as returned by a prior call to [*wave_create*]).
02375 
02376       Returns the number of DMA control blocks used in the waveform.
02377 
02378       ...
02379       cbs = pi.wave_send_using_mode(wid, WAVE_MODE_REPEAT_SYNC)
02380       ...
02381       """
02382       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTXM, wave_id, mode))
02383 
02384    def wave_tx_at(self):
02385       """
02386       Returns the id of the waveform currently being
02387       transmitted.
02388 
02389       Returns the waveform id or one of the following special
02390       values:
02391 
02392       WAVE_NOT_FOUND (9998) - transmitted wave not found. 
02393       NO_TX_WAVE (9999) - no wave being transmitted.
02394 
02395       ...
02396       wid = pi.wave_tx_at()
02397       ...
02398       """
02399       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVTAT, 0, 0))
02400 
02401    def wave_tx_busy(self):
02402       """
02403       Returns 1 if a waveform is currently being transmitted,
02404       otherwise 0.
02405 
02406       ...
02407       pi.wave_send_once(0) # send first waveform
02408 
02409       while pi.wave_tx_busy(): # wait for waveform to be sent
02410          time.sleep(0.1)
02411 
02412       pi.wave_send_once(1) # send next waveform
02413       ...
02414       """
02415       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVBSY, 0, 0))
02416 
02417    def wave_tx_stop(self):
02418       """
02419       Stops the transmission of the current waveform.
02420 
02421       This function is intended to stop a waveform started with
02422       wave_send_repeat.
02423 
02424       ...
02425       pi.wave_send_repeat(3)
02426 
02427       time.sleep(5)
02428 
02429       pi.wave_tx_stop()
02430       ...
02431       """
02432       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVHLT, 0, 0))
02433 
02434    def wave_chain(self, data):
02435       """
02436       This function transmits a chain of waveforms.
02437 
02438       NOTE: Any hardware PWM started by [*hardware_PWM*]
02439       will be cancelled.
02440 
02441       The waves to be transmitted are specified by the contents
02442       of data which contains an ordered list of [*wave_id*]s
02443       and optional command codes and related data.
02444 
02445       Returns 0 if OK, otherwise PI_CHAIN_NESTING,
02446       PI_CHAIN_LOOP_CNT, PI_BAD_CHAIN_LOOP, PI_BAD_CHAIN_CMD,
02447       PI_CHAIN_COUNTER, PI_BAD_CHAIN_DELAY, PI_CHAIN_TOO_BIG,
02448       or PI_BAD_WAVE_ID.
02449 
02450       Each wave is transmitted in the order specified.  A wave
02451       may occur multiple times per chain.
02452 
02453       A blocks of waves may be transmitted multiple times by
02454       using the loop commands. The block is bracketed by loop
02455       start and end commands.  Loops may be nested.
02456 
02457       Delays between waves may be added with the delay command.
02458 
02459       The following command codes are supported:
02460 
02461       Name         @ Cmd & Data @ Meaning
02462       Loop Start   @ 255 0      @ Identify start of a wave block
02463       Loop Repeat  @ 255 1 x y  @ loop x + y*256 times
02464       Delay        @ 255 2 x y  @ delay x + y*256 microseconds
02465       Loop Forever @ 255 3      @ loop forever
02466 
02467       If present Loop Forever must be the last entry in the chain.
02468 
02469       The code is currently dimensioned to support a chain with
02470       roughly 600 entries and 20 loop counters.
02471 
02472       ...
02473       #!/usr/bin/env python
02474 
02475       import time
02476       import pigpio
02477 
02478       WAVES=5
02479       GPIO=4
02480 
02481       wid=[0]*WAVES
02482 
02483       pi = pigpio.pi() # Connect to local Pi.
02484 
02485       pi.set_mode(GPIO, pigpio.OUTPUT);
02486 
02487       for i in range(WAVES):
02488          pi.wave_add_generic([
02489             pigpio.pulse(1<<GPIO, 0, 20),
02490             pigpio.pulse(0, 1<<GPIO, (i+1)*200)]);
02491 
02492          wid[i] = pi.wave_create();
02493 
02494       pi.wave_chain([
02495          wid[4], wid[3], wid[2],       # transmit waves 4+3+2
02496          255, 0,                       # loop start
02497             wid[0], wid[0], wid[0],    # transmit waves 0+0+0
02498             255, 0,                    # loop start
02499                wid[0], wid[1],         # transmit waves 0+1
02500                255, 2, 0x88, 0x13,     # delay 5000us
02501             255, 1, 30, 0,             # loop end (repeat 30 times)
02502             255, 0,                    # loop start
02503                wid[2], wid[3], wid[0], # transmit waves 2+3+0
02504                wid[3], wid[1], wid[2], # transmit waves 3+1+2
02505             255, 1, 10, 0,             # loop end (repeat 10 times)
02506          255, 1, 5, 0,                 # loop end (repeat 5 times)
02507          wid[4], wid[4], wid[4],       # transmit waves 4+4+4
02508          255, 2, 0x20, 0x4E,           # delay 20000us
02509          wid[0], wid[0], wid[0],       # transmit waves 0+0+0
02510          ])
02511 
02512       while pi.wave_tx_busy():
02513          time.sleep(0.1);
02514 
02515       for i in range(WAVES):
02516          pi.wave_delete(wid[i])
02517 
02518       pi.stop()
02519       ...
02520       """
02521       # I p1 0
02522       # I p2 0
02523       # I p3 len
02524       ## extension ##
02525       # s len data bytes
02526 
02527       return _u2i(_pigpio_command_ext(
02528          self.sl, _PI_CMD_WVCHA, 0, 0, len(data), [data]))
02529 
02530 
02531    def wave_get_micros(self):
02532       """
02533       Returns the length in microseconds of the current waveform.
02534 
02535       ...
02536       micros = pi.wave_get_micros()
02537       ...
02538       """
02539       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 0, 0))
02540 
02541    def wave_get_max_micros(self):
02542       """
02543       Returns the maximum possible size of a waveform in microseconds.
02544 
02545       ...
02546       micros = pi.wave_get_max_micros()
02547       ...
02548       """
02549       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSM, 2, 0))
02550 
02551    def wave_get_pulses(self):
02552       """
02553       Returns the length in pulses of the current waveform.
02554 
02555       ...
02556       pulses = pi.wave_get_pulses()
02557       ...
02558       """
02559       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 0, 0))
02560 
02561    def wave_get_max_pulses(self):
02562       """
02563       Returns the maximum possible size of a waveform in pulses.
02564 
02565       ...
02566       pulses = pi.wave_get_max_pulses()
02567       ...
02568       """
02569       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSP, 2, 0))
02570 
02571    def wave_get_cbs(self):
02572       """
02573       Returns the length in DMA control blocks of the current
02574       waveform.
02575 
02576       ...
02577       cbs = pi.wave_get_cbs()
02578       ...
02579       """
02580       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 0, 0))
02581 
02582    def wave_get_max_cbs(self):
02583       """
02584       Returns the maximum possible size of a waveform in DMA
02585       control blocks.
02586 
02587       ...
02588       cbs = pi.wave_get_max_cbs()
02589       ...
02590       """
02591       return _u2i(_pigpio_command(self.sl, _PI_CMD_WVSC, 2, 0))
02592 
02593    def i2c_open(self, i2c_bus, i2c_address, i2c_flags=0):
02594       """
02595       Returns a handle (>=0) for the device at the I2C bus address.
02596 
02597           i2c_bus:= >=0.
02598       i2c_address:= 0-0x7F.
02599         i2c_flags:= 0, no flags are currently defined.
02600 
02601       Normally you would only use the [*i2c_**] functions if
02602       you are or will be connecting to the Pi over a network.  If
02603       you will always run on the local Pi use the standard SMBus
02604       module instead.
02605 
02606       Physically buses 0 and 1 are available on the Pi.  Higher
02607       numbered buses will be available if a kernel supported bus
02608       multiplexor is being used.
02609 
02610       For the SMBus commands the low level transactions are shown
02611       at the end of the function description.  The following
02612       abbreviations are used:
02613 
02614       . .
02615       S     (1 bit) : Start bit
02616       P     (1 bit) : Stop bit
02617       Rd/Wr (1 bit) : Read/Write bit. Rd equals 1, Wr equals 0.
02618       A, NA (1 bit) : Accept and not accept bit. 
02619       Addr  (7 bits): I2C 7 bit address.
02620       reg   (8 bits): Command byte, which often selects a register.
02621       Data  (8 bits): A data byte.
02622       Count (8 bits): A byte defining the length of a block operation.
02623 
02624       [..]: Data sent by the device.
02625       . .
02626 
02627       ...
02628       h = pi.i2c_open(1, 0x53) # open device at address 0x53 on bus 1
02629       ...
02630       """
02631       # I p1 i2c_bus
02632       # I p2 i2c_addr
02633       # I p3 4
02634       ## extension ##
02635       # I i2c_flags
02636       extents = [struct.pack("I", i2c_flags)]
02637       return _u2i(_pigpio_command_ext(
02638          self.sl, _PI_CMD_I2CO, i2c_bus, i2c_address, 4, extents))
02639 
02640    def i2c_close(self, handle):
02641       """
02642       Closes the I2C device associated with handle.
02643 
02644       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02645 
02646       ...
02647       pi.i2c_close(h)
02648       ...
02649       """
02650       return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CC, handle, 0))
02651 
02652    def i2c_write_quick(self, handle, bit):
02653       """
02654       Sends a single bit to the device associated with handle.
02655 
02656       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02657          bit:= 0 or 1, the value to write.
02658 
02659       SMBus 2.0 5.5.1 - Quick command.
02660       . .
02661       S Addr bit [A] P
02662       . .
02663 
02664       ...
02665       pi.i2c_write_quick(0, 1) # send 1 to device 0
02666       pi.i2c_write_quick(3, 0) # send 0 to device 3
02667       ...
02668       """
02669       return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CWQ, handle, bit))
02670 
02671    def i2c_write_byte(self, handle, byte_val):
02672       """
02673       Sends a single byte to the device associated with handle.
02674 
02675         handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02676       byte_val:= 0-255, the value to write.
02677 
02678       SMBus 2.0 5.5.2 - Send byte.
02679       . .
02680       S Addr Wr [A] byte_val [A] P
02681       . .
02682 
02683       ...
02684       pi.i2c_write_byte(1, 17)   # send byte   17 to device 1
02685       pi.i2c_write_byte(2, 0x23) # send byte 0x23 to device 2
02686       ...
02687       """
02688       return _u2i(
02689          _pigpio_command(self.sl, _PI_CMD_I2CWS, handle, byte_val))
02690 
02691    def i2c_read_byte(self, handle):
02692       """
02693       Reads a single byte from the device associated with handle.
02694 
02695       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02696 
02697       SMBus 2.0 5.5.3 - Receive byte.
02698       . .
02699       S Addr Rd [A] [Data] NA P
02700       . .
02701 
02702       ...
02703       b = pi.i2c_read_byte(2) # read a byte from device 2
02704       ...
02705       """
02706       return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRS, handle, 0))
02707 
02708    def i2c_write_byte_data(self, handle, reg, byte_val):
02709       """
02710       Writes a single byte to the specified register of the device
02711       associated with handle.
02712 
02713         handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02714            reg:= >=0, the device register.
02715       byte_val:= 0-255, the value to write.
02716 
02717       SMBus 2.0 5.5.4 - Write byte.
02718       . .
02719       S Addr Wr [A] reg [A] byte_val [A] P
02720       . .
02721 
02722       ...
02723       # send byte 0xC5 to reg 2 of device 1
02724       pi.i2c_write_byte_data(1, 2, 0xC5)
02725 
02726       # send byte 9 to reg 4 of device 2
02727       pi.i2c_write_byte_data(2, 4, 9)
02728       ...
02729       """
02730       # I p1 handle
02731       # I p2 reg
02732       # I p3 4
02733       ## extension ##
02734       # I byte_val
02735       extents = [struct.pack("I", byte_val)]
02736       return _u2i(_pigpio_command_ext(
02737          self.sl, _PI_CMD_I2CWB, handle, reg, 4, extents))
02738 
02739    def i2c_write_word_data(self, handle, reg, word_val):
02740       """
02741       Writes a single 16 bit word to the specified register of the
02742       device associated with handle.
02743 
02744         handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02745            reg:= >=0, the device register.
02746       word_val:= 0-65535, the value to write.
02747 
02748       SMBus 2.0 5.5.4 - Write word.
02749       . .
02750       S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A] P
02751       . .
02752 
02753       ...
02754       # send word 0xA0C5 to reg 5 of device 4
02755       pi.i2c_write_word_data(4, 5, 0xA0C5)
02756 
02757       # send word 2 to reg 2 of device 5
02758       pi.i2c_write_word_data(5, 2, 23)
02759       ...
02760       """
02761       # I p1 handle
02762       # I p2 reg
02763       # I p3 4
02764       ## extension ##
02765       # I word_val
02766       extents = [struct.pack("I", word_val)]
02767       return _u2i(_pigpio_command_ext(
02768          self.sl, _PI_CMD_I2CWW, handle, reg, 4, extents))
02769 
02770    def i2c_read_byte_data(self, handle, reg):
02771       """
02772       Reads a single byte from the specified register of the device
02773       associated with handle.
02774 
02775       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02776          reg:= >=0, the device register.
02777 
02778       SMBus 2.0 5.5.5 - Read byte.
02779       . .
02780       S Addr Wr [A] reg [A] S Addr Rd [A] [Data] NA P
02781       . .
02782 
02783       ...
02784       # read byte from reg 17 of device 2
02785       b = pi.i2c_read_byte_data(2, 17)
02786 
02787       # read byte from reg  1 of device 0
02788       b = pi.i2c_read_byte_data(0, 1)
02789       ...
02790       """
02791       return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRB, handle, reg))
02792 
02793    def i2c_read_word_data(self, handle, reg):
02794       """
02795       Reads a single 16 bit word from the specified register of the
02796       device associated with handle.
02797 
02798       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02799          reg:= >=0, the device register.
02800 
02801       SMBus 2.0 5.5.5 - Read word.
02802       . .
02803       S Addr Wr [A] reg [A] S Addr Rd [A] [DataLow] A [DataHigh] NA P
02804       . .
02805 
02806       ...
02807       # read word from reg 2 of device 3
02808       w = pi.i2c_read_word_data(3, 2)
02809 
02810       # read word from reg 7 of device 2
02811       w = pi.i2c_read_word_data(2, 7)
02812       ...
02813       """
02814       return _u2i(_pigpio_command(self.sl, _PI_CMD_I2CRW, handle, reg))
02815 
02816    def i2c_process_call(self, handle, reg, word_val):
02817       """
02818       Writes 16 bits of data to the specified register of the device
02819       associated with handle and reads 16 bits of data in return.
02820 
02821         handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02822            reg:= >=0, the device register.
02823       word_val:= 0-65535, the value to write.
02824 
02825       SMBus 2.0 5.5.6 - Process call.
02826       . .
02827       S Addr Wr [A] reg [A] word_val_Low [A] word_val_High [A]
02828          S Addr Rd [A] [DataLow] A [DataHigh] NA P
02829       . .
02830 
02831       ...
02832       r = pi.i2c_process_call(h, 4, 0x1231)
02833       r = pi.i2c_process_call(h, 6, 0)
02834       ...
02835       """
02836       # I p1 handle
02837       # I p2 reg
02838       # I p3 4
02839       ## extension ##
02840       # I word_val
02841       extents = [struct.pack("I", word_val)]
02842       return _u2i(_pigpio_command_ext(
02843          self.sl, _PI_CMD_I2CPC, handle, reg, 4, extents))
02844 
02845    def i2c_write_block_data(self, handle, reg, data):
02846       """
02847       Writes up to 32 bytes to the specified register of the device
02848       associated with handle.
02849 
02850       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02851          reg:= >=0, the device register.
02852         data:= the bytes to write.
02853 
02854       SMBus 2.0 5.5.7 - Block write.
02855       . .
02856       S Addr Wr [A] reg [A] len(data) [A] data0 [A] data1 [A] ... [A]
02857          datan [A] P
02858       . .
02859 
02860       ...
02861       pi.i2c_write_block_data(4, 5, b'hello')
02862 
02863       pi.i2c_write_block_data(4, 5, "data bytes")
02864 
02865       pi.i2c_write_block_data(5, 0, b'\\x00\\x01\\x22')
02866 
02867       pi.i2c_write_block_data(6, 2, [0, 1, 0x22])
02868       ...
02869       """
02870       # I p1 handle
02871       # I p2 reg
02872       # I p3 len
02873       ## extension ##
02874       # s len data bytes
02875       if len(data):
02876          return _u2i(_pigpio_command_ext(
02877             self.sl, _PI_CMD_I2CWK, handle, reg, len(data), [data]))
02878       else:
02879          return 0
02880 
02881    def i2c_read_block_data(self, handle, reg):
02882       """
02883       Reads a block of up to 32 bytes from the specified register of
02884       the device associated with handle.
02885 
02886       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02887          reg:= >=0, the device register.
02888 
02889       SMBus 2.0 5.5.7 - Block read.
02890       . .
02891       S Addr Wr [A] reg [A]
02892          S Addr Rd [A] [Count] A [Data] A [Data] A ... A [Data] NA P
02893       . .
02894 
02895       The amount of returned data is set by the device.
02896 
02897       The returned value is a tuple of the number of bytes read and a
02898       bytearray containing the bytes.  If there was an error the
02899       number of bytes read will be less than zero (and will contain
02900       the error code).
02901 
02902       ...
02903       (b, d) = pi.i2c_read_block_data(h, 10)
02904       if b >= 0:
02905          # process data
02906       else:
02907          # process read failure
02908       ...
02909       """
02910       bytes = PI_CMD_INTERRUPTED
02911       rdata = ""
02912       with self.sl.l:
02913          bytes = u2i(_pigpio_command_nolock(
02914             self.sl, _PI_CMD_I2CRK, handle, reg))
02915          if bytes > 0:
02916             rdata = self._rxbuf(bytes)
02917       return bytes, rdata
02918 
02919    def i2c_block_process_call(self, handle, reg, data):
02920       """
02921       Writes data bytes to the specified register of the device
02922       associated with handle and reads a device specified number
02923       of bytes of data in return.
02924 
02925       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02926          reg:= >=0, the device register.
02927         data:= the bytes to write.
02928 
02929       The SMBus 2.0 documentation states that a minimum of 1 byte may
02930       be sent and a minimum of 1 byte may be received.  The total
02931       number of bytes sent/received must be 32 or less.
02932 
02933       SMBus 2.0 5.5.8 - Block write-block read.
02934       . .
02935       S Addr Wr [A] reg [A] len(data) [A] data0 [A] ... datan [A]
02936          S Addr Rd [A] [Count] A [Data] ... A P
02937       . .
02938 
02939       The returned value is a tuple of the number of bytes read and a
02940       bytearray containing the bytes.  If there was an error the
02941       number of bytes read will be less than zero (and will contain
02942       the error code).
02943 
02944       ...
02945       (b, d) = pi.i2c_block_process_call(h, 10, b'\\x02\\x05\\x00')
02946 
02947       (b, d) = pi.i2c_block_process_call(h, 10, b'abcdr')
02948 
02949       (b, d) = pi.i2c_block_process_call(h, 10, "abracad")
02950 
02951       (b, d) = pi.i2c_block_process_call(h, 10, [2, 5, 16])
02952       ...
02953       """
02954       # I p1 handle
02955       # I p2 reg
02956       # I p3 len
02957       ## extension ##
02958       # s len data bytes
02959 
02960       bytes = PI_CMD_INTERRUPTED
02961       rdata = ""
02962       with self.sl.l:
02963          bytes = u2i(_pigpio_command_ext_nolock(
02964             self.sl, _PI_CMD_I2CPK, handle, reg, len(data), [data]))
02965          if bytes > 0:
02966             rdata = self._rxbuf(bytes)
02967       return bytes, rdata
02968 
02969    def i2c_write_i2c_block_data(self, handle, reg, data):
02970       """
02971       Writes data bytes to the specified register of the device
02972       associated with handle .  1-32 bytes may be written.
02973 
02974       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
02975          reg:= >=0, the device register.
02976         data:= the bytes to write.
02977 
02978       . .
02979       S Addr Wr [A] reg [A] data0 [A] data1 [A] ... [A] datan [NA] P
02980       . .
02981 
02982       ...
02983       pi.i2c_write_i2c_block_data(4, 5, 'hello')
02984 
02985       pi.i2c_write_i2c_block_data(4, 5, b'hello')
02986 
02987       pi.i2c_write_i2c_block_data(5, 0, b'\\x00\\x01\\x22')
02988 
02989       pi.i2c_write_i2c_block_data(6, 2, [0, 1, 0x22])
02990       ...
02991       """
02992       # I p1 handle
02993       # I p2 reg
02994       # I p3 len
02995       ## extension ##
02996       # s len data bytes
02997       if len(data):
02998          return _u2i(_pigpio_command_ext(
02999             self.sl, _PI_CMD_I2CWI, handle, reg, len(data), [data]))
03000       else:
03001          return 0
03002 
03003    def i2c_read_i2c_block_data(self, handle, reg, count):
03004       """
03005       Reads count bytes from the specified register of the device
03006       associated with handle .  The count may be 1-32.
03007 
03008       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
03009          reg:= >=0, the device register.
03010        count:= >0, the number of bytes to read.
03011 
03012       . .
03013       S Addr Wr [A] reg [A]
03014          S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
03015       . .
03016 
03017       The returned value is a tuple of the number of bytes read and a
03018       bytearray containing the bytes.  If there was an error the
03019       number of bytes read will be less than zero (and will contain
03020       the error code).
03021 
03022       ...
03023       (b, d) = pi.i2c_read_i2c_block_data(h, 4, 32)
03024       if b >= 0:
03025          # process data
03026       else:
03027          # process read failure
03028       ...
03029       """
03030       # I p1 handle
03031       # I p2 reg
03032       # I p3 4
03033       ## extension ##
03034       # I count
03035       extents = [struct.pack("I", count)]
03036 
03037       bytes = PI_CMD_INTERRUPTED
03038       rdata = ""
03039       with self.sl.l:
03040          bytes = u2i(_pigpio_command_ext_nolock(
03041             self.sl, _PI_CMD_I2CRI, handle, reg, 4, extents))
03042          if bytes > 0:
03043             rdata = self._rxbuf(bytes)
03044       return bytes, rdata
03045 
03046    def i2c_read_device(self, handle, count):
03047       """
03048       Returns count bytes read from the raw device associated
03049       with handle.
03050 
03051       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
03052        count:= >0, the number of bytes to read.
03053 
03054       . .
03055       S Addr Rd [A] [Data] A [Data] A ... A [Data] NA P
03056       . .
03057 
03058       The returned value is a tuple of the number of bytes read and a
03059       bytearray containing the bytes.  If there was an error the
03060       number of bytes read will be less than zero (and will contain
03061       the error code).
03062 
03063       ...
03064       (count, data) = pi.i2c_read_device(h, 12)
03065       ...
03066       """
03067       bytes = PI_CMD_INTERRUPTED
03068       rdata = ""
03069       with self.sl.l:
03070          bytes = u2i(
03071             _pigpio_command_nolock(self.sl, _PI_CMD_I2CRD, handle, count))
03072          if bytes > 0:
03073             rdata = self._rxbuf(bytes)
03074       return bytes, rdata
03075 
03076    def i2c_write_device(self, handle, data):
03077       """
03078       Writes the data bytes to the raw device associated with handle.
03079 
03080       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
03081         data:= the bytes to write.
03082 
03083       . .
03084       S Addr Wr [A] data0 [A] data1 [A] ... [A] datan [A] P
03085       . .
03086 
03087       ...
03088       pi.i2c_write_device(h, b"\\x12\\x34\\xA8")
03089 
03090       pi.i2c_write_device(h, b"help")
03091 
03092       pi.i2c_write_device(h, 'help')
03093 
03094       pi.i2c_write_device(h, [23, 56, 231])
03095       ...
03096       """
03097       # I p1 handle
03098       # I p2 0
03099       # I p3 len
03100       ## extension ##
03101       # s len data bytes
03102       if len(data):
03103          return _u2i(_pigpio_command_ext(
03104             self.sl, _PI_CMD_I2CWD, handle, 0, len(data), [data]))
03105       else:
03106          return 0
03107 
03108 
03109    def i2c_zip(self, handle, data):
03110       """
03111       This function executes a sequence of I2C operations.  The
03112       operations to be performed are specified by the contents of data
03113       which contains the concatenated command codes and associated data.
03114 
03115       handle:= >=0 (as returned by a prior call to [*i2c_open*]).
03116         data:= the concatenated I2C commands, see below
03117 
03118       The returned value is a tuple of the number of bytes read and a
03119       bytearray containing the bytes.  If there was an error the
03120       number of bytes read will be less than zero (and will contain
03121       the error code).
03122 
03123       ...
03124       (count, data) = pi.i2c_zip(h, [4, 0x53, 7, 1, 0x32, 6, 6, 0])
03125       ...
03126 
03127       The following command codes are supported:
03128 
03129       Name    @ Cmd & Data @ Meaning
03130       End     @ 0          @ No more commands
03131       Escape  @ 1          @ Next P is two bytes
03132       On      @ 2          @ Switch combined flag on
03133       Off     @ 3          @ Switch combined flag off
03134       Address @ 4 P        @ Set I2C address to P
03135       Flags   @ 5 lsb msb  @ Set I2C flags to lsb + (msb << 8)
03136       Read    @ 6 P        @ Read P bytes of data
03137       Write   @ 7 P ...    @ Write P bytes of data
03138 
03139       The address, read, and write commands take a parameter P.
03140       Normally P is one byte (0-255).  If the command is preceded by
03141       the Escape command then P is two bytes (0-65535, least significant
03142       byte first).
03143 
03144       The address defaults to that associated with the handle.
03145       The flags default to 0.  The address and flags maintain their
03146       previous value until updated.
03147 
03148       Any read I2C data is concatenated in the returned bytearray.
03149 
03150       ...
03151       Set address 0x53, write 0x32, read 6 bytes
03152       Set address 0x1E, write 0x03, read 6 bytes
03153       Set address 0x68, write 0x1B, read 8 bytes
03154       End
03155 
03156       0x04 0x53   0x07 0x01 0x32   0x06 0x06
03157       0x04 0x1E   0x07 0x01 0x03   0x06 0x06
03158       0x04 0x68   0x07 0x01 0x1B   0x06 0x08
03159       0x00
03160       ...
03161       """
03162       # I p1 handle
03163       # I p2 0
03164       # I p3 len
03165       ## extension ##
03166       # s len data bytes
03167 
03168       bytes = PI_CMD_INTERRUPTED
03169       rdata = ""
03170       with self.sl.l:
03171          bytes = u2i(_pigpio_command_ext_nolock(
03172             self.sl, _PI_CMD_I2CZ, handle, 0, len(data), [data]))
03173          if bytes > 0:
03174             rdata = self._rxbuf(bytes)
03175       return bytes, rdata
03176 
03177 
03178    def bb_spi_open(self, CS, MISO, MOSI, SCLK, baud=100000, spi_flags=0):
03179       """
03180       This function selects a set of GPIO for bit banging SPI at a
03181       specified baud rate.
03182 
03183             CS := 0-31
03184           MISO := 0-31
03185           MOSI := 0-31
03186           SCLK := 0-31
03187           baud := 50-250000
03188       spiFlags := see below
03189       
03190       spiFlags consists of the least significant 22 bits.
03191 
03192       . .
03193       21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
03194        0  0  0  0  0  0  R  T  0  0  0  0  0  0  0  0  0  0  0  p  m  m
03195       . .
03196 
03197       mm defines the SPI mode, defaults to 0
03198 
03199       . .
03200       Mode CPOL CPHA
03201        0     0    0
03202        1     0    1
03203        2     1    0
03204        3     1    1
03205       . .
03206 
03207       The following constants may be used to set the mode:
03208 
03209       . .
03210       pigpio.SPI_MODE_0
03211       pigpio.SPI_MODE_1
03212       pigpio.SPI_MODE_2
03213       pigpio.SPI_MODE_3
03214       . .
03215 
03216       Alternatively pigpio.SPI_CPOL and/or pigpio.SPI_CPHA
03217       may be used.
03218 
03219       p is 0 if CS is active low (default) and 1 for active high.
03220       pigpio.SPI_CS_HIGH_ACTIVE may be used to set this flag.
03221 
03222       T is 1 if the least significant bit is transmitted on MOSI first,
03223       the default (0) shifts the most significant bit out first.
03224       pigpio.SPI_TX_LSBFIRST may be used to set this flag.
03225 
03226       R is 1 if the least significant bit is received on MISO first,
03227       the default (0) receives the most significant bit first.
03228       pigpio.SPI_RX_LSBFIRST may be used to set this flag.
03229 
03230       The other bits in spiFlags should be set to zero.
03231 
03232       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_SPI_BAUD, or
03233       PI_GPIO_IN_USE.
03234 
03235       If more than one device is connected to the SPI bus (defined by
03236       SCLK, MOSI, and MISO) each must have its own CS.
03237 
03238       ...
03239       bb_spi_open(10, MISO, MOSI, SCLK, 10000, 0); // device 1
03240       bb_spi_open(11, MISO, MOSI, SCLK, 20000, 3); // device 2
03241       ...
03242       """
03243       # I p1 CS
03244       # I p2 0
03245       # I p3 20
03246       ## extension ##
03247       # I MISO
03248       # I MOSI
03249       # I SCLK
03250       # I baud
03251       # I spi_flags
03252       
03253       extents = [struct.pack("IIIII", MISO, MOSI, SCLK, baud, spi_flags)]
03254       return _u2i(_pigpio_command_ext(
03255          self.sl, _PI_CMD_BSPIO, CS, 0, 20, extents))
03256 
03257 
03258    def bb_spi_close(self, CS):
03259       """
03260       This function stops bit banging SPI on a set of GPIO
03261       opened with [*bb_spi_open*].
03262 
03263       CS:= 0-31, the CS GPIO used in a prior call to [*bb_spi_open*]
03264 
03265       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_SPI_GPIO.
03266 
03267       ...
03268       pi.bb_spi_close(CS)
03269       ...
03270       """
03271       return _u2i(_pigpio_command(self.sl, _PI_CMD_BSPIC, CS, 0))
03272 
03273 
03274    def bb_spi_xfer(self, CS, data):
03275       """
03276       This function executes a bit banged SPI transfer.
03277 
03278         CS:= 0-31 (as used in a prior call to [*bb_spi_open*])
03279       data:= data to be sent
03280 
03281       The returned value is a tuple of the number of bytes read and a
03282       bytearray containing the bytes.  If there was an error the
03283       number of bytes read will be less than zero (and will contain
03284       the error code).
03285 
03286       ...
03287       #!/usr/bin/env python
03288 
03289       import pigpio
03290 
03291       CE0=5
03292       CE1=6
03293       MISO=13
03294       MOSI=19
03295       SCLK=12
03296 
03297       pi = pigpio.pi()
03298       if not pi.connected:
03299          exit()
03300 
03301       pi.bb_spi_open(CE0, MISO, MOSI, SCLK, 10000, 0) # MCP4251 DAC
03302       pi.bb_spi_open(CE1, MISO, MOSI, SCLK, 20000, 3) # MCP3008 ADC
03303 
03304       for i in range(256):
03305 
03306          count, data = pi.bb_spi_xfer(CE0, [0, i]) # Set DAC value
03307 
03308          if count == 2:
03309 
03310             count, data = pi.bb_spi_xfer(CE0, [12, 0]) # Read back DAC
03311 
03312             if count == 2:
03313 
03314                set_val = data[1]
03315 
03316                count, data = pi.bb_spi_xfer(CE1, [1, 128, 0]) # Read ADC
03317 
03318                if count == 3:
03319 
03320                   read_val = ((data[1]&3)<<8) | data[2]
03321 
03322                   print("{} {}".format(set_val, read_val))
03323 
03324       pi.bb_spi_close(CE0)
03325       pi.bb_spi_close(CE1)
03326 
03327       pi.stop()
03328       ...
03329       """
03330       # I p1 CS
03331       # I p2 0
03332       # I p3 len
03333       ## extension ##
03334       # s len data bytes
03335 
03336       bytes = PI_CMD_INTERRUPTED
03337       rdata = ""
03338       with self.sl.l:
03339          bytes = u2i(_pigpio_command_ext_nolock(
03340             self.sl, _PI_CMD_BSPIX, CS, 0, len(data), [data]))
03341          if bytes > 0:
03342             rdata = self._rxbuf(bytes)
03343       return bytes, rdata
03344 
03345 
03346    def bb_i2c_open(self, SDA, SCL, baud=100000):
03347       """
03348       This function selects a pair of GPIO for bit banging I2C at a
03349       specified baud rate.
03350 
03351       Bit banging I2C allows for certain operations which are not possible
03352       with the standard I2C driver.
03353 
03354       o baud rates as low as 50 
03355       o repeated starts 
03356       o clock stretching 
03357       o I2C on any pair of spare GPIO
03358 
03359        SDA:= 0-31
03360        SCL:= 0-31
03361       baud:= 50-500000
03362 
03363       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, PI_BAD_I2C_BAUD, or
03364       PI_GPIO_IN_USE.
03365 
03366       NOTE:
03367 
03368       The GPIO used for SDA and SCL must have pull-ups to 3V3 connected.
03369       As a guide the hardware pull-ups on pins 3 and 5 are 1k8 in value.
03370 
03371       ...
03372       h = pi.bb_i2c_open(4, 5, 50000) # bit bang on GPIO 4/5 at 50kbps
03373       ...
03374       """
03375       # I p1 SDA
03376       # I p2 SCL
03377       # I p3 4
03378       ## extension ##
03379       # I baud
03380       extents = [struct.pack("I", baud)]
03381       return _u2i(_pigpio_command_ext(
03382          self.sl, _PI_CMD_BI2CO, SDA, SCL, 4, extents))
03383 
03384 
03385    def bb_i2c_close(self, SDA):
03386       """
03387       This function stops bit banging I2C on a pair of GPIO
03388       previously opened with [*bb_i2c_open*].
03389 
03390       SDA:= 0-31, the SDA GPIO used in a prior call to [*bb_i2c_open*]
03391 
03392       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_NOT_I2C_GPIO.
03393 
03394       ...
03395       pi.bb_i2c_close(SDA)
03396       ...
03397       """
03398       return _u2i(_pigpio_command(self.sl, _PI_CMD_BI2CC, SDA, 0))
03399 
03400 
03401    def bb_i2c_zip(self, SDA, data):
03402       """
03403       This function executes a sequence of bit banged I2C operations.
03404       The operations to be performed are specified by the contents
03405       of data which contains the concatenated command codes and
03406       associated data.
03407 
03408        SDA:= 0-31 (as used in a prior call to [*bb_i2c_open*])
03409       data:= the concatenated I2C commands, see below
03410 
03411       The returned value is a tuple of the number of bytes read and a
03412       bytearray containing the bytes.  If there was an error the
03413       number of bytes read will be less than zero (and will contain
03414       the error code).
03415 
03416       ...
03417       (count, data) = pi.bb_i2c_zip(
03418                          SDA, [4, 0x53, 2, 7, 1, 0x32, 2, 6, 6, 3, 0])
03419       ...
03420 
03421       The following command codes are supported:
03422 
03423       Name    @ Cmd & Data   @ Meaning
03424       End     @ 0            @ No more commands
03425       Escape  @ 1            @ Next P is two bytes
03426       Start   @ 2            @ Start condition
03427       Stop    @ 3            @ Stop condition
03428       Address @ 4 P          @ Set I2C address to P
03429       Flags   @ 5 lsb msb    @ Set I2C flags to lsb + (msb << 8)
03430       Read    @ 6 P          @ Read P bytes of data
03431       Write   @ 7 P ...      @ Write P bytes of data
03432 
03433       The address, read, and write commands take a parameter P.
03434       Normally P is one byte (0-255).  If the command is preceded by
03435       the Escape command then P is two bytes (0-65535, least significant
03436       byte first).
03437 
03438       The address and flags default to 0.  The address and flags maintain
03439       their previous value until updated.
03440 
03441       No flags are currently defined.
03442 
03443       Any read I2C data is concatenated in the returned bytearray.
03444 
03445       ...
03446       Set address 0x53
03447       start, write 0x32, (re)start, read 6 bytes, stop
03448       Set address 0x1E
03449       start, write 0x03, (re)start, read 6 bytes, stop
03450       Set address 0x68
03451       start, write 0x1B, (re)start, read 8 bytes, stop
03452       End
03453 
03454       0x04 0x53
03455       0x02 0x07 0x01 0x32   0x02 0x06 0x06 0x03
03456 
03457       0x04 0x1E
03458       0x02 0x07 0x01 0x03   0x02 0x06 0x06 0x03
03459 
03460       0x04 0x68
03461       0x02 0x07 0x01 0x1B   0x02 0x06 0x08 0x03
03462 
03463       0x00
03464       ...
03465       """
03466       # I p1 SDA
03467       # I p2 0
03468       # I p3 len
03469       ## extension ##
03470       # s len data bytes
03471 
03472       bytes = PI_CMD_INTERRUPTED
03473       rdata = ""
03474       with self.sl.l:
03475          bytes = u2i(_pigpio_command_ext_nolock(
03476             self.sl, _PI_CMD_BI2CZ, SDA, 0, len(data), [data]))
03477          if bytes > 0:
03478             rdata = self._rxbuf(bytes)
03479       return bytes, rdata
03480 
03481    def event_trigger(self, event):
03482       """
03483       This function signals the occurrence of an event.
03484 
03485       event:= 0-31, the event
03486 
03487       Returns 0 if OK, otherwise PI_BAD_EVENT_ID.
03488 
03489       An event is a signal used to inform one or more consumers
03490       to start an action.  Each consumer which has registered an
03491       interest in the event (e.g. by calling [*event_callback*]) will
03492       be informed by a callback.
03493 
03494       One event, EVENT_BSC (31) is predefined.  This event is
03495       auto generated on BSC slave activity.
03496 
03497       The meaning of other events is arbitrary.
03498 
03499       Note that other than its id and its tick there is no data associated
03500       with an event.
03501 
03502       ...
03503       pi.event_trigger(23)
03504       ...
03505       """
03506       return _u2i(_pigpio_command(self.sl, _PI_CMD_EVT, event, 0))
03507 
03508 
03509    def bsc_xfer(self, bsc_control, data):
03510       """
03511       This function provides a low-level interface to the
03512       SPI/I2C Slave peripheral.  This peripheral allows the
03513       Pi to act as a slave device on an I2C or SPI bus.
03514 
03515       I can't get SPI to work properly.  I tried with a
03516       control word of 0x303 and swapped MISO and MOSI.
03517 
03518 
03519       The function sets the BSC mode, writes any data in
03520       the transmit buffer to the BSC transmit FIFO, and
03521       copies any data in the BSC receive FIFO to the
03522       receive buffer.
03523 
03524       bsc_control:= see below
03525              data:= the data bytes to place in the transmit FIFO.
03526 
03527       The returned value is a tuple of the status (see below),
03528       the number of bytes read, and a bytearray containing the
03529       read bytes.  If there was an error the status will be less
03530       than zero (and will contain the error code).
03531 
03532       Note that the control word sets the BSC mode.  The BSC will
03533       stay in that mode until a different control word is sent.
03534 
03535       The BSC peripheral uses GPIO 18 (SDA) and 19 (SCL)
03536       in I2C mode and GPIO 18 (MOSI), 19 (SCLK), 20 (MISO),
03537       and 21 (CE) in SPI mode.  You need to swap MISO/MOSI
03538       between master and slave.
03539 
03540       When a zero control word is received GPIO 18-21 will be reset
03541       to INPUT mode.
03542 
03543       bsc_control consists of the following bits:
03544 
03545       . .
03546       22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
03547        a  a  a  a  a  a  a  -  - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN
03548       . .
03549 
03550       Bits 0-13 are copied unchanged to the BSC CR register.  See
03551       pages 163-165 of the Broadcom peripherals document for full
03552       details.
03553 
03554       aaaaaaa @ defines the I2C slave address (only relevant in I2C mode)
03555       IT      @ invert transmit status flags
03556       HC      @ enable host control
03557       TF      @ enable test FIFO
03558       IR      @ invert receive status flags
03559       RE      @ enable receive
03560       TE      @ enable transmit
03561       BK      @ abort operation and clear FIFOs
03562       EC      @ send control register as first I2C byte
03563       ES      @ send status register as first I2C byte
03564       PL      @ set SPI polarity high
03565       PH      @ set SPI phase high
03566       I2      @ enable I2C mode
03567       SP      @ enable SPI mode
03568       EN      @ enable BSC peripheral
03569 
03570       The status has the following format:
03571 
03572       . .
03573       20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
03574        S  S  S  S  S  R  R  R  R  R  T  T  T  T  T RB TE RF TF RE TB
03575       . .
03576 
03577       Bits 0-15 are copied unchanged from the BSC FR register.  See
03578       pages 165-166 of the Broadcom peripherals document for full
03579       details.
03580 
03581       SSSSS @ number of bytes successfully copied to transmit FIFO
03582       RRRRR @ number of bytes in receieve FIFO
03583       TTTTT @ number of bytes in transmit FIFO
03584       RB    @ receive busy
03585       TE    @ transmit FIFO empty
03586       RF    @ receive FIFO full
03587       TF    @ transmit FIFO full
03588       RE    @ receive FIFO empty
03589       TB    @ transmit busy
03590 
03591       ...
03592       (status, count, data) = pi.bsc_xfer(0x330305, "Hello!")
03593       ...
03594       """
03595       # I p1 control
03596       # I p2 0
03597       # I p3 len
03598       ## extension ##
03599       # s len data bytes
03600 
03601       status = PI_CMD_INTERRUPTED
03602       bytes = 0
03603       rdata = bytearray(b'')
03604       with self.sl.l:
03605          bytes = u2i(_pigpio_command_ext_nolock(
03606             self.sl, _PI_CMD_BSCX, bsc_control, 0, len(data), [data]))
03607          if bytes > 0:
03608             rx = self._rxbuf(bytes)
03609             status = struct.unpack('I', rx[0:4])[0]
03610             bytes -= 4
03611             rdata = rx[4:]
03612          else:
03613             status = bytes
03614             bytes = 0
03615       return status, bytes, rdata
03616 
03617    def bsc_i2c(self, i2c_address, data=[]):
03618       """
03619       This function allows the Pi to act as a slave I2C device.
03620 
03621       The data bytes (if any) are written to the BSC transmit
03622       FIFO and the bytes in the BSC receive FIFO are returned.
03623 
03624       i2c_address:= the I2C slave address.
03625              data:= the data bytes to transmit.
03626 
03627       The returned value is a tuple of the status, the number
03628       of bytes read, and a bytearray containing the read bytes.
03629 
03630       See [*bsc_xfer*] for details of the status value.
03631 
03632       If there was an error the status will be less than zero
03633       (and will contain the error code).
03634 
03635       Note that an i2c_address of 0 may be used to close
03636       the BSC device and reassign the used GPIO (18/19)
03637       as inputs.
03638 
03639       This example assumes GPIO 2/3 are connected to GPIO 18/19.
03640 
03641       ...
03642       #!/usr/bin/env python
03643       import time
03644       import pigpio
03645 
03646       I2C_ADDR=0x13
03647 
03648       def i2c(id, tick):
03649           global pi
03650 
03651           s, b, d = pi.bsc_i2c(I2C_ADDR)
03652           if b:
03653               if d[0] == ord('t'): # 116 send 'HH:MM:SS*'
03654 
03655                   print("sent={} FR={} received={} [{}]".
03656                      format(s>>16, s&0xfff,b,d))
03657 
03658                   s, b, d = pi.bsc_i2c(I2C_ADDR,
03659                      "{}*".format(time.asctime()[11:19]))
03660 
03661               elif d[0] == ord('d'): # 100 send 'Sun Oct 30*'
03662 
03663                   print("sent={} FR={} received={} [{}]".
03664                      format(s>>16, s&0xfff,b,d))
03665 
03666                   s, b, d = pi.bsc_i2c(I2C_ADDR,
03667                      "{}*".format(time.asctime()[:10]))
03668 
03669       pi = pigpio.pi()
03670 
03671       if not pi.connected:
03672           exit()
03673 
03674       # Respond to BSC slave activity
03675 
03676       e = pi.event_callback(pigpio.EVENT_BSC, i2c)
03677 
03678       pi.bsc_i2c(I2C_ADDR) # Configure BSC as I2C slave
03679 
03680       time.sleep(600)
03681 
03682       e.cancel()
03683 
03684       pi.bsc_i2c(0) # Disable BSC peripheral
03685 
03686       pi.stop()
03687       ...
03688 
03689       While running the above.
03690 
03691       . .
03692       $ i2cdetect -y 1
03693           0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
03694       00:          -- -- -- -- -- -- -- -- -- -- -- -- --
03695       10: -- -- -- 13 -- -- -- -- -- -- -- -- -- -- -- --
03696       20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
03697       30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
03698       40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
03699       50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
03700       60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
03701       70: -- -- -- -- -- -- -- --
03702 
03703       $ pigs i2co 1 0x13 0
03704       0
03705 
03706       $ pigs i2cwd 0 116
03707       $ pigs i2crd 0 9 -a
03708       9 10:13:58*
03709 
03710       $ pigs i2cwd 0 116
03711       $ pigs i2crd 0 9 -a
03712       9 10:14:29*
03713 
03714       $ pigs i2cwd 0 100
03715       $ pigs i2crd 0 11 -a
03716       11 Sun Oct 30*
03717 
03718       $ pigs i2cwd 0 100
03719       $ pigs i2crd 0 11 -a
03720       11 Sun Oct 30*
03721 
03722       $ pigs i2cwd 0 116
03723       $ pigs i2crd 0 9 -a
03724       9 10:23:16*
03725 
03726       $ pigs i2cwd 0 100
03727       $ pigs i2crd 0 11 -a
03728       11 Sun Oct 30*
03729       . .
03730       """
03731       if i2c_address:
03732          control = (i2c_address<<16)|0x305
03733       else:
03734          control = 0
03735       return self.bsc_xfer(control, data)
03736 
03737    def spi_open(self, spi_channel, baud, spi_flags=0):
03738       """
03739       Returns a handle for the SPI device on channel.  Data will be
03740       transferred at baud bits per second.  The flags may be used to
03741       modify the default behaviour of 4-wire operation, mode 0,
03742       active low chip select.
03743 
03744       An auxiliary SPI device is available on all models but the
03745       A and B and may be selected by setting the A bit in the
03746       flags. The auxiliary device has 3 chip selects and a
03747       selectable word size in bits.
03748 
03749       spi_channel:= 0-1 (0-2 for the auxiliary SPI device).
03750              baud:= 32K-125M (values above 30M are unlikely to work).
03751         spi_flags:= see below.
03752 
03753       Normally you would only use the [*spi_**] functions if
03754       you are or will be connecting to the Pi over a network.  If
03755       you will always run on the local Pi use the standard SPI
03756       module instead.
03757 
03758       spi_flags consists of the least significant 22 bits.
03759 
03760       . .
03761       21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
03762        b  b  b  b  b  b  R  T  n  n  n  n  W  A u2 u1 u0 p2 p1 p0  m  m
03763       . .
03764 
03765       mm defines the SPI mode.
03766 
03767       WARNING: modes 1 and 3 do not appear to work on
03768       the auxiliary device.
03769 
03770       . .
03771       Mode POL PHA
03772        0    0   0
03773        1    0   1
03774        2    1   0
03775        3    1   1
03776       . .
03777 
03778       px is 0 if CEx is active low (default) and 1 for active high.
03779 
03780       ux is 0 if the CEx GPIO is reserved for SPI (default)
03781       and 1 otherwise.
03782 
03783       A is 0 for the standard SPI device, 1 for the auxiliary SPI.
03784 
03785       W is 0 if the device is not 3-wire, 1 if the device is 3-wire.
03786       Standard SPI device only.
03787 
03788       nnnn defines the number of bytes (0-15) to write before
03789       switching the MOSI line to MISO to read data.  This field
03790       is ignored if W is not set.  Standard SPI device only.
03791 
03792       T is 1 if the least significant bit is transmitted on MOSI
03793       first, the default (0) shifts the most significant bit out
03794       first.  Auxiliary SPI device only.
03795 
03796       R is 1 if the least significant bit is received on MISO
03797       first, the default (0) receives the most significant bit
03798       first.  Auxiliary SPI device only.
03799 
03800       bbbbbb defines the word size in bits (0-32).  The default (0)
03801       sets 8 bits per word.  Auxiliary SPI device only.
03802 
03803       The [*spi_read*], [*spi_write*], and [*spi_xfer*] functions
03804       transfer data packed into 1, 2, or 4 bytes according to
03805       the word size in bits.
03806 
03807       For bits 1-8 there will be one byte per character. 
03808       For bits 9-16 there will be two bytes per character. 
03809       For bits 17-32 there will be four bytes per character.
03810 
03811       Multi-byte transfers are made in least significant byte
03812       first order.
03813 
03814       E.g. to transfer 32 11-bit words data should
03815       contain 64 bytes.
03816 
03817       E.g. to transfer the 14 bit value 0x1ABC send the
03818       bytes 0xBC followed by 0x1A.
03819 
03820       The other bits in flags should be set to zero.
03821 
03822       ...
03823       # open SPI device on channel 1 in mode 3 at 50000 bits per second
03824 
03825       h = pi.spi_open(1, 50000, 3)
03826       ...
03827       """
03828       # I p1 spi_channel
03829       # I p2 baud
03830       # I p3 4
03831       ## extension ##
03832       # I spi_flags
03833       extents = [struct.pack("I", spi_flags)]
03834       return _u2i(_pigpio_command_ext(
03835          self.sl, _PI_CMD_SPIO, spi_channel, baud, 4, extents))
03836 
03837    def spi_close(self, handle):
03838       """
03839       Closes the SPI device associated with handle.
03840 
03841       handle:= >=0 (as returned by a prior call to [*spi_open*]).
03842 
03843       ...
03844       pi.spi_close(h)
03845       ...
03846       """
03847       return _u2i(_pigpio_command(self.sl, _PI_CMD_SPIC, handle, 0))
03848 
03849    def spi_read(self, handle, count):
03850       """
03851       Reads count bytes from the SPI device associated with handle.
03852 
03853       handle:= >=0 (as returned by a prior call to [*spi_open*]).
03854        count:= >0, the number of bytes to read.
03855 
03856       The returned value is a tuple of the number of bytes read and a
03857       bytearray containing the bytes.  If there was an error the
03858       number of bytes read will be less than zero (and will contain
03859       the error code).
03860 
03861       ...
03862       (b, d) = pi.spi_read(h, 60) # read 60 bytes from device h
03863       if b == 60:
03864          # process read data
03865       else:
03866          # error path
03867       ...
03868       """
03869       bytes = PI_CMD_INTERRUPTED
03870       rdata = ""
03871       with self.sl.l:
03872          bytes = u2i(_pigpio_command_nolock(
03873             self.sl, _PI_CMD_SPIR, handle, count))
03874          if bytes > 0:
03875             rdata = self._rxbuf(bytes)
03876       return bytes, rdata
03877 
03878    def spi_write(self, handle, data):
03879       """
03880       Writes the data bytes to the SPI device associated with handle.
03881 
03882       handle:= >=0 (as returned by a prior call to [*spi_open*]).
03883         data:= the bytes to write.
03884 
03885       ...
03886       pi.spi_write(0, b'\\x02\\xc0\\x80') # write 3 bytes to device 0
03887 
03888       pi.spi_write(0, b'defgh')        # write 5 bytes to device 0
03889 
03890       pi.spi_write(0, "def")           # write 3 bytes to device 0
03891 
03892       pi.spi_write(1, [2, 192, 128])   # write 3 bytes to device 1
03893       ...
03894       """
03895       # I p1 handle
03896       # I p2 0
03897       # I p3 len
03898       ## extension ##
03899       # s len data bytes
03900       return _u2i(_pigpio_command_ext(
03901          self.sl, _PI_CMD_SPIW, handle, 0, len(data), [data]))
03902 
03903    def spi_xfer(self, handle, data):
03904       """
03905       Writes the data bytes to the SPI device associated with handle,
03906       returning the data bytes read from the device.
03907 
03908       handle:= >=0 (as returned by a prior call to [*spi_open*]).
03909         data:= the bytes to write.
03910 
03911       The returned value is a tuple of the number of bytes read and a
03912       bytearray containing the bytes.  If there was an error the
03913       number of bytes read will be less than zero (and will contain
03914       the error code).
03915 
03916       ...
03917       (count, rx_data) = pi.spi_xfer(h, b'\\x01\\x80\\x00')
03918 
03919       (count, rx_data) = pi.spi_xfer(h, [1, 128, 0])
03920 
03921       (count, rx_data) = pi.spi_xfer(h, b"hello")
03922 
03923       (count, rx_data) = pi.spi_xfer(h, "hello")
03924       ...
03925       """
03926       # I p1 handle
03927       # I p2 0
03928       # I p3 len
03929       ## extension ##
03930       # s len data bytes
03931 
03932       bytes = PI_CMD_INTERRUPTED
03933       rdata = ""
03934       with self.sl.l:
03935          bytes = u2i(_pigpio_command_ext_nolock(
03936             self.sl, _PI_CMD_SPIX, handle, 0, len(data), [data]))
03937          if bytes > 0:
03938             rdata = self._rxbuf(bytes)
03939       return bytes, rdata
03940 
03941    def serial_open(self, tty, baud, ser_flags=0):
03942       """
03943       Returns a handle for the serial tty device opened
03944       at baud bits per second.  The device name must start
03945       with /dev/tty or /dev/serial.
03946 
03947             tty:= the serial device to open.
03948            baud:= baud rate in bits per second, see below.
03949       ser_flags:= 0, no flags are currently defined.
03950 
03951       Normally you would only use the [*serial_**] functions if
03952       you are or will be connecting to the Pi over a network.  If
03953       you will always run on the local Pi use the standard serial
03954       module instead.
03955 
03956       The baud rate must be one of 50, 75, 110, 134, 150,
03957       200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200,
03958       38400, 57600, 115200, or 230400.
03959 
03960       ...
03961       h1 = pi.serial_open("/dev/ttyAMA0", 300)
03962 
03963       h2 = pi.serial_open("/dev/ttyUSB1", 19200, 0)
03964 
03965       h3 = pi.serial_open("/dev/serial0", 9600)
03966       ...
03967       """
03968       # I p1 baud
03969       # I p2 ser_flags
03970       # I p3 len
03971       ## extension ##
03972       # s len data bytes
03973       return _u2i(_pigpio_command_ext(
03974          self.sl, _PI_CMD_SERO, baud, ser_flags, len(tty), [tty]))
03975 
03976    def serial_close(self, handle):
03977       """
03978       Closes the serial device associated with handle.
03979 
03980       handle:= >=0 (as returned by a prior call to [*serial_open*]).
03981 
03982       ...
03983       pi.serial_close(h1)
03984       ...
03985       """
03986       return _u2i(_pigpio_command(self.sl, _PI_CMD_SERC, handle, 0))
03987 
03988    def serial_read_byte(self, handle):
03989       """
03990       Returns a single byte from the device associated with handle.
03991 
03992       handle:= >=0 (as returned by a prior call to [*serial_open*]).
03993 
03994       If no data is ready a negative error code will be returned.
03995 
03996       ...
03997       b = pi.serial_read_byte(h1)
03998       ...
03999       """
04000       return _u2i(_pigpio_command(self.sl, _PI_CMD_SERRB, handle, 0))
04001 
04002    def serial_write_byte(self, handle, byte_val):
04003       """
04004       Writes a single byte to the device associated with handle.
04005 
04006         handle:= >=0 (as returned by a prior call to [*serial_open*]).
04007       byte_val:= 0-255, the value to write.
04008 
04009       ...
04010       pi.serial_write_byte(h1, 23)
04011 
04012       pi.serial_write_byte(h1, ord('Z'))
04013       ...
04014       """
04015       return _u2i(
04016          _pigpio_command(self.sl, _PI_CMD_SERWB, handle, byte_val))
04017 
04018    def serial_read(self, handle, count=1000):
04019       """
04020       Reads up to count bytes from the device associated with handle.
04021 
04022       handle:= >=0 (as returned by a prior call to [*serial_open*]).
04023        count:= >0, the number of bytes to read (defaults to 1000).
04024 
04025       The returned value is a tuple of the number of bytes read and
04026       a bytearray containing the bytes.  If there was an error the
04027       number of bytes read will be less than zero (and will contain
04028       the error code).
04029 
04030       If no data is ready a bytes read of zero is returned.
04031       ...
04032       (b, d) = pi.serial_read(h2, 100)
04033       if b > 0:
04034          # process read data
04035       ...
04036       """
04037       bytes = PI_CMD_INTERRUPTED
04038       rdata = ""
04039       with self.sl.l:
04040          bytes = u2i(
04041             _pigpio_command_nolock(self.sl, _PI_CMD_SERR, handle, count))
04042          if bytes > 0:
04043             rdata = self._rxbuf(bytes)
04044       return bytes, rdata
04045 
04046    def serial_write(self, handle, data):
04047       """
04048       Writes the data bytes to the device associated with handle.
04049 
04050       handle:= >=0 (as returned by a prior call to [*serial_open*]).
04051         data:= the bytes to write.
04052 
04053       ...
04054       pi.serial_write(h1, b'\\x02\\x03\\x04')
04055 
04056       pi.serial_write(h2, b'help')
04057 
04058       pi.serial_write(h2, "hello")
04059 
04060       pi.serial_write(h1, [2, 3, 4])
04061       ...
04062       """
04063       # I p1 handle
04064       # I p2 0
04065       # I p3 len
04066       ## extension ##
04067       # s len data bytes
04068 
04069       return _u2i(_pigpio_command_ext(
04070          self.sl, _PI_CMD_SERW, handle, 0, len(data), [data]))
04071 
04072    def serial_data_available(self, handle):
04073       """
04074       Returns the number of bytes available to be read from the
04075       device associated with handle.
04076 
04077       handle:= >=0 (as returned by a prior call to [*serial_open*]).
04078 
04079       ...
04080       rdy = pi.serial_data_available(h1)
04081 
04082       if rdy > 0:
04083          (b, d) = pi.serial_read(h1, rdy)
04084       ...
04085       """
04086       return _u2i(_pigpio_command(self.sl, _PI_CMD_SERDA, handle, 0))
04087 
04088    def gpio_trigger(self, user_gpio, pulse_len=10, level=1):
04089       """
04090       Send a trigger pulse to a GPIO.  The GPIO is set to
04091       level for pulse_len microseconds and then reset to not level.
04092 
04093       user_gpio:= 0-31
04094       pulse_len:= 1-100
04095           level:= 0-1
04096 
04097       ...
04098       pi.gpio_trigger(23, 10, 1)
04099       ...
04100       """
04101       # pigpio message format
04102 
04103       # I p1 user_gpio
04104       # I p2 pulse_len
04105       # I p3 4
04106       ## extension ##
04107       # I level
04108       extents = [struct.pack("I", level)]
04109       return _u2i(_pigpio_command_ext(
04110          self.sl, _PI_CMD_TRIG, user_gpio, pulse_len, 4, extents))
04111 
04112    def set_glitch_filter(self, user_gpio, steady):
04113       """
04114       Sets a glitch filter on a GPIO.
04115 
04116       Level changes on the GPIO are not reported unless the level
04117       has been stable for at least [*steady*] microseconds.  The
04118       level is then reported.  Level changes of less than [*steady*]
04119       microseconds are ignored.
04120 
04121       user_gpio:= 0-31
04122          steady:= 0-300000
04123 
04124       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
04125 
04126       This filter affects the GPIO samples returned to callbacks set up
04127       with [*callback*] and [*wait_for_edge*].
04128 
04129       It does not affect levels read by [*read*],
04130       [*read_bank_1*], or [*read_bank_2*].
04131 
04132       Each (stable) edge will be timestamped [*steady*]
04133       microseconds after it was first detected.
04134 
04135       ...
04136       pi.set_glitch_filter(23, 100)
04137       ...
04138       """
04139       return _u2i(_pigpio_command(self.sl, _PI_CMD_FG, user_gpio, steady))
04140 
04141    def set_noise_filter(self, user_gpio, steady, active):
04142       """
04143       Sets a noise filter on a GPIO.
04144 
04145       Level changes on the GPIO are ignored until a level which has
04146       been stable for [*steady*] microseconds is detected.  Level
04147       changes on the GPIO are then reported for [*active*]
04148       microseconds after which the process repeats.
04149 
04150       user_gpio:= 0-31
04151          steady:= 0-300000
04152          active:= 0-1000000
04153 
04154       Returns 0 if OK, otherwise PI_BAD_USER_GPIO, or PI_BAD_FILTER.
04155 
04156       This filter affects the GPIO samples returned to callbacks set up
04157       with [*callback*] and [*wait_for_edge*].
04158 
04159       It does not affect levels read by [*read*],
04160       [*read_bank_1*], or [*read_bank_2*].
04161 
04162       Level changes before and after the active period may
04163       be reported.  Your software must be designed to cope with
04164       such reports.
04165 
04166       ...
04167       pi.set_noise_filter(23, 1000, 5000)
04168       ...
04169       """
04170       # pigpio message format
04171 
04172       # I p1 user_gpio
04173       # I p2 steady
04174       # I p3 4
04175       ## extension ##
04176       # I active
04177       extents = [struct.pack("I", active)]
04178       return _u2i(_pigpio_command_ext(
04179          self.sl, _PI_CMD_FN, user_gpio, steady, 4, extents))
04180 
04181    def store_script(self, script):
04182       """
04183       Store a script for later execution.
04184 
04185       See [[http://abyz.me.uk/rpi/pigpio/pigs.html#Scripts]] for
04186       details.
04187 
04188       script:= the script text as a series of bytes.
04189 
04190       Returns a >=0 script id if OK.
04191 
04192       ...
04193       sid = pi.store_script(
04194          b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
04195       ...
04196       """
04197       # I p1 0
04198       # I p2 0
04199       # I p3 len
04200       ## extension ##
04201       # s len data bytes
04202       if len(script):
04203          return _u2i(_pigpio_command_ext(
04204             self.sl, _PI_CMD_PROC, 0, 0, len(script), [script]))
04205       else:
04206          return 0
04207 
04208    def run_script(self, script_id, params=None):
04209       """
04210       Runs a stored script.
04211 
04212       script_id:= id of stored script.
04213          params:= up to 10 parameters required by the script.
04214 
04215       ...
04216       s = pi.run_script(sid, [par1, par2])
04217 
04218       s = pi.run_script(sid)
04219 
04220       s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
04221       ...
04222       """
04223       # I p1 script id
04224       # I p2 0
04225       # I p3 params * 4 (0-10 params)
04226       ## (optional) extension ##
04227       # I[] params
04228       if params is not None:
04229          ext = bytearray()
04230          for p in params:
04231             ext.extend(struct.pack("I", p))
04232          nump = len(params)
04233          extents = [ext]
04234       else:
04235          nump = 0
04236          extents = []
04237       return _u2i(_pigpio_command_ext(
04238          self.sl, _PI_CMD_PROCR, script_id, 0, nump*4, extents))
04239 
04240    def update_script(self, script_id, params=None):
04241       """
04242       Sets the parameters of a script.  The script may or
04243       may not be running.  The first parameters of the script are
04244       overwritten with the new values.
04245 
04246       script_id:= id of stored script.
04247          params:= up to 10 parameters required by the script.
04248 
04249       ...
04250       s = pi.update_script(sid, [par1, par2])
04251 
04252       s = pi.update_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
04253       ...
04254       """
04255       # I p1 script id
04256       # I p2 0
04257       # I p3 params * 4 (0-10 params)
04258       ## (optional) extension ##
04259       # I[] params
04260       if params is not None:
04261          ext = bytearray()
04262          for p in params:
04263             ext.extend(struct.pack("I", p))
04264          nump = len(params)
04265          extents = [ext]
04266       else:
04267          nump = 0
04268          extents = []
04269       return _u2i(_pigpio_command_ext(
04270          self.sl, _PI_CMD_PROCU, script_id, 0, nump*4, extents))
04271 
04272    def script_status(self, script_id):
04273       """
04274       Returns the run status of a stored script as well as the
04275       current values of parameters 0 to 9.
04276 
04277       script_id:= id of stored script.
04278 
04279       The run status may be
04280 
04281       . .
04282       PI_SCRIPT_INITING
04283       PI_SCRIPT_HALTED
04284       PI_SCRIPT_RUNNING
04285       PI_SCRIPT_WAITING
04286       PI_SCRIPT_FAILED
04287       . .
04288 
04289       The return value is a tuple of run status and a list of
04290       the 10 parameters.  On error the run status will be negative
04291       and the parameter list will be empty.
04292 
04293       ...
04294       (s, pars) = pi.script_status(sid)
04295       ...
04296       """
04297       status = PI_CMD_INTERRUPTED
04298       params = ()
04299       with self.sl.l:
04300          bytes = u2i(
04301             _pigpio_command_nolock(self.sl, _PI_CMD_PROCP, script_id, 0))
04302          if bytes > 0:
04303             data = self._rxbuf(bytes)
04304             pars = struct.unpack('11i', _str(data))
04305             status = pars[0]
04306             params = pars[1:]
04307          else:
04308             status = bytes
04309       return status, params
04310 
04311    def stop_script(self, script_id):
04312       """
04313       Stops a running script.
04314 
04315       script_id:= id of stored script.
04316 
04317       ...
04318       status = pi.stop_script(sid)
04319       ...
04320       """
04321       return _u2i(_pigpio_command(self.sl, _PI_CMD_PROCS, script_id, 0))
04322 
04323    def delete_script(self, script_id):
04324       """
04325       Deletes a stored script.
04326 
04327       script_id:= id of stored script.
04328 
04329       ...
04330       status = pi.delete_script(sid)
04331       ...
04332       """
04333       return _u2i(_pigpio_command(self.sl, _PI_CMD_PROCD, script_id, 0))
04334 
04335    def bb_serial_read_open(self, user_gpio, baud, bb_bits=8):
04336       """
04337       Opens a GPIO for bit bang reading of serial data.
04338 
04339       user_gpio:= 0-31, the GPIO to use.
04340            baud:= 50-250000, the baud rate.
04341         bb_bits:= 1-32, the number of bits per word, default 8.
04342 
04343       The serial data is held in a cyclic buffer and is read using
04344       [*bb_serial_read*].
04345 
04346       It is the caller's responsibility to read data from the cyclic
04347       buffer in a timely fashion.
04348 
04349       ...
04350       status = pi.bb_serial_read_open(4, 19200)
04351       status = pi.bb_serial_read_open(17, 9600)
04352       ...
04353       """
04354       # pigpio message format
04355 
04356       # I p1 user_gpio
04357       # I p2 baud
04358       # I p3 4
04359       ## extension ##
04360       # I bb_bits
04361       extents = [struct.pack("I", bb_bits)]
04362       return _u2i(_pigpio_command_ext(
04363          self.sl, _PI_CMD_SLRO, user_gpio, baud, 4, extents))
04364 
04365    def bb_serial_read(self, user_gpio):
04366       """
04367       Returns data from the bit bang serial cyclic buffer.
04368 
04369       user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
04370 
04371       The returned value is a tuple of the number of bytes read and a
04372       bytearray containing the bytes.  If there was an error the
04373       number of bytes read will be less than zero (and will contain
04374       the error code).
04375 
04376       The bytes returned for each character depend upon the number of
04377       data bits [*bb_bits*] specified in the [*bb_serial_read_open*]
04378       command.
04379 
04380       For [*bb_bits*] 1-8 there will be one byte per character. 
04381       For [*bb_bits*] 9-16 there will be two bytes per character. 
04382       For [*bb_bits*] 17-32 there will be four bytes per character.
04383 
04384       ...
04385       (count, data) = pi.bb_serial_read(4)
04386       ...
04387       """
04388       bytes = PI_CMD_INTERRUPTED
04389       rdata = ""
04390       with self.sl.l:
04391           bytes = u2i(
04392              _pigpio_command_nolock(self.sl, _PI_CMD_SLR, user_gpio, 10000))
04393           if bytes > 0:
04394              rdata = self._rxbuf(bytes)
04395       return bytes, rdata
04396 
04397    
04398    def bb_serial_read_close(self, user_gpio):
04399       """
04400       Closes a GPIO for bit bang reading of serial data.
04401 
04402       user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
04403 
04404       ...
04405       status = pi.bb_serial_read_close(17)
04406       ...
04407       """
04408       return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRC, user_gpio, 0))
04409 
04410    def bb_serial_invert(self, user_gpio, invert):
04411       """
04412       Invert serial logic.
04413 
04414       user_gpio:= 0-31 (opened in a prior call to [*bb_serial_read_open*])
04415           invert:= 0-1 (1 invert, 0 normal)
04416 
04417       ...
04418       status = pi.bb_serial_invert(17, 1)
04419       ...
04420       """
04421       return _u2i(_pigpio_command(self.sl, _PI_CMD_SLRI, user_gpio, invert))
04422 
04423 
04424    def custom_1(self, arg1=0, arg2=0, argx=[]):
04425       """
04426       Calls a pigpio function customised by the user.
04427 
04428       arg1:= >=0, default 0.
04429       arg2:= >=0, default 0.
04430       argx:= extra arguments (each 0-255), default empty.
04431 
04432       The returned value is an integer which by convention
04433       should be >=0 for OK and <0 for error.
04434 
04435       ...
04436       value = pi.custom_1()
04437 
04438       value = pi.custom_1(23)
04439 
04440       value = pi.custom_1(0, 55)
04441 
04442       value = pi.custom_1(23, 56, [1, 5, 7])
04443 
04444       value = pi.custom_1(23, 56, b"hello")
04445 
04446       value = pi.custom_1(23, 56, "hello")
04447       ...
04448       """
04449       # I p1 arg1
04450       # I p2 arg2
04451       # I p3 len
04452       ## extension ##
04453       # s len argx bytes
04454 
04455       return u2i(_pigpio_command_ext(
04456          self.sl, _PI_CMD_CF1, arg1, arg2, len(argx), [argx]))
04457 
04458    def custom_2(self, arg1=0, argx=[], retMax=8192):
04459       """
04460       Calls a pigpio function customised by the user.
04461 
04462         arg1:= >=0, default 0.
04463         argx:= extra arguments (each 0-255), default empty.
04464       retMax:= >=0, maximum number of bytes to return, default 8192.
04465 
04466       The returned value is a tuple of the number of bytes
04467       returned and a bytearray containing the bytes.  If
04468       there was an error the number of bytes read will be
04469       less than zero (and will contain the error code).
04470 
04471       ...
04472       (count, data) = pi.custom_2()
04473 
04474       (count, data) = pi.custom_2(23)
04475 
04476       (count, data) = pi.custom_2(23, [1, 5, 7])
04477 
04478       (count, data) = pi.custom_2(23, b"hello")
04479 
04480       (count, data) = pi.custom_2(23, "hello", 128)
04481       ...
04482       """
04483       # I p1 arg1
04484       # I p2 retMax
04485       # I p3 len
04486       ## extension ##
04487       # s len argx bytes
04488 
04489       bytes = PI_CMD_INTERRUPTED
04490       rdata = ""
04491       with self.sl.l:
04492          bytes = u2i(_pigpio_command_ext_nolock(
04493             self.sl, _PI_CMD_CF2, arg1, retMax, len(argx), [argx]))
04494          if bytes > 0:
04495             rdata = self._rxbuf(bytes)
04496       return bytes, rdata
04497 
04498    def get_pad_strength(self, pad):
04499       """
04500       This function returns the pad drive strength in mA.
04501 
04502       pad:= 0-2, the pad to get.
04503 
04504       Returns the pad drive strength if OK, otherwise PI_BAD_PAD.
04505 
04506       Pad @ GPIO
04507       0   @ 0-27
04508       1   @ 28-45
04509       2   @ 46-53
04510 
04511       ...
04512       strength = pi.get_pad_strength(0) # Get pad 0 strength.
04513       ...
04514       """
04515       return _u2i(_pigpio_command(self.sl, _PI_CMD_PADG, pad, 0))
04516 
04517    def set_pad_strength(self, pad, pad_strength):
04518       """
04519       This function sets the pad drive strength in mA.
04520 
04521 
04522                pad:= 0-2, the pad to set.
04523       pad_strength:= 1-16 mA.
04524 
04525       Returns 0 if OK, otherwise PI_BAD_PAD, or PI_BAD_STRENGTH.
04526 
04527       Pad @ GPIO
04528       0   @ 0-27
04529       1   @ 28-45
04530       2   @ 46-53
04531 
04532       ...
04533       pi.set_pad_strength(2, 14) # Set pad 2 to 14 mA.
04534       ...
04535       """
04536       return _u2i(_pigpio_command(self.sl, _PI_CMD_PADS, pad, pad_strength))
04537 
04538 
04539    def file_open(self, file_name, file_mode):
04540       """
04541       This function returns a handle to a file opened in a specified mode.
04542 
04543       file_name:= the file to open.
04544       file_mode:= the file open mode.
04545 
04546       Returns a handle (>=0) if OK, otherwise PI_NO_HANDLE,
04547       PI_NO_FILE_ACCESS, PI_BAD_FILE_MODE,
04548       PI_FILE_OPEN_FAILED, or PI_FILE_IS_A_DIR.
04549 
04550       ...
04551       h = pi.file_open("/home/pi/shared/dir_3/file.txt",
04552               pigpio.FILE_WRITE | pigpio.FILE_CREATE)
04553 
04554       pi.file_write(h, "Hello world")
04555 
04556       pi.file_close(h)
04557       ...
04558 
04559       File
04560 
04561       A file may only be opened if permission is granted by an entry
04562       in /opt/pigpio/access.  This is intended to allow remote access
04563       to files in a more or less controlled manner.
04564 
04565       Each entry in /opt/pigpio/access takes the form of a file path
04566       which may contain wildcards followed by a single letter permission.
04567       The permission may be R for read, W for write, U for read/write,
04568       and N for no access.
04569 
04570       Where more than one entry matches a file the most specific rule
04571       applies.  If no entry matches a file then access is denied.
04572 
04573       Suppose /opt/pigpio/access contains the following entries:
04574 
04575       . .
04576       /home/* n
04577       /home/pi/shared/dir_1/* w
04578       /home/pi/shared/dir_2/* r
04579       /home/pi/shared/dir_3/* u
04580       /home/pi/shared/dir_1/file.txt n
04581       . .
04582 
04583       Files may be written in directory dir_1 with the exception
04584       of file.txt.
04585 
04586       Files may be read in directory dir_2.
04587 
04588       Files may be read and written in directory dir_3.
04589 
04590       If a directory allows read, write, or read/write access then files
04591       may be created in that directory.
04592 
04593       In an attempt to prevent risky permissions the following paths are
04594       ignored in /opt/pigpio/access:
04595 
04596       . .
04597       a path containing ..
04598       a path containing only wildcards (*?)
04599       a path containing less than two non-wildcard parts
04600       . .
04601 
04602       Mode
04603 
04604       The mode may have the following values:
04605 
04606       Constant   @ Value @ Meaning
04607       FILE_READ  @   1   @ open file for reading
04608       FILE_WRITE @   2   @ open file for writing
04609       FILE_RW    @   3   @ open file for reading and writing
04610 
04611       The following values may be or'd into the mode:
04612 
04613       Name        @ Value @ Meaning
04614       FILE_APPEND @ 4     @ All writes append data to the end of the file
04615       FILE_CREATE @ 8     @ The file is created if it doesn't exist
04616       FILE_TRUNC  @ 16    @ The file is truncated
04617 
04618       Newly created files are owned by root with permissions owner
04619       read and write.
04620 
04621       ...
04622       #!/usr/bin/env python
04623 
04624       import pigpio
04625 
04626       pi = pigpio.pi()
04627 
04628       if not pi.connected:
04629          exit()
04630 
04631       # Assumes /opt/pigpio/access contains the following line:
04632       # /ram/*.c r
04633 
04634       handle = pi.file_open("/ram/pigpio.c", pigpio.FILE_READ)
04635 
04636       done = False
04637 
04638       while not done:
04639          c, d = pi.file_read(handle, 60000)
04640          if c > 0:
04641             print(d)
04642          else:
04643             done = True
04644 
04645       pi.file_close(handle)
04646 
04647       pi.stop()
04648       ...
04649       """
04650       # I p1 file_mode
04651       # I p2 0
04652       # I p3 len
04653       ## extension ##
04654       # s len data bytes
04655       return _u2i(_pigpio_command_ext(
04656          self.sl, _PI_CMD_FO, file_mode, 0, len(file_name), [file_name]))
04657 
04658    def file_close(self, handle):
04659       """
04660       Closes the file associated with handle.
04661 
04662       handle:= >=0 (as returned by a prior call to [*file_open*]).
04663 
04664       ...
04665       pi.file_close(handle)
04666       ...
04667       """
04668       return _u2i(_pigpio_command(self.sl, _PI_CMD_FC, handle, 0))
04669 
04670    def file_read(self, handle, count):
04671       """
04672       Reads up to count bytes from the file associated with handle.
04673 
04674       handle:= >=0 (as returned by a prior call to [*file_open*]).
04675        count:= >0, the number of bytes to read.
04676 
04677       The returned value is a tuple of the number of bytes read and a
04678       bytearray containing the bytes.  If there was an error the
04679       number of bytes read will be less than zero (and will contain
04680       the error code).
04681 
04682       ...
04683       (b, d) = pi.file_read(h2, 100)
04684       if b > 0:
04685          # process read data
04686       ...
04687       """
04688       bytes = PI_CMD_INTERRUPTED
04689       rdata = ""
04690       with self.sl.l:
04691          bytes = u2i(
04692             _pigpio_command_nolock(self.sl, _PI_CMD_FR, handle, count))
04693          if bytes > 0:
04694             rdata = self._rxbuf(bytes)
04695       return bytes, rdata
04696 
04697    def file_write(self, handle, data):
04698       """
04699       Writes the data bytes to the file associated with handle.
04700 
04701       handle:= >=0 (as returned by a prior call to [*file_open*]).
04702         data:= the bytes to write.
04703 
04704       ...
04705       pi.file_write(h1, b'\\x02\\x03\\x04')
04706 
04707       pi.file_write(h2, b'help')
04708 
04709       pi.file_write(h2, "hello")
04710 
04711       pi.file_write(h1, [2, 3, 4])
04712       ...
04713       """
04714       # I p1 handle
04715       # I p2 0
04716       # I p3 len
04717       ## extension ##
04718       # s len data bytes
04719 
04720       return _u2i(_pigpio_command_ext(
04721          self.sl, _PI_CMD_FW, handle, 0, len(data), [data]))
04722 
04723    def file_seek(self, handle, seek_offset, seek_from):
04724       """
04725       Seeks to a position relative to the start, current position,
04726       or end of the file.  Returns the new position.
04727 
04728            handle:= >=0 (as returned by a prior call to [*file_open*]).
04729       seek_offset:= byte offset.
04730         seek_from:= FROM_START, FROM_CURRENT, or FROM_END.
04731 
04732       ...
04733       new_pos = pi.file_seek(h, 100, pigpio.FROM_START)
04734 
04735       cur_pos = pi.file_seek(h, 0, pigpio.FROM_CURRENT)
04736 
04737       file_size = pi.file_seek(h, 0, pigpio.FROM_END)
04738       ...
04739       """
04740       # I p1 handle
04741       # I p2 seek_offset
04742       # I p3 4
04743       ## extension ##
04744       # I seek_from
04745       extents = [struct.pack("I", seek_from)]
04746       return _u2i(_pigpio_command_ext(
04747          self.sl, _PI_CMD_FS, handle, seek_offset, 4, extents))
04748 
04749    def file_list(self, fpattern):
04750       """
04751       Returns a list of files which match a pattern.
04752 
04753       fpattern:= file pattern to match.
04754 
04755       Returns the number of returned bytes if OK, otherwise
04756       PI_NO_FILE_ACCESS, or PI_NO_FILE_MATCH.
04757 
04758       The pattern must match an entry in /opt/pigpio/access.  The
04759       pattern may contain wildcards.  See [*file_open*].
04760 
04761       NOTE
04762 
04763       The returned value is not the number of files, it is the number
04764       of bytes in the buffer.  The file names are separated by newline
04765       characters.
04766 
04767       ...
04768       #!/usr/bin/env python
04769 
04770       import pigpio
04771 
04772       pi = pigpio.pi()
04773 
04774       if not pi.connected:
04775          exit()
04776 
04777       # Assumes /opt/pigpio/access contains the following line:
04778       # /ram/*.c r
04779 
04780       c, d = pi.file_list("/ram/p*.c")
04781       if c > 0:
04782          print(d)
04783 
04784       pi.stop()
04785       ...
04786       """
04787       # I p1 60000
04788       # I p2 0
04789       # I p3 len
04790       ## extension ##
04791       # s len data bytes
04792 
04793       bytes = PI_CMD_INTERRUPTED
04794       rdata = ""
04795       with self.sl.l:
04796          bytes = u2i(_pigpio_command_ext_nolock(
04797             self.sl, _PI_CMD_FL, 60000, 0, len(fpattern), [fpattern]))
04798          if bytes > 0:
04799             rdata = self._rxbuf(bytes)
04800       return bytes, rdata
04801 
04802    def shell(self, shellscr, pstring=""):
04803       """
04804       This function uses the system call to execute a shell script
04805       with the given string as its parameter.
04806 
04807       shellscr:= the name of the script, only alphanumerics,
04808                     '-' and '_' are allowed in the name
04809       pstring := the parameter string to pass to the script
04810 
04811       The exit status of the system call is returned if OK,
04812       otherwise PI_BAD_SHELL_STATUS.
04813 
04814       [*shellscr*] must exist in /opt/pigpio/cgi and must be executable.
04815 
04816       The returned exit status is normally 256 times that set by
04817       the shell script exit function.  If the script can't be
04818       found 32512 will be returned.
04819 
04820       The following table gives some example returned statuses:
04821 
04822       Script exit status @ Returned system call status
04823       1                  @ 256
04824       5                  @ 1280
04825       10                 @ 2560
04826       200                @ 51200
04827       script not found   @ 32512
04828 
04829       ...
04830       // pass two parameters, hello and world
04831       status = pi.shell("scr1", "hello world");
04832 
04833       // pass three parameters, hello, string with spaces, and world
04834       status = pi.shell("scr1", "hello 'string with spaces' world");
04835 
04836       // pass one parameter, hello string with spaces world
04837       status = pi.shell("scr1", "\\"hello string with spaces world\\"");
04838       ...
04839       """
04840       # I p1 len(shellscr)
04841       # I p2 0
04842       # I p3 len(shellscr)+len(pstring)+1
04843       ## extension ##
04844       # s len data bytes
04845 
04846       ls = len(shellscr)
04847       lp = len(pstring)
04848       return _u2i(_pigpio_command_ext(
04849          self.sl, _PI_CMD_SHELL, ls, 0, ls+lp+1, [shellscr+'\x00'+pstring]))
04850 
04851 
04852    def callback(self, user_gpio, edge=RISING_EDGE, func=None):
04853       """
04854       Calls a user supplied function (a callback) whenever the
04855       specified GPIO edge is detected.
04856 
04857       user_gpio:= 0-31.
04858            edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
04859            func:= user supplied callback function.
04860 
04861       The user supplied callback receives three parameters, the GPIO,
04862       the level, and the tick.
04863 
04864       . .
04865       Parameter   Value    Meaning
04866 
04867       GPIO        0-31     The GPIO which has changed state
04868 
04869       level       0-2      0 = change to low (a falling edge)
04870                            1 = change to high (a rising edge)
04871                            2 = no level change (a watchdog timeout)
04872 
04873       tick        32 bit   The number of microseconds since boot
04874                            WARNING: this wraps around from
04875                            4294967295 to 0 roughly every 72 minutes
04876       . .
04877 
04878       If a user callback is not specified a default tally callback is
04879       provided which simply counts edges.  The count may be retrieved
04880       by calling the tally function.  The count may be reset to zero
04881       by calling the reset_tally function.
04882 
04883       The callback may be cancelled by calling the cancel function.
04884 
04885       A GPIO may have multiple callbacks (although I can't think of
04886       a reason to do so).
04887 
04888       ...
04889       def cbf(gpio, level, tick):
04890          print(gpio, level, tick)
04891 
04892       cb1 = pi.callback(22, pigpio.EITHER_EDGE, cbf)
04893 
04894       cb2 = pi.callback(4, pigpio.EITHER_EDGE)
04895 
04896       cb3 = pi.callback(17)
04897 
04898       print(cb3.tally())
04899 
04900       cb3.reset_tally()
04901 
04902       cb1.cancel() # To cancel callback cb1.
04903       ...
04904       """
04905       return _callback(self._notify, user_gpio, edge, func)
04906 
04907    def event_callback(self, event, func=None):
04908       """
04909       Calls a user supplied function (a callback) whenever the
04910       specified event is signalled.
04911 
04912       event:= 0-31.
04913        func:= user supplied callback function.
04914 
04915       The user supplied callback receives two parameters, the event id,
04916       and the tick.
04917 
04918       If a user callback is not specified a default tally callback is
04919       provided which simply counts events.  The count may be retrieved
04920       by calling the tally function.  The count may be reset to zero
04921       by calling the reset_tally function.
04922 
04923       The callback may be cancelled by calling the event_cancel function.
04924 
04925       An event may have multiple callbacks (although I can't think of
04926       a reason to do so).
04927 
04928       ...
04929       def cbf(event, tick):
04930          print(event, tick)
04931 
04932       cb1 = pi.event_callback(22, cbf)
04933 
04934       cb2 = pi.event_callback(4)
04935 
04936       print(cb2.tally())
04937 
04938       cb2.reset_tally()
04939 
04940       cb1.event_cancel() # To cancel callback cb1.
04941       ...
04942       """
04943 
04944       return _event(self._notify, event, func)
04945 
04946    def wait_for_edge(self, user_gpio, edge=RISING_EDGE, wait_timeout=60.0):
04947       """
04948       Wait for an edge event on a GPIO.
04949 
04950          user_gpio:= 0-31.
04951               edge:= EITHER_EDGE, RISING_EDGE (default), or
04952                      FALLING_EDGE.
04953       wait_timeout:= >=0.0 (default 60.0).
04954 
04955       The function returns when the edge is detected or after
04956       the number of seconds specified by timeout has expired.
04957 
04958       Do not use this function for precise timing purposes,
04959       the edge is only checked 20 times a second. Whenever
04960       you need to know the accurate time of GPIO events use
04961       a [*callback*] function.
04962 
04963       The function returns True if the edge is detected,
04964       otherwise False.
04965 
04966       ...
04967       if pi.wait_for_edge(23):
04968          print("Rising edge detected")
04969       else:
04970          print("wait for edge timed out")
04971 
04972       if pi.wait_for_edge(23, pigpio.FALLING_EDGE, 5.0):
04973          print("Falling edge detected")
04974       else:
04975          print("wait for falling edge timed out")
04976       ...
04977       """
04978       a = _wait_for_edge(self._notify, user_gpio, edge, wait_timeout)
04979       return a.trigger
04980 
04981    def wait_for_event(self, event, wait_timeout=60.0):
04982       """
04983       Wait for an event.
04984 
04985              event:= 0-31.
04986       wait_timeout:= >=0.0 (default 60.0).
04987 
04988       The function returns when the event is signalled or after
04989       the number of seconds specified by timeout has expired.
04990 
04991       The function returns True if the event is detected,
04992       otherwise False.
04993 
04994       ...
04995       if pi.wait_for_event(23):
04996          print("event detected")
04997       else:
04998          print("wait for event timed out")
04999       ...
05000       """
05001       a = _wait_for_event(self._notify, event, wait_timeout)
05002       return a.trigger
05003 
05004    def __init__(self,
05005                 host = os.getenv("PIGPIO_ADDR", 'localhost'),
05006                 port = os.getenv("PIGPIO_PORT", 8888),
05007                 show_errors = True):
05008       """
05009       Grants access to a Pi's GPIO.
05010 
05011       host:= the host name of the Pi on which the pigpio daemon is
05012              running.  The default is localhost unless overridden by
05013              the PIGPIO_ADDR environment variable.
05014        
05015       port:= the port number on which the pigpio daemon is listening.
05016              The default is 8888 unless overridden by the PIGPIO_PORT
05017              environment variable.  The pigpio daemon must have been
05018              started with the same port number.
05019 
05020       This connects to the pigpio daemon and reserves resources
05021       to be used for sending commands and receiving notifications.
05022 
05023       An instance attribute [*connected*] may be used to check the
05024       success of the connection.  If the connection is established
05025       successfully [*connected*] will be True, otherwise False.
05026 
05027       ...
05028       pi = pigio.pi()              # use defaults
05029       pi = pigpio.pi('mypi')       # specify host, default port
05030       pi = pigpio.pi('mypi', 7777) # specify host and port
05031 
05032       pi = pigpio.pi()             # exit script if no connection
05033       if not pi.connected:
05034          exit()
05035       ...
05036       """
05037       self.connected = True
05038 
05039       self.sl = _socklock()
05040       self._notify  = None
05041 
05042       port = int(port)
05043 
05044       if host == '':
05045          host = "localhost"
05046 
05047       self._host = host
05048       self._port = port
05049 
05050       try:
05051          self.sl.s = socket.create_connection((host, port), None)
05052 
05053          # Disable the Nagle algorithm.
05054          self.sl.s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
05055 
05056          self._notify = _callback_thread(self.sl, host, port)
05057 
05058       except socket.error:
05059          exception = 1
05060 
05061       except struct.error:
05062          exception = 2
05063 
05064       except error:
05065          # assumed to be no handle available
05066          exception = 3
05067 
05068       else:
05069          exception = 0
05070          atexit.register(self.stop)
05071 
05072       if exception != 0:
05073 
05074          self.connected = False
05075 
05076          if self.sl.s is not None:
05077             self.sl.s = None
05078 
05079          if show_errors:
05080 
05081             s = "Can't connect to pigpio at {}({})".format(host, str(port))
05082 
05083          
05084             print(_except_a.format(s))
05085             if exception == 1:
05086                 print(_except_1)
05087             elif exception == 2:
05088                 print(_except_2)
05089             else:
05090                 print(_except_3)
05091             print(_except_z)
05092 
05093    def stop(self):
05094       """Release pigpio resources.
05095 
05096       ...
05097       pi.stop()
05098       ...
05099       """
05100 
05101       self.connected = False
05102 
05103       if self._notify is not None:
05104          self._notify.stop()
05105          self._notify = None
05106 
05107       if self.sl.s is not None:
05108          self.sl.s.close()
05109          self.sl.s = None
05110 
05111 def xref():
05112    """
05113    active: 0-1000000
05114    The number of microseconds level changes are reported for once
05115    a noise filter has been triggered (by [*steady*] microseconds of
05116    a stable level).
05117 
05118 
05119    arg1:
05120    An unsigned argument passed to a user customised function.  Its
05121    meaning is defined by the customiser.
05122 
05123    arg2:
05124    An unsigned argument passed to a user customised function.  Its
05125    meaning is defined by the customiser.
05126 
05127    argx:
05128    An array of bytes passed to a user customised function.
05129    Its meaning and content is defined by the customiser.
05130 
05131    baud:
05132    The speed of serial communication (I2C, SPI, serial link, waves)
05133    in bits per second.
05134 
05135    bb_bits: 1-32
05136    The number of data bits to be used when adding serial data to a
05137    waveform.
05138 
05139    bb_stop: 2-8
05140    The number of (half) stop bits to be used when adding serial data
05141    to a waveform.
05142 
05143    bit: 0-1
05144    A value of 0 or 1.
05145 
05146    bits: 32 bit number
05147    A mask used to select GPIO to be operated on.  If bit n is set
05148    then GPIO n is selected.  A convenient way of setting bit n is to
05149    bit or in the value (1<<n).
05150 
05151    To select GPIO 1, 7, 23
05152 
05153    bits = (1<<1) | (1<<7) | (1<<23)
05154 
05155    bsc_control:
05156 
05157    . .
05158    22 21 20 19 18 17 16 15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
05159     a  a  a  a  a  a  a  -  - IT HC TF IR RE TE BK EC ES PL PH I2 SP EN
05160    . .
05161 
05162    aaaaaaa defines the I2C slave address (only relevant in I2C mode)
05163 
05164    Bits 0-13 are copied unchanged to the BSC CR register.  See
05165    pages 163-165 of the Broadcom peripherals document.
05166 
05167    byte_val: 0-255
05168    A whole number.
05169 
05170    clkfreq: 4689-250M
05171    The hardware clock frequency.
05172 
05173    connected:
05174    True if a connection was established, False otherwise.
05175 
05176    count:
05177    The number of bytes of data to be transferred.
05178 
05179    CS:
05180    The GPIO used for the slave select signal when bit banging SPI.
05181 
05182    data:
05183    Data to be transmitted, a series of bytes.
05184 
05185    delay: >=1
05186    The length of a pulse in microseconds.
05187 
05188    dutycycle: 0-range_
05189    A number between 0 and range_.
05190 
05191    The dutycycle sets the proportion of time on versus time off during each
05192    PWM cycle.
05193 
05194    Dutycycle     @ On time
05195    0             @ Off
05196    range_ * 0.25 @ 25% On
05197    range_ * 0.50 @ 50% On
05198    range_ * 0.75 @ 75% On
05199    range_        @ Fully On
05200 
05201    edge: 0-2
05202 
05203    . .
05204    EITHER_EDGE = 2 
05205    FALLING_EDGE = 1 
05206    RISING_EDGE = 0
05207    . .
05208 
05209    errnum: <0
05210 
05211    . .
05212    PI_BAD_USER_GPIO = -2
05213    PI_BAD_GPIO = -3
05214    PI_BAD_MODE = -4
05215    PI_BAD_LEVEL = -5
05216    PI_BAD_PUD = -6
05217    PI_BAD_PULSEWIDTH = -7
05218    PI_BAD_DUTYCYCLE = -8
05219    PI_BAD_WDOG_TIMEOUT = -15
05220    PI_BAD_DUTYRANGE = -21
05221    PI_NO_HANDLE = -24
05222    PI_BAD_HANDLE = -25
05223    PI_BAD_WAVE_BAUD = -35
05224    PI_TOO_MANY_PULSES = -36
05225    PI_TOO_MANY_CHARS = -37
05226    PI_NOT_SERIAL_GPIO = -38
05227    PI_NOT_PERMITTED = -41
05228    PI_SOME_PERMITTED = -42
05229    PI_BAD_WVSC_COMMND = -43
05230    PI_BAD_WVSM_COMMND = -44
05231    PI_BAD_WVSP_COMMND = -45
05232    PI_BAD_PULSELEN = -46
05233    PI_BAD_SCRIPT = -47
05234    PI_BAD_SCRIPT_ID = -48
05235    PI_BAD_SER_OFFSET = -49
05236    PI_GPIO_IN_USE = -50
05237    PI_BAD_SERIAL_COUNT = -51
05238    PI_BAD_PARAM_NUM = -52
05239    PI_DUP_TAG = -53
05240    PI_TOO_MANY_TAGS = -54
05241    PI_BAD_SCRIPT_CMD = -55
05242    PI_BAD_VAR_NUM = -56
05243    PI_NO_SCRIPT_ROOM = -57
05244    PI_NO_MEMORY = -58
05245    PI_SOCK_READ_FAILED = -59
05246    PI_SOCK_WRIT_FAILED = -60
05247    PI_TOO_MANY_PARAM = -61
05248    PI_SCRIPT_NOT_READY = -62
05249    PI_BAD_TAG = -63
05250    PI_BAD_MICS_DELAY = -64
05251    PI_BAD_MILS_DELAY = -65
05252    PI_BAD_WAVE_ID = -66
05253    PI_TOO_MANY_CBS = -67
05254    PI_TOO_MANY_OOL = -68
05255    PI_EMPTY_WAVEFORM = -69
05256    PI_NO_WAVEFORM_ID = -70
05257    PI_I2C_OPEN_FAILED = -71
05258    PI_SER_OPEN_FAILED = -72
05259    PI_SPI_OPEN_FAILED = -73
05260    PI_BAD_I2C_BUS = -74
05261    PI_BAD_I2C_ADDR = -75
05262    PI_BAD_SPI_CHANNEL = -76
05263    PI_BAD_FLAGS = -77
05264    PI_BAD_SPI_SPEED = -78
05265    PI_BAD_SER_DEVICE = -79
05266    PI_BAD_SER_SPEED = -80
05267    PI_BAD_PARAM = -81
05268    PI_I2C_WRITE_FAILED = -82
05269    PI_I2C_READ_FAILED = -83
05270    PI_BAD_SPI_COUNT = -84
05271    PI_SER_WRITE_FAILED = -85
05272    PI_SER_READ_FAILED = -86
05273    PI_SER_READ_NO_DATA = -87
05274    PI_UNKNOWN_COMMAND = -88
05275    PI_SPI_XFER_FAILED = -89
05276    PI_NO_AUX_SPI = -91
05277    PI_NOT_PWM_GPIO = -92
05278    PI_NOT_SERVO_GPIO = -93
05279    PI_NOT_HCLK_GPIO = -94
05280    PI_NOT_HPWM_GPIO = -95
05281    PI_BAD_HPWM_FREQ = -96
05282    PI_BAD_HPWM_DUTY = -97
05283    PI_BAD_HCLK_FREQ = -98
05284    PI_BAD_HCLK_PASS = -99
05285    PI_HPWM_ILLEGAL = -100
05286    PI_BAD_DATABITS = -101
05287    PI_BAD_STOPBITS = -102
05288    PI_MSG_TOOBIG = -103
05289    PI_BAD_MALLOC_MODE = -104
05290    PI_BAD_SMBUS_CMD = -107
05291    PI_NOT_I2C_GPIO = -108
05292    PI_BAD_I2C_WLEN = -109
05293    PI_BAD_I2C_RLEN = -110
05294    PI_BAD_I2C_CMD = -111
05295    PI_BAD_I2C_BAUD = -112
05296    PI_CHAIN_LOOP_CNT = -113
05297    PI_BAD_CHAIN_LOOP = -114
05298    PI_CHAIN_COUNTER = -115
05299    PI_BAD_CHAIN_CMD = -116
05300    PI_BAD_CHAIN_DELAY = -117
05301    PI_CHAIN_NESTING = -118
05302    PI_CHAIN_TOO_BIG = -119
05303    PI_DEPRECATED = -120
05304    PI_BAD_SER_INVERT = -121
05305    PI_BAD_FOREVER = -124
05306    PI_BAD_FILTER = -125
05307    PI_BAD_PAD = -126
05308    PI_BAD_STRENGTH = -127
05309    PI_FIL_OPEN_FAILED = -128
05310    PI_BAD_FILE_MODE = -129
05311    PI_BAD_FILE_FLAG = -130
05312    PI_BAD_FILE_READ = -131
05313    PI_BAD_FILE_WRITE = -132
05314    PI_FILE_NOT_ROPEN = -133
05315    PI_FILE_NOT_WOPEN = -134
05316    PI_BAD_FILE_SEEK = -135
05317    PI_NO_FILE_MATCH = -136
05318    PI_NO_FILE_ACCESS = -137
05319    PI_FILE_IS_A_DIR = -138
05320    PI_BAD_SHELL_STATUS = -139
05321    PI_BAD_SCRIPT_NAME = -140
05322    PI_BAD_SPI_BAUD = -141
05323    PI_NOT_SPI_GPIO = -142
05324    PI_BAD_EVENT_ID = -143
05325    PI_CMD_INTERRUPTED = -144
05326    . .
05327 
05328    event:0-31
05329    An event is a signal used to inform one or more consumers
05330    to start an action.
05331 
05332    file_mode:
05333    The mode may have the following values
05334 
05335    . .
05336    FILE_READ   1
05337    FILE_WRITE  2
05338    FILE_RW     3
05339    . .
05340 
05341    The following values can be or'd into the file open mode
05342 
05343    . .
05344    FILE_APPEND 4
05345    FILE_CREATE 8
05346    FILE_TRUNC  16
05347    . .
05348 
05349    file_name:
05350    A full file path.  To be accessible the path must match
05351    an entry in /opt/pigpio/access.
05352 
05353    fpattern:
05354    A file path which may contain wildcards.  To be accessible the path
05355    must match an entry in /opt/pigpio/access.
05356 
05357    frequency: 0-40000
05358    Defines the frequency to be used for PWM on a GPIO.
05359    The closest permitted frequency will be used.
05360 
05361    func:
05362    A user supplied callback function.
05363 
05364    gpio: 0-53
05365    A Broadcom numbered GPIO.  All the user GPIO are in the range 0-31.
05366 
05367    There  are 54 General Purpose Input Outputs (GPIO) named GPIO0
05368    through GPIO53.
05369 
05370    They are split into two  banks.   Bank  1  consists  of  GPIO0
05371    through GPIO31.  Bank 2 consists of GPIO32 through GPIO53.
05372 
05373    All the GPIO which are safe for the user to read and write are in
05374    bank 1.  Not all GPIO in bank 1 are safe though.  Type 1 boards
05375    have 17  safe GPIO.  Type 2 boards have 21.  Type 3 boards have 26.
05376 
05377    See [*get_hardware_revision*].
05378 
05379    The user GPIO are marked with an X in the following table
05380 
05381    . .
05382              0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
05383    Type 1    X  X  -  -  X  -  -  X  X  X  X  X  -  -  X  X
05384    Type 2    -  -  X  X  X  -  -  X  X  X  X  X  -  -  X  X
05385    Type 3          X  X  X  X  X  X  X  X  X  X  X  X  X  X
05386 
05387             16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
05388    Type 1    -  X  X  -  -  X  X  X  X  X  -  -  -  -  -  -
05389    Type 2    -  X  X  -  -  -  X  X  X  X  -  X  X  X  X  X
05390    Type 3    X  X  X  X  X  X  X  X  X  X  X  X  -  -  -  -
05391    . .
05392 
05393    gpio_off:
05394    A mask used to select GPIO to be operated on.  See [*bits*].
05395 
05396    This mask selects the GPIO to be switched off at the start
05397    of a pulse.
05398 
05399    gpio_on:
05400    A mask used to select GPIO to be operated on.  See [*bits*].
05401 
05402    This mask selects the GPIO to be switched on at the start
05403    of a pulse.
05404 
05405    handle: >=0
05406    A number referencing an object opened by one of the following
05407 
05408    [*file_open*] 
05409    [*i2c_open*] 
05410    [*notify_open*] 
05411    [*serial_open*] 
05412    [*spi_open*]
05413 
05414    host:
05415    The name or IP address of the Pi running the pigpio daemon.
05416 
05417    i2c_*:
05418    One of the i2c_ functions.
05419 
05420    i2c_address: 0-0x7F
05421    The address of a device on the I2C bus.
05422 
05423    i2c_bus: >=0
05424    An I2C bus number.
05425 
05426    i2c_flags: 0
05427    No I2C flags are currently defined.
05428 
05429    invert: 0-1
05430    A flag used to set normal or inverted bit bang serial data
05431    level logic.
05432 
05433    level: 0-1 (2)
05434 
05435    . .
05436    CLEAR = 0 
05437    HIGH = 1 
05438    LOW = 0 
05439    OFF = 0 
05440    ON = 1 
05441    SET = 1 
05442    TIMEOUT = 2 # only returned for a watchdog timeout
05443    . .
05444 
05445    MISO:
05446    The GPIO used for the MISO signal when bit banging SPI.
05447 
05448    mode:
05449 
05450    1.The operational mode of a GPIO, normally INPUT or OUTPUT.
05451 
05452    . .
05453    ALT0 = 4 
05454    ALT1 = 5 
05455    ALT2 = 6 
05456    ALT3 = 7 
05457    ALT4 = 3 
05458    ALT5 = 2 
05459    INPUT = 0 
05460    OUTPUT = 1
05461    . .
05462 
05463    2. The mode of waveform transmission.
05464 
05465    . .
05466    WAVE_MODE_ONE_SHOT = 0 
05467    WAVE_MODE_REPEAT = 1 
05468    WAVE_MODE_ONE_SHOT_SYNC = 2 
05469    WAVE_MODE_REPEAT_SYNC = 3
05470    . .
05471 
05472    MOSI:
05473    The GPIO used for the MOSI signal when bit banging SPI.
05474 
05475    offset: >=0
05476    The offset wave data starts from the beginning of the waveform
05477    being currently defined.
05478 
05479    pad: 0-2
05480    A set of GPIO which share common drivers.
05481 
05482    Pad @  GPIO
05483    0   @  0-27
05484    1   @  28-45
05485    2   @  46-53
05486 
05487    pad_strength: 1-16
05488    The mA which may be drawn from each GPIO whilst still guaranteeing the
05489    high and low levels.
05490 
05491    params: 32 bit number
05492    When scripts are started they can receive up to 10 parameters
05493    to define their operation.
05494 
05495    port: 
05496    The port used by the pigpio daemon, defaults to 8888.
05497 
05498    pstring:
05499    The string to be passed to a [*shell*] script to be executed.
05500 
05501    pud: 0-2
05502    . .
05503    PUD_DOWN = 1 
05504    PUD_OFF = 0 
05505    PUD_UP = 2 
05506    . .
05507 
05508    pulse_len: 1-100
05509    The length of the trigger pulse in microseconds.
05510 
05511    pulses:
05512    A list of class pulse objects defining the characteristics of a
05513    waveform.
05514 
05515    pulsewidth:
05516    The servo pulsewidth in microseconds.  0 switches pulses off.
05517 
05518    PWMduty: 0-1000000 (1M)
05519    The hardware PWM dutycycle.
05520 
05521    PWMfreq: 1-125000000 (125M)
05522    The hardware PWM frequency.
05523 
05524    range_: 25-40000
05525    Defines the limits for the [*dutycycle*] parameter.
05526 
05527    range_ defaults to 255.
05528 
05529    reg: 0-255
05530    An I2C device register.  The usable registers depend on the
05531    actual device.
05532 
05533    retMax: >=0
05534    The maximum number of bytes a user customised function
05535    should return, default 8192.
05536 
05537    SCL:
05538    The user GPIO to use for the clock when bit banging I2C.
05539 
05540    SCLK::
05541    The GPIO used for the SCLK signal when bit banging SPI.
05542 
05543    script:
05544    The text of a script to store on the pigpio daemon.
05545 
05546    script_id: >=0
05547    A number referencing a script created by [*store_script*].
05548 
05549    SDA:
05550    The user GPIO to use for data when bit banging I2C.
05551 
05552    seek_from: 0-2
05553    Direction to seek for [*file_seek*].
05554 
05555    . .
05556    FROM_START=0 
05557    FROM_CURRENT=1 
05558    FROM_END=2 
05559    . .
05560 
05561    seek_offset:
05562    The number of bytes to move forward (positive) or backwards
05563    (negative) from the seek position (start, current, or end of file).
05564 
05565    ser_flags: 32 bit
05566    No serial flags are currently defined.
05567 
05568    serial_*:
05569    One of the serial_ functions.
05570 
05571    shellscr:
05572    The name of a shell script.  The script must exist
05573    in /opt/pigpio/cgi and must be executable.
05574 
05575    show_errors:
05576    Controls the display of pigpio daemon connection failures.
05577    The default of True prints the probable failure reasons to
05578    standard output.
05579 
05580    spi_*:
05581    One of the spi_ functions.
05582 
05583    spi_channel: 0-2
05584    A SPI channel.
05585 
05586    spi_flags: 32 bit
05587    See [*spi_open*].
05588 
05589    steady: 0-300000
05590 
05591    The number of microseconds level changes must be stable for
05592    before reporting the level changed ([*set_glitch_filter*])
05593    or triggering the active part of a noise filter
05594    ([*set_noise_filter*]).
05595 
05596    t1:
05597    A tick (earlier).
05598 
05599    t2:
05600    A tick (later).
05601 
05602    tty:
05603    A Pi serial tty device, e.g. /dev/ttyAMA0, /dev/ttyUSB0
05604 
05605    uint32:
05606    An unsigned 32 bit number.
05607 
05608    user_gpio: 0-31
05609    A Broadcom numbered GPIO.
05610 
05611    All the user GPIO are in the range 0-31.
05612 
05613    Not all the GPIO within this range are usable, some are reserved
05614    for system use.
05615 
05616    See [*gpio*].
05617 
05618    wait_timeout: 0.0 -
05619    The number of seconds to wait in [*wait_for_edge*] before timing out.
05620 
05621    wave_add_*:
05622    One of the following
05623 
05624    [*wave_add_new*] 
05625    [*wave_add_generic*] 
05626    [*wave_add_serial*]
05627 
05628    wave_id: >=0
05629    A number referencing a wave created by [*wave_create*].
05630 
05631    wave_send_*:
05632    One of the following
05633 
05634    [*wave_send_once*] 
05635    [*wave_send_repeat*]
05636 
05637    wdog_timeout: 0-60000
05638    Defines a GPIO watchdog timeout in milliseconds.  If no level
05639    change is detected on the GPIO for timeout millisecond a watchdog
05640    timeout report is issued (with level TIMEOUT).
05641 
05642    word_val: 0-65535
05643    A whole number.
05644    """
05645    pass
05646 


cob_hand_bridge
Author(s): Mathias L├╝dtke
autogenerated on Thu Jun 6 2019 20:43:57