TinyFrame开源项目

我要开发同款
匿名用户2021年11月10日
26阅读
开发技术C/C++
所属分类其他开源、嵌入式操作系统
授权协议MIT License

作品详情

TinyFrame

TinyFrameisasimplelibraryforbuildingandparsingdataframestobesentoveraserialinterface(e.g.UART,telnet,socket).Thecodeiswrittentobuildwith--std=gnu99andmostlycompatiblewith--std=gnu89.

Thelibraryprovidesahighlevelinterfaceforpassingmessagesbetweenthetwopeers.Multi-messagesessions,responselisteners,checksums,timeoutsareallhandledbythelibrary.

TinyFrameissuitableforawiderangeofapplications,includinginter-microcontrollercommunication,asaprotocolforFTDI-basedPCapplicationsorformessagingthroughUDPpackets.

Thelibraryletsyouregisterlisteners(callbackfunctions)towaitfor(1)anyframe,(2)aparticularframeType,or(3)aspecificmessageID.Thishigh-levelAPIisgeneralenoughtoimplementmostcommunicationpatterns.

TinyFrameisre-entrantandsupportscreatingmultipleinstanceswiththelimitationthattheirstructure(fieldsizesandchecksumtype)isthesame.Thereisasupportforaddingmulti-threadedaccesstoasharedinstanceusingamutex.

TinyFramealsocomeswith(optional)helperfunctionsforbuildingandparsingmessagepayloads,thoseareprovidedintheutils/folder.

Ports

TinyFramehasbeenportedtomutiplelanguages:

ThereferenceCimplementationisinthisrepoPythonport-MightyPork/PonyFrameRustport-cpsdqs/tinyframe-rsJavaScriptport-cpsdqs/tinyframe-js

Pleasenotemostoftheportsareexperimentalandmayexhibitvariousbugsormissingfeatures.Testersarewelcome:)

Functionaloverview

ThebasicfunctionalityofTinyFrameisexplainedhere.Forparticlars,suchastheAPIfunctions,it'srecommendedtoreadthedoccommentsintheheaderfile.

Structureofaframe

Eachframeconsistsofaheaderandapayload.Bothpartscanbeprotectedbyachecksum,ensuringaframewithamalformedheader(e.g.withacorruptedlengthfield)oracorruptedpayloadisrejected.

TheframeheadercontainsaframeIDandamessagetype.FrameIDisincrementedwitheachnewmessage.ThehighestbitoftheIDfieldisfixedto1and0forthetwopeers,avoidingaconflict.

FrameIDcanbere-usedinaresponsetotiethetwomessagestogether.Valuesofthetypefieldareuserdefined.

Allfieldsintheframehaveaconfigurablesize.Bychangingafieldintheconfigfile,suchasTF_LEN_BYTES(1,2or4),thelibraryseamlesslyswitchesbetweenuint8_t,uint16_tanduint32_tforallfunctionsworkingwiththefield.

,-----+-----+-----+------+------------+----+-------------,|SOF|ID|LEN|TYPE|HEAD_CKSUM|DATA|DATA_CKSUM||0-1|1-4|1-4|1-4|0-4|...|0-4|<-size(bytes)'-----+-----+-----+------+------------+----+-------------'SOF.........startofframe,usually0x01(optional,configurable)ID.........theframeID(MSbisthepeerbit)LEN.........numberofdatabytesintheframeTYPE........messagetype(usedtorunTypeListeners,pickanyvaluesyoulike)HEAD_CKSUM..headerchecksumDATA........LENbytesofdataDATA_CKSUM..datachecksum(leftoutifLENis0)Messagelisteners

TinyFrameisbasedontheconceptofmessagelisteners.AlistenerisacallbackfunctionwaitingforaparticularmessageTypeorIDtobereceived.

Thereare3listenertypes,intheorderofprecedence:

IDlisteners-waitingforaresponseTypelisteners-waitingforamessageofthegivenTypefieldGenericlisteners-fallback

IDlistenerscanberegisteredautomaticallywhensendingamessage.Alllistenerscanalsoberegisteredandremovedmanually.

IDlistenersareusedtoreceivetheresponsetoarequest.WhenregisterignanIDlistener,it'spossibletoattachcustomuserdatatoitthatwillbemadeavailabletothelistenercallback.Thisdata(void*)canbeanykindofapplicationcontextvariable.

IDlistenerscanbeassignedatimeout.Whenalistenerexpires,beforeit'sremoved,thecallbackisfiredwithNULLpayloaddatainordertolettheuserfree()anyattacheduserdata.ThishappensonlyiftheuserdataisnotNULL.

ListenercallbacksreturnvaluesoftheTF_Resultenum:

TF_CLOSE-messageaccepted,removethelistenerTF_STAY-messageaccepted,stayregisteredTF_RENEW-sameasTF_STAY,buttheIDlistener'stimeoutisrenewedTF_NEXT-messageNOTaccepted,keepthelistenerandpassthemessagetothenextlistenercapableofhandlingit.Databuffers,multi-partframes

TinyFrameusestwodatabuffers:asmalltransmitbufferandalargerreceivebuffer.Thetransmitbufferisusedtopreparebytestosend,eitherallatonce,orinacircularfashionifthebufferisnotlargeenough.Thebuffermustonlycontaintheentireframeheader,soe.g.32bytesshouldbesufficientforshortmessages.

Usingthe*_Multipart()sendingfunctions,it'sfurtherpossibletosplittheframeheaderandpayloadtomultiplefunctioncalls,allowingtheapplciationtoe.g.generatethepayloadon-the-fly.

Incontrasttothetransmitbuffer,thereceivebuffermustbelargeenoughtocontainanentireframe.Thisisbecausethefinalchecksummustbeverifiedbeforetheframeishandled.

Ifframeslargerthanthepossiblereceivebuffersizearerequired(e.g.inembeddedsystemswithsmallRAM),it'srecommendedtoimplementamulti-messagetransportmechanismatahigherlevelandsendthedatainchunks.

UsageHintsAllTinyFramefunctions,typedefsandmacrosstartwiththeTF_prefix.BothpeersmustincludethelibrarywiththesameconfigparametersSeeTF_Integration.example.candTF_Config.example.cforreferencehowtoconfigureandintegratethelibrary.DONOTmodifythelibraryfiles,ifpossible.Thismakesiteasytoupgrade.StartbycallingTF_Init()withTF_MASTERorTF_SLAVEastheargument.Thiscreatesahandle.UseTF_InitStatic()toavoidtheuseofmalloc().Ifmultipleinstancesareused,youcantagthemusingthetf.userdata/tf.usertagfield.ImplementTF_WriteImpl()-declaredatthebottomoftheheaderfileasextern.ThisfunctionisusedbyTF_Send()andotherstowritebytestoyourUART(orotherphysicallayer).Aframecanbesentinit'sentirety,orinmultipleparts,dependingonitssize.UseTF_AcceptChar(tf,byte)togivereaddatatoTF.TF_Accept(tf,bytes,count)willacceptmulitplebytes.Ifyouwishtousetimeouts,periodicallycallTF_Tick().Thecallingperioddeterminesthelengthof1tick.Thisisusedtotime-outtheparserincaseitgetsstuckinabadstate(suchasreceivingapartialframe)andcanalsotime-outIDlisteners.BindTypeorGenericlistenersusingTF_AddTypeListener()orTF_AddGenericListener().SendamessageusingTF_Send(),TF_Query(),TF_SendSimple(),TF_QuerySimple().Queryfunctionstakealistenercallback(functionpointer)thatwillbeaddedasanIDlistenerandwaitforaresponse.Usethe*_Multipart()variantoftheabovesendingfunctionsforpayloadsgeneratedinmultiplefunctioncalls.ThepayloadissentafterwardsbycallingTF_Multipart_Payload()andtheframeisclosedbyTF_Multipart_Close().Ifcustomchecksumimplementationisneeded,selectTF_CKSUM_CUSTOM8,16or32andimplementthethreechecksumfunctions.Toreplytoamessage(whenyourlistenergetscalled),useTF_Respond()withthemsgobjectyoureceived,replacingthedatapointer(andlen)witharesponse.AtanytimeyoucanmanuallyresetthemessageparserusingTF_ResetParser().Itcanalsoberesetautomaticallyafteratimeoutconfiguredintheconfigfile.GotchastolookoutforIfanyuserdataisattachedtoanIDlistenerwithatimeout,whenthelistenertimesout,itwillbecalledwithNULLmsg->datatolettheuserfreetheuserdata.Thereforeit'sneededtocheckmsg->databeforeproceedingtohandlethemessage.Ifamulti-partframeisbeingsent,theTxpartofthelibraryislockedtopreventconcurrentaccess.Theframemustbefullysentandclosedbeforeattemptingtosendanythingelse.Ifmultiplethreadsareused,don'tforgettoimplementthemutexcallbackstoavoidconcurrentaccesstotheTxfunctions.Thedefaultimplementationisnotentirelythreadsafe,asitcan'trelyonplatform-specificresourceslikemutexesoratomicaccess.SetTF_USE_MUTEXto1intheconfigfile.Examples

You'llfindvariousexamplesinthedemo/folder.Eachexamplehasit'sownMakefile,readittoseewhatoptionsareavailable.

ThedemosarewrittenforLinux,someusingsocketsandclone()forbackgroundprocessing.TheytrytosimulaterealTinyFramebehaviorinanembeddedsystemwithasynchronousRxandTx.Ifyoucan'trunthedemos,thesourcefilesarestillgoodasexamples.

查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论