antfs_host_channel.cpp 218 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879
  1. /*
  2. This software is subject to the license described in the License.txt file
  3. included with this software distribution. You may not use this file except in compliance
  4. with this license.
  5. Copyright (c) Dynastream Innovations Inc. 2014
  6. All rights reserved.
  7. */
  8. #include "types.h"
  9. #include "dsi_framer_ant.hpp"
  10. #include "dsi_serial_generic.hpp"
  11. #include "dsi_thread.h"
  12. #include "dsi_timer.hpp"
  13. #include "dsi_convert.h"
  14. #include "crc.h"
  15. #include "antfs_host_channel.hpp"
  16. #include "antfsmessage.h"
  17. #include "config.h"
  18. #include "dsi_debug.hpp"
  19. #if defined(DEBUG_FILE)
  20. #include "macros.h"
  21. #endif
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <time.h>
  26. //////////////////////////////////////////////////////////////////////////////////
  27. // Private Definitions
  28. //////////////////////////////////////////////////////////////////////////////////
  29. #define TRANSPORT_NETWORK ((UCHAR) 0)
  30. #define TRANSPORT_MESSAGE_PERIOD ((USHORT) 4096) // 8Hz default
  31. #define TRANSPORT_MESSAGE_PERIOD_CODE ((UCHAR) 4) // 8Hz default
  32. #define TRANSPORT_SEARCH_TIMEOUT ((UCHAR) 3) // ~7.5 Seconds.
  33. #define HOST_SERIAL_NUMBER ((ULONG) 1) // Use if not configured otherwise
  34. #define UPLOAD_PROGRESS_CHECK_BYTES ((ULONG) 64) // 64 bytes (8 packets) have to be transfered in order to reset the UL loop timeout.
  35. #define ADDRESS_TYPE_PAGE_OFFSET 3
  36. #define ADDRESS_TYPE_PAGE_SMALL_0 ((UCHAR) 0x00) // Default; page contains both data offset and data block size.
  37. #define ADDRESS_TYPE_PAGE_SMALL_1 ((UCHAR) 0x01) // Contains total remaining data length (in response)
  38. #define ADDRESS_TYPE_PAGE_BIG_0 ((UCHAR) 0x02) // Page contains data offset.
  39. #define ADDRESS_TYPE_PAGE_BIG_1 ((UCHAR) 0x03) // Page contains data block size.
  40. #define ADDRESS_TYPE_PAGE_BIG_2 ((UCHAR) 0x04) // Page contains total remaining data length (in response)
  41. #define DATA_OFFSET_OFFSET_LOW 4
  42. #define DATA_OFFSET_OFFSET_HIGH 5
  43. #define DATA_BLOCK_SIZE_OFFSET_LOW 6
  44. #define DATA_BLOCK_SIZE_OFFSET_HIGH 7
  45. // ID Command
  46. #define ID_OFFSET_0 4
  47. #define ID_OFFSET_1 5
  48. #define ID_OFFSET_2 6
  49. #define ID_OFFSET_3 7
  50. #define ANTFS_RESPONSE_RETRIES 5
  51. #define SEND_DIRECT_BURST_TIMEOUT 15000 // 15 seconds.
  52. #define STRIKE_COUNT 2
  53. #define MAX_STALE_COUNT ((UCHAR) 100)
  54. #define MAJOR_STALE_COUNT ((UCHAR) 50)
  55. #define MINOR_STALE_COUNT ((UCHAR) 25)
  56. #define MIN_STALE_COUNT ((UCHAR) 1)
  57. typedef void (*CALLBACK_T)(void);
  58. static const UCHAR caucNetworkKey[] = NETWORK_KEY;
  59. static const char acSwVersion[] = SW_VER;
  60. //////////////////////////////////////////////////////////////////////////////////
  61. // Private Function Prototypes
  62. //////////////////////////////////////////////////////////////////////////////////
  63. static int ListCompare(const void *puvKeyVal, const void *puvDatum);
  64. static int DeviceParametersItemCompare(const void *pvItem1, const void *pvItem2);
  65. //////////////////////////////////////////////////////////////////////////////////
  66. // Public Functions
  67. //////////////////////////////////////////////////////////////////////////////////
  68. ANTFSHostChannel::ANTFSHostChannel()
  69. {
  70. bInitFailed = FALSE;
  71. bIgnoreListRunning = FALSE;
  72. bPingEnabled = FALSE;
  73. bRequestPageEnabled = FALSE;
  74. // Default channel configuration
  75. ucChannelNumber = ANTFS_CHANNEL;
  76. ucNetworkNumber = ANTFS_NETWORK;
  77. ucTheDeviceType = ANTFS_DEVICE_TYPE;
  78. ucTheTransmissionType = ANTFS_TRANSMISSION_TYPE;
  79. usTheMessagePeriod = ANTFS_MESSAGE_PERIOD;
  80. ucTheProxThreshold = 0; //0=Disabled
  81. memcpy(aucTheNetworkkey,caucNetworkKey,8);
  82. // Host configuration
  83. ulHostSerialNumber = HOST_SERIAL_NUMBER;
  84. hANTFSThread = (DSI_THREAD_ID)NULL; // Handle for the ANTFS thread
  85. bKillThread = FALSE;
  86. bANTFSThreadRunning = FALSE;
  87. pclANT = (DSIFramerANT*) NULL;
  88. pbCancel = &bCancel;
  89. *pbCancel = FALSE;
  90. // Ignore List variables
  91. usListIndex = 0;
  92. memset(astIgnoreList, 0, sizeof(astIgnoreList));
  93. pclQueueTimer = (DSITimer*)NULL;
  94. ucTransportFrequencyStaleCount = 0;
  95. ucCurrentTransportFreqElement = 0;
  96. memset(aucFrequencyTable, 0, sizeof(aucFrequencyTable));
  97. memset(asDeviceParametersList, 0, sizeof(asDeviceParametersList));
  98. usDeviceListSize = 0;
  99. eANTFSState = ANTFS_HOST_STATE_OFF;
  100. ResetHostState();
  101. // Debugging is initialized by DSIANTDevice (or ANTDevice in Managed Lib)
  102. if (DSIThread_MutexInit(&stMutexCriticalSection) != DSI_THREAD_ENONE)
  103. {
  104. bInitFailed = TRUE;
  105. }
  106. if (DSIThread_MutexInit(&stMutexResponseQueue) != DSI_THREAD_ENONE)
  107. {
  108. bInitFailed = TRUE;
  109. }
  110. if (DSIThread_CondInit(&stCondANTFSThreadExit) != DSI_THREAD_ENONE)
  111. {
  112. bInitFailed = TRUE;
  113. }
  114. if (DSIThread_CondInit(&stCondRequest) != DSI_THREAD_ENONE)
  115. {
  116. bInitFailed = TRUE;
  117. }
  118. if (DSIThread_CondInit(&stCondRxEvent) != DSI_THREAD_ENONE)
  119. {
  120. bInitFailed = TRUE;
  121. }
  122. if (DSIThread_CondInit(&stCondWaitForResponse) != DSI_THREAD_ENONE)
  123. {
  124. bInitFailed = TRUE;
  125. }
  126. //If the init fails, something is broken and nothing is going to work anyway
  127. //additionally the logging isn't even setup at this point
  128. //so we throw an exception so we know something is broken right away
  129. if(bInitFailed == TRUE)
  130. throw "ANTFS constructor: init failed";
  131. }
  132. ///////////////////////////////////////////////////////////////////////
  133. ANTFSHostChannel::~ANTFSHostChannel()
  134. {
  135. this->Close();
  136. if (bInitFailed == FALSE)
  137. {
  138. DSIThread_MutexDestroy(&stMutexCriticalSection);
  139. DSIThread_MutexDestroy(&stMutexResponseQueue);
  140. DSIThread_CondDestroy(&stCondANTFSThreadExit);
  141. DSIThread_CondDestroy(&stCondRequest);
  142. DSIThread_CondDestroy(&stCondRxEvent);
  143. DSIThread_CondDestroy(&stCondWaitForResponse);
  144. }
  145. }
  146. ///////////////////////////////////////////////////////////////////////
  147. UCHAR ANTFSHostChannel::GetVersion(UCHAR *pucVersionString_, UCHAR ucBufferSize_)
  148. {
  149. ucBufferSize_--; // Allow for NULL cstring termination.
  150. if (ucBufferSize_ > sizeof(acSwVersion))
  151. ucBufferSize_ = sizeof(acSwVersion);
  152. memcpy(pucVersionString_, acSwVersion, ucBufferSize_);
  153. pucVersionString_[ucBufferSize_++] = '\0'; // Terminate the string and increment the size.
  154. return ucBufferSize_; // Return the string size, including the terminator.
  155. }
  156. ///////////////////////////////////////////////////////////////////////
  157. BOOL ANTFSHostChannel::Init(DSIFramerANT* pclANT_, UCHAR ucChannel_)
  158. {
  159. if (bInitFailed == TRUE)
  160. {
  161. #if defined(DEBUG_FILE)
  162. DSIDebug::ThreadWrite("ANTFSHostChannel::Init(): bInitFailed == TRUE");
  163. #endif
  164. return FALSE;
  165. }
  166. ucChannelNumber = ucChannel_;
  167. pclANT = pclANT_;
  168. if(pclANT)
  169. {
  170. if(pclANT->GetCancelParameter() == (BOOL*) NULL) // If cancel parameter has not been configured in framer, use internal
  171. pclANT->SetCancelParameter(pbCancel);
  172. else // Use cancel parameter configured in framer
  173. pbCancel = pclANT->GetCancelParameter();
  174. }
  175. return ReInitDevice();
  176. }
  177. ///////////////////////////////////////////////////////////////////////
  178. void ANTFSHostChannel::SetChannelID(UCHAR ucDeviceType_, UCHAR ucTransmissionType_)
  179. {
  180. ucTheDeviceType = ucDeviceType_;
  181. ucTheTransmissionType = ucTransmissionType_;
  182. }
  183. ///////////////////////////////////////////////////////////////////////
  184. void ANTFSHostChannel::SetChannelPeriod(USHORT usChannelPeriod_)
  185. {
  186. usTheMessagePeriod = usChannelPeriod_;
  187. }
  188. ///////////////////////////////////////////////////////////////////////
  189. void ANTFSHostChannel::SetNetworkKey(UCHAR ucNetwork_, UCHAR ucNetworkkey[])
  190. {
  191. ucNetworkNumber = ucNetwork_;
  192. memcpy(aucTheNetworkkey,ucNetworkkey,8);
  193. }
  194. ///////////////////////////////////////////////////////////////////////
  195. void ANTFSHostChannel::SetProximitySearch(UCHAR ucSearchThreshold_)
  196. {
  197. if(ucSearchThreshold_ > 10) //Depending on device higher thresholds can be ignored, cause undefined consequences, or even have different functionality assigned to them, so we cap at the valid 0-10 range
  198. {
  199. #if defined(DEBUG_FILE)
  200. DSIDebug::ThreadWrite("ANTFSHostChannel::SetProximitySearch(): User threshold value > 10, setting to max 10.");
  201. #endif
  202. ucSearchThreshold_ = 10;
  203. }
  204. ucTheProxThreshold = ucSearchThreshold_;
  205. }
  206. ///////////////////////////////////////////////////////////////////////
  207. void ANTFSHostChannel::SetSerialNumber(ULONG ulSerialNumber_)
  208. {
  209. ulHostSerialNumber = ulSerialNumber_;
  210. }
  211. ///////////////////////////////////////////////////////////////////////
  212. BOOL ANTFSHostChannel::GetEnabled()
  213. {
  214. if(eANTFSState < ANTFS_HOST_STATE_DISCONNECTING)
  215. {
  216. return FALSE;
  217. }
  218. return TRUE;
  219. }
  220. ///////////////////////////////////////////////////////////////////////
  221. ANTFS_HOST_STATE ANTFSHostChannel::GetStatus(void)
  222. {
  223. return eANTFSState;
  224. }
  225. ///////////////////////////////////////////////////////////////////////
  226. void ANTFSHostChannel::Close(void)
  227. {
  228. #if defined(DEBUG_FILE)
  229. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Closing ANTFS...");
  230. #endif
  231. DSIThread_MutexLock(&stMutexCriticalSection);
  232. // Stop the threads.
  233. bKillThread = TRUE;
  234. *pbCancel = TRUE;
  235. #if defined(DEBUG_FILE)
  236. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): SetEvent(stCondWaitForResponse).");
  237. #endif
  238. DSIThread_MutexLock(&stMutexResponseQueue);
  239. DSIThread_CondSignal(&stCondWaitForResponse);
  240. clResponseQueue.Clear();
  241. DSIThread_MutexUnlock(&stMutexResponseQueue);
  242. if (hANTFSThread)
  243. {
  244. if (bANTFSThreadRunning == TRUE)
  245. {
  246. #if defined(DEBUG_FILE)
  247. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): SetEvent(stCondRequest).");
  248. #endif
  249. DSIThread_CondSignal(&stCondRequest);
  250. #if defined(DEBUG_FILE)
  251. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): SetEvent(stCondRxEvent).");
  252. #endif
  253. DSIThread_CondSignal(&stCondRxEvent);
  254. #if defined(DEBUG_FILE)
  255. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Killing thread.");
  256. #endif
  257. if (DSIThread_CondTimedWait(&stCondANTFSThreadExit, &stMutexCriticalSection, 9000) != DSI_THREAD_ENONE)
  258. {
  259. #if defined(DEBUG_FILE)
  260. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Thread not dead.");
  261. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Forcing thread termination...");
  262. #endif
  263. DSIThread_DestroyThread(hANTFSThread);
  264. }
  265. else
  266. {
  267. #if defined(DEBUG_FILE)
  268. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Thread terminated successfully.");
  269. #endif
  270. }
  271. }
  272. DSIThread_ReleaseThreadID(hANTFSThread);
  273. hANTFSThread = (DSI_THREAD_ID)NULL;
  274. }
  275. DSIThread_MutexUnlock(&stMutexCriticalSection);
  276. if (bIgnoreListRunning)
  277. {
  278. #if defined(DEBUG_FILE)
  279. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Deleting Timer Queue Timer...");
  280. #endif
  281. delete pclQueueTimer;
  282. pclQueueTimer = (DSITimer*)NULL;
  283. DSIThread_MutexDestroy(&stMutexIgnoreListAccess);
  284. #if defined(DEBUG_FILE)
  285. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Deleted Timer Queue Timer.");
  286. #endif
  287. bIgnoreListRunning = FALSE;
  288. }
  289. eANTFSState = ANTFS_HOST_STATE_OFF;
  290. #if defined(DEBUG_FILE)
  291. DSIDebug::ThreadWrite("ANTFSHostChannel::Close(): Closed.");
  292. #endif
  293. if (pucTransferBufferDynamic)
  294. {
  295. if (pucTransferBuffer == pucTransferBufferDynamic)
  296. pucTransferBuffer = (UCHAR*)NULL;
  297. delete[] pucTransferBufferDynamic;
  298. pucTransferBufferDynamic = (UCHAR*)NULL;
  299. }
  300. }
  301. ///////////////////////////////////////////////////////////////////////
  302. void ANTFSHostChannel::Cancel(void)
  303. {
  304. DSIThread_MutexLock(&stMutexCriticalSection);
  305. *pbCancel = TRUE;
  306. DSIThread_CondSignal(&stCondRxEvent);
  307. DSIThread_CondSignal(&stCondRequest);
  308. DSIThread_MutexUnlock(&stMutexCriticalSection);
  309. return;
  310. }
  311. ///////////////////////////////////////////////////////////////////////
  312. void ANTFSHostChannel::ProcessDeviceNotification(ANT_DEVICE_NOTIFICATION eCode_, void* pvParameter_)
  313. {
  314. DSIThread_MutexLock(&stMutexCriticalSection);
  315. if(eCode_ != ANT_DEVICE_NOTIFICATION_RESET &&
  316. eCode_ != ANT_DEVICE_NOTIFICATION_SHUTDOWN)
  317. {
  318. #if defined(DEBUG_FILE)
  319. UCHAR aucString[256];
  320. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::ProcessDeviceNotification(): Unknown code %0", eCode_);
  321. DSIDebug::ThreadWrite((char *) aucString);
  322. #endif
  323. DSIThread_MutexUnlock(&stMutexCriticalSection);
  324. return;
  325. }
  326. if(eANTFSState <= ANTFS_HOST_STATE_IDLE)
  327. {
  328. // We do not need to do anything, since ANT-FS is already in idle state
  329. DSIThread_MutexUnlock(&stMutexCriticalSection);
  330. return;
  331. }
  332. if(pvParameter_ != NULL)
  333. {
  334. //Currently we don't have any codes we have data with, so log and ignore if we see something
  335. #if defined(DEBUG_FILE)
  336. DSIDebug::ThreadWrite("ANTFSHostChannel::ProcessDeviceNotification(): Received unrecognized pvParameter data");
  337. #endif
  338. }
  339. #if defined(DEBUG_FILE)
  340. DSIDebug::ThreadWrite("ANTFSHostChannel::ProcessDeviceNotification(): Resetting state...");
  341. #endif
  342. *pbCancel = TRUE;
  343. eANTFSRequest = ANTFS_REQUEST_INIT;
  344. DSIThread_CondSignal(&stCondRxEvent);
  345. DSIThread_CondSignal(&stCondRequest);
  346. DSIThread_MutexUnlock(&stMutexCriticalSection);
  347. return;
  348. }
  349. ///////////////////////////////////////////////////////////////////////
  350. #define MESG_CHANNEL_OFFSET 0
  351. #define MESG_EVENT_ID_OFFSET 1
  352. #define MESG_EVENT_CODE_OFFSET 2
  353. void ANTFSHostChannel::ProcessMessage(ANT_MESSAGE* pstMessage_, USHORT usMesgSize_)
  354. {
  355. UCHAR ucANTChannel;
  356. BOOL bProcessed = FALSE;
  357. // Check that we are in the correct state to receive messages
  358. if(!GetEnabled())
  359. return; // Only process ANT messages if ANT-FS is on
  360. if (usMesgSize_ < DSI_FRAMER_TIMEDOUT) //if the return isn't DSI_FRAMER_TIMEDOUT or DSI_FRAMER_ERROR
  361. {
  362. ucANTChannel = pstMessage_->aucData[MESG_CHANNEL_OFFSET] & CHANNEL_NUMBER_MASK;
  363. if(!FilterANTMessages(pstMessage_, ucANTChannel))
  364. return; // Wrong channel, do not process
  365. switch (pstMessage_->ucMessageID)
  366. {
  367. case MESG_RESPONSE_EVENT_ID:
  368. if (pstMessage_->aucData[MESG_EVENT_ID_OFFSET] != MESG_EVENT_ID) // this is a response
  369. {
  370. memcpy(aucResponseBuf, pstMessage_->aucData, MESG_RESPONSE_EVENT_SIZE);
  371. bProcessed = ANTProtocolEventProcess(ucANTChannel, MESG_RESPONSE_EVENT_ID);
  372. }
  373. else // this is an event
  374. {
  375. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  376. bProcessed = ANTChannelEventProcess(ucANTChannel, pstMessage_->aucData[MESG_EVENT_CODE_OFFSET]); // pass through any events not handled here
  377. }
  378. break;
  379. case MESG_BROADCAST_DATA_ID:
  380. //Call channel event function with Broadcast message code
  381. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  382. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_BROADCAST);
  383. break;
  384. case MESG_ACKNOWLEDGED_DATA_ID:
  385. //Call channel event function with Acknowledged message code
  386. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  387. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_ACKNOWLEDGED);
  388. break;
  389. case MESG_BURST_DATA_ID:
  390. //Call channel event function with Burst message code
  391. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  392. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_BURST_PACKET);
  393. break;
  394. case MESG_EXT_BROADCAST_DATA_ID:
  395. //Call channel event function with Broadcast message code
  396. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  397. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_EXT_BROADCAST);
  398. break;
  399. case MESG_EXT_ACKNOWLEDGED_DATA_ID:
  400. //Call channel event function with Acknowledged message code
  401. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  402. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_EXT_ACKNOWLEDGED);
  403. break;
  404. case MESG_EXT_BURST_DATA_ID:
  405. //Call channel event function with Burst message code
  406. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  407. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_EXT_BURST_PACKET);
  408. break;
  409. case MESG_RSSI_BROADCAST_DATA_ID:
  410. //Call channel event function with Broadcast message code
  411. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  412. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_RSSI_BROADCAST);
  413. break;
  414. case MESG_RSSI_ACKNOWLEDGED_DATA_ID:
  415. //Call channel event function with Acknowledged message code
  416. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  417. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_RSSI_ACKNOWLEDGED);
  418. break;
  419. case MESG_RSSI_BURST_DATA_ID:
  420. //Call channel event function with Burst message code
  421. memcpy(aucRxBuf, pstMessage_->aucData, usMesgSize_);
  422. bProcessed = ANTChannelEventProcess(ucANTChannel, EVENT_RX_RSSI_BURST_PACKET);
  423. break;
  424. default:
  425. memcpy(aucResponseBuf, pstMessage_->aucData, usMesgSize_);
  426. bProcessed = ANTProtocolEventProcess(ucANTChannel, pstMessage_->ucMessageID );
  427. break;
  428. }
  429. }
  430. return;
  431. }
  432. //////////////////////////////////////////////////////////////////////////////////
  433. // ANTFS Link Layer
  434. //////////////////////////////////////////////////////////////////////////////////
  435. ///////////////////////////////////////////////////////////////////////
  436. USHORT ANTFSHostChannel::AddSearchDevice(ANTFS_DEVICE_PARAMETERS *pstDeviceSearchMask_, ANTFS_DEVICE_PARAMETERS *pstDeviceParameters_)
  437. {
  438. USHORT usHandle;
  439. if (usDeviceListSize >= SEARCH_DEVICE_LIST_MAX_SIZE)
  440. return 0;
  441. // Find the next available handle.
  442. usHandle = 0;
  443. while (usHandle < usDeviceListSize)
  444. {
  445. if ((usHandle + 1) < asDeviceParametersList[usHandle].usHandle)
  446. break;
  447. usHandle++;
  448. }
  449. asDeviceParametersList[usDeviceListSize].usHandle = ++usHandle;
  450. asDeviceParametersList[usDeviceListSize].sDeviceParameters = *pstDeviceParameters_;
  451. asDeviceParametersList[usDeviceListSize].sDeviceSearchMask = *pstDeviceSearchMask_;
  452. usDeviceListSize++;
  453. qsort(asDeviceParametersList, usDeviceListSize, sizeof(DEVICE_PARAMETERS_ITEM), &DeviceParametersItemCompare);
  454. return usHandle;
  455. }
  456. ///////////////////////////////////////////////////////////////////////
  457. void ANTFSHostChannel::RemoveSearchDevice(USHORT usHandle_)
  458. {
  459. DEVICE_PARAMETERS_ITEM sDeviceParametersItem;
  460. DEVICE_PARAMETERS_ITEM *psDeviceParametersItem;
  461. if (usDeviceListSize == 0)
  462. return; // Nothing to do.
  463. // Find the handle in the list.
  464. sDeviceParametersItem.usHandle = usHandle_;
  465. psDeviceParametersItem =(DEVICE_PARAMETERS_ITEM *) bsearch(&sDeviceParametersItem, asDeviceParametersList, usDeviceListSize, sizeof(DEVICE_PARAMETERS_ITEM), &DeviceParametersItemCompare);
  466. if (psDeviceParametersItem != NULL)
  467. {
  468. psDeviceParametersItem->usHandle = MAX_USHORT; // Make it invalid.
  469. qsort(asDeviceParametersList, usDeviceListSize, sizeof(DEVICE_PARAMETERS_ITEM), &DeviceParametersItemCompare); // Sorting will cause the large invalid item to drop to the end of the list.
  470. usDeviceListSize--; // Reduce the size to reflect that the item has been removed.
  471. }
  472. }
  473. ///////////////////////////////////////////////////////////////////////
  474. void ANTFSHostChannel::ClearSearchDeviceList(void)
  475. {
  476. usDeviceListSize = 0;
  477. }
  478. ///////////////////////////////////////////////////////////////////////
  479. ANTFS_RETURN ANTFSHostChannel::SearchForDevice(UCHAR ucSearchRadioFrequency_, UCHAR ucConnectedRadioFrequency_, USHORT usRadioChannelID_, BOOL bUseRequestPage_)
  480. {
  481. DSIThread_MutexLock(&stMutexCriticalSection);
  482. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  483. {
  484. #if defined(DEBUG_FILE)
  485. DSIDebug::ThreadWrite("ANTFSHostChannel::SearchForDevice(): Request Busy.");
  486. #endif
  487. DSIThread_MutexUnlock(&stMutexCriticalSection);
  488. return ANTFS_RETURN_BUSY;
  489. }
  490. if (eANTFSState != ANTFS_HOST_STATE_IDLE)
  491. {
  492. #if defined(DEBUG_FILE)
  493. DSIDebug::ThreadWrite("ANTFSHostChannel::SearchForDevice(): Not in correct state.");
  494. #endif
  495. DSIThread_MutexUnlock(&stMutexCriticalSection);
  496. return ANTFS_RETURN_FAIL;
  497. }
  498. #if defined(DEBUG_FILE)
  499. DSIDebug::ThreadWrite("ANTFSHostChannel::SearchForDevice(): Search starting...");
  500. #endif
  501. ucSearchRadioFrequency = ucSearchRadioFrequency_;
  502. ucTransportFrequencySelection = ucConnectedRadioFrequency_;
  503. usRadioChannelID = usRadioChannelID_;
  504. bRequestPageEnabled = bUseRequestPage_;
  505. eANTFSRequest = ANTFS_REQUEST_SEARCH;
  506. DSIThread_CondSignal(&stCondRequest);
  507. DSIThread_MutexUnlock(&stMutexCriticalSection);
  508. #if defined(DEBUG_FILE)
  509. DSIDebug::ThreadWrite("ANTFSHostChannel::SearchForDevice(): Search request pending...");
  510. #endif
  511. return ANTFS_RETURN_PASS;
  512. }
  513. ///////////////////////////////////////////////////////////////////////
  514. BOOL ANTFSHostChannel::GetFoundDeviceParameters(ANTFS_DEVICE_PARAMETERS *pstDeviceParameters_, UCHAR *aucFriendlyName_, UCHAR *pucBufferSize_)
  515. {
  516. if (eANTFSState < ANTFS_HOST_STATE_CONNECTED)
  517. {
  518. #if defined(DEBUG_FILE)
  519. DSIDebug::ThreadWrite("ANTFSHostChannel::GetFoundDeviceParameters(): Not in correct state.");
  520. #endif
  521. return FALSE;
  522. }
  523. memcpy(pstDeviceParameters_, &stFoundDeviceParameters, sizeof(ANTFS_DEVICE_PARAMETERS));
  524. if (ucRemoteFriendlyNameLength < *pucBufferSize_)
  525. *pucBufferSize_ = ucRemoteFriendlyNameLength;
  526. memcpy(aucFriendlyName_, aucRemoteFriendlyName, *pucBufferSize_);
  527. *pucBufferSize_ = ucRemoteFriendlyNameLength;
  528. return TRUE;
  529. }
  530. ///////////////////////////////////////////////////////////////////////
  531. BOOL ANTFSHostChannel::GetFoundDeviceChannelID(USHORT *pusDeviceNumber_, UCHAR *pucDeviceType_, UCHAR *pucTransmitType_)
  532. {
  533. if (eANTFSState < ANTFS_HOST_STATE_CONNECTED)
  534. {
  535. #if defined(DEBUG_FILE)
  536. DSIDebug::ThreadWrite("ANTFSHostChannel::GetFoundDeviceChannelID(): Not in correct state.");
  537. #endif
  538. return FALSE;
  539. }
  540. if(pusDeviceNumber_ != NULL)
  541. *pusDeviceNumber_ = usFoundANTFSDeviceID;
  542. if(pucDeviceType_ != NULL)
  543. *pucDeviceType_ = ucFoundANTDeviceType;
  544. if(pucTransmitType_ != NULL)
  545. *pucTransmitType_ = ucFoundANTTransmitType;
  546. return TRUE;
  547. }
  548. ///////////////////////////////////////////////////////////////////////
  549. ANTFS_RETURN ANTFSHostChannel::RequestSession(UCHAR ucBroadcastRadioFrequency_, UCHAR ucConnectRadioFrequency_)
  550. {
  551. DSIThread_MutexLock(&stMutexCriticalSection);
  552. if(eANTFSRequest != ANTFS_REQUEST_NONE)
  553. {
  554. #if defined(DEBUG_FILE)
  555. DSIDebug::ThreadWrite("ANTFSHostChannel::RequestSession(): Request Busy.");
  556. #endif
  557. DSIThread_MutexUnlock(&stMutexCriticalSection);
  558. return ANTFS_RETURN_BUSY;
  559. }
  560. if(eANTFSState != ANTFS_HOST_STATE_IDLE)
  561. {
  562. #if defined(DEBUG_FILE)
  563. DSIDebug::ThreadWrite("ANTFSHostChannel::RequestSession(): Not in correct state.");
  564. #endif
  565. DSIThread_MutexUnlock(&stMutexCriticalSection);
  566. return ANTFS_RETURN_BUSY;
  567. }
  568. ucTransportLayerRadioFrequency = ucConnectRadioFrequency_;
  569. ucSearchRadioFrequency = ucBroadcastRadioFrequency_;
  570. eANTFSRequest = ANTFS_REQUEST_SESSION_REQ;
  571. DSIThread_CondSignal(&stCondRequest);
  572. DSIThread_MutexUnlock(&stMutexCriticalSection);
  573. #if defined(DEBUG_FILE)
  574. DSIDebug::ThreadWrite("ANTFSHostChannel::RequestSession(): Request for ANT-FS session pending...");
  575. #endif
  576. return ANTFS_RETURN_PASS;
  577. }
  578. ///////////////////////////////////////////////////////////////////////
  579. ANTFS_RETURN ANTFSHostChannel::Authenticate(UCHAR ucAuthenticationType_, UCHAR *pucAuthenticationString_, UCHAR ucLength_, UCHAR *pucResponseBuffer_, UCHAR *pucResponseBufferSize_, ULONG ulResponseTimeout_)
  580. {
  581. DSIThread_MutexLock(&stMutexCriticalSection);
  582. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  583. {
  584. #if defined(DEBUG_FILE)
  585. DSIDebug::ThreadWrite("ANTFSHostChannel::Authenticate(): Request Busy.");
  586. #endif
  587. DSIThread_MutexUnlock(&stMutexCriticalSection);
  588. return ANTFS_RETURN_BUSY;
  589. }
  590. if (eANTFSState != ANTFS_HOST_STATE_CONNECTED)
  591. {
  592. #if defined(DEBUG_FILE)
  593. DSIDebug::ThreadWrite("ANTFSHostChannel::Authenticate(): Not in correct state.");
  594. #endif
  595. DSIThread_MutexUnlock(&stMutexCriticalSection);
  596. return ANTFS_RETURN_FAIL;
  597. }
  598. ucTxPasswordLength = ucLength_;
  599. ucAuthType = ucAuthenticationType_;
  600. pucResponseBuffer = pucResponseBuffer_;
  601. pucResponseBufferSize = pucResponseBufferSize_;
  602. ulAuthResponseTimeout = ulResponseTimeout_;
  603. memcpy(aucTxPassword, pucAuthenticationString_, ucTxPasswordLength);
  604. //may switch on Auth type here...
  605. eANTFSRequest = ANTFS_REQUEST_AUTHENTICATE;
  606. DSIThread_CondSignal(&stCondRequest);
  607. DSIThread_MutexUnlock(&stMutexCriticalSection);
  608. return ANTFS_RETURN_PASS;
  609. }
  610. ///////////////////////////////////////////////////////////////////////
  611. ANTFS_RETURN ANTFSHostChannel::Disconnect(USHORT usBlackoutTime_, UCHAR ucDisconnectType_, UCHAR ucTimeDuration_, UCHAR ucAppSpecificDuration_)
  612. {
  613. ANTFS_RETURN eReturn = ANTFS_RETURN_PASS;
  614. DSIThread_MutexLock(&stMutexCriticalSection);
  615. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  616. {
  617. #if defined(DEBUG_FILE)
  618. DSIDebug::ThreadWrite("ANTFSHostChannel::Disconnect(): Request Busy.");
  619. #endif
  620. DSIThread_MutexUnlock(&stMutexCriticalSection);
  621. return ANTFS_RETURN_BUSY;
  622. }
  623. if (eANTFSState < ANTFS_HOST_STATE_REQUESTING_SESSION)
  624. {
  625. #if defined(DEBUG_FILE)
  626. DSIDebug::ThreadWrite("ANTFSHostChannel::Disconnect(): Already disconnected.");
  627. #endif
  628. DSIThread_MutexUnlock(&stMutexCriticalSection);
  629. return ANTFS_RETURN_FAIL;
  630. }
  631. if (eANTFSState >= ANTFS_HOST_STATE_CONNECTED)
  632. {
  633. if (usBlackoutTime_ )
  634. {
  635. if(Blackout(usFoundANTFSDeviceID, usFoundANTFSManufacturerID, usFoundANTFSDeviceType, usBlackoutTime_) == FALSE)
  636. {
  637. #if defined(DEBUG_FILE)
  638. DSIDebug::ThreadWrite("ANTFSHostChannel::Disconnect(): Failed adding device to ignore list.");
  639. #endif
  640. eReturn = ANTFS_RETURN_FAIL;
  641. }
  642. }
  643. }
  644. ucDisconnectType = ucDisconnectType_;
  645. ucUndiscoverableTimeDuration = ucTimeDuration_;
  646. ucUndiscoverableAppSpecificDuration = ucAppSpecificDuration_;
  647. eANTFSRequest = ANTFS_REQUEST_DISCONNECT;
  648. DSIThread_CondSignal(&stCondRequest);
  649. DSIThread_MutexUnlock(&stMutexCriticalSection);
  650. return eReturn;
  651. }
  652. ///////////////////////////////////////////////////////////////////////
  653. ANTFS_RETURN ANTFSHostChannel::SwitchFrequency(UCHAR ucRadioFrequency_, UCHAR ucChannelPeriod_)
  654. {
  655. DSIThread_MutexLock(&stMutexCriticalSection);
  656. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  657. {
  658. #if defined(DEBUG_FILE)
  659. DSIDebug::ThreadWrite("ANTFSHostChannel::SwitchFrequency(): Request Busy.");
  660. #endif
  661. DSIThread_MutexUnlock(&stMutexCriticalSection);
  662. return ANTFS_RETURN_BUSY;
  663. }
  664. if (eANTFSState != ANTFS_HOST_STATE_TRANSPORT)
  665. {
  666. #if defined(DEBUG_FILE)
  667. DSIDebug::ThreadWrite("ANTFSHostChannel::SwitchFrequency(): Not in transport state.");
  668. #endif
  669. DSIThread_MutexUnlock(&stMutexCriticalSection);
  670. return ANTFS_RETURN_FAIL;
  671. }
  672. ucTransportFrequencySelection = ucRadioFrequency_;
  673. ucTransportChannelPeriodSelection = ucChannelPeriod_;
  674. eANTFSRequest = ANTFS_REQUEST_CHANGE_LINK;
  675. DSIThread_CondSignal(&stCondRequest);
  676. DSIThread_MutexUnlock(&stMutexCriticalSection);
  677. return ANTFS_RETURN_PASS;
  678. }
  679. ///////////////////////////////////////////////////////////////////////
  680. ANTFS_RETURN ANTFSHostChannel::Download(USHORT usFileIndex_, ULONG ulDataOffset_, ULONG ulMaxDataLength_, ULONG ulMaxBlockSize_)
  681. {
  682. DSIThread_MutexLock(&stMutexCriticalSection);
  683. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  684. {
  685. #if defined(DEBUG_FILE)
  686. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Request Busy.");
  687. #endif
  688. DSIThread_MutexUnlock(&stMutexCriticalSection);
  689. return ANTFS_RETURN_BUSY;
  690. }
  691. if (eANTFSState != ANTFS_HOST_STATE_TRANSPORT)
  692. {
  693. #if defined(DEBUG_FILE)
  694. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Not in transport state.");
  695. #endif
  696. DSIThread_MutexUnlock(&stMutexCriticalSection);
  697. return ANTFS_RETURN_FAIL;
  698. }
  699. bTransfer = FALSE;
  700. ulTransferTotalBytesRemaining = 0;
  701. ulTransferBytesInBlock = 0;
  702. usTransferDataFileIndex = usFileIndex_;
  703. ulTransferDataOffset = ulDataOffset_;
  704. ulTransferByteSize = ulMaxDataLength_;
  705. ulHostBlockSize = ulMaxBlockSize_;
  706. #if defined(DEBUG_FILE)
  707. {
  708. char szString[256];
  709. SNPRINTF(szString, 256, "ANTFSHostChannel::Download():\n usTransferDataFileIndex = %u.\n ulTransferDataOffset = %lu.\n ulTransferByteSize = %lu.",
  710. usTransferDataFileIndex, ulTransferDataOffset, ulTransferByteSize);
  711. DSIDebug::ThreadWrite(szString);
  712. }
  713. #endif
  714. if ((usFoundANTFSManufacturerID == 1) && (usFoundANTFSDeviceType == 782))
  715. bLargeData = FALSE; // !! Forerunner 50 only -- obsolete for all other devices.
  716. else
  717. bLargeData = TRUE;
  718. eANTFSRequest = ANTFS_REQUEST_DOWNLOAD;
  719. DSIThread_CondSignal(&stCondRequest);
  720. DSIThread_MutexUnlock(&stMutexCriticalSection);
  721. return ANTFS_RETURN_PASS;
  722. }
  723. ///////////////////////////////////////////////////////////////////////
  724. ANTFS_RETURN ANTFSHostChannel::Upload(USHORT usFileIndex_, ULONG ulDataOffset_, ULONG ulDataLength_, void *pvData_, BOOL bForceOffset_, ULONG ulMaxBlockSize_)
  725. {
  726. DSIThread_MutexLock(&stMutexCriticalSection);
  727. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  728. {
  729. #if defined(DEBUG_FILE)
  730. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Request Busy.");
  731. #endif
  732. DSIThread_MutexUnlock(&stMutexCriticalSection);
  733. return ANTFS_RETURN_BUSY;
  734. }
  735. if (eANTFSState != ANTFS_HOST_STATE_TRANSPORT)
  736. {
  737. #if defined(DEBUG_FILE)
  738. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Not in transport state.");
  739. #endif
  740. DSIThread_MutexUnlock(&stMutexCriticalSection);
  741. return ANTFS_RETURN_FAIL;
  742. }
  743. bTransfer = FALSE;
  744. ulUploadIndexProgress = 0;
  745. usTransferDataFileIndex = usFileIndex_;
  746. ulTransferDataOffset = ulDataOffset_;
  747. ulTransferByteSize = ulDataLength_;
  748. pucUploadData = (UCHAR*)pvData_;
  749. bForceUploadOffset = bForceOffset_;
  750. if (ulDataOffset_)
  751. bForceUploadOffset = TRUE; //Force the offset if the app is giving us an initial offset other than 0.
  752. if(ulMaxBlockSize_ == 0)
  753. ulHostBlockSize = MAX_ULONG;
  754. else
  755. ulHostBlockSize = ulMaxBlockSize_;
  756. #if 0
  757. if ((ulTransferDataOffset > MAX_USHORT) || (ulTransferByteSize > MAX_USHORT))
  758. bLargeData = TRUE;
  759. else
  760. bLargeData = FALSE;
  761. #endif
  762. bLargeData = TRUE;
  763. eANTFSRequest = ANTFS_REQUEST_UPLOAD;
  764. DSIThread_CondSignal(&stCondRequest);
  765. DSIThread_MutexUnlock(&stMutexCriticalSection);
  766. return ANTFS_RETURN_PASS;
  767. }
  768. ///////////////////////////////////////////////////////////////////////
  769. ANTFS_RETURN ANTFSHostChannel::ManualTransfer(USHORT usFileIndex_, ULONG ulDataOffset_, ULONG ulDataLength_, void *pvData_)
  770. {
  771. DSIThread_MutexLock(&stMutexCriticalSection);
  772. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  773. {
  774. #if defined(DEBUG_FILE)
  775. DSIDebug::ThreadWrite("ANTFSHostChannel::ManualTransfer(): Request Busy.");
  776. #endif
  777. DSIThread_MutexUnlock(&stMutexCriticalSection);
  778. return ANTFS_RETURN_BUSY;
  779. }
  780. if (eANTFSState != ANTFS_HOST_STATE_TRANSPORT)
  781. {
  782. #if defined(DEBUG_FILE)
  783. DSIDebug::ThreadWrite("ANTFSHostChannel::ManualTransfer(): Not in transport state.");
  784. #endif
  785. DSIThread_MutexUnlock(&stMutexCriticalSection);
  786. return ANTFS_RETURN_FAIL;
  787. }
  788. if (ulDataOffset_ >= DIRECT_TRANSFER_SIZE)
  789. {
  790. #if defined(DEBUG_FILE)
  791. DSIDebug::ThreadWrite("ANTFSHostChannel::ManualTransfer(): ulDataOffset) too large.");
  792. #endif
  793. DSIThread_MutexUnlock(&stMutexCriticalSection);
  794. return ANTFS_RETURN_FAIL;
  795. }
  796. if ((ulDataLength_ > DIRECT_TRANSFER_SIZE) || (ulDataLength_ == 0))
  797. {
  798. #if defined(DEBUG_FILE)
  799. DSIDebug::ThreadWrite("ANTFSHostChannel::ManualTransfer(): ulDataLength_ is 0 or too large.");
  800. #endif
  801. DSIThread_MutexUnlock(&stMutexCriticalSection);
  802. return ANTFS_RETURN_FAIL;
  803. }
  804. memcpy(&aucSendDirectBuffer[8], pvData_, ulDataLength_); //pvData_ must be little endian when sent to device!
  805. memset(&aucSendDirectBuffer[ulDataLength_ + 8], 0, 8 - (ulDataLength_ % 8) ); // Clear the rest of the last payload packet.
  806. #if defined(DEBUG_FILE)
  807. {
  808. char acString[256];
  809. SNPRINTF(acString, 256, "ANTFSHostChannel::ManualTransfer(): ulDataLength_ = %lu; ulDataOffset_ = %lu.", ulDataLength_, ulDataOffset_);
  810. DSIDebug::ThreadWrite(acString);
  811. }
  812. #endif
  813. bTransfer = FALSE;
  814. ulUploadIndexProgress = 0;
  815. ulTransferTotalBytesRemaining = 0;
  816. usTransferDataFileIndex = usFileIndex_;
  817. ulTransferDataOffset = ulDataOffset_;
  818. ulTransferByteSize = ulDataLength_;
  819. bLargeData = FALSE;
  820. eANTFSRequest = ANTFS_REQUEST_MANUAL_TRANSFER;
  821. DSIThread_CondSignal(&stCondRequest);
  822. DSIThread_MutexUnlock(&stMutexCriticalSection);
  823. return ANTFS_RETURN_PASS;
  824. }
  825. ///////////////////////////////////////////////////////////////////////
  826. BOOL ANTFSHostChannel::GetDownloadStatus(ULONG *pulByteProgress_, ULONG *pulTotalLength_)
  827. {
  828. ULONG ulOffset;
  829. if (ulTransferTotalBytesRemaining == 0)
  830. {
  831. #if defined(DEBUG_FILE)
  832. DSIDebug::ThreadWrite("ANTFSHostChannel::GetDownloadStatus(): Download not in progress.");
  833. #endif
  834. *pulTotalLength_ = 10;
  835. *pulByteProgress_ = 0;
  836. return FALSE;
  837. }
  838. *pulTotalLength_ = ulTransferTotalBytesRemaining;
  839. // The first 8 / 16 bytes of the array form the response packet.
  840. // Subtract them from the length count.
  841. if (bLargeData)
  842. ulOffset = 16;
  843. else
  844. ulOffset = 8;
  845. if (ulTransferArrayIndex >= ulOffset)
  846. *pulByteProgress_ = ulTransferArrayIndex - ulOffset;
  847. else
  848. *pulByteProgress_ = 0;
  849. *pulByteProgress_ += ulTransferDataOffset;
  850. if (*pulByteProgress_ > *pulTotalLength_) //the index can go beyond the total length because we transfer with 8 byte packets
  851. *pulByteProgress_ = *pulTotalLength_;
  852. return TRUE;
  853. }
  854. ///////////////////////////////////////////////////////////////////////
  855. BOOL ANTFSHostChannel::GetTransferData(ULONG *pulDataSize_ , void *pvData_)
  856. {
  857. ULONG ulLength;
  858. int iOffset;
  859. if ((!bTransfer) || (pucTransferBufferDynamic == NULL))
  860. {
  861. #if defined(DEBUG_FILE)
  862. DSIDebug::ThreadWrite("ANTFSHostChannel::GetTransferData(): No valid data.");
  863. #endif
  864. return FALSE;
  865. }
  866. if (bLargeData)
  867. iOffset = 16;
  868. else
  869. iOffset = 8;
  870. ulLength = ulTransferArrayIndex - iOffset;
  871. if (ulLength > ulTransferTotalBytesRemaining)
  872. ulLength = ulTransferTotalBytesRemaining;
  873. if (pvData_ != NULL)
  874. memcpy(pvData_, pucTransferBufferDynamic + iOffset, ulLength);
  875. if (pulDataSize_ != NULL)
  876. *pulDataSize_ = ulLength;
  877. return TRUE;
  878. }
  879. ///////////////////////////////////////////////////////////////////////
  880. BOOL ANTFSHostChannel::RecoverTransferData(ULONG *pulDataSize_ , void *pvData_)
  881. {
  882. ULONG ulLength;
  883. int iOffset;
  884. if (pucTransferBufferDynamic == NULL)
  885. {
  886. #if defined(DEBUG_FILE)
  887. DSIDebug::ThreadWrite("ANTFSHostChannel::GetTransferData(): No valid data.");
  888. #endif
  889. return FALSE;
  890. }
  891. if (bLargeData)
  892. iOffset = 16;
  893. else
  894. iOffset = 8;
  895. ulLength = ulTransferArrayIndex - iOffset;
  896. if (ulLength > ulTransferTotalBytesRemaining)
  897. ulLength = ulTransferTotalBytesRemaining;
  898. if (pvData_ != NULL)
  899. memcpy(pvData_, pucTransferBufferDynamic + iOffset, ulLength);
  900. if (pulDataSize_ != NULL)
  901. *pulDataSize_ = ulLength;
  902. return TRUE;
  903. }
  904. ///////////////////////////////////////////////////////////////////////
  905. BOOL ANTFSHostChannel::GetUploadStatus(ULONG *pulByteProgress_, ULONG *pulTotalLength_)
  906. {
  907. if (ulTransferByteSize == 0)
  908. {
  909. #if defined(DEBUG_FILE)
  910. DSIDebug::ThreadWrite("ANTFSHostChannel::GetDownloadStatus(): Upload not in progress.");
  911. #endif
  912. *pulTotalLength_ = 10;
  913. *pulByteProgress_ = 0;
  914. return FALSE;
  915. }
  916. *pulTotalLength_ = ulTransferByteSize;
  917. *pulByteProgress_ = ulUploadIndexProgress;
  918. if (*pulByteProgress_ >= 16) //take off the extra 8 byte overhead
  919. *pulByteProgress_ = *pulByteProgress_ - 16;
  920. return TRUE;
  921. }
  922. ///////////////////////////////////////////////////////////////////////
  923. ANTFS_RETURN ANTFSHostChannel::EraseData(USHORT usDataFileIndex_)
  924. {
  925. DSIThread_MutexLock(&stMutexCriticalSection);
  926. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  927. {
  928. #if defined(DEBUG_FILE)
  929. DSIDebug::ThreadWrite("ANTFSHostChannel::EraseData(): Request Busy.");
  930. #endif
  931. DSIThread_MutexUnlock(&stMutexCriticalSection);
  932. return ANTFS_RETURN_BUSY;
  933. }
  934. if (eANTFSState != ANTFS_HOST_STATE_TRANSPORT)
  935. {
  936. #if defined(DEBUG_FILE)
  937. DSIDebug::ThreadWrite("ANTFSHostChannel::EraseData(): Not in transport state.");
  938. #endif
  939. DSIThread_MutexUnlock(&stMutexCriticalSection);
  940. return ANTFS_RETURN_FAIL;
  941. }
  942. bTransfer = FALSE;
  943. usTransferDataFileIndex = usDataFileIndex_;
  944. eANTFSRequest = ANTFS_REQUEST_ERASE;
  945. DSIThread_CondSignal(&stCondRequest);
  946. DSIThread_MutexUnlock(&stMutexCriticalSection);
  947. return ANTFS_RETURN_PASS;
  948. }
  949. //////////////////////////////////////////////////////////////////////
  950. BOOL ANTFSHostChannel::EnablePing(BOOL bEnable_)
  951. {
  952. bPingEnabled = bEnable_;
  953. return TRUE;
  954. }
  955. //////////////////////////////////////////////////////////////////////////////////
  956. // Private Functions
  957. //////////////////////////////////////////////////////////////////////////////////
  958. DSI_THREAD_RETURN ANTFSHostChannel::ANTFSThreadStart(void *pvParameter_)
  959. {
  960. #if defined(DEBUG_FILE)
  961. DSIDebug::ThreadInit("ANTFSHost");
  962. #endif
  963. ((ANTFSHostChannel *)pvParameter_)->ANTFSThread();
  964. return 0;
  965. }
  966. ///////////////////////////////////////////////////////////////////////
  967. // ANTFS Task Thread
  968. ///////////////////////////////////////////////////////////////////////
  969. void ANTFSHostChannel::ANTFSThread(void)
  970. {
  971. ANTFS_HOST_RESPONSE eResponse;
  972. BOOL bPingNow = FALSE;
  973. bANTFSThreadRunning = TRUE;
  974. while (bKillThread == FALSE)
  975. {
  976. eResponse = ANTFS_HOST_RESPONSE_NONE;
  977. #if defined(DEBUG_FILE)
  978. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Awaiting Requests...");
  979. #endif
  980. DSIThread_MutexLock(&stMutexCriticalSection);
  981. if (*pbCancel == TRUE) //If there was a cancel, then return ANTFS_HOST_RESPONSE_CANCEL_DONE when we've reached this point
  982. {
  983. *pbCancel = FALSE;
  984. if (eANTFSRequest != ANTFS_REQUEST_INIT && eANTFSRequest != ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  985. {
  986. eANTFSRequest = ANTFS_REQUEST_NONE; //Clear any other request
  987. }
  988. AddResponse(ANTFS_HOST_RESPONSE_CANCEL_DONE);
  989. }
  990. if ((eANTFSRequest == ANTFS_REQUEST_NONE) && (bKillThread == FALSE))
  991. {
  992. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRequest, &stMutexCriticalSection, 2000);
  993. if (ucResult != DSI_THREAD_ENONE)
  994. {
  995. #if defined(DEBUG_FILE)
  996. if(ucResult == DSI_THREAD_EOTHER)
  997. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): CondTimedWait() Failed!");
  998. #endif
  999. if ((eANTFSRequest == ANTFS_REQUEST_NONE) && (bPingEnabled == TRUE) && (eANTFSState >= ANTFS_HOST_STATE_CONNECTED))
  1000. {
  1001. bPingNow = TRUE;
  1002. #if defined(DEBUG_FILE)
  1003. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Requesting Ping.");
  1004. #endif
  1005. }
  1006. }
  1007. }
  1008. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1009. if (bPingNow == TRUE)
  1010. {
  1011. bPingNow = FALSE;
  1012. Ping();
  1013. }
  1014. if (bKillThread)
  1015. break;
  1016. if (eANTFSRequest != ANTFS_REQUEST_NONE)
  1017. {
  1018. #if defined(DEBUG_FILE)
  1019. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Request received");
  1020. #endif
  1021. switch (eANTFSRequest)
  1022. {
  1023. case ANTFS_REQUEST_INIT:
  1024. {
  1025. #if defined(DEBUG_FILE)
  1026. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Idle.");
  1027. #endif
  1028. ResetHostState();
  1029. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1030. eResponse = ANTFS_HOST_RESPONSE_INIT_PASS;
  1031. } // ANTFS_REQUEST_INIT
  1032. break;
  1033. case ANTFS_REQUEST_SESSION:
  1034. {
  1035. RETURN_STATUS eReturn;
  1036. #if defined(DEBUG_FILE)
  1037. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Requesting ANT-FS session...");
  1038. #endif
  1039. eANTFSState = ANTFS_HOST_STATE_REQUESTING_SESSION;
  1040. eReturn = AttemptRequestSession();
  1041. if (eReturn == RETURN_SERIAL_ERROR)
  1042. {
  1043. #if defined(DEBUG_FILE)
  1044. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Session request serial error.");
  1045. #endif
  1046. DSIThread_MutexLock(&stMutexCriticalSection);
  1047. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1048. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1049. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1050. }
  1051. else if (eReturn == RETURN_FAIL)
  1052. {
  1053. #if defined(DEBUG_FILE)
  1054. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Session request failed.");
  1055. #endif
  1056. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1057. eResponse = ANTFS_HOST_RESPONSE_REQUEST_SESSION_FAIL;
  1058. }
  1059. else if (eReturn == RETURN_STOP)
  1060. {
  1061. #if defined(DEBUG_FILE)
  1062. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Session request stopped.");
  1063. #endif
  1064. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1065. }
  1066. else if (eReturn == RETURN_PASS)
  1067. {
  1068. RETURN_STATUS eConnectStatus;
  1069. #if defined(DEBUG_FILE)
  1070. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connecting...");
  1071. #endif
  1072. eConnectStatus = AttemptConnect();
  1073. if (eConnectStatus == RETURN_FAIL)
  1074. {
  1075. #if defined(DEBUG_FILE)
  1076. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connect failed.");
  1077. #endif
  1078. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1079. eResponse = ANTFS_HOST_RESPONSE_REQUEST_SESSION_FAIL;
  1080. }
  1081. else if (eConnectStatus == RETURN_SERIAL_ERROR)
  1082. {
  1083. #if defined(DEBUG_FILE)
  1084. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connect rejected.");
  1085. #endif
  1086. DSIThread_MutexLock(&stMutexCriticalSection);
  1087. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1088. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1089. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1090. }
  1091. else if (eConnectStatus == RETURN_PASS)
  1092. {
  1093. // No need to request the serial number in this case, as
  1094. // we already know we are connected to the right device
  1095. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1096. eResponse = ANTFS_HOST_RESPONSE_CONNECT_PASS;
  1097. }
  1098. else if (eConnectStatus == RETURN_STOP)
  1099. {
  1100. #if defined(DEBUG_FILE)
  1101. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Session request stopped.");
  1102. #endif
  1103. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1104. }
  1105. else
  1106. {
  1107. #if defined(DEBUG_FILE)
  1108. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Session request failed.");
  1109. #endif
  1110. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1111. eResponse = ANTFS_HOST_RESPONSE_REQUEST_SESSION_FAIL;
  1112. }
  1113. }
  1114. } // ANTFS_REQUEST_SESSION
  1115. break;
  1116. case ANTFS_REQUEST_SEARCH:
  1117. {
  1118. RETURN_STATUS eReturn;
  1119. eANTFSState = ANTFS_HOST_STATE_SEARCHING;
  1120. #if defined(DEBUG_FILE)
  1121. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Searching...");
  1122. #endif
  1123. eReturn = AttemptSearch();
  1124. if (eReturn == RETURN_SERIAL_ERROR)
  1125. {
  1126. #if defined(DEBUG_FILE)
  1127. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Search serial error.");
  1128. #endif
  1129. DSIThread_MutexLock(&stMutexCriticalSection);
  1130. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1131. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1132. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1133. }
  1134. else if (eReturn == RETURN_FAIL)
  1135. {
  1136. #if defined(DEBUG_FILE)
  1137. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Search failed.");
  1138. #endif
  1139. //eANTFSRequest should still be ANTFS_REQUEST_SEARCH; // Keep searching.
  1140. //stay in searching state so we keep retrying
  1141. }
  1142. else if (eReturn == RETURN_STOP)
  1143. {
  1144. RETURN_STATUS eDisconnectStatus;
  1145. eDisconnectStatus = AttemptDisconnect();
  1146. if(eDisconnectStatus == RETURN_PASS)
  1147. {
  1148. #if defined(DEBUG_FILE)
  1149. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Search stopped.");
  1150. #endif
  1151. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1152. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1153. }
  1154. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1155. {
  1156. #if defined(DEBUG_FILE)
  1157. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error stopping search.");
  1158. #endif
  1159. DSIThread_MutexLock(&stMutexCriticalSection);
  1160. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1161. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1162. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1163. }
  1164. }
  1165. else if (eReturn == RETURN_PASS)
  1166. {
  1167. RETURN_STATUS eConnectStatus;
  1168. #if defined(DEBUG_FILE)
  1169. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connecting...");
  1170. #endif
  1171. eConnectStatus = AttemptConnect();
  1172. if (eConnectStatus == RETURN_FAIL)
  1173. {
  1174. #if defined(DEBUG_FILE)
  1175. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connect failed.");
  1176. #endif
  1177. //eANTFSRequest should still be ANTFS_REQUEST_SEARCH; // Keep searching.
  1178. eANTFSState = ANTFS_HOST_STATE_SEARCHING;
  1179. }
  1180. else if (eConnectStatus == RETURN_SERIAL_ERROR)
  1181. {
  1182. #if defined(DEBUG_FILE)
  1183. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connect rejected.");
  1184. #endif
  1185. DSIThread_MutexLock(&stMutexCriticalSection);
  1186. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1187. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1188. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1189. }
  1190. else
  1191. {
  1192. #if defined(DEBUG_FILE)
  1193. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Requesting ID...");
  1194. #endif
  1195. //eANTFSState = ANTFS_HOST_STATE_REQUESTING_ID;
  1196. //We do not want to set the state to connected until after we have sucessfully retrived the serial number
  1197. ucTxPasswordLength = 0;
  1198. ucAuthType = AUTH_COMMAND_REQ_SERIAL_NUM;
  1199. pucResponseBuffer = aucRemoteFriendlyName;
  1200. ucRemoteFriendlyNameLength = sizeof(aucRemoteFriendlyName);
  1201. pucResponseBufferSize = &ucRemoteFriendlyNameLength;
  1202. ulAuthResponseTimeout = AUTH_TIMEOUT;
  1203. eReturn = AttemptAuthenticate();
  1204. if ((eReturn == RETURN_PASS) || (eReturn == RETURN_NA))
  1205. {
  1206. #if defined(DEBUG_FILE)
  1207. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connected.");
  1208. #endif
  1209. //grab and save the remote serial number
  1210. stFoundDeviceParameters.ulDeviceID = Convert_Bytes_To_ULONG(aucTransferBufferFixed[AUTH_REMOTE_SERIAL_NUMBER_OFFSET + 3],
  1211. aucTransferBufferFixed[AUTH_REMOTE_SERIAL_NUMBER_OFFSET + 2],
  1212. aucTransferBufferFixed[AUTH_REMOTE_SERIAL_NUMBER_OFFSET + 1],
  1213. aucTransferBufferFixed[AUTH_REMOTE_SERIAL_NUMBER_OFFSET]);
  1214. if (IsDeviceMatched(&stFoundDeviceParameters, FALSE) == TRUE)
  1215. {
  1216. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1217. eResponse = ANTFS_HOST_RESPONSE_CONNECT_PASS;
  1218. }
  1219. else
  1220. {
  1221. //possibly blackout the device for a period of time here.
  1222. #if defined(DEBUG_FILE)
  1223. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Full ID is not a match.");
  1224. #endif
  1225. RETURN_STATUS eDisconnectStatus;
  1226. eDisconnectStatus = AttemptDisconnect();
  1227. if(eDisconnectStatus == RETURN_PASS)
  1228. {
  1229. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1230. }
  1231. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1232. {
  1233. #if defined(DEBUG_FILE)
  1234. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error stopping search.");
  1235. #endif
  1236. DSIThread_MutexLock(&stMutexCriticalSection);
  1237. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1238. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1239. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1240. }
  1241. }
  1242. }
  1243. else if (eReturn == RETURN_STOP)
  1244. {
  1245. RETURN_STATUS eDisconnectStatus;
  1246. #if defined(DEBUG_FILE)
  1247. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Search stopped.");
  1248. #endif
  1249. eDisconnectStatus = AttemptDisconnect();
  1250. if(eDisconnectStatus == RETURN_PASS)
  1251. {
  1252. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1253. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1254. }
  1255. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1256. {
  1257. #if defined(DEBUG_FILE)
  1258. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error getting ID.");
  1259. #endif
  1260. DSIThread_MutexLock(&stMutexCriticalSection);
  1261. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1262. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1263. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1264. }
  1265. }
  1266. else
  1267. {
  1268. RETURN_STATUS eDisconnectStatus;
  1269. #if defined(DEBUG_FILE)
  1270. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Get ID failed.");
  1271. #endif
  1272. eDisconnectStatus = AttemptDisconnect();
  1273. if(eDisconnectStatus == RETURN_PASS)
  1274. {
  1275. // Keep searching.
  1276. eANTFSState = ANTFS_HOST_STATE_SEARCHING;
  1277. }
  1278. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1279. {
  1280. #if defined(DEBUG_FILE)
  1281. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error getting ID.");
  1282. #endif
  1283. DSIThread_MutexLock(&stMutexCriticalSection);
  1284. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1285. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1286. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1287. }
  1288. }
  1289. }
  1290. }
  1291. }
  1292. break;
  1293. case ANTFS_REQUEST_AUTHENTICATE:
  1294. {
  1295. RETURN_STATUS eReturn;
  1296. eANTFSState = ANTFS_HOST_STATE_AUTHENTICATING;
  1297. eResponse = ANTFS_HOST_RESPONSE_AUTHENTICATE_FAIL; //set a default response
  1298. #if defined(DEBUG_FILE)
  1299. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authenticating...");
  1300. #endif
  1301. eReturn = AttemptAuthenticate();
  1302. pucResponseBuffer = (UCHAR*)NULL; //clear response buffer pointers
  1303. pucResponseBufferSize = (UCHAR*)NULL;
  1304. if (eReturn == RETURN_PASS)
  1305. {
  1306. #if defined(DEBUG_FILE)
  1307. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication passed.");
  1308. #endif
  1309. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1310. eResponse = ANTFS_HOST_RESPONSE_AUTHENTICATE_PASS;
  1311. }
  1312. else if (eReturn == RETURN_FAIL)
  1313. {
  1314. #if defined(DEBUG_FILE)
  1315. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication failed.");
  1316. #endif
  1317. IncFreqStaleCount(MAJOR_STALE_COUNT);
  1318. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1319. eResponse = ANTFS_HOST_RESPONSE_AUTHENTICATE_FAIL;
  1320. }
  1321. else if (eReturn == RETURN_REJECT)
  1322. {
  1323. #if defined(DEBUG_FILE)
  1324. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication rejected.");
  1325. #endif
  1326. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1327. eResponse = ANTFS_HOST_RESPONSE_AUTHENTICATE_REJECT;
  1328. }
  1329. else if (eReturn == RETURN_SERIAL_ERROR)
  1330. {
  1331. #if defined(DEBUG_FILE)
  1332. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication serial error.");
  1333. #endif
  1334. DSIThread_MutexLock(&stMutexCriticalSection);
  1335. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1336. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1337. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1338. }
  1339. else if (eReturn == RETURN_STOP)
  1340. {
  1341. #if defined(DEBUG_FILE)
  1342. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication stopped.");
  1343. #endif
  1344. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1345. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS);
  1346. }
  1347. else //RETURN_NA
  1348. {
  1349. #if defined(DEBUG_FILE)
  1350. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Authentication NA.");
  1351. #endif
  1352. eANTFSState = ANTFS_HOST_STATE_CONNECTED;
  1353. eResponse = ANTFS_HOST_RESPONSE_AUTHENTICATE_NA;
  1354. }
  1355. }
  1356. break;
  1357. case ANTFS_REQUEST_DISCONNECT:
  1358. {
  1359. RETURN_STATUS eReturn;
  1360. eANTFSState = ANTFS_HOST_STATE_DISCONNECTING;
  1361. #if defined(DEBUG_FILE)
  1362. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Disconnecting...");
  1363. #endif
  1364. eReturn = AttemptDisconnect();
  1365. if(eReturn == RETURN_PASS)
  1366. {
  1367. #if defined(DEBUG_FILE)
  1368. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Disconnect passed.");
  1369. #endif
  1370. ResetHostState();
  1371. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1372. eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1373. }
  1374. else if(eReturn == RETURN_SERIAL_ERROR)
  1375. {
  1376. #if defined(DEBUG_FILE)
  1377. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Disconnect serial error.");
  1378. #endif
  1379. DSIThread_MutexLock(&stMutexCriticalSection);
  1380. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1381. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1382. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1383. }
  1384. }
  1385. break;
  1386. case ANTFS_REQUEST_CHANGE_LINK:
  1387. {
  1388. RETURN_STATUS eReturn;
  1389. #if defined(DEBUG_FILE)
  1390. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Changing radio frequency and channel period...");
  1391. #endif
  1392. eReturn = AttemptSwitchFrequency();
  1393. if (eReturn == RETURN_SERIAL_ERROR)
  1394. {
  1395. #if defined(DEBUG_FILE)
  1396. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error while changing radio frequency/period.");
  1397. #endif
  1398. DSIThread_MutexLock(&stMutexCriticalSection);
  1399. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1400. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1401. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1402. }
  1403. else if (eReturn == RETURN_FAIL)
  1404. {
  1405. RETURN_STATUS eDisconnectStatus;
  1406. #if defined(DEBUG_FILE)
  1407. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Changing radio frequency and channel period failed.");
  1408. #endif
  1409. // We end up here if we lost the beacon when trying to change the channel parameters, so
  1410. // disconnect, so we can try to connect to it again
  1411. eDisconnectStatus = AttemptDisconnect();
  1412. if(eDisconnectStatus == RETURN_PASS)
  1413. {
  1414. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1415. eResponse = ANTFS_HOST_RESPONSE_CONNECTION_LOST;
  1416. }
  1417. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1418. {
  1419. #if defined(DEBUG_FILE)
  1420. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error changing channel parameters.");
  1421. #endif
  1422. DSIThread_MutexLock(&stMutexCriticalSection);
  1423. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1424. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1425. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1426. }
  1427. }
  1428. else if (eReturn == RETURN_PASS)
  1429. {
  1430. eANTFSRequest = ANTFS_REQUEST_NONE;
  1431. #if defined(DEBUG_FILE)
  1432. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Changed radio frequency and channel period.");
  1433. #endif
  1434. // TODO: Do we need a response as well?
  1435. }
  1436. } // ANTFS_REQUEST_CHANGE_LINK
  1437. break;
  1438. case ANTFS_REQUEST_DOWNLOAD:
  1439. {
  1440. RETURN_STATUS eReturn;
  1441. eANTFSState = ANTFS_HOST_STATE_DOWNLOADING;
  1442. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_FAIL; //Set a default response
  1443. #if defined(DEBUG_FILE)
  1444. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Downloading...");
  1445. #endif
  1446. eReturn = AttemptDownload();
  1447. if (eReturn == RETURN_PASS)
  1448. {
  1449. #if defined(DEBUG_FILE)
  1450. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Download complete.");
  1451. #endif
  1452. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1453. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_PASS;
  1454. }
  1455. else if (eReturn == RETURN_FAIL)
  1456. {
  1457. RETURN_STATUS eDisconnectStatus;
  1458. #if defined(DEBUG_FILE)
  1459. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Download failed.");
  1460. #endif
  1461. IncFreqStaleCount(MINOR_STALE_COUNT);
  1462. eDisconnectStatus = AttemptDisconnect();
  1463. if(eDisconnectStatus == RETURN_PASS)
  1464. {
  1465. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1466. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_FAIL;
  1467. }
  1468. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1469. {
  1470. #if defined(DEBUG_FILE)
  1471. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error on failed download.");
  1472. #endif
  1473. DSIThread_MutexLock(&stMutexCriticalSection);
  1474. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1475. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1476. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1477. }
  1478. }
  1479. else if (eReturn == RETURN_REJECT)
  1480. {
  1481. #if defined(DEBUG_FILE)
  1482. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Download rejected.");
  1483. #endif
  1484. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1485. switch (ucRejectCode)
  1486. {
  1487. case DOWNLOAD_RESPONSE_DOES_NOT_EXIST:
  1488. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_INVALID_INDEX;
  1489. break;
  1490. case DOWNLOAD_RESPONSE_NOT_DOWNLOADABLE:
  1491. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_FILE_NOT_READABLE;
  1492. break;
  1493. case DOWNLOAD_RESPONSE_NOT_READY:
  1494. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_NOT_READY;
  1495. break;
  1496. case DOWNLOAD_RESPONSE_CRC_FAILED:
  1497. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_CRC_REJECTED;
  1498. break;
  1499. case DOWNLOAD_RESPONSE_REQUEST_INVALID:
  1500. default:
  1501. eResponse = ANTFS_HOST_RESPONSE_DOWNLOAD_REJECT;
  1502. break;
  1503. }
  1504. }
  1505. else if (eReturn == RETURN_SERIAL_ERROR)
  1506. {
  1507. #if defined(DEBUG_FILE)
  1508. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Download serial error.");
  1509. #endif
  1510. DSIThread_MutexLock(&stMutexCriticalSection);
  1511. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1512. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1513. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1514. }
  1515. else
  1516. {
  1517. #if defined(DEBUG_FILE)
  1518. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Download stopped.");
  1519. #endif
  1520. //Disconnect();
  1521. //eANTFSState = ANTFS_HOST_STATE_IDLE;
  1522. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1523. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1524. }
  1525. }
  1526. break;
  1527. case ANTFS_REQUEST_UPLOAD:
  1528. {
  1529. RETURN_STATUS eReturn;
  1530. eANTFSState = ANTFS_HOST_STATE_UPLOADING;
  1531. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_FAIL; //Set a default response
  1532. #if defined(DEBUG_FILE)
  1533. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Requesting upload.");
  1534. #endif
  1535. eReturn = UploadLoop();
  1536. if (eReturn == RETURN_PASS)
  1537. {
  1538. #if defined(DEBUG_FILE)
  1539. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Upload complete.");
  1540. #endif
  1541. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1542. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_PASS;
  1543. }
  1544. else if (eReturn == RETURN_FAIL)
  1545. {
  1546. RETURN_STATUS eDisconnectStatus;
  1547. #if defined(DEBUG_FILE)
  1548. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Upload failed.");
  1549. #endif
  1550. IncFreqStaleCount(MINOR_STALE_COUNT);
  1551. eDisconnectStatus = AttemptDisconnect();
  1552. if(eDisconnectStatus == RETURN_PASS)
  1553. {
  1554. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1555. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_FAIL;
  1556. }
  1557. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1558. {
  1559. #if defined(DEBUG_FILE)
  1560. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error on failed upload.");
  1561. #endif
  1562. DSIThread_MutexLock(&stMutexCriticalSection);
  1563. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1564. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1565. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1566. }
  1567. }
  1568. else if (eReturn == RETURN_REJECT)
  1569. {
  1570. #if defined(DEBUG_FILE)
  1571. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Upload rejected.");
  1572. #endif
  1573. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1574. switch (ucRejectCode)
  1575. {
  1576. case UPLOAD_RESPONSE_DOES_NOT_EXIST:
  1577. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_INVALID_INDEX;
  1578. break;
  1579. case UPLOAD_RESPONSE_NOT_WRITEABLE:
  1580. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_FILE_NOT_WRITEABLE;
  1581. break;
  1582. case UPLOAD_RESPONSE_INSUFFICIENT_SPACE:
  1583. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_INSUFFICIENT_SPACE;
  1584. break;
  1585. default:
  1586. eResponse = ANTFS_HOST_RESPONSE_UPLOAD_REJECT;
  1587. break;
  1588. }
  1589. }
  1590. else if (eReturn == RETURN_SERIAL_ERROR)
  1591. {
  1592. #if defined(DEBUG_FILE)
  1593. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Upload serial error.");
  1594. #endif
  1595. DSIThread_MutexLock(&stMutexCriticalSection);
  1596. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1597. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1598. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1599. }
  1600. else
  1601. {
  1602. #if defined(DEBUG_FILE)
  1603. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Upload stopped.");
  1604. #endif
  1605. //Disconnect();
  1606. //eANTFSState = ANTFS_HOST_STATE_IDLE;
  1607. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1608. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1609. }
  1610. }
  1611. break;
  1612. case ANTFS_REQUEST_MANUAL_TRANSFER:
  1613. {
  1614. RETURN_STATUS eReturn;
  1615. eANTFSState = ANTFS_HOST_STATE_SENDING;
  1616. #if defined(DEBUG_FILE)
  1617. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Sending Direct.");
  1618. #endif
  1619. eReturn = AttemptManualTransfer();
  1620. if (eReturn == RETURN_PASS)
  1621. {
  1622. #if defined(DEBUG_FILE)
  1623. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): ManualTransfer complete.");
  1624. #endif
  1625. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1626. eResponse = ANTFS_HOST_RESPONSE_MANUAL_TRANSFER_PASS;
  1627. }
  1628. else if (eReturn == RETURN_FAIL)
  1629. {
  1630. RETURN_STATUS eDisconnectStatus;
  1631. #if defined(DEBUG_FILE)
  1632. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): ManualTransfer failed to retrieve data.");
  1633. #endif
  1634. IncFreqStaleCount(MINOR_STALE_COUNT);
  1635. eDisconnectStatus = AttemptDisconnect();
  1636. if(eDisconnectStatus == RETURN_PASS)
  1637. {
  1638. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1639. eResponse = ANTFS_HOST_RESPONSE_MANUAL_TRANSFER_RESPONSE_FAIL;
  1640. }
  1641. else if(eDisconnectStatus == RETURN_SERIAL_ERROR)
  1642. {
  1643. #if defined(DEBUG_FILE)
  1644. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error on failed manual transfer.");
  1645. #endif
  1646. DSIThread_MutexLock(&stMutexCriticalSection);
  1647. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1648. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1649. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1650. }
  1651. }
  1652. else if (eReturn == RETURN_REJECT)
  1653. {
  1654. #if defined(DEBUG_FILE)
  1655. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): ManualTransfer rejected due to Tx error.");
  1656. #endif
  1657. IncFreqStaleCount(MIN_STALE_COUNT); //Have to check if a NAK on the Garmin protocol will cause this condition
  1658. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1659. eResponse = ANTFS_HOST_RESPONSE_MANUAL_TRANSFER_TRANSMIT_FAIL;
  1660. }
  1661. else if (eReturn == RETURN_SERIAL_ERROR)
  1662. {
  1663. #if defined(DEBUG_FILE)
  1664. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): ManualTransfer serial error.");
  1665. #endif
  1666. DSIThread_MutexLock(&stMutexCriticalSection);
  1667. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1668. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1669. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1670. }
  1671. else
  1672. {
  1673. #if defined(DEBUG_FILE)
  1674. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): ManualTransfer stopped.");
  1675. #endif
  1676. //Disconnect();
  1677. //eANTFSState = ANTFS_HOST_STATE_IDLE;
  1678. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1679. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1680. }
  1681. }
  1682. break;
  1683. case ANTFS_REQUEST_ERASE:
  1684. {
  1685. RETURN_STATUS eReturn;
  1686. eANTFSState = ANTFS_HOST_STATE_ERASING;
  1687. eResponse = ANTFS_HOST_RESPONSE_ERASE_FAIL; //Set default response
  1688. #if defined(DEBUG_FILE)
  1689. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Erasing...");
  1690. #endif
  1691. eReturn = AttemptErase();
  1692. if (eReturn == RETURN_PASS)
  1693. {
  1694. #if defined(DEBUG_FILE)
  1695. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Erase complete.");
  1696. #endif
  1697. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1698. eResponse = ANTFS_HOST_RESPONSE_ERASE_PASS;
  1699. }
  1700. else if (eReturn == RETURN_FAIL)
  1701. {
  1702. #if defined(DEBUG_FILE)
  1703. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Erase fail.");
  1704. #endif
  1705. IncFreqStaleCount(MINOR_STALE_COUNT);
  1706. eANTFSState = ANTFS_HOST_STATE_TRANSPORT;
  1707. eResponse = ANTFS_HOST_RESPONSE_ERASE_FAIL;
  1708. }
  1709. else if (eReturn == RETURN_SERIAL_ERROR)
  1710. {
  1711. #if defined(DEBUG_FILE)
  1712. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Erase serial error.");
  1713. #endif
  1714. DSIThread_MutexLock(&stMutexCriticalSection);
  1715. if (eANTFSRequest < ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1716. eANTFSRequest = ANTFS_REQUEST_HANDLE_SERIAL_ERROR;
  1717. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1718. }
  1719. else
  1720. {
  1721. #if defined(DEBUG_FILE)
  1722. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Erase stopped.");
  1723. #endif
  1724. //Disconnect();
  1725. //eANTFSState = ANTFS_HOST_STATE_IDLE;
  1726. //eResponse = ANTFS_HOST_RESPONSE_DISCONNECT_PASS;
  1727. }
  1728. }
  1729. break;
  1730. default:
  1731. break;
  1732. }
  1733. //This is where to handle the internal requests, because they can happen asyncronously.
  1734. //We will also clear the request here.
  1735. DSIThread_MutexLock(&stMutexCriticalSection);
  1736. if (eResponse != ANTFS_HOST_RESPONSE_NONE)
  1737. AddResponse(eResponse);
  1738. if (eANTFSRequest == ANTFS_REQUEST_CONNECTION_LOST)
  1739. {
  1740. #if defined(DEBUG_FILE)
  1741. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connection lost.");
  1742. #endif
  1743. eANTFSRequest = ANTFS_REQUEST_NONE;
  1744. bFoundDevice = FALSE;
  1745. if (eANTFSState >= ANTFS_HOST_STATE_CONNECTED)
  1746. {
  1747. #if defined(DEBUG_FILE)
  1748. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Connection lost - ignored.");
  1749. #endif
  1750. ResetHostState();
  1751. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1752. AddResponse(ANTFS_HOST_RESPONSE_CONNECTION_LOST);
  1753. }
  1754. }
  1755. else if (eANTFSRequest == ANTFS_REQUEST_HANDLE_SERIAL_ERROR)
  1756. {
  1757. #if defined(DEBUG_FILE)
  1758. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error!");
  1759. #endif
  1760. HandleSerialError();
  1761. AddResponse(ANTFS_HOST_RESPONSE_SERIAL_FAIL);
  1762. }
  1763. else if (eANTFSRequest == ANTFS_REQUEST_SERIAL_ERROR_HANDLED)
  1764. {
  1765. #if defined(DEBUG_FILE)
  1766. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Serial error handled");
  1767. #endif
  1768. ResetHostState();
  1769. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1770. eANTFSRequest = ANTFS_REQUEST_INIT;
  1771. }
  1772. else
  1773. {
  1774. if (eANTFSState == ANTFS_HOST_STATE_SEARCHING)
  1775. eANTFSRequest = ANTFS_REQUEST_SEARCH; //Set the search request if we're still in search mode
  1776. else
  1777. eANTFSRequest = ANTFS_REQUEST_NONE; //Clear any other request
  1778. }
  1779. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1780. }
  1781. }//while()
  1782. #if defined(DEBUG_FILE)
  1783. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): Exiting thread.");
  1784. #endif
  1785. eANTFSRequest = ANTFS_REQUEST_NONE;
  1786. DSIThread_MutexLock(&stMutexCriticalSection);
  1787. bANTFSThreadRunning = FALSE;
  1788. DSIThread_CondSignal(&stCondANTFSThreadExit);
  1789. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1790. #if defined(__cplusplus)
  1791. return;
  1792. #else
  1793. ExitThread(0);
  1794. #if defined(DEBUG_FILE)
  1795. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTFSThread(): C code reaching return statement unexpectedly.");
  1796. #endif
  1797. return; // Code should not be reached.
  1798. #endif
  1799. }
  1800. /////////////////////////////////////////////////////////////////////
  1801. // Returns: TRUE if the message is for the ANT-FS channel
  1802. BOOL ANTFSHostChannel::FilterANTMessages(ANT_MESSAGE* pstMessage_, UCHAR ucANTChannel_)
  1803. {
  1804. // Some messages do not include the channel number in the response, so
  1805. // they might get processed incorrectly
  1806. if(pstMessage_->ucMessageID == MESG_RESPONSE_EVENT_ID)
  1807. {
  1808. if(pstMessage_->aucData[MESG_EVENT_ID_OFFSET] == MESG_NETWORK_KEY_ID)
  1809. {
  1810. if(pstMessage_->aucData[MESG_CHANNEL_OFFSET] == ucNetworkNumber)
  1811. return TRUE; // this is the network we are using
  1812. }
  1813. }
  1814. else if(pstMessage_->ucMessageID == MESG_STARTUP_MESG_ID)
  1815. {
  1816. return TRUE;
  1817. }
  1818. if(ucANTChannel_ == ucChannelNumber)
  1819. return TRUE;
  1820. return FALSE;
  1821. }
  1822. ///////////////////////////////////////////////////////////////////////
  1823. BOOL ANTFSHostChannel::ReportDownloadProgress(void)
  1824. {
  1825. // We used to perodically signal our transfer progress, we dont do that anymore.
  1826. return TRUE;
  1827. }
  1828. ///////////////////////////////////////////////////////////////////////
  1829. void ANTFSHostChannel::ResetHostState(void)
  1830. {
  1831. // Clear all state variables, while keeping the configuration:
  1832. // channel parameters, search list, ignore list, frequency table selection
  1833. *pbCancel = FALSE;
  1834. bForceFullInit = FALSE;
  1835. memset(aucResponseBuf, 0, sizeof(aucResponseBuf));
  1836. memset(aucRxBuf, 0, sizeof(aucRxBuf));
  1837. memset(aucTxBuf, 0, sizeof(aucTxBuf));
  1838. memset(aucRemoteFriendlyName, 0, sizeof(aucRemoteFriendlyName));
  1839. ucRemoteFriendlyNameLength = 0;
  1840. ucAuthType = 0;
  1841. memset(aucTxPassword, 0, sizeof(aucTxPassword));
  1842. ucTxPasswordLength = 0;
  1843. ucPasswordLength = 0;
  1844. ucDisconnectType = DISCONNECT_COMMAND_LINK;
  1845. ucUndiscoverableTimeDuration = 0;
  1846. ucUndiscoverableAppSpecificDuration = 0;
  1847. pucUploadData = (UCHAR*)NULL;
  1848. pucResponseBuffer = (UCHAR*)NULL;
  1849. pucResponseBufferSize = (UCHAR*)NULL;
  1850. ulAuthResponseTimeout = AUTH_TIMEOUT;
  1851. ucChannelStatus = 0;
  1852. ulFoundBeaconHostID = 0;
  1853. usFoundBeaconPeriod = 0;
  1854. usFoundANTFSDeviceID = 0;
  1855. usFoundANTFSManufacturerID = 0;
  1856. usFoundANTFSDeviceType = 0;
  1857. ucFoundANTDeviceType = 0;
  1858. ucFoundANTTransmitType = 0;
  1859. bFoundDeviceHasData = FALSE;
  1860. bFoundDeviceUploadEnabled = FALSE;
  1861. bFoundDeviceInPairingMode = FALSE;
  1862. ucFoundDeviceAuthenticationType = 0;
  1863. ucFoundDeviceState = 0;
  1864. bFoundDevice = FALSE;
  1865. bFoundDeviceIsValid = FALSE;
  1866. bNewRxEvent = FALSE;
  1867. stFoundDeviceParameters.usDeviceType = 0;
  1868. stFoundDeviceParameters.usManufacturerID = 0;
  1869. stFoundDeviceParameters.ucAuthenticationType = 0;
  1870. stFoundDeviceParameters.ucStatusByte1 = 0;
  1871. stFoundDeviceParameters.ucStatusByte2 = 0;
  1872. // Download Data
  1873. pucTransferBuffer = (UCHAR*)NULL;
  1874. memset(aucTransferBufferFixed, 0, sizeof(aucTransferBufferFixed));
  1875. memset(aucSendDirectBuffer, 0, sizeof(aucSendDirectBuffer));
  1876. ulTransferArrayIndex = 0;
  1877. ulPacketCount = 0;
  1878. ulUploadIndexProgress = 0;
  1879. bTxError = FALSE;
  1880. bRxError = FALSE;
  1881. bReceivedBurst = FALSE;
  1882. bReceivedResponse = FALSE;
  1883. ulTransferTotalBytesRemaining = 0;
  1884. ulTransferBytesInBlock = 0;
  1885. bTransfer = FALSE;
  1886. usRadioChannelID = 0;
  1887. ucTransportFrequencySelection = ANTFS_AUTO_FREQUENCY_SELECTION;
  1888. ucTransportLayerRadioFrequency = 0;
  1889. ucSearchRadioFrequency = ANTFS_RF_FREQ;
  1890. usTransferDataFileIndex = 0;
  1891. ulTransferDataOffset = 0;
  1892. ulTransferByteSize = 0;
  1893. ulTransferBufferSize = 0;
  1894. bLargeData = FALSE;
  1895. ulHostBlockSize = MAX_ULONG;
  1896. ucLinkResponseRetries = 0;
  1897. ucStrikes = STRIKE_COUNT;
  1898. if(eANTFSState == ANTFS_HOST_STATE_OFF)
  1899. {
  1900. pucTransferBufferDynamic = (UCHAR*) NULL;
  1901. }
  1902. else
  1903. {
  1904. eANTFSState = ANTFS_HOST_STATE_IDLE;
  1905. if (pucTransferBufferDynamic)
  1906. {
  1907. if (pucTransferBuffer == pucTransferBufferDynamic)
  1908. pucTransferBuffer = (UCHAR*)NULL;
  1909. delete[] pucTransferBufferDynamic;
  1910. pucTransferBufferDynamic = (UCHAR*)NULL;
  1911. }
  1912. }
  1913. eANTFSRequest = ANTFS_REQUEST_NONE;
  1914. }
  1915. ///////////////////////////////////////////////////////////////////////
  1916. BOOL ANTFSHostChannel::ReInitDevice(void)
  1917. {
  1918. if (eANTFSState != ANTFS_HOST_STATE_OFF)
  1919. this->Close();
  1920. bKillThread = FALSE;
  1921. #if defined(DEBUG_FILE)
  1922. DSIDebug::ThreadWrite("ANTFSHostChannel::ReInitDevice(): Initializing");
  1923. #endif
  1924. if (hANTFSThread == NULL)
  1925. {
  1926. hANTFSThread = DSIThread_CreateThread(&ANTFSHostChannel::ANTFSThreadStart, this);
  1927. if (hANTFSThread == NULL)
  1928. return FALSE;
  1929. }
  1930. if (!bIgnoreListRunning)
  1931. {
  1932. if (DSIThread_MutexInit(&stMutexIgnoreListAccess) != DSI_THREAD_ENONE)
  1933. {
  1934. return FALSE;
  1935. }
  1936. usListIndex = 0;
  1937. bTimerThreadInitDone = FALSE;
  1938. pclQueueTimer = new DSITimer(&ANTFSHostChannel::QueueTimerStart, this, 1000, TRUE);
  1939. if (pclQueueTimer->NoError() == FALSE)
  1940. {
  1941. DSIThread_MutexDestroy(&stMutexIgnoreListAccess);
  1942. return FALSE;
  1943. }
  1944. bIgnoreListRunning = TRUE;
  1945. }
  1946. PopulateTransportFreqTable();
  1947. DSIThread_MutexLock(&stMutexResponseQueue);
  1948. clResponseQueue.Clear();
  1949. DSIThread_MutexUnlock(&stMutexResponseQueue);
  1950. DSIThread_MutexLock(&stMutexCriticalSection);
  1951. eANTFSRequest = ANTFS_REQUEST_INIT;
  1952. DSIThread_CondSignal(&stCondRequest);
  1953. DSIThread_MutexUnlock(&stMutexCriticalSection);
  1954. return TRUE;
  1955. }
  1956. ///////////////////////////////////////////////////////////////////////
  1957. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptSearch(void)
  1958. {
  1959. IGNORE_LIST_ITEM stListItem;
  1960. IGNORE_LIST_ITEM *pstListItem;
  1961. BOOL bFullInit = TRUE;
  1962. BOOL bFoundBroadcastDevice = FALSE;
  1963. UCHAR ucFirstMesgRetries;
  1964. BOOL bFirstMesgResult;
  1965. while (eANTFSState == ANTFS_HOST_STATE_SEARCHING)
  1966. {
  1967. //if (!bFullInit)
  1968. {
  1969. if(pclANT->GetChannelStatus(ucChannelNumber, &ucChannelStatus, MESSAGE_TIMEOUT) == FALSE)
  1970. {
  1971. #if defined(DEBUG_FILE)
  1972. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptOpenBeacon(): Failed ANT_GetChannelStatus().");
  1973. #endif
  1974. return RETURN_SERIAL_ERROR;
  1975. }
  1976. if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_TRACKING_CHANNEL ||
  1977. (ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_SEARCHING_CHANNEL)
  1978. {
  1979. if (pclANT->CloseChannel(ucChannelNumber, ANT_CLOSE_TIMEOUT) == FALSE)
  1980. return RETURN_SERIAL_ERROR;
  1981. if(bFullInit || bForceFullInit)
  1982. {
  1983. if(pclANT->UnAssignChannel(ucChannelNumber) == FALSE)
  1984. return RETURN_SERIAL_ERROR;
  1985. bFullInit = TRUE;
  1986. }
  1987. }
  1988. else if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_UNASSIGNED_CHANNEL)
  1989. {
  1990. bFullInit = TRUE;
  1991. }
  1992. else if(bFullInit) // Status = ASSIGNED, we only need to unassign it for full configuration
  1993. {
  1994. if(pclANT->UnAssignChannel(ucChannelNumber) == FALSE)
  1995. return RETURN_SERIAL_ERROR;
  1996. bFullInit = TRUE;
  1997. }
  1998. }
  1999. if (bFullInit)
  2000. {
  2001. #if defined(DEBUG_FILE)
  2002. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Full Init Begin");
  2003. #endif
  2004. //if (pclANT->ResetSystem() == FALSE)
  2005. // return RETURN_SERIAL_ERROR;
  2006. //DSIThread_Sleep(1000);
  2007. ucFirstMesgRetries = 0;
  2008. while (((bFirstMesgResult = pclANT->SetNetworkKey(ucNetworkNumber, (UCHAR *) aucTheNetworkkey,MESSAGE_TIMEOUT)) == FALSE) && (ucFirstMesgRetries++ < ANTFS_RESPONSE_RETRIES));
  2009. #if defined(DEBUG_FILE)
  2010. if (ucFirstMesgRetries)
  2011. {
  2012. UCHAR aucString[256];
  2013. SNPRINTF((char*)&aucString[0], 256, "ANTFSHostChannel::AttemptSearch(): %d message retries on first message.", ucFirstMesgRetries);
  2014. DSIDebug::ThreadWrite((char*)aucString);
  2015. }
  2016. #endif
  2017. if (!bFirstMesgResult)
  2018. {
  2019. #if defined(DEBUG_FILE)
  2020. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetNetworkKey().");
  2021. #endif
  2022. return RETURN_SERIAL_ERROR;
  2023. }
  2024. if (pclANT->AssignChannel(ucChannelNumber, 0x00, ucNetworkNumber, MESSAGE_TIMEOUT) == FALSE)
  2025. {
  2026. #if defined(DEBUG_FILE)
  2027. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_AssignChannel().");
  2028. #endif
  2029. return RETURN_SERIAL_ERROR;
  2030. }
  2031. if (pclANT->SetChannelPeriod(ucChannelNumber, usTheMessagePeriod, MESSAGE_TIMEOUT) == FALSE)
  2032. {
  2033. #if defined(DEBUG_FILE)
  2034. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetChannelPeriod().");
  2035. #endif
  2036. return RETURN_SERIAL_ERROR;
  2037. }
  2038. if (pclANT->SetChannelSearchTimeout(ucChannelNumber, ANTFS_SEARCH_TIMEOUT, MESSAGE_TIMEOUT) == FALSE)
  2039. {
  2040. #if defined(DEBUG_FILE)
  2041. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetChannelSearchTimeout().");
  2042. #endif
  2043. return RETURN_SERIAL_ERROR;
  2044. }
  2045. if (pclANT->SetChannelRFFrequency(ucChannelNumber, ucSearchRadioFrequency, MESSAGE_TIMEOUT) == FALSE)
  2046. {
  2047. #if defined(DEBUG_FILE)
  2048. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetChannelRFFreq().");
  2049. #endif
  2050. return RETURN_SERIAL_ERROR;
  2051. }
  2052. if (pclANT->SetFastSearch(ucChannelNumber, MESSAGE_TIMEOUT) == FALSE)
  2053. {
  2054. #if defined(DEBUG_FILE)
  2055. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed SetFastSearch().");
  2056. #endif
  2057. return RETURN_SERIAL_ERROR;
  2058. }
  2059. bForceFullInit = FALSE;
  2060. bFullInit = FALSE;
  2061. #if defined(DEBUG_FILE)
  2062. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Full Init Complete");
  2063. #endif
  2064. }
  2065. //This gets reset everytime a device is found, so we need to set it every time
  2066. if(ucTheProxThreshold > 0) //Don't need to send if it is default=0, saves sending command on unsupported devices, plus a little time
  2067. {
  2068. if(pclANT->SetProximitySearch(ucChannelNumber, ucTheProxThreshold, MESSAGE_TIMEOUT) == FALSE)
  2069. {
  2070. #if defined(DEBUG_FILE)
  2071. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetProximitySearch(). Ignored, possibly unsupported device.");
  2072. #endif
  2073. //don't return RETURN_SERIAL_ERROR, Ignore failure so we don't fail on unsupported devices and maintain compatibility.
  2074. }
  2075. }
  2076. //This gets reset everytime a device is found, so we need to set it every time
  2077. if (pclANT->SetChannelID(ucChannelNumber, usRadioChannelID, ucTheDeviceType, ucTheTransmissionType, MESSAGE_TIMEOUT) == FALSE)
  2078. {
  2079. #if defined(DEBUG_FILE)
  2080. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_SetChannelId().");
  2081. #endif
  2082. return RETURN_SERIAL_ERROR;
  2083. }
  2084. #if defined(DEBUG_FILE)
  2085. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Opening channel...");
  2086. #endif
  2087. bFoundDevice = FALSE;
  2088. bFoundBroadcastDevice = FALSE;
  2089. if (pclANT->OpenChannel(ucChannelNumber,MESSAGE_TIMEOUT) == FALSE)
  2090. {
  2091. #if defined(DEBUG_FILE)
  2092. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Failed ANT_OpenChannel().");
  2093. #endif
  2094. return RETURN_SERIAL_ERROR;
  2095. }
  2096. bNewRxEvent = FALSE;
  2097. do
  2098. {
  2099. #if defined(DEBUG_FILE)
  2100. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Waiting for search results...");
  2101. #endif
  2102. if (pclANT->GetChannelStatus(ucChannelNumber, &ucChannelStatus, MESSAGE_TIMEOUT) == FALSE)
  2103. {
  2104. #if defined(DEBUG_FILE)
  2105. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Cannot get ANT Channel Status.");
  2106. #endif
  2107. return RETURN_FAIL;
  2108. //return RETURN_SERIAL_ERROR;
  2109. }
  2110. if (ucChannelStatus < STATUS_SEARCHING_CHANNEL)
  2111. {
  2112. #if defined(DEBUG_FILE)
  2113. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): ANT Channel not searching or tracking.");
  2114. #endif
  2115. return RETURN_FAIL;
  2116. }
  2117. DSIThread_MutexLock(&stMutexCriticalSection);
  2118. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2119. {
  2120. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, SEARCH_STATUS_CHECK_TIMEOUT);
  2121. }
  2122. bNewRxEvent = FALSE;
  2123. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2124. if (*pbCancel == TRUE)
  2125. {
  2126. #if defined(DEBUG_FILE)
  2127. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Searching stopped.");
  2128. #endif
  2129. return RETURN_STOP;
  2130. }
  2131. } while (!bFoundDevice);
  2132. #if defined(DEBUG_FILE)
  2133. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Search results loop exitted.");
  2134. #endif
  2135. if (!bFoundDeviceIsValid)
  2136. {
  2137. #if defined(DEBUG_FILE)
  2138. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Device not sending a valid beacon.");
  2139. #endif
  2140. if(!bRequestPageEnabled)
  2141. continue;
  2142. #if defined(DEBUG_FILE)
  2143. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Attempting to request an ANT-FS session...");
  2144. #endif
  2145. if(AttemptRequestSession() != RETURN_PASS)
  2146. continue;
  2147. bFoundBroadcastDevice = TRUE;
  2148. }
  2149. if (ucFoundDeviceState != REMOTE_DEVICE_STATE_LINK)
  2150. {
  2151. #if defined(DEBUG_FILE)
  2152. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Device not in link mode.");
  2153. #endif
  2154. continue;
  2155. }
  2156. if (pclANT->GetChannelID(ucChannelNumber, (USHORT*)&usFoundANTFSDeviceID, (UCHAR*)&ucFoundANTDeviceType, (UCHAR*)&ucFoundANTTransmitType, MESSAGE_TIMEOUT) == FALSE)
  2157. {
  2158. #if defined(DEBUG_FILE)
  2159. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Cannot get ANT ID.");
  2160. #endif
  2161. continue;
  2162. }
  2163. // Save 2 bytes of the DeviceID
  2164. stFoundDeviceParameters.ulDeviceID &= 0xFFFF0000;
  2165. stFoundDeviceParameters.ulDeviceID |= (0x0000FFFF&usFoundANTFSDeviceID);
  2166. // Check the Ignore list
  2167. stListItem.usID = usFoundANTFSDeviceID;
  2168. stListItem.usManufacturerID = usFoundANTFSManufacturerID;
  2169. stListItem.usDeviceType = usFoundANTFSDeviceType;
  2170. #if defined(DEBUG_FILE)
  2171. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Entering critical section.");
  2172. #endif
  2173. DSIThread_MutexLock(&stMutexIgnoreListAccess);
  2174. pstListItem = (IGNORE_LIST_ITEM *) bsearch(&stListItem, astIgnoreList, usListIndex, sizeof(IGNORE_LIST_ITEM), &ListCompare);
  2175. DSIThread_MutexUnlock(&stMutexIgnoreListAccess);
  2176. #if defined(DEBUG_FILE)
  2177. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Leaving critical section.");
  2178. #endif
  2179. if (pstListItem != NULL)
  2180. {
  2181. #if defined(DEBUG_FILE)
  2182. UCHAR aucString[256];
  2183. SNPRINTF((char *)&aucString[0], 256, "ANTFSHostChannel::AttemptSearch(): Device %u is on the ignore list.", usFoundANTFSDeviceID);
  2184. DSIDebug::ThreadWrite((char *)aucString);
  2185. #endif
  2186. if(bFoundBroadcastDevice)
  2187. {
  2188. ucDisconnectType = DISCONNECT_COMMAND_BROADCAST; // Device is in ignore list, let it go back to broadcast
  2189. if(AttemptDisconnect() == RETURN_SERIAL_ERROR)
  2190. return RETURN_SERIAL_ERROR;
  2191. eANTFSState = ANTFS_HOST_STATE_SEARCHING;
  2192. }
  2193. continue; // Continue searching if the device is on the ignore list.
  2194. }
  2195. #if defined(DEBUG_FILE)
  2196. {
  2197. UCHAR aucString[256];
  2198. SNPRINTF((char *)aucString,256, "ANTFSHostChannel::AttemptSearch(): Found device %u (Manufacturer ID: %u Device Type: %u Beacon Period: %u/32768 Authentication Type: %u).", usFoundANTFSDeviceID, usFoundANTFSManufacturerID, usFoundANTFSDeviceType, usFoundBeaconPeriod, ucFoundDeviceAuthenticationType);
  2199. DSIDebug::ThreadWrite((char *)aucString);
  2200. if (bFoundDeviceHasData)
  2201. DSIDebug::ThreadWrite(" Device has data.");
  2202. else
  2203. DSIDebug::ThreadWrite(" Device has no data.");
  2204. if (bFoundDeviceUploadEnabled)
  2205. DSIDebug::ThreadWrite(" Device has upload enabled.");
  2206. else
  2207. DSIDebug::ThreadWrite(" Device has upload disabled.");
  2208. if (bFoundDeviceInPairingMode)
  2209. DSIDebug::ThreadWrite(" Device is in pairing mode.");
  2210. else
  2211. DSIDebug::ThreadWrite(" Device is not in pairing mode.");
  2212. }
  2213. #endif
  2214. // Check for a match.
  2215. if (IsDeviceMatched(&stFoundDeviceParameters, TRUE) == TRUE)
  2216. {
  2217. // We have found a match.
  2218. #if defined(DEBUG_FILE)
  2219. DSIDebug::ThreadWrite(" Device is a match.");
  2220. #endif
  2221. return RETURN_PASS;
  2222. }
  2223. #if defined(DEBUG_FILE)
  2224. DSIDebug::ThreadWrite(" Device is not a match.");
  2225. #endif
  2226. // No match; continue searching.
  2227. if(bFoundBroadcastDevice)
  2228. {
  2229. ucDisconnectType = DISCONNECT_COMMAND_BROADCAST; // Device is in ignore list, let it go back to broadcast
  2230. if(AttemptDisconnect() == RETURN_SERIAL_ERROR)
  2231. return RETURN_SERIAL_ERROR;
  2232. eANTFSState = ANTFS_HOST_STATE_SEARCHING;
  2233. }
  2234. }
  2235. #if defined(DEBUG_FILE)
  2236. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSearch(): Not searching anymore.");
  2237. #endif
  2238. return RETURN_FAIL;
  2239. }
  2240. ///////////////////////////////////////////////////////////////////////
  2241. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptConnect(void)
  2242. {
  2243. UCHAR ucTxRetries;
  2244. ANTFRAMER_RETURN eTxComplete;
  2245. UCHAR ucRxRetries = 3;
  2246. BOOL bStatus = FALSE;
  2247. if (!bFoundDevice)
  2248. {
  2249. #if defined(DEBUG_FILE)
  2250. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Device not found.");
  2251. #endif
  2252. return RETURN_FAIL;
  2253. }
  2254. if (ucTransportFrequencySelection == ANTFS_AUTO_FREQUENCY_SELECTION)
  2255. ucTransportLayerRadioFrequency = CheckForNewTransportFreq();
  2256. else
  2257. ucTransportLayerRadioFrequency = ucTransportFrequencySelection;
  2258. // Set up the command
  2259. memset(aucTxBuf,0x00,sizeof(aucTxBuf));
  2260. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2261. aucTxBuf[ANTFS_COMMAND_OFFSET] = ANTFS_CONNECT_ID;
  2262. aucTxBuf[TRANSPORT_CHANNEL_FREQ_OFFSET] = ucTransportLayerRadioFrequency;
  2263. aucTxBuf[TRANSPORT_CHANNEL_PERIOD] = TRANSPORT_MESSAGE_PERIOD_CODE;
  2264. Convert_ULONG_To_Bytes(ulHostSerialNumber,
  2265. &aucTxBuf[HOST_ID_OFFSET+3],
  2266. &aucTxBuf[HOST_ID_OFFSET+2],
  2267. &aucTxBuf[HOST_ID_OFFSET+1],
  2268. &aucTxBuf[HOST_ID_OFFSET]);
  2269. #if defined(ACCESS_POINT)
  2270. ucTxRetries = 2;
  2271. #else
  2272. ucTxRetries = 8;
  2273. #endif
  2274. do
  2275. {
  2276. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf,CONNECT_TIMEOUT);
  2277. #if defined(DEBUG_FILE)
  2278. if (eTxComplete == ANTFRAMER_FAIL)
  2279. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Tx error.");
  2280. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  2281. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Tx timeout.");
  2282. #endif
  2283. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  2284. if (eTxComplete != ANTFRAMER_PASS)
  2285. {
  2286. #if defined(DEBUG_FILE)
  2287. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Failed sending connect command.");
  2288. #endif
  2289. return RETURN_FAIL;
  2290. }
  2291. if (pclANT->SetChannelPeriod(ucChannelNumber, TRANSPORT_MESSAGE_PERIOD, MESSAGE_TIMEOUT) == FALSE)
  2292. {
  2293. #if defined(DEBUG_FILE)
  2294. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Failed ANT_SetChannelPeriod().");
  2295. #endif
  2296. return RETURN_SERIAL_ERROR;
  2297. }
  2298. if (pclANT->SetChannelSearchTimeout(ucChannelNumber, TRANSPORT_SEARCH_TIMEOUT, MESSAGE_TIMEOUT) == FALSE)
  2299. {
  2300. #if defined(DEBUG_FILE)
  2301. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Failed ANT_SetChannelSearchTimeout().");
  2302. #endif
  2303. return RETURN_SERIAL_ERROR;
  2304. }
  2305. if (pclANT->SetChannelRFFrequency(ucChannelNumber, ucTransportLayerRadioFrequency, MESSAGE_TIMEOUT) == FALSE)
  2306. {
  2307. #if defined(DEBUG_FILE)
  2308. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Failed ANT_SetChannelRFFreq().");
  2309. #endif
  2310. return RETURN_SERIAL_ERROR;
  2311. }
  2312. do
  2313. {
  2314. bNewRxEvent = FALSE;
  2315. DSIThread_MutexLock(&stMutexCriticalSection);
  2316. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2317. {
  2318. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BROADCAST_TIMEOUT);
  2319. if (ucResult != DSI_THREAD_ENONE)
  2320. {
  2321. #if defined(DEBUG_FILE)
  2322. if(ucResult == DSI_THREAD_EOTHER)
  2323. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): CondTimedWait() Failed!");
  2324. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Rx timeout.");
  2325. #endif
  2326. IncFreqStaleCount(MAX_STALE_COUNT);
  2327. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2328. return RETURN_FAIL;
  2329. }
  2330. }
  2331. bNewRxEvent = FALSE;
  2332. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2333. if (*pbCancel == TRUE)
  2334. {
  2335. #if defined(DEBUG_FILE)
  2336. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Stopped.");
  2337. #endif
  2338. return RETURN_STOP;
  2339. }
  2340. if (ucFoundDeviceState == REMOTE_DEVICE_STATE_AUTH)
  2341. bStatus = TRUE;
  2342. } while ((bStatus == FALSE) && ucRxRetries--);
  2343. if (!bStatus)
  2344. {
  2345. #if defined(DEBUG_FILE)
  2346. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Remote not in auth mode.");
  2347. #endif
  2348. IncFreqStaleCount(MINOR_STALE_COUNT); // Investigate why this happens, may be that the remote is not updating it's beacon fast enough.
  2349. return RETURN_FAIL;
  2350. }
  2351. if (ulFoundBeaconHostID != ulHostSerialNumber)
  2352. {
  2353. #if defined(DEBUG_FILE)
  2354. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Remote connected to another host.");
  2355. #endif
  2356. IncFreqStaleCount(MAX_STALE_COUNT);
  2357. return RETURN_FAIL;
  2358. }
  2359. return RETURN_PASS;
  2360. }
  2361. ///////////////////////////////////////////////////////////////////////
  2362. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptRequestSession(void)
  2363. {
  2364. ANTFRAMER_RETURN eTxComplete;
  2365. UCHAR ucTxRetries = 4;
  2366. UCHAR ucRxRetries = 3;
  2367. BOOL bStatus = FALSE;
  2368. USHORT usBroadcastANTDeviceID = 0;
  2369. UCHAR ucBroadcastANTDeviceType = 0;
  2370. UCHAR ucBroadcastANTTransmitType = 0;
  2371. if (pclANT->GetChannelStatus(ucChannelNumber, &ucChannelStatus, MESSAGE_TIMEOUT) == FALSE)
  2372. {
  2373. #if defined(DEBUG_FILE)
  2374. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Cannot get ANT Channel Status.");
  2375. #endif
  2376. return RETURN_FAIL;
  2377. }
  2378. if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) != STATUS_TRACKING_CHANNEL)
  2379. {
  2380. #if defined(DEBUG_FILE)
  2381. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Not connected to a broadcast device");
  2382. #endif
  2383. return RETURN_FAIL;
  2384. }
  2385. if (pclANT->GetChannelID(ucChannelNumber, (USHORT*)&usBroadcastANTDeviceID, (UCHAR*)&ucBroadcastANTDeviceType, (UCHAR*)&ucBroadcastANTTransmitType, MESSAGE_TIMEOUT) == FALSE)
  2386. {
  2387. #if defined(DEBUG_FILE)
  2388. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Cannot get ANT ID.");
  2389. #endif
  2390. }
  2391. else
  2392. {
  2393. #if defined(DEBUG_FILE)
  2394. UCHAR aucString[256];
  2395. SNPRINTF((char *)aucString,256, "ANTFSHostChannel::AttemptRequestSession(): Broadcast Device (Device Number: %u Device Type: %u Tx Type: %u).", usBroadcastANTDeviceID, ucBroadcastANTDeviceType, ucBroadcastANTTransmitType);
  2396. DSIDebug::ThreadWrite((char *)aucString);
  2397. #endif
  2398. }
  2399. memset(aucTxBuf, REQUEST_PAGE_INVALID, sizeof(aucTxBuf));
  2400. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_REQUEST_PAGE_ID ;
  2401. aucTxBuf[REQUEST_TX_RESPONSE_OFFSET] = (UCHAR) 0x00;
  2402. aucTxBuf[REQUEST_PAGE_NUMBER_OFFSET] = ANTFS_BEACON_ID;
  2403. aucTxBuf[REQUEST_COMMAND_TYPE_OFFSET] = ANTFS_REQUEST_SESSION;
  2404. // Send request session message
  2405. do
  2406. {
  2407. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf, REQUEST_TIMEOUT);
  2408. #if defined(DEBUG_FILE)
  2409. if (eTxComplete == ANTFRAMER_FAIL)
  2410. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Tx error.");
  2411. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  2412. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Tx timeout.");
  2413. #endif
  2414. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  2415. if (eTxComplete != ANTFRAMER_PASS)
  2416. {
  2417. #if defined(DEBUG_FILE)
  2418. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Failed sending request page.");
  2419. #endif
  2420. return RETURN_FAIL;
  2421. }
  2422. // Wait for beacon
  2423. do
  2424. {
  2425. bFoundDevice = FALSE;
  2426. bNewRxEvent = FALSE;
  2427. DSIThread_MutexLock(&stMutexCriticalSection);
  2428. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2429. {
  2430. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BROADCAST_TIMEOUT);
  2431. if(ucResult != DSI_THREAD_ENONE)
  2432. {
  2433. #if defined(DEBUG_FILE)
  2434. if(ucResult == DSI_THREAD_EOTHER)
  2435. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): CondTimedWait() Failed!");
  2436. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): Rx timeout.");
  2437. #endif
  2438. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2439. return RETURN_FAIL;
  2440. }
  2441. }
  2442. bNewRxEvent = FALSE;
  2443. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2444. if (*pbCancel == TRUE)
  2445. {
  2446. #if defined(DEBUG_FILE)
  2447. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): ANT-FS session request stopped.");
  2448. #endif
  2449. return RETURN_STOP;
  2450. }
  2451. if(bFoundDevice && bFoundDeviceIsValid)
  2452. bStatus = TRUE;
  2453. } while ((bStatus == FALSE) && ucRxRetries--);
  2454. if(!bStatus)
  2455. {
  2456. #if defined(DEBUG_FILE)
  2457. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptRequestSession(): No response to ANT-FS Session request.");
  2458. #endif
  2459. // TODO: Possibly blackout the device for a period of time here? Might need a different blacklist for this, as we should
  2460. // blacklist based on the Channel ID instead of beacon parameters
  2461. // Blackout(usFoundANTFSDeviceID, 0, 0, 300); // 5 min?
  2462. return RETURN_FAIL;
  2463. }
  2464. if(eANTFSState != ANTFS_HOST_STATE_SEARCHING)
  2465. {
  2466. usFoundANTFSDeviceID = usBroadcastANTDeviceID; // TODO: Is this needed? Assumes device ID is derived from serial number
  2467. ucFoundANTDeviceType = ucBroadcastANTDeviceType;
  2468. ucFoundANTTransmitType = ucBroadcastANTTransmitType;
  2469. }
  2470. return RETURN_PASS;
  2471. }
  2472. ///////////////////////////////////////////////////////////////////////
  2473. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptDisconnect(void)
  2474. {
  2475. UCHAR ucTxRetries;
  2476. ANTFRAMER_RETURN eTxComplete;
  2477. if(eANTFSState != ANTFS_HOST_STATE_SEARCHING)
  2478. eANTFSState = ANTFS_HOST_STATE_DISCONNECTING;
  2479. //We change the state here so that we don't get connection lost responses after we've decided to disconnect
  2480. if (bFoundDevice)
  2481. {
  2482. bFoundDevice = FALSE;
  2483. memset(aucTxBuf, 0x00, sizeof(aucTxBuf));
  2484. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2485. aucTxBuf[ANTFS_COMMAND_OFFSET] = ANTFS_DISCONNECT_ID;
  2486. aucTxBuf[DISCONNECT_COMMAND_TYPE_OFFSET] = ucDisconnectType;
  2487. aucTxBuf[DISCONNECT_TIME_DURATION_OFFSET] = ucUndiscoverableTimeDuration;
  2488. aucTxBuf[DISCONNECT_APP_DURATION_OFFSET] = ucUndiscoverableAppSpecificDuration;
  2489. ucTxRetries = 8;
  2490. do
  2491. {
  2492. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf, DISCONNECT_TIMEOUT);
  2493. #if defined(DEBUG_FILE)
  2494. if (eTxComplete == ANTFRAMER_FAIL)
  2495. DSIDebug::ThreadWrite("ANTFSHostChannel::Disconnect(): Tx error.");
  2496. else if(eTxComplete == ANTFRAMER_TIMEOUT)
  2497. DSIDebug::ThreadWrite("ANTFSHostChannel::Disconnect(): Tx timeout.");
  2498. #endif
  2499. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  2500. }
  2501. if(ucDisconnectType == DISCONNECT_COMMAND_BROADCAST)
  2502. {
  2503. // Go back to link frequency and channel period
  2504. if (pclANT->SetChannelPeriod(ucChannelNumber, usTheMessagePeriod, MESSAGE_TIMEOUT) == FALSE)
  2505. {
  2506. #if defined(DEBUG_FILE)
  2507. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDisconnect(): Failed ANT_SetChannelPeriod().");
  2508. #endif
  2509. return RETURN_SERIAL_ERROR;
  2510. }
  2511. if (pclANT->SetChannelRFFrequency(ucChannelNumber, ucSearchRadioFrequency, MESSAGE_TIMEOUT) == FALSE)
  2512. {
  2513. #if defined(DEBUG_FILE)
  2514. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDisconnect(): Failed ANT_SetChannelRFFreq().");
  2515. #endif
  2516. return RETURN_SERIAL_ERROR;
  2517. }
  2518. }
  2519. else // DISCONNECT_TYPE_LINK or custom disconnect types
  2520. {
  2521. if(ucDisconnectType != DISCONNECT_COMMAND_LINK)
  2522. {
  2523. #if defined(DEBUG_FILE)
  2524. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDisconnect(): Application specific disconnect type.");
  2525. #endif
  2526. // Disconnect anyway, and close the channel
  2527. }
  2528. // Close the channel
  2529. if(pclANT->GetChannelStatus(ucChannelNumber, &ucChannelStatus, MESSAGE_TIMEOUT) == FALSE)
  2530. {
  2531. #if defined(DEBUG_FILE)
  2532. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDisconnect(): Failed ANT_GetChannelStatus().");
  2533. #endif
  2534. return RETURN_SERIAL_ERROR;
  2535. }
  2536. if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_TRACKING_CHANNEL ||
  2537. (ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_SEARCHING_CHANNEL)
  2538. {
  2539. if (pclANT->CloseChannel(ucChannelNumber, ANT_CLOSE_TIMEOUT) == FALSE)
  2540. return RETURN_SERIAL_ERROR;
  2541. if (pclANT->UnAssignChannel(ucChannelNumber, MESSAGE_TIMEOUT) == FALSE)
  2542. return RETURN_SERIAL_ERROR;
  2543. }
  2544. else if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) == STATUS_ASSIGNED_CHANNEL)
  2545. {
  2546. if (pclANT->UnAssignChannel(ucChannelNumber, MESSAGE_TIMEOUT) == FALSE)
  2547. return RETURN_SERIAL_ERROR;
  2548. }
  2549. }
  2550. usFoundANTFSManufacturerID = 0;
  2551. usFoundANTFSDeviceType = 0;
  2552. bFoundDeviceHasData = FALSE;
  2553. ucDisconnectType = DISCONNECT_COMMAND_LINK;
  2554. ucUndiscoverableTimeDuration = 0;
  2555. ucUndiscoverableAppSpecificDuration = 0;
  2556. return RETURN_PASS;
  2557. }
  2558. ///////////////////////////////////////////////////////////////////////
  2559. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptSwitchFrequency()
  2560. {
  2561. USHORT usTransportChannelPeriod;
  2562. UCHAR ucTxRetries;
  2563. ANTFRAMER_RETURN eTxComplete;
  2564. UCHAR ucRxRetries = 3;
  2565. BOOL bStatus = FALSE;
  2566. if (ucTransportFrequencySelection == ANTFS_AUTO_FREQUENCY_SELECTION)
  2567. ucTransportLayerRadioFrequency = CheckForNewTransportFreq();
  2568. else
  2569. ucTransportLayerRadioFrequency = ucTransportFrequencySelection;
  2570. switch(ucTransportChannelPeriodSelection)
  2571. {
  2572. case BEACON_PERIOD_0_5_HZ:
  2573. usTransportChannelPeriod = 65535;
  2574. break;
  2575. case BEACON_PERIOD_1_HZ:
  2576. usTransportChannelPeriod = 32768;
  2577. break;
  2578. case BEACON_PERIOD_2_HZ:
  2579. usTransportChannelPeriod = 16384;
  2580. break;
  2581. case BEACON_PERIOD_4_HZ:
  2582. usTransportChannelPeriod = 8192;
  2583. break;
  2584. case BEACON_PERIOD_8_HZ:
  2585. default:
  2586. usTransportChannelPeriod = 4096;
  2587. break;
  2588. }
  2589. // Set up the command
  2590. memset(aucTxBuf,0x00,sizeof(aucTxBuf));
  2591. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2592. aucTxBuf[ANTFS_COMMAND_OFFSET] = ANTFS_LINK_ID;
  2593. aucTxBuf[TRANSPORT_CHANNEL_FREQ_OFFSET] = ucTransportLayerRadioFrequency;
  2594. aucTxBuf[TRANSPORT_CHANNEL_PERIOD] = ucTransportChannelPeriodSelection;
  2595. Convert_ULONG_To_Bytes(ulHostSerialNumber,
  2596. &aucTxBuf[HOST_ID_OFFSET+3],
  2597. &aucTxBuf[HOST_ID_OFFSET+2],
  2598. &aucTxBuf[HOST_ID_OFFSET+1],
  2599. &aucTxBuf[HOST_ID_OFFSET]);
  2600. ucTxRetries = 8;
  2601. do
  2602. {
  2603. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf,CONNECT_TIMEOUT);
  2604. #if defined(DEBUG_FILE)
  2605. if (eTxComplete == ANTFRAMER_FAIL)
  2606. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Tx error.");
  2607. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  2608. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Tx timeout.");
  2609. #endif
  2610. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  2611. if (eTxComplete != ANTFRAMER_PASS)
  2612. {
  2613. #if defined(DEBUG_FILE)
  2614. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Failed sending connect command.");
  2615. #endif
  2616. return RETURN_FAIL;
  2617. }
  2618. // Change channel parameters
  2619. if(ucTransportChannelPeriodSelection != BEACON_PERIOD_KEEP)
  2620. {
  2621. if (pclANT->SetChannelPeriod(ucChannelNumber, usTransportChannelPeriod, MESSAGE_TIMEOUT) == FALSE)
  2622. {
  2623. #if defined(DEBUG_FILE)
  2624. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Failed ANT_SetChannelPeriod().");
  2625. #endif
  2626. return RETURN_SERIAL_ERROR;
  2627. }
  2628. }
  2629. if (pclANT->SetChannelRFFrequency(ucChannelNumber, ucTransportLayerRadioFrequency, MESSAGE_TIMEOUT) == FALSE)
  2630. {
  2631. #if defined(DEBUG_FILE)
  2632. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Failed ANT_SetChannelRFFreq().");
  2633. #endif
  2634. return RETURN_SERIAL_ERROR;
  2635. }
  2636. // Check that the remote device changed its channel parameters as well, and that it is still a valid beacon
  2637. do
  2638. {
  2639. bNewRxEvent = FALSE;
  2640. DSIThread_MutexLock(&stMutexCriticalSection);
  2641. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2642. {
  2643. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BROADCAST_TIMEOUT);
  2644. if (ucResult != DSI_THREAD_ENONE)
  2645. {
  2646. #if defined(DEBUG_FILE)
  2647. if(ucResult == DSI_THREAD_EOTHER)
  2648. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): CondTimedWait() Failed!");
  2649. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Rx timeout.");
  2650. #endif
  2651. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2652. return RETURN_FAIL;
  2653. }
  2654. }
  2655. bNewRxEvent = FALSE;
  2656. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2657. if (*pbCancel == TRUE)
  2658. {
  2659. #if defined(DEBUG_FILE)
  2660. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Stopped.");
  2661. #endif
  2662. return RETURN_STOP;
  2663. }
  2664. if (ucFoundDeviceState == REMOTE_DEVICE_STATE_TRANS)
  2665. bStatus = TRUE;
  2666. } while ((bStatus == FALSE) && ucRxRetries--);
  2667. if (!bStatus)
  2668. {
  2669. #if defined(DEBUG_FILE)
  2670. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptSwitchFrequency(): Remote device not in transport state.");
  2671. #endif
  2672. IncFreqStaleCount(MINOR_STALE_COUNT); // Investigate why this happens, may be that the remote is not updating it's beacon fast enough.
  2673. return RETURN_FAIL;
  2674. }
  2675. return RETURN_PASS;
  2676. }
  2677. ///////////////////////////////////////////////////////////////////////
  2678. void ANTFSHostChannel::Ping(void)
  2679. {
  2680. UCHAR ucTxRetries;
  2681. ANTFRAMER_RETURN eTxComplete;
  2682. if (eANTFSState == ANTFS_HOST_STATE_TRANSPORT || eANTFSState == ANTFS_HOST_STATE_CONNECTED)
  2683. {
  2684. memset(aucTxBuf, 0x00, sizeof(aucTxBuf));
  2685. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2686. aucTxBuf[ANTFS_COMMAND_OFFSET] = ANTFS_PING_ID;
  2687. ucTxRetries = 8;
  2688. do
  2689. {
  2690. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf, PING_TIMEOUT);
  2691. #if defined(DEBUG_FILE)
  2692. if (eTxComplete == ANTFRAMER_FAIL)
  2693. DSIDebug::ThreadWrite("ANTFSHostChannel::Ping(): Tx error.");
  2694. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  2695. DSIDebug::ThreadWrite("ANTFSHostChannel::Ping(): Tx timeout.");
  2696. #endif
  2697. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  2698. }
  2699. }
  2700. ///////////////////////////////////////////////////////////////////////
  2701. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptDownload(void)
  2702. {
  2703. UCHAR ucNoRxTicks = 4;
  2704. UCHAR ucAttemptTick = 15;
  2705. UCHAR aucDownloadRequest[16];
  2706. ANTFRAMER_RETURN eTxComplete;
  2707. UCHAR ucCRCReset = 1;
  2708. USHORT usCRCCalc = 0;
  2709. ULONG ulDataOffset;
  2710. BOOL bDone = FALSE;
  2711. ULONG ulLastTransferArrayIndex = 0;
  2712. ULONG ulLastUpdateTime;
  2713. /* //The found device state may not have updated yet if we attempt to ul/dl right after authentication
  2714. if ((ucFoundDeviceState != REMOTE_DEVICE_STATE_TRANS) && (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  2715. return RETURN_FAIL; // Not in the correct mode.
  2716. */
  2717. ulTransferArrayIndex = 0;
  2718. bReceivedResponse = FALSE;
  2719. bReceivedBurst = FALSE;
  2720. #if defined(DEBUG_FILE)
  2721. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Starting download...");
  2722. #endif
  2723. ulLastUpdateTime = DSIThread_GetSystemTime();
  2724. do
  2725. {
  2726. ulDataOffset = ulTransferDataOffset;
  2727. if (bLargeData)
  2728. {
  2729. if (ulTransferArrayIndex >= 16) // The first 16 bytes of the array form the response packet so don't include it in the data offset.
  2730. ulDataOffset += (ulTransferArrayIndex - 16);
  2731. }
  2732. else
  2733. {
  2734. if (ulTransferArrayIndex >= 8) // The first 8 bytes of the array form the response packet so don't include it in the data offset.
  2735. ulDataOffset += (ulTransferArrayIndex - 8);
  2736. }
  2737. if ((!bReceivedBurst) &&(!bReceivedResponse)) //prevents us from sending requests until the Rx bursts have stopped and been cleared.
  2738. {
  2739. if (ucAttemptTick-- == 0)
  2740. {
  2741. #if defined(DEBUG_FILE)
  2742. DSIDebug::ThreadWrite("Download(): Maximum retry attempts reached.");
  2743. #endif
  2744. return RETURN_FAIL;
  2745. }
  2746. bRxError = FALSE;
  2747. DSIThread_MutexLock(&stMutexCriticalSection);
  2748. bNewRxEvent = FALSE;
  2749. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2750. {
  2751. UCHAR waitResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, DOWNLOAD_RESYNC_TIMEOUT);
  2752. if(waitResult != DSI_THREAD_ENONE)
  2753. {
  2754. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2755. if (waitResult == DSI_THREAD_ETIMEDOUT)
  2756. {
  2757. #if defined(DEBUG_FILE)
  2758. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload(): Fail syncing with remote device.");
  2759. #endif
  2760. return RETURN_FAIL; //if we've waited 10 seconds and there is no incoming messages, something is wrong with the connection
  2761. }
  2762. else
  2763. {
  2764. #if defined(DEBUG_FILE)
  2765. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload(): CondTimedWait() Failed!");
  2766. #endif
  2767. return RETURN_FAIL; //If the condition variable is broken, we are in trouble
  2768. }
  2769. }
  2770. if (bNewRxEvent == FALSE) //The way our threads are setup, we should never see this anymore now that the locks are fixed
  2771. {
  2772. #if defined(DEBUG_FILE)
  2773. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload():: CondTimedWait false alarm signal.");
  2774. #endif
  2775. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2776. continue;
  2777. }
  2778. }
  2779. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2780. if (*pbCancel == TRUE)
  2781. {
  2782. #if defined(DEBUG_FILE)
  2783. DSIDebug::ThreadWrite("AttemptDownload(): Stopped.");
  2784. #endif
  2785. return RETURN_STOP;
  2786. }
  2787. // Send out the download command.
  2788. memset(aucDownloadRequest, 0x00, sizeof(aucDownloadRequest));
  2789. if (bLargeData)
  2790. {
  2791. aucDownloadRequest[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2792. aucDownloadRequest[ANTFS_COMMAND_OFFSET] = ANTFS_DOWNLOAD_BIG_ID;
  2793. Convert_USHORT_To_Bytes(usTransferDataFileIndex,
  2794. &aucDownloadRequest[DATA_INDEX_OFFSET + 1],
  2795. &aucDownloadRequest[DATA_INDEX_OFFSET]);
  2796. Convert_ULONG_To_Bytes(ulDataOffset,
  2797. &aucDownloadRequest[DOWNLOAD_DATA_OFFSET_OFFSET + 3],
  2798. &aucDownloadRequest[DOWNLOAD_DATA_OFFSET_OFFSET + 2],
  2799. &aucDownloadRequest[DOWNLOAD_DATA_OFFSET_OFFSET + 1],
  2800. &aucDownloadRequest[DOWNLOAD_DATA_OFFSET_OFFSET]);
  2801. if (ulTransferByteSize) //if the max file size is set
  2802. {
  2803. ULONG ulLocalBlockSize = MAX_ULONG;
  2804. if(ulHostBlockSize)
  2805. ulLocalBlockSize = ulHostBlockSize;
  2806. //We need to set the block size to the max transfer size - the offset.
  2807. if(ulLocalBlockSize > (ulTransferByteSize - (ulDataOffset - ulTransferDataOffset)))
  2808. ulLocalBlockSize = ulTransferByteSize - (ulDataOffset - ulTransferDataOffset);
  2809. Convert_ULONG_To_Bytes(ulLocalBlockSize,
  2810. &aucDownloadRequest[DOWNLOAD_MAX_BLOCK_SIZE_OFFSET + 3],
  2811. &aucDownloadRequest[DOWNLOAD_MAX_BLOCK_SIZE_OFFSET + 2],
  2812. &aucDownloadRequest[DOWNLOAD_MAX_BLOCK_SIZE_OFFSET + 1],
  2813. &aucDownloadRequest[DOWNLOAD_MAX_BLOCK_SIZE_OFFSET]);
  2814. }
  2815. if (ulTransferArrayIndex > 16) // If the download has progressed at least to the first data packet
  2816. ucCRCReset = 0; // Clear the Initial download request bit, so the client knows to start checking our CRC
  2817. aucDownloadRequest[DOWNLOAD_INITIAL_REQUEST_OFFSET] = ucCRCReset; // Set initial request byte
  2818. if (ucCRCReset == 0) // If this is not the initial request
  2819. { // Calculate and send a non-zero CRC value
  2820. if (pucTransferBuffer != NULL) // Just to make sure the transfer buffer has been created
  2821. usCRCCalc = CRC_Calc16(&pucTransferBuffer[16], ulDataOffset-ulTransferDataOffset); //CRC_UpdateCRC16
  2822. else
  2823. usCRCCalc = 0;
  2824. Convert_USHORT_To_Bytes(usCRCCalc,
  2825. &aucDownloadRequest[DOWNLOAD_CRC_SEED_OFFSET + 1],
  2826. &aucDownloadRequest[DOWNLOAD_CRC_SEED_OFFSET]);
  2827. }
  2828. }
  2829. else
  2830. {
  2831. aucDownloadRequest[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  2832. aucDownloadRequest[ANTFS_COMMAND_OFFSET] = ANTFS_DOWNLOAD_SMALL_ID;
  2833. Convert_USHORT_To_Bytes(usTransferDataFileIndex,
  2834. &aucDownloadRequest[DATA_INDEX_OFFSET + 1],
  2835. &aucDownloadRequest[DATA_INDEX_OFFSET]);
  2836. Convert_ULONG_To_Bytes(ulDataOffset,
  2837. (UCHAR*)NULL,
  2838. (UCHAR*)NULL,
  2839. &aucDownloadRequest[DATA_OFFSET_SMALL_OFFSET + 1],
  2840. &aucDownloadRequest[DATA_OFFSET_SMALL_OFFSET]);
  2841. Convert_ULONG_To_Bytes(ulTransferByteSize,
  2842. (UCHAR*)NULL,
  2843. (UCHAR*)NULL,
  2844. &aucDownloadRequest[MAX_BLOCK_SIZE_SMALL_OFFSET + 1],
  2845. &aucDownloadRequest[MAX_BLOCK_SIZE_SMALL_OFFSET]);
  2846. }
  2847. if (bLargeData)
  2848. eTxComplete = pclANT->SendANTFSTransfer(ucChannelNumber, (UCHAR*)NULL, (UCHAR*)NULL, aucDownloadRequest, 16, ACKNOWLEDGED_TIMEOUT, (ULONG*)NULL);
  2849. else
  2850. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucDownloadRequest, ACKNOWLEDGED_TIMEOUT);
  2851. #if defined(DEBUG_FILE)
  2852. if (eTxComplete == ANTFRAMER_FAIL)
  2853. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Tx error sending download command.");
  2854. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  2855. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Tx timeout sending download command.");
  2856. #endif
  2857. //Removed the immediate retries to avoid the issue of queing up requests while we get a response for a request we thought we failed.
  2858. if (eTxComplete == ANTFRAMER_TIMEOUT)
  2859. return RETURN_FAIL;
  2860. }
  2861. //Do not need to clear bReceivedBurst here because it will be done if the transfer fails, if we timeout, or receive a broadcast.
  2862. //Now we wait for a response...
  2863. while (bDone == FALSE)
  2864. {
  2865. //Wait for an rxEvent before starting to check the data
  2866. //Since this event is fired for many circumstances we manage all the error checking below and
  2867. //just use this for the wait functionality.
  2868. DSIThread_MutexLock(&stMutexCriticalSection);
  2869. bNewRxEvent = FALSE;
  2870. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  2871. {
  2872. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BURST_CHECK_TIMEOUT);
  2873. }
  2874. DSIThread_MutexUnlock(&stMutexCriticalSection);
  2875. if (*pbCancel == TRUE)
  2876. {
  2877. #if defined(DEBUG_FILE)
  2878. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload(): Stopped.");
  2879. #endif
  2880. return RETURN_STOP;
  2881. }
  2882. if (bReceivedResponse) //If a response has been received, process it.
  2883. {
  2884. bReceivedResponse = FALSE; //Clear these for any potential retries
  2885. bReceivedBurst = FALSE; //Clearing this here allows for quicker retries, otherwise we would have to wait for an incoming broadcast to clear it
  2886. bDone = TRUE; //Mark that we are done... for now.
  2887. if ((pucTransferBufferDynamic) && ((pucTransferBufferDynamic[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_DOWNLOAD_SMALL_ID) || (pucTransferBufferDynamic[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_DOWNLOAD_BIG_ID)))
  2888. {
  2889. /*if (pucTransferBufferDynamic[DOWNLOAD_RESPONSE_OFFSET] == DOWNLOAD_RESPONSE_CRC_FAILED)
  2890. {
  2891. #if defined(DEBUG_FILE)
  2892. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): CRC failed, download failed.");
  2893. #endif
  2894. //clear variables to retry from start.
  2895. ucCRCReset = 1;
  2896. usCRCCalc = 0;
  2897. ulTransferArrayIndex = 16;
  2898. ulLastTransferArrayIndex = 16;
  2899. bDone = FALSE;
  2900. break;
  2901. }
  2902. else*/ //Removed Failed CRC response check and automatic retry. Return the response to the application and allow it to decide to retry or to skip the file. Can also use Recover Transfer data to recover partial files as this seems to be the most way a corrupted file will fail.
  2903. if (pucTransferBufferDynamic[DOWNLOAD_RESPONSE_OFFSET] != DOWNLOAD_RESPONSE_OK)
  2904. {
  2905. #if defined(DEBUG_FILE)
  2906. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Download request rejected.");
  2907. #endif
  2908. ucRejectCode = pucTransferBufferDynamic[DOWNLOAD_RESPONSE_OFFSET];
  2909. return RETURN_REJECT;
  2910. }
  2911. }
  2912. else
  2913. {
  2914. #if defined(DEBUG_FILE)
  2915. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Unknown response during download.");
  2916. #endif
  2917. return RETURN_FAIL;
  2918. }
  2919. // Check if we need to check the CRC
  2920. if ((bLargeData) &&
  2921. (((ulDataOffset - ulTransferDataOffset) + ulTransferBytesInBlock + 8) < ulTransferArrayIndex)) //if there is one more packet beyond the data, we will process the CRC
  2922. {
  2923. ULONG ulCRCLocation, ulLength;
  2924. USHORT usReceivedCRC;
  2925. USHORT usCalcCRC;
  2926. ulLength = (ulDataOffset - ulTransferDataOffset) + ulTransferBytesInBlock; //find length of actual data that needs to be CRC checked
  2927. ulCRCLocation = ulTransferArrayIndex - 2; //Assume that the CRC will be the last 2 bytes of the last packet received
  2928. ulTransferArrayIndex = ulLength + 16; //correct ulTransferArrayIndex in case we are downloading in odd blocks.
  2929. usReceivedCRC = pucTransferBufferDynamic[ulCRCLocation];
  2930. usReceivedCRC |= ((USHORT)pucTransferBufferDynamic[ulCRCLocation + 1] << 8);
  2931. usCalcCRC = CRC_Calc16(&pucTransferBufferDynamic[16], ulLength); //Calculate the CRC of the received data from the start, this should always be what the CRC value is based in becaue we pass in the initial seed
  2932. if (usCalcCRC != usReceivedCRC)
  2933. {
  2934. #if defined(DEBUG_FILE)
  2935. char cBuffer[256];
  2936. SNPRINTF(cBuffer, 256, "ANTFSHostChannel::Download(): Failed CRC Check. Expected %d, Got %d",usCalcCRC, usReceivedCRC);
  2937. DSIDebug::ThreadWrite(cBuffer);
  2938. #endif
  2939. //return RETURN_FAIL;
  2940. //clear variables to retry from start.
  2941. ucCRCReset = 1;
  2942. usCRCCalc = 0;
  2943. ulTransferArrayIndex = 16;
  2944. ulLastTransferArrayIndex = 16;
  2945. bDone = FALSE;
  2946. }
  2947. }
  2948. //Catch the cases where we get a completed transfer but there are more packets coming
  2949. if ((bLargeData) && ((ulTransferArrayIndex -16) < ulTransferTotalBytesRemaining))
  2950. bDone = FALSE;
  2951. ucNoRxTicks = 4; // Reset counter
  2952. ucAttemptTick = 15; // Reset counter for attempts of request
  2953. break;
  2954. }
  2955. if (bRxError)
  2956. {
  2957. #if defined(DEBUG_FILE)
  2958. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Rx error.");
  2959. #endif
  2960. break;
  2961. }
  2962. if (ulTransferArrayIndex > ulLastTransferArrayIndex)
  2963. {
  2964. ulLastUpdateTime = DSIThread_GetSystemTime();
  2965. ulLastTransferArrayIndex = ulTransferArrayIndex;
  2966. }
  2967. else
  2968. {
  2969. if ((DSIThread_GetSystemTime() - ulLastUpdateTime) > DOWNLOAD_LOOP_TIMEOUT)
  2970. {
  2971. #if defined(DEBUG_FILE)
  2972. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Timeout receiving packets.");
  2973. #endif
  2974. return RETURN_FAIL;
  2975. }
  2976. }
  2977. if (!bReceivedBurst)
  2978. {
  2979. if ((ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY) && (ucNoRxTicks > 0))
  2980. ucNoRxTicks--;
  2981. if (ucNoRxTicks == 0)
  2982. {
  2983. ucNoRxTicks = 4;
  2984. #if defined(DEBUG_FILE)
  2985. DSIDebug::ThreadWrite("ANTFSHostChannel::Download(): Not receiving packets.");
  2986. #endif
  2987. break;
  2988. }
  2989. }
  2990. else
  2991. {
  2992. ucNoRxTicks = 4; // Reset counter
  2993. ucAttemptTick = 15; // Reset counter for attempts of request
  2994. }
  2995. ReportDownloadProgress();
  2996. } //while();
  2997. } while (!bDone);
  2998. bTransfer = TRUE;
  2999. // Wait for resync.
  3000. DSIThread_MutexLock(&stMutexCriticalSection);
  3001. bNewRxEvent = FALSE;
  3002. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3003. {
  3004. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BROADCAST_TIMEOUT);
  3005. if (ucResult != DSI_THREAD_ENONE)
  3006. {
  3007. #if defined(DEBUG_FILE)
  3008. if(ucResult == DSI_THREAD_EOTHER)
  3009. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload(): CondTimedWait() Failed!");
  3010. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptDownload(): Rx timeout.");
  3011. #endif
  3012. }
  3013. }
  3014. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3015. return RETURN_PASS;
  3016. }
  3017. ///////////////////////////////////////////////////////////////////////
  3018. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::UploadLoop(void)
  3019. {
  3020. RETURN_STATUS eReturn;
  3021. ULONG ulLastProgressValue = 0;
  3022. ULONG ulLastTimeWeGotDataThru = DSIThread_GetSystemTime();
  3023. UCHAR ucFreshRetries = 3;
  3024. #if defined(DEBUG_FILE)
  3025. UCHAR aucString[256];
  3026. #endif
  3027. do
  3028. {
  3029. //ulLastProgressValue = ulUploadIndexProgress; // figure out where we thought we left off last time, this may be a little further than we actually got, but it will be okay unless the USB device has a massive amount of buffering or is broken.
  3030. eReturn = AttemptUpload();
  3031. switch (eReturn)
  3032. {
  3033. case RETURN_PASS:
  3034. if ((ulUploadIndexProgress - UPLOAD_DATA_MESG_OVERHEAD) >= ulTransferByteSize)
  3035. return RETURN_PASS;
  3036. if (ulUploadIndexProgress > ulLastProgressValue + UPLOAD_DATA_MESG_OVERHEAD) //we use the overhead size for the check here because the return was a pass
  3037. {
  3038. bForceUploadOffset = FALSE; //clear the force offset if we get any data across
  3039. ulLastTimeWeGotDataThru = DSIThread_GetSystemTime();
  3040. ulLastProgressValue = ulUploadIndexProgress;
  3041. }
  3042. #if defined(DEBUG_FILE)
  3043. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::UploadLoop(): RETURN_PASS - %lu", ulLastTimeWeGotDataThru);
  3044. DSIDebug::ThreadWrite((char *) aucString);
  3045. #endif
  3046. break;
  3047. case RETURN_FAIL:
  3048. if (ulUploadIndexProgress > ulLastProgressValue + UPLOAD_PROGRESS_CHECK_BYTES) //we use the larger check size here because the return was a failure
  3049. {
  3050. bForceUploadOffset = FALSE; //clear the force offset if we get any data across
  3051. ulLastTimeWeGotDataThru = DSIThread_GetSystemTime();
  3052. ulLastProgressValue = ulUploadIndexProgress;
  3053. }
  3054. #if defined(DEBUG_FILE)
  3055. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::UploadLoop(): RETURN_FAIL - %lu", ulLastTimeWeGotDataThru);
  3056. DSIDebug::ThreadWrite((char *) aucString);
  3057. #endif
  3058. break;
  3059. case RETURN_NA: //This means we have failed CRC or the device returned a weird last offset.
  3060. if (ucFreshRetries--)
  3061. {
  3062. ulUploadIndexProgress = 0; //reset the progress
  3063. ulLastProgressValue = 0;
  3064. ulLastTimeWeGotDataThru = DSIThread_GetSystemTime(); //reset the time
  3065. }
  3066. else
  3067. {
  3068. return RETURN_FAIL;
  3069. }
  3070. break;
  3071. case RETURN_REJECT:
  3072. case RETURN_STOP:
  3073. default:
  3074. return eReturn;
  3075. break;
  3076. }
  3077. }
  3078. while ((DSIThread_GetSystemTime() - ulLastTimeWeGotDataThru) < UPLOAD_LOOP_TIMEOUT);
  3079. return RETURN_FAIL;
  3080. }
  3081. ///////////////////////////////////////////////////////////////////////
  3082. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptUpload(void)
  3083. {
  3084. BOOL bStatus = FALSE;
  3085. UCHAR aucTxUpload[16];
  3086. UCHAR aucUploadHeader[8];
  3087. UCHAR aucUploadFooter[8];
  3088. ULONG ulStartTime;
  3089. UCHAR ucTxRetries;
  3090. ANTFRAMER_RETURN eTxComplete;
  3091. ULONG ulLastOffset;
  3092. ULONG ulMaxBlockSize, ulMaxFileSize, ulUploadTimeout, ulLocalTransferSize;
  3093. ANTFRAMER_RETURN eReturn;
  3094. USHORT usReceivedCRC;
  3095. USHORT usCalculatedCRC;
  3096. USHORT usCRCSeed;
  3097. UCHAR ucUploadResponse;
  3098. //The found device state may not have updated yet if we attempt to ul/dl right after authentication, but addition of ULLoop allows us to do this check
  3099. if ((ucFoundDeviceState != REMOTE_DEVICE_STATE_TRANS) && (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  3100. {
  3101. #if defined(DEBUG_FILE)
  3102. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Remote device is not in correct state.");
  3103. #endif
  3104. return RETURN_FAIL; // Not in the correct mode.
  3105. }
  3106. //ulTransferArrayIndex = 0;
  3107. bReceivedResponse = FALSE;
  3108. bRxError = FALSE;
  3109. bReceivedBurst = FALSE;
  3110. memset(aucTxUpload, 0x00, sizeof(aucTxUpload));
  3111. ULONG ulMaxTransferIndex = ulTransferDataOffset + ulTransferByteSize;
  3112. // Build upload request
  3113. aucTxUpload[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  3114. aucTxUpload[ANTFS_COMMAND_OFFSET] = ANTFS_UPLOAD_BIG_ID;
  3115. Convert_USHORT_To_Bytes(usTransferDataFileIndex,
  3116. &aucTxUpload[DATA_INDEX_OFFSET + 1],
  3117. &aucTxUpload[DATA_INDEX_OFFSET]);
  3118. Convert_ULONG_To_Bytes(ulMaxTransferIndex,
  3119. &aucTxUpload[UPLOAD_MAX_SIZE_OFFSET + 3],
  3120. &aucTxUpload[UPLOAD_MAX_SIZE_OFFSET + 2],
  3121. &aucTxUpload[UPLOAD_MAX_SIZE_OFFSET + 1],
  3122. &aucTxUpload[UPLOAD_MAX_SIZE_OFFSET]);
  3123. if (bForceUploadOffset)
  3124. {
  3125. Convert_ULONG_To_Bytes(ulTransferDataOffset,
  3126. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 3],
  3127. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 2],
  3128. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 1],
  3129. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET]);
  3130. }
  3131. else
  3132. {
  3133. Convert_ULONG_To_Bytes(MAX_ULONG,
  3134. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 3],
  3135. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 2],
  3136. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET + 1],
  3137. &aucTxUpload[UPLOAD_DATA_OFFSET_OFFSET]);
  3138. }
  3139. bNewRxEvent = FALSE;
  3140. ucTxRetries = 8;
  3141. // Try sending upload request until success or retries exhausted.
  3142. eTxComplete = pclANT->SendANTFSTransfer(ucChannelNumber, (UCHAR*)NULL, (UCHAR*)NULL, aucTxUpload, 16, ACKNOWLEDGED_TIMEOUT, (ULONG*)NULL);
  3143. #if defined(DEBUG_FILE)
  3144. if (eTxComplete == ANTFRAMER_FAIL)
  3145. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Tx error sending upload command.");
  3146. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  3147. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Tx timeout sending upload command.");
  3148. #endif
  3149. //Removed the immediate retries to avoid the issue of queing up requests while we get a response for a request we thought we failed.
  3150. if (eTxComplete == ANTFRAMER_TIMEOUT)
  3151. {
  3152. #if defined(DEBUG_FILE)
  3153. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Tx failed.");
  3154. #endif
  3155. return RETURN_FAIL;
  3156. }
  3157. ulStartTime = DSIThread_GetSystemTime();
  3158. ucLinkResponseRetries = ANTFS_RESPONSE_RETRIES;
  3159. do
  3160. {
  3161. DSIThread_MutexLock(&stMutexCriticalSection);
  3162. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3163. {
  3164. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, 1000);
  3165. }
  3166. bNewRxEvent = FALSE;
  3167. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3168. if (*pbCancel == TRUE)
  3169. {
  3170. #if defined(DEBUG_FILE)
  3171. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptUpload(): Stopped.");
  3172. #endif
  3173. return RETURN_STOP;
  3174. }
  3175. if (bReceivedResponse)
  3176. {
  3177. if (aucTransferBufferFixed[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_UPLOAD_ID)
  3178. {
  3179. if (aucTransferBufferFixed[UPLOAD_RESPONSE_OFFSET] == UPLOAD_RESPONSE_OK)
  3180. {
  3181. bStatus = TRUE;
  3182. bLargeData = TRUE;
  3183. }
  3184. else
  3185. {
  3186. ucRejectCode = aucTransferBufferFixed[UPLOAD_RESPONSE_OFFSET];
  3187. return RETURN_REJECT;
  3188. }
  3189. }
  3190. }
  3191. #if defined(DEBUG_FILE)
  3192. else
  3193. {
  3194. DSIDebug::ThreadWrite("-->Requesting Upload...");
  3195. }
  3196. #endif
  3197. if ((bRxError) || (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  3198. {
  3199. #if defined(DEBUG_FILE)
  3200. if (bRxError)
  3201. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Rx error");
  3202. else
  3203. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Non-busy beacon");
  3204. #endif
  3205. if (ucLinkResponseRetries == 0)
  3206. {
  3207. #if defined(DEBUG_FILE)
  3208. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Retries exhausted");
  3209. #endif
  3210. return RETURN_FAIL;
  3211. }
  3212. else
  3213. {
  3214. #if defined(DEBUG_FILE)
  3215. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Retrying");
  3216. #endif
  3217. ucLinkResponseRetries--;
  3218. bRxError = FALSE;
  3219. }
  3220. }
  3221. } while ((bStatus == FALSE) && ((DSIThread_GetSystemTime() - ulStartTime) < UPLOAD_REQUEST_TIMEOUT));
  3222. if (!bStatus)
  3223. {
  3224. #if defined(DEBUG_FILE)
  3225. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Timeout.");
  3226. #endif
  3227. return RETURN_FAIL;
  3228. }
  3229. bReceivedResponse = FALSE;
  3230. bNewRxEvent = FALSE;
  3231. ucUploadResponse = aucTransferBufferFixed[UPLOAD_RESPONSE_OFFSET];
  3232. if (!ucUploadResponse) // it's accepting the upload
  3233. {
  3234. // Decode response
  3235. ulLastOffset = Convert_Bytes_To_ULONG(aucTransferBufferFixed[UPLOAD_RESPONSE_LAST_OFFSET_OFFSET + 3],
  3236. aucTransferBufferFixed[UPLOAD_RESPONSE_LAST_OFFSET_OFFSET + 2],
  3237. aucTransferBufferFixed[UPLOAD_RESPONSE_LAST_OFFSET_OFFSET + 1],
  3238. aucTransferBufferFixed[UPLOAD_RESPONSE_LAST_OFFSET_OFFSET]);
  3239. ulMaxBlockSize = Convert_Bytes_To_ULONG(aucTransferBufferFixed[UPLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 3],
  3240. aucTransferBufferFixed[UPLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 2],
  3241. aucTransferBufferFixed[UPLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 1],
  3242. aucTransferBufferFixed[UPLOAD_RESPONSE_BLOCK_SIZE_OFFSET]);
  3243. usReceivedCRC = Convert_Bytes_To_USHORT(aucTransferBufferFixed[UPLOAD_RESPONSE_CRC_OFFSET + 1],
  3244. aucTransferBufferFixed[UPLOAD_RESPONSE_CRC_OFFSET]);
  3245. ulMaxFileSize = Convert_Bytes_To_ULONG(aucTransferBufferFixed[UPLOAD_RESPONSE_MAX_SIZE_OFFSET + 3],
  3246. aucTransferBufferFixed[UPLOAD_RESPONSE_MAX_SIZE_OFFSET + 2],
  3247. aucTransferBufferFixed[UPLOAD_RESPONSE_MAX_SIZE_OFFSET + 1],
  3248. aucTransferBufferFixed[UPLOAD_RESPONSE_MAX_SIZE_OFFSET]);
  3249. if (ulMaxTransferIndex > ulMaxFileSize)
  3250. {
  3251. #if defined(DEBUG_FILE)
  3252. UCHAR aucString[256];
  3253. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::Upload(): Upload size larger than Max Files size (%lu > %lu)", ulMaxTransferIndex, ulMaxFileSize);
  3254. DSIDebug::ThreadWrite((char *) aucString);
  3255. #endif
  3256. ucRejectCode = UPLOAD_RESPONSE_INSUFFICIENT_SPACE;
  3257. return RETURN_REJECT;
  3258. }
  3259. if (bForceUploadOffset) // Override the suggested offset if we are instructed to.
  3260. {
  3261. usCRCSeed = 0;
  3262. ulLastOffset = ulTransferDataOffset; // We will start from where the app told us to
  3263. ulLocalTransferSize = ulTransferByteSize; // and set the next transfer size to the correct value
  3264. }
  3265. else //we need to check the CRC
  3266. {
  3267. if (ulLastOffset > ulMaxTransferIndex) //The last offset we got is larger than our max, we are just going to force a restart from where we want to start
  3268. {
  3269. #if defined(DEBUG_FILE)
  3270. UCHAR aucString[256];
  3271. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::Upload(): ulLastOffset from device is larger than our max offset - Restarting UL (%lu > %lu)", ulLastOffset, ulMaxTransferIndex);
  3272. DSIDebug::ThreadWrite((char *) aucString);
  3273. #endif
  3274. bForceUploadOffset = TRUE;
  3275. return RETURN_NA;
  3276. }
  3277. usCRCSeed = CRC_Calc16(&pucUploadData[0], ulLastOffset-ulTransferDataOffset);
  3278. if (usCRCSeed != usReceivedCRC)
  3279. {
  3280. #if defined(DEBUG_FILE)
  3281. UCHAR aucString[256];
  3282. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::Upload(): CRC Check Failed - Wanted 0x%04X, Got 0x%04X", usCRCSeed, usReceivedCRC);
  3283. DSIDebug::ThreadWrite((char *) aucString);
  3284. #endif
  3285. //We are going to send no data.
  3286. ulLocalTransferSize = 0;
  3287. //ulLastOffset = 0; // we're going to start over if the client doesn't have the right CRC
  3288. bForceUploadOffset = TRUE;
  3289. return RETURN_NA;
  3290. }
  3291. }
  3292. if ((ulLastOffset == ulMaxTransferIndex))
  3293. {
  3294. #if defined(DEBUG_FILE)
  3295. UCHAR aucString[256];
  3296. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::Upload(): We think we were sucessful Last time - UploadIndexProgress %lu, TransferByteSize %lu", ulUploadIndexProgress, ulTransferByteSize);
  3297. DSIDebug::ThreadWrite((char *) aucString);
  3298. #endif
  3299. //ulLastOffset = 0;
  3300. ulLocalTransferSize = 0; //Send only the header and try if we think we actually completed last time and only failed getting the response
  3301. }
  3302. else
  3303. {
  3304. if (ulLastOffset > ulTransferDataOffset) //Check if there is a suggested last offset and if it's further along than our original offset
  3305. {
  3306. ulLocalTransferSize = ulTransferByteSize - (ulLastOffset - ulTransferDataOffset); //If it is then we'll use it, and adjust the size of the next burst
  3307. }
  3308. else
  3309. {
  3310. ulLastOffset = ulTransferDataOffset; // We will start from where the app told us to
  3311. ulLocalTransferSize = ulTransferByteSize; // and set the next transfer size to the correct value
  3312. }
  3313. }
  3314. if (ulLocalTransferSize) // If we are actually sending data
  3315. ulUploadIndexProgress = ulLastOffset - ulTransferDataOffset; // Set the progress to start at the offset
  3316. else
  3317. ulUploadIndexProgress = ulTransferByteSize; // Otherwise, we are already complete and just need confirmation, so set the progress back to the transfer size (the transfer function will keep trying to add to this because of the header)
  3318. if(ulMaxBlockSize < ulLocalTransferSize) // Check if we exceed the max client block size
  3319. ulLocalTransferSize = ulMaxBlockSize;
  3320. if(ulHostBlockSize < ulLocalTransferSize) // Check if we exceed the max host block size
  3321. ulLocalTransferSize = ulHostBlockSize;
  3322. if (ulLocalTransferSize)
  3323. {
  3324. usCalculatedCRC = CRC_Calc16(&pucUploadData[0], (ulLastOffset - ulTransferDataOffset) + ulLocalTransferSize); // compute the CRC from the start up till the end of the current block
  3325. }
  3326. else
  3327. {
  3328. usCalculatedCRC = usCRCSeed;
  3329. }
  3330. //Add CRC to the footer.
  3331. memset(aucUploadFooter,0x00,sizeof(aucUploadFooter));
  3332. Convert_USHORT_To_Bytes(usCalculatedCRC,
  3333. &aucUploadFooter[UPLOAD_DATA_CRC_OFFSET + 1],
  3334. &aucUploadFooter[UPLOAD_DATA_CRC_OFFSET]); //put CRC at the end of the footer packet
  3335. // figure out our timeout value from the size of the transfer
  3336. if (ulLocalTransferSize > ((MAX_ULONG - BROADCAST_TIMEOUT) / 2))
  3337. ulUploadTimeout = (MAX_ULONG - 1);
  3338. else
  3339. ulUploadTimeout = BROADCAST_TIMEOUT + (ulTransferByteSize * 2);
  3340. // fill in the header information
  3341. aucUploadHeader[0] = ANTFS_COMMAND_RESPONSE_ID;
  3342. aucUploadHeader[1] = ANTFS_UPLOAD_DATA_ID;
  3343. Convert_USHORT_To_Bytes(usCRCSeed,
  3344. &aucUploadHeader[UPLOAD_DATA_CRC_SEED_OFFSET + 1],
  3345. &aucUploadHeader[UPLOAD_DATA_CRC_SEED_OFFSET]);
  3346. if ((ulLastOffset == ulMaxTransferIndex)) // If we think we are done, we will fill zero into the offset but we send no data.
  3347. { // This should result in only a complete to the embedded application.
  3348. Convert_ULONG_To_Bytes(0,
  3349. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 3],
  3350. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 2],
  3351. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 1],
  3352. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET]);
  3353. }
  3354. else
  3355. {
  3356. Convert_ULONG_To_Bytes(ulLastOffset,
  3357. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 3],
  3358. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 2],
  3359. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET + 1],
  3360. &aucUploadHeader[UPLOAD_DATA_DATA_OFFSET_OFFSET]);
  3361. }
  3362. //Send the Burst
  3363. eReturn = pclANT->SendANTFSTransfer(ucChannelNumber, aucUploadHeader, aucUploadFooter, &pucUploadData[ulLastOffset], ulLocalTransferSize, ulUploadTimeout, &ulUploadIndexProgress);
  3364. if (eReturn == ANTFRAMER_FAIL)
  3365. {
  3366. #if defined(DEBUG_FILE)
  3367. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Failed Actual Upload Transfer.");
  3368. #endif
  3369. //fall thru to catch response
  3370. }
  3371. else if (eReturn == ANTFRAMER_CANCELLED)
  3372. {
  3373. #if defined(DEBUG_FILE)
  3374. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptUpload(): Stopped2.");
  3375. #endif
  3376. return RETURN_STOP;
  3377. }
  3378. else if (eReturn == ANTFRAMER_TIMEOUT)
  3379. {
  3380. #if defined(DEBUG_FILE)
  3381. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptUpload(): Tx transfer timeout.");
  3382. #endif
  3383. return RETURN_FAIL;
  3384. }
  3385. }
  3386. else
  3387. {
  3388. #if defined(DEBUG_FILE)
  3389. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Rejected by Client.");
  3390. #endif
  3391. ucRejectCode = ucUploadResponse;
  3392. return RETURN_FAIL;
  3393. }
  3394. ulStartTime = DSIThread_GetSystemTime();
  3395. //ResetEvent(hEventRx);
  3396. ucLinkResponseRetries = ANTFS_RESPONSE_RETRIES;
  3397. bStatus = FALSE;
  3398. do
  3399. {
  3400. DSIThread_MutexLock(&stMutexCriticalSection);
  3401. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3402. {
  3403. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, 1000);
  3404. }
  3405. bNewRxEvent = FALSE;
  3406. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3407. if (*pbCancel == TRUE)
  3408. {
  3409. #if defined(DEBUG_FILE)
  3410. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptUpload(): Stopped.");
  3411. #endif
  3412. return RETURN_STOP;
  3413. }
  3414. if ((bRxError) || (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  3415. {
  3416. #if defined(DEBUG_FILE)
  3417. if (bRxError)
  3418. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Rx error2");
  3419. else
  3420. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Non-busy beacon2");
  3421. #endif
  3422. if (ucLinkResponseRetries == 0)
  3423. {
  3424. #if defined(DEBUG_FILE)
  3425. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Retries exhausted2");
  3426. #endif
  3427. return RETURN_FAIL;
  3428. }
  3429. else
  3430. {
  3431. #if defined(DEBUG_FILE)
  3432. DSIDebug::ThreadWrite("ANTFSHostChannel::Upload(): Retrying2");
  3433. #endif
  3434. ucLinkResponseRetries--;
  3435. bRxError = FALSE;
  3436. }
  3437. }
  3438. if (bReceivedResponse)
  3439. {
  3440. if (aucTransferBufferFixed[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_UPLOAD_COMPLETE_ID)
  3441. {
  3442. if (aucTransferBufferFixed[UPLOAD_RESPONSE_OFFSET] == UPLOAD_RESPONSE_OK)
  3443. {
  3444. return RETURN_PASS;
  3445. }
  3446. else
  3447. {
  3448. return RETURN_FAIL;
  3449. }
  3450. }
  3451. }
  3452. #if defined(DEBUG_FILE)
  3453. else
  3454. {
  3455. DSIDebug::ThreadWrite("-->Waiting for upload complete...");
  3456. }
  3457. #endif
  3458. } while ((bStatus == FALSE) && ((DSIThread_GetSystemTime() - ulStartTime) < UPLOAD_RESPONSE_TIMEOUT));
  3459. return RETURN_FAIL;
  3460. }
  3461. ///////////////////////////////////////////////////////////////////////
  3462. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptManualTransfer(void)
  3463. {
  3464. ULONG ulBlockSize;
  3465. USHORT usBlockOffset;
  3466. // Convert bytes remaining to blocks remaining.
  3467. if (ulTransferByteSize % 8)
  3468. ulBlockSize = 1; // There is a remainder, so we need to send one extra payload to hold all the data.
  3469. else
  3470. ulBlockSize = 0;
  3471. ulBlockSize += ulTransferByteSize / 8;
  3472. // Convert byte offset to block offset.
  3473. usBlockOffset = (USHORT) ulTransferDataOffset / 8; // The remainder must be dropped when computing offset.
  3474. ulTransferArrayIndex = 0;
  3475. bReceivedBurst = FALSE;
  3476. bReceivedResponse = FALSE;
  3477. if (*pbCancel == TRUE)
  3478. return RETURN_STOP;
  3479. aucSendDirectBuffer[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  3480. aucSendDirectBuffer[ANTFS_COMMAND_OFFSET] = ANTFS_SEND_DIRECT_ID;
  3481. Convert_USHORT_To_Bytes(usTransferDataFileIndex,
  3482. &aucSendDirectBuffer[DATA_INDEX_OFFSET + 1],
  3483. &aucSendDirectBuffer[DATA_INDEX_OFFSET]);
  3484. Convert_USHORT_To_Bytes(usBlockOffset,
  3485. &aucSendDirectBuffer[DATA_OFFSET_OFFSET_HIGH],
  3486. &aucSendDirectBuffer[DATA_OFFSET_OFFSET_LOW]);
  3487. Convert_ULONG_To_Bytes(ulBlockSize - 1, // Size - 1, as per the spec.
  3488. (UCHAR*)NULL,
  3489. (UCHAR*)NULL,
  3490. &aucSendDirectBuffer[DATA_BLOCK_SIZE_OFFSET_HIGH],
  3491. &aucSendDirectBuffer[DATA_BLOCK_SIZE_OFFSET_LOW]);
  3492. #if 0
  3493. #if defined(DEBUG_FILE)
  3494. {
  3495. char acString[256];
  3496. int iCounter;
  3497. ULONG ulCounter2;
  3498. SNPRINTF(acString, 256, "ANTFSHostChannel::ManualTransfer(): ulTransferByteSize = %lu; ulTransferDataOffset = %lu.", ulTransferByteSize, ulTransferDataOffset);
  3499. DSIDebug::ThreadWrite(acString);
  3500. for (ulCounter2 = 0; ulCounter2 < ulBlockSize; ulCounter2++)
  3501. {
  3502. SNPRINTF(acString, 256, "ANTFSHostChannel::ManualTransfer(): <%lu>", ulCounter2);
  3503. for (iCounter = 0; iCounter < 8; iCounter++)
  3504. {
  3505. char acSubString[10];
  3506. SNPRINTF(acSubString, 10, "[%02X]", aucSendDirectBuffer[ulCounter2 + (ULONG) iCounter]);
  3507. SNPRINTF(acString, 256, "%s%s", acString, acSubString);
  3508. }
  3509. DSIDebug::ThreadWrite(acString);
  3510. }
  3511. }
  3512. #endif
  3513. #endif
  3514. ulUploadIndexProgress = 0;
  3515. //pclANT->SendANTFSTransfer(ucChannelNumber, aucSendDirectBuffer, &aucSendDirectBuffer[8], (ulBlockSize + 1)*8, 120000, &ulUploadIndexProgress); // Size + 1 to account for the command payload.
  3516. pclANT->SendANTFSTransfer(ucChannelNumber, (UCHAR*)NULL, (UCHAR*)NULL, aucSendDirectBuffer, (ulBlockSize + 1)*8, 120000, &ulUploadIndexProgress); // Size + 1 to account for the command payload.
  3517. //pclANT->SendTransfer(ANTFS_CHANNEL, aucSendDirectBuffer, (ulBlockSize + 1)*8,120000); // Size + 1 to account for the command payload.
  3518. //allow the receive function to return with error, even if the Tx transfer failed
  3519. return Receive();
  3520. }
  3521. ///////////////////////////////////////////////////////////////////////
  3522. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::Receive(void)
  3523. {
  3524. ULONG ulNoRxTime = DSIThread_GetSystemTime();
  3525. UCHAR ucTicks = ucTransportBeaconTicks;
  3526. bNewRxEvent = FALSE;
  3527. eANTFSState = ANTFS_HOST_STATE_RECEIVING;
  3528. while (bKillThread == FALSE)
  3529. {
  3530. DSIThread_MutexLock(&stMutexCriticalSection);
  3531. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3532. {
  3533. UCHAR ucResult = DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BURST_CHECK_TIMEOUT);
  3534. if (ucResult != DSI_THREAD_ENONE)
  3535. {
  3536. #if defined(DEBUG_FILE)
  3537. if(ucResult == DSI_THREAD_EOTHER)
  3538. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): CondTimedWait() Failed!");
  3539. #endif
  3540. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3541. return RETURN_FAIL;
  3542. }
  3543. }
  3544. bNewRxEvent = FALSE;
  3545. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3546. if (*pbCancel == TRUE)
  3547. {
  3548. #if defined(DEBUG_FILE)
  3549. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): Stopped.");
  3550. #endif
  3551. return RETURN_STOP;
  3552. }
  3553. if ((ucFoundDeviceState == REMOTE_DEVICE_STATE_TRANS) && ((ucTransportBeaconTicks - ucTicks) >= 5))
  3554. return RETURN_REJECT;
  3555. if (bReceivedResponse && (ucFoundDeviceState == REMOTE_DEVICE_STATE_TRANS))
  3556. {
  3557. if (pucTransferBufferDynamic == NULL)
  3558. {
  3559. #if defined(DEBUG_FILE)
  3560. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): pucTransferBufferDynamic is an undefined pointer.");
  3561. #endif
  3562. break;
  3563. }
  3564. if (pucTransferBufferDynamic[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_SEND_DIRECT_ID)
  3565. {
  3566. // If the index, offset and block size bytes are all 0xFF, then the
  3567. // sent data was rejected by the remote device.
  3568. int i;
  3569. BOOL bAll0xFF = TRUE;
  3570. for (i = 2; i < 8; i++)
  3571. {
  3572. if (pucTransferBufferDynamic[i] != 0xFF)
  3573. {
  3574. bAll0xFF = FALSE;
  3575. break;
  3576. }
  3577. }
  3578. if (bAll0xFF)
  3579. return RETURN_REJECT;
  3580. bTransfer = TRUE;
  3581. return RETURN_PASS;
  3582. }
  3583. else
  3584. {
  3585. #if defined(DEBUG_FILE)
  3586. char acString[256];
  3587. SNPRINTF(acString, 256, "ANTFSHostChannel::Receive(): Bad response: [%02X][%02X][%02X][%02X][%02X][%02X][%02X][%02X]",
  3588. pucTransferBufferDynamic[0],
  3589. pucTransferBufferDynamic[1],
  3590. pucTransferBufferDynamic[2],
  3591. pucTransferBufferDynamic[3],
  3592. pucTransferBufferDynamic[4],
  3593. pucTransferBufferDynamic[5],
  3594. pucTransferBufferDynamic[6],
  3595. pucTransferBufferDynamic[7]);
  3596. DSIDebug::ThreadWrite(acString);
  3597. #endif
  3598. break;
  3599. }
  3600. }
  3601. if (bRxError)
  3602. bRxError = FALSE;
  3603. if (!bReceivedBurst)
  3604. {
  3605. if ((DSIThread_GetSystemTime() - ulNoRxTime) > SEND_DIRECT_BURST_TIMEOUT)
  3606. {
  3607. #if defined(DEBUG_FILE)
  3608. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): Timeout waiting for burst packets.");
  3609. #endif
  3610. break;
  3611. }
  3612. else
  3613. {
  3614. #if defined(DEBUG_FILE)
  3615. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): Burst packet not received. Retrying...");
  3616. #endif
  3617. }
  3618. }
  3619. else
  3620. {
  3621. ulNoRxTime = DSIThread_GetSystemTime(); // Reset timeout.
  3622. #if defined(DEBUG_FILE)
  3623. DSIDebug::ThreadWrite("ANTFSHostChannel::Receive(): Burst packets received. Reset timeout.");
  3624. #endif
  3625. }
  3626. ReportDownloadProgress();
  3627. }
  3628. return RETURN_FAIL; // Shouldn't reach here.
  3629. }
  3630. ///////////////////////////////////////////////////////////////////////
  3631. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptErase(void)
  3632. {
  3633. BOOL bStatus = FALSE;
  3634. ULONG ulStartTime;
  3635. UCHAR ucTxRetries;
  3636. ANTFRAMER_RETURN eTxComplete;
  3637. if ((ucFoundDeviceState != REMOTE_DEVICE_STATE_TRANS) && (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  3638. {
  3639. #if defined(DEBUG_FILE)
  3640. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Remote device is not in transport state.");
  3641. #endif
  3642. return RETURN_FAIL; // Not in the correct mode.
  3643. }
  3644. ulTransferArrayIndex = 0;
  3645. bReceivedResponse = FALSE;
  3646. bRxError = FALSE;
  3647. memset(aucTxBuf,0x00,sizeof(aucTxBuf));
  3648. aucTxBuf[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  3649. aucTxBuf[ANTFS_COMMAND_OFFSET] = ANTFS_ERASE_ID;
  3650. Convert_USHORT_To_Bytes(usTransferDataFileIndex,
  3651. &aucTxBuf[DATA_INDEX_OFFSET+1],
  3652. &aucTxBuf[DATA_INDEX_OFFSET]);
  3653. ucTxRetries = 8;
  3654. do
  3655. {
  3656. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxBuf, ACKNOWLEDGED_TIMEOUT);
  3657. #if defined(DEBUG_FILE)
  3658. if (eTxComplete == ANTFRAMER_FAIL)
  3659. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Tx error.");
  3660. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  3661. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptConnect(): Tx timeout.");
  3662. #endif
  3663. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  3664. if (eTxComplete != ANTFRAMER_PASS)
  3665. return RETURN_FAIL;
  3666. ulStartTime = DSIThread_GetSystemTime();
  3667. bNewRxEvent = FALSE;
  3668. ucLinkResponseRetries = ANTFS_RESPONSE_RETRIES;
  3669. do
  3670. {
  3671. DSIThread_MutexLock(&stMutexCriticalSection);
  3672. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3673. {
  3674. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, ERASE_WAIT_TIMEOUT);
  3675. }
  3676. bNewRxEvent = FALSE;
  3677. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3678. if (*pbCancel == TRUE)
  3679. {
  3680. #if defined(DEBUG_FILE)
  3681. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Stopped.");
  3682. #endif
  3683. return RETURN_STOP;
  3684. }
  3685. if (bReceivedResponse)
  3686. {
  3687. if (aucTransferBufferFixed[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_ERASE_ID)
  3688. {
  3689. if (aucTransferBufferFixed[ERASE_RESPONSE_OFFSET] == ERASE_RESPONSE_OK)
  3690. {
  3691. #if defined(DEBUG_FILE)
  3692. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Erase successful.");
  3693. #endif
  3694. bStatus = TRUE;
  3695. }
  3696. else
  3697. {
  3698. #if defined(DEBUG_FILE)
  3699. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Request rejected.");
  3700. #endif
  3701. bRxError = TRUE;
  3702. }
  3703. }
  3704. }
  3705. #if defined(DEBUG_FILE)
  3706. else
  3707. {
  3708. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Erasing...");
  3709. }
  3710. #endif
  3711. if (bRxError)
  3712. {
  3713. #if defined(DEBUG_FILE)
  3714. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Erase failed.");
  3715. #endif
  3716. if (ucLinkResponseRetries == 0)
  3717. {
  3718. #if defined(DEBUG_FILE)
  3719. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Retries exhausted");
  3720. #endif
  3721. break;
  3722. }
  3723. else
  3724. {
  3725. #if defined(DEBUG_FILE)
  3726. DSIDebug::ThreadWrite("ANTFSHostChannel::Erase(): Retrying");
  3727. #endif
  3728. ucLinkResponseRetries--;
  3729. bRxError = FALSE;
  3730. }
  3731. }
  3732. } while ((bStatus == FALSE) && ((DSIThread_GetSystemTime() - ulStartTime) < ERASE_TIMEOUT));
  3733. if (!bStatus)
  3734. return RETURN_FAIL;
  3735. return RETURN_PASS;
  3736. }
  3737. ///////////////////////////////////////////////////////////////////////
  3738. ANTFSHostChannel::RETURN_STATUS ANTFSHostChannel::AttemptAuthenticate(void)
  3739. {
  3740. BOOL bStatus = FALSE;
  3741. UCHAR aucTxAuth[8 + TX_PASSWORD_MAX_LENGTH + 8];
  3742. ULONG ulStartTime;
  3743. UCHAR ucTxRetries;
  3744. ANTFRAMER_RETURN eTxComplete;
  3745. BOOL bBeaconStateIncorrect = FALSE;
  3746. if ((ucFoundDeviceState != REMOTE_DEVICE_STATE_AUTH) && (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY))
  3747. {
  3748. #if defined(DEBUG_FILE)
  3749. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Remote device is not in auth state.");
  3750. #endif
  3751. return RETURN_FAIL; // Not in the correct mode.
  3752. }
  3753. ulTransferArrayIndex = 0;
  3754. bReceivedResponse = FALSE;
  3755. bRxError = FALSE;
  3756. memset(aucTxAuth,0x00,sizeof(aucTxAuth));
  3757. aucTxAuth[ANTFS_CONNECTION_OFFSET] = ANTFS_COMMAND_RESPONSE_ID;
  3758. aucTxAuth[ANTFS_COMMAND_OFFSET] = ANTFS_AUTHENTICATE_ID;
  3759. aucTxAuth[AUTH_COMMAND_TYPE_OFFSET] = ucAuthType;
  3760. aucTxAuth[AUTH_FRIENDLY_NAME_LENGTH_OFFSET] = ucTxPasswordLength;
  3761. Convert_ULONG_To_Bytes(ulHostSerialNumber,
  3762. &aucTxAuth[AUTH_HOST_SERIAL_NUMBER_OFFSET+3],
  3763. &aucTxAuth[AUTH_HOST_SERIAL_NUMBER_OFFSET+2],
  3764. &aucTxAuth[AUTH_HOST_SERIAL_NUMBER_OFFSET+1],
  3765. &aucTxAuth[AUTH_HOST_SERIAL_NUMBER_OFFSET]);
  3766. memcpy(&aucTxAuth[8], aucTxPassword, ucTxPasswordLength);
  3767. if (ucTxPasswordLength) //Do this to not leave the last 8 bytes of the password in the host Tx buffer, but we are not required to do it.
  3768. ucTxPasswordLength = ucTxPasswordLength + 8;
  3769. #if defined(ACCESS_POINT)
  3770. ucTxRetries = 2;
  3771. #else
  3772. ucTxRetries = 8;
  3773. #endif
  3774. do
  3775. {
  3776. if (ucTxPasswordLength)
  3777. eTxComplete = pclANT->SendANTFSTransfer(ucChannelNumber, (UCHAR*)NULL, (UCHAR*)NULL, aucTxAuth, 8+ ucTxPasswordLength, ACKNOWLEDGED_TIMEOUT, (ULONG*)NULL);
  3778. else
  3779. eTxComplete = pclANT->SendAcknowledgedData(ucChannelNumber, aucTxAuth, ACKNOWLEDGED_TIMEOUT);
  3780. #if defined(DEBUG_FILE)
  3781. if (eTxComplete == ANTFRAMER_FAIL)
  3782. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Tx error.");
  3783. else if (eTxComplete == ANTFRAMER_TIMEOUT)
  3784. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Tx timeout.");
  3785. #endif
  3786. } while (eTxComplete == ANTFRAMER_FAIL && --ucTxRetries);
  3787. if (eTxComplete != ANTFRAMER_PASS)
  3788. {
  3789. #if defined(DEBUG_FILE)
  3790. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Tx failed.");
  3791. #endif
  3792. return RETURN_FAIL;
  3793. }
  3794. ulStartTime = DSIThread_GetSystemTime();
  3795. bNewRxEvent = FALSE;
  3796. #if defined(ACCESS_POINT)
  3797. ucLinkResponseRetries = 3; // Current client implementation does not retry, so there is no point in keeping waiting longer
  3798. #else
  3799. ucLinkResponseRetries = ANTFS_RESPONSE_RETRIES;
  3800. #endif
  3801. do
  3802. {
  3803. DSIThread_MutexLock(&stMutexCriticalSection);
  3804. if ((bNewRxEvent == FALSE) && (*pbCancel == FALSE))
  3805. {
  3806. DSIThread_CondTimedWait(&stCondRxEvent, &stMutexCriticalSection, BROADCAST_TIMEOUT);
  3807. }
  3808. bNewRxEvent = FALSE;
  3809. DSIThread_MutexUnlock(&stMutexCriticalSection);
  3810. if (*pbCancel == TRUE)
  3811. {
  3812. #if defined(DEBUG_FILE)
  3813. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Stopped.");
  3814. #endif
  3815. return RETURN_STOP;
  3816. }
  3817. if (ucFoundDeviceState != REMOTE_DEVICE_STATE_BUSY)
  3818. {
  3819. if (!((usFoundANTFSManufacturerID == 2) && (usFoundANTFSDeviceType == 1))) //Make an exception for the FR405
  3820. bBeaconStateIncorrect = TRUE;
  3821. }
  3822. if (bRxError || bBeaconStateIncorrect)
  3823. {
  3824. #if defined(DEBUG_FILE)
  3825. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Rx error.");
  3826. #endif
  3827. if (ucLinkResponseRetries == 0)
  3828. {
  3829. #if defined(DEBUG_FILE)
  3830. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Retries exhausted");
  3831. #endif
  3832. return RETURN_FAIL;
  3833. }
  3834. else
  3835. {
  3836. #if defined(DEBUG_FILE)
  3837. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Retrying"); // Not actual retries, just wait longer!
  3838. #endif
  3839. ucLinkResponseRetries--;
  3840. bRxError = FALSE;
  3841. bBeaconStateIncorrect = FALSE;
  3842. }
  3843. }
  3844. if (bReceivedResponse)
  3845. {
  3846. if (aucTransferBufferFixed[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_AUTH_ID)
  3847. {
  3848. if ((pucResponseBuffer != NULL) && (pucResponseBufferSize != NULL))
  3849. {
  3850. if (*pucResponseBufferSize > aucTransferBufferFixed[AUTH_PASSWORD_LENGTH_OFFSET]) //set the reponse length up to the max
  3851. *pucResponseBufferSize = aucTransferBufferFixed[AUTH_PASSWORD_LENGTH_OFFSET];
  3852. memcpy(pucResponseBuffer, &aucTransferBufferFixed[8], *pucResponseBufferSize);
  3853. }
  3854. if (aucTransferBufferFixed[AUTH_RESPONSE_OFFSET] == AUTH_RESPONSE_ACCEPT)
  3855. {
  3856. bStatus = TRUE;
  3857. }
  3858. else if (aucTransferBufferFixed[AUTH_RESPONSE_OFFSET] == AUTH_RESPONSE_REJECT)
  3859. {
  3860. return RETURN_REJECT;
  3861. }
  3862. else
  3863. {
  3864. return RETURN_NA;
  3865. }
  3866. }
  3867. }
  3868. #if defined(DEBUG_FILE)
  3869. else
  3870. {
  3871. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Authenticating...");
  3872. }
  3873. #endif
  3874. } while ((bStatus == FALSE) && ((DSIThread_GetSystemTime() - ulStartTime) < ulAuthResponseTimeout));
  3875. if (!bStatus)
  3876. {
  3877. #if defined(DEBUG_FILE)
  3878. DSIDebug::ThreadWrite("ANTFSHostChannel::AttemptAuthenticate(): Timeout.");
  3879. #endif
  3880. return RETURN_FAIL;
  3881. }
  3882. return RETURN_PASS;
  3883. }
  3884. ///////////////////////////////////////////////////////////////////////
  3885. // Returns: TRUE if the message has been handled by ANT-FS host, FALSE otherwise
  3886. BOOL ANTFSHostChannel::ANTProtocolEventProcess(UCHAR ucChannel_, UCHAR ucMessageCode_)
  3887. {
  3888. #if 0
  3889. #if defined(DEBUG_FILE)
  3890. UCHAR aucString[256];
  3891. SNPRINTF((char *)aucString,256, "ANTProtocolEventProcess(): Message 0x%02X", ucMessageCode_);
  3892. DSIDebug::ThreadWrite((char *)aucString);
  3893. #endif
  3894. #endif
  3895. if ((ucMessageCode_ == MESG_RESPONSE_EVENT_ID) && (ucChannel_ == ucChannelNumber))
  3896. {
  3897. #if defined(DEBUG_FILE)
  3898. UCHAR aucString[256];
  3899. SNPRINTF((char *) aucString, 256, "ANTFSHostChannel::ANTProtocolEventProcess(): MESG_RESPONSE_EVENT_ID - 0x%02X", aucResponseBuf[1]);
  3900. DSIDebug::ThreadWrite((char *) aucString);
  3901. #endif
  3902. if (aucResponseBuf[1] == MESG_BURST_DATA_ID)
  3903. {
  3904. if (aucResponseBuf[2] != RESPONSE_NO_ERROR)
  3905. {
  3906. #if defined(DEBUG_FILE)
  3907. UCHAR aucString1[256];
  3908. SNPRINTF((char *) aucString1, 256, "ANTFSHostChannel::ANTProtocolEventProcess(): Burst transfer error: 0x%02X.", aucResponseBuf[2]);
  3909. DSIDebug::ThreadWrite((char *) aucString1);
  3910. #endif
  3911. bTxError = TRUE;
  3912. }
  3913. }
  3914. else if (aucResponseBuf[1] == MESG_ACKNOWLEDGED_DATA_ID)
  3915. {
  3916. if(aucResponseBuf[2] == TRANSFER_IN_PROGRESS)
  3917. {
  3918. #if defined(DEBUG_FILE)
  3919. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTProtocolEventProcess(): TRANSFER_IN_PROGRESS");
  3920. #endif
  3921. bForceFullInit = TRUE; // Force assign/unassign channel as per "Uplink communication failure on slave channel" issue documented on AP2 Module Rev History
  3922. }
  3923. }
  3924. }
  3925. return TRUE;
  3926. }
  3927. ///////////////////////////////////////////////////////////////////////
  3928. // Returns: TRUE if the message has been handled by ANT-FS host, FALSE otherwise
  3929. BOOL ANTFSHostChannel::ANTChannelEventProcess(UCHAR ucChannel_, UCHAR ucMessageCode_)
  3930. {
  3931. BOOL bIsValid = TRUE;
  3932. #if 0
  3933. #if defined(DEBUG_FILE)
  3934. UCHAR aucString[256];
  3935. SNPRINTF((char *)aucString,256, "ANTFSHostChannel::ANTChannelEventProcess(): Channel %u, Event 0x%02X", ucChannel_, ucMessageCode_);
  3936. DSIDebug::ThreadWrite((char *)aucString);
  3937. #endif
  3938. #endif
  3939. // Check that we're getting a message from the correct channel.
  3940. if((ucChannel_ != ucChannelNumber) || ((aucRxBuf[0] & CHANNEL_NUMBER_MASK) != ucChannelNumber))
  3941. {
  3942. #if defined(DEBUG_FILE)
  3943. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Message received on wrong channel.");
  3944. #endif
  3945. return FALSE;
  3946. }
  3947. switch (ucMessageCode_)
  3948. {
  3949. case EVENT_RX_BROADCAST:
  3950. case EVENT_RX_ACKNOWLEDGED:
  3951. #if 0
  3952. #if defined(DEBUG_FILE)
  3953. {
  3954. UCHAR aucString[256];
  3955. if (ucMessageCode_ == EVENT_RX_BROADCAST)
  3956. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_RX_BROADCAST");
  3957. else
  3958. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_RX_ACKNOWLEDGED");
  3959. SNPRINTF((char *)aucString,256, "ANTFSHostChannel::ANTChannelEventProcess(): Broadcast message received: {0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X}.", aucRxBuf[0], aucRxBuf[1], aucRxBuf[2], aucRxBuf[3], aucRxBuf[4], aucRxBuf[5], aucRxBuf[6], aucRxBuf[7], aucRxBuf[8]);
  3960. DSIDebug::ThreadWrite((char *)aucString);
  3961. }
  3962. #endif
  3963. #endif
  3964. if (aucRxBuf[ANTFS_CONNECTION_OFFSET + 1] != ANTFS_BEACON_ID)
  3965. {
  3966. #if defined(DEBUG_FILE)
  3967. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Invalid connection ID.");
  3968. #endif
  3969. bIsValid = FALSE;
  3970. }
  3971. else if (!bFoundDevice)
  3972. {
  3973. //Decode the payload
  3974. usFoundBeaconPeriod = 0;
  3975. switch (aucRxBuf[STATUS1_OFFSET + 1] & BEACON_PERIOD_MASK)
  3976. {
  3977. case BEACON_PERIOD_0_5_HZ:
  3978. usFoundBeaconPeriod = 65535;
  3979. break;
  3980. case BEACON_PERIOD_1_HZ:
  3981. usFoundBeaconPeriod = 32768;
  3982. break;
  3983. case BEACON_PERIOD_2_HZ:
  3984. usFoundBeaconPeriod = 16384;
  3985. break;
  3986. case BEACON_PERIOD_4_HZ:
  3987. usFoundBeaconPeriod = 8192;
  3988. break;
  3989. case BEACON_PERIOD_8_HZ:
  3990. usFoundBeaconPeriod = 4096;
  3991. break;
  3992. case BEACON_PERIOD_KEEP: // Custom period
  3993. usFoundBeaconPeriod = usTheMessagePeriod;
  3994. break;
  3995. default:
  3996. #if defined(DEBUG_FILE)
  3997. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Invalid beacon period.");
  3998. #endif
  3999. bIsValid = FALSE;
  4000. break;
  4001. }
  4002. if (bIsValid)
  4003. {
  4004. if (aucRxBuf[STATUS1_OFFSET + 1] & DATA_AVAILABLE_FLAG_MASK)
  4005. bFoundDeviceHasData = TRUE;
  4006. else
  4007. bFoundDeviceHasData = FALSE;
  4008. if (aucRxBuf[STATUS1_OFFSET + 1] & UPLOAD_ENABLED_FLAG_MASK)
  4009. bFoundDeviceUploadEnabled = TRUE;
  4010. else
  4011. bFoundDeviceUploadEnabled = FALSE;
  4012. if (aucRxBuf[STATUS1_OFFSET + 1] & PAIRING_AVAILABLE_FLAG_MASK)
  4013. bFoundDeviceInPairingMode = TRUE;
  4014. else
  4015. bFoundDeviceInPairingMode = FALSE;
  4016. ucFoundDeviceAuthenticationType = aucRxBuf[AUTHENTICATION_TYPE_OFFSET + 1];
  4017. usFoundANTFSDeviceType = Convert_Bytes_To_USHORT(aucRxBuf[DEVICE_TYPE_OFFSET_HIGH + 1], aucRxBuf[DEVICE_TYPE_OFFSET_LOW + 1]);
  4018. usFoundANTFSManufacturerID = Convert_Bytes_To_USHORT(aucRxBuf[MANUFACTURER_ID_OFFSET_HIGH + 1], aucRxBuf[MANUFACTURER_ID_OFFSET_LOW + 1]);
  4019. //Set Found device paramenters here
  4020. stFoundDeviceParameters.usDeviceType = Convert_Bytes_To_USHORT(aucRxBuf[DEVICE_TYPE_OFFSET_HIGH + 1], aucRxBuf[DEVICE_TYPE_OFFSET_LOW + 1]);
  4021. stFoundDeviceParameters.usManufacturerID = Convert_Bytes_To_USHORT(aucRxBuf[MANUFACTURER_ID_OFFSET_HIGH + 1], aucRxBuf[MANUFACTURER_ID_OFFSET_LOW + 1]);
  4022. stFoundDeviceParameters.ucAuthenticationType = aucRxBuf[AUTHENTICATION_TYPE_OFFSET + 1];
  4023. stFoundDeviceParameters.ucStatusByte1 = aucRxBuf[STATUS1_OFFSET + 1];
  4024. stFoundDeviceParameters.ucStatusByte2 = aucRxBuf[STATUS2_OFFSET + 1];
  4025. }
  4026. }
  4027. if (bIsValid)
  4028. {
  4029. USHORT usDeviceType;
  4030. USHORT usManufID;
  4031. ULONG ulHostID;
  4032. UCHAR ucCurrentDeviceState = (aucRxBuf[STATUS2_OFFSET + 1] & REMOTE_DEVICE_STATE_MASK);
  4033. usDeviceType = Convert_Bytes_To_USHORT(aucRxBuf[DEVICE_TYPE_OFFSET_HIGH + 1], aucRxBuf[DEVICE_TYPE_OFFSET_LOW + 1]);
  4034. usManufID = Convert_Bytes_To_USHORT(aucRxBuf[MANUFACTURER_ID_OFFSET_HIGH + 1], aucRxBuf[MANUFACTURER_ID_OFFSET_LOW + 1]);
  4035. ulHostID = Convert_Bytes_To_ULONG ( aucRxBuf[HOST_ID_OFFSET + 4],
  4036. aucRxBuf[HOST_ID_OFFSET + 3],
  4037. aucRxBuf[HOST_ID_OFFSET + 2],
  4038. aucRxBuf[HOST_ID_OFFSET + 1]);
  4039. if (ucCurrentDeviceState > REMOTE_DEVICE_STATE_LAST_VALID)
  4040. {
  4041. bIsValid = FALSE;
  4042. #if defined(DEBUG_FILE)
  4043. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Current device state not in valid range.");
  4044. #endif
  4045. }
  4046. else if ((ulHostSerialNumber != ulHostID) && ((usDeviceType != usFoundANTFSDeviceType) || (usManufID != usFoundANTFSManufacturerID)))
  4047. {
  4048. bIsValid = FALSE;
  4049. #if defined(DEBUG_FILE)
  4050. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Host ID does not match this host and the device descriptors match do not match the found device.");
  4051. #endif
  4052. }
  4053. else if (((eANTFSState >= ANTFS_HOST_STATE_TRANSPORT) && (ucCurrentDeviceState < REMOTE_DEVICE_STATE_TRANS)) ||
  4054. ((eANTFSState >= ANTFS_HOST_STATE_CONNECTED) && (ucCurrentDeviceState == REMOTE_DEVICE_STATE_LINK)))
  4055. {
  4056. if (ucStrikes > 0)
  4057. {
  4058. ucStrikes--;
  4059. if (ucStrikes == 0)
  4060. {
  4061. #if defined(DEBUG_FILE)
  4062. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Device state changed; connection lost.");
  4063. #endif
  4064. pclANT->CloseChannel(ucChannelNumber,ANT_CLOSE_TIMEOUT);
  4065. bIsValid = FALSE;
  4066. DSIThread_MutexLock(&stMutexCriticalSection);
  4067. if (eANTFSRequest < ANTFS_REQUEST_CONNECTION_LOST)
  4068. {
  4069. eANTFSRequest = ANTFS_REQUEST_CONNECTION_LOST;
  4070. DSIThread_CondSignal(&stCondRequest);
  4071. }
  4072. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4073. }
  4074. #if defined(DEBUG_FILE)
  4075. else
  4076. {
  4077. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Device state changed; retrying.");
  4078. }
  4079. #endif
  4080. }
  4081. }
  4082. else
  4083. {
  4084. ucStrikes = STRIKE_COUNT;
  4085. ucFoundDeviceState = ucCurrentDeviceState;
  4086. if (ucFoundDeviceState == REMOTE_DEVICE_STATE_TRANS)
  4087. {
  4088. ucTransportBeaconTicks++;
  4089. stFoundDeviceParameters.ucStatusByte1 = aucRxBuf[STATUS1_OFFSET + 1];
  4090. }
  4091. if (ucFoundDeviceState == REMOTE_DEVICE_STATE_AUTH)
  4092. {
  4093. ulFoundBeaconHostID = Convert_Bytes_To_ULONG(aucRxBuf[HOST_ID_OFFSET + 4],
  4094. aucRxBuf[HOST_ID_OFFSET + 3],
  4095. aucRxBuf[HOST_ID_OFFSET + 2],
  4096. aucRxBuf[HOST_ID_OFFSET + 1]);
  4097. }
  4098. }
  4099. }
  4100. DSIThread_MutexLock(&stMutexCriticalSection);
  4101. bFoundDevice = TRUE; // Signal that we have found the device.
  4102. bReceivedBurst = FALSE;
  4103. bFoundDeviceIsValid = bIsValid;
  4104. bNewRxEvent = TRUE;
  4105. DSIThread_CondSignal(&stCondRxEvent);
  4106. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4107. break;
  4108. case EVENT_RX_BURST_PACKET:
  4109. #if 0
  4110. #if defined(DEBUG_FILE)
  4111. {
  4112. UCHAR aucString[256];
  4113. SNPRINTF((char *)aucString, 256, "ANTFSHostChannel::ANTChannelEventProcess(): EVENT_RX_BURST_PACKET received (%lu:%lu): {0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X}.", ulPacketCount, ulTransferArrayIndex / 8, aucRxBuf[0], aucRxBuf[1], aucRxBuf[2], aucRxBuf[3], aucRxBuf[4], aucRxBuf[5], aucRxBuf[6], aucRxBuf[7], aucRxBuf[8]);
  4114. DSIDebug::ThreadWrite((char *)aucString);
  4115. }
  4116. #endif
  4117. #endif
  4118. if (!bRxError)
  4119. {
  4120. if ((aucRxBuf[0] & SEQUENCE_NUMBER_MASK) == 0) // Start of a burst.
  4121. {
  4122. // Check that the message is coming from an ANTFS Device.
  4123. if (aucRxBuf[ANTFS_CONNECTION_OFFSET + 1] != ANTFS_BEACON_ID)
  4124. {
  4125. #if defined(DEBUG_FILE)
  4126. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Invalid ID.");
  4127. #endif
  4128. bRxError = TRUE;
  4129. }
  4130. else
  4131. {
  4132. #if defined(DEBUG_FILE)
  4133. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Burst started");
  4134. #endif
  4135. ucFoundDeviceState = (aucRxBuf[STATUS2_OFFSET + 1] & REMOTE_DEVICE_STATE_MASK);
  4136. }
  4137. ulPacketCount = 1;
  4138. bReceivedResponse = FALSE;
  4139. }
  4140. else
  4141. {
  4142. // Response packet.
  4143. if (ulPacketCount == 1)
  4144. {
  4145. // Check that the response contains the correct ID
  4146. if (aucRxBuf[ANTFS_CONNECTION_OFFSET + 1] != ANTFS_COMMAND_RESPONSE_ID)
  4147. {
  4148. #if defined(DEBUG_FILE)
  4149. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Invalid ID2.");
  4150. #endif
  4151. bRxError = TRUE;
  4152. }
  4153. else
  4154. {
  4155. switch (aucRxBuf[ANTFS_COMMAND_OFFSET + 1])
  4156. {
  4157. case ANTFS_RESPONSE_AUTH_ID:
  4158. case ANTFS_RESPONSE_UPLOAD_ID:
  4159. case ANTFS_RESPONSE_ERASE_ID:
  4160. case ANTFS_RESPONSE_UPLOAD_COMPLETE_ID:
  4161. memcpy(aucTransferBufferFixed, &aucRxBuf[1], 8); // Always copy the response to the start of the transfer buffer.
  4162. memset(&aucTransferBufferFixed[8],0x00,sizeof(aucTransferBufferFixed)-8); //Zero the rest of the receive buffer
  4163. ulTransferArrayIndex = 8;
  4164. pucTransferBuffer = aucTransferBufferFixed;
  4165. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4166. {
  4167. bReceivedResponse = TRUE;
  4168. #if defined(DEBUG_FILE)
  4169. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Reception of burst complete. (0)");
  4170. #endif
  4171. }
  4172. #if defined(DEBUG_FILE)
  4173. else
  4174. {
  4175. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Receiving burst... (0)");
  4176. }
  4177. #endif
  4178. ulTransferBufferSize = sizeof(aucTransferBufferFixed);
  4179. break;
  4180. case ANTFS_RESPONSE_DOWNLOAD_SMALL_ID:
  4181. if (ulTransferArrayIndex == 0)
  4182. {
  4183. ulTransferTotalBytesRemaining = Convert_Bytes_To_ULONG(0,
  4184. 0,
  4185. aucRxBuf[DATA_BLOCK_SIZE_OFFSET_HIGH + 1],
  4186. aucRxBuf[DATA_BLOCK_SIZE_OFFSET_LOW + 1]);
  4187. ulTransferBufferSize = ulTransferTotalBytesRemaining + 16 + 8; //+16 for the extra packet at the start and rounding up to the next 8 byte packet, + 8 for additional buffering
  4188. if (pucTransferBufferDynamic)
  4189. delete[] pucTransferBufferDynamic;
  4190. try
  4191. {
  4192. pucTransferBufferDynamic = new UCHAR[ulTransferBufferSize];
  4193. if (pucTransferBufferDynamic == NULL)
  4194. throw "Memory allocation failure!";
  4195. }
  4196. catch(...)
  4197. {
  4198. bRxError = TRUE;
  4199. pucTransferBuffer = (UCHAR*) NULL;
  4200. #if defined(DEBUG_FILE)
  4201. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Unable to allocate memory for download. (1)");
  4202. #endif
  4203. break;
  4204. }
  4205. ulTransferArrayIndex = 8;
  4206. pucTransferBuffer = pucTransferBufferDynamic;
  4207. }
  4208. if (pucTransferBufferDynamic == NULL)
  4209. {
  4210. #if defined(DEBUG_FILE)
  4211. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): pucTransferBufferDynamic is NULL, ignoring transfer Packet");
  4212. #endif
  4213. break;
  4214. }
  4215. memcpy(pucTransferBufferDynamic, &aucRxBuf[1], 8); // Always copy the response to the start of the download buffer.
  4216. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4217. {
  4218. bReceivedResponse = TRUE;
  4219. #if defined(DEBUG_FILE)
  4220. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Reception of burst complete. (1)");
  4221. #endif
  4222. }
  4223. #if defined(DEBUG_FILE)
  4224. else
  4225. {
  4226. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Receiving burst... (1)");
  4227. }
  4228. #endif
  4229. break;
  4230. case ANTFS_RESPONSE_DOWNLOAD_BIG_ID:
  4231. if (ulTransferArrayIndex == 0) //if this is the first packed of the this download session
  4232. {
  4233. ulTransferArrayIndex = 8;
  4234. pucTransferBuffer = aucTransferBufferFixed; //Use the fixed buffer for now
  4235. ulTransferBufferSize = sizeof(aucTransferBufferFixed);
  4236. }
  4237. ulTransferBytesInBlock = Convert_Bytes_To_ULONG(aucRxBuf[DOWNLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 3 + 1],
  4238. aucRxBuf[DOWNLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 2 + 1],
  4239. aucRxBuf[DOWNLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 1 + 1],
  4240. aucRxBuf[DOWNLOAD_RESPONSE_BLOCK_SIZE_OFFSET + 1]);
  4241. memcpy(pucTransferBuffer, &aucRxBuf[1], 8); // Always copy the response to the start of the transfer buffer.
  4242. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4243. {
  4244. bRxError = TRUE;
  4245. #if defined(DEBUG_FILE)
  4246. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Premature end of burst transfer.");
  4247. #endif
  4248. }
  4249. break;
  4250. case ANTFS_RESPONSE_SEND_DIRECT_ID:
  4251. {
  4252. ulTransferArrayIndex = Convert_Bytes_To_ULONG(0,
  4253. 0,
  4254. aucRxBuf[DATA_OFFSET_OFFSET_HIGH + 1],
  4255. aucRxBuf[DATA_OFFSET_OFFSET_LOW + 1]);
  4256. ulTransferArrayIndex *= 8;
  4257. ulTransferTotalBytesRemaining = Convert_Bytes_To_ULONG(0,
  4258. 0,
  4259. aucRxBuf[DATA_BLOCK_SIZE_OFFSET_HIGH + 1],
  4260. aucRxBuf[DATA_BLOCK_SIZE_OFFSET_LOW + 1]);
  4261. ulTransferTotalBytesRemaining *= 8;
  4262. }
  4263. if (ulTransferArrayIndex == 0)
  4264. {
  4265. ulTransferBufferSize = DIRECT_TRANSFER_SIZE + 16;
  4266. if (pucTransferBufferDynamic)
  4267. delete[] pucTransferBufferDynamic;
  4268. try
  4269. {
  4270. pucTransferBufferDynamic = new UCHAR[ulTransferBufferSize];
  4271. if (pucTransferBufferDynamic == NULL)
  4272. throw "Memory allocation failure!";
  4273. }
  4274. catch(...)
  4275. {
  4276. bRxError = TRUE;
  4277. pucTransferBuffer = (UCHAR*) NULL;
  4278. #if defined(DEBUG_FILE)
  4279. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Unable to allocate memory for download. (3)");
  4280. #endif
  4281. break;
  4282. }
  4283. pucTransferBuffer = pucTransferBufferDynamic;
  4284. }
  4285. else if (pucTransferBufferDynamic == NULL)
  4286. {
  4287. bRxError = TRUE;
  4288. #if defined(DEBUG_FILE)
  4289. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): ANTFS_RESPONSE_SEND_DIRECT index error.");
  4290. #endif
  4291. break;
  4292. }
  4293. ulTransferArrayIndex += 8; // This offset due to the response packet.
  4294. memcpy(pucTransferBufferDynamic, &aucRxBuf[1], 8); // Always copy the response to the start of the download buffer.
  4295. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4296. {
  4297. bReceivedResponse = TRUE;
  4298. #if defined(DEBUG_FILE)
  4299. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Reception of burst complete. (2)");
  4300. #endif
  4301. }
  4302. #if defined(DEBUG_FILE)
  4303. else
  4304. {
  4305. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Receiving burst... (1)");
  4306. }
  4307. #endif
  4308. break;
  4309. default:
  4310. bRxError = TRUE; // BIG DL/UL and everything else are not handled right now so we fail out here.
  4311. break;
  4312. }
  4313. }
  4314. }
  4315. else if ((ulPacketCount == 2) && (pucTransferBuffer != NULL) && (pucTransferBuffer[ANTFS_COMMAND_OFFSET] == ANTFS_RESPONSE_DOWNLOAD_BIG_ID) &&(pucTransferBuffer[ANTFS_CONNECTION_OFFSET] == ANTFS_COMMAND_RESPONSE_ID))
  4316. {
  4317. if (ulTransferArrayIndex == 8)
  4318. {
  4319. ulTransferTotalBytesRemaining = Convert_Bytes_To_ULONG(aucRxBuf[DOWNLOAD_RESPONSE_FILE_SIZE_OFFSET + 3 + 1],
  4320. aucRxBuf[DOWNLOAD_RESPONSE_FILE_SIZE_OFFSET + 2 + 1],
  4321. aucRxBuf[DOWNLOAD_RESPONSE_FILE_SIZE_OFFSET + 1 + 1],
  4322. aucRxBuf[DOWNLOAD_RESPONSE_FILE_SIZE_OFFSET + 1]);
  4323. if (ulTransferByteSize && ulTransferByteSize < ulTransferTotalBytesRemaining) //If our desired download size is less than the file size, set it.
  4324. ulTransferTotalBytesRemaining = ulTransferByteSize;
  4325. ulTransferBufferSize = ulTransferTotalBytesRemaining + 24 + 8 + 8;//+24 for the extra packets at the start and rounding up to the next 8 byte packet, + 8 for additional buffering +8 more for CRC
  4326. #if defined(DEBUG_FILE)
  4327. {
  4328. char szString[256];
  4329. SNPRINTF(szString, 256, "ANTFSHostChannel::ANTChannelEventProcess(): ulTransferBufferSize = %lu.", ulTransferBufferSize);
  4330. DSIDebug::ThreadWrite(szString);
  4331. }
  4332. #endif
  4333. if (pucTransferBufferDynamic)
  4334. delete[] pucTransferBufferDynamic;
  4335. try
  4336. {
  4337. pucTransferBufferDynamic = new UCHAR[ulTransferBufferSize];
  4338. if (pucTransferBufferDynamic == NULL)
  4339. throw "Memory allocation failure!";
  4340. }
  4341. catch(...)
  4342. {
  4343. bRxError = TRUE;
  4344. ulTransferArrayIndex = 0;
  4345. pucTransferBuffer = (UCHAR*) NULL;
  4346. #if defined(DEBUG_FILE)
  4347. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Unable to allocate memory for download. (2)");
  4348. #endif
  4349. break;
  4350. }
  4351. memcpy(pucTransferBufferDynamic, aucTransferBufferFixed, 8); // Copy over the first packet that we saved temporarily.
  4352. ulTransferArrayIndex = 16;
  4353. pucTransferBuffer = pucTransferBufferDynamic;
  4354. }
  4355. if (pucTransferBufferDynamic == NULL)
  4356. {
  4357. #if defined(DEBUG_FILE)
  4358. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): pucTransferBufferDynamic is NULL, ignoring transfer Packet");
  4359. #endif
  4360. break;
  4361. }
  4362. memcpy(&pucTransferBuffer[8], &aucRxBuf[1], 8); // Always copy the response to the start of the transfer buffer.
  4363. ULONG ulReceivedDataOffset = Convert_Bytes_To_ULONG(aucRxBuf[DOWNLOAD_RESPONSE_DATA_OFFSET_OFFSET + 3 + 1],
  4364. aucRxBuf[DOWNLOAD_RESPONSE_DATA_OFFSET_OFFSET + 2 + 1],
  4365. aucRxBuf[DOWNLOAD_RESPONSE_DATA_OFFSET_OFFSET + 1 + 1],
  4366. aucRxBuf[DOWNLOAD_RESPONSE_DATA_OFFSET_OFFSET + 1]);
  4367. if ((pucTransferBuffer[DOWNLOAD_RESPONSE_OFFSET] == DOWNLOAD_RESPONSE_OK) && ((ulReceivedDataOffset - ulTransferDataOffset) != (ulTransferArrayIndex - 16)))
  4368. {
  4369. bRxError = TRUE;
  4370. ulTransferArrayIndex = 0;
  4371. pucTransferBuffer = (UCHAR*) NULL;
  4372. #if defined(DEBUG_FILE)
  4373. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): DL offset does not match desired DL offset.");
  4374. #endif
  4375. break;
  4376. }
  4377. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4378. {
  4379. bReceivedResponse = TRUE;
  4380. #if defined(DEBUG_FILE)
  4381. {
  4382. char szString[256];
  4383. SNPRINTF(szString, 256, "ANTFSHostChannel::ANTChannelEventProcess(): Reception of burst complete. (%lu).", ulTransferArrayIndex);
  4384. DSIDebug::ThreadWrite(szString);
  4385. }
  4386. #endif
  4387. }
  4388. }
  4389. else if ((ulTransferArrayIndex + 8) <= ulTransferBufferSize)
  4390. {
  4391. #if defined(DEBUG_FILE_V1)
  4392. {
  4393. char szString[256];
  4394. SNPRINTF(szString, 256, "ANTFSHostChannel::ANTChannelEventProcess(): ulTransferArrayIndex = %lu.", ulTransferArrayIndex);
  4395. DSIDebug::ThreadWrite(szString);
  4396. }
  4397. #endif
  4398. if (pucTransferBuffer == NULL)
  4399. {
  4400. #if defined(DEBUG_FILE)
  4401. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): pucTransferBuffer is NULL, ignoring transfer Packet");
  4402. #endif
  4403. break;
  4404. }
  4405. memcpy(&pucTransferBuffer[ulTransferArrayIndex], &aucRxBuf[1], 8);
  4406. ulTransferArrayIndex += 8;
  4407. if (aucRxBuf[0] & SEQUENCE_LAST_MESSAGE)
  4408. {
  4409. bReceivedResponse = TRUE;
  4410. #if defined(DEBUG_FILE)
  4411. {
  4412. char szString[256];
  4413. SNPRINTF(szString, 256, "ANTFSHostChannel::ANTChannelEventProcess(): Reception of burst complete. (%lu).", ulTransferArrayIndex);
  4414. DSIDebug::ThreadWrite(szString);
  4415. }
  4416. #endif
  4417. }
  4418. #if defined(DEBUG_FILE_V1)
  4419. else
  4420. {
  4421. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Receiving burst... (n)");
  4422. }
  4423. #endif
  4424. }
  4425. else
  4426. {
  4427. #if defined(DEBUG_FILE)
  4428. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): Burst Buffer Overflow");
  4429. #endif
  4430. bRxError = TRUE;
  4431. }
  4432. ulPacketCount++;
  4433. }
  4434. }
  4435. DSIThread_MutexLock(&stMutexCriticalSection);
  4436. bReceivedBurst = TRUE;
  4437. bNewRxEvent = TRUE;
  4438. DSIThread_CondSignal(&stCondRxEvent);
  4439. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4440. #if defined(DEBUG_FILE_V1)
  4441. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): bReceivedBurst = TRUE");
  4442. #endif
  4443. break;
  4444. case EVENT_TRANSFER_RX_FAILED:
  4445. DSIThread_MutexLock(&stMutexCriticalSection);
  4446. bRxError = TRUE;
  4447. bReceivedBurst = FALSE;
  4448. bReceivedResponse = FALSE;
  4449. DSIThread_CondSignal(&stCondRxEvent);
  4450. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4451. #if defined(DEBUG_FILE)
  4452. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_TRANSFER_RX_FAILED");
  4453. #endif
  4454. break;
  4455. case EVENT_RX_FAIL_GO_TO_SEARCH:
  4456. if (eANTFSState == ANTFS_HOST_STATE_SEARCHING)
  4457. {
  4458. DSIThread_MutexLock(&stMutexCriticalSection);
  4459. bFoundDeviceIsValid = FALSE; // Signal that this is not a valid beacon
  4460. bFoundDevice = TRUE; // Signal that we have found the device to allow the search loop to exit.
  4461. bReceivedBurst = FALSE;
  4462. bNewRxEvent = TRUE;
  4463. DSIThread_CondSignal(&stCondRxEvent);
  4464. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4465. #if defined(DEBUG_FILE)
  4466. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_RX_FAIL_GO_TO_SEARCH");
  4467. #endif
  4468. }
  4469. break;
  4470. case EVENT_RX_SEARCH_TIMEOUT:
  4471. #if defined(DEBUG_FILE)
  4472. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_RX_SEARCH_TIMEOUT");
  4473. #endif
  4474. if (eANTFSState == ANTFS_HOST_STATE_SEARCHING)
  4475. {
  4476. pclANT->OpenChannel(ucChannelNumber); // Re-open the channel.
  4477. }
  4478. else if ((eANTFSState == ANTFS_HOST_STATE_DOWNLOADING) || (eANTFSState == ANTFS_HOST_STATE_UPLOADING) || (eANTFSState == ANTFS_HOST_STATE_SENDING) || (eANTFSState == ANTFS_HOST_STATE_RECEIVING))
  4479. {
  4480. pclANT->OpenChannel(ucChannelNumber); // Re-open the channel.
  4481. DSIThread_MutexLock(&stMutexCriticalSection);
  4482. bRxError = TRUE;
  4483. bTxError = TRUE; // Can no longer transmit data, either.
  4484. bReceivedBurst = FALSE;
  4485. DSIThread_CondSignal(&stCondRxEvent);
  4486. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4487. }
  4488. else if (eANTFSState >= ANTFS_HOST_STATE_CONNECTED)
  4489. {
  4490. DSIThread_MutexLock(&stMutexCriticalSection);
  4491. if (eANTFSRequest < ANTFS_REQUEST_CONNECTION_LOST)
  4492. {
  4493. eANTFSRequest = ANTFS_REQUEST_CONNECTION_LOST;
  4494. DSIThread_CondSignal(&stCondRequest);
  4495. }
  4496. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4497. }
  4498. // any other states we don't report the timeout
  4499. break;
  4500. case EVENT_TRANSFER_TX_COMPLETED:
  4501. #if defined(DEBUG_FILE)
  4502. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_TRANSFER_TX_COMPLETED");
  4503. #endif
  4504. break;
  4505. case EVENT_TRANSFER_TX_FAILED:
  4506. bTxError = TRUE;
  4507. #if defined(DEBUG_FILE)
  4508. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_TRANSFER_TX_FAILED");
  4509. #endif
  4510. break;
  4511. case EVENT_TRANSFER_TX_START:
  4512. #if defined(DEBUG_FILE)
  4513. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_TRANSFER_TX_START");
  4514. #endif
  4515. break;
  4516. case EVENT_CHANNEL_CLOSED:
  4517. #if defined(DEBUG_FILE)
  4518. DSIDebug::ThreadWrite("ANTFSHostChannel::ANTChannelEventProcess(): EVENT_CHANNEL_CLOSED");
  4519. #endif
  4520. break;
  4521. default:
  4522. break;
  4523. }
  4524. return TRUE; // message has been handled, do not pass to application
  4525. }
  4526. ///////////////////////////////////////////////////////////////////////
  4527. BOOL ANTFSHostChannel::Blackout(ULONG ulDeviceID_, USHORT usManufacturerID_, USHORT usDeviceType_, USHORT usBlackoutTime_)
  4528. //BOOL ANTFSHost::IgnoreDevice(USHORT usBlackoutTime_)
  4529. {
  4530. BOOL bRetVal = TRUE;
  4531. IGNORE_LIST_ITEM stListItem;
  4532. IGNORE_LIST_ITEM *pstListItem;
  4533. if (usBlackoutTime_ == 0)
  4534. return FALSE;
  4535. #if defined(DEBUG_FILE)
  4536. DSIDebug::ThreadWrite("ANTFSHostChannel::Blackout(): Entering critical section.");
  4537. #endif
  4538. DSIThread_MutexLock(&stMutexIgnoreListAccess);
  4539. stListItem.usID = (USHORT)ulDeviceID_;
  4540. stListItem.usManufacturerID = usManufacturerID_;
  4541. stListItem.usDeviceType = usDeviceType_;
  4542. pstListItem = (IGNORE_LIST_ITEM *) bsearch(&stListItem, astIgnoreList, usListIndex, sizeof(IGNORE_LIST_ITEM), &ListCompare);
  4543. if (pstListItem != NULL)
  4544. {
  4545. // If the ID is already in the list, set the blackout time.
  4546. pstListItem->usTimeout = usBlackoutTime_;
  4547. }
  4548. else
  4549. {
  4550. // If the ID is not on the list, add it.
  4551. if (usListIndex < MAX_IGNORE_LIST_SIZE)
  4552. {
  4553. astIgnoreList[usListIndex].usID = (USHORT)ulDeviceID_;
  4554. astIgnoreList[usListIndex].usManufacturerID = usManufacturerID_;
  4555. astIgnoreList[usListIndex].usDeviceType = usDeviceType_;
  4556. astIgnoreList[usListIndex].usTimeout = usBlackoutTime_;
  4557. usListIndex++;
  4558. qsort(astIgnoreList, usListIndex, sizeof(IGNORE_LIST_ITEM), &ListCompare);
  4559. }
  4560. else
  4561. {
  4562. bRetVal = FALSE; // Can't add any more devices to the list.
  4563. }
  4564. }
  4565. DSIThread_MutexUnlock(&stMutexIgnoreListAccess);
  4566. #if defined(DEBUG_FILE)
  4567. DSIDebug::ThreadWrite("ANTFSHostChannel::Blackout(): Left critical section.");
  4568. #endif
  4569. return bRetVal;
  4570. }
  4571. ///////////////////////////////////////////////////////////////////////
  4572. BOOL ANTFSHostChannel::RemoveBlackout(ULONG ulDeviceID_, USHORT usManufacturerID_, USHORT usDeviceType_)
  4573. {
  4574. BOOL bRetVal = TRUE;
  4575. IGNORE_LIST_ITEM stListItem;
  4576. IGNORE_LIST_ITEM *pstListItem;
  4577. #if defined(DEBUG_FILE)
  4578. DSIDebug::ThreadWrite("ANTFSHostChannel::RemoveBlackout(): Entering critical section.");
  4579. #endif
  4580. DSIThread_MutexLock(&stMutexIgnoreListAccess);
  4581. stListItem.usID = (USHORT)ulDeviceID_;
  4582. stListItem.usManufacturerID = usManufacturerID_;
  4583. stListItem.usDeviceType = usDeviceType_;
  4584. pstListItem = (IGNORE_LIST_ITEM *) bsearch(&stListItem, astIgnoreList, usListIndex, sizeof(IGNORE_LIST_ITEM), &ListCompare);
  4585. if (pstListItem != NULL)
  4586. {
  4587. USHORT usIndex = (USHORT)((pstListItem - astIgnoreList) / sizeof(IGNORE_LIST_ITEM));
  4588. // If the ID is found on the list, set the blackout time to 0 and remove it.
  4589. astIgnoreList[usIndex].usTimeout = 0;
  4590. #if defined(DEBUG_FILE)
  4591. {
  4592. UCHAR aucString[256];
  4593. SNPRINTF((char *)aucString,256, "Removing %u %u %u from ignore list.", astIgnoreList[usIndex].usID,astIgnoreList[usIndex].usDeviceType,astIgnoreList[usIndex].usManufacturerID);
  4594. DSIDebug::ThreadWrite((char *)aucString);
  4595. }
  4596. #endif
  4597. for (usIndex = usIndex + 1; usIndex < usListIndex; usIndex++)
  4598. astIgnoreList[usIndex - 1] = astIgnoreList[usIndex];
  4599. usListIndex--;
  4600. }
  4601. else
  4602. {
  4603. // If the ID is not on the list.
  4604. bRetVal = FALSE;
  4605. }
  4606. DSIThread_MutexUnlock(&stMutexIgnoreListAccess);
  4607. #if defined(DEBUG_FILE)
  4608. DSIDebug::ThreadWrite("ANTFSHostChannel::RemoveBlackout(): Left critical section.");
  4609. #endif
  4610. return bRetVal;
  4611. }
  4612. ///////////////////////////////////////////////////////////////////////
  4613. void ANTFSHostChannel::ClearBlackoutList(void)
  4614. {
  4615. DSIThread_MutexLock(&stMutexIgnoreListAccess);
  4616. usListIndex = 0;
  4617. DSIThread_MutexUnlock(&stMutexIgnoreListAccess);
  4618. }
  4619. ///////////////////////////////////////////////////////////////////////
  4620. static int ListCompare(const void *puvKeyVal, const void *puvDatum)
  4621. {
  4622. if (((IGNORE_LIST_ITEM *) puvKeyVal)->usManufacturerID < ((IGNORE_LIST_ITEM *) puvDatum)->usManufacturerID)
  4623. return -1;
  4624. if (((IGNORE_LIST_ITEM *) puvKeyVal)->usDeviceType < ((IGNORE_LIST_ITEM *) puvDatum)->usDeviceType)
  4625. return -1;
  4626. if (((IGNORE_LIST_ITEM *) puvKeyVal)->usID < ((IGNORE_LIST_ITEM *) puvDatum)->usID)
  4627. return -1;
  4628. if ((((IGNORE_LIST_ITEM *) puvKeyVal)->usManufacturerID == ((IGNORE_LIST_ITEM *) puvDatum)->usManufacturerID) &&
  4629. (((IGNORE_LIST_ITEM *) puvKeyVal)->usDeviceType == ((IGNORE_LIST_ITEM *) puvDatum)->usDeviceType) &&
  4630. (((IGNORE_LIST_ITEM *) puvKeyVal)->usID == ((IGNORE_LIST_ITEM *) puvDatum)->usID))
  4631. return 0;
  4632. return 1;
  4633. }
  4634. ///////////////////////////////////////////////////////////////////////
  4635. // Frequency: 1 Hz
  4636. ///////////////////////////////////////////////////////////////////////
  4637. DSI_THREAD_RETURN ANTFSHostChannel::QueueTimerStart(void *pvParameter_)
  4638. {
  4639. ((ANTFSHostChannel *)pvParameter_)->QueueTimerCallback();
  4640. return 0;
  4641. }
  4642. ///////////////////////////////////////////////////////////////////////
  4643. void ANTFSHostChannel::QueueTimerCallback(void)
  4644. {
  4645. USHORT usCounter = 0;
  4646. if(!bTimerThreadInitDone)
  4647. {
  4648. #if defined(DEBUG_FILE)
  4649. DSIDebug::ThreadInit("Timer");
  4650. #endif
  4651. bTimerThreadInitDone = TRUE;
  4652. }
  4653. #if defined(DEBUG_FILE)
  4654. DSIDebug::ThreadWrite("ANTFSHostChannel::TimerQueueTimerCall(): Entering critical section.");
  4655. #endif
  4656. DSIThread_MutexLock(&stMutexIgnoreListAccess);
  4657. #if defined(DEBUG_FILE)
  4658. DSIDebug::ThreadWrite("Updating ignore list...");
  4659. #endif
  4660. while (usCounter < usListIndex)
  4661. {
  4662. if ((astIgnoreList[usCounter].usTimeout > 0) && (astIgnoreList[usCounter].usTimeout != MAX_USHORT))
  4663. astIgnoreList[usCounter].usTimeout--;
  4664. if (astIgnoreList[usCounter].usTimeout == 0) // Remove the List Item if it has expired.
  4665. {
  4666. USHORT usInsideLoopCounter;
  4667. #if defined(DEBUG_FILE)
  4668. {
  4669. UCHAR aucString[256];
  4670. SNPRINTF((char *)aucString,256, "Removing %u %u %u from ignore list.", astIgnoreList[usCounter].usID, astIgnoreList[usCounter].usDeviceType, astIgnoreList[usCounter].usManufacturerID);
  4671. DSIDebug::ThreadWrite((char *)aucString);
  4672. }
  4673. #endif
  4674. for (usInsideLoopCounter = usCounter + 1; usInsideLoopCounter < usListIndex; usInsideLoopCounter++)
  4675. astIgnoreList[usInsideLoopCounter - 1] = astIgnoreList[usInsideLoopCounter];
  4676. usListIndex--;
  4677. }
  4678. else
  4679. {
  4680. #if defined(DEBUG_FILE)
  4681. {
  4682. UCHAR aucString[256];
  4683. SNPRINTF((char *)aucString,256, "%u %u %u is on ignore list. %us left.", astIgnoreList[usCounter].usID, astIgnoreList[usCounter].usDeviceType, astIgnoreList[usCounter].usManufacturerID, astIgnoreList[usCounter].usTimeout);
  4684. DSIDebug::ThreadWrite((char *)aucString);
  4685. }
  4686. #endif
  4687. usCounter++;
  4688. }
  4689. }
  4690. DSIThread_MutexUnlock(&stMutexIgnoreListAccess);
  4691. #if defined(DEBUG_FILE)
  4692. DSIDebug::ThreadWrite("ANTFSHostChannel::TimerQueueTimerCall(): Left critical section.");
  4693. #endif
  4694. /*
  4695. if (++usSerialWatchdog > ANTFS_SERIAL_WATCHDOG_COUNT)
  4696. {
  4697. usSerialWatchdog = 0;
  4698. HandleSerialError(); //! This is where we would want to potentially add a serial watch dog, if it makes sense to do so in the future
  4699. }
  4700. */
  4701. }
  4702. ///////////////////////////////////////////////////////////////////////
  4703. void ANTFSHostChannel::HandleSerialError(void)
  4704. {
  4705. // We ended up here because we did not receive the expected response to a serial message
  4706. // Most likely, ANT was in the wrong state, so attempt to close the channel.
  4707. // No errors raised from here, as we do not know what state we are in.
  4708. UCHAR ucChannelStatus = 0;
  4709. if(pclANT->CloseChannel(ucChannelNumber, ANT_CLOSE_TIMEOUT) != TRUE)
  4710. {
  4711. #if defined(DEBUG_FILE)
  4712. DSIDebug::ThreadWrite("ANTFSHostChannel::HandleSerialError(): Failed to close channel.");
  4713. #endif
  4714. }
  4715. if(pclANT->UnAssignChannel(ucChannelNumber, MESSAGE_TIMEOUT) != TRUE)
  4716. {
  4717. #if defined(DEBUG_FILE)
  4718. DSIDebug::ThreadWrite("ANTFSHostChannel::HandleSerialError(): Failed to unassign channel.");
  4719. #endif
  4720. }
  4721. // The following is just for information purposes...
  4722. if(pclANT->GetChannelStatus(ucChannelNumber, &ucChannelStatus, MESSAGE_TIMEOUT) == FALSE)
  4723. {
  4724. #if defined(DEBUG_FILE)
  4725. DSIDebug::ThreadWrite("ANTFSHostChannel::HandleSerialError(): Failed ANT_GetChannelStatus().");
  4726. #endif
  4727. }
  4728. #if defined(DEBUG_FILE)
  4729. else if ((ucChannelStatus & STATUS_CHANNEL_STATE_MASK) != STATUS_UNASSIGNED_CHANNEL)
  4730. {
  4731. char szString[256];
  4732. SNPRINTF(szString, 256, "ANTFSHostChannel::HandleSerialError(): Channel state... 0x%x.", ucChannelStatus);
  4733. DSIDebug::ThreadWrite(szString);
  4734. }
  4735. #endif
  4736. DSIThread_MutexLock(&stMutexCriticalSection);
  4737. eANTFSRequest = ANTFS_REQUEST_SERIAL_ERROR_HANDLED; // Reset state machine next
  4738. DSIThread_CondSignal(&stCondRequest);
  4739. DSIThread_MutexUnlock(&stMutexCriticalSection);
  4740. }
  4741. ///////////////////////////////////////////////////////////////////////
  4742. // This function is called to increment the frequency stale counter
  4743. ///////////////////////////////////////////////////////////////////////
  4744. void ANTFSHostChannel::IncFreqStaleCount(UCHAR ucInc)
  4745. {
  4746. USHORT usTemp = (USHORT)ucTransportFrequencyStaleCount + (USHORT)ucInc;
  4747. if (usTemp >= MAX_STALE_COUNT)
  4748. ucTransportFrequencyStaleCount = MAX_STALE_COUNT;
  4749. else
  4750. ucTransportFrequencyStaleCount = (UCHAR)usTemp;
  4751. }
  4752. ///////////////////////////////////////////////////////////////////////
  4753. // This function is called to populate/re-populate the frequency table randomly
  4754. ///////////////////////////////////////////////////////////////////////
  4755. void ANTFSHostChannel::PopulateTransportFreqTable(void)
  4756. {
  4757. UCHAR aucTemp[TRANSPORT_FREQUENCY_LIST_SIZE];
  4758. int i = 0;
  4759. ucTransportFrequencyStaleCount = 0;
  4760. ucCurrentTransportFreqElement = 0;
  4761. srand((unsigned int)time((time_t*)NULL));
  4762. memcpy (aucTemp, aucTransportFrequencyList, TRANSPORT_FREQUENCY_LIST_SIZE);
  4763. for (i=0; i < TRANSPORT_FREQUENCY_LIST_SIZE; i++)
  4764. {
  4765. UCHAR ucNewValue = (UCHAR)( 1 + (rand() % (TRANSPORT_FREQUENCY_LIST_SIZE-1)) );
  4766. UCHAR j = 0;
  4767. while (ucNewValue)
  4768. {
  4769. j = (j+1)%TRANSPORT_FREQUENCY_LIST_SIZE;
  4770. if (aucTemp[j] != 0xFF)
  4771. {
  4772. ucNewValue--;
  4773. }
  4774. }
  4775. aucFrequencyTable[i] = aucTemp[j];
  4776. aucTemp[j] = 0xFF;
  4777. }
  4778. }
  4779. ///////////////////////////////////////////////////////////////////////
  4780. // This function is called to check if we need to change frequencies and return the new frequncy
  4781. ///////////////////////////////////////////////////////////////////////
  4782. UCHAR ANTFSHostChannel::CheckForNewTransportFreq(void)
  4783. {
  4784. if (ucTransportFrequencyStaleCount >= MAX_STALE_COUNT)
  4785. {
  4786. ucCurrentTransportFreqElement = ((ucCurrentTransportFreqElement+1) % TRANSPORT_FREQUENCY_LIST_SIZE);
  4787. ucTransportFrequencyStaleCount = 0;
  4788. }
  4789. return aucFrequencyTable[ucCurrentTransportFreqElement];
  4790. }
  4791. ///////////////////////////////////////////////////////////////////////
  4792. static int DeviceParametersItemCompare(const void *pvItem1, const void *pvItem2)
  4793. {
  4794. if (((DEVICE_PARAMETERS_ITEM *) pvItem1)->usHandle < ((DEVICE_PARAMETERS_ITEM *) pvItem2)->usHandle)
  4795. return -1;
  4796. if (((DEVICE_PARAMETERS_ITEM *) pvItem1)->usHandle == ((DEVICE_PARAMETERS_ITEM *) pvItem2)->usHandle)
  4797. return 0;
  4798. return 1;
  4799. }
  4800. ///////////////////////////////////////////////////////////////////////
  4801. BOOL ANTFSHostChannel::IsDeviceMatched(ANTFS_DEVICE_PARAMETERS *psDeviceParameters_, BOOL bPartialID_)
  4802. {
  4803. USHORT usDeviceIndex = 0;
  4804. ULONG ulIDMask;
  4805. if (usDeviceListSize == 0)
  4806. return TRUE; // There are no devices in the list, so any device is a match.
  4807. if(bPartialID_)
  4808. ulIDMask = MAX_USHORT;
  4809. else
  4810. ulIDMask = MAX_ULONG;
  4811. while (usDeviceIndex < usDeviceListSize)
  4812. {
  4813. DEVICE_PARAMETERS_ITEM *psSearchDeviceItem = &asDeviceParametersList[usDeviceIndex];
  4814. if (
  4815. ((psDeviceParameters_->ulDeviceID & psSearchDeviceItem->sDeviceSearchMask.ulDeviceID & ulIDMask) == (psSearchDeviceItem->sDeviceParameters.ulDeviceID & psSearchDeviceItem->sDeviceSearchMask.ulDeviceID & ulIDMask))
  4816. &&
  4817. ((psDeviceParameters_->usManufacturerID & psSearchDeviceItem->sDeviceSearchMask.usManufacturerID) == (psSearchDeviceItem->sDeviceParameters.usManufacturerID & psSearchDeviceItem->sDeviceSearchMask.usManufacturerID))
  4818. &&
  4819. ((psDeviceParameters_->usDeviceType & psSearchDeviceItem->sDeviceSearchMask.usDeviceType) == (psSearchDeviceItem->sDeviceParameters.usDeviceType & psSearchDeviceItem->sDeviceSearchMask.usDeviceType))
  4820. &&
  4821. ((psDeviceParameters_->ucAuthenticationType & psSearchDeviceItem->sDeviceSearchMask.ucAuthenticationType) == (psSearchDeviceItem->sDeviceParameters.ucAuthenticationType & psSearchDeviceItem->sDeviceSearchMask.ucAuthenticationType))
  4822. &&
  4823. ((psDeviceParameters_->ucStatusByte1 & psSearchDeviceItem->sDeviceSearchMask.ucStatusByte1) == (psSearchDeviceItem->sDeviceParameters.ucStatusByte1 & psSearchDeviceItem->sDeviceSearchMask.ucStatusByte1))
  4824. &&
  4825. ((psDeviceParameters_->ucStatusByte2 & psSearchDeviceItem->sDeviceSearchMask.ucStatusByte2) == (psSearchDeviceItem->sDeviceParameters.ucStatusByte2 & psSearchDeviceItem->sDeviceSearchMask.ucStatusByte2))
  4826. )
  4827. return TRUE;
  4828. usDeviceIndex++;
  4829. }
  4830. return FALSE;
  4831. }
  4832. ///////////////////////////////////////////////////////////////////////
  4833. void ANTFSHostChannel::AddResponse(ANTFS_HOST_RESPONSE eResponse_)
  4834. {
  4835. DSIThread_MutexLock(&stMutexResponseQueue);
  4836. clResponseQueue.AddResponse(eResponse_);
  4837. DSIThread_CondSignal(&stCondWaitForResponse);
  4838. DSIThread_MutexUnlock(&stMutexResponseQueue);
  4839. }
  4840. ///////////////////////////////////////////////////////////////////////
  4841. //Returns a response if there is one ready, otherwise waits the specified time for one to occur
  4842. ANTFS_HOST_RESPONSE ANTFSHostChannel::WaitForResponse(ULONG ulMilliseconds_)
  4843. {
  4844. ANTFS_HOST_RESPONSE stResponse = ANTFS_HOST_RESPONSE_NONE;
  4845. if (bKillThread == TRUE)
  4846. return ANTFS_HOST_RESPONSE_NONE;
  4847. //Wait for response
  4848. DSIThread_MutexLock(&stMutexResponseQueue);
  4849. if(clResponseQueue.isEmpty())
  4850. {
  4851. UCHAR ucResult = DSIThread_CondTimedWait(&stCondWaitForResponse, &stMutexResponseQueue, ulMilliseconds_);
  4852. switch(ucResult)
  4853. {
  4854. case DSI_THREAD_ENONE:
  4855. stResponse = clResponseQueue.GetResponse();
  4856. break;
  4857. case DSI_THREAD_ETIMEDOUT:
  4858. stResponse = ANTFS_HOST_RESPONSE_NONE;
  4859. break;
  4860. case DSI_THREAD_EOTHER:
  4861. #if defined(DEBUG_FILE)
  4862. DSIDebug::ThreadWrite("ANTFSHostChannel::WaitForResponse(): CondTimedWait() Failed!");
  4863. #endif
  4864. stResponse = ANTFS_HOST_RESPONSE_NONE;
  4865. break;
  4866. default:
  4867. #if defined(DEBUG_FILE)
  4868. DSIDebug::ThreadWrite("ANTFSHostChannel::WaitForResponse(): Error Unknown...");
  4869. #endif
  4870. stResponse = ANTFS_HOST_RESPONSE_NONE;
  4871. break;
  4872. }
  4873. }
  4874. else
  4875. {
  4876. stResponse = clResponseQueue.GetResponse();
  4877. }
  4878. DSIThread_MutexUnlock(&stMutexResponseQueue);
  4879. return stResponse;
  4880. }