Compare commits

..
Author SHA1 Message Date
Björn Dalfors 69897b4345 test packaging 2024-03-11 13:36:28 +01:00
136 changed files with 4018 additions and 13608 deletions
+7 -13
View File
@@ -1,11 +1,4 @@
{
"import": [
"@cspell/dict-typescript/cspell-ext.json"
],
"ignoreRegExpList": [
"import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t\\{\\},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*\\{(?:[ \\n\\t]*[^ \\n\\t\"'\\{\\}]+[ \\n\\t]*,?)+\\})?[ \\n\\t]*)|[ \n\\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t\\{\\}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])\n",
"^import\\s+(['\"]).*\\1$"
],
"language": "en",
"words": [
"Bbreak",
@@ -15,13 +8,15 @@
"nowrap",
"subheader",
"basepath",
"webdriverio",
"repo",
"hexagonalize",
"pixelize",
"Transistions",
"squashfs",
"squashfs",
"provisionprofile",
"Nsis",
"webdriverio",
"Appx",
"Hashable",
"clickaway",
@@ -31,6 +26,8 @@
"Monokai",
"plottable",
"snackbar",
"webdriverio",
"prismjs",
"Nordquist",
"debounced",
"mosquitto",
@@ -50,9 +47,6 @@
"mixins",
"Explorerdmg",
"heapsnapshot",
"noconflict",
"sparkplugb",
"protojson",
"typesafe"
"noconflict"
]
}
}
-46
View File
@@ -1,46 +0,0 @@
{
"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
@@ -1,21 +0,0 @@
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
@@ -1,4 +0,0 @@
# Mosquitto configuration for development
listener 1883
allow_anonymous true
persistence false
-3
View File
@@ -1,3 +0,0 @@
package.ts @thomasnordquist
.github @thomasnordquist
scripts @thomasnordquist
-383
View File
@@ -1,383 +0,0 @@
# 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
-29
View File
@@ -1,29 +0,0 @@
on:
push:
branches:
- master
- release
- beta
paths:
- Dockerfile
- .github
jobs:
create-image:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
-39
View File
@@ -1,39 +0,0 @@
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
-53
View File
@@ -1,53 +0,0 @@
name: Build
on:
push:
branches:
- release
- beta
concurrency:
group: ${{ github.ref }}
cancel-in-progress: false
jobs:
build:
strategy:
matrix:
build:
- os: ubuntu-latest
task: linux
- os: windows-latest
task: win
- os: macos-latest
task: mac
runs-on: ${{ matrix.build.os }}
steps:
- if: matrix.build.os == 'ubuntu-latest'
run: sudo snap install snapcraft --classic
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install -g yarn
- run: yarn
- id: create_token # get ReleaseBot access token
uses: tibdex/github-app-token@v2
with:
app_id: ${{ secrets.RELEASE_BOT_APP_ID }}
private_key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}
- name: Semantic Release
uses: cycjimmy/semantic-release-action@v4
id: semantic # Need an `id` for output variables
env:
GITHUB_TOKEN: ${{ steps.create_token.outputs.token }}
- run: yarn build
if: steps.semantic.outputs.new_release_published == 'true'
- run: yarn prepare-release
if: steps.semantic.outputs.new_release_published == 'true'
- run: yarn package ${{ matrix.build.task }}
if: steps.semantic.outputs.new_release_published == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
-127
View File
@@ -1,127 +0,0 @@
on:
pull_request_target: # Use pull_request_target
branches: [master, beta, release]
jobs:
test:
runs-on: ubuntu-latest
container:
image: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
volumes:
- ./:/app
options: --user root
steps:
- uses: actions/checkout@v4
- name: Install Packages
run: yarn install --frozen-lockfile
- name: Build
run: yarn build
- name: Test
run: yarn 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
- 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
- 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
- uses: hkusu/s3-upload-action@v2
id: upload # specify some ID for use in subsequent steps
with:
aws-access-key-id: ${{ vars.AWS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: 'eu-central-1'
aws-bucket: ${{ vars.AWS_BUCKET }}
file-path: './ui-test.gif'
content-type: image/gif
output-file-url: 'true'
- name: Show URL
run: echo '${{ steps.upload.outputs.file-url }}'
id: artifact-upload-step
- 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
- 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
-17
View File
@@ -1,17 +0,0 @@
name: Update Website
on: [release, workflow_dispatch]
jobs:
update-website:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: gh-pages
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install
- run: npm run readme
- uses: stefanzweifel/git-auto-commit-action@v5
-8
View File
@@ -9,11 +9,3 @@ 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
+1
View File
@@ -0,0 +1 @@
engine-strict=true
-30
View File
@@ -1,30 +0,0 @@
{
"branches": [
"release",
{
"name": "beta",
"prerelease": true
}
],
repositoryUrl: "git@github.com:thomasnordquist/MQTT-Explorer.git",
"plugins": [
"@semantic-release/commit-analyzer",
"semantic-release-export-data",
"@semantic-release/changelog",
[
"@semantic-release/npm",
{
"npmPublish": false
}
],
[
"@semantic-release/git",
{
"assets": [
"package.json",
"yarn.lock"
]
}
]
]
}
+46
View File
@@ -0,0 +1,46 @@
language: node_js
services:
- xvfb
cache:
directories:
- node_modules
- $HOME/.cache/electron
- $HOME/.cache/electron-builder
- $HOME/.npm/_prebuilds
node_js:
- "10"
os:
- linux
- osx
osx_image: xcode10.2
dist: bionic
services:
- docker
install:
- yarn install
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get update && sudo apt-get -y install snap squashfs-tools && sudo snap install snapcraft --classic; fi;
script:
- yarn run build
- yarn lint
- yarn test
- export TRAVIS_BUILD_NUMBER="" # Override travis build number since it is uses for tagging the binary version https://github.com/electron-userland/electron-builder/issues/3730
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then docker run -e GH_TOKEN=$GH_TOKEN -e GIT_TAG=$TRAVIS_TAG --rm -v `pwd`:/app thomasnordquist/ui-test-recording-env sh -c "cd app && docker/testMounted.sh"; fi
- if [[ "$TRAVIS_TAG" != "" ]]; then yarn run prepare-release; fi
- |
if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_TAG" != "" ]]; then
openssl aes-256-cbc -d -in res/snapstore-credentials.enc -out credentials -k $SNAPSTORE_CREDENTIALS_DECRYPTION_KEY;
snapcraft login --with credentials;
rm credentials;
yarn run package linux;
fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then yarn run package -- mac; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then unset CSC_LINK; yarn run package -- win; fi
-193
View File
@@ -1,193 +0,0 @@
# 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
@@ -1,149 +0,0 @@
# 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
+24 -39
View File
@@ -1,10 +1,10 @@
When redistributing, the attribution page may not be altered or made less accessible without explicit approval.
## creative commons
# Creative Commons Attribution-ShareAlike 4.0 International
# Attribution-NoDerivatives 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,37 +12,31 @@ 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-ShareAlike 4.0 International Public License
## Creative Commons Attribution-NoDerivatives 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-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.
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.
### 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. __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.
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.
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.
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.
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.
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.
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.
e. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public 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.
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.
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.
g. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
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.
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.
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.
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.
j. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
@@ -52,7 +46,7 @@ a. ___License grant.___
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
B. produce and reproduce, but not 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.
@@ -64,9 +58,7 @@ 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. __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.
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.
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).
@@ -84,7 +76,7 @@ Your exercise of the Licensed Rights is expressly made subject to the following
a. ___Attribution.___
1. If You Share the Licensed Material (including in modified form), You must:
1. If You Share the Licensed Material, You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
@@ -102,27 +94,19 @@ 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;
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;
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
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
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.
@@ -168,6 +152,7 @@ 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.” 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 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 may be contacted at creativecommons.org.
> Creative Commons may be contacted at creativecommons.org
+19 -76
View File
@@ -6,34 +6,19 @@
[![Build status](https://ci.appveyor.com/api/projects/status/c35tkm29rm4m5364/branch/master?svg=true)](https://ci.appveyor.com/project/thomasnordquist/mqtt-explorer/branch/master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/47b26e03fce543ceac7914214482334a)](https://app.codacy.com/app/thomasnordquist/MQTT-Explorer?utm_source=github.com&utm_medium=referral&utm_content=thomasnordquist/MQTT-Explorer&utm_campaign=Badge_Grade_Dashboard)
| | | |
| :---------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: |
| [![screen_composite](https://mqtt-explorer.com/img/screen-composite_small.png)](https://mqtt-explorer.com/img/screen-composite.png) | [![screen2_small](https://mqtt-explorer.com/img/screen2_small.png)](https://mqtt-explorer.com/img/screen2.png) | [![screen3_small](https://mqtt-explorer.com/img/screen3_small.png)](https://mqtt-explorer.com/img/screen3.png) |
| | | |
|:---:|:---:|:---:|
|[![screen_composite](https://mqtt-explorer.com/img/screen-composite_small.png)](https://mqtt-explorer.com/img/screen-composite.png)|[![screen2_small](https://mqtt-explorer.com/img/screen2_small.png)](https://mqtt-explorer.com/img/screen2.png)|[![screen3_small](https://mqtt-explorer.com/img/screen3_small.png)](https://mqtt-explorer.com/img/screen3.png)|
# The App has moved to [mqtt-explorer.com](https://mqtt-explorer.com)
MQTT Explorer is a comprehensive and easy-to-use MQTT Client.
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
@@ -41,85 +26,43 @@ 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
npm install -g yarn
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 CI.
To achieve a reliable product automated tests run regularly on travis.
- **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)
- Data model
- MQTT integration
- UI-Tests (The demo is a recorded ui test)
### Run UI Test Suite
## Run UI-tests
The UI test suite validates core functionality through automated browser tests. Each test is independent and deterministic.
A [mosquitto](https://mosquitto.org/) MQTT broker is required to run the ui-tests.
Run tests with
```bash
# Run with automated setup (recommended)
./scripts/runUiTests.sh
# Or run directly (requires manual MQTT broker setup)
yarn build
yarn test:ui
# Run chromedriver in a separate terminal session
./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 --verbose
```
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.
Compile and execute tests
```bash
yarn build
yarn ui-test
npm run build
node dist/src/spec/webdriverio.js
```
## Create a release
Create a PR to `release` branch.
There needs to be a "feat: some new feature" or "fix: some bugfix" commit for a new release to be created
## Create a beta release
Create a PR to `beta` branch. A "feat" or "fix" commit is necessary to create a new version.
## Write docs
```
@@ -145,7 +88,7 @@ The readme will be generated from the docs.
## License
![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/)
![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/)
The license allows for anyone to adapt, share, and redistribute the material, as long as it is non-commercial.
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.
+10 -14
View File
@@ -7,10 +7,10 @@
"build": "webpack --mode production",
"dev": "node_modules/.bin/webpack-dev-server --mode development --progress",
"test": "cross-env TS_NODE_PROJECT=test/tsconfig.json yarn mochatest",
"mochatest": "mocha --require ts-node/register --require source-map-support/register --recursive src/*/**/*.spec.ts"
"mochatest": "mocha --require ts-node/register src/**/*.spec.ts"
},
"engines": {
"node": ">=20"
"node": "19"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -21,14 +21,13 @@
"@material-ui/styles": "4.11",
"@types/react-transition-group": "^4",
"ace-builds": "^1.4.11",
"axios": "^0.28.0",
"axios": "^0.26.0",
"compare-versions": "^3.5.0",
"copy-text-to-clipboard": "^2.1.0",
"d3": "^5.9.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",
@@ -38,9 +37,7 @@
"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",
@@ -54,8 +51,7 @@
"redux-batched-actions": "0.5",
"redux-thunk": "^2.3.0",
"sha1": "^1.1.1",
"socket.io-client": "^4.8.1",
"url": "^0.11.4",
"socket.io-client": "^2.2.0",
"uuid": "7"
},
"devDependencies": {
@@ -70,7 +66,7 @@
"@types/react-redux": "^7.0.9",
"@types/react-resize-detector": "^4.0.1",
"@types/sha1": "^1.1.1",
"@types/socket.io-client": "^3.0.0",
"@types/socket.io-client": "^1.4.32",
"@types/uuid": "^7.0.2",
"@types/vis": "^4.21.9",
"chai": "^4.2.0",
@@ -79,17 +75,17 @@
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"lodash": "^4.17.21",
"mocha": "^10.4.0",
"mocha": "^9.2.1",
"moment": "^2.29.1",
"node-loader": "^0.6.0",
"source-map-loader": "^0.2.4",
"style-loader": "^1",
"ts-loader": "^9.5.1",
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
"webpack": "^5.91.0",
"webpack": "^5.69.1",
"webpack-bundle-analyzer": "^4.5.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^5.0.4"
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"peerDependencies": {
"electron": "^29"
+3 -2
View File
@@ -9,11 +9,12 @@ 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, readFromFile } from '../../../events'
import { rendererRpc } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
export interface ConnectionDictionary {
@@ -80,7 +81,7 @@ async function openCertificate(): Promise<CertificateParameters> {
throw rejectReasons.noCertificateSelected
}
const data = await rendererRpc.call(readFromFile, { filePath: selectedFile })
const data = await fsPromise.readFile(selectedFile)
if (data.length > 16_384 || data.length < 64) {
throw rejectReasons.certificateSizeDoesNotMatch
}
+2 -49
View File
@@ -2,10 +2,7 @@ import { Action, ActionTypes } from '../reducers/Publish'
import { AppState } from '../reducers'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Dispatch } from 'redux'
import { MqttMessage, makePublishEvent, rendererEvents, rendererRpc, readFromFile } from '../../../events'
import { makeOpenDialogRpc } from '../../../events/OpenDialogRequest'
import { showError } from './Global'
import { Base64 } from 'js-base64'
import { makePublishEvent, rendererEvents } from '../../../events'
export const setTopic = (topic?: string): Action => {
return {
@@ -14,50 +11,6 @@ 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,
@@ -88,7 +41,7 @@ export const publish = (connectionId: string) => (dispatch: Dispatch<Action>, ge
}
const publishEvent = makePublishEvent(connectionId)
const mqttMessage: Partial<MqttMessage> = {
const mqttMessage = {
topic,
payload: state.publish.payload ? Base64Message.fromString(state.publish.payload) : null,
retain: state.publish.retain,
+9 -10
View File
@@ -1,5 +1,5 @@
import * as q from '../../../backend/src/Model'
import { ActionTypes, SettingsStateModel, TopicOrder, ValueRendererDisplayMode } from '../reducers/Settings'
import { ActionTypes, SettingsStateModel, TopicOrder } from '../reducers/Settings'
import { AppState } from '../reducers'
import { autoExpandLimitSet } from '../components/SettingsDrawer/Settings'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
@@ -68,14 +68,13 @@ export const selectTopicWithMouseOver = (doSelect: boolean) => (dispatch: Dispat
dispatch(storeSettings())
}
export const setValueDisplayMode =
(valueRendererDisplayMode: ValueRendererDisplayMode) => (dispatch: Dispatch<any>) => {
dispatch({
valueRendererDisplayMode,
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
})
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 toggleHighlightTopicUpdates = () => (dispatch: Dispatch<any>) => {
dispatch({
@@ -118,7 +117,7 @@ export const filterTopics = (filterStr: string) => (dispatch: Dispatch<any>, get
const messageMatches =
node.message &&
node.message.payload &&
node.message.payload.toUnicodeString().toLowerCase().indexOf(filterStr) !== -1
Base64Message.toUnicodeString(node.message.payload).toLowerCase().indexOf(filterStr) !== -1
return Boolean(messageMatches)
}
+7 -2
View File
@@ -33,8 +33,13 @@ const debouncedSelectTopic = debounce(
setTopicDispatch = setTopic(topic.path())
}
previouslySelectedTopic?.viewModel?.setSelected(false)
topic.viewModel?.setSelected(true)
if (previouslySelectedTopic && previouslySelectedTopic.viewModel) {
previouslySelectedTopic.viewModel.setSelected(false)
}
if (topic.viewModel) {
topic.viewModel.setSelected(true)
}
const selectTreeTopicDispatch = {
selectedTopic: topic,
-64
View File
@@ -1,64 +0,0 @@
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,7 +114,6 @@ 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}
@@ -1,140 +0,0 @@
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,6 +1,5 @@
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'
@@ -9,11 +8,6 @@ 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
@@ -51,7 +45,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}>
<CertSelector
<CertificateFileSelection
connection={this.props.connection}
certificate={this.props.connection.selfSignedCertificate}
title="Server Certificate (CA)"
@@ -59,7 +53,7 @@ class Certificates extends React.PureComponent<Props, State> {
/>
</Grid>
<Grid item={true} xs={12} className={classes.gridPadding}>
<CertSelector
<CertificateFileSelection
connection={this.props.connection}
certificate={this.props.connection.clientCertificate}
title="Client Certificate"
@@ -67,7 +61,7 @@ class Certificates extends React.PureComponent<Props, State> {
/>
</Grid>
<Grid item={true} xs={12} className={classes.gridPadding}>
<CertSelector
<CertificateFileSelection
connection={this.props.connection}
certificate={this.props.connection.clientKey}
title="Client Key"
@@ -1,40 +1,26 @@
import React, { useCallback } from 'react'
import React 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 { connectionActions, connectionManagerActions } from '../../../actions'
import { connectionManagerActions } from '../../../actions'
export interface Props {
connection: ConnectionOptions
actions: {
connection: any
connectionManager: any
}
actions: 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.connectionManager.selectConnection(props.connection.id)}
onDoubleClick={() => {
props.actions.connectionManager.selectConnection(props.connection.id)
connect()
}}
onClick={() => props.actions.selectConnection(props.connection.id)}
>
<Typography className={props.classes.name}>{props.connection.name || 'mqtt broker'}</Typography>
<Typography className={props.classes.details}>{connection && connection.url}</Typography>
@@ -44,12 +30,10 @@ const ConnectionItem = (props: Props) => {
export const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
connection: bindActionCreators(connectionActions, dispatch),
connectionManager: bindActionCreators(connectionManagerActions, dispatch),
},
actions: 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 } from '@material-ui/core'
import { List, ListSubheader } from '@material-ui/core'
import { Theme, withStyles } from '@material-ui/core/styles'
import { useGlobalKeyEventHandler } from '../../../effects/useGlobalKeyEventHandler'
-57
View File
@@ -1,57 +0,0 @@
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 ? node.message.payload.toUnicodeString() : ''
const str = node.message.payload ? Base64Message.toUnicodeString(node.message.payload) : ''
let value = node.message && node.message.payload ? parseFloat(str) : NaN
value = !isNaN(value) ? abbreviate(value) : str
@@ -69,11 +69,7 @@ function ChartPreview(props: Props) {
<Popper open={open} anchorEl={chartIconRef.current} placement="left-end">
<Fade in={open} timeout={300}>
<Paper style={{ width: '300px' }}>
{open ? (
<TopicPlot node={props.treeNode} history={props.treeNode.messageHistory} dotPath={props.literal.path} />
) : (
<span />
)}
{open ? <TopicPlot history={props.treeNode.messageHistory} dotPath={props.literal.path} /> : <span />}
</Paper>
</Fade>
</Popper>
+1 -20
View File
@@ -1,5 +1,5 @@
import Editor from './Editor'
import { AttachFileOutlined, FormatAlignLeft } from '@material-ui/icons'
import FormatAlignLeft from '@material-ui/icons/FormatAlignLeft'
import Message from './Model/Message'
import Navigation from '@material-ui/icons/Navigation'
import PublishHistory from './PublishHistory'
@@ -116,10 +116,6 @@ const EditorMode = memo(function EditorMode(props: {
props.actions.setEditorMode(value)
}, [])
const openFile = useCallback(() => {
props.actions.openFile()
}, [])
const formatJson = useCallback(() => {
if (props.payload) {
try {
@@ -136,7 +132,6 @@ 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>
@@ -168,20 +163,6 @@ 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) => {
+4 -2
View File
@@ -1,9 +1,10 @@
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 { ExpansionPanelDetails } from '@material-ui/core'
import { Badge, ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography } from '@material-ui/core'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { settingsActions, sidebarActions } from '../../actions'
@@ -27,7 +28,7 @@ interface Props {
}
function useUpdateNodeWhenNodeReceivesUpdates(node?: q.TreeNode<any>) {
const [, setLastUpdate] = useState(0)
const [lastUpdate, setLastUpdate] = useState(0)
const updateNode = useCallback(
throttle(() => {
setLastUpdate(node ? node.lastUpdate : 0)
@@ -51,6 +52,7 @@ 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 { TopicDeleteButton } from './TopicDeleteButton'
import { TopicTypeButton } from './TopicTypeButton'
import { sidebarActions } from '../../../actions'
import { TopicDeleteButton } from './TopicDeleteButton'
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,12 +29,11 @@ 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?.childTopicCount()]
[node, node && node.childTopicCount()]
)
}
@@ -1,103 +0,0 @@
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,6 +5,7 @@ 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'
@@ -12,8 +13,6 @@ 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')
@@ -26,100 +25,117 @@ interface Props {
}
}
export const MessageHistory: React.FC<Props> = props => {
const [, setLastUpdate] = React.useState(Date.now())
const updateNodeThrottled = React.useCallback(
throttle(() => {
setLastUpdate
}, 300),
[]
)
interface State {
displayMessage?: q.Message
anchorEl?: HTMLElement
lastUpdate: number
}
useSubscription(props.node?.onMessage, updateNodeThrottled)
const decodeMessage = useDecoder(props.node)
class MessageHistory extends React.PureComponent<Props, State> {
private updateNode = throttle(() => {
this.setState({ lastUpdate: Date.now() })
}, 300)
function addNodeToCharts(event: React.MouseEvent) {
constructor(props: any) {
super(props)
this.state = { lastUpdate: 0 }
}
private addNodeToCharts = (event: React.MouseEvent) => {
event.preventDefault()
event.stopPropagation()
const { node } = props
const { node } = this.props
if (!node) {
return null
}
props.actions.charts.addChart({ topic: node.path() })
this.props.actions.charts.addChart({ topic: node.path() })
}
function displayMessage(index: number, eventTarget: EventTarget) {
const message = props.node && props.node.messageHistory.toArray().reverse()[index]
private displayMessage = (index: number, eventTarget: EventTarget) => {
const message = this.props.node && this.props.node.messageHistory.toArray().reverse()[index]
if (message) {
props.onSelect(message)
this.props.onSelect(message)
}
}
const { node } = props
if (!node) {
return null
public componentWillReceiveProps(nextProps: Props) {
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
nextProps.node && nextProps.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 componentDidMount() {
this.props.node && this.props.node.onMessage.subscribe(this.updateNode)
}
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>
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: (
<span>
&nbsp;
<MessageId message={message} />
<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>
</span>
<div style={{ float: 'right' }}>
<Copy value={value ?? ''} />
</div>
</span>
),
selected: message && message === props.selected,
}
previousMessage = message
return element
})
),
selected: message && message === this.props.selected,
}
previousMessage = message
return element
})
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 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 mapDispatchToProps = (dispatch: any) => {
@@ -128,4 +144,4 @@ const mapDispatchToProps = (dispatch: any) => {
}
}
export default connect(null, mapDispatchToProps)(React.memo(MessageHistory))
export default connect(null, mapDispatchToProps)(MessageHistory)
@@ -1,20 +1,19 @@
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>
@@ -36,7 +35,6 @@ 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) {
@@ -56,16 +54,6 @@ 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
@@ -97,16 +85,14 @@ function ValuePanel(props: Props) {
[compareMessage]
)
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
const copyValue =
node && node.message && node.message.payload ? (
<Copy value={Base64Message.toUnicodeString(node.message.payload)} />
) : null
return (
<Panel>
<span>
Value {copyValue} {saveValue}
</span>
<span>Value {copyValue}</span>
<span style={{ width: '100%' }}>
{renderViewOptions()}
<div style={{ marginBottom: '-8px', marginTop: '8px' }}>
@@ -1,13 +1,12 @@
import * as q from '../../../../../backend/src/Model'
import React, { useMemo } from 'react'
import * as React 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
@@ -16,114 +15,103 @@ interface Props {
renderMode: ValueRendererDisplayMode
}
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'}
/>
)
interface State {
width: number
}
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
class ValueRenderer extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { width: 0 }
}
return <div>{renderDiff(treeNode, compareWithPreviousMessage, currentStr, compareStr, undefined, language)}</div>
}
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'}
/>
)
}
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>
)
}
export const ValueRenderer: React.FC<Props> = ({ treeNode, compareWith: compare, message, renderMode }) => {
const decodeMessage = useDecoder(treeNode)
const decodedMessage = useMemo(() => decodeMessage(message), [decodeMessage, message])
const previousMessages = treeNode.messageHistory.toArray()
const previousMessage = previousMessages[previousMessages.length - 2]
const compareMessage = compare || previousMessage || message
const compareWithPreviousMessage = !!compare
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]
)
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
private convertMessage(msg?: Base64Message): [string | undefined, 'json' | undefined] {
if (!msg) {
return [undefined, undefined]
}
switch (renderMode) {
case 'diff':
return renderDiffMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
default:
return renderRawMode(treeNode, currentStr, compareStr, currentType, compareType, compareWithPreviousMessage)
const str = Base64Message.toUnicodeString(msg)
try {
JSON.parse(str)
} catch (error) {
return [str, undefined]
}
return [this.messageToPrettyJson(str), 'json']
}
private messageToPrettyJson(str: string): string | undefined {
try {
const json = JSON.parse(str)
return JSON.stringify(json, undefined, ' ')
} catch {
return undefined
}
}
const renderedValue = useMemo(
() =>
renderValue(treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage),
[treeNode, currentStr, compareStr, currentType, compareType, renderMode, compareWithPreviousMessage]
)
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 style={{ padding: '0px 0px 8px 0px', width: '100%' }}>
{decodedMessage?.decoder === Decoder.SPARKPLUG && 'Decoded SparkplugB'}
{renderedValue}
</div>
)
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) {
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)
}
}
const mapStateToProps = (state: AppState) => {
+13 -24
View File
@@ -2,14 +2,12 @@ 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
@@ -27,27 +25,21 @@ function filterUsingTimeRange(startTime: number | undefined, data: Array<q.Messa
return data
}
function nodeToHistory(decodeMessage: DecoderFunction, startTime: number | undefined, history: q.MessageHistory) {
function nodeToHistory(startTime: number | undefined, history: q.MessageHistory) {
return filterUsingTimeRange(startTime, history.toArray())
.map((message: q.Message) => {
const decoded = decodeMessage(message)?.message?.toUnicodeString()
return { x: message.received.getTime(), y: toPlottableValue(decoded) }
const value = message.payload ? toPlottableValue(Base64Message.toUnicodeString(message.payload)) : NaN
return { x: message.received.getTime(), y: toPlottableValue(value) }
})
.filter(data => !isNaN(data.y as any)) as any
}
function nodeDotPathToHistory(
decodeMessage: DecoderFunction,
startTime: number | undefined,
history: q.MessageHistory,
dotPath: string
) {
function nodeDotPathToHistory(startTime: number | undefined, history: q.MessageHistory, dotPath: string) {
return filterUsingTimeRange(startTime, history.toArray())
.map((message: q.Message) => {
let json: any = {}
try {
const decoded = decodeMessage(message)?.message
json = decoded ? JSON.parse(decoded.toUnicodeString()) : {}
json = message.payload ? JSON.parse(Base64Message.toUnicodeString(message.payload)) : {}
} catch (ignore) {}
const value = dotProp.get(json, dotPath)
@@ -58,17 +50,14 @@ function nodeDotPathToHistory(
}
function TopicPlot(props: Props) {
const decodeMessage = useDecoder(props.node)
const startOffset = props.timeInterval ? parseDuration(props.timeInterval) : undefined
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])
const data = React.useMemo(
() =>
props.dotPath
? nodeDotPathToHistory(startOffset, props.history, props.dotPath)
: nodeToHistory(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,72 +14,67 @@ export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
classes: any
}
export const TreeNodeTitle = (props: TreeNodeProps) => {
const decodeMessage = useDecoder(props.treeNode)
function renderSourceEdge() {
const name = props.name || (props.treeNode.sourceEdge && props.treeNode.sourceEdge.name)
class TreeNodeTitle extends React.PureComponent<TreeNodeProps, {}> {
private renderSourceEdge() {
const name = this.props.name || (this.props.treeNode.sourceEdge && this.props.treeNode.sourceEdge.name)
return (
<span key="edge" className={props.classes.sourceEdge} data-test-topic={name}>
<span key="edge" className={this.props.classes.sourceEdge}>
{name}
</span>
)
}
function truncatedMessage() {
private truncatedMessage() {
const limit = 400
if (!props.treeNode.message || !props.treeNode.message.payload) {
if (!this.props.treeNode.message || !this.props.treeNode.message.payload) {
return ''
}
const [value = ''] = decodeMessage(props.treeNode.message)?.message?.format(props.treeNode.type) ?? []
return value.length > limit ? `${value.slice(0, limit)}` : value
const str = Base64Message.toUnicodeString(this.props.treeNode.message.payload)
return str.length > limit ? `${str.slice(0, limit)}` : str
}
function renderValue() {
return props.treeNode.message && props.treeNode.message.payload && props.treeNode.message.length > 0 ? (
<span key="value" className={props.classes.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}>
{' '}
= {truncatedMessage()}
= {this.truncatedMessage()}
</span>
) : null
}
function renderExpander() {
if (props.treeNode.edgeCount() === 0) {
private renderExpander() {
if (this.props.treeNode.edgeCount() === 0) {
return null
}
return (
<span key="expander" className={props.classes.expander} onClick={props.toggleCollapsed}>
{props.collapsed ? '▶' : '▼'}
<span key="expander" className={this.props.classes.expander} onClick={this.props.toggleCollapsed}>
{this.props.collapsed ? '▶' : '▼'}
</span>
)
}
function renderMetadata() {
if (props.treeNode.edgeCount() === 0 || !props.collapsed) {
private renderMetadata() {
if (this.props.treeNode.edgeCount() === 0 || !this.props.collapsed) {
return null
}
const messages = props.treeNode.leafMessageCount()
const topicCount = props.treeNode.childTopicCount()
const messages = this.props.treeNode.leafMessageCount()
const topicCount = this.props.treeNode.childTopicCount()
return (
<span key="metadata" className={props.classes.collapsedSubnodes}>{` (${topicCount} ${
<span key="metadata" className={this.props.classes.collapsedSubnodes}>{` (${topicCount} ${
topicCount === 1 ? 'topic' : 'topics'
}, ${messages} ${messages === 1 ? 'message' : 'messages'})`}</span>
)
}
return (
<>
{renderExpander()}
{renderSourceEdge()}
{renderMetadata()}
{renderValue()}
</>
)
public render() {
return [this.renderExpander(), this.renderSourceEdge(), this.renderMetadata(), this.renderValue()]
}
}
const styles = (theme: Theme) => ({
@@ -1,18 +0,0 @@
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,8 +1,6 @@
import * as q from '../../../../../../backend/src/Model'
import React, { useCallback } from 'react'
import React, { useEffect } from 'react'
import { TopicViewModel } from '../../../../model/TopicViewModel'
import { useSubscription } from '../../../hooks/useSubscription'
import { useViewModel } from './useViewModel'
export function useViewModelSubscriptions(
treeNode: q.TreeNode<TopicViewModel>,
@@ -10,21 +8,37 @@ export function useViewModelSubscriptions(
setSelected: (value: boolean) => void,
setCollapsedOverride: (value: boolean) => void
) {
const viewModel = useViewModel(treeNode)
useEffect(() => {
const selectionDidChange = () => {
const selected = treeNode.viewModel && treeNode.viewModel.isSelected()
treeNode.viewModel && setSelected(Boolean(selected))
const selectionDidChange = useCallback(() => {
const selected = viewModel && viewModel.isSelected()
viewModel && setSelected(Boolean(selected))
if (selected && nodeRef && nodeRef.current) {
nodeRef.current.focus({ preventScroll: false })
if (selected && nodeRef && nodeRef.current) {
nodeRef.current.focus({ preventScroll: false })
}
}
}, [viewModel])
const expandedDidChange = useCallback(() => {
viewModel && setCollapsedOverride(!viewModel.isExpanded())
}, [viewModel])
const expandedDidChange = () => {
treeNode.viewModel && setCollapsedOverride(!treeNode.viewModel.isExpanded())
}
useSubscription(viewModel?.selectionChange, selectionDidChange)
useSubscription(viewModel?.expandedChange, expandedDidChange)
function addSubscriber() {
treeNode.viewModel = new TopicViewModel()
treeNode.viewModel.selectionChange.subscribe(selectionDidChange)
treeNode.viewModel.expandedChange.subscribe(expandedDidChange)
}
function removeSubscriber() {
if (treeNode.viewModel) {
treeNode.viewModel.selectionChange.unsubscribe(selectionDidChange)
treeNode.viewModel.expandedChange.unsubscribe(expandedDidChange)
treeNode.viewModel = undefined
}
}
addSubscriber()
return function cleanup() {
removeSubscriber()
}
}, [treeNode])
}
+6 -14
View File
@@ -1,6 +1,7 @@
import compareVersions from 'compare-versions'
import electron from 'electron'
import React from 'react'
import * as compareVersions from 'compare-versions'
import * as electron from 'electron'
import * as os from 'os'
import * as React from 'react'
import axios from 'axios'
import Close from '@material-ui/icons/Close'
import CloudDownload from '@material-ui/icons/CloudDownload'
@@ -181,10 +182,9 @@ class UpdateNotifier extends React.PureComponent<Props, State> {
private assetForCurrentPlatform(asset: GithubAsset) {
let regex: RegExp
const platform = this.getPlatform()
if (platform === 'darwin') {
if (os.platform() === 'darwin') {
regex = /\.dmg$/
} else if (platform === 'win32') {
} else if (os.platform() === 'win32') {
regex = /\.exe$/
} else {
regex = /\.AppImage$/
@@ -193,14 +193,6 @@ 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) {
+2 -3
View File
@@ -9,8 +9,7 @@ import { globalActions } from '../../actions'
const copy = require('copy-text-to-clipboard')
interface Props {
value?: string
getValue?: () => string | undefined
value: string
actions: {
global: typeof globalActions
}
@@ -29,7 +28,7 @@ class Copy extends React.PureComponent<Props, State> {
private handleClick = (event: React.MouseEvent) => {
event.stopPropagation()
copy(this.props.value ?? this.props.getValue?.())
copy(this.props.value)
this.props.actions.global.showNotification('Copied to clipboard')
this.setState({ didCopy: true })
setTimeout(() => {
+5 -11
View File
@@ -1,5 +1,5 @@
import moment from 'moment'
import React from 'react'
import * as moment from 'moment'
import * as React from 'react'
import { AppState } from '../../reducers'
import { connect } from 'react-redux'
@@ -12,7 +12,6 @@ interface Props {
}
const unitMapping = {
ms: 'milliseconds',
s: 'seconds',
m: 'minutes',
h: 'hours',
@@ -22,7 +21,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 `${moment.duration(interval).as(unit).toFixed(3)} ${unitMapping[unit]}`
return `${Math.round(moment.duration(interval).as(unit) * 100) / 100} ${unitMapping[unit]}`
}
private legacyDate() {
@@ -32,11 +31,10 @@ class DateFormatter extends React.PureComponent<Props, {}> {
private localizedDate(locale: string) {
return moment(this.props.date)
.locale(locale)
.format(this.props.timeFirst ? 'LTS.SSS L' : 'L LTS.SSS')
.format(this.props.timeFirst ? 'LTS L' : 'L LTS')
}
private unitForInterval(milliseconds: number) {
const oneSecond = 1000 * 1
const oneMinute = 1000 * 60
const oneHour = oneMinute * 60
@@ -48,11 +46,7 @@ class DateFormatter extends React.PureComponent<Props, {}> {
return 'm'
}
if (milliseconds > oneSecond * 0.5) {
return 's'
}
return 'ms'
return 's'
}
public render() {
-85
View File
@@ -1,85 +0,0 @@
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
@@ -1,31 +0,0 @@
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]
)
}
@@ -1,10 +0,0 @@
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
@@ -1,56 +0,0 @@
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
@@ -1,8 +0,0 @@
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
@@ -1,13 +0,0 @@
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
@@ -1,28 +0,0 @@
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
@@ -1,10 +0,0 @@
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
@@ -1,6 +0,0 @@
import { StringDecoder } from './StringDecoder'
import { BinaryDecoder } from './BinaryDecoder'
import { SparkplugDecoder } from './SparkplugBDecoder'
export * from './MessageDecoder'
export const decoders = [SparkplugDecoder, BinaryDecoder, StringDecoder] as const
+1 -4
View File
@@ -10,7 +10,6 @@ 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)))
@@ -34,9 +33,7 @@ const Application = connect(mapStateToProps)(ApplicationRenderer)
ReactDOM.render(
<Provider store={store}>
<BrowserAuthWrapper>
<Application />
</BrowserAuthWrapper>
<Application />
</Provider>,
document.getElementById('app')
)
-12
View File
@@ -1,12 +0,0 @@
// Mock electron module for browser environment
export const shell = {
openExternal: (url: string) => {
if (typeof window !== 'undefined') {
window.open(url, '_blank')
}
},
}
export default {
shell,
}
+4 -4
View File
@@ -77,11 +77,11 @@ export function createEmptyConnection(): ConnectionOptions {
export function makeDefaultConnections() {
return {
// remember: there was also iot.eclipse.org once
'mqtt.eclipseprojects.io': {
'mqtt.eclipse.org': {
...createEmptyConnection(),
id: 'mqtt.eclipseprojects.io',
name: 'mqtt.eclipseprojects.io',
host: 'mqtt.eclipseprojects.io',
id: 'mqtt.eclipse.org',
name: 'mqtt.eclipse.org',
host: 'mqtt.eclipse.org',
},
'test.mosquitto.org': {
...createEmptyConnection(),
@@ -1,4 +1,5 @@
import { ConnectionOptions, createEmptyConnection } from './ConnectionOptions'
import { v4 } from 'uuid'
interface LegacyConnectionSettings {
host: string
+1 -59
View File
@@ -1,77 +1,19 @@
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>()
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
public constructor() {
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() {
+3
View File
@@ -0,0 +1,3 @@
--require ts-node/register
--require source-map-support/register
--recursive ./src/**/*.spec.ts
+21 -9
View File
@@ -4,26 +4,38 @@
"noImplicitAny": true,
"strictNullChecks": true,
"strict": true,
"lib": ["es2019", "dom"],
"lib": [
"es2017",
"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,
"esModuleInterop": true
"skipLibCheck": 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
@@ -1,102 +0,0 @@
// 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,
}
+12 -21
View File
@@ -1,6 +1,6 @@
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
entry: {
@@ -41,7 +41,6 @@ module.exports = {
devServer: {
// contentBase: './dist', // content not from webpack
hot: true,
liveReload: true,
},
target: 'electron-renderer',
mode: 'production',
@@ -55,15 +54,7 @@ module.exports = {
// All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
// options: {
// configFile: './tsconfig.json',
// },
},
],
exclude: /node_modules/,
loader: 'ts-loader',
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
@@ -72,8 +63,13 @@ module.exports = {
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif)$/i,
type: 'asset/resource',
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
},
// {
// test: /\.node$/,
@@ -90,6 +86,7 @@ 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$/
@@ -104,10 +101,4 @@ module.exports = {
// "react": "React",
// "react-dom": "ReactDOM"
},
cache: {
type: 'filesystem',
},
optimization: {
runtimeChunk: 'single',
},
}
};
+444 -736
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -10,10 +10,12 @@ install:
- ps: Install-Product node 19
build_script:
- yarn install --frozen-lockfile
- yarn
- yarn build
- yarn prepare-release
- yarn package appx
- yarn prepare-release
- yarn package linux
test_script:
- yarn lint
+13 -31
View File
@@ -4,14 +4,15 @@
"description": "",
"main": "build/index.js",
"scripts": {
"test": "NODE_PATH=../node_modules TS_NODE_PROJECT=./tsconfig.json mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"test": "mocha",
"build": "tsc",
"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"
"test-inspect": "mocha --inspect-brk",
"coverage": "nyc mocha",
"debug": "ts-node --inspect ./src/index.ts",
"postinstall": "yarn build"
},
"engines": {
"node": ">=20"
"node": "19"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -37,31 +38,12 @@
"sourceMap": true,
"instrument": true
},
"dependencies": {
"@types/sha1": "^1.1.5",
"builder-util-runtime": "^9",
"fs-extra": "9",
"js-base64": "^3.7.2",
"peerDependencies": {
"fs-extra": "^8.0.1",
"js-base64": "^2.5.1",
"lowdb": "^1.0.0",
"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"
"mqtt": "^3.0.0",
"protobufjs": "~6.11.2",
"long": "^4.0.0"
}
}
}
+9 -12
View File
@@ -1,18 +1,15 @@
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 * 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 { storageClearEvent, storageLoadEvent, storageStoreEvent } from '../../events/StorageEvents'
export default class ConfigStorage {
private file: string
private database: any
private rpc: Rpc
constructor(file: string, rpc: Rpc) {
constructor(file: string) {
this.file = file
this.rpc = rpc
}
private async getDb() {
@@ -29,13 +26,13 @@ export default class ConfigStorage {
}
public async init() {
this.rpc.on(storageStoreEvent, async event => {
backendRpc.on(storageStoreEvent, async event => {
const db = await this.getDb()
await db.set(event.store, event.data).write()
return
})
this.rpc.on(storageLoadEvent, async event => {
backendRpc.on(storageLoadEvent, async event => {
const db = await this.getDb()
const data = await db.get(event.store).value()
return {
@@ -44,7 +41,7 @@ export default class ConfigStorage {
}
})
this.rpc.on(storageClearEvent, async event => {
backendRpc.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 && new Base64Message(msg.payload))?.toBuffer() ?? '', {
this.client.publish(msg.topic, msg.payload ? Base64Message.toUnicodeString(msg.payload) : '', {
qos: msg.qos,
retain: msg.retain,
})
+12 -74
View File
@@ -1,93 +1,31 @@
import { Base64 } from 'js-base64'
import { TopicDataType } from './TreeNode'
export type Base64MessageDTO = Pick<Base64Message, 'base64Message'>
import { Decoder } from './Decoder'
export class Base64Message {
public base64Message: string
private _unicodeValue: string | undefined
private base64Message: string
private unicodeValue: string
public decoder: Decoder
public length: number
// Todo: Rename to `encodedLength`
public get length(): number {
return this.base64Message.length
private constructor(base64Str: string) {
this.base64Message = base64Str
this.unicodeValue = Base64.decode(base64Str)
this.length = base64Str.length
this.decoder = Decoder.NONE
}
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 toUnicodeString(message: Base64Message) {
return message.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 => {
let 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?.base64Message.length ?? 0)
this.size += this.estimatedMessageOverhead + (val.payload ? val.payload.length : 0)
this.length += 1
}
}
+1 -2
View File
@@ -1,8 +1,7 @@
import { Base64Message } from './Base64Message'
import { QoS } from '../DataSource/MqttSource'
import { MemoryConsumptionExpressedByLength } from './RingBuffer'
export interface Message extends MemoryConsumptionExpressedByLength {
export interface Message {
// mqtt based info
payload: Base64Message | null
messageId?: number
+1 -4
View File
@@ -2,8 +2,6 @@ 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
@@ -19,7 +17,6 @@ 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>>
@@ -156,7 +153,7 @@ export class TreeNode<ViewModel extends Destroyable> {
public path(): string {
if (!this.cachedPath) {
this.cachedPath = this.branch()
return this.branch()
.map(node => node.sourceEdge && node.sourceEdge.name)
.filter(name => name !== undefined)
.join('/')
+1 -3
View File
@@ -1,7 +1,6 @@
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
@@ -31,8 +30,7 @@ export abstract class TreeNodeFactory {
mqttMessage.retain
node.setMessage({
...mqttMessage,
payload: mqttMessage.payload && new Base64Message(mqttMessage.payload?.base64Message),
length: mqttMessage.payload?.base64Message.length ?? 0,
length: mqttMessage.payload?.length ?? 0,
received: receiveDate,
messageNumber: this.messageCounter,
})
+1 -1
View File
@@ -1,5 +1,5 @@
export { Edge } from './Edge'
export { TreeNode, TopicDataType } from './TreeNode'
export { TreeNode } from './TreeNode'
export { Message } from './Message'
export { TreeNodeFactory } from './TreeNodeFactory'
export { Tree } from './Tree'
+22
View File
@@ -0,0 +1,22 @@
import { readFileSync } from 'fs'
import * as protobuf from 'protobufjs'
import { Base64Message } from './Base64Message'
import { Decoder } from './Decoder'
const buffer = readFileSync(require.resolve('../../../../res/sparkplug_b.proto'))
const root = protobuf.parse(buffer.toString()).root
export let SparkplugPayload = root.lookupType('com.cirruslink.sparkplug.protobuf.Payload')
export const SparkplugDecoder = {
decode(input: Buffer): Base64Message | undefined {
try {
const message = Base64Message.fromString(
JSON.stringify(SparkplugPayload.toObject(SparkplugPayload.decode(new Uint8Array(input))))
)
message.decoder = Decoder.SPARKPLUG
return message
} catch {
// ignore
}
},
}
+6 -5
View File
@@ -1,6 +1,7 @@
import 'mocha'
import { expect } from 'chai'
import { Base64Message } from '../Base64Message'
import { makeTreeNode } from './makeTreeNode'
describe('TreeNode', () => {
@@ -13,7 +14,7 @@ describe('TreeNode', () => {
it('updateWithNode should update value', () => {
const topics = 'foo/bar'.split('/')
const leaf = makeTreeNode('foo/bar', '3')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
const updateLeave = makeTreeNode('foo/bar', '5')
@@ -21,13 +22,13 @@ describe('TreeNode', () => {
root.updateWithNode(updateLeave.firstNode())
expect(root.sourceEdge).to.eq(undefined)
expect(leaf.message!.payload!.toUnicodeString()).to.eq('5')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('5')
})
it('updateWithNode should update intermediate nodes', () => {
const topics1 = 'foo/bar/baz'.split('/')
const leaf = makeTreeNode('foo/bar/baz', '3')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
const topics2 = 'foo/bar'.split('/')
const updateLeave = makeTreeNode('foo/bar', '5')
@@ -36,10 +37,10 @@ describe('TreeNode', () => {
const barNode = leaf.firstNode().findNode('foo/bar')
expect(barNode && barNode.sourceEdge && barNode.sourceEdge.name).to.eq('bar')
expect(barNode!.message!.payload!.toUnicodeString()).to.eq('5')
expect(Base64Message.toUnicodeString(barNode!.message!.payload!)).to.eq('5')
expect(leaf.sourceEdge && leaf.sourceEdge.name).to.eq('baz')
expect(leaf.message!.payload!.toUnicodeString()).to.eq('3')
expect(Base64Message.toUnicodeString(leaf.message!.payload!)).to.eq('3')
})
it('updateWithNode should add nodes to the tree', () => {
@@ -1,5 +1,6 @@
import 'mocha'
import { expect } from 'chai'
import { Base64Message } from '../Base64Message'
import { makeTreeNode } from './makeTreeNode'
describe('TreeNodeFactory', () => {
@@ -19,7 +20,7 @@ describe('TreeNodeFactory', () => {
expect(node).to.not.eq(undefined)
expect(node.sourceEdge.name).to.eq('bar')
expect(node.message.payload!.toUnicodeString()).to.eq('5')
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
const foo = node.firstNode().findNode('foo')
expect(foo && foo.sourceEdge && foo.sourceEdge.name).to.eq('foo')
@@ -33,7 +34,7 @@ describe('TreeNodeFactory', () => {
return
}
expect(node.message.payload!.toUnicodeString()).to.eq('5')
expect(Base64Message.toUnicodeString(node.message.payload!)).to.eq('5')
expect(node.sourceEdge.name).to.eq('baz')
const barNode = node.sourceEdge.source
+9 -16
View File
@@ -4,20 +4,16 @@ import {
AddMqttConnection,
MqttMessage,
addMqttConnectionEvent,
backendEvents,
makeConnectionMessageEvent,
makeConnectionStateEvent,
makePublishEvent,
removeConnection,
} from '../../events'
import { EventBusInterface } from '../../events/EventSystem/EventBusInterface'
import { SparkplugDecoder } from './Model/sparkplugb'
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
@@ -33,12 +29,12 @@ export class ConnectionManager {
const connectionStateEvent = makeConnectionStateEvent(connectionId)
connection.stateMachine.onUpdate.subscribe(state => {
this.backendEvents.emit(connectionStateEvent, state)
backendEvents.emit(connectionStateEvent, state)
})
connection.connect(options)
this.handleNewMessagesForConnection(connectionId, connection)
this.backendEvents.subscribe(makePublishEvent(connectionId), (msg: MqttMessage) => {
backendEvents.subscribe(makePublishEvent(connectionId), (msg: MqttMessage) => {
this.connections[connectionId].publish(msg)
})
}
@@ -51,12 +47,9 @@ export class ConnectionManager {
buffer = buffer.slice(0, 20000)
}
let decoded_payload = null
decoded_payload = Base64Message.fromBuffer(buffer)
this.backendEvents.emit(messageEvent, {
backendEvents.emit(messageEvent, {
topic,
payload: decoded_payload,
payload: SparkplugDecoder.decode(buffer) ?? Base64Message.fromBuffer(buffer),
qos: packet.qos,
retain: packet.retain,
messageId: packet.messageId,
@@ -65,8 +58,8 @@ export class ConnectionManager {
}
public manageConnections() {
this.backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
this.backendEvents.subscribe(removeConnection, (connectionId: string) => {
backendEvents.subscribe(addMqttConnectionEvent, this.handleConnectionRequest)
backendEvents.subscribe(removeConnection, (connectionId: string) => {
this.removeConnection(connectionId)
})
}
@@ -74,7 +67,7 @@ export class ConnectionManager {
public removeConnection(connectionId: string) {
const connection = this.connections[connectionId]
if (connection) {
this.backendEvents.unsubscribeAll(makePublishEvent(connectionId))
backendEvents.unsubscribeAll(makePublishEvent(connectionId))
connection.disconnect()
delete this.connections[connectionId]
connection.stateMachine.onUpdate.removeAllListeners()
+3
View File
@@ -0,0 +1,3 @@
--require ts-node/register
--require source-map-support/register
--recursive ./src/**/*.spec.ts
+2 -14
View File
@@ -6,21 +6,11 @@
"strictNullChecks": true,
"outDir": "./build",
"strict": true,
"module": "commonjs",
"moduleResolution": "node",
"target": "ES2017",
"lib": [
"es2017",
"dom"
],
"sourceMap": true,
"esModuleInterop": true
},
"ts-node": {
"compilerOptions": {
"module": "commonjs"
},
"transpileOnly": true
"sourceMap": true
},
"includes": [
"src/**/*.ts"
@@ -30,8 +20,6 @@
"node_modules",
"src/**/*.spec.ts",
"**/*.d.ts",
"typings",
"../events",
"../app"
"typings"
]
}
+24 -2274
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,7 +1,7 @@
FROM node:20
FROM node:11-stretch
RUN DEBIAN_FRONTEND="noninteractive" apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates nano ffmpeg xvfb git-core tmux locales mosquitto x11vnc
&& apt-get install -y --no-install-recommends nano ffmpeg xvfb git-core tmux locales mosquitto x11vnc
RUN apt-get install -yq --no-install-recommends libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 libnss3
# Generate locales for TMUX
@@ -12,5 +12,6 @@ ENV LC_ALL en_US.UTF-8
CMD /bin/bash
COPY cloneBuildAndTest.sh ./
VOLUME /app
EXPOSE 5900
+5 -1
View File
@@ -1,7 +1,11 @@
#!/bin/bash
set -e
yarn install --frozen-lockfile
git clone https://github.com/thomasnordquist/MQTT-Explorer.git /app
cd /app
git checkout travis-ui-tests
yarn
yarn build
yarn ui-test
-29
View File
@@ -1,29 +0,0 @@
// 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
+7 -73
View File
@@ -1,54 +1,24 @@
import { IpcMain, WebContents } from 'electron'
import { IpcMain } from 'electron'
import { Event } from '../Events'
import { EventBusInterface } from './EventBusInterface'
export class IpcMainEventBus implements EventBusInterface {
private ipc: IpcMain
private clients: Map<number, WebContents> = new Map() // webContentsId -> WebContents
private connectionOwners: Map<string, number> = new Map() // connectionId -> webContentsId
private currentClient: WebContents | undefined
private client: any
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) => {
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
for (const [connectionId, webContentsId] of this.connectionOwners.entries()) {
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)
}
this.client = event.sender
callback(arg)
})
}
public unsubscribeAll<MessageType>(event: Event<MessageType>) {
console.log('unsubscribeAll', event.topic)
this.ipc.removeAllListeners(event.topic)
}
@@ -57,44 +27,8 @@ export class IpcMainEventBus implements EventBusInterface {
}
public emit<MessageType>(event: Event<MessageType>, msg: MessageType) {
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
if (!this.client.isDestroyed()) {
this.client.send(event.topic, msg)
}
// 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
@@ -1,61 +0,0 @@
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)
}
}
}
@@ -1,65 +0,0 @@
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
@@ -1,74 +0,0 @@
/**
* 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 }
}
}
@@ -1,42 +0,0 @@
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)
}
}
@@ -1,274 +0,0 @@
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, 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)
}
}
+2 -10
View File
@@ -1,4 +1,4 @@
import { Base64MessageDTO } from '../backend/src/Model/Base64Message'
import { Base64Message } 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: Base64MessageDTO | null
payload: Base64Message | null
qos: 0 | 1 | 2
retain: boolean
// Set if QoS is > 0 on received messages
@@ -54,11 +54,3 @@ 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
@@ -1,71 +0,0 @@
/**
* 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
+1 -8
View File
@@ -1,15 +1,8 @@
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
import { OpenDialogOptions, OpenDialogReturnValue } 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,5 +1,4 @@
export * from './Events'
export * from './EventsV2'
export * from './EventSystem/EventDispatcher'
export * from './EventSystem/EventBus'
export * from './EventSystem/EventBusInterface'
-14
View File
@@ -1,14 +0,0 @@
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-playwright"
],
"env": {
"PLAYWRIGHT_BROWSERS_PATH": "0"
}
}
}
}
+12 -36
View File
@@ -1,36 +1,26 @@
{
"name": "MQTT-Explorer",
"version": "0.4.0-beta.5",
"version": "0.4.0-beta1",
"description": "Explore your message queues",
"main": "dist/src/electron.js",
"engines": {
"node": ">=20"
"node": "19"
},
"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": "npm-run-all --parallel lint:prettier lint:tslint",
"lint:prettier": "prettier --check \"**/*.ts{x,}\"",
"lint:prettier:fix": "prettier --write \"**/*.ts{x,}\"",
"lint:tslint": "tslint -p ./",
"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",
@@ -84,66 +74,52 @@
"license": "CC-BY-ND-4.0",
"devDependencies": {
"@babel/runtime": "^7.17.2",
"@cspell/dict-typescript": "^3.1.2",
"@electron/notarize": "^2.3.0",
"@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": "^25.0.3",
"@types/node": "^12.6.8",
"@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",
"cspell": "^4.0.28",
"electron": "29.1.1",
"electron-builder": "^24.13.3",
"mocha": "^10.4.0",
"mocha": "7.1",
"mustache": "4",
"npm-run-all": "^4.1.5",
"nyc": "15",
"playwright": "^1.43.0",
"prettier": "^3.2.5",
"redux-thunk": "^2.3.0",
"semantic-release": "^23.0.8",
"semantic-release-export-data": "^1.0.1",
"source-map-support": "^0.5.9",
"sparkplug-client": "^3.2.4",
"spectron": "19",
"ts-node": "^10.9.2",
"tslint": "^6.1.3",
"tslint-config-airbnb": "^5.11.2",
"tslint-react": "^5.0.0",
"tslint-react-recommended": "^1.0.15",
"typescript": "^4.5.5"
"typescript": "^4.5.5",
"webdriverio": "7.16"
},
"dependencies": {
"about-window": "^1.12.1",
"axios": "^0.28.0",
"bcryptjs": "^3.0.3",
"debug": "^4.3.4",
"axios": "^0.19.0",
"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",
"protobufjs": "~6.11.2",
"sha1": "^1.1.1",
"socket.io": "^4.8.1",
"sparkplug-payload": "^1.0.3",
"uuid": "^8.3.2",
"yarn-run-all": "^3.1.1"
}
+14 -14
View File
@@ -7,16 +7,7 @@ const linuxAppImage: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: true,
arm64: true,
projectDir: './build/clean',
publish: 'always',
}
const linuxSnap: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false, // not supported to build on x64
arm64: false, // not supported to build on x64
arm64: false,
projectDir: './build/clean',
publish: 'always',
}
@@ -25,7 +16,16 @@ const linuxDeb: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: true,
arm64: true,
arm64: false,
projectDir: './build/clean',
publish: 'always',
}
const linuxSnap: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false,
arm64: false,
projectDir: './build/clean',
publish: 'always',
}
@@ -61,7 +61,7 @@ const mac: builder.CliOptions = {
x64: true,
ia32: false,
armv7l: false,
arm64: true,
arm64: false,
projectDir: './build/clean',
publish: 'always',
}
@@ -82,8 +82,8 @@ async function executeBuild() {
break
case 'mac':
await buildWithOptions(mac, { platform: 'mac', package: 'dmg' })
// await buildWithOptions(mac, { platform: 'mac', package: 'mas' })
// await buildWithOptions(mac, { platform: 'mac', package: 'zip' })
await buildWithOptions(mac, { platform: 'mac', package: 'mas' })
await buildWithOptions(mac, { platform: 'mac', package: 'zip' })
break
default:
await buildWithOptions({ ...mac, projectDir: '' }, { platform: 'mac', package: 'mas-dev' })
+197
View File
@@ -0,0 +1,197 @@
syntax = "proto2";
//
// To compile:
// cd client_libraries/java
// protoc --proto_path=../../ --java_out=src/main/java ../../sparkplug_b.proto
//
package com.cirruslink.sparkplug.protobuf;
option java_package = "com.cirruslink.sparkplug.protobuf";
option java_outer_classname = "SparkplugBProto";
message Payload {
/*
// Indexes of Data Types
// Unknown placeholder for future expansion.
Unknown = 0;
// Basic Types
Int8 = 1;
Int16 = 2;
Int32 = 3;
Int64 = 4;
UInt8 = 5;
UInt16 = 6;
UInt32 = 7;
UInt64 = 8;
Float = 9;
Double = 10;
Boolean = 11;
String = 12;
DateTime = 13;
Text = 14;
// Additional Metric Types
UUID = 15;
DataSet = 16;
Bytes = 17;
File = 18;
Template = 19;
// Additional PropertyValue Types
PropertySet = 20;
PropertySetList = 21;
*/
message Template {
message Parameter {
optional string name = 1;
optional uint32 type = 2;
oneof value {
uint32 int_value = 3;
uint64 long_value = 4;
float float_value = 5;
double double_value = 6;
bool boolean_value = 7;
string string_value = 8;
ParameterValueExtension extension_value = 9;
}
message ParameterValueExtension {
extensions 1 to max;
}
}
optional string version = 1; // The version of the Template to prevent mismatches
repeated Metric metrics = 2; // Each metric is the name of the metric and the datatype of the member but does not contain a value
repeated Parameter parameters = 3;
optional string template_ref = 4; // Reference to a template if this is extending a Template or an instance - must exist if an instance
optional bool is_definition = 5;
extensions 6 to max;
}
message DataSet {
message DataSetValue {
oneof value {
uint32 int_value = 1;
uint64 long_value = 2;
float float_value = 3;
double double_value = 4;
bool boolean_value = 5;
string string_value = 6;
DataSetValueExtension extension_value = 7;
}
message DataSetValueExtension {
extensions 1 to max;
}
}
message Row {
repeated DataSetValue elements = 1;
extensions 2 to max; // For third party extensions
}
optional uint64 num_of_columns = 1;
repeated string columns = 2;
repeated uint32 types = 3;
repeated Row rows = 4;
extensions 5 to max; // For third party extensions
}
message PropertyValue {
optional uint32 type = 1;
optional bool is_null = 2;
oneof value {
uint32 int_value = 3;
uint64 long_value = 4;
float float_value = 5;
double double_value = 6;
bool boolean_value = 7;
string string_value = 8;
PropertySet propertyset_value = 9;
PropertySetList propertysets_value = 10; // List of Property Values
PropertyValueExtension extension_value = 11;
}
message PropertyValueExtension {
extensions 1 to max;
}
}
message PropertySet {
repeated string keys = 1; // Names of the properties
repeated PropertyValue values = 2;
extensions 3 to max;
}
message PropertySetList {
repeated PropertySet propertyset = 1;
extensions 2 to max;
}
message MetaData {
// Bytes specific metadata
optional bool is_multi_part = 1;
// General metadata
optional string content_type = 2; // Content/Media type
optional uint64 size = 3; // File size, String size, Multi-part size, etc
optional uint64 seq = 4; // Sequence number for multi-part messages
// File metadata
optional string file_name = 5; // File name
optional string file_type = 6; // File type (i.e. xml, json, txt, cpp, etc)
optional string md5 = 7; // md5 of data
// Catchalls and future expansion
optional string description = 8; // Could be anything such as json or xml of custom properties
extensions 9 to max;
}
message Metric {
optional string name = 1; // Metric name - should only be included on birth
optional uint64 alias = 2; // Metric alias - tied to name on birth and included in all later DATA messages
optional uint64 timestamp = 3; // Timestamp associated with data acquisition time
optional uint32 datatype = 4; // DataType of the metric/tag value
optional bool is_historical = 5; // If this is historical data and should not update real time tag
optional bool is_transient = 6; // Tells consuming clients such as MQTT Engine to not store this as a tag
optional bool is_null = 7; // If this is null - explicitly say so rather than using -1, false, etc for some datatypes.
optional MetaData metadata = 8; // Metadata for the payload
optional PropertySet properties = 9;
oneof value {
uint32 int_value = 10;
uint64 long_value = 11;
float float_value = 12;
double double_value = 13;
bool boolean_value = 14;
string string_value = 15;
bytes bytes_value = 16; // Bytes, File
DataSet dataset_value = 17;
Template template_value = 18;
MetricValueExtension extension_value = 19;
}
message MetricValueExtension {
extensions 1 to max;
}
}
optional uint64 timestamp = 1; // Timestamp at message sending time
repeated Metric metrics = 2; // Repeated forever - no limit in Google Protobufs
optional uint64 seq = 3; // Sequence number
optional string uuid = 4; // UUID to track message type in terms of schema definitions
optional bytes body = 5; // To optionally bypass the whole definition above
extensions 6 to max; // For third party extensions
}

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