Back to Tasmota

Tasmota Developer Guide

.doc_for_ai/FOR_DEVELOPERS.md

15.4.033.7 KB
Original Source

Tasmota Developer Guide

This file is a summary of the Tasmota Documentation for the "docs" repository. It is provided here for convenience for GenAI to read it easily.

How Tasmota Works

Core Architecture

Tasmota is a modular firmware that transforms ESP8266/ESP8285 and ESP32 microcontrollers into intelligent IoT devices. The architecture follows these key principles:

1. Event-Driven System

  • Main loop processes events and callbacks
  • Non-blocking operations to maintain responsiveness
  • Callback system for sensors, drivers, and features
  • Timer-based scheduling for periodic tasks

2. Modular Design

  • Core functionality always present (WiFi, MQTT, web interface)
  • Optional features compiled conditionally using #define directives
  • Plugin architecture for sensors and peripherals
  • Template system for device configuration

3. Communication Hub

  • MQTT: Primary communication protocol for automation systems
  • HTTP: Web interface and REST API
  • Serial: Direct console access for debugging and configuration
  • WebSocket: Real-time web interface updates

Firmware Structure

tasmota/
├── tasmota.ino                    # Main firmware file
├── tasmota_xdrv_driver/           # Driver files directory (187 files)
│   ├── xdrv_01_9_webserver.ino   # Web server driver
│   ├── xdrv_02_9_mqtt.ino        # MQTT driver
│   ├── xdrv_04_light.ino         # Light driver
│   └── xdrv_##_name.ino          # Other drivers
├── tasmota_xsns_sensor/           # Sensor files directory (143 files)
│   ├── xsns_01_counter.ino       # Counter sensor
│   ├── xsns_02_analog.ino        # Analog sensor
│   └── xsns_##_name.ino          # Other sensors
├── tasmota_xlgt_light/            # Light driver files directory
├── tasmota_xnrg_energy/           # Energy monitoring files directory
├── tasmota_support/               # Support functions directory (29 files)
│   ├── support.ino                # Core support functions
│   ├── settings.ino               # Settings management
│   └── support_*.ino              # Other support modules
├── include/                       # Header files directory (18 files)
│   ├── tasmota.h                  # Main header
│   ├── tasmota_types.h            # Type definitions
│   ├── tasmota_globals.h          # Global variables
│   └── *.h                        # Other headers
└── my_user_config.h              # User configuration overrides

Command System

All Tasmota functionality is accessible through a unified command system:

  • Commands can be sent via MQTT, HTTP, serial, or web console
  • Format: Command [parameter]
  • Response format: JSON for structured data
  • Backlog support for multiple commands: Backlog cmd1; cmd2; cmd3

GPIO Management

Tasmota uses a flexible GPIO assignment system:

  1. Templates: Pre-defined GPIO configurations for specific devices
  2. Components: Logical functions assigned to physical pins
  3. Modules: Base hardware configurations
  4. Runtime Configuration: GPIO can be reassigned without recompilation

Development Environment Setup

Prerequisites

  1. PlatformIO: Primary build system
  2. Git: Version control
  3. Python: For build scripts and tools
  4. Serial Programmer: For initial flashing

Build Configuration

Create platformio_tasmota_cenv.ini for custom environments:

ini
[env:tasmota32-custom]
extends = env:tasmota32
build_flags = ${env:tasmota32.build_flags}
              -DUSE_MY_CUSTOM_FEATURE

User Configuration

Create tasmota/user_config_override.h:

c
#ifndef _USER_CONFIG_OVERRIDE_H_
#define _USER_CONFIG_OVERRIDE_H_

// Enable custom features
#define USE_CUSTOM_SENSOR
#define USE_BERRY_DEBUG

// Disable unused features to save space
#undef USE_DOMOTICZ
#undef USE_KNX

#endif

Driver Development

Sensor Driver Structure

All sensor drivers follow a standardized pattern:

c
#ifdef USE_MY_SENSOR
#define XSNS_XX  XX  // Unique sensor ID

bool MySensorDetected = false;

void MySensorInit(void) {
  // Initialize sensor
  if (sensor_detected) {
    MySensorDetected = true;
  }
}

void MySensorEverySecond(void) {
  // Read sensor data
}

void MySensorShow(bool json) {
  if (json) {
    ResponseAppend_P(PSTR(",\"MySensor\":{\"Temperature\":%d}"), temperature);
  }
#ifdef USE_WEBSERVER
  else {
    WSContentSend_PD(HTTP_SNS_TEMP, "MySensor", temperature);
  }
#endif
}

bool Xsns_XX(byte function) {
  bool result = false;
  
  if (i2c_flg) {  // Only for I2C sensors
    switch (function) {
      case FUNC_INIT:
        MySensorInit();
        break;
      case FUNC_EVERY_SECOND:
        MySensorEverySecond();
        break;
      case FUNC_JSON_APPEND:
        MySensorShow(1);
        break;
#ifdef USE_WEBSERVER
      case FUNC_WEB_SENSOR:
        MySensorShow(0);
        break;
#endif
    }
  }
  return result;
}
#endif  // USE_MY_SENSOR

Complete Driver Callback Functions Reference

VERIFIED FROM SOURCE CODE: tasmota/include/tasmota.h lines 433-454

Core System Callbacks (Functions WITHOUT return results)

FunctionPurposeWhen CalledParameters
FUNC_SETTINGS_OVERRIDEOverride default settingsBefore settings loadNone
FUNC_SETUP_RING1Early setup phase 1System initializationNone
FUNC_SETUP_RING2Early setup phase 2System initializationNone
FUNC_PRE_INITPre-initializationBefore main initNone
FUNC_INITInitialize driver/sensorOnce at startupNone
FUNC_ACTIVECheck if driver is activeStatus queriesNone
FUNC_ABOUT_TO_RESTARTPrepare for restartBefore system restartNone

Loop and Timing Callbacks

FunctionPurposeFrequencyParameters
FUNC_LOOPMain loop processingEvery loop cycle (~1ms)None
FUNC_SLEEP_LOOPSleep mode processingDuring sleep cyclesNone
FUNC_EVERY_50_MSECONDFast polling operationsEvery 50msNone
FUNC_EVERY_100_MSECONDMedium pollingEvery 100msNone
FUNC_EVERY_200_MSECONDSlower pollingEvery 200msNone
FUNC_EVERY_250_MSECONDQuarter second tasksEvery 250msNone
FUNC_EVERY_SECONDRegular updatesEvery secondNone

Settings and Configuration Callbacks

FunctionPurposeWhen CalledParameters
FUNC_RESET_SETTINGSReset to defaultsSettings resetNone
FUNC_RESTORE_SETTINGSRestore from backupSettings restoreNone
FUNC_SAVE_SETTINGSSave current settingsSettings saveNone
FUNC_SAVE_AT_MIDNIGHTMidnight save operationsDaily at 00:00None
FUNC_SAVE_BEFORE_RESTARTSave critical dataBefore restartNone

Interrupt and System Control

FunctionPurposeWhen CalledParameters
FUNC_INTERRUPT_STOPStop interruptsBefore critical sectionNone
FUNC_INTERRUPT_STARTResume interruptsAfter critical sectionNone
FUNC_FREE_MEMMemory cleanupLow memory conditionsNone

Telemetry and JSON Callbacks

FunctionPurposeWhen CalledParameters
FUNC_AFTER_TELEPERIODPost-telemetry cleanupAfter TelePeriodNone
FUNC_JSON_APPENDAdd JSON telemetryEvery TelePeriodNone
FUNC_TELEPERIOD_RULES_PROCESSRules after telemetryPost-TelePeriodNone

Web Interface Callbacks

FunctionPurposeWhen CalledParameters
FUNC_WEB_SENSORShow sensor on webSensor page loadNone
FUNC_WEB_COL_SENSORColumn sensor displayWeb page layoutNone
FUNC_WEB_ADD_BUTTONAdd web buttonsMain page loadNone
FUNC_WEB_ADD_CONSOLE_BUTTONAdd console buttonConsole pageNone
FUNC_WEB_ADD_MANAGEMENT_BUTTONAdd config buttonConfig pageNone
FUNC_WEB_ADD_MAIN_BUTTONAdd main menu buttonMain pageNone
FUNC_WEB_GET_ARGProcess web argumentsForm submissionNone
FUNC_WEB_ADD_HANDLERAdd URL handlersWeb server initNone
FUNC_WEB_STATUS_LEFTLeft status columnStatus pageNone
FUNC_WEB_STATUS_RIGHTRight status columnStatus pageNone

MQTT and Communication Callbacks

FunctionPurposeWhen CalledParameters
FUNC_MQTT_SUBSCRIBESubscribe to MQTT topicsMQTT connectNone
FUNC_MQTT_INITInitialize MQTTMQTT setupNone

Power and Hardware Control

FunctionPurposeWhen CalledParameters
FUNC_SET_POWERHandle power changesPower state changeNone
FUNC_SHOW_SENSORDisplay sensor dataStatus requestNone
FUNC_ANY_KEYHandle any key pressKey eventNone
FUNC_LED_LINKControl link LEDNetwork state changeNone
FUNC_ENERGY_EVERY_SECONDEnergy monitoringEvery secondNone
FUNC_ENERGY_RESETReset energy countersReset commandNone

Advanced System Callbacks

FunctionPurposeWhen CalledParameters
FUNC_SET_SCHEMESet color schemeTheme changeNone
FUNC_HOTPLUG_SCANScan for hotplug devicesDevice detectionNone
FUNC_TIME_SYNCEDTime synchronizationNTP sync completeNone
FUNC_DEVICE_GROUP_ITEMDevice group processingGroup operationsNone
FUNC_NETWORK_UPNetwork connectedWiFi/Ethernet upNone
FUNC_NETWORK_DOWNNetwork disconnectedWiFi/Ethernet downNone

Callback Functions WITH Return Results (ID >= 200)

These functions are expected to return boolean results:

FunctionPurposeWhen CalledReturn Value
FUNC_PIN_STATEGPIO state queryPin state checktrue if handled
FUNC_MODULE_INITModule initializationModule setuptrue if success
FUNC_ADD_BUTTONAdd button handlerButton configtrue if added
FUNC_ADD_SWITCHAdd switch handlerSwitch configtrue if added
FUNC_BUTTON_PRESSEDHandle button pressButton eventtrue if handled
FUNC_BUTTON_MULTI_PRESSEDMulti-button pressButton combotrue if handled
FUNC_SET_DEVICE_POWERDevice power controlPower commandtrue if handled
FUNC_MQTT_DATAProcess MQTT dataMQTT messagetrue if handled
FUNC_SERIALSerial data processingSerial inputtrue if handled
FUNC_COMMANDProcess commandsCommand receivedtrue if handled
FUNC_COMMAND_SENSORSensor commandsSensor commandtrue if handled
FUNC_COMMAND_DRIVERDriver commandsDriver commandtrue if handled
FUNC_RULES_PROCESSProcess rulesRule evaluationtrue if handled
FUNC_SET_CHANNELSSet PWM channelsChannel updatetrue if handled

Callback Implementation Pattern

c
bool Xdrv_XX(uint8_t function) {
  bool result = false;
  
  switch (function) {
    case FUNC_INIT:
      MyDriverInit();
      break;
    case FUNC_EVERY_SECOND:
      MyDriverEverySecond();
      break;
    case FUNC_COMMAND:
      result = MyDriverCommand();
      break;
    case FUNC_JSON_APPEND:
      MyDriverJsonAppend();
      break;
    case FUNC_WEB_SENSOR:
      MyDriverWebSensor();
      break;
    case FUNC_SAVE_BEFORE_RESTART:
      MyDriverSaveSettings();
      break;
  }
  return result;
}

### I2C Development

```c
// I2C Helper Functions
bool I2cValidRead8(uint8_t *data, uint8_t addr, uint8_t reg);
bool I2cValidRead16(uint16_t *data, uint8_t addr, uint8_t reg);
uint8_t I2cRead8(uint8_t addr, uint8_t reg);
uint16_t I2cRead16(uint8_t addr, uint8_t reg);
bool I2cWrite8(uint8_t addr, uint8_t reg, uint8_t val);

// Device Detection Pattern
void MySensorDetect(void) {
  if (MySensorDetected) return;
  
  for (uint8_t i = 0; i < SENSOR_MAX_ADDR; i++) {
    uint8_t addr = SENSOR_BASE_ADDR + i;
    if (I2cValidRead8(&sensor_id, addr, SENSOR_ID_REG)) {
      if (sensor_id == EXPECTED_ID) {
        MySensorDetected = true;
        AddLog(LOG_LEVEL_INFO, PSTR("MySensor found at 0x%02X"), addr);
        break;
      }
    }
  }
}

Scripting and Automation

Rules System

Rules provide event-driven automation:

Rule1 ON Switch1#State DO Power1 %value% ENDON
      ON Time#Minute=30 DO Publish stat/topic/alert {"time":"30min"} ENDON

Berry Scripting (ESP32)

Berry is a modern scripting language for advanced automation:

berry
# Simple sensor reading
import json

def read_sensor()
  var temp = tasmota.read_sensors()
  if temp.contains("Temperature")
    print("Current temperature:", temp["Temperature"])
  end
end

# Set up timer
tasmota.set_timer(5000, read_sensor)

# Web interface extension
def web_add_button()
  webserver.content_send("<button onclick='la(\"&m_toggle=1\");'>Toggle</button>")
end

tasmota.add_driver(web_add_button)

Command Extensions

Add custom commands through Berry or C++:

berry
def my_command(cmd, idx, payload)
  if cmd == "MYCMD"
    print("Custom command received:", payload)
    tasmota.resp_cmnd_done()
  end
end

tasmota.add_cmd('MYCMD', my_command)

Complete Settings Structure Reference

Settings Memory Layout

Tasmota uses a structured settings system stored in flash memory. The main settings structure is defined in settings.h:

c
typedef struct {
  unsigned long cfg_holder;                // 000 v6.0.0a
  unsigned long save_flag;                 // 004
  unsigned long version;                   // 008
  unsigned short flag;                     // 00C
  unsigned short save_data;                // 00E
  int8_t         timezone;                 // 010
  char           ota_url[101];             // 011
  char           mqtt_prefix[3][11];       // 076
  char           serial_delimiter;         // 09D
  uint8_t        seriallog_level;          // 09E
  uint8_t        sta_config;               // 09F
  char           sta_ssid[2][33];          // 0A0
  char           sta_pwd[2][65];           // 102
  char           hostname[33];             // 183
  char           syslog_host[33];          // 1A4
  uint16_t       syslog_port;              // 1C5
  uint8_t        syslog_level;             // 1C7
  uint8_t        webserver;                // 1C8
  uint8_t        weblog_level;             // 1C9
  char           mqtt_fingerprint[2][60];  // 1CA
  char           mqtt_host[33];            // 236
  uint16_t       mqtt_port;                // 257
  char           mqtt_client[33];          // 259
  char           mqtt_user[33];            // 27A
  char           mqtt_pwd[33];             // 29B
  char           mqtt_topic[33];           // 2BC
  char           button_topic[33];         // 2DD
  char           mqtt_grptopic[33];        // 2FE
  uint8_t        display_model;            // 31F
  uint8_t        display_mode;             // 320
  uint8_t        display_refresh;          // 321
  uint8_t        display_rows;             // 322
  uint8_t        display_cols[2];          // 323
  uint8_t        display_address[8];       // 325
  uint8_t        display_dimmer;           // 32D
  uint8_t        display_size;             // 32E
  uint16_t       pwm_frequency;            // 32F
  power_t        power;                    // 331
  uint16_t       pwm_value[MAX_PWMS];      // 335
  int16_t        altitude;                 // 345
  uint16_t       tele_period;              // 347
  uint8_t        ledstate;                 // 349
  uint8_t        param[PARAM_MAX];         // 34A
  int16_t        toffset[2];               // 35A
  uint8_t        display_font;             // 35E
} Settings;

### ESP8266 Constraints

- **Flash**: 1MB total, ~500KB available for firmware
- **RAM**: 80KB total, ~25-30KB available for application
- **Stack**: 4KB maximum

### Optimization Techniques

1. **Use PROGMEM for constants**:
```c
const char MyString[] PROGMEM = "Constant string";
  1. Minimize dynamic allocation:
c
// Avoid
String result = String(value1) + "," + String(value2);

// Prefer
char result[32];
snprintf(result, sizeof(result), "%d,%d", value1, value2);
  1. Use flash-efficient data types:
c
// Use uint32_t instead of uint8_t for local variables
// Use uint8_t only in structs to save memory

Communication Protocols

Command Context Structure

All command handlers receive context through the global XdrvMailbox structure:

c
struct XDRVMAILBOX {
  bool          grpflg;        // Group flag
  bool          usridx;        // User index flag
  uint16_t      command_code;  // Command code
  uint32_t      index;         // Command index
  uint32_t      data_len;      // Parameter length
  int32_t       payload;       // Numeric parameter
  char         *topic;         // MQTT topic
  char         *data;          // Command parameters
  char         *command;       // Command name
} XdrvMailbox;

Key Fields:

  • command: The command name (e.g., "Power", "Status")
  • data: Raw parameter string
  • payload: Numeric value of first parameter
  • data_len: Length of parameter string
  • index: Command index for numbered commands (Power1, Power2, etc.)

MQTT Integration

c
// Publish sensor data
void PublishSensorData(void) {
  Response_P(PSTR("{\"MySensor\":{\"Value\":%d}}"), sensor_value);
  MqttPublishTeleSensor();
}

// Subscribe to commands
bool MyCommand(void) {
  if (XdrvMailbox.data_len > 0) {
    // Process command
    ResponseCmndDone();
    return true;
  }
  ResponseCmndNumber(current_value);
  return true;
}

Web Interface Extensions

c
#ifdef USE_WEBSERVER
void MySensorWebShow(void) {
  WSContentSend_PD(PSTR(
    "{s}MySensor Temperature{m}%d°C{e}"
    "{s}MySensor Humidity{m}%d%%{e}"),
    temperature, humidity);
}
#endif

Advanced Features

Template System

Templates define device GPIO configurations:

json
{
  "NAME":"Custom Device",
  "GPIO":[416,0,418,0,417,2720,0,0,2624,32,2656,224,0,0],
  "FLAG":0,
  "BASE":45
}

Matter Protocol Support

For ESP32 devices, Matter provides standardized IoT communication:

c
// Matter endpoint configuration
matter.add_endpoint(1, 0x0100);  // On/Off Light
matter.add_endpoint(2, 0x0106);  // Light with dimming

Display Integration

Universal Display Driver supports 50+ display types:

DisplayModel 1    # Select display type
DisplayMode 1     # Text mode
DisplayText [s1l1]Hello World

Testing and Debugging

Debug Options

Enable debugging in user_config_override.h:

c
#define DEBUG_TASMOTA_CORE
#define DEBUG_TASMOTA_DRIVER
#define USE_DEBUG_DRIVER

Serial Debugging

c
AddLog(LOG_LEVEL_INFO, PSTR("Debug: value=%d"), value);
AddLog(LOG_LEVEL_DEBUG, PSTR("Detailed info: %s"), info_string);

Memory Monitoring

c
// Check free heap
uint32_t free_heap = ESP.getFreeHeap();
AddLog(LOG_LEVEL_DEBUG, PSTR("Free heap: %d"), free_heap);

Best Practices

Code Organization

  1. Use consistent naming: MySensor prefix for all functions
  2. Follow callback patterns: Implement standard driver callbacks
  3. Handle errors gracefully: Check return values and sensor presence
  4. Document thoroughly: Include usage examples and pin assignments

Performance Considerations

  1. Minimize blocking operations: Use state machines for long operations
  2. Cache sensor readings: Don't read sensors more often than necessary
  3. Use appropriate data types: Consider memory usage vs. precision
  4. Optimize for common cases: Fast path for normal operations

Security Guidelines

  1. Validate all inputs: Check command parameters and sensor data
  2. Use secure defaults: Enable security features by default
  3. Minimize attack surface: Disable unused network services
  4. Regular updates: Keep firmware and dependencies current

Integration Examples

Home Assistant Discovery

c
void PublishDiscovery(void) {
  Response_P(PSTR("{"
    "\"name\":\"%s MySensor\","
    "\"stat_t\":\"%s\","
    "\"unit_of_meas\":\"°C\","
    "\"dev_cla\":\"temperature\""
    "}"), SettingsText(SET_DEVICENAME), GetStateTopic());
  
  MqttPublish(GetDiscoveryTopic("sensor", "temperature"), true);
}

Custom Web Interface

c
const char HTTP_MYSENSOR[] PROGMEM =
  "{s}MySensor{m}"
  "<input type='range' min='0' max='100' value='%d' "
  "onchange='la(\"&mysensor_val=\"+this.value);'>"
  "{e}";

void MySensorWebShow(void) {
  WSContentSend_PD(HTTP_MYSENSOR, current_value);
}

This guide provides the foundation for understanding and extending Tasmota. The modular architecture, standardized APIs, and extensive documentation make it an excellent platform for IoT development, whether you're adding simple sensor support or implementing complex automation systems.

Complete Command Reference

Core System Commands

CommandParametersDescriptionExample
Status0-11System status informationStatus 0
Reset1-6Reset device with optionsReset 1
Restart1Restart deviceRestart 1
Upgrade1Start OTA upgradeUpgrade 1
Upload1Start file uploadUpload 1
OtaurlurlSet OTA URLOtaurl http://ota.server/firmware.bin
Seriallog0-4Set serial log levelSeriallog 2
Syslog0-4Set syslog levelSyslog 2
LoghosthostnameSet syslog hostLoghost 192.168.1.100
LogportportSet syslog portLogport 514
Ipaddressx.x.x.xSet IP addressIpaddress 192.168.1.100
Gatewayx.x.x.xSet gatewayGateway 192.168.1.1
Subnetmaskx.x.x.xSet subnet maskSubnetmask 255.255.255.0
Dnsserverx.x.x.xSet DNS serverDnsserver 8.8.8.8
Mac-Show MAC addressMac
HostnamenameSet hostnameHostname tasmota-device

WiFi Commands

CommandParametersDescriptionExample
Ssid1ssidSet WiFi SSID 1Ssid1 MyNetwork
Ssid2ssidSet WiFi SSID 2Ssid2 BackupNetwork
Password1passwordSet WiFi password 1Password1 MyPassword
Password2passwordSet WiFi password 2Password2 BackupPassword
Ap0-2Set AP modeAp 1
WebServer0-2Enable web serverWebServer 1
WebPasswordpasswordSet web passwordWebPassword admin
WifiConfig0-7WiFi configuration modeWifiConfig 4

MQTT Commands

CommandParametersDescriptionExample
MqttHosthostnameSet MQTT brokerMqttHost 192.168.1.100
MqttPortportSet MQTT portMqttPort 1883
MqttUserusernameSet MQTT usernameMqttUser myuser
MqttPasswordpasswordSet MQTT passwordMqttPassword mypass
MqttClientclientidSet MQTT client IDMqttClient tasmota-device
TopictopicSet MQTT topicTopic tasmota
GroupTopictopicSet group topicGroupTopic tasmotas
FullTopictemplateSet full topic templateFullTopic %prefix%/%topic%/
Prefix1prefixSet command prefixPrefix1 cmnd
Prefix2prefixSet status prefixPrefix2 stat
Prefix3prefixSet telemetry prefixPrefix3 tele
Publishtopic payloadPublish MQTT messagePublish stat/topic/test Hello
MqttRetrysecondsSet MQTT retry timeMqttRetry 10
StateText1textSet OFF state textStateText1 OFF
StateText2textSet ON state textStateText2 ON
StateText3textSet TOGGLE state textStateText3 TOGGLE
StateText4textSet HOLD state textStateText4 HOLD

Power and Relay Commands

CommandParametersDescriptionExample
Power0/1/2Control main powerPower 1
Power10/1/2Control power 1Power1 ON
Power20/1/2Control power 2Power2 OFF
Power30/1/2Control power 3Power3 TOGGLE
Power40/1/2Control power 4Power4 1
PowerOnState0-4Set power on statePowerOnState 1
PulseTime1-111Set pulse timePulseTime1 10
BlinkTime2-3600Set blink timeBlinkTime 10
BlinkCount0-32000Set blink countBlinkCount 5
Interlock0/1Enable interlockInterlock 1
Ledstate0-8Set LED stateLedstate 1
LedPower0-2Control LED powerLedPower 1
LedMaskhexSet LED maskLedMask 0xFF00

Sensor Commands

CommandParametersDescriptionExample
TelePeriod10-3600Set telemetry periodTelePeriod 300
Resolution0-3Set sensor resolutionResolution 2
HumRes0-3Set humidity resolutionHumRes 1
TempRes0-3Set temperature resolutionTempRes 2
PressRes0-3Set pressure resolutionPressRes 1
EnergyRes0-5Set energy resolutionEnergyRes 3
SpeedUnit1-4Set speed unitSpeedUnit 1
WeightRes0-3Set weight resolutionWeightRes 2
FreqRes0-3Set frequency resolutionFreqRes 2

Timer Commands

CommandParametersDescriptionExample
Timer1parametersConfigure timer 1Timer1 {"Enable":1,"Time":"06:00","Days":"1111100","Repeat":1,"Action":1}
Timer2parametersConfigure timer 2Timer2 {"Enable":1,"Time":"22:00","Action":0}
Timers0/1Enable/disable timersTimers 1
LatitudedegreesSet latitudeLatitude 52.520008
LongitudedegreesSet longitudeLongitude 13.404954
Sunrise-Show sunrise timeSunrise
Sunset-Show sunset timeSunset

GPIO and Template Commands

CommandParametersDescriptionExample
Gpiopin,functionSet GPIO functionGpio 14,21
Gpios-Show GPIO configurationGpios
TemplatejsonSet device templateTemplate {"NAME":"Generic","GPIO":[255,255,255,255,255,255,255,255,255,255,255,255,255],"FLAG":1,"BASE":18}
Module0-255Set device moduleModule 1
Modules-Show available modulesModules
I2CScan-Scan I2C busI2CScan
I2CDriverdriverEnable I2C driverI2CDriver10 1

Display Commands

CommandParametersDescriptionExample
Display-Show display infoDisplay
DisplayModel1-16Set display modelDisplayModel 2
DisplayMode0-5Set display modeDisplayMode 1
DisplayDimmer0-100Set display brightnessDisplayDimmer 50
DisplaySize1-4Set display sizeDisplaySize 2
DisplayRotate0-3Set display rotationDisplayRotate 2
DisplayTexttextDisplay textDisplayText [s1l1]Hello World
DisplayClear-Clear displayDisplayClear

Rule Commands

CommandParametersDescriptionExample
Rule1ruleSet rule 1Rule1 ON Switch1#State DO Power1 %value% ENDON
Rule2ruleSet rule 2Rule2 ON Time#Minute=30 DO Publish stat/alert 30min ENDON
Rule3ruleSet rule 3Rule3 ON Button1#State DO Backlog Power1 TOGGLE; Delay 10; Power2 TOGGLE ENDON
RuleTimer10-3600Set rule timer 1RuleTimer1 60
RuleTimer20-3600Set rule timer 2RuleTimer2 120
Mem1valueSet memory 1Mem1 Hello
Mem2valueSet memory 2Mem2 World
Var1valueSet variable 1Var1 42
Var2valueSet variable 2Var2 3.14
CalcRes0-7Set calculation resolutionCalcRes 2

Berry Script Commands (ESP32)

CommandParametersDescriptionExample
BrcodeExecute Berry codeBr print("Hello")
BrLoadfilenameLoad Berry fileBrLoad autoexec.be
BrRunfilenameRun Berry fileBrRun script.be
BrRestart-Restart Berry VMBrRestart

Energy Monitoring Commands

CommandParametersDescriptionExample
PowerCalvalueCalibrate powerPowerCal 12530
VoltageCalvalueCalibrate voltageVoltageCal 1950
CurrentCalvalueCalibrate currentCurrentCal 3500
PowerSetwattsSet power readingPowerSet 100
VoltageSetvoltsSet voltage readingVoltageSet 230
CurrentSetampsSet current readingCurrentSet 0.43
FrequencySethzSet frequency readingFrequencySet 50
EnergyReset1kWhReset energy totalEnergyReset1 0
EnergyReset2kWhReset energy yesterdayEnergyReset2 0
EnergyReset3kWhReset energy todayEnergyReset3 0
MaxPowerwattsSet max powerMaxPower 3500
MaxPowerHoldsecondsSet max power holdMaxPowerHold 10
MaxPowerWindowsecondsSet max power windowMaxPowerWindow 30
SafePowerwattsSet safe powerSafePower 3000
SafePowerHoldsecondsSet safe power holdSafePowerHold 10
SafePowerWindowsecondsSet safe power windowSafePowerWindow 30

Complete Logging and Debug Reference

Log Levels

c
#define LOG_LEVEL_NONE     0  // No logging
#define LOG_LEVEL_ERROR    1  // Critical errors only
#define LOG_LEVEL_INFO     2  // Errors and info
#define LOG_LEVEL_DEBUG    3  // Errors, info and debug
#define LOG_LEVEL_DEBUG_MORE 4  // All logging

Logging Functions

c
// Main logging function
void AddLog(uint32_t loglevel, const char* formatP, ...);

// Convenience macros
#define AddLog_P(loglevel, formatP, ...) AddLog(loglevel, PSTR(formatP), ##__VA_ARGS__)
#define AddLog_P2(loglevel, formatP, ...) AddLog(loglevel, formatP, ##__VA_ARGS__)

// Debug logging (only in debug builds)
#ifdef DEBUG_TASMOTA_CORE
  #define DEBUG_CORE_LOG(...) AddLog(__VA_ARGS__)
#else
  #define DEBUG_CORE_LOG(...)
#endif

#ifdef DEBUG_TASMOTA_DRIVER  
  #define DEBUG_DRIVER_LOG(...) AddLog(__VA_ARGS__)
#else
  #define DEBUG_DRIVER_LOG(...)
#endif

#ifdef DEBUG_TASMOTA_SENSOR
  #define DEBUG_SENSOR_LOG(...) AddLog(__VA_ARGS__)
#else
  #define DEBUG_SENSOR_LOG(...)
#endif

Debug Build Options

c
// Enable in user_config_override.h for debugging
#define DEBUG_TASMOTA_CORE        // Core system debugging
#define DEBUG_TASMOTA_DRIVER      // Driver debugging  
#define DEBUG_TASMOTA_SENSOR      // Sensor debugging
#define USE_DEBUG_DRIVER          // Enable debug driver
#define DEBUG_TASMOTA_PORT Serial // Debug output port

Memory Debugging

c
// Memory monitoring functions
uint32_t ESP_getFreeHeap(void);
uint32_t ESP_getMaxAllocHeap(void);
uint8_t ESP_getHeapFragmentation(void);
uint32_t ESP_getFreeContStack(void);

// Memory debugging macros
#define SHOW_FREE_MEM(x) AddLog(LOG_LEVEL_DEBUG, PSTR(x " free mem: %d"), ESP_getFreeHeap())
#define CHECK_OOM() if (ESP_getFreeHeap() < 1000) AddLog(LOG_LEVEL_ERROR, PSTR("Low memory: %d"), ESP_getFreeHeap())

Complete I2C Reference

I2C Configuration

c
// I2C pins (can be changed via GPIO configuration)
#define I2C_SDA_PIN 4   // Default SDA pin
#define I2C_SCL_PIN 5   // Default SCL pin

// I2C speeds
#define I2C_SPEED_SLOW    50000   // 50kHz
#define I2C_SPEED_STANDARD 100000 // 100kHz  
#define I2C_SPEED_FAST    400000  // 400kHz
#define I2C_SPEED_FAST_PLUS 1000000 // 1MHz

I2C Helper Functions

c
// Basic I2C operations
bool I2cValidRead(uint8_t addr, uint8_t reg, uint8_t size);
bool I2cValidRead8(uint8_t *data, uint8_t addr, uint8_t reg);
bool I2cValidRead16(uint16_t *data, uint8_t addr, uint8_t reg);
bool I2cValidRead16LE(uint16_t *data, uint8_t addr, uint8_t reg);
bool I2cValidRead24(int32_t *data, uint8_t addr, uint8_t reg);
bool I2cValidReadS32(int32_t *data, uint8_t addr, uint8_t reg);
bool I2cValidReadS32_LE(int32_t *data, uint8_t addr, uint8_t reg);

uint8_t I2cRead8(uint8_t addr, uint8_t reg);
uint16_t I2cRead16(uint8_t addr, uint8_t reg);
uint16_t I2cRead16LE(uint8_t addr, uint8_t reg);
int32_t I2cRead24(uint8_t addr, uint8_t reg);
int32_t I2cReadS32(uint8_t addr, uint8_t reg);
int32_t I2cReadS32_LE(uint8_t addr, uint8_t reg);

bool I2cWrite8(uint8_t addr, uint8_t reg, uint8_t val);
bool I2cWrite16(uint8_t addr, uint8_t reg, uint16_t val);
bool I2cWrite16LE(uint8_t addr, uint8_t reg, uint16_t val);

// Buffer operations
uint8_t I2cReadBuffer(uint8_t addr, uint8_t reg, uint8_t *data, uint16_t len);
uint8_t I2cWriteBuffer(uint8_t addr, uint8_t reg, uint8_t *data, uint16_t len);

// Device detection
bool I2cActive(uint8_t addr);
void I2cScan(char *devs, unsigned int devs_len);
void I2cResetActive(uint8_t addr, uint8_t count = 1);
void I2cSetActive(uint8_t addr, uint8_t count = 1);
void I2cSetActiveFound(uint8_t addr, const char *types);

I2C Device Detection Pattern

c
void MySensorDetect(void) {
  if (MySensorDetected) return;
  
  for (uint32_t i = 0; i < SENSOR_MAX_ADDR; i++) {
    uint8_t addr = SENSOR_BASE_ADDR + i;
    if (I2cActive(addr)) continue;  // Address already in use
    
    if (I2cValidRead8(&sensor_id, addr, SENSOR_ID_REG)) {
      if (sensor_id == EXPECTED_SENSOR_ID) {
        I2cSetActiveFound(addr, "MySensor");
        MySensorDetected = true;
        MySensorAddress = addr;
        AddLog(LOG_LEVEL_INFO, PSTR("MySensor found at address 0x%02X"), addr);
        break;
      }
    }
  }
}

This comprehensive developer reference provides all the essential information needed to understand, extend, and debug Tasmota firmware. The detailed callback system, complete command reference, GPIO configuration options, and debugging tools give developers everything needed to create robust IoT solutions.