- Created by Ricky Goldfarb , last modified on Jul 03, 2024
You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 4 Next »
Microprocessor Requirements
The microprocessor and memory requirements are modest. An 8 or 16-bit microcontroller running at a clock speed of 8MHz and having a total of 128kB of program memory and 16kB of SRAM should be able to easily accommodate the CWL.
Program Memory and RAM Estimates
To generate some useful estimates, the CWL was integrated onto a 16-bit MSP430 platform having 128KB of program memory and 16KB of SRAM. The baseline program memory and RAM usage was recorded before library integration. The following table is generally illustrative of the additional memory requirements the CWL imposes.
Configuration | Program Memory (KB) | RAM (KB) |
# 1: Full w/File Transfer and w/Standard Buffers | +20 | +3.0 0.5 of the 3.0 is only used during a file transfer and could be dynamically allocated |
#2: Full w/o File Transfer and w/Standard Buffers | +18 | +2.5 |
#3: Full w/o File Transfer and w/Small Buffers | +17 | +1.5 |
The compiler optimization level was set to high to derive these estimates.
Depending on the application complexity an additional 1-5KB of program memory may be required to complete a controller implementation.
In configuration #1 file transfer is supported and the additional RAM usage is 3.0KB. However, 0.5KB of the 3KB is only used as a temporary buffer during a file transfer from the OKC to the OKE system. This temporary buffer could be dynamically allocated from the heap by the application and freed when the transfer ends. This would put the additional fixed RAM cost of the CWL at 2.5KB.
The CWL does not directly use dynamic memory, so no additional burdens are placed on system heaps. However, some systems may need to increase the stack size of the main loop or task/thread that executes the CWL. Generally, a total stack size between 1-2KB is more than enough. Implementors must account for additional RAM usage if stack size must be increased. As always implementors should exercise their systems and verify that the system stacks have ample safety margin.
Also, the CWL requires a minimum of CW_PORT_MIN_SERIAL_RX_BUFFER_SIZE + CW_PORT_MIN_SERIAL_TX_BUFFER_SIZE bytes of software-based serial receive and transmit buffering, currently a total of 512 bytes. Many systems will already have software receive and transmit buffering that meets this requirement. If not, then implementors must account for the additional RAM usage to implement the required serial buffering.
Taking all these possible factors into account, in a sub-optimal situation the CWL may require up to +25KB of code space, +4KB RAM, and +0.5KB temporary heap usage.
While it is strongly recommended for OKE systems to implement the full CWL including file transfer, we understand that some legacy systems will have extreme memory constraints. For these systems the CWL can be configured to use as little as +17KB program memory and +1.5KB of RAM while still providing OpenKitchen compatibility.
It should be noted that in many instances implementors will be able to remove existing code that interfaces to other management systems, and easily achieve the program memory and RAM savings that completely offset the needs of the CWL.
OS Requirements
There are no minimum OS requirements. It is adaptable to any bare metal, RTOS, or Linux OS environment. The CWL does not directly use dynamic memory and does not directly rely on any OS task synchronization primitives.
Linux Port
The default port of the CWL is for Windows, which can be built and debugged using Visual Studio for implementors who want to experiment before starting their port.
A Linux port of the OKE simulator is available as well. To build the Linux port change directory to _OpenKitchenEquipment_OKE and run the _OpenKitchenEquipment_OKE.sh build script. The oke simulator will be created by the build process. Running the oke simulator is the same as running and using the Windows oke.exe simulator. See the Simulation section later in the document for information on how to run the oke and oke.exe simulators.
Linux versions of the CWM and OKC simulators are not available at this time. However, it is possible to run the CWM and OKC simulators on Windows and connect to the Linux oke simulator via a serial connection.
Endianness
To ensure interoperability between platforms the byte ordering of multi-byte integer values must be considered. Little-endian means that the least significant bytes of a multi-byte integer come before the most significant bytes as address values ascend. Big-endian, also known as network byte order, means that the most significant bytes of a multi-byte integer come before the least significant bytes as address values ascend.
When applicable the CWL internals will use network byte order. Controller specific application data is not required to use network byte order, although it is strongly recommended in cases where it is applicable; usually when using the %H formatter.
Equipment platforms must minimally provide ntohs() and htons() functions. If your platform does not already provide these functions the following C marcos can be placed in cwport.h:
#define htons(x) ((uint16_t) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))) #define ntohs(x) htons(x)
Recursion
During the generation of certain JSON messages some functions, in particular MJPrintf(), will be called recursively. The depth of the recursion is a function of the number of levels of object and array nesting in a generated JSON string. Implementors are encouraged to minimize nesting both to reduce stack utilization on constrained platforms and to flatten OKMs that helps minimize cloud overhead when processing OKMs.
Clocks
The porting layer requires access to read a system tick count and optional access to read and write a real time clock.
System Tick
Most systems will already have and use a system tick count. It is usually an integer value that is incremented at a constant periodic rate, typically inside a timer interrupt.
Unlike a real-time clock that usually has a resolution of 1 second, the system tick counter allows application code to time intervals down to the millisecond resolution. And unlike a real-time clock that has discontinuities when time is changed, the system tick counter always, predictably increases until the system is reset.
The CWL library requires access to a system tick count. First, the constant CW_PORT_TICKS_PER_SECOND must be defined to indicate the number of system tick counts per second. Second the CWPortTick_t type must be defined to match the data type of the system tick counter. Third, the CWPortGetTick64() function must be implemented to return the current tick counter value in a synchronized manner.
A system tick resolution of 10ms is acceptable, although a resolution of 1ms makes timing more precise and is especially beneficial for half-duplex serial communication to the CWM. By these guidelines, CW_PORT_TICKS_PER_SECOND should be roughly in the range of 100 to 1000. This constant should include a type qualifier such as ull for 64-bit system tick counters to ensure that arithmetic operations use the correct type.
As implied by the name, CWPortGetTick64() function expects to return a 64-bit tick counter value, and this is the preferred implementation. When using a 64-bit tick counter, code can safely ignore the case when the timer wraps back to zero, since this would take a very, very long time to occur. Because integer overflow is not relevant, tick comparisons are straightforward and simplify the code logic. Most modern toolchains support the uint64_t type even on 8 and 16-bit microcontrollers.
For platforms that support 64-bit integer types, but that currently use a 32-bit tick counter there are the following options: One, convert the system to a single 64-bit tick counter. Two, add a parallel 64-bit tick counter so that existing code using the 32-bit counter does not need to be updated. Three, use the 32-bit tick counter anyhow.
For platforms that do not support 64-bit integer types or that decide not to use them the implementor may simply define CWPortTick_t to be a 32-bit integer type and CWPortGetTick64() will return a 32-bit value. The drawback is that tick counter integer overflow will occur regularly on the human time scale. For example, a 32-bit 10ms timer tick will wrap every 1.3 years, and a 1ms ticker tick will wrap every 49 days. When wrap occurs, there is the possibility that active timeout intervals within the CWL will malfunction. To avoid these potential malfunctions the system controller could reset itself before the timer tick count wraps. For example, the system controller could reset itself at 3AM if the timer tick count has been running for more than 45 days. Rebooting the system controller during off hours minimizes any impact to normal operation.
CWPortGetTick64() must safely make a copy of the current tick counter and return it. For example, if the system tick counter is updated in a timer interrupt, then CWPortGetTick64() must turn off interrupts, make a copy of the system tick counter, turn on interrupts, and finally return the copy of the system tick counter. Not providing proper synchronization when accessing the system tick counter will invariably cause the CWL to malfunction in unexpected ways.
MSP430 Pseudocode Example
This section has pseudocode taken from a working MSP430-based embedded platform that properly implements synchronized retrieval of a 64-bit system tick count.
The tick counter is a uint64_t type. CWPortTick_t is defined to be a uint64_t type. The system tick fires 1024 times per second to increment the counter, so CW_PORT_TICKS_PER_SECOND is defined accordingly. The CWPortGetTick64() function makes a copy of the system tick counter while interrupts are disabled. This synchronizes it with the timer interrupt and prevents corrupted tick values from being read and returned to the CWL.
Volatile uint64_t gTimerTickCnt; #pragma vector=TIMER1_A1_VECTOR __interrupt void TimerTickIsr(void) { if (TA1IV == 2) gTimerTickCnt++; } #define CW_PORT_TICKS_PER_SECOND (1024ull) typedef uint64_t CWPortTick_t ; CWPortTick_t CWPortGetTick64(void) { CWPortTick_t temp; CS_ENTER() ; /* Disable global interrupts */ temp = gTimerTickCnt; CS_EXIT(); /* Enable global interrupts */ return temp; }
Clock Minute
The CWL library aligns heartbeat reports to the top of every clock minute. The clock epoch, whether Jan 1, 1970, 2000, or some other date will not affect the proper operation of the library. The CWPortGetClockMinute() function must be implemented to return the current clock minute, a value from 0 to 59, and must properly synchronize access to the clock data source so that data corruption does not occur.
If an OKE system does not have an RTC then the system must use the system tick counter to simulate a clock minute.
MSP430 Pseudocode Example
This section has pseudocode taken from a working MSP430-based embedded platform that properly implements synchronized retrieval of the current clock minute. For context, this MSP430 platform uses a bare metal, single threaded, main execution loop. The RTC peripheral is only accessed in the context of the main loop, therefore no other conflicting access can occur simultaneously. Therefore, using an explicit synchronization primitive such as a critical section or semaphore is not required. The while loop waiting for the RTC to be ready is an access requirement of this specific RTC and will not be applicable to all RTCs. The _RTCBCD2Bin() function converts the BCD representation of the RTCMIN register into a 2's complement integer value. Accessing hardware RTC peripheral registers will vary between platforms.
Int8_t CWPortGetClockMinute(void) { int8_t minute; CW_ASSERT(RTCIsRunning()); /* Only valid to call if RTC is inited */ while((RTCCTL01 & RTCRDY) == 0); /* Wait for RTC to be ready to read */ minute = _RTCBCD2Bin(RTCMIN); /* Read minute value */ CW_ENSURE((minute >= 0) && (minute <= 59)); /* Must be in range */ return minute; /* Return the clock minute */ }
ISO 8601 Time
ISO 8601 defines a standard way to unambiguously convey dates and times as structured ASCII strings. The CWL only requires a small subset of the standard to be implemented so that current time can be read and written as an ISO 8601 string. A platform will typically not maintain time as an ISO 8601 string. Rather a platform will convert an ISO 8601 string into its local time representation or will convert its local time representation into an ISO 8601 string on an as needed basis.
The minimum requirement for implementors is to be able to parse and generate an ISO 8601 string such as "2019-12-03T16:17:00". The string contains a date and time field separated by a capitol T. The date field is a 4-digit year, a minus sign, a 2-digit month (01-12), a minus sign, and a 2-digit day (01-31). The time field is a 2-digit hour (00-23), a colon, a 2-digit minute (00-59), a colon, and a 2-digit second (00-59). When no time zone information is explicitly indicated, the default, the OKE will treat it as local time.
Local Time
The OKC knows the correct local time, accounting for both time zone and daylight savings, of a connected OKE. When time is written to the OKE, local time will be set, and time-zone context will not be provided by default. This means that OKE can display the correct local time, but without time zone context.
UTC aligned time is not written to connected devices since this would require connected devices to also be properly configured for time zone and daylight savings to perform local time calculations competently. Only setting local time to the connected devices greatly simplifies ensuring correct time is displayed and used by the OKE.
The CWM periodically writes local time as an ISO 8601 string to the OKE. The CWM gets current local time either directly from the OCK or indirectly via the IoT Gateway which gets time from the OKC.
If a platform currently displays or allows manual configuration of current time, time zone and/or daylight savings then some adjustments must occur. First, when using the OKC manual time configuration should not be permitted since OKC expects to and will automatically set and maintain the proper clock time through the CWM. Second, when using the OKC, displayed time must not also report a time zone or daylight savings context since that information is not conveyed to the OKE.
Reading ISO Time
int8_t* CWPortGetISOTimeStr(void);
The CWPortGetISOTimeStr() function must return a pointer to a persistent, valid, NULL terminated ISO 8601 time string. The time string must not include time zone information and should report local time. Implementors may include sub-second precision only if application specific requirements warrant it. For example, a typical time string value would be: "2019-02-03T16:59:01". The string may not allocated from the stack of the CWPortGetISOTimeStr() function because the time string must persist after the function returns. Therefore, the time string should be allocated as a global variable or statically within the scope of the function. The function must also synchronize access to the RTC so that data read from it is not corrupted.
If an OKE system does not have an RTC, then it must return the string "0000-00-00T00:00:00". When the CWM receives a message from an OKE system with a "0000-00-00T00:00:00" timestamp it will update the timestamp with its current time before sending the message to the OKC.
Millisecond or Microsecond ISO Time Resolution
Nearly all OKE implementations DO NOT require sub-second time stamping. The CWM automatically ensures that the exact sequence of messages generated by the OKE is preserved and no data will be overwritten when it is transferred to and stored by the OKC even when some of those messages have the same timestamp and the same data fields.
If there is a use case for sub-second resolution time stamps, the OKE implementor will need to perform additional implementation specific steps to queue and forward the messages via the CWPortGenHeartbeatCB() callback and override the CWL's default timestamp.
Another possible solution to high resolution timestamping is to curate the data into a log file containing the desired timestamp resolution and use the CLW's file transfer to write the log to the cloud for processing.
In either case, please consult with the OKC team before designing and implementing high resolution timestamps since it will require additional OKC development to appropriately process the application specific data.
Writing ISO Time
void CWPortSetISOTime(int8_t *isoTimeStr) ;
The CWPortSetISOTime() function takes a valid ISO 8601 time string and updates its internal clock time. Implementors only need to handle and process the most basic of ISO 8601 time strings, ones of the form "yyyy-mm-ddThh:mm:ss", and must ignore any unhandled time string formats. For example, time string formats including time zone information must be ignored if the implementation only handles the basic format. When processing a basic time string without any time zone information, the function must interpret it as the current local time of the OKE. The function must also synchronize access to the RTC so that data written to it is not corrupted.
If an OKE system does not have an RTC, then it may ignore the set time request.
ISO 8601 Platform Support
Some platforms may natively support ISO 8601 time strings. Those platforms may utilize the native interfaces to implement the CWL requirements.
For platforms that do not natively support ISO 8601 time strings the example MSP430 pseudocode in the next section shows how to implement the CWL requirements using standard C library functions.
MSP430 Pseudocode Examples
This section has pseudocode taken from a working MSP430-based embedded platform that properly implements synchronized reading and writing of ISO 8601 time using only standard C library functions. This platform only supports the basic form of the ISO 8601 time string, which is always 20 bytes in length including the NULL terminator.
In the CWPortGetISOTimeStr() function the buffer into which the current local time is formatted is declared as static. This ensures the buffer persists after the function returns. The ReadCurrentTimeAndDate() function is a platform specific function that reads the current time and date into easy to use structure. Because this platform operates as a single main execution loop and the RTC is never accessed from an interrupt context it is not necessary to explicitly synchronize access to the RTC using critical sections or a semaphore. A snprintf() call is used to generate the current local time as a valid ISO 8601 string. Because snprintf() does not guarantee NULL termination, a NULL terminator is explicitly set. The pointer to the newly formatted, NULL terminated buffer is returned.
The CWPortSetISOTime() function is passed what should be an ISO 8601 time string. Since this implementation only support the basic form of ISO 8601 strings the size of the input string must be exactly 20 bytes, and the field separators must be in the correct positions. If the length and field separators are valid then the code attempts to convert the fields into integer values written to a TimeAndDate structure. The TimeAndDate structure is platform specific and is not a standard time structure. After the string to integer conversions are complete the code sanity checks the ranges of the date and time fields. Only if the sanity check passes will the code write the time to the RTC. Although this code deliberately ignores other forms of ISO 8601 time strings which may include time zone information or additional precision it meets CWL requirements.
#define ISO_STRING_SIZE 20 /* "yyyy-mm-ddThh:mm:ss" including NULL */ int8_t* CWPortGetISOTime(void) { TimeAndDate td; static int8_t isoTime[ISO_STRING_SIZE]; ReadCurrentTimeAndDate(&td); snprintf((char *)isoTime, sizeof(isoTime), "%04d-%02d-%02dT%02d:%02d:%02d", td.Year, td.Month, td.Date, td.Hour, td.Minute, td.Second); isoTime[sizeof(isoTime) – 1] = 0; /* Ensure NULL termination */ return isoTime; } void CWPortSetISOTime(int8_t *isoTimeStr, uint16_t isoTimeStrSize) { TimeAndDate td; CW_REQUIRE(isoTimeStr != NULL); /* Only process time strings of basic format, ignore anything else */ if ((isoTimeStrSize == ISO_STRING_SIZE) && (isoTimeStr[4] == '-') && (isoTimeStr[7] == '-') && (isoTimeStr[10] == 'T') && (isoTimeStr[13] == ':') && (isoTimeStr[16] == ':')) { td.Year = atoi(&time[0]); td.Month = atoi(&time[5]); td.Date = atoi(&time[8]); td.Hour = atoi(&time[11]); td.Minute = atoi(&time[14]); td.Second = atoi(&time[17]); if ((td.Year > 2018) && (td.Month >= 1) && (td.Month <= 12) && (td.Date >= 1) && (td.Date <= 31) && (td.Hour <= 23) && (td.Minute <= 59) && (td.Second <= 59)) { WriteCurrentTimeAndDate(&td); } } }
Reset
void CWPortExeReset(void);
The CWPortExeReset() function must force a full warm start of the OKE controller. The function must ensure that the serial transmit software and hardware buffers are empty before resetting. This function should not return to the caller.
It is strongly recommended that the reset function call the CW_ERROR() macro to force the reset. If the assertion handler is implemented to log the assertion, then the cause of the reset will be traceable to a deliberately commanded action rather than a spurious problem.
MSP430 Pseudocode Example
In this example port to an MSP430 platform, the CWPortExeReset() function first waits for the transmit software queue to empty, then waits 10ms for the hardware buffers to finish transmitting on the wire. Finally, an assertion is forced. The assertion handler ensures the file and line number is logged and then performs a warm reset.
Void CWPortExeReset(void) { while (TxDataQueueIsEmpty() == false); DelayMs(10); CW_ERROR(); }
Flush
void CWPortExeFlush(void);
The CWPortExeFlush() function is intended to permit the OKC to clear out persistent/non-volatile data such as accumulated logs or other data that could backlog or inhibit the desired operation of the equipment.
Primarily this function applies to the CWM that has very deep non-volatile queues, that in some cases the OKC needs to empty.
For many OKE implementations this function may not take any action.
Versions
bool CWPortGetVersion(uint8_t index, int8_t **typeStr, int8_t **fwverStr, int8_t **hwrevStr) ;
The CWPortGetVersion() function returns platform type, software/firmware version, and hardware revision information about the OKE. The function allows the CWL to sequentially read zero or more sets of version information about the platform so that it can be reported to the OKC.
This means it is possible for a controller running the CWL to report versions for multiple components of the system. This is particularly important so the OKC can determine if firmware updates must be applied. Even when a component is not in-system upgradeable, having an inventory of the versions is critical for remote asset management. So, when in doubt report the version information of as much of the OKE system as possible.
The CWL reports version information to the OKC automatically, and calls the CWPortGetVersion() to fetch the versions. The CWL will call the CWPortGetVersion() in a loop initially passing an index of 0. If there is version information for index 0, which should always be the case, then the CWPortGetVersion() will set the parameter pointers to static strings for the type, firmware, and hardware NULL terminated strings, and then return true. It is important that the string buffers are not on the stack frame of the CWPortGetVersion() function, since they must be accessible after the function returns. Next the CWL will invoke CWPortGetVersion() again with an index of 1. If there are additional versions to report then the pointers will be updated and the function will return true, then the CWL will then ask for index 2. Else the function will return false and the CWL will know that no more version information is available. When CWPortGetVersion() returns true, all of the pointers must point to a valid NULL terminated string.
The type, software/firmware version, and hardware revisions are NULL terminated strings. The CWL does not impose any restrictions on the format of any of the version strings. However, it is recommended that implementors consider how the version information will be handled by the OKC. The goal is for the OKC to reliably detect what version is running and initiate configured firmware updates. This means the type and firmware version strings should be unambiguous and consistent across versions. In some cases, the hardware revision of a component may not be known, in this case a pointer to an empty string "" should be returned.
Pseudocode Example
In this example code the CWPortGetVersion() function returns two sets of version information. The first time the CWL calls the function with an index of 0, *typeStr is set to point to "TCHEF", *fwverStr is set to point to "1.3.42", and hwrevStr is set to point to "A1", and true is returned. The second time the CWL calls the function with an index of 1, *typeStr is set to point to "TCAB", *fwverStr is set to point to "4.2.c1", and hwrevStr is set to point to "REV3", and true is returned. The last time the CWL calls the function it returns false.
Bool CWPortGetVersion(uint8_t index, int8_t** typeStr, int8_t** fwverStr, int8_t** hwrevStr) { static const int8_t *type[] = {"TCHEF","TCAB"} ; static const int8_t *fwver[] = {"1.3.42","4.2.c1"} ; static const int8_t *hwrev[] = {"A1","REV3"} ; CW_REQUIRE(typeStr != NULL); CW_REQUIRE(fwverStr != NULL); CW_REQUIRE(hwrevStr != NULL); /* There are only 2 versions to report */ if (index >= 2) return false; *typeStr = (int8_t *) type[index]; *fwverStr = (int8_t *) fwver[index]; *hwrevStr = (int8_t *) hwrev[index]; CW_ENSURE(*typeStr != NULL); CW_ENSURE(*fwverStr != NULL); CW_ENSURE(*hwrevStr != NULL); return true; }
Heartbeats
OKE systems must send periodic OKMs that contain the operational status of the system. The CWL will automatically invoke CWPortGenHeartbeatCB() once every minute to allow the application code to generate its application specific heartbeat message. The heartbeat message must be valid JSON.
CWPortGenHeartbeatCB() is an MJSON printer function invoked under the context of a MJPrintf() call triggered by the library. Implementors must use MJPrintf() calls within the context of CWPortGenHeartbeatCB()to generate the heartbeat message. The function must return the total number of new bytes written to the message. Implementors will have either 300 or 800 (default) bytes of buffer space for generating each heartbeat message depending on the CWL configuration.
Implementors can cause the callback to be invoked additional times when more than one heartbeat OKM must be generated each minute or when a critical state change occurs. This is done by calling CWCmdScheduleHeartbeat().
The last heartbeat message per minute interval should not invoke CWCmdScheduleHeartbeat() because that will cause continuous heartbeat generation.
Heartbeat Throttling
The CWL has added a throttling mechanism for heartbeats that prevents the generation of more than CW_PORT_MAX_HEARTBEATS_PER_MIN per minute. Continuous generation of heartbeat messages clogs up the outbound store and forward queues and the bandwidth to the OKC with highly redundant information. Additionally, it can starve out other CWL message generation.
CW_PORT_MAX_HEARTBEATS_PER_MIN is defined in cwport.h and the default is 15 which should be more than enough for most applications such that they are never throttled.
If a throttling event occurs the CWL will report additional diagnostics to the OKC so that the condition is recorded. When the next one-minute period begins, the application will be allowed to send another set of heartbeats.
Common causes of excessive heartbeat generation includes calling CWCmdScheduleHeartbeat() every time CWPortGenHeartbeatCB() is invoked and calling CWCmdScheduleHeartbeat()continuously while the equipment is in a fault state when the desired behavior is to send a single set of heartbeats after entering the fault state.
Partitioning Heartbeats
There is a 1000 total byte limit for each OKM including required overhead added by the CWL and NULL terminator. Implementors must target a maximum heartbeat payload size of either 300 or 800 bytes. This will adequately account for overhead and some margin for future protocol changes. Many systems will be able to encode all the required heartbeat data in 800 bytes.
However, some systems may have more than 800 bytes of heartbeat data, and/or may be organized in such a way that logically organizing data in distinct heartbeats is convenient. For example, a modular oven system, may send a separate heartbeat for each cabinet.
From an efficiency perspective it is better to have fewer, larger heartbeats, rather than many, smaller heartbeats, since the overhead of each message is constant.
OKM Formatting
It is valid for JSON strings to include whitespace and line breaks. This formatting does not alter the meaning of a JSON message. However, it does unnecessarily consume additional memory and network bandwidth. Therefore, implementors should not include whitespace or line breaks in their generated messages.
Rate Limiting
Heartbeats should only be generated once per minute. It is best to report faults and other events that occur between heartbeats as ascending counters. These counters can be reset to 0 on a restart. The OKC can determine the type and number of faults that occurred between two heartbeats. The OKE may generate additional heartbeats when certain events occur, but this is not encouraged. However, if a requirement exists to do so then the OKE must implement a rate limiting mechanism to prevent the CWM store and forward queue from being filled with OKMs that consume storage and network resources and limit the ability to diagnose problems by delaying delivery of newer OKMs to the OKC.
Every OKE must be a good OpenKitchen citizen and try to use the minimum resources necessary when sending heartbeats. By doing so the entire OpenKitchen system will work better for our customers.
Pseudocode Example
This example is from the Window port. It shows a simple scenario where the application code generates two heartbeat message each minute. This is a contrived example since all the data could have fit into a single heartbeat. When hbState is zero the callback prints the door count data, requests an additional heartbeat by calling CWCmdScheduleHeartbeat() and changes hbState to 1. The CWL will invoke the callback a second time after the first one is sent. Since hbState is one the temp data is reported, and the state is set back to 0. It does not call CWMsgTxHeartbeat() again since all the heartbeats have been sent for this cycle.
Int32_t CWPortGenHeartbeatCB(MJBuffer_t* mb, va_list* ap) { int total = 0; static uint8_t hbState; static uint32_t appcount; switch (hbState) { case 0: total += MJPrintf(mb, "%Q:%u", "door", appcount); appcount++; CWCmdScheduleHeartbeat(); hbState = 1; break; default: total += MJPrintf(mb, "%Q:%u", "temp", 350 + appcount % 10); hbState = 0; break; } return total; }
The following are messages generated by the example code.
{"_dst":["OKC"],"_src":["0011223344556677"],"_cmd":"wr","_id":24,"_ts":"2019-12-06T12:06:00","_crc":"48D7","_pld":{"_hbt":{"door":8}}} {"_dst":["OKC"],"_src":["0011223344556677"],"_cmd":"wr","_id":25,"_ts":"2019-12-06T12:06:00","_crc":"6949","_pld":{"_hbt":{"temp":359}}}
The CWPortGenHeartbeatCB() function only is responsible for the "door":8 and "temp":359 portions of the messages. The rest of the JSON is automatically generated by the library.
File Transfer
The CWL allows OKE systems to read and write files containing arbitrary data via the file transfer interface. Individual file transfers of up to 2^31-1 bytes (2GB) in size are allowed. The primary use of file transfer is for firmware updates since it is highly likely that all OKE controllers will support in-system updates. Other possible uses for file transfer include sending recipes to equipment, or for equipment to offload diagnostic logs to the OKC.
File transfer is an optional service of the CWL and may be disabled by setting CW_PORT_IS_FILE_SUPPORT_ENABLED to 0. This will save code space and also permit implementors to significantly reduce the CWL RAM requirements by also setting CW_PORT_IS_SMALL_MSG_ENABLED to 1.
The OKC can write a file to an OKE system and read a file from an OKE system.
Likewise, an OKE system can write a file to the OKC and read a file from the OKC.
When a file read request is made, regardless if sent by the OKC to an OKE system or vice versa, it will simply cause the target of the request to begin writing the file back to the requestor. This means that files are only transferred in the context of a file write operation.
The CWL makes no assumptions about the filesystem on the implementor's platform, or even if a traditional file system exists. For example, many deeply embedded platforms simply have interfaces that read and write to a non-volatile memory that is partitioned statically. Other platforms, such as Linux, will have full desktop compatible, wear leveling flash file systems. The CWL can easily work with either setup. Implementors should consider the file names used in OKMs to be logical and not necessarily have or demand a direct manifestation as a "real" file.
CWM Buffering
File transfers may need to move large quantities of data. Many embedded systems will have limited amounts of high-speed RAM buffers, and there can be significant latency and throughput bottlenecks when writing data out to a non-volatile memory. So how can a small embedded system handle the onslaught of file data sent to it from the cloud computers with 10 Gigabit network connections?
The answer is that the ConnectWare file transfer mechanism ensures that when the OKC is writing a file to OKE, an OKE system needs to only handle small amounts of file data, no more than 512 bytes, at any time and can easily throttle the rate at which it receives file data.
The CWM will only send these file fragment messages to OKE at the rate allowed by the OKE system.
Likewise, when an OKE system is writing a file to the OKC, the CWM buffers the file fragment messages from the OKE before sending them to the OKC.
By decoupling file transfer between an OKE system from the OKC, the CWM allows an OKE system to easily manage having large files written to it and write large files to the OKC.
- No labels