Initial commit

This commit is contained in:
Jasper Blanckenburg 2024-05-28 23:08:28 +02:00
commit 40fc719fec
26 changed files with 5375 additions and 0 deletions

13
.eslintignore Normal file
View File

@ -0,0 +1,13 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

31
.eslintrc.cjs Normal file
View File

@ -0,0 +1,31 @@
/** @type { import("eslint").Linter.Config } */
module.exports = {
root: true,
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'prettier'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 2020,
extraFileExtensions: ['.svelte']
},
env: {
browser: true,
es2017: true,
node: true
},
overrides: [
{
files: ['*.svelte'],
parser: 'svelte-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser'
}
}
]
};

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock

8
.prettierrc Normal file
View File

@ -0,0 +1,8 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

38
package.json Normal file
View File

@ -0,0 +1,38 @@
{
"name": "charger-display-svelte",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@types/eslint": "^8.56.0",
"@types/node": "^20.12.12",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.35.1",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"svelte": "^4.2.7",
"svelte-check": "^3.6.0",
"sveltekit-sse": "^0.13.0",
"tslib": "^2.4.1",
"typescript": "^5.0.0",
"vite": "^5.0.3"
},
"type": "module",
"dependencies": {
"socketcan": "^4.0.4"
}
}

2989
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

12
src/app.css Normal file
View File

@ -0,0 +1,12 @@
div.status-table {
border: 1px solid black;
border-radius: 5px;
padding: 5px;
display: grid;
grid-template-columns: fit-content(30%) 1fr;
gap: 1em;
}
div.status-table *:nth-child(2n + 1) {
font-weight: bold;
}

13
src/app.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
src/app.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

2
src/lib/defs.ts Normal file
View File

@ -0,0 +1,2 @@
export const N_CELLS_PER_SLAVE = 15;
export const N_TEMP_SENSORS_PER_SLAVE = 32;

1
src/lib/index.ts Normal file
View File

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

70
src/lib/messages.ts Normal file
View File

@ -0,0 +1,70 @@
export interface AMSMessage {
type: 'error' | 'status' | 'slaveStatus' | 'slaveLog';
}
export interface AMSError extends AMSMessage {
type: 'error';
kind: number;
arg: number;
}
export enum AMSState {
TS_INACTIVE = 0,
TS_ACTIVE = 1,
TS_PRECHARGE = 2,
TS_DISCHARGE = 3,
TS_ERROR = 4
}
export interface AMSStatus extends AMSMessage {
type: 'status';
state: AMSState;
sdcClosed: boolean;
soc: number;
minCellVolt: number;
maxCellTemp: number;
imdOK: boolean;
// TODO: IMD state & R_iso
}
export interface SlaveStatus extends AMSMessage {
type: 'slaveStatus';
slaveId: number;
error: boolean;
minCellVolt: number;
maxCellVolt: number;
maxTemp: number;
soc: number;
}
export interface SlaveLog extends AMSMessage {
type: 'slaveLog';
slaveId: number;
logType: 'voltage' | 'lastCell' | 'temperature';
}
export interface SlaveLogVoltage extends SlaveLog {
logType: 'voltage';
startIndex: number;
voltages: [number, number, number, number];
}
export interface SlaveLogLastCell extends SlaveLog {
logType: 'lastCell';
voltage: number;
failed_temp_sensors: number;
}
export interface SlaveLogTemperature extends SlaveLog {
logType: 'temperature';
startIndex: number;
temperatures: [number, number, number, number, number, number, number, number];
}

48
src/lib/slave-log.ts Normal file
View File

@ -0,0 +1,48 @@
import { N_CELLS_PER_SLAVE, N_TEMP_SENSORS_PER_SLAVE } from './defs';
import type { SlaveLog, SlaveLogLastCell, SlaveLogTemperature, SlaveLogVoltage } from './messages';
export class SlaveLogData {
voltages: number[];
temperatures: number[];
failedTempSensors: number;
constructor() {
this.voltages = [];
for (let i = 0; i < N_CELLS_PER_SLAVE; i++) {
this.voltages.push(0);
}
this.temperatures = [];
for (let i = 0; i < N_TEMP_SENSORS_PER_SLAVE; i++) {
this.temperatures.push(0);
}
this.failedTempSensors = 0;
}
handleMsg(msg: SlaveLog) {
switch (msg.logType) {
case 'voltage': {
const voltMsg = msg as SlaveLogVoltage;
for (let i = 0; i < 4; i++) {
this.voltages[voltMsg.startIndex + i] = voltMsg.voltages[i];
}
break;
}
case 'lastCell': {
const lastMsg = msg as SlaveLogLastCell;
this.voltages[this.voltages.length - 1] = lastMsg.voltage;
this.failedTempSensors = lastMsg.failed_temp_sensors;
break;
}
case 'temperature': {
const tempMsg = msg as SlaveLogTemperature;
for (let i = 0; i < 8; i++) {
this.temperatures[tempMsg.startIndex + i] = tempMsg.temperatures[i];
}
break;
}
default: {
console.error('Unknwon slave log type', msg.logType);
}
}
}
}

59
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,59 @@
<script lang="ts">
import type { AMSError, AMSMessage, AMSStatus, SlaveLog, SlaveStatus } from '$lib/messages';
import { source } from 'sveltekit-sse';
import MasterStatusDisplay from './master-status-display.svelte';
import SlaveStatusDisplay from './slave-status-display.svelte';
import '../app.css';
import MasterErrorDisplay from './master-error-display.svelte';
import { SlaveLogData } from '$lib/slave-log';
// const value = source('/data').select('message');
let error: AMSError | undefined;
let amsStatus: AMSStatus | undefined;
let slaveStatus: Record<number, SlaveStatus> = {};
let slaveLog: Record<number, SlaveLogData> = {};
function handleSlaveLog(msg: SlaveLog) {
if (!(msg.slaveId in slaveLog)) {
slaveLog[msg.slaveId] = new SlaveLogData();
}
const slave = slaveLog[msg.slaveId];
slave.handleMsg(msg);
}
source('/data')
.select('message')
.subscribe((value) => {
if (!value) {
return;
}
const msg = JSON.parse(value) as AMSMessage;
switch (msg.type) {
case 'error':
error = msg as AMSError;
break;
case 'status':
amsStatus = msg as AMSStatus;
break;
case 'slaveStatus': {
const status = msg as SlaveStatus;
slaveStatus[status.slaveId] = status;
break;
}
case 'slaveLog':
handleSlaveLog(msg as SlaveLog);
break;
}
});
</script>
<h1>FaSTTUBe Charger</h1>
<MasterErrorDisplay {error} />
<MasterStatusDisplay status={amsStatus} />
<div class="slaves">
{#each Object.entries(slaveStatus) as [id, status]}
<SlaveStatusDisplay {id} {status} logData={slaveLog[id]} />
{/each}
</div>

179
src/routes/data/+server.ts Normal file
View File

@ -0,0 +1,179 @@
import { produce } from 'sveltekit-sse';
import * as can from 'socketcan';
import type {
AMSError,
AMSMessage,
AMSStatus,
SlaveLog,
SlaveLogLastCell,
SlaveLogTemperature,
SlaveLogVoltage,
SlaveStatus
} from '$lib/messages';
import { N_CELLS_PER_SLAVE, N_TEMP_SENSORS_PER_SLAVE } from '$lib/defs';
const CAN_ID_AMS_ERROR = 0x00c;
const CAN_ID_AMS_STATUS = 0x00a;
const CAN_ID_AMS_SLAVE_STATUS_BASE = 0x080;
const CAN_ID_AMS_SLAVE_STATUS_MASK = 0xff0;
const CAN_ID_AMS_SLAVE_LOG_BASE = 0x600;
const CAN_ID_AMS_SLAVE_LOG_MASK = 0xf00;
type RawMessage = {
ext?: boolean;
canfd?: boolean;
id: number;
data: Buffer;
};
function decodeError(msg: RawMessage): AMSError | null {
if (msg.data.length != 2) {
console.warn('invalid error frame', msg);
return null;
}
console.log('error', msg);
const data = msg.data;
return {
type: 'error',
kind: data[0],
arg: data[1]
};
}
function decodeStatus(msg: RawMessage): AMSStatus | null {
if (msg.data.length != 8) {
console.warn('invalid status frame', msg);
return null;
}
const data = msg.data;
return {
type: 'status',
state: data[0] & 0x7f,
sdcClosed: !!(data[0] & 0x80),
soc: data[1],
minCellVolt: data.readUInt16BE(2) * 1e-3,
maxCellTemp: data.readUInt16BE(4) * 0.0625,
imdOK: !!(data[6] & 0x80)
};
}
function decodeSlaveStatus(msg: RawMessage): SlaveStatus | null {
if (msg.data.length != 8) {
console.warn('invalid slave status frame', msg);
return null;
}
const data = msg.data;
return {
type: 'slaveStatus',
slaveId: data[0] & 0x7f,
error: !!(data[0] & 0x80),
soc: data[1],
minCellVolt: data.readUInt16BE(2) * 1e-3,
maxCellVolt: data.readUInt16BE(4) * 1e-3,
maxTemp: data.readUInt16BE(6) * 0.0625
};
}
function decodeSlaveLog(msg: RawMessage): SlaveLog | null {
if (msg.data.length != 8) {
console.warn('invalid slave log frame', msg);
return null;
}
const slaveId = (msg.id & 0xf0) >> 4;
const logIndex = msg.id & 0x00f;
const data = msg.data;
if (logIndex < N_CELLS_PER_SLAVE / 4) {
const startIndex = logIndex * 4;
const voltages = [];
for (let i = 0; i < 4; i++) {
voltages.push(data.readUInt16BE(2 * i) * 1e-3);
}
const msg: SlaveLogVoltage = {
type: 'slaveLog',
slaveId,
logType: 'voltage',
startIndex,
voltages: voltages as [number, number, number, number]
};
return msg;
} else if (logIndex == N_CELLS_PER_SLAVE / 4) {
const msg: SlaveLogLastCell = {
type: 'slaveLog',
slaveId,
logType: 'lastCell',
voltage: data.readUInt16BE(0) * 1e-3,
failed_temp_sensors: data.readInt32BE(2)
};
return msg;
} else if (logIndex < N_CELLS_PER_SLAVE / 4 + 1 + N_TEMP_SENSORS_PER_SLAVE / 8) {
const temperatures = [];
for (let i = 0; i < 8; i++) {
temperatures.push(data.readInt8(i) * 1);
}
const msg: SlaveLogTemperature = {
type: 'slaveLog',
slaveId,
logType: 'temperature',
startIndex: (logIndex - N_CELLS_PER_SLAVE / 4 - 1) * 8,
temperatures: temperatures as [number, number, number, number, number, number, number, number]
};
return msg;
} else {
console.warn('Unknown slave log index', msg.id);
return null;
}
}
export function POST() {
return produce(async function start({ emit }) {
const network = can.createRawChannel('can0');
network.setRxFilters([
{ id: CAN_ID_AMS_ERROR, mask: 0xfff },
{ id: CAN_ID_AMS_STATUS, mask: 0xfff },
{ id: CAN_ID_AMS_SLAVE_STATUS_BASE, mask: CAN_ID_AMS_SLAVE_STATUS_MASK },
{ id: CAN_ID_AMS_SLAVE_LOG_BASE, mask: CAN_ID_AMS_SLAVE_LOG_MASK }
]);
network.addListener('onMessage', (msg: RawMessage) => {
if (msg.ext || msg.canfd) {
console.warn('invalid frame', msg);
return;
}
let message: AMSMessage | null = null;
if ((msg.id & CAN_ID_AMS_SLAVE_STATUS_MASK) == CAN_ID_AMS_SLAVE_STATUS_BASE) {
message = decodeSlaveStatus(msg);
} else if ((msg.id & CAN_ID_AMS_SLAVE_LOG_MASK) == CAN_ID_AMS_SLAVE_LOG_BASE) {
message = decodeSlaveLog(msg);
} else {
switch (msg.id) {
case CAN_ID_AMS_ERROR:
message = decodeError(msg);
break;
case CAN_ID_AMS_STATUS:
message = decodeStatus(msg);
break;
default:
console.warn('unknown frame', msg);
}
}
if (message) {
emit('message', JSON.stringify(message));
}
});
network.start();
return function stop() {
network.stop();
};
});
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
<script lang="ts">
import type { AMSError } from '$lib/messages';
export let error: AMSError | undefined;
</script>
{#if error}
<dialog class="error">
<h1>AMS Error</h1>
<div class="status-table">
<div>Error kind</div>
<div>{error.kind}</div>
<div>Error argument</div>
<div>{error.arg}</div>
</div>
</dialog>
{/if}

View File

@ -0,0 +1,21 @@
<script lang="ts">
import type { AMSStatus } from '$lib/messages';
export let status: AMSStatus | undefined;
</script>
{#if status}
<h2>Master Status</h2>
<div class="status-table">
<div>State:</div>
<div>{status.state}</div>
<div>SDC Closed:</div>
<div>{status.sdcClosed}</div>
<div>SoC:</div>
<div>{status.soc}</div>
<div>Min. cell voltage:</div>
<div>{status.minCellVolt}</div>
<div>Max. cell temperature:</div>
<div>{status.maxCellTemp}</div>
</div>
{/if}

View File

@ -0,0 +1,40 @@
<script lang="ts">
import type { SlaveStatus } from '$lib/messages';
import type { SlaveLogData } from '$lib/slave-log';
export let id: number;
export let status: SlaveStatus;
export let logData: SlaveLogData | undefined;
</script>
<h2>Slave #{id}</h2>
<div class="status-table">
<div>Error</div>
<div>{status.error}</div>
<div>Min. cell voltage</div>
<div>{status.minCellVolt}</div>
<div>Max. cell voltage</div>
<div>{status.maxCellVolt}</div>
<div>Max. temperature</div>
<div>{status.maxTemp}</div>
<div>SoC</div>
<div>{status.soc}</div>
<div>Failed temperature sensors</div>
<div>{logData?.failedTempSensors ?? 0}</div>
</div>
{#if logData}
<details>
<div class="status-table">
{#each logData.voltages as volt, i}
<div>V_{i}</div>
<div>{volt}</div>
{/each}
{#each logData.temperatures as temp, i}
<div>T_{i}</div>
<div>{temp}</div>
{/each}
</div>
</details>
{/if}

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

6
vite.config.ts Normal file
View File

@ -0,0 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
});