Porovnávané verzie

Kľúč

  • Tento riadok sa pridal
  • Riadok je odstránený.
  • Formátovanie sa zmenilo.

The D2Api interface represents a basic communication channel with the D2000 system for web applications. This communication interface is implemented on the client's side in JavaScript and is built on the CometD library. 

Establishing and Disconnecting Connection with D2000

Establishing a connection with D2000 is realized by creating an instance of the D2Api class to which the CometD configuration will be submitted and by the following calling the connect method. Parameters of the configuration object for CometD are described in the documentation of the CometD configuration.

The only mandatory attribute is the url attribute that defines a path to the CometD servlet on the server - it may be entered as an absolute path

D2Api rozhranie predstavuje základný komunikačný kanál so systémom D2000 pre webové aplikácie. Toto komunikačné rozhranie je na strane klienta implementované v JavaScript-e a je postavené na knižnici CometD.

Nadviazanie a rozpojenie spojenia s D2000

Nadviazanie spojenia s D2000 sa realizuje vytvorením inštancie triedy D2Api, ktorej sa odovzdá konfigurácia pre CometD a následným zavolaním metódy connect. Parametre konfiguračného objektu pre CometD sú popísané v dokumentácii konfigurácie CometD.

Jediný povinný atribút je atribút url, ktorý určuje cestu ku CometD servletu na serveri - môže byť zadaný ako absolútna cesta ("http://server:port/aplikacia/api/cometd") alebo ako relatívna cesta v rámci webového servera  or as a relative path within the web server ("/aplikaciaapplication/api/cometd").

Medzi ďalšie užitočné atribúty patrí najmä atribút maxNetworkDelay, ktorý určuje dobu v milisekundách, po uplynutí ktorej je požiadavka na server považovaná za zlyhanú. Tento parameter je vhodné zvýšiť z predvolených 10 sekúnd na vyššie číslo, ak bežné, synchrónne volané RPC procedúry majú dobu spracovávania dlhšiu.

To other useful attributes, there belongs especially the maxNetworkDelay attribute which defines the period in milliseconds and after the period is up, the request on the server is considered failed. It is good to increase this parameter from the default 10 seconds to a higher number if common synchronously calling RPC procedures have the processing period longer.

Optionally, it is possible to define the operation of error states by the registerErrorHandler method - within the SmartWeb Framework, the reportError function serves for this purpose and it displays located dialogue in a case of an error.  Voliteľne je možné definovať obsluhu chybových stavov metódou registerErrorHandler - v rámci SmartWeb Frameworku je pre tento účel dodávaná funkcia reportError, ktorá v prípade chyby zobrazuje lokalizovaný dialóg.

Blok kódu
languagejs
import D2Api from "framework\d2\d2Api"
import reportError from "framework\basic\reportError"


let cometdConfiguration = {
    url: "/smartWeb/api/cometd",
    maxNetworkDelay: 60000
}
let d2Api = new D2Api(cometdConfiguration);
d2Api.registerErrorHandler(reportError);
d2Api.connect();

Na rozpojenie spojenia s D2000 slúži metóda disconnect.For disconnecting a connection with D2000 serves the disconnect method. 

Blok kódu
languagejs
d2Api.disconnect();

Počúvanie na zmeny hodnôt objektov D2000

Listening for Value Changes of D2000 Objects

Registering for the subscription of values of D2000 objects is possible using the subscribeObject method. The name of the D2000 object, changes of which will be monitored and the service function, which will be called when the value of the object is changed, will be passed through parameters to the method. Optionally, as the third parameter, an object with attributes returnFields or returnTransformation - that will define which attributes of value should be returned or else the transformation that should be done on values - can be passed. Possible values of returnFields and returnTransformation attributes are described in the section Serialization of Data between Client and API InterfacePrihlásiť sa na odoberanie hodnôt objektov D2000 je možné metódou subscribeObject. Tejto metóde sa cez perametre odovzdá meno D2000 objektu, ktorého zmeny sa budú sledovať, obslužná funkcia, ktorá sa pri zmene hodnoty objektu zavolá, alebo komponent SmartWeb Frameworku, ktorý bude na novú hodnotu reagovať a voliteľne objekt s atribútmi returnFields, prípadne returnTransformation, ktoré určia, ktoré atribúty hodnoty majú byť vrátené a prípadne transformáciu, ktorá sa má nad hodnotami vykonať. Možné hodnoty atribútov returnFields a returnTransformation sú popísané v sekcii Serializácia dát medzi klientom a API rozhraniami.

Blok kódu
languagejs
// Obslužná funkcia zmeny hodnoty objektuService function of change of object value
function onSecChange(subscription) {
    // objektobject subscription.uniVal budewill contain obsahovaťvalue hodnotuand aattributes atribútyof D2000 objektuobject
}
...
// Registration of Registráciavalue odberusubscription hodnôt
d2Api.subscribeObject("Sec", onSecChange, {returnFields: ["FormattedValue"]});

Odber hodnôt objektu je možné zrušiť volaním metódy unSubscribeObject, kde sa ako parameter odovzdá zaregistrovaná obslužná procedúra alebo komponent SmartWeb Frameworku.Subscription of object values can be ended by calling the unSubscribeObject method where there will be a registered service procedure or a component of the SmartWeb Framework passed as a parameter. 

Blok kódu
languagejs
d2Api.unSubscribeObject(onSecChange);

Načítanie hodnôt archívnych objektov D2000

Reading Values of D2000 Archive Objects

Reading values of D2000 archive objects is possible by the loadArchive and loadArchives method that read values of one or more archive objects in the given interval. Functions return the Promise object which, in the case of success, will contain completely read data. For calling these functions, it is possible to use also the Načítanie hodnôt archívnych objektov D2000 je možné pomocou metód loadArchive a loadArchives, ktoré načítajú hodnoty jedného, resp. viacerých archívnych objektov v danom intervale. Funkcie vracajú Promise objekt, ktorý v prípade úspechu bude obsahovať kompletné načítané dáta. Na volanie týchto funkcií je možné použiť aj async/await syntax.

Blok kódu
languagejs
var extParameters = {};
var receiveDataStreamHandler = null;


// NačítaReads hodnotyvalues objektuof H.ArchivedValue vobject in intervaleinterval <startDate, endDate>
var arcData = await d2Api.loadArchive("H.ArchivedValue", startDate, endDate, extParameters, receiveDataStreamHandler).call();

// Načítareads hodnotyvalues objektovof H.ArchivedValue1, and H.ArchivedValue2 vobjects in intervaleinterval <startDate, endDate>
var arcDataMulti = await d2Api.loadArchives(["H.ArchivedValue1", "H.ArchivedValue2"], startDate, endDate, extParameters).call();

Voliteľný parameter extParameters slúži na definovanie atribútov hodnôt, ktoré majú byť vrátené - zoznam sa definuje v atribúte returnFields - popísaný v sekcii Serializácia dát medzi klientom a API rozhraniami. Okrem toho môže byť parametrom extParameters zadefinované prevzorkovanie hodnôt pomocou atribútu oversampleSeconds (krok prevzorkovania je v sekundách) a taktiež je možné obmedziť počet vrátených hodnôt z archívu nastavením atribútu limitDataLength. V prípade vynechania parametra extParameters budú vrátené len hodnoty bez ďalších atribútov a neprebehne žiadne prevzorkovanie ani orezanie dát.The optional parameter extParameters serves for defining attributes of values which should be returned - the list is defined in the returnFields attribute - described in the section Serialization of Data between Client and API Interface. In addition to that, oversampling of values using the oversampleSeconds parameter (the step of oversampling is in seconds) can be defined by the extParameters parameter and also it is possible to restrict the number of returning values from an archive by setting the limitDataLength attribute. In a case of omitting the extParameters parameter, only values with no other attributes will be returned and no data oversampling nor data trimming will occur. 

Blok kódu
languagejs
var extParameters = {
    returnFields: ["ValueTime"], // okrembesides hodnôtvalues, time požadovanéstamps ajof časovévalues značkyare hodnôtrequired
    oversampleSeconds: 3600,     // hodnotyvalues budúwere prevzorkovanéoversampled swith hodinovýmhour krokomstep
    limitDataLength: 1000        // maximally, maximálnethere budewill vrátenýchbe 1000 values hodnôtreturned
}

Pri načítaní väčšieho množstva dát z archívu, sú tieto dáta zo systému D2000 priebežne streamované po dávkach. Ak je žiadané zachytávať a spracovávať tieto čiastkové údaje, tak je to možné pomocou voliteľného parametra receiveDataStreamHandler, ktorý definuje funkciu s dvoma parametrami - v prvom budú odovzdané hodnoty dávky a v druhom je príznak či ide o poslednú dávkuWhen reading more data from an archive, the data from the D2000 system are continuously streamed in batches. If it is desired to collect and process those partial data, it will be possible using optional parameter receiveDataStreamHandler which defines a function with two parameters -  function with two parameters - in the first one, there will be values of a batch submitted and in the second one, there will be an indication whether it is the last batch.

Blok kódu
languagejs
titlereceiveDataStreamHandler
function receiveDataStreamHandler(data, noModeData) {
    // spracovaniedata dátprocessing
}

...

Calling D2000 RPC

Rovnako ako Same as the REST API aj D2Api umožňuje volanie D2000 RPC procedúr napísaných v ESL alebo v Jave. Slúžia na to metódy rpc - volanie , D2Api also enables calling D2000 RPC procedures written in ESL or in Java. The following methods serve for it: rpc - calling ESL RPC, rpcJava - volanie calling Java RPC a and rpcSBA - volanie calling Java RPC na prenos binárnych dát. Prvé dva parametre týchto metód určujú meno event objektu (skriptu) a názov RPC procedúry. Všetky ďalšie parametre sú odovzdané ako parametre do volanej RPC procedúry. Štruktúra parametrov pre volania RPC je popísaná v časti Serializácia dát medzi klientom a API rozhraniami. Metódy vracajú objekt s metódou call, ktorá vykoná volanie RPC. Návratová hodnota volania RPC je Promise objekt, ktorý v prípade úspešného volania obsahuje požadované výstupné parametre RPC procedúry ako svoje atribúty vo forme Unival hodnôt.for transmission of binary data. The first two parameters of these methods define the name of the object event (script) and the name of the RPC procedure. All other parameters are submitted as parameters into the calling RPC procedure. Structure of parameters for calling RPC is described in the section Serialization of Data between Client and API Interface. Methods return an object with the call method which does the RPC calling. Returning value of RPC calling is the Promise object which, in the case of a successful calling, contains required output parameters of the RPC procedure as its attributes in the form of the Unival value.  

Blok kódu
languagejs
// ZavoláCalls RPC procedúruprocedure Sum naon Event skriptescript E.SmartWebTutorial
const rpcResponse = await d2Api.rpc(
    "E.SmartWebTutorial",
    "Sum",
    1, // prvýfirst parameter - vstupnýinput
    2, // druhýsecond parameter - vstupnýinput
    {type: "real", returnAs: "sum"} // tretíthird parameter - výstupnýoutput
).call();
// rpcResponse.sum obsahujecontains výstupnýoutput parameter RPC akoas UniVal hodnotuvalue

Volaná Called RPC procedúra v ESL má nasledovný predpis:procedure in ESL has the following prescript: 

Blok kódu
languageesl
RPC PROCEDURE Sum (IN REAL _a, IN REAL _b, REAL _c) 
  _c := _a + _b
END Sum

...

Calling JavaScript

...

Functions from D2000

D2Api umožňuje aj spätné volania z D2000 na webový prehliadač a to vo forme registrovaných JavaScript funkcií. Takéto volania sú užitočné najmä pre notifikácie rôznych udalostí, ktoré v systéme D2000 vznikajú asynchrónne. Na registráciu JavaScript funkcie, ktorú je možné volať z D2000 slúži metóda subscribeRpc. Jej parametrami sú názov RPC procedúry, pod ktorým bude funkcia dostupná v rámci systému D2000 a samotná JavaScript funkcia, ktorá bude pri spätnom volaní zavolaná. Všetky parametre funkcie sú objekty typu Unival. Na odregistrovanie funkcie spätného volania slúži metóda unSubscribeRpc s jediným parametrom, a to danou JavaScript funkciou.enables also reverse calling from D2000 to a web browser in a form of registered JavaScript functions. Such callings are useful mainly for notifications of various events which emerge asynchronously in the D2000 system. For registering the JavaScript function which can be called from D2000 serves the subscribeRpc method. Its parameters are the name of the RPC procedure, under which the function will be available within the D2000 system, and the JavaScript function itself which will be called in return calling. All parameters of the function are objects of the Unival type. For deregistering of the function of return calling serves the unSubscribeRpc method with one parameter - the given JavaScript function. 

Blok kódu
languagejs
// RegistrovateľnáRegistered Javascript funkciafunction
smartWebSessionRPC(message) {
    // ...
}

// RegistráciaRegistration of funkciefunction
d2Api.subscribeRpc("SmartWebSessionRPC", smartWebSessionRPC);

// OdregistrovanieDeregistration of funkciefunction
d2Api.subscribeRpc(smartWebSessionRPC);

Aby bola funkcia volateľná zo systému D2000, musí byť známa session, na ktorej má byť zavolaná. Toto je možné zistiť volaním ľubovolnej, inicializačnej RPC procedúry, v rámci ktorej sa identifikuje proces, z ktorého bola zavolaná.So the function can be called from D2000, the session, on which it should be called, must be known. This can be found out by calling arbitrary initializing RPC procedure in which the process, from which it was called, is identified. 

Blok kódu
languageesl
INT _caller ; HOBJ SmartWeb session, ktoráwhich sirequested vyžiadalareturn spätnécallings volania

RPC PROCEDURE InitCallbacks
  _caller := %GetRPCCallerProcess()
END InitCallbacks

 Volanie registrovanej JavaScript funkcie z ESL potom vyzerá nasledovneThen, calling of registered JavaScript function from ESL looks like this:

Blok kódu
languageesl
CALL [(0)] SmartWebSessionRPC("Hello SmartWeb") ASYNC ON (_caller)

Pretože jedna SmartWeb session môže mať pod jedným názvom RPC procedúry zaregistrovaných viacero Javascript funkcií, ide tu prakticky o viacnásobné (multicast) volanie, a preto v ňom nie je možné použiť výstupné parametre. Volanie zároveň musí byť asynchrónne.

Zmena hesla prihláseného užívateľa

Because one SmartWeb session can have under one name of the RPC procedure registered more JavaScript functions, it is a multiple calling (multicast) in which output parameters cannot be used. Calling must be asynchronous at the same time. 

Password Change of Logged in User

The D2Api interface also enables to change the password of a logged in user. The changePassword method serves for that; it has two parameters - an old password, a new password and it returns the Promise objectRozhranie D2Api umožňuje taktiež zmeniť heslo prihláseného užívateľa. Slúži na to metóda changePassword, ktorá má dva parametre - staré heslo a nové heslo a vracia Promise objekt.

Blok kódu
languagejs
let oldPassword = 'secret';
let newPassword = 's3Cr3t*';
d2Api.changePassword(oldPassword, newPassword).
    .then(onFulfilled => {
        if (onFulfilled.data === 'ok') {
            // password changed
        }
    });

...