summaryrefslogtreecommitdiff
path: root/pigpio.py
blob: 1bb3b960a4a35bdb311023fdf04d2d202db02377 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
"""
pigpio is a Python module for the Raspberry which allows control
of the general purpose input outputs (gpios).

http://abyz.co.uk/rpi/pigpio/python.html

Features

The pigpio module's main features are:

- controlling the gpios of one or more Pi's

- PWM on any of gpios 0-31 simultaneously

- servo pulses on any of gpios 0-31 simultaneously

- callbacks when any of gpios 0-31 change state

- creating and transmitting precisely timed waveforms

- reading/writing gpios and setting their modes

- wrappers for I2C, SPI, and serial links

- creating and running scripts on the pigpio daemon

Notes

Transmitted waveforms are accurate to a microsecond.

Callback level changes are time-stamped and will be
accurate to within a few microseconds.

ALL gpios are identified by their Broadcom number.

This module uses the services of the C pigpio library.  pigpio
must be running on the Pi whose gpios are to be manipulated.

The normal way to start pigpio is as a daemon (during system
start).

sudo pigpiod

Settings

A number of settings are determined when the pigpio daemon is started.

- the sample rate (1, 2, 4, 5, 8, or 10us, default 5us).

- the set of gpios which may be updated (generally written to).  The
  default set is those listed above for the Rev.1 or Rev.2 boards.

- the available PWM frequencies (see set_PWM_frequency).

Exceptions

By default a fatal exception is raised if you pass an invalid
argument to a pigpio function.

If you wish to handle the returned status yourself you should set
pigpio.exceptions to False.

USAGE

Your Python program must import pigpio and create one or more
instances of the pigpio.pi class.  This class gives access to
a specified Pi's gpios.

...
pi1 = pigpio.pi()       # pi1 accesses the local Pi's gpios
pi2 = pigpio.pi('hard') # pi2 accesses hard's gpios
pi3 = pigpio.pi('soft') # pi3 accesses soft's gpios

pi1.write(4, 0) # set local Pi's gpio 4 low
pi2.write(4, 1) # set hard's gpio 4 to high
pi3.read(4)     # get level of soft's gpio 4
...

The later example code snippets assume that pi is an instance of
the pigpio.pi class.

OVERVIEW


Essential

pigpio.pi                 Initialise Pi connection
stop                      Stop a Pi connection

Beginner

set_mode                  Set a gpio mode
get_mode                  Get a gpio mode
set_pull_up_down          Set/clear gpio pull up/down resistor

read                      Read a gpio
write                     Write a gpio

set_PWM_dutycycle         Start/stop PWM pulses on a gpio
set_servo_pulsewidth      Start/Stop servo pulses on a gpio

callback                  Create gpio level change callback
wait_for_edge             Wait for gpio level change

Intermediate

gpio_trigger              Send a trigger pulse to a gpio

set_watchdog              Set a watchdog on a gpio

set_PWM_range             Configure PWM range of a gpio
get_PWM_range             Get configured PWM range of a gpio

set_PWM_frequency         Set PWM frequency of a gpio
get_PWM_frequency         Get PWM frequency of a gpio

read_bank_1               Read all bank 1 gpios
read_bank_2               Read all bank 2 gpios

clear_bank_1              Clear selected gpios in bank 1
clear_bank_2              Clear selected gpios in bank 2

set_bank_1                Set selected gpios in bank 1
set_bank_2                Set selected gpios in bank 2

Advanced

get_PWM_real_range        Get underlying PWM range for a gpio

notify_open               Request a notification handle
notify_begin              Start notifications for selected gpios
notify_pause              Pause notifications
notify_close              Close a notification

bb_serial_read_open       Open a gpio for bit bang serial reads
bb_serial_read            Read bit bang serial data from  a gpio
bb_serial_read_close      Close a gpio for bit bang serial reads

Scripts

store_script              Store a script
run_script                Run a stored script
script_status             Get script status and parameters
stop_script               Stop a running script
delete_script             Delete a stored script

Waves

wave_clear                Deletes all waveforms

wave_add_new              Starts a new waveform
wave_add_generic          Adds a series of pulses to the waveform
wave_add_serial           Adds serial data to the waveform

wave_create               Creates a waveform from added data
wave_delete               Deletes one or more waveforms

wave_send_once            Transmits a waveform once
wave_send_repeat          Transmits a waveform repeatedly
wave_tx_busy              Checks to see if a waveform has ended
wave_tx_stop              Aborts the current waveform

wave_tx_repeat            Creates/transmits a waveform (DEPRECATED)
wave_tx_start             Creates/transmits a waveform (DEPRECATED)

wave_get_micros           Length in microseconds of the current waveform
wave_get_max_micros       Absolute maximum allowed micros
wave_get_pulses           Length in pulses of the current waveform
wave_get_max_pulses       Absolute maximum allowed pulses
wave_get_cbs              Length in cbs of the current waveform
wave_get_max_cbs          Absolute maximum allowed cbs

I2C

i2c_open                  Opens an I2C device
i2c_close                 Closes an I2C device

i2c_read_device           Reads the raw I2C device
i2c_write_device          Writes the raw I2C device

i2c_write_quick           smbus write quick
i2c_write_byte            smbus write byte
i2c_read_byte             smbus read byte
i2c_write_byte_data       smbus write byte data
i2c_write_word_data       smbus write word data
i2c_read_byte_data        smbus read byte data
i2c_read_word_data        smbus read word data
i2c_process_call          smbus process call
i2c_write_block_data      smbus write block data
i2c_read_block_data       smbus read block data
i2c_block_process_call    smbus block process call

i2c_read_i2c_block_data   smbus read I2C block data
i2c_write_i2c_block_data  smbus write I2C block data

SPI

spi_open                  Opens a SPI device
spi_close                 Closes a SPI device

spi_read                  Reads bytes from a SPI device
spi_write                 Writes bytes to a SPI device
spi_xfer                  Transfers bytes with a SPI device

Serial

serial_open               Opens a serial device (/dev/tty*)
serial_close              Closes a serial device

serial_read               Reads bytes from a serial device
serial_read_byte          Reads a byte from a serial device

serial_write              Writes bytes to a serial device
serial_write_byte         Writes a byte to a serial device

serial_data_available     Returns number of bytes ready to be read

Utility

get_current_tick          Get current tick (microseconds)

get_hardware_revision     Get hardware revision
get_pigpio_version        Get the pigpio version

pigpio.error_text         Gets error text from error number
pigpio.tickDiff           Returns difference between two ticks
"""
import sys
import socket
import struct
import time
import threading
import os
import atexit
import codecs

VERSION = "1.6"

exceptions = True

# gpio levels

OFF   = 0
LOW   = 0
CLEAR = 0

ON   = 1
HIGH = 1
SET  = 1

TIMEOUT = 2

# gpio edges

RISING_EDGE  = 0
FALLING_EDGE = 1
EITHER_EDGE  = 2

# gpio modes

INPUT  = 0
OUTPUT = 1
ALT0   = 4
ALT1   = 5
ALT2   = 6
ALT3   = 7
ALT4   = 3
ALT5   = 2

# gpio Pull Up Down

PUD_OFF  = 0
PUD_DOWN = 1
PUD_UP   = 2

# script run status

PI_SCRIPT_HALTED =0
PI_SCRIPT_RUNNING=1
PI_SCRIPT_WAITING=2
PI_SCRIPT_FAILED =3

# pigpio command numbers

_PI_CMD_MODES= 0
_PI_CMD_MODEG= 1
_PI_CMD_PUD=   2
_PI_CMD_READ=  3
_PI_CMD_WRITE= 4
_PI_CMD_PWM=   5
_PI_CMD_PRS=   6
_PI_CMD_PFS=   7
_PI_CMD_SERVO= 8
_PI_CMD_WDOG=  9
_PI_CMD_BR1=  10
_PI_CMD_BR2=  11
_PI_CMD_BC1=  12
_PI_CMD_BC2=  13
_PI_CMD_BS1=  14
_PI_CMD_BS2=  15
_PI_CMD_TICK= 16
_PI_CMD_HWVER=17

_PI_CMD_NO=   18
_PI_CMD_NB=   19
_PI_CMD_NP=   20
_PI_CMD_NC=   21

_PI_CMD_PRG=  22
_PI_CMD_PFG=  23
_PI_CMD_PRRG= 24
_PI_CMD_HELP= 25
_PI_CMD_PIGPV=26

_PI_CMD_WVCLR=27
_PI_CMD_WVAG= 28
_PI_CMD_WVAS= 29
_PI_CMD_WVGO= 30
_PI_CMD_WVGOR=31
_PI_CMD_WVBSY=32
_PI_CMD_WVHLT=33
_PI_CMD_WVSM= 34
_PI_CMD_WVSP= 35
_PI_CMD_WVSC= 36

_PI_CMD_TRIG= 37

_PI_CMD_PROC= 38
_PI_CMD_PROCD=39
_PI_CMD_PROCR=40
_PI_CMD_PROCS=41

_PI_CMD_SLRO= 42
_PI_CMD_SLR=  43
_PI_CMD_SLRC= 44

_PI_CMD_PROCP=45
_PI_CMD_MICRO=46
_PI_CMD_MILLI=47
_PI_CMD_PARSE=48

_PI_CMD_WVCRE=49
_PI_CMD_WVDEL=50
_PI_CMD_WVTX =51
_PI_CMD_WVTXR=52
_PI_CMD_WVNEW=53

_PI_CMD_I2CO =54
_PI_CMD_I2CC =55
_PI_CMD_I2CRD=56
_PI_CMD_I2CWD=57
_PI_CMD_I2CWQ=58
_PI_CMD_I2CRS=59
_PI_CMD_I2CWS=60
_PI_CMD_I2CRB=61
_PI_CMD_I2CWB=62
_PI_CMD_I2CRW=63
_PI_CMD_I2CWW=64
_PI_CMD_I2CRK=65
_PI_CMD_I2CWK=66
_PI_CMD_I2CRI=67
_PI_CMD_I2CWI=68
_PI_CMD_I2CPC=69
_PI_CMD_I2CPK=70

_PI_CMD_SPIO =71
_PI_CMD_SPIC =72
_PI_CMD_SPIR =73
_PI_CMD_SPIW =74
_PI_CMD_SPIX =75

_PI_CMD_SERO =76
_PI_CMD_SERC =77
_PI_CMD_SERRB=78
_PI_CMD_SERWB=79
_PI_CMD_SERR =80
_PI_CMD_SERW =81
_PI_CMD_SERDA=82


_PI_CMD_NOIB= 99

# pigpio error numbers

_PI_INIT_FAILED     =-1
PI_BAD_USER_GPIO    =-2
PI_BAD_GPIO         =-3
PI_BAD_MODE         =-4
PI_BAD_LEVEL        =-5
PI_BAD_PUD          =-6
PI_BAD_PULSEWIDTH   =-7
PI_BAD_DUTYCYCLE    =-8
_PI_BAD_TIMER       =-9
_PI_BAD_MS          =-10
_PI_BAD_TIMETYPE    =-11
_PI_BAD_SECONDS     =-12
_PI_BAD_MICROS      =-13
_PI_TIMER_FAILED    =-14
PI_BAD_WDOG_TIMEOUT =-15
_PI_NO_ALERT_FUNC   =-16
_PI_BAD_CLK_PERIPH  =-17
_PI_BAD_CLK_SOURCE  =-18
_PI_BAD_CLK_MICROS  =-19
_PI_BAD_BUF_MILLIS  =-20
PI_BAD_DUTYRANGE    =-21
_PI_BAD_SIGNUM      =-22
_PI_BAD_PATHNAME    =-23
PI_NO_HANDLE        =-24
PI_BAD_HANDLE       =-25
_PI_BAD_IF_FLAGS    =-26
_PI_BAD_CHANNEL     =-27
_PI_BAD_PRIM_CHANNEL=-27
_PI_BAD_SOCKET_PORT =-28
_PI_BAD_FIFO_COMMAND=-29
_PI_BAD_SECO_CHANNEL=-30
_PI_NOT_INITIALISED =-31
_PI_INITIALISED     =-32
_PI_BAD_WAVE_MODE   =-33
_PI_BAD_CFG_INTERNAL=-34
PI_BAD_WAVE_BAUD    =-35
PI_TOO_MANY_PULSES  =-36
PI_TOO_MANY_CHARS   =-37
PI_NOT_SERIAL_GPIO  =-38
_PI_BAD_SERIAL_STRUC=-39
_PI_BAD_SERIAL_BUF  =-40
PI_NOT_PERMITTED    =-41
PI_SOME_PERMITTED   =-42
PI_BAD_WVSC_COMMND  =-43
PI_BAD_WVSM_COMMND  =-44
PI_BAD_WVSP_COMMND  =-45
PI_BAD_PULSELEN     =-46
PI_BAD_SCRIPT       =-47
PI_BAD_SCRIPT_ID    =-48
PI_BAD_SER_OFFSET   =-49
PI_GPIO_IN_USE      =-50
PI_BAD_SERIAL_COUNT =-51
PI_BAD_PARAM_NUM    =-52
PI_DUP_TAG          =-53
PI_TOO_MANY_TAGS    =-54
PI_BAD_SCRIPT_CMD   =-55
PI_BAD_VAR_NUM      =-56
PI_NO_SCRIPT_ROOM   =-57
PI_NO_MEMORY        =-58
PI_SOCK_READ_FAILED =-59
PI_SOCK_WRIT_FAILED =-60
PI_TOO_MANY_PARAM   =-61
PI_NOT_HALTED       =-62
PI_BAD_TAG          =-63
PI_BAD_MICS_DELAY   =-64
PI_BAD_MILS_DELAY   =-65
PI_BAD_WAVE_ID      =-66
PI_TOO_MANY_CBS     =-67
PI_TOO_MANY_OOL     =-68
PI_EMPTY_WAVEFORM   =-69
PI_NO_WAVEFORM_ID   =-70
PI_I2C_OPEN_FAILED  =-71
PI_SER_OPEN_FAILED  =-72
PI_SPI_OPEN_FAILED  =-73
PI_BAD_I2C_BUS      =-74
PI_BAD_I2C_ADDR     =-75
PI_BAD_SPI_CHANNEL  =-76
PI_BAD_FLAGS        =-77
PI_BAD_SPI_SPEED    =-78
PI_BAD_SER_DEVICE   =-79
PI_BAD_SER_SPEED    =-80
PI_BAD_PARAM        =-81
PI_I2C_WRITE_FAILED =-82
PI_I2C_READ_FAILED  =-83
PI_BAD_SPI_COUNT    =-84
PI_SER_WRITE_FAILED =-85
PI_SER_READ_FAILED  =-86
PI_SER_READ_NO_DATA =-87
PI_UNKNOWN_COMMAND  =-88
PI_SPI_XFER_FAILED  =-89

# pigpio error text

_errors=[
   [_PI_INIT_FAILED      , "pigpio initialisation failed"],
   [PI_BAD_USER_GPIO     , "gpio not 0-31"],
   [PI_BAD_GPIO          , "gpio not 0-53"],
   [PI_BAD_MODE          , "mode not 0-7"],
   [PI_BAD_LEVEL         , "level not 0-1"],
   [PI_BAD_PUD           , "pud not 0-2"],
   [PI_BAD_PULSEWIDTH    , "pulsewidth not 0 or 500-2500"],
   [PI_BAD_DUTYCYCLE     , "dutycycle not 0-255"],
   [_PI_BAD_TIMER        , "timer not 0-9"],
   [_PI_BAD_MS           , "ms not 10-60000"],
   [_PI_BAD_TIMETYPE     , "timetype not 0-1"],
   [_PI_BAD_SECONDS      , "seconds < 0"],
   [_PI_BAD_MICROS       , "micros not 0-999999"],
   [_PI_TIMER_FAILED     , "gpioSetTimerFunc failed"],
   [PI_BAD_WDOG_TIMEOUT  , "timeout not 0-60000"],
   [_PI_NO_ALERT_FUNC    , "DEPRECATED"],
   [_PI_BAD_CLK_PERIPH   , "clock peripheral not 0-1"],
   [_PI_BAD_CLK_SOURCE   , "clock source not 0-1"],
   [_PI_BAD_CLK_MICROS   , "clock micros not 1, 2, 4, 5, 8, or 10"],
   [_PI_BAD_BUF_MILLIS   , "buf millis not 100-10000"],
   [PI_BAD_DUTYRANGE     , "dutycycle range not 25-40000"],
   [_PI_BAD_SIGNUM       , "signum not 0-63"],
   [_PI_BAD_PATHNAME     , "can't open pathname"],
   [PI_NO_HANDLE         , "no handle available"],
   [PI_BAD_HANDLE        , "unknown notify handle"],
   [_PI_BAD_IF_FLAGS     , "ifFlags > 3"],
   [_PI_BAD_CHANNEL      , "DMA channel not 0-14"],
   [_PI_BAD_SOCKET_PORT  , "socket port not 1024-30000"],
   [_PI_BAD_FIFO_COMMAND , "unknown fifo command"],
   [_PI_BAD_SECO_CHANNEL , "DMA secondary channel not 0-6"],
   [_PI_NOT_INITIALISED  , "function called before gpioInitialise"],
   [_PI_INITIALISED      , "function called after gpioInitialise"],
   [_PI_BAD_WAVE_MODE    , "waveform mode not 0-1"],
   [_PI_BAD_CFG_INTERNAL , "bad parameter in gpioCfgInternals call"],
   [PI_BAD_WAVE_BAUD     , "baud rate not 100-250000"],
   [PI_TOO_MANY_PULSES   , "waveform has too many pulses"],
   [PI_TOO_MANY_CHARS    , "waveform has too many chars"],
   [PI_NOT_SERIAL_GPIO   , "no serial read in progress on gpio"],
   [PI_NOT_PERMITTED     , "no permission to update gpio"],
   [PI_SOME_PERMITTED    , "no permission to update one or more gpios"],
   [PI_BAD_WVSC_COMMND   , "bad WVSC subcommand"],
   [PI_BAD_WVSM_COMMND   , "bad WVSM subcommand"],
   [PI_BAD_WVSP_COMMND   , "bad WVSP subcommand"],
   [PI_BAD_PULSELEN      , "trigger pulse length > 50"],
   [PI_BAD_SCRIPT        , "invalid script"],
   [PI_BAD_SCRIPT_ID     , "unknown script id"],
   [PI_BAD_SER_OFFSET    , "add serial data offset > 30 minute"],
   [PI_GPIO_IN_USE       , "gpio already in use"],
   [PI_BAD_SERIAL_COUNT  , "must read at least a byte at a time"],
   [PI_BAD_PARAM_NUM     , "script parameter must be 0-9"],
   [PI_DUP_TAG           , "script has duplicate tag"],
   [PI_TOO_MANY_TAGS     , "script has too many tags"],
   [PI_BAD_SCRIPT_CMD    , "illegal script command"],
   [PI_BAD_VAR_NUM       , "script variable must be 0-149"],
   [PI_NO_SCRIPT_ROOM    , "no more room for scripts"],
   [PI_NO_MEMORY         , "can't allocate temporary memory"],
   [PI_SOCK_READ_FAILED  , "socket read failed"],
   [PI_SOCK_WRIT_FAILED  , "socket write failed"],
   [PI_TOO_MANY_PARAM    , "too many script parameters (> 10)"],
   [PI_NOT_HALTED        , "script already running or failed"],
   [PI_BAD_TAG           , "script has unresolved tag"],
   [PI_BAD_MICS_DELAY    , "bad MICS delay (too large)"],
   [PI_BAD_MILS_DELAY    , "bad MILS delay (too large)"],
   [PI_BAD_WAVE_ID       , "non existent wave id"],
   [PI_TOO_MANY_CBS      , "No more CBs for waveform"],
   [PI_TOO_MANY_OOL      , "No more OOL for waveform"],
   [PI_EMPTY_WAVEFORM    , "attempt to create an empty waveform"],
   [PI_NO_WAVEFORM_ID    , "No more waveform ids"],
   [PI_I2C_OPEN_FAILED   , "can't open I2C device"],
   [PI_SER_OPEN_FAILED   , "can't open serial device"],
   [PI_SPI_OPEN_FAILED   , "can't open SPI device"],
   [PI_BAD_I2C_BUS       , "bad I2C bus"],
   [PI_BAD_I2C_ADDR      , "bad I2C address"],
   [PI_BAD_SPI_CHANNEL   , "bad SPI channel"],
   [PI_BAD_FLAGS         , "bad i2c/spi/ser open flags"],
   [PI_BAD_SPI_SPEED     , "bad SPI speed"],
   [PI_BAD_SER_DEVICE    , "bad serial device name"],
   [PI_BAD_SER_SPEED     , "bad serial baud rate"],
   [PI_BAD_PARAM         , "bad i2c/spi/ser parameter"],
   [PI_I2C_WRITE_FAILED  , "I2C write failed"],
   [PI_I2C_READ_FAILED   , "I2C read failed"],
   [PI_BAD_SPI_COUNT     , "bad SPI count"],
   [PI_SER_WRITE_FAILED  , "ser write failed"],
   [PI_SER_READ_FAILED   , "ser read failed"],
   [PI_SER_READ_NO_DATA  , "ser read no data available"],
   [PI_UNKNOWN_COMMAND   , "unknown command"],
   [PI_SPI_XFER_FAILED   , "SPI xfer/read/write failed"],
]

class error(Exception):
   """pigpio module exception"""
   def __init__(self, value):
      self.value = value
   def __str__(self):
      return repr(self.value)

class pulse:
   """
   A class to store pulse information.
   """

   def __init__(self, gpio_on, gpio_off, delay):
      """
      Initialises a pulse.

       gpio_on:= the gpios to switch on at the start of the pulse.
      gpio_off:= the gpios to switch off at the start of the pulse.
         delay:= the delay in microseconds before the next pulse.

      """
      self.gpio_on = gpio_on
      self.gpio_off = gpio_off
      self.delay = delay

def error_text(errnum):
   """
   Returns a text description of a pigpio error.

   errnum:= <0, the error number

   ...
   print(pigpio.error_text(-5))
   level not 0-1
   ...
   """
   for e in _errors:
      if e[0] == errnum:
         return e[1]
   return "unknown error ({})".format(errnum)

def tickDiff(t1, t2):
   """
   Returns the microsecond difference between two ticks.

   t1:= the earlier tick
   t2:= the later tick

   ...
   print(pigpio.tickDiff(4294967272, 12))
   36
   ...
   """
   tDiff = t2 - t1
   if tDiff < 0:
      tDiff += (1 << 32)
   return tDiff

if sys.version < '3':
   def _b(x):
      return x
else:
   def _b(x):
      return codecs.latin_1_encode(x)[0]

def _u2i(number):
   """Converts a 32 bit unsigned number to signed."""
   mask = (2 ** 32) - 1
   if number & (1 << 31):
      v = number | ~mask
   else:
      v = number & mask
   if v >= 0:
      return v;
   else:
      if exceptions:
         raise error(error_text(v))
      else:
         return v

def _pigpio_command(sock, cmd, p1, p2):
   """
   Runs a pigpio socket command.

   sock:= command socket.
    cmd:= the command to be executed.
     p1:= command parameter 1 (if applicable).
     p2:=  command parameter 2 (if applicable).
   """
   sock.send(struct.pack('IIII', cmd, p1, p2, 0))
   dummy, res = struct.unpack('12sI', sock.recv(16))
   return res

def _pigpio_command_ext(sock, cmd, p1, p2, p3, extents):
   """
   Runs an extended pigpio socket command.

      sock:= command socket.
       cmd:= the command to be executed.
        p1:= command parameter 1 (if applicable).
        p2:= command parameter 2 (if applicable).
        p3:= total size in bytes of following extents
   extents:= additional data blocks
   """
   ext = bytearray(struct.pack('IIII', cmd, p1, p2, p3))
   for x in extents:
      if type(x) == type(""):
         ext.extend(_b(x))
      else:
         ext.extend(x)
   sock.sendall(ext)
   dummy, res = struct.unpack('12sI', sock.recv(16))
   return res

class _callback_ADT:
   """An ADT class to hold callback information."""

   def __init__(self, gpio, edge, func):
      """
      Initialises a callback ADT.

      gpio:= Broadcom gpio number.
      edge:= EITHER_EDGE, RISING_EDGE, or FALLING_EDGE.
      func:= a user function taking three arguments (gpio, level, tick).
      """
      self.gpio = gpio
      self.edge = edge
      self.func = func
      self.bit = 1<<gpio

class _callback_thread(threading.Thread):
   """A class to encapsulate pigpio notification callbacks."""
   def __init__(self, control, host, port):
      """Initialises notifications."""
      threading.Thread.__init__(self)
      self.control = control
      self.go = False
      self.daemon = True
      self.monitor = 0
      self.callbacks = []
      self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      self.sock.connect((host, port))
      self.handle = _pigpio_command(self.sock, _PI_CMD_NOIB, 0, 0)
      self.go = True
      self.start()

   def stop(self):
      """Stops notifications."""
      if self.go:
         self.go = False
         self.sock.send(struct.pack('IIII', _PI_CMD_NC, self.handle, 0, 0))

   def append(self, callb):
      """Adds a callback to the notification thread."""
      self.callbacks.append(callb)
      self.monitor = self.monitor | callb.bit
      _pigpio_command(self.control, _PI_CMD_NB, self.handle, self.monitor)

   def remove(self, callb):
      """Removes a callback from the notification thread."""
      if callb in self.callbacks:
         self.callbacks.remove(callb)
         newMonitor = 0
         for c in self.callbacks:
            newMonitor |= c.bit
         if newMonitor != self.monitor:
            self.monitor = newMonitor
            _pigpio_command(
               self.control, _PI_CMD_NB, self.handle, self.monitor)

   def run(self):
      """Runs the notification thread."""

      lastLevel = 0

      MSG_SIZ = 12

      while self.go:

         buf = self.sock.recv(MSG_SIZ)

         while self.go and len(buf) < MSG_SIZ:
            buf += self.sock.recv(MSG_SIZ-len(buf))

         if self.go:
            seq, flags, tick, level = (struct.unpack('HHII', buf))

            if flags == 0:
               changed = level ^ lastLevel
               lastLevel = level
               for cb in self.callbacks:
                  if cb.bit & changed:
                     newLevel = 0
                     if cb.bit & level:
                        newLevel = 1
                     if (cb.edge ^ newLevel):
                         cb.func(cb.gpio, newLevel, tick)
            else:
               gpio = flags & 31
               for cb in self.callbacks:
                  if cb.gpio == gpio:
                     cb.func(cb.gpio, TIMEOUT, tick)

      self.sock.close()

class _callback:
   """A class to provide gpio level change callbacks."""

   def __init__(self, notify, user_gpio, edge=RISING_EDGE, func=None):
      """
      Initialise a callback and adds it to the notification thread.
      """
      self._notify = notify
      self.count=0
      if func is None:
         func=self._tally
      self.callb = _callback_ADT(user_gpio, edge, func)
      self._notify.append(self.callb)

   def cancel(self):
      """Cancels a callback by removing it from the notification thread."""
      self._notify.remove(self.callb)

   def _tally(self, user_gpio, level, tick):
      """Increment the callback called count."""
      self.count += 1

   def tally(self):
      """
      Provides a count of how many times the default tally
      callback has triggered.

      The count will be zero if the user has supplied their own
      callback function.
      """
      return self.count

class _wait_for_edge:
   """Encapsulates waiting for gpio edges."""

   def __init__(self, notify, gpio, edge, timeout):
      """Initialises a wait_for_edge."""
      self._notify = notify
      self.callb = _callback_ADT(gpio, edge, self.func)
      self.trigger = False
      self._notify.append(self.callb)
      self.start = time.time()
      while (self.trigger == False) and ((time.time()-self.start) < timeout):
         time.sleep(0.05)
      self._notify.remove(self.callb)

   def func(self, gpio, level, tick):
      """Sets wait_for_edge triggered."""
      self.trigger = True

class pi():

   def _rxbuf(self, count):
      """Returns count bytes from the command socket."""
      ext = bytearray(self._control.recv(count))
      while len(ext) < count:
         ext.extend(self._control.recv(count - len(ext)))
      return ext

   def set_mode(self, gpio, mode):
      """
      Sets the gpio mode.

      gpio:= 0-53.
      mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5.

      ...
      pi.set_mode( 4, pigpio.INPUT)  # gpio  4 as input
      pi.set_mode(17, pigpio.OUTPUT) # gpio 17 as output
      pi.set_mode(24, pigpio.ALT2)   # gpio 24 as ALT2
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_MODES, gpio, mode))

   def get_mode(self, gpio):
      """
      Returns the gpio mode.

      gpio:= 0-53.

      Returns a value as follows

      . .
      0 = INPUT
      1 = OUTPUT
      2 = ALT5
      3 = ALT4
      4 = ALT0
      5 = ALT1
      6 = ALT2
      7 = ALT3
      . .

      ...
      print(pi.get_mode(0))
      4
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_MODEG, gpio, 0))

   def set_pull_up_down(self, gpio, pud):
      """
      Sets or clears the internal gpio pull-up/down resistor.

      gpio:= 0-53.
       pud:= PUD_UP, PUD_DOWN, PUD_OFF.

      ...
      pi.set_pull_up_down(17, pigpio.PUD_OFF)
      pi.set_pull_up_down(23, pigpio.PUD_UP)
      pi.set_pull_up_down(24, pigpio.PUD_DOWN)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PUD, gpio, pud))

   def read(self, gpio):
      """
      Returns the gpio level.

      gpio:= 0-53.

      ...
      pi.set_mode(23, pigpio.INPUT)

      pi.set_pull_up_down(23, pigpio.PUD_DOWN)
      print(pi.read(23))
      0

      pi.set_pull_up_down(23, pigpio.PUD_UP)
      print(pi.read(23))
      1
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_READ, gpio, 0))

   def write(self, gpio, level):
      """
      Sets the gpio level.

       gpio:= 0-53.
      level:= 0, 1.

      If PWM or servo pulses are active on the gpio they are
      switched off.

      ...
      pi.set_mode(17, pigpio.OUTPUT)

      pi.write(17,0)
      print(pi.read(17))
      0

      pi.write(17,1)
      print(pi.read(17))
      1
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WRITE, gpio, level))

   def set_PWM_dutycycle(self, user_gpio, dutycycle):
      """
      Starts (non-zero dutycycle) or stops (0) PWM pulses on the gpio.

      user_gpio:= 0-31.
      dutycycle:= 0-range (range defaults to 255).

      The set_PWM_range function can change the default range of 255.

      ...
      pi.set_PWM_dutycycle(4,   0) # PWM off
      pi.set_PWM_dutycycle(4,  64) # PWM 1/4 on
      pi.set_PWM_dutycycle(4, 128) # PWM 1/2 on
      pi.set_PWM_dutycycle(4, 192) # PWM 3/4 on
      pi.set_PWM_dutycycle(4, 255) # PWM full on
      ...
      """
      return _u2i(_pigpio_command(
         self._control, _PI_CMD_PWM, user_gpio, int(dutycycle)))

   def set_PWM_range(self, user_gpio, range_):
      """
      Sets the range of PWM values to be used on the gpio.

      user_gpio:= 0-31.
         range_:= 25-40000.

      ...
      pi.set_PWM_range(9, 100)  # now  25 1/4,   50 1/2,   75 3/4 on
      pi.set_PWM_range(9, 500)  # now 125 1/4,  250 1/2,  375 3/4 on
      pi.set_PWM_range(9, 3000) # now 750 1/4, 1500 1/2, 2250 3/4 on
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PRS, user_gpio, range_))

   def get_PWM_range(self, user_gpio):
      """
      Returns the range of PWM values being used on the gpio.

      user_gpio:= 0-31.

      ...
      pi.set_PWM_range(9, 500)
      print(pi.get_PWM_range(9))
      500
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PRG, user_gpio, 0))

   def get_PWM_real_range(self, user_gpio):
      """
      Returns the real (underlying) range of PWM values being
      used on the gpio.

      user_gpio:= 0-31.

      ...
      pi.set_PWM_frequency(4, 800)
      print(pi.get_PWM_real_range(4))
      250
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PRRG, user_gpio, 0))

   def set_PWM_frequency(self, user_gpio, frequency):
      """
      Sets the frequency (in Hz) of the PWM to be used on the gpio.

      user_gpio:= 0-31.
      frequency:= >=0 Hz

      Returns the frequency actually set.

      ...
      pi.set_PWM_frequency(4,0)
      print(pi.get_PWM_frequency(4))
      10

      pi.set_PWM_frequency(4,100000)
      print(pi.get_PWM_frequency(4))
      8000
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PFS, user_gpio, frequency))

   def get_PWM_frequency(self, user_gpio):
      """
      Returns the frequency of PWM being used on the gpio.

      user_gpio:= 0-31.

      Returns the frequency (in Hz) used for the gpio.

      ...
      pi.set_PWM_frequency(4,0)
      print(pi.get_PWM_frequency(4))
      10

      pi.set_PWM_frequency(4, 800)
      print(pi.get_PWM_frequency(4))
      800
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PFG, user_gpio, 0))

   def set_servo_pulsewidth(self, user_gpio, pulsewidth):
      """
      Starts (500-2500) or stops (0) servo pulses on the gpio.

       user_gpio:= 0-31.
      pulsewidth:= 0 (off),
                   500 (most anti-clockwise) - 2500 (most clockwise).

      The selected pulsewidth will continue to be transmitted until
      changed by a subsequent call to set_servo_pulsewidth.

      The pulsewidths supported by servos varies and should probably
      be determined by experiment. A value of 1500 should always be
      safe and represents the mid-point of rotation.

      You can DAMAGE a servo if you command it to move beyond its
      limits.

      ...
      pi.set_servo_pulsewidth(17, 0)    # off
      pi.set_servo_pulsewidth(17, 1000) # safe anti-clockwise
      pi.set_servo_pulsewidth(17, 1500) # centre
      pi.set_servo_pulsewidth(17, 2000) # safe clockwise
      ...
   """
      return _u2i(_pigpio_command(
         self._control, _PI_CMD_SERVO, user_gpio, int(pulsewidth)))

   def notify_open(self):
      """
      Returns a notification handle (>=0).

      A notification is a method for being notified of gpio state
      changes via a pipe.

      Pipes are only accessible from the local machine so this 
      function serves no purpose if you are using Python from a
      remote machine.  The in-built (socket) notifications
      provided by callback should be used instead.

      Notifications for handle x will be available at the pipe
      named /dev/pigpiox (where x is the handle number).
      E.g. if the function returns 15 then the notifications must be
      read from /dev/pigpio15.

      Notifications have the following structure.

      . .
      I seqno - increments for each report
      I flags - flags, if bit 5 is set then bits 0-4 of the flags
                indicate a gpio which has had a watchdog timeout.
      I tick  - time of sample.
      I level - 32 bits of levels for gpios 0-31.
      . .

      ...
      h = pi.notify_open()
      if h >= 0:
         pi.notify_begin(h, 1234)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_NO, 0, 0))

   def notify_begin(self, handle, bits):
      """
      Starts notifications on a handle.

      handle:= >=0 (as returned by a prior call to notify_open)
        bits:= a 32 bit mask indicating the gpios to be notified.

      The notification sends state changes for each gpio whose
      corresponding bit in bits is set.

      The following code starts notifications for gpios 1, 4,
      6, 7, and 10 (1234 = 0x04D2 = 0b0000010011010010).

      ...
      h = pi.notify_open()
      if h >= 0:
         pi.notify_begin(h, 1234)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_NB, handle, bits))

   def notify_pause(self, handle):
      """
      Pauses notifications on a handle.

      handle:= >=0 (as returned by a prior call to notify_open)

      Notifications for the handle are suspended until
      notify_begin is called again.

      ...
      h = pi.notify_open()
      if h >= 0:
         pi.notify_begin(h, 1234)
         ...
         pi.notify_pause(h)
         ...
         pi.notify_begin(h, 1234)
         ...
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_NB, handle, 0))

   def notify_close(self, handle):
      """
      Stops notifications on a handle and releases the handle for reuse.

      handle:= >=0 (as returned by a prior call to notify_open)

      ...
      h = pi.notify_open()
      if h >= 0:
         pi.notify_begin(h, 1234)
         ...
         pi.notify_close(h)
         ...
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_NC, handle, 0))

   def set_watchdog(self, user_gpio, wdog_timeout):
      """
      Sets a watchdog timeout for a gpio.

         user_gpio:= 0-31.
      wdog_timeout:= 0-60000.

      The watchdog is nominally in milliseconds.

      Only one watchdog may be registered per gpio.

      The watchdog may be cancelled by setting timeout to 0.

      If no level change has been detected for the gpio for timeout
      milliseconds any notification for the gpio has a report written
      to the fifo with the flags set to indicate a watchdog timeout.

      The callback class interprets the flags and will
      call registered callbacks for the gpio with level TIMEOUT.

      ...
      pi.set_watchdog(23, 1000) # 1000 ms watchdog on gpio 23
      pi.set_watchdog(23, 0)    # cancel watchdog on gpio 23
      ...
      """
      return _u2i(_pigpio_command(
         self._control, _PI_CMD_WDOG, user_gpio, int(wdog_timeout)))

   def read_bank_1(self):
      """
      Returns the levels of the bank 1 gpios (gpios 0-31).

      The returned 32 bit integer has a bit set if the corresponding
      gpio is high.  Gpio n has bit value (1<<n).

      ...
      print(bin(pi.read_bank_1()))
      0b10010100000011100100001001111
      ...
      """
      return _pigpio_command(self._control, _PI_CMD_BR1, 0, 0)

   def read_bank_2(self):
      """
      Returns the levels of the bank 2 gpios (gpios 32-53).

      The returned 32 bit integer has a bit set if the corresponding
      gpio is high.  Gpio n has bit value (1<<(n-32)).

      ...
      print(bin(pi.read_bank_2()))
      0b1111110000000000000000
      ...
      """
      return _pigpio_command(self._control, _PI_CMD_BR2, 0, 0)

   def clear_bank_1(self, bits):
      """
      Clears gpios 0-31 if the corresponding bit in bits is set.

      bits:= a 32 bit mask with 1 set if the corresponding gpio is
             to be cleared.

      A returned status of PI_SOME_PERMITTED indicates that the user
      is not allowed to write to one or more of the gpios.

      ...
      pi.clear_bank_1(int("111110010000",2))
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_BC1, bits, 0))

   def clear_bank_2(self, bits):
      """
      Clears gpios 32-53 if the corresponding bit (0-21) in bits is set.

      bits:= a 32 bit mask with 1 set if the corresponding gpio is
             to be cleared.

      A returned status of PI_SOME_PERMITTED indicates that the user
      is not allowed to write to one or more of the gpios.

      ...
      pi.clear_bank_2(0x1010)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_BC2, bits, 0))

   def set_bank_1(self, bits):
      """
      Sets gpios 0-31 if the corresponding bit in bits is set.

      bits:= a 32 bit mask with 1 set if the corresponding gpio is
             to be set.

      A returned status of PI_SOME_PERMITTED indicates that the user
      is not allowed to write to one or more of the gpios.

      ...
      pi.set_bank_1(int("111110010000",2))
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_BS1, bits, 0))

   def set_bank_2(self, bits):
      """
      Sets gpios 32-53 if the corresponding bit (0-21) in bits is set.

      bits:= a 32 bit mask with 1 set if the corresponding gpio is
             to be set.

      A returned status of PI_SOME_PERMITTED indicates that the user
      is not allowed to write to one or more of the gpios.

      ...
      pi.set_bank_2(0x303)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_BS2, bits, 0))

   def get_current_tick(self):
      """
      Returns the current system tick.

      Tick is the number of microseconds since system boot.  As an
      unsigned 32 bit quantity tick wraps around approximately
      every 71.6 minutes.

      ...
      t1 = pi.get_current_tick()
      time.sleep(1)
      t2 = pi.get_current_tick()
      ...
      """
      return _pigpio_command(self._control, _PI_CMD_TICK, 0, 0)

   def get_hardware_revision(self):
      """
      Returns the Pi's hardware revision number.

      The hardware revision is the last 4 characters on the Revision
      line of /proc/cpuinfo.

      The revision number can be used to determine the assignment
      of gpios to pins.

      There are at least two types of board.

      Type 1 has gpio 0 on P1-3, gpio 1 on P1-5, and gpio 21 on P1-13
      (revision numbers 2 and 3).

      Type 2 has gpio 2 on P1-3, gpio 3 on P1-5, gpio 27 on P1-13,
      and gpios 28-31 on P5 (revision numbers of 4, 5, 6, and 15).

      If the hardware revision can not be found or is not a valid
      hexadecimal number the function returns 0.

      ...
      print(pi.get_hardware_revision())
      2
      ...
      """
      return _pigpio_command(self._control, _PI_CMD_HWVER, 0, 0)

   def get_pigpio_version(self):
      """
      Returns the pigpio software version.

      ...
      v = pi.get_pigpio_version()
      ...
      """
      return _pigpio_command(self._control, _PI_CMD_PIGPV, 0, 0)

   def wave_clear(self):
      """
      Clears all waveforms and any data added by calls to the
      wave_add_* functions.

      ...
      pi.wave_clear()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVCLR, 0, 0))

   def wave_add_new(self):
      """
      Starts a new empty waveform.

      You would not normally need to call this function as it is
      automatically called after a waveform is created with the
      wave_create function.

      ...
      pi.wave_add_new()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVNEW, 0, 0))

   def wave_add_generic(self, pulses):
      """
      Adds a list of pulses to the current waveform.

      pulses:= list of pulses to add to the waveform.

      Returns the new total number of pulses in the current waveform.

      The pulses are interleaved in time order within the existing
      waveform (if any).

      Merging allows the waveform to be built in parts, that is the
      settings for gpio#1 can be added, and then gpio#2 etc.

      If the added waveform is intended to start after or within
      the existing waveform then the first pulse should consist
      solely of a delay.

      ...
      G1=4
      G2=24

      pi.set_mode(G1, pigpio.OUTPUT)
      pi.set_mode(G2, pigpio.OUTPUT)

      flash_500=[] # flash every 500 ms
      flash_100=[] # flash every 100 ms

      #                              ON     OFF  DELAY

      flash_500.append(pigpio.pulse(1<<G1, 1<<G2, 500000))
      flash_500.append(pigpio.pulse(1<<G2, 1<<G1, 500000))

      flash_100.append(pigpio.pulse(1<<G1, 1<<G2, 100000))
      flash_100.append(pigpio.pulse(1<<G2, 1<<G1, 100000))

      pi.wave_clear() # clear any existing waveforms

      pi.wave_add_generic(flash_500) # 500 ms flashes
      f500 = pi.wave_create() # create and save id

      pi.wave_add_generic(flash_100) # 100 ms flashes
      f100 = pi.wave_create() # create and save id

      pi.wave_send_repeat(f500)

      time.sleep(4)

      pi.wave_send_repeat(f100)

      time.sleep(4)

      pi.wave_send_repeat(f500)

      time.sleep(4)

      pi.wave_tx_stop() # stop waveform

      pi.wave_clear() # clear all waveforms
      ...
      """
      # pigpio message format

      # I p1 0
      # I p2 0
      # I p3 pulses * 12
      ## extension ##
      # III on/off/delay * pulses
      if len(pulses):
         ext = bytearray()
         for p in pulses:
            ext.extend(struct.pack("III", p.gpio_on, p.gpio_off, p.delay))
         extents = [ext]
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_WVAG, 0, 0, len(pulses)*12, extents))
      else:
         return 0

   def wave_add_serial(self, user_gpio, bb_baud, offset, data):
      """
      Adds a waveform representing serial data to the existing
      waveform (if any).  The serial data starts offset
      microseconds from the start of the waveform.

      user_gpio:= gpio to transmit data.  You must set the gpio mode
                  to output.
        bb_baud:= baud rate to use.
         offset:= number of microseconds from the starts of the
                  waveform.
           data:= the bytes to write.

      Returns the new total number of pulses in the current waveform.

      The serial data is formatted as one start bit, eight data bits,
      and one stop bit.

      It is legal to add serial data streams with different baud
      rates to the same waveform.

      ...
      pi.wave_add_serial(4, 300, 0, 'Hello world')

      pi.wave_add_serial(4, 300, 0, b"Hello world")

      pi.wave_add_serial(4, 300, 0, b'\\x23\\x01\\x00\\x45')

      pi.wave_add_serial(17, 38400, 5000, [23, 128, 234])
      ...
      """
      # pigpio message format

      # I p1 gpio
      # I p2 bb_baud
      # I p3 len+4
      ## extension ##
      # I offset
      # s len data bytes
      if len(data):
         extents = [struct.pack("I", offset), data]
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_WVAS, user_gpio, bb_baud, len(data)+4, extents))
      else:
         return 0

   def wave_create(self):
      """
      Creates a waveform from the data provided by the prior calls
      to the wave_add_* functions.

      Returns a wave id (>=0) if OK.

      The data provided by the wave_add_* functions is consumed by
      this function.

      As many waveforms may be created as there is space available.
      The wave id is passed to wave_send_* to specify the waveform
      to transmit.

      Normal usage would be

      Step 1. wave_clear to clear all waveforms and added data.

      Step 2. wave_add_* calls to supply the waveform data.

      Step 3. wave_create to create the waveform and get a unique id

      Repeat steps 2 and 3 as needed.

      Step 4. wave_send_* with the id of the waveform to transmit.

      A waveform comprises one or more pulses.

      A pulse specifies

      1) the gpios to be switched on at the start of the pulse. 
      2) the gpios to be switched off at the start of the pulse. 
      3) the delay in microseconds before the next pulse.

      Any or all the fields can be zero.  It doesn't make any sense
      to set all the fields to zero (the pulse will be ignored).

      When a waveform is started each pulse is executed in order with
      the specified delay between the pulse and the next.

      ...
      wid = pi.wave_create()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVCRE, 0, 0))

   def wave_delete(self, wave_id):
      """
      Deletes all created waveforms with ids greater than or equal
      to wave_id.

      wave_id:= >=0 (as returned by a prior call to wave_create).

      Wave ids are allocated in order, 0, 1, 2, etc.

      ...
      pi.wave_delete(6) # delete all waves with id 6 or greater

      pi.wave_delete(0) # delete all waves
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVDEL, wave_id, 0))

   def wave_tx_start(self): # DEPRECATED
      """
      This function is deprecated and will be removed.

      Use wave_create/wave_send_* instead.
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVGO, 0, 0))

   def wave_tx_repeat(self): # DEPRECATED
      """
      This function is deprecated and will be removed.

      Use wave_create/wave_send_* instead.
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVGOR, 0, 0))

   def wave_send_once(self, wave_id):
      """
      Transmits the waveform with id wave_id.  The waveform is sent
      once.

      wave_id:= >=0 (as returned by a prior call to wave_create).

      Returns the number of DMA control blocks used in the waveform.

      ...
      cbs = pi.wave_send_once(wid)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVTX, wave_id, 0))

   def wave_send_repeat(self, wave_id):
      """
      Transmits the waveform with id wave_id.  The waveform repeats
      until wave_tx_stop is called or another call to wave_send_*
      is made.

      wave_id:= >=0 (as returned by a prior call to wave_create).

      Returns the number of DMA control blocks used in the waveform.

      ...
      cbs = pi.wave_send_repeat(wid)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVTXR, wave_id, 0))

   def wave_tx_busy(self):
      """
      Returns 1 if a waveform is currently being transmitted,
      otherwise 0.

      ...
      pi.wave_send_once(0) # send first waveform

      while pi.wave_tx_busy(): # wait for waveform to be sent
         time.sleep(0.1)

      pi.wave_send_once(1) # send next waveform
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVBSY, 0, 0))

   def wave_tx_stop(self):
      """
      Stops the transmission of the current waveform.

      This function is intended to stop a waveform started with
      wave_send_repeat.

      ...
      pi.wave_send_repeat(3)

      time.sleep(5)

      pi.wave_tx_stop()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVHLT, 0, 0))

   def wave_get_micros(self):
      """
      Returns the length in microseconds of the current waveform.

      ...
      micros = pi.wave_get_micros()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSM, 0, 0))

   def wave_get_max_micros(self):
      """
      Returns the maximum possible size of a waveform in microseconds.

      ...
      micros = pi.wave_get_max_micros()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSM, 2, 0))

   def wave_get_pulses(self):
      """
      Returns the length in pulses of the current waveform.

      ...
      pulses = pi.wave_get_pulses()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSP, 0, 0))

   def wave_get_max_pulses(self):
      """
      Returns the maximum possible size of a waveform in pulses.

      ...
      pulses = pi.wave_get_max_pulses()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSP, 2, 0))

   def wave_get_cbs(self):
      """
      Returns the length in DMA control blocks of the current
      waveform.

      ...
      cbs = pi.wave_get_cbs()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSC, 0, 0))

   def wave_get_max_cbs(self):
      """
      Returns the maximum possible size of a waveform in DMA
      control blocks.

      ...
      cbs = pi.wave_get_max_cbs()
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_WVSC, 2, 0))

   def i2c_open(self, i2c_bus, i2c_address, i2c_flags=0):
      """
      Returns a handle (>=0) for the device at the I2C bus address.

          i2c_bus:= 0-1.
      i2c_address:= 0x08-0x77.
        i2c_flags:= 0, no flags are currently defined.

      ...
      h = pi.i2c_open(1, 0x53) # open device at address 0x53 on bus 1
      ...
      """
      # I p1 i2c_bus
      # I p2 i2c_addr
      # I p3 4
      ## extension ##
      # I i2c_flags
      extents = [struct.pack("I", i2c_flags)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CO, i2c_bus, i2c_address, 4, extents))

   def i2c_close(self, handle):
      """
      Closes the I2C device associated with handle.

      handle:= >=0 (as returned by a prior call to i2c_open).

      ...
      pi.i2c_close(h)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_I2CC, handle, 0))

   def i2c_read_device(self, handle, count):
      """
      Returns count bytes read from the raw device associated
      with handle.

      handle:= >=0 (as returned by a prior call to i2c_open).
       count:= >0, the number of bytes to read.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (count, data) = pi.i2c_read_device(h, 12)
      ...
      """
      bytes = _u2i(_pigpio_command(self._control, _PI_CMD_I2CRD, handle, count))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def i2c_write_device(self, handle, data):
      """
      Writes the data bytes to the raw device associated with handle.

      handle:= >=0 (as returned by a prior call to i2c_open).
        data:= the bytes to write.

      ...
      pi.i2c_write_device(h, b"\\x12\\x34\\xA8")

      pi.i2c_write_device(h, b"help")

      pi.i2c_write_device(h, 'help')

      pi.i2c_write_device(h, [23, 56, 231])
      ...
      """
      # I p1 handle
      # I p2 0
      # I p3 len
      ## extension ##
      # s len data bytes
      if len(data):
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_I2CWD, handle, 0, len(data), [data]))
      else:
         return 0

   def i2c_write_quick(self, handle, bit):
      """
      Sends a single bit to the device associated with handle
      (smbus 2.0 5.5.1 - Quick command).

      handle:= >=0 (as returned by a prior call to i2c_open).
         bit:= 0 or 1, the value to write.

      ...
      pi.i2c_write_quick(0, 1) # send 1 to device 0
      pi.i2c_write_quick(3, 0) # send 0 to device 3
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_I2CWQ, handle, bit))

   def i2c_write_byte(self, handle, byte_val):
      """
      Sends a single byte to the device associated with handle
      (smbus 2.0 5.5.2 - Send byte).

        handle:= >=0 (as returned by a prior call to i2c_open).
      byte_val:= 0-255, the value to write.

      ...
      pi.i2c_write_byte(1, 17)   # send byte   17 to device 1
      pi.i2c_write_byte(2, 0x23) # send byte 0x23 to device 2
      ...
      """
      return _u2i(
         _pigpio_command(self._control, _PI_CMD_I2CWS, handle, byte_val))

   def i2c_read_byte(self, handle):
      """
      Reads a single byte from the device associated with handle
      (smbus 2.0 5.5.3 - Receive byte).

      handle:= >=0 (as returned by a prior call to i2c_open).

      ...
      b = pi.i2c_read_byte(2) # read a byte from device 2
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_I2CRS, handle, 0))

   def i2c_write_byte_data(self, handle, reg, byte_val):
      """
      Writes a single byte to the specified register of the device
      associated with handle (smbus 2.0 5.5.4 - Write byte).

        handle:= >=0 (as returned by a prior call to i2c_open).
           reg:= >=0, the device register.
      byte_val:= 0-255, the value to write.

      ...
      # send byte 0xC5 to reg 2 of device 1
      pi.i2c_write_byte_data(1, 2, 0xC5)

      # send byte 9 to reg 4 of device 2
      pi.i2c_write_byte_data(2, 4, 9)
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 4
      ## extension ##
      # I byte_val
      extents = [struct.pack("I", byte_val)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CWB, handle, reg, 4, extents))

   def i2c_write_word_data(self, handle, reg, word_val):
      """
      Writes a single 16 bit word to the specified register of the
      device associated with handle (smbus 2.0 5.5.4 - Write word).

        handle:= >=0 (as returned by a prior call to i2c_open).
           reg:= >=0, the device register.
      word_val:= 0-65535, the value to write.

      ...
      # send word 0xA0C5 to reg 5 of device 4
      pi.i2c_write_word_data(4, 5, 0xA0C5)

      # send word 2 to reg 2 of device 5
      pi.i2c_write_word_data(5, 2, 23)
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 4
      ## extension ##
      # I word_val
      extents = [struct.pack("I", word_val)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CWW, handle, reg, 4, extents))

   def i2c_read_byte_data(self, handle, reg):
      """
      Reads a single byte from the specified register of the device
      associated with handle (smbus 2.0 5.5.5 - Read byte).

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.

      ...
      # read byte from reg 17 of device 2
      b = pi.i2c_read_byte_data(2, 17)

      # read byte from reg  1 of device 0
      b = pi.i2c_read_byte_data(0, 1)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_I2CRB, handle, reg))

   def i2c_read_word_data(self, handle, reg):
      """
      Reads a single 16 bit word from the specified register of the
      device associated with handle (smbus 2.0 5.5.5 - Read word).

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.

      ...
      # read word from reg 2 of device 3
      w = pi.i2c_read_word_data(3, 2)

      # read word from reg 7 of device 2
      w = pi.i2c_read_word_data(2, 7)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_I2CRW, handle, reg))

   def i2c_process_call(self, handle, reg, word_val):
      """
      Writes 16 bits of data to the specified register of the device
      associated with handle and reads 16 bits of data in return
      (smbus 2.0 5.5.6 - Process call).

        handle:= >=0 (as returned by a prior call to i2c_open).
           reg:= >=0, the device register.
      word_val:= 0-65535, the value to write.

      ...
      r = pi.i2c_process_call(h, 4, 0x1231)
      r = pi.i2c_process_call(h, 6, 0)
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 4
      ## extension ##
      # I word_val
      extents = [struct.pack("I", word_val)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CPC, handle, reg, 4, extents))

   def i2c_write_block_data(self, handle, reg, data):
      """
      Writes up to 32 bytes to the specified register of the device
      associated with handle (smbus 2.0 5.5.7 - Block write).

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.
        data:= the bytes to write.

      ...
      pi.i2c_write_block_data(4, 5, b'hello')

      pi.i2c_write_block_data(4, 5, "data bytes")

      pi.i2c_write_block_data(5, 0, b'\\x00\\x01\\x22')

      pi.i2c_write_block_data(6, 2, [0, 1, 0x22])
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 len
      ## extension ##
      # s len data bytes
      if len(data):
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_I2CWK, handle, reg, len(data), [data]))
      else:
         return 0

   def i2c_read_block_data(self, handle, reg):
      """
      Reads a block of up to 32 bytes from the specified register of
      the device associated with handle (smbus 2.0 5.5.7 - Block read).

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.

      The amount of returned data is set by the device.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (b, d) = pi.i2c_read_block_data(h, 10)
      if b >= 0:
         # process data
      else:
         # process read failure
      ...
      """
      bytes = _u2i(_pigpio_command(self._control, _PI_CMD_I2CRK, handle, reg))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def i2c_block_process_call(self, handle, reg, data):
      """
      Writes data bytes to the specified register of the device
      associated with handle and reads a device specified number
      of bytes of data in return (smbus 2.0 5.5.8 -
      Block write-block read).

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.
        data:= the bytes to write.

      The smbus 2.0 documentation states that a minimum of 1 byte may
      be sent and a minimum of 1 byte may be received.  The total
      number of bytes sent/received must be 32 or less.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (b, d) = pi.i2c_block_process_call(h, 10, b'\\x02\\x05\\x00')

      (b, d) = pi.i2c_block_process_call(h, 10, b'abcdr')

      (b, d) = pi.i2c_block_process_call(h, 10, "abracad")

      (b, d) = pi.i2c_block_process_call(h, 10, [2, 5, 16])
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 len
      ## extension ##
      # s len data bytes
      bytes = _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CPK, handle, reg, len(data), [data]))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def i2c_write_i2c_block_data(self, handle, reg, data):
      """
      Writes data bytes to the specified register of the device
      associated with handle .  1-32 bytes may be written.

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.
        data:= the bytes to write.

      ...
      pi.i2c_write_i2c_block_data(4, 5, 'hello')

      pi.i2c_write_i2c_block_data(4, 5, b'hello')

      pi.i2c_write_i2c_block_data(5, 0, b'\\x00\\x01\\x22')

      pi.i2c_write_i2c_block_data(6, 2, [0, 1, 0x22])
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 len
      ## extension ##
      # s len data bytes
      if len(data):
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_I2CWI, handle, reg, len(data), [data]))
      else:
         return 0

   def i2c_read_i2c_block_data(self, handle, reg, count):
      """
      Reads count bytes from the specified register of the device
      associated with handle .  The count may be 1-32.

      handle:= >=0 (as returned by a prior call to i2c_open).
         reg:= >=0, the device register.
       count:= >0, the number of bytes to read.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (b, d) = pi.i2c_read_i2c_block_data(h, 4, 32)
      if b >= 0:
         # process data
      else:
         # process read failure
      ...
      """
      # I p1 handle
      # I p2 reg
      # I p3 4
      ## extension ##
      # I count
      extents = [struct.pack("I", count)]
      bytes = _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_I2CRI, handle, reg, 4, extents))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def spi_open(self, spi_channel, spi_baud, spi_flags=0):
      """
      Returns a handle for the SPI device on channel.

      spi_channel:= 0 or 1, the SPI channel.
         spi_baud:= >0, the transmission rate in bits per second.
        spi_flags:= see below.

      The bottom two bits of spi_flags define the SPI mode as
      follows.

      . .
      bit bit
       1   0
      POL PHA Mode
       0   0   0
       0   1   1
       1   0   2
       1   1   3
      . .

      The other bits in spi_flags should be set to zero.

      ...
      # open SPI device on channel 1 in mode 3 at 20000 bits per second

      h = pi.spi_open(1, 20000, 3)
      ...
      """
      # I p1 spi_channel
      # I p2 spi_baud
      # I p3 4
      ## extension ##
      # I spi_flags
      extents = [struct.pack("I", spi_flags)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_SPIO, spi_channel, spi_baud, 4, extents))

   def spi_close(self, handle):
      """
      Closes the SPI device associated with handle.

      handle:= >=0 (as returned by a prior call to spi_open).

      ...
      pi.spi_close(h)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_SPIC, handle, 0))

   def spi_read(self, handle, count):
      """
      Reads count bytes from the SPI device associated with handle.

      handle:= >=0 (as returned by a prior call to spi_open).
       count:= >0, the number of bytes to read.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (b, d) = pi.spi_read(h, 60) # read 60 bytes from device h
      if b == 60:
         # process read data
      else:
         # error path
      ...
      """
      bytes = _u2i(_pigpio_command(
         self._control, _PI_CMD_SPIR, handle, count))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def spi_write(self, handle, data):
      """
      Writes the data bytes to the SPI device associated with handle.

      handle:= >=0 (as returned by a prior call to spi_open).
        data:= the bytes to write.

      ...
      pi.spi_write(0, b'\\x02\\xc0\\x80') # write 3 bytes to device 0

      pi.spi_write(0, b'defgh')        # write 5 bytes to device 0

      pi.spi_write(0, "def")           # write 3 bytes to device 0

      pi.spi_write(1, [2, 192, 128])   # write 3 bytes to device 1
      ...
      """
      # I p1 handle
      # I p2 0
      # I p3 len
      ## extension ##
      # s len data bytes
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_SPIW, handle, 0, len(data), [data]))

   def spi_xfer(self, handle, data):
      """
      Writes the data bytes to the SPI device associated with handle,
      returning the data bytes read from the device.

      handle:= >=0 (as returned by a prior call to spi_open).
        data:= the bytes to write.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (count, rx_data) = pi.spi_xfer(h, b'\\x01\\x80\\x00')

      (count, rx_data) = pi.spi_xfer(h, [1, 128, 0])

      (count, rx_data) = pi.spi_xfer(h, b"hello")

      (count, rx_data) = pi.spi_xfer(h, "hello")
      ...
      """
      # I p1 handle
      # I p2 0
      # I p3 len
      ## extension ##
      # s len data bytes
      bytes = _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_SPIX, handle, 0, len(data), [data]))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def serial_open(self, tty, ser_baud, ser_flags=0):
      """
      Returns a handle for the serial tty device opened
      at ser_baud bits per second.

            tty:= the serial device to open.
       ser_baud:= baud rate
      ser_flags:= 0, no flags are currently defined.

      ...
      h1 = pi.serial_open("/dev/ttyAMA0", 300)

      h2 = pi.serial_open("/dev/ttyUSB1", 19200, 0)
      ...
      """
      # I p1 ser_baud
      # I p2 ser_flags
      # I p3 len
      ## extension ##
      # s len data bytes
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_SERO, ser_baud, ser_flags, len(tty), [tty]))

   def serial_close(self, handle):
      """
      Closes the serial device associated with handle.

      handle:= >=0 (as returned by a prior call to serial_open).

      ...
      pi.serial_close(h1)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_SERC, handle, 0))

   def serial_read_byte(self, handle):
      """
      Returns a single byte from the device associated with handle.

      handle:= >=0 (as returned by a prior call to serial_open).

      ...
      b = pi.serial_read_byte(h1)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_SERRB, handle, 0))

   def serial_write_byte(self, handle, byte_val):
      """
      Writes a single byte to the device associated with handle.

        handle:= >=0 (as returned by a prior call to serial_open).
      byte_val:= 0-255, the value to write.

      ...
      pi.serial_write_byte(h1, 23)

      pi.serial_write_byte(h1, ord('Z'))
      ...
      """
      return _u2i(
         _pigpio_command(self._control, _PI_CMD_SERWB, handle, byte_val))

   def serial_read(self, handle, count):
      """
      Reads up to count bytes from the device associated with handle.

      handle:= >=0 (as returned by a prior call to serial_open).
       count:= >0, the number of bytes to read.

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (b, d) = pi.serial_read(h2, 100)
      if b > 0:
         # process read data
      ...
      """
      bytes = _u2i(_pigpio_command(self._control, _PI_CMD_SERR, handle, count))

      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   def serial_write(self, handle, data):
      """
      Writes the data bytes to the device associated with handle.

      handle:= >=0 (as returned by a prior call to serial_open).
        data:= the bytes to write.

      ...
      pi.serial_write(h1, b'\\x02\\x03\\x04')

      pi.serial_write(h2, b'help')

      pi.serial_write(h2, "hello")

      pi.serial_write(h1, [2, 3, 4])
      ...
      """
      # I p1 handle
      # I p2 0
      # I p3 len
      ## extension ##
      # s len data bytes

      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_SERW, handle, 0, len(data), [data]))

   def serial_data_available(self, handle):
      """
      Returns the number of bytes available to be read from the
      device associated with handle.

      handle:= >=0 (as returned by a prior call to serial_open).

      ...
      rdy = pi.serial_data_available(h1)

      if rdy > 0:
         (b, d) = pi.serial_read(h1, rdy)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_SERDA, handle, 0))

   def gpio_trigger(self, user_gpio, pulse_len=10, level=1):
      """
      Send a trigger pulse to a gpio.  The gpio is set to
      level for pulse_len microseconds and then reset to not level.

      user_gpio:= 0-31
      pulse_len:= 1-50
          level:= 0-1

      ...
      pi.gpio_trigger(23, 10, 1)
      ...
      """
      # pigpio message format

      # I p1 user_gpio
      # I p2 pulse_len
      # I p3 4
      ## extension ##
      # I level
      extents = [struct.pack("I", level)]
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_TRIG, user_gpio, pulse_len, 4, extents))

   def store_script(self, script):
      """
      Store a script for later execution.

      script:= the script text as a series of bytes.

      Returns a >=0 script id if OK.

      ...
      sid = pi.store_script(
         b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0')
      ...
      """
      # I p1 0
      # I p2 0
      # I p3 len
      ## extension ##
      # s len data bytes
      if len(script):
         return _u2i(_pigpio_command_ext(
            self._control, _PI_CMD_PROC, 0, 0, len(script), [script]))
      else:
         return 0

   def run_script(self, script_id, params=None):
      """
      Runs a stored script.

      script_id:= id of stored script.
         params:= up to 10 parameters required by the script.

      ...
      s = pi.run_script(sid, [par1, par2])

      s = pi.run_script(sid)

      s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
      ...
      """
      # I p1 script id
      # I p2 0
      # I p3 params * 4 (0-10 params)
      ## (optional) extension ##
      # I[] params
      if params is not None:
         ext = bytearray()
         for p in params:
            ext.extend(struct.pack("I", p))
         nump = len(params)
         extents = [ext]
      else:
         nump = 0
         extents = []
      return _u2i(_pigpio_command_ext(
         self._control, _PI_CMD_PROCR, script_id, 0, nump*4, extents))

   def script_status(self, script_id):
      """
      Returns the run status of a stored script as well as the
      current values of parameters 0 to 9.

      script_id:= id of stored script.

      The run status may be

      . .
      PI_SCRIPT_HALTED
      PI_SCRIPT_RUNNING
      PI_SCRIPT_WAITING
      PI_SCRIPT_FAILED
      . .

      The return value is a tuple of run status and a list of
      the 10 parameters.  On error the run status will be negative
      and the parameter list will be empty.

      ...
      (s, pars) = pi.script_status(sid)
      ...
      """
      status = _u2i(_pigpio_command(self._control, _PI_CMD_PROCP, script_id, 0))
      if status >= 0:
         param = struct.unpack('IIIIIIIIII', self._control.recv(40))
         return status, param
      return status, ()

   def stop_script(self, script_id):
      """
      Stops a running script.

      script_id:= id of stored script.

      ...
      status = pi.stop_script(sid)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PROCS, script_id, 0))

   def delete_script(self, script_id):
      """
      Deletes a stored script.

      script_id:= id of stored script.

      ...
      status = pi.delete_script(sid)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_PROCD, script_id, 0))

   def bb_serial_read_open(self, user_gpio, bb_baud):
      """
      Opens a gpio for bit bang reading of serial data.

      user_gpio:= 0-31, the gpio to use.
        bb_baud:= 300-250000, the baud rate.

      The serial data is held in a cyclic buffer and is read using
      bb_serial_read.

      It is the caller's responsibility to read data from the cyclic
      buffer in a timely fashion.

      ...
      status = pi.bb_serial_read_open(4, 19200)
      status = pi.bb_serial_read_open(17, 9600)
      ...
      """
      return _u2i(_pigpio_command(
         self._control, _PI_CMD_SLRO, user_gpio, bb_baud))

   def bb_serial_read(self, user_gpio):
      """
      Returns data from the bit bang serial cyclic buffer.

      user_gpio:= 0-31 (opened in a prior call to bb_serial_read_open)

      The returned value is a tuple of the number of bytes read and a
      bytearray containing the bytes.  If there was an error the
      number of bytes read will be less than zero (and will contain
      the error code).

      ...
      (count, data) = pi.bb_serial_read(4)
      ...
      """
      bytes = _u2i(_pigpio_command(self._control, _PI_CMD_SLR, user_gpio, 10000))
      if bytes > 0:
         return bytes, self._rxbuf(bytes)
      return bytes, ""

   
   def bb_serial_read_close(self, user_gpio):
      """
      Closes a gpio for bit bang reading of serial data.

      user_gpio:= 0-31 (opened in a prior call to bb_serial_read_open)

      ...
      status = pi.bb_serial_read_close(17)
      ...
      """
      return _u2i(_pigpio_command(self._control, _PI_CMD_SLRC, user_gpio, 0))

   def callback(self, user_gpio, edge=RISING_EDGE, func=None):
      """
      Calls a user supplied function (a callback) whenever the
      specified gpio edge is detected.

      user_gpio:= 0-31.
           edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE.
           func:= user supplied callback function.

      If a user callback is not specified a default tally callback is
      provided which simply counts edges.

      The user supplied callback receives three parameters, the gpio,
      the level, and the tick.

      ...
      def cbf(gpio, level, tick):
         print(gpio, level, tick)

      cb1 = pi.callback(22, pigpio.EITHER_EDGE, cbf)

      cb2 = pi.callback(4, pigpio.EITHER_EDGE)

      cb3 = pi.callback(17)

      print(cb3.tally())
      ...
      """
      return _callback(self._notify, user_gpio, edge, func)

   def wait_for_edge(self, user_gpio, edge=RISING_EDGE, wait_timeout=60.0):
      """
      Wait for an edge event on a gpio.

         user_gpio:= 0-31.
              edge:= EITHER_EDGE, RISING_EDGE (default), or
                     FALLING_EDGE.
      wait_timeout:= 0.0- (default 60.0).

      The function returns as soon as the edge is detected
      or after the number of seconds specified by timeout has
      expired.

      The function returns True if the edge is detected,
      otherwise False.

      ...
      if pi.wait_for_edge(23):
         print("Rising edge detected")
      else:
         print("wait for edge timed out")

      if pi.wait_for_edge(23, pigpio.FALLING_EDGE, 5.0):
         print("Falling edge detected")
      else:
         print("wait for falling edge timed out")
      ...
      """
      a = _wait_for_edge(self._notify, user_gpio, edge, wait_timeout)
      return a.trigger

   def __init__(self,
                host = os.getenv("PIGPIO_ADDR", ''),
                port = os.getenv("PIGPIO_PORT", 8888)):
      """
      Grants access to a Pi's gpios.

      host:= the host name of the Pi on which the pigpio daemon is
             running.  The default is localhost unless overwritten by
             the PIGPIO_ADDR environment variable.
       
      port:= the port number on which the pigpio daemon is listening.
             The default is 8888 unless overwritten by the PIGPIO_PORT
             environment variable.  The pigpio daemon must have been
             started with the same port number.

      This connects to the pigpio daemon and reserves resources
      to be used for sending commands and receiving notifications.

      ...
      pi = pigio.pi()              # use defaults
      pi = pigpio.pi('mypi')       # specify host, default port
      pi = pigpio.pi('mypi', 7777) # specify host and port
      ...
      """
      self.connected = True

      self._control = None
      self._notify  = None

      self._host = ''
      self._port = 8888

      self._host = host
      self._port = int(port)

      self._control = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

      try:
         self._control.connect((self._host, self._port))
         self._notify = _callback_thread(self._control, self._host, self._port)
      except socket.error:
         self.connected = False
         if self._control is not None:
            self._control = None
         if self._host == '':
            h = "localhost"
         else:
            h = self._host
         errStr = "Can't connect to pigpio on " + str(h) + "(" + str(self._port) + ")"
         print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
         print(errStr)
         print("")
         print("Did you start the pigpio daemon? E.g. sudo pigpiod")
         print("")
         print("Did you specify the correct Pi host/port in the environment")
         print("variables PIGPIO_ADDR/PIGPIO_PORT?")
         print("E.g. export PIGPIO_ADDR=soft, export PIGPIO_PORT=8888")
         print("")
         print("Did you specify the correct Pi host/port in the")
         print("pigpio.pi() function? E.g. pigpio.pi('soft', 8888))")
         print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
      else:
         atexit.register(self.stop)

   def stop(self):
      """Release pigpio resources.

      ...
      pi.stop()
      ...
      """

      if self._notify is not None:
         self._notify.stop()
         self._notify = None

      if self._control is not None:
         self._control.close()
         self._control = None

def variables():
   """
   bb_baud: 100 - 250000
   The baud rate used for the transmission of bit bang serial data.

   bit: 0-1
   A value of 0 or 1.

   bits: 32 bit number
   A mask used to select gpios to be operated on.  If bit n is set
   then gpio n is selected.  A convenient way of setting bit n is to
   bit or in the value (1<<n).

   To select gpios 1, 7, 23

   bits = (1<<1) | (1<<7) | (1<<23)

   byte_val: 0-255
   A whole number.

   count:
   The number of bytes of data to be transferred.

   data:
   Data to be transmitted, a series of bytes.

   delay: 1-
   The length of a pulse in microseconds.

   dutycycle: 0-range_
   A number between 0 and range_.  The dutycycle sets the
   proportion of on time versus off time duting each PWM
   cycle.

   0 is off. 
   range_ / 2 is 50% on. 
   range_ is fully on.

   edge: 0-2
   EITHER_EDGE = 2 
   FALLING_EDGE = 1 
   RISING_EDGE = 0

   errnum: <0
   PI_BAD_DUTYCYCLE = -8 
   PI_BAD_DUTYRANGE = -21 
   PI_BAD_FLAGS = -77 
   PI_BAD_GPIO = -3 
   PI_BAD_HANDLE = -25 
   PI_BAD_I2C_ADDR = -75 
   PI_BAD_I2C_BUS = -74 
   PI_BAD_LEVEL = -5 
   PI_BAD_MICS_DELAY = -64 
   PI_BAD_MILS_DELAY = -65 
   PI_BAD_MODE = -4 
   PI_BAD_PARAM = -81 
   PI_BAD_PARAM_NUM = -52 
   PI_BAD_PUD = -6 
   PI_BAD_PULSELEN = -46 
   PI_BAD_PULSEWIDTH = -7 
   PI_BAD_SCRIPT = -47 
   PI_BAD_SCRIPT_CMD = -55 
   PI_BAD_SCRIPT_ID = -48 
   PI_BAD_SERIAL_COUNT = -51 
   PI_BAD_SER_DEVICE = -79 
   PI_BAD_SER_OFFSET = -49 
   PI_BAD_SER_SPEED = -80 
   PI_BAD_SPI_CHANNEL = -76 
   PI_BAD_SPI_COUNT = -84 
   PI_BAD_SPI_SPEED = -78 
   PI_BAD_TAG = -63 
   PI_BAD_USER_GPIO = -2 
   PI_BAD_VAR_NUM = -56 
   PI_BAD_WAVE_BAUD = -35 
   PI_BAD_WAVE_ID = -66 
   PI_BAD_WDOG_TIMEOUT = -15 
   PI_BAD_WVSC_COMMND = -43 
   PI_BAD_WVSM_COMMND = -44 
   PI_BAD_WVSP_COMMND = -45 
   PI_DUP_TAG = -53 
   PI_EMPTY_WAVEFORM = -69 
   PI_GPIO_IN_USE = -50 
   PI_I2C_OPEN_FAILED = -71 
   PI_I2C_READ_FAILED = -83 
   PI_I2C_WRITE_FAILED = -82 
   PI_NOT_HALTED = -62 
   PI_NOT_PERMITTED = -41 
   PI_NOT_SERIAL_GPIO = -38 
   PI_NO_HANDLE = -24 
   PI_NO_MEMORY = -58 
   PI_NO_SCRIPT_ROOM = -57 
   PI_NO_WAVEFORM_ID = -70 
   PI_SER_OPEN_FAILED = -72 
   PI_SER_READ_FAILED = -86 
   PI_SER_READ_NO_DATA = -87 
   PI_SER_WRITE_FAILED = -85 
   PI_SOCK_READ_FAILED = -59 
   PI_SOCK_WRIT_FAILED = -60 
   PI_SOME_PERMITTED = -42 
   PI_SPI_OPEN_FAILED = -73 
   PI_SPI_XFER_FAILED = -89 
   PI_TOO_MANY_CBS = -67 
   PI_TOO_MANY_CHARS = -37 
   PI_TOO_MANY_OOL = -68 
   PI_TOO_MANY_PARAM = -61 
   PI_TOO_MANY_PULSES = -36 
   PI_TOO_MANY_TAGS = -54 
   PI_UNKNOWN_COMMAND = -88 

   frequency: 0-40000
   Defines the frequency to be used for PWM on a gpio.
   The closest permitted frequency will be used.

   func:
   A user supplied callback function.

   gpio: 0-53
   A Broadcom numbered gpio.  All the user gpios are in the range 0-31.

   gpio_off:
   A mask used to select gpios to be operated on.  See [*bits*].

   This mask selects the gpios to be switched off at the start
   of a pulse.

   gpio_on:
   A mask used to select gpios to be operated on.  See [*bits*].

   This mask selects the gpios to be switched on at the start
   of a pulse.

   handle: 0-
   A number referencing an object opened by one of

   [*i2c_open*] 
   [*notify_open*] 
   [*serial_open*] 
   [*spi_open*]

   host:
   The name or IP address of the Pi running the pigpio daemon.

   i2c_address:
   The address of a device on the I2C bus (0x08 - 0x77)

   i2c_bus: 0-1
   An I2C bus number.

   i2c_flags: 32 bit
   No I2C flags are currently defined.

   level: 0-1 (2)
   CLEAR = 0 
   HIGH = 1 
   LOW = 0 
   OFF = 0 
   ON = 1 
   SET = 1 
   TIMEOUT = 2 # only returned for a watchdog timeout

   mode: 0-7
   ALT0 = 4 
   ALT1 = 5 
   ALT2 = 6 
   ALT3 = 7 
   ALT4 = 3 
   ALT5 = 2 
   INPUT = 0 
   OUTPUT = 1

   offset: 0-
   The offset wave data starts from the beginning of the waveform
   being currently defined.

   params: 32 bit number
   When scripts are started they can receive up to 10 parameters
   to define their operation.

   port: 
   The port used by the pigpio daemon, defaults to 8888.

   pud: 0-2
   PUD_DOWN = 1 
   PUD_OFF = 0 
   PUD_UP = 2 

   pulse_len: 1-50
   A whole number.

   pulses:

   pulsewidth:
   The servo pulsewidth in microseconds.  0 switches pulses off.

   range_: 25-40000
   Defines the limits for the [*dutycycle*] parameter.
   range_ defaults tpo 255.

   reg: 0-255
   An I2C devive register.  The usable registers depend on the
   actual device.

   script:
   The text of a script to store on the pigpio daemon.

   script_id: 0-
   A number referencing a script created by [*store_script*].

   ser_baud:
   The transmission rate in bits per second.  The default
   allowable values are 50, 75, 110, 134, 150, 200, 300,
   600, 1200, 1800, 2400, 4800, 9600, 19200, 38400,
   57600, 115200, or 230400.

   ser_flags: 32 bit
   No serial flags are currently defined.

   spi_baud: 1-
   The transmission rate in bits per second.

   spi_channel: 0-1
   A SPI channel.

   spi_flags: 32 bit
   The flags are used to encode the SPI mode in bits 0 and 1.

   t1:
   A tick (earlier).

   t2:
   A tick (later).

   tty:
   A Pi serial tty device, e.g. /dev/ttyAMA0, /dev/ttyUSB0

   user_gpio: 0-31
   A Broadcom numbered gpio.  All the user gpios are in the range 0-31.
   Not all the gpios within this range are usable, some are reserved
   for system use.

   wait_timeout: 0.0 -
   The number of seconds to wait in wait_for_edge before timing out.

   wave_id: 0-
   A number referencing a wave created by [*wave_create*].

   wdog_timeout: 0-60000
   Defines a gpio watchdog timeout in milliseconds.  If no level
   change is detected on the gpio for timeout millisecond a watchdog
   timeout report is issued (with level TIMEOUT).

   word_val: 0-65535
   A whole number.
   """
   pass