Skip to content

Commit

Permalink
Improved serialport implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
mkurczewski committed Dec 21, 2024
1 parent dfb7045 commit 06bebb8
Show file tree
Hide file tree
Showing 39 changed files with 493 additions and 322 deletions.
7 changes: 2 additions & 5 deletions apps/app/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ function createWindow(): void {
mainWindow.webContents.openDevTools()

mainWindow.on("ready-to-show", () => {
mainWindow.show()

initSerialPort(ipcMain, mainWindow.webContents)
initSql(ipcMain)

mainWindow.show()
})

mainWindow.webContents.setWindowOpenHandler((details) => {
Expand Down Expand Up @@ -66,9 +66,6 @@ app.whenReady().then(() => {
optimizer.watchWindowShortcuts(window)
})

// IPC test
ipcMain.on("ping", () => console.log("pong"))

createWindow()

app.on("activate", function () {
Expand Down
8 changes: 4 additions & 4 deletions apps/web/src/app/app.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@

import { render } from "@testing-library/react"
import App from "./app"
import { Device } from "app-serialport/models"
import { SerialPortDeviceInfo } from "app-serialport/models"

jest.mock("app-serialport/renderer", () => {
return {
AppSerialPort: {
onChange: jest.fn().mockResolvedValue([
onDevicesChanged: jest.fn().mockResolvedValue([
{
vendorId: "0e8d",
productId: "2006",
path: "/dev/ttyUSB0.KOM123456789",
},
] as Device[]),
write: jest.fn(),
] as SerialPortDeviceInfo[]),
request: jest.fn(),
},
}
})
Expand Down
185 changes: 45 additions & 140 deletions apps/web/src/app/serialport-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,153 +3,58 @@
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

import { useCallback, useEffect, useRef } from "react"
import { AppSerialPort } from "app-serialport/renderer"
import { ChangedDevices } from "app-serialport/models"
import { useCallback, useEffect } from "react"
import { isEmpty } from "lodash"
import { SerialPortDeviceInfo } from "app-serialport/models"
import { AppSerialPort } from "app-serialport/renderer"

export const useSerialPortListener = () => {
// const interval = useRef<NodeJS.Timeout>()
const ref = useRef(false)

const listenPorts = useCallback(async () => {
if (!ref.current) {
ref.current = true
const onAttach = async (added: NonNullable<ChangedDevices["added"]>) => {
const apiConfigurationResponse = await AppSerialPort.write(added.path, {
endpoint: "API_CONFIGURATION",
method: "GET",
body: {},
options: {
connectionTimeOut: 30000,
},
})
const entitiesConfigurationResponse = await AppSerialPort.write(
added.path,
{
endpoint: "ENTITIES_CONFIGURATION",
method: "GET",
body: {
entityType: "contacts",
},
options: {
connectionTimeOut: 30000,
},
}
)
console.log({ apiConfigurationResponse, entitiesConfigurationResponse })
}
AppSerialPort.onChange((changes) => {
console.log(changes)
if (!isEmpty(changes.added)) {
void onAttach(changes.added)
}
const listenForDevicesChange = useCallback(async () => {
const onAttach = async (device: SerialPortDeviceInfo) => {
const resp1 = await AppSerialPort.request(device.path, {

Check warning on line 14 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L14

Added line #L14 was not covered by tests
endpoint: "API_CONFIGURATION",
method: "GET",
body: {},
options: {
connectionTimeOut: 30000,
},
})
console.log(resp1)

Check warning on line 22 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L22

Added line #L22 was not covered by tests

const resp2 = await AppSerialPort.request(device.path, {

Check warning on line 24 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L24

Added line #L24 was not covered by tests
endpoint: "ENTITIES_CONFIGURATION",
method: "GET",
body: {
entityType: "contacts",
},
options: {
connectionTimeOut: 30000,
},
})
console.log(resp2)

Check warning on line 34 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L34

Added line #L34 was not covered by tests

const resp3 = await AppSerialPort.request(device.path, {

Check warning on line 36 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L36

Added line #L36 was not covered by tests
endpoint: "ENTITIES_DATA",
method: "GET",
body: {
entityType: "contacts",
responseType: "json",
},
options: {
connectionTimeOut: 30000,
},
})
console.log(resp3)

Check warning on line 47 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L47

Added line #L47 was not covered by tests
}

// const req1 = () =>
// AppSerialPort.write(ports[0].path, {
// endpoint: "API_CONFIGURATION",
// method: "GET",
// body: {},
// options: {
// connectionTimeOut: 30000,
// },
// })

// const req2 = () =>
// AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_CONFIGURATION",
// method: "GET",
// body: {
// entityType: "contacts",
// },
// options: {
// connectionTimeOut: 30000,
// },
// })

// await AppSerialPort.write(ports[0].path, {
// endpoint: "API_CONFIGURATION",
// method: "GET",
// body: {},
// options: {
// connectionTimeOut: 30000,
// },
// })
// await new Promise((resolve) => setTimeout(resolve, 100))
// await AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_CONFIGURATION",
// method: "GET",
// body: {
// entityType: "contacts",
// },
// options: {
// connectionTimeOut: 30000,
// },
// })
// await new Promise((resolve) => setTimeout(resolve, 100))
// void AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_DATA",
// method: "GET",
// body: {
// entityType: "contacts",
// responseType: "json",
// },
// options: {
// connectionTimeOut: 30000,
// },
// })
// await new Promise((resolve) => setTimeout(resolve, 100))
// await AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_CONFIGURATION",
// method: "GET",
// body: {
// entityType: "contacts",
// },
// options: {
// connectionTimeOut: 30000,
// },
// })

Promise.all([
// AppSerialPort.write(ports[0].path, {
// endpoint: "API_CONFIGURATION",
// method: "GET",
// body: {},
// options: {
// connectionTimeOut: 30000,
// },
// }),
// AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_CONFIGURATION",
// method: "GET",
// body: {
// entityType: "contacts",
// },
// options: {
// connectionTimeOut: 30000,
// },
// }),
// AppSerialPort.write(ports[0].path, {
// endpoint: "ENTITIES_DATA",
// method: "GET",
// body: {
// entityType: "contacts",
// responseType: "json",
// },
// options: {
// connectionTimeOut: 30000,
// },
// }),
]).then((resp) => {
console.log(resp)
AppSerialPort.onDevicesChanged((changes) => {
console.log(changes)

Check warning on line 50 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L50

Added line #L50 was not covered by tests
if (!isEmpty(changes.added)) {
void onAttach(changes.added[0])

Check warning on line 52 in apps/web/src/app/serialport-demo.ts

View check run for this annotation

Codecov / codecov/patch

apps/web/src/app/serialport-demo.ts#L52

Added line #L52 was not covered by tests
}
})
}, [])

useEffect(() => {
void listenPorts()
// interval.current = setInterval(listenPorts, 2000)
// return () => clearInterval(interval.current)
}, [listenPorts])
void listenForDevicesChange()
}, [listenForDevicesChange])
}
7 changes: 1 addition & 6 deletions apps/web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,8 @@
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

import { StrictMode } from "react"
import * as ReactDOM from "react-dom/client"
import App from "./app/app"

const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement)
root.render(
<StrictMode>
<App />
</StrictMode>
)
root.render(<App />)
5 changes: 0 additions & 5 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@

import { getJestProjectsAsync } from "@nx/jest"

void (async () => {
const p = await getJestProjectsAsync()
console.log(p)
})()

export default async () => ({
projects: await getJestProjectsAsync(),
})
11 changes: 11 additions & 0 deletions libs/app-serialport/devices/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"presets": [
[
"@nx/react/babel",
{
"runtime": "automatic",
"useBuiltIns": "usage"
}
]
]
}
7 changes: 7 additions & 0 deletions libs/app-serialport/devices/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# app-serialport-devices

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test app-serialport-devices` to execute the unit tests via [Vitest](https://vitest.dev/).
17 changes: 17 additions & 0 deletions libs/app-serialport/devices/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Copyright (c) Mudita sp. z o.o. All rights reserved.
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

const nx = require("@nx/eslint-plugin")
const baseConfig = require("../../../eslint.config.js")

module.exports = [
...baseConfig,
...nx.configs["flat/react"],
{
files: ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"],
// Override or add rules here
rules: {},
},
]
15 changes: 15 additions & 0 deletions libs/app-serialport/devices/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Copyright (c) Mudita sp. z o.o. All rights reserved.
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

export default {
displayName: "app-serialport-devices",
preset: "../../../jest.preset.js",
transform: {
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "@nx/react/plugins/jest",
"^.+\\.[tj]sx?$": ["babel-jest", { presets: ["@nx/react/babel"] }],
},
moduleFileExtensions: ["ts", "tsx", "js", "jsx"],
coverageDirectory: "../../../coverage/libs/app-serialport/devices",
}
12 changes: 12 additions & 0 deletions libs/app-serialport/devices/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "app-serialport/devices",
"version": "0.0.1",
"main": "./index.js",
"types": "./index.d.ts",
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js"
}
}
}
9 changes: 9 additions & 0 deletions libs/app-serialport/devices/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "app-serialport-devices",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/app-serialport/devices/src",
"projectType": "library",
"tags": ["scope:main"],
"// targets": "to see all targets run: nx show project app-serialport-devices --web",
"targets": {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

export enum SerialportIpcEvents {
Change = "serialport:change",
Write = "serialport:write",
}
export * from "./lib/serial-port-device"
export * from "./lib/devices"
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright (c) Mudita sp. z o.o. All rights reserved.
* For licensing, see https://github.com/mudita/mudita-center/blob/master/LICENSE.md
*/

import {
apiDeviceRequestParser,
ApiDeviceRequest,
} from "./api-device-request-parser"

describe("apiDeviceRequestParser", () => {
const request: ApiDeviceRequest = {
rid: 1,
endpoint: "API_CONFIGURATION",
method: "GET",
}

it("returns a proper starting with #", () => {
const result = apiDeviceRequestParser(request)
expect(result[0]).toBe("#")
})

it("properly calculates the length of the payload", () => {
const result = apiDeviceRequestParser(request)
expect(result.slice(1, 10)).toBe("000000055")
})

it("properly attaches the payload", () => {
const result = apiDeviceRequestParser(request)
expect(result.slice(10)).toBe(JSON.stringify(request))
})
})
Loading

0 comments on commit 06bebb8

Please sign in to comment.