Skip to main content

TOU Profile File Format and Automation

Version 1.2​

This page describes the format of a Time of Use (TOU) profile file. A TOU profile is a JSON document with the extension .tou. It holds one or more seasons, and each season holds a list of time periods: rate periods (peak / off-peak) and battery control periods.

note

Section 8 explains how to update a profile on the server, and section 9 how to tell a gateway to use the updated profile. Section 11 has a browser test page that does both. How the gateway downloads and applies the file is covered on a separate page.


1. File Overview​

PropertyRequirement
FormatJSON, UTF-8
Extension.tou
Maximum size2 MB
Example nameCarlos_03698e2f.tou

Structure:

Profile
└── SES[] Seasons
└── TP[] Time periods

A file is accepted only if it is valid JSON and has, at minimum, an NM field and an SES array. Otherwise it is rejected and not stored.

note

Numbers can be written either as JSON numbers (1) or as strings ("1"). Both are read the same way. The examples below use strings, matching the profile editor's output.


2. Profile (root object)​

FieldTypeRequiredDescription
NMstringYesProfile name. Maximum 31 characters
EFDstringNoEffective date, yyyy-MM-dd
SESarrayYesList of seasons (section 3)
{
"NM": "Residential TOU",
"EFD": "2026-07-01",
"SES": [ ]
}

3. Season (SES[])​

A season is active for a range of calendar dates, independent of year.

FieldTypeDescription
NMstringSeason name. Maximum 31 characters
DTFstringFirst day of the season, MM-dd
DTTstringLast day of the season, MM-dd (inclusive)
TParrayList of time periods (section 4)
  • A season can wrap the year end. "DTF": "11-01" with "DTT": "02-28" covers November through February.
  • Seasons should not overlap. If they do, the first matching season in the file is used.
  • If no season matches today's date, TOU does nothing for that day.
{
"NM": "Summer",
"DTF": "12-01",
"DTT": "02-28",
"TP": [ ]
}

4. Time Period (TP[])​

Fields common to every period:

FieldTypeDescription
NMstringPeriod name. Maximum 31 characters
TYPnumberPeriod type: 0 = NA, 1 = Peak, 2 = Off-peak, 3 = Battery control
TMFnumberStart time, in minutes from midnight (inclusive). 0 = 00:00, 540 = 09:00
TMTnumberEnd time, in minutes from midnight (exclusive). 1440 = end of day
DOWnumberDays of the week, as a bitmask (below)

Days of the week (DOW)​

Add together the values for the days the period applies to:

DayValue
Sunday1
Monday2
Tuesday4
Wednesday8
Thursday16
Friday32
Saturday64

Examples: weekdays only = 62, weekends only = 65, every day = 127.

Times​

  • TMF must be less than TMT. A period cannot cross midnight. To cover 22:00 to 06:00, write two periods: 1320 to 1440, and 0 to 360.
  • The end time is exclusive: TMF 540, TMT 600 is active from 09:00:00 up to, but not including, 10:00.

4.1 Rate periods (TYP 0, 1 or 2)​

FieldTypeDescription
RATEnumberImport rate (price per unit)
ERATEnumberExport rate
RATEUnumberRate unit: 1 = kWh, 2 = kVAh
{
"NM": "Peak",
"TYP": "1",
"TMF": "960",
"TMT": "1260",
"DOW": "62",
"RATE": "0.45",
"ERATE": "0.08",
"RATEU": "1"
}

4.2 Battery control periods (TYP 3)​

FieldTypeDescription
MODEnumber1 = Charge, 2 = Discharge
MFLGnumberMode flags, as a bitmask. 0 = no flags. Meaning of each bit depends on MODE (below)
MVLAUEnumberCharge or discharge power, in kW
MSOCnumberTarget battery state of charge, in %
MTRIGnumberLoad threshold, in kW. Its meaning depends on MODE: with MODE 2 and the Load follow bit (bit 0) of MFLG set, it is the minimum load trigger; with MODE 1 and the Total effective load limit bit (bit 2) of MFLG set, it is the total effective load limit. Omitted otherwise
note

The power field is spelled MVLAUE in the file. Use that exact spelling.

Mode flags (MFLG)​

MFLG is a bitmask, like DOW. Add together the values of the flags you want; 0 means no flags are set.

MODEBitValueFlagBehavior when set
1 Charge01Charge on solar onlyCharge using only available solar power, up to MVLAUE. Never draws from the grid to charge
1 Charge12Charge on exportCharge only from power that would otherwise be exported to the grid, up to MVLAUE
1 Charge24Total effective load limitCharge at up to MVLAUE, but back off the charge power to keep the total effective load at or below MTRIG kW. MTRIG must be greater than MVLAUE
2 Discharge01Load followDischarge only enough to cover the site load, up to MVLAUE. MTRIG sets the load below which discharge is not triggered

When no flag is set (MFLG = 0), the battery charges or discharges at MVLAUE until MSOC is reached.

Charge flags can be combined. For example, Charge on solar only + Charge on export + Total effective load limit is 1 + 2 + 4 = 7.

To test a flag, check its bit rather than comparing the whole value: for example, Charge on solar only is set when MFLG & 1 is non-zero, Charge on export when MFLG & 2 is non-zero, and Total effective load limit when MFLG & 4 is non-zero.

Charging stops when the battery is at or above MSOC. Discharging stops when the battery is at or below MSOC.

{
"NM": "Evening discharge",
"TYP": "3",
"TMF": "1020",
"TMT": "1260",
"DOW": "127",
"MODE": "2",
"MFLG": "1",
"MVLAUE": "5",
"MSOC": "20",
"MTRIG": "0.5"
}

A charge period with a total effective load limit. The battery charges from solar at up to 85 kW, but backs off whenever the total effective load would go above 120 kW:

{
"NM": "Solar charge, load limited",
"TYP": "3",
"TMF": "540",
"TMT": "900",
"DOW": "62",
"MODE": "1",
"MFLG": "5",
"MVLAUE": "85",
"MSOC": "90",
"MTRIG": "120"
}

5. How Periods Are Resolved​

Rate periods and battery control periods are evaluated independently. A rate period and a battery control period can cover the same time of day.

  • Rate period: if more than one rate period matches the current time, Peak wins over Off-peak, and Off-peak wins over NA.
  • Two periods of the same type that overlap are not supported. The first one in the file is used and a warning is logged.
  • Battery control period: at most one is active at a time. When no battery control period matches, the battery follows the default behavior described in the TOU user guide.

6. Complete Example​

{
"NM": "Residential TOU",
"EFD": "2026-07-01",
"SES": [
{
"NM": "Summer",
"DTF": "11-01",
"DTT": "03-31",
"TP": [
{ "NM": "Off-peak night", "TYP": "2", "TMF": "0", "TMT": "420", "DOW": "127",
"RATE": "0.18", "ERATE": "0.05", "RATEU": "1" },
{ "NM": "Shoulder", "TYP": "0", "TMF": "420", "TMT": "960", "DOW": "127",
"RATE": "0.28", "ERATE": "0.06", "RATEU": "1" },
{ "NM": "Peak", "TYP": "1", "TMF": "960", "TMT": "1260", "DOW": "127",
"RATE": "0.52", "ERATE": "0.10", "RATEU": "1" },
{ "NM": "Off-peak late", "TYP": "2", "TMF": "1260", "TMT": "1440", "DOW": "127",
"RATE": "0.18", "ERATE": "0.05", "RATEU": "1" },

{ "NM": "Solar charge", "TYP": "3", "TMF": "540", "TMT": "900", "DOW": "127",
"MODE": "1", "MFLG": "1", "MVLAUE": "5", "MSOC": "100" },
{ "NM": "Peak discharge", "TYP": "3", "TMF": "1020", "TMT": "1260", "DOW": "127",
"MODE": "2", "MFLG": "1", "MVLAUE": "5", "MSOC": "20", "MTRIG": "0.5" }
]
},
{
"NM": "Winter",
"DTF": "04-01",
"DTT": "10-31",
"TP": [
{ "NM": "Off-peak", "TYP": "2", "TMF": "0", "TMT": "420", "DOW": "127",
"RATE": "0.15", "ERATE": "0.05", "RATEU": "1" },
{ "NM": "Peak", "TYP": "1", "TMF": "420", "TMT": "1260", "DOW": "62",
"RATE": "0.40", "ERATE": "0.08", "RATEU": "1" }
]
}
]
}

7. Field Quick Reference​

LevelFieldMeaning
ProfileNMProfile name
ProfileEFDEffective date yyyy-MM-dd
ProfileSESSeasons
SeasonNMSeason name
SeasonDTF / DTTStart / end date MM-dd
SeasonTPTime periods
PeriodNMPeriod name
PeriodTYP0 NA, 1 Peak, 2 Off-peak, 3 Battery control
PeriodTMF / TMTStart / end, minutes from midnight
PeriodDOWDay bitmask (Sun = 1 ... Sat = 64)
RateRATE / ERATE / RATEUImport rate / export rate / unit (1 kWh, 2 kVAh)
BatteryMODE1 Charge, 2 Discharge
BatteryMFLGBitmask. Charge: 1 = solar only, 2 = charge on export, 4 = total effective load limit. Discharge: 1 = load follow
BatteryMVLAUEPower, kW
BatteryMSOCTarget SOC, %
BatteryMTRIGkW. Discharge: minimum load trigger (load follow). Charge: total effective load limit

8. Updating a Profile on the Server​

A profile is changed on the server with a single authenticated PUT request. The request carries the profile document from sections 2 to 4 inside a wrapper object.

8.1 Authenticate​

Every request needs an access token. See the API Authentication page for how to obtain one, then send it as:

Authorization: Bearer <access_token>
note

The account used must have permission to write TOU profiles. Tokens expire, so request a new one when the server returns an authorization error.

8.2 Request​

PUT https://<api-host>/timeofuse/admin/update?id=<profile-id>&organizationId=<organization-id>
PartValue
<api-host>The Molecule API host for your environment. Development: api-dev.moleculesystems.com
id (query)ID of the profile to update
organizationId (query)ID of the organization that owns the profile

Headers:

HeaderValue
AuthorizationBearer <access_token>
Content-Typeapplication/json

8.3 Request body​

FieldTypeDescription
idstringProfile ID. Must match the id in the query string
namestringProfile name. Keep the same as NM inside the payload
regionstringRegion code, e.g. CA
isPublicbooleanWhether the profile is visible to other organizations
effectiveDatestringEffective date, yyyy-MM-dd. Keep the same as EFD inside the payload
payloadstringThe complete .tou document from sections 2 to 4, serialized as a JSON string
note

payload is a string containing JSON, not a nested object. The .tou document is serialized once to make the payload value, and the whole body is serialized again when sent. In JavaScript, JSON.stringify(profile) produces the payload value, and the second serialization happens when the body is stringified.

8.4 Example (JavaScript)​

const apiHost = 'api-dev.moleculesystems.com';
const profileId = '<profile-id>';
const organizationId = '<organization-id>';
const accessToken = '<access_token>';

// The .tou document (sections 2 to 4)
const profile = {
NM: 'Test',
EFD: '2026-09-09',
SES: [
{
NM: 'All',
DTF: '01-01',
DTT: '12-31',
TP: [
{ NM: 'Peak', TYP: '1', TMF: 1080, TMT: 1260, DOW: 127, RATE: '0.66', ERATE: '0.06', RATEU: 1 },
{ NM: 'Off-Peak', TYP: '2', TMF: 0, TMT: 1439, DOW: 127, RATE: '0.33', ERATE: '0.06', RATEU: 1 },
],
},
],
};

const response = await fetch(
`https://${apiHost}/timeofuse/admin/update?id=${profileId}&organizationId=${organizationId}`,
{
method: 'PUT',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: profileId,
name: profile.NM,
region: 'CA',
isPublic: false,
effectiveDate: profile.EFD,
payload: JSON.stringify(profile), // the .tou document, as a string
}),
}
);

if (!response.ok) {
throw new Error(`Update failed: ${response.status}`);
}

8.5 Example (curl)​

curl -X PUT \
"https://<api-host>/timeofuse/admin/update?id=<profile-id>&organizationId=<organization-id>" \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
"id": "<profile-id>",
"name": "Test",
"region": "CA",
"isPublic": false,
"effectiveDate": "2026-09-09",
"payload": "{\"NM\":\"Test\",\"EFD\":\"2026-09-09\",\"SES\":[{\"NM\":\"All\",\"DTF\":\"01-01\",\"DTT\":\"12-31\",\"TP\":[{\"NM\":\"Peak\",\"TYP\":\"1\",\"TMF\":1080,\"TMT\":1260,\"DOW\":127,\"RATE\":\"0.66\",\"ERATE\":\"0.06\",\"RATEU\":1}]}]}"
}'

8.6 Checklist​

  • id in the body matches id in the query string.
  • name and effectiveDate match NM and EFD inside the payload.
  • payload is a string, with its inner quotes escaped.
  • The payload passes the rules in sections 2 to 6 (times do not cross midnight, DOW is a bitmask, and so on).
  • A charge period with the Total effective load limit bit set (MFLG & 4) has an MTRIG greater than its MVLAUE.

9. Updating the Gateway​

After a profile has been updated on the server (section 8), the gateway that uses it must be told to pick up the change. This is a second PUT request, addressed to a specific gateway.

note

Always update the profile on the server first, then update the gateway. The gateway fetches the profile as it is on the server at that moment.

9.1 Request​

PUT https://<api-host>/gateway/admin/timeofuse/update?organizationId=<organization-id>&moleculeId=<molecule-id>
PartValue
<api-host>The Molecule API host for your environment. Development: api-dev.moleculesystems.com
organizationId (query)ID of the organization that owns the gateway and the profile
moleculeId (query)ID of the gateway to update

Headers are the same as in section 8.2: Authorization: Bearer <access_token> (see API Authentication) and Content-Type: application/json.

9.2 Request body​

FieldTypeDescription
idstringID of the profile the gateway should use. The same id used in section 8
{ "id": "<profile-id>" }

9.3 Example (JavaScript)​

const apiHost = 'api-dev.moleculesystems.com';
const organizationId = '<organization-id>';
const moleculeId = '<molecule-id>';
const profileId = '<profile-id>';
const accessToken = '<access_token>';

const response = await fetch(
`https://${apiHost}/gateway/admin/timeofuse/update?organizationId=${organizationId}&moleculeId=${moleculeId}`,
{
method: 'PUT',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: profileId }),
}
);

if (!response.ok) {
throw new Error(`Gateway update failed: ${response.status}`);
}

9.4 Example (curl)​

curl -X PUT \
"https://<api-host>/gateway/admin/timeofuse/update?organizationId=<organization-id>&moleculeId=<molecule-id>" \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{ "id": "<profile-id>" }'

9.5 Order of operations​

  1. Obtain an access token (API Authentication, section 8.1).
  2. PUT the updated profile to the server (section 8).
  3. PUT the gateway update for each gateway that uses the profile (this section).

10. Using TOU Data in Lua Scripts​

The controller can run a profile's battery control for you, but a profile can also be used purely as a source of rates and time periods. A Lua script can read the current TOU state and apply its own logic: your own charge and discharge rules, cost reporting, or switching loads.

10.1 When to use this​

GoalApproach
Let the controller charge and discharge the battery from the profile's Battery Control periodsEnable TOU on the device under Auto mode. No script is needed
Use the profile's rates and periods, but control the battery yourselfLeave TOU disabled on the device under Auto mode, and write a Lua automation
note

If TOU stays enabled on a device under Auto mode, the controller also controls that battery and will compete with your script. Disable it for any device your script controls.

10.2 Reading the TOU state​

Call refreshTOUData() to load the current state into the TOUData table, then read its fields. TOUData is empty until the first call, and it holds the values from the last call, so call it each time loop() runs.

Rate period (always available once a profile is active):

FieldDescription
TOUData.Valid1 once a rate period has been resolved, otherwise 0
TOUData.PeriodTypeCompare against TOUPeriodType.NA, PEAK or OFFPEAK
TOUData.ImportRateCurrent import rate
TOUData.ExportRateCurrent export rate
TOUData.RateUnit1 = kWh, 2 = kVAh

Battery control period (only meaningful while TOUData.BattValid is 1):

FieldDescription
TOUData.BattValid1 while a Battery Control period is active
TOUData.BattModeCompare against TOUBattMode.CHARGE or DISCHARGE
TOUData.BattModeFlagThe profile's MFLG bitmask. Test individual bits against TOUBattModeFlag.SOLAR_ONLY (charge, bit 0), CHARGE_ON_EXPORT (charge, bit 1), LOAD_LIMIT (charge, bit 2, value 4) or LOAD_FOLLOW (discharge, bit 0). NONE when MFLG is 0
TOUData.BattValueCharge or discharge power target, in kW
TOUData.BattSOCTarget SOC, in %
TOUData.BattMinLoadTriggerThe profile's MTRIG, in kW. Minimum load trigger for discharge load follow, or total effective load limit for charge

These fields correspond to the profile fields in section 4: PeriodType to TYP, ImportRate to RATE, ExportRate to ERATE, RateUnit to RATEU, BattMode to MODE, BattModeFlag to MFLG, BattValue to MVLAUE, BattSOC to MSOC and BattMinLoadTrigger to MTRIG.

10.3 Example​

This script reads the TOU state every 30 seconds and logs what it finds. Replace the log lines with your own logic.

-- Set this automation's script frequency (FQ) to 30

function loop()
refreshTOUData()

if TOUData.Valid == 0 then
return -- no profile active
end

if TOUData.PeriodType == TOUPeriodType.PEAK then
print("Peak: import rate " .. TOUData.ImportRate)
-- e.g. discharge the battery, or turn off flexible loads
elseif TOUData.PeriodType == TOUPeriodType.OFFPEAK then
print("Off-peak: import rate " .. TOUData.ImportRate)
-- e.g. charge the battery from the grid
end

if TOUData.BattValid == 1 and TOUData.BattMode == TOUBattMode.CHARGE then
print("Profile asks for charge at " .. TOUData.BattValue .. " kW to " .. TOUData.BattSOC .. "%")
end
end

10.4 Controlling the battery from your script​

To act on the values, your script must first take control of the device, then issue the command. The functions for this (getDeviceLock, releaseDeviceLock, runAutoFunction) are described in Lua Automation Scripting.

10.5 Notes​

  • Reading TOUData does not change the profile or start any control. It is read-only.
  • The values reflect the profile that is currently active on the device. If more than one profile is loaded, only the one marked as the default is used.
  • The script and profile are independent. Updating a profile (sections 8 and 9) changes what TOUData reports, with no change to the script.

11. Test Page: Pushing a Profile from the Browser​

The test page performs sections 8 and 9 from your browser: it obtains a token, updates the profile on the server, then updates the gateway. Use it to try a profile before building the same calls into your own system.

11.1 Download​

Download external_tou_push.zip

FileDescription
index.htmlThe test page
sample.touA sample profile you can load into the page
README.txtShort version of the steps below

You need Python 3 to serve the page, Molecule credentials with permission to write TOU profiles, and the organization, profile and gateway IDs. The profile must already exist: the page updates a profile, it does not create one.

11.2 Running the page​

  1. Unzip external_tou_push.zip into a folder.

  2. Open a terminal in the folder and run:

    python -m http.server 3000
  3. Open http://localhost:3000 in your browser.

note

On macOS and Linux use python3 if python is not found. On Windows use py if python is not found.

Port 3000 is required

The Molecule servers only accept browser requests from http://localhost:3000. Serving the page on any other port, opening it with 127.0.0.1 instead of localhost, or opening the HTML file directly from disk fails with a CORS error.

11.3 Using the page​

SectionWhat to enter
1. ConnectionChoose Development or Production. The API host and token URL are set automatically. Enter your username and password
2. TargetOrganization ID, Profile ID, Gateway (Molecule) ID and region (section 8.3). Tick Also update gateway after profile to run section 9 after section 8
3. TOU profilePaste a profile, or choose a .tou file. The page opens with a sample profile
  • Validate checks the profile against the rules in sections 2 to 5.
  • Upload validates, obtains a token, updates the profile, then updates the gateway if ticked. Each step and its result appear in the Log.
  • Save settings stores everything except the password in your browser, so it loads automatically next time. Reset to defaults clears it.
note

Saved settings are kept per browser and per address. Settings saved at http://localhost:3000 only load when the page is opened at that same address.

11.4 Troubleshooting​

ProblemLikely causeSolution
Failed to fetch, or CORS error in the browser's Network tabPage not served from http://localhost:3000Run python -m http.server 3000 and open http://localhost:3000
Auth failedWrong username, password or environmentCheck your credentials and the selected environment
Profile update failedMissing permission, or wrong Profile ID or Organization IDCheck the IDs and that your account can write TOU profiles (section 8.1)
Gateway update failedWrong Gateway ID, or the gateway belongs to another organizationCheck the Gateway (Molecule) ID and Organization ID
Validation errors in the logThe profile breaks a format ruleFix the field named in the message (sections 2 to 5)
warning

The test page sends your credentials from the browser directly to the identity server. Use it for development and testing only. For production integrations, obtain tokens server-side as described in API Authentication.