Building Xedge Standalone with BAS

This document explains how to build and integrate the standalone Xedge firmware application with the Barracuda App Server (BAS) C library. Xedge is included under the BAS examples tree because it demonstrates a complete BAS-based firmware integration, but it is more than a small example application.

Use this page when you are compiling or porting Xedge. Use Using Xedge when you want to learn the IDE, applications, configuration, deployment, and APIs. For the product overview and design philosophy, see the online Xedge product page.

Build Guide Roadmap

TaskWhere to Start
Evaluate Xedge on supported hardwareUse one of the ready-to-use RTOS projects below.
Compile a desktop test buildUse the host build approach described in the build notes and videos linked below.
Use a PSA Crypto providerFollow Building Xedge with PSA Crypto for native settings, startup, and resource selection.
Integrate Xedge into your own RTOS firmwareInclude the required C files, provide the integration hooks below, and start barracuda() in a suitable thread.
Expose product-specific hardware or C services to LuaAdd Lua bindings and implement the required Xedge integration hooks in your binding module.
Create a production firmware imageUse the release build section after the basic build is running.
The Xedge Embedded Web Server

Figure 1: Xedge components

The Xedge Lua application embedded in the executable can be viewed as Lua firmware. It is packaged as a compressed ZIP file, converted to C, linked into the executable, and mounted through ZipIo so the Lua VM can access it as its required vmio.

The following tutorials provide useful background before you design Lua bindings or decide how much application logic belongs in Lua versus C:

Compiling Xedge

This section gives the generic build requirements. If you are evaluating Xedge on supported hardware, start with one of the ready-to-use RTOS projects:

Build Process

How to Compile the Xedge C Code

Figure 2: Xedge build process

Although Xedge is primarily designed to be embedded in firmware, the same C code can also be compiled and tested as a standalone process on Windows and Linux. The Embedded Web Server vs. Embedded App Server video demonstrates this host-build workflow.

Files to Include

FileRequiredPurpose
amalgamation/BAS.cYesThe Barracuda App Server C library.
examples/xedge/src/xedge.cYesXedge startup and server integration code.
examples/xedge/obj/XedgeZip.cYesThe generated C array containing Xedge.zip, including the Xedge Lua engine and web UI.
xrc/DiskIo/[platform]/BaFile.cOptionalFile system plugin for targets with a supported persistent file system.
Your Lua binding C filesUsuallyProduct-specific glue code that lets Lua call your hardware drivers or C services.
examples/xedge/src/led.cExampleSimple Lua binding example based on the Lua binding tutorial.
examples/xedge/src/AsynchLua.cExampleShows the asynchronous C-to-Lua API used for sending real-time events from C code to Lua.

Create XedgeZip.c by running Xedge.cmd on Windows or Xedge.sh on Linux. See the BAS-Resources build directory for details. The generated file is a C array containing the zipped Xedge resources. The Xedge C startup code mounts this ZIP as a ZipIo and uses it as the Lua VM's vmio. Inspecting the generated ZIP is useful because it shows exactly which Lua and web resources are embedded in the firmware.

In addition to including the above files in your IDE/Makefile, add the required include path and #define directives as required by your platform. See the readme file builds/[platform]/readme.txt for details.

The file system plugin xrc/DiskIo/[platform]/BaFile.c is optional. Include it when the target has a file system and BAS provides a matching DiskIo port. Define XEDGE_ENABLE_DISK_IO=0 in your IDE or Makefile when the target does not use a local file system. See the DiskIo documentation for details.

Required functions and C code

The Xedge C code in examples/xedge/src/xedge.c calls the following application-supplied functions:

FunctionPurpose
int xedgeInitPsa(void);Required only with SHARKSSL_PSA_CONSUMER=1. Initializes the PSA provider before cryptographic use, resource verification, and Lua creation. Return 0 on success or a nonzero error to stop startup. See the PSA build steps.
int xedgeInitDiskIo(DiskIo* dio);Initializes or customizes the DiskIo configuration. See the example code in led.c.
int xedgeOpenAUX(XedgeOpenAUX* aux);Installs auxiliary services such as Lua bindings, persistent configuration hooks, embedded ZIP applications, or product-specific secrets. See XedgeInitDiskIo.c and led.c.

The disk and auxiliary hooks are typically implemented in your Lua binding module and can usually be left empty during the first device-porting test. The PSA hook must complete provider initialization whenever PSA is enabled. The xedgeOpenAUX() hook is skipped only when you compile with XEDGE_ENABLE_AUX=0; otherwise, provide the function even if it initially does nothing. See examples/xedge/src/xedge.h and the example function xedgeOpenAUX() in led.c for details. The file examples/xedge/src/XedgeInitDiskIo.c shows how to initialize a base path or mount point when the file system requires one.

Starting barracuda()

In an RTOS environment, create a dedicated thread to run barracuda() (Figure 2). It runs until graceful shutdown or a startup failure; the thread must normally have a stack of at least BA_THREAD_STACK_SIZE bytes in most RTOS environments. The startup code should also install an error handler and trace flush callback by calling HttpServer_setErrHnd() and HttpTrace_setFlushCallback(). See HostInit.c for examples.

Operating systems such as VxWorks and INTEGRITY supporting the standard C code entry main() can optionally use the two following C code files instead of creating a dedicated thread as explained above. These generic files are used by all examples included with BAS, not just Xedge. However, note that the stack for main() must be as detailed above.

Build Standalone Xedge with PSA Crypto

Try it on Windows: follow the standalone Xedge PSA quick start to build with the supplied development provider and check key reuse and encrypted configuration after restart.

PSA mode uses your platform's cryptographic provider and key store while keeping the ba.tpm Lua API. First check the provider requirements. The steps below keep encrypted data on its own device and need no manual root provisioning.

Xedge uses the same HKDF hash selection as Mako: SHA-512 by default, or SHA-256 with SHARKSSL_USE_SHA_512=0 (MSBuild property SharkSslUseSha512=0). See Mako's build steps for provider configuration and migration requirements.

Running Xedge inside Mako? Use a PSA-enabled Mako host. Xedge inherits its initialized TPM; these standalone build steps do not apply.

Visual Studio: open VcMake/xedge-psa.vcxproj for the ready-to-build Windows simulator. The SDK includes its provider and PSA resources. Building this project also builds the simulator provider from C source for the selected platform and configuration; no separate provider build is required. For your own provider, set PsaTestSimulator=false, supply the provider properties, and compile your xedgeInitPsa() implementation through PsaSourceFiles. Put your provider's header directory before BAS inc. The steps below describe a target build.

  1. Select PSA in the build. In make/Makefile, keep BA_ENABLE_TPM=1 and enable the optional UNIX PSA block with your provider's paths. Add the device-root definition:

    # Select PSA for both C compilation and the resource builder.
    CFLAGS += $(MFT)SHARKSSL_PSA_CONSUMER=1
    CFLAGS += $(MFT)BA_PSA_GLOBALKEY_USE_DEVICE_ROOT=1
    CFLAGS += $(IFT)/path/to/provider/include
    BA_EXTLIBS += /path/to/provider/lib/libpsacrypto.a
    export SHARKSSL_PSA_CONSUMER=1
    

    Add the provider's system libraries, startup sources, and drivers using BA_EXTLIBS, SOURCE +=, and VPATH. Put its headers before other PSA headers. For an IDE build, apply the definitions to both Xedge and BAS. BAS.c already includes the binding and consumer adapters. For the Windows Makefile build, append provider libraries with VC_FLAGS +=, which is passed to link; BA_EXTLIBS is not used on Windows.

  2. Implement int xedgeInitPsa(void). Add this platform hook to your build. Set up entropy, hardware access, and persistent storage, require psa_crypto_init() to succeed, and return 0 on success or a nonzero error on failure. barracuda() calls it before cryptographic use, resource verification, and Lua creation. Keep the provider open across debugger restarts and make repeated calls safe. See the hook contract for hardware prerequisites and lifetime. Xedge initializes ba.tpm and creates the device root automatically. Do not use xedgeInitDiskIo() or xedgeOpenAUX() for provider initialization; both run too late. To share configuration between devices, omit the device-root definition and provision a shared global root instead.

  3. Rebuild C code and resources together. From examples/xedge/make on Linux:

    # Clean also removes the previously generated embedded resources.
    make plat=posix clean
    make plat=posix io=ezip exe
    

    The Makefile exports the PSA setting to the resource builder. If running BAS-Resources/build/Xedge.cmd or Xedge.sh separately, set environment variable SHARKSSL_PSA_CONSUMER=1 first and embed the new XedgeZip.c. For XEDGE_RESOURCE_DIRECTORY, unpack the matching Xedge.zip there. The supplied Windows PSA project builds its provider and embeds the SDK's PSA resources automatically; see the Windows quick start.

  4. Check it from Lua. Run the signing example as an Xedge application. Restart and confirm that the key and saved configuration still work. Preserve the provider's key store across firmware updates.

PSA initialization errors stop startup. Before switching an existing installation, recover its saved configuration or plan a reset. See configuration portability and How It Works for storage and recovery details.

Enabling Additional Features

BAS.c includes optional features that are not compiled by default. Enable only the features your product or development workflow needs. The following options are relevant to Xedge standalone builds, including RTOS targets.

MacroUse When
BA_ENABLE_LUA_DEBUGGER=1You want Lua debugger support during development. A debugger restart recreates Lua in the same process. Termination without a restart request completes shutdown and returns from barracuda().
BA_ENABLE_EMBEDDED_CA=1Required for every standalone Xedge build, including softTPM and PSA. Apply it when compiling BAS and the Xedge host. Uses the compiled-in CA bundle without retaining a heap copy. See Embedded CA Certificates.
XEDGE_HTTP_CONNECTIONS=16Set the connection capacity shared by HTTP and HTTPS. The integer default is 16. See HTTP and HTTPS Connection Capacity for the range and resource requirements.
BA_DEFLATE_MEM_LEVEL=5Reduces working memory for compression by 112 KiB per active compressor compared with the default value of 8. Consider this setting for devices with small heaps. See Compression Memory.
BA_ENABLE_REVERSE_CONNECTION=1You plan to use the reverse connection bridge in SharkTrustX.
BA_ENABLE_LUA_OPCUA=1You need OPC UA support and your build includes the required OPC UA Lua resources and C module.
BA_ENABLE_REVERSE_PROXY=1You need the Reverse Proxy.
BA_ENABLE_UBJSON=1You need Universal Binary JSON.

Compression Memory

For an embedded build with limited heap memory, define BA_DEFLATE_MEM_LEVEL=5 when compiling BAS, for example with -DBA_DEFLATE_MEM_LEVEL=5. Apply the definition to all BAS compilation units, or to BAS.c when using the amalgamated source. The default remains 8; valid values range from 1 to MAX_MEM_LEVEL, normally 9.

This setting reduces the compressor's working arrays from 256 KiB to 144 KiB. Control structures and input/output buffers need additional memory. It applies to ba.deflate(), compression enabled through response:setresponse(), and the optional file gzip implementation. Savings occur while compression is active; serving an already compressed resource does not allocate a new compressor.

A smaller value can make compression slower and produce larger output, so measure the effect with your device and data. Compression level 6 and the 32 KiB deflate window are unchanged, as is decompression compatibility. Do not reduce MAX_WBITS or MAX_MEM_LEVEL to select this option. Output buffering is unchanged.

Embedded CA Certificates

Define BA_ENABLE_EMBEDDED_CA=1 when compiling both BAS and standalone Xedge. The resource builders omit .certificate/cacert.shark; the default client trust store is the compiled-in array. For devices running code from flash, keep constant data in directly readable flash through the linker configuration. This lets SharkSSL use the CA bundle in inc/cacert.h directly, saving the heap memory otherwise used to load .certificate/cacert.shark into a Lua string.

ba.sharkclient() automatically selects the embedded bundle when the macro is defined. You can also select it explicitly with ba.create.sharkssl("embedded", options). Standalone Xedge rejects builds without the macro. A separately built BAS library must also use the macro. Xedge running inside Mako uses its host's trust configuration. Calling ba.create.sharkssl(nil, options) still creates an object without a CA list.

Regenerate inc/cacert.h using mkEmbeddedCaCert.cmd on Windows or mkEmbeddedCaCert.sh on Linux, then rebuild the firmware when updating the trust bundle. For a smaller or private bundle, run SharkSSLParseCAList your-roots.pem > cacert.h and place that header on the BAS include path. The selected roots determine which issuers the default client trusts; explicit Lua certificate stores remain supported. Distribute the rebuilt executable or firmware together with its matching resources. This option preserves SharkSSL's CA-list and TLS trust validation. See ba.create.sharkssl() for details.

Xedge-Specific Build Reduction and Release Macros

MacroEffect
XEDGE_ENABLE_DISK_IO=0Build without the DiskIo file system plugin. Use this when the target has no local file system or when first testing a minimal embedded port.
XEDGE_ENABLE_AUX=0Do not call xedgeOpenAUX(). Use this only when you do not need product-specific Lua bindings, embedded application hooks, persistent configuration hooks, or additional TPM secrets.
BA_ENABLE_LUA_DEBUG_LIBRARY=0Exclude the Lua debug module. This is recommended for release builds unless a controlled service workflow requires Lua debugging.
BA_ENABLE_SHARKTRUST=0Exclude the built-in SharkTrustX demo portal integration. See Additional Configuration and Security Settings.
BA_ENABLE_SOFTTPM_KEY_MATERIAL=0Exclude the EncryptionKey.h key-derivation support. Automatic certificate management still requires an initialized TPM.

Thread Pool Configuration

By default, the Xedge C code initializes an environment similar to the default configuration of the Mako Server. It creates two thread pools:

  1. An HttpCmdThreadPool instance with 3 threads.
  2. An LThreadMgr instance with 2 threads.

This setup results in a total of 5 threads by default.

For an RTOS, set XEDGE_THREAD_POOL_MODE=XEDGE_THREAD_POOL_SHARED_FIXED to merge the two pools into one shared pool. Set XEDGE_THREAD_COUNT to the required number of threads (default 2). The default mode, XEDGE_THREAD_POOL_SEPARATE, keeps the two pools described above.

Selecting XEDGE_THREAD_POOL_SHARED_FIXED also disables the Lua function ba.thread.create(), preventing the creation of additional threads via Lua scripts.

For detailed information about thread management, refer to the Lua Thread Library documentation and the Thread C code documentation.

HTTP and HTTPS Connection Capacity

Set the integer macro XEDGE_HTTP_CONNECTIONS when compiling the standalone Xedge host to control the pool shared by HTTP and HTTPS, including idle persistent connections. The default is 16; accepted values range from 4 to 65535. For example, add -DXEDGE_HTTP_CONNECTIONS=32 to the compiler definitions used for examples/xedge/src/xedge.c. The default and range checks are defined in examples/xedge/src/XedgeConfig.h. In the Zephyr project, set CONFIG_XEDGE_HTTP_CONNECTIONS; its build files supply the C macro.

createServer() passes the larger of XEDGE_HTTP_CONNECTIONS and the configured HTTP command count plus three to HttpServerConfig::setNoOfHttpConnections(). This preserves the server's minimum capacity for the selected thread-pool configuration. Raising the connection count does not create worker threads or change XEDGE_THREAD_COUNT. The same setting applies to softTPM and PSA builds.

Size the BAS heap, TLS resources, and network stack for the required active connections. Reserve socket capacity for listeners, DNS, outbound clients, and other services. PSA builds also need sufficient provider operation and key slots. This setting controls the HTTP/HTTPS server pool; it does not impose a limit on established WebSocket connections or client-initiated TCP connections, which need their own network resources.

Using a Network File System During Development

Xedge includes NetIo, which is useful during development and especially important on devices compiled with XEDGE_ENABLE_DISK_IO=0. NetIo lets the embedded target access files served by a host computer, so you can edit Lua applications on the host while the target runs them. Start the NetIo file server on the host before booting the embedded device. See the Xedge NetIo tutorial for the host setup.

Xedge's Configuration File

Xedge stores configured applications and their state in an encrypted JSON file. With file system support, this file is stored persistently on the embedded file system. When Xedge is compiled with XEDGE_ENABLE_DISK_IO=0, the configuration is stored in the browser using Web Storage.

Note:

The Lua application(s) startup state differs between a device with and without file system support:

Interfacing with Device Hardware through Lua Bindings

You must set up custom Lua bindings if you want your Lua code to interact with your device's hardware through the embedded system's existing/new C code. These bindings act as bridges, allowing Lua scripts to call C functions that control hardware or perform other low-level tasks.

How to Set Up Lua Bindings

Examples in the Xedge Code Base

The Xedge code base includes two examples to help you get started:

The Xedge32 South Bridge API Example

When integrating Xedge as part of an OEM product, a common approach is to create Lua bindings for existing high-level C functions in your firmware. However, you can take integration a step further by directly interfacing with the microcontroller's hardware.

For example, the ESP32 port, Xedge32, includes a comprehensive south bridge (GPIO) integration, demonstrating how deep hardware-level integration can be achieved, including turning interrupts into real-time events. If you're looking for a reference, the Xedge32 source code and its south bridge API are available on GitHub.

Time

When using a secure TLS client connection, such as HTTPS, or enabling the Automatic Certificate Management feature, the device must either have a clock with the correct time or fetch the time from the Internet using SNTP. The Barracuda App Server relies on the time returned by the platform-dependent function baGetUnixTime() defined in TargConfig.h. This header may also include baSetUnixTime(), which SNTP code can use when updating the time on a device without a clock. When updating the clock using SNTP, send the "sntp" event upon setting the time. See the Events below for details. Example 5 in led.c shows how to send the "sntp" event.

Events

Xedge features an event mechanism via the Lua function xedge.event() that allows simple events to be sent asynchronously from C code to Lua code. The Xedge Lua code includes the following global Lua function, which the C code can call to distribute events throughout the system:

function _XedgeEvent(eventname,...)

Lua code can subscribe to events, and the Lua callbacks are triggered when the C code calls _XedgeEvent. The arguments can be any value, with one exception: Xedge requires the "sntp" event to activate Automatic Certificate Management if the device does not include a clock. To activate the certificate management, the C code must call _XedgeEvent("sntp"); see time above for details.

See Send Events Via The Lua Thread Library for more information on how to call _XedgeEvent from C code.

Additional Configuration and Security Settings

ZipBinPwd.h - Global AES ZIP Password

This optional header file enables setting a global password for all ZIP files loaded by the server. See method io:setpasswd() for details on AES encrypted ZIP files. The header file is included if the code is compiled with the BA_ENABLE_ZIP_PASSWORD macro. The data for this header file is typically created by using binpwd2str.

ZipPublicKey.h - Enforcing Signed ZIP Files

BAS enhances the security of your deployed Lua applications by supporting signed ZIP files, a feature especially valuable for Xedge Multipart Systems. For an overview, refer to the Signed and Encrypted ZIP Files tutorial. To enable this feature, compile Xedge with the BA_ENABLE_ZIP_SIGNATURE macro and update ZipPublicKey.h.

When enforcing signed ZIP files, all ZIPs, both embedded and external, must be signed, including Xedge.zip. This means the XedgeZip.c file generated by running Xedge.cmd or Xedge.sh cannot be used as-is. Instead, follow these steps to sign the ZIP file:

signzip.sh Xedge.zip private_key.pem
bin2c -z getLspZipReader Xedge.zip XedgeZip.c

Keep in mind, this feature prevents unsigned ZIP files from being loaded in production environments, but does not restrict a user with IDE access from creating or modifying non-deployed applications. See Creating a Release Build for how to secure or remove the IDE.

Automatic TLS Certificates

The generated C file tokengen.c includes SharkTrustX settings for the demo portal x.realtimelogic.com. If you're using your own SharkTrustX or SharkCA portal, replace tokengen.c with the version generated by your portal and select the matching mode in the Automatic TLS Certificate settings. To exclude this code, compile with the BA_ENABLE_SHARKTRUST=0 macro. Do not include tokengen.c in your build, as xedge.c includes it as a header file.

SharkCA requires mDNS support: Xedge hides the Use SharkCA option when the host build does not provide ba.createmdns(), with either softTPM or PSA. Include and register the multicast DNS (mDNS) binding as described in the mDNS integration guide; the Xedge startup registration is enabled by BA_ENABLE_MDNS=1 and BA_ENABLE_MDNS_LUA=1.

EncryptionKey.h

The softTPM implementation described below uses EncryptionKey.h for key derivation. The BA_ENABLE_SOFTTPM_KEY_MATERIAL=0 macro excludes this support and is set automatically by the PSA Xedge host. A custom build using Xedge's automatic certificate management must still provide and initialize a TPM implementation.

Trusted Platform Module (TPM)

Xedge uses the TPM API for encrypted configuration and certificate keys. Keep it enabled for automatic TLS certificate management. Standard builds use softTPM; follow the PSA build steps to use a PSA provider. The EncryptionKey.h and device-input settings below apply only to softTPM.

Standalone Xedge generates its default self-signed certificate with a named TPM key. For PSA, retain the provider's key store together with certificates and ACME state; a key name cannot recover an erased private key.

Can I Copy Configuration to Another Device?

With the device-root setting in the PSA build steps above, xcfg.bin works only on its original device. To share it among standalone Xedge devices, leave that setting at 0 and install the same global root on each device. Copying configuration does not copy signing keys. Xedge hosted in Mako always uses device-specific configuration encryption.

Changing roots or switching from softTPM to PSA requires data migration or a configuration reset. The encryption details, backend settings, and provider capacity requirements are in How It Works.

Xedge softTPM details and required configuration:

The src/EncryptionKey.h file contains a binary random number of variable length the product designer (you) set. This number is consistent across all firmware copies and supplemented with additional per-device-specific entropy (DDUI).

Unless the code is compiled with XEDGE_ENABLE_AUX=0, Xedge.c calls xedgeOpenAUX() at startup. This function can add additional secrets for making the pre-master key more secure by calling the provided function pointer addSecret(). See the source code in led.c for how to use this function.

This softTPM implementation needs a stable Device-Derived Unique Identifier (DDUI) for device-bound keys. Supply it through addSecret() as device-specific input. Without it, devices sharing the same product secret generate identical private keys for a given name and options. PSA derives device-specific secrets from its provisioned device root and generates named ECC keys independently inside the provider.

Choose stable device input appropriate to the threat model, such as protected hardware identity data. A CPU serial number or MAC address may distinguish devices, but a public or copyable identifier is not a secret and does not guarantee resistance to cloning. See the softTPM security model.

Suggested release compile time macros:

In addition to NDEBUG, the following settings are recommended to secure the pre-master key in a release build: do not define BA_ENABLE_LUA_DEBUGGER=1, and compile with BA_ENABLE_LUA_DEBUG_LIBRARY=0 to disable the Lua debug API.

Creating a Release Build

This section explains how to assemble the Lua resources and configuration for a production firmware image. The examples assume that xedge.c is used as-is and that product-specific C code is kept in separate files, such as your Lua binding module or the example led.c.

Release Checklist

DecisionTypical Choice
Keep applications outside the firmware or embed them?Use multipart deployment for easier OTA updates. Use a monolithic image when the target has no file system or must be shipped as one firmware image.
Keep the Xedge IDE?Keep it during development. Restrict or remove it in production unless the product intentionally exposes the IDE.
Use signed or encrypted ZIP applications?Use signed ZIP files when deployed applications must be authenticated before loading.
Protect per-device secrets?Configure the selected TPM implementation. For the key-derivation implementation, add a device-derived unique identifier through xedgeOpenAUX().
Enable debug features?Disable BA_ENABLE_LUA_DEBUGGER=1 and compile with BA_ENABLE_LUA_DEBUG_LIBRARY=0 in release builds unless a controlled service workflow requires them.

Monolithic Firmware Release vs. Multipart System

Before exploring the various options, let's distinguish between creating a product with a single component and multiple components. You've worked with multiple components during the development of your Lua application(s) with Xedge. For a release, you can either maintain this multipart system or consolidate everything into a monolithic component that embeds all of your Lua code within the firmware.

Benefits and Drawbacks of a Multipart System

The primary advantage of a multipart system is its efficiency in over-the-air (OTA) upgrades. Since the Barracuda App Server is a mature product, firmware upgrades will likely be infrequent. Most OTA updates will be focused on your applications, and the multipart system ensures these updates are lightweight and fast, making it much faster to update a ZIP file than the larger Xedge firmware.

However, the initial setup of a multipart system involves a multi-step process, including flashing the Xedge firmware and uploading the configuration file and applications. With Xedge32 (the ESP32 port of Xedge), we've simplified this process by enabling the assembly of all components into a single package. This is achieved by pre-populating the embedded file system as part of the firmware installation. For more details, refer to the Xedge32 partition page.

Embedding everything into a monolithic release eliminates the need for a device file system.

Release Build Options

In the following section, we'll explore several release build options. These options are flexible - you can mix and match them to suit your needs. Option 1, including the Xedge IDE in your build, provides the most straightforward option as you do not need to understand any of the details regarding the files that are included in the resource file Xedge.zip (XedgeZip.c). This option is recommended if you include a web interface. If your device does not include a web interface, options 2 and 3 below may be worthwhile.

  1. Use the Default Xedge Resources (recommended):
  2. Use the Xedge Engine with Customized Resources:

    Remove any unused resource files, including the IDE, to compact your build.

  3. Fully Customize the Build:

    Replace the default resources entirely and build XedgeZip.c using exclusively your own files.

Below are examples for each build option:

Option 1: Use the Default Xedge Resources

This option is the recommended method as it is the most straightforward. Assuming you have Xedge already running on your device, start by zipping together all your applications, as explained in the Creating a COTS Product section, which describes how to create a multipart system.

Creating a monolithic build with the application ZIP files and the Xedge configuration file embedded in the firmware requires a few more steps.

Start by converting all deployed applications (ZIP files) to C code using the tool bin2c, e.g.

bin2c -z myapp myapp.zip myapp.c

In the function xedgeOpenAUX, install the ZIP file as follows:

balua_installZIO(aux->L, "myapp", myapp());

See the C code example led.c, which includes an embedded ZIP file and an example showing how to install the ZIP file.

Build your system and download it to the target, or build it for HLOS. Use the Xedge UI to create or modify your Xedge configuration file. In a browser, navigate to the Xedge UI, right-click the NET file system, and select "New app" to open the application dialog. In the Name field, enter "myapp" or the name you used when calling balua_installZIO. In the URL field, enter $. This unique combination tells Xedge to mount the embedded ZIP file. Configure the rest of the fields as required by your application.

When you have everything configured, download the Xedge configuration file xcfg.bin or use the xcfg.bin produced on your host operating system if you performed this step on a HLOS such as Windows or Linux. Convert xcfg.bin to C code as follows:

bin2c -d xedgeCfg xcfg.bin xedgeCfg.h

The next step is to create a driver for the content of this header file. The example led.c explains how to make a read/write driver, but we only need one to read the content.

#include <xedgeCfg.h>

static int loadXedgeCfgFile(lua_State* L)
{
   if (lua_isstring(L, 1)) /* Write */
      lua_pushnil(L); /* Driver is in read only mode */
   else /* Read */
      lua_pushlstring(L, (char*)xedgeCfg, sizeof(xedgeCfg));
   return 1;
}

int xedgeOpenAUX(XedgeOpenAUX* aux)
{
   balua_installZIO(aux->L, "myapp", myapp());
   /* Install Xedge config file driver */
   aux->xedgeCfgFile = loadXedgeCfgFile;
}

Preparing option 2 and 3

To test the two setups discussed below, compile the code for your host platform, such as Windows or Linux, as demonstrated in the App Server vs. Web Server video. However, when compiling, include the compile-time macro -DXEDGE_RESOURCE_DIRECTORY=resources. This directive tells the xedge.c C code not to use the ZIP driver in XedgeZip.c, but instead to load resources from the "resources" directory. In other words, xedge.c will mount and use the "resources" directory on your host computer as the main IO (the VM IO).

Option 2: Use the Xedge Engine with Customized Resources

In this example, we retain the Xedge engine along with all its services and APIs but remove the web-based editor and all resources not used by Xedge. Additionally, we eliminate all modules, such as MQTT, from the resources/test/Xedge/.lua directory. You can reintroduce these components as needed.

Below is the minimum set of files required by the Xedge engine. The engine will throw an exception if any of these files are missing:

|   .config -- Xedge standalone startup code
|
\---.lua
    |   xedge.lua -- The Xedge engine
    |   404.html
    |   EventEmitter.lua
    |   jwt.lua
    |   rwfile.lua
    |   tpm.lua -- Build-selected softTPM or PSA integration
    |   wfs.lua
    |
    \---acme -- Include the shared ACME modules even if not used
    |       _server.lua
    |       _util.lua
    |       dns.lua
    |       engine.lua
    |       http.lua
    |       runtime.lua
    \---XedgePlugins -- Add your Lua files here

Testing the Setup

  1. Compile the Code: Use the instructions provided above.
  2. Create the "resources" Directory: In the directory where your compiled binary resides, create a subdirectory named "resources".
  3. Prepare the Resources Directory: Unzip Xedge.zip in the resource directory and delete all files in this directory except for the files listed above.
  4. Test the Multipart Option: This option functions identically to the Multipart setup in Option 1. However, because an Xedge configuration file is necessary to start your separate application(s), only delete the files once you have used the Xedge IDE to create your configuration file.
  5. Test the Monolithic Option: Add Lua files that must be executed at startup in the XedgePlugins directory (*). You do not need to create a configuration file if all of your code is embedded in the VM IO. However, you need a configuration file if you intend to embed additional ZIP files, as explained in Option 1.

(*) Any file you add to the XedgePlugins directory will be executed by the Xedge engine at startup. From this point, you can start building your application. Add Lua modules you have developed to the parent directory, i.e., to resources/test/Xedge/.lua.

Option 3: Fully Customize the Build

With this approach, you forgo the benefits provided by the Xedge engine, such as the secure vault user database and the TPM integration.

Follow these steps:

  1. Compile the Code: Use the instructions provided above.
  2. Create the "resources" Directory: In the directory where your compiled binary resides, create a subdirectory named "resources".
  3. Create .config: Inside the "resources" directory, create an empty file named .config. This file serves as the main entry point when xedge.c starts the Lua code.
  4. Run the Compiled Code: On the command line, start the compiled code.

At this point, you should encounter the following error: .config error: no start server or onunload. To resolve this, open the .config file in an editor, add the code below, and save the file. Re-run the compiled code, and the error should no longer appear.

local vmio=ba.openio"vm" -- this is currently our "resources" directory

local function start()
   -- Your startup code goes here.
   -- Example code:
   ba.timer(function() trace(ba.datetime"NOW") return true end):set(1000,true,true)
end

local function initialize(x)
   if true == x or nil == x then
      start()
   end
   -- Ignore all other arguments
end

local function onunload()
   -- not used
end

return initialize,onunload -- Send to C code. The C code will then call initialize()

Figure 3: Xedge .config script example

At a minimum, the .config script must have an initialize and on-unload function. Depending on the compile flags, the C code may call the initialize function multiple times. For example, the key material for the pre-master key is inserted into the initialize function. We ignore the parameters in this code and look for two possible start conditions where the provided argument is either true or nil, depending on xedge.c compile-time macros. See the original .config file for details.

The tutorial Rapid Firmware Development provides a good introduction to using option 3 for creating an IoT device.