27 Commits

Author SHA1 Message Date
whb0514
b534aef08f Update README.md 2024-09-02 15:53:30 +08:00
whb0514
aa71fa8d48 update V4.4.24 2024-09-02 10:11:38 +08:00
whb0514
1928cac53f Update README.md 2024-09-02 10:08:43 +08:00
CChen616
f565dc4e3e V4.4.21 Updates 2024-07-19 19:47:11 +08:00
CChen616
844e77a564 Sync sub repo 2024-07-19 19:44:05 +08:00
CChen616
e741d1e754 Adjust project structure 2024-07-19 19:41:46 +08:00
CChen616
88536c4d12 V4.4.21 patch correct gcode_macro.cfg 2024-07-04 01:09:08 +08:00
CChen616
9b7c36f9a6 V4.2.21 Update 2024-07-02 17:01:27 +08:00
CChen616
d6048da6c1 V4.4.20 update 2024-06-18 09:52:27 +08:00
CChen616
e62f278aa6 Update printer.cfg 2024-05-17 09:31:14 +08:00
CChen616
16f019084d update config 2024-05-10 10:46:34 +08:00
CChen616
b3c00805bf Update README.md 2024-05-03 10:03:21 +08:00
CChen616
0ce78cc607 V4.4.19 update 2024-05-03 09:57:27 +08:00
CChen616
d1d606ada4 Update config files 2024-05-03 09:56:18 +08:00
CChen616
9618b8bfca Merge pull request #9 from QIDITECH/V4.4.18
Update printer.cfg
2024-04-11 16:51:14 +08:00
CChen616
6336e7d34e Update printer.cfg 2024-04-11 16:50:46 +08:00
CChen616
a89c84c043 Merge pull request #8 from QIDITECH/V4.4.18
V4.4.18
2024-04-10 10:53:55 +08:00
CChen616
039e1167ac Merge branch 'main' into V4.4.18 2024-04-10 10:53:47 +08:00
CChen616
4c0049c0d8 Merge branch 'V4.4.18' of https://github.com/QIDITECH/QIDI_Q1_Pro into V4.4.18 2024-04-10 10:45:56 +08:00
CChen616
66ab378950 Update README.md 2024-04-10 10:28:30 +08:00
CChen616
4d3616a00d Update README.md 2024-04-10 10:14:56 +08:00
CChen616
6de965941a upload config folder 2024-04-10 09:05:25 +08:00
CChen616
474b134e40 V4.4.18 update 2024-04-09 15:18:07 +08:00
CChen616
d627567d0f Update README.md 2024-03-27 16:19:12 +08:00
CChen616
6e08b3e0da Update README.md 2024-03-27 16:18:18 +08:00
CChen616
ded3ca4041 Update README.md 2024-03-27 16:17:40 +08:00
CChen616
bc33b19902 update for V4.4.16 2024-03-27 13:52:57 +08:00
88 changed files with 2575 additions and 42982 deletions

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "moonraker"]
path = moonraker
url = https://github.com/QIDITECH/moonraker.git
[submodule "klipper"]
path = klipper
url = https://github.com/QIDITECH/klipper.git

View File

@@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.0.0)
project(MakerbaseClient VERSION 0.1.0)
# if (CMAKE_SYSTEM_NAME MATCHES "Linux")
# find_package(PkgConfig REQUIRED)
# pkg_check_modules(GTK3 REQUIRED gtk+-3.0)
# message(STATUS "----- GTK3_INCLUDE_DIRS: ${GTK3_INCLUDE_DIRS}")
# message(STATUS "----- GKT3_LIBRARIES: ${GTK3_LIBRARIES}")
# message(STATUS "----- GTK3_LINK_LIBRARIES: ${GTK3_LINK_LIBRARIES}")
# include_directories(${GTK3_INCLUDE_DIRS})
# link_directories(${GTK3_LIBRARY_DIRS})
# list(APPEND FC_DEP_LIBS ${GTK3_LIBRARIES})
# endif()
include(CTest)
enable_testing()
include_directories(./include)
# link_directories(./lib)
add_executable(xindi main.cpp)
add_subdirectory(src)
target_link_libraries(xindi src -lpthread -lboost_system -lwpa_client)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

View File

@@ -3,18 +3,22 @@
# Documentation Guidelines
QIDI_Q1_Pro is a server-side application designed specifically for the Q1_Pro model system, facilitating seamless interaction with its screen. This repository hosts our source code and offers a secure and straightforward method for updating: simply download the package file to a USB drive and perform the update locally on your device.
Q1 Pro is a 3D printer that uses Klipper as its foundation. This repository is used for updates and releases for the Q1 Pro model, as well as for issue tracking.
For convenience, QIDI provides version-specific packaged files. Please download the necessary compressed package file prefixed with "Q1_Pro." We offer several versions of the source code tailored to different needs; select the appropriate branch for download, with each branch name reflecting the corresponding version.
For convenience, QIDI provides version-specific packaged files. Please download the necessary compressed package file prefixed with "Q1_Pro." Select the appropriate branch for download, with each branch name reflecting the corresponding version.
## Update Content for Version 4.4.15
## V4.4.24 Update Content
**Note**: Post-update, the Klipper configuration file will be overwritten. The former configuration file will be renamed to printer_{datetime}.cfg as a backup, and the printer will require recalibration.
**Note:** After updating, the Klipper configuration file will be replaced. The previous configuration file will be backed up as `printer_{datetime}.cfg`, printer recalibration will be required.
1. Update the QIDI-LINK connection method to make the connection more secure.
2. Added Fluidd account management module
3. Fixed the issue of USB not being read on startup
4. Updated configuration files
1. Introduce an online update feature.
2. Implement support for the QIDI Link service.
3. Enhance the logic for canceling printing tasks.
4. Incorporate a feature for power failure recovery.
## Detailed update process
@@ -34,15 +38,19 @@ Note that all updates can not be updated from higher versions
For any concerns or suggestions, feel free to reach out to our [After-Sales Service](https://qidi3d.com/pages/warranty-policy-after-sales-support).
Should you encounter any issues related to machine mechanics, slicing software, firmware, or various other machine-related problems, our after-sales team is ready to assist. They aim to respond to all inquiries within twelve hours.
Should you encounter any issues related to machine mechanics, slicing software, firmware, or various other machine-related problems, our after-sales team is ready to assist. They aim to respond to all inquiries within twelve hours. Alternatively, you can post an issue in this repository, our developers will reply to you directly.
## Others
QIDI's 3D printers operate based on the Klipper system. Building on the Klipper open-source project, we've tailored its source code to meet specific user requirements.
Unlike the typical method of directly accessing the Fluidd web interface via an IP address, the QIDI edition modifies the default port to 10088. Therefore, you must append :10088 to the machine's IP address to access the Fluidd page.
Similarly, we've adapted Moonraker to ensure our designed screens align with web operations.
QIDI's 3D printers operate based on the Klipper system. Building on the Klipper open-source project, we've tailored its source code to meet specific user requirements. Similarly, we've adapted Moonraker to ensure our designed screens align with web operations. We extend our gratitude to the developers and maintainers of these open-source projects and encourage users to explore or support these robust platforms.
We also use Fluidd as one of the ways for users to interact with the printer.
| Software | QIDI edition |
| ------------- | -------------------------------------------------------------------------------- |
| **Klipper** | **[https://github.com/QIDITECH/klipper](https://github.com/QIDITECH/klipper)** |
| **Moonraker** | **[https://github.com/QIDITECH/moonrake](https://github.com/QIDITECH/moonrake)** |
We extend our gratitude to the developers and maintainers of these open-source projects and encourage users to explore or support these great projects.
| Software |Official| QIDI edition |
| ------------- |----------| -------------------------------------------------------------------------------- |
| **Klipper** |**[https://github.com/Klipper3d/klipper](https://github.com/Klipper3d/klipper)**| **[https://github.com/QIDITECH/klipper](https://github.com/QIDITECH/klipper)** |
| **Moonraker** |**[https://github.com/Arksine/moonraker](https://github.com/Arksine/moonraker)**| **[https://github.com/QIDITECH/moonrake](https://github.com/QIDITECH/moonrake)** |
|**Fluidd**|**[https://github.com/fluidd-core/fluidd](https://github.com/fluidd-core/fluidd)**||

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -1,6 +0,0 @@
#!/bin/bash
echo "Start makerbase-client"
time=$(date "+%Y%m%d%H%M%S")
# /root/makerbase-client/build/MakerbaseClient localhost > /root/mksclient/test-$time.log
/root/udp_server &
/root/xindi/build/xindi localhost

Binary file not shown.

225
config/Adaptive_Mesh.cfg Normal file
View File

@@ -0,0 +1,225 @@
# # # Klipper Adaptive Meshing # # #
# Heads up! If you have any other BED_MESH_CALIBRATE macros defined elsewhere in your config, you will need to comment out / remove them for this to work. (Klicky/Euclid Probe)
# You will also need to be sure that [exclude_object] is defined in printer.cfg, and your slicer is labeling objects.
# This macro will parse information from objects in your gcode to define a min and max mesh area to probe, creating an adaptive mesh!
# This macro will not increase probe_count values in your [bed_mesh] config. If you want richer meshes, be sure to increase probe_count. We recommend at least 5,5.
[gcode_macro BED_MESH_CALIBRATE]
rename_existing: _BED_MESH_CALIBRATE
### This section allows control of status LEDs your printer may have.
variable_led_enable: False # Enables/disables the use of status LEDs in this macro.
variable_status_macro: 'status_meshing' # If you have status LEDs in your printer (StealthBurner), you can use the macro that changes their status here.
### This section configures mesh point fuzzing, which allows probe points to be varied slightly if printing multiples of the same G-code file.
variable_fuzz_enable: False # Enables/disables the use of mesh point fuzzing to slightly randomize probing points to spread out wear on a build surface, default is False.
variable_fuzz_min: 0 # If enabled, the minimum amount in mm a probe point can be randomized, default is 0.
variable_fuzz_max: 4 # If enabled, the maximum amount in mm a probe point can be randomized, default is 4.
### This section is for configuring a mesh margin, which allows the probed mesh to be expanded outwards from the print area.
variable_margin_enable: False # Enables/disables adding a margin to the meshed area to pad a mesh out for specific needs, default is False.
variable_margin_size: 5 # Size in millimeters to expand the mesh outwards from the print area in all directions.
### This section is for those using a dockable probe that is stored outside of the print area. ###
variable_probe_dock_enable: False # Enables/disables the use of a dockable probe that is stored outside of the print area, default is False.
variable_attach_macro: 'Attach_Probe' # Here is where you define the macro that ATTACHES the probe to the printhead. E.g. 'Attach_Probe'
variable_detach_macro: 'Dock_Probe' # Here is where you define the macro that DETACHES the probe from the printhead. E.g. 'Dock_Probe'
### This section is for those who are using Moonraker's Update Manager for KAMP, or want a more verbose macro. ###
variable_display_parameters: True # Display macro paramters in the console, useful for debugging the SETUP_KAMP_MESHING call, or more verbosity.
gcode:
{% if display_parameters == True %}
{ action_respond_info("led_enable : %d" % (led_enable)) }
{ action_respond_info("status_macro: \'%s\'" % (status_macro)) }
{ action_respond_info("fuzz_enable : %d" % (fuzz_enable)) }
{ action_respond_info("fuzz_min : %f" % (fuzz_min)) }
{ action_respond_info("fuzz_max : %f" % (fuzz_max)) }
{ action_respond_info("probe_dock_enable: %d" % (probe_dock_enable)) }
{ action_respond_info("attach_macro: \'%s\'" % (attach_macro)) }
{ action_respond_info("detach_macro: \'%s\'" % (detach_macro)) }
{% endif %}
{% set all_points = printer.exclude_object.objects | map(attribute='polygon') | sum(start=[]) %}
{% set bed_mesh_min = printer.configfile.settings.bed_mesh.mesh_min %}
{% set bed_mesh_max = printer.configfile.settings.bed_mesh.mesh_max %}
{% set probe_count = printer.configfile.settings.bed_mesh.probe_count %}
{% set probe_count = probe_count if probe_count|length > 1 else probe_count * 2 %}
{% set max_probe_point_distance_x = ( bed_mesh_max[0] - bed_mesh_min[0] ) / (probe_count[0] - 1) %}
{% set max_probe_point_distance_y = ( bed_mesh_max[1] - bed_mesh_min[1] ) / (probe_count[1] - 1) %}
{% set x_min = all_points | map(attribute=0) | min | default(bed_mesh_min[0]) %}
{% set y_min = all_points | map(attribute=1) | min | default(bed_mesh_min[1]) %}
{% set x_max = all_points | map(attribute=0) | max | default(bed_mesh_max[0]) %}
{% set y_max = all_points | map(attribute=1) | max | default(bed_mesh_max[1]) %}
{% if margin_enable == False %}
{% set margin_size = 0 %}
{% endif %}
{ action_respond_info("{} object points, clamping to bed mesh [{!r} {!r}]".format(
all_points | count,
bed_mesh_min,
bed_mesh_max,
)) }
{% if fuzz_enable == True %}
{% set fuzz_range = range((fuzz_min * 100) | int, (fuzz_max * 100) | int + 1) %}
{% set x_min = (bed_mesh_min[0] + fuzz_max - margin_size, x_min) | max - (fuzz_range | random / 100.0) %}
{% set y_min = (bed_mesh_min[1] + fuzz_max - margin_size, y_min) | max - (fuzz_range | random / 100.0) %}
{% set x_max = (bed_mesh_max[0] - fuzz_max + margin_size, x_max) | min + (fuzz_range | random / 100.0) %}
{% set y_max = (bed_mesh_max[1] - fuzz_max + margin_size, y_max) | min + (fuzz_range | random / 100.0) %}
{% else %}
{% set x_min = [ bed_mesh_min[0], x_min - margin_size ] | max %}
{% set y_min = [ bed_mesh_min[1], y_min - margin_size ] | max %}
{% set x_max = [ bed_mesh_max[0], x_max + margin_size ] | min %}
{% set y_max = [ bed_mesh_max[1], y_max + margin_size ] | min %}
{% endif %}
{ action_respond_info("Object bounds, clamped to the bed_mesh: {!r}, {!r}".format(
(x_min, y_min),
(x_max, y_max),
)) }
{% set points_x = (((x_max - x_min) / max_probe_point_distance_x) | round(method='ceil') | int) + 1 %}
{% set points_y = (((y_max - y_min) / max_probe_point_distance_y) | round(method='ceil') | int) + 1 %}
{% if params.PROFILE is defined %}
{% set PROFILE2 =params.PROFILE %}
{% else %}
{% set PROFILE2 ="default" %}
{% endif %}
{% if (([points_x, points_y]|max) > 4) %}
{% set algorithm = "bicubic" %}
{% set min_points = 4 %}
{% else %}
{% set algorithm = "lagrange" %}
{% set min_points = 3 %}
{% endif %}
{ action_respond_info( "Algorithm: {}".format(algorithm)) }
{% set points_x = [points_x, min_points]|max %}
{% set points_y = [points_y, min_points]|max %}
{ action_respond_info( "Points: x: {}, y: {}".format(points_x, points_y) ) }
{% if printer.configfile.settings.bed_mesh.relative_reference_index is defined %}
{% set ref_index = (points_x * points_y / 2) | int %}
{ action_respond_info( "Reference index: {}".format(ref_index) ) }
{% else %}
{% set ref_index = -1 %}
{% endif %}
{% if probe_dock_enable == True %}
{attach_macro} # Attach/deploy a probe if the probe is stored somewhere outside of the print area
{% endif %}
{% if led_enable == True %}
{status_macro} # Set status LEDs
{% endif %}
_BED_MESH_CALIBRATE mesh_min={x_min},{y_min} mesh_max={x_max},{y_max} ALGORITHM={algorithm} PROBE_COUNT={points_x},{points_y} RELATIVE_REFERENCE_INDEX={ref_index} PROFILE={params.PROFILE|default("default")}
{% if probe_dock_enable == True %}
{detach_macro} # Detach/stow a probe if the probe is stored somewhere outside of the print area
{% endif %}
[gcode_macro SETUP_KAMP_MESHING]
gcode:
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=display_parameters VALUE={params.DISPLAY_PARAMETERS|default(True)|int}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=led_enable VALUE={params.LED_ENABLE|default(False)|int}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=status_macro VALUE='"{params.STATUS_MACRO|default('status_meshing')|string}"'
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=fuzz_enable VALUE={params.FUZZ_ENABLE|default(False)|int}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=fuzz_min VALUE={params.FUZZ_MIN|default(0)|float}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=fuzz_max VALUE={params.FUZZ_MAX|default(4)|float}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=probe_dock_enable VALUE={params.PROBE_DOCK_ENABLE|default(False)|int}
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=attach_macro VALUE='"{params.ATTACH_MACRO|default('Attach_Probe')|string}"'
SET_GCODE_VARIABLE MACRO=BED_MESH_CALIBRATE VARIABLE=detach_macro VALUE='"{params.DETACH_MACRO|default('Dock_Probe')|string}"'
# # # Klipper Adaptive Purging - Line # # #
# This macro will parse information from objects in your gcode and create a nearby purge!
# For successful purging, you may need to configure:
#
# [extruder]
# ...
# max_extrude_cross_section: 5
[gcode_macro LINE_PURGE]
description: A purge macro that adapts to be near your actual printed objects
variable_adaptive_enable: True # Change to False if you'd like the purge to be in the same spot every print
variable_z_height: 0.4 # Height above the bed to purge
variable_purge_amount: 40 # Amount of filament in millimeters to purge
variable_line_length: 50 # Overall desired length of purge line in millimeters, around 1/5th of X axis length is a good starting value
variable_flow_rate: 12 # Desired flow rate in mm3/s (Around 12 for standard flow hotends, around 24 for high flow hotends)
variable_x_default: 10 # Default X location to purge. If adaptive_enable is True, this is overwritten
variable_y_default: 10 # Default Y location to purge. If adaptive_enable is True, this is overwritten
variable_distance_to_object_y: 10 # Y distance in millimeters away from the print area for purging. Must be less than or equal to y_default if adaptive_enable is False
### This section is for those who are using Moonraker's Update Manager for KAMP, or want a more verbose macro. ###
variable_display_parameters: True # Display macro paramters in the console, useful for debugging the SETUP_LINE_PURGE call, or more verbosity.
gcode:
{% if display_parameters == True %}
{ action_respond_info("adaptive_enable : %d" % (adaptive_enable)) }
{ action_respond_info("z_height : %f" % (z_height)) }
{ action_respond_info("purge_amount : %f" % (purge_amount)) }
{ action_respond_info("line_length : %f" % (line_length)) }
{ action_respond_info("flow_rate : %f" % (flow_rate)) }
{ action_respond_info("x_default : %f" % (x_default)) }
{ action_respond_info("y_default : %f" % (y_default)) }
{ action_respond_info("distance_to_object_y : %f" % (distance_to_object_y)) }
{% endif %}
{% if adaptive_enable == True %}
{% set all_points = printer.exclude_object.objects | map(attribute='polygon') | sum(start=[]) %}
{% set x_origin = (all_points | map(attribute=0) | min | default(x_default)) %}
{% set y_origin = (all_points | map(attribute=1) | min | default(y_default)) %}
{% set x_origin = ([x_origin, 0] | max) %}
{% set y_origin = ([y_origin, 0] | max) %}
{% else %}
{% set x_origin = x_default | float %}
{% set y_origin = y_default | float %}
{% endif %}
{% set nozzle_dia = printer.configfile.config.extruder.nozzle_diameter | float %}
{% set cross_section = nozzle_dia * z_height | float %}
{% set purge_move_speed = (cross_section * flow_rate) * 60 | float %}
{% set travel_speed = (printer.toolhead.max_velocity) * 30 | float %}
G92 E0 # Reset extruder
G0 F{travel_speed} # Set travel speed
G90 # Absolute positioning
G0 X{x_origin} Y{y_origin - distance_to_object_y} # Move to purge position
G0 Z{z_height} # Move to purge Z height
M83 # Relative extrusion mode
G1 X{x_origin + line_length} E{purge_amount} F{purge_move_speed} # Purge line
G1 E-.5 F2100 # Retract
G92 E0 # Reset extruder distance
M82 # Absolute extrusion mode
G0 Z{z_height * 2} F{travel_speed} # Z hop
[gcode_macro SETUP_LINE_PURGE]
gcode:
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=display_parameters VALUE={params.DISPLAY_PARAMETERS|default(True)|int}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=adaptive_enable VALUE={params.ADAPTIVE_ENABLE|default(True)|int}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=z_height VALUE={params.Z_HEIGHT|default(0.4)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=purge_amount VALUE={params.PURGE_AMOUNT|default(40)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=line_length VALUE={params.LINE_LENGTH|default(50)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=flow_rate VALUE={params.FLOW_RATE|default(12)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=x_default VALUE={params.X_DEFAULT|default(10)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=y_default VALUE={params.Y_DEFAULT|default(10)|float}
SET_GCODE_VARIABLE MACRO=LINE_PURGE VARIABLE=distance_to_object_y VALUE={params.DISTANCE_TO_OBJECT_Y|default(10)|float}

775
config/gcode_macro.cfg Normal file
View File

@@ -0,0 +1,775 @@
# Q1_Pro
# V4.4.16 2024-3-14
# update: variable change M106 & M141 & M107
# V4.4.16 2024-3-26
# update: variable change [homing_override]->add M204 S10000
# V4.4.20 2024-6-17
# update: Z_DOUDONG CLEAR_NOZZLE get_zoffset rewrite
# move_subzoffset added
# V4.4.21 2024-6-22
# update: Enable chamber exhaust fan by default when chamber temp not set
[gcode_macro test_zoffset]
gcode:
G28
get_zoffset
G1 X{120 - printer.probe["x_offset"]} Y{120 - printer.probe["y_offset"]} F9000
G1 Z10 F600
probe
M400
G4 P5000
G1 Z10 F600
[gcode_macro move_subzoffset]
gcode:
G1 Z{printer.probe.last_z_result} F600
[gcode_macro get_zoffset]
gcode:
G1 Z10 F600
Z_DOUDONG
;G4 P500
QIDI_PROBE_PIN_1
M204 S30
G4 P500
probe probe_speed=5 lift_speed=5 samples=5 sample_retract_dist=5
move_subzoffset
M114
SET_KINEMATIC_POSITION Z=-0.07
G1 Z30 F600
QIDI_PROBE_PIN_2
M204 S10000
[gcode_macro save_zoffset]
gcode:
{% if printer.gcode_move.homing_origin.z < 0.5 %}
SAVE_VARIABLE VARIABLE=z_offset VALUE={printer.gcode_move.homing_origin.z}
{% endif %}
[gcode_macro set_zoffset]
gcode:
{% set z = printer.save_variables.variables.z_offset %}
SET_GCODE_OFFSET Z={z} MOVE=0
[gcode_macro CLEAR_NOZZLE_PLR]
gcode:
{% set hotendtemp = params.HOTEND|default(250)|int %}
{% if (printer.gcode_move.position.z ) < 35 %}
G90
G1 Z35 F900
{% else %}
G91
G1 Z5 F900
G90
{% endif %}
G1 X97 F15000
G1 Y243 F15000
G1 Y254 F800
M109 S{hotendtemp}
G92 E0
G1 E80 F400
M106 S255
G1 X97 F500
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 Y240 F800
[gcode_macro CLEAR_NOZZLE]
gcode:
{% set hotendtemp = params.HOTEND|int %}
{% if (printer.gcode_move.position.z ) < 35 %}
G1 Z35 F900
{% else %}
G91
G1 Z5 F900
G90
{% endif %}
G1 X97 F15000
G1 Y243 F15000
G1 Y254 F800
M109 S{hotendtemp}
G92 E0
G1 E80 F400
M106 S255
M400
M106 P2 S0
M104 S0
TEMPERATURE_WAIT SENSOR=extruder MAXIMUM={hotendtemp-20}
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X65 F500
G1 X88 F500
G1 X65 F500
G1 X88 F500
G1 X65 F500
G1 X88 F500
G1 X65 F500
G1 X88 F500
G1 X65 F500
G1 X97 F500
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
G1 X85 F2000
G1 X97 F2000
M400
M118 Nozzle cleared
G1 Y240 F800
G1 Y120 F15000
G1 X230 F15000
TEMPERATURE_WAIT SENSOR=extruder MAXIMUM=140
M107
M106 P2 S0
M400
M118 Nozzle cooled
[gcode_macro PRINT_START]
gcode:
AUTOTUNE_SHAPERS
{% set bedtemp = params.BED|int %}
{% set hotendtemp = params.HOTEND|int %}
{% set chambertemp = params.CHAMBER|default(0)|int %}
set_zoffset
M104 S0
M140 S{bedtemp}
# M141 S{chambertemp}
G28
CLEAR_NOZZLE HOTEND={hotendtemp}
M190 S{bedtemp}
# Z_TILT_ADJUST
G29
G0 Z50 F600
G0 X0 Y0 F6000
M109 S{hotendtemp}
M141 S{chambertemp}
M204 S10000
{% if chambertemp == 0 %}
M106 P3 S255
{% endif %}
ENABLE_ALL_SENSOR
save_last_file
[gcode_macro ENABLE_ALL_SENSOR]
gcode:
ENABLE_FILAMENT_WIDTH_SENSOR
RESET_FILAMENT_WIDTH_SENSOR
query_filament_width
SET_FILAMENT_SENSOR SENSOR=fila ENABLE=1
[gcode_macro DISABLE_ALL_SENSOR]
gcode:
SET_FILAMENT_SENSOR SENSOR=fila ENABLE=0
DISABLE_FILAMENT_WIDTH_SENSOR
[gcode_macro AUTOTUNE_SHAPERS]
variable_autotune_shapers: 'ei'
gcode:
[gcode_macro M84]
rename_existing:M84.1
gcode:
M84.1
SET_STEPPER_ENABLE STEPPER=stepper_x enable=0
SET_STEPPER_ENABLE STEPPER=stepper_y enable=0
SET_STEPPER_ENABLE STEPPER=stepper_z enable=1
SET_STEPPER_ENABLE STEPPER=stepper_z1 enable=1
SET_STEPPER_ENABLE STEPPER=extruder enable=0
[gcode_macro DETECT_INTERRUPTION]
gcode:
{% set was_interrupted = printer.save_variables.variables.was_interrupted %}
{% if was_interrupted %}
M118 Detected unexpected interruption during the last print. Do you want to resume printing? (Do not move the extruder before resuming.)
M118 Yes: RESUME_INTERRUPTED
M118 No: CLEAR_LAST_FILE
{% endif %}
[delayed_gcode PRINTER_INIT]
initial_duration:0.2
gcode:
SET_STEPPER_ENABLE STEPPER=stepper_z enable=1
SET_STEPPER_ENABLE STEPPER=stepper_z1 enable=1
BED_MESH_CLEAR
SET_FILAMENT_SENSOR SENSOR=fila ENABLE=0
[homing_override]
axes:xyz
gcode:
{% set HOME_CUR = 1 %}
{% set driver_config = printer.configfile.settings['tmc2240 stepper_x'] %}
{% set RUN_CUR = driver_config.run_current %}
{% set HOLD_CUR = driver_config.hold_current %}
M204 S10000
M220 S100
{% if params.X is defined %}
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR * 0.7}
G28 X
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR}
BEEP I=1 DUR=100
G1 X10 F1200
{% endif %}
{% if params.Y is defined %}
SET_TMC_CURRENT STEPPER=stepper_y CURRENT={HOME_CUR * 0.9}
G28 Y
SET_TMC_CURRENT STEPPER=stepper_y CURRENT={HOME_CUR}
BEEP I=1 DUR=100
G1 Y10 F1200
{% endif %}
{% if params.Z is defined %}
SET_KINEMATIC_POSITION Z={printer.toolhead.axis_maximum.z-5}
QIDI_PROBE_PIN_2
probe samples=2
SET_KINEMATIC_POSITION Z=1.9
G1 Z10 F600
Z_DOUDONG
QIDI_PROBE_PIN_1
probe probe_speed=10
SET_KINEMATIC_POSITION Z=-0.1
G1 Z30 F480
{% endif %}
{% if params.X is undefined %}
{% if params.Y is undefined %}
{% if params.Z is undefined %}
SET_KINEMATIC_POSITION X=0
SET_KINEMATIC_POSITION Y=0
SET_KINEMATIC_POSITION Z={printer.toolhead.axis_maximum.z-10}
G91
G1 Z7 F600
G1 X10 F2400
G1 Y10 F2400
G4 P2000
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR * 0.8}
G28 X
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR}
BEEP I=1 DUR=100
G1 X10 F1200
SET_TMC_CURRENT STEPPER=stepper_y CURRENT={HOME_CUR * 0.9}
G28 Y
SET_TMC_CURRENT STEPPER=stepper_y CURRENT={HOME_CUR}
BEEP I=1 DUR=100
G1 Y10 F1200
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR * 0.8}
G28 X
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={HOME_CUR}
BEEP I=1 DUR=100
G1 X10 F1200
SET_KINEMATIC_POSITION Z={printer.toolhead.axis_maximum.z-10}
G90
G1 X120 Y120 F7800
G91
QIDI_PROBE_PIN_2
G28 Z
G1 Z30 F600
{% endif %}
{% endif %}
{% endif %}
SET_TMC_CURRENT STEPPER=stepper_x CURRENT={RUN_CUR}
SET_TMC_CURRENT STEPPER=stepper_y CURRENT={RUN_CUR}
M204 S10000
G90
QIDI_PROBE_PIN_2
[gcode_macro SHAPER_CALIBRATE]
rename_existing: RESHAPER_CALIBRATE
gcode:
RESHAPER_CALIBRATE FREQ_START=20 FREQ_END=150
[gcode_macro PRINT_END]
gcode:
SET_IDLE_TIMEOUT TIMEOUT={printer.configfile.settings.idle_timeout.timeout} ; set timeout back to configured value
CLEAR_PAUSE
save_zoffset
M106 P2 S0
M106 P0 S0
M106 P3 S0
M104 S0
M140 S0
M141 S0
M220 S100
M221 S100
SET_STEPPER_ENABLE STEPPER=stepper_x enable=0
SET_STEPPER_ENABLE STEPPER=stepper_y enable=0
SET_STEPPER_ENABLE STEPPER=stepper_z enable=1
SET_STEPPER_ENABLE STEPPER=stepper_z1 enable=1
SET_STEPPER_ENABLE STEPPER=extruder enable=0
DISABLE_ALL_SENSOR
SET_GCODE_OFFSET Z=0 MOVE=0
BED_MESH_CLEAR
G31
CLEAR_LAST_FILE
BEEP I=2 DUR=500
[gcode_macro CANCEL_PRINT]
rename_existing: BASE_CANCEL_PRINT
gcode:
{% if (printer.gcode_move.position.z) < 150 %} ; check that zhop doesn't exceed z max
G1 Z150 F480
{% endif %}
G1 X0 Y0 F7800
SET_IDLE_TIMEOUT TIMEOUT={printer.configfile.settings.idle_timeout.timeout} ; set timeout back to configured value
CLEAR_PAUSE
save_zoffset
M106 P2 S0
M106 P0 S0
M106 P3 S0
M104 S0
M140 S0
M141 S0
M220 S100
M221 S100
SET_STEPPER_ENABLE STEPPER=stepper_x enable=0
SET_STEPPER_ENABLE STEPPER=stepper_y enable=0
SET_STEPPER_ENABLE STEPPER=stepper_z enable=1
SET_STEPPER_ENABLE STEPPER=stepper_z1 enable=1
SET_STEPPER_ENABLE STEPPER=extruder enable=0
DISABLE_ALL_SENSOR
SET_GCODE_OFFSET Z=0 MOVE=0
BED_MESH_CLEAR
G31
BEEP I=2 DUR=500
SDCARD_RESET_FILE
BASE_CANCEL_PRINT
CLEAR_LAST_FILE
[gcode_macro PAUSE]
rename_existing: BASE_PAUSE
gcode:
{% set z = params.Z|default(35)|int %} ; z hop amount
{% if printer['pause_resume'].is_paused|int == 0 %}
SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=zhop VALUE={z} ; set z hop variable for reference in resume macro
SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=etemp VALUE={printer['extruder'].target} ; set hotend temp variable for reference in resume macro
DISABLE_FILAMENT_WIDTH_SENSOR
SET_FILAMENT_SENSOR SENSOR=fila ENABLE=0 ; disable filament sensor
SAVE_GCODE_STATE NAME=PAUSE ; save current print position for resume
BASE_PAUSE ; pause print
G92 E0
G1 E-5 F1800
{% if (printer.gcode_move.position.z ) < z %}
G91 ; relative positioning
G1 Z{z} F900 ; raise Z up by z hop amount
{% else %}
G91 ; relative positioning
G1 Z{5} F900
SET_GCODE_VARIABLE MACRO=RESUME VARIABLE=zhop VALUE=0
{% endif %}
SAVE_GCODE_STATE NAME=PAUSEPARK2
G90 ; absolute positioning
G1 X97 F9000
G1 Y253 F9000 ; park toolhead at front center
SAVE_GCODE_STATE NAME=PAUSEPARK ; save parked position in case toolhead is moved during the pause (otherwise the return zhop can error)
M104 S0 ; turn off hotend
SET_IDLE_TIMEOUT TIMEOUT=86400 ; set timeout to 24 hours
SET_STEPPER_ENABLE STEPPER=extruder enable=0
{% endif %}
[gcode_macro RESUME]
rename_existing: BASE_RESUME
variable_zhop: 0
variable_etemp: 0
gcode:
{% set e = params.E|default(5)|int %} ; hotend prime amount (in mm)
{% if printer['pause_resume'].is_paused|int == 1 %}
SET_IDLE_TIMEOUT TIMEOUT={printer.configfile.settings.idle_timeout.timeout} ; set timeout back to configured value
{% if etemp > 0 %}
M109 S{etemp|int} ; wait for hotend to heat back up
{% endif %}
M83 ; relative extruder positioning
G1 X97 F9000
G1 Y253 F9000
G91
G1 E{e} F300 ; prime nozzle by E, lower Z back down
G90
G1 X85 F3000
G1 X98 F3000
G1 X85 F3000
G1 X98 F3000
G1 X85 F3000
G1 X98 F3000
G1 X85 F3000
G1 X98 F3000
G1 X85 F3000
G1 X98 F3000
G1 X85 F3000
G1 X98 F3000
G1 X65 F500
G1 Y200 F3000
RESTORE_GCODE_STATE NAME=PAUSEPARK2 MOVE=1 MOVE_SPEED=200
RESTORE_GCODE_STATE NAME=PAUSE MOVE=1 MOVE_SPEED=10 ; restore position
BASE_RESUME
ENABLE_FILAMENT_WIDTH_SENSOR
RESET_FILAMENT_WIDTH_SENSOR
query_filament_width ; resume print
SET_FILAMENT_SENSOR SENSOR=fila ENABLE=1 ; enable filament sensor
{% endif %}
[gcode_macro BEEP]
gcode:
{% set i = params.I|default(1)|int %} ; Iterations (number of times to beep).
{% set dur = params.DUR|default(100)|int %} ; Duration/wait of each beep in ms. Default 100ms.
{% if printer["output_pin sound"].value|int == 1 %}
{% for iteration in range(i|int) %}
SET_PIN PIN=beeper VALUE=1
G4 P{dur}
SET_PIN PIN=beeper VALUE=0
G4 P{dur}
{% endfor %}
{% endif %}
[gcode_macro M141]
gcode:
{% if printer["heater_generic chamber"] is defined %}
{% set s = params.S|float %}
SET_HEATER_TEMPERATURE HEATER=chamber TARGET={([s, 60]|min)}
{% endif %}
[gcode_macro M191]
gcode:
#Parameters
{% if printer["heater_generic chamber"] is defined %}
{% set s = params.S|float %}
M141 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %}
{% if s != 0 %}
TEMPERATURE_WAIT SENSOR="heater_generic chamber" MINIMUM={([s, 60]|min)-2} #MAXIMUM={s+1}
{% endif %}
{% endif %}
[gcode_macro M106]
gcode:
{% set p = params.P|default(0)|int %}
{% if p == 2 %}
{% if params.S is defined %}
SET_FAN_SPEED FAN=auxiliary_cooling_fan SPEED={(params.S|float / 255.0)}
{% else %}
SET_FAN_SPEED FAN=auxiliary_cooling_fan SPEED=1
{% endif %}
{% endif %}
{% if p == 0 %}
{% if params.S is defined %}
SET_FAN_SPEED FAN=cooling_fan SPEED={(params.S|float / 255.0)}
{% else %}
SET_FAN_SPEED FAN=cooling_fan SPEED=1
{% endif %}
{% endif %}
{% if p == 3 %}
{% if params.S is defined %}
SET_FAN_SPEED FAN=chamber_circulation_fan SPEED={(params.S|float / 255.0)}
{% else %}
SET_FAN_SPEED FAN=chamber_circulation_fan SPEED=1
{% endif %}
{% endif %}
[gcode_macro M107]
gcode:
SET_FAN_SPEED FAN=cooling_fan SPEED=0
[gcode_macro M303]
gcode:
{% if params.E is defined %}
{% if params.S is defined %}
{% if (params.E|int)==-1 %}
PID_CALIBRATE HEATER=heater_bed TARGET={params.S|int}
{% endif %}
{% if (params.E|int)==0 %}
PID_CALIBRATE HEATER=extruder TARGET={params.S|int}
{% endif %}
{% endif %}
{% endif %}
[gcode_macro M8029]
gcode:
{% if params.D is defined %}
{% if (params.D|int)==1 %}
ENABLE_FILAMENT_WIDTH_SENSOR
{% endif %}
{% if (params.D|int)==0 %}
DISABLE_FILAMENT_WIDTH_SENSOR
{% endif %}
{% endif %}
[gcode_macro M900]
gcode:
{% if params.K is defined %}
SET_PRESSURE_ADVANCE ADVANCE={params.K}
{% endif %}
{% if params.T is defined %}
SET_PRESSURE_ADVANCE SMOOTH_TIME={params.T}
{% endif %}
[gcode_macro M290]
gcode:
SET_GCODE_OFFSET Z_ADJUST={params.Z}
[gcode_macro M901]
gcode:
G28
SHAPER_CALIBRATE
M400
M118 Input shaping complete
SAVE_CONFIG
[gcode_macro M0]
gcode:
PAUSE
[gcode_macro M25]
rename_existing: M9925
gcode:
PAUSE
[gcode_macro RESPOND_INFO]
variable_S:0
gcode:
{% if params.S is defined %}
{% set s = params.S|int %}
{% if s == 0 %}
{ action_respond_info("Nozzle cooled") }
{% endif %}
{% endif %}
[gcode_macro M4027]
gcode:
G1 X{120 - printer.probe["x_offset"]} Y{120 - printer.probe["y_offset"]} F9000
probe
save_meshoffset
G1 z10 F600
SET_GCODE_OFFSET Z=0 MOVE=1
BED_MESH_CALIBRATE
set_meshoffset
G0 Z50 F600
G0 X0 Y0 F9000
M400
M118 Bed mesh calibrate complete
SAVE_CONFIG
[gcode_macro M4028]
gcode:
G28
get_zoffset
M400
M118 Position init complete
[gcode_macro M4029]
gcode:
M104 S140
SAVE_VARIABLE VARIABLE=z_offset VALUE=0
G28
M400
M118 Position init complete
CLEAR_NOZZLE HOTEND=240
G28
get_zoffset
[gcode_macro M4030]
gcode:
BED_MESH_CLEAR
SET_GCODE_OFFSET Z=0 MOVE=0
G28
get_zoffset
G1 X120 Y120 F9000
G1 Z0 F600
[gcode_macro M4031]
gcode:
SET_TMC_CURRENT STEPPER=stepper_z CURRENT={printer.configfile.settings['tmc2209 stepper_z'].run_current * 0.8 }
SET_TMC_CURRENT STEPPER=stepper_z1 CURRENT={printer.configfile.settings['tmc2209 stepper_z1'].run_current * 0.8 }
REVERSE_HOMING
SET_TMC_CURRENT STEPPER=stepper_z CURRENT={printer.configfile.settings['tmc2209 stepper_z'].run_current}
SET_TMC_CURRENT STEPPER=stepper_z1 CURRENT={printer.configfile.settings['tmc2209 stepper_z1'].run_current}
G91
G1 Z-30 F600
G90
SET_TMC_CURRENT STEPPER=stepper_z CURRENT={printer.configfile.settings['tmc2209 stepper_z'].run_current * 0.8 }
SET_TMC_CURRENT STEPPER=stepper_z1 CURRENT={printer.configfile.settings['tmc2209 stepper_z1'].run_current * 0.8 }
REVERSE_HOMING
SET_TMC_CURRENT STEPPER=stepper_z CURRENT={printer.configfile.settings['tmc2209 stepper_z'].run_current}
SET_TMC_CURRENT STEPPER=stepper_z1 CURRENT={printer.configfile.settings['tmc2209 stepper_z1'].run_current}
G91
G1 Z-30 F600
G90
[gcode_macro M603]
description: unload filament
gcode:
M118 Heat up complete
G92 E0
G0 E15 F400
G4 P1000
G92 E0
G1 E-90 F800
M400
M118 Filament unloaded
[gcode_macro M604]
description: load filament
gcode:
M118 Heat up complete
M83
G1 E80 F400
M400
M118 Filament loaded
[output_pin sound]
pin: gpio8
value:0
[gcode_macro beep_on]
gcode:
SET_PIN PIN=sound VALUE=1
[gcode_macro beep_off]
gcode:
SET_PIN PIN=sound VALUE=0
[gcode_arcs]
resolution: 1.0
[gcode_macro M109]
rename_existing: M99109
gcode:
{% set s = params.S|float %}
M104 {% for p in params %}{'%s%s' % (p, params[p])}{% endfor %} ; Set hotend temp
{% if s != 0 %}
TEMPERATURE_WAIT SENSOR=extruder MINIMUM={s} MAXIMUM={s+1} ; Wait for hotend temp (within 1 degree)
{% endif %}
[exclude_object]
[gcode_macro G31]
gcode:
SET_GCODE_VARIABLE MACRO=G29 VARIABLE=k VALUE=1
[gcode_macro G32]
gcode:
SET_GCODE_VARIABLE MACRO=G29 VARIABLE=k VALUE=0
[gcode_macro set_meshoffset]
variable_zoffset:0
gcode:
ADD_Z_OFFSET_TO_BED_MESH ZOFFSET={0 - zoffset}
SET_GCODE_VARIABLE MACRO=set_meshoffset VARIABLE=zoffset VALUE=0
[gcode_macro save_meshoffset]
gcode:
SET_GCODE_VARIABLE MACRO=set_meshoffset VARIABLE=zoffset VALUE={printer.probe.last_z_result}
[gcode_macro G29]
variable_k:1
gcode:
BED_MESH_CLEAR
{% if k|int==1 %}
G28
get_zoffset
G1 X{120 - printer.probe["x_offset"]} Y{120 - printer.probe["y_offset"]} F9000
G1 Z10 F600
probe
save_meshoffset
G1 z10 F600
BED_MESH_CALIBRATE PROFILE=kamp
SAVE_VARIABLE VARIABLE=profile_name VALUE='"kamp"'
set_meshoffset
SAVE_CONFIG_QD
{% else %}
g28
get_zoffset
BED_MESH_PROFILE LOAD=default
SAVE_VARIABLE VARIABLE=profile_name VALUE='"default"'
{% endif %}
[gcode_macro M204]
rename_existing: M99204
gcode:
{% if params.S is defined %}
{% set s = params.S|float %}
{% endif %}
{% if params.P is defined %}
{% if params.T is defined %}
{% set s = [params.P|float ,params.T|float] | min %}
{% endif %}
{% endif %}
SET_VELOCITY_LIMIT ACCEL={s}
SET_VELOCITY_LIMIT ACCEL_TO_DECEL={s/2}
[gcode_macro Z_DOUDONG]
gcode:
M204 S30
G90
G0 Z1
G91
G4 P3000
SET_PIN PIN=ctlyd VALUE=1
{% for z in range(1,7) %}
G1 Z10 F900
G1 Z-10 F900
{% endfor %}
SET_PIN PIN=ctlyd VALUE=0
G4 P1000
G1 Z4
G90
# M204 S10000

54
config/moonraker.conf Normal file
View File

@@ -0,0 +1,54 @@
[server]
host: 0.0.0.0
port: 7125
enable_debug_logging: False
klippy_uds_address: /tmp/klippy_uds
[authorization]
trusted_clients:
10.0.0.0/8
127.0.0.0/8
169.254.0.0/16
172.16.0.0/12
192.168.0.0/16
FE80::/10
::1/128
cors_domains:
http://*.lan
http://*.local
https://my.mainsail.xyz
http://my.mainsail.xyz
https://app.fluidd.xyz
http://app.fluidd.xyz
[database]
database_path: /home/mks/.moonraker_database
[file_manager]
config_path: /home/mks/klipper_config
log_path: /home/mks/klipper_logs
[octoprint_compat]
[history]
[timelapse]
# [update_manager]
# channel: dev
# refresh_interval: 168
# enable_system_updates: False
# [update_manager fluidd]
# type: web
# channel: stable
# repo: fluidd-core/fluidd
# path: ~/fluidd
# [update_manager KlipperScreen]
# type: git_repo
# path: /home/mks/KlipperScreen
# origin: https://github.com/jordanruthe/KlipperScreen.git
# env: /home/mks/.KlipperScreen-env/bin/python
# requirements: scripts/KlipperScreen-requirements.txt
# install_script: scripts/KlipperScreen-install.sh

66
config/plr.cfg Normal file
View File

@@ -0,0 +1,66 @@
[gcode_shell_command POWER_LOSS_RESUME]
command: bash /home/mks/scripts/plr/plr.sh
timeout: 120
[gcode_shell_command UPDATE_GCODE_LINES]
command: bash /home/mks/scripts/plr/update_gcode_lines.sh
[gcode_macro save_last_file]
gcode:
{% set svv = printer.save_variables.variables %}
{% set filepath=printer.virtual_sdcard.file_path %}
{% set filename=filepath.split('/')%}
SAVE_VARIABLE VARIABLE=was_interrupted VALUE=True
SAVE_VARIABLE VARIABLE=print_temp VALUE={printer.extruder.target}
SAVE_VARIABLE VARIABLE=bed_temp VALUE={printer['heater_bed'].target}
{% if printer["heater_generic chamber"] is defined %}
SAVE_VARIABLE VARIABLE=hot_temp VALUE={printer['heater_generic chamber'].target}
{% else %}
SAVE_VARIABLE VARIABLE=hot_temp VALUE=0
{% endif %}
M118 Last File: { filename[-1] }
M117 Last File: { filename[-1] }
G4 P2000
[gcode_macro CLEAR_LAST_FILE]
gcode:
{% set filename='' %}
SAVE_VARIABLE VARIABLE=last_file VALUE='"{ filename }"'
SAVE_VARIABLE VARIABLE=was_interrupted VALUE=False
[gcode_macro LOG_Z]
gcode:
{% set z_pos = printer.gcode_move.gcode_position.z %}
RESPOND MSG="Current Z is {z_pos}"
SAVE_VARIABLE VARIABLE=power_resume_z VALUE={z_pos}
[gcode_macro RESUME_INTERRUPTED]
gcode:
set_zoffset
RUN_SHELL_COMMAND CMD=UPDATE_GCODE_LINES
{% set profile_name = params.PROFILE_NAME|default(printer.save_variables.variables.profile_name)|string %}
# {% set g_lines = params.GCODE_LINES|default(printer.save_variables.variables.gcode_lines)|string %}
# {% set last_file = params.GCODE_FILE|default(printer.save_variables.variables.last_file)|string %}
# {% set print_temp = params.PRINT_TEMP|default(printer.save_variables.variables.print_temp)|float %}
# {% set bed_temp = params.BED_TEMP|default(printer.save_variables.variables.bed_temp)|float %}
# {% set hot_temp = params.HOT_TEMP|default(printer.save_variables.variables.hot_temp)|float %}
# {% set filepath = params.FILE_PATH|default(printer.save_variables.variables.file_path)|string %}
BED_MESH_PROFILE LOAD={profile_name}
RUN_SHELL_COMMAND CMD=POWER_LOSS_RESUME
SDCARD_PRINT_FILE FILENAME=/.plr/plr.gcode
# [gcode_macro RESUME_INTERRUPTED]
# gcode:
# set_zoffset
# {% set profile_name = params.PROFILE_NAME|default(printer.save_variables.variables.profile_name)|string %}
# {% set z_height = params.Z_HEIGHT|default(printer.save_variables.variables.power_resume_z)|float %}
# {% set last_file = params.GCODE_FILE|default(printer.save_variables.variables.last_file)|string %}
# {% set print_temp = params.PRINT_TEMP|default(printer.save_variables.variables.print_temp)|float %}
# {% set bed_temp = params.BED_TEMP|default(printer.save_variables.variables.bed_temp)|float %}
# {% set hot_temp = params.HOT_TEMP|default(printer.save_variables.variables.hot_temp)|float %}
# {% set filepath = params.FILE_PATH|default(printer.save_variables.variables.file_path)|string %}
# BED_MESH_PROFILE LOAD={profile_name}
# RUN_SHELL_COMMAND CMD=POWER_LOSS_RESUME PARAMS="{z_height} {last_file} {print_temp} {bed_temp} {hot_temp} {filepath}"
# SDCARD_PRINT_FILE FILENAME=/.plr/plr.gcode

515
config/printer.cfg Normal file
View File

@@ -0,0 +1,515 @@
# Q1_Pro
# V4.4.14 2024-3-14
# update: heater_generic hot -> chamber
# out_put_pin fan0 -> fan_generic cooling_fan
# out_put_pin fan2 -> fan_generic auxiliary_cooling_fan
# out_put_pin fan3 -> fan_generic chamber_circulation_fan
# heater_fan hot -> heater_fan chamber
# verify_heater hot -> verify_heater chamber
# V4.4.17 2024-3-29
# update: delete comments
# add time_update macro
# [bed_mesh] 6,6 ->8,8
# V4.4.19 2024-4-16
# update: add [chamber_fan chamber_fan]
# V4.4.20 2024-6-17
# update: [smart_effector]
# samples_result: average -> submaxmin
# speed: 10 -> 5
# sample_retract_dist: 3.0 -> 5.0
# [stepper_x]
# position_max: 245 -> 246
[include timelapse.cfg]
[include Adaptive_Mesh.cfg]
[include gcode_macro.cfg]
[include plr.cfg]
[include time_update.cfg]
[mcu]
serial: /dev/ttyS2
restart_method: command
[mcu U_1]
serial: /dev/ttyS0
restart_method: command
[respond]
default_type: echo
[save_variables]
filename =/home/mks/klipper_config/saved_variables.cfg
[resonance_tester]
accel_per_hz: 150
max_smoothing:0.5
[duplicate_pin_override]
pins:
gpio21 ,U_1:PC3
[bed_screws]
screw1:10,10
screw1_name: Front left
screw2: 230,10
screw2_name: Front right
screw3: 125,240
screw3_name: Last right
[screws_tilt_adjust]
screw1:-5,5.6
screw1_name: Front left
screw2: 216,5.6
screw2_name: Front right
screw3: 103,235.6
screw3_name: Last right
screw_thread: CW-M4
[force_move]
enable_force_move : false
[hall_filament_width_sensor]
adc1: gpio27
adc2: gpio28
cal_dia1: 1.50
cal_dia2: 2.0
raw_dia1: 14397
raw_dia2: 15058
default_nominal_filament_diameter: 1.75
max_difference: 0
measurement_delay: 50
enable: false
measurement_interval: 10
logging: False
min_diameter: 0.3
use_current_dia_while_delay: False
pause_on_runout:True
runout_gcode:
RESET_FILAMENT_WIDTH_SENSOR
M118 Filament run out
event_delay: 3.0
pause_delay: 0.5
[extruder]
step_pin:gpio5
dir_pin:gpio4
enable_pin:!gpio10
rotation_distance: 53.7 #22.6789511 #Bondtech 5mm Drive Gears
gear_ratio: 1517:170
microsteps: 16
full_steps_per_rotation: 200 #200 for 1.8 degree, 400 for 0.9 degree
nozzle_diameter: 0.400
filament_diameter: 1.75
min_temp: 0
max_temp: 360
min_extrude_temp: 175
smooth_time: 0.000001
heater_pin:gpio24
sensor_type:MAX6675
sensor_pin:gpio17
spi_speed: 100000
spi_software_sclk_pin:gpio18
spi_software_mosi_pin:gpio19
spi_software_miso_pin:gpio16
max_power: 1
control : pid
pid_Kp=33.555
pid_Ki=4.76
pid_Kd=59.141
pressure_advance: 0.032
pressure_advance_smooth_time: 0.03
max_extrude_cross_section:500
instantaneous_corner_velocity: 10.000
max_extrude_only_distance: 1000.0
max_extrude_only_velocity:5000
max_extrude_only_accel:2000
step_pulse_duration:0.000002
[tmc2209 extruder]
uart_pin:gpio6
interpolate: True
run_current: 0.714
stealthchop_threshold: 0
[adxl345]
cs_pin:gpio13
spi_software_sclk_pin:gpio14
spi_software_mosi_pin:gpio15
spi_software_miso_pin:gpio12
axes_map: -x, z, -y
[printer]
kinematics:corexy
max_velocity: 600
max_accel: 20000
max_accel_to_decel: 10000
max_z_velocity: 10
max_z_accel: 500
square_corner_velocity: 8
[stepper_x]
step_pin:U_1:PB4
dir_pin:!U_1:PB3
enable_pin:!U_1:PB5
microsteps:16
rotation_distance: 39.88
full_steps_per_rotation:200 #set to 400 for 0.9 degree stepper
endstop_pin:tmc2240_stepper_x:virtual_endstop
position_min: -5.5
position_endstop: -5.5
position_max:246
homing_speed:50
homing_retract_dist:0
homing_positive_dir:False
step_pulse_duration:0.0000001
[stepper_y]
step_pin:U_1:PC14
dir_pin:!U_1:PC13
enable_pin:!U_1:PC15
microsteps: 16
rotation_distance: 39.88
full_steps_per_rotation:200 #set to 400 for 0.9 degree stepper
endstop_pin:tmc2240_stepper_y:virtual_endstop
position_min: -4.5
position_endstop: -4.5
position_max: 258
homing_speed:50
homing_retract_dist:0
homing_positive_dir:False
step_pulse_duration:0.0000001
[stepper_z]
step_pin:U_1:PC10
dir_pin:U_1:PA15
enable_pin:!U_1:PC11
microsteps: 128
rotation_distance: 4
full_steps_per_rotation: 200
endstop_pin:probe:z_virtual_endstop #U_1:PC3 for Z-max
endstop_pin_reverse:tmc2209_stepper_z:virtual_endstop
position_endstop:-0.2
position_endstop_reverse:248
position_max:248
position_min: -4
homing_speed: 8
homing_speed_reverse: 8
second_homing_speed: 10
homing_retract_dist: 5.0
homing_positive_dir:false
homing_positive_dir_reverse:true
step_pulse_duration:0.0000001
[stepper_z1]
step_pin:U_1:PB1
dir_pin:U_1:PB6
enable_pin:!U_1:PB0
microsteps: 128
rotation_distance: 4
full_steps_per_rotation: 200
step_pulse_duration:0.0000001
endstop_pin_reverse:tmc2209_stepper_z1:virtual_endstop
[z_tilt]
z_positions:
-59,125
307.5,125
points:
0,125
215,125
speed: 150
horizontal_move_z: 5
retries: 2
retry_tolerance: 0.05
[tmc2240 stepper_y]
cs_pin:U_1:PB9
spi_software_sclk_pin:U_1:PA5
spi_software_mosi_pin:U_1:PA7
spi_software_miso_pin:U_1:PA6
spi_speed:200000
run_current: 1.07
#hold_current: 0.5
interpolate:true
stealthchop_threshold:0
diag0_pin:!U_1:PC0
driver_SGT:1
[tmc2240 stepper_x]
cs_pin:U_1:PD2
spi_software_sclk_pin:U_1:PA5
spi_software_mosi_pin:U_1:PA7
spi_software_miso_pin:U_1:PA6
spi_speed:200000
run_current: 1.07
#hold_current: 0.5
interpolate:true
stealthchop_threshold:0
diag0_pin:!U_1:PB8
driver_SGT:1
[tmc2209 stepper_z]
uart_pin:U_1: PC5
run_current: 0.6
#hold_current: 0.17
interpolate: True
stealthchop_threshold: 9999999999
diag_pin:^U_1:PC12
driver_SGTHRS:130
[tmc2209 stepper_z1]
uart_pin:U_1: PB7
run_current: 0.6
#hold_current: 0.17
interpolate: True
stealthchop_threshold: 9999999999
diag_pin:^U_1:PA13
driver_SGTHRS:130
[heater_bed]
heater_pin: U_1:PB10
sensor_type:NTC 100K MGB18-104F39050L32
sensor_pin:U_1: PA0
max_power: 1.0
control = pid
pid_Kp=63.418
pid_Ki=1.342
pid_Kd=749.125
min_temp: -60
max_temp: 125
[heater_generic chamber]
heater_pin:U_1:PC8
max_power:1.0
sensor_type:NTC 100K MGB18-104F39050L32
sensor_pin:U_1:PA1
control = pid#watermark
pid_Kp=63.418
pid_Ki=1.342
pid_Kd=749.125
min_temp:-100
max_temp:65
[verify_heater chamber]
max_error: 300
check_gain_time:480
hysteresis: 5
heating_gain: 1
[verify_heater extruder]
max_error: 120
check_gain_time:20
hysteresis: 5
heating_gain: 1
[verify_heater heater_bed]
max_error: 200
check_gain_time:60
hysteresis: 5
heating_gain: 1
[fan_generic auxiliary_cooling_fan]
pin: U_1:PA8
shutdown_speed: 0.0
cycle_time: 0.0100
hardware_pwm: false
kick_start_time: 0.100
off_below: 0.0
[fan_generic chamber_circulation_fan]
pin:U_1:PC9
shutdown_speed: 0.0
cycle_time: 0.100
hardware_pwm: false
kick_start_time: 0.100
off_below: 0.0
[chamber_fan chamber_fan]
pin:U_1:PA4
max_power: 1.0
shutdown_speed: 0
kick_start_time: 0.5
heater:chamber
fan_speed: 1.0
off_below: 0
idle_timeout:60
idle_speed:1.0
[heater_fan hotend_fan]
pin:gpio25
max_power: 1.0
shutdown_speed:1.0
kick_start_time: 0.5
heater: extruder
heater_temp: 50.0
fan_speed: 1.0
off_below: 0
[heater_fan hotend_fan2]
pin:gpio11
max_power: 1.0
shutdown_speed:1.0
kick_start_time: 0.5
heater: extruder
heater_temp: 50.0
fan_speed: 1.0
off_below: 0
[controller_fan board_fan]
pin:U_1:PC4
max_power:1.0
shutdown_speed:1.0
cycle_time:0.01
fan_speed: 0.6
stepper:stepper_x,stepper_y
[fan_generic cooling_fan]
pin:gpio2
max_power: 1.0
shutdown_speed: 0
cycle_time: 0.0100
hardware_pwm: false
kick_start_time: 0.100
off_below: 0.0
[output_pin caselight]
pin: U_1:PC7
pwm: false
shutdown_value:1
value:1
[output_pin beeper]
pin:U_1: PA2
pwm: false
shutdown_value:0
value:0
[output_pin ctlyd]
pin:U_1: PA14
pwm: false
shutdown_value:0
value:0
[smart_effector]
pin:U_1:PC1
recovery_time:0
x_offset: 17.6
y_offset: 4.4
z_offset: 0.000001
speed:5
lift_speed:5
probe_accel:50
samples: 2
samples_result: submaxmin
sample_retract_dist: 5.0
samples_tolerance: 0.05
samples_tolerance_retries:5
[qdprobe]
pin:!gpio21
z_offset:0.000001
[bed_mesh]
speed:150
horizontal_move_z:7
mesh_min:20,15
mesh_max:230,230
probe_count:8,8
algorithm:bicubic
bicubic_tension:0.2
mesh_pps: 2, 2
vibrate_gcode:
Z_DOUDONG
[filament_switch_sensor fila]
pause_on_runout: True
runout_gcode:
M118 Filament tangle detected
event_delay: 3.0
pause_delay: 0.5
switch_pin:U_1:PC3
[resonance_tester]
accel_chip:adxl345
probe_points:
120, 120, 10
[gcode_macro_break]
# Used for cancel print in a macro
[idle_timeout]
timeout: 43200
gcode:
PRINT_END
[pause_resume]
[display_status]
[virtual_sdcard]
path: ~/gcode_files
#*# <---------------------- SAVE_CONFIG ---------------------->
#*# DO NOT EDIT THIS BLOCK OR BELOW. The contents are auto-generated.
#*#
#*# [input_shaper]
#*# shaper_type_x = ei
#*# shaper_freq_x = 81.6
#*# shaper_type_y = ei
#*# shaper_freq_y = 39.8
#*#
#*# [adxl345]
#*# probe_pin = gpio9
#*# int_pin = int1
#*# tap_thresh = 3500
#*# tap_dur = 0.01
#*# speed = 20
#*# z_offset = -0.1
#*# samples = 3
#*# sample_retract_dist = 10.0
#*# samples_result = median
#*# samples_tolerance = 0.05
#*# samples_tolerance_retries = 3
#*#
#*# [bed_mesh default]
#*# version = 1
#*# points =
#*# 0,0,0,0,0,0
#*# 0,0,0,0,0,0
#*# 0,0,0,0,0,0
#*# 0,0,0,0,0,0
#*# 0,0,0,0,0,0
#*# 0,0,0,0,0,0
#*# tension = 0.2
#*# min_x = 20.0
#*# algo = lagrange
#*# y_count = 6
#*# mesh_y_pps = 2
#*# min_y = 10.0
#*# x_count = 6
#*# max_y = 230.0
#*# mesh_x_pps = 2
#*# max_x = 230.0
#*#
#*# [bed_mesh kamp]
#*# version = 1
#*# points =
#*# 0, 0, 0
#*# 0, 0, 0
#*# 0, 0, 0
#*# tension = 0.2
#*# min_x = 86.05
#*# algo = lagrange
#*# y_count = 3
#*# mesh_y_pps = 2
#*# min_y = 86.05
#*# x_count = 3
#*# max_y = 158.95
#*# mesh_x_pps = 2
#*# max_x = 158.93

View File

@@ -0,0 +1,11 @@
[Variables]
bed_temp = 60.0
filepath = ''
hot_temp = 0.0
last_file = ''
power_resume_z = 0.0
print_temp = 210.0
profile_name = 'kamp'
was_interrupted = False
z_offset = 0.0

441
config/time_update.cfg Normal file
View File

@@ -0,0 +1,441 @@
[gcode_shell_command UPDATE_SYSTEM_TIME]
command: bash /home/mks/scripts/time_update/time_update.sh
timeout: 60
# Usage:
# Run the following Gcode macro in fluidd console to update the printer system time
#
# RUN_SHELL_COMMAND CMD=UPDATE_SYSTEM_TIME PARAMS={TimeZone}
#
# Example
# RUN_SHELL_COMMAND CMD=UPDATE_SYSTEM_TIME PARAMS=Asia/Shanghai
#
# Internet connection needed
#
# Available TimeZones
#
# Africa/Abidjan
# Africa/Accra
# Africa/Addis_Ababa
# Africa/Algiers
# Africa/Asmara
# Africa/Bamako
# Africa/Bangui
# Africa/Banjul
# Africa/Bissau
# Africa/Blantyre
# Africa/Brazzaville
# Africa/Bujumbura
# Africa/Cairo
# Africa/Casablanca
# Africa/Ceuta
# Africa/Conakry
# Africa/Dakar
# Africa/Dar_es_Salaam
# Africa/Djibouti
# Africa/Douala
# Africa/El_Aaiun
# Africa/Freetown
# Africa/Gaborone
# Africa/Harare
# Africa/Johannesburg
# Africa/Juba
# Africa/Kampala
# Africa/Khartoum
# Africa/Kigali
# Africa/Kinshasa
# Africa/Lagos
# Africa/Libreville
# Africa/Lome
# Africa/Luanda
# Africa/Lubumbashi
# Africa/Lusaka
# Africa/Malabo
# Africa/Maputo
# Africa/Maseru
# Africa/Mbabane
# Africa/Mogadishu
# Africa/Monrovia
# Africa/Nairobi
# Africa/Ndjamena
# Africa/Niamey
# Africa/Nouakchott
# Africa/Ouagadougou
# Africa/Porto-Novo
# Africa/Sao_Tome
# Africa/Tripoli
# Africa/Tunis
# Africa/Windhoek
# America/Adak
# America/Anchorage
# America/Anguilla
# America/Antigua
# America/Araguaina
# America/Argentina/Buenos_Aires
# America/Argentina/Catamarca
# America/Argentina/Cordoba
# America/Argentina/Jujuy
# America/Argentina/La_Rioja
# America/Argentina/Mendoza
# America/Argentina/Rio_Gallegos
# America/Argentina/Salta
# America/Argentina/San_Juan
# America/Argentina/San_Luis
# America/Argentina/Tucuman
# America/Argentina/Ushuaia
# America/Aruba
# America/Asuncion
# America/Atikokan
# America/Bahia
# America/Bahia_Banderas
# America/Barbados
# America/Belem
# America/Belize
# America/Blanc-Sablon
# America/Boa_Vista
# America/Bogota
# America/Boise
# America/Cambridge_Bay
# America/Campo_Grande
# America/Cancun
# America/Caracas
# America/Cayenne
# America/Cayman
# America/Chicago
# America/Chihuahua
# America/Costa_Rica
# America/Creston
# America/Cuiaba
# America/Curacao
# America/Danmarkshavn
# America/Dawson
# America/Dawson_Creek
# America/Denver
# America/Detroit
# America/Dominica
# America/Edmonton
# America/Eirunepe
# America/El_Salvador
# America/Fort_Nelson
# America/Fortaleza
# America/Glace_Bay
# America/Goose_Bay
# America/Grand_Turk
# America/Grenada
# America/Guadeloupe
# America/Guatemala
# America/Guayaquil
# America/Guyana
# America/Halifax
# America/Havana
# America/Hermosillo
# America/Indiana/Indianapolis
# America/Indiana/Knox
# America/Indiana/Marengo
# America/Indiana/Petersburg
# America/Indiana/Tell_City
# America/Indiana/Vevay
# America/Indiana/Vincennes
# America/Indiana/Winamac
# America/Inuvik
# America/Iqaluit
# America/Jamaica
# America/Juneau
# America/Kentucky/Louisville
# America/Kentucky/Monticello
# America/Kralendijk
# America/La_Paz
# America/Lima
# America/Los_Angeles
# America/Lower_Princes
# America/Maceio
# America/Managua
# America/Manaus
# America/Marigot
# America/Martinique
# America/Matamoros
# America/Mazatlan
# America/Menominee
# America/Merida
# America/Metlakatla
# America/Mexico_City
# America/Miquelon
# America/Moncton
# America/Monterrey
# America/Montevideo
# America/Montserrat
# America/Nassau
# America/New_York
# America/Nipigon
# America/Nome
# America/Noronha
# America/North_Dakota/Beulah
# America/North_Dakota/Center
# America/North_Dakota/New_Salem
# America/Nuuk
# America/Ojinaga
# America/Panama
# America/Pangnirtung
# America/Paramaribo
# America/Phoenix
# America/Port-au-Prince
# America/Port_of_Spain
# America/Porto_Velho
# America/Puerto_Rico
# America/Punta_Arenas
# America/Rainy_River
# America/Rankin_Inlet
# America/Recife
# America/Regina
# America/Resolute
# America/Rio_Branco
# America/Santarem
# America/Santiago
# America/Santo_Domingo
# America/Sao_Paulo
# America/Scoresbysund
# America/Sitka
# America/St_Barthelemy
# America/St_Johns
# America/St_Kitts
# America/St_Lucia
# America/St_Thomas
# America/St_Vincent
# America/Swift_Current
# America/Tegucigalpa
# America/Thule
# America/Thunder_Bay
# America/Tijuana
# America/Toronto
# America/Tortola
# America/Vancouver
# America/Whitehorse
# America/Winnipeg
# America/Yakutat
# America/Yellowknife
# Antarctica/Casey
# Antarctica/Davis
# Antarctica/DumontDUrville
# Antarctica/Macquarie
# Antarctica/Mawson
# Antarctica/McMurdo
# Antarctica/Palmer
# Antarctica/Rothera
# Antarctica/Syowa
# Antarctica/Troll
# Antarctica/Vostok
# Arctic/Longyearbyen
# Asia/Aden
# Asia/Almaty
# Asia/Amman
# Asia/Anadyr
# Asia/Aqtau
# Asia/Aqtobe
# Asia/Ashgabat
# Asia/Atyrau
# Asia/Baghdad
# Asia/Bahrain
# Asia/Baku
# Asia/Bangkok
# Asia/Barnaul
# Asia/Beirut
# Asia/Bishkek
# Asia/Brunei
# Asia/Chita
# Asia/Choibalsan
# Asia/Colombo
# Asia/Damascus
# Asia/Dhaka
# Asia/Dili
# Asia/Dubai
# Asia/Dushanbe
# Asia/Famagusta
# Asia/Gaza
# Asia/Hebron
# Asia/Ho_Chi_Minh
# Asia/Hong_Kong
# Asia/Hovd
# Asia/Irkutsk
# Asia/Jakarta
# Asia/Jayapura
# Asia/Jerusalem
# Asia/Kabul
# Asia/Kamchatka
# Asia/Karachi
# Asia/Kathmandu
# Asia/Khandyga
# Asia/Kolkata
# Asia/Krasnoyarsk
# Asia/Kuala_Lumpur
# Asia/Kuching
# Asia/Kuwait
# Asia/Macau
# Asia/Magadan
# Asia/Makassar
# Asia/Manila
# Asia/Muscat
# Asia/Nicosia
# Asia/Novokuznetsk
# Asia/Novosibirsk
# Asia/Omsk
# Asia/Oral
# Asia/Phnom_Penh
# Asia/Pontianak
# Asia/Pyongyang
# Asia/Qatar
# Asia/Qostanay
# Asia/Qyzylorda
# Asia/Riyadh
# Asia/Sakhalin
# Asia/Samarkand
# Asia/Seoul
# Asia/Shanghai
# Asia/Singapore
# Asia/Srednekolymsk
# Asia/Taipei
# Asia/Tashkent
# Asia/Tbilisi
# Asia/Tehran
# Asia/Thimphu
# Asia/Tokyo
# Asia/Tomsk
# Asia/Ulaanbaatar
# Asia/Urumqi
# Asia/Ust-Nera
# Asia/Vientiane
# Asia/Vladivostok
# Asia/Yakutsk
# Asia/Yangon
# Asia/Yekaterinburg
# Asia/Yerevan
# Atlantic/Azores
# Atlantic/Bermuda
# Atlantic/Canary
# Atlantic/Cape_Verde
# Atlantic/Faroe
# Atlantic/Madeira
# Atlantic/Reykjavik
# Atlantic/South_Georgia
# Atlantic/St_Helena
# Atlantic/Stanley
# Australia/Adelaide
# Australia/Brisbane
# Australia/Broken_Hill
# Australia/Darwin
# Australia/Eucla
# Australia/Hobart
# Australia/Lindeman
# Australia/Lord_Howe
# Australia/Melbourne
# Australia/Perth
# Australia/Sydney
# Europe/Amsterdam
# Europe/Andorra
# Europe/Astrakhan
# Europe/Athens
# Europe/Belgrade
# Europe/Berlin
# Europe/Bratislava
# Europe/Brussels
# Europe/Bucharest
# Europe/Budapest
# Europe/Busingen
# Europe/Chisinau
# Europe/Copenhagen
# Europe/Dublin
# Europe/Gibraltar
# Europe/Guernsey
# Europe/Helsinki
# Europe/Isle_of_Man
# Europe/Istanbul
# Europe/Jersey
# Europe/Kaliningrad
# Europe/Kiev
# Europe/Kirov
# Europe/Lisbon
# Europe/Ljubljana
# Europe/London
# Europe/Luxembourg
# Europe/Madrid
# Europe/Malta
# Europe/Mariehamn
# Europe/Minsk
# Europe/Monaco
# Europe/Moscow
# Europe/Oslo
# Europe/Paris
# Europe/Podgorica
# Europe/Prague
# Europe/Riga
# Europe/Rome
# Europe/Samara
# Europe/San_Marino
# Europe/Sarajevo
# Europe/Saratov
# Europe/Simferopol
# Europe/Skopje
# Europe/Sofia
# Europe/Stockholm
# Europe/Tallinn
# Europe/Tirane
# Europe/Ulyanovsk
# Europe/Uzhgorod
# Europe/Vaduz
# Europe/Vatican
# Europe/Vienna
# Europe/Vilnius
# Europe/Volgograd
# Europe/Warsaw
# Europe/Zagreb
# Europe/Zaporozhye
# Europe/Zurich
# Indian/Antananarivo
# Indian/Chagos
# Indian/Christmas
# Indian/Cocos
# Indian/Comoro
# Indian/Kerguelen
# Indian/Mahe
# Indian/Maldives
# Indian/Mauritius
# Indian/Mayotte
# Indian/Reunion
# Pacific/Apia
# Pacific/Auckland
# Pacific/Bougainville
# Pacific/Chatham
# Pacific/Chuuk
# Pacific/Easter
# Pacific/Efate
# Pacific/Enderbury
# Pacific/Fakaofo
# Pacific/Fiji
# Pacific/Funafuti
# Pacific/Galapagos
# Pacific/Gambier
# Pacific/Guadalcanal
# Pacific/Guam
# Pacific/Honolulu
# Pacific/Kiritimati
# Pacific/Kosrae
# Pacific/Kwajalein
# Pacific/Majuro
# Pacific/Marquesas
# Pacific/Midway
# Pacific/Nauru
# Pacific/Niue
# Pacific/Norfolk
# Pacific/Noumea
# Pacific/Pago_Pago
# Pacific/Palau
# Pacific/Pitcairn
# Pacific/Pohnpei
# Pacific/Port_Moresby
# Pacific/Rarotonga
# Pacific/Saipan
# Pacific/Tahiti
# Pacific/Tarawa
# Pacific/Tongatapu
# Pacific/Wake
# Pacific/Wallis
# UTC

424
config/timelapse.cfg Normal file
View File

@@ -0,0 +1,424 @@
# Timelapse klipper macro definition
#
# Copyright (C) 2021 Christoph Frei <fryakatkop@gmail.com>
# Copyright (C) 2021 Alex Zellner <alexander.zellner@googlemail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
#
# Macro version 1.14
#
##### DO NOT CHANGE ANY MACRO!!! #####
##########################################################################
# #
# GET_TIMELAPSE_SETUP: Print the Timelapse setup to console #
# #
##########################################################################
[gcode_macro GET_TIMELAPSE_SETUP]
description: Print the Timelapse setup
gcode:
{% set tl = printer['gcode_macro TIMELAPSE_TAKE_FRAME'] %}
{% set output_txt = ["Timelapse Setup:"] %}
{% set _dummy = output_txt.append("enable: %s" % tl.enable) %}
{% set _dummy = output_txt.append("park: %s" % tl.park.enable) %}
{% if tl.park.enable %}
{% set _dummy = output_txt.append("park position: %s time: %s s" % (tl.park.pos, tl.park.time)) %}
{% set _dummy = output_txt.append("park cord x:%s y:%s dz:%s" % (tl.park.coord.x, tl.park.coord.y, tl.park.coord.dz)) %}
{% set _dummy = output_txt.append("travel speed: %s mm/s" % tl.speed.travel) %}
{% endif %}
{% set _dummy = output_txt.append("fw_retract: %s" % tl.extruder.fw_retract) %}
{% if not tl.extruder.fw_retract %}
{% set _dummy = output_txt.append("retract: %s mm speed: %s mm/s" % (tl.extruder.retract, tl.speed.retract)) %}
{% set _dummy = output_txt.append("extrude: %s mm speed: %s mm/s" % (tl.extruder.extrude, tl.speed.extrude)) %}
{% endif %}
{% set _dummy = output_txt.append("verbose: %s" % tl.verbose) %}
{action_respond_info(output_txt|join("\n"))}
################################################################################################
# #
# Use _SET_TIMELAPSE_SETUP [ENABLE=value] [VERBOSE=value] [PARK_ENABLE=value] [PARK_POS=value] #
# [PARK_TIME=value] [CUSTOM_POS_X=value] [CUSTOM_POS_Y=value] #
# [CUSTOM_POS_DZ=value][TRAVEL_SPEED=value] [RETRACT_SPEED=value] #
# [EXTRUDE_SPEED=value] [EXTRUDE_DISTANCE=value] #
# [RETRACT_DISTANCE=value] [FW_RETRACT=value] #
# #
################################################################################################
[gcode_macro _SET_TIMELAPSE_SETUP]
description: Set user parameters for timelapse
gcode:
{% set tl = printer['gcode_macro TIMELAPSE_TAKE_FRAME'] %}
##### get min and max bed size #####
{% set min = printer.toolhead.axis_minimum %}
{% set max = printer.toolhead.axis_maximum %}
{% set round_bed = True if printer.configfile.settings.printer.kinematics is in ['delta','polar','rotary_delta','winch']
else False %}
{% set park = {'min' : {'x': (min.x / 1.42)|round(3) if round_bed else min.x|round(3),
'y': (min.y / 1.42)|round(3) if round_bed else min.y|round(3)},
'max' : {'x': (max.x / 1.42)|round(3) if round_bed else max.x|round(3),
'y': (max.y / 1.42)|round(3) if round_bed else max.y|round(3)},
'center': {'x': (max.x-(max.x-min.x)/2)|round(3),
'y': (max.y-(max.y-min.y)/2)|round(3)}} %}
##### set new values #####
{% if params.ENABLE %}
{% if params.ENABLE|lower is in ['true', 'false'] %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=enable VALUE={True if params.ENABLE|lower == 'true' else False}
{% else %}
{action_raise_error("ENABLE=%s not supported. Allowed values are [True, False]" % params.ENABLE|capitalize)}
{% endif %}
{% endif %}
{% if params.VERBOSE %}
{% if params.VERBOSE|lower is in ['true', 'false'] %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=verbose VALUE={True if params.VERBOSE|lower == 'true' else False}
{% else %}
{action_raise_error("VERBOSE=%s not supported. Allowed values are [True, False]" % params.VERBOSE|capitalize)}
{% endif %}
{% endif %}
{% if params.CUSTOM_POS_X %}
{% if params.CUSTOM_POS_X|float >= min.x and params.CUSTOM_POS_X|float <= max.x %}
{% set _dummy = tl.park.custom.update({'x':params.CUSTOM_POS_X|float|round(3)}) %}
{% else %}
{action_raise_error("CUSTOM_POS_X=%s must be within [%s - %s]" % (params.CUSTOM_POS_X, min.x, max.x))}
{% endif %}
{% endif %}
{% if params.CUSTOM_POS_Y %}
{% if params.CUSTOM_POS_Y|float >= min.y and params.CUSTOM_POS_Y|float <= max.y %}
{% set _dummy = tl.park.custom.update({'y':params.CUSTOM_POS_Y|float|round(3)}) %}
{% else %}
{action_raise_error("CUSTOM_POS_Y=%s must be within [%s - %s]" % (params.CUSTOM_POS_Y, min.y, max.y))}
{% endif %}
{% endif %}
{% if params.CUSTOM_POS_DZ %}
{% if params.CUSTOM_POS_DZ|float >= min.z and params.CUSTOM_POS_DZ|float <= max.z %}
{% set _dummy = tl.park.custom.update({'dz':params.CUSTOM_POS_DZ|float|round(3)}) %}
{% else %}
{action_raise_error("CUSTOM_POS_DZ=%s must be within [%s - %s]" % (params.CUSTOM_POS_DZ, min.z, max.z))}
{% endif %}
{% endif %}
{% if params.PARK_ENABLE %}
{% if params.PARK_ENABLE|lower is in ['true', 'false'] %}
{% set _dummy = tl.park.update({'enable':True if params.PARK_ENABLE|lower == 'true' else False}) %}
{% else %}
{action_raise_error("PARK_ENABLE=%s not supported. Allowed values are [True, False]" % params.PARK_ENABLE|capitalize)}
{% endif %}
{% endif %}
{% if params.PARK_POS %}
{% if params.PARK_POS|lower is in ['center','front_left','front_right','back_left','back_right','custom','x_only','y_only'] %}
{% set dic = {'center' : {'x': park.center.x , 'y': park.center.y , 'dz': 1 },
'front_left' : {'x': park.min.x , 'y': park.min.y , 'dz': 0 },
'front_right' : {'x': park.max.x , 'y': park.min.y , 'dz': 0 },
'back_left' : {'x': park.min.x , 'y': park.max.y , 'dz': 0 },
'back_right' : {'x': park.max.x , 'y': park.max.y , 'dz': 0 },
'custom' : {'x': tl.park.custom.x, 'y': tl.park.custom.y, 'dz': tl.park.custom.dz},
'x_only' : {'x': tl.park.custom.x, 'y': 'none' , 'dz': tl.park.custom.dz},
'y_only' : {'x': 'none' , 'y': tl.park.custom.y, 'dz': tl.park.custom.dz}} %}
{% set _dummy = tl.park.update({'pos':params.PARK_POS|lower}) %}
{% set _dummy = tl.park.update({'coord':dic[tl.park.pos]}) %}
{% else %}
{action_raise_error("PARK_POS=%s not supported. Allowed values are [CENTER, FRONT_LEFT, FRONT_RIGHT, BACK_LEFT, BACK_RIGHT, CUSTOM, X_ONLY, Y_ONLY]"
% params.PARK_POS|upper)}
{% endif %}
{% endif %}
{% if params.PARK_TIME %}
{% if params.PARK_TIME|float >= 0.0 %}
{% set _dummy = tl.park.update({'time':params.PARK_TIME|float|round(3)}) %}
{% else %}
{action_raise_error("PARK_TIME=%s must be a positive number" % params.PARK_TIME)}
{% endif %}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=park VALUE="{tl.park}"
{% if params.TRAVEL_SPEED %}
{% if params.TRAVEL_SPEED|float > 0.0 %}
{% set _dummy = tl.speed.update({'travel':params.TRAVEL_SPEED|float|round(3)}) %}
{% else %}
{action_raise_error("TRAVEL_SPEED=%s must be larger than 0" % params.TRAVEL_SPEED)}
{% endif %}
{% endif %}
{% if params.RETRACT_SPEED %}
{% if params.RETRACT_SPEED|float > 0.0 %}
{% set _dummy = tl.speed.update({'retract':params.RETRACT_SPEED|float|round(3)}) %}
{% else %}
{action_raise_error("RETRACT_SPEED=%s must be larger than 0" % params.RETRACT_SPEED)}
{% endif %}
{% endif %}
{% if params.EXTRUDE_SPEED %}
{% if params.EXTRUDE_SPEED|float > 0.0 %}
{% set _dummy = tl.speed.update({'extrude':params.EXTRUDE_SPEED|float|round(3)}) %}
{% else %}
{action_raise_error("EXTRUDE_SPEED=%s must be larger than 0" % params.EXTRUDE_SPEED)}
{% endif %}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=speed VALUE="{tl.speed}"
{% if params.EXTRUDE_DISTANCE %}
{% if params.EXTRUDE_DISTANCE|float >= 0.0 %}
{% set _dummy = tl.extruder.update({'extrude':params.EXTRUDE_DISTANCE|float|round(3)}) %}
{% else %}
{action_raise_error("EXTRUDE_DISTANCE=%s must be specified as positiv number" % params.EXTRUDE_DISTANCE)}
{% endif %}
{% endif %}
{% if params.RETRACT_DISTANCE %}
{% if params.RETRACT_DISTANCE|float >= 0.0 %}
{% set _dummy = tl.extruder.update({'retract':params.RETRACT_DISTANCE|float|round(3)}) %}
{% else %}
{action_raise_error("RETRACT_DISTANCE=%s must be specified as positiv number" % params.RETRACT_DISTANCE)}
{% endif %}
{% endif %}
{% if params.FW_RETRACT %}
{% if params.FW_RETRACT|lower is in ['true', 'false'] %}
{% if 'firmware_retraction' in printer.configfile.settings %}
{% set _dummy = tl.extruder.update({'fw_retract': True if params.FW_RETRACT|lower == 'true' else False}) %}
{% else %}
{% set _dummy = tl.extruder.update({'fw_retract':False}) %}
{% if params.FW_RETRACT|capitalize == 'True' %}
{action_raise_error("[firmware_retraction] not defined in printer.cfg. Can not enable fw_retract")}
{% endif %}
{% endif %}
{% else %}
{action_raise_error("FW_RETRACT=%s not supported. Allowed values are [True, False]" % params.FW_RETRACT|capitalize)}
{% endif %}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=extruder VALUE="{tl.extruder}"
{% if printer.configfile.settings['gcode_macro pause'] is defined %}
{% set _dummy = tl.macro.update({'pause': printer.configfile.settings['gcode_macro pause'].rename_existing}) %}
{% endif %}
{% if printer.configfile.settings['gcode_macro resume'] is defined %}
{% set _dummy = tl.macro.update({'resume': printer.configfile.settings['gcode_macro resume'].rename_existing}) %}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=macro VALUE="{tl.macro}"
##########################################################################
# #
# TIMELAPSE_TAKE_FRAME: take the next picture #
# #
##########################################################################
######################### definition #########################
## enable: enable or disable the next frame. Valid inputs: [True, False]
## takingframe: internal use. Valid inputs: [True, False]
##
## park.enable: enable or disable to park the head while taking a picture. Valid inputs: [True, False]
## park.pos : used position for parking. Valid inputs: [center, front_left, front_right, back_left, back_right, custom, x_only, y_only]
## park.time : used for the debug macro. Time in s
## park.custom.x, park.custom.y: coordinates of the custom parkposition. Unit [mm]
## park.custom.dz : custom z hop for the picture. Unit [mm]
## park.coord : internal use
##
## extruder.fw_retract: enable disable fw retraction [True,False]
## extruder.extrude : filament extruded at the end of park. Unit [mm]
## extruder.retract : filament retract at the start of park. Unit [mm]
##
## speed.travel : used speed for travel from and to the park positon. Unit: [mm/min]
## speed.retract: used speed for retract [mm/min]
## speed.extrude: used speed for extrude [mm/min]
##
## verbose: Enable mesage output of TIMELAPSE_TAKE_FRAME
##
## restore.absolute.coordinates: internal use
## restore.absolute.extrude : internal use
## restore.speed : internal use
## restore.e : internal use
## restore.factor.speed : internal use
## restore.factor.extrude : internal use
##
## macro.pause : internal use
## macro.resume : internal use
##
## is_paused: internal use
###############################################################
[gcode_macro TIMELAPSE_TAKE_FRAME]
description: Take Timelapse shoot
variable_enable: False
variable_takingframe: False
variable_park: {'enable': False,
'pos' : 'center',
'time' : 0.1,
'custom': {'x': 0, 'y': 0, 'dz': 0},
'coord' : {'x': 0, 'y': 0, 'dz': 0}}
variable_extruder: {'fw_retract': False,
'retract': 1.0,
'extrude': 1.0}
variable_speed: {'travel': 100,
'retract': 15,
'extrude': 15}
variable_verbose: True
variable_restore: {'absolute': {'coordinates': True, 'extrude': True}, 'speed': 1500, 'e':0, 'factor': {'speed': 1.0, 'extrude': 1.0}}
variable_macro: {'pause': 'PAUSE', 'resume': 'RESUME'}
variable_is_paused: False
gcode:
{% set hyperlapse = True if params.HYPERLAPSE and params.HYPERLAPSE|lower =='true' else False %}
{% if enable %}
{% if (hyperlapse and printer['gcode_macro HYPERLAPSE'].run) or
(not hyperlapse and not printer['gcode_macro HYPERLAPSE'].run) %}
{% if park.enable %}
{% set pos = {'x': 'X' + park.coord.x|string if park.pos != 'y_only' else '',
'y': 'Y' + park.coord.y|string if park.pos != 'x_only' else '',
'z': 'Z'+ [printer.gcode_move.gcode_position.z + park.coord.dz, printer.toolhead.axis_maximum.z]|min|string} %}
{% set restore = {'absolute': {'coordinates': printer.gcode_move.absolute_coordinates,
'extrude' : printer.gcode_move.absolute_extrude},
'speed' : printer.gcode_move.speed,
'e' : printer.gcode_move.gcode_position.e,
'factor' : {'speed' : printer.gcode_move.speed_factor,
'extrude': printer.gcode_move.extrude_factor}} %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=restore VALUE="{restore}"
{% if not printer[printer.toolhead.extruder].can_extrude %}
{% if verbose %}{action_respond_info("Timelapse: Warning, minimum extruder temperature not reached!")}{% endif %}
{% else %}
{% if extruder.fw_retract %}
G10
{% else %}
M83 ; insure relative extrusion
G0 E-{extruder.retract} F{speed.retract * 60}
{% endif %}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=is_paused VALUE=True
{macro.pause} ; execute the klipper PAUSE command
SET_GCODE_OFFSET X=0 Y=0 ; this will insure that the head parks always at the same position in a multi setup
G90 ; insure absolute move
{% if "xyz" not in printer.toolhead.homed_axes %}
{% if verbose %}{action_respond_info("Timelapse: Warning, axis not homed yet!")}{% endif %}
{% else %}
G0 {pos.x} {pos.y} {pos.z} F{speed.travel * 60}
{% endif %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=takingframe VALUE=True
UPDATE_DELAYED_GCODE ID=_WAIT_TIMELAPSE_TAKE_FRAME DURATION=0.5
M400
{% endif %}
_TIMELAPSE_NEW_FRAME HYPERLAPSE={hyperlapse}
{% endif %}
{% else %}
{% if verbose %}{action_respond_info("Timelapse: disabled, take frame ignored")}{% endif %}
{% endif %}
[gcode_macro _TIMELAPSE_NEW_FRAME]
description: action call for timelapse shoot. must be a seperate macro
gcode:
{action_call_remote_method("timelapse_newframe",
macropark=printer['gcode_macro TIMELAPSE_TAKE_FRAME'].park,
hyperlapse=params.HYPERLAPSE)}
[delayed_gcode _WAIT_TIMELAPSE_TAKE_FRAME]
gcode:
{% set tl = printer['gcode_macro TIMELAPSE_TAKE_FRAME'] %}
{% set factor = {'speed': printer.gcode_move.speed_factor, 'extrude': printer.gcode_move.extrude_factor} %}
{% if tl.takingframe %}
UPDATE_DELAYED_GCODE ID=_WAIT_TIMELAPSE_TAKE_FRAME DURATION=0.5
{% else %}
{tl.macro.resume} VELOCITY={tl.speed.travel} ; execute the klipper RESUME command
SET_GCODE_VARIABLE MACRO=TIMELAPSE_TAKE_FRAME VARIABLE=is_paused VALUE=False
{% if not printer[printer.toolhead.extruder].can_extrude %}
{action_respond_info("Timelapse: Warning minimum extruder temperature not reached!")}
{% else %}
{% if tl.extruder.fw_retract %}
G11
{% else %}
G0 E{tl.extruder.extrude} F{tl.speed.extrude * 60}
G0 F{tl.restore.speed}
{% if tl.restore.absolute.extrude %}
M82
G92 E{tl.restore.e}
{% endif %}
{% endif %}
{% endif %}
{% if tl.restore.factor.speed != factor.speed %} M220 S{(factor.speed*100)|round(0)} {% endif %}
{% if tl.restore.factor.extrude != factor.extrude %} M221 S{(factor.extrude*100)|round(0)} {% endif %}
{% if not tl.restore.absolute.coordinates %} G91 {% endif %}
{% endif %}
####################################################################################################
# #
# HYPERLAPSE: Starts or stops a Hyperlapse video #
# Usage: HYPERLAPSE ACTION=START [CYCLE=time] starts a hyperlapse with cycle time (default 30 sec) #
# HYPERLAPSE ACTION=STOP stops the hyperlapse recording #
# #
####################################################################################################
######################### definition #########################
## cycle: cycle time in seconds
## run: internal use [True/False]
###############################################################
[gcode_macro HYPERLAPSE]
description: Start/Stop a hyperlapse recording
variable_cycle: 0
variable_run: False
gcode:
{% set cycle = params.CYCLE|default(30)|int %}
{% if params.ACTION and params.ACTION|lower == 'start' %}
{action_respond_info("Hyperlapse: frames started (Cycle %d sec)" % cycle)}
SET_GCODE_VARIABLE MACRO=HYPERLAPSE VARIABLE=run VALUE=True
SET_GCODE_VARIABLE MACRO=HYPERLAPSE VARIABLE=cycle VALUE={cycle}
UPDATE_DELAYED_GCODE ID=_HYPERLAPSE_LOOP DURATION={cycle}
TIMELAPSE_TAKE_FRAME HYPERLAPSE=True
{% elif params.ACTION and params.ACTION|lower == 'stop' %}
{% if run %}{action_respond_info("Hyperlapse: frames stopped")}{% endif %}
SET_GCODE_VARIABLE MACRO=HYPERLAPSE VARIABLE=run VALUE=False
UPDATE_DELAYED_GCODE ID=_HYPERLAPSE_LOOP DURATION=0
{% else %}
{action_raise_error("Hyperlapse: No valid input parameter
Use:
- HYPERLAPSE ACTION=START [CYCLE=time]
- HYPERLAPSE ACTION=STOP")}
{% endif %}
[delayed_gcode _HYPERLAPSE_LOOP]
gcode:
UPDATE_DELAYED_GCODE ID=_HYPERLAPSE_LOOP DURATION={printer["gcode_macro HYPERLAPSE"].cycle}
TIMELAPSE_TAKE_FRAME HYPERLAPSE=True
##########################################################################
# #
# TIMELAPSE_RENDER: Render the video at print end #
# #
##########################################################################
######################### definition #########################
## render: internal use. Valid inputs: [True, False]
## run_identifier: internal use. Valid input [0 .. 3]
###############################################################
[gcode_macro TIMELAPSE_RENDER]
description: Render Timelapse video and wait for the result
variable_render: False
variable_run_identifier: 0
gcode:
{action_respond_info("Timelapse: Rendering started")}
{action_call_remote_method("timelapse_render", byrendermacro="True")}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_RENDER VARIABLE=render VALUE=True
{printer.configfile.settings['gcode_macro pause'].rename_existing} ; execute the klipper PAUSE command
UPDATE_DELAYED_GCODE ID=_WAIT_TIMELAPSE_RENDER DURATION=0.5
[delayed_gcode _WAIT_TIMELAPSE_RENDER]
gcode:
{% set ri = printer['gcode_macro TIMELAPSE_RENDER'].run_identifier % 4 %}
SET_GCODE_VARIABLE MACRO=TIMELAPSE_RENDER VARIABLE=run_identifier VALUE={ri + 1}
{% if printer['gcode_macro TIMELAPSE_RENDER'].render %}
M117 Rendering {['-','\\','|','/'][ri]}
UPDATE_DELAYED_GCODE ID=_WAIT_TIMELAPSE_RENDER DURATION=0.5
{% else %}
{action_respond_info("Timelapse: Rendering finished")}
M117
{printer.configfile.settings['gcode_macro resume'].rename_existing} ; execute the klipper RESUME command
{% endif %}
##########################################################################
# #
# TEST_STREAM_DELAY: Helper macro to find stream and park delay #
# #
##########################################################################
[gcode_macro TEST_STREAM_DELAY]
description: Helper macro to find stream and park delay
gcode:
{% set min = printer.toolhead.axis_minimum %}
{% set max = printer.toolhead.axis_maximum %}
{% set act = printer.toolhead.position %}
{% set tl = printer['gcode_macro TIMELAPSE_TAKE_FRAME'] %}
{% if act.z > 5.0 %}
G0 X{min.x + 5.0} F{tl.speed.travel|int * 60}
G0 X{(max.x-min.x)/2}
G4 P{tl.park.time|float * 1000}
_TIMELAPSE_NEW_FRAME HYPERLAPSE=FALSE
G0 X{max.x - 5.0}
{% else %}
{action_raise_error("Toolhead z %.3f to low. Please place head above z = 5.0" % act.z)}
{% endif %}

File diff suppressed because it is too large Load Diff

View File

@@ -1,60 +0,0 @@
#ifndef KLIPPY_GCODES_H
#define KILPPY_GCODES_H
#include <iostream>
#define AXIS_X "X"
#define AXIS_Y "Y"
#define AXIS_Z "Z"
#define HOME "G28"
#define HOME_X "G28 X"
#define HOME_Y "G28 Y"
#define HOME_Z "G28 Z"
#define HOME_XY "G28 X Y"
#define Z_TILT "Z_TILT_ADJUST"
#define QUAD_GANTRY_LEVEL "QUAD_GANTRY_LEVEL"
#define MOVE "G1"
#define MOVE_ABSOLUTE "G90"
#define MOVE_RELATIVE "G91"
#define EXTRUDE_ABS "M82"
#define EXTRUDE_REL "M83"
#define SET_EXT_TEMP "M104"
#define SET_BED_TEMP "M140"
#define SET_EXT_FACTOR "M221"
#define SET_FAN_SPEED "M106"
#define SET_SPD_FACTOR "M220"
#define PROBE_CALIBRATE "PROBE_CALIBRATE"
#define Z_ENDSTOP_CALIBRATE "Z_ENDSTOP_CALIBRATE"
#define TESTZ "TESTZ Z="
#define ABORT "ABORT"
#define ACCEPT "ACCEPT"
#define SAVE_CONFIG "SAVE_CONFIG"
#define RESTART "RESTART"
#define FIRMWARE_RESTART = "FIRMWARE_RESTART"
std::string set_bed_temp(int temp);
std::string set_ext_temp(int temp, int tool);
std::string set_heater_temp(std::string heater, int temp);
std::string set_temp_fan_temp(std::string temp_fan, int temp);
std::string set_fan_speed(int speed);
std::string set_fan0_speed(int speed);
std::string set_fan2_speed(int speed);
std::string set_fan3_speed(int speed);
std::string set_extrusion_rate(std::string rate);
std::string set_speed_rate(std::string rate);
std::string testz_move(std::string dist);
std::string extrude(std::string dist, int speed);
std::string bed_mesh_load(std::string profile);
std::string bed_mesh_remove(std::string profile);
std::string bed_mesh_save(std::string profile);
#endif

View File

@@ -1,41 +0,0 @@
#ifndef KLIPPY_REST_H
#define KLIPPY_REST_H
#include <iostream>
#include "./HTTPRequest.hpp"
std::string get_server_files_list(std::string ip, std::string port);
std::string get_server_files_directory(std::string ip, std::string port);
std::string server_files_metadata(std::string ip, std::string port, std::string filename);
/* 打印机对象参数获取 */
std::string printer_objects_query(std::string ip, std::string port, std::string parameter);
/* 打印管理 */
// 打印文件
std::string printer_print_start(std::string ip, std::string port, std::string filename);
// 暂停打印
std::string printer_print_pause(std::string ip, std::string port);
// 继续打印
std::string printer_print_resume(std::string ip, std::string port);
// 取消打印
std::string printer_print_cancel(std::string ip, std::string port);
/* 打印机状态 */
std::string get_server_info(std::string ip, std::string port);
std::string get_oneshot_token(std::string ip, std::string port);
std::string get_printer_info(std::string ip, std::string port);
/* File Operations */
std::string delete_file_delete(std::string ip, std::string port, std::string filepath);
std::string get_thumbnail_stream(std::string ip, std::string port, std::string thumbnail);
std::string send_request(std::string ip, std::string port, std::string method, std::string request_type);
// std::string send_post_request(std::string ip, std::string port, std::string method);
#endif

View File

@@ -1,137 +0,0 @@
#ifndef MAKERBASE_CLIENT_H
#define MAKERBASE_CLIENT_H
// 不包含TLS Client
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
// 包含TLS Client
// #include <websocketpp/config/asio_client.hpp>
// #include <websocketpp/client.hpp>
#include <websocketpp/common/thread.hpp>
#include <websocketpp/common/memory.hpp>
#include <string>
#include <locale>
#include <codecvt>
#include "./mks_log.h"
#include "./MoonrakerAPI.h"
#include "./MakerbaseParseMessage.h"
extern std::string message;
extern bool is_get_message;
typedef websocketpp::client<websocketpp::config::asio_client> client;
// 保存一个连接的metadata
class connection_metadata {
public:
typedef websocketpp::lib::shared_ptr<connection_metadata> ptr;
connection_metadata(websocketpp::connection_hdl hdl, std::string url) {
this->m_Hdl = hdl;
this->m_Status = "Connecting";
this->m_Url = url;
this->m_Server = "N/A";
}
void on_open(client * c, websocketpp::connection_hdl hdl) {
this->m_Status = "Open";
// c->get_alog().write(websocketpp::log::alevel::app, "Open client, the url is" + this->m_Url);
client::connection_ptr con = c->get_con_from_hdl(hdl);
m_Server = con->get_response_header("Server");
MKSLOG("websocket连接成功\n");
// std::cout << this->m_Status << "the m_Server is" + m_Server << std::endl;
}
void on_fail(client * c, websocketpp::connection_hdl hdl)
{
this->m_Status = "Failed";
c->get_alog().write(websocketpp::log::alevel::app, "Connection Failed");
client::connection_ptr con = c->get_con_from_hdl(hdl);
m_Server = con->get_response_header("Server");
m_Error_reason = con->get_ec().message();
// std::cout << this->m_Status << "the m_Server is " + m_Server << std::endl;
std::cout << "连接服务端失败,请重新连接" << std::endl;
}
void on_close(client * c, websocketpp::connection_hdl hdl)
{
this->m_Status = "Closed";
client::connection_ptr con = c->get_con_from_hdl(hdl);
std::stringstream s;
s << "close code: " << con->get_remote_close_code() << " ("
<< websocketpp::close::status::get_string(con->get_remote_close_code())
<< "), close reason: " << con->get_remote_close_reason();
m_Error_reason = s.str();
// std::cout << this->m_Status << "the m_Server is " + m_Server << std::endl;
}
void on_message(websocketpp::connection_hdl, client::message_ptr msg) {
if (msg->get_opcode() == websocketpp::frame::opcode::text) {
// std::string message = msg->get_payload();
// std::cout << "收到来自服务器的消息:" << message << std::endl;
// this->m_Message = msg->get_payload();
message = msg->get_payload();
is_get_message = true;
} else {
std::string message = websocketpp::utility::to_hex(msg->get_payload());
}
}
websocketpp::connection_hdl get_hdl() const {
return m_Hdl;
}
std::string get_status() const {
return m_Status;
}
private:
websocketpp::connection_hdl m_Hdl; // websocketpp表示连接的编号
std::string m_Status; // 连接自动状态
std::string m_Url; // 连接的URI
std::string m_Server; // 服务器信息
std::string m_Error_reason; // 错误原因
std::string m_Message; // 回收到的消息
bool is_recv_result = false; // 是否已经收到 result 为 "OK" 的回调信息
};
class MakerbaseClient
{
public:
MakerbaseClient(std::string host, std::string port);
virtual~MakerbaseClient();
public:
bool Connect(std::string const & url);
bool Close(std::string reason = "");
bool Send(std::string message);
bool GetIsConnected();
std::string GetStatus();
connection_metadata::ptr GetConnectionMetadataPtr();
std::string GetURL();
private:
bool is_connected = false; // 连接判断
std::string status = "none"; // 连接的状态,用字符串表示
std::string host; // 目标地址 host
std::string port; // 目标地址 port
std::string sending_message; // 发送的消息
connection_metadata::ptr m_ConnectionMetadataPtr;
client m_WebsocketClient;
websocketpp::lib::shared_ptr<websocketpp::lib::thread> m_Thread; // 线程
};
#endif // !MAKERBASE_CLIENT_H

View File

@@ -1,261 +0,0 @@
#ifndef MAKERBASE_COMMAND_H
#define MAKERBASE_COMMAND_H
#include <map>
/**
* @brief 接收的执行与API映射定义
*
*/
static std::map<int, std::string> method2command = {
{0x01, "server.connection.identify"},
{0x02, "server.websocket.id"},
{0x03, "printer.info"},
{0x04, "printer.emergency_stop"},
{0x05, "printer.restart"},
{0x06, "printer.firmware_restart"},
{0x11, "printer.objects.list"},
{0x12, "printer.objects.query"},
{0x13, "printer.objects.subscribe"},
{0x14, "printer.query_endstops.status"},
{0x15, "server.info"},
{0x16, "server.config"},
{0x17, "server.temperature_store"},
{0x18, "server.gcode_store"},
{0x19, "server.restart"},
{0x21, "printer.gcode.script"},
{0x22, "printer.gcode.help"},
{0x31, "printer.print.start"},
{0x32, "printer.print.pause"},
{0x33, "printer.print.resume"},
{0x34, "printer.print.cancel"},
{0x41, "machine.system_info"},
{0x42, "machine.shutdown"},
{0x43, "machine.reboot"},
{0x44, "machine.services.restart"},
{0x45, "machine.services.stop"},
{0x46, "machine.services.start"},
{0x47, "machine.proc_stats"},
{0x51, "server.files.list"},
{0x52, "server.files.metadata"},
{0x53, "server.files.get_directory"},
{0x54, "server.files.post_directory"},
{0x55, "server.files.delete_directory"},
{0x56, "server.files.move"},
{0x57, "server.files.copy"},
// 0x58 留给 文件下载 功能只有http请求可以用
// 0x59 留给 上传文件 功能只有http请求可以用
{0x5a, "server.files.delete_file"},
// 0x5b 留给 下载klippy.log 功能只有http请求可以用
// 0x5c 留给 下载moonraker.log 功能只有http请求可以用
// 0x61 登录用户
// 0x62 注销当前用户
// 0x63 获取当前用户
// 0x64 创建用户
// 0x65 删除用户
// 0x66 列出可用用户
// 0x67 重置用户密码
// 0x68 刷新 JSON Web 令牌
// 0x69 生成 Oneshot 令牌
// 0x6a 检索有关授权端点的信息
// 0x6b 获取当前 API 密钥
// 0x6c 生成新的 API 密钥
{0x71, "server.database.list"},
{0x72, "server.database.get_item"},
{0x73, "server.database.post_item"},
{0x74, "server.database.delete_item"},
{0x81, "server.job_queue.status"},
{0x82, "server.job_queue.post_job"},
{0x83, "server.job_queue.delete_job"},
{0x84, "server.job_queue.pause"},
{0x85, "server.job_queue.start"},
{0x86, "server.announcements.list"},
{0x87, "server.announcements.update"},
{0x88, "server.announcements.dismiss"},
{0x89, "server.announcements.feeds"},
{0x8a, "server.announcements.post_feed"},
{0x8b, "server.announcements.delete_feed"},
{0x8c, "machine.update.status"},
{0x90, "machine.update.full"},
{0x91, "machine.update.status"},
{0x92, "machine.update.moonraker"},
{0x93, "machine.update.klipper"},
{0x94, "machine.update.client"},
{0x95, "machine.update.system"},
{0x96, "machine.update.recover"},
{0xa1, "machine.device_power.devices"},
{0xa2, "machine.device_power.get_device"},
{0xa3, "machine.device_power.post_device"},
{0xa4, "machine.device_power.status"},
{0xa5, "machine.device_power.on"},
{0xa6, "machine.device_power.off"},
{0xb1, "machine.wled.strips"},
{0xb2, "machine.wled.status"},
{0xb3, "machine.wled.on"},
{0xb4, "machine.wled.off"},
{0xb5, "machine.wled.toggle"},
{0xb6, "machine.wled.get_strip"},
// OctoPrint API 模拟 暂不添加 0xc 字段保留
{0xd1, "server.history.list"},
{0xd2, "server.history.totals"},
{0xd3, "server.history.reset_totals"},
{0xd4, "server.history.get_job"},
{0xd5, "server.history.delete_job"},
{0xe1, "server.mqtt.publish"},
{0xe2, "server.mqtt.subscribe"},
{0x101, "server.webcams.list"},
{0x102, "server.webcams.get_item"},
{0x103, "server.webcams.post_item"},
{0x104, "server.webcams.delete_item"},
{0x105, "server.webcams.test"},
{0xf1, "server.extensions.list"},
{0xf2, "server.extensions.request"},
{0xf3, "connection.send_event"}
};
static std::map<int, int> method2id = {
{0x01, 4656},
{0x02, 4656},
{0x03, 5445},
{0x04, 4564},
{0x05, 4894},
{0x06, 8463},
{0x11, 1454},
{0x12, 4654},
{0x13, 5434},
{0x14, 3456},
{0x15, 9546},
{0x16, 5616},
{0x17, 2313},
{0x18, 7643},
{0x19, 4656},
{0x21, 7466},
{0x22, 4645},
{0x31, 4654},
{0x32, 4564},
{0x33, 1465},
{0x34, 2578},
{0x41, 4665},
{0x42, 4665},
{0x43, 4665},
{0x44, 4656},
{0x45, 4645},
{0x46, 4645},
{0x47, 7896},
{0x51, 4644},
{0x52, 3545},
{0x53, 5644},
{0x54, 6548},
{0x55, 6545},
{0x56, 5664},
{0x57, 5623},
// 0x58
// 0x59
{0x5a, 1323},
// 0x5b
// 0x5c
// 0x61 登录用户
// 0x62 注销当前用户
// 0x63 获取当前用户
// 0x64 创建用户
// 0x65 删除用户
// 0x66 列出可用用户
// 0x67 重置用户密码
// 0x68 刷新 JSON Web 令牌
// 0x69 生成 Oneshot 令牌
// 0x6a 检索有关授权端点的信息
// 0x6b 获取当前 API 密钥
// 0x6c 生成新的 API 密钥
{0x71, 8694},
{0x72, 5644},
{0x73, 4654},
{0x74, 4654},
{0x81, 4654},
{0x82, 4654},
{0x83, 4654},
{0x84, 4654},
{0x85, 4654},
{0x86, 4654},
{0x87, 4654},
{0x88, 4654},
{0x89, 4654},
{0x8a, 4654},
{0x8b, 4654},
{0x8c, 4644},
{0x90, 4645},
{0x91, 4644},
{0x92, 4645},
{0x93, 5745},
{0x94, 8546},
{0x95, 4564},
{0x96, 4564},
{0xa1, 5646},
{0xa2, 4564},
{0xa3, 4564},
{0xa4, 4564},
{0xa5, 4564},
{0xa6, 4564},
{0xb1, 7123},
{0xb2, 7124},
{0xb3, 7125},
{0xb4, 7126},
{0xb5, 7127},
{0xb6, 7128},
// OctoPrint API 模拟 暂不添加 0xc 字段保留
{0xd1, 5656},
{0xd2, 5656},
{0xd3, 5534},
{0xd4, 4564},
{0xd5, 5534},
{0xe1, 4564},
{0xe2, 4564},
{0xf1, 4564},
{0xf2, 4564},
// 0xf2 without id
{0x101, 4654},
{0x102, 4654},
{0x103, 4654},
{0x104, 4654},
{0x105, 4654}
};
#endif

View File

@@ -1,39 +0,0 @@
/**
* 进程间通信暂时不使用,此部分为消息队列,过程可能会出现阻塞现象,导致后面加载不起来
*
*/
#ifndef MAKERBASEIPC_H
#define MAKERBASEIPC_H
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#define MKS_SEM_1_NAME "mkssem1" // 定义内部使用的信号量名称
#define MKS_SEM_2_NAME "mkssem2" // 定义内部使用的信号量名称
#define MKS_MSG_ID 318 // 定义消息队列 id
struct commandBuf
{
long mtype;
char mtext[1024];
};
struct commandBuf cmd_to_rcv;
int msqid;
int ret;
sem_t *sem1 = NULL; // 保存信号量地址
sem_t *sem2 = NULL; // 保存信号量地址
ssize_t rcv_bytes; // 保存从队列读取的字节数
#endif

View File

@@ -1,9 +0,0 @@
#ifndef MAKERBASE_NETWORK_H
#define MAKERBASE_NETWORK_H
#include <iostream>
#include "./MakerbaseShell.h"
std::string get_wlan0_ip();
#endif

View File

@@ -1,20 +0,0 @@
#ifndef MAKERBASE_PANEL_H
#define MAKERBASE_PANEL_H
#include <iostream>
#include "nlohmann/json.hpp"
#define AXIS_X "X"
#define AXIS_Y "Y"
#define AXIS_Z "Z"
std::string home();
std::string homexy();
std::string z_tilt();
std::string quad_gantry_level();
std::string move(std::string axis, std::string dist, int speed);
std::string get_printer_object_status();
#endif

View File

@@ -1,43 +0,0 @@
#ifndef MAKERBASEPARSEINI_H
#define MAKERBASEPARSEINI_H
#define XINDI_PLUS 1
#define XINDI_MAX 0
#define XINDI_MINI 0
#include <iostream>
#include "./dictionary.h"
#include "./iniparser.h"
//#define INIPATH "/root/config.mksini"
#define INIPATH "/home/mks/klipper_config/config.mksini"
#ifdef XINDI_PLUS
#define VERSION_PATH "/root/xindi/version"
#elif XINDI_MAX
#define VERSION_PATH "/root/xindi/version-max"
#elif XINDI_MINI
#define VERSION_PATH "/root/xindi/version-4-3"
#endif
// std::string get_cfg_serial();
int mksini_load();
void mksini_free();
std::string mksini_getstring(std::string section, std::string key, std::string def);
int mksini_getint(std::string section, std::string key, int notfound);
double mksini_getdouble(std::string section, std::string key, double notfound);
bool mksini_getboolean(std::string section, std::string key, int notfound);
int mksini_set(std::string section, std::string key, std::string value);
void mksini_unset(std::string section, std::string key);
void mksini_save();
int mksversion_load();
void mksversion_free();
std::string mksversion_mcu(std::string def);
std::string mksversion_ui(std::string def);
std::string mksversion_soc(std::string def);
int updateini_load();
int progressini_load();
#endif

View File

@@ -1,11 +0,0 @@
#ifndef MAKERBASE_PARSE_MESSAGE
#define MAKERBASE_PARSE_MESSAGE
/**
* 通过发送的 method id 来获得相应的回调信息,使用不同的 response type id 可以通过
* switch 的方式,快速找到相应的解析方式
*
*/
void *json_parse(void *arg);
#endif

View File

@@ -1,18 +0,0 @@
#ifndef MAKERBASE_SERIAL_H
#define MAKERBASE_SERIAL_H
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <termios.h>
int set_option(int fd, int baudrate, int bits, unsigned char parity, unsigned char stopbit);
#endif

View File

@@ -1,11 +0,0 @@
#ifndef MAKERBASE_SHELL_H
#define MAKERBASE_SHELL_H
#include <stdio.h>
#include <string.h>
#define MAX_FILE_LEN 1024*4
void execute_cmd(const char *cmd, char *result);
#endif

View File

@@ -1,47 +0,0 @@
#ifndef MAKERBASE_WIFI_H
#define MAKERBASE_WIFI_H
#include "./MakerbaseShell.h"
void set_page_wifi_ssid_list(int pages);
void get_ssid_list_pages();
void get_wlan0_status();
bool detected_wlan0();
void split_scan_result(std::string result);
// void set_wpa_supplicant(std::string ssid, std::string psk);
// parse scan result
// std::string get_mac_from_result(std::string result);
// std::string get_frequency_from_result(std::string result);
// std::string get_signal_level_from_result(std::string result);
// std::string get_flags_from_result(std::string result);
// std::string get_ssid_from_result(std::string result);
//
void get_connected_ssid();
void get_current_wifi();
// void read_wpa_supplicant();
// std::string rescan();
std::string save_wpa_conf();
// void scan_results();
std::string wpa_cli(std::string command);
static std::string lookup(int freq);
/*
void mid_wifi_ssid_convert_utf8(unsigned char *ssid, char *bssid, int size);
unsigned char mid_wifi_ssid_convert_decimal(char ssid);
*/
size_t printf_decode(unsigned char *buf, size_t maxlen, const char *str);
int hex2byte(const char *hex);
static int hex2num(char c);
int parse_scan_results(char* scan_results);
#endif

View File

@@ -1,170 +0,0 @@
/**
* @file MoonrakerAPI.h
* @author Kenneth Lin (kenneth.lin.gd.cn@gmail.com)
* @brief Create APIs by reading moonraker.readthedocs.io
* @version 0.1
* @date 2022-07-06
*
* @copyright Copyright (c) 2022
*
*/
#ifndef MOONRAKERAPI_H
#define MOONRAKERAPI_H
#include <iostream>
#include "nlohmann/json.hpp"
nlohmann::json string2json(std::string response);
// API definition
// 👇 makerbase client 发起连接的json消息
#define STRING_IDENTIFY_CONNECTION "{\"jsonrpc\":\"2.0\",\"method\":\"server.connection.identify\",\"params\":{\"client_name\":\"makerbase-client\",\"version\":\"0.0.1\",\"type\":\"web\",\"url\":\"http://makerbase.com/test\"},\"id\":4656}"
#define STRING_GET_KLIPPY_HOST_INFORMATION "{\"jsonrpc\":\"2.0\",\"method\":\"printer.info\",\"id\":5445}"
// Function for creating json
inline std::string create_json_without_params(int cmd);
inline std::string create_json(int cmd, nlohmann::json params);
// Printer Administration
// std::string json_identify_connection(std::string client_name, std::string json_version, std::string type, std::string url);
std::string json_get_websocket_id();
std::string json_get_klippy_host_information();
std::string json_emergency_stop();
std::string json_host_restart();
std::string json_firmware_restart();
// Print Status
std::string json_list_available_printer_objects();
std::string json_query_printer_object_status(nlohmann::json objects);
std::string json_subscribe_to_printer_object_status(nlohmann::json objects);
std::string json_query_endstops();
std::string json_query_server_info();
std::string json_get_server_configuration();
std::string json_request_cached_temperature_data();
std::string json_request_cached_gcode_responses();
std::string json_restart_server();
// GCode APIs
std::string json_run_a_gcode(std::string script); // script 参数调用 KlippyGcodes.h 里面的相关函数执行
std::string json_get_gcode_help();
// Print Management
std::string json_print_a_file(std::string filename);
std::string json_pause_a_print();
std::string json_resume_a_print();
std::string json_cancel_a_print();
// Machine Commands
std::string json_get_system_info();
std::string json_shutdown_the_operating_system();
std::string json_reboot_the_operating_system();
std::string json_restart_a_system_service();
std::string json_stop_a_system_service();
std::string json_start_a_system_service();
std::string json_get_moonraker_process_stats();
// File Operations
std::string json_list_available_files();
std::string json_get_gcode_metadata(std::string path);
std::string json_get_directory_information(bool extended);
std::string json_create_directory(std::string path);
std::string json_delete_directory();
std::string json_move_a_file_or_directory();
std::string json_copy_a_file_or_directory();
std::string json_file_download();
std::string json_file_upload();
std::string json_file_delete(std::string path);
// std::string json_download_klippy_log();
// std::string json_download_moonraker_log();
// Authorization
// std::string json_login_user();
// std::string json_logout_current_user();
// std::string json_get_current_user();
// std::string json_create_user();
// std::string json_delete_user();
// std::string json_list_available_users();
// std::string json_reset_user_password();
// std::string json_generate_a_oneshot_token();
// std::string json_retrieve_information_about_authorization_endpoints();
// std::string json_get_the_current_api_key();
// std::string json_generate_a_new_api_key();
// Database APIs
std::string json_list_namespaces();
std::string json_get_database_item(std::string nsp, std::string key);
std::string json_add_database_item(std::string nsp, std::string key, int value);
std::string json_delete_database_item(std::string nsp, std::string key);
// Job Queue APIs
std::string json_retrieve_the_job_queue_status();
std::string json_enqueue_a_job(std::vector<std::string> filenames); // 需要传递字符串数组作为参数,后面再进行实现
std::string json_remove_a_job(std::vector<std::string> job_ids);
std::string json_pause_the_job_queue();
std::string json_start_the_job_queue();
// Announcement APIs
std::string json_list_announcements(bool incluede_dismissed);
std::string json_update_announcements();
std::string json_dismiss_an_announcement(std::string entry_id, int wake_time);
std::string json_list_announcement_feeds();
std::string json_add_an_announcement_feed(std::string name);
std::string json_remove_an_announcement_feed(std::string name);
// Webcam APIs
std::string json_list_webcams();
std::string json_get_webcam_information(std::string name);
std::string json_add_or_update_a_webcam(std::string name);
std::string json_delete_a_webcam(std::string name);
std::string json_test_a_webcam(std::string name);
// Update Manager APIs
std::string json_get_update_status(bool refresh);
// Perform a full update
std::string json_perform_a_full_update();
std::string json_update_moonraker();
std::string json_update_klipper();
std::string json_update_client(std::string name);
std::string json_update_system_packages();
std::string json_recover_a_corrupt_repo(std::string name, bool hard);
// Power APIs
std::string json_get_device_list();
std::string json_get_device_status(std::string device);
std::string json_get_device_state(std::string device, std::string action);
std::string json_get_batch_device_status(std::string dev_x[]);
std::string json_batch_power_on_devices(std::string dev_x[]); // 需要根据api做特殊处理
std::string json_batch_power_off_devices(std::string dev_x[]); // 需要根据api做特殊处理
// WLED APIs
std::string json_get_strips();
std::string json_get_strip_status();
std::string json_turn_strip_on();
std::string json_turn_strip_off();
std::string json_toggle_strip_on_off_state();
// std::string control_individual_strip_state(); // 这个比较特殊,后面再研究一下
// OctoPrint API emulation
// History APIs
std::string json_get_job_list(int limit, int start, float since, float before, std::string order = "desc");
std::string json_get_job_totals();
std::string json_reset_totals();
std::string json_get_a_single_job(std::string uid);
std::string json_delete_job(std::string uid);
// MQTT APIs
std::string json_publish_a_topic(std::string topic, std::string payload, int qos, bool retain, int timeout);
std::string json_subscribe_to_a_topic(std::string topic, int qos, int timeout);
// Extension APIs
// std::string json_list_extensions();
// std::string json_call_an_extension_method();
std::string json_send_an_agent_event();
// Websocket notifications
#endif

View File

@@ -1,9 +0,0 @@
#ifndef COMMON_H
#define COMMON_H
#include <iostream>
#include <vector>
void super_split(const std::string& s, std::vector<std::string>& v, const std::string& c);
#endif

View File

@@ -1,173 +0,0 @@
/*-------------------------------------------------------------------------*/
/**
@file dictionary.h
@author N. Devillard
@brief Implements a dictionary for string variables.
This module implements a simple dictionary object, i.e. a list
of string/string associations. This object is useful to store e.g.
informations retrieved from a configuration file (ini files).
*/
/*--------------------------------------------------------------------------*/
#ifndef _DICTIONARY_H_
#define _DICTIONARY_H_
/*---------------------------------------------------------------------------
Includes
---------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
/*---------------------------------------------------------------------------
New types
---------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
/**
@brief Dictionary object
This object contains a list of string/string associations. Each
association is identified by a unique string key. Looking up values
in the dictionary is speeded up by the use of a (hopefully collision-free)
hash function.
*/
/*-------------------------------------------------------------------------*/
typedef struct _dictionary_ {
int n ; /** Number of entries in dictionary */
ssize_t size ; /** Storage size */
char ** val ; /** List of string values */
char ** key ; /** List of string keys */
unsigned * hash ; /** List of hash values for keys */
} dictionary ;
/*---------------------------------------------------------------------------
Function prototypes
---------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
/**
@brief Compute the hash key for a string.
@param key Character string to use for key.
@return 1 unsigned int on at least 32 bits.
This hash function has been taken from an Article in Dr Dobbs Journal.
This is normally a collision-free function, distributing keys evenly.
The key is stored anyway in the struct so that collision can be avoided
by comparing the key itself in last resort.
*/
/*--------------------------------------------------------------------------*/
unsigned dictionary_hash(const char * key);
/*-------------------------------------------------------------------------*/
/**
@brief Create a new dictionary object.
@param size Optional initial size of the dictionary.
@return 1 newly allocated dictionary object.
This function allocates a new dictionary object of given size and returns
it. If you do not know in advance (roughly) the number of entries in the
dictionary, give size=0.
*/
/*--------------------------------------------------------------------------*/
dictionary * dictionary_new(size_t size);
/*-------------------------------------------------------------------------*/
/**
@brief Delete a dictionary object
@param d dictionary object to deallocate.
@return void
Deallocate a dictionary object and all memory associated to it.
*/
/*--------------------------------------------------------------------------*/
void dictionary_del(dictionary * vd);
/*-------------------------------------------------------------------------*/
/**
@brief Get a value from a dictionary.
@param d dictionary object to search.
@param key Key to look for in the dictionary.
@param def Default value to return if key not found.
@return 1 pointer to internally allocated character string.
This function locates a key in a dictionary and returns a pointer to its
value, or the passed 'def' pointer if no such key can be found in
dictionary. The returned character pointer points to data internal to the
dictionary object, you should not try to free it or modify it.
*/
/*--------------------------------------------------------------------------*/
const char * dictionary_get(const dictionary * d, const char * key, const char * def);
/*-------------------------------------------------------------------------*/
/**
@brief Set a value in a dictionary.
@param d dictionary object to modify.
@param key Key to modify or add.
@param val Value to add.
@return int 0 if Ok, anything else otherwise
If the given key is found in the dictionary, the associated value is
replaced by the provided one. If the key cannot be found in the
dictionary, it is added to it.
It is Ok to provide a NULL value for val, but NULL values for the dictionary
or the key are considered as errors: the function will return immediately
in such a case.
Notice that if you dictionary_set a variable to NULL, a call to
dictionary_get will return a NULL value: the variable will be found, and
its value (NULL) is returned. In other words, setting the variable
content to NULL is equivalent to deleting the variable from the
dictionary. It is not possible (in this implementation) to have a key in
the dictionary without value.
This function returns non-zero in case of failure.
*/
/*--------------------------------------------------------------------------*/
int dictionary_set(dictionary * vd, const char * key, const char * val);
/*-------------------------------------------------------------------------*/
/**
@brief Delete a key in a dictionary
@param d dictionary object to modify.
@param key Key to remove.
@return void
This function deletes a key in a dictionary. Nothing is done if the
key cannot be found.
*/
/*--------------------------------------------------------------------------*/
void dictionary_unset(dictionary * d, const char * key);
/*-------------------------------------------------------------------------*/
/**
@brief Dump a dictionary to an opened file pointer.
@param d Dictionary to dump
@param f Opened file pointer.
@return void
Dumps a dictionary onto an opened file pointer. Key pairs are printed out
as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
output file pointers.
*/
/*--------------------------------------------------------------------------*/
void dictionary_dump(const dictionary * d, FILE * out);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,255 +0,0 @@
#ifndef EVENT_H
#define EVENT_H
#include <vector>
void refresh_page_show();
void refresh_page_open_filament_video_2();
void refresh_page_open_leveling();
void refresh_page_wifi_keyboard();
void refresh_page_wifi_list();
void refresh_page_wifi_list_2();
void refresh_page_syntony_finish();
void refresh_page_auto_level();
void refresh_page_stopping();
void refresh_page_syntony_move();
void refresh_page_print_filament();
void refresh_page_auto_finish();
void refresh_page_auto_moving();
void refresh_page_move();
void refresh_page_offset(float intern_zoffset);
void refresh_page_printing_zoffset();
void refresh_page_printing();
void clear_page_printing_arg();
void refresh_page_preview();
void refresh_page_main();
void refresh_page_files_list();
void refresh_page_files(int pages);
void sub_object_status();
void get_object_status();
void get_file_estimated_time(std::string filename);
void delete_file(std::string filepath);
void start_printing(std::string filepath);
void set_target(std::string heater, int target);
void set_extruder_target(int target);
void set_heater_bed_target(int target);
void set_hot_target(int target);
void set_fan(int speed);
void set_fan0(int speed);
void set_fan2(int speed);
void set_fan3(int speed);
void set_target(std::string heater, int target);
void set_intern_zoffset(float offset);
void set_zoffset(bool positive);
void set_move_dist(float dist);
void set_printer_speed(int speed);
void set_printer_flow(int rate);
std::string show_time(int seconds);
void move_home();
void move_x_decrease();
void move_x_increase();
void move_y_decrease();
void move_y_increase();
void move_z_decrease();
void move_z_increase();
bool get_filament_detected();
bool get_filament_detected_enable();
bool get_print_pause_resume();
void set_print_pause_resume();
void set_print_pause();
void set_print_resume();
void cancel_print();
void sdcard_reset_file();
void set_auto_level_dist(float dist);
void open_calibrate_start();
void start_auto_level();
void start_auto_level_dist(bool positive);
void set_filament_extruder_target(bool positive);
void set_print_filament_dist(float dist);
void start_retract();
void start_extrude();
std::string get_ip(std::string net);
void move_home_tips();
void filament_tips();
void move_tips();
void reset_klipper();
void reset_firmware();
void finish_print();
void set_filament_sensor();
void motors_off();
void beep_on_off();
void led_on_off();
void shutdown_mcu();
void firmware_reset();
void go_to_page_power_off();
int get_mks_led_status();
void set_mks_led_status();
int get_mks_beep_status();
void set_mks_beep_status();
void get_mks_language_status();
void set_mks_language_status();
void get_mks_extruder_target();
void set_mks_extruder_target(int target);
void get_mks_heater_bed_target();
void set_mks_heater_bed_target(int target);
void get_mks_hot_target();
void set_mks_hot_target(int target);
void filament_extruder_target();
void filament_heater_bed_target();
void filament_hot_target();
void filament_fan0();
void filament_fan2();
void filament_fan3();
void go_to_reset();
void go_to_network();
void scan_ssid_and_show();
void get_wifi_list_ssid(int index);
void set_print_filament_target();
void complete_print();
void back_to_main();
void go_to_syntony_move();
void print_ssid_psk(char *psk);
void clear_page_preview();
void set_mks_babystep(std::string value);
void get_mks_babystep();
void clear_cp0_image();
void printer_set_babystep();
int get_mks_fila_status();
void set_mks_fila_status();
void init_mks_status();
int detect_disk();
void set_printing_shutdown();
void mks_get_version();
void wifi_save_config();
void disable_page_about_successed();
void finish_tjc_update();
void filament_load();
void filament_unload();
int get_cal_printed_time(int print_time);
int get_mks_total_printed_time();
void set_mks_total_printed_time(int printed_time);
void get_total_time();
void do_not_x_clear();
void do_x_clear();
void level_mode_printing_set_target();
void level_mode_printing_print_file();
void update_finished_tips();
bool get_mks_oobe_enabled();
void set_mks_oobe_enabled(bool enable);
void move_motors_off();
void open_more_level_finish();
void open_move_tip();
void open_set_print_filament_target();
void open_start_extrude();
void close_mcu_port();
void oobe_set_intern_zoffset(float offset);
void oobe_set_zoffset(bool positive);
void refresh_page_zoffset();
void refresh_page_auto_heaterbed();
void set_auto_level_heater_bed_target(bool positive);
void detect_error();
void clear_previous_data();
void print_start();
void open_heater_bed_up();
void refresh_page_open_heaterbed();
void refresh_page_open_leveling();
void bed_leveling_switch(bool positive);
void refresh_page_filament_pop();
void save_current_zoffset();
void check_filament_type();
void refresh_page_preview_pop();
//4.4.2 CLL mates适配霍尔耗材宽度检测器
void check_filament_width();
//4.4.2 CLL 文件列表新增本地、U盘切换按钮
void refresh_page_files_list_2();
//4.4.3 CLL 修改更新按钮始终显示
void go_to_update();
//4.4.3 CLL 新增恢复出厂设置按钮
void restore_config();
void refresh_page_open_calibrate();
void refresh_page_filament_set_fan();
void go_to_adjust();
void go_to_setting();
void refresh_page_common_setting();
void print_log();
std::string replaceCharacters(const std::string& path, const std::string& searchChars, const std::string& replacement);
void refresh_page_bed_moving();
void bed_calibrate();
void bed_adjust(bool status);
void go_to_file_list();
void send_gcode(std::string command);
void refresh_files_list_picture(std::string path, int pixel, int i);
void refresh_files_list_picture_2(std::string path, int size, int i);
void refresh_page_filament();
void get_mks_connection_method();
void set_mks_connection_method(int target);
void refresh_page_show_qr();
void go_to_showqr();
struct Server_config
{
std::string address;
std::string name;
};
void get_mks_selected_server();
void go_to_server_set(int n);
void updateServerConfig(std::vector<std::string> &lines, const Server_config &config);
void update_server(int choice);
void refresh_page_server_set();
void local_update();
std::string run_python_code(const char* cmd);
void check_online_version();
void online_update();
void *recevice_progress_handle(void *arg);
void refresh_page_auto_unload();
#endif

View File

@@ -1,46 +0,0 @@
/*
* wpa_supplicant/hostapd - Default include files
* Copyright (c) 2005-2006, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*
* This header file is included into all C files so that commonly used header
* files can be selected with OS specific ifdef blocks in one place instead of
* having to have OS/C library specific selection in many files.
*/
#ifndef INCLUDES_H
#define INCLUDES_H
/* Include possible build time configuration before including anything else */
// #include "build_config.h"
#include <stdlib.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#ifndef _WIN32_WCE
#include <signal.h>
#include <sys/types.h>
#include <errno.h>
#endif /* _WIN32_WCE */
#include <ctype.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif /* _MSC_VER */
#ifndef CONFIG_NATIVE_WINDOWS
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifndef __vxworks
#include <sys/uio.h>
#include <sys/time.h>
#endif /* __vxworks */
#endif /* CONFIG_NATIVE_WINDOWS */
#endif /* INCLUDES_H */

View File

@@ -1,358 +0,0 @@
/*-------------------------------------------------------------------------*/
/**
@file iniparser.h
@author N. Devillard
@brief Parser for ini files.
*/
/*--------------------------------------------------------------------------*/
#ifndef _INIPARSER_H_
#define _INIPARSER_H_
/*---------------------------------------------------------------------------
Includes
---------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* The following #include is necessary on many Unixes but not Linux.
* It is not needed for Windows platforms.
* Uncomment it if needed.
*/
/* #include <unistd.h> */
#include "dictionary.h"
#ifdef __cplusplus
extern "C" {
#endif
/*-------------------------------------------------------------------------*/
/**
@brief Configure a function to receive the error messages.
@param errback Function to call.
By default, the error will be printed on stderr. If a null pointer is passed
as errback the error callback will be switched back to default.
*/
/*--------------------------------------------------------------------------*/
void iniparser_set_error_callback(int (*errback)(const char *, ...));
/*-------------------------------------------------------------------------*/
/**
@brief Get number of sections in a dictionary
@param d Dictionary to examine
@return int Number of sections found in dictionary
This function returns the number of sections found in a dictionary.
The test to recognize sections is done on the string stored in the
dictionary: a section name is given as "section" whereas a key is
stored as "section:key", thus the test looks for entries that do not
contain a colon.
This clearly fails in the case a section name contains a colon, but
this should simply be avoided.
This function returns -1 in case of error.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getnsec(const dictionary * d);
/*-------------------------------------------------------------------------*/
/**
@brief Get name for section n in a dictionary.
@param d Dictionary to examine
@param n Section number (from 0 to nsec-1).
@return Pointer to char string
This function locates the n-th section in a dictionary and returns
its name as a pointer to a string statically allocated inside the
dictionary. Do not free or modify the returned string!
This function returns NULL in case of error.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getsecname(const dictionary * d, int n);
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary to a loadable ini file
@param d Dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given dictionary into a loadable ini file.
It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump_ini(const dictionary * d, FILE * f);
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary section to a loadable ini file
@param d Dictionary to dump
@param s Section name of dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given section of a given dictionary into a loadable ini
file. It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dumpsection_ini(const dictionary * d, const char * s, FILE * f);
/*-------------------------------------------------------------------------*/
/**
@brief Dump a dictionary to an opened file pointer.
@param d Dictionary to dump.
@param f Opened file pointer to dump to.
@return void
This function prints out the contents of a dictionary, one element by
line, onto the provided file pointer. It is OK to specify @c stderr
or @c stdout as output files. This function is meant for debugging
purposes mostly.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump(const dictionary * d, FILE * f);
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@return Number of keys in section
*/
/*--------------------------------------------------------------------------*/
int iniparser_getsecnkeys(const dictionary * d, const char * s);
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@param keys Already allocated array to store the keys in
@return The pointer passed as `keys` argument or NULL in case of error
This function queries a dictionary and finds all keys in a given section.
The keys argument should be an array of pointers which size has been
determined by calling `iniparser_getsecnkeys` function prior to this one.
Each pointer in the returned char pointer-to-pointer is pointing to
a string allocated in the dictionary; do not free or modify them.
*/
/*--------------------------------------------------------------------------*/
const char ** iniparser_getseckeys(const dictionary * d, const char * s, const char ** keys);
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key
@param d Dictionary to search
@param key Key string to look for
@param def Default value to return if key not found.
@return pointer to statically allocated character string
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the pointer passed as 'def' is returned.
The returned char pointer is pointing to a string allocated in
the dictionary, do not free or modify it.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getstring(const dictionary * d, const char * key, const char * def);
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to an int
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
Supported values for integers include the usual C notation
so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
are supported. Examples:
- "42" -> 42
- "042" -> 34 (octal -> decimal)
- "0x42" -> 66 (hexa -> decimal)
Warning: the conversion may overflow in various ways. Conversion is
totally outsourced to strtol(), see the associated man page for overflow
handling.
Credits: Thanks to A. Becker for suggesting strtol()
*/
/*--------------------------------------------------------------------------*/
int iniparser_getint(const dictionary * d, const char * key, int notfound);
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to an long int
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
Supported values for integers include the usual C notation
so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
are supported. Examples:
- "42" -> 42
- "042" -> 34 (octal -> decimal)
- "0x42" -> 66 (hexa -> decimal)
Warning: the conversion may overflow in various ways. Conversion is
totally outsourced to strtol(), see the associated man page for overflow
handling.
*/
/*--------------------------------------------------------------------------*/
long int iniparser_getlongint(const dictionary * d, const char * key, long int notfound);
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a double
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return double
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
*/
/*--------------------------------------------------------------------------*/
double iniparser_getdouble(const dictionary * d, const char * key, double notfound);
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a boolean
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
A true boolean is found if one of the following is matched:
- A string starting with 'y'
- A string starting with 'Y'
- A string starting with 't'
- A string starting with 'T'
- A string starting with '1'
A false boolean is found if one of the following is matched:
- A string starting with 'n'
- A string starting with 'N'
- A string starting with 'f'
- A string starting with 'F'
- A string starting with '0'
The notfound value returned if no boolean is identified, does not
necessarily have to be 0 or 1.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getboolean(const dictionary * d, const char * key, int notfound);
/*-------------------------------------------------------------------------*/
/**
@brief Set an entry in a dictionary.
@param ini Dictionary to modify.
@param entry Entry to modify (entry name)
@param val New value to associate to the entry.
@return int 0 if Ok, -1 otherwise.
If the given entry can be found in the dictionary, it is modified to
contain the provided value. If it cannot be found, the entry is created.
It is Ok to set val to NULL.
*/
/*--------------------------------------------------------------------------*/
int iniparser_set(dictionary * ini, const char * entry, const char * val);
/*-------------------------------------------------------------------------*/
/**
@brief Delete an entry in a dictionary
@param ini Dictionary to modify
@param entry Entry to delete (entry name)
@return void
If the given entry can be found, it is deleted from the dictionary.
*/
/*--------------------------------------------------------------------------*/
void iniparser_unset(dictionary * ini, const char * entry);
/*-------------------------------------------------------------------------*/
/**
@brief Finds out if a given entry exists in a dictionary
@param ini Dictionary to search
@param entry Name of the entry to look for
@return integer 1 if entry exists, 0 otherwise
Finds out if a given entry exists in the dictionary. Since sections
are stored as keys with NULL associated values, this is the only way
of querying for the presence of sections in a dictionary.
*/
/*--------------------------------------------------------------------------*/
int iniparser_find_entry(const dictionary * ini, const char * entry) ;
/*-------------------------------------------------------------------------*/
/**
@brief Parse an ini file and return an allocated dictionary object
@param ininame Name of the ini file to read.
@return Pointer to newly allocated dictionary
This is the parser for ini files. This function is called, providing
the name of the file to be read. It returns a dictionary object that
should not be accessed directly, but through accessor functions
instead.
The returned dictionary must be freed using iniparser_freedict().
*/
/*--------------------------------------------------------------------------*/
dictionary * iniparser_load(const char * ininame);
/*-------------------------------------------------------------------------*/
/**
@brief Free all memory associated to an ini dictionary
@param d Dictionary to free
@return void
Free all memory associated to an ini dictionary.
It is mandatory to call this function before the dictionary object
gets out of the current context.
*/
/*--------------------------------------------------------------------------*/
void iniparser_freedict(dictionary * d);
#ifdef __cplusplus
}
#endif
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
#ifndef MKS_ERROR_H
#define MKS_ERROR_H
#include "nlohmann/json.hpp"
#include "./mks_log.h"
void parse_error(nlohmann::json error);
#endif

View File

@@ -1,31 +0,0 @@
#ifndef MKS_FILE_H
#define MKS_FILE_H
#include "./mks_log.h"
#include "nlohmann/json.hpp"
void parse_file_estimated_time(nlohmann::json response);
void parse_server_files_list(nlohmann::json result);
void parse_server_files_get_directory(nlohmann::json result);
void parse_server_files_metadata(nlohmann::json result);
void parse_create_directory(nlohmann::json result);
void parse_delete_directory(nlohmann::json result);
void parse_move_a_file_or_directory(nlohmann::json result);
void parse_copy_a_file_or_directory(nlohmann::json result);
void parse_file_delete(nlohmann::json result);
void get_page_files_filelist(std::string current_dir);
void set_page_files_show_list(int pages);
void get_sub_dir_files_list(int button);
void get_parenet_dir_files_list();
// void get_file_estimated_time(std::string filename, int *estimated_time);
void parse_file_estimated_time_send(nlohmann::json response);
std::string getParentDirectory(const std::string& path);
int output_imgdata(std::string thumbpath, int size);
int output_jpg(std::string thumbpath, int size);
std::string extractFileName(const std::string& filePath);
#endif

View File

@@ -1,8 +0,0 @@
#ifndef MKS_GCODE_H
#define MKS_GCODE_H
#include "nlohmann/json.hpp"
void parse_gcode_response(nlohmann::json params);
#endif

View File

@@ -1,13 +0,0 @@
#ifndef MKS_GPIO_H
#define MKS_GPIO_H
static int gpio_config(const char *attr, const char *val);
int set_GPIO1_C5_low();
int set_GPIO1_C5_high();
int init_GPIO1_B2();
void *monitor_GPIO1_B2(void *arg);
int init_GPIO1_C3();
void *monitor_GPIO1_C3(void *arg);
int set_GPIO1_B3_low();
#endif

View File

@@ -1,18 +0,0 @@
#ifndef MKS_INIT_H
#define MKS_INIT_H
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <iostream>
#include <fstream>
bool get_by_id();
std::string generate_by_id();
bool FileStringReplace(std::ifstream &instream, std::ofstream &outstream);
std::string get_cfg_by_id();
#endif

View File

@@ -1,6 +0,0 @@
#ifndef MKS_JOB_H
#define MKS_JOB_H
#include "./mks_log.h"
#endif

View File

@@ -1,30 +0,0 @@
#ifndef MKS_LOG_H
#define MKS_LOG_H
#include <iostream>
#include <stdio.h>
#define LOG_RED "\033[31;1m"
#define LOG_YELLOW "\033[0;33m"
#define LOG_GREEN "\033[0;32m"
#define LOG_BLUE "\033[0;34m"
#define LOG_PURPLE "\033[0;35m"
#define LOG_SKYBLUE "\033[0;36m"
#define LOG_HIGHLIGHT "\033[7m\033[5m"
#define LOG_END "\033[0m"
#if 0
#define MKSLOG(fmt, ...) printf(("[%s][%s] %s: %d\n" fmt "\n"), __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__)
#define MKSLOG_RED(fmt, ...) printf(("%s[%s][%s] %s: %d\n" fmt "\n%s"), LOG_RED, __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__, LOG_END)
#define MKSLOG_YELLOW(fmt, ...) printf(("%s[%s][%s] %s: %d\n" fmt "\n%s"), LOG_YELLOW, __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__, LOG_END)
#define MKSLOG_BLUE(fmt, ...) printf(("%s[%s][%s] %s: %d\n" fmt "\n%s"), LOG_SKYBLUE, __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__, LOG_END)
#define MKSLOG_GREEN(fmt, ...) printf(("%s[%s][%s] %s: %d\n" fmt "\n%s"), LOG_GREEN, __DATE__, __TIME__, __FILE__, __LINE__, ##__VA_ARGS__, LOG_END)
#else
#define MKSLOG(fmt, ...) printf((fmt "\n"), ##__VA_ARGS__)
#define MKSLOG_RED(fmt, ...) printf(("%s" fmt "\n%s"), LOG_RED, ##__VA_ARGS__, LOG_END)
#define MKSLOG_YELLOW(fmt, ...) printf(("%s" fmt "\n%s"), LOG_YELLOW, ##__VA_ARGS__, LOG_END)
#define MKSLOG_BLUE(fmt, ...) printf(("%s" fmt "\n%s"), LOG_SKYBLUE, ##__VA_ARGS__, LOG_END)
#define MKSLOG_GREEN(fmt, ...) printf(("%s" fmt "\n%s"), LOG_GREEN, ##__VA_ARGS__, LOG_END)
#define MKSLOG_HIGHLIGHT(fmt, ...) printf(("%s" fmt "\n%s"), LOG_HIGHLIGHT, ##__VA_ARGS__, LOG_END)
#endif
#endif

View File

@@ -1,12 +0,0 @@
#ifndef MKS_PREVIEW_H
#define MKS_PREVIEW_H
#include <iostream>
#include <fstream>
#include <vector>
void generate_gimage(std::string filename);
void generate_simage(std::string filename);
#endif

View File

@@ -1,40 +0,0 @@
#ifndef MKS_PRINTER_H
#define MKS_PRINTER_H
#include "nlohmann/json.hpp"
#include "./mks_log.h"
void parse_server_history_totals(nlohmann::json totals);
void parse_printer_probe(nlohmann::json probe);
void parse_printer_beep(nlohmann::json beep);
void parse_printer_caselight(nlohmann::json caselight);
void parse_printer_heater_fan_my_nozzle_fan1(nlohmann::json heater_fan_my_nozzle_fan1);
void parse_printer_out_pin_fan0(nlohmann::json out_pin_fan0);
void parse_printer_out_pin_fan2(nlohmann::json out_pin_fan2);
void parse_printer_out_pin_fan3(nlohmann::json out_pin_fan3);
void parse_filament_switch_sensor_fila(nlohmann::json filament_switch_sensor);
void parse_idle_timeout(nlohmann::json idle_timeout);
void parse_bed_mesh(nlohmann::json bed_mesh);
void parse_webhooks(nlohmann::json webhooks);
void parse_gcode_move(nlohmann::json gcode_move);
void parse_toolhead(nlohmann::json toolhead);
void parse_extruder(nlohmann::json extruder);
void parse_heater_bed(nlohmann::json heater_bed);
void parse_heater_generic_hot(nlohmann::json heater_generic_hot);
void parse_fan(nlohmann::json fan);
void parse_heater_fan(nlohmann::json heater_fan);
void parse_print_stats(nlohmann::json print_stats);
void parse_display_status(nlohmann::json display_status);
void parse_pause_resume(nlohmann::json pause_resume);
void parse_subscribe_objects_status(nlohmann::json status);
nlohmann::json subscribe_objects_status();
int get_cal_printing_time(int print_time, int estimated_time, int progress);
void parse_printer_info(nlohmann::json result);
#endif

View File

@@ -1,6 +0,0 @@
#ifndef MKS_SYSTEM_H
#define MKS_SYSTEM_H
#include "./mks_log.h"
#endif

View File

@@ -1,19 +0,0 @@
#ifndef MKS_TEST_H
#define MKS_TEST_H
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <exception>
#include <string.h>
void *mks_test(void *arg);
bool testUSB();
bool moko_test_func();
bool network_test_func();
#endif

View File

@@ -1,16 +0,0 @@
#ifndef MKS_UPDATE_H
#define MKS_UPDATE_H
int u_disk_update();
bool detect_update();
void start_update();
void download_to_screen();
void init_download_to_screen();
void back_to_screen_old();
#endif

View File

@@ -1,106 +0,0 @@
#ifndef MKS_WPA_CLI
#define MKS_WPA_CLI
#include <stdlib.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <wpa_ctrl.h>
struct mks_wifi_signal_poll_result_t {
char ack[1024];
int rssi;
int linkspeed;
int noise;
int frequency;
};
struct mks_wifi_status_result_t {
char ack[1024];
char bssid[18];
int freq;
char ssid[128];
int id;
char mode[16];
char pairwise_cipher[16];
char group_cipher[16];
char key_mgmt[16];
char wpa_state[32];
char ip_address[18];
char address[18];
char uuid[64];
};
struct mks_wifi_status_t {
char bssid[18];
int freq;
char ssid[128];
int id;
char mode[16];
char pairwise_cipher[16];
char group_cipher[16];
char key_mgmt[16];
char wpa_state[32];
char ip_address[18];
char address[18];
char uuid[64];
};
static void wpa_cli_msg_cb(char *msg, size_t len);
static int result_get(char *str, char *key, char *val, int val_len);
int mks_wifi_run_cmd_signal_poll(struct mks_wifi_signal_poll_result_t *result);
int mks_wifi_run_cmd(char const *cmd, char *result, size_t *len);
int mks_wifi_run_cmd_status(struct mks_wifi_status_result_t *result);
// void mks_wifi_set_config(char *ssid, char *psk);
// int mks_wifi_get_config(char *ssid, char *psk);
void test_wifi_run_cmd_signal(void);
void test_wifi_run_cmd_status(void);
int wifi_send_command(const char *cmd, char *reply, size_t *reply_len);
// int mks_wifi_connect_ap_fun(char *ssid, char *psk);
void *mks_wifi_hdlevent_thread(void *arg);
int mks_wpa_scan_scanresults();
// int mks_wifi_connect(char *ssid, char *psk);
int mks_set_ssid(char *ssid);
int mks_set_psk(char *psk);
int mks_disable_network();
int mks_enable_network();
int mks_save_config();
int mks_wpa_cli_open_connection();
int mks_wpa_cli_close_connection();
int mks_wpa_scan();
int mks_wpa_scan_results(char *mks_result);
int mks_wpa_get_status();
int mks_parse_status(struct mks_wifi_status_t *status);
#endif

View File

@@ -1,55 +0,0 @@
#ifndef SEND_JPG_H
#define SEND_JPG_H
#include <stdio.h>
#include <stdint.h>
#include <stdint.h>
#include "mks_log.h"
#include "send_msg.h"
// #define BLOCK_SIZE 3072
#define BLOCK_SIZE 3800
#define HEADER_SIZE 12
extern bool get_0xfe;
extern bool get_0x06;
extern bool get_0x05;
extern bool get_0xfd;
extern bool get_0x04;
extern bool get_0x24;
extern bool have_64_jpg[6];
extern std::string have_64_png_path[6];
extern bool begin_show_64_jpg;
extern bool begin_show_160_jpg;
extern bool begin_show_192_jpg;
extern bool show_192_jpg_complete;
#define LOG_RED "\033[31;1m"
#define LOG_YELLOW "\033[0;33m"
#define LOG_GREEN "\033[0;32m"
#define LOG_BLUE "\033[0;34m"
#define LOG_PURPLE "\033[0;35m"
#define LOG_SKYBLUE "\033[0;36m"
#define LOG_HIGHLIGHT "\033[7m\033[5m"
#define LOG_END "\033[0m"
void printHex(const uint8_t *data, size_t size);
// bool mks_send_jpg(char *path, int fd, int index);
void *sent_jpg_thread_handle(void *arg);
void delet_pic(std::string ram_path);
// void *sent_jpg_thread_handle(void *arg);
void png_to_64_jpg(std::string dir_path, std::string file_name, uint8_t i);
void png_to_160_jpg(std::string dir_path, std::string file_name);
void png_to_192_jpg(std::string dir_path, std::string file_name);
void delet_pic(std::string ram_path);
void delete_small_jpg();
bool sent_jpg_to_tjc(std::string ram_path, std::string pic_path);
#endif

View File

@@ -1,99 +0,0 @@
#ifndef SEND_MSG_H
#define SEND_MSG_H
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void send_cmd_page(int fd, std::string pageid);
void send_cmd_ref(int fd, std::string obj);
void send_cmd_click(int fd, std::string obj, std::string event);
void send_cmd_get(int fd, std::string att);
void send_cmd_prints(int fd, std::string att, int lenth);
void send_cmd_printh(int fd, std::string hex);
void send_cmd_vis(int fd, std::string obj, std::string state);
void send_cmd_tsw(int fd, std::string obj, std::string state);
void send_cmd_randset(int fd, std::string minval, std::string maxval);
void send_cmd_add(int fd, std::string objid, std::string ch, std::string val);
void send_cmd_cle(int fd, std::string objid, std::string ch);
void send_cmd_addt(int fd, std::string objid, std::string ch, std::string qyt);
void send_cmd_doevents(int fd);
void send_cmd_sendme(int fd);
void send_cmd_covx(int fd, std::string att1, std::string att2, std::string lenth);
void send_cmd_strlen(int fd, std::string att0, std::string att1);
void send_cmd_btlen(int fd, std::string att0, std::string att1);
void send_cmd_substr(int fd, std::string att0, std::string att1, std::string star, std::string lenth);
void send_cmd_spstr(int fd, std::string src, std::string dec, std::string key, std::string indec);
void send_cmd_touch_j(int fd);
void send_cmd_ref_stop(int fd);
void send_cmd_ref_star(int fd);
void send_cmd_com_stop(int fd);
void send_cmd_com_star(int fd);
void send_cmd_code_c(int fd);
void send_cmd_rest(int fd);
void send_cmd_wepo(int fd, std::string att, std::string add);
void send_cmd_repo(int fd, std::string att, std::string add);
void send_cmd_wept(int fd, std::string add, std::string lenth);
void send_cmd_rept(int fd, std::string add, std::string lenth);
void send_cmd_cfgpio(int fd, std::string id, std::string state, std::string obj);
void send_cmd_crcrest(int fd, std::string crctype, std::string initval);
void send_cmd_crcputs(int fd, std::string att, std::string length);
void send_cmd_crcputh(int fd, std::string hex);
void send_cmd_crcputu(int fd, std::string star, std::string length);
void send_cmd_setlayer(int fd, std::string obj0, std::string obj1);
void send_cmd_move(int fd, std::string obj, std::string startx, std::string starty, std::string endx, std::string endy, std::string first, std::string time);
void send_cmd_play(int fd, std::string ch, std::string audio, std::string loop);
void send_cmd_twfile(int fd, std::string filepath, std::string filesize);
void send_cmd_delfile(int fd, std::string filepath);
void send_cmd_refile(int fd, std::string srcfilepath, std::string decfilepath);
void send_cmd_findfile(int fd, std::string filepath, std::string att);
void send_cmd_rdfile(int fd, std::string filepath, std::string addr, std::string size, std::string crc);
void send_cmd_newfile(int fd, std::string filepath, std::string size);
void send_cmd_newdir(int fd, std::string dir);
void send_cmd_deldir(int fd, std::string dir);
void send_cmd_redir(int fd, std::string srcdir, std::string decdir);
void send_cmd_finddir(int fd, std::string dir, std::string att);
void send_cmd_beep(int fd, std::string time);
void send_cmd_txt(int fd, std::string obj, std::string txt);
void send_cmd_pic(int fd, std::string obj, std::string pic);
void send_cmd_picc(int fd, std::string obj, std::string picc);
void send_cmd_picc2(int fd, std::string obj, std::string picc);
void send_cmd_val(int fd, std::string obj, std::string val);
void send_cmd_val(int fd, std::string obj, std::string val);
void send_cmd_pco(int fd, std::string obj, std::string poc);
void send_cmd_pco2(int fd, std::string obj, std::string poc2);
void send_cmd_bpic(int fd, std::string obj, std::string bpic);
void send_cmd_vid(int fd, std::string obj, std::string vid);
void send_cmd_cp(int fd, std::string obj);
void send_cmd_cp_write(int fd, std::string obj, std::string data);
void send_cmd_cp_end(int fd);
void send_cmd_cp_close(int fd, std::string obj);
void send_cmd_byte_data(int fd, char data);
void send_cmd_write(int fd, std::string obj);
void send_cmd_write_end(int fd);
void send_cmd_cp_image(int fd, std::string obj, std::string image);
void send_cmd_txt_start(int fd, std::string obj);
void send_cmd_txt_data(int fd, std::string txt);
void send_cmd_txt_end(int fd);
void send_cmd_txt_plus(int fd, std::string obj1, std::string obj2, std::string obj3);
void send_cmd_download(int fd, int filesize);
void send_cmd_download_data(int fd, std::string data);
void send_cmd_vid_en(int fd, std::string obj, int value);
void send_cmd_bauds(int fd, int bauds);
void send_cmd_baud(int fd, int baud);
void send_var_value(int fd, std::string var, int value);
#endif

View File

@@ -1,428 +0,0 @@
#ifndef UI_H
#define UI_H
//所有页面的下方跳转按钮的发送比特均一致
#define TJC_PAGE_ALL_TO_MAIN 0x1e
#define TJC_PAGE_ALL_TO_ADJUST 0x1f
#define TJC_PAGE_ALL_TO_FILE_LIST 0x20
#define TJC_PAGE_ALL_TO_SETTING 0x21
#define TJC_PAGE_LOGO 0
#define TJC_PAGE_RESTART 1
#define TJC_PAGE_SHUTDOWN 2
#define TJC_PAGE_OPEN_LANGUAGE 3
#define TJC_PAGE_OPEN_LANGUAGE_NEXT 0x00
#define TJC_PAGE_OPEN_LANGUAGE_SKIP 0x01
#define TJC_PAGE_OPEN_POP 4
#define TJC_PAGE_OPEN_POP_YES 0x00
#define TJC_PAGE_OPEN_POP_NO 0x01
#define TJC_PAGE_OPEN_VIDEO_1 5
#define TJC_PAGE_OPEN_VIDEO_1_NEXT 0x00
#define TJC_PAGE_OPEN_VIDEO_2 6
#define TJC_PAGE_OPEN_VIDEO_2_NEXT 0x00
#define TJC_PAGE_OPEN_WARNING 7
#define TJC_PAGE_OPEN_WARNING_NEXT 0x00
#define TJC_PAGE_OPEN_VIDEO_3 8
#define TJC_PAGE_OPEN_VIDEO_3_NEXT 0x00
#define TJC_PAGE_OPEN_VIDEO_3_UP 0x01
#define TJC_PAGE_OPEN_VIDEO_3_DOWN 0x02
#define TJC_PAGE_OPEN_HEATERBED 9
#define TJC_PAGE_OPEN_HEATERBED_ON_OFF 0x00
#define TJC_PAGE_OPEN_HEATERBED_UP 0x01
#define TJC_PAGE_OPEN_HEATERBED_DOWN 0x02
#define TJC_PAGE_OPEN_HEATERBED_NEXT 0x03
#define TJC_PAGE_OPEN_CALIBRATE 10
#define TJC_PAGE_OPEN_FILAMENTVIDEO_0 72
#define TJC_PAGE_OPEN_FILAMENTVIDEO_0_NEXT 0x00
#define TJC_PAGE_OPEN_FILAMENTVIDEO_1 11
#define TJC_PAGE_OPEN_FILAMENTVIDEO_1_NEXT 0x00
#define TJC_PAGE_OPEN_FILAMENTVIDEO_2 12
#define TJC_PAGE_OPEN_FILAMENTVIDEO_2_DOWN 0x00
#define TJC_PAGE_OPEN_FILAMENTVIDEO_2_UP 0x01
#define TJC_PAGE_OPEN_FILAMENTVIDEO_2_NEXT 0x02
#define TJC_PAGE_OPEN_FILAMENTVIDEO_2_ON_OFF 0x03
#define TJC_PAGE_OPEN_FILAMENTVIDEO_3 13
#define TJC_PAGE_OPEN_FILAMENTVIDEO_3_NEXT 0x00
#define TJC_PAGE_OPEN_FILAMENTVIDEO_3_EXTRUDE 0x01
#define TJC_PAGE_OPEN_FINISH 14
#define TJC_PAGE_OPEN_FINISH_YES 0x00
#define TJC_PAGE_MAIN 15
#define TJC_PAGE_MAIN_CASELIGHT 0x00
#define TJC_PAGE_MAIN_BEEP 0x01
#define TJC_PAGE_MAIN_STOP 0x02
#define TJC_PAGE_MAIN_SET_TEMP 0x03
#define TJC_PAGE_MAIN_CACHE 0x06
#define TJC_PAGE_FILE_LIST 16
#define TJC_PAGE_FILE_LIST_BACK 0x00
#define TJC_PAGE_FILE_LIST_BTN_1 0x01
#define TJC_PAGE_FILE_LIST_BTN_2 0x02
#define TJC_PAGE_FILE_LIST_BTN_3 0x03
#define TJC_PAGE_FILE_LIST_BTN_4 0x04
#define TJC_PAGE_FILE_LIST_BTN_5 0x05
#define TJC_PAGE_FILE_LIST_PREVIOUS 0x0a
#define TJC_PAGE_FILE_LIST_NEXT 0x0b
#define TJC_PAGE_FILE_LIST_LOCAL 0x0c
#define TJC_PAGE_FILE_LIST_USB 0x0d
#define TJC_PAGE_PREVIEW 17
#define TJC_PAGE_PREVIEW_BACK 0x00
#define TJC_PAGE_PREVIEW_START 0x01
#define TJC_PAGE_PREVIEW_BED_LEVELING 0x02
#define TJC_PAGE_PREVIEW_POP_1 18
#define TJC_PAGE_PREVIEW_POP_2 19
#define TJC_PAGE_PREVIEW_POP_YES 0x00
//4.4.1 CLL 耗材确认弹窗新增不再提示按钮
#define TJC_PAGE_PREVIEW_POP_NO_POP 0x01
#define TJC_PAGE_PRINTING 20
#define TJC_PAGE_PRINTING_EXTRUDER 0x00
#define TJC_PAGE_PRINTING_HEATER_BED 0x01
#define TJC_PAGE_PRINTING_NEXT 0x02
#define TJC_PAGE_PRINTING_CASE_LIGHT 0x03
#define TJC_PAGE_PRINTING_FAN_1 0x04
#define TJC_PAGE_PRINTING_FAN_2 0x05
#define TJC_PAGE_PRINTING_FAN_3 0x06
#define TJC_PAGE_PRINTING_HOT 0x07
#define TJC_PAGE_PRINTING_PAUSE_RESUME 0x0a
#define TJC_PAGE_PRINTING_STOP 0x0b
#define TJC_PAGE_PRINTING_KB 21
#define TJC_PAGE_PRINTING_KB_BACK 0x00
#define TJC_PAGE_PRINTING_KB_PAUSE_RESUME 0x0a
#define TJC_PAGE_PRINTING_KB_STOP 0x0b
#define TJC_PAGE_PRINT_ZOFFSET 22
#define TJC_PAGE_PRINT_ZOFFSET_BACK 0x00
#define TJC_PAGE_PRINT_ZOFFSET_SET_001 0x01
#define TJC_PAGE_PRINT_ZOFFSET_SET_005 0x02
#define TJC_PAGE_PRINT_ZOFFSET_SET_01 0x03
#define TJC_PAGE_PRINT_ZOFFSET_SET_1 0x04
#define TJC_PAGE_PRINT_ZOFFSET_UP 0x05
#define TJC_PAGE_PRINT_ZOFFSET_DOWN 0x06
#define TJC_PAGE_PRINT_ZOFFSET_PAUSE_RESUME 0x0a
#define TJC_PAGE_PRINT_ZOFFSET_STOP 0x0b
#define TJC_PAGE_PRINT_FILAMENT 23
#define TJC_PAGE_PRINT_FILAMENT_ON_OFF 0x00
#define TJC_PAGE_PRINT_FILAMENT_T_UP 0x01
#define TJC_PAGE_PRINT_FILAMENT_T_DOWN 0x02
#define TJC_PAGE_PRINT_FILAMENT_LOAD 0x03
#define TJC_PAGE_PRINT_FILAMENT_UNLOAD 0x04
#define TJC_PAGE_PRINT_FILAMENT_RETRACT 0x05
#define TJC_PAGE_PRINT_FILAMENT_EXTRUDE 0x06
#define TJC_PAGE_PRINT_FILAMENT_PAUSE_RESUME 0x0a
#define TJC_PAGE_PRINT_FILAMENT_STOP 0x0b
#define TJC_PAGE_PRINTING_2 24
#define TJC_PAGE_PRINTING_2_BACK 0x00
#define TJC_PAGE_PRINTING_2_ZOFFSET 0x01
#define TJC_PAGE_PRINTING_2_SPEED 0x02
#define TJC_PAGE_PRINTING_2_FLOW 0x03
#define TJC_PAGE_PRINTING_2_PAUSE_RESUME 0x0a
#define TJC_PAGE_PRINTING_2_STOP 0x0b
#define TJC_PAGE_PRINT_FINISH 25
#define TJC_PAGE_PRINT_FINISH_YES 0x00
#define TJC_PAGE_PRINT_STOP 26
#define TJC_PAGE_PRINT_STOP_YES 0x00
#define TJC_PAGE_PRINT_STOP_NO 0x01
#define TJC_PAGE_PRINT_STOPPING 27
#define TJC_PAGE_PRINT_NO_FILAMENT 28
#define TJC_PAGE_PRINT_NO_FILAMENT_YES 0x00
#define TJC_PAGE_PRINT_LOW_TEMP 29
#define TJC_PAGE_PRINT_LOW_TEMP_YES 0x00
#define TJC_PAGE_MOVE 30
#define TJC_PAGE_MOVE_SET_01 0x00
#define TJC_PAGE_MOVE_SET_1 0x01
#define TJC_PAGE_MOVE_SET_10 0x02
#define TJC_PAGE_MOVE_Z_UP 0x03
#define TJC_PAGE_MOVE_MOTOR 0x04
#define TJC_PAGE_MOVE_Z_DOWN 0x05
#define TJC_PAGE_MOVE_Y_UP 0x06
#define TJC_PAGE_MOVE_Y_DOWN 0x07
#define TJC_PAGE_MOVE_X_DOWN 0x08
#define TJC_PAGE_MOVE_X_UP 0x09
#define TJC_PAGE_MOVE_HOME 0x0a
#define TJC_PAGE_MOVE_TO_FILAMENT 0x16
#define TJC_PAGE_MOVE_POP_1 31
#define TJC_PAGE_MOVE_POP_1_YES 0x00
#define TJC_PAGE_MOVE_POP_2 32
#define TJC_PAGE_MOVE_POP_2_YES 0x00
#define TJC_PAGE_MOVE_POP_2_NO 0x01
#define TJC_PAGE_FILAMENT_SET_FAN 33
#define TJC_PAGE_FILAMENT_SET_FAN_BACK 0x00
#define TJC_PAGE_FILAMENT_SET_FAN_SETTING 0x01
#define TJC_PAGE_FILAMENT_KB 34
#define TJC_PAGE_FILAMENT_KB_BACK 0x00
#define TJC_PAGE_FILAMENT_POP_1 35
#define TJC_PAGE_FILAMENT_POP_1_YES 0x00
#define TJC_PAGE_FILAMENT_POP_2 36
#define TJC_PAGE_FILAMENT_POP_2_YES 0x00
#define TJC_PAGE_FILAMENT_POP_2_TO_LOAD 0x01
#define TJC_PAGE_FILAMENT_POP_2_NEXT 0x02
#define TJC_PAGE_FILAMENT_POP_2_BACK 0x03
#define TJC_PAGE_FILAMENT_POP_3 37
#define TJC_PAGE_FILAMENT_POP_3_YES 0x00
#define TJC_PAGE_FILAMENT_POP_3_RETRY 0x01
#define TJC_PAGE_FILAMENT_POP_3_NEXT 0x02
#define TJC_PAGE_FILAMENT_POP_3_BACK 0x03
#define TJC_PAGE_FILAMENT_UNLOAD_FINISH 38
#define TJC_PAGE_FILAMENT_UNLOAD_FINISH_YES 0x00
#define TJC_PAGE_LEVEL_MODE 39
#define TJC_PAGE_LEVEL_MODE_AUTO_LEVEL 0x00
#define TJC_PAGE_LEVEL_MODE_SYNTONY 0x01
#define TJC_PAGE_LEVEL_MODE_BED_CALIBRATION 0x02
#define TJC_PAGE_LEVEL_MODE_TO_COMMON_SETTING 0x17
#define TJC_PAGE_LEVEL_MODE_ZOFFSET 0x18
#define TJC_PAGE_ZOFFSET 40
#define TJC_PAGE_ZOFFSET_BACK 0x00
#define TJC_PAGE_AUTO_HEATERBED 41
#define TJC_PAGE_AUTO_HEATERBED_DOWN 0x00
#define TJC_PAGE_AUTO_HEATERBED_UP 0x01
#define TJC_PAGE_AUTO_HEATERBED_ON_OFF 0x02
#define TJC_PAGE_AUTO_HEATERBED_BACK 0x03
#define TJC_PAGE_AUTO_HEATERBED_NEXT 0x04
#define TJC_PAGE_AUTO_MOVING 42
#define TJC_PAGE_AUTO_FINISH 43
#define TJC_PAGE_AUTO_FINISH_YES 0x00
#define TJC_PAGE_PRE_BED_CALIBRATION 44
#define TJC_PAGE_PRE_BED_CALIBRATION_SET_001 0x00
#define TJC_PAGE_PRE_BED_CALIBRATION_SET_005 0x01
#define TJC_PAGE_PRE_BED_CALIBRATION_SET_01 0x02
#define TJC_PAGE_PRE_BED_CALIBRATION_SET_1 0x03
#define TJC_PAGE_PRE_BED_CALIBRATION_UP 0x04
#define TJC_PAGE_PRE_BED_CALIBRATION_DOWN 0x05
#define TJC_PAGE_PRE_BED_CALIBRATION_ENTER 0x06
#define TJC_PAGE_BED_MOVING 45
#define TJC_PAGE_BED_CALIBRATION 46
#define TJC_PAGE_BED_CALIBRATION_NEXT 0x00
#define TJC_PAGE_BED_FINISH 47
#define TJC_PAGE_BED_FINISH_OK 0x00
#define TJC_PAGE_BED_FINISH_SCREW1 0x01
#define TJC_PAGE_BED_FINISH_SCREW2 0x02
#define TJC_PAGE_BED_FINISH_SCREW3 0x03
#define TJC_PAGE_BED_FINISH_Z_TILT 0x04
#define TJC_PAGE_SYNTONY_MOVE 48
#define TJC_PAGE_SYNTONY_MOVE_JUMP_OUT 0x00
#define TJC_PAGE_SYNTONY_FINISH 49
#define TJC_PAGE_SYNTONY_FINISH_YES 0x00
#define TJC_PAGE_INTERNET 50
#define TJC_PAGE_INTERNET_REFRESH 0x00
#define TJC_PAGE_INTERNET_TO_WIFI 0x16
#define TJC_PAGE_INTERNET_TO_SETTING 0x17
#define TJC_PAGE_WIFI_LIST 51
#define TJC_PAGE_WIFI_LIST_SSID_1 0x00
#define TJC_PAGE_WIFI_LIST_SSID_2 0x01
#define TJC_PAGE_WIFI_LIST_SSID_3 0x02
#define TJC_PAGE_WIFI_LIST_SSID_4 0x03
#define TJC_PAGE_WIFI_LIST_SSID_5 0x04
#define TJC_PAGE_WIFI_LIST_REFRESH 0x07
#define TJC_PAGE_WIFI_LIST_PREVIOUS 0x05
#define TJC_PAGE_WIFI_LIST_NEXT 0x06
#define TJC_PAGE_WIFI_LIST_TO_WIFI 0x16
#define TJC_PAGE_WIFI_LIST_TO_SETTING 0x17
#define TJC_PAGE_WIFI_CONNECT 52
#define TJC_PAGE_WIFI_SAVING 53
#define TJC_PAGE_WIFI_SUCCESS 54
#define TJC_PAGE_WIFI_SUCCESS_YES 0x00
#define TJC_PAGE_WIFI_FAILED 55
#define TJC_PAGE_WIFI_FAILED_YES 0x00
#define TJC_PAGE_WIFI_KB 56
#define TJC_PAGE_WIFI_KB_BACK 0x00
#define TJC_PAGE_COMMON_SETTING 57
#define TJC_PAGE_COMMON_SETTING_LANGUAGE 0x00
#define TJC_PAGE_COMMON_SETTING_WIFI 0x01
#define TJC_PAGE_COMMON_SETTING_SYSTEM 0x02
#define TJC_PAGE_COMMON_SETTING_SERVICE 0x03
#define TJC_PAGE_COMMON_SETTING_SCREEN_SLEEP 0x04
#define TJC_PAGE_COMMON_SETTING_UPDATE 0x05
#define TJC_PAGE_COMMON_SETTING_RESTORE 0x06
#define TJC_PAGE_COMMON_SETTING_OOBE_OFF 0x07
#define TJC_PAGE_COMMON_SETTING_TO_LEVEL_MODE 0x16
#define TJC_PAGE_COMMON_SETTING_OOBE_ON 0x17
// CLL 以下几个页面需要xindi执行的功能相似所以统一执行响应函数其他功能主要由UI内置程序实现
#define TJC_PAGE_LANGUAGE 58
#define TJC_PAGE_SYS_OK 59
#define TJC_PAGE_RESET 60
#define TJC_PAGE_SERVICE 61
#define TJC_PAGE_SLEEP_MODE 62
#define TJC_PAGE_BACK_TO_COMMON_SETTING 0x00
#define TJC_PAGE_RESET_PRINT_LOG 0x01
#define TJC_PAGE_RESET_RESTART_KLIPPER 0x02
#define TJC_PAGE_RESET_RESTART_FIRMWARE 0x03
#define TJC_PAGE_UPDATE_FOUND 63
#define TJC_PAGE_UPDATE_FOUND_YES 0x00
#define TJC_PAGE_UPDATE_FOUND_NO 0x01
#define TJC_PAGE_UPDATE_NOT_FOUND 64
#define TJC_PAGE_UPDATE_NOT_FOUND_YES 0x00
#define TJC_PAGE_UPDATE_FINISH 65
#define TJC_PAGE_UPDATE_SUCCESS 66
#define TJC_PAGE_UPDATE_SUCCESS_YES 0x00
#define TJC_PAGE_RESTORE_CONFIG 67
#define TJC_PAGE_RESTORE_CONFIG_YES 0x00
#define TJC_PAGE_RESTORE_CONFIG_NO 0x01
#define TJC_PAGE_PRINT_LOG_S 68
#define TJC_PAGE_PRINT_LOG_F 69
#define TJC_PAGE_PRINT_LOG_YES 0x00
#define TJC_PAGE_DETECT_ERROR 70
#define TJC_PAGE_DETECT_ERROR_YES 0x00
#define TJC_PAGE_GCODE_ERROR 71
#define TJC_PAGE_GCODE_ERROR_YES 0x00
//4.4.2 CLL 新增息屏功能
#define TJC_PAGE_SCREEN_SLEEP 73
#define TJC_PAGE_SCREEN_SLEEP_ENTER 0x01
#define TJC_PAGE_SCREEN_SLEEP_EXIT 0x00
#define TJC_PAGE_LEVEL_ERROR 74
#define TJC_PAGE_LEVEL_ERROR_YES 0x00
#define TJC_PAGE_FILAMENT 75
#define TJC_PAGE_FILAMENT_SET_EXTRUDER 0x00
#define TJC_PAGE_FILAMENT_SET_HEATERBED 0x01
#define TJC_PAGE_FILAMENT_EXTRUDER_ON_OFF 0x02
#define TJC_PAGE_FILAMENT_HEATERBED_ON_OFF 0x03
#define TJC_PAGE_FILAMENT_TO_FAN 0x04
#define TJC_PAGE_FILAMENT_LOAD 0x05
#define TJC_PAGE_FILAMENT_UNLOAD 0x06
#define TJC_PAGE_FILAMENT_EXTRUDER_UP 0x07
#define TJC_PAGE_FILAMENT_EXTRUDER_DOWN 0x08
#define TJC_PAGE_FILAMENT_SET_10 0x09
#define TJC_PAGE_FILAMENT_SET_50 0x0a
#define TJC_PAGE_FILAMENT_SET_100 0x0b
#define TJC_PAGE_FILAMENT_SET_FAN_1 0x0c
#define TJC_PAGE_FILAMENT_SET_FAN_2 0x0d
#define TJC_PAGE_FILAMENT_SET_FAN_3 0x0e
#define TJC_PAGE_FILAMENT_HOT_ON_OFF 0x0f
#define TJC_PAGE_FILAMENT_SET_HOT 0x10
#define TJC_PAGE_FILAMENT_TO_FILAMENT 0x16
#define TJC_PAGE_FILAMENT_TO_MOVE 0x17
#define TJC_PAGE_PRINT_NO_FILAMENT_2 76
#define TJC_PAGE_PRINT_NO_FILAMENT_2_YES 0x00
#define TJC_PAGE_MEMORY_WARNING 77
#define TJC_PAGE_MEMORY_WARNING_YES 0x00
#define TJC_PAGE_UPDATING 78
#define TJC_PAGE_PRE_HEAT 79
#define TJC_PAGE_PRE_HEAT_SET_220 0x00
#define TJC_PAGE_PRE_HEAT_SET_250 0x01
#define TJC_PAGE_PRE_HEAT_SET_300 0x02
#define TJC_PAGE_PRE_HEAT_BACK 0x04
#define TJC_PAGE_RESUME_PRINT 80
#define TJC_PAGE_RESUME_PRINT_YES 0x00
#define TJC_PAGE_RESUME_PRINT_NO 0x01
#define TJC_PAGE_SHOW_QR 81
#define TJC_PAGE_SHOW_QR_REFRESH 0x00
#define TJC_PAGE_SHOW_QR_BACK 0x01
#define TJC_PAGE_SHOW_QR_WIFI 0x02
#define TJC_PAGE_SHOW_QR_SET 0x03
#define TJC_PAGE_SERVER_SET 82
#define TJC_PAGE_SERVER_SET_REFRESH 0x00
#define TJC_PAGE_SERVER_SET_BACK 0x01
#define TJC_PAGE_SERVER_SET_LOCAL 0x02
#define TJC_PAGE_SERVER_SET_PREVIOUS 0x03
#define TJC_PAGE_SERVER_SET_NEXT 0x04
#define TJC_PAGE_SERVER_SET_1 0x05
#define TJC_PAGE_SERVER_SET_2 0x06
#define TJC_PAGE_SERVER_SET_3 0x07
#define TJC_PAGE_SERVER_SET_4 0x08
#define TJC_PAGE_UPDATE_MODE 83
#define TJC_PAGE_UPDATE_MODE_BACK 0x00
#define TJC_PAGE_UPDATE_MODE_LOCAL 0x01
#define TJC_PAGE_UPDATE_MODE_ONLINE 0x02
#define TJC_PAGE_ONLINE_UPDATE 84
#define TJC_PAGE_ONLINE_UPDATE_BACK 0x00
#define TJC_PAGE_ONLINE_UPDATE_YES 0x01
#define TJC_PAGE_ONLINE_UPDATE_NO 0x02
#define TJC_PAGE_SEARCH_SERVER 85
#define TJC_PAGE_UNLOAD_MODE 86
#define TJC_PAGE_UNLOAD_MODE_MANUAL 0x00
#define TJC_PAGE_UNLOAD_MODE_AUTO 0x01
#define TJC_PAGE_UNLOAD_MODE_BACK 0x02
#define TJC_PAGE_AUTO_UNLOAD 87
#define TJC_PAGE_AUTO_UNLOAD_TO_LOAD 0x00
#define TJC_PAGE_AUTO_UNLOAD_YES 0x01
#define TJC_PAGE_OPEN_LANGUAGE2 88
#define TJC_PAGE_LANGUAGE2 89
#define TJC_PAGE_INSTALLING 90
void parse_cmd_msg_from_tjc_screen(char *cmd);
void page_to(int page_id);
void tjc_event_clicked_handler(int page_id, int widget_id, int type_id);
void tjc_event_setted_handler(int page_id, int widget_id, unsigned char first, unsigned char second);
void tjc_event_keyboard(char *cmd);
#endif

1
klipper Submodule

Submodule klipper added at 5a41ce0a0e

241
main.cpp
View File

@@ -1,241 +0,0 @@
#include <fstream>
#include <wpa_ctrl.h>
#include "include/MakerbaseClient.h"
#include "include/MoonrakerAPI.h"
#include "include/MakerbaseIPC.h"
#include "include/MakerbaseSerial.h"
#include "include/MakerbaseParseMessage.h"
#include "include/MakerbasePanel.h"
#include "include/MakerbaseParseIni.h"
#include "include/MakerbaseWiFi.h"
#include "include/MakerbaseNetwork.h"
#include "include/KlippyGcodes.h"
#include "include/mks_log.h"
#include "include/mks_preview.h"
#include "include/mks_init.h"
#include "include/mks_gpio.h"
#include "include/mks_update.h"
#include "include/mks_wpa_cli.h"
#include "include/mks_test.h"
#include "include/send_jpg.h"
// #include <gtk/gtk.h>
#include "include/ui.h"
#include "include/send_msg.h"
// #include "include/receive_msg.h"
// #include "include/printer.h"
// #include "include/systeminfo.h"
#include "include/KlippyRest.h"
#include "include/event.h"
extern int tty_fd;
extern int current_page_id;
extern int previous_page_id;
MakerbaseClient *ep;
extern std::string serial_by_id;
extern std::string str_gimage;
bool is_download_to_screen = false;
bool find_screen_tft_file = false;
// extern struct wpa_ctrl *mon_conn;
int main(int argc, char** argv) {
DIR *dir;
struct dirent *entry;
dir = opendir("/dev");
if (dir == NULL) {
perror("无法打开目录 /dev");
}
while ((entry = readdir(dir))) {
if (strstr(entry->d_name, "/dev/sd") == entry->d_name) {
if (strlen(entry->d_name) >= 8) {
char *partition_suffix = entry->d_name + 7;
if (partition_suffix[1] == '1') {
char command[256];
snprintf(command, sizeof(command), "/usr/bin/systemctl --no-block restart makerbase-automount@%s.service", partition_suffix);
system(command);
}
}
}
}
// getIPAddress();
/*
if (access("/dev/sda", F_OK) == 0) {
if (access("/dev/sda1", F_OK) == 0) {
if (access("/home/mks/gcode_files/sda1", F_OK) != 0) {
system("/usr/bin/systemctl --no-block restart makerbase-automount@sda1.service");
}
}
}
*/
if (access("/home/mks/gcode_files/sda1/mksscreen.recovery", F_OK) == 0) {
system("cp /home/mks/gcode_files/sda1/mksscreen.recovery /root/800_480.tft; sync");
}
if (access("/home/mks/gcode_files/sda1/mksclient.recovery", F_OK) == 0) {
system("dpkg -i /home/mks/gcode_files/sda1/mksclient.recovery; sync");
}
if (access("/root/800_480.tft", F_OK) == 0) {
find_screen_tft_file = true;
MKSLOG_BLUE("找到tft升级文件");
} else {
find_screen_tft_file = false;
MKSLOG_BLUE("没有找到tft升级文件");
}
/*
if (set_GPIO1_C5_high() == 0) {
MKSLOG("GPIO1_C5拉高成功");
} else {
MKSLOG("GPIO1_C5拉高失败");
}
if (init_GPIO1_B2() == 0) {
MKSLOG("初始化GPIO1_B2成功");
} else {
MKSLOG("初始化GPIO1_B2失败");
}
if (init_GPIO1_C3() == 0) {
MKSLOG("GPIO1_C3初始化成功");
} else {
MKSLOG("GPIO1_C3初始化失败");
}
*/
if (find_screen_tft_file == true) {
MKSLOG("执行移动程序");
system("/root/uart; mv /root/800_480.tft /root/800_480.tft.bak");
}
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0) {
system("dmesg > /home/mks/gcode_files/sda1/mks-dmesg.log; sync; ");
if (access("/home/mks/gcode_files/sda1/mks-super.sh", F_OK) == 0) {
system("bash /home/mks/gcode_files/sda1/mks-super.sh");
}
}
// pthread_t monitor_thread;
// pthread_t monitor_C3_thread;
pthread_t wpa_recv_thread;
// pthread_t test_thread;
// pthread_create(&monitor_thread, NULL, monitor_GPIO1_B2, NULL);
// pthread_create(&monitor_C3_thread, NULL, monitor_GPIO1_C3, NULL);
pthread_create(&wpa_recv_thread, NULL, mks_wifi_hdlevent_thread, NULL);
bool done = false;
pthread_t tid_msg_parse;
pthread_t sent_jpg_thread;
std::string host = "localhost";
std::string url = "ws://localhost:7125/websocket?";
MKSLOG("%s", url.data());
MKSLOG_RED("TEST");
if (argc == 2) {
host = argv[1];
url = "ws://" + host + ":7125/websocket?";
}
ep = new MakerbaseClient(host, "7125");
std::cout << ep->GetURL() << std::endl;
std::cout << ep->GetStatus() << std::endl;
std::cout << ep->GetIsConnected() << std::endl;
int fd; // 串口文件描述符
char buff[4096];
int count;
bool start_connect = false;
int connected_count = 0;
while (!ep->GetIsConnected()) {
std::cout << connected_count << "状态未连接: " << ep->GetIsConnected() << std::endl;
ep->Close();
ep->Connect(url);
connected_count++;
sleep(1);
ep->GetStatus();
sleep(1);
}
pthread_create(&tid_msg_parse, NULL, json_parse, NULL);
pthread_create(&sent_jpg_thread, NULL, sent_jpg_thread_handle, NULL); // 创建预览图线程
if ((fd = open("/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)) < 0) {
printf("Open tty failed\n");
} else {
MKSLOG_BLUE("%d", tty_fd);
tty_fd = fd;
printf("Open tty success\n");
set_option(fd, 115200, 8, 'N', 1);
try
{
fcntl(fd, F_SETFL, FNDELAY);
get_total_time();
sleep(2);
sub_object_status(); // 订阅相关的参数
sleep(2);
get_object_status(); // 主动获取必备的参数
sleep(2);
init_mks_status();
get_wlan0_status();
mks_wpa_scan_scanresults();
get_ssid_list_pages();
mks_get_version();
sleep(3);
send_cmd_val(tty_fd, "logo.version", "14"); // CLL 检测UI与SOC版本是否匹配4.4.14版本输出标记数字为14
if (find_screen_tft_file == false) {
previous_page_id = TJC_PAGE_LOGO;
if (get_mks_oobe_enabled() == true) {
current_page_id = TJC_PAGE_OPEN_LANGUAGE;
} else {
current_page_id = TJC_PAGE_MAIN;
}
} else {
current_page_id = TJC_PAGE_UPDATE_SUCCESS;
}
page_to(current_page_id);
}
catch(const std::exception& e)
{
std::cerr << "Page main error, " << e.what() << '\n';
}
}
while(1) {
refresh_page_show(); // CLL 修复刷新函数冲突问题,修改后xindi在同一时段内只能处理一条屏幕返回信息若同时多条信息输入则会造成丢失现象(尤其是刷新函数错误使屏幕返回变量名称无效信息,将会导致大量无效输入)
if ((count = read(fd, buff, sizeof(buff))) > 0) {
char *cmd = buff;
parse_cmd_msg_from_tjc_screen(cmd);
memset(buff, 0, sizeof(buff));
}
usleep(1000);
}
close(fd);
return 0;
}

View File

@@ -1,26 +0,0 @@
#! /bin/bash
if [ -d "/dev/serial/by-id" ];then
path=$(ls /dev/serial/by-id/*)
# echo $path
if [ -f "/home/mks/klipper_config/MKS_THR.cfg" ];then
# SERIALLINE=`cat /home/mks/klipper_config/MKS_THR.cfg | grep -E 'serial'`
# serial = ${SERIALLINE#*:}
# echo ${serial}
sed -i "s|serial:.*|serial:"${path}"|g" /home/mks/klipper_config/MKS_THR.cfg
fi
fi
# 删除多余的printer-* 冗余文件
CONFIG_DIR="/home/mks/klipper_config"
# 检查目录是否存在
if [ -d "$CONFIG_DIR" ]; then
# 进入目录
cd "$CONFIG_DIR"
# 找出所有带日期的printer-*.cfg文件按文件名中的日期排序然后删除排在前三之外的所有文件
ls printer-*.cfg | sort -t '-' -k 2,2r | tail -n +4 | xargs -r rm --
ls printer_*.cfg | sort -t '_' -k 2,2r | tail -n +3 | xargs -r rm --
fi

1
moonraker Submodule

Submodule moonraker added at 756cb2e8bb

View File

@@ -1,2 +0,0 @@
aux_source_directory(. DIR_LIB_SRCS)
add_library(src ${DIR_LIB_SRCS})

View File

@@ -1,73 +0,0 @@
#include "../include/KlippyGcodes.h"
std::string set_bed_temp(int temp) {
return SET_BED_TEMP + (std::string)" S" + std::to_string(temp);
}
std::string set_ext_temp(int temp, int tool) {
return SET_EXT_TEMP + (std::string)" T" + std::to_string(tool) + (std::string)" S" + std::to_string(temp);
}
std::string set_heater_temp(std::string heater, int temp) {
return "SET_HEATER_TEMPERATURE heater=" + heater + " target=" + std::to_string(temp);
}
std::string set_temp_fan_temp(std::string temp_fan, int temp) {
return "SET_TEMPERATURE_FAN_TARGET temperature_fan=" + temp_fan + " target=" + std::to_string(temp);
}
std::string set_fan_speed(int speed) {
// std::cout << "设置速率的计算结果为 = " << ((float)(int(speed) % 101) / 100 * 255) << std::endl;
// std::cout << "设置速率的计算结果为 = " << (int)((float)(int(speed) % 101) / 100 * 255) << std::endl;
std::string speed_temp = std::to_string(int(float(int(speed) % 101) / 100 * 255));
return SET_FAN_SPEED + (std::string)" S" + speed_temp;
}
/* Xindi */
std::string set_fan0_speed(int speed) {
// std::string speed_temp = std::to_string(int(float(int(speed)) / 100 * 255));
std::string speed_temp = std::to_string(float((float)(speed * 255) / 100));
std::cout << speed_temp << std::endl;
return "M106 P0 S" + speed_temp;
}
std::string set_fan2_speed(int speed) {
std::string speed_temp = std::to_string(float((float)(speed * 255) / 100));
return "M106 P2 S" + speed_temp;
}
std::string set_fan3_speed(int speed) {
std::string speed_temp = std::to_string(float((float)(speed * 255) / 100));
return "M106 P3 S" + speed_temp;
}
/* Xindi */
std::string set_extrusion_rate(std::string rate) {
return SET_EXT_FACTOR + (std::string)" S" + rate;
}
std::string set_speed_rate(std::string rate) {
return SET_SPD_FACTOR + (std::string)" S" + rate;
}
std::string testz_move(std::string dist) {
return TESTZ + dist;
}
std::string extrude(std::string dist, int speed) {
return MOVE + (std::string)" E" + dist + (std::string)" F" + std::to_string(speed);
}
std::string bed_mesh_load(std::string profile) {
return "BED_MESH_PROFILE LOAD=" + profile;
}
std::string bed_mesh_remove(std::string profile) {
return "BED_MESH_PROFILE REMOVE=" + profile;
}
std::string bed_mesh_save(std::string profile) {
return "BED_MESH_PROFILE SAVE=" + profile;
}

View File

@@ -1,101 +0,0 @@
#include "../include/KlippyRest.h"
#include "../include/mks_log.h"
#include "../include/event.h"
std::string server_files_metadata(std::string ip, std::string port, std::string filename) {
return send_request(ip, port, "server/files/metadata?filename=" + filename, "GET");
}
std::string printer_objects_query(std::string ip, std::string port, std::string parameter) {
return send_request(ip, port, "printer/objects/query?" + parameter, "GET");
}
std::string printer_print_start(std::string ip, std::string port, std::string filename) {
return send_request(ip, port, "printer/print/start?filename=" + filename, "POST");
}
std::string printer_print_pause(std::string ip, std::string port) {
return send_request(ip, port, "printer/print/pause", "POST");
}
std::string printer_print_resume(std::string ip, std::string port) {
return send_request(ip, port, "printer/print/resume", "POST");
}
std::string printer_print_cancel(std::string ip, std::string port) {
return send_request(ip, port, "printer/print/cancel", "POST");
}
std::string get_server_files_list(std::string ip, std::string port) {
return send_request(ip, port, "server/files/list?", "GET");
}
std::string get_server_files_directory(std::string ip, std::string port) {
return send_request(ip, port, "server/files/directory?", "GET");
}
std::string get_server_info(std::string ip, std::string port) {
return send_request(ip, port, "server/info", "GET");
}
std::string get_oneshot_token(std::string ip, std::string port) {
return send_request(ip, port, "access/oneshot_token", "GET");
}
std::string get_printer_info(std::string ip, std::string port) {
return send_request(ip, port, "printer/info", "GET");
}
// File delete
std::string delete_file_delete(std::string ip, std::string port, std::string filepath) {
return send_request(ip, port, "server/files/" + filepath, "DELETE");
}
std::string get_thumbnail_stream(std::string ip, std::string port, std::string thumbnail) {
std::string url = "http://" + ip + ":" + port + "/server/files/gcodes/" + thumbnail;
http::Request request{url};
struct http::Response response = request.send("GET");
if (response.status.code == 200) {
return std::string{response.body.begin(), response.body.end()};
} else {
return "";
}
}
std::string send_request(std::string ip, std::string port, std::string method, std::string request_type) {
std::string url = "http://" + ip + ":" + port + "/" + method;
std::string str_response = "";
url=replaceCharacters(url," ","%20");
MKSLOG_BLUE("Sending request to %s", url.data());
try
{
http::Request request{url};
struct http::Response response = request.send(request_type);
str_response = std::string{response.body.begin(), response.body.end()};
}
catch(const std::exception& e)
{
std::cerr << "Request failed, error" << e.what() << '\n';
}
return str_response;
}
/*
std::string send_post_request(std::string ip, std::string port, std::string method) {
std::string url = "http://" + ip + ":" + port + "/" + method;
std::cout << url << std::endl;
std::string str_response = "";
MKSLOG_BLUE("Sending request to %s", url.data());
try
{
http::Request request{url};
struct http::Response response = request.send("POST");
str_response = std::string{response.body.begin(), response.body.end()};
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return str_response;
}
*/

View File

@@ -1,161 +0,0 @@
#include "../include/MakerbaseClient.h"
MakerbaseClient::MakerbaseClient(std::string host = "localhost", std::string port = "7125") {
m_WebsocketClient.clear_access_channels(websocketpp::log::alevel::all); // 开启全部接入日志级别
m_WebsocketClient.clear_error_channels(websocketpp::log::elevel::all); // 开启全部错误日志级别
m_WebsocketClient.set_error_channels(websocketpp::log::elevel::none);
m_WebsocketClient.init_asio(); // 初始化asio
m_WebsocketClient.start_perpetual(); // 避免请求为空时退出实际上也是避免asio退出
// 独立运行client::run()的线程,主要是避免阻塞
m_Thread = websocketpp::lib::make_shared<websocketpp::lib::thread>(&client::run, &m_WebsocketClient);
this->host = host;
this->port = port;
this->is_connected = false;
}
MakerbaseClient::~MakerbaseClient()
{
m_WebsocketClient.stop_perpetual();
if (m_ConnectionMetadataPtr != nullptr && m_ConnectionMetadataPtr->get_status() == "Open")
{
websocketpp::lib::error_code ec;
m_WebsocketClient.close(m_ConnectionMetadataPtr->get_hdl(), websocketpp::close::status::going_away, "", ec); // 关闭连接
if (ec) {
std::cout << "> Error initiating close: " << ec.message() << std::endl;
}
}
m_Thread->join();
}
bool MakerbaseClient::Connect(std::string const & url) {
websocketpp::lib::error_code ec;
// 创建connect的共享指针注意此时创建并没有实际建立
client::connection_ptr con = m_WebsocketClient.get_connection(url, ec);
if (ec) {
std::cout << "> Connect initialization error: " << ec.message() << std::endl;
return false;
}
// 创建连接的metadata信息并保存
connection_metadata::ptr metadata_ptr = websocketpp::lib::make_shared<connection_metadata>(con->get_handle(), url);
m_ConnectionMetadataPtr = metadata_ptr;
try {
// 注册连接打开的Handler
con->set_open_handler(websocketpp::lib::bind(
&connection_metadata::on_open,
metadata_ptr,
&m_WebsocketClient,
websocketpp::lib::placeholders::_1
));
// 注册连接失败的Handler
con->set_fail_handler(websocketpp::lib::bind(
&connection_metadata::on_fail,
metadata_ptr,
&m_WebsocketClient,
websocketpp::lib::placeholders::_1
));
// 注册连接关闭的Handler
con->set_close_handler(websocketpp::lib::bind(
&connection_metadata::on_close,
metadata_ptr,
&m_WebsocketClient,
websocketpp::lib::placeholders::_1
));
// 注册连接接收消息的Handler
con->set_message_handler(websocketpp::lib::bind(
&connection_metadata::on_message,
metadata_ptr,
websocketpp::lib::placeholders::_1,
websocketpp::lib::placeholders::_2
));
// 进行连接
m_WebsocketClient.connect(con);
// this->status = m_ConnectionMetadataPtr->get_status();
std::cout << "Websocket连接中" << std::endl;
} catch (const std::exception & e) {
std::cout << e.what() << std::endl;
} catch (websocketpp::lib::error_code e) {
std::cout << e.message() << std::endl;
} catch (...) {
std::cout << "other exception" << std::endl;
}
return true;
}
bool MakerbaseClient::Close(std::string reason) {
websocketpp::lib::error_code ec;
if (m_ConnectionMetadataPtr != nullptr)
{
int close_code = websocketpp::close::status::normal;
// 关闭连接
m_WebsocketClient.close(m_ConnectionMetadataPtr->get_hdl(), close_code, reason, ec);
if (ec) {
std::cout << "> Error initiating close: " << ec.message() << std::endl;
return false;
}
std::cout << "关闭Websocket连接成功" << std::endl;
}
return true;
}
bool MakerbaseClient::Send(std::string message) {
websocketpp::lib::error_code ec;
if (m_ConnectionMetadataPtr != nullptr)
{
// 连接发送数据
m_WebsocketClient.send(m_ConnectionMetadataPtr->get_hdl(), message, websocketpp::frame::opcode::text, ec);
if (ec) {
std::cout << "> Error sending message: " << ec.message() << std::endl;
return false;
} else {
this->sending_message = message;
std::cout << "发送数据成功, 数据内容" + this->sending_message << std::endl;
}
}
return true;
}
bool MakerbaseClient::GetIsConnected() {
return this->is_connected;
}
std::string MakerbaseClient::GetStatus() {
if (m_ConnectionMetadataPtr != nullptr) {
this->status = m_ConnectionMetadataPtr->get_status();
}
if (this->status == "Open") {
this->is_connected = true;
} else {
this->is_connected = false;
}
return this->status;
}
connection_metadata::ptr MakerbaseClient::GetConnectionMetadataPtr() {
return m_ConnectionMetadataPtr;
}
std::string MakerbaseClient::GetURL() {
return "ws://" + this->host + ":" + this->port + "/websocket?";
}

View File

@@ -1,9 +0,0 @@
#include "../include/MakerbaseNetwork.h"
std::string get_wlan0_ip() {
char result[MAX_FILE_LEN] = {0};
std::string cmd = "ifconfig wlan0 | awk 'NR==2{print $2}' | tr -d '\n\r'";
execute_cmd(cmd.data(), result);
printf("%s", result);
return result;
}

View File

@@ -1,56 +0,0 @@
#include "../include/MakerbasePanel.h"
#include "../include/KlippyGcodes.h"
#include "../include/MoonrakerAPI.h"
#include "../include/MakerbasePanel.h"
std::string home() {
return json_run_a_gcode(HOME);
}
std::string homexy() {
return json_run_a_gcode(HOME_XY);
}
std::string z_tilt() {
return json_run_a_gcode(Z_TILT);
}
std::string quad_gantry_level() {
return json_run_a_gcode(QUAD_GANTRY_LEVEL);
}
// Move 函数
/**
* @brief
*
* @param axis 可选参数AXIS_X, AXIS_Y, AXIS_Z
* @param dist 距离与方向:如 +10, -100
* @param speed 速度
* @return std::string
*/
std::string move(std::string axis, std::string dist, int speed) {
return json_run_a_gcode(MOVE_RELATIVE + (std::string)"\n" + MOVE + (std::string)" "
+ axis + dist + (std::string)" F" + std::to_string(speed * 60) + (std::string)"\nG90");
}
/* 这个地方写在这里合不合适? */
std::string get_printer_object_status() {
nlohmann::json objects;
objects["webhook"];
objects["gcode_move"];
objects["toolhead"];
objects["configfile"];
objects["extruder"];
objects["heater_bed"];
objects["fan"];
objects["idle_timeout"];
objects["virtual_sdcard"];
objects["print_stats"];
objects["display_status"];
// objects["temperature_sensor sensor_name"];
// objects["filament_switch_sensor sensor_name"];
// objects["output_pin pin_name"];
objects["bed_mesh"];
// objects["gcode_macro macro_name"];
return json_query_printer_object_status(objects);
}

View File

@@ -1,138 +0,0 @@
#include "../include/MakerbaseParseIni.h"
dictionary *mksini = NULL;
dictionary *printer_cfg = NULL;
dictionary *mksversion = NULL;
// std::string get_cfg_serial() {
// printer_cfg = iniparser_load("/home/mks/klipper_config/MKS_THR.cfg");
// if (printer_cfg == NULL) {
// std::cout << "cfg parse failure!" << std::endl;
// return "";
// }
// std::string sk = "mcu MKS_THR:serial";
// std::cout << "打开配置文件成功" << std::endl;
// const char *value = iniparser_getstring(mksini, sk.c_str(), "");
// return (std::string)value;
// }
// CLL 用于获取在线更新信息
int updateini_load() {
mksini = iniparser_load("/root/auto_update/update_info.ini");
if (mksini == NULL) {
std::cout << "Ini parse failure" << std::endl;
return -1;
}
return 0;
}
// CLL 用于获取在线更新进度
int progressini_load() {
mksini = iniparser_load("/root/auto_update/update_progress.ini");
if (mksini == NULL) {
std::cout << "Ini parse failure" << std::endl;
return -1;
}
return 0;
}
int mksini_load() {
mksini = iniparser_load(INIPATH);
if (mksini == NULL) {
std::cout << "Ini parse failure!" << std::endl;
return -1;
}
return 0;
}
void mksini_free() {
iniparser_freedict(mksini);
}
std::string mksini_getstring(std::string section, std::string key, std::string def) {
std::string sk = section + ":" + key;
const char *value = iniparser_getstring(mksini, sk.c_str(), def.c_str());
return (std::string)value;
}
int mksini_getint(std::string section, std::string key, int notfound) {
std::string sk = section + ":" + key;
int value = iniparser_getint(mksini, sk.c_str(), notfound);
return value;
}
double mksini_getdouble(std::string section, std::string key, double notfound) {
std::string sk = section + ":" + key;
double value = iniparser_getdouble(mksini, sk.c_str(), notfound);
return value;
}
bool mksini_getboolean(std::string section, std::string key, int notfound) {
std::string sk = section + ":" + key;
int value = iniparser_getboolean(mksini, sk.c_str(), notfound);
return (value == 0) ? false : true;
}
int mksini_set(std::string section, std::string key, std::string value) {
std::string sk = section + ":" + key;
int ret;
ret = iniparser_set(mksini, sk.c_str(), value.c_str());
return ret;
}
void mksini_unset(std::string section, std::string key) {
std::string sk = section + ":" + key;
iniparser_unset(mksini, sk.c_str());
}
// 保存到配置文件
void mksini_save() {
FILE *ini = fopen(INIPATH, "w");
if (ini == NULL) {
printf("[error] open mksini failed");
return;
}
iniparser_dump_ini(mksini, ini);
fclose(ini);
}
int mksversion_load() {
mksversion = iniparser_load(VERSION_PATH);
if (mksversion == NULL) {
std::cout << "Mks version failure!" << std::endl;
return -1;
}
return 0;
}
void mksversion_free() {
iniparser_freedict(mksversion);
}
std::string mksversion_mcu(std::string def) {
std::string version = "version:mcu";
const char *value = iniparser_getstring(mksversion, version.c_str(), def.c_str());
return (std::string)value;
}
std::string mksversion_ui(std::string def) {
std::string version = "version:ui";
const char *value = iniparser_getstring(mksversion, version.c_str(), def.c_str());
return (std::string)value;
}
std::string mksversion_soc(std::string def) {
std::string version = "version:soc";
const char *value = iniparser_getstring(mksversion, version.c_str(), def.c_str());
return (std::string)value;
}

View File

@@ -1,205 +0,0 @@
#include "nlohmann/json.hpp"
#include "../include/MakerbaseClient.h"
#include "../include/MakerbaseCommand.h"
#include "../include/MoonrakerAPI.h"
#include "../include/mks_log.h"
#include "../include/MakerbaseParseMessage.h"
#include "../include/event.h"
#include "../include/mks_error.h"
#include "../include/mks_printer.h"
#include "../include/mks_file.h"
#include "../include/mks_gcode.h"
// #include "../include/systeminfo.h"
// #include "../include/printer.h"
// #include "../include/file.h"
// #include "../include/job.h"
// #include "../include/tjc_event.h"
#include "../include/ui.h"
extern MakerbaseClient *ep;
bool get_status_flag = false;
std::string message;
bool is_get_message = false;
int response_type_id;
nlohmann::json response;
nlohmann::json res;
extern bool filelist_changed;
extern bool all_level_saving;
//4.4.3 CLL 修改网页打印信息订阅
extern bool jump_to_print;
extern nlohmann::json output_metadata;
extern int current_page_id;
void *json_parse(void *arg) {
while (1) {
if (is_get_message == true) {
try
{
response = string2json(message);
res = response;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
if (res["id"] != nlohmann::detail::value_t::null) {
std::cout << response["id"] << std::endl;
// std::cout << response << std::endl;
int id = response["id"];
switch (id)
{
case 3545:
std::cout << response << std::endl;
parse_file_estimated_time(response);
break;
case 4654:
std::cout << response << std::endl;
if (response["result"] == "ok") {
std::cout << response << std::endl;
} else if (response["result"] != nlohmann::detail::value_t::null) {
if (response["result"]["status"] != nlohmann::detail::value_t::null) {
std::cout << response["result"]["status"] << std::endl;
parse_subscribe_objects_status(response["result"]["status"]);
}
}
break;
case 5445:
std::cout << response << std::endl;
if (response["result"] != nlohmann::detail::value_t::null) {
parse_printer_info(response["result"]);
}
break;
// 解析一下总的时间
case 5656:
std::cout << response << std::endl;
if (response["result"] != nlohmann::detail::value_t::null) {
// parse_server_history_totals(response["result"]);
if (response["result"]["job_totals"] != nlohmann::detail::value_t::null) {
parse_server_history_totals(response["result"]["job_totals"]);
}
}
break;
default:
break;
}
}
if (res["error"] != nlohmann::detail::value_t::null) {
parse_error(response["error"]);
} else {
if (response["method"] != nlohmann::detail::value_t::null) {
// std::cout << response << std::endl;
std::string method = response["method"];
if (response["method"] == "notify_proc_stat_update") {
// MKSLOG_BLUE("%s", message.data());
/*
if (get_status_flag == false) {
// get_object_status(); // 主动获取必备的参数
sleep(1);
sub_object_status(); // 订阅相关的参数
sleep(1);
get_status_flag = true;
}
*/
} else if (method == "notify_gcode_response") {
MKSLOG_RED("%s", message.data());
parse_gcode_response(response["params"]);
MKSLOG_BLUE("Gcode 响应");
} else if (method == "notify_status_update") {
//std::cout << response["params"][0] << std::endl;
parse_subscribe_objects_status(response["params"][0]);
/*
if (get_status_flag == false) {
get_status_flag = true;
}
*/
} else if (method == "notify_klippy_ready") {
std::cout << response << std::endl;
MKSLOG_BLUE("Klippy 准备好了");
// 在这里进行订阅操作
get_object_status();
sub_object_status();
} else if (method == "notify_klippy_shutdown") {
MKSLOG_BLUE("Klippy 关机");
} else if (method == "notify_klippy_disconnected") {
MKSLOG_BLUE("Klippy 已断开连接");
get_object_status();
sub_object_status();
} else if (method == "notify_filelist_changed") {
filelist_changed = true;
MKSLOG_BLUE("文件列表已更改");
if (all_level_saving == false) {
all_level_saving = true;
}
} else if (method == "notify_update_response") {
MKSLOG_BLUE("更新管理器响应");
} else if (method == "notify_update_refreshed") {
MKSLOG_BLUE("更新管理器已刷新");
} else if (method == "notify_cpu_throttled") {
MKSLOG_BLUE("Moonraker 进程统计更新");
} else if (method == "notify_history_changed") {
//MKSLOG_RED("%s", message.data());
//std::cout << response << std::endl;
//4.4.3 CLL 修改网页打印信息订阅
switch (current_page_id)
{
case TJC_PAGE_PRINTING:
case TJC_PAGE_PRINT_ZOFFSET:
case TJC_PAGE_PRINT_FILAMENT:
case TJC_PAGE_PRINTING_2:
break;
default:
parse_file_estimated_time_send(response["params"][0]["job"]["metadata"]);
MKSLOG_BLUE("历史改变");
break;
}
} else if (method == "notify_user_created") {
MKSLOG_BLUE("授权用户创建");
} else if (method == "notify_user_deleted") {
MKSLOG_BLUE("已删除授权用户");
} else if (method == "notify_service_state_changed") {
// std::cout << response << std::endl;
// MKSLOG_BLUE("服务状态已更改");
} else if (method == "notify_job_queue_changed") {
MKSLOG_BLUE("作业队列已更改");
} else if (method == "notify_button_event") {
MKSLOG_BLUE("按钮事件");
} else if (method == "notify_announcement_update") {
MKSLOG_BLUE("公告更新事件");
} else if (method == "notify_announcement_dismissed") {
MKSLOG_BLUE("公告驳回事件");
} else if (method == "notify_announcement_wake") {
MKSLOG_BLUE("公告唤醒事件");
} else if (method == "notify_agent_event") {
MKSLOG_BLUE("代理事件");
} else if (method == "notify_power_changed") {
MKSLOG_BLUE("notify_power_changed");
// std::cout << response << std::endl;
}
}
}
response.clear();
is_get_message = false;
}
// usleep(300);
usleep(50);
}
// pthread_exit(NULL);
}

View File

@@ -1,192 +0,0 @@
#include <../include/MakerbaseSerial.h>
#include <time.h>
int set_option(int fd, int baudrate, int bits, unsigned char parity, unsigned char stopbit) {
// time_t start_time = 0, end_time = 0;
// time(&start_time);
struct termios newtio, oldtio;
if (tcgetattr(fd, &oldtio) != 0) {
// printf("读取串口参数发生错误\n");
return -1;
}
memset(&newtio, 0, sizeof(struct termios));
cfmakeraw(&newtio); // 设置为原始模式
/* 使能接收 */
newtio.c_cflag |= CREAD;
speed_t speed;
// 数据位相关的比特位清零
newtio.c_cflag &= ~CSIZE;
switch (bits)
{
case 7:
newtio.c_cflag |= CS7;
// printf("7数据位\n");
break;
case 8:
newtio.c_cflag |= CS8;
// printf("8数据位\n");
break;
default:
newtio.c_cflag |= CS8;
// printf("8数据位\n");
break;
}
switch (parity)
{
case 'O':
case 'o':
newtio.c_cflag |= (PARENB | PARODD);
newtio.c_cflag |= INPCK;
// printf("奇校验\n");
break;
case 'E':
case 'e':
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
newtio.c_iflag |= INPCK;
// printf("偶校验\n");
break;
case 'N':
default:
newtio.c_cflag &= ~PARENB;
newtio.c_iflag &= ~INPCK;
// printf("设置为无校验");
break;
}
// 设置波特率
switch (baudrate)
{
case 1200:
speed = B1200;
// printf("波特率为1200\n");
break;
case 1800:
speed = B1800;
// printf("波特率为1800\n");
break;
case 2400:
speed = B2400;
// printf("波特率为2400\n");
break;
case 4800:
speed = B4800;
// printf("波特率为4800\n");
break;
case 9600:
speed = B9600;
printf("波特率为9600\n");
break;
case 19200:
speed = B19200;
// printf("波特率为19200\n");
break;
case 38400:
speed = B38400;
// printf("波特率为38400\n");
break;
case 57600:
speed = B57600;
// printf("波特率为57600\n");
break;
case 115200:
speed = B115200;
// printf("波特率为115200\n");
break;
case 230400:
speed = B230400;
// printf("波特率为230400\n");
break;
case 460800:
speed = B460800;
// printf("波特率为460800\n");
break;
case 500000:
speed = B500000;
// printf("波特率为500000\n");
break;
case 921600:
speed = B921600;
printf("波特率为921600\n");
break;
default:
speed = B115200;
// printf("波特率为115200\n");
break;
}
if (0 > cfsetspeed(&newtio, speed)) {
// printf("设置波特率失败\n");
return -1;
}
// 设置停止位
switch (stopbit) {
case 1:
newtio.c_cflag &= ~CSTOPB;
// printf("设置1个停止位\n");
break;
case 2:
newtio.c_cflag |= CSTOPB;
// printf("设置2个停止位\n");
break;
default:
newtio.c_cflag &= ~CSTOPB;
// printf("默认设置1个停止位\n");
break;
}
// 将MIN和TIME设置为0
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
// 清空缓冲区
if (0 > tcflush(fd, TCIOFLUSH)) {
// printf("清空缓冲区失败\n");
return -1;
}
// 写入配置、使配置生效
if (0 > tcsetattr(fd, TCSANOW, &newtio)) {
// printf("配置串口失败");
return -1;
}
// time(&end_time);
// printf("设置波特率使用的时间: %f\n", difftime(end_time, start_time));
return 0;
}
char *create_command(char *cmd) {
char end[4] = {(char)0xff, (char)0xff, (char)0xff, 0};
return strcat(cmd, end);
}

View File

@@ -1,19 +0,0 @@
#include "../include/MakerbaseShell.h"
void execute_cmd(const char *cmd, char *result) {
char buf_ps[MAX_FILE_LEN];
char ps[MAX_FILE_LEN];
FILE *ptr;
strcpy(ps, cmd);
if ((ptr = popen(ps, "r")) != NULL) {
while (fgets(buf_ps, MAX_FILE_LEN, ptr) != NULL)
{
strcat(result, buf_ps);
if (strlen(result) > MAX_FILE_LEN)
break;
}
pclose(ptr);
} else {
printf("popen %s error\n", ps);
}
}

View File

@@ -1,563 +0,0 @@
#include <iostream>
#include <cstring>
#include <vector>
#include <set>
#include <regex>
#include <unistd.h>
#include "../include/MakerbaseWiFi.h"
#include "../include/MakerbaseShell.h"
#include "../include/mks_log.h"
#include "../include/mks_wpa_cli.h"
#include "../include/common.h"
struct mks_wifi_status_result_t status_result;
struct mks_wifi_status_t wpa_status;
std::vector<std::string> result_list;
std::vector<std::string> ssid_list;
std::vector<int> level_list;
std::string page_wifi_ssid_list[5] = {"", "", "", "", ""};
int page_wifi_ssid_list_pages = 0;
int page_wifi_current_pages;
std::string get_wifi_name = "";
extern std::string current_connected_ssid_name;
void set_page_wifi_ssid_list(int pages) {
page_wifi_ssid_list[0] = "";
page_wifi_ssid_list[1] = "";
page_wifi_ssid_list[2] = "";
page_wifi_ssid_list[3] = "";
page_wifi_ssid_list[4] = "";
auto it = ssid_list.begin();
for (int i = 0; i < pages * 5; i++) {
it++;
}
if (it != ssid_list.end()) {
page_wifi_ssid_list[0] = *it;
it++;
}
if (it != ssid_list.end()) {
page_wifi_ssid_list[1] = *it;
it++;
}
if (it != ssid_list.end()) {
page_wifi_ssid_list[2] = *it;
it++;
}
if (it != ssid_list.end()) {
page_wifi_ssid_list[3] = *it;
it++;
}
if (it != ssid_list.end()) {
page_wifi_ssid_list[4] = *it;
}
for (int j = 0; j < 5; j++) {
std::cout << page_wifi_ssid_list[j] << std::endl;
}
}
//4.4.1 CLL 修复WiFi刷新
void get_ssid_list_pages() {
if (ssid_list.size() % 5 == 0) {
page_wifi_ssid_list_pages = ssid_list.size() / 5;
} else {
page_wifi_ssid_list_pages = ssid_list.size() / 5 + 1;
}
if (page_wifi_ssid_list_pages > 5) {
page_wifi_ssid_list_pages = 5;
}
}
void get_wlan0_status() {
mks_wifi_run_cmd_status(&status_result);
}
bool detected_wlan0() {
if (access("/var/run/wpa_supplicant/wlan0", F_OK) == 0) {
return true;
} else {
return false;
}
}
//
void split_scan_result(std::string result) {
result_list.clear();
level_list.clear();
ssid_list.clear();
char *sub_result;
std::string token;
std::string delimiter = "\n";
size_t pos = 0;
int n_level = -100;
int index = 0;
while ((pos = result.find(delimiter)) != std::string::npos) {
token = result.substr(0, pos);
result_list.push_back(token);
result.erase(0, pos + delimiter.length());
}
for (int i = 1; i < result_list.size(); i++) {
char bssid[64];
char freq[64];
char level[64];
char flag[64];
char ssid[64];
unsigned char re[100];
sub_result = const_cast<char*>(result_list[i].data());
if (5 == sscanf(sub_result, "%s \t %s \t %s \t %s \t %s", &bssid, &freq, &level, &flag, &ssid)) {
printf_decode(re, 64, ssid);
level_list.push_back(atoi(level));
if (re[0] == '\x00') {
MKSLOG_YELLOW("扫描出来的ssid为\\0");
} else {
ssid_list.push_back((char *)re);
// ssid_list.insert((char *)re);
}
}
memset(sub_result, 0x00, sizeof(sub_result));
memset(ssid, 0x00, sizeof(ssid));
}
for (int j = 0; j < ssid_list.size(); j++) {
if (current_connected_ssid_name == ssid_list[j]) {
std::string temp = ssid_list[j];
ssid_list[j] = ssid_list[0];
ssid_list[0] = temp;
}
}
for (int k = 0; k < ssid_list.size(); k++) {
MKSLOG_RED("%s", ssid_list[k].c_str());
}
}
std::string rescan() {
MKSLOG("wpa_cli SCAN");
return wpa_cli("SCAN");
}
std::string save_wpa_conf() {
MKSLOG("Saving WPA config");
return wpa_cli("SAVE_CONFIG");
}
std::string wpa_cli(std::string command) {
char result[MAX_FILE_LEN];
std::string cmd = "wpa_cli " + command;
execute_cmd(cmd.data(), result);
return result;
}
// WifiChannels:
static std::string lookup(int freq) {
switch (freq)
{
case 2412:
return "2.4GHz 1";
break;
case 2417:
return "2.4GHz 2";
break;
case 2422:
return "2.4GHz 3";
break;
case 2427:
return "2.4GHz 4";
break;
case 2432:
return "2.4GHz 5";
break;
case 2437:
return "2.4GHz 6";
break;
case 2442:
return "2.4GHz 7";
break;
case 2447:
return "2.4GHz 8";
break;
case 2452:
return "2.4GHz 9";
break;
case 2457:
return "2.4GHz 10";
break;
case 2462:
return "2.4GHz 11";
break;
case 2467:
return "2.4GHz 12";
break;
case 2472:
return "2.4GHz 13";
break;
case 2484:
return "2.4GHz 14";
break;
case 5035:
return "5GHz 7";
break;
case 5040:
return "5GHz 8";
break;
case 5045:
return "5GHz 9";
break;
case 5055:
return "5GHz 11";
break;
case 5060:
return "5GHz 12";
break;
case 5080:
return "5GHz 16";
break;
case 5170:
return "5GHz 34";
break;
case 5180:
return "5GHz 36";
break;
case 5190:
return "5GHz 38";
break;
case 5200:
return "5GHz 40";
break;
case 5210:
return "5GHz 42";
break;
case 5220:
return "5GHz 44";
break;
case 5230:
return "5GHz 46";
break;
case 5240:
return "5GHz 48";
break;
case 5260:
return "5GHz 52";
break;
case 5280:
return "5GHz 56";
break;
case 5300:
return "5GHz 60";
break;
case 5320:
return "5GHz 64";
break;
case 5500:
return "5GHz 100";
break;
case 5560:
return "5GHz 112";
break;
case 5580:
return "5GHz 116";
break;
case 5600:
return "5GHz 120";
break;
case 5620:
return "5GHz 124";
break;
case 5640:
return "5GHz 128";
break;
case 5660:
return "5GHz 132";
break;
case 5680:
return "5GHz 136";
break;
case 5700:
return "5GHz 140";
break;
case 5720:
return "5GHz 144";
break;
case 5745:
return "5GHz 149";
break;
case 5765:
return "5GHz 153";
break;
case 5785:
return "5GHz 157";
break;
case 5805:
return "5GHz 161";
break;
case 5825:
return "5GHz 165";
break;
case 4915:
return "5GHz 183";
break;
case 4920:
return "5GHz 184";
break;
case 4925:
return "5GHz 185";
break;
case 4935:
return "5GHz 187";
break;
case 4940:
return "5GHz 188";
break;
case 4945:
return "5GHz 189";
break;
case 4960:
return "5GHz 192";
break;
case 4980:
return "5GHz 196";
break;
default:
return "";
break;
}
}
size_t printf_decode(unsigned char *buf, size_t maxlen, const char *str)
{
const char *pos = str;
size_t len = 0;
int val;
while (*pos) {
if (len + 1 >= maxlen)
break;
switch (*pos) {
case '\\':
pos++;
switch (*pos) {
case '\\':
buf[len++] = '\\';
pos++;
break;
case '"':
buf[len++] = '"';
pos++;
break;
case 'n':
buf[len++] = '\n';
pos++;
break;
case 'r':
buf[len++] = '\r';
pos++;
break;
case 't':
buf[len++] = '\t';
pos++;
break;
case 'e':
buf[len++] = '\033';
pos++;
break;
case 'x':
pos++;
val = hex2byte(pos);
if (val < 0) {
val = hex2num(*pos);
if (val < 0)
break;
buf[len++] = val;
pos++;
} else {
buf[len++] = val;
pos += 2;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
val = *pos++ - '0';
if (*pos >= '0' && *pos <= '7')
val = val * 8 + (*pos++ - '0');
if (*pos >= '0' && *pos <= '7')
val = val * 8 + (*pos++ - '0');
buf[len++] = val;
break;
default:
break;
}
break;
default:
buf[len++] = *pos++;
break;
}
}
if (maxlen > len)
buf[len] = '\0';
return len;
}
int hex2byte(const char *hex)
{
int a, b;
a = hex2num(*hex++);
if (a < 0)
return -1;
b = hex2num(*hex++);
if (b < 0)
return -1;
return (a << 4) | b;
}
static int hex2num(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
int parse_scan_results(char* scan_results) {
result_list.clear();
level_list.clear();
ssid_list.clear();
char* lines[1024] = {0};
int num_lines = 0;
char* line = strtok(scan_results, "\n");
while (line != NULL) {
lines[num_lines++] = line;
line = strtok(NULL, "\n");
}
for (int i = 1; i < num_lines; ++i) {
char* fields[5] = {0};
int num_fields = 0;
char ssid_line[128] = {0};
memset(ssid_line, 0x00, sizeof(ssid_line));
strcpy(ssid_line, lines[i]);
int ssid_line_index = 0;
char* field = strtok(lines[i], " \t");
while (field != NULL) {
if (4 == num_fields) {
ssid_line_index = field - lines[i];
}
fields[num_fields++] = field;
field = strtok(NULL, " \t");
}
if (num_fields < 5) {
printf("Invalid scan result: %s\n", lines[i]);
continue;
} else {
unsigned char ssid_name[64];
printf_decode(ssid_name, 64, ssid_line + ssid_line_index);
if (ssid_name[0] == '\x00') {
} else {
ssid_list.push_back((char *)ssid_name);
}
}
if (strstr(fields[3], "ESS") && strstr(fields[3], "privacy") && strstr(fields[3], "hidden-ssid")) {
} else {
}
}
for (int j = 0; j < ssid_list.size(); j++) {
if (current_connected_ssid_name == ssid_list[j]) {
std::string temp = ssid_list[j];
ssid_list[j] = ssid_list[0];
ssid_list[0] = temp;
}
}
for (int k = 0; k < ssid_list.size(); k++) {
MKSLOG_RED("%s", ssid_list[k].c_str());
}
return 0;
}

View File

@@ -1,476 +0,0 @@
#include "../include/MoonrakerAPI.h"
#include "../include/MakerbaseCommand.h"
#include "nlohmann/json.hpp"
extern int response_type_id;
nlohmann::json string2json(std::string response) {
return nlohmann::json::parse(response);
}
inline std::string create_json_without_params(int cmd) {
response_type_id = cmd;
nlohmann::json api;
api["jsonrpc"] = "2.0";
api["method"] = method2command[cmd];
api["id"] = method2id[cmd];
return api.dump();
}
inline std::string create_json(int cmd, nlohmann::json params) {
response_type_id = cmd;
nlohmann::json api;
api["jsonrpc"] = "2.0";
api["method"] = method2command[cmd];
api["params"] = params;
api["id"] = method2id[cmd];
return api.dump();
}
std::string json_get_klippy_host_information() {
return create_json_without_params(0x03);
}
std::string json_emergency_stop() {
// return create_json(0x04, no_params, 4564);
return create_json_without_params(0x04);
}
std::string json_host_restart() {
return create_json_without_params(0x05);
}
std::string json_firmware_restart() {
return create_json_without_params(0x06);
}
std::string json_list_available_printer_objects() {
return create_json_without_params(0x11);
}
std::string json_query_printer_object_status(nlohmann::json objects) {
nlohmann::json params;
params["objects"] = objects;
return create_json(0x12, params);
}
std::string json_subscribe_to_printer_object_status(nlohmann::json objects) {
nlohmann::json params;
params["objects"] = objects;
return create_json(0x13, params);
}
std::string json_query_endstops() {
return create_json_without_params(0x14);
}
std::string json_query_server_info() {
return create_json_without_params(0x15);
}
std::string json_get_server_configuration() {
return create_json_without_params(0x16);
}
std::string json_request_cached_temperature_data() {
return create_json_without_params(0x17);
}
std::string json_request_cached_gcode_responses(int count) {
nlohmann::json params;
params["count"] = count;
return create_json(0x18, params);
}
std::string json_restart_server() {
return create_json_without_params(0x19);
}
/* GCode APIs */
std::string json_run_a_gcode(std::string script) {
nlohmann::json params;
params["script"] = script;
return create_json(0x21, params);
}
std::string json_get_gcode_help() {
return create_json_without_params(0x22);
}
/* Print Management */
std::string json_print_a_file(std::string filename) {
nlohmann::json params;
params["filename"] = filename;
return create_json(0x31, params);
}
std::string json_pause_a_print() {
return create_json_without_params(0x32);
}
std::string json_resume_a_print() {
return create_json_without_params(0x33);
}
std::string json_cancel_a_print() {
return create_json_without_params(0x34);
}
/* Machine Commands */
std::string json_get_system_info() {
return create_json_without_params(0x41);
}
std::string json_shutdown_the_operating_system(){
return create_json_without_params(0x42);
}
std::string json_reboot_the_operating_system() {
return create_json_without_params(0x43);
}
std::string json_restart_a_system_service(std::string name) {
nlohmann::json params;
params["service"] = name;
return create_json(0x44, params);
}
std::string json_stop_a_system_service(std::string name) {
nlohmann::json params;
params["service"] = name;
return create_json(0x45, params);
}
std::string json_start_a_system_service(std::string name) {
nlohmann::json params;
params["service"] = name;
return create_json(0x46, params);
}
std::string json_get_moonraker_process_stats() {
return create_json_without_params(0x47);
}
/* File Operations */
std::string json_list_available_files() {
nlohmann::json params;
// params["root"] = root_folder;
// return create_json(0x51, params);
return create_json_without_params(0x51);
}
std::string json_get_gcode_metadata(std::string filename) {
nlohmann::json params;
params["filename"] = filename;
return create_json(0x52, params);
}
std::string json_get_directory_information(bool extended) {
nlohmann::json params;
// params["path"] = path;
params["extended"] = extended;
return create_json(0x53, params);
}
std::string json_create_directory(std::string path) {
nlohmann::json params;
params["path"] = path;
return create_json(0x54, params);
}
std::string json_delete_directory(std::string path, bool force) {
nlohmann::json params;
params["path"] = path;
params["force"] = force;
return create_json(0x55, params);
}
std::string json_move_a_file_or_directory(std::string source, std::string dest) {
nlohmann::json params;
params["source"] = source;
params["dest"] = dest;
return create_json(0x56, params);
}
std::string json_copy_a_file_or_directory(std::string source, std::string dest) {
nlohmann::json params;
params["source"] = source;
params["dest"] = dest;
return create_json(0x57, params);
}
// std::string json_file_download() {
// return "";
// }
// std::string json_file_upload() {
// return "";
// }
std::string json_file_delete(std::string path) {
// path: {root}/{filename}
nlohmann::json params;
params["path"] = path;
return create_json(0x5a, params);
}
// std::string json_download_klippy_log() {
// return "";
// }
// std::string json_download_moonraker_log() {
// return "";
// }
/* Authorization */
// std::string json_login_user() {
// return "";
// }
// std::string json_logout_current_user() {
// return "";
// }
// std::string json_get_current_user() {
// return "";
// }
// std::string json_create_user() {
// return "";
// }
// std::string json_delete_user() {
// return "";
// }
// std::string json_list_available_users() {
// return "";
// }
// std::string json_reset_user_password() {
// return "";
// }
// std::string json_generate_a_oneshot_token() {
// return "";
// }
// std::string json_retrieve_information_about_authorization_endpoints() {
// return "";
// }
/* Database APIs */
std::string json_list_namespaces() {
return create_json_without_params(0x71);
}
std::string json_get_database_item(std::string nsp, std::string key) {
nlohmann::json params;
params["namespace"] = nsp;
params["key"] = key;
return create_json(0x72, params);
}
std::string json_add_database_item(std::string nsp, std::string key, int value) {
nlohmann::json params;
params["namespace"] = nsp;
params["key"] = key;
params["value"] = value;
return create_json(0x73, params);
}
std::string json_delete_database_item(std::string nsp, std::string key) {
nlohmann::json params;
params["namespace"] = nsp;
params["key"] = key;
return create_json(0x74, params);
}
/* Job Queue APIs */
std::string json_retrieve_the_job_queue_status() {
return create_json_without_params(0x81);
}
std::string json_enqueue_a_job(std::vector<std::string> filenames) {
nlohmann::json params;
params["filenames"] = filenames;
return create_json(0x82, params);
}
std::string json_remove_a_job(std::vector<std::string> job_ids) {
nlohmann::json params;
params["job_ids"] = job_ids;
return create_json(0x83, params);
}
std::string json_pause_the_job_queue() {
return create_json_without_params(0x84);
}
std::string json_start_the_job_queue() {
return create_json_without_params(0x85);
}
/* Announcement APIs */
std::string json_list_announcements(bool incluede_dismissed) {
nlohmann::json params;
params["include_dismissed"] = incluede_dismissed;
return create_json(0x86, params);
}
std::string json_update_announcements() {
return create_json_without_params(0x87);
}
std::string json_dismiss_an_announcement(std::string entry_id, int wake_time) {
nlohmann::json params;
params["entry_id"] = entry_id;
params["wake_time"] = wake_time;
return create_json(0x88, params);
}
std::string json_list_announcement_feeds() {
return create_json_without_params(0x89);
}
std::string json_add_an_announcement_feed(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x8a, params);
}
std::string json_remove_an_announcement_feed(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x8b, params);
}
/* Webcam APIs */
std::string json_list_webcams() {
return create_json_without_params(0x101);
}
std::string json_get_webcam_information(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x102, params);
}
std::string json_add_or_update_a_webcam(std::string name) {
nlohmann::json params;
params["name"] = name;
params["snapshot_url"] = "/webcam?action=snapshot";
params["stream_url"] = "/webcam?action=stream";
return create_json(0x103, params);
}
std::string json_delete_a_webcam(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x104, params);
}
std::string json_test_a_webcam(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x105, params);
}
/* Update Manager APIs */
std::string json_get_update_status(bool refresh) {
nlohmann::json params;
params["refresh"] = refresh;
return create_json(0x91, params);
}
/* Perform a full update */
std::string json_perform_a_full_update() {
return create_json_without_params(0x90);
}
std::string json_update_moonraker() {
return create_json_without_params(0x92);
}
std::string json_update_klipper() {
return create_json_without_params(0x93);
}
std::string json_update_client(std::string name) {
nlohmann::json params;
params["name"] = name;
return create_json(0x94, params);
}
std::string json_update_system_packages() {
return create_json_without_params(0x95);
}
std::string json_recover_a_corrupt_repo(std::string name, bool hard) {
nlohmann::json params;
params["name"] = name;
params["hard"] = hard;
return create_json(0x96, params);
}
/* Power APIs */
std::string json_get_device_list() {
return create_json_without_params(0xa1);
}
std::string json_get_device_status(std::string device) {
nlohmann::json params;
params["device"] = device;
return create_json(0xa2, params);
}
std::string json_get_device_state(std::string device, std::string action) {
nlohmann::json params;
params["device"] = device;
params["action"] = action;
return create_json(0xa3, params);
}
// std::string json_get_batch_device_status(std::string dev_x[]);
// std::string json_batch_power_on_devices(std::string dev_x[]);
// std::string json_batch_power_off_devices(std::string dev_x[]);
/* WLED APIs */
std::string json_get_strips() {
return create_json_without_params(0xb1);
}
std::string json_get_strip_status() {
nlohmann::json params;
params["lights"];
params["desk"];
return create_json(0xb2, params);
}
std::string json_turn_strip_on() {
nlohmann::json params;
params["lights"];
params["desk"];
return create_json(0xb3, params);
}
std::string json_turn_strip_off() {
nlohmann::json params;
params["lights"];
params["desk"];
return create_json(0xb4, params);
}
std::string json_toggle_strip_on_off_state() {
nlohmann::json params;
params["lights"];
params["desk"];
return create_json(0xb5, params);
}
std::string json_get_job_totals() {
return create_json_without_params(0xd2);
}
std::string json_reset_totals() {
return create_json_without_params(0xd3);
}

View File

@@ -1,17 +0,0 @@
#include "../include/common.h"
void super_split(const std::string& s, std::vector<std::string>& v, const std::string& c) {
std::string::size_type pos1, pos2;
size_t len = s.length();
pos2 = s.find(c);
pos1 = 0;
while (std::string::npos != pos2)
{
v.emplace_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
}
if (pos1 != len) {
v.emplace_back(s.substr(pos1));
}
}

View File

@@ -1,380 +0,0 @@
/*-------------------------------------------------------------------------*/
/**
@file dictionary.c
@author N. Devillard
@brief Implements a dictionary for string variables.
This module implements a simple dictionary object, i.e. a list
of string/string associations. This object is useful to store e.g.
informations retrieved from a configuration file (ini files).
*/
/*--------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------
Includes
---------------------------------------------------------------------------*/
#include "dictionary.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/** Maximum value size for integers and doubles. */
#define MAXVALSZ 1024
/** Minimal allocated number of entries in a dictionary */
#define DICTMINSZ 128
/** Invalid key token */
#define DICT_INVALID_KEY ((char*)-1)
/*---------------------------------------------------------------------------
Private functions
---------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
/**
@brief Duplicate a string
@param s String to duplicate
@return Pointer to a newly allocated string, to be freed with free()
This is a replacement for strdup(). This implementation is provided
for systems that do not have it.
*/
/*--------------------------------------------------------------------------*/
static char * xstrdup(const char * s)
{
char * t ;
size_t len ;
if (!s)
return NULL ;
len = strlen(s) + 1 ;
t = (char*) malloc(len) ;
if (t) {
memcpy(t, s, len) ;
}
return t ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Double the size of the dictionary
@param d Dictionary to grow
@return This function returns non-zero in case of failure
*/
/*--------------------------------------------------------------------------*/
static int dictionary_grow(dictionary * d)
{
char ** new_val ;
char ** new_key ;
unsigned * new_hash ;
new_val = (char**) calloc(d->size * 2, sizeof *d->val);
new_key = (char**) calloc(d->size * 2, sizeof *d->key);
new_hash = (unsigned*) calloc(d->size * 2, sizeof *d->hash);
if (!new_val || !new_key || !new_hash) {
/* An allocation failed, leave the dictionary unchanged */
if (new_val)
free(new_val);
if (new_key)
free(new_key);
if (new_hash)
free(new_hash);
return -1 ;
}
/* Initialize the newly allocated space */
memcpy(new_val, d->val, d->size * sizeof(char *));
memcpy(new_key, d->key, d->size * sizeof(char *));
memcpy(new_hash, d->hash, d->size * sizeof(unsigned));
/* Delete previous data */
free(d->val);
free(d->key);
free(d->hash);
/* Actually update the dictionary */
d->size *= 2 ;
d->val = new_val;
d->key = new_key;
d->hash = new_hash;
return 0 ;
}
/*---------------------------------------------------------------------------
Function codes
---------------------------------------------------------------------------*/
/*-------------------------------------------------------------------------*/
/**
@brief Compute the hash key for a string.
@param key Character string to use for key.
@return 1 unsigned int on at least 32 bits.
This hash function has been taken from an Article in Dr Dobbs Journal.
This is normally a collision-free function, distributing keys evenly.
The key is stored anyway in the struct so that collision can be avoided
by comparing the key itself in last resort.
*/
/*--------------------------------------------------------------------------*/
unsigned dictionary_hash(const char * key)
{
size_t len ;
unsigned hash ;
size_t i ;
if (!key)
return 0 ;
len = strlen(key);
for (hash=0, i=0 ; i<len ; i++) {
hash += (unsigned)key[i] ;
hash += (hash<<10);
hash ^= (hash>>6) ;
}
hash += (hash <<3);
hash ^= (hash >>11);
hash += (hash <<15);
return hash ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Create a new dictionary object.
@param size Optional initial size of the dictionary.
@return 1 newly allocated dictionary object.
This function allocates a new dictionary object of given size and returns
it. If you do not know in advance (roughly) the number of entries in the
dictionary, give size=0.
*/
/*-------------------------------------------------------------------------*/
dictionary * dictionary_new(size_t size)
{
dictionary * d ;
/* If no size was specified, allocate space for DICTMINSZ */
if (size<DICTMINSZ) size=DICTMINSZ ;
d = (dictionary*) calloc(1, sizeof *d) ;
if (d) {
d->size = size ;
d->val = (char**) calloc(size, sizeof *d->val);
d->key = (char**) calloc(size, sizeof *d->key);
d->hash = (unsigned*) calloc(size, sizeof *d->hash);
}
return d ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Delete a dictionary object
@param d dictionary object to deallocate.
@return void
Deallocate a dictionary object and all memory associated to it.
*/
/*--------------------------------------------------------------------------*/
void dictionary_del(dictionary * d)
{
ssize_t i ;
if (d==NULL) return ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]!=NULL)
free(d->key[i]);
if (d->val[i]!=NULL)
free(d->val[i]);
}
free(d->val);
free(d->key);
free(d->hash);
free(d);
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get a value from a dictionary.
@param d dictionary object to search.
@param key Key to look for in the dictionary.
@param def Default value to return if key not found.
@return 1 pointer to internally allocated character string.
This function locates a key in a dictionary and returns a pointer to its
value, or the passed 'def' pointer if no such key can be found in
dictionary. The returned character pointer points to data internal to the
dictionary object, you should not try to free it or modify it.
*/
/*--------------------------------------------------------------------------*/
const char * dictionary_get(const dictionary * d, const char * key, const char * def)
{
unsigned hash ;
ssize_t i ;
hash = dictionary_hash(key);
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
/* Compare hash */
if (hash==d->hash[i]) {
/* Compare string, to avoid hash collisions */
if (!strcmp(key, d->key[i])) {
return d->val[i] ;
}
}
}
return def ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Set a value in a dictionary.
@param d dictionary object to modify.
@param key Key to modify or add.
@param val Value to add.
@return int 0 if Ok, anything else otherwise
If the given key is found in the dictionary, the associated value is
replaced by the provided one. If the key cannot be found in the
dictionary, it is added to it.
It is Ok to provide a NULL value for val, but NULL values for the dictionary
or the key are considered as errors: the function will return immediately
in such a case.
Notice that if you dictionary_set a variable to NULL, a call to
dictionary_get will return a NULL value: the variable will be found, and
its value (NULL) is returned. In other words, setting the variable
content to NULL is equivalent to deleting the variable from the
dictionary. It is not possible (in this implementation) to have a key in
the dictionary without value.
This function returns non-zero in case of failure.
*/
/*--------------------------------------------------------------------------*/
int dictionary_set(dictionary * d, const char * key, const char * val)
{
ssize_t i ;
unsigned hash ;
if (d==NULL || key==NULL) return -1 ;
/* Compute hash for this key */
hash = dictionary_hash(key) ;
/* Find if value is already in dictionary */
if (d->n>0) {
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (hash==d->hash[i]) { /* Same hash value */
if (!strcmp(key, d->key[i])) { /* Same key */
/* Found a value: modify and return */
if (d->val[i]!=NULL)
free(d->val[i]);
d->val[i] = (val ? xstrdup(val) : NULL);
/* Value has been modified: return */
return 0 ;
}
}
}
}
/* Add a new value */
/* See if dictionary needs to grow */
if (d->n==d->size) {
/* Reached maximum size: reallocate dictionary */
if (dictionary_grow(d) != 0)
return -1;
}
/* Insert key in the first empty slot. Start at d->n and wrap at
d->size. Because d->n < d->size this will necessarily
terminate. */
for (i=d->n ; d->key[i] ; ) {
if(++i == d->size) i = 0;
}
/* Copy key */
d->key[i] = xstrdup(key);
d->val[i] = (val ? xstrdup(val) : NULL) ;
d->hash[i] = hash;
d->n ++ ;
return 0 ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Delete a key in a dictionary
@param d dictionary object to modify.
@param key Key to remove.
@return void
This function deletes a key in a dictionary. Nothing is done if the
key cannot be found.
*/
/*--------------------------------------------------------------------------*/
void dictionary_unset(dictionary * d, const char * key)
{
unsigned hash ;
ssize_t i ;
if (key == NULL || d == NULL) {
return;
}
hash = dictionary_hash(key);
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
/* Compare hash */
if (hash==d->hash[i]) {
/* Compare string, to avoid hash collisions */
if (!strcmp(key, d->key[i])) {
/* Found key */
break ;
}
}
}
if (i>=d->size)
/* Key not found */
return ;
free(d->key[i]);
d->key[i] = NULL ;
if (d->val[i]!=NULL) {
free(d->val[i]);
d->val[i] = NULL ;
}
d->hash[i] = 0 ;
d->n -- ;
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Dump a dictionary to an opened file pointer.
@param d Dictionary to dump
@param f Opened file pointer.
@return void
Dumps a dictionary onto an opened file pointer. Key pairs are printed out
as @c [Key]=[Value], one per line. It is Ok to provide stdout or stderr as
output file pointers.
*/
/*--------------------------------------------------------------------------*/
void dictionary_dump(const dictionary * d, FILE * out)
{
ssize_t i ;
if (d==NULL || out==NULL) return ;
if (d->n<1) {
fprintf(out, "empty dictionary\n");
return ;
}
for (i=0 ; i<d->size ; i++) {
if (d->key[i]) {
fprintf(out, "%20s\t[%s]\n",
d->key[i],
d->val[i] ? d->val[i] : "UNDEF");
}
}
return ;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,836 +0,0 @@
/*-------------------------------------------------------------------------*/
/**
@file iniparser.c
@author N. Devillard
@brief Parser for ini files.
*/
/*--------------------------------------------------------------------------*/
/*---------------------------- Includes ------------------------------------*/
#include <ctype.h>
#include <stdarg.h>
#include "iniparser.h"
/*---------------------------- Defines -------------------------------------*/
#define ASCIILINESZ (1024)
#define INI_INVALID_KEY ((char*)-1)
/*---------------------------------------------------------------------------
Private to this module
---------------------------------------------------------------------------*/
/**
* This enum stores the status for each parsed line (internal use only).
*/
typedef enum _line_status_ {
LINE_UNPROCESSED,
LINE_ERROR,
LINE_EMPTY,
LINE_COMMENT,
LINE_SECTION,
LINE_VALUE
} line_status ;
/*-------------------------------------------------------------------------*/
/**
@brief Convert a string to lowercase.
@param in String to convert.
@param out Output buffer.
@param len Size of the out buffer.
@return ptr to the out buffer or NULL if an error occured.
This function convert a string into lowercase.
At most len - 1 elements of the input string will be converted.
*/
/*--------------------------------------------------------------------------*/
static const char * strlwc(const char * in, char *out, unsigned len)
{
unsigned i ;
if (in==NULL || out == NULL || len==0) return NULL ;
i=0 ;
while (in[i] != '\0' && i < len-1) {
out[i] = (char)tolower((int)in[i]);
i++ ;
}
out[i] = '\0';
return out ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Duplicate a string
@param s String to duplicate
@return Pointer to a newly allocated string, to be freed with free()
This is a replacement for strdup(). This implementation is provided
for systems that do not have it.
*/
/*--------------------------------------------------------------------------*/
static char * xstrdup(const char * s)
{
char * t ;
size_t len ;
if (!s)
return NULL ;
len = strlen(s) + 1 ;
t = (char*) malloc(len) ;
if (t) {
memcpy(t, s, len) ;
}
return t ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Remove blanks at the beginning and the end of a string.
@param str String to parse and alter.
@return unsigned New size of the string.
*/
/*--------------------------------------------------------------------------*/
static unsigned strstrip(char * s)
{
char *last = NULL ;
char *dest = s;
if (s==NULL) return 0;
last = s + strlen(s);
while (isspace((int)*s) && *s) s++;
while (last > s) {
if (!isspace((int)*(last-1)))
break ;
last -- ;
}
*last = (char)0;
memmove(dest,s,last - s + 1);
return last - s;
}
/*-------------------------------------------------------------------------*/
/**
@brief Default error callback for iniparser: wraps `fprintf(stderr, ...)`.
*/
/*--------------------------------------------------------------------------*/
static int default_error_callback(const char *format, ...)
{
int ret;
va_list argptr;
va_start(argptr, format);
ret = vfprintf(stderr, format, argptr);
va_end(argptr);
return ret;
}
static int (*iniparser_error_callback)(const char*, ...) = default_error_callback;
/*-------------------------------------------------------------------------*/
/**
@brief Configure a function to receive the error messages.
@param errback Function to call.
By default, the error will be printed on stderr. If a null pointer is passed
as errback the error callback will be switched back to default.
*/
/*--------------------------------------------------------------------------*/
void iniparser_set_error_callback(int (*errback)(const char *, ...))
{
if (errback) {
iniparser_error_callback = errback;
} else {
iniparser_error_callback = default_error_callback;
}
}
/*-------------------------------------------------------------------------*/
/**
@brief Get number of sections in a dictionary
@param d Dictionary to examine
@return int Number of sections found in dictionary
This function returns the number of sections found in a dictionary.
The test to recognize sections is done on the string stored in the
dictionary: a section name is given as "section" whereas a key is
stored as "section:key", thus the test looks for entries that do not
contain a colon.
This clearly fails in the case a section name contains a colon, but
this should simply be avoided.
This function returns -1 in case of error.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getnsec(const dictionary * d)
{
int i ;
int nsec ;
if (d==NULL) return -1 ;
nsec=0 ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (strchr(d->key[i], ':')==NULL) {
nsec ++ ;
}
}
return nsec ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get name for section n in a dictionary.
@param d Dictionary to examine
@param n Section number (from 0 to nsec-1).
@return Pointer to char string
This function locates the n-th section in a dictionary and returns
its name as a pointer to a string statically allocated inside the
dictionary. Do not free or modify the returned string!
This function returns NULL in case of error.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getsecname(const dictionary * d, int n)
{
int i ;
int foundsec ;
if (d==NULL || n<0) return NULL ;
foundsec=0 ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (strchr(d->key[i], ':')==NULL) {
foundsec++ ;
if (foundsec>n)
break ;
}
}
if (foundsec<=n) {
return NULL ;
}
return d->key[i] ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Dump a dictionary to an opened file pointer.
@param d Dictionary to dump.
@param f Opened file pointer to dump to.
@return void
This function prints out the contents of a dictionary, one element by
line, onto the provided file pointer. It is OK to specify @c stderr
or @c stdout as output files. This function is meant for debugging
purposes mostly.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump(const dictionary * d, FILE * f)
{
int i ;
if (d==NULL || f==NULL) return ;
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
if (d->val[i]!=NULL) {
fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]);
} else {
fprintf(f, "[%s]=UNDEF\n", d->key[i]);
}
}
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary to a loadable ini file
@param d Dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given dictionary into a loadable ini file.
It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dump_ini(const dictionary * d, FILE * f)
{
int i ;
int nsec ;
const char * secname ;
if (d==NULL || f==NULL) return ;
nsec = iniparser_getnsec(d);
if (nsec<1) {
/* No section in file: dump all keys as they are */
for (i=0 ; i<d->size ; i++) {
if (d->key[i]==NULL)
continue ;
fprintf(f, "%s = %s\n", d->key[i], d->val[i]);
}
return ;
}
for (i=0 ; i<nsec ; i++) {
secname = iniparser_getsecname(d, i) ;
iniparser_dumpsection_ini(d, secname, f);
}
fprintf(f, "\n");
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Save a dictionary section to a loadable ini file
@param d Dictionary to dump
@param s Section name of dictionary to dump
@param f Opened file pointer to dump to
@return void
This function dumps a given section of a given dictionary into a loadable ini
file. It is Ok to specify @c stderr or @c stdout as output files.
*/
/*--------------------------------------------------------------------------*/
void iniparser_dumpsection_ini(const dictionary * d, const char * s, FILE * f)
{
int j ;
char keym[ASCIILINESZ+1];
int seclen ;
if (d==NULL || f==NULL) return ;
if (! iniparser_find_entry(d, s)) return ;
seclen = (int)strlen(s);
fprintf(f, "\n[%s]\n", s);
sprintf(keym, "%s:", s);
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1)) {
fprintf(f,
"%-30s = %s\n",
d->key[j]+seclen+1,
d->val[j] ? d->val[j] : "");
}
}
fprintf(f, "\n");
return ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@return Number of keys in section
*/
/*--------------------------------------------------------------------------*/
int iniparser_getsecnkeys(const dictionary * d, const char * s)
{
int seclen, nkeys ;
char keym[ASCIILINESZ+1];
int j ;
nkeys = 0;
if (d==NULL) return nkeys;
if (! iniparser_find_entry(d, s)) return nkeys;
seclen = (int)strlen(s);
strlwc(s, keym, sizeof(keym));
keym[seclen] = ':';
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1))
nkeys++;
}
return nkeys;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the number of keys in a section of a dictionary.
@param d Dictionary to examine
@param s Section name of dictionary to examine
@param keys Already allocated array to store the keys in
@return The pointer passed as `keys` argument or NULL in case of error
This function queries a dictionary and finds all keys in a given section.
The keys argument should be an array of pointers which size has been
determined by calling `iniparser_getsecnkeys` function prior to this one.
Each pointer in the returned char pointer-to-pointer is pointing to
a string allocated in the dictionary; do not free or modify them.
*/
/*--------------------------------------------------------------------------*/
const char ** iniparser_getseckeys(const dictionary * d, const char * s, const char ** keys)
{
int i, j, seclen ;
char keym[ASCIILINESZ+1];
if (d==NULL || keys==NULL) return NULL;
if (! iniparser_find_entry(d, s)) return NULL;
seclen = (int)strlen(s);
strlwc(s, keym, sizeof(keym));
keym[seclen] = ':';
i = 0;
for (j=0 ; j<d->size ; j++) {
if (d->key[j]==NULL)
continue ;
if (!strncmp(d->key[j], keym, seclen+1)) {
keys[i] = d->key[j];
i++;
}
}
return keys;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key
@param d Dictionary to search
@param key Key string to look for
@param def Default value to return if key not found.
@return pointer to statically allocated character string
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the pointer passed as 'def' is returned.
The returned char pointer is pointing to a string allocated in
the dictionary, do not free or modify it.
*/
/*--------------------------------------------------------------------------*/
const char * iniparser_getstring(const dictionary * d, const char * key, const char * def)
{
const char * lc_key ;
const char * sval ;
char tmp_str[ASCIILINESZ+1];
if (d==NULL || key==NULL)
return def ;
lc_key = strlwc(key, tmp_str, sizeof(tmp_str));
sval = dictionary_get(d, lc_key, def);
return sval ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to an long int
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return long integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
Supported values for integers include the usual C notation
so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
are supported. Examples:
"42" -> 42
"042" -> 34 (octal -> decimal)
"0x42" -> 66 (hexa -> decimal)
Warning: the conversion may overflow in various ways. Conversion is
totally outsourced to strtol(), see the associated man page for overflow
handling.
Credits: Thanks to A. Becker for suggesting strtol()
*/
/*--------------------------------------------------------------------------*/
long int iniparser_getlongint(const dictionary * d, const char * key, long int notfound)
{
const char * str ;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
if (str==INI_INVALID_KEY) return notfound ;
return strtol(str, NULL, 0);
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to an int
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
Supported values for integers include the usual C notation
so decimal, octal (starting with 0) and hexadecimal (starting with 0x)
are supported. Examples:
"42" -> 42
"042" -> 34 (octal -> decimal)
"0x42" -> 66 (hexa -> decimal)
Warning: the conversion may overflow in various ways. Conversion is
totally outsourced to strtol(), see the associated man page for overflow
handling.
Credits: Thanks to A. Becker for suggesting strtol()
*/
/*--------------------------------------------------------------------------*/
int iniparser_getint(const dictionary * d, const char * key, int notfound)
{
return (int)iniparser_getlongint(d, key, notfound);
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a double
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return double
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
*/
/*--------------------------------------------------------------------------*/
double iniparser_getdouble(const dictionary * d, const char * key, double notfound)
{
const char * str ;
str = iniparser_getstring(d, key, INI_INVALID_KEY);
if (str==INI_INVALID_KEY) return notfound ;
return atof(str);
}
/*-------------------------------------------------------------------------*/
/**
@brief Get the string associated to a key, convert to a boolean
@param d Dictionary to search
@param key Key string to look for
@param notfound Value to return in case of error
@return integer
This function queries a dictionary for a key. A key as read from an
ini file is given as "section:key". If the key cannot be found,
the notfound value is returned.
A true boolean is found if one of the following is matched:
- A string starting with 'y'
- A string starting with 'Y'
- A string starting with 't'
- A string starting with 'T'
- A string starting with '1'
A false boolean is found if one of the following is matched:
- A string starting with 'n'
- A string starting with 'N'
- A string starting with 'f'
- A string starting with 'F'
- A string starting with '0'
The notfound value returned if no boolean is identified, does not
necessarily have to be 0 or 1.
*/
/*--------------------------------------------------------------------------*/
int iniparser_getboolean(const dictionary * d, const char * key, int notfound)
{
int ret ;
const char * c ;
c = iniparser_getstring(d, key, INI_INVALID_KEY);
if (c==INI_INVALID_KEY) return notfound ;
if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') {
ret = 1 ;
} else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') {
ret = 0 ;
} else {
ret = notfound ;
}
return ret;
}
/*-------------------------------------------------------------------------*/
/**
@brief Finds out if a given entry exists in a dictionary
@param ini Dictionary to search
@param entry Name of the entry to look for
@return integer 1 if entry exists, 0 otherwise
Finds out if a given entry exists in the dictionary. Since sections
are stored as keys with NULL associated values, this is the only way
of querying for the presence of sections in a dictionary.
*/
/*--------------------------------------------------------------------------*/
int iniparser_find_entry(const dictionary * ini, const char * entry)
{
int found=0 ;
if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) {
found = 1 ;
}
return found ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Set an entry in a dictionary.
@param ini Dictionary to modify.
@param entry Entry to modify (entry name)
@param val New value to associate to the entry.
@return int 0 if Ok, -1 otherwise.
If the given entry can be found in the dictionary, it is modified to
contain the provided value. If it cannot be found, the entry is created.
It is Ok to set val to NULL.
*/
/*--------------------------------------------------------------------------*/
int iniparser_set(dictionary * ini, const char * entry, const char * val)
{
char tmp_str[ASCIILINESZ+1];
return dictionary_set(ini, strlwc(entry, tmp_str, sizeof(tmp_str)), val) ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Delete an entry in a dictionary
@param ini Dictionary to modify
@param entry Entry to delete (entry name)
@return void
If the given entry can be found, it is deleted from the dictionary.
*/
/*--------------------------------------------------------------------------*/
void iniparser_unset(dictionary * ini, const char * entry)
{
char tmp_str[ASCIILINESZ+1];
dictionary_unset(ini, strlwc(entry, tmp_str, sizeof(tmp_str)));
}
/*-------------------------------------------------------------------------*/
/**
@brief Load a single line from an INI file
@param input_line Input line, may be concatenated multi-line input
@param section Output space to store section
@param key Output space to store key
@param value Output space to store value
@return line_status value
*/
/*--------------------------------------------------------------------------*/
static line_status iniparser_line(
const char * input_line,
char * section,
char * key,
char * value)
{
line_status sta ;
char * line = NULL;
size_t len ;
line = xstrdup(input_line);
len = strstrip(line);
sta = LINE_UNPROCESSED ;
if (len<1) {
/* Empty line */
sta = LINE_EMPTY ;
} else if (line[0]=='#' || line[0]==';') {
/* Comment line */
sta = LINE_COMMENT ;
} else if (line[0]=='[' && line[len-1]==']') {
/* Section name */
sscanf(line, "[%[^]]", section);
strstrip(section);
strlwc(section, section, len);
sta = LINE_SECTION ;
} else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2
|| sscanf (line, "%[^=] = '%[^\']'", key, value) == 2) {
/* Usual key=value with quotes, with or without comments */
strstrip(key);
strlwc(key, key, len);
/* Don't strip spaces from values surrounded with quotes */
sta = LINE_VALUE ;
} else if (sscanf (line, "%[^=] = %[^;#]", key, value) == 2) {
/* Usual key=value without quotes, with or without comments */
strstrip(key);
strlwc(key, key, len);
strstrip(value);
/*
* sscanf cannot handle '' or "" as empty values
* this is done here
*/
if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) {
value[0]=0 ;
}
sta = LINE_VALUE ;
} else if (sscanf(line, "%[^=] = %[;#]", key, value)==2
|| sscanf(line, "%[^=] %[=]", key, value) == 2) {
/*
* Special cases:
* key=
* key=;
* key=#
*/
strstrip(key);
strlwc(key, key, len);
value[0]=0 ;
sta = LINE_VALUE ;
} else {
/* Generate syntax error */
sta = LINE_ERROR ;
}
free(line);
return sta ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Parse an ini file and return an allocated dictionary object
@param ininame Name of the ini file to read.
@return Pointer to newly allocated dictionary
This is the parser for ini files. This function is called, providing
the name of the file to be read. It returns a dictionary object that
should not be accessed directly, but through accessor functions
instead.
The returned dictionary must be freed using iniparser_freedict().
*/
/*--------------------------------------------------------------------------*/
dictionary * iniparser_load(const char * ininame)
{
FILE * in ;
char line [ASCIILINESZ+1] ;
char section [ASCIILINESZ+1] ;
char key [ASCIILINESZ+1] ;
char tmp [(ASCIILINESZ * 2) + 2] ;
char val [ASCIILINESZ+1] ;
int last=0 ;
int len ;
int lineno=0 ;
int errs=0;
int mem_err=0;
dictionary * dict ;
if ((in=fopen(ininame, "r"))==NULL) {
iniparser_error_callback("iniparser: cannot open %s\n", ininame);
return NULL ;
}
dict = dictionary_new(0) ;
if (!dict) {
fclose(in);
return NULL ;
}
memset(line, 0, ASCIILINESZ);
memset(section, 0, ASCIILINESZ);
memset(key, 0, ASCIILINESZ);
memset(val, 0, ASCIILINESZ);
last=0 ;
while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) {
lineno++ ;
len = (int)strlen(line)-1;
if (len<=0)
continue;
/* Safety check against buffer overflows */
if (line[len]!='\n' && !feof(in)) {
iniparser_error_callback(
"iniparser: input line too long in %s (%d)\n",
ininame,
lineno);
dictionary_del(dict);
fclose(in);
return NULL ;
}
/* Get rid of \n and spaces at end of line */
while ((len>=0) &&
((line[len]=='\n') || (isspace(line[len])))) {
line[len]=0 ;
len-- ;
}
if (len < 0) { /* Line was entirely \n and/or spaces */
len = 0;
}
/* Detect multi-line */
if (line[len]=='\\') {
/* Multi-line value */
last=len ;
continue ;
} else {
last=0 ;
}
switch (iniparser_line(line, section, key, val)) {
case LINE_EMPTY:
case LINE_COMMENT:
break ;
case LINE_SECTION:
mem_err = dictionary_set(dict, section, NULL);
break ;
case LINE_VALUE:
sprintf(tmp, "%s:%s", section, key);
mem_err = dictionary_set(dict, tmp, val);
break ;
case LINE_ERROR:
iniparser_error_callback(
"iniparser: syntax error in %s (%d):\n-> %s\n",
ininame,
lineno,
line);
errs++ ;
break;
default:
break ;
}
memset(line, 0, ASCIILINESZ);
last=0;
if (mem_err<0) {
iniparser_error_callback("iniparser: memory allocation failure\n");
break ;
}
}
if (errs) {
dictionary_del(dict);
dict = NULL ;
}
fclose(in);
return dict ;
}
/*-------------------------------------------------------------------------*/
/**
@brief Free all memory associated to an ini dictionary
@param d Dictionary to free
@return void
Free all memory associated to an ini dictionary.
It is mandatory to call this function before the dictionary object
gets out of the current context.
*/
/*--------------------------------------------------------------------------*/
void iniparser_freedict(dictionary * d)
{
dictionary_del(d);
}

View File

@@ -1,10 +0,0 @@
#include "../include/MoonrakerAPI.h"
#include "../include/mks_error.h"
#include "../include/event.h"
void parse_error(nlohmann::json error) {
std::cout << error << std::endl;
}

View File

@@ -1,471 +0,0 @@
#include <iostream>
#include <stack>
#include <set>
#include <fstream>
#include <string>
#include <sstream>
#include "../include/send_msg.h"
#include "../include/mks_file.h"
#include "../include/KlippyRest.h"
#include "../include/event.h"
#include "../include/ui.h"
#include "../include/mks_preview.h"
// List available files
// Get gcode metadata
std::string file_filename; // 文件名
std::string file_current_filename; // 当前文件名
std::string file_previous_filename; // 先前文件名
float file_filament_total; // 用料
float file_estimated_time; // 文件预估时间
// Directory
std::stack<std::string> file_path_stack; // 路径栈
std::string file_root_path; // Gcodes根目录
std::string file_previous_path; // 之前的路径
std::string file_current_path; // 文件当前所在的路径
std::string file_print_path; // 要打印的文件路径
// 文件管理
std::set<std::string> server_files_list; // gcodes文件列表
std::set<std::string> server_files_get_directroy; // 路径下面的目录列表
std::set<std::string> newfiles;
std::set<std::string> deletedfiles;
std::set<std::string> updatedfiles;
// 解析文件内容相关
std::set<std::string> page_files_dirname_list;
std::set<std::string> page_files_filename_list;
std::set<std::string> page_files_dirname_filename_list;
std::string page_files_last_printing_files_dir;
bool page_files_is_last_print_files_dir;
// 文件列表相关处理变量
bool filelist_changed = false;
int page_files_pages;
int page_files_current_pages;
int page_files_folder_layers;
std::string page_files_list_name[9] = {"", "", "", "", "", "", "", "", ""}; // 文件列表显示文件名称
std::string page_files_list_show_name[9] = {"", "", "", "", "", "", "", "", ""}; // 文件列表名称
std::string page_files_list_show_type[9] = {"[n]", "[n]", "[n]", "[n]", "[n]", "[n]", "[n]", "[n]", "[n]"}; // 文件类型: [f]或者[d],或者[n]
bool page_files_refresh_status = false;
std::stack<std::string> page_files_path_stack; // 路径栈
std::string page_files_root_path; // Klippy根目录
std::string page_files_previous_path; // 之前的路径
std::string page_files_path; // 文件所在路径
std::string page_files_print_files_path; // 要打印的文件路径
int file_metadata_estimated_time = 0;
std::string file_metadata_filename;
float file_metadata_filament_total = 0.0;
int file_metadata_object_height = 0;
std::string file_metadata_filament_name;
std::string file_metadata_filament_type;
float file_metadata_filament_weight_total = 0.0;
std::string file_metadata_gimage;
std::string file_metadata_simage;
bool mks_file_parse_finished = false;
extern bool show_preview_complete;
extern int current_page_id;
//4.4.2 CLL 文件列表页面新增本地、U盘按钮
extern std::string file_mode;
extern bool jump_to_print;
std::string thumbnail_relative_path;
std::string thumbnail_path;
bool cache_clicked = false;
void parse_file_estimated_time(nlohmann::json response) {
if (response["result"]["estimated_time"] != nlohmann::detail::value_t::null) {
file_metadata_estimated_time = (float)response["result"]["estimated_time"];
}
if (response["result"]["filename"] != nlohmann::detail::value_t::null) {
file_metadata_filename = response["result"]["filename"];
}
if (response["result"]["filament_total"] != nlohmann::detail::value_t::null) {
file_metadata_filament_total = (int)response["result"]["filament_total"];
MKSLOG_RED("用料长度%f", file_metadata_filament_total);
}
if (response["result"]["object_height"] != nlohmann::detail::value_t::null) {
file_metadata_object_height = (int)response["result"]["object_height"];
}
if (response["result"]["filament_name"] != nlohmann::detail::value_t::null) {
file_metadata_filament_name = response["result"]["filament_name"];
}
if (response["result"]["filament_type"] != nlohmann::detail::value_t::null) {
file_metadata_filament_type = response["result"]["filament_type"];
}
if (response["result"]["filament_weight_total"] != nlohmann::detail::value_t::null) {
file_metadata_filament_weight_total = response["result"]["filament_weight_total"];
}
if (response["result"]["gimage"] != nlohmann::detail::value_t::null) {
file_metadata_gimage = response["result"]["gimage"];
}
if (response["result"]["simage"] != nlohmann::detail::value_t::null) {
file_metadata_simage = response["result"]["simage"];
}
if (response["result"]["thumbnails"] != nlohmann::detail::value_t::null) {
for (int i = 0; response["result"]["thumbnails"][i] != nlohmann::detail::value_t::null; i++) {
if (response["result"]["thumbnails"][i]["width"] == 168|| response["result"]["thumbnails"][i]["width"] == 300) {
thumbnail_relative_path = response["result"]["thumbnails"][i]["relative_path"];
if (getParentDirectory(file_metadata_filename) == "") {
thumbnail_path = thumbnail_relative_path;
} else {
thumbnail_path = getParentDirectory(file_metadata_filename) + "/" + thumbnail_relative_path;
}
MKSLOG_RED("图片路径%s", thumbnail_path.c_str());
break;
}
if (response["result"]["thumbnails"][i] == nlohmann::detail::value_t::null) {
thumbnail_relative_path.clear();
thumbnail_path.clear();
}
}
}
mks_file_parse_finished = true;
}
void parse_server_files_list(nlohmann::json result) {
server_files_list.clear();
std::string path_temp = "";
for (int i = 0; i < result.size(); i++) {
path_temp = result[i]["path"];
server_files_list.insert(path_temp);
}
}
void parse_server_files_get_directory(nlohmann::json result) {
server_files_get_directroy.clear();
server_files_list.clear();
std::string dirname_temp = "";
std::string filename_temp = "";
for (int i = 0; i < result["dirs"].size(); i++) {
std::cout << result["dirs"][i]["dirname"] << std::endl;
dirname_temp = result["dirs"][i]["dirname"];
server_files_list.insert(filename_temp);
}
for (int j = 0; j < result["files"].size(); j++) {
std::cout << result["files"][j]["filename"] << std::endl;
filename_temp = result["files"][j]["filename"];
server_files_list.insert(filename_temp);
}
}
void parse_server_files_metadata(nlohmann::json result) {
}
void parse_create_directory(nlohmann::json result) {
std::cout << "path: " << result["item"]["path"] << std::endl;
std::cout << "root: " << result["item"]["root"] << std::endl;
std::cout << "action: " << result["action"] << std::endl;
}
void parse_delete_directory(nlohmann::json result) {
std::cout << "path: " << result["item"]["path"] << std::endl;
std::cout << "root: " << result["item"]["root"] << std::endl;
}
void parse_move_a_file_or_directory(nlohmann::json result) {
std::cout << "item: " << result["item"] << std::endl;
std::cout << "source_item" << result["source_item"] << std::endl;
std::cout << "action: " << result["action"] << std::endl;
}
void parse_copy_a_file_or_directory(nlohmann::json result) {
std::cout << "root: " << result["item"]["root"] << std::endl;
std::cout << "path: " << result["item"]["path"] << std::endl;
std::cout << "action: " << result["action"] << std::endl;
}
void parse_file_delete(nlohmann::json result) {
std::cout << "path: " << result["item"]["path"] << std::endl;
std::cout << "root: " << result["item"]["root"] << std::endl;
std::cout << "action: " << result["action"] << std::endl;
}
// 获取文件列表信息
void get_page_files_filelist(std::string current_dir) {
if (page_files_last_printing_files_dir == current_dir) {
page_files_is_last_print_files_dir = true;
} else {
page_files_is_last_print_files_dir = false;
}
page_files_dirname_list.clear();
page_files_filename_list.clear();
page_files_dirname_filename_list.clear();
nlohmann::json json_temp;
nlohmann::json result;
//4.4.2 CLL 新增在文件首页第一个显示打印过文件
std::string temp_dirname = "";
std::string temp_filename = "";
std::string json_files_directory = send_request("localhost", "7125", "server/files/directory?path=gcodes//.cache", "GET");
if (json_files_directory != "" && page_files_folder_layers == 0) {
json_temp = nlohmann::json::parse(json_files_directory);
result = json_temp["result"];
if (0 < result["files"].size()) {
std::cout << result["files"][0]["filename"] << std::endl;
temp_filename = result["files"][0]["filename"];
if (temp_filename.find(".gcode") != -1) {
if (temp_filename.find(".") != 0) {
page_files_filename_list.insert(temp_filename);
auto it = page_files_filename_list.begin();
page_files_dirname_filename_list.insert("[c] " + *it);
page_files_filename_list.clear();
}
}
}
}
json_files_directory = send_request("localhost", "7125", "server/files/directory?path=" + current_dir, "GET");
if (json_files_directory != "") {
json_temp = nlohmann::json::parse(json_files_directory);
result = json_temp["result"];
}
for (int i = 0; i < result["dirs"].size(); i++) {
temp_dirname = result["dirs"][i]["dirname"];
if (temp_dirname != "System Volume Information" && temp_dirname.find(".") != 0 && temp_dirname != "sda1") {
page_files_dirname_list.insert(temp_dirname);
}
}
for (int j = 0; j < result["files"].size(); j++) {
std::cout << result["files"][j]["filename"] << std::endl;
temp_filename = result["files"][j]["filename"];
if (temp_filename.find(".gcode") != -1) {
if (temp_filename.find(".") != 0) {
page_files_filename_list.insert(temp_filename);
}
}
}
for (auto it = page_files_dirname_list.begin(); it != page_files_dirname_list.end(); it++) {
page_files_dirname_filename_list.insert("[d] " + *it);
}
for (auto it = page_files_filename_list.begin(); it != page_files_filename_list.end(); it++) {
page_files_dirname_filename_list.insert("[f] " + *it);
}
if (0 == page_files_dirname_filename_list.size() % 4) { // CLL 此函数后的除数为一页所包含的文件数
page_files_pages = page_files_dirname_filename_list.size() / 4 - 1;
if (page_files_pages <= 0) {
page_files_pages = 0;
}
} else {
page_files_pages = page_files_dirname_filename_list.size() / 4;
}
}
void set_page_files_show_list(int pages) {
page_files_list_name[0] = "";
page_files_list_name[1] = "";
page_files_list_name[2] = "";
page_files_list_name[3] = "";
auto it = page_files_dirname_filename_list.begin();
for (int i = 0; i < pages * 4; i++) {
it++;
std::cout << *it << std::endl;
}
for (int i = 0; i < 4; i++) {
if (it != page_files_dirname_filename_list.end()) {
page_files_list_name[i] = *it;
it++;
}
}
// 打印测试
for (int j = 0; j < 4; j++) {
if (page_files_list_name[j] != "") {
page_files_list_show_type[j] = page_files_list_name[j].substr(0, 3);
page_files_list_show_name[j] = page_files_list_name[j].substr(4);
} else {
page_files_list_show_type[j] = "[n]";
page_files_list_show_name[j] = "";
}
}
}
void get_sub_dir_files_list(int button) {
//4.4.2 CLL 在文件列表界面第一页显示打印过文件
if ("[c]" == page_files_list_show_type[button]) {
jump_to_print = false;
show_preview_complete = false;
cache_clicked = true;
page_files_path_stack.push(page_files_path);
page_files_print_files_path = page_files_path + "/.cache/" + page_files_list_show_name[button];
page_files_folder_layers++;
get_file_estimated_time(page_files_print_files_path.substr(1));
page_to(TJC_PAGE_PREVIEW);
} else if ("[d]" == page_files_list_show_type[button]) {
page_files_path_stack.push(page_files_path);
page_files_path = page_files_path + "/" + page_files_list_show_name[button];
page_files_folder_layers++;
page_to(TJC_PAGE_FILE_LIST);
page_files_current_pages = 0;
refresh_page_files(page_files_current_pages);
refresh_page_files_list();
} else if ("[f]" == page_files_list_show_type[button]) {
jump_to_print = false;
show_preview_complete = false;
cache_clicked = false;
page_files_path_stack.push(page_files_path);
page_files_print_files_path = page_files_path + "/" + page_files_list_show_name[button];
page_files_folder_layers++;
MKSLOG("%s", page_files_print_files_path.substr(1).c_str());
get_file_estimated_time(page_files_print_files_path.substr(1));
page_to(TJC_PAGE_PREVIEW);
}
}
void get_parenet_dir_files_list() {
page_files_previous_path = page_files_path_stack.top();
page_files_path = page_files_previous_path;
if (current_page_id != TJC_PAGE_PREVIEW) {
page_files_current_pages = 0;
}
//4.4.2 CLL 文件列表页面新增本地、U盘切换按钮
if (detect_disk() == -1 && file_mode == "USB") {
page_to(TJC_PAGE_FILE_LIST);
page_files_pages = 0;
page_files_current_pages = 0;
page_files_folder_layers = 1;
page_files_previous_path = "";
page_files_root_path = "gcodes/";
page_files_path = "/sda1";
refresh_page_files(page_files_current_pages);
refresh_page_files_list();
get_object_status();
} else if (page_files_folder_layers > 0) {
page_to(TJC_PAGE_FILE_LIST);
page_files_folder_layers--;
if (page_files_folder_layers == 0) {
refresh_page_files(page_files_current_pages);
refresh_page_files_list();
page_files_previous_path = "";
page_files_path = "";
} else {
refresh_page_files(page_files_current_pages);
refresh_page_files_list();
page_files_path_stack.pop();
}
}
}
void parse_file_estimated_time_send(nlohmann::json response) {
if (response["estimated_time"] != nlohmann::detail::value_t::null) {
file_metadata_estimated_time = (float)response["estimated_time"];
}
if (response["filename"] != nlohmann::detail::value_t::null) {
file_metadata_filename = response["filename"];
}
if (response["filament_total"] != nlohmann::detail::value_t::null) {
file_metadata_filament_total = (int)response["filament_total"];
MKSLOG_RED("用料长度%f", file_metadata_filament_total);
}
if (response["object_height"] != nlohmann::detail::value_t::null) {
file_metadata_object_height = (int)response["object_height"];
}
if (response["filament_name"] != nlohmann::detail::value_t::null) {
file_metadata_filament_name = response["filament_name"];
}
if (response["filament_type"] != nlohmann::detail::value_t::null) {
file_metadata_filament_type = response["filament_type"];
}
if (response["filament_weight_total"] != nlohmann::detail::value_t::null) {
file_metadata_filament_weight_total = response["filament_weight_total"];
}
if (response["gimage"] != nlohmann::detail::value_t::null) {
file_metadata_gimage = response["gimage"];
MKSLOG_RED("gimage");
}
if (response["simage"] != nlohmann::detail::value_t::null) {
file_metadata_simage = response["simage"];
MKSLOG_RED("simage");
}
if (response["result"]["thumbnails"] != nlohmann::detail::value_t::null) {
if (response["result"]["thumbnails"].back() != nlohmann::detail::value_t::null) {
thumbnail_relative_path = response["result"]["thumbnails"].back()["relative_path"];
if (getParentDirectory(file_metadata_filename) == "") {
thumbnail_path = thumbnail_relative_path;
} else {
thumbnail_path = getParentDirectory(file_metadata_filename) + "/" + thumbnail_relative_path;
}
MKSLOG_RED("图片路径%s", thumbnail_path.c_str());
}
} else {
thumbnail_relative_path.clear();
thumbnail_path.clear();
}
mks_file_parse_finished = true;
}
std::string getParentDirectory(const std::string& path) {
size_t found = path.find_last_of("/\\");
if (found != std::string::npos) {
return path.substr(0, found);
} else {
return ""; // 如果没有找到分隔符,说明是根目录,返回空字符串或根据需求返回当前目录 "."
}
}
int output_imgdata(std::string thumbpath, int size) {
std::string path;
if (size != 176) {
path = "/home/mks/gcode_files/" + thumbpath;
} else {
path = thumbpath;
}
// std::string path = "/home/mks/printer_data/gcodes/" + thumbpath;
std::string temp= "python3 /home/mks/gene4.py \"" + path + "\" /home/mks/tjc " + std::to_string(size);
std::cout << temp << std::endl;
const char* command = temp.c_str();
system(command);
return 0;
}
int output_jpg(std::string thumbpath, int size) {
std::string path = "/home/mks/gcode_files/" + thumbpath;
std::string path2 = path + ".jpg";
// std::string temp= "python3 /home/mks/gene5.py \"" + path + "\" /home/mks/tjc.jpg " + std::to_string(size);
std::string temp= "python3 /home/mks/gene5.py \"" + path + "\" \"" + path2 +"\" " + std::to_string(size);
std::cout << temp << std::endl;
const char* command = temp.c_str();
if (access(path2.c_str(), F_OK) == -1) {
system(command);
}
return 0;
}
// 自定义函数来提取文件名
std::string extractFileName(const std::string& filePath) {
size_t lastSlash = filePath.find_last_of("/\\"); // 找到最后一个路径分隔符的位置
if (lastSlash != std::string::npos) {
return filePath.substr(lastSlash + 1); // 提取文件名部分
}
return filePath; // 如果没有路径分隔符,则返回整个路径
}

View File

@@ -1,238 +0,0 @@
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <regex>
#include "../include/MakerbaseCommand.h"
#include "../include/MoonrakerAPI.h"
#include "../include/mks_log.h"
#include "../include/mks_gcode.h"
#include "../include/event.h"
#include "../include/ui.h"
#include "../include/mks_file.h"
extern std::string str_manual_level_offset;
extern std::string printer_webhooks_state;
extern std::string printer_webhooks_state_message;
/* 共振补偿值 */
extern std::string page_syntony_shaper_freq_x;
extern std::string page_syntony_shaper_freq_y;
extern bool all_level_saving;
std::string filament_message;
//4.4.2 CLL 修改调平无需手动设置zoffset
extern bool step_1;
extern bool step_2;
extern bool step_3;
extern bool step_4;
//4.4.2 CLL 新增息屏功能
extern int current_page_id;
extern int previous_page_id;
extern bool previous_caselight_value;
extern std::string printer_idle_timeout_state;
// extern std::string mks_babystep_value; // 获取调平补偿值后保存babystep
//4.4.3 CLL 修改网页打印信息订阅
nlohmann::json output_metadata;
extern bool jump_to_print;
extern bool jump_to_memory_warning;
extern std::string printer_print_stats_state;
extern std::string error_message;
extern bool jump_to_resume_print;
void parse_gcode_response(nlohmann::json params) {
std::cout << params << std::endl;
if (params != nlohmann::detail::value_t::null) {
std::string params0 = params[0];
//4.4.2 CLL 新增息屏功能
if (current_page_id == TJC_PAGE_SCREEN_SLEEP) { // SCREEN_SLEEP中没有刷新函数跳转不会出现冲突
page_to(previous_page_id);
if (previous_caselight_value == true) {
led_on_off();
previous_caselight_value = false;
}
}
// std::cout << params0.substr(0, 23) << std::endl;
// bltouch: z_offset: 1.000
if (params0 == "// Klipper state: Ready") {
printer_idle_timeout_state = "Ready";
MKSLOG("重启Klipper已准备就绪发送订阅内容");
printer_webhooks_state = "ready";
printer_webhooks_state_message = "Klipper state: Ready";
// if (all_level_saving == false) {
sleep(5);
sub_object_status();
sleep(2);
get_object_status();
// printer_set_babystep();
// sleep(1);
init_mks_status(); // 重启后初始化之前保存的参数
if (all_level_saving == false) {
all_level_saving = true;
}
// printer_webhooks_state_message = "Klipper state: Ready";
MKSLOG_YELLOW("重启之后打印下 %s", printer_webhooks_state.c_str());
} else if (params0 == "// Klipper state: Disconnect") {
sub_object_status();
// sleep(2);
// get_object_status();
// Klipper state: Disconnect
} else if (params0.substr(0, 19) == "// PID parameters: ") {
MKSLOG_RED("// PID parameters: ");
std::string str{"(\\d+\\.\\d+)"}; // 匹配小数
std::smatch matchResult;
std::regex re(str);
if (std::regex_match(params0, matchResult, re)) {
std::cout << "pid_Kp == " << matchResult[0] << std::endl;
std::cout << "pid_Ki == " << matchResult[1] << std::endl;
std::cout << "pid_Kd == " << matchResult[2] << std::endl;
}
// 匹配到的pid转化为字符串尝试一下
std::cout << (std::string)matchResult[0] << std::endl;
std::cout << (std::string)matchResult[1] << std::endl;
std::cout << (std::string)matchResult[2] << std::endl;
std::cout << "成功获得PID的数值" << std::endl;
} else if (params0.substr(0, 20) == "// probe: z_offset: ") {
MKSLOG_RED("得到z_offset: %s", params0.substr(20).c_str());
float temp;
std::stringstream ss;
ss << params0.substr(20);
ss >> temp;
temp = -temp;
temp = temp - 0.15; // 按照要求减去0.15mm
std::string value = std::to_string(temp);
std::string babystep = value.substr(0, value.find(".") + 4);
set_mks_babystep(babystep); // 设置babystep到我们的配置文件里面去
} else if (params0.substr(0, 22) == "// bltouch: z_offset: ") {
MKSLOG_RED("得到z_offset: %s", params0.substr(22).c_str());
float temp;
std::stringstream ss;
ss << params0.substr(22);
ss >> temp;
temp = -temp;
std::string value = std::to_string(temp);
std::string babystep = value.substr(0, value.find(".") + 4);
set_mks_babystep(babystep); // 设置babystep到我们的配置文件里面去
} else if (params0 == "// action:cancel") {
//back_to_main();
} else if (params0.substr(0, 28) == "// Klipper state: Disconnect") {
// printer_webhooks_state_message = "Restarting ...";
} else if (params0.substr(0, 23) == "!! Must home axis first") {
move_home_tips();
} else if (params0.substr(0, 29) == "!! Extrude below minimum temp") {
filament_tips();
} else if (params0.substr(0, 31) == "// Recommended shaper_type_x = ") {
std::string str{"(\\d+\\.\\d+)"}; // 匹配小数
std::smatch matchResult;
std::regex re(str);
std::string temp = params0.substr(31);
if (std::regex_search(temp, matchResult, re)) {
page_syntony_shaper_freq_x = matchResult[0];
}
std::cout << "得到共振补偿的界面" << std::endl;
// page_syntony_shaper_freq_x = params0.substr(52);
MKSLOG_YELLOW("Shaper_freq_x = %s", page_syntony_shaper_freq_x.c_str());
} else if (params0.substr(0, 31) == "// Recommended shaper_type_y = ") {
std::string str{"(\\d+\\.\\d+)"};
std::smatch matchResult;
std::regex re(str);
std::string temp = params0.substr(31);
if (std::regex_search(temp, matchResult, re)) {
page_syntony_shaper_freq_y = matchResult[0];
}
std::cout << "得到共振补偿的界面" << std::endl;
MKSLOG_YELLOW("Shaper_freq_y = %s", page_syntony_shaper_freq_y.c_str());
// page_syntony_shaper_freq_y = params0.substr(51);
} else if (params0.substr(0, 14) == "// Z position:") {
int start = params0.find(">") + 1;
int end = params0.substr(start).find("<") - 1;
str_manual_level_offset = params0.substr(start, end);
std::cout << params0.substr(start, end) << std::endl;
} else if (params0.substr(0, 21) == "!! Move out of range:") {
move_tips();
} else if (params0.substr(0, 52) == "!! Can not update MCU 'mcu' config as it is shutdown") {
printer_webhooks_state_message = "Can not update MCU 'mcu' config as it is shutdown";
} else if (params0.substr(0, 33) == "// accelerometer values (x, y, z)") {
} else if (params0.substr(0, 12) == "// Lost comm") {
} else if (params0 == "Can not update") {
} else if (params0.find("Result is z=") != -1) { //4.4.3 CLL 修改自动取zoffset值时等打印机变为就绪状态时再保存数据
if (current_page_id == TJC_PAGE_AUTO_MOVING || current_page_id == TJC_PAGE_OPEN_CALIBRATE) {
// set_mks_babystep(params0.substr(15));
// save_current_zoffset();
}
} else if (params0 == "!! Insufficient disk space, unable to read the file.") {
jump_to_memory_warning = true;
} else if (params0.substr(0, 2) == "!!") {
error_message = params0;
detect_error();
} else if (params0.find("// Filament dia (measured mm):") != -1 || params0.find("// Filament NOT present") != -1 || params0.find("echo: Filament run out") != -1) { //4.4.2 CLL 使mates和霍尔宽度检测器适配
filament_message = params0;
check_filament_width();
} else if (params0.substr(0, 12) == "// metadata=") { //4.1.7 CLL 修改网页打印信息订阅 已弃用
/*
std::string str_metadata = params0.substr(12);
output_metadata = string2json(str_metadata);
std::cout << output_metadata << std::endl;
parse_file_estimated_time_send(output_metadata);
printer_print_stats_state = "printing";
MKSLOG_BLUE("跳转至打印");
*/
} else if (params0.find("echo: Position init complete") != -1) { // CLL 收到echo:前缀的返回信息即是自定义的返回信息
if (current_page_id == TJC_PAGE_OPEN_CALIBRATE || current_page_id == TJC_PAGE_AUTO_MOVING) {
step_1 = true;
}
} else if (params0.find("echo: Bed mesh calibrate complete") != -1) {
if (current_page_id == TJC_PAGE_OPEN_CALIBRATE) {
step_2 = true;
printer_webhooks_state = "shutdown";
}
if (current_page_id == TJC_PAGE_AUTO_MOVING) {
step_4 = true;
}
} else if (params0.find("echo: Input shaping complete") != -1) {
if (current_page_id == TJC_PAGE_OPEN_CALIBRATE) {
step_3 = true;
}
if (current_page_id == TJC_PAGE_SYNTONY_MOVE) {
step_1 = true;
}
} else if (params0.find("echo: Nozzle cleared") != -1) {
if (current_page_id == TJC_PAGE_AUTO_MOVING) {
step_2 = true;
}
} else if (params0.find("echo: Nozzle cooled") != -1) {
if (current_page_id == TJC_PAGE_AUTO_MOVING) {
step_3 = true;
}
} else if (params0.find("echo: Heat up complete") != -1) {
if (current_page_id == TJC_PAGE_FILAMENT_POP_2 || current_page_id == TJC_PAGE_FILAMENT_POP_3 || current_page_id == TJC_PAGE_AUTO_UNLOAD) {
step_1 = true;
}
} else if (params0.find("echo: Unload finish") != -1) {
if (current_page_id == TJC_PAGE_AUTO_UNLOAD) {
step_2 = true;
}
} else if (params0.find("echo: Load finish") != -1) {
if (current_page_id == TJC_PAGE_FILAMENT_POP_3 || current_page_id == TJC_PAGE_FILAMENT_POP_2) {
step_2 = true;
}
} else if (params0.find("echo: Detected unexpected interruption during the last print.") != -1 || params0.find("echo: Yes: RESUME_INTERRUPTED") != -1 || params0.find("echo: No: CLEAR_LAST_FILE") != -1) {
jump_to_resume_print = true;
}
}
}

View File

@@ -1,359 +0,0 @@
#include "../include/mks_gpio.h"
#include "../include/mks_log.h"
#include "../include/event.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <poll.h>
// static char gpio_path[64];
static int gpio_config(const char *attr, const char *val, const char *gpio_path) {
char file_path[64];
int len;
int fd;
sprintf(file_path, "%s/%s", gpio_path, attr);
if (0 > (fd = open(file_path, O_WRONLY))) {
perror("open error");
return fd;
}
len = strlen(val);
if (len != write(fd, val, len)) {
perror("write error");
close(fd);
return -1;
}
close(fd);
return 0;
}
// 32+2*8+5=53
int set_GPIO1_C5_low() {
if (access("/sys/class/gpio/gpio53", F_OK)) {
int fd;
int len;
char arg[] = "53";
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error");
return -1;
}
len = strlen(arg);
if (len != write(fd, arg, len)) {
perror("write error");
close(fd);
return -1;
}
close(fd); // 关闭文件
}
/* 配置为输出模式 */
if (gpio_config("direction", "out", "/sys/class/gpio/gpio53")) {
printf("配置输出模式出错\n");
return -1;
}
/* 极性设置 */
if (gpio_config("active_low", "0", "/sys/class/gpio/gpio53")) {
printf("配置极性设置出错\n");
return -1;
}
/* 控制GPIO输出低电平 */
if (gpio_config("value", "0", "/sys/class/gpio/gpio53")) {
printf("配置输出低电平出错\n");
return -1;
}
return 0;
}
int set_GPIO1_C5_high() {
if (access("/sys/class/gpio/gpio53", F_OK)) {
int fd;
int len;
char arg[] = "53";
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error");
return -1;
}
len = strlen(arg);
if (len != write(fd, arg, len)) {
perror("write error");
close(fd);
return -1;
}
close(fd); // 关闭文件
}
/* 配置为输出模式 */
if (gpio_config("direction", "out", "/sys/class/gpio/gpio53")) {
printf("配置输出模式出错\n");
return -1;
}
/* 极性设置 */
if (gpio_config("active_low", "0", "/sys/class/gpio/gpio53")) {
printf("配置极性设置出错\n");
return -1;
}
/* 控制GPIO输出高电平 */
if (gpio_config("value", "1", "/sys/class/gpio/gpio53")) {
printf("配置输出低电平出错\n");
return -1;
}
return 0;
}
// 32+1*8+2=42
int init_GPIO1_B2() {
if (access("/sys/class/gpio/gpio42", F_OK)) {
int fd;
int len;
char arg[] = "42";
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error");
return -1;
}
len = strlen(arg);
if (len != write(fd, arg, len)) {
perror("write error");
close(fd);
exit(-1);
}
close(fd);
}
/* 配置为输入模式 */
if (gpio_config("direction", "in", "/sys/class/gpio/gpio42")) {
return -1;
}
/* 极性设置 */
if (gpio_config("active_low", "0", "/sys/class/gpio/gpio42")) {
return -1;
}
/* 配置为非中断方式 */
if (gpio_config("edge", "falling", "/sys/class/gpio/gpio42")) {
return -1;
}
return 0;
}
void *monitor_GPIO1_B2(void *arg) {
struct pollfd pfd;
int ret;
char val;
/* 打开 value 属性文件 */
if (0 > (pfd.fd = open("/sys/class/gpio/gpio42/value", O_RDONLY))) {
perror("打开value出错");
// return ;
}
/* 调用 poll */
pfd.events = POLLPRI; // 只关心高优先级数据可读(中断)
read(pfd.fd, &val, 1); // 先读取一次清除状态
for (;;) {
ret = poll(&pfd, 1, -1);
if (0 > ret) {
perror("poll error");
// return ;
} else if (0 == ret) {
fprintf(stderr, "poll timeout.\n");
continue;
}
/* 检验高优先级数据是否可读 */
if (pfd.revents & POLLPRI) {
if (0 > lseek(pfd.fd, 0, SEEK_SET)) { // 将读位置移动到头部
perror("lseek error");
// return ;
}
if (0 > read(pfd.fd, &val, 1)) {
perror("read error");
// return ;
}
if ((val - '0') == 0) {
// 检测到低电平之后要执行的
// set_GPIO1_C5_low();
//4.4.1 CLL 屏蔽关机页面
system("echo TEST > /root/TESTGPIO; sync");
//go_to_page_power_off();
system("sync; shutdown -h now;");
}
}
usleep(110000); // 检测电平减少一点
}
}
int init_GPIO1_C3() {
if (access("/sys/class/gpio/gpio51", F_OK)) {
int fd;
int len;
char arg[] = "51";
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error");
return -1;
}
len = strlen(arg);
if (len != write(fd, arg, len)) {
perror("write error");
close(fd);
exit(-1);
}
close(fd);
}
/* 配置为输入模式 */
if (gpio_config("direction", "in", "/sys/class/gpio/gpio51")) {
return -1;
}
/* 极性设置 */
if (gpio_config("active_low", "0", "/sys/class/gpio/gpio51")) {
return -1;
}
/* 配置为非中断方式 */
if (gpio_config("edge", "both", "/sys/class/gpio/gpio51")) {
// if (gpio_config("edge", "rising", "/sys/class/gpio/gpio51")) {
return -1;
}
return 0;
}
void *monitor_GPIO1_C3(void *arg) {
struct pollfd pfd;
int ret;
char val;
int cnt = 0;
const int debounce_limit = 5; // 防抖计数器限制
const int debounce_interval = 30; // 防抖时间间隔(毫秒)
/* 打开 value 属性文件 */
if (0 > (pfd.fd = open("/sys/class/gpio/gpio51/value", O_RDONLY))) {
perror("打开value出错");
// return ;
}
/* 调用 poll */
pfd.events = POLLPRI; // 只关心高优先级数据可读(中断)
read(pfd.fd, &val, 1); // 先读取一次清除状态
for (;;) {
ret = poll(&pfd, 1, -1);
if (0 > ret) {
perror("poll error");
// return ;
} else if (0 == ret) {
fprintf(stderr, "poll timeout.\n");
continue;
}
/* 检验高优先级数据是否可读 */
if (pfd.revents & POLLPRI) {
if (0 > lseek(pfd.fd, 0, SEEK_SET)) { // 将读位置移动到头部
perror("lseek error");
// return ;
}
if (0 > read(pfd.fd, &val, 1)) {
perror("read error");
// return ;
}
if ((val - '0') == 1) {
if (cnt >= debounce_limit) {
// 检测到低电平之后要执行的
// set_GPIO1_C5_low();
// system("echo TEST > /root/TESTGPIO; sync");
go_to_page_power_off();
shutdown_mcu();
set_GPIO1_B3_low();
system("sync");
// system("sync; shutdown -h now;");
cnt = 0;
} else {
cnt++;
usleep(debounce_interval * 1000);
}
}else {
cnt = 0;
}
MKSLOG_BLUE("cnt=%d",cnt);
}
usleep(110000);
// 检测电平减少一点
}
}
int set_GPIO1_B3_low() {
if (access("/sys/class/gpio/gpio43", F_OK)) {
int fd;
int len;
char arg[] = "43";
if (0 > (fd = open("/sys/class/gpio/export", O_WRONLY))) {
perror("open error");
return -1;
}
len = strlen(arg);
if (len != write(fd, arg, len)) {
perror("write error");
close(fd);
return -1;
}
close(fd); // 关闭文件
}
/* 配置为输出模式 */
if (gpio_config("direction", "out", "/sys/class/gpio/gpio43")) {
printf("配置输出模式出错\n");
return -1;
}
/* 极性设置 */
if (gpio_config("active_low", "0", "/sys/class/gpio/gpio43")) {
printf("配置极性设置出错\n");
return -1;
}
/* 控制GPIO输出低电平 */
if (gpio_config("value", "0", "/sys/class/gpio/gpio43")) {
printf("配置输出低电平出错\n");
return -1;
}
return 0;
}

View File

@@ -1,63 +0,0 @@
#include "../include/mks_init.h"
#include "../include/MakerbaseShell.h"
std::string serial_by_id;
bool get_by_id() {
struct dirent *dir;
DIR *dirp;
dirp = opendir("/dev/serial/by-id");
if (NULL == dirp) {
printf("读取串口失败!!!!!!!!!!!!!!!!\n");
return false;
} else {
serial_by_id = generate_by_id();
serial_by_id = serial_by_id.substr(0, 58);
std::cout << serial_by_id.length() << " 成功读取到ID号 " + serial_by_id << std::endl;
closedir(dirp);
return true;
}
}
std::string generate_by_id() {
char result[MAX_FILE_LEN] = {0};
std::string cmd = "ls /dev/serial/by-id/*";
execute_cmd(cmd.data(), result);
printf("%s", result);
return result;
}
bool FileStringReplace(std::ifstream &instream, std::ofstream &outstream)
{
std::string str;
size_t pos = 0;
while (getline(instream, str)) // 按行读取
{
pos = str.find("serial:"); // 查找每一行中的"Tom"
if (pos != std::string::npos)
{
str = str.replace(pos, str.length(), "Jerry"); // 将Tom替换为Jerry
outstream << str << std::endl;
continue;
}
outstream << str << std::endl;
}
return true;
}
std::string get_cfg_by_id() {
std::string path = "/home/mks/klipper_config/MKS_THR.cfg";
std::ifstream data(path.c_str());
std::string strline;
std::string ret;
while (getline(data, strline)) {
bool exists = strline.find("serial: ") == std::string::npos;
if (!exists) {
std::cout << strline.length() << " CFG文件里面的serial的值 " + strline.substr(8, 62) << std::endl;
ret = strline.substr(8, 63);
break;
}
}
data.close();
return ret;
}

View File

@@ -1,26 +0,0 @@
/*
#include <stdio.h>
#include <sqlite3.h>
sqlite3 *db = NULL;
int mks_open_database() {
int rc = 0;
rc = sqlite3_open("/root/mks.db", &db);
if (rc != SQLITE_OK) {
printf("Open db error :%s", sqlite3_errmsg(db));
return -1;
}
return 0;
}
void mks_close_database() {
if (db != NULL) {
sqlite3_close(db);
db = NULL;
}
}
*/

View File

@@ -1,55 +0,0 @@
#include "../include/mks_preview.h"
bool gimage_is_showed = false;
bool simage_is_showed = false;
// std::vector<std::string> gimage;
// std::vector<std::string> simage;
// std::string str_gimage = "";
// std::vector<std::string> gimage_temp;
// std::vector<std::string> simage_temp;
/*
void generate_gimage(std::string filename) {
gimage.clear();
// gimage_temp.clear();
std::string path = "/home/mks/gcode_files" + filename;
std::ifstream data(path.c_str());
std::string strline;
while (getline(data, strline)) {
bool exists = strline.find(";gimage:") == std::string::npos;
if (!exists) {
std::cout << strline.substr(8) + "\n" << std::endl;
gimage.push_back(strline.substr(8));
// str_gimage += strline.substr(8);
}
// std::cout << str_gimage << std::endl;
}
data.close();
}
*/
/*
void generate_simage(std::string filename) {
simage.clear();
// simage_temp.clear();
std::string path = "/home/mks/gcode_files" + filename;
std::ifstream data(path.c_str());
std::string strline;
while (getline(data, strline)) {
bool exists = strline.find(";simage:") == std::string::npos;
if (!exists) {
std::cout << strline.substr(8) + "\n" << std::endl;
// simage.push_back(strline.substr(8));
}
}
data.close();
// for (int i = 0; i < simage.size(); i++) {
// std::cout << simage[i] << "\n" << std::endl;
// }
}
*/

View File

@@ -1,622 +0,0 @@
#include <iostream>
#include "../include/mks_printer.h"
// mks ini data
bool mks_led_status;
bool mks_beep_status;
bool mks_fila_status;
int mks_language_status;
int mks_extruder_target;
int mks_heater_bed_target;
int mks_hot_target;
std::string mks_babystep_value;
std::string mks_adxl_offset;
std::string mks_version_soc;
std::string mks_version_mcu;
std::string mks_version_ui;
// webhooks
std::string printer_webhooks_state;
std::string printer_webhooks_state_message;
std::string current_webhooks_state_message;
// gcode_move
float printer_gcode_move_speed_factor;
float printer_gcode_move_speed;
float printer_gcode_move_extrude_factor;
float printer_gcode_move_homing_origin[4]; // [X, Y, Z, E] - 返回应用于每个轴的“gcode 偏移”。例如可以检查“Z”轴以确定通过“babystepping”应用了多少偏移量。
float printer_gcode_move_position[4];
float printer_gcode_move_gcode_position[4];
// toolhead
std::string printer_toolhead_homed_axes;
float printer_toolhead_print_time;
float printer_toolhead_extimated_print_time;
double printer_toolhead_position[4];
double printer_toolhead_axis_minimum[4];
double printer_toolhead_axis_maximum[4];
// x, y, z坐标
double x_position;
double y_position;
double z_position;
// gcode, z坐标
double gcode_z_position;
float e_position;
// extruder
int printer_extruder_temperature = 0;
int printer_extruder_target = 0;
// heater bed
int printer_heater_bed_temperature = 0;
int printer_heater_bed_target = 0;
// hot
int printer_hot_temperature = 0;
int printer_hot_target = 0;
// fan
float printer_fan_speed;
// heater fan
float printer_heater_fan_speed;
// heater_fan my_nozzle_fan1
float printer_heater_fan_my_nozzle_fan1_speed;
// output_pin fan0
float printer_out_pin_fan0_value;
// output_pin fan2
float printer_out_pin_fan2_value;
float printer_out_pin_fan3_value;
float printer_out_pin_beep_value;
// idle_timeout
std::string printer_idle_timeout_state;
float printer_printing_time;
// virtual sdcard
// print stats
std::string printer_print_stats_filename;
float printer_print_stats_total_duration;
float printer_print_stats_print_duration;
float printer_print_stats_filament_used;
std::string printer_print_stats_state; // 这个状态很有用
std::string printer_print_stats_message; // error detected, error message
// display status
std::string printer_display_status_message;
int printer_display_status_progress = 0;
// temperature_sensor sensor_name
// temperature_fan fan_name
// filament_switch_sensor sensor_name
// output_pin pin_name
// bed_mesh
float auto_level_dist = 0.05;
bool auto_level_finished = false;
bool auto_level_enabled = false;
float manual_level_dist = 0.05;
int manual_level_count = 15;
bool manual_level_finished = false;
// bool manual_level_enabled = false;
float printer_bed_mesh_mesh_min[2] = {0.0, 0.0};
float printer_bed_mesh_mesh_max[2] = {0.0, 0.0};
float printer_bed_mesh_profiles_mks_points[5][5] = {0.0};
float printer_bed_mesh_profiles_mks_mesh_params_tension = 0.0;
float printer_bed_mesh_profiles_mks_mesh_params_mesh_x_pps = 0;
std::string printer_bed_mesh_profiles_mks_mesh_params_algo = "";
float printer_bed_mesh_profiles_mks_mesh_params_min_x = 0;
float printer_bed_mesh_profiles_mks_mesh_params_min_y = 0;
float printer_bed_mesh_profiles_mks_mesh_params_x_count = 0;
float printer_bed_mesh_profiles_mks_mesh_params_y_count = 0;
float printer_bed_mesh_profiles_mks_mesh_params_mesh_y_pps = 0;
float printer_bed_mesh_profiles_mks_mesh_params_max_x = 0;
float printer_bed_mesh_profiles_mks_mesh_params_max_y = 0;
float page_set_zoffset_x_y_position[16][2] = {
{30, 30}, // 1
{30, 93.33}, // 2
{30, 156.66}, // 3
{30, 219.99}, // 4
{93.33, 30}, // 5
{93.33, 93.33}, // 6
{93.33, 156.66}, // 7
{93.33, 219.99}, // 8
{156.66, 30}, // 9
{156.66, 93.33}, // 10
{156.66, 156.66}, // 11
{156.66, 219.99}, // 12
{219.99, 30}, // 13
{219.99, 93.33}, // 14
{219.99, 156.66}, // 15
{219.99, 219.99} // 16
};
float page_set_zoffset_z_position[16] = {0};
bool fresh_page_set_zoffset_data = false;
bool refresh_page_auto_finish_data = false;
int page_set_zoffset_index;
// pause resume
int printer_pause_taget;
bool printer_pause_resume_is_paused;
float printer_set_offset = 0.01;
float printer_z_offset = 0.0;
float printer_intern_z_offset = 0.0;
float printer_extern_z_offset = 0.0;
float printer_move_dist = 10.0;
int printer_filament_extruder_target = 0;
int printer_filament_extruedr_dist = 50;
// filament switch sensor fila
bool filament_switch_sensor_fila_filament_detected = false;
bool filament_switch_sensor_fila_enabled = false;
// output_pin caselight
float printer_caselight_value = 0;
// probe
float printer_probe_x_zoffset = 0.0;
float printer_probe_y_zoffset = 0.0;
float printer_probe_z_zoffset = 0.0;
// printer info software version
std::string printer_info_software_version;
// server history totals
int total_jobs = 0;
double total_time = 0.0;
double total_print_time = 0.0;
double total_filament_used = 0.0;
// oobe
float oobe_printer_set_offset = 0.05;
void parse_server_history_totals(nlohmann::json totals) {
/*
if (totals["total_time"] != nlohmann::detail::value_t::null) {
total_time = totals["total_time"];
}
*/
if (totals["total_print_time"] != nlohmann::detail::value_t::null) {
total_print_time = totals["total_print_time"];
}
std::cout << "total_print_time = " << (int)(total_print_time) << std::endl;
}
void parse_printer_probe(nlohmann::json probe) {
if (probe["x_offset"] != nlohmann::detail::value_t::null) {
printer_probe_x_zoffset = probe["x_offset"];
}
if (probe["y_offset"] != nlohmann::detail::value_t::null) {
printer_probe_y_zoffset = probe["y_offset"];
}
if (probe["z_offset"] != nlohmann::detail::value_t::null) {
printer_probe_z_zoffset = probe["z_offset"];
}
}
void parse_printer_beep(nlohmann::json beep) {
if (beep["value"] != nlohmann::detail::value_t::null) {
printer_out_pin_beep_value = beep["value"];
MKSLOG_BLUE("printer_out_pin_beep_value = %f", printer_out_pin_beep_value);
}
}
void parse_printer_caselight(nlohmann::json caselight) {
if (caselight["value"] != nlohmann::detail::value_t::null) {
printer_caselight_value = caselight["value"];
MKSLOG_BLUE("printer_caselight_value = %f", printer_caselight_value);
}
}
void parse_printer_heater_fan_my_nozzle_fan1(nlohmann::json heater_fan_my_nozzle_fan1) {
if (heater_fan_my_nozzle_fan1["speed"] != nlohmann::detail::value_t::null) {
printer_heater_fan_my_nozzle_fan1_speed = heater_fan_my_nozzle_fan1["speed"];
}
}
void parse_printer_out_pin_fan0(nlohmann::json out_pin_fan0) {
if (out_pin_fan0["speed"] != nlohmann::detail::value_t::null) {
printer_out_pin_fan0_value = out_pin_fan0["speed"];
}
std::cout << "printer_out_pin_fan0_value " << printer_out_pin_fan0_value << std::endl;
};
void parse_printer_out_pin_fan2(nlohmann::json out_pin_fan2) {
if (out_pin_fan2["speed"] != nlohmann::detail::value_t::null) {
printer_out_pin_fan2_value = out_pin_fan2["speed"];
}
std::cout << "printer_out_pin_fan2_value " << printer_out_pin_fan2_value << std::endl;
};
void parse_printer_out_pin_fan3(nlohmann::json out_pin_fan3) {
if (out_pin_fan3["speed"] != nlohmann::detail::value_t::null) {
printer_out_pin_fan3_value = out_pin_fan3["speed"];
}
std::cout << "printer_out_pin_fan3_value " << printer_out_pin_fan3_value << std::endl;
};
void parse_filament_switch_sensor_fila(nlohmann::json filament_switch_sensor) {
if (filament_switch_sensor["filament_detected"] != nlohmann::detail::value_t::null) {
filament_switch_sensor_fila_filament_detected = filament_switch_sensor["filament_detected"];
std::cout << "!!!! filament_detected: " << filament_switch_sensor_fila_filament_detected << std::endl;
}
if (filament_switch_sensor["enabled"] != nlohmann::detail::value_t::null) {
filament_switch_sensor_fila_enabled = filament_switch_sensor["enabled"];
std::cout << "!!!! enabled: " << filament_switch_sensor_fila_enabled << std::endl;
}
}
void parse_idle_timeout(nlohmann::json idle_timeout) {
if (idle_timeout["state"] != nlohmann::detail::value_t::null) {
printer_idle_timeout_state = idle_timeout["state"];
std::cout << "idle_timeout: " << printer_idle_timeout_state << std::endl;
MKSLOG_RED("idle_timeout 发生变化: %s", printer_idle_timeout_state.c_str());
}
}
void parse_bed_mesh(nlohmann::json bed_mesh) {
if (bed_mesh["mesh_min"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_mesh_min[0] = bed_mesh["mesh_min"][0];
printer_bed_mesh_mesh_min[1] = bed_mesh["mesh_min"][1];
}
if (bed_mesh["mesh_max"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_mesh_max[0] = bed_mesh["mesh_max"][0];
printer_bed_mesh_mesh_max[1] = bed_mesh["mesh_max"][1];
}
if (bed_mesh["profiles"] != nlohmann::detail::value_t::null) {
if (bed_mesh["profiles"]["default"] != nlohmann::detail::value_t::null) {
if (bed_mesh["profiles"]["default"]["mesh_params"] != nlohmann::detail::value_t::null) {
if (bed_mesh["profiles"]["default"]["mesh_params"]["tension"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_tension = bed_mesh["profiles"]["default"]["mesh_params"]["tension"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["mesh_x_pps"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_mesh_x_pps = bed_mesh["profiles"]["default"]["mesh_params"]["mesh_x_pps"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["algo"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_algo = bed_mesh["profiles"]["default"]["mesh_params"]["algo"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["min_x"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_min_x = bed_mesh["profiles"]["default"]["mesh_params"]["min_x"];
std::cout << "printer_bed_mesh_profiles_mks_mesh_params_min_x = " << printer_bed_mesh_profiles_mks_mesh_params_min_x << std::endl;
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["min_y"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_min_y = bed_mesh["profiles"]["default"]["mesh_params"]["min_y"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["y_count"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_y_count = bed_mesh["profiles"]["default"]["mesh_params"]["y_count"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["mesh_y_pps"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_mesh_y_pps = bed_mesh["profiles"]["default"]["mesh_params"]["mesh_y_pps"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["x_count"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_x_count = bed_mesh["profiles"]["default"]["mesh_params"]["x_count"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["max_x"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_max_x = bed_mesh["profiles"]["default"]["mesh_params"]["max_x"];
}
if (bed_mesh["profiles"]["default"]["mesh_params"]["max_y"] != nlohmann::detail::value_t::null) {
printer_bed_mesh_profiles_mks_mesh_params_max_y = bed_mesh["profiles"]["default"]["mesh_params"]["max_y"];
}
}
if (bed_mesh["profiles"]["default"]["points"] != nlohmann::detail::value_t::null) {
for (int i = 0; i < printer_bed_mesh_profiles_mks_mesh_params_y_count; i++) {
if (i == 5) {
break;
}
for (int j = 0; j < printer_bed_mesh_profiles_mks_mesh_params_x_count; j++) {
if (j == 5) {
break;
}
printer_bed_mesh_profiles_mks_points[i][j] = bed_mesh["profiles"]["default"]["points"][i][j];
}
}
}
}
}
}
void parse_webhooks(nlohmann::json webhooks) {
if (webhooks["state"] != nlohmann::detail::value_t::null) {
printer_webhooks_state = webhooks["state"];
}
// MKSLOG_RED("Webhooks state: %s", printer_webhooks_state);
if (webhooks["state_message"] != nlohmann::detail::value_t::null) {
printer_webhooks_state_message = webhooks["state_message"];
}
MKSLOG_RED("State message: %s", printer_webhooks_state_message.c_str());
}
void parse_gcode_move(nlohmann::json gcode_move) {
if (gcode_move["speed_factor"] != nlohmann::detail::value_t::null) {
printer_gcode_move_speed_factor = gcode_move["speed_factor"];
}
if (gcode_move["speed"] != nlohmann::detail::value_t::null) {
printer_gcode_move_speed = gcode_move["speed"];
}
if (gcode_move["extrude_factor"] != nlohmann::detail::value_t::null) {
printer_gcode_move_extrude_factor = gcode_move["extrude_factor"];
}
if (gcode_move["homing_origin"] != nlohmann::detail::value_t::null) {
printer_gcode_move_homing_origin[0] = gcode_move["homing_origin"][0];
printer_gcode_move_homing_origin[1] = gcode_move["homing_origin"][1];
printer_gcode_move_homing_origin[2] = gcode_move["homing_origin"][2];
printer_gcode_move_homing_origin[3] = gcode_move["homing_origin"][3];
}
if (gcode_move["gcode_position"] != nlohmann::detail::value_t::null) {
// printer_gcode_move_gcode_position[0] = gcode_move["gcode_position"][0];
// printer_gcode_move_gcode_position[1] = gcode_move["gcode_position"][1];
printer_gcode_move_gcode_position[2] = gcode_move["gcode_position"][2];
// printer_gcode_move_gcode_position[3] = gcode_move["gcode_position"][3];
// std::cout << "printer_gcode_move_gcode_position[2] " << printer_gcode_move_gcode_position[2] << std::endl;
gcode_z_position = round(printer_gcode_move_gcode_position[2] * 1000) / 1000;
}
}
void parse_toolhead(nlohmann::json toolhead) {
if (toolhead["position"] != nlohmann::detail::value_t::null) {
printer_toolhead_position[0] = toolhead["position"][0];
x_position = round(printer_toolhead_position[0] * 10) / 10;
printer_toolhead_position[1] = toolhead["position"][1];
y_position = round(printer_toolhead_position[1] * 10) / 10;
printer_toolhead_position[2] = toolhead["position"][2];
// std::cout << "printer_toolhead_position[2] " << printer_toolhead_position[2] << std::endl;
// std::cout << "printer_toolhead_position[2] " << std::to_string(printer_toolhead_position[2]) << std::endl;
z_position = round(printer_toolhead_position[2] * 10) / 10;
// std::cout << "z_position: " << z_position << std::endl;
printer_toolhead_position[3] = toolhead["position"][3];
// std::cout << "printer_toolhead_position z == " << printer_toolhead_position << std::endl;
}
if (toolhead["axis_minimum"] != nlohmann::detail::value_t::null) {
printer_toolhead_axis_minimum[0] = toolhead["axis_minimum"][0];
printer_toolhead_axis_minimum[1] = toolhead["axis_minimum"][1];
printer_toolhead_axis_minimum[2] = toolhead["axis_minimum"][2];
printer_toolhead_axis_minimum[3] = toolhead["axis_minimum"][3];
}
if (toolhead["axis_maximum"] != nlohmann::detail::value_t::null) {
printer_toolhead_axis_maximum[0] = toolhead["axis_maximum"][0];
printer_toolhead_axis_maximum[1] = toolhead["axis_maximum"][1];
printer_toolhead_axis_maximum[2] = toolhead["axis_maximum"][2];
printer_toolhead_axis_maximum[3] = toolhead["axis_maximum"][3];
}
}
void parse_extruder(nlohmann::json extruder) {
float temp;
if (extruder["temperature"] != nlohmann::detail::value_t::null) {
temp = extruder["temperature"];
printer_extruder_temperature = (int)(temp + 0.5);
// printer_extruder_temperature = extruder["temperature"];
}
if (extruder["target"] != nlohmann::detail::value_t::null) {
temp = extruder["target"];
printer_extruder_target = (int)(temp + 0.5);
// printer_extruder_target = extruder["target"];
}
}
void parse_heater_bed(nlohmann::json heater_bed) {
float temp;
if (heater_bed["temperature"] != nlohmann::detail::value_t::null) {
temp = heater_bed["temperature"];
printer_heater_bed_temperature = (int)(temp + 0.5);
}
if (heater_bed["target"] != nlohmann::detail::value_t::null) {
temp = heater_bed["target"];
printer_heater_bed_target = (int)(temp + 0.5);
}
}
void parse_heater_generic_hot(nlohmann::json heater_generic_hot) {
float temp;
if (heater_generic_hot["temperature"] != nlohmann::detail::value_t::null) {
temp = heater_generic_hot["temperature"];
printer_hot_temperature = (int)(temp + 0.5);
}
if (heater_generic_hot["target"] != nlohmann::detail::value_t::null) {
temp = heater_generic_hot["target"];
printer_hot_target = (int)(temp + 0.5);
}
}
void parse_fan(nlohmann::json fan) {
if (fan["speed"] != nlohmann::detail::value_t::null) {
printer_fan_speed = fan["speed"];
}
}
void parse_heater_fan(nlohmann::json heater_fan) {
if (heater_fan["speed"] != nlohmann::detail::value_t::null) {
printer_heater_fan_speed = heater_fan["speed"];
}
}
void parse_print_stats(nlohmann::json print_stats) {
if (print_stats["state"] != nlohmann::detail::value_t::null) {
printer_print_stats_state = print_stats["state"];
std::cout << "\033[31;1m" << "printer_print_stats_state = " << printer_print_stats_state << "\033[0m" << std::endl;
}
if (print_stats["filename"] != nlohmann::detail::value_t::null) {
printer_print_stats_filename = print_stats["filename"];
std::cout << "\033[31;1m" << "printer_print_stats_filename = " << printer_print_stats_filename << "\033[0m" << std::endl;
}
if (print_stats["print_duration"] != nlohmann::detail::value_t::null) {
printer_print_stats_print_duration = print_stats["print_duration"];
}
if (print_stats["total_duration"] != nlohmann::detail::value_t::null) {
printer_print_stats_total_duration = print_stats["total_duration"];
}
}
void parse_display_status(nlohmann::json display_status) {
double temp = 0.0;
if (display_status["progress"] != nlohmann::detail::value_t::null) {
temp = display_status["progress"];
printer_display_status_progress = (int)(temp * 100);
}
}
void parse_pause_resume(nlohmann::json pause_resume) {
std::cout << pause_resume << std::endl;
if (pause_resume["is_paused"] != nlohmann::detail::value_t::null) {
printer_pause_resume_is_paused = pause_resume["is_paused"];
}
}
// 解析订阅对象状态
void parse_subscribe_objects_status(nlohmann::json status) {
if (status["idle_timeout"] != nlohmann::detail::value_t::null) {
parse_idle_timeout(status["idle_timeout"]);
}
if (status["bed_mesh"] != nlohmann::detail::value_t::null) {
std::cout << status["bed_mesh"] << std::endl;
parse_bed_mesh(status["bed_mesh"]);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
std::cout << "############# Points :" << i << ", " << j << " " << printer_bed_mesh_profiles_mks_points[i][j] << std::endl;
}
}
}
if (status["webhooks"] != nlohmann::detail::value_t::null) {
// MKSLOG("Webhooks update");
parse_webhooks(status["webhooks"]);
}
if (status["gcode_move"] != nlohmann::detail::value_t::null) {
// MKSLOG("Gcode move update");
parse_gcode_move(status["gcode_move"]);
}
if (status["toolhead"] != nlohmann::detail::value_t::null) {
// MKSLOG("toolhead update");
parse_toolhead(status["toolhead"]);
}
if (status["extruder"] != nlohmann::detail::value_t::null) {
// MKSLOG("Extruder update");
parse_extruder(status["extruder"]);
}
if (status["heater_bed"] != nlohmann::detail::value_t::null) {
// MKSLOG("Heater bed update");
parse_heater_bed(status["heater_bed"]);
}
if (status["heater_generic chamber"] != nlohmann::detail::value_t::null) {
parse_heater_generic_hot(status["heater_generic chamber"]);
}
if (status["fan"] != nlohmann::detail::value_t::null) {
// MKSLOG("Fan update");
parse_fan(status["fan"]);
}
if (status["heater_fan fan1"] != nlohmann::detail::value_t::null) {
parse_heater_fan(status["heater_fan fan1"]);
}
if (status["pause_resume"] != nlohmann::detail::value_t::null) {
parse_pause_resume(status["pause_resume"]);
}
if (status["print_stats"] != nlohmann::detail::value_t::null) {
// MKSLOG("Print stats update");
parse_print_stats(status["print_stats"]);
}
if (status["display_status"] != nlohmann::detail::value_t::null) {
// MKSLOG("Display status update");
parse_display_status(status["display_status"]);
}
if (status["heater_fan my_nozzle_fan1"] != nlohmann::detail::value_t::null) {
parse_printer_heater_fan_my_nozzle_fan1(status["heater_fan my_nozzle_fan1"]);
}
if (status["fan_generic cooling_fan"] != nlohmann::detail::value_t::null) {
parse_printer_out_pin_fan0(status["fan_generic cooling_fan"]);
}
if (status["fan_generic auxiliary_cooling_fan"] != nlohmann::detail::value_t::null) {
parse_printer_out_pin_fan2(status["fan_generic auxiliary_cooling_fan"]);
}
if (status["fan_generic chamber_circulation_fan"] != nlohmann::detail::value_t::null) {
parse_printer_out_pin_fan3(status["fan_generic chamber_circulation_fan"]);
}
if (status["filament_switch_sensor fila"] != nlohmann::detail::value_t::null) {
parse_filament_switch_sensor_fila(status["filament_switch_sensor fila"]);
}
if (status["output_pin caselight"] != nlohmann::detail::value_t::null) {
parse_printer_caselight(status["output_pin caselight"]);
}
if (status["output_pin sound"] != nlohmann::detail::value_t::null) {
parse_printer_beep(status["output_pin sound"]);
}
if (status["probe"] != nlohmann::detail::value_t::null) {
parse_printer_probe(status["probe"]);
}
}
nlohmann::json subscribe_objects_status() {
nlohmann::json objects;
objects["extruder"];
objects["heater_generic chamber"];
objects["heater_bed"];
objects["gcode_move"];
objects["fan"] = {"speed"};
objects["heater_fan fan1"] = {"speed"};
objects["toolhead"];
objects["print_stats"] = {"print_duration", "total_duration", "filament_used", "filename", "state", "message"};
objects["display_status"] = {"progress", "message"};
objects["idle_timeout"] = {"state"};
objects["pause_resume"] = {"is_paused"};
objects["webhooks"] = {"state", "state_message"};
// objects["webhooks"];
objects["firmware_retraction"] = {"retract_length", "retract_speed", "unretract_extra_length",
"unretract_speed"};
objects["bed_mesh"];
objects["heater_fan my_nozzle_fan1"];
objects["filament_switch_sensor fila"] = {"filament_detected", "enabled"};
objects["fan_generic cooling_fan"] = {"speed", "rpm"};
objects["fan_generic auxiliary_cooling_fan"] = {"speed", "rpm"};
objects["fan_generic chamber_circulation_fan"] = {"speed", "rpm"};
objects["output_pin caselight"];
objects["output_pin sound"];
objects["probe"];
return objects;
}
int get_cal_printing_time(int print_time, int estimated_time, int progress) {
int left_time;
int total_time = 0;
if (progress <= 10) {
total_time = estimated_time;
left_time = total_time - print_time;
} else if (progress > 10) {
total_time = (print_time) * 100 / (progress);
left_time = total_time - print_time;
}
return left_time;
}
void parse_printer_info(nlohmann::json result) {
if (result["software_version"] != nlohmann::detail::value_t::null) {
// std::cout << result["software_version"] << std::endl;
printer_info_software_version = result["software_version"];
MKSLOG_RED("Version: %s", printer_info_software_version.c_str());
}
}

View File

@@ -1,4 +0,0 @@
#include "../include/mks_system.h"

View File

@@ -1,120 +0,0 @@
#include "../include/mks_test.h"
#include "../include/ui.h"
#include "../include/send_msg.h"
#include "../include/event.h"
extern int tty_fd;
extern int current_page_id;
// void *mks_test(void *arg) {
// while (1) {
// if (current_page_id == TJC_PAGE_MKS_TEST) {
// if (true == testUSB()) {
// send_cmd_txt(tty_fd, "t2", "Okay");
// send_cmd_pco(tty_fd, "t2", "2047");
// sleep(2);
// } else {
// send_cmd_txt(tty_fd, "t2", "fail");
// send_cmd_pco(tty_fd, "t2", "63488");
// }
// if (true == moko_test_func()) {
// send_cmd_txt(tty_fd, "t2", "okay");
// send_cmd_pco(tty_fd, "t2", "1024");
// sleep(2);
// } else {
// send_cmd_txt(tty_fd, "t2", "fail");
// send_cmd_pco(tty_fd, "t2", "63488");
// }
// if (true == network_test_func()) {
// send_cmd_txt(tty_fd, "t3", "Okay");
// send_cmd_pco(tty_fd, "t3", "2047");
// } else {
// send_cmd_txt(tty_fd, "t3", "fail");
// send_cmd_pco(tty_fd, "t3", "63488");
// }
// }
// refresh_page_mks_test();
// usleep(50000);
// }
// }
bool testUSB()
{
FILE *fp;
char buffer[1024];
static int last_style = 0;
fp=popen("lsusb | grep \"QinHeng Electronics\"", "r");
fgets(buffer,sizeof(buffer),fp);
//printf("%s",buffer);
if(strstr(buffer, "QinHeng Electronics") != 0)
{
pclose(fp);
return true;
}
else
{
pclose(fp);
return false;
}
}
bool moko_test_func()
{
FILE *fp;
char buffer[1024];
static int last_style = 0;
fp = popen("lsusb | grep \"OpenMoko\"", "r");
fgets(buffer, sizeof(buffer), fp);
if (strstr(buffer, "OpenMoko") != 0) {
pclose(fp);
return true;
} else {
pclose(fp);
return false;
}
}
bool network_test_func()
{
FILE *fp;
char buffer[1024];
static int last_style = 0;
try
{
fp=popen("ifconfig | grep \"inet 192.168.\"", "r");
fgets(buffer,sizeof(buffer),fp);
if(strstr(buffer, "inet 192.168.") != 0)
{
pclose(fp);
return true;
}
else
{
pclose(fp);
return false;
}
}
catch (char *str)
{ pclose(fp);
std::cout << "Standard exception: " << str << std::endl;
}
return 0;
}

View File

@@ -1,536 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <map>
#include <memory>
#include <dirent.h>
#include <cstring>
#include <cstdlib>
#include "../include/event.h"
#include "../include/send_msg.h"
#include "../include/MakerbaseSerial.h"
extern int tty_fd; // main.cpp 里面的变量
extern bool is_download_to_screen; // main.cpp 里面的变量
int copy_fd;
bool detected_soc_data;
bool detected_mcu_data;
bool detected_ui_data;
// CLL 新增检测Q1的SOC和UI更新
bool detected_q1_soc_data;
bool detected_q1_ui_data;
// CCW 4.4.14 新增Q1补丁包检测更新
bool detected_q1_patch_data = false;
DIR *dir;
struct dirent *entry;
std::string base_path = "/home/mks/gcode_files/sda1/QD_Update/";
bool detected_printer_cfg;
bool detected_gcode_cfg;
bool detected_MKS_THR_cfg;
bool detected_gcode;
// 4.4.3 CLL 修改deb文件也能更新
bool detected_soc_deb;
std::ifstream tftfile;
int tft_buff = 4096;
int tft_start;
int tft_end;
std::string tft_s;
std::string tft_data;
int tft_len;
int filesize;
int tft_index;
char tft_buffer[4096] = {0};
int u_disk_update()
{
int fd = 1;
char PATH[64];
char cmd[64];
char chOrder[50];
char chOrder1[50];
int i = 0;
int j = 0;
char ch[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
for (j = 0; j < 4; j++)
{
for (i = 0; i < 8; i++)
{
sprintf(PATH, "/home/mks/gcode_files/sd%c%d/QD_Update/QD_Mates3_SOC", ch[i], j);
fd = access(PATH, F_OK);
if (fd == 0)
{
printf("检测到U盘下存在目录%s正在检测更新文件\n", PATH);
sprintf(cmd, "dpkg -i %s; rm %s -f", PATH, PATH);
system(cmd);
break;
}
else
{
// printf("没有检测到U盘相关的内容\n");
continue;
}
}
if (fd == 0)
{
break;
}
}
if (fd == -1)
{
printf("无法打开u盘\n");
}
else
{
close(fd);
}
return 0;
}
bool detect_update()
{
int fd_soc_data;
int fd_mcu_data;
int fd_ui_data;
int fd_printer_cfg;
int fd_gcode_cfg;
int fd_mks_thr_cfg;
int fd_gcode;
// 4.4.3 CLL 新增deb文件也能更新
int fd_soc_deb;
fd_soc_data = access("/home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC", F_OK);
if (fd_soc_data == 0)
{
detected_soc_data = true;
}
else
{
detected_soc_data = false;
fd_soc_data = access("/home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC", F_OK);
if (fd_soc_data == 0)
{
detected_q1_soc_data = true;
}
else
{
detected_q1_soc_data = false;
}
}
if ((dir = opendir(base_path.c_str())) != nullptr)
{
while ((entry = readdir(dir)) != nullptr)
{
std::string filename = entry->d_name;
if (filename.find("QD_Q1_PATCH") == 0)
{
detected_q1_patch_data = true; // 找到 QD_Q1_PATCH 开头文件
break;
}
}
closedir(dir);
}
fd_mcu_data = access("/home/mks/gcode_files/sda1/QD_MCU/MCU", F_OK);
if (fd_mcu_data == 0)
{
detected_mcu_data = true;
}
else
{
detected_mcu_data = false;
}
fd_ui_data = access("/home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI", F_OK);
if (fd_ui_data == 0)
{
detected_ui_data = true;
}
else
{
detected_ui_data = false;
fd_ui_data = access("/home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI", F_OK);
if (fd_ui_data == 0)
{
detected_q1_ui_data = true;
}
else
{
detected_q1_ui_data = false;
}
}
fd_gcode_cfg = access("/home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg", F_OK);
if (fd_gcode_cfg == 0)
{
detected_gcode_cfg = true;
}
else
{
detected_gcode_cfg = false;
}
fd_printer_cfg = access("/home/mks/gcode_files/sda1/QD_Update/printer.cfg", F_OK);
if (fd_printer_cfg == 0)
{
detected_printer_cfg = true;
}
else
{
detected_printer_cfg = false;
}
fd_mks_thr_cfg = access("/home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg", F_OK);
if (fd_mks_thr_cfg == 0)
{
detected_MKS_THR_cfg = true;
}
else
{
detected_MKS_THR_cfg = false;
}
fd_gcode = access("/home/mks/gcode_files/sda1/QD_Update/QD_Gcode", F_OK);
if (fd_gcode == 0)
{
detected_gcode = true;
}
else
{
detected_gcode = false;
}
// 4.4.3 CLL 新增deb文件也能更新
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
fd_soc_deb = access("/home/mks/gcode_files/sda1/QD_Update/mks.deb", F_OK);
if (fd_soc_deb == 0)
{
detected_soc_deb = true;
}
else
{
detected_soc_deb = false;
}
}
return (detected_soc_data | detected_q1_soc_data | detected_mcu_data | detected_ui_data | detected_q1_ui_data | detected_printer_cfg | detected_MKS_THR_cfg | detected_gcode | detected_soc_deb | detected_gcode_cfg | detected_q1_patch_data);
}
void start_update()
{
system("rm /home/mks/gcode_files/.cache/*");
if (detected_mcu_data == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
// std::cout << "检测到qidi文件" << std::endl;
system("cp /home/mks/gcode_files/sda1/QD_MCU/MCU /root/klipper.bin;");
// reset_firmware();
close_mcu_port();
// sleep(1);
// system("service klipper stop; /root/hid-flash /root/klipper.bin ttyS0;");
system("service klipper stop; /root/hid-flash /root/klipper.bin ttyS0; systemctl start klipper; ");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
// std::cout << "检测到qidi文件" << std::endl;
system("cp /home/mks/gcode_files/sda1/QD_MCU/MCU /root/klipper.bin;");
// reset_firmware();
close_mcu_port();
// sleep(1);
// system("service klipper stop; /root/hid-flash /root/klipper.bin ttyS0;");
system("service klipper stop; /root/hid-flash /root/klipper.bin ttyS0; systemctl start klipper; ");
}
else
{
// std::cout << "没有检测到qidi文件" << std::endl;
system("cp /home/mks/gcode_files/sda1/QD_MCU/MCU /root/klipper.bin;");
// reset_firmware();
close_mcu_port();
// sleep(2);
system("service klipper stop; /root/hid-flash /root/klipper.bin ttyS0; systemctl start klipper; mv /home/mks/gcode_files/sda1/QD_MCU/MCU /home/mks/gcode_files/sda1/QD_MCU/MCU.bak");
}
}
}
if (detected_ui_data == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI /root/800_480.tft; sync");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI /root/800_480.tft; sync");
}
else
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI /root/800_480.tft; mv /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_UI.bak; sync");
}
}
}
else if (detected_q1_ui_data == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI /root/800_480.tft; sync");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI /root/800_480.tft; sync");
}
else
{
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI /root/800_480.tft; mv /home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI /home/mks/gcode_files/sda1/QD_Update/QD_Q1_UI.bak; sync");
}
}
}
if (detected_gcode_cfg == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg /home/mks/klipper_config/gcode_macro.cfg; chmod 777 /home/mks/klipper_config/gcode_macro.cfg; sync");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg /home/mks/klipper_config/gcode_macro.cfg; chmod 777 /home/mks/klipper_config/gcode_macro.cfg; sync");
}
else
{
system("cp /home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg /home/mks/klipper_config/gcode_macro.cfg; chmod 777 /home/mks/klipper_config/gcode_macro.cfg; mv /home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg /home/mks/gcode_files/sda1/QD_Update/gcode_macro.cfg.bak; sync");
}
}
}
if (detected_printer_cfg == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/printer.cfg /home/mks/klipper_config/printer.cfg; chmod 777 /home/mks/klipper_config/printer.cfg; sync");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/printer.cfg /home/mks/klipper_config/printer.cfg; chmod 777 /home/mks/klipper_config/printer.cfg; sync");
}
else
{
system("cp /home/mks/gcode_files/sda1/QD_Update/printer.cfg /home/mks/klipper_config/printer.cfg; chmod 777 /home/mks/klipper_config/printer.cfg; mv /home/mks/gcode_files/sda1/QD_Update/printer.cfg /home/mks/gcode_files/sda1/QD_Update/printer.cfg.bak; sync");
}
}
}
if (detected_MKS_THR_cfg == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg /home/mks/klipper_config/MKS_THR.cfg; chmod 777 /home/mks/klipper_config/MKS_THR.cfg; sync");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
system("cp /home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg /home/mks/klipper_config/MKS_THR.cfg; chmod 777 /home/mks/klipper_config/MKS_THR.cfg; sync");
}
else
{
system("cp /home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg /home/mks/klipper_config/MKS_THR.cfg; chmod 777 /home/mks/klipper_config/MKS_THR.cfg; mv /home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg /home/mks/gcode_files/sda1/QD_Update/MKS_THR.cfg.bak; sync");
}
}
}
if (detected_gcode == true)
{
// 先清空gcode_files文件夹中的所有其他文件,会保留下sda1目录和其中的文件使用-rf指令更改路径需要谨慎
system("rm /home/mks/gcode_files/*\n");
system("rm /home/mks/gcode_files/.thumbs/*\n");
system("systemctl stop moonraker.service\n");
system("find /home/mks/gcode_files -maxdepth 1 -type d ! -name sd* -a ! -name '.*' | grep gcode_files/ | xargs rm -rf");
system("cp /home/mks/gcode_files/sda1/QD_Update/QD_gcode/*.gcode /home/mks/gcode_files; chmod 777 /home/mks/gcode_files/*.gcode; sync");
}
// 检测到补丁文件
if (detected_q1_patch_data)
{
bool factory_mode = (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) != -1);
if ((dir = opendir(base_path.c_str())) != nullptr)
{
while ((entry = readdir(dir)) != nullptr)
{
std::string filename = entry->d_name;
if (filename.find("QD_Q1_PATCH") == 0)
{
std::string file_path = base_path + filename;
std::string command = "mv " + file_path + " " + base_path + "mks.deb; dpkg -i --force-overwrite " + base_path + "mks.deb;";
system(command.c_str());
std::string new_file_name = file_path;
if (!factory_mode)
{
new_file_name += ".bak";
}
command = "mv " + base_path + "mks.deb " + new_file_name + "; sync";
system(command.c_str());
}
}
closedir(dir);
}
}
if (detected_soc_data == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
std::cout << "检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC; sync;");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
std::cout << "检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC; sync;");
}
else
{
std::cout << "没有检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Mates3_SOC.bak; sync;");
}
}
}
else if (detected_soc_deb == true)
{ // 4.4.3 CLL 修改deb文件可以更新
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
system("dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb;sync");
}
}
else if (detected_q1_soc_data == true)
{
if (access("/home/mks/gcode_files/sda1/QD_factory_mode.txt", F_OK) == 0)
{
std::cout << "检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC; sync;");
}
else
{
if (access("/home/mks/gcode_files/sda1/QD_Update/QD_factory_mode.txt", F_OK) == 0)
{
std::cout << "检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC; sync;");
}
else
{
std::cout << "没有检测到qidi文件" << std::endl;
system("mv /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC /home/mks/gcode_files/sda1/QD_Update/mks.deb; dpkg -i --force-overwrite /home/mks/gcode_files/sda1/QD_Update/mks.deb; mv /home/mks/gcode_files/sda1/QD_Update/mks.deb /home/mks/gcode_files/sda1/QD_Update/QD_Q1_SOC.bak; sync;");
}
}
}
update_finished_tips();
}
void download_to_screen()
{
std::cout << "tft_start == " << tft_start << std::endl;
if (tft_start < tft_len)
{
if (tft_end > tft_len)
{
tft_s = tft_data.substr(tft_start, tft_len - tft_start);
std::cout << "发送下载数据 == " << tft_start << "/" << filesize << std::endl;
send_cmd_download_data(tty_fd, tft_s);
}
tft_s = tft_data.substr(tft_start, tft_buff);
std::cout << tft_s.length() << " 发送下载数据 == " << tft_start << "/" << filesize << std::endl;
tft_start = tft_end;
tft_end = tft_end + tft_buff;
send_cmd_download_data(tty_fd, tft_s);
}
}
void init_download_to_screen()
{
if (access("/root/800_480.tft", F_OK) == 0)
{
tft_data.clear();
tftfile.open("/root/800_480.tft");
struct stat tft_stat;
stat("/root/800_480.tft", &tft_stat);
filesize = tft_stat.st_size;
std::cout << "文件大小为: " << filesize << std::endl;
std::ostringstream temp;
temp << tftfile.rdbuf();
tft_data = temp.str();
std::cout << "读取的字符串长度为:" << tft_data.length() << std::endl;
tft_len = tft_data.length();
tft_end = tft_buff;
tftfile.close();
}
}
void back_to_screen_old()
{
if (access("/root/800_480.tft.bak", F_OK) == 0)
{
tft_data.clear();
tftfile.open("/root/800_480.tft.bak");
struct stat tft_stat;
stat("/root/800_480.tft.bak", &tft_stat);
filesize = tft_stat.st_size;
std::cout << "文件大小为: " << filesize << std::endl;
send_cmd_download(tty_fd, filesize);
std::ostringstream temp;
temp << tftfile.rdbuf();
tft_data = temp.str();
tft_len = tft_data.length();
tft_end = tft_buff;
tftfile.close();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,610 +0,0 @@
#include "../include/mks_log.h"
#include "../include/send_msg.h"
#include "../include/MakerbaseSerial.h"
#include "../include/send_jpg.h"
#include "../include/mks_file.h"
// #define BLOCK_SIZE 2048
// #define HEADER_SIZE 12
extern int tty_fd;
bool get_0xfe = false;
bool get_0x06 = false;
bool get_0x05 = false;
bool get_0xfd = false;
bool get_0x04 = false;
bool get_0x24 = false;
bool have_64_jpg[6];
std::string have_64_png_path[6];
bool begin_show_64_jpg;
bool begin_show_160_jpg;
bool begin_show_192_jpg;
bool show_192_jpg_complete = true;
std::string jpg_160_path;
int time_differ(int duration, int start_time) {
int tmp;
tmp = time(NULL);
tmp = tmp - start_time;
if (tmp > duration) {
return 1;
} else {
return 0;
}
}
int time_differ_ms(long duration, long start_time) {
struct timeval tv1;
gettimeofday(&tv1, NULL);
long tmp;
tmp = tv1.tv_sec * 1000 + tv1.tv_usec / 1000;
tmp = tmp - start_time;
if (tmp > duration) {
return 1;
} else {
return 0;
}
}
extern std::string input_path;
extern int input_size;
extern bool start_path;
// 刷预览图线程
void *sent_jpg_thread_handle(void *arg)
{
std::string png_path = "";
std::string ram_path = "";
std::string jpg_path = "";
while (1)
{
// 刷新小预览图
if (begin_show_64_jpg)
{
begin_show_64_jpg = false;
for (uint i = 0; i < 6; i++)
{
if (have_64_jpg[i] == true)
{
send_cmd_tsw(tty_fd, "255", "0"); // 禁止屏幕触摸
MKSLOG_BLUE("不能触摸屏幕");
usleep(50500 + i * 500);
ram_path = std::string("ram/") + std::string("file") + std::to_string(i) + std::string(".jpg");
// jpg_path = page_files_root_path + std::string("/") + page_files_path + std::string("/.thumbs/") + page_files_list_show_name[i].substr(0, page_files_list_show_name[i].find(".gcode")) + std::string("-64x64.jpg");
// output_jpg(have_64_png_path[i], input_size);
// std::cout << extractFileName(have_64_png_path[i]) << std::endl;
// if (i < 4) {
// output_jpg(have_64_png_path[i], 112);
// } else {
// output_jpg(have_64_png_path[i], 160);
// }
// jpg_path = "/home/mks/tjc.jpg";
jpg_path = "/home/mks/gcode_files/" + have_64_png_path[i] ;
// send_cmd_baud(tty_fd, 230400);
std::cout << jpg_path << std::endl;
// usleep(50000);
// set_option(tty_fd, 230400, 8, 'N', 1);
// if (sent_jpg_to_tjc(ram_path, jpg_path) != true)
// {
sent_jpg_to_tjc(ram_path, jpg_path);
// }
// send_cmd_baud(tty_fd, 115200);
// usleep(50000);
// set_option(tty_fd, 115200, 8, 'N', 1);
have_64_jpg[i] = false;
// system("rm /home/mks/tjc.jpg");
send_cmd_tsw(tty_fd, "255", "1"); // 使能屏幕触摸
MKSLOG_BLUE("可以触摸屏幕");
}
}
}
// 刷新预览界面预览图
// if (begin_show_192_jpg)
// {
// // jpg_path = page_files_root_path + std::string("/") + page_files_path + std::string("/.thumbs/") + current_select_file.substr(0, current_select_file.find(".gcode")) + std::string("-192x192.jpg");
// jpg_path = "/root/tjc.jpg";
// while (1)
// {
// if (sent_jpg_to_tjc("ram/file0.jpg", jpg_path) == true)
// {
// break;
// }
// delet_pic("ram/file0.jpg");
// usleep(500000);
// }
// begin_show_192_jpg = false;
// show_192_jpg_complete = true;
// }
// 刷新打印界面预览图
// if (begin_show_160_jpg)
// {
// while (1)
// {
// if (sent_jpg_to_tjc("ram/160.jpg", jpg_160_path) == true)
// {
// break;
// }
// delet_pic("ram/160.jpg");
// usleep(500000);
// }
// begin_show_160_jpg = false;
// }
// 提前删除预览界面的预览图,防止进入预览页面时闪一下
// if (current_page_id != TJC_PAGE_PREVIEW)
// {
// if (show_192_jpg_complete)
// {
// delet_pic("ram/192.jpg");
// show_192_jpg_complete = false;
// }
// }
usleep(60000);
}
}
// 删除图片
void delet_pic(std::string ram_path)
{
send_cmd_delfile(tty_fd, ram_path);
}
// 获取文件大小
long getFileSize(FILE *file)
{
long fileSize = -1;
if (file != NULL)
{
if (fseek(file, 0L, SEEK_END) == 0)
{
fileSize = ftell(file);
}
rewind(file);
}
return fileSize;
}
// 计算单个数据的校验码
unsigned int calccrc(unsigned char crcbuf, unsigned int crc)
{
unsigned char i;
crc = crc ^ crcbuf;
for (i = 0; i < 8; i++)
{
unsigned char chk;
chk = crc & 1;
crc = crc >> 1;
crc = crc & 0x7fff;
if (chk == 1)
crc = crc ^ 0xa001;
crc = crc & 0xffff;
}
return crc;
}
// 计算一串数据的校验码
unsigned int check_crc(unsigned char *buf, unsigned int len)
{
unsigned char hi, lo;
unsigned int i;
unsigned int crc;
crc = 0xFFFF;
for (i = 0; i < len; i++)
{
crc = calccrc(*buf, crc);
buf++;
}
hi = crc % 256;
lo = crc / 256;
crc = (hi << 8) | lo;
return crc;
}
// 删除所有小预览图
void delete_small_jpg()
{
delet_pic("ram/file0.jpg");
usleep(56000);
delet_pic("ram/file1.jpg");
usleep(56000);
delet_pic("ram/file2.jpg");
usleep(56000);
delet_pic("ram/file3.jpg");
usleep(56000);
}
// 发送图片
bool sent_jpg_to_tjc(std::string ram_path, std::string jpg_path)
{
FILE *file;
long filesize;
int file_res = 0;
static int start_time;
struct timeval tv1;
long resent_time;
uint16_t head_id = 0;
uint8_t head_buf[12] = {0x3A, 0xA1, 0xBB, 0x44, 0x7F, 0xFF, 0xFE, 0x01, 0x00, 0x00, 0xDC, 0x07};
uint8_t exit_buf[12] = {0x3A, 0xA1, 0xBB, 0x44, 0x7F, 0xFF, 0xFE, 0x00, 0xFF, 0xFF, 0x00, 0x00};
uint8_t read_buf[BLOCK_SIZE - sizeof(head_buf)] = {0}; // 最大4096 - 帧头
// MKSLOG_BLUE("图片路径为:%s", jpg_path.c_str());
file = fopen(jpg_path.c_str(), "r");
if (file == NULL)
{
MKSLOG_BLUE("文件打开失败");
return true;
}
filesize = getFileSize(file);
// MKSLOG_BLUE("文件大小为: %ld字节", filesize);
// 发送透传指令
send_cmd_twfile(tty_fd, ram_path, std::to_string(filesize));
// 延时等待收到0xfe+结束符
usleep(105000);
// 循环发送包头+4096个数据直到文件结尾
start_time = time(NULL);
while (1)
{
memset(read_buf, 0x00, sizeof(read_buf));
file_res = fread(read_buf, 1, (sizeof(read_buf) - 2), file); // 留两字节存放校验码
// MKSLOG_BLUE("读取大小为: %ld字节", file_res);
if (file_res <= 0)
{
break;
}
// 发送包头
head_buf[8] = head_id & 0xff;
head_buf[9] = head_id >> 8;
head_buf[10] = (file_res+2) & 0xff;
head_buf[11] = (file_res+2) >> 8;
write(tty_fd, head_buf, sizeof(head_buf));
// 打印头数据
// for (int i = 0; i < sizeof(head_buf); i++)
// {
// printf("%02X", head_buf[i]);
// }
// printf("\n");
// 获取校验码,存放在最后两字节
uint16_t crc_val = check_crc(read_buf, file_res);
read_buf[file_res] = crc_val >> 8;
read_buf[file_res + 1] = crc_val & 0xff;
// MKSLOG_BLUE("校验码为: %02X, %02X", crc_val >> 8, crc_val & 0xff);
// tcdrain(tty_fd);
// 发送数据
write(tty_fd, read_buf, file_res+2);
// tcdrain(tty_fd);
// 打印数据
// for (int i = 0; i < file_res+2; i++)
// {
// printf("%02X", read_buf[i]);
// }
// printf("\n");
// 返回0x05表示这一帧写入成功
start_time = time(NULL);
gettimeofday(&tv1, NULL);
resent_time = tv1.tv_sec * 1000 + tv1.tv_usec / 1000;
get_0x05 = false;
get_0xfd = false;
get_0x04 = false;
while (!get_0x05 && !get_0xfd)
{
usleep(80000);
// 返回0x04表示这一帧写入失败
if (get_0x04)
{
// 打印退出透传模式
// tcdrain(tty_fd);
write(tty_fd, exit_buf, sizeof(exit_buf));
// tcdrain(tty_fd);
for (int i = 0; i < sizeof(exit_buf); i++)
{
printf("%02X", exit_buf[i]);
}
printf("\n");
write(tty_fd, exit_buf, sizeof(exit_buf));
// tcdrain(tty_fd);
MKSLOG_GREEN("返回0x04失败");
fclose(file);
return false;
}
// 超时重发机制
gettimeofday(&tv1, NULL);
if (time_differ_ms(800, resent_time) && get_0x24 == false)
{
gettimeofday(&tv1, NULL);
resent_time = tv1.tv_sec * 1000 + tv1.tv_usec / 1000;
// 重发数据帧
write(tty_fd, head_buf, sizeof(head_buf));
// tcdrain(tty_fd);
write(tty_fd, read_buf, file_res+2);
MKSLOG_GREEN("返回超时,重发数据包");
}
// 超时机制
if (time_differ(4, start_time))
{
write(tty_fd, exit_buf, sizeof(exit_buf));
for (int i = 0; i < sizeof(exit_buf); i++)
{
printf("%02X", exit_buf[i]);
}
printf("\n");
write(tty_fd, exit_buf, sizeof(exit_buf));
// tcdrain(tty_fd);
write(tty_fd, exit_buf, sizeof(exit_buf));
// tcdrain(tty_fd);
MKSLOG_GREEN("写数据帧超时,失败");
fclose(file);
return false;
}
// CLL 缓冲区溢出时停止发送
if (get_0x24 == true) {
sleep(4);
get_0x24 = false;
return false;
}
}
// 修改包头ID
head_id++;
// 超时机制
if (time_differ(6, start_time))
{
write(tty_fd, exit_buf, sizeof(exit_buf));
for (int i = 0; i < sizeof(exit_buf); i++)
{
printf("%02X", exit_buf[i]);
}
printf("\n");
write(tty_fd, exit_buf, sizeof(exit_buf));
write(tty_fd, exit_buf, sizeof(exit_buf));
MKSLOG_GREEN("写图片超时,失败");
fclose(file);
break;
}
}
MKSLOG_GREEN("成功写入图片到内存");
fclose(file);
return true;
}
void printHex(const uint8_t *data, size_t size) {
for (size_t i = 0; i < size; ++i) {
printf("%02X", data[i]);
}
// printf("\n");
}
// bool mks_send_jpg(char *path, int fd, int index) {
// // FILE *input_file, *output_file;
// FILE *input_file;
// uint8_t head_buf[HEADER_SIZE] = {0x3A, 0xA1, 0xBB, 0x44, 0x7F, 0xFF, 0xFE, 0x00, 0x00, 0x00, 0xDC, 0x07};
// uint8_t exit_buf[12] = {0x3A, 0xA1, 0xBB, 0x44, 0x7F, 0xFF, 0xFE, 0x00, 0xFF, 0xFF, 0x00, 0x00};
// uint8_t buffer[BLOCK_SIZE - HEADER_SIZE]; // 数据块的大小减去帧头的大小
// size_t bytes_read;
// long file_size;
// uint16_t head_id = 0;
// input_file = fopen(path, "rb");
// if (input_file == NULL) {
// perror("Error opening input file");
// return false;
// }
// // 获取文件大小
// fseek(input_file, 0, SEEK_END);
// file_size = ftell(input_file);
// fseek(input_file, 0, SEEK_SET);
// // char cmd[32];
// // sprintf(cmd, "twfile \"ram/file%d.jpg\",%ld\xff\xff\xff", index, file_size);
// // write(fd, cmd, sizeof(cmd));
// // usleep(100000);
// char ram_path[32];
// sprintf(ram_path, "ram/file%d.jpg", index);
// std::string to_out = ram_path;
// send_cmd_twfile(fd, to_out, std::to_string(file_size));
/*
sleep(5);
// 逐块读取输入文件,动态拼接帧头和数据,然后写入输出文件
while ((bytes_read = fread(buffer, 1, sizeof(buffer), input_file)) > 0) {
head_buf[8] = head_id & 0xff;
head_buf[9] = head_id >> 8;
head_buf[10] = bytes_read & 0xff;
head_buf[11] = bytes_read >> 8;
// 写入帧头
write(fd, head_buf, sizeof(head_buf));
tcdrain(fd);
// 写入读取的数据块
write(fd, buffer, bytes_read);
// 写入帧头
// fwrite(head_buf, 1, sizeof(head_buf), output_file);
// 写入读取的数据块
// fwrite(buffer, 1, bytes_read, output_file);
printf("Hexadecimal content written:\n");
printHex(head_buf, sizeof(head_buf));
printHex(buffer, bytes_read);
printf("\n");
head_id++;
usleep(2000000);
}
*/
// static int start_time;
// struct timeval tv1;
// long resent_time;
// start_time = time(NULL);
// while (1) {
// bytes_read = fread(buffer, 1, sizeof(buffer), input_file);
// head_buf[8] = head_id & 0xff;
// head_buf[9] = head_id >> 8;
// head_buf[10] = bytes_read & 0xff;
// head_buf[11] = bytes_read >> 8;
// write(fd, head_buf, sizeof(head_buf));
// tcdrain(fd);
// write(fd, buffer, bytes_read);
// printf("Hexadecimal content written:\n");
// printHex(head_buf, sizeof(head_buf));
// printHex(buffer, bytes_read);
// printf("\n");
// // 返回0x05表示这一帧写入成功
// start_time = time(NULL);
// gettimeofday(&tv1, NULL);
// resent_time = tv1.tv_sec * 1000 + tv1.tv_usec / 1000;
// get_0x05 = false;
// get_0xfd = false;
// get_0x04 = false;
// while (!get_0x05 && !get_0xfd)
// {
// usleep(100000);
// // 返回0x04表示这一帧写入失败
// if (get_0x04)
// {
// // 打印退出透传模式
// write(fd, exit_buf, sizeof(exit_buf));
// for (int i = 0; i < sizeof(exit_buf); i++)
// {
// printf("%02X", exit_buf[i]);
// }
// printf("\n");
// write(fd, exit_buf, sizeof(exit_buf));
// MKSLOG_YELLOW("返回0x04失败");
// fclose(input_file);
// return false;
// }
// // 超时重发机制
// gettimeofday(&tv1, NULL);
// if (time_differ_ms(6000, resent_time))
// {
// gettimeofday(&tv1, NULL);
// resent_time = tv1.tv_sec * 1000 + tv1.tv_usec / 1000;
// // 重发数据帧
// write(fd, head_buf, sizeof(head_buf));
// write(fd, buffer, bytes_read);
// MKSLOG_YELLOW("返回超时,重发数据包");
// }
// // 超时机制
// if (time_differ(3, start_time))
// {
// write(fd, exit_buf, sizeof(exit_buf));
// for (int i = 0; i < sizeof(exit_buf); i++)
// {
// printf("%02X", exit_buf[i]);
// }
// printf("\n");
// write(fd, exit_buf, sizeof(exit_buf));
// write(fd, exit_buf, sizeof(exit_buf));
// MKSLOG_YELLOW("写数据帧超时,失败");
// fclose(input_file);
// return false;
// }
// }
// head_id++;
// // 超时机制
// if (time_differ(10, start_time))
// {
// write(fd, exit_buf, sizeof(exit_buf));
// for (int i = 0; i < sizeof(exit_buf); i++)
// {
// printf("%02X", exit_buf[i]);
// }
// printf("\n");
// write(fd, exit_buf, sizeof(exit_buf));
// write(fd, exit_buf, sizeof(exit_buf));
// MKSLOG_YELLOW("写图片超时,失败");
// fclose(input_file);
// break;
// }
// }
// // 关闭文件
// fclose(input_file);
// MKSLOG_YELLOW("成功写入图片到内存");
// printf("File processing complete.\n");
// return true;
// }
// bool begin_show_64_jpg;
// bool begin_show_160_jpg;
// bool begin_show_192_jpg;
// bool show_192_jpg_complete = true;
// bool have_64_jpg[4];
// void *sent_jpg_thread_handle(void *arg) {
// std::string png_path = "";
// std::string ram_path = "";
// std::string jpg_path = "";
// while (1) {
// // 刷新小预览图
// if (begin_show_64_jpg) {
// begin_show_64_jpg = false;
// for (uint i = 0; i < 4; i++) {
// if (have_64_jpg[i] == true) {
// /*
// if (mks_send_jpg(jpg_path.c_str(), tty_fd, i) != false) {
// }
// */
// }
// }
// }
// usleep(50000);
// }
// }

View File

@@ -1,644 +0,0 @@
#include "../include/mks_log.h"
#include "../include/send_msg.h"
#include "../include/MakerbaseSerial.h"
extern int copy_fd;
// 刷新页面
void send_cmd_page(int fd, std::string pageid) {
std::string cmd = "page " + pageid + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 重绘控件
void send_cmd_ref(int fd, std::string obj) {
std::string cmd = "ref " + obj + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 激活控件按下/弹起事件
void send_cmd_click(int fd, std::string obj, std::string event) {
std::string cmd = "click " + obj + "," + event + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), sizeof(cmd));
}
// 带格式获取变量值/常量值
void send_cmd_get(int fd, std::string att) {
std::string cmd = "get " + att + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 从串口打印一个变量/常量
void send_cmd_prints(int fd, std::string att, int lenth = 0) {
std::string cmd = "prints " + att + "," + std::to_string(lenth) + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 隐藏/显示控件
void send_cmd_vis(int fd, std::string obj, std::string state) {
std::string cmd = "vis " + obj + "," + state + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 控件触摸使能
void send_cmd_tsw(int fd, std::string obj, std::string state) {
std::string cmd = "tsw " + obj + "," + state + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 随机数范围设置
void send_cmd_randset(int fd, std::string minval, std::string maxval) {
std::string cmd = "randset " + minval + "," + maxval + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 往曲线控件添加数据
void send_cmd_add(int fd, std::string objid, std::string ch, std::string val) {
std::string cmd = "add " + objid + "," + ch + "," + val + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 清除曲线控件中的数据
void send_cmd_cle(int fd, std::string objid, std::string ch) {
std::string cmd = "cle " + objid + "," + ch + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 曲线数据透传指令
void send_cmd_addt(int fd, std::string objid, std::string ch, std::string qyt) {
std::string cmd = "addt " + objid + "," + ch + "," + qyt + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 转让系统控制权给屏幕刷新
void send_cmd_doevents(int fd) {
std::string cmd = "doevents\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 发送当前页面ID号到串口
void send_cmd_sendme(int fd) {
std::string cmd = "sendme\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 变量类型转换
void send_cmd_covx(int fd, std::string att1, std::string att2, std::string lenth) {
std::string cmd = "covx " + att1 + "," + att2 + "," + lenth + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 字符串变量字符长度测试
void send_cmd_strlen(int fd, std::string att0, std::string att1) {
std::string cmd = "strlen " + att0 + "," + att1 + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 字符串变量字节长度测试
void send_cmd_btlen(int fd, std::string att0, std::string att1) {
std::string cmd = "btlen " + att0 + "," + att1 + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 字符串截取
void send_cmd_substr(int fd, std::string att0, std::string att1, std::string star, std::string lenth) {
std::string cmd = "substr " + att0 + "," + att1 + "," + star + "," + lenth + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 字符串分割
void send_cmd_spstr(int fd, std::string src, std::string dec, std::string key, std::string indec) {
std::string cmd = "spstr " + src + "," + dec + "," + key + "," + indec + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 触摸校准
void send_cmd_touch_j(int fd) {
std::string cmd = "touch_j\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 暂停屏幕刷新
void send_cmd_ref_stop(int fd) {
std::string cmd = "ref_stop\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 恢复屏幕刷新
void send_cmd_ref_star(int fd) {
std::string cmd = "ref_star\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 暂停串口指令执行
void send_cmd_com_stop(int fd) {
std::string cmd = "com_stop\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 恢复串口指令执行
void send_cmd_com_star(int fd) {
std::string cmd = "com_star\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 清空串口指令缓冲区
void send_cmd_code_c(int fd) {
std::string cmd = "code_c\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 复位
void send_cmd_rest(int fd) {
std::string cmd = "rest\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 写入一个变量到用户存储区
void send_cmd_wepo(int fd, std::string att, std::string add) {
std::string cmd = "wepo " + att + "," + add + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 从用户存储区读数据到变量
void send_cmd_repo(int fd, std::string att, std::string add) {
std::string cmd = "repo " + att + "," + add + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 透传数据写入用户存储区
void send_cmd_wept(int fd, std::string add, std::string lenth) {
std::string cmd = "wept " + add + "," + lenth + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 从用户存储区透传数据到串口
void send_cmd_rept(int fd, std::string add, std::string lenth) {
std::string cmd = "rept " + add + "," + lenth + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 扩展IO模式配置
void send_cmd_cfgpio(int fd, std::string id, std::string state, std::string obj) {
std::string cmd = "cfgpio " + id + "," + state + "," + obj + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 复位crc初始值
void send_cmd_crcrest(int fd, std::string crctype, std::string initval) {
std::string cmd = "crcrest " + crctype + "," + initval + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// crc校验一个变量/常量
void send_cmd_crcputs(int fd, std::string att, std::string length) {
std::string cmd = "crcputs " + att + "," + length + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// crc校验一组Hex
void send_cmd_crcputh(int fd, std::string hex) {
std::string cmd = "crcputh " + hex + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// crc校验一段串口缓冲区数据(recmod=1时有效)
void send_cmd_crcputu(int fd, std::string star, std::string length) {
std::string cmd = "crcputu " + star + "," + length + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 运行中改变控件图层顺序(仅X3,X5系列支持)
void send_cmd_setlayer(int fd, std::string obj0, std::string obj1) {
std::string cmd = "setplayer " + obj0 + "," + obj1 + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 控件移动 (仅X3,X5系列支持)
void send_cmd_move(int fd, std::string obj, std::string startx, std::string starty, std::string endx, std::string endy, std::string first, std::string time) {
std::string cmd = "move " + obj + "," + startx + "," + starty + "," + endx + "," + endy + "," + first + "," + time + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 音频播放 (仅X3,X5系列支持)
void send_cmd_play(int fd, std::string ch, std::string audio, std::string loop) {
std::string cmd = "play " + ch + "," + audio + "," + loop + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 串口透传文件 (仅X3,X5系列支持)
void send_cmd_twfile(int fd, std::string filepath, std::string filesize) {
std::string cmd = "twfile \"" + filepath + "\"," + filesize + "\xff\xff\xff";
MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 删除文件 (仅X3,X5系列支持)
void send_cmd_delfile(int fd, std::string filepath) {
std::string cmd = "delfile \"" + filepath + "\"\xff\xff\xff";
MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 重命名文件 (仅X3,X5系列支持)
void send_cmd_refile(int fd, std::string srcfilepath, std::string decfilepath) {
std::string cmd = "refile " + srcfilepath + "," + decfilepath + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 查找文件 (仅X3,X5系列支持)
void send_cmd_findfile(int fd, std::string filepath, std::string att) {
std::string cmd = "findfile " + filepath + "," + att + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 透传读文件 (仅X3,X5系列支持)
void send_cmd_rdfile(int fd, std::string filepath, std::string addr, std::string size, std::string crc) {
std::string cmd = "rdfile " + filepath + "," + addr + "," + size + "," + crc + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 创建文件 (仅X3,X5系列支持)
void send_cmd_newfile(int fd, std::string filepath, std::string size) {
std::string cmd = "newfile " + filepath + "," + size + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 创建文件夹 (仅X3,X5系列支持)
void send_cmd_newdir(int fd, std::string dir) {
std::string cmd = "newdir " + dir + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 删除文件夹 (仅X3,X5系列支持)
void send_cmd_deldir(int fd, std::string dir) {
std::string cmd = "deldir " + dir + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 重命名文件夹 (仅X3,X5系列支持)
void send_cmd_redir(int fd, std::string srcdir, std::string decdir) {
std::string cmd = "redir " + srcdir + "," + decdir + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 查找文件夹 (仅X3,X5系列支持)
void send_cmd_finddir(int fd, std::string dir, std::string att) {
std::string cmd = "finddir " + dir + "," + att + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 蜂鸣器 (仅X2系列支持)
void send_cmd_beep(int fd, std::string time) {
std::string cmd = "beep " + time + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 更改控件显示文本
void send_cmd_txt(int fd, std::string obj, std::string txt) {
std::string cmd = obj + ".txt=" + "\"" + txt + "\"" + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 更改控件显示图片
void send_cmd_pic(int fd, std::string obj, std::string pic) {
std::string cmd = obj + ".pic=" + pic + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_picc(int fd, std::string obj, std::string picc) {
std::string cmd = obj + ".picc=" + picc + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_picc2(int fd, std::string obj, std::string picc) {
std::string cmd = obj + ".picc2=" + picc + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 修改变量的值
void send_cmd_val(int fd, std::string obj, std::string val) {
std::string cmd = obj + ".val=" + val + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 修改颜色
void send_cmd_pco(int fd, std::string obj, std::string poc) {
std::string cmd = obj + ".pco=" + poc + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_pco2(int fd, std::string obj, std::string poc2) {
std::string cmd = obj + ".pco2=" + poc2 + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
// 修改背景图片
void send_cmd_bpic(int fd, std::string obj, std::string bpic) {
std::string cmd = obj + ".bpic=" + bpic + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_cp(int fd, std::string obj) {
std::string cp0 = obj + ".write(\"";
tcdrain(fd);
write(fd, cp0.data(), cp0.length());
}
void send_cmd_vid(int fd, std::string obj, std::string vid) {
std::string cmd = obj + ".vid=" + vid + "\xff\xff\xff";
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_cp_write(int fd, std::string obj, std::string data) {
// std::string cmd = obj + ".write(\"" + data + "\")\xff\xff\xff";
// std::string cp0 = obj + ".write(\"";
// std::string end = "\")\xff\xff\xff";
// write(fd, cp0.data(), cp0.length());
tcdrain(fd);
write(fd, data.data(), data.length());
// write(fd, end.data(), end.length());
// write(fd, cmd.data(), cmd.length());
}
void send_cmd_cp_end(int fd) {
std::string end = "\")\xff\xff\xff";
tcdrain(fd);
write(fd, end.data(), end.length());
}
void send_cmd_cp_close(int fd, std::string obj) {
std::string cmd = obj + ".close()\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_byte_data(int fd, char data) {
char buff[1];
buff[0] = data;
tcdrain(fd);
write(fd, buff, 1);
}
void send_cmd_write(int fd, std::string obj) {
std::string cmd = obj + ".write(\"";
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_write_end(int fd) {
std::string cmd = "\")\xff\xff\xff";
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_cp_image(int fd, std::string obj, std::string image) {
send_cmd_write(fd, obj);
tcdrain(fd);
write(fd, image.data(), image.length());
// MKSLOG_RED("写入图片");
/*
for (int i = 0; i < image.length(); i++) {
send_cmd_byte_data(fd, static_cast<char>(image[i]));
}
*/
send_cmd_write_end(fd);
}
void send_cmd_txt_start(int fd, std::string obj) {
std::string cmd = obj + ".txt=\"";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_txt_data(int fd, std::string txt) {
tcdrain(fd);
write(fd, txt.data(), txt.length());
}
void send_cmd_txt_end(int fd) {
std::string cmd = "\"\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_txt_plus(int fd, std::string obj1, std::string obj2, std::string obj3) {
std::string cmd = obj1 + ".txt=" + obj2 + ".txt+" + obj3 + ".txt\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_download(int fd, int filesize) {
std::string cmd = "whmi-wri " + std::to_string(filesize) + ",115200,0\xff\xff\xff";
// std::string cmd = "whmi-wri " + std::to_string(filesize) + ",9600,0\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
// set_option(fd, 230400, 8, 'N', 1);
}
void send_cmd_download_data(int fd, std::string data) {
// write(fd, data.data(), data.length());
// write(copy_fd, data.data(), data.length());
// int num = 1024;
int num = 512;
int len = data.length();
int end = num;
std::string sub_data;
for (int start = 0; start < len; ) {
if (end > len) {
sub_data = data.substr(start, len - start);
write(fd, sub_data.data(), sub_data.length());
// write(copy_fd, sub_data.data(), sub_data.length());
// set_option(fd, 115200, 8, 'N', 1);
break;
}
sub_data = data.substr(start, num);
write(fd, sub_data.data(), sub_data.length());
start = end;
end = end + num;
MKSLOG_BLUE("发送下载数据");
// usleep(45000);
// usleep(25000);
}
// write(fd, data.data(), data.length());
// usleep(5000);
/*
std::string data_1 = data.substr(0, 512);
std::string data_2 = data.substr(512, 1024);
std::string data_3 = data.substr(1024, 1536);
std::string data_4 = data.substr(1536, 2048);
std::string data_5 = data.substr(2048, 2560);
std::string data_6 = data.substr(2560, 3072);
std::string data_7 = data.substr(3072, 3584);
std::string data_8 = data.substr(3584, 4096);
*/
// write(fd, data.data(), data.length());
// usleep(500);
// write(fd, data_1.data(), data.length());
// usleep(50000);
// write(fd, data_2.data(), data.length());
// usleep(50000);
// write(fd, data_3.data(), data.length());
// usleep(50000);
// write(fd, data_4.data(), data.length());
// usleep(50000);
// write(fd, data_5.data(), data.length());
// usleep(50000);
// write(fd, data_6.data(), data.length());
// usleep(50000);
// write(fd, data_7.data(), data.length());
// usleep(50000);
// write(fd, data_8.data(), data.length());
// usleep(50000);
}
void send_cmd_vid_en(int fd, std::string obj, int value) {
std::string cmd = obj + ".en=" + std::to_string(value) + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_bauds(int fd, int bauds) {
std::string cmd = "bauds=" + std::to_string(bauds) + "\xff\xff\xff";
// MKSLOG_YELLOW("%s", cmd.data());
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_cmd_baud(int fd, int baud) {
std::string cmd = "baud=" + std::to_string(baud) + "\xff\xff\xff";
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}
void send_var_value(int fd, std::string var, int value) {
std::string cmd = var + "=" + std::to_string(value) + "\xff\xff\xff";
tcdrain(fd);
write(fd, cmd.data(), cmd.length());
}

2543
src/ui.cpp

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +0,0 @@
[version]
mcu = V0.10.0
ui = V4.4.14
soc = V4.4.14