Kvaser CanKing Service Extensions SDK
============================================================================================================================

Introduction
----------------------------------------------------------------------------------------------------------------------------

The purpose with the projects in this folder is to help developers to create service extensions for the Kvaser CanKing bus
analysis tool.

Kvaser CanKing is a free of charge, general-purpose CAN and LIN bus analysis software that is compatible with all Kvaser
CAN/LIN interfaces and the Kvaser virtual CAN bus. It's available on Windows (x64) and Linux (x64 and ARM).

There are a lot of functionality already included in the base version of CanKing, but it is also possible to extend the
functionality by creating extensions.

This folder includes examples of CanKing service extensions. Extensions can be written in any programming language given
that they can be made into wasm components.


Directories
----------------------------------------------------------------------------------------------------------------------------

- examples: Includes examples of service extensions (wasm components) created using different programming languages.
- wit:      Includes the canking_extensions.wit file that defines the interface between the host and the wasm components.
            This is the contract between CanKing and the service extension. It defines what functions a service extension
            must implement and what functions CanKing implements that can be called from the service extension.


Information About Wasm Components
----------------------------------------------------------------------------------------------------------------------------

In the component model, the type definitions are written in a language called WIT (Wasm Interface Type), and the way they
translate into bits and bytes is called the Canonical ABI (Application Binary Interface). A Wasm component is thus a wrapper
around a core module that specifies its imports and exports using such Interfaces.

The agreement of an interface adds a new dimension to Wasm portability. Not only are components portable across
architectures and operating systems, but they are now portable across languages. A Go component can communicate directly and
safely with a C or Rust component. It need not even know which language another component was written in - it needs only the
component interface, expressed in WIT. Additionally, components can be linked into larger graphs, with one component's
exports satisfying another's imports.

- Logically,    components are containers for modules - or other components - which express their interfaces and dependencies
                via WIT.
- Conceptually, components are self-describing units of code that interact only through interfaces instead of shared memory.
- Physically,   a component is a specially-formatted WebAssembly file. Internally, the component could include multiple
                traditional ("core") WebAssembly modules, and sub-components, composed via their imports and exports.

The external interface of a component - its imports and exports - corresponds to a world. The component, however, internally
defines how that world is implemented.


Create CanKing Service Extension in C#
----------------------------------------------------------------------------------------------------------------------------

This guide has been created with help of this web page: https://component-model.bytecodealliance.org/language-support/csharp.html

First, install the .NET 10 SDK.
Once you have the .NET SDK installed, create a new project:

    dotnet new classlib -o ck-service-extension
    cd ck-service-extension

The componentize-dotnet package depends on the NativeAOT-LLVM package, which resides at the dotnet-experimental package source,
so you will need to make sure that NuGet is configured to refer to experimental packages. You can create a project-scoped NuGet
configuration by running:

    dotnet new nugetconfig

Edit your nuget.config file to look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <packageSources>
        <!--To inherit the global NuGet package sources remove the <clear/> line below -->
        <clear />
        <add key="dotnet-experimental" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json" />
        <add key="nuget" value="https://api.nuget.org/v3/index.json" />
      </packageSources>
    </configuration>

Now back in the console we'll add the BytecodeAlliance.Componentize.DotNet.Wasm.SDK package:

    dotnet add package BytecodeAlliance.Componentize.DotNet.Wasm.SDK --prerelease

If you're developing on Windows then you'll also need the runtime.win-x64.microsoft.dotnet.ilcompiler.llvm package:

    dotnet add package runtime.win-x64.microsoft.dotnet.ilcompiler.llvm --prerelease

On Linux you need the runtime.linux-x64.microsoft.dotnet.ilcompiler.llvm package instead:

    dotnet add package runtime.linux-x64.microsoft.dotnet.ilcompiler.llvm --prerelease

In the .csproj project file, add the following to the <PropertyGroup>:

    <RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>
    <UseAppHost>false</UseAppHost>
    <PublishTrimmed>true</PublishTrimmed>
    <InvariantGlobalization>true</InvariantGlobalization>
    <SelfContained>true</SelfContained>

Now you should copy the canking_extensions.wit file to your project. In the .csproj project file, add a new <ItemGroup>:

    <ItemGroup>
      <Wit Update="canking_extensions.wit" World="extension" />
    </ItemGroup>

If you try to build the project with dotnet build, you'll get an error like "The name 'ExtensionWorldImpl' does not exist in the current context".
This is because you've said you'll provide an implementation, but haven't yet done so. To fix this, rename the Class1.cs file to MyServiceExtension.cs
and replace its contents with this code:

    using ExtensionWorld.wit.imports.canking.extensions;
    namespace ExtensionWorld;
    public class ExtensionWorldImpl: IExtensionWorld {

        public static string DisplayName() => "My Service Extension";
        public static string Description() => "A CanKing service extension";
        public static string Version() => "1.0.0";
        public static string Author() => "";
        public static ITypes.ExtensionType ExtensionType() => ITypes.ExtensionType.DATA_PROCESSOR;
        public static string DefaultConfig() => "{}";

        public static ITypes.Filter RxFilter() => ITypes.Filter.PassAll();
        public static ITypes.Filter TxFilter() => ITypes.Filter.BlockAll();
        public static bool PassErrorFrames() => false;
        public static List<string> SignalsFilter() => [];

        public static void OnStartMeasurement(string config)
        {
            CankingInterop.Log("Received start measurement in dotnet component", ITypes.LogSeverity.DEBUG);
        }

        public static void OnStopMeasurement() {}

        public static ITypes.ProcessResult? OnRxFrame(ITypes.Frame frame)
        {
            CankingInterop.Log("Received frame in dotnet component", ITypes.LogSeverity.DEBUG);
            return null;
        }

        public static ITypes.ProcessResult? OnTxFrame(ITypes.Frame frame) => null;

        public static ITypes.ProcessResult? OnErrorFrame(ITypes.Frame frame) => null;

        public static void OnSignalValue(string name, string unit, double time, double value) { }
    }

If we build it:

    dotnet build

The component will be available at bin/Debug/net10.0/wasi-wasm/native/ck-service-extension.wasm.


Install a CanKing Service Extension
----------------------------------------------------------------------------------------------------------------------------

A CanKing service extension can be installed using the CanKing Application. Select the 'More'->'Extensions'->'Install...'
menu item from the window title bar. Browse and select the ck-service-extension.wasm.

To add your extension to a measurement setup you need to click on one of the '+'-buttons on one of the present nodes in the
measurement setup view and select Extension from the drop down menu.

Your extension should be present in the Extension config dialog. Select your extension and edit any configuration for it.


Useful Links
----------------------------------------------------------------------------------------------------------------------------

- wasm components - https://component-model.bytecodealliance.org/design/why-component-model.html
- building wasm components (C#)
  - https://component-model.bytecodealliance.org/language-support/csharp.html
  - https://github.com/bytecodealliance/componentize-dotnet
- building wasm components (JavaScript)
  - https://component-model.bytecodealliance.org/language-support/javascript.html
  - https://github.com/bytecodealliance/ComponentizeJS
- building wasm components (Python)
  - https://component-model.bytecodealliance.org/language-support/python.html
  - https://github.com/bytecodealliance/componentize-py
