Compare commits

...
Author SHA1 Message Date
Thomas Nordquist 633e092ecf Merge branch 'master' into copilot/visualize-mouse-movements 2025-12-20 20:25:20 +01:00
Copilotandthomasnordquist c55c3a8245 Fix UI tests: correct expandTopic parameter order and CI workflow (#936)
Fixes TypeScript compilation errors in UI tests and resolves CI workflow
configuration issue.

## Changes Made

### 1. Fixed expandTopic parameter order in ui-tests.spec.ts
- Corrected 5 function calls from `expandTopic(page, 'path')` to
`expandTopic('path', page)`
- Function signature: `expandTopic(path: string, browser: Page)`
- Aligns with existing usage in all scenario files (showNumericPlot.ts,
publishTopic.ts, etc.)

### 2. Fixed CI workflow configuration
- Updated `.github/workflows/tests.yml` to checkout PR code instead of
base branch
- Added `ref: ${{ github.event.pull_request.head.sha }}` to all 4
checkout actions
- The `pull_request_target` event defaults to checking out the base
branch; this fix ensures CI tests the PR's code

## Root Cause

The CI workflow was testing the base branch (master) which still had the
wrong parameter order, while the PR had the correct fix. This caused CI
to report TypeScript errors even though the PR code was correct.

## Testing

-  TypeScript compilation passes locally (`tsc` and `yarn build`)
-  Parameter order matches function signature and codebase conventions
-  CI workflow now correctly tests PR code
-  All 4 CI jobs (test, ui-tests, demo-video, test-browser) will use
corrected code

<!-- START COPILOT ORIGINAL PROMPT -->



<details>

<summary>Original prompt</summary>

> 
> ----
> 
> *This section details on the original issue you should resolve*
> 
> <issue_title>Fix tests</issue_title>
> <issue_description>- fix backend tests
> - fix UI tests</issue_description>
> 
> ## Comments on the Issue (you are @copilot in this section)
> 
> <comments>
> </comments>
> 


</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes thomasnordquist/MQTT-Explorer#935

<!-- START COPILOT CODING AGENT TIPS -->
---

 Let Copilot coding agent [set things up for
you](https://github.com/thomasnordquist/MQTT-Explorer/issues/new?title=+Set+up+Copilot+instructions&body=Configure%20instructions%20for%20this%20repository%20as%20documented%20in%20%5BBest%20practices%20for%20Copilot%20coding%20agent%20in%20your%20repository%5D%28https://gh.io/copilot-coding-agent-tips%29%2E%0A%0A%3COnboard%20this%20repo%3E&assignees=copilot)
— coding agent works faster and does higher quality work when set up for
your repo.

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 19:34:34 +01:00
Copilot 92aa2c9fa8 Fix UI test timeouts, TypeScript compilation, dependency compatibility, and backend tests with isolated test suite using per-test mocking (#930) 2025-12-20 15:09:26 +01:00
copilot-swe-agent[bot]andthomasnordquist d6282e6499 Address code review: improve PRNG quality, handle edge cases, extract constants
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 08:01:15 +00:00
copilot-swe-agent[bot]andthomasnordquist 75d599d2fa Add jitter, variable timing, and overshoot with correction for human-like movement
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 07:58:16 +00:00
copilot-swe-agent[bot]andthomasnordquist a3e0f89a32 Increase arc to 80% and enhance click visualization visibility
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 02:58:37 +00:00
copilot-swe-agent[bot]andthomasnordquist 3b5bd45d8c Fix memory leaks and improve z-index handling in click visualization
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 02:11:55 +00:00
copilot-swe-agent[bot]andthomasnordquist daead9273c Increase arc height and add click visualization to mouse movement
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 02:08:15 +00:00
Copilot 5a54ba4983 Upgrade Electron to 39.2.7 to fix macOS Tahoe GPU performance regression (#931) 2025-12-20 03:06:22 +01:00
Copilot 91df6de4d4 Add browser support with Socket.io transport, authentication, performance-optimized IPC, and CI/CD (#925) 2025-12-20 02:35:34 +01:00
copilot-swe-agent[bot]andthomasnordquist 429cc190b4 Remove test spec file to keep changes minimal
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 01:33:54 +00:00
copilot-swe-agent[bot]andthomasnordquist ffd4010561 Fix code review comments: update documentation and prevent division by zero
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 01:33:09 +00:00
copilot-swe-agent[bot]andthomasnordquist 9ebce15dd2 Implement bezier curve for human-like mouse movements with curved trajectory
Co-authored-by: thomasnordquist <7721625+thomasnordquist@users.noreply.github.com>
2025-12-20 01:26:10 +00:00
copilot-swe-agent[bot] 180d7b3226 Initial plan 2025-12-20 01:19:50 +00:00
Copilot 8285627c5f Implement comprehensive UI test suite with meaningful assertions and best practices (#921) 2025-12-20 02:13:31 +01:00
Thomas Nordquist 55f8b7d2b7 Allow commercial use
Updated the license from Creative Commons Attribution-NonCommercial 4.0 to Attribution-ShareAlike 4.0. Adjusted terms and conditions to reflect the new license's requirements.
2025-12-19 23:30:08 +01:00
Copilot 8f1eeedbaf Configure comprehensive Copilot instructions for repository best practices (#923) 2025-12-19 22:01:29 +01:00
Copilot 4843b2ec18 Add MCP introspection support for Electron frontend with Copilot agent integration (#916) 2025-12-19 21:46:43 +01:00
Thomas Nordquist 803413a087 Merge pull request #897 from scubanarc/license
Update license to CC by-nd
2025-08-22 21:19:01 +02:00
Jason Bauer b457559b4a Update license 2025-08-21 12:54:21 -07:00
Björn Dalfors 03ba43038c Merge pull request #812 from thomasnordquist/chore/fix-broken-test-locators
fix broken test locators
2024-06-17 09:31:25 +00:00
Björn Dalfors 8975e7b641 Merge pull request #813 from thomasnordquist/chore/dont-use-pull-request-target-for-untrusted-code
dont use pull_request_target as it opens the repo for pwnage..
2024-06-17 09:30:23 +00:00
Björn Dalfors efc9fb9736 dont use pull_request_target as it opens the repo for pwnage.. 2024-06-17 11:25:07 +02:00
Björn Dalfors 61f2389c1c fix broken test locators 2024-06-17 10:01:34 +02:00
Thomas Nordquist f539e03c7e Merge pull request #801 from thomasnordquist/feat/set-payload-from-file
feat: support save and load payload from file
2024-06-02 08:35:53 +02:00
Thomas Nordquist 724ea5acbf Merge pull request #804 from thomasnordquist/chore/add-sparkplug-to-demovideo
add sparkplug decoding to demo video
2024-06-02 08:34:48 +02:00
Björn Dalfors e009940530 fix inputs not being cleared 2024-06-01 22:24:41 +02:00
Björn Dalfors e19178780f add sparkplug decoding to demo video 2024-06-01 22:24:41 +02:00
Björn Dalfors 3229ef5643 Chore/fix workflow sha (#807)
* checkout merge commit of PR, not base branch head

https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#pull_request_target

* use link to test result, gif exceeds github allowed content length
2024-06-01 22:23:25 +02:00
Björn Dalfors b4a6199936 Move file operation to backend 2024-05-29 10:02:00 +02:00
Björn Dalfors bd6a1a0d2d Support specifying file encoding 2024-05-29 10:01:32 +02:00
Björn Dalfors 9d09ab2165 move filesystem operation to backend 2024-05-27 22:09:12 +02:00
Björn Dalfors f17640c9db feat: save value to file 2024-05-27 22:09:12 +02:00
Björn Dalfors 1ba0d07757 feat: support set payload from file when publishing 2024-05-27 22:09:12 +02:00
Thomas Nordquist 20a3202b5f Merge pull request #802 from thomasnordquist/tnordquist/fix-hot-reload
chore: fix webpack reload
2024-05-27 18:06:08 +02:00
Thomas Nordquist 28b99f5774 chore: fix webpack reload 2024-05-27 18:05:24 +02:00
Thomas Nordquist 42565c8bdc chore: coerce ui-test to end 2024-05-27 10:07:23 +02:00
Thomas Nordquist 8b43e20f2e Merge pull request #795 from thomasnordquist/tnordquist/decode-data-in-frontend
decode data in frontend
2024-05-25 16:28:53 +02:00
Thomas Nordquist a2a75588c9 Merge pull request #799 from thomasnordquist/tnordquist/allow-to-connect-with-double-click
feat: connect with double-click
2024-05-25 16:28:37 +02:00
Thomas Nordquist c13b60cd18 Merge pull request #800 from thomasnordquist/tnordquist/fix-eclipse-server
chore: update eclipse server url
2024-05-25 16:27:55 +02:00
Thomas Nordquist 18f8da9054 test: fix demo video 2024-05-24 22:29:49 +02:00
Thomas Nordquist 79fbd34cfa feat: connect with double-click 2024-05-24 22:23:26 +02:00
Thomas Nordquist 3bc23e6d74 test: fix demo video 2024-05-24 22:01:13 +02:00
Thomas Nordquist e9a56ac48d Merge remote-tracking branch 'origin/master' into tnordquist/decode-data-in-frontend 2024-05-24 17:51:24 +02:00
Björn Dalfors b4bdd01808 add sparkplug messages to demovideo 2024-05-24 17:50:08 +02:00
Björn Dalfors 4406bf5de4 feat: use tahu for sparkplug decoding 2024-05-24 17:50:07 +02:00
Thomas Nordquist bbe2ae3f29 test: fix tests 2024-05-23 23:19:37 +02:00
Thomas Nordquist a2c4388c78 fix: repair types 2024-05-23 17:05:27 +02:00
Thomas Nordquist c88978f0dd fix: fix ui updates 2024-05-22 15:12:45 +02:00
Thomas Nordquist b3a37e4794 chore: refactor 2024-05-22 14:44:06 +02:00
Thomas Nordquist 1ecb53b397 fix: update react when decoder has been overriden 2024-05-22 09:04:06 +02:00
Björn Dalfors 97fedcba08 fix sparkplug topic regexp 2024-05-21 15:26:43 +02:00
Björn Dalfors 1f23c65484 Stop click event propagation prevent panel from collapsing 2024-05-21 15:17:18 +02:00
Thomas Nordquist 980072f680 chore: decode data in frontend 2024-05-21 09:22:11 +02:00
Thomas Nordquist 10aae59c92 Merge remote-tracking branch 'fb/multi-decoder/master' into feat/use-tahu-for-sparkplug-decoding 2024-05-18 11:26:39 +02:00
Björn Dalfors f4bda3e242 feat: use tahu for sparkplug decoding 2024-05-17 16:14:32 +02:00
mhorsche 626b9cab7d Specific int/uint byte size
- possible data types are: 'json', 'string', 'hex', 'uint8', 'uint16', 'uint32', 'uint64', 'int8', 'int16', 'int32', 'int64', 'float', 'double'
- default is 'json'
2022-06-21 21:14:59 +02:00
Max Horsche 567f6d2d50 Added support for binary data types
- Select data type (string, json, hex, uint, int, float) for each topic individually
- Default data type is 'string'
- Show milliseconds in message received timestamp
2021-01-11 10:11:34 +01:00
107 changed files with 8595 additions and 1209 deletions
+46
View File
@@ -0,0 +1,46 @@
{
"name": "MQTT Explorer Development",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
"workspaceFolder": "/workspace",
"customizations": {
"vscode": {
"extensions": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-vscode.vscode-typescript-next",
"ms-azuretools.vscode-docker",
"eamodio.gitlens"
],
"settings": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"typescript.tsdk": "node_modules/typescript/lib",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
}
}
},
"forwardPorts": [3000, 8080, 1883],
"portsAttributes": {
"3000": {
"label": "MQTT Explorer Server",
"onAutoForward": "notify"
},
"8080": {
"label": "Webpack Dev Server",
"onAutoForward": "notify"
},
"1883": {
"label": "MQTT Broker",
"onAutoForward": "ignore"
}
},
"postCreateCommand": "yarn install",
"remoteUser": "node"
}
+21
View File
@@ -0,0 +1,21 @@
version: '3.8'
services:
app:
image: mcr.microsoft.com/devcontainers/javascript-node:20
volumes:
- ../..:/workspace:cached
command: sleep infinity
network_mode: service:mosquitto
environment:
- MQTT_EXPLORER_USERNAME=dev
- MQTT_EXPLORER_PASSWORD=dev123
mosquitto:
image: eclipse-mosquitto:2
ports:
- "1883:1883"
- "3000:3000"
- "8080:8080"
volumes:
- ./mosquitto.conf:/mosquitto/config/mosquitto.conf:ro
+4
View File
@@ -0,0 +1,4 @@
# Mosquitto configuration for development
listener 1883
allow_anonymous true
persistence false
+383
View File
@@ -0,0 +1,383 @@
# GitHub Copilot Agent Instructions for MQTT Explorer
## Overview
MQTT Explorer is an Electron-based desktop application for exploring MQTT brokers. It provides a comprehensive UI for connecting to MQTT brokers, browsing topics, and analyzing message flows.
## Technology Stack
- **Frontend**: React 16.x with Material-UI
- **Backend**: Node.js with TypeScript
- **Desktop Framework**: Electron 29.x
- **MQTT Client**: [mqttjs](https://github.com/mqttjs/MQTT.js) v4.x
- **State Management**: Redux with redux-thunk
- **Build Tools**: webpack, TypeScript compiler
- **Testing**: Mocha + Chai for unit tests, Playwright for MCP introspection tests
## Project Setup
### Building and Running
```bash
# Install dependencies
yarn install
# Build the project
yarn build
# Set password for browser testing
export MQTT_EXPLORER_USERNAME=admin
export MQTT_EXPLORER_PASSWORD=secretpassword
# Start the application
yarn start
# Start in development mode
yarn dev
```
### Running with MCP Introspection (for testing)
```bash
# Build first
yarn build
# Start with MCP introspection enabled
electron . --enable-mcp-introspection
# Or with custom port
electron . --enable-mcp-introspection --remote-debugging-port=9223
```
## Writing Tests
### Requirements for All Tests
1. **Tests MUST be deterministic** - They should produce the same results every time they run
2. **Tests MUST be independent** - Each test should be able to run in isolation without depending on other tests
3. **Include screenshots** - Visual verification is required for UI changes
4. **Handle asynchronous operations properly** - This is an MQTT message queue tool
### Best Practices for UI Tests
#### 1. Use Given-When-Then Pattern
Structure tests with clear Given-When-Then comments to make them readable:
```typescript
it('Given a JSON message sent to topic foo/bar/baz, the tree should display nested topics', async function () {
// Given: Mock MQTT publishes JSON to foo/bar/baz
// When: We wait for the topic to appear in the tree
// Then: Topic hierarchy should be visible (foo -> bar -> baz)
})
```
#### 2. Wait for Elements, Don't Use Fixed Delays
Prefer `waitFor` over `sleep` whenever possible:
```typescript
// ✓ Good: Wait for specific element
const topic = await page.locator('span[data-test-topic="kitchen"]')
await topic.waitFor({ state: 'visible', timeout: 5000 })
// ✗ Bad: Fixed delay without verification
await sleep(5000)
```
#### 3. Use Meaningful Assertions
Every test should have explicit assertions that verify the expected state:
```typescript
// ✓ Good: Explicit assertion with meaningful message
const treeNodes = await page.locator('[class*="TreeNode"]')
const count = await treeNodes.count()
expect(count).to.be.greaterThan(0, 'Topic tree should contain nodes')
// ✗ Bad: No assertion, only screenshot
await page.screenshot({ path: 'test.png' })
```
#### 4. Test Data-Driven Scenarios
Write tests that describe the data flow:
```typescript
it('Given messages sent to livingroom/lamp/state and livingroom/lamp/brightness, both should appear under livingroom/lamp', async function () {
// Test implementation verifies the specific data flow
})
```
#### 5. Use Data Test Attributes
Leverage `data-test-*` attributes for reliable selectors:
```typescript
// ✓ Good: Use data-test attributes
const topic = await page.locator('span[data-test-topic="kitchen"]')
// ⚠ Acceptable: Use role/text when data attributes aren't available
const button = await page.locator('//button/span[contains(text(),"Connect")]')
// ✗ Bad: Rely on CSS classes that may change
const topic = await page.locator('.MuiTreeItem-label')
```
#### 6. Verify Multiple Aspects
Test should verify both state and UI:
```typescript
// Verify the action completed
const isVisible = await disconnectButton.isVisible()
expect(isVisible).to.be.true
// Capture screenshot for visual verification
await page.screenshot({ path: 'test-screenshot-connection.png' })
```
#### 7. Handle MQTT Asynchronous Nature
Account for message propagation time:
```typescript
// Publish message
await mockClient.publish('topic/name', 'value')
// Wait for UI to update
await page.locator(`text="value"`).waitFor({ timeout: 5000 })
// Verify state
const value = await page.textContent('.message-value')
expect(value).toBe('value')
```
### Handling MQTT Asynchronous Operations
MQTT is inherently asynchronous. When writing tests:
- **Wait for message propagation**: Use proper wait strategies (e.g., `await page.waitForSelector()`, `await sleep()`)
- **Don't assume immediate updates**: Messages take time to send, receive, and update the UI
- **Use event-based waiting**: Wait for specific UI elements or state changes rather than fixed timeouts when possible
- **Account for network latency**: MQTT broker communication involves network round trips
### Example Test Pattern
```typescript
// 1. Perform action (e.g., publish message)
await publishMessage(topic, payload)
// 2. Wait for UI to update (not just arbitrary sleep)
await page.waitForSelector(`text="${expectedValue}"`, { timeout: 5000 })
// 3. Verify state
const value = await page.textContent('.message-value')
expect(value).toBe(expectedValue)
// 4. Take screenshot for verification
await page.screenshot({ path: 'test-result.png' })
```
### Running Tests
```bash
# Run all tests
yarn test
# Run specific test suites
yarn test:app
yarn test:backend
yarn test:mcp
# Run linters
yarn lint
yarn lint:fix
```
### Running UI Tests (yarn test:ui)
The UI tests require specific setup in the test environment:
**Prerequisites:**
1. **Xvfb (X Virtual Framebuffer)** - Required for headless Electron testing
```bash
# Start Xvfb on display :99
Xvfb :99 -screen 0 1024x720x24 -ac &
export DISPLAY=:99
```
2. **Mosquitto MQTT Broker** - Required for MQTT message testing
```bash
# Install mosquitto
sudo apt-get install -y mosquitto mosquitto-clients
# Start mosquitto service
sudo systemctl start mosquitto
# Verify it's running on port 1883
sudo systemctl status mosquitto
```
3. **@types/node** - Required for TypeScript compilation
```bash
yarn add -D @types/node
```
**Running UI Tests:**
```bash
# Build the application first
yarn build
# Run UI tests with proper display
DISPLAY=:99 yarn test:ui
```
**Common Issues:**
- **"Timeout exceeded" in before hook**: Mosquitto is not running or not accessible on port 1883
- **"Cannot find type definition file for 'node'"**: Run `yarn add -D @types/node`
- **Electron fails to launch**: Xvfb is not running or DISPLAY variable not set
- **Tests hang**: Check if old Electron/mosquitto processes are still running and kill them
**Environment Cleanup:**
```bash
# Kill old Electron processes
ps aux | grep electron | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null
# Kill old mosquitto processes (if running custom instance)
ps aux | grep mosquitto | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null
```
## MCP Introspection Testing
The project supports MCP (Model Context Protocol) for automated testing with Playwright:
- Use `yarn test:mcp` to run automated UI tests
- Tests launch the app with remote debugging enabled on port 9222
- Connect to `http://localhost:9222` via Chrome DevTools Protocol
## Project Structure
- `app/` - Frontend React application
- `backend/` - Backend models, tests, and connection management
- `src/` - Electron main process and bindings
- `src/spec/` - Test specifications including MCP introspection tests
## Code Style and Formatting
### Linting
The project uses TSLint with Airbnb config and Prettier for code formatting:
```bash
# Run all linters
yarn lint
# Run linters individually
yarn lint:prettier # Check Prettier formatting
yarn lint:tslint # Check TSLint rules
yarn lint:spellcheck # Check spelling in code
# Auto-fix issues
yarn lint:fix # Fix TSLint and Prettier issues
yarn lint:tslint:fix # Fix TSLint issues only
yarn lint:prettier:fix # Fix Prettier issues only
```
### Code Style Rules
- **Semicolons**: Never use semicolons (enforced by TSLint and Prettier)
- **Quotes**: Single quotes for strings
- **Indentation**: 2 spaces
- **Line length**: Maximum 120 characters (Prettier) / 200 characters (TSLint)
- **Arrow functions**: No parentheses for single parameters (`x => x + 1`)
- **Trailing commas**: Required for multiline objects and arrays (ES5 compatible)
### TypeScript Guidelines
- Enable strict null checks and no implicit any
- Use TypeScript interfaces for data structures
- Prefer `const` over `let`, avoid `var`
- Use type inference when possible, explicit types when clarity is needed
## Dependency Management
### Adding Dependencies
```bash
# Add to root project
yarn add <package-name>
# Add to app (frontend)
cd app && yarn add <package-name>
# Add to backend
cd backend && yarn add <package-name>
# Add dev dependencies
yarn add -D <package-name>
```
### Important Dependency Notes
- Main dependencies are in the root `package.json`
- Frontend React app has its own dependencies in `app/package.json`
- Backend models and logic have dependencies in `backend/package.json`
- Always use `--frozen-lockfile` in CI to ensure reproducible builds
- Run `yarn install` after pulling changes that modify `yarn.lock`
## Debugging
### Development Mode
```bash
# Start with hot reload for frontend
yarn dev
# This runs two processes in parallel:
# 1. webpack-dev-server for the React app (port varies)
# 2. Electron in development mode with the --development flag
```
### Debugging TypeScript
- Source maps are enabled in `tsconfig.json`
- Use `ts-node` for running TypeScript files directly
- Backend tests can be debugged with: `cd backend && yarn test-inspect`
### Common Issues
- **Build fails**: Clear `dist/` and `app/build/` directories, then rebuild
- **Electron won't start**: Ensure `yarn build` completed successfully
- **Tests fail**: Check if MQTT broker (mosquitto) is running for integration tests
- **UI not updating**: In dev mode, ensure webpack-dev-server is running
## Deployment and Packaging
### Creating Releases
```bash
# Prepare release (updates version, changelog)
yarn prepare-release
# Package the application for distribution
yarn package
# Package with Docker (for consistent builds)
yarn package-with-docker
```
### Release Workflow
- **Beta releases**: Create PR to `beta` branch with "feat:" or "fix:" commits
- **Production releases**: Create PR to `release` branch with "feat:" or "fix:" commits
- Semantic release automatically handles versioning and changelog
- Builds are created for Windows, macOS, and Linux
### Build Artifacts
- Output directory: `build/`
- Supported formats: DMG (macOS), EXE/NSIS (Windows), AppImage/Snap (Linux), AppX (Windows Store)
- Code signing is configured via `res/` directory certificates and provisioning profiles
## Important Notes
- Always run `yarn build` before starting the application
- The app uses Electron (see `package.json` for version)
- MQTT communication is handled via [mqttjs](https://github.com/mqttjs/MQTT.js)
- All code changes should pass linting (`yarn lint`)
- Node.js version requirement: >= 20
- The project uses workspace-like structure with separate package.json files for app and backend
+39
View File
@@ -0,0 +1,39 @@
name: Copilot Agent Setup
on:
workflow_call:
jobs:
setup:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Cache yarn dependencies
uses: actions/cache@v4
id: yarn-cache
with:
path: |
${{ steps.yarn-cache-dir-path.outputs.dir }}
node_modules
app/node_modules
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install dependencies
run: yarn install --frozen-lockfile
- name: Build project
run: yarn build
+99 -2
View File
@@ -12,13 +12,58 @@ jobs:
options: --user root
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Install Packages
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Test
run: yarn test
- name: UI-Test
ui-tests:
runs-on: ubuntu-latest
container:
image: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
volumes:
- ./:/app
options: --user root
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Install Packages
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Run UI Tests
timeout-minutes: 10
run: ./scripts/runUiTests.sh
- name: Upload Test Screenshots
if: always()
uses: actions/upload-artifact@v4
with:
name: ui-test-screenshots
path: |
test-screenshot-*.png
retention-days: 30
demo-video:
runs-on: ubuntu-latest
container:
image: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
volumes:
- ./:/app
options: --user root
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Install Packages
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Generate Demo Video
run: yarn ui-test
- name: Post-processing
run: ./scripts/prepareVideo.sh
@@ -35,4 +80,56 @@ jobs:
- name: Show URL
run: echo '${{ steps.upload.outputs.file-url }}'
id: artifact-upload-step
- run: echo '![test](${{ steps.upload.outputs.file-url }})' >> $GITHUB_STEP_SUMMARY
- run: echo '<picture><img src="${{ steps.upload.outputs.file-url }}"></picture>' >> $GITHUB_STEP_SUMMARY
test-browser:
runs-on: ubuntu-latest
services:
mosquitto:
image: eclipse-mosquitto:2
ports:
- 1883:1883
options: >-
--health-cmd "mosquitto_sub -t '$SYS/#' -C 1"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Dependencies
run: yarn install --frozen-lockfile
- name: Build Browser Mode
run: yarn build:server
- name: Test App
run: yarn test:app
- name: Test Backend
run: yarn test:backend
- name: Start Server in Background
run: |
yarn start:server &
echo $! > server.pid
env:
MQTT_EXPLORER_USERNAME: test
MQTT_EXPLORER_PASSWORD: test123
PORT: 3000
- name: Wait for Server
run: |
timeout 30 bash -c 'until curl -f http://localhost:3000; do sleep 1; done'
- name: Browser Smoke Test
run: |
# Test server is running
curl -f http://localhost:3000 || exit 1
echo "Browser mode server is running successfully"
- name: Stop Server
if: always()
run: |
if [ -f server.pid ]; then
kill $(cat server.pid) || true
rm server.pid
fi
+8
View File
@@ -9,3 +9,11 @@ test.png
.awcache
.scannerwork
screen*.png
# MCP introspection artifacts
mqtt-explorer-mcp-screenshot.png
screenshot-mcp-*.png
test-mcp-introspection.js
/data
test-screenshot-*.png
+193
View File
@@ -0,0 +1,193 @@
# Browser Mode Documentation
MQTT Explorer now supports running as a web application served by a Node.js server, in addition to the existing Electron desktop app.
## Running in Browser Mode
### Quick Start
1. Build the application for browser mode:
```bash
yarn build:server
```
2. Start the server:
```bash
yarn start:server
```
3. Open your browser and navigate to `http://localhost:3000`
4. You'll be prompted to log in with credentials that were generated on server startup.
### Development Mode
To run in development mode with hot reload:
```bash
yarn dev:server
```
This starts both the webpack dev server and the backend server.
## Authentication
### Environment Variables
You can set custom authentication credentials using environment variables:
```bash
export MQTT_EXPLORER_USERNAME=admin
export MQTT_EXPLORER_PASSWORD=secretpassword
yarn start:server
```
### Generated Credentials
If no environment variables are set, the server will generate credentials on first startup and save them to `data/credentials.json`. The generated credentials will be printed to the console:
```
============================================================
Generated new credentials:
Username: user-abc123
Password: 123e4567-e89b-12d3-a456-426614174000
============================================================
Please save these credentials. They will be persisted to:
/path/to/data/credentials.json
============================================================
```
## Features
### Certificate Upload
In browser mode, certificate files are uploaded directly through the browser using the HTML5 File API. The certificates are:
- Read client-side as base64
- Stored in the connection configuration
- Used when establishing MQTT connections
### Data Storage
In browser mode, all data is stored on the server:
- Credentials: `data/credentials.json`
- Uploaded certificates: `data/certificates/`
- File uploads: `data/uploads/`
### Port Configuration
The default port is 3000. You can change it using the `PORT` environment variable:
```bash
PORT=8080 yarn start:server
```
## Architecture
### Client-Server Communication
- **Electron Mode**: Uses Electron IPC for communication between renderer and main process
- **Browser Mode**: Uses Socket.io WebSockets for real-time communication between browser and server
The application automatically detects the environment and uses the appropriate transport layer.
### Event Bus Abstraction
Both Electron IPC and Socket.io implement the same `EventBusInterface`, allowing the application code to work seamlessly in both modes without modification.
## Differences from Electron Mode
### Browser Mode Limitations
1. **File System Access**: Limited to server-side operations
2. **Native Dialogs**: File selection uses browser file input instead of native dialogs
3. **Auto-Updates**: Not available in browser mode
4. **Tray Icon**: Not available in browser mode
### Browser Mode Advantages
1. **No Installation**: Access from any browser
2. **Cross-Platform**: Works on any device with a modern browser
3. **Remote Access**: Can be deployed on a server for remote access
4. **Multi-User**: Can support authentication for multiple users
## Security Considerations
1. **HTTPS**: For production, always use HTTPS to encrypt credentials and MQTT data
2. **Authentication**: Keep credentials secure and rotate them regularly
3. **Network**: Ensure the server is on a trusted network or behind a firewall
4. **Environment Variables**: Use environment variables for production credentials, not the generated ones
## Deployment
For production deployment:
1. Build the application:
```bash
yarn build:server
```
2. Set environment variables:
```bash
export MQTT_EXPLORER_USERNAME=your_username
export MQTT_EXPLORER_PASSWORD=your_secure_password
export PORT=3000
```
3. Start the server:
```bash
yarn start:server
```
4. Use a reverse proxy (nginx, Apache) to add HTTPS and additional security features
## Troubleshooting
### Debugging
Enable detailed Socket.IO connection and lifecycle debugging:
```bash
DEBUG=mqtt-explorer:socketio* yarn start:server
```
Available debug namespaces:
- `mqtt-explorer:socketio` - General Socket.IO events and metrics
- `mqtt-explorer:socketio:connect` - Client connection events
- `mqtt-explorer:socketio:disconnect` - Client disconnection and cleanup
- `mqtt-explorer:socketio:subscriptions` - Subscription lifecycle tracking
- `mqtt-explorer:socketio:connections` - MQTT connection ownership
This will log:
- Client connect/disconnect events
- Subscription counts per socket
- MQTT connection ownership tracking
- Memory leak detection metrics (subscriptions, handlers, connections)
Example output:
```
mqtt-explorer:socketio:connect Client connected: abc123de
mqtt-explorer:socketio [connect] clients=1 subscriptions=8 mqttConns=0 | socket[abc123de]: subs=8 conns=0
mqtt-explorer:socketio:connections Connection my-mqtt owned by socket abc123de (total: 1)
mqtt-explorer:socketio:disconnect Client disconnected: abc123de
mqtt-explorer:socketio:subscriptions Removed 8 subscriptions for socket abc123de
mqtt-explorer:socketio [disconnect] clients=0 subscriptions=0 mqttConns=0 | socket[abc123de]: subs=0 conns=0
```
### Authentication Fails
1. Check the console output for the generated credentials
2. Clear browser session storage: `sessionStorage.clear()` in browser console
3. Restart the server to regenerate credentials
### Connection Issues
1. Check that the server is running: `http://localhost:3000`
2. Check browser console for Socket.io connection errors
3. Verify firewall rules allow the port
### Certificate Upload Issues
In browser mode, certificates are handled differently:
- Use the file upload button to select certificate files
- Files are read and encoded client-side
- Large certificate files (>16KB) will be rejected
+149
View File
@@ -0,0 +1,149 @@
# CI/CD Pipeline Documentation
## Overview
MQTT Explorer uses GitHub Actions for continuous integration and testing. The pipeline tests both Electron (desktop) and browser modes.
## Workflows
### Test Workflow (`.github/workflows/tests.yml`)
This workflow runs on pull requests to `master`, `beta`, and `release` branches.
#### Jobs
##### 1. `test` - Electron Mode Tests
Tests the traditional Electron desktop application:
- **Environment**: Custom Docker container (`ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest`)
- **Steps**:
1. Install dependencies with frozen lockfile
2. Build the Electron application
3. Run unit tests (app + backend)
4. Run UI tests with video recording
5. Upload test video to S3
6. Display test results in GitHub summary
**Artifacts**: UI test video (GIF format) uploaded to S3
##### 2. `test-browser` - Browser Mode Tests
Tests the new browser/server mode:
- **Environment**: Ubuntu latest with Node.js 20
- **Services**:
- **Mosquitto MQTT Broker**: Eclipse Mosquitto v2 on port 1883
- Health checks enabled
- Anonymous connections allowed
- **Steps**:
1. Setup Node.js 20
2. Install dependencies
3. Build browser mode (`yarn build:server`)
4. Run unit tests (app + backend)
5. Start server in background with test credentials
6. Wait for server to be ready
7. Run browser smoke tests
8. Clean up server process
**Environment Variables**:
- `MQTT_EXPLORER_USERNAME=test`
- `MQTT_EXPLORER_PASSWORD=test123`
- `PORT=3000`
## Test Commands
The following npm scripts are used in CI/CD:
```bash
# Unit tests
yarn test # Run all tests (app + backend)
yarn test:app # Frontend tests only
yarn test:backend # Backend tests only
# Build
yarn build # Build Electron mode
yarn build:server # Build browser mode
# UI Tests (Electron only)
yarn ui-test # Run UI tests with video recording
```
## Adding New Tests
### For Electron Mode
Add tests to the `test` job. UI tests should be added to the test suite that `yarn ui-test` runs.
### For Browser Mode
Browser-specific tests should:
1. Use the pre-configured Mosquitto service
2. Connect to `mqtt://mosquitto:1883`
3. Test server endpoints at `http://localhost:3000`
Example:
```yaml
- name: Browser Integration Test
run: |
# Test MQTT connection through server
curl -X POST http://localhost:3000/api/test
```
## Local Testing
### Electron Mode
```bash
yarn build
yarn test
yarn ui-test
```
### Browser Mode
```bash
# Start Mosquitto in Docker
docker run -d -p 1883:1883 eclipse-mosquitto:2
# Build and test
yarn build:server
yarn test
# Start server
MQTT_EXPLORER_USERNAME=test MQTT_EXPLORER_PASSWORD=test123 yarn start:server
# Run manual tests
curl http://localhost:3000
```
## GitHub Codespaces / Devcontainer
The repository includes a devcontainer configuration that automatically sets up:
- Node.js 20
- MQTT broker (Mosquitto)
- All development dependencies
- Port forwarding for development
See [.devcontainer/README.md](.devcontainer/README.md) for details.
## Troubleshooting
### Browser Tests Failing
1. **Server won't start**: Check if port 3000 is already in use
2. **MQTT connection fails**: Ensure Mosquitto service is healthy
3. **Timeout errors**: Increase timeout in "Wait for Server" step
### Electron Tests Failing
1. **UI tests timeout**: Check if the Docker container has display access
2. **Build fails**: Verify all dependencies are in yarn.lock
## Future Improvements
- [ ] Add E2E browser tests with Playwright
- [ ] Test WebSocket connections in browser mode
- [ ] Add performance benchmarks
- [ ] Test with different MQTT broker versions
- [ ] Add security scanning for browser mode
+39 -24
View File
@@ -1,10 +1,10 @@
## creative commons
When redistributing, the attribution page may not be altered or made less accessible without explicit approval.
# Attribution-NoDerivatives 4.0 International
# Creative Commons Attribution-ShareAlike 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
**Using Creative Commons Public Licenses**
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
@@ -12,31 +12,37 @@ Creative Commons public licenses provide a standard set of terms and conditions
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NoDerivatives 4.0 International Public License
## Creative Commons Attribution-ShareAlike 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NoDerivatives 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
### Section 1 Definitions.
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
b. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
c. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
d. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
e. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
f. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
g. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
h. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
i. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
j. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
### Section 2 Scope.
@@ -46,7 +52,7 @@ a. ___License grant.___
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce and reproduce, but not Share, Adapted Material.
B. produce, reproduce, and Share Adapted Material.
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
@@ -58,7 +64,9 @@ a. ___License grant.___
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
B. __Additional offer from the Licensor Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapters License You apply.
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
@@ -76,7 +84,7 @@ Your exercise of the Licensed Rights is expressly made subject to the following
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
@@ -94,19 +102,27 @@ a. ___Attribution.___
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
b. ___ShareAlike.___
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
1. The Adapters License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database, provided You do not Share Adapted Material;
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
@@ -152,7 +168,6 @@ c. No term or condition of this Public License will be waived and no failure to
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
>
> Creative Commons may be contacted at creativecommons.org
> Creative Commons may be contacted at creativecommons.org.
+62 -16
View File
@@ -18,8 +18,22 @@ Downloads can be found at the link above.
This page is dedicated to its development.
Pull-Requests and error reports are welcome.
## Quick Start with GitHub Codespaces
The fastest way to start developing is with GitHub Codespaces:
1. Click the green "Code" button above
2. Select "Codespaces" tab
3. Click "Create codespace on [branch]"
4. Wait for the environment to set up (includes Node.js and MQTT broker)
5. Run `yarn dev:server` to start development
The devcontainer includes a pre-configured MQTT broker and all development tools. See [.devcontainer/README.md](.devcontainer/README.md) for details.
## Run from sources
### Desktop Application (Electron)
```bash
npm install -g yarn
yarn
@@ -27,8 +41,23 @@ yarn build
yarn start
```
### Browser Mode (Web Application)
MQTT Explorer can also run as a web application served by a Node.js server:
```bash
npm install -g yarn
yarn
yarn build:server
yarn start:server
```
Then open your browser to `http://localhost:3000`. For more details, see [BROWSER_MODE.md](BROWSER_MODE.md).
## Develop
### Desktop Application
Launch Application
```bash
@@ -37,32 +66,49 @@ yarn
yarn dev
```
### Browser Mode
Launch in development mode with hot reload:
```bash
npm install -g yarn
yarn
yarn dev:server
```
The `app` directory contains all the rendering logic, the `backend` directory currently contains the models, tests, connection management, `src` contains all the electron bindings. [mqttjs](https://github.com/mqttjs/MQTT.js) is used to facilitate communication to MQTT brokers.
## Automated Tests
To achieve a reliable product automated tests run regularly on travis.
To achieve a reliable product automated tests run regularly on CI.
- Data model
- MQTT integration
- UI-Tests (The demo is a recorded ui test)
- **Data model tests**: `yarn test:backend`
- **App tests**: `yarn test:app`
- **UI test suite**: `yarn test:ui` (independent, deterministic tests)
- **Demo video**: `yarn ui-test` (UI test recording for documentation)
## Run UI-tests
### Run UI Test Suite
A [mosquitto](https://mosquitto.org/) MQTT broker is required to run the ui-tests.
Run tests with
The UI test suite validates core functionality through automated browser tests. Each test is independent and deterministic.
```bash
# Run chromedriver in a separate terminal session
./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 --verbose
# Run with automated setup (recommended)
./scripts/runUiTests.sh
# Or run directly (requires manual MQTT broker setup)
yarn build
yarn test:ui
```
Compile and execute tests
See [docs/UI-TEST-SUITE.md](docs/UI-TEST-SUITE.md) for more details.
### Run Demo Video Generation
A [mosquitto](https://mosquitto.org/) MQTT broker is required to generate the demo video.
```bash
npm run build
node dist/src/spec/webdriverio.js
yarn build
yarn ui-test
```
## Create a release
@@ -99,7 +145,7 @@ The readme will be generated from the docs.
## License
![CC-BY-ND 4.0](https://img.shields.io/badge/License-CC%20BY--ND%204.0-blue.svg)
[CC-BY-ND 4.0](https://creativecommons.org/licenses/by-nd/4.0/)
![CC-BY-Nc 4.0](https://img.shields.io/badge/License-CC%20BY--NC%204.0-blue.svg)
[CC-BY-Nc 4.0](https://creativecommons.org/licenses/by-nC/4.0/)
The license is a little restrictive to distributing derived work, this may change in the future if the interest arises or more people work on this project.
The license allows for anyone to adapt, share, and redistribute the material, as long as it is non-commercial.
+13 -9
View File
@@ -10,7 +10,7 @@
"mochatest": "mocha --require ts-node/register --require source-map-support/register --recursive src/*/**/*.spec.ts"
},
"engines": {
"node": ">=18"
"node": ">=20"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -28,6 +28,7 @@
"d3-shape": "^1.3.5",
"diff": "^4.0.1",
"dot-prop": "^5.0.0",
"events": "^3.3.0",
"get-value": "^3.0.1",
"immutable": "^4.0.0-rc.12",
"in-viewport": "^3.6.0",
@@ -37,7 +38,9 @@
"lodash.throttle": "^4.1.1",
"moving-average": "^1.0.0",
"number-abbreviate": "^2.0.0",
"os-browserify": "^0.3.0",
"parse-duration": "^0.1.1",
"path-browserify": "^1.0.1",
"prismjs": "^1.15.0",
"react": "^16.11",
"react-ace": "^8",
@@ -51,7 +54,8 @@
"redux-batched-actions": "0.5",
"redux-thunk": "^2.3.0",
"sha1": "^1.1.1",
"socket.io-client": "^2.2.0",
"socket.io-client": "^4.8.1",
"url": "^0.11.4",
"uuid": "7"
},
"devDependencies": {
@@ -66,7 +70,7 @@
"@types/react-redux": "^7.0.9",
"@types/react-resize-detector": "^4.0.1",
"@types/sha1": "^1.1.1",
"@types/socket.io-client": "^1.4.32",
"@types/socket.io-client": "^3.0.0",
"@types/uuid": "^7.0.2",
"@types/vis": "^4.21.9",
"chai": "^4.2.0",
@@ -80,14 +84,14 @@
"node-loader": "^0.6.0",
"source-map-loader": "^0.2.4",
"style-loader": "^1",
"ts-loader": "^9.2.6",
"ts-loader": "^9.5.1",
"typescript": "^4.5.5",
"webpack": "^5.69.1",
"webpack": "^5.91.0",
"webpack-bundle-analyzer": "^4.5.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
},
"peerDependencies": {
"electron": "^29"
"electron": "^39"
}
}
}
+2 -3
View File
@@ -9,12 +9,11 @@ import {
import { default as persistentStorage, StorageIdentifier } from '../utils/PersistentStorage'
import { Dispatch } from 'redux'
import { showError } from './Global'
import { promises as fsPromise } from 'fs'
import * as path from 'path'
import { ActionTypes, Action } from '../reducers/ConnectionManager'
import { Subscription } from '../../../backend/src/DataSource/MqttSource'
import { connectionsMigrator } from './migrations/Connection'
import { rendererRpc } from '../../../events'
import { rendererRpc, readFromFile } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
export interface ConnectionDictionary {
@@ -81,7 +80,7 @@ async function openCertificate(): Promise<CertificateParameters> {
throw rejectReasons.noCertificateSelected
}
const data = await fsPromise.readFile(selectedFile)
const data = await rendererRpc.call(readFromFile, { filePath: selectedFile })
if (data.length > 16_384 || data.length < 64) {
throw rejectReasons.certificateSizeDoesNotMatch
}
+49 -2
View File
@@ -2,7 +2,10 @@ import { Action, ActionTypes } from '../reducers/Publish'
import { AppState } from '../reducers'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Dispatch } from 'redux'
import { makePublishEvent, rendererEvents } from '../../../events'
import { MqttMessage, makePublishEvent, rendererEvents, rendererRpc, readFromFile } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
import { showError } from './Global'
import { Base64 } from 'js-base64'
export const setTopic = (topic?: string): Action => {
return {
@@ -11,6 +14,50 @@ export const setTopic = (topic?: string): Action => {
}
}
export const openFile =
(encoding: 'utf8' = 'utf8') =>
async (dispatch: Dispatch<any>, getState: () => AppState) => {
try {
const file = await getFileContent(encoding)
if (file) {
dispatch(setPayload(file.data))
}
} catch (error) {
dispatch(showError(error))
}
}
type FileParameters = {
name: string
data: string
}
async function getFileContent(encoding: string): Promise<FileParameters | undefined> {
const rejectReasons = {
noFileSelected: 'No file selected',
errorReadingFile: 'Error reading file',
}
const { canceled, filePaths } = await rendererRpc.call(makeOpenDialogRpc(), {
properties: ['openFile'],
securityScopedBookmarks: true,
})
if (canceled) {
return
}
const selectedFile = filePaths[0]
if (!selectedFile) {
throw rejectReasons.noFileSelected
}
try {
const data = await rendererRpc.call(readFromFile, { filePath: selectedFile, encoding })
return { name: selectedFile, data: data.toString(encoding) }
} catch (error) {
throw rejectReasons.errorReadingFile
}
}
export const setPayload = (payload?: string): Action => {
return {
payload,
@@ -41,7 +88,7 @@ export const publish = (connectionId: string) => (dispatch: Dispatch<Action>, ge
}
const publishEvent = makePublishEvent(connectionId)
const mqttMessage = {
const mqttMessage: Partial<MqttMessage> = {
topic,
payload: state.publish.payload ? Base64Message.fromString(state.publish.payload) : null,
retain: state.publish.retain,
+10 -9
View File
@@ -1,5 +1,5 @@
import * as q from '../../../backend/src/Model'
import { ActionTypes, SettingsStateModel, TopicOrder } from '../reducers/Settings'
import { ActionTypes, SettingsStateModel, TopicOrder, ValueRendererDisplayMode } from '../reducers/Settings'
import { AppState } from '../reducers'
import { autoExpandLimitSet } from '../components/SettingsDrawer/Settings'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
@@ -68,13 +68,14 @@ export const selectTopicWithMouseOver = (doSelect: boolean) => (dispatch: Dispat
dispatch(storeSettings())
}
export const setValueDisplayMode = (valueRendererDisplayMode: 'diff' | 'raw') => (dispatch: Dispatch<any>) => {
dispatch({
valueRendererDisplayMode,
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
})
dispatch(storeSettings())
}
export const setValueDisplayMode =
(valueRendererDisplayMode: ValueRendererDisplayMode) => (dispatch: Dispatch<any>) => {
dispatch({
valueRendererDisplayMode,
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
})
dispatch(storeSettings())
}
export const toggleHighlightTopicUpdates = () => (dispatch: Dispatch<any>) => {
dispatch({
@@ -117,7 +118,7 @@ export const filterTopics = (filterStr: string) => (dispatch: Dispatch<any>, get
const messageMatches =
node.message &&
node.message.payload &&
Base64Message.toUnicodeString(node.message.payload).toLowerCase().indexOf(filterStr) !== -1
node.message.payload.toUnicodeString().toLowerCase().indexOf(filterStr) !== -1
return Boolean(messageMatches)
}
+2 -7
View File
@@ -33,13 +33,8 @@ const debouncedSelectTopic = debounce(
setTopicDispatch = setTopic(topic.path())
}
if (previouslySelectedTopic && previouslySelectedTopic.viewModel) {
previouslySelectedTopic.viewModel.setSelected(false)
}
if (topic.viewModel) {
topic.viewModel.setSelected(true)
}
previouslySelectedTopic?.viewModel?.setSelected(false)
topic.viewModel?.setSelected(true)
const selectTreeTopicDispatch = {
selectedTopic: topic,
+64
View File
@@ -0,0 +1,64 @@
import * as React from 'react'
import { LoginDialog } from './LoginDialog'
interface BrowserAuthWrapperProps {
children: React.ReactNode
}
const isBrowserMode =
typeof window !== 'undefined' && (typeof process === 'undefined' || process.env?.BROWSER_MODE === 'true')
export function BrowserAuthWrapper(props: BrowserAuthWrapperProps) {
const [isAuthenticated, setIsAuthenticated] = React.useState(false)
const [loginError, setLoginError] = React.useState<string | undefined>()
const [showLogin, setShowLogin] = React.useState(false)
React.useEffect(() => {
if (!isBrowserMode) {
// Not in browser mode, skip authentication
setIsAuthenticated(true)
return
}
// Check if already authenticated
const username = sessionStorage.getItem('mqtt-explorer-username')
const password = sessionStorage.getItem('mqtt-explorer-password')
if (username && password) {
// Try to use stored credentials
setIsAuthenticated(true)
} else {
// Show login dialog
setShowLogin(true)
}
}, [])
const handleLogin = async (username: string, password: string) => {
try {
// Store credentials in session storage
sessionStorage.setItem('mqtt-explorer-username', username)
sessionStorage.setItem('mqtt-explorer-password', password)
// The socket will use these credentials on next connection
setIsAuthenticated(true)
setShowLogin(false)
setLoginError(undefined)
// Reload to reinitialize socket with new auth
window.location.reload()
} catch (error) {
setLoginError('Login failed. Please check your credentials.')
}
}
if (!isBrowserMode) {
// Not in browser mode, render children directly
return <>{props.children}</>
}
if (!isAuthenticated) {
return <LoginDialog open={showLogin} onLogin={handleLogin} error={loginError} />
}
return <>{props.children}</>
}
@@ -114,6 +114,7 @@ function TopicChart(props: Props) {
</div>
</div>
<TopicPlot
node={props.treeNode ? props.treeNode : undefined}
color={props.parameters.color}
interpolation={props.parameters.interpolation}
timeInterval={props.parameters.timeRange ? props.parameters.timeRange.until : undefined}
@@ -0,0 +1,140 @@
import * as React from 'react'
import ClearAdornment from '../helper/ClearAdornment'
import Lock from '@material-ui/icons/Lock'
import { bindActionCreators } from 'redux'
import { Button, Theme, Tooltip, Typography } from '@material-ui/core'
import { CertificateParameters, ConnectionOptions } from '../../model/ConnectionOptions'
import { CertificateTypes } from '../../actions/ConnectionManager'
import { connect } from 'react-redux'
import { connectionManagerActions } from '../../actions'
import { withStyles } from '@material-ui/styles'
import { rendererRpc } from '../../../../events'
import { RpcEvents } from '../../../../events/EventsV2'
function BrowserCertificateFileSelection(props: {
certificateType: CertificateTypes
title: string
certificate?: CertificateParameters
classes: any
actions: {
connectionManager: typeof connectionManagerActions
}
connection: ConnectionOptions
}) {
const fileInputRef = React.useRef<HTMLInputElement>(null)
const clearCertificate = React.useCallback(() => {
props.actions.connectionManager.updateConnection(props.connection.id, {
[props.certificateType]: undefined,
})
}, [props.connection, props.certificateType])
const handleFileSelect = React.useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) {
return
}
try {
// Read file content
const reader = new FileReader()
reader.onload = async e => {
const content = e.target?.result
if (typeof content === 'string') {
// Convert to base64
const base64Data = content.split(',')[1] || content
// Upload via IPC instead of HTTP POST
const result = await rendererRpc.call(RpcEvents.uploadCertificate, {
filename: file.name,
data: base64Data,
})
// Create certificate parameters
const certificate: CertificateParameters = {
name: result.name,
data: result.data,
}
// Update connection
props.actions.connectionManager.updateConnection(props.connection.id, {
[props.certificateType]: certificate,
})
}
}
reader.readAsDataURL(file)
} catch (error) {
console.error('Error uploading certificate:', error)
}
// Reset input
if (fileInputRef.current) {
fileInputRef.current.value = ''
}
},
[props.connection.id, props.certificateType, props.actions.connectionManager]
)
const handleButtonClick = () => {
fileInputRef.current?.click()
}
return (
<span>
<input
ref={fileInputRef}
type="file"
accept=".pem,.crt,.cer,.key"
style={{ display: 'none' }}
onChange={handleFileSelect}
/>
<Tooltip title="Select certificate" placement="top">
<Button variant="contained" className={props.classes.button} onClick={handleButtonClick}>
<Lock /> {props.title}
</Button>
</Tooltip>
<ClearCertificate classes={props.classes} certificate={props.certificate} action={clearCertificate} />
</span>
)
}
function ClearCertificate(props: { classes: any; certificate?: CertificateParameters; action: () => void }) {
if (!props.certificate) {
return null
}
return (
<Tooltip title={props.certificate.name}>
<Typography className={props.classes.certificateName}>
<ClearAdornment action={props.action} value={props.certificate.name} />
{props.certificate.name}
</Typography>
</Tooltip>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
connectionManager: bindActionCreators(connectionManagerActions, dispatch),
},
}
}
const styles = (theme: Theme) => ({
certificateName: {
width: '100%',
height: 'calc(1em + 4px)',
overflow: 'hidden' as 'hidden',
whiteSpace: 'nowrap' as 'nowrap',
textOverflow: 'ellipsis' as 'ellipsis',
color: theme.palette.text.hint,
},
button: {
marginTop: theme.spacing(3),
marginRight: theme.spacing(2),
},
})
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(BrowserCertificateFileSelection))
@@ -1,5 +1,6 @@
import * as React from 'react'
import CertificateFileSelection from './CertificateFileSelection'
import BrowserCertificateFileSelection from './BrowserCertificateFileSelection'
import Undo from '@material-ui/icons/Undo'
import { bindActionCreators } from 'redux'
import { Button, Grid } from '@material-ui/core'
@@ -8,6 +9,11 @@ import { connectionManagerActions } from '../../actions'
import { ConnectionOptions } from '../../model/ConnectionOptions'
import { Theme, withStyles } from '@material-ui/core/styles'
// Check if we're in browser mode
const isBrowserMode =
typeof window !== 'undefined' && (typeof process === 'undefined' || process.env?.BROWSER_MODE === 'true')
const CertSelector = isBrowserMode ? BrowserCertificateFileSelection : CertificateFileSelection
interface Props {
connection: ConnectionOptions
classes: any
@@ -45,7 +51,7 @@ class Certificates extends React.PureComponent<Props, State> {
<form noValidate={true} autoComplete="off">
<Grid container={true} spacing={3}>
<Grid item={true} xs={12} className={classes.gridPadding}>
<CertificateFileSelection
<CertSelector
connection={this.props.connection}
certificate={this.props.connection.selfSignedCertificate}
title="Server Certificate (CA)"
@@ -53,7 +59,7 @@ class Certificates extends React.PureComponent<Props, State> {
/>
</Grid>
<Grid item={true} xs={12} className={classes.gridPadding}>
<CertificateFileSelection
<CertSelector
connection={this.props.connection}
certificate={this.props.connection.clientCertificate}
title="Client Certificate"
@@ -61,7 +67,7 @@ class Certificates extends React.PureComponent<Props, State> {
/>
</Grid>
<Grid item={true} xs={12} className={classes.gridPadding}>
<CertificateFileSelection
<CertSelector
connection={this.props.connection}
certificate={this.props.connection.clientKey}
title="Client Key"
@@ -1,26 +1,40 @@
import React from 'react'
import React, { useCallback } from 'react'
import { connect } from 'react-redux'
import { ListItem, Typography } from '@material-ui/core'
import { toMqttConnection, ConnectionOptions } from '../../../model/ConnectionOptions'
import { withStyles, Theme } from '@material-ui/core/styles'
import { bindActionCreators } from 'redux'
import { connectionManagerActions } from '../../../actions'
import { connectionActions, connectionManagerActions } from '../../../actions'
export interface Props {
connection: ConnectionOptions
actions: any
actions: {
connection: any
connectionManager: any
}
selected: boolean
classes: any
}
const ConnectionItem = (props: Props) => {
const connect = useCallback(() => {
const mqttOptions = toMqttConnection(props.connection)
if (mqttOptions) {
props.actions.connection.connect(mqttOptions, props.connection.id)
}
}, [props.connection, props])
const connection = props.connection.host && toMqttConnection(props.connection)
return (
<ListItem
button={true}
selected={props.selected}
style={{ display: 'block' }}
onClick={() => props.actions.selectConnection(props.connection.id)}
onClick={() => props.actions.connectionManager.selectConnection(props.connection.id)}
onDoubleClick={() => {
props.actions.connectionManager.selectConnection(props.connection.id)
connect()
}}
>
<Typography className={props.classes.name}>{props.connection.name || 'mqtt broker'}</Typography>
<Typography className={props.classes.details}>{connection && connection.url}</Typography>
@@ -30,10 +44,12 @@ const ConnectionItem = (props: Props) => {
export const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(connectionManagerActions, dispatch),
actions: {
connection: bindActionCreators(connectionActions, dispatch),
connectionManager: bindActionCreators(connectionManagerActions, dispatch),
},
}
}
export const connectionItemStyle = (theme: Theme) => ({
name: {
width: '100%',
@@ -7,7 +7,7 @@ import { connect } from 'react-redux'
import { connectionManagerActions } from '../../../actions'
import { ConnectionOptions } from '../../../model/ConnectionOptions'
import { KeyCodes } from '../../../utils/KeyCodes'
import { List, ListSubheader } from '@material-ui/core'
import { List } from '@material-ui/core'
import { Theme, withStyles } from '@material-ui/core/styles'
import { useGlobalKeyEventHandler } from '../../../effects/useGlobalKeyEventHandler'
+253 -20
View File
@@ -6,40 +6,219 @@ interface State {
enabled: boolean
target: { x: number; y: number }
position: { x: number; y: number }
stepSizeX: number
stepSizeY: number
startPosition: { x: number; y: number }
startTime: number
duration: number
clicking: boolean
jitterSeed: number
overshootTarget: { x: number; y: number } | null
isOvershootCorrection: boolean
}
class Demo extends React.Component<{ classes: any }, State> {
private timer: any
private clickTimer: any
private frameInterval = 20
private readonly correctionDelayMs = 50 // Delay before overshoot correction starts
constructor(props: any) {
super(props)
this.state = { enabled: false, target: { x: 0, y: 0 }, position: { x: 0, y: 0 }, stepSizeX: 1, stepSizeY: 1 }
this.state = {
enabled: false,
target: { x: 0, y: 0 },
position: { x: 0, y: 0 },
startPosition: { x: 0, y: 0 },
startTime: 0,
duration: 0,
clicking: false,
jitterSeed: Math.random(),
overshootTarget: null,
isOvershootCorrection: false,
}
}
private moveCloser(steps: number = 0) {
const steSizeX = Math.min(this.state.stepSizeX, Math.abs(this.state.position.x - this.state.target.x))
const steSizeY = Math.min(this.state.stepSizeY, Math.abs(this.state.position.y - this.state.target.y))
const dirX = this.state.position.x > this.state.target.x ? -1 : 1
const dirY = this.state.position.y > this.state.target.y ? -1 : 1
/**
* Generates a seeded random value using a simple LCG algorithm
* Better quality than sin-based PRNG for consistent jitter patterns
*/
private seededRandom(seed: number): number {
// Linear Congruential Generator with common constants
const a = 1664525
const c = 1013904223
const m = Math.pow(2, 32)
const x = (a * seed + c) % m
return x / m
}
if (steSizeX <= 0.1 && steSizeY <= 0.1) {
this.timer && clearTimeout(this.timer)
return
/**
* Adds human-like micro-movements to the cursor position
* Small random offsets that don't affect the overall path significantly
*/
private addJitter(x: number, y: number, progress: number): { x: number; y: number } {
// Jitter is strongest in the middle of the movement (more natural)
const jitterStrength = Math.sin(progress * Math.PI) * 2 // 0 at start/end, max at middle
// Use progress to vary the seed for different jitter at each frame
const seed1 = this.state.jitterSeed * 1000 + progress * 100
const seed2 = this.state.jitterSeed * 2000 + progress * 150
const jitterX = (this.seededRandom(seed1) - 0.5) * jitterStrength
const jitterY = (this.seededRandom(seed2) - 0.5) * jitterStrength
return {
x: x + jitterX,
y: y + jitterY,
}
}
/**
* Cubic bezier easing function for natural-looking mouse movement
* Uses control points (0.25, 0.75) for a smooth ease-in-out curve
*/
private cubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number {
const u = 1 - t
return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3
}
/**
* Easing function that creates a smooth acceleration and deceleration
* This makes the mouse movement appear more human-like
*/
private easeInOutCubic(t: number): number {
// Cubic bezier approximation for ease-in-out
return this.cubicBezier(t, 0, 0.25, 0.75, 1)
}
/**
* Calculates an overshoot target for more realistic human-like movement
* Returns null if no overshoot, or a point slightly past the target
*/
private calculateOvershootTarget(
startX: number,
startY: number,
targetX: number,
targetY: number
): { x: number; y: number } | null {
const dx = targetX - startX
const dy = targetY - startY
const distance = Math.sqrt(dx * dx + dy * dy)
// Don't overshoot for very short distances (less than 10px)
if (distance < 10) {
return null
}
// 30% chance of overshoot for natural variation
if (this.seededRandom(this.state.jitterSeed * 3) > 0.3) {
return null
}
// Overshoot by 2-8% of the distance
const overshootPercent = 0.02 + this.seededRandom(this.state.jitterSeed * 4) * 0.06
const overshootDistance = distance * overshootPercent
// Overshoot in the direction of movement
const dirX = dx / distance
const dirY = dy / distance
return {
x: targetX + dirX * overshootDistance,
y: targetY + dirY * overshootDistance,
}
}
private moveCloser() {
const elapsed = Date.now() - this.state.startTime
const progress = Math.min(elapsed / (this.state.duration || 1), 1)
// Apply easing function for smooth, human-like movement timing
const easedProgress = this.easeInOutCubic(progress)
// Determine actual target (could be overshoot target or final target)
const actualTarget = this.state.overshootTarget || this.state.target
// Calculate bezier curve control points for a natural arc trajectory
// Instead of moving in a straight line, the cursor follows a curved path
const startX = this.state.startPosition.x
const startY = this.state.startPosition.y
const endX = actualTarget.x
const endY = actualTarget.y
// Create control points for a quadratic bezier curve
// The control point is offset perpendicular to the direct line, creating an arc
const dx = endX - startX
const dy = endY - startY
const distance = Math.sqrt(dx * dx + dy * dy)
// Arc height is proportional to distance (80% of distance, capped at 200px max)
// Quadrupled from original 20% to make the curve highly visible
// For overshoot correction, use smaller arc (more direct)
const arcPercent = this.state.isOvershootCorrection ? 0.3 : 0.8
const arcCap = this.state.isOvershootCorrection ? 50 : 200
const arcHeight = Math.min(distance * arcPercent, arcCap)
// Calculate perpendicular offset for the control point
const perpX = -dy / (distance || 1)
const perpY = dx / (distance || 1)
// Add slight randomness to control point to avoid perfectly predictable curves
const controlPointJitter = this.seededRandom(this.state.jitterSeed * 5) * 20 - 10
// Control point is at the midpoint, offset perpendicular to create an arc
const controlX = (startX + endX) / 2 + perpX * (arcHeight + controlPointJitter)
const controlY = (startY + endY) / 2 + perpY * (arcHeight + controlPointJitter)
// Calculate position on quadratic bezier curve: B(t) = (1-t)²P₀ + 2(1-t)tP₁ + t²P₂
const t = easedProgress
const u = 1 - t
let newX = u * u * startX + 2 * u * t * controlX + t * t * endX
let newY = u * u * startY + 2 * u * t * controlY + t * t * endY
// Add jitter for human-like micro-movements
const jittered = this.addJitter(newX, newY, progress)
newX = jittered.x
newY = jittered.y
this.setState({
position: {
x: this.state.position.x + dirX * steSizeX,
y: this.state.position.y + dirY * steSizeY,
x: newX,
y: newY,
},
})
this.timer = setTimeout(() => {
this.moveCloser(steps + 1)
}, this.frameInterval)
// Continue animation if not complete
if (progress < 1) {
// Add random delay variation (jitter in timing)
// Frame interval varies between 15-25ms for irregular movement
// Use modulo to keep seed in reasonable range
const jitterDelay = this.seededRandom((this.state.jitterSeed * 6 + elapsed) % 100000) * 10 - 5
const nextInterval = Math.max(10, this.frameInterval + jitterDelay)
this.timer = setTimeout(() => {
this.moveCloser()
}, nextInterval)
} else {
this.timer && clearTimeout(this.timer)
// If we just reached overshoot target, start correction to actual target
if (this.state.overshootTarget && !this.state.isOvershootCorrection) {
const correctionDuration = this.state.duration * 0.15 // Correction takes 15% of original time
setTimeout(() => {
this.setState({
startPosition: { x: this.state.position.x, y: this.state.position.y },
target: this.state.target, // Keep original target
overshootTarget: null, // Clear overshoot
isOvershootCorrection: true,
startTime: Date.now(),
duration: correctionDuration,
})
this.moveCloser()
}, this.correctionDelayMs)
} else {
// Reset overshoot state for next movement
this.setState({ isOvershootCorrection: false })
}
}
}
public componentDidMount() {
@@ -47,11 +226,40 @@ class Demo extends React.Component<{ classes: any }, State> {
this.setState({ enabled: true })
}
;(window as any).demo.moveMouse = (x: number, y: number, animationTime: number) => {
const stepSizeX = Math.abs(this.state.position.x - x) / (animationTime / this.frameInterval)
const stepSizeY = Math.abs(this.state.position.y - y) / (animationTime / this.frameInterval)
this.setState({ stepSizeX, stepSizeY, enabled: true, target: { x, y } })
const newJitterSeed = Math.random()
const currentPos = this.state.position
// Calculate if this movement should have overshoot
const overshoot = this.calculateOvershootTarget(currentPos.x, currentPos.y, x, y)
// If overshoot exists, adjust duration to account for correction time
// Main movement gets 85% of time, correction gets 15%
const mainDuration = overshoot ? animationTime * 0.85 : animationTime
this.setState({
enabled: true,
target: { x, y }, // Store the actual target
overshootTarget: overshoot, // May be null or an overshoot position
isOvershootCorrection: false,
startPosition: { x: currentPos.x, y: currentPos.y },
startTime: Date.now(),
duration: mainDuration,
jitterSeed: newJitterSeed,
})
this.moveCloser()
}
;(window as any).demo.clickMouse = () => {
this.setState({ clicking: true })
this.clickTimer && clearTimeout(this.clickTimer)
this.clickTimer = setTimeout(() => {
this.setState({ clicking: false })
}, 300)
}
}
public componentWillUnmount() {
this.timer && clearTimeout(this.timer)
this.clickTimer && clearTimeout(this.clickTimer)
}
public render() {
@@ -64,11 +272,26 @@ class Demo extends React.Component<{ classes: any }, State> {
top: this.state.position.y + 2,
}
return <img src={cursor} style={cursorStyle} className={this.props.classes.cursor} />
return (
<>
<img src={cursor} style={cursorStyle} className={this.props.classes.cursor} />
{this.state.clicking && <div style={cursorStyle} className={this.props.classes.clickRipple} />}
</>
)
}
}
const style = (theme: Theme) => ({
'@keyframes clickPulse': {
from: {
transform: 'scale(1)',
opacity: 1,
},
to: {
transform: 'scale(2.5)',
opacity: 0,
},
},
cursor: {
width: '32px',
height: '32px',
@@ -77,6 +300,16 @@ const style = (theme: Theme) => ({
filter: theme.palette.type === 'light' ? undefined : 'invert(100%)',
pointerEvents: 'none' as 'none',
},
clickRipple: {
width: '48px',
height: '48px',
position: 'fixed' as 'fixed',
zIndex: 1000000 - 1, // Just below cursor
borderRadius: '50%',
border: '4px solid #4CAF50',
animation: '$clickPulse 300ms ease-out',
pointerEvents: 'none' as 'none',
},
})
export default withStyles(style)(Demo)
+57
View File
@@ -0,0 +1,57 @@
import * as React from 'react'
import { Dialog, DialogTitle, DialogContent, DialogActions, TextField, Button, Typography } from '@material-ui/core'
interface LoginDialogProps {
open: boolean
onLogin: (username: string, password: string) => void
error?: string
}
export function LoginDialog(props: LoginDialogProps) {
const [username, setUsername] = React.useState('')
const [password, setPassword] = React.useState('')
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
props.onLogin(username, password)
}
return (
<Dialog open={props.open} disableEscapeKeyDown disableBackdropClick>
<form onSubmit={handleSubmit}>
<DialogTitle>Login to MQTT Explorer</DialogTitle>
<DialogContent>
{props.error && (
<Typography color="error" style={{ marginBottom: 16 }}>
{props.error}
</Typography>
)}
<TextField
autoFocus
margin="dense"
label="Username"
type="text"
fullWidth
value={username}
onChange={e => setUsername(e.target.value)}
required
/>
<TextField
margin="dense"
label="Password"
type="password"
fullWidth
value={password}
onChange={e => setPassword(e.target.value)}
required
/>
</DialogContent>
<DialogActions>
<Button type="submit" color="primary" variant="contained">
Login
</Button>
</DialogActions>
</form>
</Dialog>
)
}
@@ -123,7 +123,7 @@ function renderStat(tree: q.Tree<TopicViewModel>, stat: Stats) {
return null
}
const str = node.message.payload ? Base64Message.toUnicodeString(node.message.payload) : ''
const str = node.message.payload ? node.message.payload.toUnicodeString() : ''
let value = node.message && node.message.payload ? parseFloat(str) : NaN
value = !isNaN(value) ? abbreviate(value) : str
@@ -69,7 +69,11 @@ function ChartPreview(props: Props) {
<Popper open={open} anchorEl={chartIconRef.current} placement="left-end">
<Fade in={open} timeout={300}>
<Paper style={{ width: '300px' }}>
{open ? <TopicPlot history={props.treeNode.messageHistory} dotPath={props.literal.path} /> : <span />}
{open ? (
<TopicPlot node={props.treeNode} history={props.treeNode.messageHistory} dotPath={props.literal.path} />
) : (
<span />
)}
</Paper>
</Fade>
</Popper>
+20 -1
View File
@@ -1,5 +1,5 @@
import Editor from './Editor'
import FormatAlignLeft from '@material-ui/icons/FormatAlignLeft'
import { AttachFileOutlined, FormatAlignLeft } from '@material-ui/icons'
import Message from './Model/Message'
import Navigation from '@material-ui/icons/Navigation'
import PublishHistory from './PublishHistory'
@@ -116,6 +116,10 @@ const EditorMode = memo(function EditorMode(props: {
props.actions.setEditorMode(value)
}, [])
const openFile = useCallback(() => {
props.actions.openFile()
}, [])
const formatJson = useCallback(() => {
if (props.payload) {
try {
@@ -132,6 +136,7 @@ const EditorMode = memo(function EditorMode(props: {
<div style={{ width: '100%', lineHeight: '64px', textAlign: 'center' }}>
<EditorModeSelect value={props.editorMode} onChange={updateMode} focusEditor={props.focusEditor} />
<FormatJsonButton editorMode={props.editorMode} focusEditor={props.focusEditor} formatJson={formatJson} />
<OpenFileButton editorMode={props.editorMode} openFile={openFile} />
<div style={{ float: 'right' }}>
<PublishButton publish={props.publish} focusEditor={props.focusEditor} />
</div>
@@ -163,6 +168,20 @@ const FormatJsonButton = React.memo(function FormatJsonButton(props: {
)
})
const OpenFileButton = React.memo(function OpenFileButton(props: { editorMode: string; openFile: () => void }) {
return (
<Tooltip title="Open file">
<Fab
style={{ width: '36px', height: '36px', margin: '0 8px' }}
onClick={props.openFile}
id="sidebar-publish-open-file"
>
<AttachFileOutlined style={{ fontSize: '20px' }} />
</Fab>
</Tooltip>
)
})
const PublishButton = memo(function PublishButton(props: { publish: () => void; focusEditor: () => void }) {
const handleClickPublish = useCallback(
(e: React.MouseEvent) => {
+2 -4
View File
@@ -1,10 +1,9 @@
import * as q from '../../../../backend/src/Model'
import React, { useState, useEffect, useCallback } from 'react'
import ExpandMore from '@material-ui/icons/ExpandMore'
import NodeStats from './NodeStats'
import ValuePanel from './ValueRenderer/ValuePanel'
import { AppState } from '../../reducers'
import { Badge, ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography } from '@material-ui/core'
import { ExpansionPanelDetails } from '@material-ui/core'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { settingsActions, sidebarActions } from '../../actions'
@@ -28,7 +27,7 @@ interface Props {
}
function useUpdateNodeWhenNodeReceivesUpdates(node?: q.TreeNode<any>) {
const [lastUpdate, setLastUpdate] = useState(0)
const [, setLastUpdate] = useState(0)
const updateNode = useCallback(
throttle(() => {
setLastUpdate(node ? node.lastUpdate : 0)
@@ -52,7 +51,6 @@ function Sidebar(props: Props) {
const { classes, tree, nodePath } = props
const node = usePollingToFetchTreeNode(tree, nodePath || '')
useUpdateNodeWhenNodeReceivesUpdates(node)
// console.log(node && node.path(), tree, nodePath)
return (
<div id="Sidebar" className={classes.drawer}>
@@ -6,19 +6,19 @@ import Topic from './Topic'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { RecursiveTopicDeleteButton } from './RecursiveTopicDeleteButton'
import { sidebarActions } from '../../../actions'
import { TopicDeleteButton } from './TopicDeleteButton'
import { TopicTypeButton } from './TopicTypeButton'
import { sidebarActions } from '../../../actions'
const TopicPanel = (props: { node?: q.TreeNode<any>; actions: typeof sidebarActions }) => {
const { node } = props
console.log(node && node.path())
const copyTopic = node ? <Copy value={node.path()} /> : null
const deleteTopic = useCallback((topic?: q.TreeNode<any>, recursive: boolean = false) => {
if (!topic) {
return
}
props.actions.clearTopic(topic, recursive)
}, [])
@@ -29,11 +29,12 @@ const TopicPanel = (props: { node?: q.TreeNode<any>; actions: typeof sidebarActi
Topic {copyTopic}
<TopicDeleteButton node={node} deleteTopicAction={deleteTopic} />
<RecursiveTopicDeleteButton node={node} deleteTopicAction={deleteTopic} />
<TopicTypeButton node={node} />
</span>
<Topic node={node} />
</Panel>
),
[node, node && node.childTopicCount()]
[node, node?.childTopicCount()]
)
}
@@ -0,0 +1,103 @@
import React, { useCallback, useMemo } from 'react'
import * as q from '../../../../../backend/src/Model'
import ClickAwayListener from '@material-ui/core/ClickAwayListener'
import Grow from '@material-ui/core/Grow'
import Button from '@material-ui/core/Button'
import Paper from '@material-ui/core/Paper'
import Popper from '@material-ui/core/Popper'
import MenuItem from '@material-ui/core/MenuItem'
import MenuList from '@material-ui/core/MenuList'
import WarningRounded from '@material-ui/icons/WarningRounded'
import { MessageDecoder, decoders } from '../../../decoders'
import { Tooltip } from '@material-ui/core'
export const TopicTypeButton = (props: { node?: q.TreeNode<any> }) => {
const { node } = props
if (!node || !node.message || !node.message.payload) {
return null
}
const options = decoders.flatMap(decoder => decoder.formats.map(format => [decoder, format] as const))
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null)
const [open, setOpen] = React.useState(false)
const selectOption = useCallback(
(decoder: MessageDecoder, format: string) => {
if (!node) {
return
}
node.viewModel.decoder = { decoder, format }
setOpen(false)
},
[node]
)
const handleToggle = useCallback(
(event: React.MouseEvent<HTMLElement>) => {
event.stopPropagation()
if (open === true) {
return
}
setAnchorEl(event.currentTarget)
setOpen(prevOpen => !prevOpen)
},
[open]
)
const handleClose = useCallback((event: React.MouseEvent<Document, MouseEvent>) => {
if (anchorEl && anchorEl.contains(event.target as HTMLElement)) {
return
}
setOpen(false)
}, [])
return (
<Button onClick={handleToggle}>
{props.node?.viewModel.decoder?.format ?? props.node?.type}
<Popper open={open} anchorEl={anchorEl} role={undefined} transition>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
style={{
transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom',
}}
>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList id="topicTypeMode">
{options.map(([decoder, format], index) => (
<MenuItem
key={format}
selected={node && format === node.type}
onClick={() => selectOption(decoder, format)}
>
<DecoderStatus decoder={decoder} format={format} node={node} />
</MenuItem>
))}
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>
</Button>
)
}
function DecoderStatus({ node, decoder, format }: { node: q.TreeNode<any>; decoder: MessageDecoder; format: string }) {
const decoded = useMemo(() => {
return node.message?.payload && decoder.decode(node.message?.payload, format)
}, [node.message, decoder, format])
return decoded?.error ? (
<Tooltip title={decoded.error}>
<div>
{format} <WarningRounded />
</div>
</Tooltip>
) : (
<>{format}</>
)
}
@@ -5,7 +5,6 @@ import Copy from '../../helper/Copy'
import DateFormatter from '../../helper/DateFormatter'
import History from '../HistoryDrawer'
import TopicPlot from '../../TopicPlot'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { isPlottable } from '../CodeDiff/util'
import { TopicViewModel } from '../../../model/TopicViewModel'
import { bindActionCreators } from 'redux'
@@ -13,6 +12,8 @@ import { chartActions } from '../../../actions'
import { connect } from 'react-redux'
import CustomIconButton from '../../helper/CustomIconButton'
import { MessageId } from '../MessageId'
import { useSubscription } from '../../hooks/useSubscription'
import { useDecoder } from '../../hooks/useDecoder'
const throttle = require('lodash.throttle')
@@ -25,117 +26,100 @@ interface Props {
}
}
interface State {
displayMessage?: q.Message
anchorEl?: HTMLElement
lastUpdate: number
}
export const MessageHistory: React.FC<Props> = props => {
const [, setLastUpdate] = React.useState(Date.now())
const updateNodeThrottled = React.useCallback(
throttle(() => {
setLastUpdate
}, 300),
[]
)
class MessageHistory extends React.PureComponent<Props, State> {
private updateNode = throttle(() => {
this.setState({ lastUpdate: Date.now() })
}, 300)
useSubscription(props.node?.onMessage, updateNodeThrottled)
const decodeMessage = useDecoder(props.node)
constructor(props: any) {
super(props)
this.state = { lastUpdate: 0 }
}
private addNodeToCharts = (event: React.MouseEvent) => {
function addNodeToCharts(event: React.MouseEvent) {
event.preventDefault()
event.stopPropagation()
const { node } = this.props
const { node } = props
if (!node) {
return null
}
this.props.actions.charts.addChart({ topic: node.path() })
props.actions.charts.addChart({ topic: node.path() })
}
private displayMessage = (index: number, eventTarget: EventTarget) => {
const message = this.props.node && this.props.node.messageHistory.toArray().reverse()[index]
function displayMessage(index: number, eventTarget: EventTarget) {
const message = props.node && props.node.messageHistory.toArray().reverse()[index]
if (message) {
this.props.onSelect(message)
props.onSelect(message)
}
}
public componentWillReceiveProps(nextProps: Props) {
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
nextProps.node && nextProps.node.onMessage.subscribe(this.updateNode)
const { node } = props
if (!node) {
return null
}
public componentDidMount() {
this.props.node && this.props.node.onMessage.subscribe(this.updateNode)
}
const history = node.messageHistory.toArray()
let previousMessage: q.Message | undefined = node.message
const historyElements = [...history].reverse().map((message, idx) => {
const value = node.message ? decodeMessage(message)?.message?.format()[0] ?? null : null
public componentWillUnMount() {
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
}
public render() {
const { node } = this.props
if (!node) {
return null
}
const history = node.messageHistory.toArray()
let previousMessage: q.Message | undefined = node.message
const historyElements = [...history].reverse().map((message, idx) => {
const value = message.payload ? Base64Message.toUnicodeString(message.payload) : ''
const element = {
value,
key: `${message.messageNumber}-${message.received}`,
title: (
const element = {
value: value ?? '',
key: `${message.messageNumber}-${message.received}`,
title: (
<span>
<div style={{ float: 'left' }}>
<DateFormatter date={message.received} />
{previousMessage && previousMessage !== message ? (
<i>
(-
<DateFormatter date={message.received} intervalSince={previousMessage.received} />)
</i>
) : null}
</div>
<span>
<div style={{ float: 'left' }}>
<DateFormatter date={message.received} />
{previousMessage && previousMessage !== message ? (
<i>
(-
<DateFormatter date={message.received} intervalSince={previousMessage.received} />)
</i>
) : null}
</div>
<span>
&nbsp;
<MessageId message={message} />
</span>
<div style={{ float: 'right' }}>
<Copy value={value} />
</div>
&nbsp;
<MessageId message={message} />
</span>
),
selected: message && message === this.props.selected,
}
previousMessage = message
return element
})
<div style={{ float: 'right' }}>
<Copy value={value ?? ''} />
</div>
</span>
),
selected: message && message === props.selected,
}
previousMessage = message
return element
})
const isMessagePlottable =
node.message && node.message.payload && isPlottable(Base64Message.toUnicodeString(node.message.payload))
return (
<div>
<History
items={historyElements}
contentTypeIndicator={
isMessagePlottable ? (
<CustomIconButton
style={{ height: '22px', width: '22px' }}
onClick={this.addNodeToCharts}
tooltip="Add to chart panel"
>
<ShowChart style={{ marginTop: '-5px' }} />
</CustomIconButton>
) : undefined
}
onClick={this.displayMessage}
>
{isMessagePlottable ? <TopicPlot history={node.messageHistory} /> : null}
</History>
</div>
)
}
const value = node.message ? decodeMessage(node.message)?.message?.format()[0] ?? null : null
const isMessagePlottable = isPlottable(value)
return (
<div>
<History
items={historyElements}
contentTypeIndicator={
isMessagePlottable ? (
<CustomIconButton
style={{ height: '22px', width: '22px' }}
onClick={addNodeToCharts}
tooltip="Add to chart panel"
>
<ShowChart style={{ marginTop: '-5px' }} />
</CustomIconButton>
) : undefined
}
onClick={displayMessage}
>
{isMessagePlottable ? <TopicPlot node={node} history={node.messageHistory} /> : null}
</History>
</div>
)
}
const mapDispatchToProps = (dispatch: any) => {
@@ -144,4 +128,4 @@ const mapDispatchToProps = (dispatch: any) => {
}
}
export default connect(null, mapDispatchToProps)(MessageHistory)
export default connect(null, mapDispatchToProps)(React.memo(MessageHistory))
@@ -1,19 +1,20 @@
import * as q from '../../../../../backend/src/Model'
import ActionButtons from './ActionButtons'
import Copy from '../../helper/Copy'
import Save from '../../helper/Save'
import DateFormatter from '../../helper/DateFormatter'
import MessageHistory from './MessageHistory'
import Panel from '../Panel'
import React, { useCallback } from 'react'
import ValueRenderer from './ValueRenderer'
import { AppState } from '../../../reducers'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { bindActionCreators } from 'redux'
import { Theme, Typography, withStyles } from '@material-ui/core'
import { connect } from 'react-redux'
import { sidebarActions } from '../../../actions'
import DeleteSelectedTopicButton from './DeleteSelectedTopicButton'
import { MessageId } from '../MessageId'
import { useDecoder } from '../../hooks/useDecoder'
interface Props {
node?: q.TreeNode<any>
@@ -35,6 +36,7 @@ function RenderedValue(props: { node?: q.TreeNode<any>; compareMessage?: q.Messa
function ValuePanel(props: Props) {
const { node, compareMessage } = props
const decodeMessage = useDecoder(node)
function renderViewOptions() {
if (!props.node || !props.node.message) {
@@ -54,6 +56,16 @@ function ValuePanel(props: Props) {
)
}
const getDecodedValue = useCallback(() => {
return node?.message && decodeMessage(node.message)?.message?.toUnicodeString()
}, [node, decodeMessage])
const getData = () => {
if (node?.message && node.message.payload) {
return node.message.payload.base64Message
}
}
function messageMetaInfo() {
if (!props.node || !props.node.message) {
return null
@@ -85,14 +97,16 @@ function ValuePanel(props: Props) {
[compareMessage]
)
const copyValue =
node && node.message && node.message.payload ? (
<Copy value={Base64Message.toUnicodeString(node.message.payload)} />
) : null
const [value] =
node && node.message && node.message.payload ? node.message.payload?.format(node.type) : [null, undefined]
const copyValue = value ? <Copy getValue={getDecodedValue} /> : null
const saveValue = value ? <Save getData={getData} /> : null
return (
<Panel>
<span>Value {copyValue}</span>
<span>
Value {copyValue} {saveValue}
</span>
<span style={{ width: '100%' }}>
{renderViewOptions()}
<div style={{ marginBottom: '-8px', marginTop: '8px' }}>
@@ -1,12 +1,13 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import React, { useMemo } from 'react'
import CodeDiff from '../CodeDiff'
import { AppState } from '../../../reducers'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { connect } from 'react-redux'
import { ValueRendererDisplayMode } from '../../../reducers/Settings'
import { Fade } from '@material-ui/core'
import { Decoder } from '../../../../../backend/src/Model/Decoder'
import { useDecoder } from '../../hooks/useDecoder'
import { TopicViewModel } from '../../../model/TopicViewModel'
interface Props {
message: q.Message
@@ -15,103 +16,114 @@ interface Props {
renderMode: ValueRendererDisplayMode
}
interface State {
width: number
type Language = 'json'
function renderDiff(
treeNode: q.TreeNode<TopicViewModel>,
compareWithPreviousMessage: boolean,
current: string = '',
previous: string = '',
title?: string,
language?: Language
) {
return (
<CodeDiff
treeNode={treeNode}
previous={previous}
current={current}
title={title}
language={language}
nameOfCompareMessage={compareWithPreviousMessage ? 'selected' : 'previous'}
/>
)
}
class ValueRenderer extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { width: 0 }
}
function renderDiffMode(
treeNode: q.TreeNode<TopicViewModel>,
currentStr: string | undefined,
compareStr: string | undefined,
currentType: Language | undefined,
compareType: Language | undefined,
compareWithPreviousMessage: boolean
) {
const language = currentType === compareType && compareType === 'json' ? 'json' : undefined
private renderDiff(current: string = '', previous: string = '', title?: string, language?: 'json') {
return (
<CodeDiff
treeNode={this.props.treeNode}
previous={previous}
current={current}
title={title}
language={language}
nameOfCompareMessage={this.props.compareWith ? 'selected' : 'previous'}
/>
)
}
return <div>{renderDiff(treeNode, compareWithPreviousMessage, currentStr, compareStr, undefined, language)}</div>
}
private convertMessage(msg?: Base64Message): [string | undefined, 'json' | undefined] {
if (!msg) {
return [undefined, undefined]
}
function renderRawMode(
treeNode: q.TreeNode<TopicViewModel>,
currentStr: string | undefined,
compareStr: string | undefined,
currentType: Language | undefined,
compareType: Language | undefined,
compareWithPreviousMessage: boolean
) {
return (
<div>
{renderDiff(treeNode, compareWithPreviousMessage, currentStr, currentStr, undefined, currentType)}
<Fade in={Boolean(compareStr)} timeout={400}>
<div>
{Boolean(compareStr)
? renderDiff(treeNode, compareWithPreviousMessage, compareStr, compareStr, 'selected', compareType)
: null}
</div>
</Fade>
</div>
)
}
const str = Base64Message.toUnicodeString(msg)
try {
JSON.parse(str)
} catch (error) {
return [str, undefined]
}
export const ValueRenderer: React.FC<Props> = ({ treeNode, compareWith: compare, message, renderMode }) => {
const decodeMessage = useDecoder(treeNode)
const decodedMessage = useMemo(() => decodeMessage(message), [decodeMessage, message])
return [this.messageToPrettyJson(str), 'json']
}
const previousMessages = treeNode.messageHistory.toArray()
const previousMessage = previousMessages[previousMessages.length - 2]
const compareMessage = compare || previousMessage || message
const compareWithPreviousMessage = !!compare
private messageToPrettyJson(str: string): string | undefined {
try {
const json = JSON.parse(str)
return JSON.stringify(json, undefined, ' ')
} catch {
return undefined
}
}
const [currentStr, currentType] = useMemo(
() => decodedMessage?.message?.format(treeNode.type) ?? [],
[decodedMessage, treeNode.type]
)
const [compareStr, compareType] = useMemo(
() => decodeMessage(compareMessage)?.message?.format(treeNode.type) ?? [],
[compareMessage, decodeMessage, treeNode.type]
)
private renderRawMode(message: q.Message, compare?: q.Message) {
if (!message.payload) {
return
}
const [value, valueLanguage] = this.convertMessage(message.payload)
const [compareStr, compareStrLanguage] =
compare && compare.payload ? this.convertMessage(compare.payload) : [undefined, undefined]
return (
<div>
{this.renderDiff(value, value, undefined, valueLanguage)}
<Fade in={Boolean(compareStr)} timeout={400}>
<div>
{Boolean(compareStr) ? this.renderDiff(compareStr, compareStr, 'selected', compareStrLanguage) : null}
</div>
</Fade>
</div>
)
}
public render() {
return (
<div style={{ padding: '0px 0px 8px 0px', width: '100%' }}>
{this.props.message?.payload?.decoder === Decoder.SPARKPLUG && 'Decoded SparkplugB'}
{this.renderValue()}
</div>
)
}
public renderValue() {
const { message, treeNode, compareWith, renderMode } = this.props
const previousMessages = treeNode.messageHistory.toArray()
const previousMessage = previousMessages[previousMessages.length - 2]
const compareMessage = compareWith || previousMessage || message
if (renderMode === 'raw') {
return this.renderRawMode(message, compareWith)
}
if (!message.payload) {
function renderValue(
treeNode: q.TreeNode<TopicViewModel>,
currentStr: string | undefined,
compareStr: string | undefined,
currentType: Language | undefined,
compareType: Language | undefined,
renderMode: string,
compareWithPreviousMessage: boolean
) {
if (!decodedMessage) {
return null
}
const compareValue = compareMessage.payload || message.payload
const [current, currentLanguage] = this.convertMessage(message.payload)
const [compare, compareLanguage] = this.convertMessage(compareValue)
const language = currentLanguage === compareLanguage && compareLanguage === 'json' ? 'json' : undefined
return this.renderDiff(current, compare, undefined, language)
switch (renderMode) {
case 'diff':
return renderDiffMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
default:
return renderRawMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
}
}
const renderedValue = useMemo(
() =>
renderValue(treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage),
[treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage]
)
return (
<div style={{ padding: '0px 0px 8px 0px', width: '100%' }}>
{decodedMessage?.decoder === Decoder.SPARKPLUG && 'Decoded SparkplugB'}
{renderedValue}
</div>
)
}
const mapStateToProps = (state: AppState) => {
+24 -13
View File
@@ -2,12 +2,14 @@ import * as dotProp from 'dot-prop'
import * as q from '../../../backend/src/Model'
import * as React from 'react'
import PlotHistory from './Chart/Chart'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { toPlottableValue } from './Sidebar/CodeDiff/util'
import { PlotCurveTypes } from '../reducers/Charts'
import { DecoderFunction, useDecoder } from './hooks/useDecoder'
const parseDuration = require('parse-duration')
interface Props {
node?: q.TreeNode<any>
history: q.MessageHistory
dotPath?: string
timeInterval?: string
@@ -25,21 +27,27 @@ function filterUsingTimeRange(startTime: number | undefined, data: Array<q.Messa
return data
}
function nodeToHistory(startTime: number | undefined, history: q.MessageHistory) {
function nodeToHistory(decodeMessage: DecoderFunction, startTime: number | undefined, history: q.MessageHistory) {
return filterUsingTimeRange(startTime, history.toArray())
.map((message: q.Message) => {
const value = message.payload ? toPlottableValue(Base64Message.toUnicodeString(message.payload)) : NaN
return { x: message.received.getTime(), y: toPlottableValue(value) }
const decoded = decodeMessage(message)?.message?.toUnicodeString()
return { x: message.received.getTime(), y: toPlottableValue(decoded) }
})
.filter(data => !isNaN(data.y as any)) as any
}
function nodeDotPathToHistory(startTime: number | undefined, history: q.MessageHistory, dotPath: string) {
function nodeDotPathToHistory(
decodeMessage: DecoderFunction,
startTime: number | undefined,
history: q.MessageHistory,
dotPath: string
) {
return filterUsingTimeRange(startTime, history.toArray())
.map((message: q.Message) => {
let json: any = {}
try {
json = message.payload ? JSON.parse(Base64Message.toUnicodeString(message.payload)) : {}
const decoded = decodeMessage(message)?.message
json = decoded ? JSON.parse(decoded.toUnicodeString()) : {}
} catch (ignore) {}
const value = dotProp.get(json, dotPath)
@@ -50,14 +58,17 @@ function nodeDotPathToHistory(startTime: number | undefined, history: q.MessageH
}
function TopicPlot(props: Props) {
const decodeMessage = useDecoder(props.node)
const startOffset = props.timeInterval ? parseDuration(props.timeInterval) : undefined
const data = React.useMemo(
() =>
props.dotPath
? nodeDotPathToHistory(startOffset, props.history, props.dotPath)
: nodeToHistory(startOffset, props.history),
[props.history.last(), startOffset, props.dotPath]
)
const data = React.useMemo(() => {
if (!props.node) {
return []
}
return props.dotPath
? nodeDotPathToHistory(decodeMessage, startOffset, props.history, props.dotPath)
: nodeToHistory(decodeMessage, startOffset, props.history)
}, [props.history.last(), startOffset, props.dotPath])
return (
<PlotHistory
@@ -1,8 +1,8 @@
import * as q from '../../../../../backend/src/Model'
import React, { memo } from 'react'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { Theme, withStyles } from '@material-ui/core'
import { TopicViewModel } from '../../../model/TopicViewModel'
import { useDecoder } from '../../hooks/useDecoder'
export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
treeNode: q.TreeNode<TopicViewModel>
@@ -14,67 +14,72 @@ export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
classes: any
}
class TreeNodeTitle extends React.PureComponent<TreeNodeProps, {}> {
private renderSourceEdge() {
const name = this.props.name || (this.props.treeNode.sourceEdge && this.props.treeNode.sourceEdge.name)
export const TreeNodeTitle = (props: TreeNodeProps) => {
const decodeMessage = useDecoder(props.treeNode)
function renderSourceEdge() {
const name = props.name || (props.treeNode.sourceEdge && props.treeNode.sourceEdge.name)
return (
<span key="edge" className={this.props.classes.sourceEdge} data-test-topic={name}>
<span key="edge" className={props.classes.sourceEdge} data-test-topic={name}>
{name}
</span>
)
}
private truncatedMessage() {
function truncatedMessage() {
const limit = 400
if (!this.props.treeNode.message || !this.props.treeNode.message.payload) {
if (!props.treeNode.message || !props.treeNode.message.payload) {
return ''
}
const [value = ''] = decodeMessage(props.treeNode.message)?.message?.format(props.treeNode.type) ?? []
const str = Base64Message.toUnicodeString(this.props.treeNode.message.payload)
return str.length > limit ? `${str.slice(0, limit)}` : str
return value.length > limit ? `${value.slice(0, limit)}` : value
}
private renderValue() {
return this.props.treeNode.message &&
this.props.treeNode.message.payload &&
this.props.treeNode.message.length > 0 ? (
<span key="value" className={this.props.classes.value}>
function renderValue() {
return props.treeNode.message && props.treeNode.message.payload && props.treeNode.message.length > 0 ? (
<span key="value" className={props.classes.value}>
{' '}
= {this.truncatedMessage()}
= {truncatedMessage()}
</span>
) : null
}
private renderExpander() {
if (this.props.treeNode.edgeCount() === 0) {
function renderExpander() {
if (props.treeNode.edgeCount() === 0) {
return null
}
return (
<span key="expander" className={this.props.classes.expander} onClick={this.props.toggleCollapsed}>
{this.props.collapsed ? '▶' : '▼'}
<span key="expander" className={props.classes.expander} onClick={props.toggleCollapsed}>
{props.collapsed ? '▶' : '▼'}
</span>
)
}
private renderMetadata() {
if (this.props.treeNode.edgeCount() === 0 || !this.props.collapsed) {
function renderMetadata() {
if (props.treeNode.edgeCount() === 0 || !props.collapsed) {
return null
}
const messages = this.props.treeNode.leafMessageCount()
const topicCount = this.props.treeNode.childTopicCount()
const messages = props.treeNode.leafMessageCount()
const topicCount = props.treeNode.childTopicCount()
return (
<span key="metadata" className={this.props.classes.collapsedSubnodes}>{` (${topicCount} ${
<span key="metadata" className={props.classes.collapsedSubnodes}>{` (${topicCount} ${
topicCount === 1 ? 'topic' : 'topics'
}, ${messages} ${messages === 1 ? 'message' : 'messages'})`}</span>
)
}
public render() {
return [this.renderExpander(), this.renderSourceEdge(), this.renderMetadata(), this.renderValue()]
}
return (
<>
{renderExpander()}
{renderSourceEdge()}
{renderMetadata()}
{renderValue()}
</>
)
}
const styles = (theme: Theme) => ({
@@ -0,0 +1,18 @@
import * as q from '../../../../../../backend/src/Model'
import { useEffect } from 'react'
import { TopicViewModel } from '../../../../model/TopicViewModel'
export function useViewModel(treeNode: q.TreeNode<TopicViewModel> | undefined) {
useEffect(() => {
if (treeNode && !treeNode?.viewModel) {
treeNode.viewModel = new TopicViewModel(treeNode)
}
treeNode?.viewModel?.retain()
return function cleanup() {
treeNode?.viewModel?.release()
}
}, [treeNode])
return treeNode?.viewModel
}
@@ -1,6 +1,8 @@
import * as q from '../../../../../../backend/src/Model'
import React, { useEffect } from 'react'
import React, { useCallback } from 'react'
import { TopicViewModel } from '../../../../model/TopicViewModel'
import { useSubscription } from '../../../hooks/useSubscription'
import { useViewModel } from './useViewModel'
export function useViewModelSubscriptions(
treeNode: q.TreeNode<TopicViewModel>,
@@ -8,37 +10,21 @@ export function useViewModelSubscriptions(
setSelected: (value: boolean) => void,
setCollapsedOverride: (value: boolean) => void
) {
useEffect(() => {
const selectionDidChange = () => {
const selected = treeNode.viewModel && treeNode.viewModel.isSelected()
treeNode.viewModel && setSelected(Boolean(selected))
const viewModel = useViewModel(treeNode)
if (selected && nodeRef && nodeRef.current) {
nodeRef.current.focus({ preventScroll: false })
}
}
const selectionDidChange = useCallback(() => {
const selected = viewModel && viewModel.isSelected()
viewModel && setSelected(Boolean(selected))
const expandedDidChange = () => {
treeNode.viewModel && setCollapsedOverride(!treeNode.viewModel.isExpanded())
if (selected && nodeRef && nodeRef.current) {
nodeRef.current.focus({ preventScroll: false })
}
}, [viewModel])
function addSubscriber() {
treeNode.viewModel = new TopicViewModel()
treeNode.viewModel.selectionChange.subscribe(selectionDidChange)
treeNode.viewModel.expandedChange.subscribe(expandedDidChange)
}
const expandedDidChange = useCallback(() => {
viewModel && setCollapsedOverride(!viewModel.isExpanded())
}, [viewModel])
function removeSubscriber() {
if (treeNode.viewModel) {
treeNode.viewModel.selectionChange.unsubscribe(selectionDidChange)
treeNode.viewModel.expandedChange.unsubscribe(expandedDidChange)
treeNode.viewModel = undefined
}
}
addSubscriber()
return function cleanup() {
removeSubscriber()
}
}, [treeNode])
useSubscription(viewModel?.selectionChange, selectionDidChange)
useSubscription(viewModel?.expandedChange, expandedDidChange)
}
+14 -6
View File
@@ -1,7 +1,6 @@
import * as compareVersions from 'compare-versions'
import * as electron from 'electron'
import * as os from 'os'
import * as React from 'react'
import compareVersions from 'compare-versions'
import electron from 'electron'
import React from 'react'
import axios from 'axios'
import Close from '@material-ui/icons/Close'
import CloudDownload from '@material-ui/icons/CloudDownload'
@@ -182,9 +181,10 @@ class UpdateNotifier extends React.PureComponent<Props, State> {
private assetForCurrentPlatform(asset: GithubAsset) {
let regex: RegExp
if (os.platform() === 'darwin') {
const platform = this.getPlatform()
if (platform === 'darwin') {
regex = /\.dmg$/
} else if (os.platform() === 'win32') {
} else if (platform === 'win32') {
regex = /\.exe$/
} else {
regex = /\.AppImage$/
@@ -193,6 +193,14 @@ class UpdateNotifier extends React.PureComponent<Props, State> {
return regex.test(asset.name)
}
private getPlatform(): string {
if (typeof window === 'undefined') return 'linux'
const userAgent = window.navigator.userAgent.toLowerCase()
if (userAgent.includes('mac')) return 'darwin'
if (userAgent.includes('win')) return 'win32'
return 'linux'
}
private renderDownloads() {
const latestUpdate = this.state.newerVersions[0]
if (!latestUpdate || !latestUpdate.assets) {
+3 -2
View File
@@ -9,7 +9,8 @@ import { globalActions } from '../../actions'
const copy = require('copy-text-to-clipboard')
interface Props {
value: string
value?: string
getValue?: () => string | undefined
actions: {
global: typeof globalActions
}
@@ -28,7 +29,7 @@ class Copy extends React.PureComponent<Props, State> {
private handleClick = (event: React.MouseEvent) => {
event.stopPropagation()
copy(this.props.value)
copy(this.props.value ?? this.props.getValue?.())
this.props.actions.global.showNotification('Copied to clipboard')
this.setState({ didCopy: true })
setTimeout(() => {
+11 -5
View File
@@ -1,5 +1,5 @@
import * as moment from 'moment'
import * as React from 'react'
import moment from 'moment'
import React from 'react'
import { AppState } from '../../reducers'
import { connect } from 'react-redux'
@@ -12,6 +12,7 @@ interface Props {
}
const unitMapping = {
ms: 'milliseconds',
s: 'seconds',
m: 'minutes',
h: 'hours',
@@ -21,7 +22,7 @@ class DateFormatter extends React.PureComponent<Props, {}> {
private intervalSince(intervalSince: Date) {
const interval = intervalSince.getTime() - this.props.date.getTime()
const unit = this.unitForInterval(interval)
return `${Math.round(moment.duration(interval).as(unit) * 100) / 100} ${unitMapping[unit]}`
return `${moment.duration(interval).as(unit).toFixed(3)} ${unitMapping[unit]}`
}
private legacyDate() {
@@ -31,10 +32,11 @@ class DateFormatter extends React.PureComponent<Props, {}> {
private localizedDate(locale: string) {
return moment(this.props.date)
.locale(locale)
.format(this.props.timeFirst ? 'LTS L' : 'L LTS')
.format(this.props.timeFirst ? 'LTS.SSS L' : 'L LTS.SSS')
}
private unitForInterval(milliseconds: number) {
const oneSecond = 1000 * 1
const oneMinute = 1000 * 60
const oneHour = oneMinute * 60
@@ -46,7 +48,11 @@ class DateFormatter extends React.PureComponent<Props, {}> {
return 'm'
}
return 's'
if (milliseconds > oneSecond * 0.5) {
return 's'
}
return 'ms'
}
public render() {
+85
View File
@@ -0,0 +1,85 @@
import * as React from 'react'
import { connect } from 'react-redux'
import Check from '@material-ui/icons/Check'
import CustomIconButton from './CustomIconButton'
import { SaveAlt } from '@material-ui/icons'
import { bindActionCreators } from 'redux'
import { rendererRpc, writeToFile } from '../../../../events'
import { makeSaveDialogRpc } from '../../../../events/OpenDialogRequest'
import { globalActions } from '../../actions'
export async function saveToFile(data: string): Promise<string | undefined> {
const rejectReasons = {
errorWritingFile: 'Error writing file',
}
const { canceled, filePath } = await rendererRpc.call(makeSaveDialogRpc(), {
securityScopedBookmarks: true,
})
if (!canceled && filePath !== undefined) {
try {
const filename = await rendererRpc.call(writeToFile, { filePath, data })
return filePath
} catch (error) {
throw rejectReasons.errorWritingFile
}
}
}
interface Props {
getData: () => string | undefined
actions: {
global: typeof globalActions
}
}
interface State {
didSave: boolean
}
class Save extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props)
this.state = { didSave: false }
}
private handleClick = async (event: React.MouseEvent) => {
event.stopPropagation()
const data = this.props.getData()
if (data != undefined) {
const filename = await saveToFile(data)
this.props.actions.global.showNotification(`Saved to ${filename}`)
this.setState({ didSave: true })
setTimeout(() => {
this.setState({ didSave: false })
}, 1500)
}
}
public render() {
const icon = !this.state.didSave ? (
<SaveAlt fontSize="inherit" />
) : (
<Check fontSize="inherit" style={{ cursor: 'default' }} />
)
return (
<CustomIconButton onClick={this.handleClick} tooltip="Save to file">
<div style={{ marginTop: '2px' }}>{icon}</div>
</CustomIconButton>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
global: bindActionCreators(globalActions, dispatch),
},
}
}
export default connect(undefined, mapDispatchToProps)(Save)
+31
View File
@@ -0,0 +1,31 @@
import * as q from '../../../../backend/src/Model'
import { useCallback, useState } from 'react'
import { TopicViewModel } from '../../model/TopicViewModel'
import { useSubscription } from './useSubscription'
import { useViewModel } from '../Tree/TreeNode/effects/useViewModel'
import { DecoderEnvelope } from '../../decoders/DecoderEnvelope'
import { Decoder } from '../../../../backend/src/Model/Decoder'
export type DecoderFunction = (message: q.Message) => DecoderEnvelope | undefined
/**
* Provides the latest decoder for a topic
*
* @param treeNode
* @returns
*/
export function useDecoder(treeNode: q.TreeNode<TopicViewModel> | undefined): DecoderFunction {
const viewModel = useViewModel(treeNode)
const [decoder, setDecoder] = useState(viewModel?.decoder)
useSubscription(viewModel?.onDecoderChange, setDecoder)
return useCallback(
message => {
return decoder && message.payload
? decoder.decoder.decode(message.payload, decoder.format)
: { message: message.payload ?? undefined, decoder: Decoder.NONE }
},
[decoder]
)
}
@@ -0,0 +1,10 @@
import { useEffect } from 'react'
import { EventDispatcher } from '../../../../events'
export function useSubscription<T>(dispatcher: EventDispatcher<T> | undefined, callback: (value: T) => void) {
useEffect(() => {
dispatcher?.subscribe(callback)
return () => dispatcher?.unsubscribe(callback)
}, [dispatcher, callback])
}
+56
View File
@@ -0,0 +1,56 @@
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Decoder } from '../../../backend/src/Model/Decoder'
import { DecoderEnvelope } from './DecoderEnvelope'
import { MessageDecoder } from './MessageDecoder'
type BinaryFormats =
| 'int8'
| 'int16'
| 'int32'
| 'int64'
| 'uint8'
| 'uint16'
| 'uint32'
| 'uint64'
| 'float'
| 'double'
/**
* Binary decode primitive binary data type and arrays of these
*/
export const BinaryDecoder: MessageDecoder<BinaryFormats> = {
formats: ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float', 'double'],
decode(input: Base64Message, format: BinaryFormats): DecoderEnvelope {
const decodingOption = {
int8: [Buffer.prototype.readInt8, 1],
int16: [Buffer.prototype.readInt16LE, 2],
int32: [Buffer.prototype.readInt32LE, 4],
int64: [Buffer.prototype.readBigInt64LE, 8],
uint8: [Buffer.prototype.readUint8, 1],
uint16: [Buffer.prototype.readUint16LE, 2],
uint32: [Buffer.prototype.readUint32LE, 4],
uint64: [Buffer.prototype.readBigUint64LE, 8],
float: [Buffer.prototype.readFloatLE, 4],
double: [Buffer.prototype.readDoubleLE, 8],
} as const
const [readNumber, bytesToRead] = decodingOption[format]
const buf = input.toBuffer()
let str: String[] = []
if (buf.length % bytesToRead !== 0) {
return {
error: 'Data type does not align with message',
decoder: Decoder.NONE,
}
}
for (let index = 0; index < buf.length; index += bytesToRead) {
str.push((readNumber as any).apply(buf, [index]).toString())
}
return {
message: Base64Message.fromString(JSON.stringify(str.length === 1 ? str[0] : str)),
decoder: Decoder.NONE,
}
},
}
+8
View File
@@ -0,0 +1,8 @@
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Decoder } from '../../../backend/src/Model/Decoder'
export interface DecoderEnvelope {
message?: Base64Message
error?: string
decoder: Decoder
}
+13
View File
@@ -0,0 +1,13 @@
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { DecoderEnvelope } from './DecoderEnvelope'
export interface MessageDecoder<T = string> {
/**
* Can be used to
* @param topic
*/
formats: T[]
canDecodeTopic?(topic: string): boolean
canDecodeData?(data: Base64Message): boolean
decode(input: Base64Message, format: T | string | undefined): DecoderEnvelope
}
+28
View File
@@ -0,0 +1,28 @@
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Decoder } from '../../../backend/src/Model/Decoder'
import { get } from 'sparkplug-payload'
import { MessageDecoder } from './MessageDecoder'
var sparkplug = get('spBv1.0')
export const SparkplugDecoder: MessageDecoder = {
formats: ['Sparkplug'],
canDecodeTopic(topic: string) {
return !!topic.match(/^spBv1\.0\/[^/]+\/[ND](DATA|CMD|DEATH|BIRTH)\/[^/]+(\/[^/]+)?$/u)
},
decode(input) {
try {
const message = Base64Message.fromString(
JSON.stringify(
// @ts-ignore
sparkplug.decodePayload(new Uint8Array(input.toBuffer()))
)
)
return { message, decoder: Decoder.SPARKPLUG }
} catch {
return {
error: 'Failed to decode sparkplugb payload',
decoder: Decoder.NONE,
}
}
},
}
+10
View File
@@ -0,0 +1,10 @@
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Decoder } from '../../../backend/src/Model/Decoder'
import { MessageDecoder } from './MessageDecoder'
export const StringDecoder: MessageDecoder = {
formats: ['string'],
decode(input: Base64Message) {
return { message: input, decoder: Decoder.NONE }
},
}
+6
View File
@@ -0,0 +1,6 @@
import { StringDecoder } from './StringDecoder'
import { BinaryDecoder } from './BinaryDecoder'
import { SparkplugDecoder } from './SparkplugBDecoder'
export * from './MessageDecoder'
export const decoders = [SparkplugDecoder, BinaryDecoder, StringDecoder] as const
+4 -1
View File
@@ -10,6 +10,7 @@ import { connect, Provider } from 'react-redux'
import { ThemeProvider } from '@material-ui/styles'
import './utils/tracking'
import { themes } from './theme'
import { BrowserAuthWrapper } from './components/BrowserAuthWrapper'
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(reducers, composeEnhancers(applyMiddleware(reduxThunk, batchDispatchMiddleware)))
@@ -33,7 +34,9 @@ const Application = connect(mapStateToProps)(ApplicationRenderer)
ReactDOM.render(
<Provider store={store}>
<Application />
<BrowserAuthWrapper>
<Application />
</BrowserAuthWrapper>
</Provider>,
document.getElementById('app')
)
+12
View File
@@ -0,0 +1,12 @@
// Mock electron module for browser environment
export const shell = {
openExternal: (url: string) => {
if (typeof window !== 'undefined') {
window.open(url, '_blank')
}
},
}
export default {
shell,
}
@@ -1,5 +1,4 @@
import { ConnectionOptions, createEmptyConnection } from './ConnectionOptions'
import { v4 } from 'uuid'
interface LegacyConnectionSettings {
host: string
+59 -1
View File
@@ -1,19 +1,77 @@
import * as q from '../../../backend/src/Model'
import { Destroyable } from '../../../backend/src/Model/Destroyable'
import { MessageDecoder, decoders } from '../decoders'
import { EventDispatcher } from '../../../events'
function findDecoder<T extends Destroyable>(node: q.TreeNode<T>): TopicDecoder | undefined {
const decoder = decoders.find(
decoder =>
decoder.canDecodeTopic?.(node.path()) || (node.message?.payload && decoder.canDecodeData?.(node.message?.payload))
)
return decoder
? {
decoder,
format: undefined,
}
: undefined
}
type TopicDecoder = { decoder: MessageDecoder; format: string | undefined }
export class TopicViewModel implements Destroyable {
private selected: boolean
private expanded: boolean
private owner: q.TreeNode<TopicViewModel> | undefined
private _decoder?: TopicDecoder
/**
* Reference counter for useViewModel hook
*/
private referenceCounter = 0
public selectionChange = new EventDispatcher<void>()
public expandedChange = new EventDispatcher<void>()
public onDecoderChange = new EventDispatcher<TopicDecoder | undefined>()
public constructor() {
get decoder(): TopicDecoder | undefined {
if (!this._decoder) {
this._decoder = this.owner && findDecoder(this.owner)
}
return this._decoder
}
set decoder(override: TopicDecoder | undefined) {
this._decoder = override
this.onDecoderChange.dispatch(override)
}
public constructor(treeNode: q.TreeNode<TopicViewModel>) {
this.owner = treeNode
this.selected = false
this.expanded = false
}
public retain() {
this.referenceCounter += 1
}
public release() {
this.referenceCounter -= 1
if (this.referenceCounter <= 0) {
this.destroy()
}
}
public destroy() {
console.log('destroy', this.referenceCounter)
if (this.owner) {
this.owner.viewModel = undefined
this.owner = undefined
}
this.selectionChange.removeAllListeners()
this.onDecoderChange.removeAllListeners()
this.expandedChange.removeAllListeners()
}
public isSelected() {
+9 -21
View File
@@ -4,38 +4,26 @@
"noImplicitAny": true,
"strictNullChecks": true,
"strict": true,
"lib": [
"es2017",
"dom"
],
"lib": ["es2019", "dom"],
"moduleResolution": "node",
"outDir": "./build/",
"sourceMap": true,
"module": "esnext",
"target": "es2017",
"target": "ES2017",
"jsx": "react",
"paths": {
"react": [
"./node_modules/@types/react"
]
"react": ["./node_modules/@types/react"]
},
"types": [
"react"
],
"types": ["react"],
"allowSyntheticDefaultImports": true,
"skipLibCheck": true
"skipLibCheck": true,
"esModuleInterop": true
},
"include": [
"./src/**/*"
],
"exclude": [
"**/*.d.ts",
".src/**/*.png",
"./node_modules"
],
"include": ["./src/**/*"],
"exclude": ["**/*.d.ts", ".src/**/*.png", "./node_modules"],
"awesomeTypescriptLoaderOptions": {
"useCache": true,
"transpileModule": true,
"errorsAsWarnings": true
}
}
}
+102
View File
@@ -0,0 +1,102 @@
// Browser-specific webpack configuration
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const path = require('path')
module.exports = {
entry: {
app: './src/index.tsx',
bugtracking: './src/utils/bugtracking.ts',
},
output: {
chunkFilename: '[name].bundle.js',
filename: '[name].bundle.js',
path: `${__dirname}/build`,
},
optimization: {
minimize: false,
splitChunks: {
chunks: 'all',
minSize: 30000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/](react|react-dom|@material-ui|popper\.js|react|react-redux|prop-types|jss|redux|scheduler|react-transition-group)[\\/]/,
name: 'vendors',
chunks: 'all',
priority: -10,
},
default: {
name: 'default',
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
runtimeChunk: 'single',
},
devServer: {
hot: true,
liveReload: true,
},
target: 'web', // Changed from 'electron-renderer' to 'web'
mode: 'production',
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.mjs', '.m.js', '.tsx', '.js', '.json'],
modules: ['node_modules', path.resolve(__dirname, 'node_modules')],
alias: {
electron: require.resolve('./src/mocks/electron.ts'),
},
fallback: {
// Browser fallbacks for Node.js modules
path: require.resolve('path-browserify'),
fs: false,
crypto: false,
url: require.resolve('url/'),
os: require.resolve('os-browserify/browser'),
events: require.resolve('events/'),
},
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true, // Skip type checking, we already did it with tsc
},
},
],
exclude: /node_modules/,
},
{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif)$/i,
type: 'asset/resource',
},
],
},
plugins: [
new HtmlWebpackPlugin({ template: './index.html', file: './build/index.html', inject: false }),
new webpack.DefinePlugin({
'process.env.BROWSER_MODE': JSON.stringify('true'),
}),
new webpack.NormalModuleReplacementPlugin(/EventSystem[\\/]EventBus$/, resource => {
console.log('Replacing EventBus:', resource.request);
resource.request = resource.request.replace(/EventBus$/, 'BrowserEventBus');
}),
],
externals: {},
cache: false,
}
+16 -2
View File
@@ -41,6 +41,7 @@ module.exports = {
devServer: {
// contentBase: './dist', // content not from webpack
hot: true,
liveReload: true,
},
target: 'electron-renderer',
mode: 'production',
@@ -54,7 +55,15 @@ module.exports = {
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{
test: /\.tsx?$/,
loader: 'ts-loader',
use: [
{
loader: 'ts-loader',
// options: {
// configFile: './tsconfig.json',
// },
},
],
exclude: /node_modules/,
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
@@ -81,7 +90,6 @@ module.exports = {
plugins: [
new HtmlWebpackPlugin({ template: './index.html', file: './build/index.html', inject: false }),
// new BundleAnalyzerPlugin(),
new webpack.HotModuleReplacementPlugin(),
// new webpack.IgnorePlugin({
// resourceRegExp: /\.\/build\/Debug\/addon/,
// contextRegExp: /heapdump$/
@@ -96,4 +104,10 @@ module.exports = {
// "react": "React",
// "react-dom": "ReactDOM"
},
cache: {
type: 'filesystem',
},
optimization: {
runtimeChunk: 'single',
},
}
+652 -380
View File
File diff suppressed because it is too large Load Diff
+31 -13
View File
@@ -4,15 +4,14 @@
"description": "",
"main": "build/index.js",
"scripts": {
"test": "mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"test": "NODE_PATH=../node_modules TS_NODE_PROJECT=./tsconfig.json mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"build": "tsc",
"test-inspect": "mocha --inspect-brk --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"coverage": "nyc mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"debug": "ts-node --inspect ./src/index.ts",
"postinstall": "yarn build"
"test-inspect": "NODE_PATH=../node_modules TS_NODE_PROJECT=./tsconfig.json mocha --inspect-brk --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"coverage": "NODE_PATH=../node_modules TS_NODE_PROJECT=./tsconfig.json nyc mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"debug": "ts-node --inspect ./src/index.ts"
},
"engines": {
"node": ">=18"
"node": ">=20"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -38,12 +37,31 @@
"sourceMap": true,
"instrument": true
},
"peerDependencies": {
"fs-extra": "^8.0.1",
"js-base64": "^2.5.1",
"long": "^4.0.0",
"dependencies": {
"@types/sha1": "^1.1.5",
"builder-util-runtime": "^9",
"fs-extra": "9",
"js-base64": "^3.7.2",
"lowdb": "^1.0.0",
"mqtt": "^3.0.0",
"protobufjs": "^6.11.4"
"mqtt": "^4.3.6",
"protobufjs": "^8.0.0",
"sha1": "^1.1.1",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/fs-extra": "8",
"@types/lowdb": "^1.0.6",
"@types/mocha": "^7.0.2",
"@types/node": "^25.0.3",
"@types/sha1": "^1.1.1",
"@types/uuid": "^8.3.4",
"chai": "^4.2.0",
"electron": "29.2.0",
"mocha": "^10.4.0",
"nyc": "15",
"source-map-support": "^0.5.9",
"ts-node": "^10.9.2",
"typescript": "^4.5.5"
}
}
}
+12 -9
View File
@@ -1,15 +1,18 @@
import * as FileAsync from 'lowdb/adapters/FileAsync'
import * as fs from 'fs-extra'
import * as lowdb from 'lowdb'
import * as path from 'path'
import { backendRpc } from '../../events'
import FileAsync from 'lowdb/adapters/FileAsync'
import fs from 'fs-extra'
import lowdb from 'lowdb'
import path from 'path'
import { Rpc } from '../../events/EventSystem/Rpc'
import { storageClearEvent, storageLoadEvent, storageStoreEvent } from '../../events/StorageEvents'
export default class ConfigStorage {
private file: string
private database: any
constructor(file: string) {
private rpc: Rpc
constructor(file: string, rpc: Rpc) {
this.file = file
this.rpc = rpc
}
private async getDb() {
@@ -26,13 +29,13 @@ export default class ConfigStorage {
}
public async init() {
backendRpc.on(storageStoreEvent, async event => {
this.rpc.on(storageStoreEvent, async event => {
const db = await this.getDb()
await db.set(event.store, event.data).write()
return
})
backendRpc.on(storageLoadEvent, async event => {
this.rpc.on(storageLoadEvent, async event => {
const db = await this.getDb()
const data = await db.get(event.store).value()
return {
@@ -41,7 +44,7 @@ export default class ConfigStorage {
}
})
backendRpc.on(storageClearEvent, async event => {
this.rpc.on(storageClearEvent, async event => {
const db = await this.getDb()
const keys = await db.keys().value()
for (const key of keys) {
+1 -1
View File
@@ -98,7 +98,7 @@ export class MqttSource implements DataSource<MqttOptions> {
public publish(msg: MqttMessage) {
if (this.client) {
this.client.publish(msg.topic, msg.payload ? Base64Message.toUnicodeString(msg.payload) : '', {
this.client.publish(msg.topic, (msg.payload && new Base64Message(msg.payload))?.toBuffer() ?? '', {
qos: msg.qos,
retain: msg.retain,
})
+74 -12
View File
@@ -1,31 +1,93 @@
import { Base64 } from 'js-base64'
import { Decoder } from './Decoder'
import { TopicDataType } from './TreeNode'
export type Base64MessageDTO = Pick<Base64Message, 'base64Message'>
export class Base64Message {
private base64Message: string
private unicodeValue: string
public decoder: Decoder
public length: number
public base64Message: string
private _unicodeValue: string | undefined
private constructor(base64Str: string) {
this.base64Message = base64Str
this.unicodeValue = Base64.decode(base64Str)
this.length = base64Str.length
this.decoder = Decoder.NONE
// Todo: Rename to `encodedLength`
public get length(): number {
return this.base64Message.length
}
public static toUnicodeString(message: Base64Message) {
return message.unicodeValue || ''
private get unicodeValue(): string {
if (!this._unicodeValue) {
this._unicodeValue = Base64.decode(this.base64Message ?? '')
}
return this._unicodeValue
}
constructor(base64Str?: string | Base64MessageDTO, error?: string) {
if (typeof base64Str === 'string' || typeof base64Str === 'undefined') {
this.base64Message = base64Str ?? ''
} else {
if (typeof base64Str.base64Message !== 'string') {
throw new Error('Received unexpected type in copy constructor')
}
this.base64Message = base64Str.base64Message
}
}
/**
* Override default JSON serialization behavior to only return the DTO
* @returns
*/
public toJSON(): Base64MessageDTO {
return { base64Message: this.base64Message }
}
public toUnicodeString() {
return this.unicodeValue || ''
}
public static fromBuffer(buffer: Buffer) {
return new Base64Message(buffer.toString('base64'))
}
public toBuffer(): Buffer {
return Buffer.from(this.base64Message, 'base64')
}
public static fromString(str: string) {
return new Base64Message(Base64.encode(str))
}
public format(type: TopicDataType = 'string'): [string, 'json' | undefined] {
try {
switch (type) {
case 'json': {
const json = JSON.parse(this.toUnicodeString())
return [JSON.stringify(json, undefined, ' '), 'json']
}
case 'hex': {
const hex = Base64Message.toHex(this)
return [hex, undefined]
}
default: {
const str = this.toUnicodeString()
return [str, undefined]
}
}
} catch (error) {
const str = this.toUnicodeString()
return [str, undefined]
}
}
public static toHex(message: Base64Message) {
const buf = Buffer.from(message.base64Message, 'base64')
let str: string = ''
buf.forEach(element => {
const hex = element.toString(16).toUpperCase()
str += `0x${hex.length < 2 ? '0' + hex : hex} `
})
return str.trimRight()
}
public static toDataUri(message: Base64Message, mimeType: string) {
return `data:${mimeType};base64,${message.base64Message}`
}
+1 -1
View File
@@ -15,7 +15,7 @@ export class ChangeBuffer {
public push(val: MqttMessage) {
if (!this.isFull()) {
this.buffer.push({ message: val, received: new Date() })
this.size += this.estimatedMessageOverhead + (val.payload ? val.payload.length : 0)
this.size += this.estimatedMessageOverhead + (val.payload?.base64Message.length ?? 0)
this.length += 1
}
}
+2 -1
View File
@@ -1,7 +1,8 @@
import { Base64Message } from './Base64Message'
import { QoS } from '../DataSource/MqttSource'
import { MemoryConsumptionExpressedByLength } from './RingBuffer'
export interface Message {
export interface Message extends MemoryConsumptionExpressedByLength {
// mqtt based info
payload: Base64Message | null
messageId?: number
+4 -1
View File
@@ -2,6 +2,8 @@ import { Destroyable } from './Destroyable'
import { Edge, Message, RingBuffer, MessageHistory } from './'
import { EventDispatcher } from '../../../events'
export type TopicDataType = 'string' | 'json' | 'hex'
export class TreeNode<ViewModel extends Destroyable> {
public sourceEdge?: Edge<ViewModel>
public message?: Message
@@ -17,6 +19,7 @@ export class TreeNode<ViewModel extends Destroyable> {
public onMessage = new EventDispatcher<Message>()
public onDestroy = new EventDispatcher<TreeNode<ViewModel>>()
public isTree = false
public type: TopicDataType = 'json'
private cachedPath?: string
private cachedChildTopics?: Array<TreeNode<ViewModel>>
@@ -153,7 +156,7 @@ export class TreeNode<ViewModel extends Destroyable> {
public path(): string {
if (!this.cachedPath) {
return this.branch()
this.cachedPath = this.branch()
.map(node => node.sourceEdge && node.sourceEdge.name)
.filter(name => name !== undefined)
.join('/')
+3 -1
View File
@@ -1,6 +1,7 @@
import { Destroyable } from './Destroyable'
import { Edge, Tree, TreeNode } from './'
import { MqttMessage } from '../../../events'
import { Base64Message } from './Base64Message'
export abstract class TreeNodeFactory {
private static messageCounter = 0
@@ -30,7 +31,8 @@ export abstract class TreeNodeFactory {
mqttMessage.retain
node.setMessage({
...mqttMessage,
length: mqttMessage.payload?.length ?? 0,
payload: mqttMessage.payload && new Base64Message(mqttMessage.payload?.base64Message),
length: mqttMessage.payload?.base64Message.length ?? 0,
received: receiveDate,
messageNumber: this.messageCounter,
})
+1 -1
View File
@@ -1,5 +1,5 @@
export { Edge } from './Edge'
export { TreeNode } from './TreeNode'
export { TreeNode, TopicDataType } from './TreeNode'
export { Message } from './Message'
export { TreeNodeFactory } from './TreeNodeFactory'
export { Tree } from './Tree'
-21
View File
@@ -1,21 +0,0 @@
import { Base64Message } from './Base64Message'
import { Decoder } from './Decoder'
import { get } from 'sparkplug-payload'
var sparkplug = get("spBv1.0")
export const SparkplugDecoder = {
decode(input: Buffer): Base64Message {
try {
const message = Base64Message.fromString(JSON.stringify(
// @ts-ignore
sparkplug.decodePayload(new Uint8Array(input)))
)
message.decoder = Decoder.SPARKPLUG
return message
} catch {
const message = Base64Message.fromString("Failed to decode sparkplugb payload")
message.decoder = Decoder.NONE
return message
}
},
}
+5 -6
View File
@@ -1,7 +1,6 @@
import 'mocha'
import { expect } from 'chai'
import { Base64Message } from '../Base64Message'
import { makeTreeNode } from './makeTreeNode'
describe('TreeNode', () => {
@@ -14,7 +13,7 @@ describe('TreeNode', () => {
it('updateWithNode should update value', () => {
const topics = 'foo/bar'.split('/')
const leaf = makeTreeNode('foo/bar', '3')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
const updateLeave = makeTreeNode('foo/bar', '5')
@@ -22,13 +21,13 @@ describe('TreeNode', () => {
root.updateWithNode(updateLeave.firstNode())
expect(root.sourceEdge).to.eq(undefined)
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('5')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('5')
})
it('updateWithNode should update intermediate nodes', () => {
const topics1 = 'foo/bar/baz'.split('/')
const leaf = makeTreeNode('foo/bar/baz', '3')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
const topics2 = 'foo/bar'.split('/')
const updateLeave = makeTreeNode('foo/bar', '5')
@@ -37,10 +36,10 @@ describe('TreeNode', () => {
const barNode = leaf.firstNode().findNode('foo/bar')
expect(barNode && barNode.sourceEdge && barNode.sourceEdge.name).to.eq('bar')
expect(Base64Message.toUnicodeString(barNode!.message!.payload!)).to.eq('5')
expect(barNode!.message!.payload!.toUnicodeString()).to.eq('5')
expect(leaf.sourceEdge && leaf.sourceEdge.name).to.eq('baz')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
})
it('updateWithNode should add nodes to the tree', () => {
@@ -1,6 +1,5 @@
import 'mocha'
import { expect } from 'chai'
import { Base64Message } from '../Base64Message'
import { makeTreeNode } from './makeTreeNode'
describe('TreeNodeFactory', () => {
@@ -20,7 +19,7 @@ describe('TreeNodeFactory', () => {
expect(node).to.not.eq(undefined)
expect(node.sourceEdge.name).to.eq('bar')
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
expect(node.message.payload!.toUnicodeString()).to.eq('5')
const foo = node.firstNode().findNode('foo')
expect(foo && foo.sourceEdge && foo.sourceEdge.name).to.eq('foo')
@@ -34,7 +33,7 @@ describe('TreeNodeFactory', () => {
return
}
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
expect(node.message.payload!.toUnicodeString()).to.eq('5')
expect(node.sourceEdge.name).to.eq('baz')
const barNode = node.sourceEdge.source
+13 -14
View File
@@ -4,16 +4,20 @@ import {
AddMqttConnection,
MqttMessage,
addMqttConnectionEvent,
backendEvents,
makeConnectionMessageEvent,
makeConnectionStateEvent,
makePublishEvent,
removeConnection,
} from '../../events'
import { SparkplugDecoder } from './Model/sparkplugb'
import { EventBusInterface } from '../../events/EventSystem/EventBusInterface'
export class ConnectionManager {
private connections: { [s: string]: DataSource<any> } = {}
private backendEvents: EventBusInterface
constructor(backendEvents: EventBusInterface) {
this.backendEvents = backendEvents
}
private handleConnectionRequest = (event: AddMqttConnection) => {
const connectionId = event.id
@@ -29,12 +33,12 @@ export class ConnectionManager {
const connectionStateEvent = makeConnectionStateEvent(connectionId)
connection.stateMachine.onUpdate.subscribe(state => {
backendEvents.emit(connectionStateEvent, state)
this.backendEvents.emit(connectionStateEvent, state)
})
connection.connect(options)
this.handleNewMessagesForConnection(connectionId, connection)
backendEvents.subscribe(makePublishEvent(connectionId), (msg: MqttMessage) => {
this.backendEvents.subscribe(makePublishEvent(connectionId), (msg: MqttMessage) => {
this.connections[connectionId].publish(msg)
})
}
@@ -48,14 +52,9 @@ export class ConnectionManager {
}
let decoded_payload = null
// spell-checker: disable-next-line
if (topic.match(/^spBv1\.0\/[^/]+\/[ND](DATA|CMD|DEATH|BIRTH)\/[^/]+(\/[^/]+)?$/u)) {
decoded_payload = SparkplugDecoder.decode(buffer)
} else {
decoded_payload = Base64Message.fromBuffer(buffer)
}
decoded_payload = Base64Message.fromBuffer(buffer)
backendEvents.emit(messageEvent, {
this.backendEvents.emit(messageEvent, {
topic,
payload: decoded_payload,
qos: packet.qos,
@@ -66,8 +65,8 @@ export class ConnectionManager {
}
public manageConnections() {
backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
backendEvents.subscribe(removeConnection, (connectionId: string) => {
this.backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
this.backendEvents.subscribe(removeConnection, (connectionId: string) => {
this.removeConnection(connectionId)
})
}
@@ -75,7 +74,7 @@ export class ConnectionManager {
public removeConnection(connectionId: string) {
const connection = this.connections[connectionId]
if (connection) {
backendEvents.unsubscribeAll(makePublishEvent(connectionId))
this.backendEvents.unsubscribeAll(makePublishEvent(connectionId))
connection.disconnect()
delete this.connections[connectionId]
connection.stateMachine.onUpdate.removeAllListeners()
+14 -2
View File
@@ -6,11 +6,21 @@
"strictNullChecks": true,
"outDir": "./build",
"strict": true,
"module": "commonjs",
"moduleResolution": "node",
"target": "ES2017",
"lib": [
"es2017",
"dom"
],
"sourceMap": true
"sourceMap": true,
"esModuleInterop": true
},
"ts-node": {
"compilerOptions": {
"module": "commonjs"
},
"transpileOnly": true
},
"includes": [
"src/**/*.ts"
@@ -20,6 +30,8 @@
"node_modules",
"src/**/*.spec.ts",
"**/*.d.ts",
"typings"
"typings",
"../events",
"../app"
]
}
+2265 -22
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
// Browser-specific EventBus implementation using Socket.io
import io from 'socket.io-client'
import { SocketIOClientEventBus } from './SocketIOClientEventBus'
import { Rpc } from './Rpc'
// Get auth from sessionStorage or use empty (will show login dialog)
const username = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('mqtt-explorer-username') || '' : ''
const password = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('mqtt-explorer-password') || '' : ''
// Connect to the server (same origin in browser mode)
const socket = io({
auth: {
username,
password,
},
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
transports: ['websocket', 'polling'],
})
export const rendererEvents = new SocketIOClientEventBus(socket)
export const rendererRpc = new Rpc(rendererEvents)
// In browser mode, the backend is on the server
// For compatibility, export same instances (renderer communicates with server backend via socket)
export const backendEvents = rendererEvents
export const backendRpc = rendererRpc
+73 -7
View File
@@ -1,24 +1,54 @@
import { IpcMain } from 'electron'
import { IpcMain, WebContents } from 'electron'
import { Event } from '../Events'
import { EventBusInterface } from './EventBusInterface'
export class IpcMainEventBus implements EventBusInterface {
private ipc: IpcMain
private client: any
private clients: Map<number, WebContents> = new Map() // webContentsId -> WebContents
private connectionOwners: Map<string, number> = new Map() // connectionId -> webContentsId
private currentClient: WebContents | undefined
constructor(ipc: IpcMain) {
this.ipc = ipc
}
public subscribe<MessageType>(subscribeEvent: Event<MessageType>, callback: (msg: MessageType) => void) {
console.log('subscribing', subscribeEvent.topic)
this.ipc.on(subscribeEvent.topic, (event: any, arg: any) => {
this.client = event.sender
const sender = event.sender as WebContents
this.currentClient = sender
// Track the client (O(1) operation)
if (!this.clients.has(sender.id)) {
this.clients.set(sender.id, sender)
// Clean up when window is closed
sender.once('destroyed', () => {
this.clients.delete(sender.id)
// Clean up owned connections
Array.from(this.connectionOwners.entries()).forEach(([connectionId, webContentsId]) => {
if (webContentsId === sender.id) {
this.connectionOwners.delete(connectionId)
}
})
})
}
// Track connection ownership
if (subscribeEvent.topic === 'connection/add/mqtt' && arg?.id) {
this.connectionOwners.set(arg.id, sender.id)
}
// Remove connection ownership
if (subscribeEvent.topic === 'connection/remove' && typeof arg === 'string') {
this.connectionOwners.delete(arg)
}
callback(arg)
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
console.log('unsubscribeAll', event.topic)
this.ipc.removeAllListeners(event.topic)
}
@@ -27,8 +57,44 @@ export class IpcMainEventBus implements EventBusInterface {
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
if (!this.client.isDestroyed()) {
this.client.send(event.topic, msg)
const topic = event.topic
// RPC responses go only to the requesting client
if (topic.includes('/response/')) {
if (this.currentClient && !this.currentClient.isDestroyed()) {
this.currentClient.send(topic, msg)
}
return
}
// Connection-specific events - optimized with early pattern match
if (topic.startsWith('conn/')) {
const parts = topic.split('/')
let connectionId: string | undefined
if (parts.length === 2) {
connectionId = parts[1]
} else if (parts.length === 3 && (parts[1] === 'state' || parts[1] === 'publish')) {
connectionId = parts[2]
}
if (connectionId) {
const ownerWebContentsId = this.connectionOwners.get(connectionId)
if (ownerWebContentsId !== undefined) {
const ownerClient = this.clients.get(ownerWebContentsId)
if (ownerClient && !ownerClient.isDestroyed()) {
ownerClient.send(topic, msg)
return
}
}
}
}
// All other events go to all clients
this.clients.forEach(client => {
if (!client.isDestroyed()) {
client.send(topic, msg)
}
})
}
}
+61
View File
@@ -0,0 +1,61 @@
import { IpcMain } from 'electron'
import { Event } from '../Events'
import { EventBusInterface } from './EventBusInterface'
import { MessageCodec } from './MessageCodec'
/**
* Enhanced IPC Main Event Bus with Protobuf support
*
* This version uses binary serialization for better performance
* while maintaining backward compatibility with the old JSON-based system.
*/
export class IpcMainEventBusV2 implements EventBusInterface {
private ipc: IpcMain
private client: any
private useBinary: boolean
constructor(ipc: IpcMain, useBinary: boolean = true) {
this.ipc = ipc
this.useBinary = useBinary
}
public subscribe<MessageType>(subscribeEvent: Event<MessageType>, callback: (msg: MessageType) => void) {
console.log('subscribing', subscribeEvent.topic, this.useBinary ? '(binary)' : '(json)')
this.ipc.on(subscribeEvent.topic, (event: any, arg: any) => {
this.client = event.sender
if (this.useBinary && arg instanceof Uint8Array) {
// Binary message - decode it
const { data } = MessageCodec.decodeWithPayload<MessageType>(arg)
callback(data)
} else {
// Regular JSON message
callback(arg)
}
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
console.log('unsubscribeAll', event.topic)
this.ipc.removeAllListeners(event.topic)
}
public unsubscribe<MessageType>(event: Event<MessageType>, callback: any) {
throw new Error('Not implemented') // Todo: implement
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
if (!this.client || this.client.isDestroyed()) {
return
}
if (this.useBinary) {
// Encode as binary
const binary = MessageCodec.encode(event.topic, msg)
this.client.send(event.topic, binary)
} else {
// Send as JSON (legacy)
this.client.send(event.topic, msg)
}
}
}
@@ -0,0 +1,65 @@
import { CallbackStore } from './CallbackStore'
import { EventBusInterface } from './EventBusInterface'
import { Event } from '../Events'
import { IpcRenderer } from 'electron'
import { MessageCodec } from './MessageCodec'
/**
* Enhanced IPC Renderer Event Bus with Protobuf support
*
* This version uses binary serialization for better performance
* while maintaining backward compatibility with the old JSON-based system.
*/
export class IpcRendererEventBusV2 implements EventBusInterface {
private ipc: IpcRenderer
private callbacks: Array<CallbackStore> = []
private useBinary: boolean
constructor(ipc: IpcRenderer, useBinary: boolean = true) {
this.ipc = ipc
this.useBinary = useBinary
}
public subscribe<MessageType>(event: Event<MessageType>, callback: (msg: MessageType) => void) {
const wrappedCallback = (_: any, arg: any) => {
if (this.useBinary && arg instanceof Uint8Array) {
// Binary message - decode it
const { data } = MessageCodec.decodeWithPayload<MessageType>(arg)
callback(data)
} else {
// Regular JSON message
callback(arg)
}
}
console.log('subscribing', event.topic, this.useBinary ? '(binary)' : '(json)')
this.ipc.on(event.topic, wrappedCallback)
this.callbacks.push({
callback,
wrappedCallback,
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
this.ipc.removeAllListeners(event.topic)
}
public unsubscribe<MessageType>(event: Event<MessageType>, callback: any) {
const item = this.callbacks.find(store => store.callback === callback)
if (!item) {
return
}
this.ipc.removeListener(event.topic, item.wrappedCallback)
this.callbacks = this.callbacks.filter(a => a !== item)
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
if (this.useBinary) {
// Encode as binary
const binary = MessageCodec.encode(event.topic, msg)
this.ipc.send(event.topic, binary)
} else {
// Send as JSON (legacy)
this.ipc.send(event.topic, msg)
}
}
}
+74
View File
@@ -0,0 +1,74 @@
/**
* Binary Message Codec using Protobuf
*
* This provides efficient binary serialization for IPC messages,
* avoiding JSON stringify/parse overhead.
*/
import * as protobuf from 'protobufjs'
// Define message schema
const messageSchema = {
nested: {
mqtt: {
nested: {
Envelope: {
fields: {
topic: { type: 'string', id: 1 },
payload: { type: 'bytes', id: 2 },
},
},
},
},
},
}
// Create root from JSON schema
const root = protobuf.Root.fromJSON(messageSchema)
const Envelope = root.lookupType('mqtt.Envelope')
export interface BinaryMessage {
topic: string
payload: Uint8Array
}
export class MessageCodec {
/**
* Encode a message to binary format
*/
public static encode(topic: string, data: any): Uint8Array {
// Serialize the payload to JSON, then to bytes
const jsonString = JSON.stringify(data)
const payloadBytes = new TextEncoder().encode(jsonString)
// Create protobuf envelope
const message = Envelope.create({
topic,
payload: payloadBytes,
})
// Encode to binary
return Envelope.encode(message).finish()
}
/**
* Decode a binary message
*/
public static decode(binary: Uint8Array): BinaryMessage {
const message = Envelope.decode(binary) as any
return {
topic: message.topic,
payload: message.payload,
}
}
/**
* Decode and parse payload as JSON
*/
public static decodeWithPayload<T>(binary: Uint8Array): { topic: string; data: T } {
const { topic, payload } = this.decode(binary)
const jsonString = new TextDecoder().decode(payload)
const data = JSON.parse(jsonString)
return { topic, data }
}
}
@@ -0,0 +1,42 @@
import { Socket } from 'socket.io-client'
import { CallbackStore } from './CallbackStore'
import { EventBusInterface } from './EventBusInterface'
import { Event } from '../Events'
export class SocketIOClientEventBus implements EventBusInterface {
private socket: Socket
private callbacks: Array<CallbackStore> = []
constructor(socket: Socket) {
this.socket = socket
}
public subscribe<MessageType>(event: Event<MessageType>, callback: (msg: MessageType) => void) {
const wrappedCallback = (arg: any) => {
callback(arg)
}
console.log('subscribing', event.topic)
this.socket.on(event.topic, wrappedCallback)
this.callbacks.push({
callback,
wrappedCallback,
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
this.socket.removeAllListeners(event.topic)
}
public unsubscribe<MessageType>(event: Event<MessageType>, callback: any) {
const item = this.callbacks.find(store => store.callback === callback)
if (!item) {
return
}
this.socket.off(event.topic, item.wrappedCallback)
this.callbacks = this.callbacks.filter(a => a !== item)
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
this.socket.emit(event.topic, msg)
}
}
@@ -0,0 +1,274 @@
import { Server as SocketIOServer, Socket } from 'socket.io'
import { Event } from '../Events'
import { EventBusInterface } from './EventBusInterface'
import Debug from 'debug'
const debug = Debug('mqtt-explorer:socketio')
const debugConnect = Debug('mqtt-explorer:socketio:connect')
const debugDisconnect = Debug('mqtt-explorer:socketio:disconnect')
const debugSubscriptions = Debug('mqtt-explorer:socketio:subscriptions')
const debugConnections = Debug('mqtt-explorer:socketio:connections')
const debugEmit = Debug('mqtt-explorer:socketio:emit')
interface SocketSubscription {
topic: string
handler: (arg: any) => void
}
export class SocketIOServerEventBus implements EventBusInterface {
private io: SocketIOServer
private clients: Map<string, Socket> = new Map() // socketId -> Socket
// Global handlers that apply to ALL sockets (like RPC endpoints)
private globalHandlers: Map<string, (socket: Socket, arg: any) => void> = new Map()
// Per-socket subscriptions for cleanup
private socketSubscriptions: Map<string, Array<SocketSubscription>> = new Map()
// Track which socket is currently processing a request
private currentSocket: Socket | undefined
// Map connectionId -> socketId to route messages to correct client
private connectionOwners: Map<string, string> = new Map()
// Track which connections to close when a socket disconnects
private socketConnections: Map<string, Set<string>> = new Map()
constructor(io: SocketIOServer) {
this.io = io
// Register connection handler once
this.io.on('connection', socket => {
debugConnect('Client connected: %s', socket.id)
this.clients.set(socket.id, socket)
this.socketSubscriptions.set(socket.id, [])
this.socketConnections.set(socket.id, new Set())
// Register all global handlers on this socket
this.globalHandlers.forEach((handler, topic) => {
this.registerHandlerOnSocket(socket, topic, handler)
})
// Log connection metrics
this.logConnectionMetrics('connect', socket.id)
socket.on('disconnect', () => {
debugDisconnect('Client disconnected: %s', socket.id)
this.cleanupSocket(socket)
this.clients.delete(socket.id)
this.logConnectionMetrics('disconnect', socket.id)
})
})
}
private logConnectionMetrics(event: 'connect' | 'disconnect', socketId: string) {
const totalClients = this.clients.size
const totalSubscriptions = Array.from(this.socketSubscriptions.values()).reduce((sum, subs) => sum + subs.length, 0)
const totalConnections = this.connectionOwners.size
const socketSubs = this.socketSubscriptions.get(socketId)?.length || 0
const socketConns = this.socketConnections.get(socketId)?.size || 0
debug(
'[%s] clients=%d subscriptions=%d mqttConns=%d | socket[%s]: subs=%d conns=%d',
event,
totalClients,
totalSubscriptions,
totalConnections,
socketId.substring(0, 8),
socketSubs,
socketConns
)
debugSubscriptions(
'Total subscriptions: %d across %d sockets (avg: %d per socket)',
totalSubscriptions,
totalClients,
totalClients > 0 ? Math.round(totalSubscriptions / totalClients) : 0
)
debugConnections(
'MQTT connections: %d total, %d owned by socket %s',
totalConnections,
socketConns,
socketId.substring(0, 8)
)
}
private registerHandlerOnSocket(socket: Socket, topic: string, handler: (socket: Socket, arg: any) => void) {
const wrappedHandler = (arg: any) => {
this.currentSocket = socket
// Track connection ownership when a connection is added
if (topic === 'connection/add/mqtt' && arg?.id) {
this.connectionOwners.set(arg.id, socket.id)
const socketConns = this.socketConnections.get(socket.id)
if (socketConns) {
socketConns.add(arg.id)
}
debugConnections(
'Connection %s owned by socket %s (total: %d)',
arg.id,
socket.id.substring(0, 8),
socketConns?.size || 0
)
}
// Remove connection ownership when a connection is removed
if (topic === 'connection/remove' && typeof arg === 'string') {
this.connectionOwners.delete(arg)
const socketConns = this.socketConnections.get(socket.id)
if (socketConns) {
socketConns.delete(arg)
}
debugConnections(
'Connection %s removed (socket %s remaining: %d)',
arg,
socket.id.substring(0, 8),
socketConns?.size || 0
)
}
handler(socket, arg)
}
socket.on(topic, wrappedHandler)
// Track subscription for cleanup
const subscriptions = this.socketSubscriptions.get(socket.id)
if (subscriptions) {
subscriptions.push({ topic, handler: wrappedHandler })
}
}
private cleanupSocket(socket: Socket) {
debugDisconnect('Cleaning up socket %s', socket.id)
// Remove all event listeners for this socket
const subscriptions = this.socketSubscriptions.get(socket.id)
if (subscriptions) {
subscriptions.forEach(({ topic, handler }) => {
socket.off(topic, handler)
})
this.socketSubscriptions.delete(socket.id)
debugSubscriptions('Removed %d subscriptions for socket %s', subscriptions.length, socket.id.substring(0, 8))
}
// Close all MQTT connections owned by this socket
const ownedConnections = this.socketConnections.get(socket.id)
if (ownedConnections && ownedConnections.size > 0) {
debugConnections(
'Socket %s owned %d connections, requesting cleanup',
socket.id.substring(0, 8),
ownedConnections.size
)
// Emit connection/remove for each owned connection
// This will be handled by ConnectionManager to actually close the MQTT connection
ownedConnections.forEach(connectionId => {
debugConnections('Auto-closing connection %s (owner disconnected)', connectionId)
// Simulate a remove request from this socket
const removeHandler = this.globalHandlers.get('connection/remove')
if (removeHandler) {
this.currentSocket = socket
removeHandler(socket, connectionId)
}
this.connectionOwners.delete(connectionId)
})
this.socketConnections.delete(socket.id)
}
// Remove from clients set
this.clients.delete(socket.id)
// Clear current socket if it was this one
if (this.currentSocket === socket) {
this.currentSocket = undefined
}
debugDisconnect('Cleanup complete for socket %s', socket.id.substring(0, 8))
}
public subscribe<MessageType>(subscribeEvent: Event<MessageType>, callback: (msg: MessageType) => void) {
const handler = (socket: Socket, arg: any) => {
this.currentSocket = socket
callback(arg)
}
// Store as global handler
this.globalHandlers.set(subscribeEvent.topic, handler)
// Register on all currently connected clients
this.clients.forEach(client => {
this.registerHandlerOnSocket(client, subscribeEvent.topic, handler)
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
// Remove from global handlers
this.globalHandlers.delete(event.topic)
// Remove from all sockets
this.clients.forEach(client => {
const subscriptions = this.socketSubscriptions.get(client.id)
if (subscriptions) {
const toRemove = subscriptions.filter(s => s.topic === event.topic)
toRemove.forEach(({ handler }) => {
client.off(event.topic, handler)
})
// Update subscriptions list
this.socketSubscriptions.set(
client.id,
subscriptions.filter(s => s.topic !== event.topic)
)
}
})
}
public unsubscribe<MessageType>(event: Event<MessageType>, callback: any) {
throw new Error('Not implemented - use unsubscribeAll instead')
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
const topic = event.topic
// Check if this is an RPC response (contains /response/ in topic)
if (topic.includes('/response/')) {
if (this.currentSocket && this.currentSocket.connected) {
this.currentSocket.emit(topic, msg)
}
return
}
// Check if this is a connection-specific event - optimized with early pattern match
// Patterns: conn/${connectionId}, conn/state/${connectionId}, conn/publish/${connectionId}
if (topic.startsWith('conn/')) {
const parts = topic.split('/')
let connectionId: string | undefined
if (parts.length === 2) {
// conn/${connectionId}
connectionId = parts[1]
} else if (parts.length === 3 && (parts[1] === 'state' || parts[1] === 'publish')) {
// conn/state/${connectionId} or conn/publish/${connectionId}
connectionId = parts[2]
}
if (connectionId) {
const ownerSocketId = this.connectionOwners.get(connectionId)
if (ownerSocketId) {
const ownerSocket = this.clients.get(ownerSocketId)
if (ownerSocket && ownerSocket.connected) {
ownerSocket.emit(topic, msg)
return
}
}
}
}
// All other events go to all clients
this.io.emit(topic, msg)
}
}
+10 -2
View File
@@ -1,4 +1,4 @@
import { Base64Message } from '../backend/src/Model/Base64Message'
import { Base64MessageDTO } from '../backend/src/Model/Base64Message'
import { DataSourceState, MqttOptions } from '../backend/src/DataSource'
import { UpdateInfo } from 'builder-util-runtime'
import { RpcEvent } from './EventSystem/Rpc'
@@ -32,7 +32,7 @@ export const updateAvailable: Event<UpdateInfo> = {
export interface MqttMessage {
topic: string
payload: Base64Message | null
payload: Base64MessageDTO | null
qos: 0 | 1 | 2
retain: boolean
// Set if QoS is > 0 on received messages
@@ -54,3 +54,11 @@ export function makeConnectionMessageEvent(connectionId: string): Event<MqttMess
export const getAppVersion: RpcEvent<void, string> = {
topic: 'getAppVersion',
}
export const writeToFile: RpcEvent<{ filePath: string; data: string; encoding?: string }, void> = {
topic: 'writeFile',
}
export const readFromFile: RpcEvent<{ filePath: string; encoding?: string }, Buffer> = {
topic: 'readFromFile',
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Simplified Event System V2
*
* This provides a simpler, more type-safe way to define and use events.
* Instead of factory functions like makeConnectionStateEvent(id),
* you can now use: Events.connectionState(id)
*/
import { Base64MessageDTO } from '../backend/src/Model/Base64Message'
import { DataSourceState, MqttOptions } from '../backend/src/DataSource'
import { UpdateInfo } from 'builder-util-runtime'
import { RpcEvent } from './EventSystem/Rpc'
export type EventV2<MessageType> = {
topic: string
}
// Simple event definitions (no parameters)
export const Events = {
// Connection management
addMqttConnection: { topic: 'connection/add/mqtt' } as EventV2<AddMqttConnectionV2>,
removeConnection: { topic: 'connection/remove' } as EventV2<string>,
updateAvailable: { topic: 'app/update/available' } as EventV2<UpdateInfo>,
// Parameterized events (for connection-specific events)
connectionState: (connectionId: string) => ({ topic: `conn/state/${connectionId}` }) as EventV2<DataSourceState>,
connectionMessage: (connectionId: string) => ({ topic: `conn/${connectionId}` }) as EventV2<MqttMessageV2>,
publish: (connectionId: string) => ({ topic: `conn/publish/${connectionId}` }) as EventV2<MqttMessageV2>,
}
// RPC Events - type-safe request/response patterns
export const RpcEvents = {
getAppVersion: { topic: 'getAppVersion' } as RpcEvent<void, string>,
writeToFile: { topic: 'writeFile' } as RpcEvent<{ filePath: string; data: string; encoding?: string }, void>,
readFromFile: { topic: 'readFromFile' } as RpcEvent<{ filePath: string; encoding?: string }, Buffer>,
openDialog: { topic: 'openDialog' } as RpcEvent<OpenDialogOptionsV2, OpenDialogReturnValueV2>,
saveDialog: { topic: 'saveDialog' } as RpcEvent<SaveDialogOptionsV2, SaveDialogReturnValueV2>,
uploadCertificate: { topic: 'uploadCertificate' } as RpcEvent<CertificateUploadRequest, CertificateUploadResponse>,
}
// Type definitions
export interface AddMqttConnectionV2 {
id: string
options: MqttOptions
}
export interface MqttMessageV2 {
topic: string
payload: Base64MessageDTO | null
qos: 0 | 1 | 2
retain: boolean
messageId: number | undefined
}
export interface CertificateUploadRequest {
filename: string
data: string // base64 encoded
}
export interface CertificateUploadResponse {
name: string
data: string // base64 encoded
}
// Electron dialog types (re-exported for convenience)
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
export type OpenDialogOptionsV2 = OpenDialogOptions
export type OpenDialogReturnValueV2 = OpenDialogReturnValue
export type SaveDialogOptionsV2 = SaveDialogOptions
export type SaveDialogReturnValueV2 = SaveDialogReturnValue
+8 -1
View File
@@ -1,8 +1,15 @@
import { OpenDialogOptions, OpenDialogReturnValue } from 'electron'
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
import { RpcEvent } from './EventSystem/Rpc'
// Legacy functions - use RpcEvents from EventsV2.ts for new code
export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogReturnValue> {
return {
topic: 'openDialog',
}
}
export function makeSaveDialogRpc(): RpcEvent<SaveDialogOptions, SaveDialogReturnValue> {
return {
topic: 'saveDialog',
}
}
+1
View File
@@ -1,4 +1,5 @@
export * from './Events'
export * from './EventsV2'
export * from './EventSystem/EventDispatcher'
export * from './EventSystem/EventBus'
export * from './EventSystem/EventBusInterface'
+14
View File
@@ -0,0 +1,14 @@
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-playwright"
],
"env": {
"PLAYWRIGHT_BROWSERS_PATH": "0"
}
}
}
}
+18 -3
View File
@@ -4,18 +4,24 @@
"description": "Explore your message queues",
"main": "dist/src/electron.js",
"engines": {
"node": ">=18"
"node": ">=20"
},
"private": "true",
"scripts": {
"start": "electron .",
"start:server": "npx tsc && node dist/src/server.js",
"test": "yarn test:app && yarn test:backend",
"test:app": "cd app && yarn test",
"test:backend": "cd backend && yarn test",
"test:ui": "tsc && mocha --require source-map-support/register dist/src/spec/ui-tests.spec.js",
"test:mcp": "tsc && node dist/src/spec/testMcpIntrospection.js",
"install": "cd app && yarn && cd ..",
"dev": "npm-run-all --parallel dev:*",
"dev:app": "cd app && npm run dev",
"dev:electron": "tsc && electron . --development",
"dev:server": "npm-run-all --parallel dev:server:*",
"dev:server:app": "cd app && npx webpack-dev-server --config webpack.browser.config.js --mode development --progress",
"dev:server:backend": "tsc && node dist/src/server.js",
"lint": "npm-run-all --parallel lint:prettier lint:tslint lint:spellcheck",
"lint:fix": "npm-run-all lint:tslint:fix lint:prettier:fix",
"lint:prettier": "prettier --check \"**/*.ts{x,}\"",
@@ -24,6 +30,7 @@
"lint:tslint:fix": "tslint -p ./ --fix",
"lint:spellcheck": "cspell -e ./build -e \"node_modules\" \"**/*.ts{x,}\"",
"build": "tsc && cd app && yarn run build && cd ..",
"build:server": "npx tsc && cd app && npx webpack --config webpack.browser.config.js --mode production && cd ..",
"prepare-release": "ts-node scripts/prepare-release.ts",
"package": "ts-node package.ts",
"ui-test": "./scripts/uiTests.sh",
@@ -82,20 +89,23 @@
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/commit-analyzer": "^12.0.0",
"@semantic-release/git": "^10.0.1",
"@types/bcryptjs": "^3.0.0",
"@types/chai": "^4.1.7",
"@types/express": "^5.0.6",
"@types/fs-extra": "8",
"@types/lowdb": "^1.0.6",
"@types/mime": "^2.0.0",
"@types/mocha": "^7.0.2",
"@types/mustache": "4",
"@types/node": "^12.6.8",
"@types/node": "^25.0.3",
"@types/semver": "7",
"@types/sha1": "^1.1.1",
"@types/socket.io": "^3.0.2",
"@types/uuid": "^8.3.4",
"builder-util-runtime": "^9",
"chai": "^4.2.0",
"cspell": "^8.6.1",
"electron": "29.2.0",
"electron": "39.2.7",
"electron-builder": "^24.13.3",
"mocha": "^10.4.0",
"mustache": "4",
@@ -118,16 +128,21 @@
"dependencies": {
"about-window": "^1.12.1",
"axios": "^0.28.0",
"bcryptjs": "^3.0.3",
"debug": "^4.3.4",
"dot-prop": "^5.0.0",
"electron-log": "4.4.6",
"electron-updater": "^4.6",
"express": "^5.2.1",
"fs-extra": "9",
"js-base64": "^3.7.2",
"json-to-ast": "^2.1.0",
"lowdb": "^1.0.0",
"mime": "^2.4.4",
"mqtt": "^4.3.6",
"protobufjs": "^8.0.0",
"sha1": "^1.1.1",
"socket.io": "^4.8.1",
"sparkplug-payload": "^1.0.3",
"uuid": "^8.3.2",
"yarn-run-all": "^3.1.1"
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
set -e
function finish {
set +e
echo "Exiting, cleaning up.."
if [[ ! -z "$PID_MOSQUITTO" ]]; then
echo "Stopping mosquitto ($PID_MOSQUITTO).."
kill "$PID_MOSQUITTO" || echo "Already stopped"
fi
if [[ ! -z "$PID_XVFB" ]]; then
echo "Stopping XVFB ($PID_XVFB).."
kill "$PID_XVFB" || echo "Already stopped"
fi
}
trap finish EXIT
DIMENSIONS="1024x720"
SCR=99
# Start new window manager
Xvfb :$SCR -screen 0 "$DIMENSIONS"x24 -ac &
export PID_XVFB=$!
sleep 2
# Start mqtt broker
mosquitto &
export PID_MOSQUITTO=$!
sleep 1
# Run UI tests
DISPLAY=:$SCR yarn test:ui
TEST_EXIT_CODE=$?
echo "UI tests exited with $TEST_EXIT_CODE"
exit $TEST_EXIT_CODE
+94
View File
@@ -0,0 +1,94 @@
import * as fs from 'fs'
import * as path from 'path'
import * as bcrypt from 'bcryptjs'
import { v4 as uuidv4 } from 'uuid'
export interface Credentials {
username: string
passwordHash: string
}
export class AuthManager {
private credentialsPath: string
private credentials: Credentials | undefined
constructor(credentialsPath: string) {
this.credentialsPath = credentialsPath
}
public async initialize(): Promise<void> {
// Try to get credentials from environment variables
const envUsername = process.env.MQTT_EXPLORER_USERNAME
const envPassword = process.env.MQTT_EXPLORER_PASSWORD
if (envUsername && envPassword) {
// Use environment credentials
console.log('Using credentials from environment variables')
console.log('Username:', envUsername)
this.credentials = {
username: envUsername,
passwordHash: await bcrypt.hash(envPassword, 10),
}
return
}
// Try to load from file
if (fs.existsSync(this.credentialsPath)) {
try {
const data = fs.readFileSync(this.credentialsPath, 'utf8')
this.credentials = JSON.parse(data)
console.log('Loaded credentials from', this.credentialsPath)
console.log('Username:', this.credentials!.username)
return
} catch (error) {
console.error('Failed to load credentials from file:', error)
}
}
// Generate new credentials
const username = `user-${uuidv4().substring(0, 8)}`
const password = uuidv4()
console.log('='.repeat(60))
console.log('Generated new credentials:')
console.log('Username:', username)
console.log('Password:', password)
console.log('='.repeat(60))
console.log('Please save these credentials. They will be persisted to:')
console.log(this.credentialsPath)
console.log('='.repeat(60))
this.credentials = {
username,
passwordHash: await bcrypt.hash(password, 10),
}
// Save to file
try {
const dir = path.dirname(this.credentialsPath)
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
fs.writeFileSync(this.credentialsPath, JSON.stringify(this.credentials, null, 2))
console.log('Credentials saved successfully')
} catch (error) {
console.error('Failed to save credentials:', error)
}
}
public async verifyCredentials(username: string, password: string): Promise<boolean> {
if (!this.credentials) {
return false
}
if (username !== this.credentials.username) {
return false
}
return bcrypt.compare(password, this.credentials.passwordHash)
}
public getUsername(): string | undefined {
return this.credentials?.username
}
}
+19
View File
@@ -32,3 +32,22 @@ export function isDev() {
export function runningUiTestOnCi() {
return Boolean(process.argv.find(arg => arg === '--runningUiTestOnCi'))
}
export function enableMcpIntrospection() {
return Boolean(process.argv.find(arg => arg === '--enable-mcp-introspection'))
}
export function getRemoteDebuggingPort() {
const portArg = process.argv.find(arg => arg.startsWith('--remote-debugging-port='))
if (portArg) {
const parts = portArg.split('=')
if (parts.length === 2 && parts[1]) {
const port = parseInt(parts[1], 10)
// Return the port only if it's a valid number between 1 and 65535
if (!isNaN(port) && port > 0 && port <= 65535) {
return port
}
}
}
return enableMcpIntrospection() ? 9222 : undefined
}
+51 -8
View File
@@ -4,14 +4,23 @@ import ConfigStorage from '../backend/src/ConfigStorage'
import { app, BrowserWindow, Menu, dialog } from 'electron'
import { autoUpdater } from 'electron-updater'
import { ConnectionManager } from '../backend/src/index'
import { promises as fsPromise } from 'fs'
// import { electronTelemetryFactory } from 'electron-telemetry'
import { menuTemplate } from './MenuTemplate'
import buildOptions from './buildOptions'
import { waitForDevServer, isDev, runningUiTestOnCi, loadDevTools } from './development'
import {
waitForDevServer,
isDev,
runningUiTestOnCi,
loadDevTools,
enableMcpIntrospection,
getRemoteDebuggingPort,
} from './development'
import { shouldAutoUpdate, handleAutoUpdate } from './autoUpdater'
import { registerCrashReporter } from './registerCrashReporter'
import { makeOpenDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion } from '../events'
import { makeOpenDialogRpc, makeSaveDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, backendEvents, getAppVersion, writeToFile, readFromFile } from '../events'
import { RpcEvents } from '../events/EventsV2'
registerCrashReporter()
@@ -19,21 +28,57 @@ registerCrashReporter()
// const electronTelemetry = electronTelemetryFactory('9b0c8ca04a361eb8160d98c5', buildOptions)
// }
app.commandLine.appendSwitch('--no-sandbox')
// disable-dev-shm-usage is required to run the debug console
app.commandLine.appendSwitch('--no-sandbox --disable-dev-shm-usage')
// Enable remote debugging for MCP introspection
const remoteDebuggingPort = getRemoteDebuggingPort()
if (remoteDebuggingPort) {
app.commandLine.appendSwitch('--remote-debugging-port', remoteDebuggingPort.toString())
log.info(`Remote debugging enabled on port ${remoteDebuggingPort}`)
}
app.whenReady().then(() => {
backendRpc.on(makeOpenDialogRpc(), async request => {
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(makeSaveDialogRpc(), async request => {
return dialog.showSaveDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(getAppVersion, async () => app.getVersion())
backendRpc.on(writeToFile, async ({ filePath, data, encoding }) => {
await fsPromise.writeFile(filePath, Buffer.from(data, 'base64'), { encoding: encoding as BufferEncoding })
})
backendRpc.on(readFromFile, async ({ filePath, encoding }) => {
if (encoding) {
const content = await fsPromise.readFile(filePath, { encoding: encoding as BufferEncoding })
return Buffer.from(content)
}
return fsPromise.readFile(filePath)
})
// Certificate upload handler - works for both Electron and browser mode via IPC
backendRpc.on(RpcEvents.uploadCertificate, async ({ filename, data }) => {
// In Electron, we just return the data as-is since it's already read
// The client will use it directly
return {
name: filename,
data,
}
})
})
autoUpdater.logger = log
log.info('App starting...')
const connectionManager = new ConnectionManager()
const connectionManager = new ConnectionManager(backendEvents)
connectionManager.manageConnections()
const configStorage = new ConfigStorage(path.join(app.getPath('userData'), 'settings.json'))
const configStorage = new ConfigStorage(path.join(app.getPath('userData'), 'settings.json'), backendRpc)
configStorage.init()
// Keep a global reference of the window object, if you don't, the window will
@@ -69,8 +114,6 @@ async function createWindow() {
}
})
console.log('icon path', iconPath)
// Load the index.html of the app.
if (isDev()) {
mainWindow.loadURL('http://localhost:8080')
+177
View File
@@ -0,0 +1,177 @@
import express from 'express'
import * as http from 'http'
import * as path from 'path'
import { Server } from 'socket.io'
import { promises as fsPromise } from 'fs'
import { Request, Response } from 'express'
import { AuthManager } from './AuthManager'
import { ConnectionManager } from '../backend/src/index'
import ConfigStorage from '../backend/src/ConfigStorage'
import { SocketIOServerEventBus } from '../events/EventSystem/SocketIOServerEventBus'
import { Rpc } from '../events/EventSystem/Rpc'
import { makeOpenDialogRpc, makeSaveDialogRpc } from '../events/OpenDialogRequest'
import { getAppVersion, writeToFile, readFromFile } from '../events'
import { RpcEvents } from '../events/EventsV2'
const PORT = process.env.PORT || 3000
const CREDENTIALS_PATH = path.join(process.cwd(), 'data', 'credentials.json')
async function startServer() {
// Initialize authentication
const authManager = new AuthManager(CREDENTIALS_PATH)
await authManager.initialize()
// Create Express app
const app = express()
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
allowEIO3: true, // Allow Engine.IO v3 clients (backwards compatibility)
transports: ['websocket', 'polling'], // Support both transports
pingTimeout: 60000, // Increase ping timeout
pingInterval: 25000, // Ping interval
})
// Authentication middleware for Socket.io
io.use(async (socket, next) => {
const { username, password } = socket.handshake.auth
if (!username || !password) {
return next(new Error('Authentication required'))
}
const isValid = await authManager.verifyCredentials(username, password)
if (!isValid) {
return next(new Error('Invalid credentials'))
}
console.log('Client authenticated:', username)
next()
})
// Initialize backend event bus with Socket.io
const backendEvents = new SocketIOServerEventBus(io)
const backendRpc = new Rpc(backendEvents)
// Initialize connection manager
const connectionManager = new ConnectionManager(backendEvents)
connectionManager.manageConnections()
// Initialize config storage
const configStorage = new ConfigStorage(path.join(process.cwd(), 'data', 'settings.json'), backendRpc)
configStorage.init()
// Setup RPC handlers for file operations
backendRpc.on(makeOpenDialogRpc(), async request => {
// In browser mode, file selection is handled client-side via upload
// Return empty result as this will be handled differently
return { canceled: true, filePaths: [] }
})
backendRpc.on(makeSaveDialogRpc(), async request => {
// In browser mode, file saving is handled client-side via download
return { canceled: true, filePath: '' }
})
backendRpc.on(getAppVersion, async () => {
// Return version from package.json
try {
const packageJsonPath = path.join(__dirname, '..', '..', 'package.json')
const packageJsonData = await fsPromise.readFile(packageJsonPath, 'utf8')
const packageJson = JSON.parse(packageJsonData)
return packageJson.version
} catch (e) {
return '0.0.0'
}
})
backendRpc.on(writeToFile, async ({ filePath, data, encoding }) => {
// In browser mode, we store files in the server's data directory
const dataDir = path.join(process.cwd(), 'data', 'uploads')
const safePath = path.join(dataDir, path.basename(filePath))
try {
await fsPromise.mkdir(dataDir, { recursive: true })
if (encoding) {
await fsPromise.writeFile(safePath, Buffer.from(data, 'base64'), { encoding: encoding as BufferEncoding })
} else {
await fsPromise.writeFile(safePath, Buffer.from(data, 'base64'))
}
} catch (error) {
console.error('Error writing file:', error)
throw error
}
})
backendRpc.on(readFromFile, async ({ filePath, encoding }) => {
// In browser mode, files are read from the server's data directory
const dataDir = path.join(process.cwd(), 'data', 'uploads')
const safePath = path.join(dataDir, path.basename(filePath))
try {
if (encoding) {
const content = await fsPromise.readFile(safePath, { encoding: encoding as BufferEncoding })
return Buffer.from(content)
}
return await fsPromise.readFile(safePath)
} catch (error) {
console.error('Error reading file:', error)
throw error
}
})
// Certificate upload handler - via IPC for consistency
backendRpc.on(RpcEvents.uploadCertificate, async ({ filename, data }) => {
// Store certificate on server for browser mode
const dataDir = path.join(process.cwd(), 'data', 'certificates')
await fsPromise.mkdir(dataDir, { recursive: true })
const safePath = path.join(dataDir, path.basename(filename))
await fsPromise.writeFile(safePath, Buffer.from(data, 'base64'))
console.log('Certificate uploaded:', filename)
// Return the certificate data for client to use
return {
name: filename,
data,
}
})
// Serve static files
app.use(express.static(path.join(__dirname, '..', '..', 'app', 'build')))
// Serve index.html for all other routes (SPA)
app.use((req: Request, res: Response) => {
res.sendFile(path.join(__dirname, '..', '..', 'app', 'index.html'))
})
// Start server
server.listen(PORT, () => {
console.log('='.repeat(60))
console.log(`MQTT Explorer server running on http://localhost:${PORT}`)
console.log('='.repeat(60))
})
// Handle graceful shutdown
process.on('SIGTERM' as any, () => {
console.log('SIGTERM received, closing connections...')
connectionManager.closeAllConnections()
server.close()
})
process.on('SIGINT' as any, () => {
console.log('SIGINT received, closing connections...')
connectionManager.closeAllConnections()
server.close()
process.exit(0)
})
}
startServer().catch(error => {
console.error('Failed to start server:', error)
process.exit(1)
})
+1
View File
@@ -19,6 +19,7 @@ export type SceneNames =
| 'settings'
| 'customize_subscriptions'
| 'keyboard_shortcuts'
| 'sparkplugb-decoding'
| 'end'
export class SceneBuilder {
+22 -1
View File
@@ -21,6 +21,7 @@ import { showMenu } from './scenarios/showMenu'
import { showNumericPlot } from './scenarios/showNumericPlot'
import { showOffDiffCapability } from './scenarios/showOffDiffCapability'
import { showZoomLevel } from './scenarios/showZoomLevel'
import { showSparkPlugDecoding } from './scenarios/showSparkplugDecoding'
/**
* A convenience method that handles gracefully cleaning up the test run.
@@ -31,11 +32,19 @@ const cleanUp = async (scenes: SceneBuilder, electronApp: ElectronApplication) =
await electronApp.close()
}
process.on('unhandledRejection', (error: Error | any) => {
process.on('unhandledRejection' as any, (error: Error | any) => {
console.error('unhandledRejection', error.message, error.stack)
process.exit(1)
})
setTimeout(
() => {
console.error('Timeout reached')
process.exit(1)
},
60 * 10 * 1000
)
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
async function doStuff() {
@@ -112,6 +121,11 @@ async function doStuff() {
await sleep(1000)
})
await scenes.record('sparkplugb-decoding', async () => {
await showText('SparkplugB Decoding', 2000, page, 'top')
await showSparkPlugDecoding(page)
})
// disable this scenario for now until expandTopic is sorted out
// await scenes.record('delete_retained_topics', async () => {
// await hideText(page)
@@ -143,10 +157,17 @@ async function doStuff() {
await sleep(3000)
})
setTimeout(() => {
console.log('Forced quit')
process.exit(0)
}, 10 * 1000)
stopMqtt()
console.log('Stopped mqtt client')
cleanUp(scenes, electronApp)
// Force exit since there appear to be open handles
process.exit(0)
}
doStuff()
+1 -1
View File
@@ -7,7 +7,7 @@ import { clearSearch, searchTree } from './scenarios/searchTree'
import { connectTo } from './scenarios/connect'
import { reconnect } from './scenarios/reconnect'
process.on('unhandledRejection', (error: Error | any) => {
process.on('unhandledRejection' as any, (error: Error | any) => {
console.error('unhandledRejection', error.message, error.stack)
process.exit(1)
})
+40
View File
@@ -0,0 +1,40 @@
import * as mqtt from 'mqtt'
/**
* Test-specific MQTT mock (no timers)
*
* This mock connects to the broker but doesn't publish any messages automatically.
* Each test should publish only the messages it needs via the returned client.
*
* This is different from the demo video mock which uses timers.
*/
let mqttClient: mqtt.MqttClient | null = null
export async function createTestMock(): Promise<mqtt.MqttClient> {
if (mqttClient) {
return mqttClient
}
return new Promise(resolve => {
const client = mqtt.connect('mqtt://127.0.0.1:1883', {
username: '',
password: '',
})
client.once('connect', () => {
mqttClient = client
resolve(client)
})
})
}
export function stopTestMock() {
if (mqttClient) {
try {
mqttClient.end()
mqttClient = null
} catch {
// ignore
}
}
}
+215 -219
View File
@@ -18,232 +18,228 @@ import type { UMetric } from 'sparkplug-payload/lib/sparkplugbpayload'
* Main sample function which includes the run() function for running the sample
*/
export interface MockSparkplugClient {
stop: () => void
stop: () => void
}
var sample = (function () {
var config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
let sample = (function () {
let config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
},
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'Boolean',
value: false,
},
{
name: 'Template1',
type: 'Template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'Boolean' },
{ name: 'myInt', value: 0, type: 'UInt32' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value1',
},
],
},
},
],
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'Boolean',
value: false,
},
{
name: 'Template1',
type: 'Template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'Boolean' },
{ name: 'myInt', value: 0, type: 'UInt32' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value1',
},
],
},
},
],
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'Float' },
{ name: 'my_int', value: randomInt(), type: 'Int8' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'Int64' },
{ name: 'Inputs/0', value: true, type: 'Boolean' },
{ name: 'Inputs/1', value: 0, type: 'Int8' },
{ name: 'Inputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Outputs/0', value: true, type: 'Boolean' },
{ name: 'Outputs/1', value: 0, type: 'Int16' },
{ name: 'Outputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'String' },
{ name: 'Properties/sw_version', value: swVersion, type: 'String' },
{
name: 'my_dataset',
type: 'DataSet',
value: {
numOfColumns: 2,
types: ['String', 'String'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'Template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'Boolean' },
{ name: 'myInt', value: 100, type: 'Int8' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value2',
},
],
},
},
],
}
},
// Get data payload for the device
getDataPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'UInt64' },
{ name: 'my_int', value: randomInt(), type: 'Int16' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'UInt64' },
],
}
},
// Runs the sample
run = async function (): Promise<MockSparkplugClient> {
// Create the SparkplugClient
const sparkplugClient = SparkplugClient.newClient(config)
let updateInterval: NodeJS.Timeout | null = null
const connected = new Promise<MockSparkplugClient>(resolve => {
// Create 'birth' handler
sparkplugClient.on('birth', () => {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
resolve({
stop: () => {
if (updateInterval) {
clearInterval(updateInterval)
}
sparkplugClient.stop()
},
})
})
})
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic: string, payload: UPayload) {
console.log(topic, payload)
})
// Create node command handler
// spell-checker: disable-next-line
sparkplugClient.on('ncmd', function (payload: UPayload) {
let timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (let i = 0; i < metrics.length; i++) {
let metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'Float' },
{ name: 'my_int', value: randomInt(), type: 'Int8' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'Int64' },
{ name: 'Inputs/0', value: true, type: 'Boolean' },
{ name: 'Inputs/1', value: 0, type: 'Int8' },
{ name: 'Inputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Outputs/0', value: true, type: 'Boolean' },
{ name: 'Outputs/1', value: 0, type: 'Int16' },
{ name: 'Outputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'String' },
{ name: 'Properties/sw_version', value: swVersion, type: 'String' },
{
name: 'my_dataset',
type: 'DataSet',
value: {
numOfColumns: 2,
types: ['String', 'String'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'Template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'Boolean' },
{ name: 'myInt', value: 100, type: 'Int8' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value2',
},
],
},
},
],
}
}
})
// Create device command handler
// spell-checker: disable-next-line
sparkplugClient.on('dcmd', function (deviceId: string, payload: UPayload) {
let timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap: { [name: string]: any } = {},
outboundMetric: Array<UMetric> = [],
outboundPayload: UPayload
console.log('Command received for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (let i = 0; i < metrics.length; i++) {
let metric = metrics[i]
if (metric.name !== undefined && metric.name !== null) {
inboundMetricMap[metric.name] = metric.value
}
},
// Get data payload for the device
getDataPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'UInt64' },
{ name: 'my_int', value: randomInt(), type: 'Int16' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'UInt64' },
],
}
},
// Runs the sample
run = async function (): Promise<MockSparkplugClient> {
// Create the SparkplugClient
const sparkplugClient = SparkplugClient.newClient(config)
let updateInterval: NodeJS.Timeout | null = null
const connected = new Promise<MockSparkplugClient>((resolve) => {
// Create 'birth' handler
sparkplugClient.on('birth', () => {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
resolve({
stop: () => {
if (updateInterval) {
clearInterval(updateInterval)
}
sparkplugClient.stop()
}
})
})
})
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic: string, payload: UPayload) {
console.log(topic, payload)
})
// Create node command handler
// spell-checker: disable-next-line
sparkplugClient.on('ncmd', function (payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
}
}
})
// Create device command handler
// spell-checker: disable-next-line
sparkplugClient.on('dcmd', function (deviceId: string, payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap: { [name: string]: any } = {},
outboundMetric: Array<UMetric> = [],
outboundPayload: UPayload
console.log('Command received for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name !== undefined && metric.name !== null) {
inboundMetricMap[metric.name] = metric.value
}
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
updateInterval = setInterval(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
}, 2000)
return connected
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
return { run: run }
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
updateInterval = setInterval(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
}, 2000)
return connected
}
return { run }
})()
export default sample
export default sample
+1 -1
View File
@@ -2,6 +2,6 @@ import { Page } from 'playwright'
import { clickOn } from '../util'
export async function copyValueToClipboard(browser: Page) {
const copyButton = await browser.locator('//span[contains(text(), "Value")]//button')
const copyButton = await browser.getByRole('button', { name: 'Value' }).getByRole('button').first()
await clickOn(copyButton, 1)
}
+3 -2
View File
@@ -14,7 +14,7 @@ export async function publishTopic(browser: Page) {
const topicInput = await browser.locator('//input[contains(@value,"kitchen/lamp/state")][1]')
await clickOn(topicInput)
await deleteTextWithBackspaces(topicInput, 120, 5)
await writeText('set', topicInput, 300)
await writeText('set', topicInput)
const payloadInput = await browser.locator('//*[contains(@class, "ace_text-input")]')
await writeTextPayload(payloadInput, 'off')
@@ -34,5 +34,6 @@ export async function publishTopic(browser: Page) {
}
async function writeTextPayload(payloadInput: Locator, text: string) {
await payloadInput.fill(text)
await clickOn(payloadInput)
await writeText(text, payloadInput)
}
+2 -1
View File
@@ -4,7 +4,7 @@ import { clickOn, deleteTextWithBackspaces, showText, sleep, writeText } from '.
export async function searchTree(text: string, browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await writeText(text, searchField, 100)
await writeText(text, searchField)
await sleep(1500)
}
@@ -12,4 +12,5 @@ export async function clearSearch(browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await deleteTextWithBackspaces(searchField, 100)
await sleep(300) // Give time for search to clear and tree to rerender
}
+5 -3
View File
@@ -1,5 +1,5 @@
import { Page } from 'playwright'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep, writeText } from '../util'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep } from '../util'
export async function showNumericPlot(browser: Page) {
await expandTopic('kitchen/coffee_maker', browser)
@@ -45,12 +45,14 @@ export async function showNumericPlot(browser: Page) {
async function valuePreviewGuttersShowChartIcon(name: string, browser: Page) {
for (let retries = 0; retries < 2; retries += 1) {
try {
return await browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
return await browser
.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
.first()
} catch {
// ignore
}
}
return browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
return browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`).first()
}
async function chartSettings(name: string, browser: Page) {
@@ -0,0 +1,9 @@
import { Page } from 'playwright'
import { expandTopic, sleep } from '../util'
export async function showSparkPlugDecoding(browser: Page) {
// spell-checker: disable-next-line
await expandTopic('spBv1.0/Sparkplug Devices/DDATA/JavaScript Edge Node/Emulated Device', browser)
await browser.screenshot({ path: 'screen_sparkplugb_decoding.png' })
await sleep(1000)
}

Some files were not shown because too many files have changed in this diff Show More