myio-js-library 0.1.113 → 0.1.115

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
@@ -1511,26 +1511,233 @@ MyIOLibrary.openDashboardPopupAllReport({
1511
1511
  <script src="https://unpkg.com/myio-js-library@latest/dist/myio-js-library.umd.min.js"></script>
1512
1512
  <script>
1513
1513
  const { openDashboardPopupReport } = MyIOLibrary;
1514
-
1514
+
1515
1515
  const modal = openDashboardPopupReport({
1516
1516
  ingestionId: 'demo-ingestion-123',
1517
1517
  deviceId: 'demo-device-123',
1518
1518
  identifier: 'ENTRADA-001',
1519
1519
  label: 'Outback',
1520
- api: {
1520
+ api: {
1521
1521
  clientId: 'demo-client',
1522
1522
  clientSecret: 'demo-secret',
1523
1523
  dataApiBaseUrl: 'https://api.data.apps.myio-bas.com',
1524
1524
  ingestionToken: 'demo-ingestion-token'
1525
1525
  }
1526
1526
  });
1527
-
1527
+
1528
1528
  modal.on('loaded', (data) => {
1529
1529
  console.log('Device report loaded with', data.count, 'days of data');
1530
1530
  });
1531
1531
  </script>
1532
1532
  ```
1533
1533
 
1534
+ #### `openDashboardPopupWaterTank(params: OpenDashboardPopupWaterTankOptions): Promise<{ close: () => void }>`
1535
+
1536
+ Opens a water tank telemetry modal that fetches data directly from ThingsBoard REST API (NOT Ingestion API). Displays real-time water level data with visual indicators, interactive charts, and CSV export functionality. Specifically designed for TANK and CAIXA_DAGUA device types.
1537
+
1538
+ **Parameters:**
1539
+ - `deviceId: string` - ThingsBoard device UUID (required)
1540
+ - `tbJwtToken: string` - ThingsBoard JWT token for REST API authentication (required)
1541
+ - `startTs: number` - Start timestamp in milliseconds (required)
1542
+ - `endTs: number` - End timestamp in milliseconds (required)
1543
+ - `label?: string` - Display label for the device (default: deviceId)
1544
+ - `currentLevel?: number` - Current water level percentage 0-100 (optional)
1545
+ - `deviceType?: string` - Device type (TANK, CAIXA_DAGUA, etc.)
1546
+ - `slaveId?: string | number` - Slave device ID (optional)
1547
+ - `centralId?: string` - Central controller ID (optional)
1548
+ - `telemetryKeys?: string[]` - Telemetry keys to fetch (default: ['waterLevel', 'nivel', 'level'])
1549
+ - `aggregation?: string` - Aggregation method: NONE, MIN, MAX, AVG, SUM, COUNT (default: 'NONE')
1550
+ - `limit?: number` - Maximum data points to fetch (default: 1000, max: 10000)
1551
+ - `timezone?: string` - Timezone (default: 'America/Sao_Paulo')
1552
+ - `ui?: object` - UI configuration:
1553
+ - `title?: string` - Modal title (default: "Water Tank - {label}")
1554
+ - `width?: number` - Modal width in pixels (default: 900)
1555
+ - `height?: number` - Modal height in pixels (default: 600)
1556
+ - `showExport?: boolean` - Show CSV export button (default: true)
1557
+ - `showLevelIndicator?: boolean` - Show visual level indicator (default: true)
1558
+ - `onOpen?: (context) => void` - Callback when modal opens
1559
+ - `onClose?: () => void` - Callback when modal closes
1560
+ - `onError?: (error) => void` - Callback on error
1561
+ - `onDataLoaded?: (data) => void` - Callback when telemetry data is loaded
1562
+
1563
+ **Returns:** Promise resolving to an object with:
1564
+ - `close(): void` - Method to close the modal programmatically
1565
+
1566
+ **Key Features:**
1567
+ - **ThingsBoard Telemetry API Integration**: Fetches data directly from `/api/plugins/telemetry/DEVICE/{deviceId}/values/timeseries`
1568
+ - **Real-time Level Visualization**: Interactive canvas chart showing water level trends
1569
+ - **Status-Based Color Coding**: Critical (<20%), Low (20-40%), Medium (40-70%), Good (70-90%), Full (>90%)
1570
+ - **Summary Statistics**: Current level, average, minimum, maximum values
1571
+ - **Device Metadata Display**: Shows device ID, label, type, slave ID, central ID
1572
+ - **CSV Export**: Download telemetry data with proper Brazilian formatting
1573
+ - **Responsive Design**: Adapts to different screen sizes with smooth animations
1574
+ - **Error Handling**: Graceful error display with user-friendly messages
1575
+
1576
+ **Usage Example:**
1577
+ ```javascript
1578
+ import { openDashboardPopupWaterTank } from 'myio-js-library';
1579
+
1580
+ // Basic usage
1581
+ const modal = await openDashboardPopupWaterTank({
1582
+ deviceId: 'water-tank-uuid-123',
1583
+ tbJwtToken: localStorage.getItem('jwt_token'),
1584
+ startTs: Date.now() - 86400000 * 7, // Last 7 days
1585
+ endTs: Date.now(),
1586
+ label: 'Water Tank - Building A',
1587
+ currentLevel: 75.5
1588
+ });
1589
+
1590
+ // Close programmatically
1591
+ modal.close();
1592
+
1593
+ // Advanced usage with callbacks and customization
1594
+ const modal = await openDashboardPopupWaterTank({
1595
+ deviceId: 'caixa-dagua-uuid-456',
1596
+ tbJwtToken: myToken,
1597
+ startTs: startTimestamp,
1598
+ endTs: endTimestamp,
1599
+ label: 'Caixa D\'Água Principal',
1600
+ deviceType: 'CAIXA_DAGUA',
1601
+ currentLevel: 82.3,
1602
+ slaveId: 'SLAVE-001',
1603
+ centralId: 'CENTRAL-A',
1604
+ telemetryKeys: ['waterLevel', 'nivel_agua', 'level'],
1605
+ aggregation: 'AVG',
1606
+ limit: 500,
1607
+ ui: {
1608
+ title: 'Análise de Nível - Caixa Principal',
1609
+ width: 1000,
1610
+ height: 700,
1611
+ showExport: true
1612
+ },
1613
+ onOpen: (context) => {
1614
+ console.log('Modal opened for device:', context.device.label);
1615
+ console.log('Time range:', new Date(context.timeRange.startTs), '-', new Date(context.timeRange.endTs));
1616
+ },
1617
+ onDataLoaded: (data) => {
1618
+ console.log('Telemetry loaded:', data.telemetry.length, 'points');
1619
+ console.log('Summary:', data.summary);
1620
+ },
1621
+ onClose: () => {
1622
+ console.log('Modal closed');
1623
+ },
1624
+ onError: (error) => {
1625
+ console.error('Error:', error.message);
1626
+ alert(`Failed to load water tank data: ${error.message}`);
1627
+ }
1628
+ });
1629
+ ```
1630
+
1631
+ **UMD Usage (ThingsBoard widgets):**
1632
+ ```html
1633
+ <script src="https://unpkg.com/myio-js-library@latest/dist/myio-js-library.umd.min.js"></script>
1634
+ <script>
1635
+ const { openDashboardPopupWaterTank } = MyIOLibrary;
1636
+
1637
+ // In your widget action handler
1638
+ async function handleDashboardAction() {
1639
+ const jwtToken = localStorage.getItem('jwt_token');
1640
+ const deviceId = entityId.id;
1641
+ const startTs = ctx.timeWindow.minTime;
1642
+ const endTs = ctx.timeWindow.maxTime;
1643
+
1644
+ try {
1645
+ const modal = await openDashboardPopupWaterTank({
1646
+ deviceId: deviceId,
1647
+ tbJwtToken: jwtToken,
1648
+ startTs: startTs,
1649
+ endTs: endTs,
1650
+ label: entityName,
1651
+ deviceType: 'CAIXA_DAGUA',
1652
+ currentLevel: currentLevelValue,
1653
+ onOpen: (context) => {
1654
+ console.log('Water tank modal opened');
1655
+ },
1656
+ onError: (error) => {
1657
+ console.error('Modal error:', error);
1658
+ showNotification(error.message, 'error');
1659
+ }
1660
+ });
1661
+ } catch (error) {
1662
+ console.error('Failed to open water tank modal:', error);
1663
+ }
1664
+ }
1665
+ </script>
1666
+ ```
1667
+
1668
+ **ThingsBoard API Integration:**
1669
+ ```
1670
+ GET /api/plugins/telemetry/DEVICE/{deviceId}/values/timeseries
1671
+ ?keys=waterLevel,nivel,level
1672
+ &startTs={startMillis}
1673
+ &endTs={endMillis}
1674
+ &limit=1000
1675
+
1676
+ Headers:
1677
+ X-Authorization: Bearer {tbJwtToken}
1678
+ ```
1679
+
1680
+ **Level Status Color Coding:**
1681
+ - **Critical** (<20%): Red (#e74c3c) - Risk of running dry
1682
+ - **Low** (20-40%): Orange (#e67e22) - Needs attention
1683
+ - **Medium** (40-70%): Yellow (#f39c12) - Normal range
1684
+ - **Good** (70-90%): Green (#27ae60) - Optimal level
1685
+ - **Full** (>90%): Blue (#3498db) - Near capacity
1686
+
1687
+ **Data Structure Returned:**
1688
+ ```javascript
1689
+ {
1690
+ deviceId: 'device-uuid',
1691
+ telemetry: [
1692
+ { ts: 1704067200000, value: 75.5, key: 'waterLevel' },
1693
+ { ts: 1704153600000, value: 72.3, key: 'waterLevel' }
1694
+ ],
1695
+ summary: {
1696
+ currentLevel: 75.5, // Most recent reading
1697
+ avgLevel: 73.8, // Average over period
1698
+ minLevel: 65.2, // Minimum level
1699
+ maxLevel: 82.1, // Maximum level
1700
+ totalReadings: 245, // Number of data points
1701
+ firstReadingTs: 1704067200000,
1702
+ lastReadingTs: 1704672000000
1703
+ },
1704
+ metadata: {
1705
+ keys: ['waterLevel', 'nivel', 'level'],
1706
+ aggregation: 'NONE',
1707
+ limit: 1000
1708
+ }
1709
+ }
1710
+ ```
1711
+
1712
+ **Error Handling:**
1713
+ The modal includes comprehensive error handling with specific error codes:
1714
+ - `VALIDATION_ERROR` - Invalid parameters provided
1715
+ - `AUTH_ERROR` - Authentication failed (invalid or expired token)
1716
+ - `TOKEN_EXPIRED` - JWT token has expired
1717
+ - `NETWORK_ERROR` - Network request failed
1718
+ - `NO_DATA` - Device not found or no telemetry available
1719
+ - `UNKNOWN_ERROR` - Unexpected error occurred
1720
+
1721
+ **Integration with TELEMETRY Widget:**
1722
+ The modal automatically integrates with the v5.2.0 TELEMETRY widget controller:
1723
+ ```javascript
1724
+ // Automatic device type detection and routing
1725
+ if (deviceType === 'TANK' || deviceType === 'CAIXA_DAGUA') {
1726
+ // Opens water tank modal (uses TB telemetry API)
1727
+ await MyIOLibrary.openDashboardPopupWaterTank({
1728
+ deviceId: deviceId,
1729
+ tbJwtToken: jwtToken,
1730
+ startTs: startTimestamp,
1731
+ endTs: endTimestamp,
1732
+ label: deviceLabel,
1733
+ currentLevel: levelPercentage
1734
+ });
1735
+ } else {
1736
+ // Opens energy/water modal (uses Ingestion API)
1737
+ await MyIO.openDashboardPopupEnergy({...});
1738
+ }
1739
+ ```
1740
+
1534
1741
  **Migration from Legacy API:**
1535
1742
  ```javascript
1536
1743
  // OLD API (deprecated)