antfs_host_channel.cpp 215 KB

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