unetjs 1.1.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,21 +1,19 @@
1
- JavaScript Helper Library for UnetStack
2
- ==========================
1
+ # JavaScript Helper Library for UnetStack
3
2
 
4
3
  The JavaScript Helper Library for UnetStack is a JavaScript library that enables controlling of a UnetStack Node from JavaScript, both Browser-based (over WebSockets) and Node.JS (TCP).
5
4
 
6
5
  The library contains helper methods, commonly used [Messages](https://fjage.readthedocs.io/en/latest/messages.html) and [Services](https://fjage.readthedocs.io/en/latest/services.html) in Unet, and an implementation of the [UnetSocket API](https://unetstack.net/handbook/unet-handbook_unetsocket_api.html), which is a high-level [Socket-like](https://en.wikipedia.org/wiki/Network_socket) API for communicating over an Unet.
7
6
 
8
-
9
7
  ## Installation
10
8
 
11
9
  ```sh
12
10
  $ npm install unetjs
11
+ ...
13
12
  ```
14
13
 
15
14
  ## Documentation
16
15
 
17
- The API documentation of the latest version of unet.js is published at https://github.com/org-arl/unet-contrib/tree/master/unetsocket/js/docs
18
-
16
+ The API documentation of the latest version of unet.js is published at [https://github.com/org-arl/unet-contrib/tree/master/unetsocket/js/docs](https://github.com/org-arl/unet-contrib/tree/master/unetsocket/js/docs)
19
17
 
20
18
  ## Usage
21
19
 
@@ -57,10 +55,46 @@ rxNtf instanceof UnetMessages.DatagramReq; // returns true;
57
55
 
58
56
  ### UnetSocket
59
57
 
60
- The UnetSocket API is a high-level API exposed by UnetStack to allow users to communicate over an Unet. It is a socket-style API, which allows a user to send [Datagrams]() to specific nodes, or as a broadcast, and similarly listen to Datagrams from specific nodes, etc. A detailed explanation of UnetSocket API can be found in the [Unet Handbook](https://unetstack.net/handbook/unet-handbook_unetsocket_api.html)
58
+ The UnetSocket API is a high-level API exposed by UnetStack to allow users to communicate over an Unet. It is a socket-style API, which allows a user to send [Datagrams](https://unetstack.net/handbook/unet-handbook_datagram_service.html) to specific nodes, or as a broadcast, and similarly listen to Datagrams from specific nodes, etc. A detailed explanation of UnetSocket API can be found in the [Unet Handbook](https://unetstack.net/handbook/unet-handbook_unetsocket_api.html)
61
59
 
62
60
  The JavaScript version of the UnetSocket API allows a user to connect to a node in an Unet from a browser/Node.JS-based application and communicate with other nodes in the Unet. The Datagrams received on those nodes could be consumed by other instances of the UnetSocket, either directly on the node, or on a remote [Gateway](https://fjage.readthedocs.io/en/latest/remote.html#interacting-with-agents-using-a-gateway) connected to that node.
63
61
 
62
+ ### Caching Parameter Responses
63
+
64
+ The UnetSocket API allows a user to cache responses to parameter requests. This is useful in a scenario where the parameters aren't changing very often, and the user wants to reduce the round trip time for parameter requests.
65
+
66
+ UnetSocket API acheives this using two mechanism, firstly, it can request ALL of the parameters from an Agent instead of just one, and then cache the responses. This is called the `greedy` mode. The greedy mode is enabled by default but can be disabled by setting the `greedy` property to `false` in the `CachingAgentID` constructor.
67
+
68
+ Secondly, the UnetSocket API caches the responses to parameter requests for a limited time. If the user requests the same parameter again, the UnetSocket will return the cached response. The time to cache a response is set by the `cacheTime` property in the `CachingAgentID` constructor.
69
+
70
+ ```js
71
+ import {UnetMessages, Gateway} from 'unetjs'
72
+ let gw = new Gateway({...});
73
+ let nodeinfo = await gw.agentForService(Services.NODE_INFO); // returns a CachingAgentID by default.
74
+ let cLoc = nodeinfo.get('location'); // this will request all the Parameters from the Agent, and cache the responses.
75
+ ...
76
+ cLoc = nodeinfo.get('location', maxage=5000); // this will return the cached response if it was called within 5000ms of the original request.
77
+ ...
78
+ cLoc = nodeinfo.get('location', maxage=0); // this will force the Gateway to request the parameter again.
79
+ ```
80
+
81
+ ```js
82
+ import {UnetMessages, Gateway} from 'unetjs'
83
+ let gw = new Gateway({...});
84
+ let nodeinfo = await gw.agentForService(Services.NODE_INFO); // returns a CachingAgentID by default.
85
+ let nonCachingNodeInfo = await gw.agentForService(Services.NODE_INFO, false); // returns an AgentID without caching (original fjage.js functionality).
86
+ let cLoc = nonCachingNodeInfo.get('location'); // this will request the `location` parameter from the Agent.
87
+ ...
88
+ cLoc = nonCachingNodeInfo.get('location'); // this will request the `location` parameter from the Agent again.
89
+
90
+ let nonGreedyNodeInfo = await gw.agentForService(Services.NODE_INFO, true, false); // returns an CachingAgentID that's not greedy.
91
+ let cLoc = nonGreedyNodeInfo.get('location'); // this will request the `location` parameter from the Agent.
92
+ ...
93
+ cLoc = nonCachingNodeInfo.get('location'); // this will request the `location` parameter from the cache.
94
+ ...
95
+ let cLoc = nonGreedyNodeInfo.get('heading'); // this will request the `heading` parameter from the Agent.
96
+ ```
97
+
64
98
  ### Importing/Modules
65
99
 
66
100
  A distribution-ready bundle is available for types of module systems commonly used in the JS world. Examples of how to use it for the different module systems are available in the [examples](/examples) directory.
@@ -92,6 +126,7 @@ const gw = new Gateway({
92
126
  ```
93
127
 
94
128
  ### [UMD](dist)
129
+
95
130
  ```js
96
131
  <script src="unet.min.js"></script>
97
132
  <script>
@@ -102,4 +137,4 @@ const gw = new Gateway({
102
137
  pathname: '/ws/'
103
138
  });
104
139
  </script>
105
- ```
140
+ ```
package/dist/cjs/unet.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /* unet.js v1.1.0 2022-02-19T07:01:46.580Z */
1
+ /* unet.js v2.0.2 2022-06-10T03:18:03.319Z */
2
2
 
3
3
  'use strict';
4
4
 
@@ -1417,6 +1417,268 @@ let UnetMessages = {
1417
1417
  'SaveStateReq' : MessageClass('org.arl.unet.state.SaveStateReq')
1418
1418
  };
1419
1419
 
1420
+ /**
1421
+ * Convert coordinates from a local coordinates to GPS coordinate
1422
+ * @param {Array} origin - Local coordinate system's origin as `[latitude, longitude]`
1423
+ * @param {Number} x - X coordinate of the local coordinate to be converted
1424
+ * @param {Number} y - Y coordinate of the local coordinate to be converted
1425
+ * @returns {Array} - GPS coordinates (in decimal degrees) as `[latitude, longitude]`
1426
+ */
1427
+
1428
+ function toGps(origin, x, y) {
1429
+ let coords = [] ;
1430
+ let [xScale,yScale] = _initConv(origin[0]);
1431
+ coords[1] = x/xScale + origin[1];
1432
+ coords[0] = y/yScale + origin[0];
1433
+ return coords;
1434
+ }
1435
+
1436
+ /**
1437
+ * Convert coordinates from a GPS coordinates to local coordinate
1438
+ * @param {Array} origin - Local coordinate system's origin as `[latitude, longitude]`
1439
+ * @param {Number} lat - Latitude of the GPS coordinate to be converted
1440
+ * @param {Number} lon - Longitude of the GPS coordinate to be converted
1441
+ * @returns {Array} - GPS coordinates (in decimal degrees) as `[latitude, longitude]`
1442
+ */
1443
+ function toLocal(origin, lat, lon) {
1444
+ let pos = [];
1445
+ let [xScale,yScale] = _initConv(origin[0]);
1446
+ pos[0] = (lon-origin[1]) * xScale;
1447
+ pos[1] = (lat-origin[0]) * yScale;
1448
+ return pos;
1449
+ }
1450
+
1451
+ function _initConv(lat){
1452
+ let rlat = lat * Math.PI/180;
1453
+ let yScale = 111132.92 - 559.82*Math.cos(2*rlat) + 1.175*Math.cos(4*rlat) - 0.0023*Math.cos(6*rlat);
1454
+ let xScale = 111412.84*Math.cos(rlat) - 93.5*Math.cos(3*rlat) + 0.118*Math.cos(5*rlat);
1455
+ return [xScale, yScale];
1456
+ }
1457
+
1458
+ /**
1459
+ * A message which requests the transmission of the datagram from the Unet
1460
+ *
1461
+ * @typedef {Message} DatagramReq
1462
+ * @property {number[]} data - data as an Array of bytes
1463
+ * @property {number} from - from/source node address
1464
+ * @property {number} to - to/destination node address
1465
+ * @property {number} protocol - protocol number to be used to send this Datagram
1466
+ * @property {boolean} reliability - true if Datagram should be reliable, false if unreliable
1467
+ * @property {number} ttl - time-to-live for the datagram. Time-to-live is advisory, and an agent may choose it ignore it
1468
+ */
1469
+
1470
+ /**
1471
+ * Notification of received datagram message received by the Unet node.
1472
+ *
1473
+ * @typedef {Message} DatagramNtf
1474
+ * @property {number[]} data - data as an Array of bytes
1475
+ * @property {number} from - from/source node address
1476
+ * @property {number} to - to/destination node address
1477
+ * @property {number} protocol - protocol number to be used to send this Datagram
1478
+ * @property {number} ttl - time-to-live for the datagram. Time-to-live is advisory, and an agent may choose it ignore it
1479
+ */
1480
+
1481
+ /**
1482
+ * An identifier for an agent or a topic.
1483
+ * @external AgentID
1484
+ * @see {@link https://org-arl.github.io/fjage/jsdoc/|fjåge.js Documentation}
1485
+ */
1486
+
1487
+ /**
1488
+ * Services supported by fjage agents.
1489
+ * @external Services
1490
+ * @see {@link https://org-arl.github.io/fjage/jsdoc/|fjåge.js Documentation}
1491
+ */
1492
+
1493
+ /**
1494
+ * An action represented by a message.
1495
+ * @external Performative
1496
+ * @see {@link https://org-arl.github.io/fjage/jsdoc/|fjåge.js Documentation}
1497
+ */
1498
+
1499
+ /**
1500
+ * Function to creates a unqualified message class based on a fully qualified name.
1501
+ * @external MessageClass
1502
+ * @see {@link https://org-arl.github.io/fjage/jsdoc/|fjåge.js Documentation}
1503
+ */
1504
+
1505
+ /**
1506
+ * A caching CachingAgentID which caches Agent parameters locally.
1507
+ *
1508
+ * @class
1509
+ * @extends AgentID
1510
+ * @param {string | AgentID} name - name of the agent or an AgentID to copy
1511
+ * @param {boolean} topic - name of topic
1512
+ * @param {Gateway} owner - Gateway owner for this AgentID
1513
+ * @param {Boolean} [greedy=true] - greedily fetches and caches all parameters if this Agent
1514
+ *
1515
+ */
1516
+ class CachingAgentID extends AgentID {
1517
+
1518
+ constructor(name, topic, owner, greedy=true) {
1519
+ if (name instanceof AgentID) {
1520
+ super(name.getName(), name.topic, name.owner);
1521
+ } else {
1522
+ super(name, topic, owner);
1523
+ }
1524
+ this.greedy = greedy;
1525
+ this.cache = {};
1526
+ }
1527
+
1528
+ /**
1529
+ * Sets parameter(s) on the Agent referred to by this AgentID, and caches the parameter(s).
1530
+ *
1531
+ * @param {(string|string[])} params - parameters name(s) to be set
1532
+ * @param {(Object|Object[])} values - parameters value(s) to be set
1533
+ * @param {number} [index=-1] - index of parameter(s) to be set
1534
+ * @param {number} [timeout=5000] - timeout for the response
1535
+ * @returns {Promise<(Object|Object[])>} - a promise which returns the new value(s) of the parameters
1536
+ */
1537
+ async set(params, values, index=-1, timeout=5000) {
1538
+ let s = await super.set(params, values, index, timeout);
1539
+ this._updateCache(params, s, index);
1540
+ }
1541
+
1542
+ /**
1543
+ * Gets parameter(s) on the Agent referred to by this AgentID, getting them from the cache if possible.
1544
+ *
1545
+ * @param {(string|string[])} params - parameters name(s) to be fetched
1546
+ * @param {number} [index=-1] - index of parameter(s) to be fetched
1547
+ * @param {number} [timeout=5000] - timeout for the response
1548
+ * @param {number} [maxage=5000] - maximum age of the cached result to retreive
1549
+ * @returns {Promise<(Object|Object[])>} - a promise which returns the value(s) of the parameters
1550
+ */
1551
+ async get(params, index=-1, timeout=5000, maxage=5000) {
1552
+ if (this._isCached(params, index, maxage)) return this._getCache(params, index);
1553
+ if (this.greedy && !(Array.isArray(params) && params.includes('name')) && params != 'name') {
1554
+ let rsp = await super.get(null, index, timeout);
1555
+ this._updateCache(null, rsp, index);
1556
+ if (Array.isArray(params)) {
1557
+ return params.map(p => {
1558
+ let f = Object.keys(rsp).find(rv => this._toNamed(rv) === p);
1559
+ return f ? rsp[f] : null;
1560
+ });
1561
+ } else {
1562
+ let f = Object.keys(rsp).find(rv => this._toNamed(rv) === params);
1563
+ return f ? rsp[f] : null;
1564
+ }
1565
+ } else {
1566
+ let r = await super.get(params, index, timeout);
1567
+ this._updateCache(params, r, index);
1568
+ return r;
1569
+ }
1570
+ }
1571
+
1572
+ _updateCache(params, vals, index) {
1573
+ if (vals == null || Array.isArray(vals) && vals.every(v => v == null)) return;
1574
+ if (params == null) {
1575
+ params = Object.keys(vals);
1576
+ vals = Object.values(vals);
1577
+ } else if (!Array.isArray(params)) params = [params];
1578
+ if (!Array.isArray(vals)) vals = [vals];
1579
+ params = params.map(this._toNamed);
1580
+ if (this.cache[index.toString()] === undefined) this.cache[index.toString()] = {};
1581
+ let c = this.cache[index.toString()];
1582
+ for (let i = 0; i < params.length; i++) {
1583
+ if (c[params[i]] === undefined) c[params[i]] = {};
1584
+ c[params[i]].value = vals[i];
1585
+ c[params[i]].ctime = Date.now();
1586
+ }
1587
+ }
1588
+
1589
+ _isCached(params, index, maxage) {
1590
+ if (maxage <= 0) return false;
1591
+ if (params == null) return false;
1592
+ let c = this.cache[index.toString()];
1593
+ if (!c) {
1594
+ return false;
1595
+ }
1596
+ if (!Array.isArray(params)) params = [params];
1597
+ const rv = params.every(p => {
1598
+ p = this._toNamed(p);
1599
+ return (p in c) && (Date.now() - c[p].ctime <= maxage);
1600
+ });
1601
+ return rv;
1602
+ }
1603
+
1604
+ _getCache(params, index) {
1605
+ let c = this.cache[index.toString()];
1606
+ if (!c) return null;
1607
+ if (!Array.isArray(params)){
1608
+ if (params in c) return c[params].value;
1609
+ return null;
1610
+ }else {
1611
+ return params.map(p => p in c ? c[p].value : null);
1612
+ }
1613
+ }
1614
+
1615
+ _toNamed(param) {
1616
+ const idx = param.lastIndexOf('.');
1617
+ if (idx < 0) return param;
1618
+ else return param.slice(idx+1);
1619
+ }
1620
+
1621
+ }
1622
+
1623
+
1624
+ class CachingGateway extends Gateway{
1625
+
1626
+ /**
1627
+ * Get an AgentID for a given agent name.
1628
+ *
1629
+ * @param {string} name - name of agent
1630
+ * @param {Boolean} [caching=true] - if the AgentID should cache parameters
1631
+ * @param {Boolean} [greedy=true] - greedily fetches and caches all parameters if this Agent
1632
+ * @returns {AgentID|CachingAgentID} - AgentID for the given name
1633
+ */
1634
+ agent(name, caching=true, greedy=true) {
1635
+ const aid = super.agent(name);
1636
+ return caching ? new CachingAgentID(aid, null, null, greedy) : aid;
1637
+ }
1638
+
1639
+ /**
1640
+ * Returns an object representing the named topic.
1641
+ *
1642
+ * @param {string|AgentID} topic - name of the topic or AgentID
1643
+ * @param {string} topic2 - name of the topic if the topic param is an AgentID
1644
+ * @param {Boolean} [caching=true] - if the AgentID should cache parameters
1645
+ * @param {Boolean} [greedy=true] - greedily fetches and caches all parameters if this Agent
1646
+ * @returns {AgentID|CachingAgentID} - object representing the topic
1647
+ */
1648
+ topic(topic, topic2, caching=true, greedy=true) {
1649
+ const aid = super.topic(topic, topic2);
1650
+ return caching ? new CachingAgentID(aid, null, null, greedy) : aid;
1651
+ }
1652
+
1653
+ /**
1654
+ * Finds an agent that provides a named service. If multiple agents are registered
1655
+ * to provide a given service, any of the agents' id may be returned.
1656
+ *
1657
+ * @param {string} service - the named service of interest
1658
+ * @param {Boolean} [caching=true] - if the AgentID should cache parameters
1659
+ * @param {Boolean} [greedy=true] - greedily fetches and caches all parameters if this Agent
1660
+ * @returns {Promise<?AgentID|CachingAgentID>} - a promise which returns an agent id for an agent that provides the service when resolved
1661
+ */
1662
+ async agentForService(service, caching=true, greedy=true) {
1663
+ const aid = await super.agentForService(service);
1664
+ if (!aid) return aid;
1665
+ return caching ? new CachingAgentID(aid, null, null, greedy) : aid;
1666
+ }
1667
+
1668
+ /**
1669
+ * Finds all agents that provides a named service.
1670
+ *
1671
+ * @param {string} service - the named service of interest
1672
+ * @param {Boolean} [caching=true] - if the AgentID should cache parameters
1673
+ * @param {Boolean} [greedy=true] - greedily fetches and caches all parameters if this Agent
1674
+ * @returns {Promise<?AgentID|CachingAgentID[]>} - a promise which returns an array of all agent ids that provides the service when resolved
1675
+ */
1676
+ async agentsForService(service, caching=true, greedy=true) {
1677
+ const aids = await super.agentsForService(service);
1678
+ return caching ? aids.map(a => new CachingAgentID(a, null, null, greedy)) : aids;
1679
+ }
1680
+ }
1681
+
1420
1682
  const REQUEST_TIMEOUT = 1000;
1421
1683
 
1422
1684
  const AddressResolutionReq = UnetMessages.AddressResolutionReq;
@@ -1444,7 +1706,7 @@ class UnetSocket {
1444
1706
 
1445
1707
  constructor(hostname, port, path='') {
1446
1708
  return (async () => {
1447
- this.gw = new Gateway({
1709
+ this.gw = new CachingGateway({
1448
1710
  hostname : hostname,
1449
1711
  port : port,
1450
1712
  path : path
@@ -1655,31 +1917,34 @@ class UnetSocket {
1655
1917
  /**
1656
1918
  * Gets an AgentID providing a specified service for low-level access to UnetStack
1657
1919
  * @param {string} svc - the named service of interest
1920
+ * @param {Boolean} caching - if the AgentID should cache parameters
1658
1921
  * @returns {Promise<?AgentID>} - a promise which returns an {@link AgentID} that provides the service when resolved
1659
1922
  */
1660
- async agentForService(svc) {
1923
+ async agentForService(svc, caching=true) {
1661
1924
  if (this.gw == null) return null;
1662
- return await this.gw.agentForService(svc);
1925
+ return await this.gw.agentForService(svc, caching);
1663
1926
  }
1664
1927
 
1665
1928
  /**
1666
1929
  *
1667
1930
  * @param {string} svc - the named service of interest
1931
+ * @param {Boolean} caching - if the AgentID should cache parameters
1668
1932
  * @returns {Promise<AgentID[]>} - a promise which returns an array of {@link AgentID|AgentIDs} that provides the service when resolved
1669
1933
  */
1670
- async agentsForService(svc) {
1934
+ async agentsForService(svc, caching=true) {
1671
1935
  if (this.gw == null) return null;
1672
- return await this.gw.agentsForService(svc);
1936
+ return await this.gw.agentsForService(svc, caching``);
1673
1937
  }
1674
1938
 
1675
1939
  /**
1676
1940
  * Gets a named AgentID for low-level access to UnetStack.
1677
1941
  * @param {string} name - name of agent
1942
+ * @param {Boolean} caching - if the AgentID should cache parameters
1678
1943
  * @returns {AgentID} - AgentID for the given name
1679
1944
  */
1680
- agent(name) {
1945
+ agent(name, caching=true) {
1681
1946
  if (this.gw == null) return null;
1682
- return this.gw.agent(name);
1947
+ return this.gw.agent(name, caching);
1683
1948
  }
1684
1949
 
1685
1950
  /**
@@ -1700,7 +1965,8 @@ class UnetSocket {
1700
1965
  }
1701
1966
 
1702
1967
  exports.AgentID = AgentID;
1703
- exports.Gateway = Gateway;
1968
+ exports.CachingAgentID = CachingAgentID;
1969
+ exports.Gateway = CachingGateway;
1704
1970
  exports.Message = Message;
1705
1971
  exports.MessageClass = MessageClass;
1706
1972
  exports.Performative = Performative;
@@ -1708,3 +1974,5 @@ exports.Protocol = Protocol;
1708
1974
  exports.Services = Services;
1709
1975
  exports.UnetMessages = UnetMessages;
1710
1976
  exports.UnetSocket = UnetSocket;
1977
+ exports.toGps = toGps;
1978
+ exports.toLocal = toLocal;