| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620 |
- #include "lpc176x.h"
- #include "usb_hardware.h"
- #include <stdlib.h>
- #include <stdio.h>
- #include "options.h"
- #ifdef USBTMC // #endif в конце файла
- #include "utils.h"
- #include "gpib_parser.h"
- #include "usb_enumeration.h"
- #include "usbtmc.h"
- #include "utilits.h"
- #include "usb_options.h"
- //#include "spi.h"
- #include "i2_c.h"
- #include "common\buffer.h"
- #include <math.h>
- #include "usb_application.h"
- #include "usb_proto.h"
- #include "acm_base.h"
- #include "acm_base_model.h"
- #define DBPOINTS_BUFFER_NUM 128
- // @dbPointsBuffer - the temporary buffer for the points in the intermediate, double format
- static sACMChrzPoint_t dbPointsBuffer[ DBPOINTS_BUFFER_NUM ];
- // ==============================================================================================
- // GPIB функции идентичны по строению. Вначале они получают указатель на выходной буфер данных,
- // куда собираются печатать ответ (pBulkData_DeviceOut) и размер этого буфера (MAX).
- // Далее, из очереди pQParameters в зависимости от функции извлекаются параметры в том виде, в каком
- // они были переданы от компьютера, за исключением того, что первым байтом каждого параметра является
- // его тип (eParTypeChar, eParTypeNR1, ...) - тип параметра может быть строковый, числовой, символьный и т.п.
- // К тому же, в зависимости от функции, проверяется количество переданных параметров, если оно не сов-
- // падает, функция генерирует ошибку и завершает работу. Параметры извлекаются по очереди, если не удалось
- // извлечь хотя бы один, функция генерирует ошибку и завершает работу. Далее, параметры обрабатываются
- // в зависимости от их типа и предполагаемого назначения (задается функцией), получаются конкретные
- // значения, например тип порта (ePORT_A, ePORT_B из "A" и "B"). Если значение параметра не корректно,
- // тоесть невозможно преобразовать порт C например, параметр объявляется ошибочным и функция ведет себя
- // аналогично, как и в случае с ошибкой получения параметра - то есть завершает работу, генерируя ошибку
- // Также она себя ведет, если значение параметра понято, обработано, но не применимо в данной ситуации,
- // например, невозможно установить состояние THRU для одного порта A.
- //
- // Если все эти условия не выполнились, функция приступает к генерации ответа, если она запросная
- // Если нет, выполняет какие-то дейтсвия. Если функция запросная, а вызвана как комманда, функция генерирует ошибку.
- // И наоборот, коммандные функции не могут вызываться как запрос. (Конечно, если функция Командно-запросная, ничего страшного)
- //
- // Функция GPIB ВСЕГДА возвращает количество записанных в буфер символов.
- //
- // Если функции недостаточно места в буфере, как например в случае с MEM:TABLE:DATA, она поступает так:
- // она сохраняет контекст выполнения (все необходимые ей данные, для того чтобы можно было начать выполнениеъ
- // с места остановки), регистриует себя в качестве обработчика события опустошения буфера. Затем функция
- // сбросит флаг EOM и завершит работу. Обработчик канала USB будет знать, что это сообщение не последнее, EOM сброшен.
- // Как только место в буфере освободится, обработчик канала USB (см в endpoints.c) вызовет функцию еще раз.
- // На этот раз, она будет знать, что вызвана по событю опустошения буфера и загрузит контекст выполнения,
- // подготовит часть данных, которая уместится в освободившееся место, и вновь, при необходимости, повторит
- // такую операцию с сохранением-загрузкой контекста. Как только функция обнаружит, что все данные переданы,
- // она не станет сбрасывать EOM, не станет сохранять контекст а просто завершится.
- //
- // Если при работе функции возникает ошибка, она передается в функцию RaiseStandartError, та в свою
- // очередь, зная код ошибки, запишет необходимые данные в очередь ошибок, включая необходимое описание
- // ошибки (если необходимо). При вызове SYST:ERR? эта ошибка приобретает сформатированный вид и выдается наружу.
- //
- // Некоторые команды, например MEM:TABLE:FREQ:STAR и MEM:TABLE:FREQ:STOP абсолютно идентичны по топологии
- // но различаются лишь в самом последнем звене - смещению данных в стуртуре заголовка, которые нужно
- // выдать в ответе. Чтобы не делать две одинаковые функции, отличающиеся только одним словом, сделаны т.н.
- // специальные функции. При инициализации GPIB дерева обычные команды регистрируют на себя по одной функции.
- // Специальные команды делят между собой одну единственную обслуживающую функцию. Эта функция идентифицирует
- // каждую команду и запрос по специальному полю FunctionID, которое помещается в очередь параметров функции pQParameters
- // перед вызовом и перед занесением в очередб параметров функции. Это поле задается для каждой команды
- // уникальным 32 разрядным числом при иницализации дерева команд GPIB. Функция обязательно должна знать, что
- // это поле нужно прочесть и использоватть. Для этого, перед получением параметров функции, она должна извлечь
- // FunctionID из очереди как обычный параметр. В зависимости от значения параметра FunctionID она должна
- // предпринимать различные действия: в одном случае выдавать Fmin, а в другом случае Fmax например.
- // Например, для :MEM:TABLE:FREQ:STAR;STOP;:MEM:TABLE:CONN;ADAP;ANAL;TIME;DATA ... существует всего одна
- // фунция MemTableFields(), зато она разбирает 11 различных FunctionID.
- // ==============================================================================================
- // ==============================================================================================
- // GPIB_Identification(...)
- // Назначенная комманда - *IDN?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - строка IDN
- // ---------------------------------------------------------------------------------------------------------
- // IDN string format: "<manufactor>,<device_name>,<device_serial>,0"
- // <manufactor> - Planar (http://planar.chel.ru) or "Copper Mountain Technologies"
- // <device_name> - Auto Calibration Module
- // <device_serial> - 0000-0000-0000
- unsigned int GPIB_Identification ( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *IDN?
- {
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- size_t count;
- unsigned int err = 0;
- int i = 0+strlen(ACMClass->properties.manufacturerId);
- i+= 1+strlen(ACMClass->properties.modelName);
- i+= 1+strlen(ACMClass->properties.serialNumber);
- i+= 1+strlen(ACMClass->properties.firmwareId);
- if(!queue_getcount( pQParameters, &count ))
- err = ERROR_GPIB_INTERNAL;
- else if( count != 0)
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- else if( !request )
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- else
- {
- if( MAX >= i )
- {
- return snprintf( pBulkData_DeviceOut, MAX, "%s,%s,%s,%s",
- ACMClass->properties.manufacturerId,
- ACMClass->properties.modelName,
- ACMClass->properties.serialNumber,
- ACMClass->properties.firmwareId );
- }
- else
- err = ERROR_GPIB_BUFFER_OVERFLOW;
- }
- // -------------------------------------------------------
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return 0;
- }
- // ====================================================================================================
- // GPIB_SystemVersion(...) - сервисная комманда, недокументирована
- // Назначенная комманда - SYSTem:VERSion?
- // Параметры комманды - любые
- // Возвращаемое значение - сообщение о номере версии парсера SCPI
- unsigned int GPIB_SystemVersion( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк system:info, system:info?
- {
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- //--------------------------------------------------------
- if( MAX >= 16)
- {
- s_memcpy( pBulkData_DeviceOut, "SCPI parser v1.3", 16 ); // ----- Copy respond data
- return (request==TRUE)?16:0; // -- respond length
- } else return 0;
- }
- // ==============================================================================================
- // GPIB_Clear(...)
- // Назначенная комманда - *CLS, очищает очередь ошибок и регисты STB и SRE
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - отсутствует
- unsigned int GPIB_Clear( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *CLS
- {
- QUEUE * pQueue = &udi->usbtmcGpib.StateMachine.qErrorQueue;
-
- size_t count = 0;
- unsigned int err = 0;
- //--------------------------------------------------------
- if( !queue_getcount( pQParameters, &count ) )
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( request )
- {
- err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
- }
- else
- {
- // Clear Event Status Register
- // Clear Status Register
- // Clear Error Queue
- udi->usbtmcGpib.StateMachine.STB = 0x00;
- udi->usbtmcGpib.StateMachine.ESR = 0x00;
-
- // - Error/Event Queue
- queue_clear( pQueue ); // Clear error queue
- GPIB_CLR_MAV(); // Clear Status Bit: message available
- GPIB_CLR_EAV(); // Clear Status Bit: event available
- }
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return 0; // -- respond length
- }
- // ==============================================================================================
- // GPIB_Reset(...)
- // Назначенная комманда - *RST, сбрасывает состояние портов на LOAD/LOAD
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - отсутствует
- unsigned int GPIB_Reset( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request ) // Обработчк *RST
- {
- QUEUE * pQueue = &udi->usbtmcGpib.StateMachine.qErrorQueue;
- size_t count = 0; unsigned int err = 0;
- //--------------------------------------------------------
- if( !queue_getcount( pQParameters, &count ) )
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( request )
- {
- err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
- }
- else
- {
- udi->EPBulkStatus.InPipe.dwLength = 0; // Clear bytes counters
- udi->EPBulkStatus.OutPipe.dwLength = 0; // - send counter
- udi->EPBulkStatus.shortpacket=FALSE; // - recv counter
- udi->EPBulkStatus.shortpacketsending=FALSE; // And clear also shortpacket signal flags
- //---------------
- udi->BulkRespondStatus.INTransferInProgress=FALSE; // Clear signal variables
- udi->BulkRespondStatus.nBytesSent=0; //
- udi->BulkRespondStatus.INTransferTerminating=FALSE; //
- //---------------
- //udi->usbtmcStatus.USBTMC_status = STATUS_SUCCESS; // usbtmcStatus do'nt depends from any bulk commands
- //udi->usbtmcStatus.USBTMC_InitiateRecieved = FALSE; //
- //---------------
- queue_clear( pQueue ); // Clear error queue
- GPIB_CLR_EAV();
- GPIB_CLR_MAV(); // No messages available
- //---------------
- udi->BulkMessageStatus.bBulkHeaderRecieved=FALSE; // Clears Header flag
- udi->BulkMessageStatus.nBytesRecieved=0; // Clears bytes counter
- udi->BulkMessageStatus.OUTTransferInProgress=FALSE; // Clears signal variable
- //---------------
- usb_lpc_cmd(CMD_EP_SELECT | USB_EP_PHY_ADDRESS_BULK_OUT ); // Clear EPOUT buffers
- usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
- usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
- //---------------
- usb_lpc_cmd(CMD_EP_SELECT | USB_EP_PHY_ADDRESS_BULK_IN ); // Clear EPIN buffers
- usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
- usb_lpc_cmd(CMD_EP_CLEAR_BUFFER);
- //---------------
- GPIB_DevDepInit( udi );
- //--------------- --- переход в состояние, когда устройство ждет комманды
- }
- }
- }
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return 0; // -- no bytes in respond
- }
- // ==============================================================================================
- // GPIB_SystemError(...)
- // Назначенная комманда - SYSTem:ERRor[:NEXT]?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - строка последней ошибки в очереди ошибок
- unsigned int GPIB_SystemError( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- //char * str = pQParameters->str;
- size_t count;
- unsigned int err = 0;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- //--------------------------------------------------------
- // request - если пришел запрос Enable? то request - 0x01
- // Request and Command support
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- return usbtmc_GetErrorText( udi, pBulkData_DeviceOut, MAX );
- }
- }
- }
-
- if( 0!= err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return 0;
- }
- // ==============================================================================================
- // GPIB_SystemErrorAll(...)
- // Назначенная комманда - SYSTem:ERRor:ALL?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - строка всех ошибок в очереди
- unsigned int GPIB_SystemErrorAll( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- //--------------------------------------------------------
- int a = 0;
- // Request ONLY
- if (request)
- {
- int c = 0;
-
- do{
- if( a>0 ) { *(pBulkData_DeviceOut+a) = ','; a++; *(pBulkData_DeviceOut+a) = ' ';a++;}
- c = usbtmc_GetErrorText( udi, pBulkData_DeviceOut+a, MAX-a );
- a+=c;
- }while( GPIB_GET_EAV() );
- }
- return a;
- }
- // ==============================================================================================
- // GPIB_EventStatusEnable(...)
- // Назначенная комманда - ESE?
- // Параметры комманды - отсутствуют или значение регистра
- // Возвращаемое значение - значение регистра разрешения статусов событий (Event Status Enable Register)
- unsigned int GPIB_EventStatusEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned size = 0, err = 0;
- unsigned int ESE;
- char NUMBER[11]={0,0,0,0,0,0,0,0,0,0,0x0A};
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != TernaryOperator(request, 0, 1))
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request && !queue_get( pQParameters, NUMBER, 10, &size ))
- {
- err = ERROR_GPIB_INVALID_PARAMETER;
- }
- else
- {
- if( !request && NUMBER[0] != eParTypeNR1 )
- {
- err = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- }
- else
- {
- if( !request && 0!=GPIB_ParseNumbers( NUMBER+1,USBTMC_PARSENUMBERS_TYPE_INT,1, (int*)&ESE ))
- {
- err = ERROR_GPIB_INVALID_PARAMETER;
- }
- else
- {
- if(request)
- {
- return snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.ESE );
- }
- else
- {
- udi->usbtmcGpib.StateMachine.ESE = ESE&0xff;
- USBTMC_StateMachine_Modified( &udi->usbtmcGpib.StateMachine );
- }
- }
- }
- }
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return 0;
- }
- // ==============================================================================================
- // GPIB_OperationComplete(...)
- // Назначенная комманда - OPC?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "1"
- unsigned int GPIB_OperationComplete( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned /*size = 0,*/ err = 0;
- // unsigned int ESE;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- GPIB_SET_OPC();
-
- if(request)
- {
- return snprintf(pBulkData_DeviceOut, MAX, "%d", 1 );
- }
- else
- {
- (void)0;
- }
- }
- }
-
- if( 0!=err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return 0;
- }
- // ==============================================================================================
- // GPIB_Wait(...)
- // Назначенная комманда - *WAI
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - отсутствует
- unsigned int GPIB_Wait( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned /*size = 0,*/ err = 0;
- // unsigned int ESE;
- // int MAX = udi->BulkRespondStatus.RespondBufferSize;
- // BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if(!request)
- {
- (void)0;
- }
- else
- {
- (void)0;
- }
- }
- }
- if( 0!=err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return 0;
- }
- // ==============================================================================================
- // GPIB_Trigger(...)
- // Назначенная комманда - *TRG
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - отсутствует
- unsigned int GPIB_Trigger( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned int err = 0;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- err = ERROR_GPIB_TRIGGER_IGNORED;
- else
- err = ERROR_GPIB_COMMAND_ONLY_SUPPORT;
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, "Trigger ignored", GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, "Trigger ignored", errClass_Autodetect );
- }
-
- return 0;
- }
- // ==============================================================================================
- // GPIB_EventStatusRegister(...)
- // Назначенная комманда - *ESR?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - значение регистра статсуса событий
- unsigned int GPIB_EventStatusRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned int err = 0;
- unsigned int rc = 0;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( !request)
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- if( count != 0 )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- rc = snprintf(pBulkData_DeviceOut, MAX, "%d", GPIB_GET_ESR() );
-
- // IEEE 488.2, 11.5.1.2.2 Reading
- // The Standard Event Status Register is destructively read (that is, read and cleared) with the *ESR? common query, see 10.12.
- GPIB_CLR_ESR();
-
- // 27/08/18
- // --- replaced with: GPIB_SET_PWN() and GPIB_SET_OPC() ----
- // udi->usbtmcGpib.StateMachine.ESR = 129;
- // USBTMC_StateMachine_Modified( &udi->usbtmcGpib.StateMachine );
- //
- //
- // 27/08/18
- // --- Note: in this implementation the PowerOn(7) and OperationComplete(0) bits are disabled
- // GPIB_SET_PWN();
- // GPIB_SET_OPC();
-
- }
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return rc;
- }
- // ==============================================================================================
- // GPIB_StatusRegister(...)
- // Назначенная комманда - *STB?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - значение регистра статсуса устройства
- unsigned int GPIB_StatusRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned int err = 0;
- unsigned int rc = 0;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- rc = snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.STB );
- GPIB_CLR_RQS__(); // no state-machine state modify, clear ServiceRequestBit
- }
- }
- }
-
- if( 0!=err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return rc;
- }
- // ==============================================================================================
- // GPIB_StatusEnableRegister(...)
- // Назначенная комманда - *SRE?
- // Параметры комманды - отсутствуют или значение регистра
- // Возвращаемое значение - значение регистра разрешения статсуса устройства
- unsigned int GPIB_StatusEnableRegister( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count = 0;
- unsigned int err = 0;
- unsigned int rc = 0;
- unsigned int size = 0;
- BYTE SRE;
- char NUMBER[11]={0,0,0,0,0,0,0,0,0,0,0x0A};
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != ((request)?0:1) )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request && !queue_get( pQParameters, NUMBER, 10, &size ))
- {
- err = ERROR_GPIB_INVALID_PARAMETER;
- }
- else
- {
- if( !request && NUMBER[0] != eParTypeNR1 )
- {
- err = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- }
- else
- {
- if( !request && 0!=GPIB_ParseNumbers( NUMBER+1,USBTMC_PARSENUMBERS_TYPE_INT,1, (int*)&SRE ))
- {
- err = ERROR_GPIB_INVALID_PARAMETER;
- }
- else
- {
- if(request)
- {
- rc = snprintf(pBulkData_DeviceOut, MAX, "%d", udi->usbtmcGpib.StateMachine.SRE );
- }
- else
- {
- udi->usbtmcGpib.StateMachine.SRE = SRE&0xff;
- }
- }
- }
- }
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return rc;
- }
- // ==============================================================================================
- /*
- // GPIB_StatusOperationEvent(...)
- // Назначенная комманда - STATus:OPERation[:EVENt]?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- unsigned int GPIB_StatusOperationEvent( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // request равен 0x00 если комманда :STAT:OPER, а не :STAT:OPER? или :STAT:OPER:EVEN?
- // Request ONLY
- size_t count = 0;
- unsigned err = 0;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0)
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- return snprintf(pBulkData_DeviceOut, MAX, "%d", 0 );
- }
- }
- }
-
- if( 0!= err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return 0;
- }
- */
- /*
- // ==============================================================================================
- // GPIB_StatusOperationCondition(...)
- // Назначенная комманда - STATus:OPERation:CONDition?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- unsigned int GPIB_StatusOperationCondition( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // request - всегда 0x01
- // Request ONLY
- return GPIB_StatusOperationEvent(udi, pQParameters, request);
- }
- */
- /*
- // ==============================================================================================
- // GPIB_StatusOperationEnable(...)
- // Назначенная комманда - STATus:OPERation:ENABle?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- unsigned int GPIB_StatusOperationEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- { // request - если пришел запрос Enable? то request - 0x01
- // Request and Command support
- return GPIB_StatusQuestionableEnable(udi, pQParameters, request);
- }
- */
- /*
- // ==============================================================================================
- // GPIB_StatusQuestionableEvent(...)
- // Назначенная комманда - STATus:QUEStionable[:EVENt]?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- unsigned int GPIB_StatusQuestionableEvent( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- { // request равен 0x00 если комманда :STAT:QUES, а не :STAT:QUES? или :STAT:QUES:EVEN?
- // Request ONLY
- return GPIB_StatusOperationEvent(udi, pQParameters, request);
- }
- */
- /*
- // ==============================================================================================
- // GPIB_StatusQuestionableCondition(...)
- // Назначенная комманда - STATus:QUEStionable:CONDition?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- unsigned int GPIB_StatusQuestionableCondition( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- { // request равен 0x00 если комманда :STAT:QUES, а не :STAT:QUES? или :STAT:QUES:EVEN?
- // Request ONLY
- return GPIB_StatusOperationEvent(udi, pQParameters, request);
- }
- */
- // ==============================================================================================
- // GPIB_StatusQuestionableEnable(...)
- // Назначенная комманда - STATus:QUEStionable:ENABle?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - "0"
- /*
- unsigned int GPIB_StatusQuestionableEnable( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // request - если пришел запрос Enable? то request - 0x01
- // Request and Command support
- size_t count = 0;
- unsigned err = 0;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- // --------------------------------------------------
- if(!queue_getcount( pQParameters, &count ))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != ((request)?0:1) )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- {
- (void)0;
- }
- else
- {
- return snprintf(pBulkData_DeviceOut, MAX, "%d", 0 );
- }
- }
- }
-
- if( 0!=err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
- return 0;
- }
- */
- /*
- // ==============================================================================================
- // GPIB_StatusPreset(...)
- // Назначенная комманда - *RST, STATus:PRESet
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - отсутствует
- unsigned int GPIB_StatusPreset( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- { // request всегда 0x00
- // Command support only
- return GPIB_Reset(udi, pQParameters, request);
- }
- */
- // ==============================================================================================
- // GPIB_InterfaceSwitch(...)
- // Назначенная комманда - INTerface:SWitch? - переключение режима SCPI -> EZUSB
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - строка результата операции
- unsigned int GPIB_InterfaceSwitch( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- unsigned int rc = 0;
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- // -------------------------------------------------------
- if( InterfaceSwitch( udi, USB_INTERFACE_CONT )==0x01 )
- {
- if( request)
- {
- rc = snprintf( pBulkData_DeviceOut, MAX, "%s", "! The Interface will be switched at next connecting a USB cable!" );
- }
-
- {
- SET_SYSTEM_CODE(CODE_REBOOT_ID, CODE_REBOOT ); // магическое число
- SET_SYSTEM_FLAG(FLAG_REBOOT); // флажок на перезагрузку
- DeviceBusy( 1 ); // device is busy by writing.
- }
- }
- else
- {
- if( request)
- {
- rc = snprintf( pBulkData_DeviceOut, MAX, "%s", "# There was SPI flash error. The Interface will not be switched!" );
- }
-
- GPIB_RaiseStandartError( udi, ERROR_GPIB_INTERNAL, NULL, errClass_Autodetect );
- }
-
- return rc;
- }
- // ==============================================================================================
- // GPIB_GetTemperature(...)
- // Назначенная комманда - MEASure:TEMPerature?
- // Параметры комманды - отсутствуют
- // Возвращаемое значение - значение температуры в градусах
- unsigned int GPIB_GetTemperature( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- BYTE * pBulkData_DeviceOut = (BYTE*)udi->usbtmcGpib.pData;
- int MAX = udi->BulkRespondStatus.RespondBufferSize;
- size_t count =0;
- int err = 0;
- // -------------------------------------------------
- if(!queue_getcount( pQParameters, &count))
- {
- err = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( count != 0 )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !request )
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- return temperature_convert( pBulkData_DeviceOut, MAX, get_average_temperature() );
- }
- }
- }
-
- if( 0 != err )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- }
-
- return 0;
- }
- // GPIB_SwitchCount(...)
- // Назначенная комманда - [SYSTem:]SWITch:COUNt?
- // Параметры комманды - НЕТ
- // Возвращаемое значение - общее количество состояний портов
- unsigned int GPIB_SwitchCount( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count;
- unsigned int err = 0;
- unsigned int rc = 0;
- //-----------------------------------------------------------------------------------------
- if(!queue_getcount(pQParameters, &count))
- {
- err = ERROR_GPIB_INTERNAL;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- if(!request)
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- if( count != 0 )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- {
- BYTE * pBuffer = (BYTE*)udi->usbtmcGpib.pData;
- int freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- int32_t states = (int32_t)ACMClass->properties.allowedStatesCount;
-
- rc = GPIB_Integer2Str( states, pBuffer, freeSpace, Format_Int2Str_N );
- }
- L_GPIB_SwitchList_EXIT:
-
- if( err != 0 )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
-
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- rc = 0;
- }
- return rc;
- }
- // GPIB_SwitchList(...)
- // Назначенная комманда - [SWITch:]LIST?
- // Параметры комманды - порт( A, B, AB )
- // Возвращаемое значение - количество состояний порта
- unsigned int GPIB_SwitchList( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- size_t count;
- unsigned int err = 0;
- unsigned int rc = 0;
- //-----------------------------------------------------------------------------------------
- if(!queue_getcount(pQParameters, &count))
- {
- err = ERROR_GPIB_INTERNAL;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- if(!request)
- {
- err = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- if( count != 0 )
- {
- err = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_SwitchList_EXIT;
- }
-
- {
- BYTE * pBuffer = (BYTE*)udi->usbtmcGpib.pData;
- int freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- rc = ACMClass->methods.getKeyStateList( pBuffer, freeSpace );
- }
- L_GPIB_SwitchList_EXIT:
-
- if( err != 0 )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, err, NULL, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, err, NULL, errClass_Autodetect );
- rc = 0;
- }
- return rc;
- }
- //------------------------------------------------------------------------------
- // __Util_CheckParamTableId:
- // Is used as a universal parameter checker for following functions:
- // * GPIB_MemoryTableTime
- // * GPIB_MemoryTableDate
- // etc.
- // All the functions listed above have the same "command prototype" - MEM:TABLE:CMD [FACTory|USER1|USER2|USER3]
- // This function checks the only parameter - characterization table id (factory/user1/user2/user3),
- // parses it and converts into the [eChrz_t].
- // The function returns the error code.
- static unsigned int __Util_CheckParamTableId( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request,
- eChrz_t * pId )
- {
- unsigned int errCode = 0;
- size_t rc = 0;
- char textBuffer[16];
- eChrz_t id; // Characterization Table Id
-
- // check the requiest status
- if(!request )
- {
- // error: command must be a request
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L__Util_CheckParamTableId_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &rc) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L__Util_CheckParamTableId_EXIT;
- }
- // Check parameters count
- else if( 1 < rc ) // only one OPTIONAL parameter allowed for this command
- {
- // error: wrong parameters count ( must be 0 or 1 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L__Util_CheckParamTableId_EXIT;
- }
-
- if( 1 == rc ) // one parameter - table identifier (factory/user1/user2/user3)
- {
- // optional parameter is specified
-
- // retrieve the first parameter: table identifier (factory/user1/user2/user3)
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L__Util_CheckParamTableId_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L__Util_CheckParamTableId_EXIT;
- }
-
- // retrieve the parameter
- id = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
-
- if( eCh_MAX == id )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L__Util_CheckParamTableId_EXIT;
- }
- }
- else
- {
- // optional parameter is absent
-
- // table identifier omitted, "FACTory" is supposed
- id = eChFactory;
- }
-
- L__Util_CheckParamTableId_EXIT:
- if( 0 == errCode )
- {
- if( NULL != pId )
- {
- *pId = id;
- }
- }
-
- return errCode;
- }
- //------------------------------------------------------------------------------
- // Descriptions for elements of [eChrz_t]
- static const char * const aChrzDesc[] =
- {
- "Factory characterization data", // eChFactory
- "USER1 characterization data", // eChUser1
- "USER2 characterization data", // eChUser2
- "USER3 characterization data", // eChUser3
- NULL // eCh_MAX
- };
- const char pcThermoDesc[] = "Thermocompensation data";
- // Descriptions for elements of [ePortComb_t]
- static const char * const aPortComb[] =
- {
- "Port A" , // ePortComb_A
- "Port B" , // ePortComb_B
- "Port C" , // ePortComb_C
- "Port D" , // ePortComb_D
- "Thru AB" , // ePortComb_AB
- "Thru AC" , // ePortComb_AC
- "Thru AD" , // ePortComb_AD
- "Thru BC" , // ePortComb_BC
- "Thru BD" , // ePortComb_BD
- "Thru CD" , // ePortComb_CD
- "CHECK state" , // ePortComb_CHECK
- NULL // ePortComb_MAX
- };
- /*
- // Descriptions for elements of [eChrz_t]
- static const char * aPortDesc[] =
- {
- "port A", // ePortId_A
- "port B", // ePortId_B
- "port C", // ePortId_C
- "port D", // ePortId_D
- NULL // eCh_MAX
- };*/
- //------------------------------------------------------------------------------
- // GPIB_MemoryTablePoints()
- // Prints amount of characterization points of the characterization table: factory or user
- size_t GPIB_MemoryTablePoints( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
- size_t nPoints;
-
- if( 0 == errCode )
- {
- nPoints = ACMClass->methods.xCharacterization.getPointsCount( id );
-
- if( 0 != nPoints )
- {
- rc = snprintf( (char*)pBuffer, freeSpace, "%d", nPoints );
-
- if( 0 == rc || rc == freeSpace )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- }
- }
- else
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- // L_GPIB_MemoryTablePoints_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
- rc = 0;
- }
-
- return rc;
- }
- //------------------------------------------------------------------------------
- // GPIB_MemoryTableDate()
- // Prints the characterization date
- size_t GPIB_MemoryTableDate( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getDate( id, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableTime()
- // Prints the characterization time
- size_t GPIB_MemoryTableTime( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getTime( id, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableTemp()
- // Prints the characterization temperature
- size_t GPIB_MemoryTableTemp( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
- double temperature = 0;
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getChrzTemp( id, &temperature ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- else
- {
- rc = GPIB_Double2Str( temperature, (char*)pBuffer, freeSpace, Format_Double2Str_Ndot3 );
-
- if( 0 == rc )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- }
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableFreqType()
- // Prints the type of the characterization frequency scale
- size_t GPIB_MemoryTableFreqType( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- eChrzScaleType_t scaleType;
-
- if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- else
- {
- if( eChScaleLinear == scaleType )
- {
- rc = snprintf( (char*)pBuffer, freeSpace, "%s", "LIN" );
- }
- else if( eChScaleSegment == scaleType )
- {
- rc = snprintf( (char*)pBuffer, freeSpace, "%s", "SEGM" );
- }
- else rc = 0;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableFreqData()
- // Prints all the frequency points of the characterization frequency scale
- size_t GPIB_MemoryTableFreqData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // 1
- char * pBuffer = (char*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0; // full amount of bytes returned
- size_t bytes = 0; // bytes returned
- unsigned int errCode = 0; // error identifier
- sEcalSegment_t segment; // scale segment data
-
- size_t iSeg = 0, nSeg = 0; // amount of segments
- size_t iPnt = 0, nPnt = 0; // amount of points
- eChrz_t id = eCh_MAX; // characterization id
- eChrzScaleType_t scaleType; // scale type
-
- // 2
- // Check if the function context is saved and must be continued
- if( !udi->GPIBFunctionContext.bEnable )
- {
- // no context found
-
- // check input parameters
- errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- if( 0 != errCode || eCh_MAX == id )
- {
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- // retrieve the scale type
- if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- if( eChScaleLinear == scaleType )
- {
- // Linear scale
-
- nSeg = 1;
- iSeg = 0;
- iPnt = 0;
- }
- else
- {
- // Segment scale
-
- // read amount of segments
- nSeg = ACMClass->methods.xCharacterization.getScaleSegment( id, NULL, 0 );
- iSeg = 0;
- iPnt = 0;
-
- if( 0 == nSeg )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
- }
- }
- // 3
- else
- {
- // load previous context
- /* */
- if(
- queue_get( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id), &bytes ) // load memory segment id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&nSeg , sizeof(nSeg), &bytes ) // load amount of segments
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&iSeg , sizeof(iSeg), &bytes ) // load segment index
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&nPnt , sizeof(nPnt), &bytes ) // load amount of points
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&iPnt , sizeof(iPnt), &bytes ) // load point index
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&scaleType , sizeof(scaleType), &bytes ) // load the scale type
- )
- {
- // OK
- }
- else
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
- }
-
- rc = 0;
- // 4
- // try to print frequencies list
- for( (void)iSeg; iSeg < nSeg; ++iSeg ) // for each segment
- {
- // For segment scale: load the segment data
- if( eChScaleSegment == scaleType )
- {
- // retrieve the segment information
- if( 1 != ACMClass->methods.xCharacterization.getScaleSegment( id, &segment, iSeg ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- // load the points count
- nPnt = segment.Points;
- }
-
- if( eChScaleLinear == scaleType )
- {
- // load the points count
- nPnt = ACMClass->methods.xCharacterization.getPointsCount( id );
-
- // load start and stop frequencies
- if( !ACMClass->methods.xCharacterization.getStartFreq( id, &segment.Fstart )
- || !ACMClass->methods.xCharacterization.getStopFreq( id, &segment.Fstop ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- // store @nPnt into the @segment to unify the access
- segment.Points = nPnt;
- }
-
- if( 0 == nPnt )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- for( (void)iPnt; iPnt < nPnt; ++iPnt ) // for each point
- {
- // One point has the following format:
- // <Freq_i>,<SPACE>
- // where @i is the point number,
- // @nPnt - amount of points.
- // Total amount of numbers to be print: nPnt
- // One number has 16 symbols length plus 2 (comma and space)
- // So, 18 characters required to print one point.
- // To prevent overflowing by snprintf() with printing null-term,
- // it is required at lease 20 characters free
- if( freeSpace >= 20 )
- {
- double dbl_freq_point = 0.0;
-
- if( segment.Points > 1 )
- {
- // e.g. segment #1, (1.0e+5;2.0e+5,11 points)
- // START_FREQ=100000; STOP_FREQ=200000; N=11
- // 100000, 110000, 120000, 130000, 140000 } 5 points
- // 150000, 160000, 170000, 180000, 190000, 20000 } 6 points
- // Total: 11 points on (1.0e+5;2.0e+5)
- // So, STEP is (STOP_FREQ - START_FREQ)/(N-1) = 10000
-
- #define SegmentFreqStep( seg ) ((seg.Fstop - seg.Fstart) / (seg.Points - 1))
-
- // calculate current frequency point (MAGNITUDE)
- // print the frequency point
- dbl_freq_point = segment.Fstart + SegmentFreqStep( segment ) * iPnt;
- /*
- bytes = GPIB_Double2Str( segment.Fstart + SegmentFreqStep( segment ) * iPnt,
- pBuffer, freeSpace, Format_Double2Str_Sci );*/
- }
- else
- {
- dbl_freq_point = segment.Fstart;
- /*
- bytes = GPIB_Double2Str( segment.Fstart,
- pBuffer, freeSpace, Format_Double2Str_Sci );*/
- }
-
- { // fix: 05/09/18
- // round the value to [Hz]
- dbl_freq_point = round( dbl_freq_point );
-
- // print rounded value
- bytes = GPIB_Double2Str( dbl_freq_point,
- pBuffer, freeSpace, Format_Double2Str_Sci );
- }
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // print the delimeter
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
- }
- else
- {
- // --------------------------------------------------------------------------
- // Save context
- usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableFreqData );
-
- if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id) ) // Save memory segment id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&nSeg , sizeof(nSeg) ) // Save amount of segments
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&iSeg , sizeof(iSeg) ) // Save segment index
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&nPnt , sizeof(nPnt) ) // Save amount of points
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&iPnt , sizeof(iPnt) ) // Save point index
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&scaleType , sizeof(scaleType) ) // Save the scale type
- )
- {
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = FALSE;
- errCode = 0;
- // --------------------------------------------------------------------------
-
- goto L_GPIB_MemoryTableFreqData_EXIT;
- }
-
- /*for( const char * p = __Buffer; p != pBuffer; ++p )
- {
- if( *p == '\0' )
- {
- asm( "bkpt #0" );
- }
- }*/
- }
-
- // For the last point of last segment
- if( iSeg >= nSeg-1 )
- if( iPnt >= nPnt )
- {
- if( rc > 2 )
- rc -= 2; // cut off the last comma separator and space
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
- }
-
- iPnt = 0;
- }
-
- // 5
- L_GPIB_MemoryTableFreqData_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableFreqSegmData()
- // Prints the scale segments parameters of the characterization frequency scale
- size_t GPIB_MemoryTableFreqSegmData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // 1
- char * pBuffer = (char*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0; // full amount of bytes returned
- size_t bytes = 0; // bytes returned
- size_t i, n = 0; // amount of segments
- eChrz_t id = eCh_MAX; // characterization id
- unsigned int errCode = 0; // error identifier
- sEcalSegment_t segment; // scale segment data
- eChrzScaleType_t scaleType; // scale type
-
- // 2
- // Check if the function context is saved and must be continued
- if( !udi->GPIBFunctionContext.bEnable )
- {
- // no context found
-
- // check input parameters
- errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- if( 0 != errCode || eCh_MAX == id )
- {
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
-
- // retrieve the scale type
- // check the conditions: the scale must be a Segment Type Scale
- if( !ACMClass->methods.xCharacterization.getScaleType( id, &scaleType )
- || eChScaleSegment != scaleType)
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
-
- // read amount of segments
- n = ACMClass->methods.xCharacterization.getScaleSegment( id, NULL, 0 );
- i = 0;
-
- if( 0 == n )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
-
- // print amount of segements
- bytes = snprintf( pBuffer, freeSpace, "%d%s", n, ",\n" /* ",\r\n" */);
-
- if( 0 == bytes || bytes == freeSpace )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
- else
- {
- rc += bytes;
- freeSpace -= bytes;
- pBuffer += bytes;
- }
- }
- // 3
- else
- {
- // load previous context
- /* */
- if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id),&bytes ) // load memory segment id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&n , sizeof(n), &bytes ) // load amount of segments
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&i , sizeof(i), &bytes ) // load segment number
- )
- {
- // OK
- }
- else
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
- }
-
- // 4
- // try to print the segment list
- for( /*@i is loaded from context*/; i < n; ++i )
- {
- // segment data format:
- // <StartFreq>, <StopFreq>, <NumberOfPoints><CR><LF>
- // e.g.
- // 1.0000000000e+5, 2.0000000000e+6, 13<CR><LF>
- // Minimum free space required to one segment: 36 + amount of chars in <NumberOfPoints>
- // Let it be 4.
- // Whole number of free bytes in the buffer: 40
- // To prevent overflowing by snprintf() with printing null-term,
- // it is required at lease 44 characters free
- if( freeSpace >= 44 )
- {
- if( 1 == ACMClass->methods.xCharacterization.getScaleSegment( id, &segment, i ) )
- {
- // print the segment data
-
- bytes = GPIB_Double2Str( segment.Fstart, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- bytes = GPIB_Double2Str( segment.Fstop, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- bytes = snprintf( pBuffer, freeSpace, "%d%s", segment.Points, "\n"/*"\r\n"*/ );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
- }
- else
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
- }
- else
- {
- // --------------------------------------------------------------------------
- // Save context
- usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableFreqSegmData );
-
- if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&id, sizeof(id) ) // Save memory segment id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&n , sizeof(n) ) // Save amount of segments
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&i , sizeof(i) ) // Save segment number
- )
- {
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableFreqSegmData_EXIT;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = FALSE;
- errCode = 0;
- // --------------------------------------------------------------------------
-
- break;
- }
- }
- // 5
- L_GPIB_MemoryTableFreqSegmData_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableFreqStart()
- // Prints the start frequency of the characterization frequency scale
- size_t GPIB_MemoryTableFreqStart( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- double startFreq = 0.0f;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getStartFreq( id, &startFreq ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- else
- {
- rc = GPIB_Double2Str( startFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemoryTableFreqStop()
- // Prints the stop frequency of the characterization frequency scale
- size_t GPIB_MemoryTableFreqStop( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- double stopFreq = 0.0f;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getStopFreq( id, &stopFreq ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- else
- {
- rc = GPIB_Double2Str( stopFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableAdapter()
- //
- size_t GPIB_MemoryTableAdapter( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- size_t rc = 0;
- size_t nParams = 0;
- unsigned int errCode = 0;
-
- eChrz_t id = eCh_MAX; // by default
- ePortId_t pid; // Port ID
- char textBuffer[16];
-
- // check the requiest status
- if(!request )
- {
- // error: command must be a request
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &nParams) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- // Check parameters count
- else if( 1 != nParams && 2 != nParams ) // this command must have 1 or 2 parameters
- {
- // error: wrong parameters count ( must be 1 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // first parameter - port identifier (A/B/C/D)
- {
- // retrieve the first parameter: port identifier (A/B/C/D)
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // retrieve the parameter
- pid = GPIB_GetPortId( &textBuffer[1], rc - 1 );
-
- if( ePortId_MAX == pid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- if( 2 == nParams )
- {
- // retrieve second parameter: table identifier (factory/user1/user2/user3)
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // retrieve the parameter
- id = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
-
- if( eCh_MAX == id )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- }
- else
- {
- id = eChFactory;
- }
- }
-
- if( !ACMClass->methods.xCharacterization.getAdapterDesc( id, pid, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
-
- L_GPIB_MemoryTableAdapter_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return 0;
- }
- // GPIB_MemTableConnector()
- //
- size_t GPIB_MemoryTableConnector( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- size_t rc = 0;
- unsigned int errCode = 0;
-
- ePortId_t pid; // Port ID
- char textBuffer[16];
-
- // check the requiest status
- if(!request )
- {
- // error: command must be a request
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &rc) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- // Check parameters count
- else if( 1 != rc ) // this command must have only one parameter
- {
- // error: wrong parameters count ( must be 1 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // parameter - port identifier (A/B/C/D)
- {
- // retrieve the first parameter: port identifier (A/B/C/D)
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
-
- // retrieve the parameter
- pid = GPIB_GetPortId( &textBuffer[1], rc - 1 );
-
- if( ePortId_MAX == pid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableAdapter_EXIT;
- }
- }
-
- if( !ACMClass->methods.xCharacterization.getConnectorType( pid, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
-
- L_GPIB_MemoryTableAdapter_EXIT:
-
- if( 0 != errCode )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, aChrzDesc[ (size_t)eChFactory ], GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, aChrzDesc[ (size_t)eChFactory ], errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableAnalyzer()
- // Prints the analyzer model of the characterization
- size_t GPIB_MemoryTableAnalyzer( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getAnalyzer( id, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTablePlace()
- // Prints the location where the characterization has been created
- size_t GPIB_MemoryTablePlace( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getPlace( id, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableOperator()
- // Prints the operator's name who created the characterization
- size_t GPIB_MemoryTableOperator( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
-
- eChrz_t id = eCh_MAX;
- unsigned int errCode = __Util_CheckParamTableId( udi, pQParameters, request, &id );
-
- size_t rc = 0;
-
- if( 0 == errCode )
- {
- if( !ACMClass->methods.xCharacterization.getOperator( id, (char*)pBuffer, freeSpace, &rc ) )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != id )
- {
- pDescription = aChrzDesc[ (size_t)id ];
- }
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // ==============================================================================================
- // volatile size_t debug_call = 0;
- // GPIB_MemoryTableData()
- // MEM:TABLE:DATA? <PORT_COMBINATION>, <PORT_STATE>, [MEMORY_SECTOR]
- // Prints the contents of the characterization table depending on the following parameters:
- // - port combination (A, B, or CD, or CHECK, etc)
- // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
- // - memory sector (Factory/USER1/USER2/USER3), OPTIONAL, by default = FACTORY
- size_t GPIB_MemoryTableData( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // 1
- char * pBuffer = (char*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0; // full amount of bytes returned
- unsigned int errCode = 0; // error identifier
-
- sACMGetPoints_t tableContext; // table context to store the data between calls
- eChrz_t msid = eCh_MAX; // characterization id, = memory sector id
- ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
- ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
-
- // debug_call++;
- // 2
- // Check if the function context is saved and must be continued
- if( !udi->GPIBFunctionContext.bEnable )
- {
- // no context found
- size_t nParam = 0; // amount of parameters
-
- if( !request )
- {
- // error: request only supported
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &nParam) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- // Check parameters count
- else if( 2 != nParam && 3 != nParam ) // this command must have 2 or 3 parameters
- {
- // error: wrong parameters count ( must be 2 or 3 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port combination
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // retrieve the parameter
- pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
-
- if( ePortComb_UNDEFINED == pcid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- }
-
- // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port state
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // retrieve the parameter
- psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
-
- if( ePortStateId_UNDEFINED == psid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- }
-
- // parameter #3 - memory sector (FACTORY/USER1/USER2/USER3)
- if( 3 == nParam ) // if third parameter is not omitted
- {
- char textBuffer[16];
-
- // retrieve the first parameter: memory sector
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // retrieve the parameter
- msid = GPIB_GetChrzTableId( &textBuffer[1], rc - 1 );
-
- if( eCh_MAX == msid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- }
- else
- {
- msid = eChFactory;
- }
-
- // Validate given parameters: port state and port combination
- if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // initialize the table context @.out just for order
- tableContext.out.max = 0; // don't care
- tableContext.out.min = 0; // don't care
- tableContext.out.TableAddress = 0; // don't care
- tableContext.out.nPoints = 0; // don't care
-
- // initialize @.in to make the @.getPoints() call to load
- // the table header.
- // - set @.nCount to 0 to load the table header
- tableContext.in.nCount = 0; // must be 0
- tableContext.in.nStartPoint = 0; // don't care
- tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
-
- // load table header and validate it
- // During this call the @tableContext.out will be initialized
- if( 1 != ACMClass->methods.xCharacterization.getPoints(
- msid, // memory sector
- pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- errCode = ERROR_GPIB_DATA_NOT_FOUND;
-
- // failed
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_DATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // ok, now @tableContext is initialized
- // Let's initialize the rest variables
- tableContext.in.nStartPoint = 0; // starting point = 0
- tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
- tableContext.in.nCount = 0; // zero yet, see below
- }
- // 3
- else
- {
- // load previous context
- size_t bytes;
-
- if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&msid , sizeof(msid), &bytes ) // load memory segment id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
- )
- {
- // OK
-
- // Note:
- // @tableContext.out.nPoints is remembered, amount of points
- // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
- }
- else
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableData_EXIT;
- }
- }
-
- rc = 0;
- // 4
- {
- size_t nPoints = tableContext.out.nPoints; // amount of points in the table
- size_t nStart = tableContext.in.nStartPoint; // starting point
-
- // do until all the points are processed
- while( nStart < nPoints )
- {
- // specify the number of points to retrieve: @tableContext.in.nCount
- // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
- // already specified or remembered
- size_t nStepPoints = (nPoints - nStart);
-
- // check the points number for the limit
- if( nStepPoints >= DBPOINTS_BUFFER_NUM )
- {
- tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
- }
- else
- {
- // not greater than it is required
- tableContext.in.nCount = nStepPoints;
- }
-
- // retrieve the points from the memory
- if( tableContext.in.nCount != ACMClass->methods.xCharacterization.getPoints(
- msid, // memory sector
- pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- // error
- // Strange... The table is already validated. Maybe, it is I/O error issue.
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
-
- // failed
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_DATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- // Ok, the double-points are loaded...
- // Let's convert it!
- // @iPoint - just counts amount of converted points at this step.
- for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
- {
- // the point format is:
- // <Magnitude>,<SPACE><Phase>,<SPACE>
- // where <Magnitude> and <Phase> is a number in scientific format
- // with 10 fractional digits. Let's leave 2 digits for the exponent,
- // and one number takes 16 characters, plus the separator and the space.
- // So one point takes (16+2)*2 = 36 characters. To be in save we will
- // suppose the one point takes 48 characters.
- // e.g.
- // 1.0000000000e+5, 1.0000000000e+0,
- if( freeSpace >= 48 )
- {
- size_t bytes = 0;
-
- // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
-
- // Convert a magnitude
- bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].magn, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- if( 0 == bytes )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // print the delimeter
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // Convert a phase
- bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].phase, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- if( 0 == bytes )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // print the delimeter
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // move to the next point in the table
- nStart++;
- }
- else
- {
- // not enough free space in the text buffer
-
- (void)tableContext.out.nPoints;
- tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
- // --------------------------------------------------------------------------
- // Save context
- usbtmc_create_function_context( udi, (void*)GPIB_MemoryTableData );
-
- if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&msid , sizeof(msid) ) // Save memory segment id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
- )
- {
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemoryTableData_EXIT;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = FALSE;
- errCode = 0;
- // --------------------------------------------------------------------------
-
- goto L_GPIB_MemoryTableData_EXIT;
- }
- } // for
-
- tableContext.in.nStartPoint = nStart; // modify the starting point
-
- } // while( nStart < nPoints )
-
- // Ok, all the points are converted here due to
- // otherwise, the program jumps to L_GPIB_MemoryTableData_EXIT label
- // after saving context.
- if( rc > 2 )
- {
- // cut off the last space and comma
- rc -= 2;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
- }
- // 5
- L_GPIB_MemoryTableData_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = NULL;
-
- if( eCh_MAX != msid )
- {
- pDescription = aChrzDesc[ (size_t)msid ];
- }
-
- if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
- && ePortComb_MAX != pcid )
- {
- pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // ==============================================================================================
- // ==============================================================================================
- // GPIB_SwitchState(...)
- // Назначенная комманда - [SYSTem:]SWITch:STATe, [SYSTem:]SWITch:STATe?
- // Параметры комманды - состояние (SALL, OALL, THBD, ...) или отстутствует (запрос)
- // Возвращаемое значение - строка имени состояния порта и количество байт
- unsigned int GPIB_SwitchState( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- union
- {
- char stateRaw[ 16 ];
- struct
- {
- BYTE stateNameParamType;
- char stateName[ 15 ];
- };
- } = {
- .stateRaw = {0}
- };
-
- unsigned int errCode = 0;
- size_t stateNameLength = 0;
- size_t count = 0;
- BYTE * pBuffer = NULL;
- int nFreeSpace = 0;
- size_t bytes = 0;
- eACMKeyState_t keyState;
-
- // -------------------------------------------------
- pBuffer = (BYTE*)udi->usbtmcGpib.pData;
- nFreeSpace = udi->BulkRespondStatus.RespondBufferSize;
- // -------------------------------------------------
-
- if(!queue_getcount(pQParameters, &count))
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- if( TernaryOperator(request,0,1) != count )
- {
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- if( !request ) // == (count==1)
- {
- if( !queue_get( pQParameters, stateRaw, sizeof(stateRaw), &stateNameLength ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- if( stateNameLength < 2 || eParTypeChar != stateNameParamType )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- stateNameLength--; // decrease parameter length by 1 byte - 1 byte for parameter type
-
- keyState = ACMClass->methods.getKeyStateByName( stateName, stateNameLength );
-
- if( eKeyState_Undefined == keyState )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- // -------------------------------------------------
-
- if( ! ACMClass->methods.checkStateAvailable( keyState ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_SwitchState_EXIT;
- }
-
- /*
- bytes = ACMClass->methods.getKeyStateName( keyState, pBuffer, nFreeSpace );
-
- if( (0 == bytes) && ( bytes > nFreeSpace ) )
- {
- err = ERROR_GPIB_INTERNAL;
- goto L_GPIB_SwitchState_EXIT;
- }
- */
-
- if( ! ACMClass->methods.setKeyStateCommon( keyState ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_SwitchState_EXIT;
- }
- }
- else
- {
- keyState = ACMClass->methods.getKeyStateCommon();
-
- bytes = ACMClass->methods.getKeyStateName( keyState, pBuffer, nFreeSpace );
-
- if( (0 == bytes) && ( bytes > nFreeSpace ) )
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_SwitchState_EXIT;
- }
- }
- // -------------------------------------------------
-
- L_GPIB_SwitchState_EXIT:
-
- if( 0 != errCode )
- {
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, NULL, errClass_Autodetect );
-
- bytes = 0;
- }
-
- return bytes;
- }
- void GPIB_DevDepInit( USB_DEVICE_INFO * udi )
- {
- //InitKeyState();
-
- //SETKEY_LOADB(udi->CommandStatus.key_stat);
- //SETKEY_LOADA(udi->CommandStatus.key_stat);
- //usbapp_SET_KEY_STAT(&udi->CommandStatus);
-
- /* ACMClass is uninitialized yet! */
- }
- // GPIB_MemTableTherCorrFreqStart()
- // Prints the start frequency of the thermocompensation data array
- size_t GPIB_MemTableTherCorrFreqStart( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0;
- double startFreq = 0.0f;
- unsigned int errCode = 0;
- size_t count = 0;
- if( !request )
- {
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- if( !queue_getcount( pQParameters, &count) )
- {
- errCode = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( 0 != count )
- {
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !ACMClass->methods.xThermo.getStartFreq( &startFreq ) )
- {
- errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
- }
- else
- {
- rc = GPIB_Double2Str( startFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
- }
- }
- }
- }
-
-
- if( 0 != errCode )
- {
- const char * pDescription = pcThermoDesc;
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableTherCorrFreqStop()
- // Prints the stop frequency of the thermocompensation data array
- size_t GPIB_MemTableTherCorrFreqStop( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0;
- double stopFreq = 0.0f;
- unsigned int errCode = 0;
- size_t count = 0;
-
- if( !request )
- {
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- if( !queue_getcount( pQParameters, &count) )
- {
- errCode = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( 0 != count )
- {
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- if( !ACMClass->methods.xThermo.getStopFreq( &stopFreq ) )
- {
- errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
- }
- else
- {
- rc = GPIB_Double2Str( stopFreq, (char*)pBuffer, freeSpace, Format_Double2Str_Sci );
- }
- }
- }
- }
-
- if( 0 != errCode )
- {
- const char * pDescription = pcThermoDesc;
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- size_t GPIB_MemTableTherCorrPoints( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- uint8_t * pBuffer = (uint8_t*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0;
- size_t nPoints = 0;
- unsigned int errCode = 0;
- size_t count = 0;
-
- if( !request )
- {
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- }
- else
- {
- if( !queue_getcount( pQParameters, &count) )
- {
- errCode = ERROR_GPIB_INTERNAL;
- }
- else
- {
- if( 0 != count )
- {
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- }
- else
- {
- nPoints = ACMClass->methods.xThermo.getPointsCount();
-
- if( 0 == nPoints )
- {
- errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
- }
- else
- {
- rc = snprintf( (char*)pBuffer, freeSpace, "%d", nPoints );
- }
- }
- }
- }
- if( 0 != errCode )
- {
- const char * pDescription = pcThermoDesc;
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableTherCorrMagniture()
- // MEM:TABLE:THER:CORR:MAGN? <PORT_COMBINATION>, <PORT_STATE>
- // Prints the contents of the characterization table depending on the following parameters:
- // - port combination (A, B, or CD, or CHECK, etc)
- // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
- size_t GPIB_MemTableTherCorrMagniture( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // 1
- char * pBuffer = (char*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0; // full amount of bytes returned
- unsigned int errCode = 0; // error identifier
-
- sACMGetPoints_t tableContext; // table context to store the data between calls
- ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
- ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
- // 2
- // Check if the function context is saved and must be continued
- if( !udi->GPIBFunctionContext.bEnable )
- {
- // no context found
- size_t nParam = 0; // amount of parameters
-
- if( !request )
- {
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &nParam) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- // Check parameters count
- else if( 2 != nParam ) // this command must have 2 parameters
- {
- // error: wrong parameters count ( must be 2 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port combination
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // retrieve the parameter
- pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
-
- if( ePortComb_UNDEFINED == pcid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- }
-
- // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port state
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // retrieve the parameter
- psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
-
- if( ePortStateId_UNDEFINED == psid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- }
-
- // Validate given parameters: port state and port combination
- if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // initialize the table context @.out just for order
- tableContext.out.max = 0; // don't care
- tableContext.out.min = 0; // don't care
- tableContext.out.TableAddress = 0; // don't care
- tableContext.out.nPoints = 0; // don't care
-
- // initialize @.in to make the @.getPoints() call to load
- // the table header.
- // - set @.nCount to 0 to load the table header
- tableContext.in.nCount = 0; // must be 0
- tableContext.in.nStartPoint = 0; // don't care
- tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
-
- // load table header and validate it
- // During this call the @tableContext.out will be initialized
- if( 1 != ACMClass->methods.xThermo.getPointsMagn( pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- // failed
- errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
-
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // ok, now @tableContext is initialized
- // Let's initialize the rest variables
- tableContext.in.nStartPoint = 0; // starting point = 0
- tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
- tableContext.in.nCount = 0; // zero yet, see below
- }
- // 3
- else
- {
- // load previous context
- size_t bytes;
-
- if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
- )
- {
- // OK
-
- // Note:
- // @tableContext.out.nPoints is remembered, amount of points
- // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
- }
- else
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- }
-
- rc = 0;
- // 4
- {
- size_t nPoints = tableContext.out.nPoints; // amount of points in the table
- size_t nStart = tableContext.in.nStartPoint; // starting point
-
- // do until all the points are processed
- while( nStart < nPoints )
- {
- // specify the number of points to retrieve: @tableContext.in.nCount
- // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
- // already specified or remembered
- size_t nStepPoints = (nPoints - nStart);
-
- // check the points number for the limit
- if( nStepPoints >= DBPOINTS_BUFFER_NUM )
- {
- tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
- }
- else
- {
- // not greater than it is required
- tableContext.in.nCount = nStepPoints;
- }
-
- // retrieve the points from the memory
- if( tableContext.in.nCount != ACMClass->methods.xThermo.getPointsMagn(
- pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- // error
- // Strange... The table is already validated. Maybe, it is I/O error issue.
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
-
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- // Ok, the double-points are loaded...
- // Let's convert it!
- // @iPoint - just counts amount of converted points at this step.
- for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
- {
- // the point format is:
- // <Number>,<SPACE>
- // where <Number> is a number in scientific format
- // with 10 fractional digits. Let's leave 2 digits for the exponent,
- // and one number takes 16 characters, plus the separator and the space.
- // So one point takes (16+2) = 18 characters. To be in save we will
- // suppose the one point takes 24 characters.
- // e.g.
- // 1.0000000000e+5,
- if( freeSpace >= 24 )
- {
- size_t bytes = 0;
-
- // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
-
- // Convert a magnitude
- bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].magn, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- if( 0 == bytes )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // print the delimeter
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // move to the next point in the table
- nStart++;
- }
- else
- {
- // not enough free space in the text buffer
-
- (void)tableContext.out.nPoints;
- tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
- // --------------------------------------------------------------------------
- // Save context
- usbtmc_create_function_context( udi, (void*)GPIB_MemTableTherCorrMagniture );
-
- if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
- )
- {
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = FALSE;
- errCode = 0;
- // --------------------------------------------------------------------------
-
- goto L_GPIB_MemTableTherCorrMagniture_EXIT;
- }
- } // for
-
- tableContext.in.nStartPoint = nStart; // modify the starting point
-
- } // while( nStart < nPoints )
-
- // Ok, all the points are converted here due to
- // otherwise, the program jumps to L_GPIB_MemTableTherCorrMagniture_EXIT label
- // after saving context.
- if( rc > 2 )
- {
- // cut off the last space and comma
- rc -= 2;
- }
- }
- // 5
- L_GPIB_MemTableTherCorrMagniture_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = pcThermoDesc;
-
- if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
- && ePortComb_MAX != pcid )
- {
- pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- // GPIB_MemTableTherCorrPhase()
- // MEM:TABLE:THER:CORR:PHAS? <PORT_COMBINATION>, <PORT_STATE>
- // Prints the contents of the characterization table depending on the following parameters:
- // - port combination (A, B, or CD, or CHECK, etc)
- // - port state (Load, Short, Thru11=S11, Check12=S12, etc.)
- size_t GPIB_MemTableTherCorrPhase( USB_DEVICE_INFO * udi, QUEUE * pQParameters, BOOL request )
- {
- // 1
- char * pBuffer = (char*)udi->usbtmcGpib.pData;
- size_t freeSpace = udi->BulkRespondStatus.RespondBufferSize;
- size_t rc = 0; // full amount of bytes returned
- unsigned int errCode = 0; // error identifier
-
- sACMGetPoints_t tableContext; // table context to store the data between calls
- ePortComb_t pcid = ePortComb_UNDEFINED; // port combination id
- ePortStateId_t psid = ePortStateId_UNDEFINED; // port state id
- // 2
- // Check if the function context is saved and must be continued
- if( !udi->GPIBFunctionContext.bEnable )
- {
- // no context found
- size_t nParam = 0; // amount of parameters
-
- if( !request )
- {
- errCode = ERROR_GPIB_REQUEST_ONLY_SUPPORT;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // Retrieve amount of parameters from the queue
- if( !queue_getcount(pQParameters, &nParam) )
- {
- // error: can't get parameters count
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- // Check parameters count
- else if( 2 != nParam ) // this command must have 2 parameters
- {
- // error: wrong parameters count ( must be 2 )
- errCode = ERROR_GPIB_WRONG_PARAMETERS_COUNT;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // parameter #1 - port combination (A/B/C/D/AB/AC/AD/BC/BD/CD/CHECK)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port combination
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // retrieve the parameter
- pcid = GPIB_GetPortComb( &textBuffer[1], rc - 1 );
-
- if( ePortComb_UNDEFINED == pcid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- }
-
- // parameter #2 - port state (SHORT, OPEN, LOAD, LOAD2, OPEN2, S11, S12, ..., S44)
- {
- char textBuffer[16];
-
- // retrieve the first parameter: port state
- if( !queue_get( pQParameters, (BYTE*)textBuffer, sizeof(textBuffer), &rc ))
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- // check the parameter type
- else if( eParTypeChar != textBuffer[0] )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER_TYPE;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // retrieve the parameter
- psid = GPIB_GetPortStateId( &textBuffer[1], rc - 1 );
-
- if( ePortStateId_UNDEFINED == psid )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- }
-
- // Validate given parameters: port state and port combination
- if( ! ACMClass->methods.checkTableParams( pcid, psid ) )
- {
- errCode = ERROR_GPIB_INVALID_PARAMETER;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // initialize the table context @.out just for order
- tableContext.out.max = 0; // don't care
- tableContext.out.min = 0; // don't care
- tableContext.out.TableAddress = 0; // don't care
- tableContext.out.nPoints = 0; // don't care
-
- // initialize @.in to make the @.getPoints() call to load
- // the table header.
- // - set @.nCount to 0 to load the table header
- tableContext.in.nCount = 0; // must be 0
- tableContext.in.nStartPoint = 0; // don't care
- tableContext.in.pDataArray = dbPointsBuffer; // must be initialized to pass internal checks
-
- // load table header and validate it
- // During this call the @tableContext.out will be initialized
- if( 1 != ACMClass->methods.xThermo.getPointsPhase( pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- // failed
- errCode = ERROR_GPIB_THERMDATA_NOT_FOUND;
-
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // ok, now @tableContext is initialized
- // Let's initialize the rest variables
- tableContext.in.nStartPoint = 0; // starting point = 0
- tableContext.in.pDataArray = dbPointsBuffer; // initialize the temporary buffer
- tableContext.in.nCount = 0; // zero yet, see below
- }
- // 3
- else
- {
- // load previous context
- size_t bytes;
-
- if( queue_get( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid), &bytes ) // load port combination id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid), &bytes ) // load port state id
- && queue_get( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext), &bytes ) // load table context
- )
- {
- // OK
-
- // Note:
- // @tableContext.out.nPoints is remembered, amount of points
- // @tableContext.in.nStartPoint is remembered, starting point (the next after the lastest processed)
- }
- else
- {
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- }
-
- rc = 0;
- // 4
- {
- size_t nPoints = tableContext.out.nPoints; // amount of points in the table
- size_t nStart = tableContext.in.nStartPoint; // starting point
-
- // do until all the points are processed
- while( nStart < nPoints )
- {
- // specify the number of points to retrieve: @tableContext.in.nCount
- // Note: @tableContext.out.nPoints and @tableContext.in.nStartPoint are
- // already specified or remembered
- size_t nStepPoints = (nPoints - nStart);
-
- // check the points number for the limit
- if( nStepPoints >= DBPOINTS_BUFFER_NUM )
- {
- tableContext.in.nCount = DBPOINTS_BUFFER_NUM; // (nPoints - nStart)
- }
- else
- {
- // not greater than it is required
- tableContext.in.nCount = nStepPoints;
- }
-
- // retrieve the points from the memory
- if( tableContext.in.nCount != ACMClass->methods.xThermo.getPointsPhase(
- pcid, // port combination
- psid, // port state
- &tableContext )
- )
- {
- // error
- // Strange... The table is already validated. Maybe, it is I/O error issue.
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
-
- switch( tableContext.svc.errCode )
- {
- case ERR_ACMGETPOINTS_INVAL : errCode = ERROR_GPIB_INVALID_PARAMETER; break;
- case ERR_ACMGETPOINTS_INVTBL: errCode = ERROR_GPIB_ARRAY_CORRUPTED; break;
- case ERR_ACMGETPOINTS_INVHDR: errCode = ERROR_GPIB_THERMDATA_NOT_FOUND; break;
- case ERR_ACMGETPOINTS_IO : errCode = ERROR_GPIB_INTERNAL; break;
- }
-
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- // Ok, the double-points are loaded...
- // Let's convert it!
- // @iPoint - just counts amount of converted points at this step.
- for( size_t iPoint = 0; iPoint < tableContext.in.nCount; ++iPoint )
- {
- // the point format is:
- // <Number>,<SPACE>
- // where <Number> is a number in scientific format
- // with 10 fractional digits. Let's leave 2 digits for the exponent,
- // and one number takes 16 characters, plus the separator and the space.
- // So one point takes (16+2) = 18 characters. To be in save we will
- // suppose the one point takes 24 characters.
- // e.g.
- // 1.0000000000e+5,
- if( freeSpace >= 24 )
- {
- size_t bytes = 0;
-
- // @dbPointsBuffer[iPoint] is one of points retrieved at this step.
-
- // Convert a phase
- bytes = GPIB_Double2Str( dbPointsBuffer[ iPoint ].phase, pBuffer, freeSpace, Format_Double2Str_Sci );
-
- if( 0 == bytes )
- {
- errCode = ERROR_GPIB_BUFFER_OVERFLOW;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // print the delimeter
- bytes = snprintf( pBuffer, freeSpace, "%s", ", " );
-
- pBuffer += bytes;
- freeSpace -= bytes;
- rc += bytes;
-
- // move to the next point in the table
- nStart++;
- }
- else
- {
- // not enough free space in the text buffer
-
- (void)tableContext.out.nPoints;
- tableContext.in.nStartPoint = nStart; // modify the starting point for the next call
- // --------------------------------------------------------------------------
- // Save context
- usbtmc_create_function_context( udi, (void*)GPIB_MemTableTherCorrPhase );
-
- if( !queue_add( &udi->GPIBFunctionContext.Context, (char*)&pcid , sizeof(pcid) ) // Save port combination id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&psid , sizeof(psid) ) // Save port state id
- || !queue_add( &udi->GPIBFunctionContext.Context, (char*)&tableContext , sizeof(tableContext) ) // Save table context
- )
- {
- udi->GPIBFunctionContext.LastFunction = NULL;
- errCode = ERROR_GPIB_INTERNAL;
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = FALSE;
- errCode = 0;
- // --------------------------------------------------------------------------
-
- goto L_GPIB_MemTableTherCorrPhase_EXIT;
- }
- } // for
-
- tableContext.in.nStartPoint = nStart; // modify the starting point
-
- } // while( nStart < nPoints )
-
- // Ok, all the points are converted here due to
- // otherwise, the program jumps to L_GPIB_MemTableTherCorrMagniture_EXIT label
- // after saving context.
- if( rc > 2 )
- {
- // cut off the last space and comma
- rc -= 2;
- }
- }
- // 5
- L_GPIB_MemTableTherCorrPhase_EXIT:
-
- if( 0 != errCode )
- {
- const char * pDescription = pcThermoDesc;
-
- if( ERROR_GPIB_ARRAY_CORRUPTED == errCode
- && ePortComb_MAX != pcid )
- {
- pDescription = aPortComb[ ((pcid - ePortComb_MIN)%ePortComb_MAX) ];
- }
-
- udi->BulkRespondStatus.bIsLastTransfer = TRUE;
-
- // 27/08/18
- // GPIB_RaiseStandartError( udi, errCode, pDescription, GPIB_ERROR_ID_COR | request );
- GPIB_RaiseStandartError( udi, errCode, pDescription, errClass_Autodetect );
-
- rc = 0;
- }
-
- return rc;
- }
- #endif
-
|