Skip to content

Commit

Permalink
Merge pull request #76 from Jalle19/recommended-type-checked
Browse files Browse the repository at this point in the history
Switch to the recommended-type-checked linter preset
  • Loading branch information
Jalle19 authored Sep 2, 2024
2 parents 25808f8 + 6f6bbae commit 24e41fc
Show file tree
Hide file tree
Showing 14 changed files with 46 additions and 26 deletions.
9 changes: 7 additions & 2 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const compat = new FlatCompat({
});

export default [
...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended"),
...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended-type-checked"),
{
plugins: {
"@typescript-eslint": typescriptEslint,
Expand All @@ -25,14 +25,19 @@ export default [
globals: {
...globals.node,
},

parser: tsParser,
parserOptions: {
project: "./tsconfig.json"
},
ecmaVersion: 2021,
sourceType: "module",
},

rules: {
"no-console": "error",
// We have type-hinted functions that in their dummy implementations return static data
"@typescript-eslint/require-await": "off",
"@typescript-eslint/return-await": "error"
},
},
];
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@influxdata/influxdb-client": "^1.33.2",
"modbus-serial": "^8.0.16",
"mqtt": "^5.1.2",
"set-interval-async": "^3.0.3",
"slugify": "^1.6.6",
"winston": "^3.11.0",
"ws": "^8.17.1",
Expand Down
2 changes: 1 addition & 1 deletion src/characteristics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ export const pollCharacteristicsSensors = async (
promises.push(sensor.pollFunc(timestamp, c))
}

return await Promise.all(promises)
return Promise.all(promises)
}
2 changes: 1 addition & 1 deletion src/circuit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ export const pollPowerSensors = async (
promises.push(sensor.pollFunc(timestamp, circuit, existingSensorData))
}

return await Promise.all(promises)
return Promise.all(promises)
}
2 changes: 1 addition & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export const resolveAndValidateConfig = (config: Config): Config => {
circuit.sensor.pollFunc = getDummySensorData
break
default:
throw new Error(`Unrecognized sensor type ${circuit.sensor.type}`)
throw new Error(`Unrecognized sensor type ${circuit.sensor.type as string}`)
}
}

Expand Down
9 changes: 5 additions & 4 deletions src/eachwatt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { createLogger, LogLevel, setLogLevel } from './logger'
import { setRequestTimeout as setHttpRequestTimeout } from './http/client'
import { setRequestTimeout as setModbusRequestTimeout } from './modbus/client'
import { applyFilters } from './filter/filter'
import { setIntervalAsync } from 'set-interval-async'

// Set up a signal handler, so we can exit on Ctrl + C when run from Docker
process.on('SIGINT', () => {
Expand Down Expand Up @@ -95,7 +96,7 @@ const mainPollerFunc = async (config: Config) => {
}
}

;(async () => {
void (async () => {
const configFile = argv.config as string
if (!fs.existsSync(configFile)) {
logger.error(`Configuration ${configFile} file does not exist or is not readable`)
Expand All @@ -120,13 +121,13 @@ const mainPollerFunc = async (config: Config) => {
})

// Adjust request timeouts to be half that of the polling interval
const pollingInterval = config.settings.pollingInterval
const pollingInterval = config.settings.pollingInterval as number
logger.info(`Polling sensors with interval ${pollingInterval} milliseconds`)
const timeoutMs = (pollingInterval as number) / 2
const timeoutMs = pollingInterval / 2
setHttpRequestTimeout(timeoutMs)
setModbusRequestTimeout(timeoutMs)

// Start polling sensors
await mainPollerFunc(config)
setInterval(mainPollerFunc, pollingInterval, config)
setIntervalAsync(mainPollerFunc, pollingInterval, config)
})()
4 changes: 2 additions & 2 deletions src/http/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const logger = createLogger('http')

let requestTimeout = 0
let lastTimestamp = 0
const promiseCache = new Map()
const promiseCache = new Map<string, Promise<Response>>()

const createRequestParams = (): RequestInit => {
return {
Expand All @@ -30,7 +30,7 @@ export const getDedupedResponse = async (timestamp: number, url: string): Promis
const key = `${timestamp}_${url}`

if (promiseCache.has(key)) {
return promiseCache.get(key)
return promiseCache.get(key)!
}

const request = new Request(url, createRequestParams())
Expand Down
7 changes: 5 additions & 2 deletions src/http/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const mimeTypes = new Map<string, string>([
['.png', 'image/png'],
])

export const httpRequestHandler: RequestListener = async (req: IncomingMessage, res: ServerResponse) => {
export const httpRequestHandler: RequestListener = (req: IncomingMessage, res: ServerResponse) => {
const filePath = resolveFilePath(req.url)

// Serve 404 if file doesn't exist
Expand All @@ -28,7 +28,10 @@ export const httpRequestHandler: RequestListener = async (req: IncomingMessage,
const extension = path.extname(filePath).toLowerCase()
const mimeType = mimeTypes.get(extension)

await serveStaticFile(filePath, mimeType, res)
// RequestListener returns void so we must wrap awaits
void (async () => {
await serveStaticFile(filePath, mimeType, res)
})()
}

const resolveFilePath = (reqUrl: string | undefined): string => {
Expand Down
4 changes: 2 additions & 2 deletions src/modbus/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ export const parseRegisterDefinition = (definition: string): ModbusRegister => {
}

if (!isValidDataType(dataType)) {
throw new Error(`Invalid data type specified: ${dataType}`)
throw new Error(`Invalid data type specified: ${dataType as string}`)
}

return {
registerType: registerType as RegisterType,
registerType,
address: parsedAddress,
dataType,
}
Expand Down
4 changes: 2 additions & 2 deletions src/publisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ export enum PublisherType {
}

export interface PublisherImpl {
publishSensorData: (sensorData: PowerSensorData[]) => void
publishCharacteristicsSensorData: (sensorData: CharacteristicsSensorData[]) => void
publishSensorData: (sensorData: PowerSensorData[]) => Promise<void>
publishCharacteristicsSensorData: (sensorData: CharacteristicsSensorData[]) => Promise<void>
}

export interface Publisher {
Expand Down
4 changes: 2 additions & 2 deletions src/publisher/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ export interface ConsolePublisher extends Publisher {
const logger = createLogger('publisher.console')

export class ConsolePublisherImpl implements PublisherImpl {
publishSensorData(sensorData: PowerSensorData[]): void {
async publishSensorData(sensorData: PowerSensorData[]): Promise<void> {
for (const data of sensorData) {
logger.info(`${data.circuit.name}: ${data.power}W`)
}
}

publishCharacteristicsSensorData(sensorData: CharacteristicsSensorData[]): void {
async publishCharacteristicsSensorData(sensorData: CharacteristicsSensorData[]): Promise<void> {
for (const data of sensorData) {
logger.info(`${data.characteristics.name}: ${data.voltage}V, ${data.frequency}Hz`)
}
Expand Down
6 changes: 3 additions & 3 deletions src/publisher/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class WebSocketPublisherImpl implements PublisherImpl {
// Reuse the HTTP server given to us
this.wss = new WebSocketServer({ server: httpServer })

// Keep track of the last published sensor data so we can deliver it immediately (if available) to newly connected
// Keep track of the last published sensor data, so we can deliver it immediately (if available) to newly connected
// clients
this.lastPublishedSensorData = {
characteristicsSensorData: null,
Expand Down Expand Up @@ -62,7 +62,7 @@ export class WebSocketPublisherImpl implements PublisherImpl {
})
}

publishCharacteristicsSensorData(sensorData: CharacteristicsSensorData[]): void {
async publishCharacteristicsSensorData(sensorData: CharacteristicsSensorData[]): Promise<void> {
this.broadcastMessage({
type: 'characteristicsSensorData',
data: sensorData,
Expand All @@ -71,7 +71,7 @@ export class WebSocketPublisherImpl implements PublisherImpl {
this.lastPublishedSensorData.characteristicsSensorData = sensorData
}

publishSensorData(sensorData: PowerSensorData[]): void {
async publishSensorData(sensorData: PowerSensorData[]): Promise<void> {
// Remove circular references so we can encode as JSON
sensorData = untangleCircularDeps(sensorData)

Expand Down
8 changes: 4 additions & 4 deletions src/sensor/modbus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ const readRegisters = async (

switch (register.registerType) {
case RegisterType.HOLDING_REGISTER:
return await client.readHoldingRegisters(address, length)
return client.readHoldingRegisters(address, length)
case RegisterType.INPUT_REGISTER:
return await client.readInputRegisters(address, length)
return client.readInputRegisters(address, length)
case RegisterType.COIL:
return await client.readCoils(address, length)
return client.readCoils(address, length)
case RegisterType.DISCRETE_INPUT:
return await client.readDiscreteInputs(address, length)
return client.readDiscreteInputs(address, length)
}
}

Expand Down

0 comments on commit 24e41fc

Please sign in to comment.