3 Commits

Author SHA1 Message Date
JonatanRek
dcc8f97639 Fixes 2026-04-07 18:25:58 +02:00
JonatanRek
3159d4c875 Fixes 2026-04-07 09:35:29 +02:00
JonatanRek
270a92ba06 Refactor Marlin2 component and add new features
- Updated __init__.py to include max_sd_files configuration option.
- Refactored Marlin2 class to use new namespaces and improved structure.
- Added support for binary sensors and select components in binary_sensor.py and select.py.
- Enhanced sensor.py and text_sensor.py to include new configuration options for SD card file count and selected file.
- Improved code readability and organization across multiple files.
2026-04-07 08:19:25 +02:00
8 changed files with 466 additions and 459 deletions

View File

@@ -3,71 +3,42 @@ import esphome.config_validation as cv
from esphome.components import uart from esphome.components import uart
from esphome.const import ( from esphome.const import (
CONF_ID, CONF_ID,
CONF_INDEX, CONF_VALUE,
CONF_SENSORS,
CONF_HUMIDITY,
CONF_MODEL,
CONF_PIN,
CONF_TEMPERATURE,
UNIT_CELSIUS,
UNIT_PERCENT,
UNIT_SECOND,
STATE_CLASS_MEASUREMENT,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_DURATION,
CONF_DATA,
CONF_VALUE
) )
from esphome import pins, automation from esphome import automation
from esphome.core import CORE, coroutine_with_priority from esphome.core import coroutine_with_priority
CODEOWNERS = ["@jonatanrek"] CODEOWNERS = ["@jonatanrek"]
DEPENDENCIES = ['uart'] DEPENDENCIES = ["uart"]
CONF_MARLIN2_ID = "marlin2_id" MULTI_CONF = False
Marlin2 = cg.esphome_ns.class_('Marlin2', cg.Component) CONF_MARLIN2_ID = "marlin2_id"
WriteAction = cg.esphome_ns.class_("WriteAction", automation.Action) CONF_MAX_SD_FILES = "max_sd_files"
PrintFileAction = cg.esphome_ns.class_("PrintFileAction", automation.Action)
marlin2_ns = cg.esphome_ns.namespace("marlin2")
Marlin2 = marlin2_ns.class_("Marlin2", cg.PollingComponent, uart.UARTDevice)
WriteAction = marlin2_ns.class_("WriteAction", automation.Action)
PrintFileAction = marlin2_ns.class_("PrintFileAction", automation.Action)
CONFIG_SCHEMA = cv.All( CONFIG_SCHEMA = cv.All(
cv.Schema({ cv.Schema({
cv.GenerateID(): cv.declare_id(Marlin2), cv.GenerateID(): cv.declare_id(Marlin2),
cv.Optional(CONF_MAX_SD_FILES, default=20): cv.int_range(min=1, max=255),
}) })
.extend(cv.COMPONENT_SCHEMA) .extend(cv.COMPONENT_SCHEMA)
.extend(uart.UART_DEVICE_SCHEMA), .extend(uart.UART_DEVICE_SCHEMA),
) )
def validate_raw_data(value):
if isinstance(value, str):
return value.encode("utf-8")
if isinstance(value, str):
return value
if isinstance(value, list):
return cv.Schema([cv.hex_uint8_t])(value)
raise cv.Invalid("data must either be a string wrapped in quotes or a list of bytes")
@coroutine_with_priority(100.0)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await uart.register_uart_device(var, config)
OPERATION_BASE_SCHEMA = cv.Schema({ OPERATION_BASE_SCHEMA = cv.Schema({
cv.GenerateID(): cv.use_id(Marlin2), cv.GenerateID(): cv.use_id(Marlin2),
cv.Required(CONF_VALUE): cv.templatable(cv.string_strict), cv.Required(CONF_VALUE): cv.templatable(cv.string_strict),
}) })
OPERATION_BASE_SCHEMA_2 = cv.Schema({
cv.GenerateID(): cv.use_id(Marlin2),
cv.Required(CONF_VALUE): cv.templatable(cv.string_strict),
})
@automation.register_action( @automation.register_action(
"marlin2.write", "marlin2.write",
WriteAction, WriteAction,
OPERATION_BASE_SCHEMA, OPERATION_BASE_SCHEMA,
) )
async def marlin2_write_to_code(config, action_id, template_arg, args): async def marlin2_write_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID]) paren = await cg.get_variable(config[CONF_ID])
var = cg.new_Pvariable(action_id, template_arg, paren) var = cg.new_Pvariable(action_id, template_arg, paren)
@@ -78,7 +49,7 @@ async def marlin2_write_to_code(config, action_id, template_arg, args):
@automation.register_action( @automation.register_action(
"marlin2.print_file", "marlin2.print_file",
PrintFileAction, PrintFileAction,
OPERATION_BASE_SCHEMA_2, OPERATION_BASE_SCHEMA,
) )
async def marlin2_print_file_to_code(config, action_id, template_arg, args): async def marlin2_print_file_to_code(config, action_id, template_arg, args):
paren = await cg.get_variable(config[CONF_ID]) paren = await cg.get_variable(config[CONF_ID])
@@ -86,3 +57,10 @@ async def marlin2_print_file_to_code(config, action_id, template_arg, args):
template_ = await cg.templatable(config[CONF_VALUE], args, cg.std_string) template_ = await cg.templatable(config[CONF_VALUE], args, cg.std_string)
cg.add(var.set_value(template_)) cg.add(var.set_value(template_))
return var return var
@coroutine_with_priority(100.0)
async def to_code(config):
var = cg.new_Pvariable(config[CONF_ID])
await cg.register_component(var, config)
await uart.register_uart_device(var, config)
cg.add(var.set_max_sd_files(config[CONF_MAX_SD_FILES]))

View File

@@ -4,8 +4,7 @@
#include "esphome/core/component.h" #include "esphome/core/component.h"
#include "marlin2.h" #include "marlin2.h"
namespace esphome { namespace esphome::marlin2 {
static const char *TAG = "marlin2";
template<typename... Ts> class WriteAction : public Action<Ts...> { template<typename... Ts> class WriteAction : public Action<Ts...> {
public: public:
@@ -27,6 +26,7 @@ namespace esphome {
TEMPLATABLE_VALUE(std::string, value) TEMPLATABLE_VALUE(std::string, value)
void play(Ts... x) override { void play(Ts... x) override {
static const char *const TAG = "marlin2";
std::string file_name = this->marlin2_->to_dos_name(this->value_.value(x...)); std::string file_name = this->marlin2_->to_dos_name(this->value_.value(x...));
ESP_LOGD(TAG, "->FILE: %s", file_name.c_str()); ESP_LOGD(TAG, "->FILE: %s", file_name.c_str());
this->marlin2_->write(str_sprintf("M32 P !%s#", file_name.c_str())); this->marlin2_->write(str_sprintf("M32 P !%s#", file_name.c_str()));
@@ -35,4 +35,5 @@ namespace esphome {
protected: protected:
Marlin2 *marlin2_; Marlin2 *marlin2_;
}; };
} // namespace esphome
} // namespace esphome::marlin2

26
binary_sensor.py Normal file
View File

@@ -0,0 +1,26 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import (
DEVICE_CLASS_CONNECTIVITY,
)
from . import Marlin2
CONF_MARLIN = "marlin2"
CONF_SD_CARD_PRESENT = "sd_card_present"
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(CONF_MARLIN): cv.use_id(Marlin2),
cv.Optional(CONF_SD_CARD_PRESENT): binary_sensor.binary_sensor_schema(
device_class=DEVICE_CLASS_CONNECTIVITY,
),
}
).extend(cv.polling_component_schema("15s"))
async def to_code(config):
server = await cg.get_variable(config[CONF_MARLIN])
if CONF_SD_CARD_PRESENT in config:
bs = await binary_sensor.new_binary_sensor(config[CONF_SD_CARD_PRESENT])
cg.add(server.add_binary_sensor(CONF_SD_CARD_PRESENT, bs))

View File

@@ -1,417 +1,363 @@
#include "marlin2.h" #include "marlin2.h"
#include "esphome/core/log.h" #include "esphome/core/log.h"
#include <string>
namespace esphome { namespace esphome::marlin2 {
static const char *TAG = "marlin2"; static const char *TAG = "marlin2";
// ── Entity registration ───────────────────────────────────────────────────
#ifdef USE_SENSOR #ifdef USE_SENSOR
void Marlin2::add_sensor(const std::string& sName, sensor::Sensor *sens) { void Marlin2::add_sensor(const std::string &name, sensor::Sensor *sens) {
sensors.push_back({sName, sens}); sensors_.push_back({name, sens});
} }
sensor::Sensor* Marlin2::find_sensor(std::string key) { void Marlin2::publish_sensor(const std::string &key, float value) {
for (const auto& pair : sensors) { auto *s = find_in_(sensors_, key);
if (key == std::string(pair.first)) { // Convert char* to std::string for comparison if (s != nullptr && s->get_state() != value)
return pair.second; s->publish_state(value);
}
}
return nullptr; // Return nullptr if no match is found
} }
#endif #endif
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
void Marlin2::add_text_sensor(const std::string& sName, text_sensor::TextSensor *sens) { void Marlin2::add_text_sensor(const std::string &name, text_sensor::TextSensor *sens) {
text_sensors.push_back({sName, sens}); text_sensors_.push_back({name, sens});
} }
text_sensor::TextSensor* Marlin2::find_text_sensor(std::string key) { void Marlin2::publish_text_sensor(const std::string &key, const std::string &value) {
for (const auto& pair : text_sensors) { auto *s = find_in_(text_sensors_, key);
if (key == std::string(pair.first)) { // Convert char* to std::string for comparison if (s != nullptr && s->get_state() != value)
return pair.second; s->publish_state(value);
}
}
return nullptr; // Return nullptr if no match is found
} }
#endif #endif
#ifdef USE_SELECT
void Marlin2::add_select(const std::string &name, select::Select *sel) {
selects_.push_back({name, sel});
}
#endif
#ifdef USE_BINARY_SENSOR
void Marlin2::add_binary_sensor(const std::string &name, binary_sensor::BinarySensor *bs) {
binary_sensors_.push_back({name, bs});
}
void Marlin2::publish_binary_sensor(const std::string &key, bool value) {
auto *s = find_in_(binary_sensors_, key);
if (s != nullptr && s->state != value)
s->publish_state(value);
}
#endif
// ── Lifecycle ─────────────────────────────────────────────────────────────
void Marlin2::setup() { void Marlin2::setup() {
MarlinOutput.reserve(256); marlin_output_.reserve(256);
MarlinOutput = ""; marlin_time_.reserve(32);
MarlinResponseOutput.reserve(256);
MarlinResponseOutput = "";
MarlinTime.reserve(32);
PrinterState.reserve(32);
//ESP_LOGD(TAG, "M155 S10");
write_str("\r\n\r\nM155 S10\r\n"); write_str("\r\n\r\nM155 S10\r\n");
write_str("\r\n\r\nM117 ESP Home Connected!\r\n"); write_str("\r\n\r\nM117 ESP Home Connected!\r\n");
flush(); flush();
set_printer_state("IDLE"); set_printer_state("IDLE");
set_interval(15000, [this]() {
if (print_progress_ != 100)
write_str("M27\r\nM31\r\n");
});
} }
void Marlin2::write(std::string gcode) { void Marlin2::loop() {
while (available()) {
char c = read();
if (c == '\n' || c == '\r') {
process_line();
} else {
marlin_output_ += c;
}
}
}
void Marlin2::dump_config() {
ESP_LOGCONFIG(TAG, "Marlin2:");
this->check_uart_settings(115200);
}
// ── G-code output ─────────────────────────────────────────────────────────
void Marlin2::write(const std::string &gcode) {
ESP_LOGD(TAG, "->GCODE: %s", gcode.c_str()); ESP_LOGD(TAG, "->GCODE: %s", gcode.c_str());
write_str((std::string("\r\n\r\n") + gcode + std::string("\r\n")).c_str()); write_str(("\r\n\r\n" + gcode + "\r\n").c_str());
flush(); flush();
} }
void Marlin2::update() { // ── Line parsing ──────────────────────────────────────────────────────────
while (available()) {
char c = read();
if( c == '\n' || c == '\r' ) {
//ESP_LOGD(TAG, "#%s#",MarlinOutput.c_str());
process_line();
} else {
MarlinOutput += c;
}
}
if(millis() - millisProgress > 15000 && print_progress != 100) {
millisProgress = millis();
//ESP_LOGD(TAG, "M27");
//ESP_LOGD(TAG, "M31");
write_str("M27\r\nM31\r\n");
}
}
void Marlin2::process_line() { void Marlin2::process_line() {
if(MarlinOutput.size() < 3) { if (marlin_output_.size() < 3) {
MarlinOutput=""; marlin_output_ = "";
return; return;
} }
if(MarlinOutput.compare("ok") == 0 || MarlinOutput.compare(" ok") == 0) { if (marlin_output_.compare("ok") == 0 || marlin_output_.compare(" ok") == 0) {
listingFile = false; listing_file_ = false;
MarlinOutput=""; marlin_output_ = "";
return; return;
} }
ESP_LOGD(TAG, "DEBUG>#%s#", marlin_output_.c_str());
ESP_LOGD(TAG, "DEBUG>#%s#",MarlinOutput.c_str()); if (!listing_file_ && marlin_output_.compare("Begin file list") == 0) {
if(!listingFile && MarlinOutput.compare("Begin file list") == 0) {
ESP_LOGD(TAG, "Listing of files started!"); ESP_LOGD(TAG, "Listing of files started!");
listingFile = true; listing_file_ = true;
//reset string for next line file_table_.clear();
MarlinOutput=""; marlin_output_ = "";
return; return;
} }
if(listingFile && MarlinOutput.compare("End file list") == 0) { if (listing_file_ && marlin_output_.compare("End file list") == 0) {
ESP_LOGD(TAG, "Listing of files stopped!"); ESP_LOGD(TAG, "Listing of files stopped!");
listingFile = false; listing_file_ = false;
//reset string for next line publish_sd_files();
#ifdef USE_BINARY_SENSOR
#ifdef USE_TEXT_SENSOR publish_binary_sensor("sd_card_present", true);
std::string sd_files;
for (const auto& [key, value] : file_table_) {
if (!sd_files.empty()) sd_files += "|";
sd_files += key;
}
if (find_text_sensor("sd_card_files") != nullptr){
ESP_LOGD(TAG, "SD Files: %s", sd_files.c_str());
find_text_sensor("sd_card_files")->publish_state(sd_files.c_str());
}
#endif #endif
#ifdef USE_SENSOR
MarlinOutput=""; publish_sensor("sd_card_file_count", static_cast<float>(file_table_.size()));
#endif
marlin_output_ = "";
return; return;
} }
if(listingFile && MarlinOutput.find(".GCO ") > 1) { if (listing_file_ && marlin_output_.find(".GCO ") > 1) {
int first_space = MarlinOutput.find(' '); size_t first_space = marlin_output_.find(' ');
int second_space = MarlinOutput.find(' ', first_space + 1); size_t second_space = marlin_output_.find(' ', first_space + 1);
if(first_space > 0) { if (first_space != std::string::npos) {
std::string short_name = MarlinOutput.substr(0, first_space); std::string short_name = marlin_output_.substr(0, first_space);
if (short_name.find("/") != std::string::npos){ // Omit subdirectories if (short_name.find("/") != std::string::npos) {
ESP_LOGD(TAG, "peskočeno kvůli vnořen %s",short_name.c_str()); ESP_LOGD(TAG, "Skipping subdirectory: %s", short_name.c_str());
MarlinOutput=""; marlin_output_ = "";
return; return;
} }
std::string long_name = short_name; std::string long_name = (second_space != std::string::npos && second_space > first_space)
? marlin_output_.substr(second_space + 1)
if (second_space > first_space){ : short_name;
long_name = MarlinOutput.substr(second_space + 1);
}
file_table_[long_name] = short_name; file_table_[long_name] = short_name;
} }
//reset string for next line marlin_output_ = "";
MarlinOutput="";
return; return;
} }
//Parse periodic Temperature read out message // Temperature report: T:xx/xx B:xx/xx
if( if (
MarlinOutput.find(" T:") == 0 || marlin_output_.find(" T:") == 0 ||
MarlinOutput.find("T:") == 0 || marlin_output_.find("T:") == 0 ||
MarlinOutput.find("ok T:") == 0 || marlin_output_.find("ok T:") == 0 ||
MarlinOutput.find(" ok T:") == 0 marlin_output_.find(" ok T:") == 0
) { ) {
float ext_temperature, ext_set_temperature, bed_temperature, bed_set_temperature; float ext_temp, ext_set, bed_temp, bed_set;
if (process_temp_msg(&ext_temperature, &ext_set_temperature, &bed_temperature, &bed_set_temperature) != 0) { if (process_temp_msg(&ext_temp, &ext_set, &bed_temp, &bed_set) != 0) {
#ifdef USE_SENSOR #ifdef USE_SENSOR
if (find_sensor("bed_temperature") != nullptr) publish_sensor("bed_temperature", bed_temp);
find_sensor("bed_temperature")->publish_state(bed_temperature); publish_sensor("bed_set_temperature", bed_set);
publish_sensor("ext_temperature", ext_temp);
if (find_sensor("bed_set_temperature") != nullptr) publish_sensor("ext_set_temperature", ext_set);
find_sensor("bed_set_temperature")->publish_state(bed_set_temperature);
if (find_sensor("ext_temperature") != nullptr)
find_sensor("ext_temperature")->publish_state(ext_temperature);
if (find_sensor("ext_set_temperature") != nullptr)
find_sensor("ext_set_temperature")->publish_state(ext_set_temperature);
#endif #endif
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
if(bed_set_temperature==0.0 && ext_set_temperature==0.0) { if (bed_set == 0.0f && ext_set == 0.0f) {
if(ext_temperature < 32.0 && bed_temperature < 32.0){ //TODO define constants for these if (ext_temp < 32.0f && bed_temp < 32.0f)
set_printer_state("IDLE"); set_printer_state("IDLE");
} else if (ext_temp < 150.0f && bed_temp < 55.0f)
else if(ext_temperature < 150.0 && bed_temperature < 55.0){
set_printer_state("COOLING"); set_printer_state("COOLING");
} }
} if (print_progress_ == 0.0f && (bed_set != 0.0f || ext_set != 0.0f))
if(print_progress == 0.0 && (bed_set_temperature!=0.0 || ext_set_temperature!=0.0)) {
//print_time_offset = print_time save print time ofset to deduct from total value send to hass
set_printer_state("PREHEATING"); set_printer_state("PREHEATING");
}
#endif #endif
//ESP_LOGD(TAG, "Bed Temperature=%.1f°C Ext Temperature=%.1f°C ", bed_temperature, ext_temperature);
} }
marlin_output_ = "";
//reset string for next line
MarlinOutput="";
return; return;
} }
//Parse Progress of the print // Print progress: SD printing byte X/Y
if(MarlinOutput.find("SD printing byte") == 0 ) { if (marlin_output_.find("SD printing byte") == 0) {
print_progress = process_progress_msg(); print_progress_ = process_progress_msg();
#ifdef USE_SENSOR #ifdef USE_SENSOR
if (find_sensor("print_progress") != nullptr) publish_sensor("print_progress", print_progress_);
find_sensor("print_progress")->publish_state(print_progress);
//ESP_LOGD(TAG, "progress=%.1f", print_progress);
#endif #endif
set_printer_state("PRINTING"); set_printer_state("PRINTING");
//reset string for next line marlin_output_ = "";
MarlinOutput="";
return; return;
} }
//Parse Printitme // Print time: echo:Print time: Xh Xm Xs
if(MarlinOutput.find("echo:Print time: ") == 0) { if (marlin_output_.find("echo:Print time: ") == 0) {
double current=0; double current = 0, remaining = 0;
double remaining=0; if (process_print_time_msg(&current, &remaining, print_progress_) != 0) {
if (process_print_time_msg(&current, &remaining, print_progress) != 0) {
#ifdef USE_SENSOR #ifdef USE_SENSOR
if (find_sensor("print_time") != nullptr) publish_sensor("print_time", static_cast<float>(current));
find_sensor("print_time")->publish_state(current); publish_sensor("print_time_remaining", static_cast<float>(remaining));
if (find_sensor("print_time_remaining") != nullptr)
find_sensor("print_time_remaining")->publish_state(remaining);
#endif #endif
//ESP_LOGD(TAG, "time=%f remaining=%f", current, remaining);
} }
marlin_output_ = "";
//reset string for next line
MarlinOutput="";
return; return;
} }
//File opened: salma_~2.gco Size: 12279971 // File opened: SALMA_~2.GCO Size: 12279971
if(MarlinOutput.find("File opened: ") == 0) { if (marlin_output_.find("File opened: ") == 0) {
size_t first_space = MarlinOutput.find("File opened: "); size_t start_pos = std::strlen("File opened: ");
size_t second_space = MarlinOutput.find(" Size: "); size_t size_pos = marlin_output_.find(" Size: ");
if (size_pos != std::string::npos) {
if (first_space != std::string::npos && second_space != std::string::npos) { std::string filename = from_dos_name(marlin_output_.substr(start_pos, size_pos - start_pos));
size_t start = first_space + std::strlen("File opened: "); ESP_LOGD(TAG, "File: %s", filename.c_str());
size_t len = second_space - start;
ESP_LOGD(TAG, "position");
std::string filename = from_dos_name(MarlinOutput.substr(start, len));
ESP_LOGD("Soubor: %s\n", filename.c_str());
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
if (find_text_sensor("sd_card_file_selected") != nullptr){ publish_text_sensor("sd_card_file_selected", filename);
find_text_sensor("sd_card_file_selected")->publish_state(filename.c_str());
}
#endif #endif
} }
marlin_output_ = "";
//reset string for next line
MarlinOutput="";
return; return;
} }
//Print From SD Card Started if (marlin_output_.compare("File selected") == 0) {
if(MarlinOutput.compare("File selected") == 0) {
set_printer_state("PRINTING"); set_printer_state("PRINTING");
marlin_output_ = "";
//reset string for next line
MarlinOutput="";
return; return;
} }
//Print Finished if (marlin_output_.compare("Done printing") == 0) {
if(MarlinOutput.compare("Done printing") == 0) { print_progress_ = 100;
print_progress = 100;
#ifdef USE_SENSOR #ifdef USE_SENSOR
if (find_sensor("print_progress") != nullptr) publish_sensor("print_progress", 100.0f);
find_sensor("print_progress")->publish_state(print_progress); publish_sensor("print_time_remaining", 0.0f);
if (find_sensor("print_time_remaining") != nullptr)
find_sensor("print_time_remaining")->publish_state(0);
#endif #endif
#ifdef USE_TEXT_SENSOR
set_printer_state("FINISHED"); set_printer_state("FINISHED");
marlin_output_ = "";
return;
}
if (marlin_output_.compare("Print Aborted") == 0) {
set_printer_state("STOPPED");
marlin_output_ = "";
return;
}
ESP_LOGD(TAG, ">#%s#", marlin_output_.c_str());
marlin_output_ = "";
}
// ── SD card file list ─────────────────────────────────────────────────────
void Marlin2::publish_sd_files() {
std::string chunk;
uint8_t count = 0;
#ifdef USE_SELECT
std::vector<std::string> file_names;
#endif #endif
//reset string for next line for (const auto &[key, value] : file_table_) {
MarlinOutput=""; if (count >= max_sd_files_) {
return; ESP_LOGW(TAG, "SD file list truncated to %u files (total: %u)",
max_sd_files_, (unsigned) file_table_.size());
break;
}
if (!chunk.empty()) chunk += "|";
chunk += key;
#ifdef USE_SELECT
file_names.push_back(key);
#endif
count++;
} }
// //Print Paused #ifdef USE_TEXT_SENSOR
// if(MarlinOutput.compare("Printer halted") == 0) { publish_text_sensor("sd_card_files", chunk);
// set_printer_state("PAUSED"); #endif
#ifdef USE_SELECT
// //reset string for next line auto *sel = find_in_(selects_, std::string("sd_card_file_select"));
// MarlinOutput=""; if (sel != nullptr)
// return; sel->traits.set_options(file_names);
// } #endif
// //Print Stoped
if(MarlinOutput.compare("Print Aborted") == 0) {
set_printer_state("STOPPED");
//reset string for next line
MarlinOutput="";
return;
} }
ESP_LOGD(TAG, ">#%s#",MarlinOutput.c_str()); // ── Message parsers ───────────────────────────────────────────────────────
MarlinOutput="";
return;
}
int Marlin2::process_temp_msg(float* ext_temperature, float* ext_set_temperature, float* bed_temperature, float* bed_set_temperature) { int Marlin2::process_temp_msg(float *ext_temperature, float *ext_set_temperature, float *bed_temperature, float *bed_set_temperature) {
float dc; float dc;
while(MarlinOutput.find(" ") != std::string::npos) while (marlin_output_.find(" ") != std::string::npos)
MarlinOutput.erase(MarlinOutput.find(' '), 1); marlin_output_.erase(marlin_output_.find(' '), 1);
while (marlin_output_.find("ok") != std::string::npos)
marlin_output_.erase(marlin_output_.find("ok"), 2);
while(MarlinOutput.find("ok") != std::string::npos) if (sscanf(marlin_output_.c_str(), "T:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, bed_temperature, bed_set_temperature) == 4)
MarlinOutput.erase(MarlinOutput.find("ok"), 2);
if(sscanf(MarlinOutput.c_str() ,"T:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, bed_temperature, bed_set_temperature) == 4 )
return 1; return 1;
if (sscanf(marlin_output_.c_str(), "T:%f/%f(%f)B:%f/%f(%f)", ext_temperature, ext_set_temperature, &dc, bed_temperature, bed_set_temperature, &dc) == 6)
if(sscanf(MarlinOutput.c_str() ,"T:%f/%f(%f)B:%f/%f(%f)", ext_temperature, ext_set_temperature, &dc, bed_temperature, bed_set_temperature, &dc) == 6 )
return 2; return 2;
if (sscanf(marlin_output_.c_str(), "T:%f/%fT0:%f/%fT1:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, &dc, &dc, &dc, &dc, bed_temperature, bed_set_temperature) == 8)
if(sscanf(MarlinOutput.c_str() ,"T:%f/%fT0:%f/%fT1:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, &dc, &dc, &dc, &dc, bed_temperature, bed_set_temperature) == 8 )
return 3; return 3;
if (sscanf(marlin_output_.c_str(), "T0:%f/%fT1:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, &dc, &dc, bed_temperature, bed_set_temperature) == 6)
if(sscanf(MarlinOutput.c_str() ,"T0:%f/%fT1:%f/%fB:%f/%f", ext_temperature, ext_set_temperature, &dc, &dc, bed_temperature, bed_set_temperature) == 6 )
return 4; return 4;
return 0; return 0;
} }
float Marlin2::process_progress_msg(){ float Marlin2::process_progress_msg() {
float current = std::stoi(MarlinOutput.substr(17)); size_t slash_pos = marlin_output_.find('/');
float total = std::stoi(MarlinOutput.substr(MarlinOutput.find('/')+1)); if (slash_pos == std::string::npos || slash_pos + 1 >= marlin_output_.size())
return 0.0f;
if (total==0) { float current = std::stof(marlin_output_.substr(17));
return 0.0; float total = std::stof(marlin_output_.substr(slash_pos + 1));
if (total < 1.0f)
return 0.0f;
return roundf((current * 100.0f) / total);
} }
return round(((float) current * 100.0) / (float) total); int Marlin2::process_print_time_msg(double *current, double *remaining, float progress) {
} marlin_time_ = marlin_output_.substr(16);
int Marlin2::process_print_time_msg(double* current, double* remaining, float progress){
MarlinTime = MarlinOutput.substr(16);
float d = 0, h = 0, m = 0, s = 0; float d = 0, h = 0, m = 0, s = 0;
//ESP_LOGD(TAG,MarlinTime.c_str()); if (sscanf(marlin_time_.c_str(), "%fd %fh %fm %fs", &d, &h, &m, &s) != 4) {
d = 0;
if (sscanf(MarlinTime.c_str() ,"%fd %fh %fm %fs", &d, &h, &m, &s)!=4) { if (sscanf(marlin_time_.c_str(), "%fh %fm %fs", &h, &m, &s) != 3) {
d=0; h = 0;
if (sscanf(MarlinTime.c_str() ,"%fh %fm %fs", &h, &m, &s)!=3) { if (sscanf(marlin_time_.c_str(), "%fm %fs", &m, &s) != 2) {
d=0; h=0; m = 0;
if (sscanf(MarlinTime.c_str() ,"%fm %fs", &m, &s)!=2) { if (sscanf(marlin_time_.c_str(), "%fs", &s) != 1)
d=0; h=0; m=0;
if (sscanf(MarlinTime.c_str() ,"%fs", &s)!=1) {
return 0; return 0;
} }
} }
} }
}
*current = round(((d)*24*60*60) + ((h)*60*60) + ((m)*60) + (s)); *current = round((d * 24 * 60 * 60) + (h * 60 * 60) + (m * 60) + s);
if(progress != 0.0 && progress != 100.0) { if (progress != 0.0f && progress != 100.0f)
*remaining = (((100 * *current) / round(progress)) - *current); *remaining = ((100.0 * *current) / round(progress)) - *current;
}
return 1; return 1;
} }
void Marlin2::set_printer_state(std::string status){ void Marlin2::set_printer_state(const std::string &status) {
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
// if (!PrinterState.compare(status)) publish_text_sensor("printer_state", status);
// return;
if (find_text_sensor("printer_state") != nullptr){
find_text_sensor("printer_state")->publish_state(status);
}
// ESP_LOGD(TAG, "Printer Status %s", status.c_str());
// PrinterState = status;
#endif #endif
} }
std::string Marlin2::to_dos_name(std::string filename) { // ── Filename mapping ──────────────────────────────────────────────────────
std::string Marlin2::to_dos_name(const std::string &filename) {
auto it = file_table_.find(filename); auto it = file_table_.find(filename);
if (it != file_table_.end()) { return (it != file_table_.end()) ? it->second : filename;
return file_table_[filename];
}
return filename;
}
std::string Marlin2::from_dos_name(std::string dos_filename ) {
for (const auto& [key, value] : file_table_) {
if (value == dos_filename) {
return key;
}
} }
std::string Marlin2::from_dos_name(const std::string &dos_filename) {
for (const auto &[key, value] : file_table_)
if (value == dos_filename) return key;
return dos_filename; return dos_filename;
} }
std::string to_lower(std::string s) { } // namespace esphome::marlin2
return s;
// String arduinoStr(s.c_str()); // převod na Arduino String
// arduinoStr.toLowerCase(); // změní obsah přímo
// return std::string(arduinoStr.c_str()); // zpět na std::string
}
} // namespace esphome

View File

@@ -10,56 +10,83 @@
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
#include "esphome/components/text_sensor/text_sensor.h" #include "esphome/components/text_sensor/text_sensor.h"
#endif #endif
#ifdef USE_SELECT
#include "esphome/components/select/select.h"
#endif
#ifdef USE_BINARY_SENSOR
#include "esphome/components/binary_sensor/binary_sensor.h"
#endif
namespace esphome { namespace esphome::marlin2 {
class Marlin2 : public PollingComponent, public uart::UARTDevice { class Marlin2 : public Component, public uart::UARTDevice {
public: public:
Marlin2() = default; Marlin2() = default;
#ifdef USE_SENSOR #ifdef USE_SENSOR
void add_sensor(const std::string& sName, sensor::Sensor *sens); void add_sensor(const std::string &name, sensor::Sensor *sens);
sensor::Sensor* find_sensor(std::string key); void publish_sensor(const std::string &key, float value);
#endif #endif
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
void add_text_sensor(const std::string& sName, text_sensor::TextSensor *tSens); void add_text_sensor(const std::string &name, text_sensor::TextSensor *tSens);
text_sensor::TextSensor* find_text_sensor(std::string key); void publish_text_sensor(const std::string &key, const std::string &value);
#endif #endif
void write(std::string status); #ifdef USE_SELECT
std::string to_dos_name(std::string filename); void add_select(const std::string &name, select::Select *sel);
std::string from_dos_name(std::string dos_filename); #endif
std::string to_lower(std::string s); #ifdef USE_BINARY_SENSOR
void add_binary_sensor(const std::string &name, binary_sensor::BinarySensor *bs);
void publish_binary_sensor(const std::string &key, bool value);
#endif
void set_max_sd_files(uint8_t n) { max_sd_files_ = n; }
void write(const std::string &gcode);
std::string to_dos_name(const std::string &filename);
std::string from_dos_name(const std::string &dos_filename);
float get_setup_priority() const override { return setup_priority::LATE; } float get_setup_priority() const override { return setup_priority::LATE; }
void setup() override; void setup() override;
void update() override; void loop() override;
void dump_config() override;
protected: protected:
std::string MarlinOutput; std::string marlin_output_;
std::string MarlinResponseOutput; std::string marlin_time_;
std::string MarlinTime;
std::string PrinterState;
float print_progress = 0; float print_progress_ = 0;
double print_time_offset = 0; uint8_t max_sd_files_ = 20;
#ifdef USE_SENSOR #ifdef USE_SENSOR
std::vector<std::pair<std::string, sensor::Sensor *>> sensors; std::vector<std::pair<std::string, sensor::Sensor *>> sensors_;
#endif #endif
#ifdef USE_TEXT_SENSOR #ifdef USE_TEXT_SENSOR
std::vector<std::pair<std::string, text_sensor::TextSensor *>> text_sensors; std::vector<std::pair<std::string, text_sensor::TextSensor *>> text_sensors_;
#endif
#ifdef USE_SELECT
std::vector<std::pair<std::string, select::Select *>> selects_;
#endif
#ifdef USE_BINARY_SENSOR
std::vector<std::pair<std::string, binary_sensor::BinarySensor *>> binary_sensors_;
#endif #endif
void process_line(); void process_line();
void set_printer_state(std::string status); void set_printer_state(const std::string &status);
int process_temp_msg(float* ext_temperature, float* ext_set_temperature, float* bed_temperature, float* bed_set_temperature); void publish_sd_files();
int process_temp_msg(float *ext_temperature, float *ext_set_temperature, float *bed_temperature, float *bed_set_temperature);
float process_progress_msg(); float process_progress_msg();
int process_print_time_msg(double* current, double* remaining, float progress); int process_print_time_msg(double *current, double *remaining, float progress);
private: private:
unsigned long millisProgress=0; template<typename T>
static T *find_in_(std::vector<std::pair<std::string, T *>> &vec, const std::string &key) {
for (auto &pair : vec)
if (pair.first == key) return pair.second;
return nullptr;
}
std::unordered_map<std::string, std::string> file_table_; std::unordered_map<std::string, std::string> file_table_;
bool listingFile = false; bool listing_file_ = false;
}; };
} // namespace esphome } // namespace esphome::marlin2

26
select.py Normal file
View File

@@ -0,0 +1,26 @@
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import select
from esphome.const import (
ENTITY_CATEGORY_NONE,
)
from . import Marlin2
CONF_MARLIN = "marlin2"
CONF_SD_CARD_FILE_SELECT = "sd_card_file_select"
CONFIG_SCHEMA = cv.Schema(
{
cv.GenerateID(CONF_MARLIN): cv.use_id(Marlin2),
cv.Optional(CONF_SD_CARD_FILE_SELECT): select.select_schema(
entity_category=ENTITY_CATEGORY_NONE,
),
}
).extend(cv.polling_component_schema("15s"))
async def to_code(config):
server = await cg.get_variable(config[CONF_MARLIN])
if CONF_SD_CARD_FILE_SELECT in config:
sel = await select.new_select(config[CONF_SD_CARD_FILE_SELECT], options=[])
cg.add(server.add_select(CONF_SD_CARD_FILE_SELECT, sel))

View File

@@ -1,17 +1,8 @@
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
from esphome import automation
from esphome.components import uart
from esphome.components import sensor from esphome.components import sensor
# from esphome.components import text_sensor
from esphome.const import ( from esphome.const import (
CONF_ID, CONF_ID,
CONF_INDEX,
CONF_SENSORS,
CONF_HUMIDITY,
CONF_MODEL,
CONF_PIN,
CONF_TEMPERATURE,
UNIT_CELSIUS, UNIT_CELSIUS,
UNIT_PERCENT, UNIT_PERCENT,
UNIT_SECOND, UNIT_SECOND,
@@ -30,6 +21,7 @@ CONF_EXT_SET_TEMPERATURE = "ext_set_temperature"
CONF_PRINT_PROGRESS = "print_progress" CONF_PRINT_PROGRESS = "print_progress"
CONF_PRINT_TIME = "print_time" CONF_PRINT_TIME = "print_time"
CONF_PRINT_TIME_REMAINING = "print_time_remaining" CONF_PRINT_TIME_REMAINING = "print_time_remaining"
CONF_SD_CARD_FILE_COUNT = "sd_card_file_count"
CONF_MARLIN = "marlin2" CONF_MARLIN = "marlin2"
CONFIG_SCHEMA = cv.Schema( CONFIG_SCHEMA = cv.Schema(
@@ -76,13 +68,20 @@ CONFIG_SCHEMA = cv.Schema(
device_class=DEVICE_CLASS_DURATION, device_class=DEVICE_CLASS_DURATION,
state_class=STATE_CLASS_MEASUREMENT, state_class=STATE_CLASS_MEASUREMENT,
), ),
cv.Optional(CONF_SD_CARD_FILE_COUNT): sensor.sensor_schema(
accuracy_decimals=0,
state_class=STATE_CLASS_MEASUREMENT,
),
} }
).extend(cv.polling_component_schema("15s")) ).extend(cv.polling_component_schema("15s"))
async def to_code(config): async def to_code(config):
server = await cg.get_variable(config[CONF_MARLIN]) server = await cg.get_variable(config[CONF_MARLIN])
for sName in [CONF_BED_TEMPERATURE, CONF_BED_SET_TEMPERATURE, CONF_EXT_TEMPERATURE, CONF_EXT_SET_TEMPERATURE, CONF_PRINT_PROGRESS, CONF_PRINT_TIME, CONF_PRINT_TIME_REMAINING]: // Takhle:
auto *s = find_sensor("bed_temperature");
if (s != nullptr && s->get_state() != bed_temperature)
s->publish_state(bed_temperature);
if sName in config: if sName in config:
sens = await sensor.new_sensor(config[sName]) sens = await sensor.new_sensor(config[sName])
cg.add(server.add_sensor(sName,sens)) cg.add(server.add_sensor(sName, sens))

View File

@@ -7,16 +7,20 @@ from esphome.const import (
from . import Marlin2 from . import Marlin2
CONF_MARLIN = "marlin2" CONF_MARLIN = "marlin2"
CONF_PRINTER_STATE = "printer_state"
CONF_SD_CARD_FILES = "sd_card_files"
CONF_SD_CARD_FILE_SELECTED = "sd_card_file_selected"
CONFIG_SCHEMA = cv.Schema( CONFIG_SCHEMA = cv.Schema(
{ {
cv.GenerateID(CONF_MARLIN): cv.use_id(Marlin2), cv.GenerateID(CONF_MARLIN): cv.use_id(Marlin2),
cv.Optional("printer_state"): text_sensor.text_sensor_schema( cv.Optional(CONF_PRINTER_STATE): text_sensor.text_sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC, entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
), ),
cv.Optional("sd_card_files"): text_sensor.text_sensor_schema( cv.Optional(CONF_SD_CARD_FILES): text_sensor.text_sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC, entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
), ),
cv.Optional("sd_card_file_selected"): text_sensor.text_sensor_schema( cv.Optional(CONF_SD_CARD_FILE_SELECTED): text_sensor.text_sensor_schema(
entity_category=ENTITY_CATEGORY_DIAGNOSTIC, entity_category=ENTITY_CATEGORY_DIAGNOSTIC,
), ),
} }
@@ -25,7 +29,7 @@ CONFIG_SCHEMA = cv.Schema(
async def to_code(config): async def to_code(config):
server = await cg.get_variable(config[CONF_MARLIN]) server = await cg.get_variable(config[CONF_MARLIN])
for sName in ["printer_state", "sd_card_files", "sd_card_file_selected"]: for sName in [CONF_PRINTER_STATE, CONF_SD_CARD_FILES, CONF_SD_CARD_FILE_SELECTED]:
if sName in config: if sName in config:
sens = await text_sensor.new_text_sensor(config[sName]) sens = await text_sensor.new_text_sensor(config[sName])
cg.add(server.add_text_sensor(sName,sens)) cg.add(server.add_text_sensor(sName, sens))