熱門(mén)
OpenHaptics編程環(huán)境搭建
SensAble Technologies(已被3Dsystems收購(gòu))公司是3D可觸摸(力反饋)解決方案和技術(shù)領(lǐng)域中的領(lǐng)先開(kāi)發(fā)商,,其解決方案和技術(shù)不僅使用戶(hù)能夠看到并聽(tīng)到屏幕計(jì)算機(jī)應(yīng)用,,還可以對(duì)該應(yīng)用進(jìn)行實(shí)際“感應(yīng)”。該公司的PHANTOM系列觸覺(jué)與力反饋交互設(shè)備能使用戶(hù)接觸并操作虛擬物體,。其觸覺(jué)技術(shù)廣泛應(yīng)用于諸多領(lǐng)域,,包括外科手術(shù)模擬、牙科整形,、虛擬裝配與虛擬維修,、3D 設(shè)計(jì)(藝術(shù)和雕塑),以及機(jī)器人遙操作等領(lǐng)域,。
使用官方提供的OpenHaptics Toolkit可以方便的編寫(xiě)基于Phantom觸覺(jué)力反饋設(shè)備的應(yīng)用程序,。OpenHaptics工具包包括QuickHaptics Micro API、Haptic Device API(HDAPI),、Haptic Library API (HLAPI),、PHANTOM Device Drivers(PDD)、實(shí)用工具和源代碼示例,。最底層的是PDD設(shè)備驅(qū)動(dòng)程序,,它支持公司所有系列的力反饋設(shè)備;HDAPI提供了一個(gè)底層接口,,通過(guò)它能直接產(chǎn)生反饋力以及獲取設(shè)備的狀態(tài)信息,;HLAPI則為熟悉OpenGL的編程人員提供了一個(gè)上層接口。
下面來(lái)搭建OpenHaptics的編程環(huán)境(Win7 64位系統(tǒng) + VS2013 + OpenHaptics 3.4.0),,先在這里下載設(shè)備驅(qū)動(dòng)程序和OpenHaptics Toolkit,。參考安裝手冊(cè)連接好電腦和Phantom設(shè)備后可以打開(kāi)官方自帶的Phantom Test程序進(jìn)行測(cè)試,驗(yàn)證設(shè)備是否連接成功,。
接下來(lái)使用HDAPI創(chuàng)建一個(gè)力反饋應(yīng)用程序(以examples\HD\console\HelloHapticDevice為例),,程序基本流程如下:
1. ?Initialize the device.
2. ?Create a scheduler callback.
3. ?Enable device forces.
4. ?Start the scheduler.
5. ?Cleanup the device and scheduler when the application is terminated.?
參考下面的程序結(jié)構(gòu)圖,為了實(shí)現(xiàn)流暢穩(wěn)定的觸覺(jué)力反饋,,創(chuàng)建的任務(wù)將以1000Hz的頻率運(yùn)行在優(yōu)先級(jí)高的線程中(The scheduler manages a high frequency, high priority thread for sending forces and retrieving state information from the device.?Typically, force updates need to be sent at 1000 Hz frequency in order to create compelling and stable force feedback):
下面配置VS工程:
1)設(shè)置頭文件包含目錄(Set the correct include path, as shown below in “Additional Include Directories.”)
Examples for setting include paths:
$(OH_SDK_BASE)\include ? ? ? ? ? ? ? ? ? ? Main include directory for the HD library.
$(OH_SDK_BASE)\utilities\include ? ? ? ? Include directory for utilities.
2)添加庫(kù)文件(Add the appropriate library modules as shown below in “Additional Dependencies”)
3)設(shè)置附加庫(kù)目錄(Make sure the linker paths are set correctly on the “Additional Library Directories” line so that the library fles can be found whenyour application links)
As for the header fle include paths, the library directories will use the OH_SDK_BASE environment variable. In general VisualStudio?will automatically set the PlatformName to be one of Win32 or x64 and the ConfgurationName to be either Release or Debug.?
配置好工程屬性后就可以點(diǎn)擊生成按鈕,,不過(guò)生成過(guò)程中出現(xiàn)了“error LNK2019:無(wú)法解析的外部符號(hào)”這種錯(cuò)誤(很多人遇到過(guò)這個(gè)問(wèn)題):
在網(wǎng)上搜索解決方案,3DSystems Haptics Forums上有一種辦法是將utilities中的lib文件重新編譯一遍,,源文件就在utilities/src中:
使用VS013重新生成Win32,、x64平臺(tái)下的Debug和Release版本的lib,然后將原先的替換掉,,再進(jìn)行編譯就OK了,。
下面看看HelloHapticDevice的代碼:
- /***************************************************************************** ?
- Description:? ?
- ?
- ??This?application?creates?a?gravity?well,?which?will?attract ?
- ??the?device?towards?its?center?when?the?device?enters?its?proximity.?? ?
- *******************************************************************************/?
- ?
- #include?<stdio.h> ?
- #include?<string.h> ?
- #include?<conio.h> ?
- ?
- #include?<HD/hd.h> ?
- #include?<HDU/hduError.h> ?
- #include?<HDU/hduVector.h> ?
- ?
- HDCallbackCode?HDCALLBACK?gravityWellCallback(void?*data); ?
- ?
- ?
- /*******************************************************************************
- ?Main?function. ?
- ?Initializes?the?device,?starts?the?schedule,?creates?a?schedule?callback ?
- ?to?handle?gravity?well?forces,?waits?for?the?user?to?press?a?button,?exits ?
- ?the?application. ?
- *******************************************************************************/?
- int?main(int?argc,?char*?argv[]) ?
- {???? ?
- ????HDErrorInfo?error; ?
- ????HDSchedulerHandle?hGravityWell; ?
- ?
- ????/*?Initialize?the?device,?must?be?done?before?attempting?to?call?any?hd?
- ???????functions.?Passing?in?HD_DEFAULT_DEVICE?causes?the?default?device?to?be? ?
- ???????initialized.?*/?
- ????HHD?hHD?=?hdInitDevice(HD_DEFAULT_DEVICE); ?
- ????if?(HD_DEVICE_ERROR(error?=?hdGetError()))? ?
- ????{ ?
- ????????hduPrintError(stderr,?&error,?"Failed?to?initialize?haptic?device"); ?
- ????????fprintf(stderr,?"\nPress?any?key?to?quit.\n"); ?
- ????????return?-1; ?
- ????} ?
- ?
- ????printf("Hello?Haptic?Device!\n"); ?
- ????printf("Found?device?model:?%s.\n\n",?hdGetString(HD_DEVICE_MODEL_TYPE)); ?
- ?
- ????/*?Schedule?the?main?callback?that?will?render?forces?to?the?device.?*/?
- ????hGravityWell?=?hdScheduleAsynchronous(gravityWellCallback,?0,?HD_MAX_SCHEDULER_PRIORITY); ?
- ?
- ????hdEnable(HD_FORCE_OUTPUT); ?
- ????hdStartScheduler(); ?
- ?
- ????/*?Check?for?errors?and?abort?if?so.?*/?
- ????if?(HD_DEVICE_ERROR(error?=?hdGetError())) ?
- ????{ ?
- ????????hduPrintError(stderr,?&error,?"Failed?to?start?scheduler"); ?
- ????????fprintf(stderr,?"\nPress?any?key?to?quit.\n"); ?
- ????????return?-1; ?
- ????} ?
- ?
- ????/*?Wait?until?the?user?presses?a?key.??Meanwhile,?the?scheduler
- ????runs?and?applies?forces?to?the?device.?*/?
- ????printf("Feel?around?for?the?gravity?well...\n"); ?
- ????printf("Press?any?key?to?quit.\n\n"); ?
- ????while?(!kbhit()) ?
- ????{ ?
- ????????/*?Periodically?check?if?the?gravity?well?callback?has?exited.?*/?
- ????????if?(!hdWaitForCompletion(hGravityWell,?HD_WAIT_CHECK_STATUS))??//?Checks?if?a?callback?is?still?scheduled?for?execution. ?
- ????????{ ?
- ????????????fprintf(stderr,?"Press?any?key?to?quit.\n");????? ?
- ????????????break; ?
- ????????} ?
- ????} ?
- ?
- ????/*?For?cleanup,?unschedule?callback?and?stop?the?scheduler.?*/?
- ????hdStopScheduler();??????????//?Typically?call?this?as?a?frst?step?for?cleanup?and?shutdown?of?devices ?
- ????hdUnschedule(hGravityWell);?//?removing?the?associated?callback?from?the?scheduler. ?
- ????hdDisableDevice(hHD);???????//?Disables?a?device.?The?handle?should?not?be?used?afterward ?
- ?
- ????return?0; ?
- } ?
- ?
- ?
- ?
- /*******************************************************************************
- ?Servo?callback.?? ?
- ?Called?every?servo?loop?tick.??Simulates?a?gravity?well,?which?sucks?the?device? ?
- ?towards?its?center?whenever?the?device?is?within?a?certain?range. ?
- *******************************************************************************/?
- HDCallbackCode?HDCALLBACK?gravityWellCallback(void?*data) ?
- { ?
- ????const?HDdouble?kStiffness?=?0.075;?/*?N/mm?*/?
- ????const?HDdouble?kGravityWellInfluence?=?40;?/*?mm?*/?
- ?
- ????/*?This?is?the?position?of?the?gravity?well?in?cartesian(i.e.?x,y,z)?space.?*/?
- ????static?const?hduVector3Dd?wellPos?=?{0,0,0}; ?
- ?
- ????HDErrorInfo?error; ?
- ????hduVector3Dd?position; ?
- ????hduVector3Dd?force; ?
- ????hduVector3Dd?positionTwell; ?
- ?
- ????HHD?hHD?=?hdGetCurrentDevice();??//?Gets?the?handle?of?the?current?device ?
- ?
- ????/*?Begin?haptics?frame.??(?In?general,?all?state-related?haptics?calls
- ???????should?be?made?within?a?frame.?)?*/?
- ????hdBeginFrame(hHD); ?
- ?
- ????/*?Get?the?current?position?of?the?device.?*/?
- ????hdGetDoublev(HD_CURRENT_POSITION,?position); ?
- ???? ?
- ????memset(force,?0,?sizeof(hduVector3Dd)); ?
- ???? ?
- ????/*?>??positionTwell?=?wellPos-position??<?
- ???????Create?a?vector?from?the?device?position?towards?the?gravity? ?
- ???????well's?center.?*/?
- ????hduVecSubtract(positionTwell,?wellPos,?position); ?
- ???? ?
- ????/*?If?the?device?position?is?within?some?distance?of?the?gravity?well's?
- ???????center,?apply?a?spring?force?towards?gravity?well's?center.??The?force ?
- ???????calculation?differs?from?a?traditional?gravitational?body?in?that?the ?
- ???????closer?the?device?is?to?the?center,?the?less?force?the?well?exerts; ?
- ???????the?device?behaves?as?if?a?spring?were?connected?between?itself?and ?
- ???????the?well's?center.?*/?
- ????if?(hduVecMagnitude(positionTwell)?<?kGravityWellInfluence) ?
- ????{ ?
- ????????/*?>??F?=?k?*?x??<?
- ???????????F:?Force?in?Newtons?(N) ?
- ???????????k:?Stiffness?of?the?well?(N/mm) ?
- ???????????x:?Vector?from?the?device?endpoint?position?to?the?center? ?
- ???????????of?the?well.?*/?
- ????????hduVecScale(force,?positionTwell,?kStiffness); ?
- ????} ?
- ?
- ????/*?Send?the?force?to?the?device.?*/?
- ????hdSetDoublev(HD_CURRENT_FORCE,?force); ?
- ???? ?
- ????/*?End?haptics?frame.?*/?
- ????hdEndFrame(hHD); ?
- ?
- ????/*?Check?for?errors?and?abort?the?callback?if?a?scheduler?error
- ???????is?detected.?*/?
- ????if?(HD_DEVICE_ERROR(error?=?hdGetError())) ?
- ????{ ?
- ????????hduPrintError(stderr,?&error,? ?
- ??????????????????????"Error?detected?while?rendering?gravity?well\n"); ?
- ???????? ?
- ????????if?(hduIsSchedulerError(&error)) ?
- ????????{ ?
- ????????????return?HD_CALLBACK_DONE; ?
- ????????} ?
- ????} ?
- ?
- ????/*?Signify?that?the?callback?should?continue?running,?i.e.?that
- ???????it?will?be?called?again?the?next?scheduler?tick.?*/?
- ????return?HD_CALLBACK_CONTINUE; ?
- }?
?
該程序在循環(huán)執(zhí)行的任務(wù)中實(shí)時(shí)獲取操作手柄的位置信息,并以此來(lái)計(jì)算輸出力來(lái)模擬彈簧力,。這里有幾個(gè)需要注意的地方:
1. Haptic Frames:
為了保證數(shù)據(jù)訪問(wèn)的一致性,OpenHaptics提供了一種Frame框架結(jié)構(gòu),反饋給用戶(hù)力的過(guò)程一般都是在力反饋幀中處理的,,使用hdBeginFrame和hdEndFrame作為訪問(wèn)的開(kāi)始和結(jié)束,。在同一幀中多次調(diào)用hdGet類(lèi)函數(shù)獲取信息會(huì)得到相同的結(jié)果;多次調(diào)用hdSet類(lèi)函數(shù)設(shè)置同一狀態(tài),,則最后的調(diào)用會(huì)替代掉以前的(Forces are not actually sent to the device until the end of the frame. Setting the same state twice will replace the frst with the?second),。即在幀的結(jié)尾,所有的屬性改變才會(huì)得以應(yīng)用,。
Haptic frames defne a scope within which the device state is guaranteed to be consistent. Frames are bracketed by?hdBeginFrame()?and?hdEndFrame()?statements. At the start of the frame, the device state is updated and stored for use in that frame so that?all state?queries in the frame re?ects a snapshot of that data. At the end of the frame, new state such as forces is written out to the device .?Most haptics operations should be run within a frame. Calling operations within a frame ensures consistency for the data being used?because state remains the same within the frame. Getting state outside a frame typically returns the state from the last frame.?Setting?state outside a frame typically results in an error.
HDAPI力反饋程序框架如下圖所示:
2. 同步調(diào)用與異步調(diào)用:
所謂同步就是在發(fā)出一個(gè)“調(diào)用”時(shí),,在沒(méi)有得到結(jié)果之前,該“調(diào)用”就不返回,;而異步則是相反,,“調(diào)用”在發(fā)出之后這個(gè)調(diào)用就直接返回了,即當(dāng)一個(gè)異步過(guò)程調(diào)用發(fā)出后,,調(diào)用者不會(huì)立刻得到結(jié)果,。Synchronous calls only return after they are completed, so?the application thread waits for a synchronous call before continuing. Asynchronous calls return immediately after being scheduled.?
同步調(diào)用主要用于獲取設(shè)備當(dāng)前狀態(tài),比如位置,、力,、開(kāi)關(guān)狀態(tài)等。Synchronous calls are primarily used for getting a snapshot of the state of the scheduler for the application. For example, if the?application needs to query position or button state, or any other variable or state that the scheduler is changing, it should do so using a?synchronous call.
下面是同步調(diào)用的一個(gè)例子:
- //?client?data?declaration ?
- struct?DeviceDisplayState ?
- { ?
- ????HDdouble?position[3]; ?
- ????HDdouble?force[3]; ?
- }? ?
- ?
- //?usage?of?the?above?client?data,?within?a?simple?callback. ?
- HDCallbackCode?HDCALLBACK?DeviceStateCallback(void?*pUserData)? ?
- { ?
- ????DeviceDisplayState?*pDisplayState?=?(DeviceDisplayState?*)pUserData; ?
- ???? ?
- ????hdGetDoublev(HD_CURRENT_POSITION,?pDisplayState->position); ?
- ????hdGetDoublev(HD_CURRENT_FORCE,????pDisplayState->force); ?
- ???? ?
- ????return?HD_CALLBACK_DONE;??//?execute?this?only?once ?
- }? ?
- ?
- ?
- //?get?the?current?position?of?end-effector ?
- DeviceDisplayState?state; ?
- ?
- hdScheduleSynchronous(DeviceStateCallback,?&state,?HD_MIN_SCHEDULER_PRIORITY);?
?
異步調(diào)用主要用于循環(huán)處理任務(wù)中,,例如根據(jù)力反饋設(shè)備操作末端的位置來(lái)計(jì)算并輸出力,。Asynchronous calls are often the best mechanism for managing the haptics loop. For example, an asynchronous callback can persist in?the scheduler to represent a haptics effect: during each iteration, the callback applies the effect to the device.?
- HDCallbackCode?HDCALLBACK?CoulombCallback(void?*data) ?
- { ?
- ????HHD?hHD?=?hdGetCurrentDevice(); ?
- ???? ?
- ????hdBeginFrame(hHD); ?
- ???? ?
- ????HDdouble?pos[3]; ?
- ????hdGetDoublev(HD_CURRENT_POSITION,?pos);?//retrieve?the?position?of?the?end-effector. ?
- ???? ?
- ????HDdouble?force[3]; ?
- ????forceField(pos,?force);?????????????????//?given?the?position,?calculate?a?force ?
- ????hdSetDoublev(HD_CURRENT_FORCE,?force);??//?set?the?force?to?the?device ?
- ???? ?
- ????hdEndFrame(hHD);????????????????????????//??ush?the?force ?
- ???? ?
- ????return?HD_CALLBACK_CONTINUE;????????????//?run?at?every?servo?loop?tick. ?
- } ?
- ?
- hdScheduleAsynchronous(AForceSettingCallback,?0,?HD_DEFAULT_SCHEDULER_PRIORITY);?
?
3. 任務(wù)返回值:
?HD_CALLBACK_DONE (只執(zhí)行一次)
?HD_CALLBACK_CONTINUE(循環(huán)執(zhí)行)
根據(jù)不同的返回值,回調(diào)函數(shù)會(huì)在當(dāng)前幀運(yùn)行完畢后判斷是否在下一幀再次運(yùn) 行,,當(dāng)返回值為HD_CALLBACK_CONTINUE時(shí),,此回調(diào)函數(shù)在下一幀時(shí)會(huì)繼續(xù)重新 運(yùn)行;而當(dāng)返回值為HD_CALLBACK_DONE?時(shí),,此回調(diào)函數(shù)在下一幀時(shí)不再次運(yùn)行,。Callbacks can be set to run either once or multiple times, depending on the callback’s return value. If the return value requests for?the callback to continue, it is rescheduled and run again during the next scheduler tick. Otherwise it is taken off the scheduler and?considered complete, and control is returned to the calling thread in the case of synchronous operations.
4. 任務(wù)優(yōu)先級(jí):
Callbacks are scheduled with a priority, which determines what order they are run in the scheduler.?For every scheduler tick, each?callback is always executed. The order the callbacks are executed depends on the priority;?highest priority items are run before lowest.?Operations with equal priority are executed in arbitrary order.?
下面再看一個(gè)獲取設(shè)備信息的典型例子(examples\HD\console\QueryDevice):
- #include?<stdio.h> ?
- #include?<string.h> ?
- #include?<conio.h> ?
- ?
- #include?<HD/hd.h> ?
- #include?<HDU/hduError.h> ?
- #include?<HDU/hduVector.h> ?
- ?
- /*?Holds?data?retrieved?from?HDAPI.?*/?
- typedef?struct?
- { ?
- ????HDboolean?m_buttonState;???????/*?Has?the?device?button?has?been?pressed.?*/?
- ????hduVector3Dd?m_devicePosition;?/*?Current?device?coordinates.?*/?
- ????HDErrorInfo?m_error; ?
- }?DeviceData; ?
- ?
- static?DeviceData?gServoDeviceData; ?
- ?
- /*******************************************************************************
- Checks?the?state?of?the?gimbal?button?and?gets?the?position?of?the?device. ?
- *******************************************************************************/?
- HDCallbackCode?HDCALLBACK?updateDeviceCallback(void?*pUserData) ?
- { ?
- ????int?nButtons?=?0; ?
- ?
- ????hdBeginFrame(hdGetCurrentDevice()); ?
- ?
- ????/*?Retrieve?the?current?button(s).?*/?
- ????hdGetIntegerv(HD_CURRENT_BUTTONS,?&nButtons); ?
- ?
- ????/*?In?order?to?get?the?specific?button?1?state,?we?use?a?bitmask?to
- ????test?for?the?HD_DEVICE_BUTTON_1?bit.?*/?
- ????gServoDeviceData.m_buttonState?= ?
- ????????(nButtons?&?HD_DEVICE_BUTTON_1)???HD_TRUE?:?HD_FALSE; ?
- ?
- ????/*?Get?the?current?location?of?the?device?(HD_GET_CURRENT_POSITION)
- ????We?declare?a?vector?of?three?doubles?since?hdGetDoublev?returns ?
- ????the?information?in?a?vector?of?size?3.?*/?
- ????hdGetDoublev(HD_CURRENT_POSITION,?gServoDeviceData.m_devicePosition); ?
- ?
- ????/*?Also?check?the?error?state?of?HDAPI.?*/?
- ????gServoDeviceData.m_error?=?hdGetError(); ?
- ?
- ????/*?Copy?the?position?into?our?device_data?tructure.?*/?
- ????hdEndFrame(hdGetCurrentDevice()); ?
- ?
- ????return?HD_CALLBACK_CONTINUE; ?
- } ?
- ?
- ?
- /*******************************************************************************
- Checks?the?state?of?the?gimbal?button?and?gets?the?position?of?the?device. ?
- *******************************************************************************/?
- HDCallbackCode?HDCALLBACK?copyDeviceDataCallback(void?*pUserData) ?
- { ?
- ????DeviceData?*pDeviceData?=?(DeviceData?*)pUserData; ?
- ?
- ????//?void?*memcpy(void?*dest,?const?void?*src,?size_t?n); ?
- ????memcpy(pDeviceData,?&gServoDeviceData,?sizeof(DeviceData));?? ?
- ?
- ????return?HD_CALLBACK_DONE; ?
- } ?
- ?
- ?
- /*******************************************************************************
- Prints?out?a?help?string?about?using?this?example. ?
- *******************************************************************************/?
- void?printHelp(void) ?
- { ?
- ????static?const?char?help[]?=?{?"\ ?
- ?????????????????????????????????Press?and?release?the?stylus?button?to?print?out?the?current?device?location.\n\ ?
- ?????????????????????????????????Press?and?hold?the?stylus?button?to?exit?the?application\n"?}; ?
- ?
- ????fprintf(stdout,?"%s\n",?help); ?
- } ?
- ?
- ?
- /*******************************************************************************
- This?routine?allows?the?device?to?provide?information?about?the?current ?
- location?of?the?stylus,?and?contains?a?mechanism?for?terminating?the ?
- application. ?
- Pressing?the?button?causes?the?application?to?display?the?current?location ?
- of?the?device. ?
- Holding?the?button?down?for?N?iterations?causes?the?application?to?exit. ?
- *******************************************************************************/?
- void?mainLoop(void) ?
- { ?
- ????static?const?int?kTerminateCount?=?1000; ?
- ????int?buttonHoldCount?=?0; ?
- ?
- ????/*?Instantiate?the?structure?used?to?capture?data?from?the?device.?*/?
- ????DeviceData?currentData; ?
- ????DeviceData?prevData; ?
- ?
- ????/*?Perform?a?synchronous?call?to?copy?the?most?current?device?state.?*/?
- ????hdScheduleSynchronous(copyDeviceDataCallback, ?
- ????????¤tData,?HD_MIN_SCHEDULER_PRIORITY); ?
- ?
- ????memcpy(&prevData,?¤tData,?sizeof(DeviceData)); ?
- ?
- ????printHelp(); ?
- ?
- ????/*?Run?the?main?loop?until?the?gimbal?button?is?held.?*/?
- ????while?(1) ?
- ????{ ?
- ????????/*?Perform?a?synchronous?call?to?copy?the?most?current?device?state.
- ????????This?synchronous?scheduler?call?ensures?that?the?device?state ?
- ????????is?obtained?in?a?thread-safe?manner.?*/?
- ????????hdScheduleSynchronous(copyDeviceDataCallback, ?
- ????????????¤tData, ?
- ????????????HD_MIN_SCHEDULER_PRIORITY); ?
- ?
- ????????/*?If?the?user?depresses?the?gimbal?button,?display?the?current
- ????????location?information.?*/?
- ????????if?(currentData.m_buttonState?&&?!prevData.m_buttonState) ?
- ????????{ ?
- ????????????fprintf(stdout,?"Current?position:?(%g,?%g,?%g)\n", ?
- ????????????????currentData.m_devicePosition[0], ?
- ????????????????currentData.m_devicePosition[1], ?
- ????????????????currentData.m_devicePosition[2]); ?
- ????????} ?
- ????????else?if?(currentData.m_buttonState?&&?prevData.m_buttonState) ?
- ????????{ ?
- ????????????/*?Keep?track?of?how?long?the?user?has?been?pressing?the?button.
- ????????????If?this?exceeds?N?ticks,?then?terminate?the?application.?*/?
- ????????????buttonHoldCount++; ?
- ?
- ????????????if?(buttonHoldCount?>?kTerminateCount) ?
- ????????????{ ?
- ????????????????/*?Quit,?since?the?user?held?the?button?longer?than
- ????????????????the?terminate?count.?*/?
- ????????????????break; ?
- ????????????} ?
- ????????} ?
- ????????else?if?(!currentData.m_buttonState?&&?prevData.m_buttonState) ?
- ????????{ ?
- ????????????/*?Reset?the?button?hold?count,?since?the?user?stopped?holding
- ????????????down?the?stylus?button.?*/?
- ????????????buttonHoldCount?=?0; ?
- ????????} ?
- ?
- ?
- ????????/*?Check?if?an?error?occurred.?*/?
- ????????if?(HD_DEVICE_ERROR(currentData.m_error)) ?
- ????????{ ?
- ????????????hduPrintError(stderr,?¤tData.m_error,?"Device?error?detected"); ?
- ?
- ????????????if?(hduIsSchedulerError(¤tData.m_error)) ?
- ????????????{ ?
- ????????????????/*?Quit,?since?communication?with?the?device?was?disrupted.?*/?
- ????????????????fprintf(stderr,?"\nPress?any?key?to?quit.\n"); ?
- ????????????????break; ?
- ????????????} ?
- ????????} ?
- ?
- ????????/*?Store?off?the?current?data?for?the?next?loop.?*/?
- ????????memcpy(&prevData,?¤tData,?sizeof(DeviceData)); ?
- ????} ?
- } ?
- ?
- /*******************************************************************************
- Main?function. ?
- Sets?up?the?device,?runs?main?application?loop,?cleans?up?when?finished. ?
- *******************************************************************************/?
- int?main(int?argc,?char*?argv[]) ?
- { ?
- ????HDSchedulerHandle?hUpdateHandle?=?0; ?
- ????HDErrorInfo?error; ?
- ?
- ????/*?Initialize?the?device,?must?be?done?before?attempting?to?call?any?hd
- ????functions.?*/?
- ????HHD?hHD?=?hdInitDevice(HD_DEFAULT_DEVICE); ?
- ????if?(HD_DEVICE_ERROR(error?=?hdGetError())) ?
- ????{ ?
- ????????hduPrintError(stderr,?&error,?"Failed?to?initialize?the?device"); ?
- ????????fprintf(stderr,?"\nPress?any?key?to?quit.\n"); ?
- ????????return?-1; ?
- ????} ?
- ?
- ????/*?Schedule?the?main?scheduler?callback?that?updates?the?device?state.?*/?
- ????hUpdateHandle?=?hdScheduleAsynchronous( ?
- ????????updateDeviceCallback,?0,?HD_MAX_SCHEDULER_PRIORITY); ?
- ?
- ????/*?Start?the?servo?loop?scheduler.?*/?
- ????hdStartScheduler(); ?
- ????if?(HD_DEVICE_ERROR(error?=?hdGetError())) ?
- ????{ ?
- ????????hduPrintError(stderr,?&error,?"Failed?to?start?the?scheduler"); ?
- ????????fprintf(stderr,?"\nPress?any?key?to?quit.\n"); ?
- ????????return?-1; ?
- ????} ?
- ?
- ????/*?Run?the?application?loop.?*/?
- ????mainLoop(); ?
- ?
- ????/*?For?cleanup,?unschedule?callbacks?and?stop?the?servo?loop.?*/?
- ????hdStopScheduler(); ?
- ????hdUnschedule(hUpdateHandle); ?
- ????hdDisableDevice(hHD); ?
- ?
- ????return?0; ?
- }?
主函數(shù)中開(kāi)啟updateDeviceCallback異步任務(wù)后,該任務(wù)不停地刷新設(shè)備末端的位置以及按鈕狀態(tài)等信息,,保存在靜態(tài)全局變量gServoDeviceData中,。在主程序的mainLoop循環(huán)中使用copyDeviceDataCallback同步調(diào)用方式獲取設(shè)備狀態(tài)信息,然后進(jìn)行判斷,。按一下操作手柄上的按鈕打印一條當(dāng)前位置信息,;長(zhǎng)按按鈕超過(guò)一定時(shí)間則退出mainLoop循環(huán),結(jié)束程序,。
值得注意的是主線程中函數(shù)獲取Servo Loop線程(任務(wù)線程)中的數(shù)據(jù),,可以通過(guò)同步調(diào)用來(lái)實(shí)現(xiàn),是一種線程安全(thread-safe)方式,。線程安全就是多線程訪問(wèn)時(shí),,采用了加鎖機(jī)制,,當(dāng)一個(gè)線程訪問(wèn)該類(lèi)的某個(gè)數(shù)據(jù)時(shí),進(jìn)行保護(hù),,其他線程不能進(jìn)行訪問(wèn)直到該線程讀取完,,其他線程才可使用。hdScheduleSynchronous:Typically used as a synchronization mechanism between the servo loop thread and other threads in the application. For example,?if the main application thread needs to access the position or?button state, it can do so through a synchronous scheduler call. Can be used for synchronously?copying state from the servo loop.
在mainLoop函數(shù)中也可以直接訪問(wèn)全局變量gServoDeviceData來(lái)獲取設(shè)備信息,,但這種方式是線程不安全的,,即不提供數(shù)據(jù)訪問(wèn)保護(hù),有可能出現(xiàn)多個(gè)線程先后更改數(shù)據(jù)造成所得到的數(shù)據(jù)是臟數(shù)據(jù),。如果其他線程企圖訪問(wèn)一個(gè)處于不可用狀態(tài)的對(duì)象,,該對(duì)象將不能正確響應(yīng)從而產(chǎn)生無(wú)法預(yù)料的結(jié)果,如何避免這種情況發(fā)生是線程安全性的核心問(wèn)題,。
電話:010-50951355 傳真:010-50951352 郵箱:[email protected] ,;點(diǎn)擊查看區(qū)域負(fù)責(zé)人電話
手機(jī):13811546370 / 13720091697 / 13720096040 / 13811548270 /
13811981522 / 18600440988 /13810279720 /13581546145