首页 openwrt ubus简介

openwrt ubus简介

举报
开通vip

openwrt ubus简介UbusBriefTheubusisdesignedforprovidingcommunicationbetweenvariousdaemonsandapplications.ThearchitectureasbelowObjectsandObjectpathsTheObjectpathsarebindingscannameobjectinstances,andallowapplicationstorefertothem.InOpenWRT,theobjectpathisnamespacelikenetwork.i...

openwrt ubus简介
UbusBriefTheubusisdesignedforprovidingcommunicationbetweenvariousdaemonsandapplications.ThearchitectureasbelowObjectsandObjectpathsTheObjectpathsarebindingscannameobjectinstances,andallowapplicationstorefertothem.InOpenWRT,theobjectpathisnamespacelikenetwork.interface.lanMethodsandNotificationsMethodsareoperationsthatcanbeinvokedonanobject,withoptionalinputparametersandoutput.Notificationsarebroadcastsfromtheobjecttoanyinterestedobserversoftheobject.ThenotificationsmaycontainadatapayloadCallingamethodAmethodcallinubusconsistsoftwomessages;AcallmessagesfromprocessAtoprocessBandthereplymessagesfromprocessBtoprocessA.Thesendmessageandreplymessagesarebothroutedthroughtheubusdaemon.Thecallmessagecontainsthemethodarguments.Thereplymessagesmaybeerrormessages,ormaycontainmethodreturneddata.CallProcess1.Thecallmethodmessagescontainstheubusconnectioncontext,thedestinationobjectid,themethodname,themethodarguments.2.Themethodcallmessageissendtotheubusdaemon3.Theubusdaemonlookupthedestinationobjectid,ifaprocessownstheobjectinstance,thenthedaemonwillforwardthemethodcalltothefindprocess.Otherwisetheubusdaemoncreatesanerrormessagesandsendstheerrormessagebacktothemessagecallasreply.4.Thereceivingprocesswillparsetheubusobjectmessages,andfindthecallmethodandargumentsbelongtothemethod.Thenmatchtheobjectmethodsinobjectinstance,iffindmatchedmethod,willinvokethemethodandthensendthereplymessages.5.Ubusdaemonreceivethereplymessageandforwardthereplymessagetotheprocessthatmadethemethodcall.6.ThereplymessagesistransferredasubusblobmessagesstructurewhichisTLV(Type-Length-Value)basedbinarymessagestype.7.Theprocessreceivedthereplymessageshouldparsethemessageandformattohuman-nicemessagetypeasJSONorXML.NotifyNotificationsAnotificationinubusconsistsofasinglemessages,sendbyoneprocesstoanynumberofotherprocesses,whichmeansthenotificationisaunidirectionalbroadcast,noneedexpectedreplymessage.Thenotificationsenderdonotknowthenotificationsrecipients,itjustsendthenotificationontobusTheinterestrecipientsshouldsubscribethesenderobjectwiththebusdaemon.NotificationProcess1. Addnotificationobjectontoubusdaemon2. Thenotificationmessagecontainsubusconnectioncontext,thenotificationsenderobjectID,thenotificationtypeandoptionalargumentswiththetype.3. Anyprocessontheubuscansubscribethenotificationobject.Thebusmayhasalistofsubscribers,whichwillmatchtheobserverswhendaemonhandlethenotificationmessage.4. Theubusdaemoncheckthenotificationanddetermineswhichprocessesareinterestedinit.Thensendthenotificationtoalloftheinterestedprocesses.5. Eachsubscriberprocessreceivingthenotificationdecideswhattodowiththenotificationmessage.Blob_bufstructureonubusBlob_attrBlob_msgBlob_bufHowtouseubusServerMainprocessM1.DefineaobjectwithsomeabstractmethodsM2.Connecttheserverprocesstoubusdaemonandgetaubus_context,thecontextwillcontainedtheconnectedfd,registeredfdcallbackandanAVLtreetomanageallobjectsinformationwiththisconnectionM3.Usingulooputilitiestoaddtheubus_context,whichistoregistertheconnectedfdintoepollsetM4.AddthedefinedobjectintoubusdM5.ForeverlooptoepollthefdsetWhattodoinmethodhandlerH1.Parsetheblob_attrmsgintoablob_attrtable,whichcaneasyusingbyindexthetablebymsgIDH2.Getthemethodargumentsaccordingtomsgid,thehandlermaybecallmethodinanotherobjectsorinvokeashellscripttodosomeservice,etcH3.Preparetheresponsemsgintoblob_buffandsendtheresponsetoubusdaemon,whichwillforwardtheresponsetorequestclientifnotspecify“no_reply”or”deferred”flagH4.Ifspecify“deferred”flaginreqcontextinthemethodhandler,whichmeanstheserverprocesswillnotexpecttheresponseinthisrequesthandlerandjustcompletethisrequest.#include<libubox/blobmsg_json.h>#include"libubus.h"staticstructubus_context*ctx;staticinttest_hello(structubus_context*ctx,structubus_object*obj, structubus_request_data*req,constchar*method, structblob_attr*msg){structhello_request*hreq;structblob_attr*tb[__HELLO_MAX];constchar*format="%sreceivedamessage:%s";constchar*msgstr="(unknown)"; //H1.Parsetheblob_attrmsg(blob_data(msg))intoablob_attr//table(tb),whichcaneasilyusebymsgIDtoindexthetableblobmsg_parse(hello_policy,ARRAY_SIZE(hello_policy),tb,blob_data(msg),blob_len(msg));//H2.GetmethodargumentsbymsgID if(tb[HELLO_MSG]) msgstr=blobmsg_data(tb[HELLO_MSG]);hreq=calloc(1,sizeof(*hreq)+strlen(format)+strlen(obj->name)+strlen(msgstr)+1);sprintf(hreq->data,format,obj->name,msgstr);//H4.Deferthereplyfortherequest//Thereplywillbemakingintimercallbackubus_defer_request(ctx,req,&hreq->req);hreq->timeout.cb=test_hello_reply;uloop_timeout_set(&hreq->timeout,1000);return0;}//Definehellomethodwithtest_hellohandle//hellopolicytellubusdtheobjectmethodparameterstypestaticconststructubus_methodtest_methods[]={ UBUS_METHOD("hello",test_hello,hello_policy),};//M1.Definetest_objectstaticstructubus_objecttest_object={.name="test",.type=&test_object_type,.methods=test_methods,.n_methods=ARRAY_SIZE(test_methods),};staticvoidserver_main(void){intret;//M4.Addthedefinedobjectintoubusdret=ubus_add_object(ctx,&test_object);if(ret)fprintf(stderr,"Failedtoaddobject:%s\n",ubus_strerror(ret)); //M5.Foreverlooptoepollthefdsetandhandletheavailablefduloop_run();}intmain(intargc,char**argv){constchar*ubus_socket=NULL;intch;uloop_init();signal(SIGPIPE,SIG_IGN);//M2.Connecttoubusd,willgettheubus_contextctx=ubus_connect(ubus_socket);if(!ctx){fprintf(stderr,"Failedtoconnecttoubus\n"); return-1;}//M3.Addtheubusconnectionintoepollsetubus_add_uloop(ctx);server_main();ubus_free(ctx);uloop_done();return0;}ClientMainProcessM1.Connecttheclientprocesstoubusdaemon,willgettheubuscontext,thecontextwillcontainedtheconnectedfd,registeredfdcallbackandanAVLtreetomanageallobjectsinformationwiththisconnectionM2.Usingulooputilitiestoaddtheubus_context,whichistoregistertheconnectedfdintoepollsetM3.LookupthetargetobjectidbytheobjectpathinubuscontextM4.Arrangetheubuscallmethodandmethodargumentsintoblob_buff.M5.InvokeubushighlevelAPItoinvokeamethodonaspecificobject,andwaitforthereply./*invokeamethodonaspecificobject*/intubus_invoke(structubus_context*ctx,uint32_tobj,constchar*method,structblob_attr*msg,ubus_data_handler_tcb,void*priv,inttimeout);Specifyacallbacktohandletheresponseblob_msgtohuman-nicemessageformatlikeJSONorXMLOrM4.Forsomecase,wemaynotneedtowaitfortheresponse,shouldcallasynchronousversioninvoke/*asynchronousversionofubus_invoke()*/intubus_invoke_async(structubus_context*ctx,uint32_tobj,constchar*method,structblob_attr*msg,structubus_request*req);staticintubus_cli_call(structubus_context*ctx,intargc,char**argv){ uint32_tid; intret; if(argc<2||argc>3) return-2;//M4.Arrangetheubuscallmethodandmethodargumentsintoblob_buffblob_buf_init(&b,0); if(argc==3&&!blobmsg_add_json_from_string(&b,argv[2])){ if(!simple_output) fprintf(stderr,"Failedtoparsemessagedata\n"); return-1; }//M3.Lookupthetargetobjectidbytheobjectpath ret=ubus_lookup_id(ctx,argv[0],&id); if(ret) returnret; //M5.Invokethemethodandwaitforthereply//receive_call_result_datacallbackwillconvertblob_attrdatatoJSONformat returnubus_invoke(ctx,id,argv[1],b.head,receive_call_result_data,NULL,timeout*1000);}intmain(intargc,char**argv){ constchar*ubus_socket=NULL; intch; while((ch=getopt(argc,argv,"cs:"))!=-1){ switch(ch){ case's': ubus_socket=optarg; break; default: break; } } argc-=optind; argv+=optind; uloop_init();//M1.Connecttoubusdaemonandgettheconnectedubuscontext ctx=ubus_connect(ubus_socket); if(!ctx){ fprintf(stderr,"Failedtoconnecttoubus\n"); return-1; }//M2.Addtheconnectedfdintoepollfdset ubus_add_uloop(ctx); //callspecificubusmethodubus_cli_call(ctx,argc,argv); //Whenrequestdone,justfreetheresource,andreturn ubus_free(ctx); uloop_done(); return0;}HowtousenotificationSubscriberS1.Connecttheprocesstoubusdaemon,willgettheubuscontext,thecontextwillcontainedtheconnectedfd,registeredfdcallbackandanAVLtreetomanageallobjectsinformationwiththisconnectionS2.Usingulooputilitiestoaddtheubus_context,whichistoregistertheconnectedfdintoepollsetS3.Defineasubscriberobject,whichcontainaubusobjectandacallbacktohandlereceivedsubscribenotificationS4.AddubusobjectontoubusdaemonS5.SpecifycallbackhandlertohandlenotificationS6.Subscribeinterestedobject(notifyobject)staticstructubus_subscribertest_event;staticvoidsubscriber_main(void){intret;uint32_tid;//S4.Addsubscriberobjectontobus ret=ubus_register_subscriber(ctx,&test_event); if(ret) fprintf(stderr,"Failedtoaddwatchhandler:%s\n",ubus_strerror(ret));//S5.Specifycallbackhandlertohandlenotificationtest_event.remove_cb=test_handle_remove;test_event.cb=test_notify;//Lookupthenotifyobjectret=ubus_lookup_id(ctx,"network.interface",&id);//S6.Subscribeinterestedobject ret=ubus_subscribe(ctx,&test_event,id);uloop_run();}intmain(intargc,char**argv){constchar*ubus_socket=NULL;intch;while((ch=getopt(argc,argv,"cs:"))!=-1){switch(ch){ case's': ubus_socket=optarg; break; default: break; }}argc-=optind;argv+=optind;uloop_init();signal(SIGPIPE,SIG_IGN);//S1.Connecttheprocesstoubusdaemonctx=ubus_connect(ubus_socket);if(!ctx){ fprintf(stderr,"Failedtoconnecttoubus\n"); return-1;}//S2.Addconnectedfdintoepollfdset.ubus_add_uloop(ctx);//Subscribermainprocesssubscriber_main();ubus_free(ctx);uloop_done();return0;}NotificationSenderN1.Connecttheprocesstoubusdaemon,willgettheubuscontext,thecontextwillcontainedtheconnectedfd,registeredfdcallbackandanAVLtreetomanageallobjectsinformationwiththisconnectionN2.Usingulooputilitiestoaddtheubus_context,whichistoregistertheconnectedfdintoepollsetN3.DefineanotifyobjectN4.AddnotifyobjectontobusN5.PreparenotifytypeandargumentswhenactuallyaneventhappensN6.Broadcasttheeventnotificationtobus//N3.Defineanotifyobjectstaticstructubus_objecttest_object;staticvoidevent_broadcast(char*event){//prepareeventargumentifnecessary//N6.Broadcasttheeventnotificationtobusubus_notify(ctx,&test_object,event,NULL,-1);}intmain(intargc,char**argv){constchar*ubus_socket=NULL;intch;while((ch=getopt(argc,argv,"cs:"))!=-1){ switch(ch){ case's': ubus_socket=optarg; break; default: break; }}argc-=optind;argv+=optind;uloop_init();//N1.Connecttheprocesstoubusdaemonctx=ubus_connect(ubus_socket);if(!ctx){ fprintf(stderr,"Failedtoconnecttoubus\n"); return-1;}//N2.Addconnectedfdintoepollfdsetubus_add_uloop(ctx);//N4.Addnotifyobjectontobusubus_add_object(ctx,&test_object);//N5.Preparenotifytypeandargumentswhenactuallyaneventhappens ……event_broadcast(event);ubus_free(ctx);uloop_done();return0;}Theexamplecodecanrefertoubus\examples\
本文档为【openwrt ubus简介】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
个人认证用户
飞哥
暂无简介~
格式:doc
大小:144KB
软件:Word
页数:0
分类:企业经营
上传时间:2018-05-11
浏览量:13