Typica is a free program for professional coffee roasters. https://typica.us
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

dataqsdk.w 45KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. @** Support for Devices Using the DATAQ SDK.
  2. \noindent Support for hardware from DATAQ Instruments is currently provided
  3. through the DATAQ SDK. This means that this support is currently only available
  4. on Microsoft Windows. The first planned supported device is the DI-145 with
  5. support for the DI-148U planned later. The devices are sufficiently similar
  6. that adding support for other devices from this manufacturer should be easy,
  7. but I do not have hardware samples to use for testing with other devices. The
  8. DI-145 additionally has a documented serial protocol which should make the
  9. hardware usable without the DATAQ SDK both on Microsoft Windows and on other
  10. platforms for which there is a suitable serial driver.
  11. Originally the classes were surrounded with conditional compilation directives
  12. but moc failed to generate the appropriate meta-objects on Windows when this
  13. was done. The |DataqSdkDevice| and |DataqSdkDeviceImplementation| classes will
  14. truly only work on Microsoft Windows at this time. Attempts to use it elsewhere
  15. will not end well.
  16. @<Class declarations@>=
  17. class DataqSdkDeviceImplementation;
  18. class DataqSdkDevice : public QObject
  19. {
  20. Q_OBJECT
  21. DataqSdkDeviceImplementation *imp;
  22. private slots:
  23. void threadFinished();
  24. public:
  25. DataqSdkDevice(QString device);
  26. ~DataqSdkDevice();
  27. Channel* newChannel(Units::Unit scale);
  28. Q_INVOKABLE void setClockRate(double Hz);
  29. Q_INVOKABLE void start();
  30. static QStringList detectPorts();
  31. static QStringList detectHardware(); // Friendly names
  32. };
  33. @ The |DataqSdkDevice| class has as a private member an instance of a class
  34. called |DataqSdkDeviceImplementation|. The two classes together create and run
  35. a new thread of execution. This thread spends most of its time blocking while
  36. waiting for a new measurement to become available. When a new measurement is
  37. available, that measurement is passed to the appropriate channel which in turn
  38. passes it to any interested object.
  39. Note that subclassing |QThread| in this way is no longer considered best
  40. practice. This particular code architecture is based on code written when this
  41. was considered the right thing to do, but it would be good to rewrite this to
  42. not subclass |QThread| now that this is no longer required.
  43. @<Class declarations@>=
  44. class DataqSdkDeviceImplementation : public QThread
  45. {
  46. Q_OBJECT
  47. public:
  48. DataqSdkDeviceImplementation();
  49. ~DataqSdkDeviceImplementation();
  50. void run();
  51. @<DATAQ SDK library function pointers@>@;
  52. @<DataqSdkDeviceImplementation member data@>@;
  53. public slots:
  54. void measure();
  55. private:
  56. qint16 *buffer;
  57. };
  58. @ While the |DAQ| class for communicating with National Instruments devices
  59. uses a single function pointer type, increased variety of function signatures
  60. in the DATAQ SDK makes using several types a better option. This also
  61. eliminates the need for explicit casts on the arguments.
  62. @<DATAQ SDK library function pointers@>=
  63. typedef struct di_inlist_struct {
  64. unsigned short chan;
  65. unsigned short diff;
  66. unsigned short gain;
  67. unsigned short unipolar;
  68. unsigned short dig_out_enable;
  69. unsigned short dig_out;
  70. unsigned short ave;
  71. unsigned short counter;
  72. } DI_INLIST_STRUCT;
  73. typedef int (PASCAL *FPDIOPEN)(unsigned);
  74. typedef int (PASCAL *FPDICLOSE)(void);
  75. typedef double (PASCAL *FPDISAMPLERATE)(double, long*, long*);
  76. typedef double (PASCAL *FPDIMAXIMUMRATE)(double);
  77. typedef int (PASCAL *FPDILISTLENGTH)(unsigned, unsigned);
  78. typedef int (PASCAL *FPDIINLIST)(di_inlist_struct*);
  79. typedef int* (PASCAL *FPDIBUFFERALLOC)(unsigned, unsigned);
  80. typedef int (PASCAL *FPDISTARTSCAN)(void);
  81. typedef unsigned (PASCAL *FPDISTATUSREAD)(short*, unsigned);
  82. typedef unsigned (PASCAL *FPDIBUFFERSTATUS)(unsigned);
  83. typedef int (PASCAL *FPDIBURSTRATE)(unsigned);
  84. typedef int (PASCAL *FPDISTOPSCAN)(void);
  85. FPDIOPEN di_open;
  86. FPDICLOSE di_close;
  87. FPDISAMPLERATE di_sample_rate;
  88. FPDIMAXIMUMRATE di_maximum_rate;
  89. FPDILISTLENGTH di_list_length;
  90. FPDIINLIST di_inlist;
  91. FPDIBUFFERALLOC di_buffer_alloc;
  92. FPDISTARTSCAN di_start_scan;
  93. FPDISTATUSREAD di_status_read;
  94. FPDIBUFFERSTATUS di_buffer_status;
  95. FPDIBURSTRATE di_burst_rate;
  96. FPDISTOPSCAN di_stop_scan;
  97. @ The |PASCAL| macro is defined in the {\tt windef.h} header file which will
  98. need to be included. This modifies the mechanics of the function call. A
  99. feature of the C language which C++ inherits is the ability to create variadic
  100. functions. To facilitate this, when one function calls another, the function
  101. making that call is responsible for cleaning up the stack. The function being
  102. called has no reliable way of knowing how many and what type of arguments have
  103. been passed if it is a variadic function, but this can be determined in the
  104. calling function at compile time. This is effectively a compiler implementation
  105. detail which is unimportant to the vast majority of application code. Use of
  106. the |PASCAL| macro informs the compiler that the function being called will
  107. clean up the stack itself. This precludes the use of variadic functions, but
  108. results in a smaller executable. The choice of name for that macro is
  109. unfortunate as arguments are placed on the stack in the order opposite of
  110. calling conventions of the Pascal programming language, but these are
  111. unimportant details so long as the resulting program works.
  112. @<Header files to include@>=
  113. #ifdef Q_OS_WIN32
  114. #include <windef.h>
  115. #else
  116. #define PASCAL
  117. #endif
  118. @ |DataqSdkDeviceImplementation| maintains information about the device and the
  119. channels the measurements are sent to.
  120. @<DataqSdkDeviceImplementation member data@>=
  121. bool isOpen;
  122. double sampleRate;
  123. long oversample;
  124. long burstDivisor;
  125. QString device;
  126. unsigned deviceNumber;
  127. QVector<Channel*> channelMap;
  128. int error;
  129. int channels;
  130. bool ready;
  131. QLibrary *driver;
  132. QVector<Units::Unit> unitMap;
  133. int *input_buffer;
  134. QTimer *eventClock;
  135. QMultiMap<int, double> smoother;
  136. @ Most of the interesting work associated with the |DataqSdkDevice| class is
  137. handled in the |measure()| method of |DataqSdkDeviceImplementation|. This
  138. method will block until a measurement is available. Once |buffer| is filled by
  139. |di_status_read()| that function returns and new |Measurement| objects are
  140. created based on the information in the buffer. These measurements are sent to
  141. |Channel| objects tracked by |channelMap|.
  142. The buffered values are presented in terms of ADC counts. Before using these
  143. values to convert to a voltage measurement, the two least significant binary
  144. digits of the count are set to 0 to improve measurement accuracy as recommended
  145. in the DATAQ SDK reference documentation.
  146. One of the use cases for this class is using the data port provided on some
  147. roasters from Diedrich Manufacturing. In this case there are three channels
  148. that are used: one provides a 0-10V signal that maps to temperature
  149. measurements of 32 to 1832 degrees F, one provides a signal in the same range
  150. requiring distinguishing among three values for air flow settings, and one is
  151. intended to show a percentage for the fuel setting. After experimenting with
  152. the most direct approach, there are limitations of the hardware that complicate
  153. matters for the channel representing bean temperature. The hardware is
  154. providing a 14 bit value representing a signal in the range of +/-10V so as a
  155. practical matter we only have 13 bits for temperature values. There is a desire
  156. to present measurements with at least one digit after the decimal point,
  157. meaning that we require 18,000 distinct values despite likely only ever seeing
  158. values in the lower third of that range. A 13 bit value only allows 8,192
  159. distinct values to be represented. The result of this is that stable signals
  160. between representable values are coded in an inconsistent fashion which can be
  161. seen as displayed measurements varying erratically. The usual solution to this
  162. problem is to collect many measurements quickly and average them, which is a
  163. reasonable thing to do with the sample rates available on DATAQ hardware.
  164. Examining measurements at a higher sample rate unfortunately reveals a periodic
  165. structure to the measurement error which averaging alone is not adequate to
  166. solve. The quality of the measurements can be improved somewhat by removing the
  167. extreme values from each set of measurements prior to averaging, however this
  168. does not fully address the lower frequency error sources. Further improvements
  169. can be made by maintaining a multimap of recent ADC count values to averaged
  170. voltage values and producing results that take this slightly longer term data
  171. into account. This is essential for obtaining a sufficiently stable low
  172. temperature calibration value and introduces minimal additional measurement
  173. latency during a roast.
  174. At present smoothing is applied to the first data channel and no others. It
  175. should be possible to enable or disable adaptive smoothing for all channels
  176. independently to better handle different hardware configurations.
  177. @<DataqSdkDevice implementation@>=
  178. void DataqSdkDeviceImplementation::measure()
  179. {
  180. unsigned count = channels * 40;
  181. di_status_read(buffer, count);
  182. QTime time = QTime::currentTime();
  183. for(unsigned int i = 0; i < count; i++)
  184. {
  185. buffer[i] = buffer[i] & 0xFFFC;
  186. }
  187. QList<int> countList;
  188. for(unsigned int i = 0; i < (unsigned)channels; i++)
  189. {
  190. QList<double> channelBuffer;
  191. for(unsigned int j = 0; j < 40; j++)
  192. {
  193. channelBuffer << ((double)buffer[i+(channels*j)] * 10.0) / 32768.0;
  194. if(i == 0)
  195. {
  196. countList << buffer[i+(channels*j)];
  197. }
  198. }
  199. double value = 0.0;
  200. for(unsigned int j = 0; j < 40; j++)
  201. {
  202. value += channelBuffer[j];
  203. }
  204. value /= 40.0;
  205. if(i == 0)
  206. {
  207. QList<double> smoothingList;
  208. smoothingList << value;
  209. QList<int> smoothingKeys = smoother.uniqueKeys();
  210. for(int j = 0; j < smoothingKeys.size(); j++)
  211. {
  212. if(countList.contains(smoothingKeys[j]))
  213. {
  214. QList<double> keyValues = smoother.values(smoothingKeys[j]);
  215. for(int k = 0; k < keyValues.size(); k++)
  216. {
  217. smoothingList << keyValues[k];
  218. }
  219. }
  220. else
  221. {
  222. smoother.remove(smoothingKeys[j]);
  223. }
  224. }
  225. qSort(countList);
  226. int lastCount = 0;
  227. for(int j = 0; j < countList.size(); j++)
  228. {
  229. if(j == 0 || countList[j] != lastCount)
  230. {
  231. smoother.insert(countList[j], value);
  232. lastCount = countList[j];
  233. }
  234. }
  235. value = 0.0;
  236. for(int j = 0; j < smoothingList.size(); j++)
  237. {
  238. value += smoothingList[j];
  239. }
  240. value /= smoothingList.size();
  241. }
  242. Measurement measure(value, time, unitMap[i]);
  243. channelMap[i]->input(measure);
  244. }
  245. }
  246. @ It was noted that |di_status_read()| blocks until it is able to fill the
  247. |buffer| passed to it. To prevent this behavior from having adverse effects on
  248. the rest of the program, |measure()| is called from a loop running in its own
  249. thread of execution. When the thread is started, it begins its execution from
  250. the |run()| method of |DataqSdkDeviceImplementation| which overrides the
  251. |run()| method of |QThread|.
  252. The while loop is controlled by |ready| which is set to |false| when there is
  253. an error in collecting a measurement or when there is a desire to stop logging.
  254. It could also be set to |false| for reconfiguration events.
  255. All device initialization happens in this method.
  256. Note that while the equivalent method when communicating with National
  257. Instruments hardware sets a time critical thread priority in an attempt to cut
  258. down on the variation in time between recorded measurements, that is a really
  259. bad idea when using the DATAQ SDK. The result was that the main thread never
  260. got enough time to report measurements and responsiveness throughout the entire
  261. system became barely usable to the point that it was difficult to kill the
  262. process. If anybody reading this can provide some insight into why setting the
  263. thread priority is fine with interacting with either DAQmx or DAQmxBase but not
  264. when interacting with the DATAQ SDK, I would like to read such an explanation.
  265. @<DataqSdkDevice implementation@>=
  266. void DataqSdkDeviceImplementation::run()
  267. {
  268. if(!ready)
  269. {
  270. error = 9; // Device data not available
  271. return;
  272. }
  273. driver = new QLibrary(device);
  274. if(!driver->load())
  275. {
  276. error = 1; // Failed to load driver.
  277. qDebug() << "Failed to load driver: " << device;
  278. return;
  279. }
  280. di_open = (FPDIOPEN)driver->resolve("di_open");
  281. di_close = (FPDICLOSE)driver->resolve("di_close");
  282. di_sample_rate = (FPDISAMPLERATE)driver->resolve("di_sample_rate");
  283. di_maximum_rate = (FPDIMAXIMUMRATE)driver->resolve("di_maximum_rate");
  284. di_list_length = (FPDILISTLENGTH)driver->resolve("di_list_length");
  285. di_inlist = (FPDIINLIST)driver->resolve("di_inlist");
  286. di_buffer_alloc = (FPDIBUFFERALLOC)driver->resolve("di_buffer_alloc");
  287. di_start_scan = (FPDISTARTSCAN)driver->resolve("di_start_scan");
  288. di_status_read = (FPDISTATUSREAD)driver->resolve("di_status_read");
  289. di_buffer_status = (FPDIBUFFERSTATUS)driver->resolve("di_buffer_status");
  290. di_burst_rate = (FPDIBURSTRATE)driver->resolve("di_burst_rate");
  291. di_stop_scan = (FPDISTOPSCAN)driver->resolve("di_stop_scan");
  292. if((!di_open) || (!di_close) || (!di_sample_rate) || (!di_maximum_rate) ||
  293. (!di_list_length) || (!di_inlist) || (!di_buffer_alloc) ||
  294. (!di_start_scan) || (!di_status_read) || (!di_buffer_status) ||
  295. (!di_burst_rate) || (!di_stop_scan))
  296. {
  297. error = 2; // Failed to link required symbol
  298. return;
  299. }
  300. error = di_open(deviceNumber);
  301. if(error)
  302. {
  303. di_close();
  304. error = di_open(deviceNumber);
  305. if(error)
  306. {
  307. error = 3; // Failed to open device
  308. di_close();
  309. return;
  310. }
  311. }
  312. isOpen = true;
  313. di_maximum_rate(240.0);
  314. sampleRate = di_sample_rate(sampleRate * channels * 40, &oversample,
  315. &burstDivisor);
  316. buffer = new qint16[(int)sampleRate];
  317. di_inlist_struct inlist[16] = {{0, 0, 0, 0, 0, 0, 0, 0}};
  318. for(unsigned short i = 0; i < channels; i++)
  319. {
  320. inlist[i].chan = i;
  321. inlist[i].gain = 0;
  322. inlist[i].ave = 1;
  323. inlist[i].counter = (oversample - 1);
  324. }
  325. error = di_list_length(channels, 0);
  326. if(error)
  327. {
  328. error = 4; // List length error
  329. return;
  330. }
  331. error = di_inlist(inlist);
  332. if(error)
  333. {
  334. error = 5; // Inlist error
  335. return;
  336. }
  337. input_buffer = di_buffer_alloc(0, 4096);
  338. if(input_buffer == NULL)
  339. {
  340. error = 6; // Failed to allocate buffer
  341. return;
  342. }
  343. error = di_start_scan();
  344. if(error)
  345. {
  346. error = 7; // Failed to start scanning
  347. return;
  348. }
  349. while(ready)
  350. {
  351. measure();
  352. }
  353. }
  354. @ When the loop exits, |DataqSdkDeviceImplementation| emits a finished signal
  355. to indicate that the thread is no longer running. This could be due to normal
  356. conditions or there could be a problem that should be reported. That signal is
  357. connected to a function that checks for error conditions and reports them if
  358. needed.
  359. @<DataqSdkDevice implementation@>=
  360. void DataqSdkDevice::threadFinished()
  361. {
  362. if(imp->error)
  363. {
  364. @<Display DATAQ SDK Error@>@;
  365. }
  366. }
  367. @ The DATAQ SDK does not have a single method for reporting errors. Instead,
  368. any method that can return an error code has its return value checked and
  369. |error| is set to a value that allows the source of the problem to be
  370. determined. At present, error handling is very poor.
  371. @<Display DATAQ SDK Error@>=
  372. imp->ready = false;
  373. QMessageBox warning;
  374. warning.setStandardButtons(QMessageBox::Cancel);
  375. warning.setIcon(QMessageBox::Warning);
  376. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  377. warning.setInformativeText(tr("An error occurred"));
  378. warning.setWindowTitle(QString(PROGRAM_NAME));
  379. warning.exec();
  380. @ Starting the thread is very simple. Device initialization happens in the new
  381. thread which then begins taking measurements. The call to |imp->start()| starts
  382. the new thread and passes control of that thread to |imp->run()|. The main
  383. thread of execution returns without waiting for the new thread to do anything.
  384. When the thread is finished, the |finished()| signal is emitted which we have
  385. connected to |threadFinished()|.
  386. @<DataqSdkDevice implementation@>=
  387. void DataqSdkDevice::start()
  388. {
  389. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  390. imp->start();
  391. }
  392. @ When configuring Typica to use a device supported through the DATAQ SDK it is
  393. useful to have a way to report the ports where supported hardware has been
  394. detected. This is also used for automatic detection.
  395. @<DataqSdkDevice implementation@>=
  396. QStringList DataqSdkDevice::detectHardware()
  397. {
  398. QSettings deviceLookup("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\usbser\\Enum",
  399. QSettings::NativeFormat);
  400. QStringList keys = deviceLookup.childKeys();
  401. QStringList devices;
  402. for(int i = 0; i < keys.size(); i++)
  403. {
  404. QString value = deviceLookup.value(keys.at(i)).toString();
  405. if(value.startsWith("USB\\VID_0683&PID_1450\\"))
  406. {
  407. devices.append(value.split("\\").at(2));
  408. }
  409. }
  410. QStringList portList;
  411. foreach(QString device, devices)
  412. {
  413. QString deviceKey = QString("HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_0683&PID_1450\\%1").arg(device);
  414. QSettings deviceEntry(deviceKey, QSettings::NativeFormat);
  415. portList.append(deviceEntry.value("FriendlyName").toString());
  416. }
  417. return portList;
  418. }
  419. QStringList DataqSdkDevice::detectPorts()
  420. {
  421. QStringList friendlyNames = detectHardware();
  422. QStringList portList;
  423. foreach(QString name, friendlyNames)
  424. {
  425. name.remove(0, name.indexOf("COM"));
  426. name.chop(1);
  427. portList.append(name);
  428. }
  429. return portList;
  430. }
  431. @ Setting up the device begins by constructing a new |DataqSdkDevice| object.
  432. The constructor takes as its argument a string which identifies the device. For
  433. legacy reasons this currently accepts device names such as |"Dev1"| and looks
  434. up currently connected devices to determine which serial port should be used.
  435. Now that it is preferred to configure devices graphically this is not a good
  436. way to do this. This should be changed before release.
  437. @<DataqSdkDevice implementation@>=
  438. DataqSdkDevice::DataqSdkDevice(QString device) : imp(new DataqSdkDeviceImplementation)
  439. {
  440. bool usesAuto = false;
  441. int autoIndex = device.toInt(&usesAuto);
  442. QString finalizedPort;
  443. if(usesAuto)
  444. {
  445. QStringList portList = detectPorts();
  446. if(autoIndex > 0 && autoIndex <= portList.size())
  447. {
  448. finalizedPort = portList.at(autoIndex - 1);
  449. }
  450. else
  451. {
  452. imp->error = 8; // Failed to find device.
  453. qDebug() << "Failed to detect port.";
  454. }
  455. }
  456. else
  457. {
  458. finalizedPort = device;
  459. }
  460. int rstart = finalizedPort.indexOf("COM");
  461. finalizedPort.remove(0, rstart + 3);
  462. bool chopFinished = false;
  463. int finalizedPortNumber = 0;
  464. while(finalizedPort.size() > 0 && !chopFinished)
  465. {
  466. finalizedPortNumber = finalizedPort.toInt(&chopFinished);
  467. if(!chopFinished)
  468. {
  469. finalizedPort.chop(1);
  470. }
  471. }
  472. if(finalizedPortNumber < 10)
  473. {
  474. imp->device = QString("DI10%1NT.DLL").arg(finalizedPort);
  475. }
  476. else
  477. {
  478. imp->device = QString("DI1%1NT.DLL").arg(finalizedPort);
  479. }
  480. imp->deviceNumber = 0x12C02D00;
  481. imp->deviceNumber += finalizedPortNumber;
  482. imp->ready = true;
  483. }
  484. @ Once the |DataqSdkDevice| is created, one or more channels can be added.
  485. @<DataqSdkDevice implementation@>=
  486. Channel* DataqSdkDevice::newChannel(Units::Unit scale)
  487. {
  488. Channel *retval = NULL;
  489. if(imp->ready)
  490. {
  491. retval = new Channel();
  492. imp->channelMap[imp->channels] = retval;
  493. imp->unitMap[imp->channels] = scale;
  494. imp->channels++;
  495. }
  496. return retval;
  497. }
  498. @ Once the channels are created, it is necessary to set the clock rate of the
  499. device. The DATAQ SDK will set the clock rate to be whichever value is closest
  500. to the specified value that is supported by the hardware. Note that when
  501. measuring multiple channels the device clock rate should be the desired sample
  502. rate per channel multiplied by the number of channels.
  503. The amount of time between measurements may vary slightly. Tests have shown
  504. that while most measurements come within 1ms of the expected time, some
  505. measurements do not come in within 100ms of the expected time.
  506. @<DataqSdkDevice implementation@>=
  507. void DataqSdkDevice::setClockRate(double Hz)
  508. {
  509. imp->sampleRate = Hz;
  510. }
  511. @ The destructor instructs the measurement thread to stop, waits for it to
  512. finish, and resets the device. If this is not done, an error would be issued
  513. the next time a program attempted to use the device.
  514. @<DataqSdkDevice implementation@>=
  515. DataqSdkDevice::~DataqSdkDevice()
  516. {
  517. if(imp->ready)
  518. {
  519. imp->ready = false;
  520. }
  521. imp->wait(ULONG_MAX);
  522. delete imp;
  523. }
  524. @ The constructor and destructor in |DataqSdkDeviceImplementation| currently
  525. limit the number of channels to 4. As additional devices are supported this
  526. restriction should be lifted.
  527. Very little is needed from the constructor. The destructor is responsible for
  528. closing the device and unloading the device driver.
  529. @<DataqSdkDevice implementation@>=
  530. DataqSdkDeviceImplementation::DataqSdkDeviceImplementation() : QThread(NULL),
  531. channelMap(4), error(0), channels(0), ready(false), unitMap(4)
  532. {
  533. /* Nothing needs to be done here. */
  534. }
  535. DataqSdkDeviceImplementation::~DataqSdkDeviceImplementation()
  536. {
  537. if(isOpen)
  538. {
  539. di_stop_scan();
  540. di_close();
  541. }
  542. if(driver->isLoaded())
  543. {
  544. driver->unload();
  545. }
  546. }
  547. @ This is exposed to the scripting engine in the usual way.
  548. @<Function prototypes for scripting@>=
  549. QScriptValue constructDataqSdkDevice(QScriptContext *context, QScriptEngine *engine);
  550. QScriptValue DataqSdkDevice_newChannel(QScriptContext *context, QScriptEngine *engine);
  551. void setDataqSdkDeviceProperties(QScriptValue value, QScriptEngine *engine);
  552. @ These functions are made known to the scripting engine.
  553. @<Set up the scripting engine@>=
  554. constructor = engine->newFunction(constructDataqSdkDevice);
  555. value = engine->newQMetaObject(&DataqSdkDevice::staticMetaObject, constructor);
  556. engine->globalObject().setProperty("DataqSdkDevice", value);
  557. @ When creating a new device we make sure that it is owned by the script
  558. engine. This is necessary to ensure that the destructor is called before \pn{}
  559. exits. Just as the constructor requires an argument that specifies the device
  560. name, the constructor available from a script also requires this argument.
  561. @<Functions for scripting@>=
  562. QScriptValue constructDataqSdkDevice(QScriptContext *context, QScriptEngine *engine)
  563. {
  564. QScriptValue object;
  565. if(context->argumentCount() == 1)
  566. {
  567. object = engine->newQObject(new DataqSdkDevice(argument<QString>(0, context)),
  568. QScriptEngine::ScriptOwnership);
  569. setDataqSdkDeviceProperties(object, engine);
  570. }
  571. else
  572. {
  573. context->throwError("Incorrect number of arguments passed to "
  574. "DataqSdkDevice. The constructor takes one string "
  575. "as an argument specifying a device name. "
  576. "Example: Dev1");
  577. }
  578. return object;
  579. }
  580. @ As |DataqSdkDevice| inherits |QObject| we add the |newChannel()| property
  581. after adding any |QObject| properties.
  582. @<Functions for scripting@>=
  583. void setDataqSdkDeviceProperties(QScriptValue value, QScriptEngine *engine)
  584. {
  585. setQObjectProperties(value, engine);
  586. value.setProperty("newChannel", engine->newFunction(DataqSdkDevice_newChannel));
  587. }
  588. @ The |newChannel()| wrapper requires one argument to specify the measurement
  589. unit that will eventually be produced from that channel.
  590. @<Functions for scripting@>=
  591. QScriptValue DataqSdkDevice_newChannel(QScriptContext *context, QScriptEngine *engine)
  592. {
  593. DataqSdkDevice *self = getself<DataqSdkDevice *>(context);
  594. QScriptValue object;
  595. if(self)
  596. {
  597. object = engine->newQObject(self->newChannel((Units::Unit)argument<int>(0, context)));
  598. setChannelProperties(object, engine);
  599. }
  600. return object;
  601. }
  602. @ In order to configure supported devices within Typica, a set of configuration
  603. controls is required. First there is the base device configuration widget.
  604. @<Class declarations@>=
  605. class DataqSdkDeviceConfWidget : public BasicDeviceConfigurationWidget
  606. {
  607. Q_OBJECT
  608. public:
  609. Q_INVOKABLE DataqSdkDeviceConfWidget(DeviceTreeModel *model,
  610. const QModelIndex &index);
  611. private slots:
  612. void updateAutoSelect(bool automatic);
  613. void updateDeviceNumber(int deviceNumber);
  614. void updatePort(QString portId);
  615. void addChannel();
  616. private:
  617. QStackedWidget *deviceIdStack;
  618. };
  619. @ The constructor sets up the interface for updating device configuration
  620. settings.
  621. @<DataqSdkDeviceConfWidget implementation@>=
  622. DataqSdkDeviceConfWidget::DataqSdkDeviceConfWidget(DeviceTreeModel *model,
  623. const QModelIndex &index)
  624. : BasicDeviceConfigurationWidget(model, index),
  625. deviceIdStack(new QStackedWidget)
  626. {
  627. QVBoxLayout *layout = new QVBoxLayout;
  628. QCheckBox *autoDetect = new QCheckBox("Automatically select device");
  629. layout->addWidget(autoDetect);
  630. QWidget *autoLayerWidget = new QWidget;
  631. QHBoxLayout *autoLayerLayout = new QHBoxLayout;
  632. QLabel *autoLabel = new QLabel(tr("Device number"));
  633. QSpinBox *autoNumber = new QSpinBox;
  634. autoNumber->setMinimum(1);
  635. autoNumber->setMaximum(99);
  636. autoLayerLayout->addWidget(autoLabel);
  637. autoLayerLayout->addWidget(autoNumber);
  638. autoLayerWidget->setLayout(autoLayerLayout);
  639. QWidget *fixedLayerWidget = new QWidget;
  640. QHBoxLayout *fixedLayerLayout = new QHBoxLayout;
  641. QLabel *fixedLabel = new QLabel(tr("Device port"));
  642. QComboBox *portSelection = new QComboBox;
  643. portSelection->setEditable(true);
  644. portSelection->addItems(DataqSdkDevice::detectHardware());
  645. fixedLayerLayout->addWidget(fixedLabel);
  646. fixedLayerLayout->addWidget(portSelection);
  647. fixedLayerWidget->setLayout(fixedLayerLayout);
  648. deviceIdStack->addWidget(autoLayerWidget);
  649. deviceIdStack->addWidget(fixedLayerWidget);
  650. layout->addWidget(deviceIdStack);
  651. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  652. layout->addWidget(addChannelButton);
  653. @<Get device configuration data for current node@>@;
  654. for(int i = 0; i < configData.size(); i++)
  655. {
  656. node = configData.at(i).toElement();
  657. if(node.attribute("name") == "autoSelect")
  658. {
  659. autoDetect->setChecked(node.attribute("value") == "true" ? true : false);
  660. }
  661. else if(node.attribute("name") == "deviceNumber")
  662. {
  663. autoNumber->setValue(node.attribute("value").toInt());
  664. }
  665. else if(node.attribute("name") == "port")
  666. {
  667. int index = portSelection->findText(node.attribute("value"));
  668. if(index > -1)
  669. {
  670. portSelection->setCurrentIndex(index);
  671. }
  672. else
  673. {
  674. portSelection->setEditText(node.attribute("value"));
  675. }
  676. }
  677. }
  678. updateAutoSelect(autoDetect->isChecked());
  679. updateDeviceNumber(autoNumber->value());
  680. updatePort(portSelection->currentText());
  681. connect(autoDetect, SIGNAL(toggled(bool)), this, SLOT(updateAutoSelect(bool)));
  682. connect(autoNumber, SIGNAL(valueChanged(int)), this, SLOT(updateDeviceNumber(int)));
  683. connect(portSelection, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  684. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  685. setLayout(layout);
  686. }
  687. @ In addition to setting a value in the device configuration, the choice to
  688. automatically select devices also requires changing which controls in the
  689. configuration widget are presently available. It is recommended that automatic
  690. device selection is only used in cases where there is a single device supported
  691. by the DATAQ SDK present and it will always be the first detected device
  692. regardless of the current virtual COM port number. In cases where multiple
  693. devices must be connected, it is recommended to always plug devices into the
  694. same port and specify the port for each device explicitly.
  695. @<DataqSdkDeviceConfWidget implementation@>=
  696. void DataqSdkDeviceConfWidget::updateAutoSelect(bool automatic)
  697. {
  698. if(automatic)
  699. {
  700. updateAttribute("autoSelect", "true");
  701. deviceIdStack->setCurrentIndex(0);
  702. }
  703. else
  704. {
  705. updateAttribute("autoSelect", "false");
  706. deviceIdStack->setCurrentIndex(1);
  707. }
  708. }
  709. @ Other update methods only need to set a new current value.
  710. @<DataqSdkDeviceConfWidget implementation@>=
  711. void DataqSdkDeviceConfWidget::updateDeviceNumber(int deviceNumber)
  712. {
  713. updateAttribute("deviceNumber", QString("%1").arg(deviceNumber));
  714. }
  715. void DataqSdkDeviceConfWidget::updatePort(QString portId)
  716. {
  717. updateAttribute("port", portId);
  718. }
  719. @ The Add Channel button creates a new configuration node.
  720. @<DataqSdkDeviceConfWidget implementation@>=
  721. void DataqSdkDeviceConfWidget::addChannel()
  722. {
  723. insertChildNode(tr("Channel"), "dataqsdkchannel");
  724. }
  725. @ Channel configuration requires a slightly more complex configuration than
  726. it does on other devices. As these devices can be used for both temperature and
  727. non-temperature measurements the channel requires both the column name for the
  728. measurement series and the unit that the measurements will eventually be
  729. transformed into. The output of each channel will likely need to be run through
  730. a |LinearCalibrator| so the lower and upper values for both the measured and
  731. the mapped ranges are set here. It is also necessary to know if that interval
  732. is open or closed, if adaptive smoothing should be enabled on that channel, and
  733. how much precision the measurements should be presented with. In addition to
  734. the controls for setting these values, there should be a panel that assists in
  735. determining appropriate values by connecting to the device, collecting
  736. measurements on the channel, and showing how those measurements are presented
  737. with the current settings.
  738. @<Class declarations@>=
  739. class DataqSdkChannelConfWidget : public BasicDeviceConfigurationWidget
  740. {
  741. Q_OBJECT
  742. public:
  743. Q_INVOKABLE DataqSdkChannelConfWidget(DeviceTreeModel *model,
  744. const QModelIndex &index);
  745. private slots:
  746. void updateUnits(const QString &unit);
  747. void updateColumnName(const QString &value);
  748. void updateMeasuredLower(const QString &value);
  749. void updateMeasuredUpper(const QString &value);
  750. void updateMappedLower(const QString &value);
  751. void updateMappedUpper(const QString &value);
  752. void updateClosedInterval(bool closed);
  753. void updateSmoothingEnabled(bool enabled);
  754. void updateSensitivity(const QString &value);
  755. void startCalibration();
  756. void stopCalibration();
  757. void resetCalibration();
  758. void updateInput(Measurement measure);
  759. void updateOutput(Measurement measure);
  760. void updateHidden(bool hidden);
  761. private:
  762. QPushButton *startButton;
  763. QPushButton *resetButton;
  764. QPushButton *stopButton;
  765. @<DATAQ SDK device settings@>@;
  766. DataqSdkDevice *calibrationDevice;
  767. LinearCalibrator *calibrator;
  768. QLineEdit *currentMeasurement;
  769. QLineEdit *minimumMeasurement;
  770. QLineEdit *maximumMeasurement;
  771. QLineEdit *averageMeasurement;
  772. QLineEdit *currentMapped;
  773. QLineEdit *minimumMapped;
  774. QLineEdit *maximumMapped;
  775. QLineEdit *averageMapped;
  776. int rmCount;
  777. int cmCount;
  778. double rmin;
  779. double rmax;
  780. double rmean;
  781. double cmin;
  782. double cmax;
  783. double cmean;
  784. };
  785. @ Private members that hold minimum and maximum aggregate data for channel
  786. calibration will be initialized to the maximum and minimum values available for
  787. the |double| type respectively. This guarantees that the first measurement will
  788. overwrite these values. This is done with |std::numeric_limits| so we require a
  789. header to be included to gain access to this.
  790. @<Header files to include@>=
  791. #include <limits>
  792. @ The constructor sets up the interface. Calibration settings line edits need
  793. to have numeric validators added.
  794. @<DataqSdkDeviceConfWidget implementation@>=
  795. DataqSdkChannelConfWidget::DataqSdkChannelConfWidget(DeviceTreeModel *model,
  796. const QModelIndex &index)
  797. : BasicDeviceConfigurationWidget(model, index),
  798. startButton(new QPushButton(tr("Start"))),
  799. resetButton(new QPushButton(tr("Reset"))),
  800. stopButton(new QPushButton(tr("Stop"))),
  801. calibrator(new LinearCalibrator),
  802. currentMeasurement(new QLineEdit), minimumMeasurement(new QLineEdit),
  803. maximumMeasurement(new QLineEdit), averageMeasurement(new QLineEdit),
  804. currentMapped(new QLineEdit), minimumMapped(new QLineEdit),
  805. maximumMapped(new QLineEdit), averageMapped(new QLineEdit),
  806. rmCount(0), cmCount(0),
  807. rmin(std::numeric_limits<double>::max()),
  808. rmax(std::numeric_limits<double>::min()), rmean(0),
  809. cmin(std::numeric_limits<double>::max()),
  810. cmax(std::numeric_limits<double>::min()), cmean(0)
  811. {
  812. @<Find DATAQ SDK device settings from parent node@>@;
  813. resetButton->setEnabled(false);
  814. stopButton->setEnabled(false);
  815. connect(startButton, SIGNAL(clicked()), this, SLOT(startCalibration()));
  816. connect(resetButton, SIGNAL(clicked()), this, SLOT(resetCalibration()));
  817. connect(stopButton, SIGNAL(clicked()), this, SLOT(stopCalibration()));
  818. QVBoxLayout *layout = new QVBoxLayout;
  819. QFormLayout *topLayout = new QFormLayout;
  820. QLineEdit *columnEdit = new QLineEdit;
  821. topLayout->addRow(tr("Column name"), columnEdit);
  822. QComboBox *unitSelector = new QComboBox;
  823. unitSelector->addItem(tr("Temperature"));
  824. unitSelector->addItem(tr("Control"));
  825. topLayout->addRow(tr("Measurement type"), unitSelector);
  826. QCheckBox *smoothingBox = new QCheckBox(tr("Enable smoothing"));
  827. topLayout->addRow(smoothingBox);
  828. layout->addLayout(topLayout);
  829. QCheckBox *hideSeries = new QCheckBox(tr("Hide this channel"));
  830. topLayout->addRow(hideSeries);
  831. QLabel *calibrationLabel = new QLabel(tr("Calibration settings"));
  832. layout->addWidget(calibrationLabel);
  833. QHBoxLayout *calibrationLayout = new QHBoxLayout;
  834. QFormLayout *calibrationControlsLayout = new QFormLayout;
  835. QLineEdit *measuredLowerEdit = new QLineEdit;
  836. measuredLowerEdit->setText("0");
  837. QLineEdit *measuredUpperEdit = new QLineEdit;
  838. measuredUpperEdit->setText("10");
  839. QLineEdit *mappedLowerEdit = new QLineEdit;
  840. mappedLowerEdit->setText("0");
  841. QLineEdit *mappedUpperEdit = new QLineEdit;
  842. mappedUpperEdit->setText("10");
  843. calibrationControlsLayout->addRow(tr("Measured lower value"), measuredLowerEdit);
  844. calibrationControlsLayout->addRow(tr("Mapped lower value"), mappedLowerEdit);
  845. calibrationControlsLayout->addRow(tr("Measured upper value"), measuredUpperEdit);
  846. calibrationControlsLayout->addRow(tr("Mapped upper value"), mappedUpperEdit);
  847. QCheckBox *closedBox = new QCheckBox(tr("Closed range"));
  848. calibrationControlsLayout->addRow(closedBox);
  849. QLineEdit *sensitivityEdit = new QLineEdit;
  850. sensitivityEdit->setText("0");
  851. calibrationControlsLayout->addRow(tr("Discrete interval skip"), sensitivityEdit);
  852. QVBoxLayout *calibrationTestLayout = new QVBoxLayout;
  853. QHBoxLayout *deviceControlLayout = new QHBoxLayout;
  854. deviceControlLayout->addWidget(startButton);
  855. deviceControlLayout->addWidget(resetButton);
  856. deviceControlLayout->addWidget(stopButton);
  857. QFormLayout *indicatorLayout = new QFormLayout;
  858. currentMeasurement->setReadOnly(true);
  859. minimumMeasurement->setReadOnly(true);
  860. maximumMeasurement->setReadOnly(true);
  861. averageMeasurement->setReadOnly(true);
  862. currentMapped->setReadOnly(true);
  863. minimumMapped->setReadOnly(true);
  864. maximumMapped->setReadOnly(true);
  865. averageMapped->setReadOnly(true);
  866. indicatorLayout->addRow(tr("Measured Values"), new QWidget);
  867. indicatorLayout->addRow(tr("Current"), currentMeasurement);
  868. indicatorLayout->addRow(tr("Minimum"), minimumMeasurement);
  869. indicatorLayout->addRow(tr("Maximum"), maximumMeasurement);
  870. indicatorLayout->addRow(tr("Mean"), averageMeasurement);
  871. indicatorLayout->addRow(tr("Mapped Values"), new QWidget);
  872. indicatorLayout->addRow(tr("Current Mapped"), currentMapped);
  873. indicatorLayout->addRow(tr("Minimum Mapped"), minimumMapped);
  874. indicatorLayout->addRow(tr("Maximum Mapped"), maximumMapped);
  875. indicatorLayout->addRow(tr("Mean Mapped"), averageMapped);
  876. calibrationTestLayout->addLayout(deviceControlLayout);
  877. calibrationTestLayout->addLayout(indicatorLayout);
  878. calibrationLayout->addLayout(calibrationControlsLayout);
  879. calibrationLayout->addLayout(calibrationTestLayout);
  880. layout->addLayout(calibrationLayout);
  881. @<Get device configuration data for current node@>@;
  882. for(int i = 0; i < configData.size(); i++)
  883. {
  884. node = configData.at(i).toElement();
  885. if(node.attribute("name") == "column")
  886. {
  887. columnEdit->setText(node.attribute("value"));
  888. }
  889. else if(node.attribute("name") == "type")
  890. {
  891. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  892. }
  893. else if(node.attribute("name") == "smoothing")
  894. {
  895. smoothingBox->setChecked(node.attribute("value") == "true");
  896. }
  897. else if(node.attribute("name") == "calibrationMeasuredLower")
  898. {
  899. measuredLowerEdit->setText(node.attribute("value"));
  900. }
  901. else if(node.attribute("name") == "calibrationMeasuredUpper")
  902. {
  903. measuredUpperEdit->setText(node.attribute("value"));
  904. }
  905. else if(node.attribute("name") == "calibrationMappedLower")
  906. {
  907. mappedLowerEdit->setText(node.attribute("value"));
  908. }
  909. else if(node.attribute("name") == "calibrationMappedUpper")
  910. {
  911. mappedUpperEdit->setText(node.attribute("value"));
  912. }
  913. else if(node.attribute("name") == "calibrationClosedInterval")
  914. {
  915. closedBox->setChecked(node.attribute("value") == "true");
  916. }
  917. else if(node.attribute("name") == "calibrationSensitivity")
  918. {
  919. sensitivityEdit->setText(node.attribute("value"));
  920. }
  921. else if(node.attribute("name") == "hidden")
  922. {
  923. hideSeries->setChecked(node.attribute("value") == "true");
  924. }
  925. }
  926. updateColumnName(columnEdit->text());
  927. updateUnits(unitSelector->currentText());
  928. updateSmoothingEnabled(smoothingBox->isChecked());
  929. updateMeasuredLower(measuredLowerEdit->text());
  930. updateMeasuredUpper(measuredUpperEdit->text());
  931. updateMappedLower(mappedLowerEdit->text());
  932. updateMappedUpper(mappedUpperEdit->text());
  933. updateClosedInterval(closedBox->isChecked());
  934. updateSensitivity(sensitivityEdit->text());
  935. updateHidden(hideSeries->isChecked());
  936. connect(columnEdit, SIGNAL(textChanged(QString)),
  937. this, SLOT(updateColumnName(QString)));
  938. connect(unitSelector, SIGNAL(currentIndexChanged(QString)),
  939. this, SLOT(updateUnits(QString)));
  940. connect(smoothingBox, SIGNAL(toggled(bool)),
  941. this, SLOT(updateSmoothingEnabled(bool)));
  942. connect(measuredLowerEdit, SIGNAL(textChanged(QString)),
  943. this, SLOT(updateMeasuredLower(QString)));
  944. connect(mappedLowerEdit, SIGNAL(textChanged(QString)),
  945. this, SLOT(updateMappedLower(QString)));
  946. connect(measuredUpperEdit, SIGNAL(textChanged(QString)),
  947. this, SLOT(updateMeasuredUpper(QString)));
  948. connect(mappedUpperEdit, SIGNAL(textChanged(QString)),
  949. this, SLOT(updateMappedUpper(QString)));
  950. connect(closedBox, SIGNAL(toggled(bool)),
  951. this, SLOT(updateClosedInterval(bool)));
  952. connect(sensitivityEdit, SIGNAL(textChanged(QString)),
  953. this, SLOT(updateSensitivity(QString)));
  954. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  955. setLayout(layout);
  956. }
  957. @ We generate measurements with whatever unit will eventually be required to
  958. avoid the need for something that only exists to change one value of every
  959. measurement. At present we generate measurements either in Fahrenheit or as
  960. Unitless. It might not be a bad idea to have the calibration adjustment allow
  961. display of temperature measurements in Celsius.
  962. @<DataqSdkDeviceConfWidget implementation@>=
  963. void DataqSdkChannelConfWidget::updateUnits(const QString &unit)
  964. {
  965. updateAttribute("type", unit);
  966. }
  967. @ Changing calibration settings requires both saving the settings and updating
  968. the |LinearCalibrator| used for calibration assistance.
  969. @<DataqSdkDeviceConfWidget implementation@>=
  970. void DataqSdkChannelConfWidget::updateMeasuredLower(const QString &value)
  971. {
  972. updateAttribute("calibrationMeasuredLower", value);
  973. calibrator->setMeasuredLower(value.toDouble());
  974. }
  975. void DataqSdkChannelConfWidget::updateMeasuredUpper(const QString &value)
  976. {
  977. updateAttribute("calibrationMeasuredUpper", value);
  978. calibrator->setMeasuredUpper(value.toDouble());
  979. }
  980. void DataqSdkChannelConfWidget::updateMappedLower(const QString &value)
  981. {
  982. updateAttribute("calibrationMappedLower", value);
  983. calibrator->setMappedLower(value.toDouble());
  984. }
  985. void DataqSdkChannelConfWidget::updateMappedUpper(const QString &value)
  986. {
  987. updateAttribute("calibrationMappedUpper", value);
  988. calibrator->setMappedUpper(value.toDouble());
  989. }
  990. void DataqSdkChannelConfWidget::updateClosedInterval(bool closed)
  991. {
  992. updateAttribute("calibrationClosedInterval", closed ? "true" : "false");
  993. calibrator->setClosedRange(closed);
  994. }
  995. void DataqSdkChannelConfWidget::updateSmoothingEnabled(bool enabled)
  996. {
  997. updateAttribute("smoothing", enabled ? "true" : "false");
  998. }
  999. void DataqSdkChannelConfWidget::updateSensitivity(const QString &value)
  1000. {
  1001. updateAttribute("calibrationSensitivity", value);
  1002. calibrator->setSensitivity(value.toDouble());
  1003. }
  1004. void DataqSdkChannelConfWidget::updateHidden(bool hidden)
  1005. {
  1006. updateAttribute("hidden", hidden ? "true" : "false");
  1007. }
  1008. @ When calibrating a device, we must know certain information to open a
  1009. connection to the appropriate hardware and know which channel we are interested
  1010. in.
  1011. @<DATAQ SDK device settings@>=
  1012. bool autoSelect;
  1013. QString deviceID;
  1014. unsigned int channelOfInterest;
  1015. @ This information is accessed through the reference element associated with
  1016. the parent node of the current configuration and from the row number of the
  1017. current node.
  1018. @<Find DATAQ SDK device settings from parent node@>=
  1019. QDomElement parentReference = model->referenceElement(model->data(index.parent(), Qt::UserRole).toString());
  1020. QDomNodeList deviceConfigData = parentReference.elementsByTagName("attribute");
  1021. QDomElement deviceNode;
  1022. QString configPort;
  1023. QString configAuto;
  1024. for(int i = 0; i < deviceConfigData.size(); i++)
  1025. {
  1026. deviceNode = deviceConfigData.at(i).toElement();
  1027. if(deviceNode.attribute("name") == "autoSelect")
  1028. {
  1029. autoSelect = (deviceNode.attribute("value") == "true");
  1030. }
  1031. else if(deviceNode.attribute("name") == "deviceNumber")
  1032. {
  1033. configAuto = deviceNode.attribute("value");
  1034. }
  1035. else if(deviceNode.attribute("name") == "port")
  1036. {
  1037. configPort = deviceNode.attribute("value");
  1038. }
  1039. }
  1040. deviceID = autoSelect ? configAuto : configPort;
  1041. channelOfInterest = index.row();
  1042. @ It must be possible to perform calibration operations with the hardware not
  1043. connected. As such, the device should only be opened on request. Methods for
  1044. opening and closing these connections to the hardware are provided.
  1045. @<DataqSdkDeviceConfWidget implementation@>=
  1046. void DataqSdkChannelConfWidget::startCalibration()
  1047. {
  1048. startButton->setEnabled(false);
  1049. stopButton->setEnabled(true);
  1050. resetButton->setEnabled(true);
  1051. calibrationDevice = new DataqSdkDevice(deviceID);
  1052. Channel *channel;
  1053. for(unsigned int i = 0; i <= channelOfInterest; i++)
  1054. {
  1055. channel = calibrationDevice->newChannel(Units::Unitless);
  1056. }
  1057. connect(channel, SIGNAL(newData(Measurement)), this, SLOT(updateInput(Measurement)));
  1058. connect(channel, SIGNAL(newData(Measurement)), calibrator, SLOT(newMeasurement(Measurement)));
  1059. connect(calibrator, SIGNAL(newData(Measurement)), this, SLOT(updateOutput(Measurement)));
  1060. calibrationDevice->setClockRate(6.0 / (1.0 + channelOfInterest));
  1061. calibrationDevice->start();
  1062. }
  1063. void DataqSdkChannelConfWidget::stopCalibration()
  1064. {
  1065. startButton->setEnabled(true);
  1066. stopButton->setEnabled(false);
  1067. resetButton->setEnabled(false);
  1068. calibrationDevice->deleteLater();
  1069. @<Reset DATAQ SDK channel calibration aggregates@>@;
  1070. }
  1071. @ When collecting calibration data it is useful to have a few types of
  1072. information. The most recent reported measurement is fine, but the hardware
  1073. supported here does not produce a constant value in response to a stable input,
  1074. making this less useful than it would be if that were not the case. Aggregate
  1075. data such as the minimum, maximum, and mean of measured values for a stable
  1076. input are useful to have, but it must be possible to reset these statistics for
  1077. convenient testing in multiple parts of the range.
  1078. @<DataqSdkDeviceConfWidget implementation@>=
  1079. void DataqSdkChannelConfWidget::resetCalibration()
  1080. {
  1081. @<Reset DATAQ SDK channel calibration aggregates@>@;
  1082. }
  1083. @ When calibration is stopped or reset, aggregate statistics are set to
  1084. their initial values;
  1085. @<Reset DATAQ SDK channel calibration aggregates@>=
  1086. rmCount = 0;
  1087. cmCount = 0;
  1088. rmin = std::numeric_limits<double>::max();
  1089. rmax = std::numeric_limits<double>::min();
  1090. rmean = 0;
  1091. cmin = std::numeric_limits<double>::max();
  1092. cmax = std::numeric_limits<double>::min();
  1093. cmean = 0;
  1094. @ Two methods are responsible for updating line edits with current and
  1095. aggregate data when calibrating a channel. One handles raw measurements from
  1096. the channel and the other handles output from the |LinearCalibrator|.
  1097. @<DataqSdkDeviceConfWidget implementation@>=
  1098. void DataqSdkChannelConfWidget::updateInput(Measurement measure)
  1099. {
  1100. double nv = measure.temperature();
  1101. currentMeasurement->setText(QString("%1").arg(nv));
  1102. rmin = qMin(nv, rmin);
  1103. minimumMeasurement->setText(QString("%1").arg(rmin));
  1104. rmax = qMax(nv, rmax);
  1105. maximumMeasurement->setText(QString("%1").arg(rmax));
  1106. rmean = ((rmean * rmCount) + nv) / (rmCount + 1);
  1107. rmCount++;
  1108. averageMeasurement->setText(QString("%1").arg(rmean));
  1109. }
  1110. void DataqSdkChannelConfWidget::updateOutput(Measurement measure)
  1111. {
  1112. double nv = measure.temperature();
  1113. currentMapped->setText(QString("%1").arg(nv));
  1114. cmin = qMin(nv, cmin);
  1115. minimumMapped->setText(QString("%1").arg(cmin));
  1116. cmax = qMax(nv, cmax);
  1117. maximumMapped->setText(QString("%1").arg(cmax));
  1118. cmean = ((cmean * cmCount) + nv) / (cmCount + 1);
  1119. cmCount++;
  1120. averageMapped->setText(QString("%1").arg(cmean));
  1121. }
  1122. @ Column name is handled as usual.
  1123. @<DataqSdkDeviceConfWidget implementation@>=
  1124. void DataqSdkChannelConfWidget::updateColumnName(const QString &value)
  1125. {
  1126. updateAttribute("column", value);
  1127. }
  1128. @ These configuration widgets are registered with the configuration system.
  1129. @<Register device configuration widgets@>=
  1130. app.registerDeviceConfigurationWidget("dataqsdk", DataqSdkDeviceConfWidget::staticMetaObject);
  1131. app.registerDeviceConfigurationWidget("dataqsdkchannel",
  1132. DataqSdkChannelConfWidget::staticMetaObject);
  1133. @ A |NodeInserter| is also added to provide access to
  1134. |DataqSdkDeviceConfWidget|, but only on Windows.
  1135. @<Register top level device configuration nodes@>=
  1136. #ifdef Q_OS_WIN32
  1137. inserter = new NodeInserter(tr("DATAQ SDK Device"), tr("DATAQ Device"),
  1138. "dataqsdk", NULL);
  1139. topLevelNodeInserters.append(inserter);
  1140. #endif