Compare commits

..
Author SHA1 Message Date
Björn Dalfors 69897b4345 test packaging 2024-03-11 13:36:28 +01:00
108 changed files with 3814 additions and 7406 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"
]
}
}
-3
View File
@@ -1,3 +0,0 @@
package.ts @thomasnordquist
.github @thomasnordquist
scripts @thomasnordquist
-105
View File
@@ -1,105 +0,0 @@
# GitHub Copilot Agent Instructions for MQTT Explorer
## Project Setup
### Building and Running
```bash
# Install dependencies
yarn install
# Build the project
yarn build
# 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
### 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
```
## 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
## 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`)
-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: '18'
- 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 }}
-38
View File
@@ -1,38 +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
- name: UI-Test
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
-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
-5
View File
@@ -9,8 +9,3 @@ test.png
.awcache
.scannerwork
screen*.png
# MCP introspection artifacts
mqtt-explorer-mcp-screenshot.png
screenshot-mcp-*.png
test-mcp-introspection.js
+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
+24 -26
View File
@@ -1,8 +1,10 @@
# Creative Commons Attribution-NonCommercial 4.0 International
## creative commons
# 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.
@@ -10,35 +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-NonCommercial 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-NonCommercial 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. __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. __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. __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. __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. __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. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
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. __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. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
h. __Licensor__ means the individual(s) or entity(ies) granting rights under 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. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
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. __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.
k. __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.
l. __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.
@@ -46,9 +44,9 @@ a. ___License grant.___
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
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.
@@ -58,9 +56,9 @@ a. ___License grant.___
5. __Downstream recipients.__
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.
A. __Offer from the Licensor Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
B. __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).
@@ -70,7 +68,7 @@ b. ___Other rights.___
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
### Section 3 License Conditions.
@@ -78,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:
@@ -96,17 +94,17 @@ 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.
4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
### 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 for NonCommercial purposes only;
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; and
+6 -17
View File
@@ -6,12 +6,11 @@
[![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.
@@ -30,7 +29,6 @@ yarn start
## Develop
Launch Application
```bash
npm install -g yarn
yarn
@@ -65,15 +63,6 @@ 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
```
@@ -99,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.
+8 -8
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": ">=18"
"node": "19"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -21,7 +21,7 @@
"@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",
@@ -75,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 -48
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,49 +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,
@@ -87,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,
@@ -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,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'
@@ -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
@@ -52,16 +52,16 @@ function ChartPreview(props: Props) {
/>
</Tooltip>
) : (
<Tooltip title="Add to chart panel, not enough data for preview">
<ShowChart
onClick={onClick}
className={props.classes.icon}
style={{ color: '#aaa' }}
data-test-type="ShowChart"
data-test={props.literal.path}
/>
</Tooltip>
)
<Tooltip title="Add to chart panel, not enough data for preview">
<ShowChart
onClick={onClick}
className={props.classes.icon}
style={{ color: '#aaa' }}
data-test-type="ShowChart"
data-test={props.literal.path}
/>
</Tooltip>
)
return (
<span>
@@ -69,7 +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])
}
+4 -4
View File
@@ -1,7 +1,7 @@
import compareVersions from 'compare-versions'
import electron from 'electron'
import os from 'os'
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'
+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
+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
}
}
}
+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',
},
}
};
+296 -525
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
+6 -6
View File
@@ -4,15 +4,15 @@
"description": "",
"main": "build/index.js",
"scripts": {
"test": "mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"test": "mocha",
"build": "tsc",
"test-inspect": "mocha --inspect-brk --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"coverage": "nyc mocha --require ts-node/register --require source-map-support/register --recursive ./src/*/**/*.spec.ts",
"test-inspect": "mocha --inspect-brk",
"coverage": "nyc mocha",
"debug": "ts-node --inspect ./src/index.ts",
"postinstall": "yarn build"
},
"engines": {
"node": ">=18"
"node": "19"
},
"author": "",
"license": "CC-BY-ND-4.0",
@@ -41,9 +41,9 @@
"peerDependencies": {
"fs-extra": "^8.0.1",
"js-base64": "^2.5.1",
"long": "^4.0.0",
"lowdb": "^1.0.0",
"mqtt": "^3.0.0",
"protobufjs": "^6.11.4"
"protobufjs": "~6.11.2",
"long": "^4.0.0"
}
}
+4 -4
View File
@@ -1,7 +1,7 @@
import FileAsync from 'lowdb/adapters/FileAsync'
import fs from 'fs-extra'
import lowdb from 'lowdb'
import path from 'path'
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'
+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
+2 -4
View File
@@ -10,6 +10,7 @@ import {
makePublishEvent,
removeConnection,
} from '../../events'
import { SparkplugDecoder } from './Model/sparkplugb'
export class ConnectionManager {
private connections: { [s: string]: DataSource<any> } = {}
@@ -46,12 +47,9 @@ export class ConnectionManager {
buffer = buffer.slice(0, 20000)
}
let decoded_payload = null
decoded_payload = Base64Message.fromBuffer(buffer)
backendEvents.emit(messageEvent, {
topic,
payload: decoded_payload,
payload: SparkplugDecoder.decode(buffer) ?? Base64Message.fromBuffer(buffer),
qos: packet.qos,
retain: packet.retain,
messageId: packet.messageId,
+3
View File
@@ -0,0 +1,3 @@
--require ts-node/register
--require source-map-support/register
--recursive ./src/**/*.spec.ts
+18 -25
View File
@@ -5,7 +5,7 @@
"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@protobufjs/aspromise/-/aspromise-1.1.2.tgz#9b8b0cc663d669a7d8f6f5d0893a14d348f30fbf"
integrity sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==
integrity sha1-m4sMxmPWaafY9vXQiToU00jzD78=
"@protobufjs/base64@^1.1.2":
version "1.1.2"
@@ -20,12 +20,12 @@
"@protobufjs/eventemitter@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz#355cbc98bafad5978f9ed095f397621f1d066b70"
integrity sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==
integrity sha1-NVy8mLr61ZePntCV85diHx0Ga3A=
"@protobufjs/fetch@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/fetch/-/fetch-1.1.0.tgz#ba99fb598614af65700c1619ff06d454b0d84c45"
integrity sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==
integrity sha1-upn7WYYUr2VwDBYZ/wbUVLDYTEU=
dependencies:
"@protobufjs/aspromise" "^1.1.1"
"@protobufjs/inquire" "^1.1.0"
@@ -33,49 +33,47 @@
"@protobufjs/float@^1.0.2":
version "1.0.2"
resolved "https://registry.yarnpkg.com/@protobufjs/float/-/float-1.0.2.tgz#5e9e1abdcb73fc0a7cb8b291df78c8cbd97b87d1"
integrity sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==
integrity sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=
"@protobufjs/inquire@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/inquire/-/inquire-1.1.0.tgz#ff200e3e7cf2429e2dcafc1140828e8cc638f089"
integrity sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==
integrity sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=
"@protobufjs/path@^1.1.2":
version "1.1.2"
resolved "https://registry.yarnpkg.com/@protobufjs/path/-/path-1.1.2.tgz#6cc2b20c5c9ad6ad0dccfd21ca7673d8d7fbf68d"
integrity sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==
integrity sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=
"@protobufjs/pool@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/pool/-/pool-1.1.0.tgz#09fd15f2d6d3abfa9b65bc366506d6ad7846ff54"
integrity sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==
integrity sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=
"@protobufjs/utf8@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570"
integrity sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==
integrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=
"@types/long@^4.0.1":
version "4.0.2"
resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.2.tgz#b74129719fc8d11c01868010082d483b7545591a"
integrity sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==
version "4.0.1"
resolved "https://registry.yarnpkg.com/@types/long/-/long-4.0.1.tgz#459c65fa1867dafe6a8f322c4c51695663cc55e9"
integrity sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w==
"@types/node@>=13.7.0":
version "20.12.2"
resolved "https://registry.yarnpkg.com/@types/node/-/node-20.12.2.tgz#9facdd11102f38b21b4ebedd9d7999663343d72e"
integrity sha512-zQ0NYO87hyN6Xrclcqp7f8ZbXNbRfoGWNcMvHTPQp9UUrwI0mI7XBz+cu7/W6/VClYo2g63B0cjull/srU7LgQ==
dependencies:
undici-types "~5.26.4"
version "16.4.13"
resolved "https://registry.yarnpkg.com/@types/node/-/node-16.4.13.tgz#7dfd9c14661edc65cccd43a29eb454174642370d"
integrity sha512-bLL69sKtd25w7p1nvg9pigE4gtKVpGTPojBFLMkGHXuUgap2sLqQt2qUnqmVCDfzGUL0DRNZP+1prIZJbMeAXg==
long@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28"
integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==
protobufjs@^6.11.4:
version "6.11.4"
resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.11.4.tgz#29a412c38bf70d89e537b6d02d904a6f448173aa"
integrity sha512-5kQWPaJHi1WoCpjTGszzQ32PG2F4+wRY6BmAT4Vfw56Q2FZ4YZzK20xUYQH4YkfehY1e6QSICrJquM6xXZNcrw==
protobufjs@^6.11.2:
version "6.11.2"
resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-6.11.2.tgz#de39fabd4ed32beaa08e9bb1e30d08544c1edf8b"
integrity sha512-4BQJoPooKJl2G9j3XftkIXjoC9C0Av2NOrWmbLWT1vH32GcSUHjM0Arra6UfTsVyfMAuFzaLucXn1sadxJydAw==
dependencies:
"@protobufjs/aspromise" "^1.1.2"
"@protobufjs/base64" "^1.1.2"
@@ -90,8 +88,3 @@ protobufjs@^6.11.4:
"@types/long" "^4.0.1"
"@types/node" ">=13.7.0"
long "^4.0.0"
undici-types@~5.26.4:
version "5.26.5"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617"
integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==
+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
+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',
}
+1 -7
View File
@@ -1,4 +1,4 @@
import { OpenDialogOptions, OpenDialogReturnValue, SaveDialogOptions, SaveDialogReturnValue } from 'electron'
import { OpenDialogOptions, OpenDialogReturnValue } from 'electron'
import { RpcEvent } from './EventSystem/Rpc'
export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogReturnValue> {
@@ -6,9 +6,3 @@ export function makeOpenDialogRpc(): RpcEvent<OpenDialogOptions, OpenDialogRetur
topic: 'openDialog',
}
}
export function makeSaveDialogRpc(): RpcEvent<SaveDialogOptions, SaveDialogReturnValue> {
return {
topic: 'saveDialog',
}
}
-14
View File
@@ -1,14 +0,0 @@
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-playwright"
],
"env": {
"PLAYWRIGHT_BROWSERS_PATH": "0"
}
}
}
}
+11 -21
View File
@@ -1,28 +1,24 @@
{
"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": ">=18"
"node": "19"
},
"private": "true",
"scripts": {
"start": "electron .",
"test": "yarn test:app && yarn test:backend",
"test:app": "cd app && yarn test",
"test:backend": "cd backend && yarn test",
"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",
"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 ..",
"prepare-release": "ts-node scripts/prepare-release.ts",
@@ -78,11 +74,7 @@
"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/chai": "^4.1.7",
"@types/fs-extra": "8",
"@types/lowdb": "^1.0.6",
@@ -95,30 +87,28 @@
"@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",
"axios": "^0.19.0",
"dot-prop": "^5.0.0",
"electron-log": "4.4.6",
"electron-updater": "^4.6",
@@ -128,8 +118,8 @@
"lowdb": "^1.0.0",
"mime": "^2.4.4",
"mqtt": "^4.3.6",
"protobufjs": "~6.11.2",
"sha1": "^1.1.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
}
+3 -3
View File
@@ -17,18 +17,18 @@ async function prepareRelease() {
// Install app dependencies
chdir('app')
await exec('yarn', ['install', '--frozen-lockfile'])
await exec('yarn')
chdir('..')
// Install electron dependencies
await exec('yarn', ['install', '--frozen-lockfile'])
await exec('yarn')
// Build App and Electron backend
await exec('yarn', ['build'])
// Clean up
await fs.remove('node_modules')
await exec('yarn', ['install', '--production', '--frozen-lockfile']) // Do not clean up, electron version detection will fail otherwise
await exec('yarn', ['install', '--production']) // Do not clean up, electron version detection will fail otherwise
await fs.remove(path.join('app', 'node_modules'))
chdir(originalDir)
-232
View File
@@ -1,232 +0,0 @@
/********************************************************************************
* Copyright (c) 2016-2018 Cirrus Link Solutions and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Cirrus Link Solutions - initial implementation
********************************************************************************/
var SparkplugClient = require('sparkplug-client')
/*
* Main sample function which includes the run() function for running the sample
*/
var sample = (function () {
var config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
},
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'boolean',
value: false,
},
{
name: 'Template1',
type: 'template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'boolean' },
{ name: 'myInt', value: 0, type: 'int' },
],
parameters: [
{
name: 'param1',
type: 'string',
value: 'value1',
},
],
},
},
],
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'float' },
{ name: 'my_int', value: randomInt(), type: 'int' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'long' },
{ name: 'Inputs/0', value: true, type: 'boolean' },
{ name: 'Inputs/1', value: 0, type: 'int' },
{ name: 'Inputs/2', value: 1.23, type: 'float' },
{ name: 'Outputs/0', value: true, type: 'boolean' },
{ name: 'Outputs/1', value: 0, type: 'int' },
{ name: 'Outputs/2', value: 1.23, type: 'float' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'string' },
{ name: 'Properties/sw_version', value: swVersion, type: 'string' },
{
name: 'my_dataset',
type: 'dataset',
value: {
numOfColumns: 2,
types: ['string', 'string'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'boolean' },
{ name: 'myInt', value: 100, type: 'int' },
],
parameters: [
{
name: 'param1',
type: 'string',
value: 'value2',
},
],
},
},
],
}
},
// Get data payload for the device
getDataPayload = function () {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'float' },
{ name: 'my_int', value: randomInt(), type: 'int' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'long' },
],
}
},
// Runs the sample
run = function () {
// Create the SparkplugClient
sparkplugClient = SparkplugClient.newClient(config)
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic, payload) {
console.log(topic, payload)
})
// Create 'birth' handler
sparkplugClient.on('birth', function () {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
})
// Create node command handler
sparkplugClient.on('ncmd', function (payload) {
var timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
}
}
})
// Create device command handler
sparkplugClient.on('dcmd', function (deviceId, payload) {
var timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap = {},
outboundMetric = [],
outboundPayload
console.log('Command recevied for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
inboundMetricMap[metric.name] = metric.value
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'int' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'int' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'float' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'float' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
for (var i = 1; i < 101; i++) {
// Set up a device data publish for i*publishPeriod milliseconds from now
setTimeout(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
// End the client connection after the last publish
if (i === 100) {
sparkplugClient.stop()
}
}, i * publishPeriod)
}
}
return { run: run }
})()
// Run the sample
sample.run()
+17 -26
View File
@@ -1,25 +1,10 @@
#!/bin/bash
function finish {
set +e
echo "Exiting, cleaning up.."
echo "Stopping TMUX session (record).."
tmux kill-session -t record || echo "Already stopped"
if [[ ! -z "$PID_MOSQUITTO" ]]; then
echo "Stopping mosquitto ($PID_MOSQUITTO).."
kill "$PID_MOSQUITTO" || echo "Already stopped"
fi
if [[ ! -z "$PID_VNC" ]]; then
echo "Stopping VNC ($PID_VNC).."
kill "$PID_VNC" || echo "Already stopped"
fi
if [[ ! -z "$PID_XVFB" ]]; then
echo "Stopping XVFB ($PID_XVFB).."
kill "$PID_XVFB" || echo "Already stopped"
fi
echo "Exiting, cleaning up"
tmux send-keys -t record q || echo "No tmux was running"
#echo kill $PID_XVFB $PID_CHROMEDRIVER $PID_MOSQUITTO
#kill $PID_XVFB $PID_CHROMEDRIVER $PID_MOSQUITTO
}
trap finish EXIT
@@ -33,25 +18,28 @@ export PID_XVFB=$!
sleep 2
# Debug with VNC
x11vnc -localhost -rfbport 5900 -passwd "bierbier" -display :$SCR &
while [ "$TEST_EXIT_CODE" = "" ]; do x11vnc -localhost -passwd "bierbier" -display :$SCR; done &
export PID_VNC=$!
# Start mqtt broker
mosquitto &
export PID_MOSQUITTO=$!
DISPLAY=:$SCR ./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 &
export PID_CHROMEDRIVER=$!
sleep 2
# Delete old video
rm -f ./app*.mp4
rm -f ./qrawvideorgb24.yuv
rm ./app.mp4 || echo no need to delete ./app.mp4
# Start recoring in tmux
# tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -codec:v libx264 -r 20 ./app.mp4
#tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -codec:v libx264 -r 20 ./app.mp4
tmux new-session -d -s record ffmpeg -f x11grab -draw_mouse 0 -video_size $DIMENSIONS -i :$SCR -r 20 -vcodec rawvideo -pix_fmt yuv420p qrawvideorgb24.yuv
# Start tests
DISPLAY=:$SCR node dist/src/spec/demoVideo.js
node dist/src/spec/demoVideo.js
TEST_EXIT_CODE=$?
echo "Test script exited with $TEST_EXIT_CODE"
echo "Webriver exitet with $TEST_EXIT_CODE"
# Stop recording
tmux send-keys -t record q
@@ -59,4 +47,7 @@ tmux send-keys -t record q
# Ensure video is written
sleep 5
# Process the video
./scripts/prepareVideo.sh
exit $TEST_EXIT_CODE
+1 -2
View File
@@ -27,7 +27,7 @@ async function createDraft(tag: string) {
draft: true,
},
})
// @ts-ignore
return cleanUploadUrl(response.data.upload_url)
}
@@ -76,7 +76,6 @@ async function uploadFile(uploadUrl: string, file: string) {
const data = fs.readFileSync(file)
const mimeType = mime.getType(path.extname(file))
// @ts-ignore
return axios({
data,
method: 'post',
-21
View File
@@ -17,12 +17,10 @@ export async function waitForDevServer() {
}
export function loadDevTools() {
/* spell-checker: disable */
// Redux
// BrowserWindow.addDevToolsExtension(
// path.join(os.homedir(), '/Library/Application Support/Google/Chrome/Default/Extensions/lmhkpmbekcpmknklioeibfkpmmfibljd/2.17.0_0/')
// )
/* spell-checker: enable */
}
export function isDev() {
@@ -32,22 +30,3 @@ export function isDev() {
export function runningUiTestOnCi() {
return Boolean(process.argv.find(arg => arg === '--runningUiTestOnCi'))
}
export function enableMcpIntrospection() {
return Boolean(process.argv.find(arg => arg === '--enable-mcp-introspection'))
}
export function getRemoteDebuggingPort() {
const portArg = process.argv.find(arg => arg.startsWith('--remote-debugging-port='))
if (portArg) {
const parts = portArg.split('=')
if (parts.length === 2 && parts[1]) {
const port = parseInt(parts[1], 10)
// Return the port only if it's a valid number between 1 and 65535
if (!isNaN(port) && port > 0 && port <= 65535) {
return port
}
}
}
return enableMcpIntrospection() ? 9222 : undefined
}
+7 -35
View File
@@ -4,22 +4,14 @@ import ConfigStorage from '../backend/src/ConfigStorage'
import { app, BrowserWindow, Menu, dialog } from 'electron'
import { autoUpdater } from 'electron-updater'
import { ConnectionManager } from '../backend/src/index'
import { promises as fsPromise } from 'fs'
// import { electronTelemetryFactory } from 'electron-telemetry'
import { menuTemplate } from './MenuTemplate'
import buildOptions from './buildOptions'
import {
waitForDevServer,
isDev,
runningUiTestOnCi,
loadDevTools,
enableMcpIntrospection,
getRemoteDebuggingPort,
} from './development'
import { waitForDevServer, isDev, runningUiTestOnCi, loadDevTools } from './development'
import { shouldAutoUpdate, handleAutoUpdate } from './autoUpdater'
import { registerCrashReporter } from './registerCrashReporter'
import { makeOpenDialogRpc, makeSaveDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion, writeToFile, readFromFile } from '../events'
import { makeOpenDialogRpc } from '../events/OpenDialogRequest'
import { backendRpc, getAppVersion } from '../events'
registerCrashReporter()
@@ -27,34 +19,12 @@ registerCrashReporter()
// const electronTelemetry = electronTelemetryFactory('9b0c8ca04a361eb8160d98c5', buildOptions)
// }
// disable-dev-shm-usage is required to run the debug console
app.commandLine.appendSwitch('--no-sandbox --disable-dev-shm-usage')
// Enable remote debugging for MCP introspection
const remoteDebuggingPort = getRemoteDebuggingPort()
if (remoteDebuggingPort) {
app.commandLine.appendSwitch('--remote-debugging-port', remoteDebuggingPort.toString())
log.info(`Remote debugging enabled on port ${remoteDebuggingPort}`)
}
app.commandLine.appendSwitch('--no-sandbox')
app.whenReady().then(() => {
backendRpc.on(makeOpenDialogRpc(), async request => {
return dialog.showOpenDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(makeSaveDialogRpc(), async request => {
return dialog.showSaveDialog(BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows()[0], request)
})
backendRpc.on(getAppVersion, async () => app.getVersion())
backendRpc.on(writeToFile, async ({ filePath, data, encoding }) => {
await fsPromise.writeFile(filePath, Buffer.from(data, 'base64'), { encoding })
})
backendRpc.on(readFromFile, async ({ filePath, encoding }) => {
return fsPromise.readFile(filePath, { encoding })
})
})
autoUpdater.logger = log
@@ -63,7 +33,7 @@ log.info('App starting...')
const connectionManager = new ConnectionManager()
connectionManager.manageConnections()
const configStorage = new ConfigStorage(path.join(app.getPath('userData'), 'settings.json'))
const configStorage = new ConfigStorage(path.join(app.getPath('appData'), app.name, 'settings.json'))
configStorage.init()
// Keep a global reference of the window object, if you don't, the window will
@@ -99,6 +69,8 @@ async function createWindow() {
}
})
console.log('icon path', iconPath)
// Load the index.html of the app.
if (isDev()) {
mainWindow.loadURL('http://localhost:8080')
-1
View File
@@ -19,7 +19,6 @@ export type SceneNames =
| 'settings'
| 'customize_subscriptions'
| 'keyboard_shortcuts'
| 'sparkplugb-decoding'
| 'end'
export class SceneBuilder {
+63 -93
View File
@@ -1,11 +1,7 @@
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { ElectronApplication, _electron as electron } from 'playwright'
import * as webdriverio from 'webdriverio'
import mockMqtt, { stop as stopMqtt } from './mock-mqtt'
import { default as MockSparkplug } from './mock-sparkplugb'
import { clearOldTopics } from './scenarios/clearOldTopics'
import { clearSearch, searchTree } from './scenarios/searchTree'
import { clickOnHistory, createFakeMousePointer, hideText, showText, sleep } from './util'
@@ -14,160 +10,134 @@ import { copyTopicToClipboard } from './scenarios/copyTopicToClipboard'
import { copyValueToClipboard } from './scenarios/copyValueToClipboard'
import { disconnect } from './scenarios/disconnect'
import { publishTopic } from './scenarios/publishTopic'
import { Scene, SceneBuilder } from './SceneBuilder'
import { SceneBuilder } from './SceneBuilder'
import { showAdvancedConnectionSettings } from './scenarios/showAdvancedConnectionSettings'
import { showJsonPreview } from './scenarios/showJsonPreview'
import { showMenu } from './scenarios/showMenu'
import { showNumericPlot } from './scenarios/showNumericPlot'
import { showOffDiffCapability } from './scenarios/showOffDiffCapability'
import { showZoomLevel } from './scenarios/showZoomLevel'
import { showSparkPlugDecoding } from './scenarios/showSparkplugDecoding'
/**
* A convenience method that handles gracefully cleaning up the test run.
*/
const cleanUp = async (scenes: SceneBuilder, electronApp: ElectronApplication) => {
// Exit app.
fs.writeFileSync('scenes.json', JSON.stringify(scenes.scenes, undefined, ' '))
await electronApp.close()
}
process.on('unhandledRejection', (error: Error | any) => {
console.error('unhandledRejection', error.message, error.stack)
process.exit(1)
})
setTimeout(
() => {
console.error('Timeout reached')
process.exit(1)
},
60 * 10 * 1000
)
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
const options = {
host: '127.0.0.1', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
path: '/wd/hub',
capabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
binary: `${__dirname}/../../../node_modules/.bin/electron`,
args: [
`--app=${__dirname}/../../..`,
'--force-device-scale-factor=1',
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-extensions',
].concat(runningUiTestOnCi),
windowTypes: ['app', 'webview'],
},
},
}
async function doStuff() {
console.log('Waiting for MQTT Broker on port 1880 (no auth)')
await mockMqtt()
console.log('start webdriver')
console.log('Starting playwright/electron')
// Launch Electron app.
const electronApp: ElectronApplication = await electron.launch({
args: [`${__dirname}/../../..`, ...runningUiTestOnCi],
})
console.log('Playwright started')
// Get the first window that the app opens, wait if necessary.
const page = await electronApp.firstWindow({ timeout: 3000 })
// Print the title.
console.log(await page.title())
// Capture a screenshot.
await page.screenshot({ path: 'intro.png' })
// Direct Electron console to Node terminal.
page.on('console', console.log)
const browser = await webdriverio.remote(options)
await createFakeMousePointer(browser)
// Wait for Username input to be visible
await page.locator('//label[contains(text(), "Username")]/..//input')
await browser.$('//label[contains(text(), "Username")]/..//input')
const scenes = new SceneBuilder()
await scenes.record('connect', async () => {
await connectTo('127.0.0.1', page)
await MockSparkplug.run() // Start sparkplug client after connect or birth topics will be missed
await connectTo('127.0.0.1', browser)
await sleep(1000)
})
await scenes.record('numeric_plots', async () => {
await showText('Plot topic history', 1500, page)
await showNumericPlot(page)
await showText('Plot topic history', 1500, browser)
await showNumericPlot(browser)
await sleep(2000)
})
await scenes.record('json-formatting', async () => {
await showJsonPreview(page)
await showText('Formatted messages', 1500, page, 'top')
await showJsonPreview(browser)
await showText('Formatted messages', 1500, browser, 'top')
await sleep(1500)
})
await scenes.record('diffs', async () => {
await showOffDiffCapability(page)
await hideText(page)
await showOffDiffCapability(browser)
await hideText(browser)
})
// disable this scenario for now until expandTopic is sorted out
// await scenes.record('publish_topic', async () => {
// await showText('Publish topics', 1500, page, 'top')
// await clickOnHistory(page)
// await publishTopic(page)
// await sleep(1000)
// })
await scenes.record('publish_topic', async () => {
await showText('Publish topics', 1500, browser, 'top')
await clickOnHistory(browser)
await publishTopic(browser)
await sleep(1000)
})
await scenes.record('clipboard', async () => {
await showText('Copy to Clipboard', 1500, page)
await copyTopicToClipboard(page)
await hideText(page)
await copyValueToClipboard(page)
await showText('Copy to Clipboard', 1500, browser)
await copyTopicToClipboard(browser)
await hideText(browser)
await copyValueToClipboard(browser)
await sleep(1000)
})
await scenes.record('topic_filter', async () => {
await showText('Search topic hierarchy', 0, page, 'middle')
await searchTree('temp', page)
await hideText(page)
await showText('Topics containing "temp"', 1500, page)
await showText('Search topic hierarchy', 0, browser, 'middle')
await searchTree('temp', browser)
await hideText(browser)
await showText('Topics containing "temp"', 1500, browser)
await sleep(1500)
await clearSearch(page)
await clearSearch(browser)
await sleep(1000)
})
await scenes.record('sparkplugb-decoding', async () => {
await showText('SparkplugB Decoding', 2000, page, 'top')
await showSparkPlugDecoding(page)
await scenes.record('delete_retained_topics', async () => {
await hideText(browser)
await showText('Delete retained topics', 5000, browser)
await clearOldTopics(browser)
await hideText(browser)
})
// disable this scenario for now until expandTopic is sorted out
// await scenes.record('delete_retained_topics', async () => {
// await hideText(page)
// await showText('Delete retained topics', 5000, page)
// await clearOldTopics(page)
// await hideText(page)
// })
await scenes.record('settings', async () => {
await showText('Settings', 1500, page)
await showMenu(page)
await showText('Settings', 1500, browser)
await showMenu(browser)
})
await scenes.record('customize_subscriptions', async () => {
await sleep(2000)
await disconnect(page)
await showText('Customize Subscriptions', 1500, page, 'top')
await showAdvancedConnectionSettings(page)
await disconnect(browser)
await showText('Customize Subscriptions', 1500, browser, 'top')
await showAdvancedConnectionSettings(browser)
})
await scenes.record('keyboard_shortcuts', async () => {
await showText('Keyboard shortcuts', 1500, page, 'middle')
await showText('Keyboard shortcuts', 1500, browser, 'middle')
await sleep(1750)
await showZoomLevel(page)
await showZoomLevel(browser)
})
await scenes.record('end', async () => {
await showText('The End', 3000, page, 'middle')
await showText('The End', 3000, browser, 'middle')
await sleep(3000)
})
setTimeout(() => {
console.log('Forced quit')
process.exit(0)
}, 10 * 1000)
browser.closeWindow()
stopMqtt()
console.log('Stopped mqtt client')
cleanUp(scenes, electronApp)
// Force exit since there appear to be open handles
process.exit(0)
fs.writeFileSync('scenes.json', JSON.stringify(scenes.scenes, undefined, ' '))
}
doStuff()
+38 -20
View File
@@ -1,6 +1,5 @@
import * as os from 'os'
import { ElectronApplication, _electron as electron } from 'playwright'
import * as webdriverio from 'webdriverio'
import mockMqtt, { stopUpdates as stopMqttUpdates } from './mock-mqtt'
import { ClassNameMapping, countInstancesOf, createFakeMousePointer, getHeapDump, setFast, sleep } from './util'
import { clearSearch, searchTree } from './scenarios/searchTree'
@@ -14,53 +13,67 @@ process.on('unhandledRejection', (error: Error | any) => {
const runningUiTestOnCi = os.platform() === 'darwin' ? [] : ['--runningUiTestOnCi']
const options = {
host: '127.0.0.1', // Use localhost as chrome driver server
port: 9515, // "9515" is the port opened by chrome driver.
capabilities: {
browserName: 'chrome',
'goog:chromeOptions': {
binary: `${__dirname}/../../../node_modules/.bin/electron`,
args: [
`--app=${__dirname}/../../..`,
'--force-device-scale-factor=1',
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-extensions',
].concat(runningUiTestOnCi),
windowTypes: ['app', 'webview'],
},
},
}
async function doStuff() {
console.log('Waiting for MQTT Broker on port 1880 (no auth)')
await mockMqtt()
console.log('start webdriver')
console.log('Starting playwright/electron')
// Launch Electron app.
const electronApp: ElectronApplication = await electron.launch({
args: [`${__dirname}/../../..`, ...runningUiTestOnCi],
})
console.log('Playwright started')
// Get the first window that the app opens, wait if necessary.
const browser = await electronApp.firstWindow({ timeout: 3000 })
// Print the title.
console.log(await browser.title())
// Capture a screenshot.
await browser.screenshot({ path: 'intro.png' })
// Direct Electron console to Node terminal.
browser.on('console', console.log)
const browser = await webdriverio.remote(options)
setFast()
await createFakeMousePointer(browser)
// Wait for Username input to be visible
await browser.locator('//label[contains(text(), "Username")]/..//input')
await browser.$('//label[contains(text(), "Username")]/..//input')
await connectTo('127.0.0.1', browser)
stopMqttUpdates()
await sleep(1000, true)
const heapDump = await getHeapDump(browser)
const initialTreeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.Tree)
const initialNodeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.TreeNode)
console.log(initialTreeOccurrences, initialNodeOccurrences)
await doX(3, async () => {
await reconnect(browser)
})
await sleep(1000, true)
await doX(15, async () => {
await searchTree('temp', browser)
await reconnect(browser)
})
await searchTree('ab', browser)
await clearSearch(browser)
await searchTree('temp', browser)
await clearSearch(browser)
await sleep(1000, true)
await waitForGarbageCollectorToDetermineLeak(browser, initialTreeOccurrences, initialNodeOccurrences)
}
async function waitForGarbageCollectorToDetermineLeak(
browser: any,
initialTreeOccurrences: number,
@@ -77,6 +90,7 @@ async function waitForGarbageCollectorToDetermineLeak(
const heapDump = await getHeapDump(browser)
const currentTreeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.Tree)
const currentNodeOccurrences = await countInstancesOf(heapDump, ClassNameMapping.TreeNode)
// Temporary "leaks" are expected due to React Fibers memoization
if (
Math.abs(initialTreeOccurrences - currentTreeOccurrences) > 1 ||
@@ -93,17 +107,21 @@ async function waitForGarbageCollectorToDetermineLeak(
} else {
leak = false
}
const treeDelta = lastTreeOccurrences >= 0 ? currentTreeOccurrences - lastTreeOccurrences : -1
const nodeDelta = lastTreeOccurrences >= 0 ? currentNodeOccurrences - lastNodeOccurrences : -1
delta = treeDelta + nodeDelta
lastTreeOccurrences = currentTreeOccurrences
lastNodeOccurrences = currentNodeOccurrences
}
if (leak) {
console.error('leak')
process.exit(100)
}
}
async function doX(x: number, action: () => Promise<any>) {
for (let i = 0; i < x; i += 1) {
await action()
-249
View File
@@ -1,249 +0,0 @@
/********************************************************************************
* Copyright (c) 2016-2018 Cirrus Link Solutions and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Cirrus Link Solutions - initial implementation
********************************************************************************/
import * as SparkplugClient from 'sparkplug-client'
import type { UPayload } from 'sparkplug-client'
import type { UMetric } from 'sparkplug-payload/lib/sparkplugbpayload'
/*
* Main sample function which includes the run() function for running the sample
*/
export interface MockSparkplugClient {
stop: () => void
}
var sample = (function () {
var config = {
serverUrl: 'tcp://127.0.0.1:1883',
username: '',
password: '',
groupId: 'Sparkplug Devices',
edgeNode: 'JavaScript Edge Node',
clientId: 'JavaScriptSimpleEdgeNode',
version: 'spBv1.0',
},
hwVersion = 'Emulated Hardware',
swVersion = 'v1.0.0',
deviceId = 'Emulated Device',
sparkPlugClient,
publishPeriod = 5000,
// Generates a random integer
randomInt = function () {
return 1 + Math.floor(Math.random() * 10)
},
// Get BIRTH payload for the edge node
getNodeBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{
name: 'Node Control/Rebirth',
type: 'Boolean',
value: false,
},
{
name: 'Template1',
type: 'Template',
value: {
isDefinition: true,
metrics: [
{ name: 'myBool', value: false, type: 'Boolean' },
{ name: 'myInt', value: 0, type: 'UInt32' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value1',
},
],
},
},
],
}
},
// Get BIRTH payload for the device
getDeviceBirthPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'Float' },
{ name: 'my_int', value: randomInt(), type: 'Int8' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'Int64' },
{ name: 'Inputs/0', value: true, type: 'Boolean' },
{ name: 'Inputs/1', value: 0, type: 'Int8' },
{ name: 'Inputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Outputs/0', value: true, type: 'Boolean' },
{ name: 'Outputs/1', value: 0, type: 'Int16' },
{ name: 'Outputs/2', value: 1.23, type: 'UInt64' },
{ name: 'Properties/hw_version', value: hwVersion, type: 'String' },
{ name: 'Properties/sw_version', value: swVersion, type: 'String' },
{
name: 'my_dataset',
type: 'DataSet',
value: {
numOfColumns: 2,
types: ['String', 'String'],
columns: ['str1', 'str2'],
rows: [
['x', 'a'],
['y', 'b'],
],
},
},
{
name: 'TemplateInstance1',
type: 'Template',
value: {
templateRef: 'Template1',
isDefinition: false,
metrics: [
{ name: 'myBool', value: true, type: 'Boolean' },
{ name: 'myInt', value: 100, type: 'Int8' },
],
parameters: [
{
name: 'param1',
type: 'String',
value: 'value2',
},
],
},
},
],
}
},
// Get data payload for the device
getDataPayload = function (): UPayload {
return {
timestamp: new Date().getTime(),
metrics: [
{ name: 'my_boolean', value: Math.random() > 0.5, type: 'Boolean' },
{ name: 'my_double', value: Math.random() * 0.123456789, type: 'Double' },
{ name: 'my_float', value: Math.random() * 0.123, type: 'UInt64' },
{ name: 'my_int', value: randomInt(), type: 'Int16' },
{ name: 'my_long', value: randomInt() * 214748364700, type: 'UInt64' },
],
}
},
// Runs the sample
run = async function (): Promise<MockSparkplugClient> {
// Create the SparkplugClient
const sparkplugClient = SparkplugClient.newClient(config)
let updateInterval: NodeJS.Timeout | null = null
const connected = new Promise<MockSparkplugClient>((resolve) => {
// Create 'birth' handler
sparkplugClient.on('birth', () => {
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
resolve({
stop: () => {
if (updateInterval) {
clearInterval(updateInterval)
}
sparkplugClient.stop()
}
})
})
})
// Create Incoming Message Handler
sparkplugClient.on('message', function (topic: string, payload: UPayload) {
console.log(topic, payload)
})
// Create node command handler
// spell-checker: disable-next-line
sparkplugClient.on('ncmd', function (payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name == 'Node Control/Rebirth' && metric.value) {
console.log("Received 'Rebirth' command")
// Publish Node BIRTH certificate
sparkplugClient.publishNodeBirth(getNodeBirthPayload())
// Publish Device BIRTH certificate
sparkplugClient.publishDeviceBirth(deviceId, getDeviceBirthPayload())
}
}
}
})
// Create device command handler
// spell-checker: disable-next-line
sparkplugClient.on('dcmd', function (deviceId: string, payload: UPayload) {
var timestamp = payload.timestamp,
metrics = payload.metrics,
inboundMetricMap: { [name: string]: any } = {},
outboundMetric: Array<UMetric> = [],
outboundPayload: UPayload
console.log('Command received for device ' + deviceId)
// Loop over the metrics and store them in a map
if (metrics !== undefined && metrics !== null) {
for (var i = 0; i < metrics.length; i++) {
var metric = metrics[i]
if (metric.name !== undefined && metric.name !== null) {
inboundMetricMap[metric.name] = metric.value
}
}
}
if (inboundMetricMap['Outputs/0'] !== undefined && inboundMetricMap['Outputs/0'] !== null) {
console.log('Outputs/0: ' + inboundMetricMap['Outputs/0'])
outboundMetric.push({ name: 'Inputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
outboundMetric.push({ name: 'Outputs/0', value: inboundMetricMap['Outputs/0'], type: 'Boolean' })
console.log('Updated value for Inputs/0 ' + inboundMetricMap['Outputs/0'])
} else if (inboundMetricMap['Outputs/1'] !== undefined && inboundMetricMap['Outputs/1'] !== null) {
console.log('Outputs/1: ' + inboundMetricMap['Outputs/1'])
outboundMetric.push({ name: 'Inputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
outboundMetric.push({ name: 'Outputs/1', value: inboundMetricMap['Outputs/1'], type: 'Int32' })
console.log('Updated value for Inputs/1 ' + inboundMetricMap['Outputs/1'])
} else if (inboundMetricMap['Outputs/2'] !== undefined && inboundMetricMap['Outputs/2'] !== null) {
console.log('Outputs/2: ' + inboundMetricMap['Outputs/2'])
outboundMetric.push({ name: 'Inputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
outboundMetric.push({ name: 'Outputs/2', value: inboundMetricMap['Outputs/2'], type: 'UInt64' })
console.log('Updated value for Inputs/2 ' + inboundMetricMap['Outputs/2'])
}
outboundPayload = {
timestamp: new Date().getTime(),
metrics: outboundMetric,
}
// Publish device data
sparkplugClient.publishDeviceData(deviceId, outboundPayload)
})
updateInterval = setInterval(function () {
// Publish device data
sparkplugClient.publishDeviceData(deviceId, getDataPayload())
}, 2000)
return connected
}
return { run: run }
})()
export default sample
+5 -5
View File
@@ -1,15 +1,15 @@
import { Page } from 'playwright'
import { Browser, Element } from 'webdriverio'
import { clickOn, expandTopic, moveToCenterOfElement, sleep, writeText } from '../util'
export async function clearOldTopics(browser: Page) {
export async function clearOldTopics(browser: Browser<'async'>) {
const topics = ['hello', 'test 123']
for (const topic of topics) {
await expandTopic(topic, browser)
await sleep(1000)
const deleteButton = await browser.locator('//button[contains(@title, "Delete retained topic")]')
await moveToCenterOfElement(deleteButton)
await clickOn(deleteButton)
const deleteButton = await browser.$('//button[contains(@title, "Delete retained topic")]')
await moveToCenterOfElement(deleteButton, browser)
await clickOn(deleteButton, browser)
await sleep(700)
}
}
+6 -5
View File
@@ -1,10 +1,11 @@
import { Browser, Element } from 'webdriverio'
import { clickOn, setTextInInput } from '../util'
import { Page, Locator } from 'playwright'
export async function connectTo(host: string, browser: Page) {
export async function connectTo(host: string, browser: Browser<'async'>) {
await setTextInInput('Host', host, browser)
await browser.screenshot({ path: 'screen1.png' })
await browser.saveScreenshot('screen1.png')
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Page } from 'playwright'
import { Browser } from 'webdriverio'
import { clickOn } from '../util'
export async function copyTopicToClipboard(browser: Page) {
const copyButton = await browser.locator('//span[contains(text(), "Topic")]//button[1]')
await clickOn(copyButton, 1)
export async function copyTopicToClipboard(browser: Browser<'async'>) {
const copyButton = await browser.$('//span[contains(text(), "Topic")]//button')
await clickOn(copyButton, browser, 1)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Page } from 'playwright'
import { Browser } from 'webdriverio'
import { clickOn } from '../util'
export async function copyValueToClipboard(browser: Page) {
const copyButton = await browser.getByRole('button', { name: 'Value' }).getByRole('button').first()
await clickOn(copyButton, 1)
export async function copyValueToClipboard(browser: Browser<'async'>) {
const copyButton = await browser.$('//span[contains(text(), "Value")]//button')
await clickOn(copyButton, browser, 1)
}
+4 -4
View File
@@ -1,7 +1,7 @@
import { Page } from 'playwright'
import { Browser, Element } from 'webdriverio'
import { clickOn } from '../util'
export async function disconnect(browser: Page) {
const disconnectButton = await browser.locator('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton)
export async function disconnect(browser: Browser<'async'>) {
const disconnectButton = await browser.$('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton, browser)
}
+16 -17
View File
@@ -1,4 +1,4 @@
import { Page, Locator } from 'playwright'
import { Browser, Element } from 'webdriverio'
import {
clickOn,
sleep,
@@ -9,31 +9,30 @@ import {
showText,
} from '../util'
export async function publishTopic(browser: Page) {
export async function publishTopic(browser: Browser<'async'>) {
await expandTopic('kitchen/lamp/state', browser)
const topicInput = await browser.locator('//input[contains(@value,"kitchen/lamp/state")][1]')
await clickOn(topicInput)
await deleteTextWithBackspaces(topicInput, 120, 5)
await writeText('set', topicInput)
const topicInput = await browser.$('//input[contains(@value,"kitchen/lamp/state")][1]')
await clickOn(topicInput, browser)
await deleteTextWithBackspaces(topicInput, browser, 120, 5)
await writeText('set', browser, 300)
const payloadInput = await browser.locator('//*[contains(@class, "ace_text-input")]')
const payloadInput = await browser.$('//*[contains(@class, "ace_text-input")]')
await writeTextPayload(payloadInput, 'off')
await sleep(500)
const formatJsonButton = await browser.locator('#sidebar-publish-format-json')
await clickOn(formatJsonButton)
const formatJsonButton = await browser.$('#sidebar-publish-format-json')
await clickOn(formatJsonButton, browser)
const publishButton = await browser.locator('#publish-button')
await moveToCenterOfElement(publishButton)
const publishButton = await browser.$('#publish-button')
await moveToCenterOfElement(publishButton, browser)
await showText('Lamp turns on', 1000, browser, 'top')
await sleep(500)
await clickOn(publishButton)
await clickOn(publishButton, browser)
const sidebarDrawer = await browser.locator('#Sidebar')
await sidebarDrawer.scrollIntoViewIfNeeded()
const sidebarDrawer = await browser.$('#Sidebar')
await sidebarDrawer.scrollIntoView()
}
async function writeTextPayload(payloadInput: Locator, text: string) {
await clickOn(payloadInput)
await writeText(text, payloadInput)
async function writeTextPayload(payloadInput: any, text: string) {
await payloadInput.setValue(text)
}
+6 -6
View File
@@ -1,9 +1,9 @@
import { Page } from 'playwright'
import { Browser, Element } from 'webdriverio'
import { clickOn } from '../util'
export async function reconnect(browser: Page) {
const disconnectButton = await browser.locator('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton)
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
export async function reconnect(browser: Browser<'async'>) {
const disconnectButton = await browser.$('//button/span[contains(text(),"Disconnect")]')
await clickOn(disconnectButton, browser)
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
}
+9 -9
View File
@@ -1,15 +1,15 @@
import { Page } from 'playwright'
import { Browser, Element } from 'webdriverio'
import { clickOn, deleteTextWithBackspaces, showText, sleep, writeText } from '../util'
export async function searchTree(text: string, browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await writeText(text, searchField)
export async function searchTree(text: string, browser: Browser<'async'>) {
const searchField = await browser.$('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, browser, 1)
await writeText(text, browser, 100)
await sleep(1500)
}
export async function clearSearch(browser: Page) {
const searchField = await browser.locator('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, 1)
await deleteTextWithBackspaces(searchField, 100)
export async function clearSearch(browser: Browser<'async'>) {
const searchField = await browser.$('//input[contains(@placeholder, "Search")]')
await clickOn(searchField, browser, 1)
await deleteTextWithBackspaces(searchField, browser, 100)
}
@@ -1,30 +1,30 @@
import { Page } from 'playwright'
import { Browser } from 'webdriverio'
import { clickOn, sleep, setInputText } from '../util'
export async function showAdvancedConnectionSettings(browser: Page) {
const advancedSettingsButton = await browser.locator('//button/span[contains(text(),"Advanced")]')
const addButton = await browser.locator('//button/span[contains(text(),"Add")]')
const topicInput = await browser.locator('//*[contains(@class, "advanced-connection-settings-topic-input")]//input')
export async function showAdvancedConnectionSettings(browser: Browser<'async'>) {
const advancedSettingsButton = await browser.$('//button/span[contains(text(),"Advanced")]')
const addButton = await browser.$('//button/span[contains(text(),"Add")]')
const topicInput = await browser.$('//*[contains(@class, "advanced-connection-settings-topic-input")]//input')
await clickOn(advancedSettingsButton)
await clickOn(advancedSettingsButton, browser)
await setInputText(topicInput, 'garden/#', browser)
await clickOn(addButton)
await clickOn(addButton, browser)
await setInputText(topicInput, 'livingroom/#', browser)
await clickOn(addButton)
await clickOn(addButton, browser)
await deleteFirstSubscribedTopic(browser)
await deleteFirstSubscribedTopic(browser)
await sleep(1000)
const backButton = await browser.locator('//button/span[contains(text(),"Back")]').first()
await clickOn(backButton)
const backButton = await browser.$('//button/span[contains(text(),"Back")]')
await clickOn(backButton, browser)
const connectButton = await browser.locator('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton)
const connectButton = await browser.$('//button/span[contains(text(),"Connect")]')
await clickOn(connectButton, browser)
}
async function deleteFirstSubscribedTopic(browser: Page) {
const deleteButton = await browser.locator('.advanced-connection-settings-topic-list button').first()
await clickOn(deleteButton)
async function deleteFirstSubscribedTopic(browser: Browser<'async'>) {
const deleteButton = await browser.$('.advanced-connection-settings-topic-list button')
await clickOn(deleteButton, browser)
}
+3 -3
View File
@@ -1,8 +1,8 @@
import { Page, Locator } from 'playwright'
import { Browser, Element } from 'webdriverio'
import { expandTopic, sleep } from '../util'
export async function showJsonPreview(browser: Page) {
export async function showJsonPreview(browser: Browser<'async'>) {
await expandTopic('actuality/showcase', browser)
await browser.screenshot({ path: 'screen3.png' })
await browser.saveScreenshot('screen3.png')
await sleep(1000)
}
+14 -14
View File
@@ -1,31 +1,31 @@
import { Page } from 'playwright'
import { Browser } from 'webdriverio'
import { clickOn, showText, sleep } from '../util'
export async function showMenu(browser: Page) {
const menuButton = await browser.locator('//button[contains(@aria-label, "Menu")]')
await clickOn(menuButton)
export async function showMenu(browser: Browser<'async'>) {
const menuButton = await browser.$('//button[contains(@aria-label, "Menu")]')
await clickOn(menuButton, browser)
// const brokerStatistics = await browser.$('//div[contains(@class, "BrokerStatistics")]/div[1]')
// moveToCenterOfElement(brokerStatistics, browser)
await sleep(2000)
await browser.screenshot({ path: 'screen4.png' })
await browser.saveScreenshot('screen4.png')
const topicOrder = await browser.locator('//input[@name="node-order"]/../div')
await clickOn(topicOrder)
const topicOrder = await browser.$('//input[@name="node-order"]/../div')
await clickOn(topicOrder, browser)
await sleep(1000)
const alphabetically = await browser.locator('//li[contains(@data-value, "abc")]')
await clickOn(alphabetically)
const alphabetically = await browser.$('//li[contains(@data-value, "abc")]')
await clickOn(alphabetically, browser)
await sleep(2000)
await showText('Dark Mode', 1500, browser, 'top')
await sleep(1500)
const themeSwitch = await browser.locator('//*[contains(text(), "Dark Mode")]/..//input')
await clickOn(themeSwitch)
const themeSwitch = await browser.$('//*[contains(text(), "Dark Mode")]/..//input')
await clickOn(themeSwitch, browser)
await sleep(3000)
await browser.screenshot({ path: 'screen_dark_mode.png' })
await clickOn(themeSwitch)
await browser.saveScreenshot('screen_dark_mode.png')
await clickOn(themeSwitch, browser)
await clickOn(menuButton)
await clickOn(menuButton, browser)
}
+22 -26
View File
@@ -1,10 +1,10 @@
import { Page } from 'playwright'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep } from '../util'
import { Browser, Element } from 'webdriverio'
import { moveToCenterOfElement, clickOn, clickOnHistory, expandTopic, sleep, writeText } from '../util'
export async function showNumericPlot(browser: Page) {
export async function showNumericPlot(browser: Browser<'async'>) {
await expandTopic('kitchen/coffee_maker', browser)
let heater = await valuePreviewGuttersShowChartIcon('heater', browser)
await moveToCenterOfElement(heater)
await moveToCenterOfElement(heater, browser)
await sleep(1000)
// Refocus and click
heater = await valuePreviewGuttersShowChartIcon('heater', browser)
@@ -12,7 +12,7 @@ export async function showNumericPlot(browser: Page) {
await sleep(1000)
let temperature = await valuePreviewGuttersShowChartIcon('temperature', browser)
await moveToCenterOfElement(temperature)
await moveToCenterOfElement(temperature, browser)
await sleep(1000)
// Refocus and click
temperature = await valuePreviewGuttersShowChartIcon('temperature', browser)
@@ -30,7 +30,7 @@ export async function showNumericPlot(browser: Page) {
await clickAway('temperature', browser)
await sleep(2500)
await browser.screenshot({ path: 'screen_chart_panel.png' })
await browser.saveScreenshot('screen_chart_panel.png')
await removeChart('heater', browser)
await sleep(750)
@@ -42,38 +42,34 @@ export async function showNumericPlot(browser: Page) {
await clickOnHistory(browser)
}
async function valuePreviewGuttersShowChartIcon(name: string, browser: Page) {
async function valuePreviewGuttersShowChartIcon(name: string, browser: Browser<'async'>) {
for (let retries = 0; retries < 2; retries += 1) {
try {
return await browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`).first()
return await browser.$(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
} catch {
// ignore
}
}
return browser.locator(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`).first()
return browser.$(`//*[contains(@data-test-type, "ShowChart")][contains(@data-test, "${name}")]`)
}
async function chartSettings(name: string, browser: Page) {
const settings = await browser.locator(
`//*[contains(@data-test-type, "ChartSettings")][contains(@data-test, "${name}")]`
)
return clickOn(settings)
async function chartSettings(name: string, browser: Browser<'async'>) {
const settings = await browser.$(`//*[contains(@data-test-type, "ChartSettings")][contains(@data-test, "${name}")]`)
return clickOn(settings, browser)
}
async function clickAway(name: string, browser: Page) {
const settings = await browser.locator(
`//*[contains(@data-test-type, "ChartPaper")][contains(@data-test, "${name}")]`
)
await moveToCenterOfElement(settings)
await settings.press('Escape')
async function clickAway(name: string, browser: Browser<'async'>) {
const settings = await browser.$(`//*[contains(@data-test-type, "ChartPaper")][contains(@data-test, "${name}")]`)
await moveToCenterOfElement(settings, browser)
await browser.keys(['Escape'])
}
async function removeChart(name: string, browser: Page) {
const remove = await browser.locator(`//*[contains(@data-test-type, "RemoveChart")][contains(@data-test, "${name}")]`)
return clickOn(remove)
async function removeChart(name: string, browser: Browser<'async'>) {
const remove = await browser.$(`//*[contains(@data-test-type, "RemoveChart")][contains(@data-test, "${name}")]`)
return clickOn(remove, browser)
}
async function clickOnMenuPoint(name: string, browser: Page) {
const item = await browser.locator(`//li/span[contains(text(), "${name}")]`)
return clickOn(item)
async function clickOnMenuPoint(name: string, browser: Browser<'async'>) {
const item = await browser.$(`//li/span[contains(text(), "${name}")]`)
return clickOn(item, browser)
}

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