gpib_functions.c 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620
  1. #include "lpc176x.h"
  2. #include "usb_hardware.h"
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include "options.h"
  6. #ifdef USBTMC // #endif в конце файла
  7. #include "utils.h"
  8. #include "gpib_parser.h"
  9. #include "usb_enumeration.h"
  10. #include "usbtmc.h"
  11. #include "utilits.h"
  12. #include "usb_options.h"
  13. //#include "spi.h"
  14. #include "i2_c.h"
  15. #include "common\buffer.h"
  16. #include <math.h>
  17. #include "usb_application.h"
  18. #include "usb_proto.h"
  19. #include "acm_base.h"
  20. #include "acm_base_model.h"
  21. #define DBPOINTS_BUFFER_NUM 128
  22. // @dbPointsBuffer - the temporary buffer for the points in the intermediate, double format
  23. static sACMChrzPoint_t dbPointsBuffer[ DBPOINTS_BUFFER_NUM ];
  24. // ==============================================================================================
  25. // GPIB функции идентичны по строению. Вначале они получают указатель на выходной буфер данных,
  26. // куда собираются печатать ответ (pBulkData_DeviceOut) и размер этого буфера (MAX).
  27. // Далее, из очереди pQParameters в зависимости от функции извлекаются параметры в том виде, в каком
  28. // они были переданы от компьютера, за исключением того, что первым байтом каждого параметра является
  29. // его тип (eParTypeChar, eParTypeNR1, ...) - тип параметра может быть строковый, числовой, символьный и т.п.
  30. // К тому же, в зависимости от функции, проверяется количество переданных параметров, если оно не сов-
  31. // падает, функция генерирует ошибку и завершает работу. Параметры извлекаются по очереди, если не удалось
  32. // извлечь хотя бы один, функция генерирует ошибку и завершает работу. Далее, параметры обрабатываются
  33. // в зависимости от их типа и предполагаемого назначения (задается функцией), получаются конкретные
  34. // значения, например тип порта (ePORT_A, ePORT_B из "A" и "B"). Если значение параметра не корректно,
  35. // тоесть невозможно преобразовать порт C например, параметр объявляется ошибочным и функция ведет себя
  36. // аналогично, как и в случае с ошибкой получения параметра - то есть завершает работу, генерируя ошибку
  37. // Также она себя ведет, если значение параметра понято, обработано, но не применимо в данной ситуации,
  38. // например, невозможно установить состояние THRU для одного порта A.
  39. //
  40. // Если все эти условия не выполнились, функция приступает к генерации ответа, если она запросная
  41. // Если нет, выполняет какие-то дейтсвия. Если функция запросная, а вызвана как комманда, функция генерирует ошибку.
  42. // И наоборот, коммандные функции не могут вызываться как запрос. (Конечно, если функция Командно-запросная, ничего страшного)
  43. //
  44. // Функция GPIB ВСЕГДА возвращает количество записанных в буфер символов.
  45. //
  46. // Если функции недостаточно места в буфере, как например в случае с MEM:TABLE:DATA, она поступает так:
  47. // она сохраняет контекст выполнения (все необходимые ей данные, для того чтобы можно было начать выполнениеъ
  48. // с места остановки), регистриует себя в качестве обработчика события опустошения буфера. Затем функция
  49. // сбросит флаг EOM и завершит работу. Обработчик канала USB будет знать, что это сообщение не последнее, EOM сброшен.
  50. // Как только место в буфере освободится, обработчик канала USB (см в endpoints.c) вызовет функцию еще раз.
  51. // На этот раз, она будет знать, что вызвана по событю опустошения буфера и загрузит контекст выполнения,
  52. // подготовит часть данных, которая уместится в освободившееся место, и вновь, при необходимости, повторит
  53. // такую операцию с сохранением-загрузкой контекста. Как только функция обнаружит, что все данные переданы,
  54. // она не станет сбрасывать EOM, не станет сохранять контекст а просто завершится.
  55. //
  56. // Если при работе функции возникает ошибка, она передается в функцию RaiseStandartError, та в свою
  57. // очередь, зная код ошибки, запишет необходимые данные в очередь ошибок, включая необходимое описание
  58. // ошибки (если необходимо). При вызове SYST:ERR? эта ошибка приобретает сформатированный вид и выдается наружу.
  59. //
  60. // Некоторые команды, например MEM:TABLE:FREQ:STAR и MEM:TABLE:FREQ:STOP абсолютно идентичны по топологии
  61. // но различаются лишь в самом последнем звене - смещению данных в стуртуре заголовка, которые нужно
  62. // выдать в ответе. Чтобы не делать две одинаковые функции, отличающиеся только одним словом, сделаны т.н.
  63. // специальные функции. При инициализации GPIB дерева обычные команды регистрируют на себя по одной функции.
  64. // Специальные команды делят между собой одну единственную обслуживающую функцию. Эта функция идентифицирует
  65. // каждую команду и запрос по специальному полю FunctionID, которое помещается в очередь параметров функции pQParameters
  66. // перед вызовом и перед занесением в очередб параметров функции. Это поле задается для каждой команды
  67. // уникальным 32 разрядным числом при иницализации дерева команд GPIB. Функция обязательно должна знать, что
  68. // это поле нужно прочесть и использоватть. Для этого, перед получением параметров функции, она должна извлечь
  69. // FunctionID из очереди как обычный параметр. В зависимости от значения параметра FunctionID она должна
  70. // предпринимать различные действия: в одном случае выдавать Fmin, а в другом случае Fmax например.
  71. // Например, для :MEM:TABLE:FREQ:STAR;STOP;:MEM:TABLE:CONN;ADAP;ANAL;TIME;DATA ... существует всего одна
  72. // фунция MemTableFields(), зато она разбирает 11 различных FunctionID.
  73. // ==============================================================================================
  74. // ==============================================================================================
  75. // GPIB_Identification(...)
  76. // Назначенная комманда - *IDN?
  77. // Параметры комманды - отсутствуют
  78. // Возвращаемое значение - строка IDN
  79. // ---------------------------------------------------------------------------------------------------------
  80. // IDN string format: "<manufactor>,<device_name>,<device_serial>,0"
  81. // <manufactor> - Planar (http://planar.chel.ru) or "Copper Mountain Technologies"
  82. // <device_name> - Auto Calibration Module
  83. // <device_serial> - 0000-0000-0000
  84. unsigned int GPIB_Identification ( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *IDN?
  85. {
  86. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  87. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  88. size_t count;
  89. unsigned int err = 0;
  90. int i = 0+strlen(ACMClass->properties.manufacturerId);
  91. i+= 1+strlen(ACMClass->properties.modelName);
  92. i+= 1+strlen(ACMClass->properties.serialNumber);
  93. i+= 1+strlen(ACMClass->properties.firmwareId);
  94. if(!queue_getcount( pQParameters, &count ))
  95. err = ERROR_GPIB_INTERNAL;
  96. else if( count != 0)
  97. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  98. else if( !request )
  99. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  100. else
  101. {
  102. if( MAX >= i )
  103. {
  104. return snprintf( pBulkData_DeviceOut, MAX, "%s,%s,%s,%s",
  105. ACMClass->properties.manufacturerId,
  106. ACMClass->properties.modelName,
  107. ACMClass->properties.serialNumber,
  108. ACMClass->properties.firmwareId );
  109. }
  110. else
  111. err = ERROR_GPIB_BUFFER_OVERFLOW;
  112. }
  113. // -------------------------------------------------------
  114. if( 0 != err )
  115. {
  116. // 27/08/18
  117. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  118. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  119. }
  120. return 0;
  121. }
  122. // ====================================================================================================
  123. // GPIB_SystemVersion(...) - сервисная комманда, недокументирована
  124. // Назначенная комманда - SYSTem:VERSion?
  125. // Параметры комманды - любые
  126. // Возвращаемое значение - сообщение о номере версии парсера SCPI
  127. unsigned int GPIB_SystemVersion( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк system:info, system:info?
  128. {
  129. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  130. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  131. //--------------------------------------------------------
  132. if( MAX >= 16)
  133. {
  134. s_memcpy( pBulkData_DeviceOut, "SCPI parser v1.3", 16 ); // ----- Copy respond data
  135. return (request==TRUE)?16:0; // -- respond length
  136. } else return 0;
  137. }
  138. // ==============================================================================================
  139. // GPIB_Clear(...)
  140. // Назначенная комманда - *CLS, очищает очередь ошибок и регисты STB и SRE
  141. // Параметры комманды - отсутствуют
  142. // Возвращаемое значение - отсутствует
  143. unsigned int GPIB_Clear( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *CLS
  144. {
  145. QUEUE * pQueue = &udi->usbtmcGpib.StateMachine.qErrorQueue;
  146. size_t count = 0;
  147. unsigned int err = 0;
  148. //--------------------------------------------------------
  149. if( !queue_getcount( pQParameters, &count ) )
  150. {
  151. err = ERROR_GPIB_INTERNAL;
  152. }
  153. else
  154. {
  155. if( count != 0)
  156. {
  157. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  158. }
  159. else
  160. {
  161. if( request )
  162. {
  163. err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
  164. }
  165. else
  166. {
  167. // Clear Event Status Register
  168. // Clear Status Register
  169. // Clear Error Queue
  170. udi->usbtmcGpib.StateMachine.STB = 0x00;
  171. udi->usbtmcGpib.StateMachine.ESR = 0x00;
  172. // - Error/Event Queue
  173. queue_clear( pQueue ); // Clear error queue
  174. GPIB_CLR_MAV(); // Clear Status Bit: message available
  175. GPIB_CLR_EAV(); // Clear Status Bit: event available
  176. }
  177. }
  178. }
  179. if( 0 != err )
  180. {
  181. // 27/08/18
  182. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  183. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  184. }
  185. return 0; // -- respond length
  186. }
  187. // ==============================================================================================
  188. // GPIB_Reset(...)
  189. // Назначенная комманда - *RST, сбрасывает состояние портов на LOAD/LOAD
  190. // Параметры комманды - отсутствуют
  191. // Возвращаемое значение - отсутствует
  192. unsigned int GPIB_Reset( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *RST
  193. {
  194. QUEUE * pQueue = &udi->usbtmcGpib.StateMachine.qErrorQueue;
  195. size_t count = 0; unsigned int err = 0;
  196. //--------------------------------------------------------
  197. if( !queue_getcount( pQParameters, &count ) )
  198. {
  199. err = ERROR_GPIB_INTERNAL;
  200. }
  201. else
  202. {
  203. if( count != 0)
  204. {
  205. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  206. }
  207. else
  208. {
  209. if( request )
  210. {
  211. err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
  212. }
  213. else
  214. {
  215. udi->EPBulkStatus.InPipe.dwLength = 0; // Clear bytes counters
  216. udi->EPBulkStatus.OutPipe.dwLength = 0; // - send counter
  217. udi->EPBulkStatus.shortpacket=FALSE; // - recv counter
  218. udi->EPBulkStatus.shortpacketsending=FALSE; // And clear also shortpacket signal flags
  219. //---------------
  220. udi->BulkRespondStatus.INTransferInProgress=FALSE; // Clear signal variables
  221. udi->BulkRespondStatus.nBytesSent=0; //
  222. udi->BulkRespondStatus.INTransferTerminating=FALSE; //
  223. //---------------
  224. //udi->usbtmcStatus.USBTMC_status = STATUS_SUCCESS; // usbtmcStatus do'nt depends from any bulk commands
  225. //udi->usbtmcStatus.USBTMC_InitiateRecieved = FALSE; //
  226. //---------------
  227. queue_clear( pQueue ); // Clear error queue
  228. GPIB_CLR_EAV();
  229. GPIB_CLR_MAV(); // No messages available
  230. //---------------
  231. udi->BulkMessageStatus.bBulkHeaderRecieved=FALSE; // Clears Header flag
  232. udi->BulkMessageStatus.nBytesRecieved=0; // Clears bytes counter
  233. udi->BulkMessageStatus.OUTTransferInProgress=FALSE; // Clears signal variable
  234. //---------------
  235. usb_lpc_cmd(CMD_EP_SELECT | USB_EP_PHY_ADDRESS_BULK_OUT ); // Clear EPOUT buffers
  236. usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
  237. usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
  238. //---------------
  239. usb_lpc_cmd(CMD_EP_SELECT | USB_EP_PHY_ADDRESS_BULK_IN ); // Clear EPIN buffers
  240. usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
  241. usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
  242. //---------------
  243. GPIB_DevDepInit( udi );
  244. //--------------- --- переход в состояние, когда устройство ждет комманды
  245. }
  246. }
  247. }
  248. if( 0 != err )
  249. {
  250. // 27/08/18
  251. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  252. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  253. }
  254. return 0; // -- no bytes in respond
  255. }
  256. // ==============================================================================================
  257. // GPIB_SystemError(...)
  258. // Назначенная комманда - SYSTem:ERRor[:NEXT]?
  259. // Параметры комманды - отсутствуют
  260. // Возвращаемое значение - строка последней ошибки в очереди ошибок
  261. unsigned int GPIB_SystemError( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  262. {
  263. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  264. //char * str = pQParameters->str;
  265. size_t count;
  266. unsigned int err = 0;
  267. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  268. //--------------------------------------------------------
  269. // request - если пришел запрос Enable? то request - 0x01
  270. // Request and Command support
  271. if(!queue_getcount( pQParameters, &count ))
  272. {
  273. err = ERROR_GPIB_INTERNAL;
  274. }
  275. else
  276. {
  277. if( count != 0)
  278. {
  279. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  280. }
  281. else
  282. {
  283. if( !request )
  284. {
  285. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  286. }
  287. else
  288. {
  289. return usbtmc_GetErrorText( udi, pBulkData_DeviceOut, MAX );
  290. }
  291. }
  292. }
  293. if( 0!= err )
  294. {
  295. // 27/08/18
  296. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  297. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  298. }
  299. return 0;
  300. }
  301. // ==============================================================================================
  302. // GPIB_SystemErrorAll(...)
  303. // Назначенная комманда - SYSTem:ERRor:ALL?
  304. // Параметры комманды - отсутствуют
  305. // Возвращаемое значение - строка всех ошибок в очереди
  306. unsigned int GPIB_SystemErrorAll( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  307. {
  308. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  309. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  310. //--------------------------------------------------------
  311. int a = 0;
  312. // Request ONLY
  313. if (request)
  314. {
  315. int c = 0;
  316. do{
  317. if( a>0 ) { *(pBulkData_DeviceOut+a) = ','; a++; *(pBulkData_DeviceOut+a) = ' ';a++;}
  318. c = usbtmc_GetErrorText( udi, pBulkData_DeviceOut+a, MAX-a );
  319. a+=c;
  320. }while( GPIB_GET_EAV() );
  321. }
  322. return a;
  323. }
  324. // ==============================================================================================
  325. // GPIB_EventStatusEnable(...)
  326. // Назначенная комманда - ESE?
  327. // Параметры комманды - отсутствуют или значение регистра
  328. // Возвращаемое значение - значение регистра разрешения статусов событий (Event Status Enable Register)
  329. unsigned int GPIB_EventStatusEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  330. {
  331. size_t count = 0;
  332. unsigned size = 0, err = 0;
  333. unsigned int ESE;
  334. char NUMBER[11]={0,0,0,0,0,0,0,0,0,0,0x0A};
  335. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  336. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  337. // --------------------------------------------------
  338. if(!queue_getcount( pQParameters, &count ))
  339. {
  340. err = ERROR_GPIB_INTERNAL;
  341. }
  342. else
  343. {
  344. if( count != TernaryOperator(request, 0, 1))
  345. {
  346. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  347. }
  348. else
  349. {
  350. if( !request && !queue_get( pQParameters, NUMBER, 10, &size ))
  351. {
  352. err = ERROR_GPIB_INVALID_PARAMETER;
  353. }
  354. else
  355. {
  356. if( !request && NUMBER[0] != eParTypeNR1 )
  357. {
  358. err = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  359. }
  360. else
  361. {
  362. if( !request && 0!=GPIB_ParseNumbers( NUMBER+1,USBTMC_PARSENUMBERS_TYPE_INT,1, (int*)&ESE ))
  363. {
  364. err = ERROR_GPIB_INVALID_PARAMETER;
  365. }
  366. else
  367. {
  368. if(request)
  369. {
  370. return snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.ESE );
  371. }
  372. else
  373. {
  374. udi->usbtmcGpib.StateMachine.ESE = ESE&0xff;
  375. USBTMC_StateMachine_Modified( &udi->usbtmcGpib.StateMachine );
  376. }
  377. }
  378. }
  379. }
  380. }
  381. }
  382. if( 0 != err )
  383. {
  384. // 27/08/18
  385. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  386. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  387. }
  388. return 0;
  389. }
  390. // ==============================================================================================
  391. // GPIB_OperationComplete(...)
  392. // Назначенная комманда - OPC?
  393. // Параметры комманды - отсутствуют
  394. // Возвращаемое значение - "1"
  395. unsigned int GPIB_OperationComplete( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  396. {
  397. size_t count = 0;
  398. unsigned /*size = 0,*/ err = 0;
  399. // unsigned int ESE;
  400. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  401. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  402. // --------------------------------------------------
  403. if(!queue_getcount( pQParameters, &count ))
  404. {
  405. err = ERROR_GPIB_INTERNAL;
  406. }
  407. else
  408. {
  409. if( count != 0)
  410. {
  411. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  412. }
  413. else
  414. {
  415. GPIB_SET_OPC();
  416. if(request)
  417. {
  418. return snprintf(pBulkData_DeviceOut, MAX, "%d", 1 );
  419. }
  420. else
  421. {
  422. (void)0;
  423. }
  424. }
  425. }
  426. if( 0!=err )
  427. {
  428. // 27/08/18
  429. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  430. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  431. }
  432. return 0;
  433. }
  434. // ==============================================================================================
  435. // GPIB_Wait(...)
  436. // Назначенная комманда - *WAI
  437. // Параметры комманды - отсутствуют
  438. // Возвращаемое значение - отсутствует
  439. unsigned int GPIB_Wait( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  440. {
  441. size_t count = 0;
  442. unsigned /*size = 0,*/ err = 0;
  443. // unsigned int ESE;
  444. // int MAX = udi->BulkRespondStatus.RespondBufferSize;
  445. // BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  446. // --------------------------------------------------
  447. if(!queue_getcount( pQParameters, &count ))
  448. {
  449. err = ERROR_GPIB_INTERNAL;
  450. }
  451. else
  452. {
  453. if( count != 0)
  454. {
  455. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  456. }
  457. else
  458. {
  459. if(!request)
  460. {
  461. (void)0;
  462. }
  463. else
  464. {
  465. (void)0;
  466. }
  467. }
  468. }
  469. if( 0!=err )
  470. {
  471. // 27/08/18
  472. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  473. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  474. }
  475. return 0;
  476. }
  477. // ==============================================================================================
  478. // GPIB_Trigger(...)
  479. // Назначенная комманда - *TRG
  480. // Параметры комманды - отсутствуют
  481. // Возвращаемое значение - отсутствует
  482. unsigned int GPIB_Trigger( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  483. {
  484. size_t count = 0;
  485. unsigned int err = 0;
  486. // --------------------------------------------------
  487. if(!queue_getcount( pQParameters, &count ))
  488. {
  489. err = ERROR_GPIB_INTERNAL;
  490. }
  491. else
  492. {
  493. if( count != 0)
  494. {
  495. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  496. }
  497. else
  498. {
  499. if( !request )
  500. err = ERROR_GPIB_TRIGGER_IGNORED;
  501. else
  502. err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
  503. }
  504. }
  505. if( 0 != err )
  506. {
  507. // 27/08/18
  508. // GPIB_RaiseStandartError( udi, err, "Trigger ignored", GPIB_ERROR_ID_COR | request );
  509. GPIB_RaiseStandartError( udi, err, "Trigger ignored", errClass_Autodetect );
  510. }
  511. return 0;
  512. }
  513. // ==============================================================================================
  514. // GPIB_EventStatusRegister(...)
  515. // Назначенная комманда - *ESR?
  516. // Параметры комманды - отсутствуют
  517. // Возвращаемое значение - значение регистра статсуса событий
  518. unsigned int GPIB_EventStatusRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  519. {
  520. size_t count = 0;
  521. unsigned int err = 0;
  522. unsigned int rc = 0;
  523. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  524. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  525. // --------------------------------------------------
  526. if(!queue_getcount( pQParameters, &count ))
  527. {
  528. err = ERROR_GPIB_INTERNAL;
  529. }
  530. else
  531. {
  532. if( !request)
  533. {
  534. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  535. }
  536. else
  537. {
  538. if( count != 0 )
  539. {
  540. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  541. }
  542. else
  543. {
  544. rc = snprintf(pBulkData_DeviceOut, MAX, "%d", GPIB_GET_ESR() );
  545. // IEEE 488.2, 11.5.1.2.2 Reading
  546. // The Standard Event Status Register is destructively read (that is, read and cleared) with the *ESR? common query, see 10.12.
  547. GPIB_CLR_ESR();
  548. // 27/08/18
  549. // --- replaced with: GPIB_SET_PWN() and GPIB_SET_OPC() ----
  550. // udi->usbtmcGpib.StateMachine.ESR = 129;
  551. // USBTMC_StateMachine_Modified( &udi->usbtmcGpib.StateMachine );
  552. //
  553. //
  554. // 27/08/18
  555. // --- Note: in this implementation the PowerOn(7) and OperationComplete(0) bits are disabled
  556. // GPIB_SET_PWN();
  557. // GPIB_SET_OPC();
  558. }
  559. }
  560. }
  561. if( 0 != err )
  562. {
  563. // 27/08/18
  564. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  565. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  566. }
  567. return rc;
  568. }
  569. // ==============================================================================================
  570. // GPIB_StatusRegister(...)
  571. // Назначенная комманда - *STB?
  572. // Параметры комманды - отсутствуют
  573. // Возвращаемое значение - значение регистра статсуса устройства
  574. unsigned int GPIB_StatusRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  575. {
  576. size_t count = 0;
  577. unsigned int err = 0;
  578. unsigned int rc = 0;
  579. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  580. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  581. // --------------------------------------------------
  582. if(!queue_getcount( pQParameters, &count ))
  583. {
  584. err = ERROR_GPIB_INTERNAL;
  585. }
  586. else
  587. {
  588. if( count != 0)
  589. {
  590. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  591. }
  592. else
  593. {
  594. if( !request )
  595. {
  596. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  597. }
  598. else
  599. {
  600. rc = snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.STB );
  601. GPIB_CLR_RQS__(); // no state-machine state modify, clear ServiceRequestBit
  602. }
  603. }
  604. }
  605. if( 0!=err )
  606. {
  607. // 27/08/18
  608. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  609. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  610. }
  611. return rc;
  612. }
  613. // ==============================================================================================
  614. // GPIB_StatusEnableRegister(...)
  615. // Назначенная комманда - *SRE?
  616. // Параметры комманды - отсутствуют или значение регистра
  617. // Возвращаемое значение - значение регистра разрешения статсуса устройства
  618. unsigned int GPIB_StatusEnableRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  619. {
  620. size_t count = 0;
  621. unsigned int err = 0;
  622. unsigned int rc = 0;
  623. unsigned int size = 0;
  624. BYTE SRE;
  625. char NUMBER[11]={0,0,0,0,0,0,0,0,0,0,0x0A};
  626. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  627. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  628. // --------------------------------------------------
  629. if(!queue_getcount( pQParameters, &count ))
  630. {
  631. err = ERROR_GPIB_INTERNAL;
  632. }
  633. else
  634. {
  635. if( count != ((request)?0:1) )
  636. {
  637. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  638. }
  639. else
  640. {
  641. if( !request && !queue_get( pQParameters, NUMBER, 10, &size ))
  642. {
  643. err = ERROR_GPIB_INVALID_PARAMETER;
  644. }
  645. else
  646. {
  647. if( !request && NUMBER[0] != eParTypeNR1 )
  648. {
  649. err = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  650. }
  651. else
  652. {
  653. if( !request && 0!=GPIB_ParseNumbers( NUMBER+1,USBTMC_PARSENUMBERS_TYPE_INT,1, (int*)&SRE ))
  654. {
  655. err = ERROR_GPIB_INVALID_PARAMETER;
  656. }
  657. else
  658. {
  659. if(request)
  660. {
  661. rc = snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.SRE );
  662. }
  663. else
  664. {
  665. udi->usbtmcGpib.StateMachine.SRE = SRE&0xff;
  666. }
  667. }
  668. }
  669. }
  670. }
  671. }
  672. if( 0 != err )
  673. {
  674. // 27/08/18
  675. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  676. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  677. }
  678. return rc;
  679. }
  680. // ==============================================================================================
  681. /*
  682. // GPIB_StatusOperationEvent(...)
  683. // Назначенная комманда - STATus:OPERation[:EVENt]?
  684. // Параметры комманды - отсутствуют
  685. // Возвращаемое значение - "0"
  686. unsigned int GPIB_StatusOperationEvent( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  687. {
  688. // request равен 0x00 если комманда :STAT:OPER, а не :STAT:OPER? или :STAT:OPER:EVEN?
  689. // Request ONLY
  690. size_t count = 0;
  691. unsigned err = 0;
  692. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  693. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  694. // --------------------------------------------------
  695. if(!queue_getcount( pQParameters, &count ))
  696. {
  697. err = ERROR_GPIB_INTERNAL;
  698. }
  699. else
  700. {
  701. if( count != 0)
  702. {
  703. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  704. }
  705. else
  706. {
  707. if( !request )
  708. {
  709. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  710. }
  711. else
  712. {
  713. return snprintf(pBulkData_DeviceOut, MAX, "%d", 0 );
  714. }
  715. }
  716. }
  717. if( 0!= err )
  718. {
  719. // 27/08/18
  720. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  721. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  722. }
  723. return 0;
  724. }
  725. */
  726. /*
  727. // ==============================================================================================
  728. // GPIB_StatusOperationCondition(...)
  729. // Назначенная комманда - STATus:OPERation:CONDition?
  730. // Параметры комманды - отсутствуют
  731. // Возвращаемое значение - "0"
  732. unsigned int GPIB_StatusOperationCondition( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  733. {
  734. // request - всегда 0x01
  735. // Request ONLY
  736. return GPIB_StatusOperationEvent(udi, pQParameters, request);
  737. }
  738. */
  739. /*
  740. // ==============================================================================================
  741. // GPIB_StatusOperationEnable(...)
  742. // Назначенная комманда - STATus:OPERation:ENABle?
  743. // Параметры комманды - отсутствуют
  744. // Возвращаемое значение - "0"
  745. unsigned int GPIB_StatusOperationEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  746. { // request - если пришел запрос Enable? то request - 0x01
  747. // Request and Command support
  748. return GPIB_StatusQuestionableEnable(udi, pQParameters, request);
  749. }
  750. */
  751. /*
  752. // ==============================================================================================
  753. // GPIB_StatusQuestionableEvent(...)
  754. // Назначенная комманда - STATus:QUEStionable[:EVENt]?
  755. // Параметры комманды - отсутствуют
  756. // Возвращаемое значение - "0"
  757. unsigned int GPIB_StatusQuestionableEvent( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  758. { // request равен 0x00 если комманда :STAT:QUES, а не :STAT:QUES? или :STAT:QUES:EVEN?
  759. // Request ONLY
  760. return GPIB_StatusOperationEvent(udi, pQParameters, request);
  761. }
  762. */
  763. /*
  764. // ==============================================================================================
  765. // GPIB_StatusQuestionableCondition(...)
  766. // Назначенная комманда - STATus:QUEStionable:CONDition?
  767. // Параметры комманды - отсутствуют
  768. // Возвращаемое значение - "0"
  769. unsigned int GPIB_StatusQuestionableCondition( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  770. { // request равен 0x00 если комманда :STAT:QUES, а не :STAT:QUES? или :STAT:QUES:EVEN?
  771. // Request ONLY
  772. return GPIB_StatusOperationEvent(udi, pQParameters, request);
  773. }
  774. */
  775. // ==============================================================================================
  776. // GPIB_StatusQuestionableEnable(...)
  777. // Назначенная комманда - STATus:QUEStionable:ENABle?
  778. // Параметры комманды - отсутствуют
  779. // Возвращаемое значение - "0"
  780. /*
  781. unsigned int GPIB_StatusQuestionableEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  782. {
  783. // request - если пришел запрос Enable? то request - 0x01
  784. // Request and Command support
  785. size_t count = 0;
  786. unsigned err = 0;
  787. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  788. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  789. // --------------------------------------------------
  790. if(!queue_getcount( pQParameters, &count ))
  791. {
  792. err = ERROR_GPIB_INTERNAL;
  793. }
  794. else
  795. {
  796. if( count != ((request)?0:1) )
  797. {
  798. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  799. }
  800. else
  801. {
  802. if( !request )
  803. {
  804. (void)0;
  805. }
  806. else
  807. {
  808. return snprintf(pBulkData_DeviceOut, MAX, "%d", 0 );
  809. }
  810. }
  811. }
  812. if( 0!=err )
  813. {
  814. // 27/08/18
  815. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  816. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  817. }
  818. return 0;
  819. }
  820. */
  821. /*
  822. // ==============================================================================================
  823. // GPIB_StatusPreset(...)
  824. // Назначенная комманда - *RST, STATus:PRESet
  825. // Параметры комманды - отсутствуют
  826. // Возвращаемое значение - отсутствует
  827. unsigned int GPIB_StatusPreset( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  828. { // request всегда 0x00
  829. // Command support only
  830. return GPIB_Reset(udi, pQParameters, request);
  831. }
  832. */
  833. // ==============================================================================================
  834. // GPIB_InterfaceSwitch(...)
  835. // Назначенная комманда - INTerface:SWitch? - переключение режима SCPI -> EZUSB
  836. // Параметры комманды - отсутствуют
  837. // Возвращаемое значение - строка результата операции
  838. unsigned int GPIB_InterfaceSwitch( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  839. {
  840. unsigned int rc = 0;
  841. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  842. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  843. // -------------------------------------------------------
  844. if( InterfaceSwitch( udi, USB_INTERFACE_CONT )==0x01 )
  845. {
  846. if( request)
  847. {
  848. rc = snprintf( pBulkData_DeviceOut, MAX, "%s", "! The Interface will be switched at next connecting a USB cable!" );
  849. }
  850. {
  851. SET_SYSTEM_CODE(CODE_REBOOT_ID, CODE_REBOOT ); // магическое число
  852. SET_SYSTEM_FLAG(FLAG_REBOOT); // флажок на перезагрузку
  853. DeviceBusy( 1 ); // device is busy by writing.
  854. }
  855. }
  856. else
  857. {
  858. if( request)
  859. {
  860. rc = snprintf( pBulkData_DeviceOut, MAX, "%s", "# There was SPI flash error. The Interface will not be switched!" );
  861. }
  862. GPIB_RaiseStandartError( udi, ERROR_GPIB_INTERNAL, NULL, errClass_Autodetect );
  863. }
  864. return rc;
  865. }
  866. // ==============================================================================================
  867. // GPIB_GetTemperature(...)
  868. // Назначенная комманда - MEASure:TEMPerature?
  869. // Параметры комманды - отсутствуют
  870. // Возвращаемое значение - значение температуры в градусах
  871. unsigned int GPIB_GetTemperature( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  872. {
  873. BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
  874. int MAX = udi->BulkRespondStatus.RespondBufferSize;
  875. size_t count =0;
  876. int err = 0;
  877. // -------------------------------------------------
  878. if(!queue_getcount( pQParameters, &count))
  879. {
  880. err = ERROR_GPIB_INTERNAL;
  881. }
  882. else
  883. {
  884. if( count != 0 )
  885. {
  886. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  887. }
  888. else
  889. {
  890. if( !request )
  891. {
  892. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  893. }
  894. else
  895. {
  896. return temperature_convert( pBulkData_DeviceOut, MAX, get_average_temperature() );
  897. }
  898. }
  899. }
  900. if( 0 != err )
  901. {
  902. // 27/08/18
  903. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  904. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  905. }
  906. return 0;
  907. }
  908. // GPIB_SwitchCount(...)
  909. // Назначенная комманда - [SYSTem:]SWITch:COUNt?
  910. // Параметры комманды - НЕТ
  911. // Возвращаемое значение - общее количество состояний портов
  912. unsigned int GPIB_SwitchCount( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  913. {
  914. size_t count;
  915. unsigned int err = 0;
  916. unsigned int rc = 0;
  917. //-----------------------------------------------------------------------------------------
  918. if(!queue_getcount(pQParameters, &count))
  919. {
  920. err = ERROR_GPIB_INTERNAL;
  921. goto L_GPIB_SwitchList_EXIT;
  922. }
  923. if(!request)
  924. {
  925. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  926. goto L_GPIB_SwitchList_EXIT;
  927. }
  928. if( count != 0 )
  929. {
  930. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  931. goto L_GPIB_SwitchList_EXIT;
  932. }
  933. {
  934. BYTE * pBuffer = (BYTE*)udi->usbtmcGpib.pData;
  935. int freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  936. int32_t states = (int32_t)ACMClass->properties.allowedStatesCount;
  937. rc = GPIB_Integer2Str( states, pBuffer, freeSpace, Format_Int2Str_N );
  938. }
  939. L_GPIB_SwitchList_EXIT:
  940. if( err != 0 )
  941. {
  942. // 27/08/18
  943. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  944. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  945. rc = 0;
  946. }
  947. return rc;
  948. }
  949. // GPIB_SwitchList(...)
  950. // Назначенная комманда - [SWITch:]LIST?
  951. // Параметры комманды - порт( A, B, AB )
  952. // Возвращаемое значение - количество состояний порта
  953. unsigned int GPIB_SwitchList( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  954. {
  955. size_t count;
  956. unsigned int err = 0;
  957. unsigned int rc = 0;
  958. //-----------------------------------------------------------------------------------------
  959. if(!queue_getcount(pQParameters, &count))
  960. {
  961. err = ERROR_GPIB_INTERNAL;
  962. goto L_GPIB_SwitchList_EXIT;
  963. }
  964. if(!request)
  965. {
  966. err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  967. goto L_GPIB_SwitchList_EXIT;
  968. }
  969. if( count != 0 )
  970. {
  971. err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  972. goto L_GPIB_SwitchList_EXIT;
  973. }
  974. {
  975. BYTE * pBuffer = (BYTE*)udi->usbtmcGpib.pData;
  976. int freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  977. rc = ACMClass->methods.getKeyStateList( pBuffer, freeSpace );
  978. }
  979. L_GPIB_SwitchList_EXIT:
  980. if( err != 0 )
  981. {
  982. // 27/08/18
  983. // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
  984. GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
  985. rc = 0;
  986. }
  987. return rc;
  988. }
  989. //------------------------------------------------------------------------------
  990. // __Util_CheckParamTableId:
  991. // Is used as a universal parameter checker for following functions:
  992. // * GPIB_MemoryTableTime
  993. // * GPIB_MemoryTableDate
  994. // etc.
  995. // All the functions listed above have the same "command prototype" - MEM:TABLE:CMD [FACTory|USER1|USER2|USER3]
  996. // This function checks the only parameter - characterization table id (factory/user1/user2/user3),
  997. // parses it and converts into the [eChrz_t].
  998. // The function returns the error code.
  999. static unsigned int __Util_CheckParamTableId( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request,
  1000. eChrz_t * pId )
  1001. {
  1002. unsigned int errCode = 0;
  1003. size_t rc = 0;
  1004. char textBuffer[16];
  1005. eChrz_t id; // Characterization Table Id
  1006. // check the requiest status
  1007. if(!request )
  1008. {
  1009. // error: command must be a request
  1010. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  1011. goto L__Util_CheckParamTableId_EXIT;
  1012. }
  1013. // Retrieve amount of parameters from the queue
  1014. if( !queue_getcount(pQParameters, &rc) )
  1015. {
  1016. // error: can't get parameters count
  1017. errCode = ERROR_GPIB_INTERNAL;
  1018. goto L__Util_CheckParamTableId_EXIT;
  1019. }
  1020. // Check parameters count
  1021. else if( 1 < rc ) // only one OPTIONAL parameter allowed for this command
  1022. {
  1023. // error: wrong parameters count ( must be 0 or 1 )
  1024. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  1025. goto L__Util_CheckParamTableId_EXIT;
  1026. }
  1027. if( 1 == rc ) // one parameter - table identifier (factory/user1/user2/user3)
  1028. {
  1029. // optional parameter is specified
  1030. // retrieve the first parameter: table identifier (factory/user1/user2/user3)
  1031. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  1032. {
  1033. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1034. goto L__Util_CheckParamTableId_EXIT;
  1035. }
  1036. // check the parameter type
  1037. else if( eParTypeChar != textBuffer[0] )
  1038. {
  1039. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  1040. goto L__Util_CheckParamTableId_EXIT;
  1041. }
  1042. // retrieve the parameter
  1043. id = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
  1044. if( eCh_MAX == id )
  1045. {
  1046. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1047. goto L__Util_CheckParamTableId_EXIT;
  1048. }
  1049. }
  1050. else
  1051. {
  1052. // optional parameter is absent
  1053. // table identifier omitted, "FACTory" is supposed
  1054. id = eChFactory;
  1055. }
  1056. L__Util_CheckParamTableId_EXIT:
  1057. if( 0 == errCode )
  1058. {
  1059. if( NULL != pId )
  1060. {
  1061. *pId = id;
  1062. }
  1063. }
  1064. return errCode;
  1065. }
  1066. //------------------------------------------------------------------------------
  1067. // Descriptions for elements of [eChrz_t]
  1068. static const char * const aChrzDesc[] =
  1069. {
  1070. "Factory characterization data", // eChFactory
  1071. "USER1 characterization data", // eChUser1
  1072. "USER2 characterization data", // eChUser2
  1073. "USER3 characterization data", // eChUser3
  1074. NULL // eCh_MAX
  1075. };
  1076. const char pcThermoDesc[] = "Thermocompensation data";
  1077. // Descriptions for elements of [ePortComb_t]
  1078. static const char * const aPortComb[] =
  1079. {
  1080. "Port A" , // ePortComb_A
  1081. "Port B" , // ePortComb_B
  1082. "Port C" , // ePortComb_C
  1083. "Port D" , // ePortComb_D
  1084. "Thru AB" , // ePortComb_AB
  1085. "Thru AC" , // ePortComb_AC
  1086. "Thru AD" , // ePortComb_AD
  1087. "Thru BC" , // ePortComb_BC
  1088. "Thru BD" , // ePortComb_BD
  1089. "Thru CD" , // ePortComb_CD
  1090. "CHECK state" , // ePortComb_CHECK
  1091. NULL // ePortComb_MAX
  1092. };
  1093. /*
  1094. // Descriptions for elements of [eChrz_t]
  1095. static const char * aPortDesc[] =
  1096. {
  1097. "port A", // ePortId_A
  1098. "port B", // ePortId_B
  1099. "port C", // ePortId_C
  1100. "port D", // ePortId_D
  1101. NULL // eCh_MAX
  1102. };*/
  1103. //------------------------------------------------------------------------------
  1104. // GPIB_MemoryTablePoints()
  1105. // Prints amount of characterization points of the characterization table: factory or user
  1106. size_t GPIB_MemoryTablePoints( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1107. {
  1108. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1109. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1110. eChrz_t id = eCh_MAX;
  1111. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1112. size_t rc = 0;
  1113. size_t nPoints;
  1114. if( 0 == errCode )
  1115. {
  1116. nPoints = ACMClass->methods.xCharacterization.getPointsCount( id );
  1117. if( 0 != nPoints )
  1118. {
  1119. rc = snprintf( (char*)pBuffer, freeSpace, "%d", nPoints );
  1120. if( 0 == rc || rc == freeSpace )
  1121. {
  1122. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  1123. }
  1124. }
  1125. else
  1126. {
  1127. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1128. }
  1129. }
  1130. // L_GPIB_MemoryTablePoints_EXIT:
  1131. if( 0 != errCode )
  1132. {
  1133. const char * pDescription = NULL;
  1134. if( eCh_MAX != id )
  1135. {
  1136. pDescription = aChrzDesc[ (size_t)id ];
  1137. }
  1138. // 27/08/18
  1139. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1140. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1141. rc = 0;
  1142. }
  1143. return rc;
  1144. }
  1145. //------------------------------------------------------------------------------
  1146. // GPIB_MemoryTableDate()
  1147. // Prints the characterization date
  1148. size_t GPIB_MemoryTableDate( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1149. {
  1150. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1151. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1152. eChrz_t id = eCh_MAX;
  1153. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1154. size_t rc = 0;
  1155. if( 0 == errCode )
  1156. {
  1157. if( !ACMClass->methods.xCharacterization.getDate( id, (char*)pBuffer, freeSpace, &rc ) )
  1158. {
  1159. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1160. }
  1161. }
  1162. if( 0 != errCode )
  1163. {
  1164. const char * pDescription = NULL;
  1165. if( eCh_MAX != id )
  1166. {
  1167. pDescription = aChrzDesc[ (size_t)id ];
  1168. }
  1169. // 27/08/18
  1170. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1171. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1172. rc = 0;
  1173. }
  1174. return rc;
  1175. }
  1176. // GPIB_MemoryTableTime()
  1177. // Prints the characterization time
  1178. size_t GPIB_MemoryTableTime( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1179. {
  1180. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1181. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1182. eChrz_t id = eCh_MAX;
  1183. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1184. size_t rc = 0;
  1185. if( 0 == errCode )
  1186. {
  1187. if( !ACMClass->methods.xCharacterization.getTime( id, (char*)pBuffer, freeSpace, &rc ) )
  1188. {
  1189. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1190. }
  1191. }
  1192. if( 0 != errCode )
  1193. {
  1194. const char * pDescription = NULL;
  1195. if( eCh_MAX != id )
  1196. {
  1197. pDescription = aChrzDesc[ (size_t)id ];
  1198. }
  1199. // 27/08/18
  1200. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1201. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1202. rc = 0;
  1203. }
  1204. return rc;
  1205. }
  1206. // GPIB_MemoryTableTemp()
  1207. // Prints the characterization temperature
  1208. size_t GPIB_MemoryTableTemp( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1209. {
  1210. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1211. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1212. eChrz_t id = eCh_MAX;
  1213. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1214. double temperature = 0;
  1215. size_t rc = 0;
  1216. if( 0 == errCode )
  1217. {
  1218. if( !ACMClass->methods.xCharacterization.getChrzTemp( id, &temperature ) )
  1219. {
  1220. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1221. }
  1222. else
  1223. {
  1224. rc = GPIB_Double2Str( temperature, (char*)pBuffer, freeSpace, Format_Double2Str_Ndot3 );
  1225. if( 0 == rc )
  1226. {
  1227. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  1228. }
  1229. }
  1230. }
  1231. if( 0 != errCode )
  1232. {
  1233. const char * pDescription = NULL;
  1234. if( eCh_MAX != id )
  1235. {
  1236. pDescription = aChrzDesc[ (size_t)id ];
  1237. }
  1238. // 27/08/18
  1239. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1240. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1241. rc = 0;
  1242. }
  1243. return rc;
  1244. }
  1245. // GPIB_MemoryTableFreqType()
  1246. // Prints the type of the characterization frequency scale
  1247. size_t GPIB_MemoryTableFreqType( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1248. {
  1249. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1250. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1251. eChrz_t id = eCh_MAX;
  1252. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1253. size_t rc = 0;
  1254. if( 0 == errCode )
  1255. {
  1256. eChrzScaleType_t scaleType;
  1257. if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType ) )
  1258. {
  1259. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1260. }
  1261. else
  1262. {
  1263. if( eChScaleLinear == scaleType )
  1264. {
  1265. rc = snprintf( (char*)pBuffer, freeSpace, "%s", "LIN" );
  1266. }
  1267. else if( eChScaleSegment == scaleType )
  1268. {
  1269. rc = snprintf( (char*)pBuffer, freeSpace, "%s", "SEGM" );
  1270. }
  1271. else rc = 0;
  1272. }
  1273. }
  1274. if( 0 != errCode )
  1275. {
  1276. const char * pDescription = NULL;
  1277. if( eCh_MAX != id )
  1278. {
  1279. pDescription = aChrzDesc[ (size_t)id ];
  1280. }
  1281. // 27/08/18
  1282. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1283. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1284. rc = 0;
  1285. }
  1286. return rc;
  1287. }
  1288. // GPIB_MemoryTableFreqData()
  1289. // Prints all the frequency points of the characterization frequency scale
  1290. size_t GPIB_MemoryTableFreqData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1291. {
  1292. // 1
  1293. char * pBuffer = (char*)udi->usbtmcGpib.pData;
  1294. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1295. size_t rc = 0; // full amount of bytes returned
  1296. size_t bytes = 0; // bytes returned
  1297. unsigned int errCode = 0; // error identifier
  1298. sEcalSegment_t segment; // scale segment data
  1299. size_t iSeg = 0, nSeg = 0; // amount of segments
  1300. size_t iPnt = 0, nPnt = 0; // amount of points
  1301. eChrz_t id = eCh_MAX; // characterization id
  1302. eChrzScaleType_t scaleType; // scale type
  1303. // 2
  1304. // Check if the function context is saved and must be continued
  1305. if( !udi->GPIBFunctionContext.bEnable )
  1306. {
  1307. // no context found
  1308. // check input parameters
  1309. errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1310. if( 0 != errCode || eCh_MAX == id )
  1311. {
  1312. goto L_GPIB_MemoryTableFreqData_EXIT;
  1313. }
  1314. // retrieve the scale type
  1315. if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType ) )
  1316. {
  1317. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1318. goto L_GPIB_MemoryTableFreqData_EXIT;
  1319. }
  1320. if( eChScaleLinear == scaleType )
  1321. {
  1322. // Linear scale
  1323. nSeg = 1;
  1324. iSeg = 0;
  1325. iPnt = 0;
  1326. }
  1327. else
  1328. {
  1329. // Segment scale
  1330. // read amount of segments
  1331. nSeg = ACMClass->methods.xCharacterization.getScaleSegment( id, NULL, 0 );
  1332. iSeg = 0;
  1333. iPnt = 0;
  1334. if( 0 == nSeg )
  1335. {
  1336. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1337. goto L_GPIB_MemoryTableFreqData_EXIT;
  1338. }
  1339. }
  1340. }
  1341. // 3
  1342. else
  1343. {
  1344. // load previous context
  1345. /* */
  1346. if(
  1347. queue_get( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id), &bytes ) // load memory segment id
  1348. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&nSeg , sizeof(nSeg), &bytes ) // load amount of segments
  1349. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&iSeg , sizeof(iSeg), &bytes ) // load segment index
  1350. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&nPnt , sizeof(nPnt), &bytes ) // load amount of points
  1351. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&iPnt , sizeof(iPnt), &bytes ) // load point index
  1352. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&scaleType , sizeof(scaleType), &bytes ) // load the scale type
  1353. )
  1354. {
  1355. // OK
  1356. }
  1357. else
  1358. {
  1359. errCode = ERROR_GPIB_INTERNAL;
  1360. goto L_GPIB_MemoryTableFreqData_EXIT;
  1361. }
  1362. }
  1363. rc = 0;
  1364. // 4
  1365. // try to print frequencies list
  1366. for( (void)iSeg; iSeg < nSeg; ++iSeg ) // for each segment
  1367. {
  1368. // For segment scale: load the segment data
  1369. if( eChScaleSegment == scaleType )
  1370. {
  1371. // retrieve the segment information
  1372. if( 1 != ACMClass->methods.xCharacterization.getScaleSegment( id, &segment, iSeg ) )
  1373. {
  1374. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1375. goto L_GPIB_MemoryTableFreqData_EXIT;
  1376. }
  1377. // load the points count
  1378. nPnt = segment.Points;
  1379. }
  1380. if( eChScaleLinear == scaleType )
  1381. {
  1382. // load the points count
  1383. nPnt = ACMClass->methods.xCharacterization.getPointsCount( id );
  1384. // load start and stop frequencies
  1385. if( !ACMClass->methods.xCharacterization.getStartFreq( id, &segment.Fstart )
  1386. || !ACMClass->methods.xCharacterization.getStopFreq( id, &segment.Fstop ) )
  1387. {
  1388. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1389. goto L_GPIB_MemoryTableFreqData_EXIT;
  1390. }
  1391. // store @nPnt into the @segment to unify the access
  1392. segment.Points = nPnt;
  1393. }
  1394. if( 0 == nPnt )
  1395. {
  1396. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1397. goto L_GPIB_MemoryTableFreqData_EXIT;
  1398. }
  1399. for( (void)iPnt; iPnt < nPnt; ++iPnt ) // for each point
  1400. {
  1401. // One point has the following format:
  1402. // <Freq_i>,<SPACE>
  1403. // where @i is the point number,
  1404. // @nPnt - amount of points.
  1405. // Total amount of numbers to be print: nPnt
  1406. // One number has 16 symbols length plus 2 (comma and space)
  1407. // So, 18 characters required to print one point.
  1408. // To prevent overflowing by snprintf() with printing null-term,
  1409. // it is required at lease 20 characters free
  1410. if( freeSpace >= 20 )
  1411. {
  1412. double dbl_freq_point = 0.0;
  1413. if( segment.Points > 1 )
  1414. {
  1415. // e.g. segment #1, (1.0e+5;2.0e+5,11 points)
  1416. // START_FREQ=100000; STOP_FREQ=200000; N=11
  1417. // 100000, 110000, 120000, 130000, 140000 } 5 points
  1418. // 150000, 160000, 170000, 180000, 190000, 20000 } 6 points
  1419. // Total: 11 points on (1.0e+5;2.0e+5)
  1420. // So, STEP is (STOP_FREQ - START_FREQ)/(N-1) = 10000
  1421. #define SegmentFreqStep( seg ) ((seg.Fstop - seg.Fstart) / (seg.Points - 1))
  1422. // calculate current frequency point (MAGNITUDE)
  1423. // print the frequency point
  1424. dbl_freq_point = segment.Fstart + SegmentFreqStep( segment ) * iPnt;
  1425. /*
  1426. bytes = GPIB_Double2Str( segment.Fstart + SegmentFreqStep( segment ) * iPnt,
  1427. pBuffer, freeSpace, Format_Double2Str_Sci );*/
  1428. }
  1429. else
  1430. {
  1431. dbl_freq_point = segment.Fstart;
  1432. /*
  1433. bytes = GPIB_Double2Str( segment.Fstart,
  1434. pBuffer, freeSpace, Format_Double2Str_Sci );*/
  1435. }
  1436. { // fix: 05/09/18
  1437. // round the value to [Hz]
  1438. dbl_freq_point = round( dbl_freq_point );
  1439. // print rounded value
  1440. bytes = GPIB_Double2Str( dbl_freq_point,
  1441. pBuffer, freeSpace, Format_Double2Str_Sci );
  1442. }
  1443. pBuffer += bytes;
  1444. freeSpace -= bytes;
  1445. rc += bytes;
  1446. // print the delimeter
  1447. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  1448. pBuffer += bytes;
  1449. freeSpace -= bytes;
  1450. rc += bytes;
  1451. }
  1452. else
  1453. {
  1454. // --------------------------------------------------------------------------
  1455. // Save context
  1456. usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableFreqData );
  1457. if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id) ) // Save memory segment id
  1458. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&nSeg , sizeof(nSeg) ) // Save amount of segments
  1459. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&iSeg , sizeof(iSeg) ) // Save segment index
  1460. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&nPnt , sizeof(nPnt) ) // Save amount of points
  1461. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&iPnt , sizeof(iPnt) ) // Save point index
  1462. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&scaleType , sizeof(scaleType) ) // Save the scale type
  1463. )
  1464. {
  1465. udi->GPIBFunctionContext.LastFunction = NULL;
  1466. errCode = ERROR_GPIB_INTERNAL;
  1467. goto L_GPIB_MemoryTableFreqData_EXIT;
  1468. }
  1469. udi->BulkRespondStatus.bIsLastTransfer = FALSE;
  1470. errCode = 0;
  1471. // --------------------------------------------------------------------------
  1472. goto L_GPIB_MemoryTableFreqData_EXIT;
  1473. }
  1474. /*for( const char * p = __Buffer; p != pBuffer; ++p )
  1475. {
  1476. if( *p == '\0' )
  1477. {
  1478. asm( "bkpt #0" );
  1479. }
  1480. }*/
  1481. }
  1482. // For the last point of last segment
  1483. if( iSeg >= nSeg-1 )
  1484. if( iPnt >= nPnt )
  1485. {
  1486. if( rc > 2 )
  1487. rc -= 2; // cut off the last comma separator and space
  1488. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  1489. }
  1490. iPnt = 0;
  1491. }
  1492. // 5
  1493. L_GPIB_MemoryTableFreqData_EXIT:
  1494. if( 0 != errCode )
  1495. {
  1496. const char * pDescription = NULL;
  1497. if( eCh_MAX != id )
  1498. {
  1499. pDescription = aChrzDesc[ (size_t)id ];
  1500. }
  1501. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  1502. // 27/08/18
  1503. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1504. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1505. rc = 0;
  1506. }
  1507. return rc;
  1508. }
  1509. // GPIB_MemoryTableFreqSegmData()
  1510. // Prints the scale segments parameters of the characterization frequency scale
  1511. size_t GPIB_MemoryTableFreqSegmData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1512. {
  1513. // 1
  1514. char * pBuffer = (char*)udi->usbtmcGpib.pData;
  1515. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1516. size_t rc = 0; // full amount of bytes returned
  1517. size_t bytes = 0; // bytes returned
  1518. size_t i, n = 0; // amount of segments
  1519. eChrz_t id = eCh_MAX; // characterization id
  1520. unsigned int errCode = 0; // error identifier
  1521. sEcalSegment_t segment; // scale segment data
  1522. eChrzScaleType_t scaleType; // scale type
  1523. // 2
  1524. // Check if the function context is saved and must be continued
  1525. if( !udi->GPIBFunctionContext.bEnable )
  1526. {
  1527. // no context found
  1528. // check input parameters
  1529. errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1530. if( 0 != errCode || eCh_MAX == id )
  1531. {
  1532. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1533. }
  1534. // retrieve the scale type
  1535. // check the conditions: the scale must be a Segment Type Scale
  1536. if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType )
  1537. || eChScaleSegment != scaleType)
  1538. {
  1539. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1540. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1541. }
  1542. // read amount of segments
  1543. n = ACMClass->methods.xCharacterization.getScaleSegment( id, NULL, 0 );
  1544. i = 0;
  1545. if( 0 == n )
  1546. {
  1547. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1548. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1549. }
  1550. // print amount of segements
  1551. bytes = snprintf( pBuffer, freeSpace, "%d%s", n, ",\n" /* ",\r\n" */);
  1552. if( 0 == bytes || bytes == freeSpace )
  1553. {
  1554. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  1555. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1556. }
  1557. else
  1558. {
  1559. rc += bytes;
  1560. freeSpace -= bytes;
  1561. pBuffer += bytes;
  1562. }
  1563. }
  1564. // 3
  1565. else
  1566. {
  1567. // load previous context
  1568. /* */
  1569. if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id),&bytes ) // load memory segment id
  1570. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&n , sizeof(n), &bytes ) // load amount of segments
  1571. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&i , sizeof(i), &bytes ) // load segment number
  1572. )
  1573. {
  1574. // OK
  1575. }
  1576. else
  1577. {
  1578. errCode = ERROR_GPIB_INTERNAL;
  1579. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1580. }
  1581. }
  1582. // 4
  1583. // try to print the segment list
  1584. for( /*@i is loaded from context*/; i < n; ++i )
  1585. {
  1586. // segment data format:
  1587. // <StartFreq>, <StopFreq>, <NumberOfPoints><CR><LF>
  1588. // e.g.
  1589. // 1.0000000000e+5, 2.0000000000e+6, 13<CR><LF>
  1590. // Minimum free space required to one segment: 36 + amount of chars in <NumberOfPoints>
  1591. // Let it be 4.
  1592. // Whole number of free bytes in the buffer: 40
  1593. // To prevent overflowing by snprintf() with printing null-term,
  1594. // it is required at lease 44 characters free
  1595. if( freeSpace >= 44 )
  1596. {
  1597. if( 1 == ACMClass->methods.xCharacterization.getScaleSegment( id, &segment, i ) )
  1598. {
  1599. // print the segment data
  1600. bytes = GPIB_Double2Str( segment.Fstart, pBuffer, freeSpace, Format_Double2Str_Sci );
  1601. pBuffer += bytes;
  1602. freeSpace -= bytes;
  1603. rc += bytes;
  1604. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  1605. pBuffer += bytes;
  1606. freeSpace -= bytes;
  1607. rc += bytes;
  1608. bytes = GPIB_Double2Str( segment.Fstop, pBuffer, freeSpace, Format_Double2Str_Sci );
  1609. pBuffer += bytes;
  1610. freeSpace -= bytes;
  1611. rc += bytes;
  1612. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  1613. pBuffer += bytes;
  1614. freeSpace -= bytes;
  1615. rc += bytes;
  1616. bytes = snprintf( pBuffer, freeSpace, "%d%s", segment.Points, "\n"/*"\r\n"*/ );
  1617. pBuffer += bytes;
  1618. freeSpace -= bytes;
  1619. rc += bytes;
  1620. }
  1621. else
  1622. {
  1623. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1624. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1625. }
  1626. }
  1627. else
  1628. {
  1629. // --------------------------------------------------------------------------
  1630. // Save context
  1631. usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableFreqSegmData );
  1632. if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id) ) // Save memory segment id
  1633. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&n , sizeof(n) ) // Save amount of segments
  1634. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&i , sizeof(i) ) // Save segment number
  1635. )
  1636. {
  1637. udi->GPIBFunctionContext.LastFunction = NULL;
  1638. errCode = ERROR_GPIB_INTERNAL;
  1639. goto L_GPIB_MemoryTableFreqSegmData_EXIT;
  1640. }
  1641. udi->BulkRespondStatus.bIsLastTransfer = FALSE;
  1642. errCode = 0;
  1643. // --------------------------------------------------------------------------
  1644. break;
  1645. }
  1646. }
  1647. // 5
  1648. L_GPIB_MemoryTableFreqSegmData_EXIT:
  1649. if( 0 != errCode )
  1650. {
  1651. const char * pDescription = NULL;
  1652. if( eCh_MAX != id )
  1653. {
  1654. pDescription = aChrzDesc[ (size_t)id ];
  1655. }
  1656. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  1657. // 27/08/18
  1658. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1659. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1660. rc = 0;
  1661. }
  1662. return rc;
  1663. }
  1664. // GPIB_MemoryTableFreqStart()
  1665. // Prints the start frequency of the characterization frequency scale
  1666. size_t GPIB_MemoryTableFreqStart( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1667. {
  1668. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1669. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1670. eChrz_t id = eCh_MAX;
  1671. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1672. size_t rc = 0;
  1673. double startFreq = 0.0f;
  1674. if( 0 == errCode )
  1675. {
  1676. if( !ACMClass->methods.xCharacterization.getStartFreq( id, &startFreq ) )
  1677. {
  1678. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1679. }
  1680. else
  1681. {
  1682. rc = GPIB_Double2Str( startFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
  1683. }
  1684. }
  1685. if( 0 != errCode )
  1686. {
  1687. const char * pDescription = NULL;
  1688. if( eCh_MAX != id )
  1689. {
  1690. pDescription = aChrzDesc[ (size_t)id ];
  1691. }
  1692. // 27/08/18
  1693. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1694. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1695. rc = 0;
  1696. }
  1697. return rc;
  1698. }
  1699. // GPIB_MemoryTableFreqStop()
  1700. // Prints the stop frequency of the characterization frequency scale
  1701. size_t GPIB_MemoryTableFreqStop( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1702. {
  1703. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1704. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1705. eChrz_t id = eCh_MAX;
  1706. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1707. size_t rc = 0;
  1708. double stopFreq = 0.0f;
  1709. if( 0 == errCode )
  1710. {
  1711. if( !ACMClass->methods.xCharacterization.getStopFreq( id, &stopFreq ) )
  1712. {
  1713. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1714. }
  1715. else
  1716. {
  1717. rc = GPIB_Double2Str( stopFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
  1718. }
  1719. }
  1720. if( 0 != errCode )
  1721. {
  1722. const char * pDescription = NULL;
  1723. if( eCh_MAX != id )
  1724. {
  1725. pDescription = aChrzDesc[ (size_t)id ];
  1726. }
  1727. // 27/08/18
  1728. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1729. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1730. rc = 0;
  1731. }
  1732. return rc;
  1733. }
  1734. // GPIB_MemTableAdapter()
  1735. //
  1736. size_t GPIB_MemoryTableAdapter( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1737. {
  1738. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1739. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1740. size_t rc = 0;
  1741. size_t nParams = 0;
  1742. unsigned int errCode = 0;
  1743. eChrz_t id = eCh_MAX; // by default
  1744. ePortId_t pid; // Port ID
  1745. char textBuffer[16];
  1746. // check the requiest status
  1747. if(!request )
  1748. {
  1749. // error: command must be a request
  1750. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  1751. goto L_GPIB_MemoryTableAdapter_EXIT;
  1752. }
  1753. // Retrieve amount of parameters from the queue
  1754. if( !queue_getcount(pQParameters, &nParams) )
  1755. {
  1756. // error: can't get parameters count
  1757. errCode = ERROR_GPIB_INTERNAL;
  1758. goto L_GPIB_MemoryTableAdapter_EXIT;
  1759. }
  1760. // Check parameters count
  1761. else if( 1 != nParams && 2 != nParams ) // this command must have 1 or 2 parameters
  1762. {
  1763. // error: wrong parameters count ( must be 1 )
  1764. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  1765. goto L_GPIB_MemoryTableAdapter_EXIT;
  1766. }
  1767. // first parameter - port identifier (A/B/C/D)
  1768. {
  1769. // retrieve the first parameter: port identifier (A/B/C/D)
  1770. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  1771. {
  1772. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1773. goto L_GPIB_MemoryTableAdapter_EXIT;
  1774. }
  1775. // check the parameter type
  1776. else if( eParTypeChar != textBuffer[0] )
  1777. {
  1778. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  1779. goto L_GPIB_MemoryTableAdapter_EXIT;
  1780. }
  1781. // retrieve the parameter
  1782. pid = GPIB_GetPortId( &textBuffer[1], rc - 1 );
  1783. if( ePortId_MAX == pid )
  1784. {
  1785. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1786. goto L_GPIB_MemoryTableAdapter_EXIT;
  1787. }
  1788. if( 2 == nParams )
  1789. {
  1790. // retrieve second parameter: table identifier (factory/user1/user2/user3)
  1791. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  1792. {
  1793. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1794. goto L_GPIB_MemoryTableAdapter_EXIT;
  1795. }
  1796. // check the parameter type
  1797. else if( eParTypeChar != textBuffer[0] )
  1798. {
  1799. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  1800. goto L_GPIB_MemoryTableAdapter_EXIT;
  1801. }
  1802. // retrieve the parameter
  1803. id = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
  1804. if( eCh_MAX == id )
  1805. {
  1806. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1807. goto L_GPIB_MemoryTableAdapter_EXIT;
  1808. }
  1809. }
  1810. else
  1811. {
  1812. id = eChFactory;
  1813. }
  1814. }
  1815. if( !ACMClass->methods.xCharacterization.getAdapterDesc( id, pid, (char*)pBuffer, freeSpace, &rc ) )
  1816. {
  1817. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1818. }
  1819. L_GPIB_MemoryTableAdapter_EXIT:
  1820. if( 0 != errCode )
  1821. {
  1822. const char * pDescription = NULL;
  1823. if( eCh_MAX != id )
  1824. {
  1825. pDescription = aChrzDesc[ (size_t)id ];
  1826. }
  1827. // 27/08/18
  1828. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1829. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1830. rc = 0;
  1831. }
  1832. return 0;
  1833. }
  1834. // GPIB_MemTableConnector()
  1835. //
  1836. size_t GPIB_MemoryTableConnector( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1837. {
  1838. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1839. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1840. size_t rc = 0;
  1841. unsigned int errCode = 0;
  1842. ePortId_t pid; // Port ID
  1843. char textBuffer[16];
  1844. // check the requiest status
  1845. if(!request )
  1846. {
  1847. // error: command must be a request
  1848. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  1849. goto L_GPIB_MemoryTableAdapter_EXIT;
  1850. }
  1851. // Retrieve amount of parameters from the queue
  1852. if( !queue_getcount(pQParameters, &rc) )
  1853. {
  1854. // error: can't get parameters count
  1855. errCode = ERROR_GPIB_INTERNAL;
  1856. goto L_GPIB_MemoryTableAdapter_EXIT;
  1857. }
  1858. // Check parameters count
  1859. else if( 1 != rc ) // this command must have only one parameter
  1860. {
  1861. // error: wrong parameters count ( must be 1 )
  1862. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  1863. goto L_GPIB_MemoryTableAdapter_EXIT;
  1864. }
  1865. // parameter - port identifier (A/B/C/D)
  1866. {
  1867. // retrieve the first parameter: port identifier (A/B/C/D)
  1868. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  1869. {
  1870. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1871. goto L_GPIB_MemoryTableAdapter_EXIT;
  1872. }
  1873. // check the parameter type
  1874. else if( eParTypeChar != textBuffer[0] )
  1875. {
  1876. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  1877. goto L_GPIB_MemoryTableAdapter_EXIT;
  1878. }
  1879. // retrieve the parameter
  1880. pid = GPIB_GetPortId( &textBuffer[1], rc - 1 );
  1881. if( ePortId_MAX == pid )
  1882. {
  1883. errCode = ERROR_GPIB_INVALID_PARAMETER;
  1884. goto L_GPIB_MemoryTableAdapter_EXIT;
  1885. }
  1886. }
  1887. if( !ACMClass->methods.xCharacterization.getConnectorType( pid, (char*)pBuffer, freeSpace, &rc ) )
  1888. {
  1889. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1890. }
  1891. L_GPIB_MemoryTableAdapter_EXIT:
  1892. if( 0 != errCode )
  1893. {
  1894. // 27/08/18
  1895. // GPIB_RaiseStandartError( udi, errCode, aChrzDesc[ (size_t)eChFactory ], GPIB_ERROR_ID_COR | request );
  1896. GPIB_RaiseStandartError( udi, errCode, aChrzDesc[ (size_t)eChFactory ], errClass_Autodetect );
  1897. rc = 0;
  1898. }
  1899. return rc;
  1900. }
  1901. // GPIB_MemTableAnalyzer()
  1902. // Prints the analyzer model of the characterization
  1903. size_t GPIB_MemoryTableAnalyzer( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1904. {
  1905. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1906. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1907. eChrz_t id = eCh_MAX;
  1908. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1909. size_t rc = 0;
  1910. if( 0 == errCode )
  1911. {
  1912. if( !ACMClass->methods.xCharacterization.getAnalyzer( id, (char*)pBuffer, freeSpace, &rc ) )
  1913. {
  1914. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1915. }
  1916. }
  1917. if( 0 != errCode )
  1918. {
  1919. const char * pDescription = NULL;
  1920. if( eCh_MAX != id )
  1921. {
  1922. pDescription = aChrzDesc[ (size_t)id ];
  1923. }
  1924. // 27/08/18
  1925. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1926. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1927. rc = 0;
  1928. }
  1929. return rc;
  1930. }
  1931. // GPIB_MemTablePlace()
  1932. // Prints the location where the characterization has been created
  1933. size_t GPIB_MemoryTablePlace( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1934. {
  1935. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1936. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1937. eChrz_t id = eCh_MAX;
  1938. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1939. size_t rc = 0;
  1940. if( 0 == errCode )
  1941. {
  1942. if( !ACMClass->methods.xCharacterization.getPlace( id, (char*)pBuffer, freeSpace, &rc ) )
  1943. {
  1944. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1945. }
  1946. }
  1947. if( 0 != errCode )
  1948. {
  1949. const char * pDescription = NULL;
  1950. if( eCh_MAX != id )
  1951. {
  1952. pDescription = aChrzDesc[ (size_t)id ];
  1953. }
  1954. // 27/08/18
  1955. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1956. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1957. rc = 0;
  1958. }
  1959. return rc;
  1960. }
  1961. // GPIB_MemTableOperator()
  1962. // Prints the operator's name who created the characterization
  1963. size_t GPIB_MemoryTableOperator( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  1964. {
  1965. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  1966. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  1967. eChrz_t id = eCh_MAX;
  1968. unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
  1969. size_t rc = 0;
  1970. if( 0 == errCode )
  1971. {
  1972. if( !ACMClass->methods.xCharacterization.getOperator( id, (char*)pBuffer, freeSpace, &rc ) )
  1973. {
  1974. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  1975. }
  1976. }
  1977. if( 0 != errCode )
  1978. {
  1979. const char * pDescription = NULL;
  1980. if( eCh_MAX != id )
  1981. {
  1982. pDescription = aChrzDesc[ (size_t)id ];
  1983. }
  1984. // 27/08/18
  1985. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  1986. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  1987. rc = 0;
  1988. }
  1989. return rc;
  1990. }
  1991. // ==============================================================================================
  1992. // volatile size_t debug_call = 0;
  1993. // GPIB_MemoryTableData()
  1994. // MEM:TABLE:DATA? <PORT_COMBINATION>, <PORT_STATE>, [MEMORY_SECTOR]
  1995. // Prints the contents of the characterization table depending on the following parameters:
  1996. // - port combination (A, B, or CD, or CHECK, etc)
  1997. // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
  1998. // - memory sector (Factory/USER1/USER2/USER3), OPTIONAL, by default = FACTORY
  1999. size_t GPIB_MemoryTableData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2000. {
  2001. // 1
  2002. char * pBuffer = (char*)udi->usbtmcGpib.pData;
  2003. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2004. size_t rc = 0; // full amount of bytes returned
  2005. unsigned int errCode = 0; // error identifier
  2006. sACMGetPoints_t tableContext; // table context to store the data between calls
  2007. eChrz_t msid = eCh_MAX; // characterization id, = memory sector id
  2008. ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
  2009. ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
  2010. // debug_call++;
  2011. // 2
  2012. // Check if the function context is saved and must be continued
  2013. if( !udi->GPIBFunctionContext.bEnable )
  2014. {
  2015. // no context found
  2016. size_t nParam = 0; // amount of parameters
  2017. if( !request )
  2018. {
  2019. // error: request only supported
  2020. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2021. goto L_GPIB_MemoryTableData_EXIT;
  2022. }
  2023. // Retrieve amount of parameters from the queue
  2024. if( !queue_getcount(pQParameters, &nParam) )
  2025. {
  2026. // error: can't get parameters count
  2027. errCode = ERROR_GPIB_INTERNAL;
  2028. goto L_GPIB_MemoryTableData_EXIT;
  2029. }
  2030. // Check parameters count
  2031. else if( 2 != nParam && 3 != nParam ) // this command must have 2 or 3 parameters
  2032. {
  2033. // error: wrong parameters count ( must be 2 or 3 )
  2034. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2035. goto L_GPIB_MemoryTableData_EXIT;
  2036. }
  2037. // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
  2038. {
  2039. char textBuffer[16];
  2040. // retrieve the first parameter: port combination
  2041. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2042. {
  2043. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2044. goto L_GPIB_MemoryTableData_EXIT;
  2045. }
  2046. // check the parameter type
  2047. else if( eParTypeChar != textBuffer[0] )
  2048. {
  2049. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2050. goto L_GPIB_MemoryTableData_EXIT;
  2051. }
  2052. // retrieve the parameter
  2053. pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
  2054. if( ePortComb_UNDEFINED == pcid )
  2055. {
  2056. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2057. goto L_GPIB_MemoryTableData_EXIT;
  2058. }
  2059. }
  2060. // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
  2061. {
  2062. char textBuffer[16];
  2063. // retrieve the first parameter: port state
  2064. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2065. {
  2066. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2067. goto L_GPIB_MemoryTableData_EXIT;
  2068. }
  2069. // check the parameter type
  2070. else if( eParTypeChar != textBuffer[0] )
  2071. {
  2072. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2073. goto L_GPIB_MemoryTableData_EXIT;
  2074. }
  2075. // retrieve the parameter
  2076. psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
  2077. if( ePortStateId_UNDEFINED == psid )
  2078. {
  2079. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2080. goto L_GPIB_MemoryTableData_EXIT;
  2081. }
  2082. }
  2083. // parameter #3 - memory sector (FACTORY/USER1/USER2/USER3)
  2084. if( 3 == nParam ) // if third parameter is not omitted
  2085. {
  2086. char textBuffer[16];
  2087. // retrieve the first parameter: memory sector
  2088. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2089. {
  2090. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2091. goto L_GPIB_MemoryTableData_EXIT;
  2092. }
  2093. // check the parameter type
  2094. else if( eParTypeChar != textBuffer[0] )
  2095. {
  2096. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2097. goto L_GPIB_MemoryTableData_EXIT;
  2098. }
  2099. // retrieve the parameter
  2100. msid = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
  2101. if( eCh_MAX == msid )
  2102. {
  2103. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2104. goto L_GPIB_MemoryTableData_EXIT;
  2105. }
  2106. }
  2107. else
  2108. {
  2109. msid = eChFactory;
  2110. }
  2111. // Validate given parameters: port state and port combination
  2112. if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
  2113. {
  2114. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2115. goto L_GPIB_MemoryTableData_EXIT;
  2116. }
  2117. // initialize the table context @.out just for order
  2118. tableContext.out.max = 0; // don't care
  2119. tableContext.out.min = 0; // don't care
  2120. tableContext.out.TableAddress = 0; // don't care
  2121. tableContext.out.nPoints = 0; // don't care
  2122. // initialize @.in to make the @.getPoints() call to load
  2123. // the table header.
  2124. // - set @.nCount to 0 to load the table header
  2125. tableContext.in.nCount = 0; // must be 0
  2126. tableContext.in.nStartPoint = 0; // don't care
  2127. tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
  2128. // load table header and validate it
  2129. // During this call the @tableContext.out will be initialized
  2130. if( 1 != ACMClass->methods.xCharacterization.getPoints(
  2131. msid, // memory sector
  2132. pcid, // port combination
  2133. psid, // port state
  2134. &tableContext )
  2135. )
  2136. {
  2137. errCode = ERROR_GPIB_DATA_NOT_FOUND;
  2138. // failed
  2139. switch( tableContext.svc.errCode )
  2140. {
  2141. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  2142. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  2143. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_DATA_NOT_FOUND; break;
  2144. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  2145. }
  2146. goto L_GPIB_MemoryTableData_EXIT;
  2147. }
  2148. // ok, now @tableContext is initialized
  2149. // Let's initialize the rest variables
  2150. tableContext.in.nStartPoint = 0; // starting point = 0
  2151. tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
  2152. tableContext.in.nCount = 0; // zero yet, see below
  2153. }
  2154. // 3
  2155. else
  2156. {
  2157. // load previous context
  2158. size_t bytes;
  2159. if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&msid , sizeof(msid), &bytes ) // load memory segment id
  2160. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
  2161. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
  2162. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
  2163. )
  2164. {
  2165. // OK
  2166. // Note:
  2167. // @tableContext.out.nPoints is remembered, amount of points
  2168. // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
  2169. }
  2170. else
  2171. {
  2172. errCode = ERROR_GPIB_INTERNAL;
  2173. goto L_GPIB_MemoryTableData_EXIT;
  2174. }
  2175. }
  2176. rc = 0;
  2177. // 4
  2178. {
  2179. size_t nPoints = tableContext.out.nPoints; // amount of points in the table
  2180. size_t nStart = tableContext.in.nStartPoint; // starting point
  2181. // do until all the points are processed
  2182. while( nStart < nPoints )
  2183. {
  2184. // specify the number of points to retrieve: @tableContext.in.nCount
  2185. // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
  2186. // already specified or remembered
  2187. size_t nStepPoints = (nPoints - nStart);
  2188. // check the points number for the limit
  2189. if( nStepPoints >= DBPOINTS_BUFFER_NUM )
  2190. {
  2191. tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
  2192. }
  2193. else
  2194. {
  2195. // not greater than it is required
  2196. tableContext.in.nCount = nStepPoints;
  2197. }
  2198. // retrieve the points from the memory
  2199. if( tableContext.in.nCount != ACMClass->methods.xCharacterization.getPoints(
  2200. msid, // memory sector
  2201. pcid, // port combination
  2202. psid, // port state
  2203. &tableContext )
  2204. )
  2205. {
  2206. // error
  2207. // Strange... The table is already validated. Maybe, it is I/O error issue.
  2208. udi->GPIBFunctionContext.LastFunction = NULL;
  2209. errCode = ERROR_GPIB_INTERNAL;
  2210. // failed
  2211. switch( tableContext.svc.errCode )
  2212. {
  2213. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  2214. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  2215. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_DATA_NOT_FOUND; break;
  2216. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  2217. }
  2218. goto L_GPIB_MemoryTableData_EXIT;
  2219. }
  2220. // Ok, the double-points are loaded...
  2221. // Let's convert it!
  2222. // @iPoint - just counts amount of converted points at this step.
  2223. for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
  2224. {
  2225. // the point format is:
  2226. // <Magnitude>,<SPACE><Phase>,<SPACE>
  2227. // where <Magnitude> and <Phase> is a number in scientific format
  2228. // with 10 fractional digits. Let's leave 2 digits for the exponent,
  2229. // and one number takes 16 characters, plus the separator and the space.
  2230. // So one point takes (16+2)*2 = 36 characters. To be in save we will
  2231. // suppose the one point takes 48 characters.
  2232. // e.g.
  2233. // 1.0000000000e+5, 1.0000000000e+0,
  2234. if( freeSpace >= 48 )
  2235. {
  2236. size_t bytes = 0;
  2237. // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
  2238. // Convert a magnitude
  2239. bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].magn, pBuffer, freeSpace, Format_Double2Str_Sci );
  2240. if( 0 == bytes )
  2241. {
  2242. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  2243. goto L_GPIB_MemoryTableData_EXIT;
  2244. }
  2245. pBuffer += bytes;
  2246. freeSpace -= bytes;
  2247. rc += bytes;
  2248. // print the delimeter
  2249. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  2250. pBuffer += bytes;
  2251. freeSpace -= bytes;
  2252. rc += bytes;
  2253. // Convert a phase
  2254. bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].phase, pBuffer, freeSpace, Format_Double2Str_Sci );
  2255. if( 0 == bytes )
  2256. {
  2257. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  2258. goto L_GPIB_MemoryTableData_EXIT;
  2259. }
  2260. pBuffer += bytes;
  2261. freeSpace -= bytes;
  2262. rc += bytes;
  2263. // print the delimeter
  2264. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  2265. pBuffer += bytes;
  2266. freeSpace -= bytes;
  2267. rc += bytes;
  2268. // move to the next point in the table
  2269. nStart++;
  2270. }
  2271. else
  2272. {
  2273. // not enough free space in the text buffer
  2274. (void)tableContext.out.nPoints;
  2275. tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
  2276. // --------------------------------------------------------------------------
  2277. // Save context
  2278. usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableData );
  2279. if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&msid , sizeof(msid) ) // Save memory segment id
  2280. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
  2281. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
  2282. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
  2283. )
  2284. {
  2285. udi->GPIBFunctionContext.LastFunction = NULL;
  2286. errCode = ERROR_GPIB_INTERNAL;
  2287. goto L_GPIB_MemoryTableData_EXIT;
  2288. }
  2289. udi->BulkRespondStatus.bIsLastTransfer = FALSE;
  2290. errCode = 0;
  2291. // --------------------------------------------------------------------------
  2292. goto L_GPIB_MemoryTableData_EXIT;
  2293. }
  2294. } // for
  2295. tableContext.in.nStartPoint = nStart; // modify the starting point
  2296. } // while( nStart < nPoints )
  2297. // Ok, all the points are converted here due to
  2298. // otherwise, the program jumps to L_GPIB_MemoryTableData_EXIT label
  2299. // after saving context.
  2300. if( rc > 2 )
  2301. {
  2302. // cut off the last space and comma
  2303. rc -= 2;
  2304. }
  2305. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  2306. }
  2307. // 5
  2308. L_GPIB_MemoryTableData_EXIT:
  2309. if( 0 != errCode )
  2310. {
  2311. const char * pDescription = NULL;
  2312. if( eCh_MAX != msid )
  2313. {
  2314. pDescription = aChrzDesc[ (size_t)msid ];
  2315. }
  2316. if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
  2317. && ePortComb_MAX != pcid )
  2318. {
  2319. pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
  2320. }
  2321. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  2322. // 27/08/18
  2323. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2324. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  2325. rc = 0;
  2326. }
  2327. return rc;
  2328. }
  2329. // ==============================================================================================
  2330. // ==============================================================================================
  2331. // GPIB_SwitchState(...)
  2332. // Назначенная комманда - [SYSTem:]SWITch:STATe, [SYSTem:]SWITch:STATe?
  2333. // Параметры комманды - состояние (SALL, OALL, THBD, ...) или отстутствует (запрос)
  2334. // Возвращаемое значение - строка имени состояния порта и количество байт
  2335. unsigned int GPIB_SwitchState( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2336. {
  2337. union
  2338. {
  2339. char stateRaw[ 16 ];
  2340. struct
  2341. {
  2342. BYTE stateNameParamType;
  2343. char stateName[ 15 ];
  2344. };
  2345. } = {
  2346. .stateRaw = {0}
  2347. };
  2348. unsigned int errCode = 0;
  2349. size_t stateNameLength = 0;
  2350. size_t count = 0;
  2351. BYTE * pBuffer = NULL;
  2352. int nFreeSpace = 0;
  2353. size_t bytes = 0;
  2354. eACMKeyState_t keyState;
  2355. // -------------------------------------------------
  2356. pBuffer = (BYTE*)udi->usbtmcGpib.pData;
  2357. nFreeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2358. // -------------------------------------------------
  2359. if(!queue_getcount(pQParameters, &count))
  2360. {
  2361. errCode = ERROR_GPIB_INTERNAL;
  2362. goto L_GPIB_SwitchState_EXIT;
  2363. }
  2364. if( TernaryOperator(request,0,1) != count )
  2365. {
  2366. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2367. goto L_GPIB_SwitchState_EXIT;
  2368. }
  2369. if( !request ) // == (count==1)
  2370. {
  2371. if( !queue_get( pQParameters, stateRaw, sizeof(stateRaw), &stateNameLength ) )
  2372. {
  2373. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2374. goto L_GPIB_SwitchState_EXIT;
  2375. }
  2376. if( stateNameLength < 2 || eParTypeChar != stateNameParamType )
  2377. {
  2378. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2379. goto L_GPIB_SwitchState_EXIT;
  2380. }
  2381. stateNameLength--; // decrease parameter length by 1 byte - 1 byte for parameter type
  2382. keyState = ACMClass->methods.getKeyStateByName( stateName, stateNameLength );
  2383. if( eKeyState_Undefined == keyState )
  2384. {
  2385. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2386. goto L_GPIB_SwitchState_EXIT;
  2387. }
  2388. // -------------------------------------------------
  2389. if( ! ACMClass->methods.checkStateAvailable( keyState ) )
  2390. {
  2391. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2392. goto L_GPIB_SwitchState_EXIT;
  2393. }
  2394. /*
  2395. bytes = ACMClass->methods.getKeyStateName( keyState, pBuffer, nFreeSpace );
  2396. if( (0 == bytes) && ( bytes > nFreeSpace ) )
  2397. {
  2398. err = ERROR_GPIB_INTERNAL;
  2399. goto L_GPIB_SwitchState_EXIT;
  2400. }
  2401. */
  2402. if( ! ACMClass->methods.setKeyStateCommon( keyState ) )
  2403. {
  2404. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2405. goto L_GPIB_SwitchState_EXIT;
  2406. }
  2407. }
  2408. else
  2409. {
  2410. keyState = ACMClass->methods.getKeyStateCommon();
  2411. bytes = ACMClass->methods.getKeyStateName( keyState, pBuffer, nFreeSpace );
  2412. if( (0 == bytes) && ( bytes > nFreeSpace ) )
  2413. {
  2414. errCode = ERROR_GPIB_INTERNAL;
  2415. goto L_GPIB_SwitchState_EXIT;
  2416. }
  2417. }
  2418. // -------------------------------------------------
  2419. L_GPIB_SwitchState_EXIT:
  2420. if( 0 != errCode )
  2421. {
  2422. // 27/08/18
  2423. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2424. GPIB_RaiseStandartError( udi, errCode, NULL, errClass_Autodetect );
  2425. bytes = 0;
  2426. }
  2427. return bytes;
  2428. }
  2429. void GPIB_DevDepInit( USB_DEVICE_INFO * udi )
  2430. {
  2431. //InitKeyState();
  2432. //SETKEY_LOADB(udi->CommandStatus.key_stat);
  2433. //SETKEY_LOADA(udi->CommandStatus.key_stat);
  2434. //usbapp_SET_KEY_STAT(&udi->CommandStatus);
  2435. /* ACMClass is uninitialized yet! */
  2436. }
  2437. // GPIB_MemTableTherCorrFreqStart()
  2438. // Prints the start frequency of the thermocompensation data array
  2439. size_t GPIB_MemTableTherCorrFreqStart( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2440. {
  2441. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  2442. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2443. size_t rc = 0;
  2444. double startFreq = 0.0f;
  2445. unsigned int errCode = 0;
  2446. size_t count = 0;
  2447. if( !request )
  2448. {
  2449. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2450. }
  2451. else
  2452. {
  2453. if( !queue_getcount( pQParameters, &count) )
  2454. {
  2455. errCode = ERROR_GPIB_INTERNAL;
  2456. }
  2457. else
  2458. {
  2459. if( 0 != count )
  2460. {
  2461. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2462. }
  2463. else
  2464. {
  2465. if( !ACMClass->methods.xThermo.getStartFreq( &startFreq ) )
  2466. {
  2467. errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
  2468. }
  2469. else
  2470. {
  2471. rc = GPIB_Double2Str( startFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
  2472. }
  2473. }
  2474. }
  2475. }
  2476. if( 0 != errCode )
  2477. {
  2478. const char * pDescription = pcThermoDesc;
  2479. // 27/08/18
  2480. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2481. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  2482. rc = 0;
  2483. }
  2484. return rc;
  2485. }
  2486. // GPIB_MemTableTherCorrFreqStop()
  2487. // Prints the stop frequency of the thermocompensation data array
  2488. size_t GPIB_MemTableTherCorrFreqStop( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2489. {
  2490. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  2491. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2492. size_t rc = 0;
  2493. double stopFreq = 0.0f;
  2494. unsigned int errCode = 0;
  2495. size_t count = 0;
  2496. if( !request )
  2497. {
  2498. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2499. }
  2500. else
  2501. {
  2502. if( !queue_getcount( pQParameters, &count) )
  2503. {
  2504. errCode = ERROR_GPIB_INTERNAL;
  2505. }
  2506. else
  2507. {
  2508. if( 0 != count )
  2509. {
  2510. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2511. }
  2512. else
  2513. {
  2514. if( !ACMClass->methods.xThermo.getStopFreq( &stopFreq ) )
  2515. {
  2516. errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
  2517. }
  2518. else
  2519. {
  2520. rc = GPIB_Double2Str( stopFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
  2521. }
  2522. }
  2523. }
  2524. }
  2525. if( 0 != errCode )
  2526. {
  2527. const char * pDescription = pcThermoDesc;
  2528. // 27/08/18
  2529. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2530. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  2531. rc = 0;
  2532. }
  2533. return rc;
  2534. }
  2535. size_t GPIB_MemTableTherCorrPoints( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2536. {
  2537. uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
  2538. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2539. size_t rc = 0;
  2540. size_t nPoints = 0;
  2541. unsigned int errCode = 0;
  2542. size_t count = 0;
  2543. if( !request )
  2544. {
  2545. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2546. }
  2547. else
  2548. {
  2549. if( !queue_getcount( pQParameters, &count) )
  2550. {
  2551. errCode = ERROR_GPIB_INTERNAL;
  2552. }
  2553. else
  2554. {
  2555. if( 0 != count )
  2556. {
  2557. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2558. }
  2559. else
  2560. {
  2561. nPoints = ACMClass->methods.xThermo.getPointsCount();
  2562. if( 0 == nPoints )
  2563. {
  2564. errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
  2565. }
  2566. else
  2567. {
  2568. rc = snprintf( (char*)pBuffer, freeSpace, "%d", nPoints );
  2569. }
  2570. }
  2571. }
  2572. }
  2573. if( 0 != errCode )
  2574. {
  2575. const char * pDescription = pcThermoDesc;
  2576. // 27/08/18
  2577. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2578. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  2579. rc = 0;
  2580. }
  2581. return rc;
  2582. }
  2583. // GPIB_MemTableTherCorrMagniture()
  2584. // MEM:TABLE:THER:CORR:MAGN? <PORT_COMBINATION>, <PORT_STATE>
  2585. // Prints the contents of the characterization table depending on the following parameters:
  2586. // - port combination (A, B, or CD, or CHECK, etc)
  2587. // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
  2588. size_t GPIB_MemTableTherCorrMagniture( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2589. {
  2590. // 1
  2591. char * pBuffer = (char*)udi->usbtmcGpib.pData;
  2592. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2593. size_t rc = 0; // full amount of bytes returned
  2594. unsigned int errCode = 0; // error identifier
  2595. sACMGetPoints_t tableContext; // table context to store the data between calls
  2596. ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
  2597. ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
  2598. // 2
  2599. // Check if the function context is saved and must be continued
  2600. if( !udi->GPIBFunctionContext.bEnable )
  2601. {
  2602. // no context found
  2603. size_t nParam = 0; // amount of parameters
  2604. if( !request )
  2605. {
  2606. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2607. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2608. }
  2609. // Retrieve amount of parameters from the queue
  2610. if( !queue_getcount(pQParameters, &nParam) )
  2611. {
  2612. // error: can't get parameters count
  2613. errCode = ERROR_GPIB_INTERNAL;
  2614. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2615. }
  2616. // Check parameters count
  2617. else if( 2 != nParam ) // this command must have 2 parameters
  2618. {
  2619. // error: wrong parameters count ( must be 2 )
  2620. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2621. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2622. }
  2623. // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
  2624. {
  2625. char textBuffer[16];
  2626. // retrieve the first parameter: port combination
  2627. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2628. {
  2629. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2630. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2631. }
  2632. // check the parameter type
  2633. else if( eParTypeChar != textBuffer[0] )
  2634. {
  2635. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2636. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2637. }
  2638. // retrieve the parameter
  2639. pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
  2640. if( ePortComb_UNDEFINED == pcid )
  2641. {
  2642. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2643. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2644. }
  2645. }
  2646. // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
  2647. {
  2648. char textBuffer[16];
  2649. // retrieve the first parameter: port state
  2650. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2651. {
  2652. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2653. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2654. }
  2655. // check the parameter type
  2656. else if( eParTypeChar != textBuffer[0] )
  2657. {
  2658. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2659. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2660. }
  2661. // retrieve the parameter
  2662. psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
  2663. if( ePortStateId_UNDEFINED == psid )
  2664. {
  2665. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2666. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2667. }
  2668. }
  2669. // Validate given parameters: port state and port combination
  2670. if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
  2671. {
  2672. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2673. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2674. }
  2675. // initialize the table context @.out just for order
  2676. tableContext.out.max = 0; // don't care
  2677. tableContext.out.min = 0; // don't care
  2678. tableContext.out.TableAddress = 0; // don't care
  2679. tableContext.out.nPoints = 0; // don't care
  2680. // initialize @.in to make the @.getPoints() call to load
  2681. // the table header.
  2682. // - set @.nCount to 0 to load the table header
  2683. tableContext.in.nCount = 0; // must be 0
  2684. tableContext.in.nStartPoint = 0; // don't care
  2685. tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
  2686. // load table header and validate it
  2687. // During this call the @tableContext.out will be initialized
  2688. if( 1 != ACMClass->methods.xThermo.getPointsMagn( pcid, // port combination
  2689. psid, // port state
  2690. &tableContext )
  2691. )
  2692. {
  2693. // failed
  2694. errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
  2695. switch( tableContext.svc.errCode )
  2696. {
  2697. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  2698. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  2699. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
  2700. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  2701. }
  2702. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2703. }
  2704. // ok, now @tableContext is initialized
  2705. // Let's initialize the rest variables
  2706. tableContext.in.nStartPoint = 0; // starting point = 0
  2707. tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
  2708. tableContext.in.nCount = 0; // zero yet, see below
  2709. }
  2710. // 3
  2711. else
  2712. {
  2713. // load previous context
  2714. size_t bytes;
  2715. if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
  2716. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
  2717. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
  2718. )
  2719. {
  2720. // OK
  2721. // Note:
  2722. // @tableContext.out.nPoints is remembered, amount of points
  2723. // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
  2724. }
  2725. else
  2726. {
  2727. errCode = ERROR_GPIB_INTERNAL;
  2728. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2729. }
  2730. }
  2731. rc = 0;
  2732. // 4
  2733. {
  2734. size_t nPoints = tableContext.out.nPoints; // amount of points in the table
  2735. size_t nStart = tableContext.in.nStartPoint; // starting point
  2736. // do until all the points are processed
  2737. while( nStart < nPoints )
  2738. {
  2739. // specify the number of points to retrieve: @tableContext.in.nCount
  2740. // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
  2741. // already specified or remembered
  2742. size_t nStepPoints = (nPoints - nStart);
  2743. // check the points number for the limit
  2744. if( nStepPoints >= DBPOINTS_BUFFER_NUM )
  2745. {
  2746. tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
  2747. }
  2748. else
  2749. {
  2750. // not greater than it is required
  2751. tableContext.in.nCount = nStepPoints;
  2752. }
  2753. // retrieve the points from the memory
  2754. if( tableContext.in.nCount != ACMClass->methods.xThermo.getPointsMagn(
  2755. pcid, // port combination
  2756. psid, // port state
  2757. &tableContext )
  2758. )
  2759. {
  2760. // error
  2761. // Strange... The table is already validated. Maybe, it is I/O error issue.
  2762. udi->GPIBFunctionContext.LastFunction = NULL;
  2763. errCode = ERROR_GPIB_INTERNAL;
  2764. switch( tableContext.svc.errCode )
  2765. {
  2766. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  2767. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  2768. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
  2769. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  2770. }
  2771. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2772. }
  2773. // Ok, the double-points are loaded...
  2774. // Let's convert it!
  2775. // @iPoint - just counts amount of converted points at this step.
  2776. for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
  2777. {
  2778. // the point format is:
  2779. // <Number>,<SPACE>
  2780. // where <Number> is a number in scientific format
  2781. // with 10 fractional digits. Let's leave 2 digits for the exponent,
  2782. // and one number takes 16 characters, plus the separator and the space.
  2783. // So one point takes (16+2) = 18 characters. To be in save we will
  2784. // suppose the one point takes 24 characters.
  2785. // e.g.
  2786. // 1.0000000000e+5,
  2787. if( freeSpace >= 24 )
  2788. {
  2789. size_t bytes = 0;
  2790. // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
  2791. // Convert a magnitude
  2792. bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].magn, pBuffer, freeSpace, Format_Double2Str_Sci );
  2793. if( 0 == bytes )
  2794. {
  2795. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  2796. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2797. }
  2798. pBuffer += bytes;
  2799. freeSpace -= bytes;
  2800. rc += bytes;
  2801. // print the delimeter
  2802. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  2803. pBuffer += bytes;
  2804. freeSpace -= bytes;
  2805. rc += bytes;
  2806. // move to the next point in the table
  2807. nStart++;
  2808. }
  2809. else
  2810. {
  2811. // not enough free space in the text buffer
  2812. (void)tableContext.out.nPoints;
  2813. tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
  2814. // --------------------------------------------------------------------------
  2815. // Save context
  2816. usbtmc_create_function_context( udi, (void*)GPIB_MemTableTherCorrMagniture );
  2817. if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
  2818. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
  2819. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
  2820. )
  2821. {
  2822. udi->GPIBFunctionContext.LastFunction = NULL;
  2823. errCode = ERROR_GPIB_INTERNAL;
  2824. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2825. }
  2826. udi->BulkRespondStatus.bIsLastTransfer = FALSE;
  2827. errCode = 0;
  2828. // --------------------------------------------------------------------------
  2829. goto L_GPIB_MemTableTherCorrMagniture_EXIT;
  2830. }
  2831. } // for
  2832. tableContext.in.nStartPoint = nStart; // modify the starting point
  2833. } // while( nStart < nPoints )
  2834. // Ok, all the points are converted here due to
  2835. // otherwise, the program jumps to L_GPIB_MemTableTherCorrMagniture_EXIT label
  2836. // after saving context.
  2837. if( rc > 2 )
  2838. {
  2839. // cut off the last space and comma
  2840. rc -= 2;
  2841. }
  2842. }
  2843. // 5
  2844. L_GPIB_MemTableTherCorrMagniture_EXIT:
  2845. if( 0 != errCode )
  2846. {
  2847. const char * pDescription = pcThermoDesc;
  2848. if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
  2849. && ePortComb_MAX != pcid )
  2850. {
  2851. pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
  2852. }
  2853. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  2854. // 27/08/18
  2855. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  2856. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  2857. rc = 0;
  2858. }
  2859. return rc;
  2860. }
  2861. // GPIB_MemTableTherCorrPhase()
  2862. // MEM:TABLE:THER:CORR:PHAS? <PORT_COMBINATION>, <PORT_STATE>
  2863. // Prints the contents of the characterization table depending on the following parameters:
  2864. // - port combination (A, B, or CD, or CHECK, etc)
  2865. // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
  2866. size_t GPIB_MemTableTherCorrPhase( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
  2867. {
  2868. // 1
  2869. char * pBuffer = (char*)udi->usbtmcGpib.pData;
  2870. size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
  2871. size_t rc = 0; // full amount of bytes returned
  2872. unsigned int errCode = 0; // error identifier
  2873. sACMGetPoints_t tableContext; // table context to store the data between calls
  2874. ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
  2875. ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
  2876. // 2
  2877. // Check if the function context is saved and must be continued
  2878. if( !udi->GPIBFunctionContext.bEnable )
  2879. {
  2880. // no context found
  2881. size_t nParam = 0; // amount of parameters
  2882. if( !request )
  2883. {
  2884. errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
  2885. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2886. }
  2887. // Retrieve amount of parameters from the queue
  2888. if( !queue_getcount(pQParameters, &nParam) )
  2889. {
  2890. // error: can't get parameters count
  2891. errCode = ERROR_GPIB_INTERNAL;
  2892. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2893. }
  2894. // Check parameters count
  2895. else if( 2 != nParam ) // this command must have 2 parameters
  2896. {
  2897. // error: wrong parameters count ( must be 2 )
  2898. errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
  2899. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2900. }
  2901. // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
  2902. {
  2903. char textBuffer[16];
  2904. // retrieve the first parameter: port combination
  2905. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2906. {
  2907. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2908. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2909. }
  2910. // check the parameter type
  2911. else if( eParTypeChar != textBuffer[0] )
  2912. {
  2913. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2914. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2915. }
  2916. // retrieve the parameter
  2917. pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
  2918. if( ePortComb_UNDEFINED == pcid )
  2919. {
  2920. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2921. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2922. }
  2923. }
  2924. // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
  2925. {
  2926. char textBuffer[16];
  2927. // retrieve the first parameter: port state
  2928. if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
  2929. {
  2930. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2931. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2932. }
  2933. // check the parameter type
  2934. else if( eParTypeChar != textBuffer[0] )
  2935. {
  2936. errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
  2937. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2938. }
  2939. // retrieve the parameter
  2940. psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
  2941. if( ePortStateId_UNDEFINED == psid )
  2942. {
  2943. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2944. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2945. }
  2946. }
  2947. // Validate given parameters: port state and port combination
  2948. if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
  2949. {
  2950. errCode = ERROR_GPIB_INVALID_PARAMETER;
  2951. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2952. }
  2953. // initialize the table context @.out just for order
  2954. tableContext.out.max = 0; // don't care
  2955. tableContext.out.min = 0; // don't care
  2956. tableContext.out.TableAddress = 0; // don't care
  2957. tableContext.out.nPoints = 0; // don't care
  2958. // initialize @.in to make the @.getPoints() call to load
  2959. // the table header.
  2960. // - set @.nCount to 0 to load the table header
  2961. tableContext.in.nCount = 0; // must be 0
  2962. tableContext.in.nStartPoint = 0; // don't care
  2963. tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
  2964. // load table header and validate it
  2965. // During this call the @tableContext.out will be initialized
  2966. if( 1 != ACMClass->methods.xThermo.getPointsPhase( pcid, // port combination
  2967. psid, // port state
  2968. &tableContext )
  2969. )
  2970. {
  2971. // failed
  2972. errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
  2973. switch( tableContext.svc.errCode )
  2974. {
  2975. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  2976. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  2977. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
  2978. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  2979. }
  2980. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  2981. }
  2982. // ok, now @tableContext is initialized
  2983. // Let's initialize the rest variables
  2984. tableContext.in.nStartPoint = 0; // starting point = 0
  2985. tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
  2986. tableContext.in.nCount = 0; // zero yet, see below
  2987. }
  2988. // 3
  2989. else
  2990. {
  2991. // load previous context
  2992. size_t bytes;
  2993. if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
  2994. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
  2995. && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
  2996. )
  2997. {
  2998. // OK
  2999. // Note:
  3000. // @tableContext.out.nPoints is remembered, amount of points
  3001. // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
  3002. }
  3003. else
  3004. {
  3005. errCode = ERROR_GPIB_INTERNAL;
  3006. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  3007. }
  3008. }
  3009. rc = 0;
  3010. // 4
  3011. {
  3012. size_t nPoints = tableContext.out.nPoints; // amount of points in the table
  3013. size_t nStart = tableContext.in.nStartPoint; // starting point
  3014. // do until all the points are processed
  3015. while( nStart < nPoints )
  3016. {
  3017. // specify the number of points to retrieve: @tableContext.in.nCount
  3018. // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
  3019. // already specified or remembered
  3020. size_t nStepPoints = (nPoints - nStart);
  3021. // check the points number for the limit
  3022. if( nStepPoints >= DBPOINTS_BUFFER_NUM )
  3023. {
  3024. tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
  3025. }
  3026. else
  3027. {
  3028. // not greater than it is required
  3029. tableContext.in.nCount = nStepPoints;
  3030. }
  3031. // retrieve the points from the memory
  3032. if( tableContext.in.nCount != ACMClass->methods.xThermo.getPointsPhase(
  3033. pcid, // port combination
  3034. psid, // port state
  3035. &tableContext )
  3036. )
  3037. {
  3038. // error
  3039. // Strange... The table is already validated. Maybe, it is I/O error issue.
  3040. udi->GPIBFunctionContext.LastFunction = NULL;
  3041. errCode = ERROR_GPIB_INTERNAL;
  3042. switch( tableContext.svc.errCode )
  3043. {
  3044. case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
  3045. case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
  3046. case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
  3047. case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
  3048. }
  3049. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  3050. }
  3051. // Ok, the double-points are loaded...
  3052. // Let's convert it!
  3053. // @iPoint - just counts amount of converted points at this step.
  3054. for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
  3055. {
  3056. // the point format is:
  3057. // <Number>,<SPACE>
  3058. // where <Number> is a number in scientific format
  3059. // with 10 fractional digits. Let's leave 2 digits for the exponent,
  3060. // and one number takes 16 characters, plus the separator and the space.
  3061. // So one point takes (16+2) = 18 characters. To be in save we will
  3062. // suppose the one point takes 24 characters.
  3063. // e.g.
  3064. // 1.0000000000e+5,
  3065. if( freeSpace >= 24 )
  3066. {
  3067. size_t bytes = 0;
  3068. // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
  3069. // Convert a phase
  3070. bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].phase, pBuffer, freeSpace, Format_Double2Str_Sci );
  3071. if( 0 == bytes )
  3072. {
  3073. errCode = ERROR_GPIB_BUFFER_OVERFLOW;
  3074. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  3075. }
  3076. pBuffer += bytes;
  3077. freeSpace -= bytes;
  3078. rc += bytes;
  3079. // print the delimeter
  3080. bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
  3081. pBuffer += bytes;
  3082. freeSpace -= bytes;
  3083. rc += bytes;
  3084. // move to the next point in the table
  3085. nStart++;
  3086. }
  3087. else
  3088. {
  3089. // not enough free space in the text buffer
  3090. (void)tableContext.out.nPoints;
  3091. tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
  3092. // --------------------------------------------------------------------------
  3093. // Save context
  3094. usbtmc_create_function_context( udi, (void*)GPIB_MemTableTherCorrPhase );
  3095. if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
  3096. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
  3097. || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
  3098. )
  3099. {
  3100. udi->GPIBFunctionContext.LastFunction = NULL;
  3101. errCode = ERROR_GPIB_INTERNAL;
  3102. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  3103. }
  3104. udi->BulkRespondStatus.bIsLastTransfer = FALSE;
  3105. errCode = 0;
  3106. // --------------------------------------------------------------------------
  3107. goto L_GPIB_MemTableTherCorrPhase_EXIT;
  3108. }
  3109. } // for
  3110. tableContext.in.nStartPoint = nStart; // modify the starting point
  3111. } // while( nStart < nPoints )
  3112. // Ok, all the points are converted here due to
  3113. // otherwise, the program jumps to L_GPIB_MemTableTherCorrMagniture_EXIT label
  3114. // after saving context.
  3115. if( rc > 2 )
  3116. {
  3117. // cut off the last space and comma
  3118. rc -= 2;
  3119. }
  3120. }
  3121. // 5
  3122. L_GPIB_MemTableTherCorrPhase_EXIT:
  3123. if( 0 != errCode )
  3124. {
  3125. const char * pDescription = pcThermoDesc;
  3126. if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
  3127. && ePortComb_MAX != pcid )
  3128. {
  3129. pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
  3130. }
  3131. udi->BulkRespondStatus.bIsLastTransfer = TRUE;
  3132. // 27/08/18
  3133. // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
  3134. GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
  3135. rc = 0;
  3136. }
  3137. return rc;
  3138. }
  3139. #endif