control.cpp 79 KB
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
////////////////////////////////////////////////////////////////////////////////
//
//  OpenHantek
//  hantek/control.cpp
//
//  Copyright (C) 2008, 2009  Oleg Khudyakov
//  prcoder@potrebitel.ru
//  Copyright (C) 2010 - 2012  Oliver Haag
//  oliver.haag@gmail.com
//
//  This program is free software: you can redistribute it and/or modify it
//  under the terms of the GNU General Public License as published by the Free
//  Software Foundation, either version 3 of the License, or (at your option)
//  any later version.
//
//  This program is distributed in the hope that it will be useful, but WITHOUT
//  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
//  more details.
//
//  You should have received a copy of the GNU General Public License along with
//  this program.  If not, see <http://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////////////

#include <cmath>
#include <limits>
#include <vector>

#include <QList>
#include <QMutex>
#include <QTimer>

#include "hantek/control.h"

#include "hantek/device.h"
#include "hantek/types.h"
#include "helper.h"

namespace Hantek {
/// \brief Initializes the command buffers and lists.
/// \param parent The parent widget.
Control::Control(QObject *parent) : DsoControl(parent) {
  // Use DSO-2090 specification as default
  this->specification.command.bulk.setRecordLength = (BulkCode)-1;
  this->specification.command.bulk.setChannels = (BulkCode)-1;
  this->specification.command.bulk.setGain = (BulkCode)-1;
  this->specification.command.bulk.setSamplerate = (BulkCode)-1;
  this->specification.command.bulk.setTrigger = (BulkCode)-1;
  this->specification.command.bulk.setPretrigger = (BulkCode)-1;
  this->specification.command.control.setOffset = (ControlCode)-1;
  this->specification.command.control.setRelays = (ControlCode)-1;
  this->specification.command.values.offsetLimits = (ControlValue)-1;
  this->specification.command.values.voltageLimits = (ControlValue)-1;

  this->specification.samplerate.single.base = 50e6;
  this->specification.samplerate.single.max = 50e6;
  this->specification.samplerate.single.recordLengths << 0;
  this->specification.samplerate.multi.base = 100e6;
  this->specification.samplerate.multi.max = 100e6;
  this->specification.samplerate.multi.recordLengths << 0;

  for (unsigned int channel = 0; channel < HANTEK_CHANNELS; ++channel) {
    for (unsigned int gainId = 0; gainId < 9; ++gainId) {
      this->specification.offsetLimit[channel][gainId][OFFSET_START] = 0x0000;
      this->specification.offsetLimit[channel][gainId][OFFSET_END] = 0xffff;
    }
  }

  // Set settings to default values
  this->settings.samplerate.limits = &(this->specification.samplerate.single);
  this->settings.samplerate.downsampler = 1;
  this->settings.samplerate.current = 1e8;
  this->settings.trigger.position = 0;
  this->settings.trigger.point = 0;
  this->settings.trigger.mode = Dso::TRIGGERMODE_NORMAL;
  this->settings.trigger.slope = Dso::SLOPE_POSITIVE;
  this->settings.trigger.special = false;
  this->settings.trigger.source = 0;
  for (unsigned int channel = 0; channel < HANTEK_CHANNELS; ++channel) {
    this->settings.trigger.level[channel] = 0.0;
    this->settings.voltage[channel].gain = 0;
    this->settings.voltage[channel].offset = 0.0;
    this->settings.voltage[channel].offsetReal = 0.0;
    this->settings.voltage[channel].used = false;
  }
  this->settings.recordLengthId = 1;
  this->settings.usedChannels = 0;

  // Special trigger sources
  this->specialTriggerSources << tr("EXT") << tr("EXT/10");

  // Instantiate bulk command later, some are not the same for all models
  for (int command = 0; command < BULK_COUNT; ++command) {
    this->command[command] = 0;
    this->commandPending[command] = false;
  }

  // Transmission-ready control commands
  this->control[CONTROLINDEX_SETOFFSET] = new ControlSetOffset();
  this->controlCode[CONTROLINDEX_SETOFFSET] = CONTROL_SETOFFSET;
  this->control[CONTROLINDEX_SETRELAYS] = new ControlSetRelays();
  this->controlCode[CONTROLINDEX_SETRELAYS] = CONTROL_SETRELAYS;

  for (int control = 0; control < CONTROLINDEX_COUNT; ++control)
    this->controlPending[control] = false;

  // USB device
  this->device = new Device(this);

  // Thread execution timer
  this->timer = 0;

  // State of the device
  this->captureState = CAPTURE_WAITING;
  this->rollState = 0;
  this->samplingStarted = false;
  this->lastTriggerMode = (Dso::TriggerMode)-1;

  // Sample buffers
  this->samples.resize(HANTEK_CHANNELS);

  this->previousSampleCount = 0;

  connect(this->device, SIGNAL(disconnected()), this, SLOT(disconnectDevice()));
}

/// \brief Disconnects the device.
Control::~Control() {
  this->device->disconnect();

  // Clean up commands
  for (int command = 0; command < BULK_COUNT; ++command) {
    if (this->command[command])
      delete this->command[command];
  }
}

/// \brief Gets the physical channel count for this oscilloscope.
/// \return The number of physical channels.
unsigned int Control::getChannelCount() { return HANTEK_CHANNELS; }

/// \brief Get available record lengths for this oscilloscope.
/// \return The number of physical channels, empty list for continuous.
QList<unsigned int> *Control::getAvailableRecordLengths() {
  return &this->settings.samplerate.limits->recordLengths;
}

/// \brief Get minimum samplerate for this oscilloscope.
/// \return The minimum samplerate for the current configuration in S/s.
double Control::getMinSamplerate() {
  return (double)this->specification.samplerate.single.base /
         this->specification.samplerate.single.maxDownsampler;
}

/// \brief Get maximum samplerate for this oscilloscope.
/// \return The maximum samplerate for the current configuration in S/s.
double Control::getMaxSamplerate() {
  ControlSamplerateLimits *limits =
      (this->settings.usedChannels <= 1)
          ? &this->specification.samplerate.multi
          : &this->specification.samplerate.single;
  return limits->max;
}

/// \brief Handles all USB things until the device gets disconnected.
void Control::run() {
  // Initialize communication thread state
  this->captureState = CAPTURE_WAITING;
  this->rollState = 0;
  this->samplingStarted = false;
  this->lastTriggerMode = (Dso::TriggerMode)-1;

  this->cycleCounter = 0;
  this->startCycle = 0;

  // Thread execution timer
  this->timer = new QTimer(this);
  connect(this->timer, SIGNAL(timeout()), this, SLOT(handler()),
          Qt::DirectConnection);

  this->updateInterval();
  this->timer->start();

  // The control loop is running until the device is disconnected
  exec();

  this->timer->stop();
  this->device->disconnect();

  delete this->timer;
  this->timer = 0;

  emit statusMessage(tr("The device has been disconnected"), 0);
}

/// \brief Updates the interval of the periodic thread timer.
void Control::updateInterval() {
  if (!this->timer)
    return;

  int cycleTime;

  // Check the current oscilloscope state everytime 25% of the time the buffer
  // should be refilled
  if (this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId] == UINT_MAX)
    cycleTime = (int)((double)this->device->getPacketSize() /
                      ((this->settings.samplerate.limits ==
                        &this->specification.samplerate.multi)
                           ? 1
                           : HANTEK_CHANNELS) /
                      this->settings.samplerate.current * 250);
  else
    cycleTime = (int)((double)this->settings.samplerate.limits
                          ->recordLengths[this->settings.recordLengthId] /
                      this->settings.samplerate.current * 250);

  // Not more often than every 10 ms though but at least once every second
  cycleTime = qBound(10, cycleTime, 1000);

  this->timer->setInterval(cycleTime);
}

/// \brief Calculates the trigger point from the CommandGetCaptureState data.
/// \param value The data value that contains the trigger point.
/// \return The calculated trigger point for the given data.
unsigned int Control::calculateTriggerPoint(unsigned int value) {
  unsigned int result = value;

  // Each set bit inverts all bits with a lower value
  for (unsigned int bitValue = 1; bitValue; bitValue <<= 1)
    if (result & bitValue)
      result ^= bitValue - 1;

  return result;
}

/// \brief Gets the current state.
/// \return The current CaptureState of the oscilloscope, libusb error code on
/// error.
int Control::getCaptureState() {
  int errorCode;

  // Command not supported by this model
  if (this->device->getModel() == MODEL_DSO6022BE)
    return CAPTURE_READY;

  errorCode = this->device->bulkCommand(this->command[BULK_GETCAPTURESTATE], 1);
  if (errorCode < 0)
    return errorCode;

  BulkResponseGetCaptureState response;
  errorCode = this->device->bulkRead(response.data(), response.getSize());
  if (errorCode < 0)
    return errorCode;

  this->settings.trigger.point =
      this->calculateTriggerPoint(response.getTriggerPoint());

  return (int)response.getCaptureState();
}

/// \brief Gets sample data from the oscilloscope and converts it.
/// \return sample count on success, libusb error code on error.
int Control::getSamples(bool process) {
  int errorCode;

  if (this->device->getModel() != MODEL_DSO6022BE) {
    // Request data
    errorCode = this->device->bulkCommand(this->command[BULK_GETDATA], 1);
    if (errorCode < 0)
      return errorCode;
  }

  // Save raw data to temporary buffer
  bool fastRate = false;
  unsigned int totalSampleCount = this->getSampleCount(&fastRate);
  if (totalSampleCount == UINT_MAX)
    return LIBUSB_ERROR_INVALID_PARAM;

  // To make sure no samples will remain in the scope buffer, also check the
  // sample count before the last sampling started
  if (totalSampleCount < this->previousSampleCount) {
    unsigned int currentSampleCount = totalSampleCount;
    totalSampleCount = this->previousSampleCount;
    this->previousSampleCount =
        currentSampleCount; // Using sampleCount as temporary buffer since it
                            // was set to totalSampleCount
  } else {
    this->previousSampleCount = totalSampleCount;
  }

  unsigned int sampleCount = totalSampleCount;
  if (!fastRate)
    sampleCount /= HANTEK_CHANNELS;
  unsigned int dataLength = totalSampleCount;
  if (this->specification.sampleSize > 8)
    dataLength *= 2;

  std::vector<unsigned char> data(dataLength);
  errorCode = this->device->bulkReadMulti(data.data(), dataLength);
  if (errorCode < 0)
    return errorCode;

  // Process the data only if we want it
  if (process) {
    // How much data did we really receive?
    dataLength = errorCode;
    if (this->specification.sampleSize > 8)
      totalSampleCount = dataLength / 2;
    else
      totalSampleCount = dataLength;

    this->samplesMutex.lock();

    // Convert channel data
    if (fastRate) {
      // Fast rate mode, one channel is using all buffers
      sampleCount = totalSampleCount;
      int channel = 0;
      for (; channel < HANTEK_CHANNELS; ++channel) {
        if (this->settings.voltage[channel].used)
          break;
      }

      // Clear unused channels
      for (int channelCounter = 0; channelCounter < HANTEK_CHANNELS;
           ++channelCounter)
        if (channelCounter != channel) {

          this->samples[channelCounter].clear();
        }

      if (channel < HANTEK_CHANNELS) {
        // Resize sample vector
        this->samples[channel].resize(sampleCount);

        // Convert data from the oscilloscope and write it into the sample
        // buffer
        unsigned int bufferPosition = this->settings.trigger.point * 2;
        if (this->specification.sampleSize > 8) {
          // Additional most significant bits after the normal data
          unsigned int extraBitsPosition; // Track the position of the extra
                                          // bits in the additional byte
          unsigned int extraBitsSize =
              this->specification.sampleSize - 8; // Number of extra bits
          unsigned short int extraBitsMask =
              (0x00ff << extraBitsSize) &
              0xff00; // Mask for extra bits extraction

          for (unsigned int realPosition = 0; realPosition < sampleCount;
               ++realPosition, ++bufferPosition) {
            if (bufferPosition >= sampleCount)
              bufferPosition %= sampleCount;

            extraBitsPosition = bufferPosition % HANTEK_CHANNELS;

            this->samples[channel][realPosition] =
                ((double)((unsigned short int)data[bufferPosition] +
                          (((unsigned short int)
                                data[sampleCount + bufferPosition -
                                     extraBitsPosition]
                            << (8 -
                                (HANTEK_CHANNELS - 1 - extraBitsPosition) *
                                    extraBitsSize)) &
                           extraBitsMask)) /
                     this->specification
                         .voltageLimit[channel]
                                      [this->settings.voltage[channel].gain] -
                 this->settings.voltage[channel].offsetReal) *
                this->specification
                    .gainSteps[this->settings.voltage[channel].gain];
          }
        } else {
          for (unsigned int realPosition = 0; realPosition < sampleCount;
               ++realPosition, ++bufferPosition) {
            if (bufferPosition >= sampleCount)
              bufferPosition %= sampleCount;

            double dataBuf = (double)((int)data[bufferPosition]);
            this->samples[channel][realPosition] =
                (dataBuf /
                     this->specification
                         .voltageLimit[channel]
                                      [this->settings.voltage[channel].gain] -
                 this->settings.voltage[channel].offsetReal) *
                this->specification
                    .gainSteps[this->settings.voltage[channel].gain];
          }
        }
      }
    } else {
      // Normal mode, channels are using their separate buffers
      sampleCount = totalSampleCount / HANTEK_CHANNELS;
      // if device is 6022BE, drop first 1000 samples
      if (this->device->getModel() == MODEL_DSO6022BE)
        sampleCount -= 1000;
      for (int channel = 0; channel < HANTEK_CHANNELS; ++channel) {
        if (this->settings.voltage[channel].used) {
          // Resize sample vector
          this->samples[channel].resize(sampleCount);

          // Convert data from the oscilloscope and write it into the sample
          // buffer
          unsigned int bufferPosition = this->settings.trigger.point * 2;
          if (this->specification.sampleSize > 8) {
            // Additional most significant bits after the normal data
            unsigned int extraBitsSize =
                this->specification.sampleSize - 8; // Number of extra bits
            unsigned short int extraBitsMask =
                (0x00ff << extraBitsSize) &
                0xff00; // Mask for extra bits extraction
            unsigned int extraBitsIndex =
                8 -
                channel * 2; // Bit position offset for extra bits extraction

            for (unsigned int realPosition = 0; realPosition < sampleCount;
                 ++realPosition, bufferPosition += HANTEK_CHANNELS) {
              if (bufferPosition >= totalSampleCount)
                bufferPosition %= totalSampleCount;

              this->samples[channel][realPosition] =
                  ((double)((unsigned short int)
                                data[bufferPosition + HANTEK_CHANNELS - 1 -
                                     channel] +
                            (((unsigned short int)
                                  data[totalSampleCount + bufferPosition]
                              << extraBitsIndex) &
                             extraBitsMask)) /
                       this->specification
                           .voltageLimit[channel]
                                        [this->settings.voltage[channel].gain] -
                   this->settings.voltage[channel].offsetReal) *
                  this->specification
                      .gainSteps[this->settings.voltage[channel].gain];
            }
          } else {
            if (this->device->getModel() == MODEL_DSO6022BE) {
              bufferPosition += channel;
              // if device is 6022BE, offset 1000 incrementally
              bufferPosition += 1000 * 2;
            } else
              bufferPosition += HANTEK_CHANNELS - 1 - channel;

            for (unsigned int realPosition = 0; realPosition < sampleCount;
                 ++realPosition, bufferPosition += HANTEK_CHANNELS) {
              if (bufferPosition >= totalSampleCount)
                bufferPosition %= totalSampleCount;

              if (this->device->getModel() == MODEL_DSO6022BE) {
                double dataBuf = (double)((int)(data[bufferPosition] - 0x83));
                this->samples[channel][realPosition] =
                    (dataBuf /
                     this->specification
                         .voltageLimit[channel]
                                      [this->settings.voltage[channel].gain]) *
                    this->specification
                        .gainSteps[this->settings.voltage[channel].gain];
              } else {
                double dataBuf = (double)((int)(data[bufferPosition]));
                this->samples[channel][realPosition] =
                    (dataBuf /
                         this->specification.voltageLimit
                             [channel][this->settings.voltage[channel].gain] -
                     this->settings.voltage[channel].offsetReal) *
                    this->specification
                        .gainSteps[this->settings.voltage[channel].gain];
              }
            }
          }
        } else {
          // Clear unused channels
          this->samples[channel].clear();
        }
      }
    }

    this->samplesMutex.unlock();
#ifdef DEBUG
    static unsigned int id = 0;
    ++id;
    Helper::timestampDebug(QString("Received packet %1").arg(id));
#endif
    emit samplesAvailable(
        &(this->samples), this->settings.samplerate.current,
        this->settings.samplerate.limits
                ->recordLengths[this->settings.recordLengthId] == UINT_MAX,
        &(this->samplesMutex));
  }

  return errorCode;
}

/// \brief Calculated the nearest samplerate supported by the oscilloscope.
/// \param samplerate The target samplerate, that should be met as good as
/// possible.
/// \param fastRate true, if the fast rate mode is enabled.
/// \param maximum The target samplerate is the maximum allowed when true, the
/// minimum otherwise.
/// \param downsampler Pointer to where the selected downsampling factor should
/// be written.
/// \return The nearest samplerate supported, 0.0 on error.
double Control::getBestSamplerate(double samplerate, bool fastRate,
                                  bool maximum, unsigned int *downsampler) {
  // Abort if the input value is invalid
  if (samplerate <= 0.0)
    return 0.0;

  double bestSamplerate = 0.0;

  // Get samplerate specifications for this mode and model
  ControlSamplerateLimits *limits;
  if (fastRate)
    limits = &(this->specification.samplerate.multi);
  else
    limits = &(this->specification.samplerate.single);

  // Get downsampling factor that would provide the requested rate
  double bestDownsampler =
      (double)limits->base /
      this->specification.bufferDividers[this->settings.recordLengthId] /
      samplerate;
  // Base samplerate sufficient, or is the maximum better?
  if (bestDownsampler < 1.0 &&
      (samplerate <= limits->max /
                         this->specification
                             .bufferDividers[this->settings.recordLengthId] ||
       !maximum)) {
    bestDownsampler = 0.0;
    bestSamplerate =
        limits->max /
        this->specification.bufferDividers[this->settings.recordLengthId];
  } else {
    switch (this->specification.command.bulk.setSamplerate) {
    case BULK_SETTRIGGERANDSAMPLERATE:
      // DSO-2090 supports the downsampling factors 1, 2, 4 and 5 using
      // valueFast or all even values above using valueSlow
      if ((maximum && bestDownsampler <= 5.0) ||
          (!maximum && bestDownsampler < 6.0)) {
        // valueFast is used
        if (maximum) {
          // The samplerate shall not be higher, so we round up
          bestDownsampler = ceil(bestDownsampler);
          if (bestDownsampler > 2.0) // 3 and 4 not possible with the DSO-2090
            bestDownsampler = 5.0;
        } else {
          // The samplerate shall not be lower, so we round down
          bestDownsampler = floor(bestDownsampler);
          if (bestDownsampler > 2.0 &&
              bestDownsampler < 5.0) // 3 and 4 not possible with the DSO-2090
            bestDownsampler = 2.0;
        }
      } else {
        // valueSlow is used
        if (maximum) {
          bestDownsampler =
              ceil(bestDownsampler / 2.0) * 2.0; // Round up to next even value
        } else {
          bestDownsampler = floor(bestDownsampler / 2.0) *
                            2.0; // Round down to next even value
        }
        if (bestDownsampler > 2.0 * 0x10001) // Check for overflow
          bestDownsampler = 2.0 * 0x10001;
      }
      break;

    case BULK_CSETTRIGGERORSAMPLERATE:
      // DSO-5200 may not supports all downsampling factors, requires testing
      if (maximum) {
        bestDownsampler =
            ceil(bestDownsampler); // Round up to next integer value
      } else {
        bestDownsampler =
            floor(bestDownsampler); // Round down to next integer value
      }
      break;

    case BULK_ESETTRIGGERORSAMPLERATE:
      // DSO-2250 doesn't have a fast value, so it supports all downsampling
      // factors
      if (maximum) {
        bestDownsampler =
            ceil(bestDownsampler); // Round up to next integer value
      } else {
        bestDownsampler =
            floor(bestDownsampler); // Round down to next integer value
      }
      break;

    default:
      return 0.0;
    }

    // Limit maximum downsampler value to avoid overflows in the sent commands
    if (bestDownsampler > limits->maxDownsampler)
      bestDownsampler = limits->maxDownsampler;

    bestSamplerate =
        limits->base / bestDownsampler /
        this->specification.bufferDividers[this->settings.recordLengthId];
  }

  if (downsampler)
    *downsampler = (unsigned int)bestDownsampler;
  return bestSamplerate;
}

/// \brief Get the count of samples that are expected returned by the scope.
/// \param fastRate Is set to the state of the fast rate mode when provided.
/// \return The total number of samples the scope should return.
unsigned int Control::getSampleCount(bool *fastRate) {
  unsigned int totalSampleCount =
      this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId];
  bool fastRateEnabled =
      this->settings.samplerate.limits == &this->specification.samplerate.multi;

  if (totalSampleCount == UINT_MAX) {
    // Roll mode
    const int packetSize = this->device->getPacketSize();
    if (packetSize < 0)
      totalSampleCount = UINT_MAX;
    else
      totalSampleCount = packetSize;
  } else {
    if (!fastRateEnabled)
      totalSampleCount *= HANTEK_CHANNELS;
  }
  if (fastRate)
    *fastRate = fastRateEnabled;
  return totalSampleCount;
}

/// \brief Sets the size of the sample buffer without updating dependencies.
/// \param index The record length index that should be set.
/// \return The record length that has been set, 0 on error.
unsigned int Control::updateRecordLength(unsigned int index) {
  if (index >=
      (unsigned int)this->settings.samplerate.limits->recordLengths.size())
    return 0;

  switch (this->specification.command.bulk.setRecordLength) {
  case BULK_SETTRIGGERANDSAMPLERATE:
    // SetTriggerAndSamplerate bulk command for record length
    static_cast<BulkSetTriggerAndSamplerate *>(
        this->command[BULK_SETTRIGGERANDSAMPLERATE])
        ->setRecordLength(index);
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;

    break;

  case BULK_DSETBUFFER:
    if (this->specification.command.bulk.setPretrigger == BULK_FSETBUFFER) {
      // Pointers to needed commands
      BulkSetRecordLength2250 *commandSetRecordLength2250 =
          static_cast<BulkSetRecordLength2250 *>(
              this->command[BULK_DSETBUFFER]);

      commandSetRecordLength2250->setRecordLength(index);
    } else {
      // SetBuffer5200 bulk command for record length
      BulkSetBuffer5200 *commandSetBuffer5200 =
          static_cast<BulkSetBuffer5200 *>(this->command[BULK_DSETBUFFER]);

      commandSetBuffer5200->setUsedPre(DTRIGGERPOSITION_ON);
      commandSetBuffer5200->setUsedPost(DTRIGGERPOSITION_ON);
      commandSetBuffer5200->setRecordLength(index);
    }

    this->commandPending[BULK_DSETBUFFER] = true;

    break;

  default:
    return 0;
  }

  // Check if the divider has changed and adapt samplerate limits accordingly
  bool bDividerChanged =
      this->specification.bufferDividers[index] !=
      this->specification.bufferDividers[this->settings.recordLengthId];

  this->settings.recordLengthId = index;

  if (bDividerChanged) {
    this->updateSamplerateLimits();

    // Samplerate dividers changed, recalculate it
    this->restoreTargets();
  }

  return this->settings.samplerate.limits->recordLengths[index];
}

/// \brief Sets the samplerate based on the parameters calculated by
/// Control::getBestSamplerate.
/// \param downsampler The downsampling factor.
/// \param fastRate true, if one channel uses all buffers.
/// \return The downsampling factor that has been set.
unsigned int Control::updateSamplerate(unsigned int downsampler,
                                       bool fastRate) {
  // Get samplerate limits
  Hantek::ControlSamplerateLimits *limits =
      fastRate ? &this->specification.samplerate.multi
               : &this->specification.samplerate.single;

  // Set the calculated samplerate
  switch (this->specification.command.bulk.setSamplerate) {
  case BULK_SETTRIGGERANDSAMPLERATE: {
    short int downsamplerValue = 0;
    unsigned char samplerateId = 0;
    bool downsampling = false;

    if (downsampler <= 5) {
      // All dividers up to 5 are done using the special samplerate IDs
      if (downsampler == 0 && limits->base >= limits->max)
        samplerateId = 1;
      else if (downsampler <= 2)
        samplerateId = downsampler;
      else { // Downsampling factors 3 and 4 are not supported
        samplerateId = 3;
        downsampler = 5;
        downsamplerValue = (short int)0xffff;
      }
    } else {
      // For any dividers above the downsampling factor can be set directly
      downsampler &= ~0x0001; // Only even values possible
      downsamplerValue = (short int)(0x10001 - (downsampler >> 1));

      downsampling = true;
    }

    // Pointers to needed commands
    BulkSetTriggerAndSamplerate *commandSetTriggerAndSamplerate =
        static_cast<BulkSetTriggerAndSamplerate *>(
            this->command[BULK_SETTRIGGERANDSAMPLERATE]);

    // Store if samplerate ID or downsampling factor is used
    commandSetTriggerAndSamplerate->setDownsamplingMode(downsampling);
    // Store samplerate ID
    commandSetTriggerAndSamplerate->setSamplerateId(samplerateId);
    // Store downsampling factor
    commandSetTriggerAndSamplerate->setDownsampler(downsamplerValue);
    // Set fast rate when used
    commandSetTriggerAndSamplerate->setFastRate(false /*fastRate*/);

    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;

    break;
  }
  case BULK_CSETTRIGGERORSAMPLERATE: {
    // Split the resulting divider into the values understood by the device
    // The fast value is kept at 4 (or 3) for slow sample rates
    long int valueSlow = qMax(((long int)downsampler - 3) / 2, (long int)0);
    unsigned char valueFast = downsampler - valueSlow * 2;

    // Pointers to needed commands
    BulkSetSamplerate5200 *commandSetSamplerate5200 =
        static_cast<BulkSetSamplerate5200 *>(
            this->command[BULK_CSETTRIGGERORSAMPLERATE]);
    BulkSetTrigger5200 *commandSetTrigger5200 =
        static_cast<BulkSetTrigger5200 *>(
            this->command[BULK_ESETTRIGGERORSAMPLERATE]);

    // Store samplerate fast value
    commandSetSamplerate5200->setSamplerateFast(4 - valueFast);
    // Store samplerate slow value (two's complement)
    commandSetSamplerate5200->setSamplerateSlow(
        valueSlow == 0 ? 0 : 0xffff - valueSlow);
    // Set fast rate when used
    commandSetTrigger5200->setFastRate(fastRate);

    this->commandPending[BULK_CSETTRIGGERORSAMPLERATE] = true;
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;

    break;
  }
  case BULK_ESETTRIGGERORSAMPLERATE: {
    // Pointers to needed commands
    BulkSetSamplerate2250 *commandSetSamplerate2250 =
        static_cast<BulkSetSamplerate2250 *>(
            this->command[BULK_ESETTRIGGERORSAMPLERATE]);

    bool downsampling = downsampler >= 1;
    // Store downsampler state value
    commandSetSamplerate2250->setDownsampling(downsampling);
    // Store samplerate value
    commandSetSamplerate2250->setSamplerate(
        downsampler > 1 ? 0x10001 - downsampler : 0);
    // Set fast rate when used
    commandSetSamplerate2250->setFastRate(fastRate);

    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;

    break;
  }
  default:
    return UINT_MAX;
  }

  // Update settings
  bool fastRateChanged = fastRate != (this->settings.samplerate.limits ==
                                      &this->specification.samplerate.multi);
  if (fastRateChanged) {
    this->settings.samplerate.limits = limits;
  }

  this->settings.samplerate.downsampler = downsampler;
  if (downsampler)
    this->settings.samplerate.current =
        this->settings.samplerate.limits->base /
        this->specification.bufferDividers[this->settings.recordLengthId] /
        downsampler;
  else
    this->settings.samplerate.current =
        this->settings.samplerate.limits->max /
        this->specification.bufferDividers[this->settings.recordLengthId];

  // Update dependencies
  this->setPretriggerPosition(this->settings.trigger.position);

  // Emit signals for changed settings
  if (fastRateChanged) {
    emit availableRecordLengthsChanged(
        this->settings.samplerate.limits->recordLengths);
    emit recordLengthChanged(
        this->settings.samplerate.limits
            ->recordLengths[this->settings.recordLengthId]);
  }

  // Check for Roll mode
  if (this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId] != UINT_MAX)
    emit recordTimeChanged((double)this->settings.samplerate.limits
                               ->recordLengths[this->settings.recordLengthId] /
                           this->settings.samplerate.current);
  emit samplerateChanged(this->settings.samplerate.current);

  return downsampler;
}

/// \brief Restore the samplerate/timebase targets after divider updates.
void Control::restoreTargets() {
  if (this->settings.samplerate.target.samplerateSet)
    this->setSamplerate();
  else
    this->setRecordTime();
}

/// \brief Update the minimum and maximum supported samplerate.
void Control::updateSamplerateLimits() {
  // Works only if the minimum samplerate for normal mode is lower than for fast
  // rate mode, which is the case for all models
  ControlSamplerateLimits *limits =
      (this->settings.usedChannels <= 1)
          ? &this->specification.samplerate.multi
          : &this->specification.samplerate.single;
  emit samplerateLimitsChanged(
      (double)this->specification.samplerate.single.base /
          this->specification.samplerate.single.maxDownsampler /
          this->specification.bufferDividers[this->settings.recordLengthId],
      limits->max /
          this->specification.bufferDividers[this->settings.recordLengthId]);
}

/// \brief Try to connect to the oscilloscope.
void Control::connectDevice() {
  int errorCode;

  emit statusMessage(this->device->search(), 0);
  if (!this->device->isConnected())
    return;

  // Clean up commands and their pending state
  for (int command = 0; command < BULK_COUNT; ++command) {
    if (this->command[command])
      delete this->command[command];
    this->commandPending[command] = false;
  }
  // Instantiate the commands needed for all models
  this->command[BULK_FORCETRIGGER] = new BulkForceTrigger();
  this->command[BULK_STARTSAMPLING] = new BulkCaptureStart();
  this->command[BULK_ENABLETRIGGER] = new BulkTriggerEnabled();
  this->command[BULK_GETDATA] = new BulkGetData();
  this->command[BULK_GETCAPTURESTATE] = new BulkGetCaptureState();
  this->command[BULK_SETGAIN] = new BulkSetGain();
  // Initialize the command versions to the ones used on the DSO-2090
  this->specification.command.bulk.setRecordLength = (BulkCode)-1;
  this->specification.command.bulk.setChannels = (BulkCode)-1;
  this->specification.command.bulk.setGain = BULK_SETGAIN;
  this->specification.command.bulk.setSamplerate = (BulkCode)-1;
  this->specification.command.bulk.setTrigger = (BulkCode)-1;
  this->specification.command.bulk.setPretrigger = (BulkCode)-1;
  this->specification.command.control.setOffset = CONTROL_SETOFFSET;
  this->specification.command.control.setRelays = CONTROL_SETRELAYS;
  this->specification.command.values.offsetLimits = VALUE_OFFSETLIMITS;
  this->specification.command.values.voltageLimits = (ControlValue)-1;

  // Determine the command version we need for this model
  bool unsupported = false;
  int lastControlIndex = 0;
  switch (this->device->getModel()) {
  case MODEL_DSO2150:
    unsupported = true;

  case MODEL_DSO2090:
    // Instantiate additional commands for the DSO-2090
    this->command[BULK_SETTRIGGERANDSAMPLERATE] =
        new BulkSetTriggerAndSamplerate();
    this->specification.command.bulk.setRecordLength =
        BULK_SETTRIGGERANDSAMPLERATE;
    this->specification.command.bulk.setChannels = BULK_SETTRIGGERANDSAMPLERATE;
    this->specification.command.bulk.setSamplerate =
        BULK_SETTRIGGERANDSAMPLERATE;
    this->specification.command.bulk.setTrigger = BULK_SETTRIGGERANDSAMPLERATE;
    this->specification.command.bulk.setPretrigger =
        BULK_SETTRIGGERANDSAMPLERATE;
    lastControlIndex = CONTROLINDEX_SETRELAYS;
    // Initialize those as pending
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;
    break;

  case MODEL_DSO2250:
    // Instantiate additional commands for the DSO-2250
    this->command[BULK_BSETCHANNELS] = new BulkSetChannels2250();
    this->command[BULK_CSETTRIGGERORSAMPLERATE] = new BulkSetTrigger2250();
    this->command[BULK_DSETBUFFER] = new BulkSetRecordLength2250();
    this->command[BULK_ESETTRIGGERORSAMPLERATE] = new BulkSetSamplerate2250();
    this->command[BULK_FSETBUFFER] = new BulkSetBuffer2250();
    this->specification.command.bulk.setRecordLength = BULK_DSETBUFFER;
    this->specification.command.bulk.setChannels = BULK_BSETCHANNELS;
    this->specification.command.bulk.setSamplerate =
        BULK_ESETTRIGGERORSAMPLERATE;
    this->specification.command.bulk.setTrigger = BULK_CSETTRIGGERORSAMPLERATE;
    this->specification.command.bulk.setPretrigger = BULK_FSETBUFFER;
    /// \todo Test if lastControlIndex is correct
    lastControlIndex = CONTROLINDEX_SETRELAYS;

    this->commandPending[BULK_BSETCHANNELS] = true;
    this->commandPending[BULK_CSETTRIGGERORSAMPLERATE] = true;
    this->commandPending[BULK_DSETBUFFER] = true;
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;
    this->commandPending[BULK_FSETBUFFER] = true;

    break;

  case MODEL_DSO5200A:
    unsupported = true;

  case MODEL_DSO5200:
    // Instantiate additional commands for the DSO-5200
    this->command[BULK_CSETTRIGGERORSAMPLERATE] = new BulkSetSamplerate5200();
    this->command[BULK_DSETBUFFER] = new BulkSetBuffer5200();
    this->command[BULK_ESETTRIGGERORSAMPLERATE] = new BulkSetTrigger5200();
    this->specification.command.bulk.setRecordLength = BULK_DSETBUFFER;
    this->specification.command.bulk.setChannels = BULK_ESETTRIGGERORSAMPLERATE;
    this->specification.command.bulk.setSamplerate =
        BULK_CSETTRIGGERORSAMPLERATE;
    this->specification.command.bulk.setTrigger = BULK_ESETTRIGGERORSAMPLERATE;
    this->specification.command.bulk.setPretrigger =
        BULK_ESETTRIGGERORSAMPLERATE;
    // this->specification.command.values.voltageLimits = VALUE_ETSCORRECTION;
    /// \todo Test if lastControlIndex is correct
    lastControlIndex = CONTROLINDEX_SETRELAYS;

    this->commandPending[BULK_CSETTRIGGERORSAMPLERATE] = true;
    this->commandPending[BULK_DSETBUFFER] = true;
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;

    break;

  case MODEL_DSO6022BE:
    // 6022BE do not support any bulk commands
    this->control[CONTROLINDEX_SETVOLTDIV_CH1] = new ControlSetVoltDIV_CH1();
    this->controlCode[CONTROLINDEX_SETVOLTDIV_CH1] = CONTROL_SETVOLTDIV_CH1;
    this->controlPending[CONTROLINDEX_SETVOLTDIV_CH1] = true;

    this->control[CONTROLINDEX_SETVOLTDIV_CH2] = new ControlSetVoltDIV_CH2();
    this->controlCode[CONTROLINDEX_SETVOLTDIV_CH2] = CONTROL_SETVOLTDIV_CH2;
    this->controlPending[CONTROLINDEX_SETVOLTDIV_CH2] = true;

    this->control[CONTROLINDEX_SETTIMEDIV] = new ControlSetTimeDIV();
    this->controlCode[CONTROLINDEX_SETTIMEDIV] = CONTROL_SETTIMEDIV;
    this->controlPending[CONTROLINDEX_SETTIMEDIV] = true;

    this->control[CONTROLINDEX_ACQUIIRE_HARD_DATA] =
        new ControlAcquireHardData();
    this->controlCode[CONTROLINDEX_ACQUIIRE_HARD_DATA] =
        CONTROL_ACQUIIRE_HARD_DATA;
    this->controlPending[CONTROLINDEX_ACQUIIRE_HARD_DATA] = true;
    /// \todo Test if lastControlIndex is correct
    lastControlIndex = CONTROLINDEX_ACQUIIRE_HARD_DATA;
    break;

  default:
    this->device->disconnect();
    emit statusMessage(tr("Unknown model"), 0);
    return;
  }

  if (unsupported)
    qWarning("Warning: This Hantek DSO model isn't supported officially, so it "
             "may not be working as expected. Reports about your experiences "
             "are very welcome though (Please open a feature request in the "
             "tracker at https://sf.net/projects/openhantek/ or email me "
             "directly to oliver.haag@gmail.com). If it's working perfectly I "
             "can remove this warning, if not it should be possible to get it "
             "working with your help soon.");

  for (int control = 0; control <= lastControlIndex; ++control)
    this->controlPending[control] = true;

  // Disable controls not supported by 6022BE
  if (this->device->getModel() == MODEL_DSO6022BE) {
    this->controlPending[CONTROLINDEX_SETOFFSET] = false;
    this->controlPending[CONTROLINDEX_SETRELAYS] = false;
  }

  // Maximum possible samplerate for a single channel and dividers for record
  // lengths
  this->specification.bufferDividers.clear();
  this->specification.samplerate.single.recordLengths.clear();
  this->specification.samplerate.multi.recordLengths.clear();
  this->specification.gainSteps.clear();
  for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
    this->specification.voltageLimit[channel].clear();

  switch (this->device->getModel()) {
  case MODEL_DSO5200:
  case MODEL_DSO5200A:
    this->specification.samplerate.single.base = 100e6;
    this->specification.samplerate.single.max = 125e6;
    this->specification.samplerate.single.maxDownsampler = 131072;
    this->specification.samplerate.single.recordLengths << UINT_MAX << 10240
                                                        << 14336;
    this->specification.samplerate.multi.base = 200e6;
    this->specification.samplerate.multi.max = 250e6;
    this->specification.samplerate.multi.maxDownsampler = 131072;
    this->specification.samplerate.multi.recordLengths << UINT_MAX << 20480
                                                       << 28672;
    this->specification.bufferDividers << 1000 << 1 << 1;
    this->specification.gainSteps << 0.16 << 0.40 << 0.80 << 1.60 << 4.00 << 8.0
                                  << 16.0 << 40.0 << 80.0;
    /// \todo Use calibration data to get the DSO-5200(A) sample ranges
    for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
      this->specification.voltageLimit[channel]
          << 368 << 454 << 908 << 368 << 454 << 908 << 368 << 454 << 908;
    this->specification.gainIndex << 1 << 0 << 0 << 1 << 0 << 0 << 1 << 0 << 0;
    this->specification.sampleSize = 10;
    break;

  case MODEL_DSO2250:
    this->specification.samplerate.single.base = 100e6;
    this->specification.samplerate.single.max = 100e6;
    this->specification.samplerate.single.maxDownsampler = 65536;
    this->specification.samplerate.single.recordLengths << UINT_MAX << 10240
                                                        << 524288;
    this->specification.samplerate.multi.base = 200e6;
    this->specification.samplerate.multi.max = 250e6;
    this->specification.samplerate.multi.maxDownsampler = 65536;
    this->specification.samplerate.multi.recordLengths << UINT_MAX << 20480
                                                       << 1048576;
    this->specification.bufferDividers << 1000 << 1 << 1;
    this->specification.gainSteps << 0.08 << 0.16 << 0.40 << 0.80 << 1.60
                                  << 4.00 << 8.0 << 16.0 << 40.0;
    for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
      this->specification.voltageLimit[channel]
          << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255;
    this->specification.gainIndex << 0 << 2 << 3 << 0 << 2 << 3 << 0 << 2 << 3;
    this->specification.sampleSize = 8;
    break;

  case MODEL_DSO2150:
    this->specification.samplerate.single.base = 50e6;
    this->specification.samplerate.single.max = 75e6;
    this->specification.samplerate.single.maxDownsampler = 131072;
    this->specification.samplerate.single.recordLengths << UINT_MAX << 10240
                                                        << 32768;
    this->specification.samplerate.multi.base = 100e6;
    this->specification.samplerate.multi.max = 150e6;
    this->specification.samplerate.multi.maxDownsampler = 131072;
    this->specification.samplerate.multi.recordLengths << UINT_MAX << 20480
                                                       << 65536;
    this->specification.bufferDividers << 1000 << 1 << 1;
    this->specification.gainSteps << 0.08 << 0.16 << 0.40 << 0.80 << 1.60
                                  << 4.00 << 8.0 << 16.0 << 40.0;
    for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
      this->specification.voltageLimit[channel]
          << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255;
    this->specification.gainIndex << 0 << 1 << 2 << 0 << 1 << 2 << 0 << 1 << 2;
    this->specification.sampleSize = 8;
    break;

  case MODEL_DSO6022BE:
    this->specification.samplerate.single.base = 1e6;
    this->specification.samplerate.single.max = 48e6;
    this->specification.samplerate.single.maxDownsampler = 10;
    this->specification.samplerate.single.recordLengths << UINT_MAX << 10240
                                                        << 32768;
    this->specification.samplerate.multi.base = 1e6;
    this->specification.samplerate.multi.max = 48e6;
    this->specification.samplerate.multi.maxDownsampler = 10;
    this->specification.samplerate.multi.recordLengths << UINT_MAX << 20480
                                                       << 65536;
    this->specification.bufferDividers << 1000 << 1 << 1;
    this->specification.gainSteps << 0.08 << 0.16 << 0.40 << 0.80 << 1.60
                                  << 4.00 << 8.0 << 16.0 << 40.0;
    // This data was based on testing and depends on Divider.
    for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
      this->specification.voltageLimit[channel] << 25 << 51 << 103 << 206 << 412
                                                << 196 << 392 << 784 << 1000;
    // Divider. Tested and calculated results are different!
    this->specification.gainDiv << 10 << 10 << 10 << 10 << 10 << 2 << 2 << 2
                                << 1;
    this->specification.sampleSteps << 1e5 << 2e5 << 5e5 << 1e6 << 2e6 << 4e6
                                    << 8e6 << 16e6 << 24e6 << 48e6;
    this->specification.sampleDiv << 10 << 20 << 50 << 1 << 2 << 4 << 8 << 16
                                  << 24 << 48;
    this->specification.sampleSize = 8;
    break;

  default:
    this->specification.samplerate.single.base = 50e6;
    this->specification.samplerate.single.max = 50e6;
    this->specification.samplerate.single.maxDownsampler = 131072;
    this->specification.samplerate.single.recordLengths << UINT_MAX << 10240
                                                        << 32768;
    this->specification.samplerate.multi.base = 100e6;
    this->specification.samplerate.multi.max = 100e6;
    this->specification.samplerate.multi.maxDownsampler = 131072;
    this->specification.samplerate.multi.recordLengths << UINT_MAX << 20480
                                                       << 65536;
    this->specification.bufferDividers << 1000 << 1 << 1;
    this->specification.gainSteps << 0.08 << 0.16 << 0.40 << 0.80 << 1.60
                                  << 4.00 << 8.0 << 16.0 << 40.0;
    for (int channel = 0; channel < HANTEK_CHANNELS; ++channel)
      this->specification.voltageLimit[channel]
          << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255 << 255;
    this->specification.gainIndex << 0 << 1 << 2 << 0 << 1 << 2 << 0 << 1 << 2;
    this->specification.sampleSize = 8;
    break;
  }
  this->settings.recordLengthId = 1;
  this->settings.samplerate.limits = &(this->specification.samplerate.single);
  this->settings.samplerate.downsampler = 1;
  this->previousSampleCount = 0;

  // Get channel level data
  errorCode = this->device->controlRead(
      CONTROL_VALUE, (unsigned char *)&(this->specification.offsetLimit),
      sizeof(this->specification.offsetLimit), (int)VALUE_OFFSETLIMITS);
  if (errorCode < 0) {
    this->device->disconnect();
    emit statusMessage(tr("Couldn't get channel level data from oscilloscope"),
                       0);
    return;
  }

  // Emit signals for initial settings
  emit availableRecordLengthsChanged(
      this->settings.samplerate.limits->recordLengths);
  updateSamplerateLimits();
  emit recordLengthChanged(this->settings.samplerate.limits
                               ->recordLengths[this->settings.recordLengthId]);
  if (this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId] != UINT_MAX)
    emit recordTimeChanged((double)this->settings.samplerate.limits
                               ->recordLengths[this->settings.recordLengthId] /
                           this->settings.samplerate.current);
  emit samplerateChanged(this->settings.samplerate.current);

  if (this->device->getModel() == MODEL_DSO6022BE) {
    QList<double> sampleSteps;
    sampleSteps << 1.0 << 2.0 << 5.0 << 10.0 << 20.0 << 40.0 << 80.0 << 160.0
                << 240.0 << 480.0;
    emit samplerateSet(1, sampleSteps);
  }

  DsoControl::connectDevice();
}

/// \brief Sets the size of the oscilloscopes sample buffer.
/// \param index The record length index that should be set.
/// \return The record length that has been set, 0 on error.
unsigned int Control::setRecordLength(unsigned int index) {
  if (!this->device->isConnected())
    return 0;

  if (!this->updateRecordLength(index))
    return 0;

  this->restoreTargets();
  this->setPretriggerPosition(this->settings.trigger.position);

  emit recordLengthChanged(this->settings.samplerate.limits
                               ->recordLengths[this->settings.recordLengthId]);
  return this->settings.samplerate.limits
      ->recordLengths[this->settings.recordLengthId];
}

/// \brief Sets the samplerate of the oscilloscope.
/// \param samplerate The samplerate that should be met (S/s), 0.0 to restore
/// current samplerate.
/// \return The samplerate that has been set, 0.0 on error.
double Control::setSamplerate(double samplerate) {
  if (!this->device->isConnected())
    return 0.0;

  if (samplerate == 0.0) {
    samplerate = this->settings.samplerate.target.samplerate;
  } else {
    this->settings.samplerate.target.samplerate = samplerate;
    this->settings.samplerate.target.samplerateSet = true;
  }

  if (this->device->getModel() != MODEL_DSO6022BE) {
    // When possible, enable fast rate if it is required to reach the requested
    // samplerate
    bool fastRate =
        (this->settings.usedChannels <= 1) &&
        (samplerate >
         this->specification.samplerate.single.max /
             this->specification.bufferDividers[this->settings.recordLengthId]);

    // What is the nearest, at least as high samplerate the scope can provide?
    unsigned int downsampler = 0;
    double bestSamplerate =
        getBestSamplerate(samplerate, fastRate, false, &(downsampler));

    // Set the calculated samplerate
    if (this->updateSamplerate(downsampler, fastRate) == UINT_MAX)
      return 0.0;
    else {
      return bestSamplerate;
    }
  } else {
    int sampleId;
    for (sampleId = 0; sampleId < this->specification.sampleSteps.count() - 1;
         ++sampleId)
      if (this->specification.sampleSteps[sampleId] == samplerate)
        break;
    this->controlCode[CONTROLINDEX_SETTIMEDIV] = CONTROL_SETTIMEDIV;
    static_cast<ControlSetTimeDIV *>(this->control[CONTROLINDEX_SETTIMEDIV])
        ->setDiv(this->specification.sampleDiv[sampleId]);
    this->controlPending[CONTROLINDEX_SETTIMEDIV] = true;
    this->settings.samplerate.current = samplerate;

    // Check for Roll mode
    if (this->settings.samplerate.limits
            ->recordLengths[this->settings.recordLengthId] != UINT_MAX)
      emit recordTimeChanged(
          (double)this->settings.samplerate.limits
              ->recordLengths[this->settings.recordLengthId] /
          this->settings.samplerate.current);
    emit samplerateChanged(this->settings.samplerate.current);

    return samplerate;
  }
}

/// \brief Sets the time duration of one aquisition by adapting the samplerate.
/// \param duration The record time duration that should be met (s), 0.0 to
/// restore current record time.
/// \return The record time duration that has been set, 0.0 on error.
double Control::setRecordTime(double duration) {
  if (!this->device->isConnected())
    return 0.0;

  if (duration == 0.0) {
    duration = this->settings.samplerate.target.duration;
  } else {
    this->settings.samplerate.target.duration = duration;
    this->settings.samplerate.target.samplerateSet = false;
  }

  if (this->device->getModel() != MODEL_DSO6022BE) {
    // Calculate the maximum samplerate that would still provide the requested
    // duration
    double maxSamplerate = (double)this->specification.samplerate.single
                               .recordLengths[this->settings.recordLengthId] /
                           duration;

    // When possible, enable fast rate if the record time can't be set that low
    // to improve resolution
    bool fastRate =
        (this->settings.usedChannels <= 1) &&
        (maxSamplerate >=
         this->specification.samplerate.multi.base /
             this->specification.bufferDividers[this->settings.recordLengthId]);

    // What is the nearest, at most as high samplerate the scope can provide?
    unsigned int downsampler = 0;
    double bestSamplerate =
        getBestSamplerate(maxSamplerate, fastRate, true, &(downsampler));

    // Set the calculated samplerate
    if (this->updateSamplerate(downsampler, fastRate) == UINT_MAX)
      return 0.0;
    else {
      return (double)this->settings.samplerate.limits
                 ->recordLengths[this->settings.recordLengthId] /
             bestSamplerate;
    }
  } else {
    // For now - we go for the 10240 size sampling - the other seems not to be
    // supported
    // Find highest samplerate using less than 10240 samples to obtain our
    // duration.
    // Better add some margin for our SW trigger
    unsigned int sampleMargin = 2000;
    unsigned int sampleCount = 10240;
    int bestId = 0;
    int sampleId;
    for (sampleId = 0; sampleId < this->specification.sampleSteps.count();
         ++sampleId) {
      if (this->specification.sampleSteps[sampleId] * duration <
          (sampleCount - sampleMargin))
        bestId = sampleId;
    }
    sampleId = bestId;
    // Usable sample value
    this->controlCode[CONTROLINDEX_SETTIMEDIV] = CONTROL_SETTIMEDIV;
    static_cast<ControlSetTimeDIV *>(this->control[CONTROLINDEX_SETTIMEDIV])
        ->setDiv(this->specification.sampleDiv[sampleId]);
    this->controlPending[CONTROLINDEX_SETTIMEDIV] = true;
    this->settings.samplerate.current =
        this->specification.sampleSteps[sampleId];

    emit samplerateChanged(this->settings.samplerate.current);
    return this->settings.samplerate.current;
  }
}

/// \brief Enables/disables filtering of the given channel.
/// \param channel The channel that should be set.
/// \param used true if the channel should be sampled.
/// \return See ::Dso::ErrorCode.
int Control::setChannelUsed(unsigned int channel, bool used) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (channel >= HANTEK_CHANNELS)
    return Dso::ERROR_PARAMETER;

  // Update settings
  this->settings.voltage[channel].used = used;
  unsigned int channelCount = 0;
  for (int channelCounter = 0; channelCounter < HANTEK_CHANNELS;
       ++channelCounter) {
    if (this->settings.voltage[channelCounter].used)
      ++channelCount;
  }

  // Calculate the UsedChannels field for the command
  unsigned char usedChannels = USED_CH1;

  if (this->settings.voltage[1].used) {
    if (this->settings.voltage[0].used) {
      usedChannels = USED_CH1CH2;
    } else {
      // DSO-2250 uses a different value for channel 2
      if (this->specification.command.bulk.setChannels == BULK_BSETCHANNELS)
        usedChannels = BUSED_CH2;
      else
        usedChannels = USED_CH2;
    }
  }

  switch (this->specification.command.bulk.setChannels) {
  case BULK_SETTRIGGERANDSAMPLERATE: {
    // SetTriggerAndSamplerate bulk command for trigger source
    static_cast<BulkSetTriggerAndSamplerate *>(
        this->command[BULK_SETTRIGGERANDSAMPLERATE])
        ->setUsedChannels(usedChannels);
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;
    break;
  }
  case BULK_BSETCHANNELS: {
    // SetChannels2250 bulk command for active channels
    static_cast<BulkSetChannels2250 *>(this->command[BULK_BSETCHANNELS])
        ->setUsedChannels(usedChannels);
    this->commandPending[BULK_BSETCHANNELS] = true;

    break;
  }
  case BULK_ESETTRIGGERORSAMPLERATE: {
    // SetTrigger5200s bulk command for trigger source
    static_cast<BulkSetTrigger5200 *>(
        this->command[BULK_ESETTRIGGERORSAMPLERATE])
        ->setUsedChannels(usedChannels);
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;
    break;
  }
  default:
    break;
  }

  // Check if fast rate mode availability changed
  bool fastRateChanged =
      (this->settings.usedChannels <= 1) != (channelCount <= 1);
  this->settings.usedChannels = channelCount;

  if (fastRateChanged)
    this->updateSamplerateLimits();

  return Dso::ERROR_NONE;
}

/// \brief Set the coupling for the given channel.
/// \param channel The channel that should be set.
/// \param coupling The new coupling for the channel.
/// \return See ::Dso::ErrorCode.
int Control::setCoupling(unsigned int channel, Dso::Coupling coupling) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (channel >= HANTEK_CHANNELS)
    return Dso::ERROR_PARAMETER;

  //	if (this->device->getModel() == MODEL_DSO6022BE)
  //		Dso::ERROR_NONE;

  // SetRelays control command for coupling relays
  if (this->device->getModel() != MODEL_DSO6022BE) {
    static_cast<ControlSetRelays *>(this->control[CONTROLINDEX_SETRELAYS])
        ->setCoupling(channel, coupling != Dso::COUPLING_AC);
    this->controlPending[CONTROLINDEX_SETRELAYS] = true;
  }

  return Dso::ERROR_NONE;
}

/// \brief Sets the gain for the given channel.
/// \param channel The channel that should be set.
/// \param gain The gain that should be met (V/div).
/// \return The gain that has been set, ::Dso::ErrorCode on error.
double Control::setGain(unsigned int channel, double gain) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (channel >= HANTEK_CHANNELS)
    return Dso::ERROR_PARAMETER;

  // Find lowest gain voltage thats at least as high as the requested
  int gainId;
  for (gainId = 0; gainId < this->specification.gainSteps.count() - 1; ++gainId)
    if (this->specification.gainSteps[gainId] >= gain)
      break;

  // Fixme, shoulb be some kind of protocol check instead of model check.
  if (this->device->getModel() == MODEL_DSO6022BE) {
    if (channel == 0) {
      static_cast<ControlSetVoltDIV_CH1 *>(
          this->control[CONTROLINDEX_SETVOLTDIV_CH1])
          ->setDiv(this->specification.gainDiv[gainId]);
      this->controlPending[CONTROLINDEX_SETVOLTDIV_CH1] = true;
    } else if (channel == 1) {
      static_cast<ControlSetVoltDIV_CH2 *>(
          this->control[CONTROLINDEX_SETVOLTDIV_CH2])
          ->setDiv(this->specification.gainDiv[gainId]);
      this->controlPending[CONTROLINDEX_SETVOLTDIV_CH2] = true;
    } else
      qDebug("%s: Unsuported channel: %i\n", __func__, channel);
  } else {
    // SetGain bulk command for gain
    static_cast<BulkSetGain *>(this->command[BULK_SETGAIN])
        ->setGain(channel, this->specification.gainIndex[gainId]);
    this->commandPending[BULK_SETGAIN] = true;

    // SetRelays control command for gain relays
    ControlSetRelays *controlSetRelays =
        static_cast<ControlSetRelays *>(this->control[CONTROLINDEX_SETRELAYS]);
    controlSetRelays->setBelow1V(channel, gainId < 3);
    controlSetRelays->setBelow100mV(channel, gainId < 6);
    this->controlPending[CONTROLINDEX_SETRELAYS] = true;
  }

  this->settings.voltage[channel].gain = gainId;

  this->setOffset(channel, this->settings.voltage[channel].offset);

  return this->specification.gainSteps[gainId];
}

/// \brief Set the offset for the given channel.
/// \param channel The channel that should be set.
/// \param offset The new offset value (0.0 - 1.0).
/// \return The offset that has been set, ::Dso::ErrorCode on error.
double Control::setOffset(unsigned int channel, double offset) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (channel >= HANTEK_CHANNELS)
    return Dso::ERROR_PARAMETER;

  // Calculate the offset value
  // The range is given by the calibration data (convert from big endian)
  unsigned short int minimum =
      ((unsigned short int)*((unsigned char *)&(
           this->specification
               .offsetLimit[channel][this->settings.voltage[channel].gain]
                           [OFFSET_START]))
       << 8) +
      *((unsigned char *)&(
            this->specification
                .offsetLimit[channel][this->settings.voltage[channel].gain]
                            [OFFSET_START]) +
        1);
  unsigned short int maximum =
      ((unsigned short int)*((unsigned char *)&(
           this->specification
               .offsetLimit[channel][this->settings.voltage[channel].gain]
                           [OFFSET_END]))
       << 8) +
      *((unsigned char *)&(
            this->specification
                .offsetLimit[channel][this->settings.voltage[channel].gain]
                            [OFFSET_END]) +
        1);
  unsigned short int offsetValue = offset * (maximum - minimum) + minimum + 0.5;
  double offsetReal = (double)(offsetValue - minimum) / (maximum - minimum);

  // SetOffset control command for channel offset
  // Don't set control command if 6022be.
  // Otherwise, pipe error messages will be appeared.
  if (this->device->getModel() != MODEL_DSO6022BE) {
    static_cast<ControlSetOffset *>(this->control[CONTROLINDEX_SETOFFSET])
        ->setChannel(channel, offsetValue);
    this->controlPending[CONTROLINDEX_SETOFFSET] = true;
  }

  this->settings.voltage[channel].offset = offset;
  this->settings.voltage[channel].offsetReal = offsetReal;

  this->setTriggerLevel(channel, this->settings.trigger.level[channel]);

  return offsetReal;
}

/// \brief Set the trigger mode.
/// \return See ::Dso::ErrorCode.
int Control::setTriggerMode(Dso::TriggerMode mode) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (mode < Dso::TRIGGERMODE_AUTO || mode >= Dso::TRIGGERMODE_COUNT)
    return Dso::ERROR_PARAMETER;

  this->settings.trigger.mode = mode;
  return Dso::ERROR_NONE;
}

/// \brief Set the trigger source.
/// \param special true for a special channel (EXT, ...) as trigger source.
/// \param id The number of the channel, that should be used as trigger.
/// \return See ::Dso::ErrorCode.
int Control::setTriggerSource(bool special, unsigned int id) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if ((!special && id >= HANTEK_CHANNELS) ||
      (special && id >= HANTEK_SPECIAL_CHANNELS))
    return Dso::ERROR_PARAMETER;

  switch (this->specification.command.bulk.setTrigger) {
  case BULK_SETTRIGGERANDSAMPLERATE:
    // SetTriggerAndSamplerate bulk command for trigger source
    static_cast<BulkSetTriggerAndSamplerate *>(
        this->command[BULK_SETTRIGGERANDSAMPLERATE])
        ->setTriggerSource(special ? 3 + id : 1 - id);
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;
    break;

  case BULK_CSETTRIGGERORSAMPLERATE:
    // SetTrigger2250 bulk command for trigger source
    static_cast<BulkSetTrigger2250 *>(
        this->command[BULK_CSETTRIGGERORSAMPLERATE])
        ->setTriggerSource(special ? 0 : 2 + id);
    this->commandPending[BULK_CSETTRIGGERORSAMPLERATE] = true;
    break;

  case BULK_ESETTRIGGERORSAMPLERATE:
    // SetTrigger5200 bulk command for trigger source
    static_cast<BulkSetTrigger5200 *>(
        this->command[BULK_ESETTRIGGERORSAMPLERATE])
        ->setTriggerSource(special ? 3 + id : 1 - id);
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;
    break;

  default:
    return Dso::ERROR_UNSUPPORTED;
  }

  // SetRelays control command for external trigger relay
  static_cast<ControlSetRelays *>(this->control[CONTROLINDEX_SETRELAYS])
      ->setTrigger(special);
  this->controlPending[CONTROLINDEX_SETRELAYS] = true;

  this->settings.trigger.special = special;
  this->settings.trigger.source = id;

  // Apply trigger level of the new source
  if (special) {
    // SetOffset control command for changed trigger level
    static_cast<ControlSetOffset *>(this->control[CONTROLINDEX_SETOFFSET])
        ->setTrigger(0x7f);
    this->controlPending[CONTROLINDEX_SETOFFSET] = true;
  } else
    this->setTriggerLevel(id, this->settings.trigger.level[id]);

  return Dso::ERROR_NONE;
}

/// \brief Set the trigger level.
/// \param channel The channel that should be set.
/// \param level The new trigger level (V).
/// \return The trigger level that has been set, ::Dso::ErrorCode on error.
double Control::setTriggerLevel(unsigned int channel, double level) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (channel >= HANTEK_CHANNELS)
    return Dso::ERROR_PARAMETER;

  //		if (this->device->getModel() == MODEL_DSO6022BE)
  //			return Dso::ERROR_NONE;

  // Calculate the trigger level value
  unsigned short int minimum, maximum;
  switch (this->device->getModel()) {
  case MODEL_DSO5200:
  case MODEL_DSO5200A:
    // The range is the same as used for the offsets for 10 bit models
    minimum =
        ((unsigned short int)*((unsigned char *)&(
             this->specification
                 .offsetLimit[channel][this->settings.voltage[channel].gain]
                             [OFFSET_START]))
         << 8) +
        *((unsigned char *)&(
              this->specification
                  .offsetLimit[channel][this->settings.voltage[channel].gain]
                              [OFFSET_START]) +
          1);
    maximum =
        ((unsigned short int)*((unsigned char *)&(
             this->specification
                 .offsetLimit[channel][this->settings.voltage[channel].gain]
                             [OFFSET_END]))
         << 8) +
        *((unsigned char *)&(
              this->specification
                  .offsetLimit[channel][this->settings.voltage[channel].gain]
                              [OFFSET_END]) +
          1);
    break;

  default:
    // It's from 0x00 to 0xfd for the 8 bit models
    minimum = 0x00;
    maximum = 0xfd;
    break;
  }

  // Never get out of the limits
  unsigned short int levelValue = qBound(
      (long int)minimum,
      (long int)((this->settings.voltage[channel].offsetReal +
                  level /
                      this->specification
                          .gainSteps[this->settings.voltage[channel].gain]) *
                     (maximum - minimum) +
                 0.5) +
          minimum,
      (long int)maximum);

  // Check if the set channel is the trigger source
  if (!this->settings.trigger.special &&
      channel == this->settings.trigger.source &&
      this->device->getModel() != MODEL_DSO6022BE) {
    // SetOffset control command for trigger level
    static_cast<ControlSetOffset *>(this->control[CONTROLINDEX_SETOFFSET])
        ->setTrigger(levelValue);
    this->controlPending[CONTROLINDEX_SETOFFSET] = true;
  }

  /// \todo Get alternating trigger in here

  this->settings.trigger.level[channel] = level;
  return (double)((levelValue - minimum) / (maximum - minimum) -
                  this->settings.voltage[channel].offsetReal) *
         this->specification.gainSteps[this->settings.voltage[channel].gain];
}

/// \brief Set the trigger slope.
/// \param slope The Slope that should cause a trigger.
/// \return See ::Dso::ErrorCode.
int Control::setTriggerSlope(Dso::Slope slope) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  if (slope != Dso::SLOPE_NEGATIVE && slope != Dso::SLOPE_POSITIVE)
    return Dso::ERROR_PARAMETER;

  switch (this->specification.command.bulk.setTrigger) {
  case BULK_SETTRIGGERANDSAMPLERATE: {
    // SetTriggerAndSamplerate bulk command for trigger slope
    static_cast<BulkSetTriggerAndSamplerate *>(
        this->command[BULK_SETTRIGGERANDSAMPLERATE])
        ->setTriggerSlope(slope);
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;
    break;
  }
  case BULK_CSETTRIGGERORSAMPLERATE: {
    // SetTrigger2250 bulk command for trigger slope
    static_cast<BulkSetTrigger2250 *>(
        this->command[BULK_CSETTRIGGERORSAMPLERATE])
        ->setTriggerSlope(slope);
    this->commandPending[BULK_CSETTRIGGERORSAMPLERATE] = true;
    break;
  }
  case BULK_ESETTRIGGERORSAMPLERATE: {
    // SetTrigger5200 bulk command for trigger slope
    static_cast<BulkSetTrigger5200 *>(
        this->command[BULK_ESETTRIGGERORSAMPLERATE])
        ->setTriggerSlope(slope);
    this->commandPending[BULK_ESETTRIGGERORSAMPLERATE] = true;
    break;
  }
  default:
    return Dso::ERROR_UNSUPPORTED;
  }

  this->settings.trigger.slope = slope;
  return Dso::ERROR_NONE;
}

int Control::forceTrigger() {
  this->commandPending[BULK_FORCETRIGGER] = true;
  return 0;
}

/// \brief Set the trigger position.
/// \param position The new trigger position (in s).
/// \return The trigger position that has been set.
double Control::setPretriggerPosition(double position) {
  if (!this->device->isConnected())
    return -2;

  // All trigger positions are measured in samples
  unsigned int positionSamples = position * this->settings.samplerate.current;
  unsigned int recordLength =
      this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId];
  bool rollMode = recordLength == UINT_MAX;
  // Fast rate mode uses both channels
  if (this->settings.samplerate.limits == &this->specification.samplerate.multi)
    positionSamples /= HANTEK_CHANNELS;

  switch (this->specification.command.bulk.setPretrigger) {
  case BULK_SETTRIGGERANDSAMPLERATE: {
    // Calculate the position value (Start point depending on record length)
    unsigned int position =
        rollMode ? 0x1 : 0x7ffff - recordLength + positionSamples;

    // SetTriggerAndSamplerate bulk command for trigger position
    static_cast<BulkSetTriggerAndSamplerate *>(
        this->command[BULK_SETTRIGGERANDSAMPLERATE])
        ->setTriggerPosition(position);
    this->commandPending[BULK_SETTRIGGERANDSAMPLERATE] = true;

    break;
  }
  case BULK_FSETBUFFER: {
    // Calculate the position values (Inverse, maximum is 0x7ffff)
    unsigned int positionPre = 0x7ffff - recordLength + positionSamples;
    unsigned int positionPost = 0x7ffff - positionSamples;

    // SetBuffer2250 bulk command for trigger position
    BulkSetBuffer2250 *commandSetBuffer2250 =
        static_cast<BulkSetBuffer2250 *>(this->command[BULK_FSETBUFFER]);
    commandSetBuffer2250->setTriggerPositionPre(positionPre);
    commandSetBuffer2250->setTriggerPositionPost(positionPost);
    this->commandPending[BULK_FSETBUFFER] = true;

    break;
  }
  case BULK_ESETTRIGGERORSAMPLERATE: {
    // Calculate the position values (Inverse, maximum is 0xffff)
    unsigned short int positionPre = 0xffff - recordLength + positionSamples;
    unsigned short int positionPost = 0xffff - positionSamples;

    // SetBuffer5200 bulk command for trigger position
    BulkSetBuffer5200 *commandSetBuffer5200 =
        static_cast<BulkSetBuffer5200 *>(this->command[BULK_DSETBUFFER]);
    commandSetBuffer5200->setTriggerPositionPre(positionPre);
    commandSetBuffer5200->setTriggerPositionPost(positionPost);
    this->commandPending[BULK_DSETBUFFER] = true;

    break;
  }
  default:
    return Dso::ERROR_UNSUPPORTED;
  }

  this->settings.trigger.position = position;
  return (double)positionSamples / this->settings.samplerate.current;
}

#ifdef DEBUG
/// \brief Sends bulk/control commands directly.
/// <p>
///		<b>Syntax:</b><br />
///		<br />
///		Bulk command:
///		<pre>send bulk [<em>hex data</em>]</pre>
///		%Control command:
///		<pre>send control [<em>hex code</em>] [<em>hex data</em>]</pre>
/// </p>
/// \param command The command as string (Has to be parsed).
/// \return See ::Dso::ErrorCode.
int Control::stringCommand(QString command) {
  if (!this->device->isConnected())
    return Dso::ERROR_CONNECTION;

  QStringList commandParts = command.split(' ', QString::SkipEmptyParts);

  if (commandParts.count() >= 1) {
    if (commandParts[0] == "send") {
      if (commandParts.count() >= 2) {
        if (commandParts[1] == "bulk") {
          QString data = command.section(' ', 2, -1, QString::SectionSkipEmpty);
          unsigned char commandCode = 0;

          // Read command code (First byte)
          Helper::hexParse(commandParts[2], &commandCode, 1);
          if (commandCode > BULK_COUNT)
            return Dso::ERROR_UNSUPPORTED;

          // Update bulk command and mark as pending
          Helper::hexParse(data, this->command[commandCode]->data(),
                           this->command[commandCode]->getSize());
          this->commandPending[commandCode] = true;
          return Dso::ERROR_NONE;
        } else if (commandParts[1] == "control") {
          unsigned char controlCode = 0;

          // Read command code (First byte)
          Helper::hexParse(commandParts[2], &controlCode, 1);
          int control;
          for (control = 0; control < CONTROLINDEX_COUNT; ++control) {
            if (this->controlCode[control] == controlCode)
              break;
          }
          if (control >= CONTROLINDEX_COUNT)
            return Dso::ERROR_UNSUPPORTED;

          QString data = command.section(' ', 3, -1, QString::SectionSkipEmpty);

          // Update control command and mark as pending
          Helper::hexParse(data, this->control[control]->data(),
                           this->control[control]->getSize());
          this->controlPending[control] = true;
          return Dso::ERROR_NONE;
        }
      } else {
        return Dso::ERROR_PARAMETER;
      }
    }
  } else {
    return Dso::ERROR_PARAMETER;
  }

  return Dso::ERROR_UNSUPPORTED;
}
#endif

/// \brief Called periodically in the control thread by a timer.
void Control::handler() {
  int errorCode = 0;

  // Send all pending bulk commands
  for (int command = 0; command < BULK_COUNT; ++command) {
    if (!this->commandPending[command])
      continue;

#ifdef DEBUG
    Helper::timestampDebug(
        QString("Sending bulk command:%1")
            .arg(Helper::hexDump(this->command[command]->data(),
                                 this->command[command]->getSize())));
#endif

    errorCode = this->device->bulkCommand(this->command[command]);
    if (errorCode < 0) {
      qWarning("Sending bulk command %02x failed: %s", command,
               Helper::libUsbErrorString(errorCode).toLocal8Bit().data());

      if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
        this->quit();
        return;
      }
    } else
      this->commandPending[command] = false;
  }

  // Send all pending control commands
  for (int control = 0; control < CONTROLINDEX_COUNT; ++control) {
    if (!this->controlPending[control])
      continue;

#ifdef DEBUG
    Helper::timestampDebug(
        QString("Sending control command %1:%2")
            .arg(QString::number(this->controlCode[control], 16),
                 Helper::hexDump(this->control[control]->data(),
                                 this->control[control]->getSize())));
#endif

    errorCode = this->device->controlWrite(this->controlCode[control],
                                           this->control[control]->data(),
                                           this->control[control]->getSize());
    if (errorCode < 0) {
      qWarning("Sending control command %2x failed: %s",
               this->controlCode[control],
               Helper::libUsbErrorString(errorCode).toLocal8Bit().data());

      if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
        this->quit();
        return;
      }
    } else
      this->controlPending[control] = false;
  }

  // State machine for the device communication
  if (this->settings.samplerate.limits
          ->recordLengths[this->settings.recordLengthId] == UINT_MAX) {
    // Roll mode
    this->captureState = CAPTURE_WAITING;
    bool toNextState = true;

    switch (this->rollState) {
    case ROLL_STARTSAMPLING:
      // Don't iterate through roll mode steps when stopped
      if (!this->sampling) {
        toNextState = false;
        break;
      }

      // Sampling hasn't started, update the expected sample count
      this->previousSampleCount = this->getSampleCount();

      errorCode = this->device->bulkCommand(this->command[BULK_STARTSAMPLING]);
      if (errorCode < 0) {
        if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
          this->quit();
          return;
        }
        break;
      }
#ifdef DEBUG
      Helper::timestampDebug("Starting to capture");
#endif

      this->samplingStarted = true;

      break;

    case ROLL_ENABLETRIGGER:
      errorCode = this->device->bulkCommand(this->command[BULK_ENABLETRIGGER]);
      if (errorCode < 0) {
        if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
          this->quit();
          return;
        }
        break;
      }
#ifdef DEBUG
      Helper::timestampDebug("Enabling trigger");
#endif

      break;

    case ROLL_FORCETRIGGER:
      errorCode = this->device->bulkCommand(this->command[BULK_FORCETRIGGER]);
      if (errorCode < 0) {
        if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
          this->quit();
          return;
        }
        break;
      }
#ifdef DEBUG
      Helper::timestampDebug("Forcing trigger");
#endif

      break;

    case ROLL_GETDATA:
      // Get data and process it, if we're still sampling
      errorCode = this->getSamples(this->samplingStarted);
      if (errorCode < 0)
        qWarning("Getting sample data failed: %s",
                 Helper::libUsbErrorString(errorCode).toLocal8Bit().data());
#ifdef DEBUG
      else
        Helper::timestampDebug(
            QString("Received %1 B of sampling data").arg(errorCode));
#endif

      // Check if we're in single trigger mode
      if (this->settings.trigger.mode == Dso::TRIGGERMODE_SINGLE &&
          this->samplingStarted)
        this->stopSampling();

      // Sampling completed, restart it when necessary
      this->samplingStarted = false;

      break;

    default:
#ifdef DEBUG
      Helper::timestampDebug("Roll mode state unknown");
#endif
      break;
    }

    // Go to next state, or restart if last state was reached
    if (toNextState)
      this->rollState = (this->rollState + 1) % ROLL_COUNT;
  } else {
    // Standard mode
    this->rollState = ROLL_STARTSAMPLING;

#ifdef DEBUG
    int lastCaptureState = this->captureState;
#endif
    this->captureState = this->getCaptureState();
    if (this->captureState < 0)
      qWarning(
          "Getting capture state failed: %s",
          Helper::libUsbErrorString(this->captureState).toLocal8Bit().data());
#ifdef DEBUG
    else if (this->captureState != lastCaptureState)
      Helper::timestampDebug(
          QString("Capture state changed to %1").arg(this->captureState));
#endif
    switch (this->captureState) {
    case CAPTURE_READY:
    case CAPTURE_READY2250:
    case CAPTURE_READY5200:
      // Get data and process it, if we're still sampling
      errorCode = this->getSamples(this->samplingStarted);
      if (errorCode < 0)
        qWarning("Getting sample data failed: %s",
                 Helper::libUsbErrorString(errorCode).toLocal8Bit().data());
#ifdef DEBUG
      else
        Helper::timestampDebug(
            QString("Received %1 B of sampling data").arg(errorCode));
#endif

      // Check if we're in single trigger mode
      if (this->settings.trigger.mode == Dso::TRIGGERMODE_SINGLE &&
          this->samplingStarted)
        this->stopSampling();

      // Sampling completed, restart it when necessary
      this->samplingStarted = false;

      // Start next capture if necessary by leaving out the break statement
      if (!this->sampling)
        break;

    case CAPTURE_WAITING:
      // Sampling hasn't started, update the expected sample count
      this->previousSampleCount = this->getSampleCount();

      if (this->samplingStarted &&
          this->lastTriggerMode == this->settings.trigger.mode) {
        ++this->cycleCounter;

        if (this->cycleCounter == this->startCycle &&
            this->settings.samplerate.limits
                    ->recordLengths[this->settings.recordLengthId] !=
                UINT_MAX) {
          // Buffer refilled completely since start of sampling, enable the
          // trigger now
          errorCode =
              this->device->bulkCommand(this->command[BULK_ENABLETRIGGER]);
          if (errorCode < 0) {
            if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
              this->quit();
              return;
            }
            break;
          }
#ifdef DEBUG
          Helper::timestampDebug("Enabling trigger");
#endif
        } else if (this->cycleCounter >= 8 + this->startCycle &&
                   this->settings.trigger.mode == Dso::TRIGGERMODE_AUTO) {
          // Force triggering
          errorCode =
              this->device->bulkCommand(this->command[BULK_FORCETRIGGER]);
          if (errorCode < 0) {
            if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
              this->quit();
              return;
            }
            break;
          }
#ifdef DEBUG
          Helper::timestampDebug("Forcing trigger");
#endif
        }

        if (this->cycleCounter < 20 ||
            this->cycleCounter < 4000 / this->timer->interval())
          break;
      }

      // Start capturing
      errorCode = this->device->bulkCommand(this->command[BULK_STARTSAMPLING]);
      if (errorCode < 0) {
        if (errorCode == LIBUSB_ERROR_NO_DEVICE) {
          this->quit();
          return;
        }
        break;
      }
#ifdef DEBUG
      Helper::timestampDebug("Starting to capture");
#endif

      this->samplingStarted = true;
      this->cycleCounter = 0;
      this->startCycle =
          this->settings.trigger.position * 1000 / this->timer->interval() + 1;
      this->lastTriggerMode = this->settings.trigger.mode;
      break;

    case CAPTURE_SAMPLING:
      break;
    default:
      break;
    }
  }

  this->updateInterval();
}
}