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
#![deny(missing_docs, unsafe_code)] use super::{BitMode, DeviceType, FtStatus, FtdiCommon, TimeoutError}; use std::convert::From; use std::time::Duration; /// MPSSE opcodes. /// /// Exported for use by [`mpsse`] macro. May also be used for manual command array construction. /// /// Data clocking MPSSE commands are broken out into separate enums for API ergonomics: /// * [`ClockDataOut`] /// * [`ClockBitsOut`] /// * [`ClockDataIn`] /// * [`ClockBitsIn`] /// * [`ClockData`] #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u8)] #[non_exhaustive] pub enum MpsseCmd { /// Used by [`set_gpio_lower`][`MpsseCmdBuilder::set_gpio_lower`]. SetDataBitsLowbyte = 0x80, /// Used by [`gpio_lower`][`MpsseCmdBuilder::gpio_lower`]. GetDataBitsLowbyte = 0x81, /// Used by [`set_gpio_upper`][`MpsseCmdBuilder::set_gpio_upper`]. SetDataBitsHighbyte = 0x82, /// Used by [`gpio_upper`][`MpsseCmdBuilder::gpio_upper`]. GetDataBitsHighbyte = 0x83, /// Used by [`enable_loopback`][`MpsseCmdBuilder::enable_loopback`]. EnableLoopback = 0x84, /// Used by [`disable_loopback`][`MpsseCmdBuilder::disable_loopback`]. DisableLoopback = 0x85, /// Used by [`set_clock`][`MpsseCmdBuilder::set_clock`]. SetClockFrequency = 0x86, /// Used by [`send_immediate`][`MpsseCmdBuilder::send_immediate`]. SendImmediate = 0x87, /// Used by [`wait_on_io_high`][`MpsseCmdBuilder::wait_on_io_high`]. WaitOnIOHigh = 0x88, /// Used by [`wait_on_io_low`][`MpsseCmdBuilder::wait_on_io_low`]. WaitOnIOLow = 0x89, /// Used by [`set_clock`][`MpsseCmdBuilder::set_clock`]. DisableClockDivide = 0x8A, /// Used by [`set_clock`][`MpsseCmdBuilder::set_clock`]. EnableClockDivide = 0x8B, /// Used by [`enable_3phase_data_clocking`][`MpsseCmdBuilder::enable_3phase_data_clocking`]. Enable3PhaseClocking = 0x8C, /// Used by [`disable_3phase_data_clocking`][`MpsseCmdBuilder::disable_3phase_data_clocking`]. Disable3PhaseClocking = 0x8D, // EnableDriveOnlyZero = 0x9E, } /// Modes for clocking data out of the FTDI device. /// /// This is an argument to the [`clock_data_out`] method. /// /// [`clock_data_out`]: MpsseCmdBuilder::clock_data_out #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockDataOut { /// Positive clock edge MSB first. /// /// The data is sent MSB first. /// /// The data will change to the next bit on the rising edge of the CLK pin. MsbPos = 0x10, /// Negative clock edge MSB first. /// /// The data is sent MSB first. /// /// The data will change to the next bit on the falling edge of the CLK pin. MsbNeg = 0x11, /// Positive clock edge LSB first. /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will change to the next bit on the rising edge of the CLK pin. LsbPos = 0x18, /// Negative clock edge LSB first. /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will change to the next bit on the falling edge of the CLK pin. LsbNeg = 0x19, } impl From<ClockDataOut> for u8 { fn from(value: ClockDataOut) -> u8 { value as u8 } } /// Modes for clocking bits out of the FTDI device. /// /// This is an argument to the [`clock_bits_out`] method. /// /// [`clock_bits_out`]: MpsseCmdBuilder::clock_bits_out #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockBitsOut { /// Positive clock edge MSB first. /// /// The data is sent MSB first (bit 7 first). /// /// The data will change to the next bit on the rising edge of the CLK pin. MsbPos = 0x12, /// Negative clock edge MSB first. /// /// The data is sent MSB first (bit 7 first). /// /// The data will change to the next bit on the falling edge of the CLK pin. MsbNeg = 0x13, /// Positive clock edge LSB first (bit 0 first). /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will change to the next bit on the rising edge of the CLK pin. LsbPos = 0x1A, /// Negative clock edge LSB first (bit 0 first). /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will change to the next bit on the falling edge of the CLK pin. LsbNeg = 0x1B, } impl From<ClockBitsOut> for u8 { fn from(value: ClockBitsOut) -> u8 { value as u8 } } /// Modes for clocking data into the FTDI device. /// /// This is an argument to the [`clock_data_in`] method. /// /// [`clock_data_in`]: MpsseCmdBuilder::clock_data_in #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockDataIn { /// Positive clock edge MSB first. /// /// The first bit in will be the MSB of the first byte and so on. /// /// The data will be sampled on the rising edge of the CLK pin. MsbPos = 0x20, /// Negative clock edge MSB first. /// /// The first bit in will be the MSB of the first byte and so on. /// /// The data will be sampled on the falling edge of the CLK pin. MsbNeg = 0x24, /// Positive clock edge LSB first. /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will be sampled on the rising edge of the CLK pin. LsbPos = 0x28, /// Negative clock edge LSB first. /// /// The first bit in will be the LSB of the first byte and so on. /// /// The data will be sampled on the falling edge of the CLK pin. LsbNeg = 0x2C, } impl From<ClockDataIn> for u8 { fn from(value: ClockDataIn) -> u8 { value as u8 } } /// Modes for clocking data bits into the FTDI device. /// /// This is an argument to the [`clock_bits_in`] method. /// /// [`clock_bits_in`]: MpsseCmdBuilder::clock_bits_in #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockBitsIn { /// Positive clock edge MSB first. /// /// The data will be shifted up so that the first bit in may not be in bit 7 /// but from 6 downwards depending on the number of bits to shift /// (i.e. a length of 1 bit will have the data bit sampled in bit 0 of the /// byte sent back to the PC). /// /// The data will be sampled on the rising edge of the CLK pin. MsbPos = 0x22, /// Negative clock edge MSB first. /// /// The data will be shifted up so that the first bit in may not be in bit 7 /// but from 6 downwards depending on the number of bits to shift /// (i.e. a length of 1 bit will have the data bit sampled in bit 0 of the /// byte sent back to the PC). /// /// The data will be sampled on the falling edge of the CLK pin. MsbNeg = 0x26, /// Positive clock edge LSB first. /// /// The data will be shifted down so that the first bit in may not be in bit /// 0 but from 1 upwards depending on the number of bits to shift /// (i.e. a length of 1 bit will have the data bit sampled in bit 7 of the /// byte sent back to the PC). /// /// The data will be sampled on the rising edge of the CLK pin. LsbPos = 0x2A, /// Negative clock edge LSB first. /// /// The data will be shifted down so that thefirst bit in may not be in bit /// 0 but from 1 upwards depending on the number of bits to shift /// (i.e. a length of 1 bit will have the data bit sampled in bit 7 of the /// byte sent back to the PC). /// /// The data will be sampled on the falling edge of the CLK pin. LsbNeg = 0x2E, } impl From<ClockBitsIn> for u8 { fn from(value: ClockBitsIn) -> u8 { value as u8 } } /// Modes for clocking data in and out of the FTDI device. /// /// This is an argument to the [`clock_data`] method. /// /// [`clock_data`]: MpsseCmdBuilder::clock_data #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockData { /// MSB first, data in on positive edge, data out on negative edge. MsbPosIn = 0x31, /// MSB first, data in on negative edge, data out on positive edge. MsbNegIn = 0x34, /// LSB first, data in on positive edge, data out on negative edge. LsbPosIn = 0x39, /// LSB first, data in on negative edge, data out on positive edge. LsbNegIn = 0x3C, } impl From<ClockData> for u8 { fn from(value: ClockData) -> u8 { value as u8 } } /// Modes for clocking data bits in and out of the FTDI device. /// /// This is an argument to the [`clock_bits`] method. /// /// [`clock_bits`]: MpsseCmdBuilder::clock_bits #[repr(u8)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ClockBits { /// MSB first, data in on positive edge, data out on negative edge. MsbPosIn = 0x33, /// MSB first, data in on negative edge, data out on positive edge. MsbNegIn = 0x36, /// LSB first, data in on positive edge, data out on negative edge. LsbPosIn = 0x3B, /// LSB first, data in on negative edge, data out on positive edge. LsbNegIn = 0x3E, } impl From<ClockBits> for u8 { fn from(value: ClockBits) -> u8 { value as u8 } } // seemingly arbitrary values from libmpsse // const ECHO_CMD_1: u8 = 0xAA; const ECHO_CMD_2: u8 = 0xAB; impl From<MpsseCmd> for u8 { fn from(value: MpsseCmd) -> Self { value as u8 } } fn check_limits(device: DeviceType, frequency: u32, max: u32) { const MIN: u32 = 92; assert!( frequency >= MIN, "frequency of {} exceeds minimum of {} for {:?}", frequency, MIN, device ); assert!( frequency <= max, "frequency of {} exceeds maximum of {} for {:?}", frequency, max, device ); } // calculate the clock divisor from a frequency fn clock_divisor(device: DeviceType, frequency: u32) -> (u32, Option<MpsseCmd>) { match device { // FT2232D appears as FT2232C in FTD2XX DeviceType::FT2232C => { check_limits(device, frequency, 6_000_000); (6_000_000 / frequency - 1, None) } DeviceType::FT2232H | DeviceType::FT4232H | DeviceType::FT232H => { check_limits(device, frequency, 30_000_000); if frequency <= 6_000_000 { (6_000_000 / frequency - 1, Some(MpsseCmd::EnableClockDivide)) } else { ( 30_000_000 / frequency - 1, Some(MpsseCmd::DisableClockDivide), ) } } _ => panic!("Unknown device type: {:?}", device), } } #[cfg(test)] mod clock_divisor { use super::*; macro_rules! pos { ($NAME:ident, $DEVICE:expr, $FREQ:expr, $OUT:expr) => { #[test] fn $NAME() { assert_eq!(clock_divisor($DEVICE, $FREQ), $OUT); } }; } macro_rules! neg { ($NAME:ident, $DEVICE:expr, $FREQ:expr) => { #[test] #[should_panic] fn $NAME() { clock_divisor($DEVICE, $FREQ); } }; } pos!(ft232c_min, DeviceType::FT2232C, 92, (65216, None)); pos!(ft232c_max, DeviceType::FT2232C, 6_000_000, (0, None)); pos!( min, DeviceType::FT2232H, 92, (65216, Some(MpsseCmd::EnableClockDivide)) ); pos!( max_with_div, DeviceType::FT2232H, 6_000_000, (0, Some(MpsseCmd::EnableClockDivide)) ); pos!( min_without_div, DeviceType::FT2232H, 6_000_001, (3, Some(MpsseCmd::DisableClockDivide)) ); pos!( max, DeviceType::FT4232H, 30_000_000, (0, Some(MpsseCmd::DisableClockDivide)) ); neg!(panic_unknown, DeviceType::Unknown, 1_000); neg!(panic_ft232c_min, DeviceType::FT2232C, 91); neg!(panic_ft232c_max, DeviceType::FT2232C, 6_000_001); neg!(panic_min, DeviceType::FT232H, 91); neg!(panic_max, DeviceType::FT232H, 30_000_001); } /// Initialization settings for the MPSSE. /// /// Used by [`initialize_mpsse`]. /// /// [`initialize_mpsse`]: FtdiMpsse::initialize_mpsse #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct MpsseSettings { /// Reset the MPSSE on initialization. /// /// This calls [`reset`] if `true`. /// /// [`reset`]: FtdiCommon::reset pub reset: bool, /// USB in transfer size in bytes. /// /// This gets passed to [`set_usb_parameters`]. /// /// [`set_usb_parameters`]: FtdiCommon::set_usb_parameters pub in_transfer_size: u32, /// Read timeout. /// /// This gets passed along with [`write_timeout`] to [`set_timeouts`]. /// /// [`set_timeouts`]: FtdiCommon::set_timeouts /// [`write_timeout`]: MpsseSettings::write_timeout pub read_timeout: Duration, /// Write timeout. /// /// This gets passed along with [`read_timeout`] to [`set_timeouts`]. /// /// [`set_timeouts`]: FtdiCommon::set_timeouts /// [`read_timeout`]: MpsseSettings::read_timeout pub write_timeout: Duration, /// Latency timer. /// /// This gets passed to [`set_latency_timer`]. /// /// [`set_latency_timer`]: FtdiCommon::set_latency_timer pub latency_timer: Duration, /// Bitmode mask. /// /// * A bit value of `0` sets the corresponding pin to an input. /// * A bit value of `1` sets the corresponding pin to an output. /// /// This gets passed to [`set_bit_mode`]. /// /// [`set_bit_mode`]: FtdiCommon::set_bit_mode pub mask: u8, /// Clock frequency. /// /// If not `None` this will call [`set_clock`] to set the clock frequency. /// /// [`set_clock`]: crate::FtdiMpsse::set_clock pub clock_frequency: Option<u32>, } impl std::default::Default for MpsseSettings { fn default() -> Self { MpsseSettings { reset: true, in_transfer_size: 4096, read_timeout: Duration::from_secs(1), write_timeout: Duration::from_secs(1), latency_timer: Duration::from_millis(16), mask: 0x00, clock_frequency: None, } } } /// FTDI Multi-Protocol Synchronous Serial Engine (MPSSE). /// /// For details about the MPSSE read the [FTDI MPSSE Basics]. /// /// [FTDI MPSSE Basics]: https://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_Basics.pdf pub trait FtdiMpsse: FtdiCommon { /// Set the clock frequency. /// /// # Frequency Limits /// /// | Device Type | Minimum | Maximum | /// |--------------------------|---------|---------| /// | FT2232D | 92 Hz | 6 MHz | /// | FT4232H, FT2232H, FT232H | 92 Hz | 30 MHz | /// /// Values outside of these limits will result in panic. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft4232h, FtdiMpsse}; /// /// let mut ft = Ft4232h::with_serial_number("FT4PWSEOA")?; /// ft.initialize_mpsse_default()?; /// ft.set_clock(100_000)?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn set_clock(&mut self, frequency: u32) -> Result<(), TimeoutError> { let (value, divisor) = clock_divisor(Self::DEVICE_TYPE, frequency); debug_assert!(value <= 0xFFFF); let mut buf: Vec<u8> = Vec::new(); if let Some(div) = divisor { buf.push(div.into()); }; buf.push(MpsseCmd::SetClockFrequency.into()); buf.push((value & 0xFF) as u8); buf.push(((value >> 8) & 0xFF) as u8); self.write_all(&buf.as_slice()) } /// Initialize the MPSSE. /// /// This method does the following: /// /// 1. Optionally [`reset`]s the device. /// 2. Sets USB transfer sizes using values provided. /// 3. Disables special characters. /// 4. Sets the transfer timeouts using values provided. /// 5. Sets latency timers using values provided. /// 6. Sets the flow control to RTS CTS. /// 7. Resets the bitmode, then sets it to MPSSE. /// 8. Enables loopback. /// 9. Synchronizes the MPSSE. /// 10. Disables loopback. /// 11. Optionally sets the clock frequency. /// /// Upon failure cleanup is not guaranteed. /// /// # Example /// /// Initialize the MPSSE with a 5 second read timeout. /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse, MpsseSettings}; /// use std::time::Duration; /// /// let mut settings = MpsseSettings::default(); /// settings.read_timeout = Duration::from_secs(5); /// let mut ft = Ft232h::with_serial_number("FT59UO4C")?; /// ft.initialize_mpsse(&settings)?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` /// /// [`reset`]: FtdiCommon::reset fn initialize_mpsse(&mut self, settings: &MpsseSettings) -> Result<(), TimeoutError> { if settings.reset { self.reset()?; } self.purge_rx()?; debug_assert_eq!(self.queue_status()?, 0); self.set_usb_parameters(settings.in_transfer_size)?; self.set_chars(0, false, 0, false)?; self.set_timeouts(settings.read_timeout, settings.write_timeout)?; self.set_latency_timer(settings.latency_timer)?; self.set_flow_control_rts_cts()?; self.set_bit_mode(0x0, BitMode::Reset)?; self.set_bit_mode(settings.mask, BitMode::Mpsse)?; self.enable_loopback()?; self.synchronize_mpsse()?; // bundle the disable loopback and clock divisor writes together // to save some time let mut mpsse_cmd = MpsseCmdBuilder::new().disable_loopback(); if let Some(frequency) = settings.clock_frequency { mpsse_cmd = mpsse_cmd.set_clock(frequency, Self::DEVICE_TYPE); } self.write_all(mpsse_cmd.as_slice())?; Ok(()) } /// Initializes the MPSSE to default settings. /// /// This simply calles [`initialize_mpsse`] with the default /// [`MpsseSettings`]. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT59UO4C")?; /// ft.initialize_mpsse_default()?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` /// /// [`initialize_mpsse`]: FtdiMpsse::initialize_mpsse fn initialize_mpsse_default(&mut self) -> Result<(), TimeoutError> { self.initialize_mpsse(&MpsseSettings::default()) } /// Synchronize the MPSSE port with the application. /// /// There are various implementations of the synchronization flow, this /// uses the flow from [FTDI MPSSE Basics]. /// /// [FTDI MPSSE Basics]: https://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_Basics.pdf fn synchronize_mpsse(&mut self) -> Result<(), TimeoutError> { self.purge_rx()?; debug_assert_eq!(self.queue_status()?, 0); self.write_all(&[ECHO_CMD_2])?; // the FTDI MPSSE basics polls the queue status here // we purged the RX buffer so the response should always be 2 bytes // this allows us to leverage the timeout built into read let mut buf: [u8; 2] = [0; 2]; self.read_all(&mut buf)?; if buf[0] == 0xFA && buf[1] == ECHO_CMD_2 { Ok(()) } else { Err(TimeoutError::from(FtStatus::OTHER_ERROR)) } } /// Enable the MPSSE loopback state. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft4232h, FtdiMpsse}; /// /// let mut ft = Ft4232h::with_serial_number("FT4PWSEOA")?; /// ft.initialize_mpsse_default()?; /// ft.enable_loopback()?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn enable_loopback(&mut self) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::EnableLoopback.into()]) } /// Disable the MPSSE loopback state. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft4232h, FtdiMpsse}; /// /// let mut ft = Ft4232h::with_serial_number("FT4PWSEOA")?; /// ft.initialize_mpsse_default()?; /// ft.disable_loopback()?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn disable_loopback(&mut self) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::DisableLoopback.into()]) } /// Set the pin direction and state of the lower byte (0-7) GPIO pins on the /// MPSSE interface. /// /// The pins that this controls depends on the device. /// /// * On the FT232H this will control the AD0-AD7 pins. /// /// # Arguments /// /// * `state` - GPIO state mask, `0` is low (or input pin), `1` is high. /// * `direction` - GPIO direction mask, `0` is input, `1` is output. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.set_gpio_lower(0xFF, 0xFF)?; /// ft.set_gpio_lower(0x00, 0xFF)?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn set_gpio_lower(&mut self, state: u8, direction: u8) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::SetDataBitsLowbyte.into(), state, direction]) } /// Get the pin state state of the lower byte (0-7) GPIO pins on the MPSSE /// interface. /// /// # Example /// /// Set the first GPIO, without modify the state of the other GPIOs. /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT59UO4C")?; /// ft.initialize_mpsse_default()?; /// let mut gpio_state: u8 = ft.gpio_lower()?; /// gpio_state |= 0x01; /// ft.set_gpio_lower(gpio_state, 0xFF)?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn gpio_lower(&mut self) -> Result<u8, TimeoutError> { self.write_all(&[ MpsseCmd::GetDataBitsLowbyte.into(), MpsseCmd::SendImmediate.into(), ])?; let mut buf: [u8; 1] = [0]; self.read_all(&mut buf)?; Ok(buf[0]) } /// Set the pin direction and state of the upper byte (8-15) GPIO pins on /// the MPSSE interface. /// /// The pins that this controls depends on the device. /// This method may do nothing for some devices, such as the FT4232H that /// only have 8 pins per port. /// /// See [`set_gpio_lower`] for an example. /// /// # Arguments /// /// * `state` - GPIO state mask, `0` is low (or input pin), `1` is high. /// * `direction` - GPIO direction mask, `0` is input, `1` is output. /// /// # FT232H Corner Case /// /// On the FT232H only CBUS5, CBUS6, CBUS8, and CBUS9 can be controlled. /// These pins confusingly map to the first four bits in the direction and /// state masks. /// /// [`set_gpio_lower`]: FtdiMpsse::set_gpio_lower fn set_gpio_upper(&mut self, state: u8, direction: u8) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::SetDataBitsHighbyte.into(), state, direction]) } /// Get the pin state state of the upper byte (8-15) GPIO pins on the MPSSE /// interface. /// /// See [`gpio_lower`] for an example. /// /// See [`set_gpio_upper`] for additional information about physical pin /// mappings. /// /// [`gpio_lower`]: FtdiMpsse::gpio_lower /// [`set_gpio_upper`]: FtdiMpsse::set_gpio_upper fn gpio_upper(&mut self) -> Result<u8, TimeoutError> { self.write_all(&[ MpsseCmd::GetDataBitsHighbyte.into(), MpsseCmd::SendImmediate.into(), ])?; let mut buf: [u8; 1] = [0]; self.read_all(&mut buf)?; Ok(buf[0]) } /// Clock data out. /// /// This will clock out bytes on TDI/DO. /// No data is clocked into the device on TDO/DI. /// /// # Example /// /// ```no_run /// use libftd2xx::{ClockDataOut, Ft232h, FtdiMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.set_clock(100_000)?; /// ft.set_gpio_lower(0xFA, 0xFB)?; /// ft.set_gpio_lower(0xF2, 0xFB)?; /// ft.clock_data_out(ClockDataOut::MsbNeg, &[0x12, 0x34, 0x56])?; /// ft.set_gpio_lower(0xFA, 0xFB)?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn clock_data_out(&mut self, mode: ClockDataOut, data: &[u8]) -> Result<(), TimeoutError> { let mut len = data.len(); if len == 0 { return Ok(()); } len -= 1; assert!(len <= 65536); let mut payload = vec![mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8]; payload.extend_from_slice(&data); self.write_all(&payload.as_slice()) } /// Clock data in. /// /// This will clock in bytes on TDO/DI. /// No data is clocked out of the device on TDI/DO. fn clock_data_in(&mut self, mode: ClockDataIn, data: &mut [u8]) -> Result<(), TimeoutError> { let mut len = data.len(); if len == 0 { return Ok(()); } len -= 1; assert!(len <= 65536); self.write_all(&[mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8])?; self.read_all(data) } /// Clock data in and out at the same time. fn clock_data(&mut self, mode: ClockData, data: &mut [u8]) -> Result<(), TimeoutError> { let mut len = data.len(); if len == 0 { return Ok(()); } len -= 1; assert!(len <= 65536); let mut payload = vec![mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8]; payload.extend_from_slice(&data); self.write_all(&payload.as_slice())?; self.read_all(data) } } /// This contains MPSSE commands that are only available on the the FT232H, /// FT2232H, and FT4232H devices. /// /// For details about the MPSSE read the [FTDI MPSSE Basics]. /// /// [FTDI MPSSE Basics]: https://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_Basics.pdf pub trait Ftx232hMpsse: FtdiMpsse { /// Enable 3 phase data clocking. /// /// This will give a 3 stage data shift for the purposes of supporting /// interfaces such as I2C which need the data to be valid on both edges of /// the clock. /// /// It will appears as: /// /// 1. Data setup for 1/2 clock period /// 2. Pulse clock for 1/2 clock period /// 3. Data hold for 1/2 clock period /// /// # Example /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse, Ftx232hMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.enable_3phase_data_clocking()?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn enable_3phase_data_clocking(&mut self) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::Enable3PhaseClocking.into()]) } /// Disable 3 phase data clocking. /// /// This will give a 2 stage data shift which is the default state. /// /// It will appears as: /// /// 1. Data setup for 1/2 clock period /// 2. Pulse clock for 1/2 clock period /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiMpsse, Ftx232hMpsse}; /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.disable_3phase_data_clocking()?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` fn disable_3phase_data_clocking(&mut self) -> Result<(), TimeoutError> { self.write_all(&[MpsseCmd::Disable3PhaseClocking.into()]) } } /// FTDI Multi-Protocol Synchronous Serial Engine (MPSSE) command builder. /// /// For details about the MPSSE read the [FTDI MPSSE Basics]. /// /// This structure is a `Vec<u8>` that the methods push bytewise commands onto. /// These commands can then be written to the device with the [`write_all`] /// method. /// /// This is useful for creating commands that need to do multiple operations /// quickly, since individual [`write_all`] calls can be expensive. /// For example, this can be used to set a GPIO low and clock data out for /// SPI operations. /// /// If dynamic command layout is not required, the [`mpsse`] macro can build /// command `[u8; N]` arrays at compile-time. /// /// [FTDI MPSSE Basics]: https://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_Basics.pdf /// [`write_all`]: FtdiCommon::write_all pub struct MpsseCmdBuilder(pub Vec<u8>); impl MpsseCmdBuilder { /// Create a new command builder. /// /// # Example /// /// ``` /// use libftd2xx::MpsseCmdBuilder; /// /// MpsseCmdBuilder::new(); /// ``` pub const fn new() -> MpsseCmdBuilder { MpsseCmdBuilder(Vec::new()) } /// Create a new command builder from a vector. /// /// # Example /// /// ``` /// use libftd2xx::MpsseCmdBuilder; /// /// MpsseCmdBuilder::with_vec(Vec::new()); /// ``` pub const fn with_vec(vec: Vec<u8>) -> MpsseCmdBuilder { MpsseCmdBuilder(vec) } /// Get the MPSSE command as a slice. /// /// # Example /// /// ```no_run /// use libftd2xx::{DeviceType, Ft232h, FtdiCommon, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().set_clock(100_000, DeviceType::FT232H); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn as_slice(&self) -> &[u8] { self.0.as_slice() } /// Set the clock frequency. /// /// # Frequency Limits /// /// | Device Type | Minimum | Maximum | /// |--------------------------|---------|---------| /// | FT2232D | 92 Hz | 6 MHz | /// | FT4232H, FT2232H, FT232H | 92 Hz | 30 MHz | /// /// Values outside of these limits will result in panic. /// /// # Example /// /// ```no_run /// use libftd2xx::{DeviceType, Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new() /// .set_clock(100_000, DeviceType::FT232H) /// .set_gpio_lower(0xFF, 0xFF); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn set_clock(mut self, frequency: u32, device_type: DeviceType) -> Self { let (value, divisor) = clock_divisor(device_type, frequency); debug_assert!(value <= 0xFFFF); if let Some(div) = divisor { self.0.push(div.into()); }; self.0.push(MpsseCmd::SetClockFrequency.into()); self.0.push((value & 0xFF) as u8); self.0.push(((value >> 8) & 0xFF) as u8); self } /// Enable the MPSSE loopback state. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().enable_loopback(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn enable_loopback(mut self) -> Self { self.0.push(MpsseCmd::EnableLoopback.into()); self } /// Disable the MPSSE loopback state. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().disable_loopback(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn disable_loopback(mut self) -> Self { self.0.push(MpsseCmd::DisableLoopback.into()); self } /// Disable 3 phase data clocking. /// /// This is only avaliable on FTx232H devices. /// /// This will give a 2 stage data shift which is the default state. /// /// It will appears as: /// /// 1. Data setup for 1/2 clock period /// 2. Pulse clock for 1/2 clock period /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().disable_3phase_data_clocking(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn disable_3phase_data_clocking(mut self) -> Self { self.0.push(MpsseCmd::Disable3PhaseClocking.into()); self } /// Enable 3 phase data clocking. /// /// This is only avaliable on FTx232H devices. /// /// This will give a 3 stage data shift for the purposes of supporting /// interfaces such as I2C which need the data to be valid on both edges of /// the clock. /// /// It will appears as: /// /// 1. Data setup for 1/2 clock period /// 2. Pulse clock for 1/2 clock period /// 3. Data hold for 1/2 clock period /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().enable_3phase_data_clocking(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn enable_3phase_data_clocking(mut self) -> Self { self.0.push(MpsseCmd::Enable3PhaseClocking.into()); self } /// Set the pin direction and state of the lower byte (0-7) GPIO pins on the /// MPSSE interface. /// /// The pins that this controls depends on the device. /// /// * On the FT232H this will control the AD0-AD7 pins. /// /// # Arguments /// /// * `state` - GPIO state mask, `0` is low (or input pin), `1` is high. /// * `direction` - GPIO direction mask, `0` is input, `1` is output. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new() /// .set_gpio_lower(0xFF, 0xFF) /// .set_gpio_lower(0x00, 0xFF); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn set_gpio_lower(mut self, state: u8, direction: u8) -> Self { self.0 .extend_from_slice(&[MpsseCmd::SetDataBitsLowbyte.into(), state, direction]); self } /// Set the pin direction and state of the upper byte (8-15) GPIO pins on /// the MPSSE interface. /// /// The pins that this controls depends on the device. /// This method may do nothing for some devices, such as the FT4232H that /// only have 8 pins per port. /// /// # Arguments /// /// * `state` - GPIO state mask, `0` is low (or input pin), `1` is high. /// * `direction` - GPIO direction mask, `0` is input, `1` is output. /// /// # FT232H Corner Case /// /// On the FT232H only CBUS5, CBUS6, CBUS8, and CBUS9 can be controlled. /// These pins confusingly map to the first four bits in the direction and /// state masks. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new() /// .set_gpio_upper(0xFF, 0xFF) /// .set_gpio_upper(0x00, 0xFF); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn set_gpio_upper(mut self, state: u8, direction: u8) -> Self { self.0 .extend_from_slice(&[MpsseCmd::SetDataBitsHighbyte.into(), state, direction]); self } /// Get the pin state state of the lower byte (0-7) GPIO pins on the MPSSE /// interface. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().gpio_lower().send_immediate(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// let mut buf: [u8; 1] = [0; 1]; /// ft.read_all(&mut buf)?; /// println!("GPIO lower state: 0x{:02X}", buf[0]); /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` pub fn gpio_lower(mut self) -> Self { self.0.push(MpsseCmd::GetDataBitsLowbyte.into()); self } /// Get the pin state state of the upper byte (8-15) GPIO pins on the MPSSE /// interface. /// /// See [`set_gpio_upper`] for additional information about physical pin /// mappings. /// /// # Example /// /// ```no_run /// use libftd2xx::{Ft232h, FtdiCommon, FtdiMpsse, MpsseCmdBuilder}; /// /// let cmd = MpsseCmdBuilder::new().gpio_upper().send_immediate(); /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(cmd.as_slice())?; /// let mut buf: [u8; 1] = [0; 1]; /// ft.read_all(&mut buf)?; /// println!("GPIO upper state: 0x{:02X}", buf[0]); /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` /// /// [`set_gpio_upper`]: FtdiMpsse::set_gpio_upper pub fn gpio_upper(mut self) -> Self { self.0.push(MpsseCmd::GetDataBitsHighbyte.into()); self } /// Send the preceding commands immediately. /// /// # Example /// /// ``` /// use libftd2xx::MpsseCmdBuilder; /// /// let cmd = MpsseCmdBuilder::new() /// .set_gpio_upper(0xFF, 0xFF) /// .set_gpio_upper(0x00, 0xFF) /// .send_immediate(); /// ``` pub fn send_immediate(mut self) -> Self { self.0.push(MpsseCmd::SendImmediate.into()); self } /// Make controller wait until GPIOL1 or I/O1 is high before running further commands. /// /// # Example /// /// ``` /// use libftd2xx::{ClockData, MpsseCmdBuilder}; /// /// // Assume a "chip ready" signal is connected to GPIOL1. This signal is pulled high /// // shortly after AD3 (chip select) is pulled low. Data will not be clocked out until /// // the chip is ready. /// let cmd = MpsseCmdBuilder::new() /// .set_gpio_lower(0x0, 0xb) /// .wait_on_io_high() /// .clock_data(ClockData::MsbPosIn, &[0x12, 0x34, 0x56]) /// .set_gpio_lower(0x8, 0xb) /// .send_immediate(); /// ``` pub fn wait_on_io_high(mut self) -> Self { self.0.push(MpsseCmd::WaitOnIOHigh.into()); self } /// Make controller wait until GPIOL1 or I/O1 is low before running further commands. /// /// # Example /// /// ``` /// use libftd2xx::{ClockData, MpsseCmdBuilder}; /// /// // Assume a "chip ready" signal is connected to GPIOL1. This signal is pulled low /// // shortly after AD3 (chip select) is pulled low. Data will not be clocked out until /// // the chip is ready. /// let cmd = MpsseCmdBuilder::new() /// .set_gpio_lower(0x0, 0xb) /// .wait_on_io_low() /// .clock_data(ClockData::MsbPosIn, &[0x12, 0x34, 0x56]) /// .set_gpio_lower(0x8, 0xb) /// .send_immediate(); /// ``` pub fn wait_on_io_low(mut self) -> Self { self.0.push(MpsseCmd::WaitOnIOLow.into()); self } /// Clock data out. /// /// This will clock out bytes on TDI/DO. /// No data is clocked into the device on TDO/DI. /// /// This will panic for data lengths greater than `u16::MAX + 1`. pub fn clock_data_out(mut self, mode: ClockDataOut, data: &[u8]) -> Self { let mut len = data.len(); assert!(len <= 65536, "data length cannot exceed u16::MAX + 1"); if len == 0 { return self; } len -= 1; self.0 .extend_from_slice(&[mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8]); self.0.extend_from_slice(&data); self } /// Clock data in. /// /// This will clock in bytes on TDO/DI. /// No data is clocked out of the device on TDI/DO. /// /// # Arguments /// /// * `mode` - Data clocking mode. /// * `len` - Number of bytes to clock in. /// This will panic for values greater than `u16::MAX + 1`. pub fn clock_data_in(mut self, mode: ClockDataIn, mut len: usize) -> Self { assert!(len <= 65536, "data length cannot exceed u16::MAX + 1"); if len == 0 { return self; } len -= 1; self.0 .extend_from_slice(&[mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8]); self } /// Clock data in and out simultaneously. /// /// This will panic for data lengths greater than `u16::MAX + 1`. pub fn clock_data(mut self, mode: ClockData, data: &[u8]) -> Self { let mut len = data.len(); assert!(len <= 65536, "data length cannot exceed u16::MAX + 1"); if len == 0 { return self; } len -= 1; self.0 .extend_from_slice(&[mode.into(), (len & 0xFF) as u8, ((len >> 8) & 0xFF) as u8]); self.0.extend_from_slice(&data); self } /// Clock data bits out. /// /// # Arguments /// /// * `mode` - Bit clocking mode. /// * `data` - Data bits. /// * `len` - Number of bits to clock out. /// This will panic for values greater than 8. pub fn clock_bits_out(mut self, mode: ClockBitsOut, data: u8, mut len: u8) -> Self { assert!(len <= 8, "data length cannot exceed 8"); if len == 0 { return self; } len -= 1; self.0.extend_from_slice(&[mode.into(), len, data]); self } /// Clock data bits in. /// /// # Arguments /// /// * `mode` - Bit clocking mode. /// * `len` - Number of bits to clock in. /// This will panic for values greater than 8. pub fn clock_bits_in(mut self, mode: ClockBitsIn, mut len: u8) -> Self { assert!(len <= 8, "data length cannot exceed 8"); if len == 0 { return self; } len -= 1; self.0.extend_from_slice(&[mode.into(), len]); self } /// Clock data bits in and out simultaneously. /// /// # Arguments /// /// * `mode` - Bit clocking mode. /// * `len` - Number of bits to clock in. /// This will panic for values greater than 8. pub fn clock_bits(mut self, mode: ClockBits, data: u8, mut len: u8) -> Self { assert!(len <= 8, "data length cannot exceed 8"); if len == 0 { return self; } len -= 1; self.0.extend_from_slice(&[mode.into(), len, data]); self } } /// Construct an MPSSE command array at compile-time. /// /// Alternative to [`MpsseCmdBuilder`]. Parses a specialized grammar that gathers MPSSE commands /// into pseudo-statements contained within zero or more assigned blocks. The pseudo-assignment /// syntax of each block creates a fixed-length `[u8; N]` array that is bound with `let` or /// `const`[^const_note]. /// /// [^const_note]: In `const` bindings, all values used as command parameters and data must be const. /// /// # Syntax /// /// ```compile_fail /// mpsse! { let command_data = { command1(); command2(); /* ... */ commandN(); }; } /// ``` /// or /// ```compile_fail /// mpsse! { let (command_data, READ_LEN) = { command1(); command2(); /* ... */ commandN(); }; } /// ``` /// The second form provides the caller with a constant size value of the expected data length to /// read after writing the commands to the device. /// /// # Commands /// /// * [`enable_loopback()`][`MpsseCmdBuilder::enable_loopback`] /// * [`disable_loopback()`][`MpsseCmdBuilder::disable_loopback`] /// * [`enable_3phase_data_clocking()`][`MpsseCmdBuilder::enable_3phase_data_clocking`] /// * [`disable_3phase_data_clocking()`][`MpsseCmdBuilder::disable_3phase_data_clocking`] /// * [`set_gpio_lower(state: u8, direction: u8)`][`MpsseCmdBuilder::set_gpio_lower`] /// * [`set_gpio_upper(state: u8, direction: u8)`][`MpsseCmdBuilder::set_gpio_upper`] /// * [`gpio_lower() -> usize`][`MpsseCmdBuilder::gpio_lower`] /// * [`gpio_upper() -> usize`][`MpsseCmdBuilder::gpio_upper`] /// * [`send_immediate()`][`MpsseCmdBuilder::send_immediate`] /// * [`wait_on_io_high()`][`MpsseCmdBuilder::wait_on_io_high`] /// * [`wait_on_io_low()`][`MpsseCmdBuilder::wait_on_io_low`] /// * [`clock_data_out(mode: ClockDataOut, data: [u8])`][`MpsseCmdBuilder::clock_data_out`] /// * [`clock_data_in(mode: ClockDataIn, len: u16) -> std::ops::Range<usize>`][`MpsseCmdBuilder::clock_data_in`] /// * [`clock_data(mode: ClockData, data: [u8]) -> std::ops::Range<usize>`][`MpsseCmdBuilder::clock_data`] /// * [`clock_bits_out(mode: ClockBitsOut, data: u8, len: u8)`][`MpsseCmdBuilder::clock_bits_out`] /// * [`clock_bits_in(mode: ClockBitsIn, len: u8) -> usize`][`MpsseCmdBuilder::clock_bits_in`] /// * [`clock_bits(mode: ClockBits, data: u8, len: u8) -> usize`][`MpsseCmdBuilder::clock_bits`] /// /// Command pseudo-statements that read data from the device may optionally have the form: /// ``` /// # use libftd2xx::{mpsse, ClockDataIn}; /// mpsse! { /// // command_data and DATA_IN_RANGE are both declared in the scope of the macro expansion. /// let command_data = { /// const DATA_IN_RANGE = clock_data_in(ClockDataIn::MsbNeg, 3); /// }; /// } /// ``` /// This provides a constant [`Range`][`std::ops::Range`] or [`usize`] index value that may be used /// to subscript the data read from the device. /// /// `clock_data` and `clock_data_out` require that the second argument is a fixed-length, square /// bracketed list of `u8` values. Compile-time limitations make arbitrary array concatenation or /// coersion infeasible. /// /// # Asserts /// /// For `let` bindings, the standard [`assert`] macro is used for validating parameter size inputs. /// For `const` bindings, [`const_assert`][`static_assertions::const_assert`] is used instead. /// /// `const_assert` lacks the ability to provide meaningful compile errors, so it may be useful /// to temporarily use a `let` binding within function scope to diagnose failing macro expansions. /// /// # User Abstractions /// /// With macro shadowing, it is possible to extend the macro with additional rules for abstract, /// device-specific commands. /// /// Comments within the implementation of this macro contain hints on how to implement these rules. /// /// For example, a SPI device typically delineates transfers with the CS line. Fundamental /// commands like `cs_high` and `cs_low` can be implmented this way, along with other /// device-specific abstractions. /// /// ``` /// # use libftd2xx::mpsse; /// macro_rules! mpsse { /// // Practical abstraction of CS line for SPI devices. /// ($passthru:tt {cs_low(); $($tail:tt)*} -> [$($out:tt)*]) => { /// mpsse!($passthru { /// set_gpio_lower(0x0, 0xb); /// $($tail)* /// } -> [$($out)*]); /// }; /// ($passthru:tt {cs_high(); $($tail:tt)*} -> [$($out:tt)*]) => { /// mpsse!($passthru { /// set_gpio_lower(0x8, 0xb); /// $($tail)* /// } -> [$($out)*]); /// }; /// /// // Hypothetical device-specific command. Leverages both user and libftd2xx commands. /// ($passthru:tt /// {const $idx_id:ident = command_42([$($data:expr),* $(,)*]); $($tail:tt)*} -> /// [$($out:tt)*]) => { /// mpsse!($passthru { /// cs_low(); /// const $idx_id = clock_data(::libftd2xx::ClockData::MsbPosIn, [0x42, $($data,)*]); /// cs_high(); /// $($tail)* /// } -> [$($out)*]); /// }; /// /// // Everything else handled by libftd2xx crate implementation. /// ($($tokens:tt)*) => { /// ::libftd2xx::mpsse!($($tokens)*); /// }; /// } /// /// mpsse! { /// const (COMMAND_DATA, READ_LEN) = { /// wait_on_io_high(); /// const COMMAND_42_RESULT_RANGE = command_42([11, 22, 33]); /// send_immediate(); /// }; /// } /// ``` /// /// # Example /// /// ```no_run /// use libftd2xx::{mpsse, ClockDataIn, ClockDataOut, Ft232h, FtdiCommon, FtdiMpsse}; /// /// mpsse! { /// const (COMMAND_DATA, READ_LEN) = { /// set_gpio_lower(0xFA, 0xFB); /// set_gpio_lower(0xF2, 0xFB); /// clock_data_out(ClockDataOut::MsbNeg, [0x12, 0x34, 0x56]); /// const DATA_IN_RANGE = clock_data_in(ClockDataIn::MsbNeg, 3); /// set_gpio_lower(0xFA, 0xFB); /// send_immediate(); /// }; /// } /// /// let mut ft = Ft232h::with_serial_number("FT5AVX6B")?; /// ft.initialize_mpsse_default()?; /// ft.write_all(&COMMAND_DATA)?; /// let mut buf: [u8; READ_LEN] = [0; READ_LEN]; /// ft.read_all(&mut buf)?; /// println!("Data slice in: {:?}", &buf[DATA_IN_RANGE]); /// # Ok::<(), std::boxed::Box<dyn std::error::Error>>(()) /// ``` #[macro_export] macro_rules! mpsse { // Replacement method for counting comma-separated expressions. // https://danielkeep.github.io/tlborm/book/blk-counting.html#repetition-with-replacement (@replace_expr $_t:tt $sub:expr) => {$sub}; (@count_elements $($tts:expr),* $(,)*) => {(0usize $(+ mpsse!(@replace_expr $tts 1usize))*)}; // Assert that is selectively compile-time depending on let vs. const expansion. // // Unfortunately, the compile-time error is not very helpful due to the lack of message and // macro depth, but still ensures safe command construction. // // Temporarily running a let expansion can be helpful to diagnose errors. (@assert ((let, $_user_passthru:tt), $_read_len:expr), $e:expr, $msg:expr) => { ::std::assert!($e, $msg); }; (@assert ((const, $_user_passthru:tt), $_read_len:expr), $e:expr, $_msg:expr) => { ::static_assertions::const_assert!($e); }; // Unit rule () => {}; // let command_data = { command1(); command2(); ... commandN(); }; (let $id:ident = {$($commands:tt)*}; $($tail:tt)*) => { mpsse!(((let, ($id, _)), 0) {$($commands)*} -> []); mpsse!($($tail)*); }; // const COMMAND_DATA = { command1(); command2(); ... commandN(); }; (const $id:ident = {$($commands:tt)*}; $($tail:tt)*) => { mpsse!(((const, ($id, _)), 0) {$($commands)*} -> []); mpsse!($($tail)*); }; // let (command_data, READ_LEN) = { command1(); command2(); ... commandN(); }; (let ($id:ident, $read_len_id:ident) = {$($commands:tt)*}; $($tail:tt)*) => { mpsse!(((let, ($id, $read_len_id)), 0) {$($commands)*} -> []); mpsse!($($tail)*); }; // const (COMMAND_DATA, READ_LEN) = { command1(); command2(); ... commandN(); }; (const ($id:ident, $read_len_id:ident) = {$($commands:tt)*}; $($tail:tt)*) => { mpsse!(((const, ($id, $read_len_id)), 0) {$($commands)*} -> []); mpsse!($($tail)*); }; // Rules generally follow a structure based on three root token trees: // (<passthru>) {<input>} -> [<output>] // // "Statements" are recursively shifted off the front of the input and the resulting u8 tokens // are appended to the output. Recursion ends when the input token tree is empty. // // Rules have the following form: // ($passthru:tt {<FUNCTION NAME>(); $($tail:tt)*} -> [$($out:tt)*]) // // For functions that perform data reads, cumulative read_len can be accessed with this form: // (($passthru:tt, $read_len:tt) {<FUNCTION NAME>(); $($tail:tt)*} -> [$($out:tt)*]) // // Additionally, the following form is used to provide the invoker with a usize index or // range to later access a specific data read `const READ_INDEX = <FUNCTION NAME>();`: // (($passthru:tt, $read_len:tt) {const $idx_id:ident = <FUNCTION NAME>(); $($tail:tt)*} -> [$($out:tt)*]) ($passthru:tt {enable_loopback(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::EnableLoopback as u8,]); }; ($passthru:tt {disable_loopback(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::DisableLoopback as u8,]); }; ($passthru:tt {enable_3phase_data_clocking(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::Enable3PhaseClocking as u8,]); }; ($passthru:tt {disable_3phase_data_clocking(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::Disable3PhaseClocking as u8,]); }; ($passthru:tt {set_gpio_lower($state:expr, $direction:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::SetDataBitsLowbyte as u8, $state as u8, $direction as u8,]); }; ($passthru:tt {set_gpio_upper($state:expr, $direction:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::SetDataBitsHighbyte as u8, $state as u8, $direction as u8,]); }; (($passthru:tt, $read_len:tt) {gpio_lower(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(($passthru, ($read_len + 1)) {$($tail)*} -> [$($out)* $crate::MpsseCmd::GetDataBitsLowbyte as u8,]); }; (($passthru:tt, $read_len:tt) {const $idx_id:ident = gpio_lower(); $($tail:tt)*} -> [$($out:tt)*]) => { const $idx_id: usize = $read_len; mpsse!(($passthru, $read_len) {gpio_lower(); $($tail)*} -> [$($out)*]); }; (($passthru:tt, $read_len:tt) {gpio_upper(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(($passthru, ($read_len + 1)) {$($tail)*} -> [$($out)* $crate::MpsseCmd::GetDataBitsHighbyte as u8,]); }; (($passthru:tt, $read_len:tt) {const $idx_id:ident = gpio_upper(); $($tail:tt)*} -> [$($out:tt)*]) => { const $idx_id: usize = $read_len; mpsse!(($passthru, $read_len) {gpio_upper(); $($tail)*} -> [$($out)*]); }; ($passthru:tt {send_immediate(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::SendImmediate as u8,]); }; ($passthru:tt {wait_on_io_high(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::WaitOnIOHigh as u8,]); }; ($passthru:tt {wait_on_io_low(); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!($passthru {$($tail)*} -> [$($out)* $crate::MpsseCmd::WaitOnIOLow as u8,]); }; ($passthru:tt {clock_data_out($mode:expr, [$($data:expr),* $(,)*]); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert $passthru, (mpsse!(@count_elements $($data,)*) as usize > 0_usize && mpsse!(@count_elements $($data,)*) as usize <= 65536_usize), "data length must be in 1..=(u16::MAX + 1)"); mpsse!($passthru {$($tail)*} -> [$($out)* $mode as $crate::ClockDataOut as u8, ((mpsse!(@count_elements $($data,)*) - 1) & 0xFF_usize) as u8, (((mpsse!(@count_elements $($data,)*) - 1) >> 8) & 0xFF_usize) as u8, $($data as u8,)*]); }; (($passthru:tt, $read_len:tt) {clock_data_in($mode:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert ($passthru, $read_len), (($len) as usize > 0_usize && ($len) as usize <= 65536_usize), "data length must be in 1..=(u16::MAX + 1)"); mpsse!(($passthru, ($read_len + ($len))) {$($tail)*} -> [$($out)* $mode as $crate::ClockDataIn as u8, ((($len) - 1) & 0xFF_usize) as u8, (((($len) - 1) >> 8) & 0xFF_usize) as u8,]); }; (($passthru:tt, $read_len:tt) {const $range_id:ident = clock_data_in($mode:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { const $range_id: ::std::ops::Range<usize> = $read_len..$read_len + ($len); mpsse!(($passthru, $read_len) {clock_data_in($mode, $len); $($tail)*} -> [$($out)*]); }; (($passthru:tt, $read_len:tt) {clock_data($mode:expr, [$($data:expr),* $(,)*]); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert ($passthru, $read_len), (mpsse!(@count_elements $($data,)*) as usize > 0_usize && mpsse!(@count_elements $($data,)*) as usize <= 65536_usize), "data length must be in 1..=(u16::MAX + 1)"); mpsse!(($passthru, ($read_len + mpsse!(@count_elements $($data,)*))) {$($tail)*} -> [$($out)* $mode as $crate::ClockData as u8, ((mpsse!(@count_elements $($data,)*) - 1) & 0xFF_usize) as u8, (((mpsse!(@count_elements $($data,)*) - 1) >> 8) & 0xFF_usize) as u8, $($data as u8,)*]); }; (($passthru:tt, $read_len:tt) {const $range_id:ident = clock_data($mode:expr, [$($data:expr),* $(,)*]); $($tail:tt)*} -> [$($out:tt)*]) => { const $range_id: ::std::ops::Range<usize> = $read_len..$read_len + mpsse!(@count_elements $($data,)*); mpsse!(($passthru, $read_len) {clock_data($mode, [$($data,)*]); $($tail)*} -> [$($out)*]); }; ($passthru:tt {clock_bits_out($mode:expr, $data:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert $passthru, ($len as u8 > 0_u8 && $len as u8 <= 8_u8), "data length must be in 1..=8"); mpsse!($passthru {$($tail)*} -> [$($out)* $mode as $crate::ClockBitsOut as u8, (($len) - 1) as u8, $data as u8,]); }; (($passthru:tt, $read_len:tt) {clock_bits_in($mode:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert ($passthru, $read_len), ($len as u8 > 0_u8 && $len as u8 <= 8_u8), "data length must be in 1..=8"); mpsse!(($passthru, ($read_len + 1)) {$($tail)*} -> [$($out)* $mode as $crate::ClockBitsIn as u8, (($len) - 1) as u8,]); }; (($passthru:tt, $read_len:tt) {const $idx_id:ident = clock_bits_in($mode:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { const $idx_id: usize = $read_len; mpsse!(($passthru, $read_len) {clock_bits_in($mode, $len); $($tail)*} -> [$($out)*]); }; (($passthru:tt, $read_len:tt) {clock_bits($mode:expr, $data:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { mpsse!(@assert ($passthru, $read_len), ($len as u8 > 0_u8 && $len as u8 <= 8_u8), "data length must be in 1..=8"); mpsse!(($passthru, ($read_len + 1)) {$($tail)*} -> [$($out)* $mode as $crate::ClockBits as u8, (($len) - 1) as u8, $data as u8,]); }; (($passthru:tt, $read_len:tt) {const $idx_id:ident = clock_bits($mode:expr, $data:expr, $len:expr); $($tail:tt)*} -> [$($out:tt)*]) => { const $idx_id: usize = $read_len; mpsse!(($passthru, $read_len) {clock_bits($mode, $data, $len); $($tail)*} -> [$($out)*]); }; // Emit command_data ((($const_let:tt, ($id:tt, _)), $read_len:expr) {} -> [$($out:tt)*]) => { $const_let $id: [u8; mpsse!(@count_elements $($out)*)] = [$($out)*]; }; // Emit command_data, READ_LEN ((($const_let:tt, ($id:tt, $read_len_id:tt)), $read_len:expr) {} -> [$($out:tt)*]) => { $const_let $id: [u8; mpsse!(@count_elements $($out)*)] = [$($out)*]; const $read_len_id: usize = $read_len; }; }