id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,532,815
atomic_map.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_map.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct atomic_map final : public discrete_timed_state<X, data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; using function_t = std::function<data_set_t(const input_t &)>; data_mgr_t manager; data_set_t value; std::vector<node_ptr_t> mappings; explicit atomic_map(const data_mgr_t &mgr, const std::vector<node_ptr_t> &nodeptrs) : manager(mgr), value(mgr->zero()), mappings(nodeptrs) {} explicit atomic_map(const kwargs &kw) : atomic_map(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} void update(const input_t &args, time_t now) override { value = mappings[0]->output(now); for (std::size_t i = 1; i < mappings.size(); i++) { value *= mappings[i]->output(now); } } output_t output(time_t) override { return value; } }; } // namespace untimed_data_setting } // namespace reelay
1,781
C++
.h
47
34.234043
79
0.681977
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,816
atomic_gt.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_gt.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_gt final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; double constant; explicit atomic_gt(const data_mgr_t &mgr, const key_t &k, const std::string &c) : manager(mgr), value(mgr->zero()), key(k), constant(std::stod(c)) {} explicit atomic_gt(const kwargs &kw) : atomic_gt(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key")), reelay::any_cast<std::string>(kw.at("constant"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } double new_data = datafield<input_t>::as_floating(args, key); if (new_data > constant) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace dense_timed_setting } // namespace reelay
1,781
C++
.h
51
30.54902
79
0.66161
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,817
atomic_list.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_list.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct atomic_list final : public discrete_timed_state<X, data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; data_mgr_t manager; data_set_t value; std::vector<node_ptr_t> listings; explicit atomic_list(const data_mgr_t &mgr, const std::vector<node_ptr_t> &nodeptrs) : manager(mgr), value(mgr->zero()), listings(nodeptrs) {} explicit atomic_list(const kwargs &kw) : atomic_list(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} void update(const input_t &args, time_t now) override { if(args.size() != listings.size()){ value = manager->zero(); return; } else { value = listings[0]->output(now); for (std::size_t i = 1; i < listings.size(); i++) { value *= listings[i]->output(now); } } } output_t output(time_t) override { return value; } }; } // namespace untimed_data_setting } // namespace reelay
1,717
C++
.h
49
30.959184
80
0.665459
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,818
previous.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/previous.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "memory" #include "vector" #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct previous final : public discrete_timed_state<X, data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; data_mgr_t manager; node_ptr_t first; data_set_t prev_value; data_set_t value; explicit previous(const data_mgr_t &mgr, const std::vector<node_ptr_t> &args) : manager(mgr), first(args[0]) { prev_value = mgr->zero(); value = mgr->zero(); } explicit previous(const kwargs &kw) : previous(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} void update(const input_t &, time_t now) override { prev_value = value; value = first->output(now); } output_t output(time_t now) override { return prev_value; } }; } // namespace discrete_timed_setting } // namespace reelay
1,559
C++
.h
44
32.113636
79
0.689333
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,819
past_sometime.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/past_sometime.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct past_sometime final : public discrete_timed_state<X, data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; data_mgr_t manager; output_t value; node_ptr_t first; explicit past_sometime(const data_mgr_t &mgr, const std::vector<node_ptr_t> &args) : manager(mgr), value(mgr->zero()), first(args[0]) {} explicit past_sometime(const kwargs &kw) : past_sometime( reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} void update(const input_t &, time_t now) { value += first->output(now); } output_t output(time_t) { return value; } }; } // namespace discrete_timed_setting } // namespace reelay
1,497
C++
.h
40
33.525
76
0.680055
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,820
disjunction.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/disjunction.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct disjunction final : public discrete_timed_node<data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; std::vector<node_ptr_t> args; explicit disjunction(const std::vector<node_ptr_t> &nodeptrs) : args(nodeptrs) {} explicit disjunction(const kwargs &kw) : disjunction(reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} output_t output(time_t now) { output_t result = args[0]->output(now); for (size_t i = 1; i < args.size(); i++) { result += args[i]->output(now); } return result; } }; } // namespace discrete_timed_robustness_setting } // namespace reelay
1,415
C++
.h
40
32.45
80
0.697947
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,821
atomic_le.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_le.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_le final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; double constant; explicit atomic_le(const data_mgr_t &mgr, const key_t &k, const std::string &c) : manager(mgr), value(mgr->zero()), key(k), constant(std::stod(c)) {} explicit atomic_le(const kwargs &kw) : atomic_le(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key")), reelay::any_cast<std::string>(kw.at("constant"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } double new_data = datafield<input_t>::as_floating(args, key); if (new_data <= constant) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,776
C++
.h
51
30.490196
79
0.661017
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,822
exists.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/exists.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct exists final : public discrete_timed_node<data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; node_ptr_t arg1; data_set_t cube; exists(const data_mgr_t &mgr, const std::vector<std::string> &vars, const std::vector<node_ptr_t> &args) : arg1(args[0]) { cube = mgr->one(); for (const auto &name : vars) { cube *= mgr->variables[name].cube; } } exists(const kwargs &kw) : exists(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<std::vector<std::string>>(kw.at("vars")), reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} output_t output(time_t now) override { data_set_t value = arg1->output(now); return value.ExistAbstract(cube); } }; } // namespace untimed_data_setting } // namespace reelay
1,624
C++
.h
46
31.413043
75
0.670708
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,823
conjunction.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/conjunction.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct conjunction final : public discrete_timed_node<data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; std::vector<node_ptr_t> args; explicit conjunction(const std::vector<node_ptr_t> &nodeptrs) : args(nodeptrs) {} explicit conjunction(const kwargs &kw) : conjunction(reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} output_t output(time_t now) { output_t result = args[0]->output(now); for (size_t i = 1; i < args.size(); i++) { result *= args[i]->output(now); } return result; } }; } // namespace discrete_timed_robustness_setting } // namespace reelay
1,415
C++
.h
40
32.45
80
0.697947
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,824
atomic_any.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_any.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_any final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; explicit atomic_any(const data_mgr_t &mgr, const key_t &key) : manager(mgr), value(mgr->one()), key(key) {} explicit atomic_any(const kwargs &kw) : atomic_any(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key"))) {} void update(const input_t &args, time_t now) override { bool key_exists = datafield<input_t>::contains(args, key); if (key_exists) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace discrete_timed_data_setting } // namespace reelay
1,474
C++
.h
44
30.181818
73
0.68358
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,825
atomic_ge.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_ge.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_ge final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; double constant; explicit atomic_ge(const data_mgr_t &mgr, const key_t &k, const std::string &c) : manager(mgr), value(mgr->zero()), key(k), constant(std::stod(c)) {} explicit atomic_ge(const kwargs &kw) : atomic_ge(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key")), reelay::any_cast<std::string>(kw.at("constant"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } double new_data = datafield<input_t>::as_floating(args, key); if (new_data >= constant) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,776
C++
.h
51
30.490196
79
0.661017
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,826
implication.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/implication.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T> struct implication final : public discrete_timed_node<data_set_t, T> { using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; using node_t = discrete_timed_node<output_t, time_t>; using state_t = discrete_timed_state<input_t, output_t, time_t>; using node_ptr_t = std::shared_ptr<node_t>; using state_ptr_t = std::shared_ptr<state_t>; node_ptr_t arg1; node_ptr_t arg2; explicit implication(const std::vector<node_ptr_t> &args) : arg1(args[0]), arg2(args[1]) {} explicit implication(const kwargs &kw) : implication(reelay::any_cast<std::vector<node_ptr_t>>(kw.at("args"))) {} output_t output(time_t now) { return ~arg1->output(now) + arg2->output(now);} }; } // namespace discrete_timed_robustness_setting } // namespace reelay
1,321
C++
.h
35
35.171429
80
0.713725
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,827
atomic_false.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_false.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_false final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; explicit atomic_false(const data_mgr_t &mgr, const key_t &key) : manager(mgr), value(mgr->zero()), key(key) {} explicit atomic_false(const kwargs &kw) : atomic_false(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } bool new_data = datafield<input_t>::as_bool(args, key); if (new_data) { value = manager->zero(); } else { value = manager->one(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,613
C++
.h
47
30.723404
79
0.679124
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,828
atomic_prop.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_prop.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_prop final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; explicit atomic_prop(const data_mgr_t &mgr, const key_t &key) : manager(mgr), value(mgr->zero()), key(key) {} explicit atomic_prop(const kwargs &kw) : atomic_prop(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } bool new_data = datafield<input_t>::as_bool(args, key); if (new_data) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,590
C++
.h
46
30.934783
79
0.677778
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,829
atomic_ne.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_ne.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_ne final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; double constant; explicit atomic_ne(const data_mgr_t &mgr, const key_t &k, const std::string &c_str) : manager(mgr), value(mgr->zero()), key(k), constant(std::stod(c_str)) {} explicit atomic_ne(const kwargs &kw) : atomic_ne(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key")), reelay::any_cast<std::string>(kw.at("constant"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } double new_data = datafield<input_t>::as_floating(args, key); if (new_data != constant) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,784
C++
.h
51
30.647059
79
0.661431
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,830
atomic_string.hpp
doganulus_reelay/include/reelay/settings/discrete_timed_data/atomic_string.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <vector> #include "reelay/common.hpp" #include "reelay/datafield.hpp" #include "reelay/networks/basic_structure.hpp" #include "reelay/unordered_data.hpp" namespace reelay { namespace discrete_timed_data_setting { template <typename X, typename T, typename K = std::string> struct atomic_string final : public discrete_timed_state<X, data_set_t, T> { using key_t = K; using time_t = T; using input_t = X; using value_t = data_set_t; using output_t = data_set_t; data_mgr_t manager; data_set_t value; key_t key; std::string constant; explicit atomic_string(const data_mgr_t &mgr, const key_t &k, const std::string &c) : manager(mgr), value(mgr->zero()), key(k), constant(c) {} explicit atomic_string(const kwargs &kw) : atomic_string(reelay::any_cast<data_mgr_t>(kw.at("manager")), reelay::any_cast<key_t>(kw.at("key")), reelay::any_cast<std::string>(kw.at("constant"))) {} void update(const input_t &args, time_t now) override { if (not datafield<input_t>::contains(args, key)) { return; // Do nothing if the key does not exist - existing value persists } std::string new_data = datafield<input_t>::as_string(args, key); if (new_data == constant) { value = manager->one(); } else { value = manager->zero(); } } output_t output(time_t) override { return value; } }; } // namespace untimed_setting } // namespace reelay
1,775
C++
.h
49
31.673469
79
0.660631
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,831
json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/json/condensing_json_formatter.hpp" #include "reelay/formatters/json/dense_timed_data_json_formatter.hpp" #include "reelay/formatters/json/dense_timed_json_formatter.hpp" #include "reelay/formatters/json/dense_timed_robustness_json_formatter.hpp" #include "reelay/formatters/json/discrete_timed_json_formatter.hpp"
607
C++
.h
13
45.153846
75
0.782462
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,832
formatter.hpp
doganulus_reelay/include/reelay/formatters/formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once namespace reelay { template <typename TimeT, typename ValueT, typename OutputT, bool condensing> struct discrete_timed_formatter {}; template <typename TimeT, typename ValueT, typename OutputT> struct dense_timed_formatter {}; template <typename TimeT, typename ValueT, typename OutputT> struct dense_timed_robustness_formatter {}; template <typename TimeT, typename ValueT, typename OutputT> struct dense_timed_data_formatter {}; } // namespace reelay
723
C++
.h
18
38.5
77
0.776824
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,833
python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/python/condensing_python_formatter.hpp" #include "reelay/formatters/python/dense_timed_data_python_formatter.hpp" #include "reelay/formatters/python/dense_timed_python_formatter.hpp" #include "reelay/formatters/python/dense_timed_robustness_python_formatter.hpp" #include "reelay/formatters/python/discrete_timed_python_formatter.hpp"
627
C++
.h
13
46.692308
79
0.78956
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,834
condensing_json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json/condensing_json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/json.hpp" #include "reelay/intervals.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename ValueT> struct discrete_timed_formatter<TimeT, ValueT, json, true> { using time_t = TimeT; using value_t = ValueT; using output_t = json; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; value_t lastval = std::numeric_limits<value_t>::lowest(); std::string t_name; std::string y_name; explicit discrete_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) {} explicit discrete_timed_formatter(const basic_options& options) : discrete_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) {} inline output_t now(time_t now) { return json({{t_name, now}}); } inline output_t format(value_t result, time_t now) { if (result != lastval or now == 0) { lastval = result; return json({{t_name, now}, {y_name, result}}); } else { lastval = result; return json({}); // Empty JSON object {} } } }; } // namespace reelay
1,507
C++
.h
44
30.704545
76
0.678596
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,835
dense_timed_robustness_json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json/dense_timed_robustness_json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/json.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename ValueT> struct dense_timed_robustness_formatter<TimeT, ValueT, json> { using time_t = TimeT; using value_t = ValueT; using output_t = json; using interval = reelay::interval<time_t>; using interval_map = reelay::robustness_interval_map<time_t, value_t>; std::string t_name; std::string y_name; value_t lastval = false; explicit dense_timed_robustness_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) {} explicit dense_timed_robustness_formatter(const basic_options& options) : dense_timed_robustness_formatter( options.get_time_field_name(), options.get_value_field_name()) {} inline output_t now(time_t now) { return json({{t_name, now}}); } inline output_t format( const interval_map& result, time_t previous, time_t now) { output_t vresult; for (const auto& intv : result) { if (lastval != intv.second or now == 0) { vresult.push_back( json({{t_name, intv.first.lower()}, {y_name, intv.second}})); lastval = intv.second; } } return vresult; } }; } //namespace reelay
1,620
C++
.h
47
30.489362
76
0.681818
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,836
dense_timed_data_json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json/dense_timed_data_json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/json.hpp" #include "reelay/unordered_data.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT> struct dense_timed_data_formatter<TimeT, bool, json> { using time_t = TimeT; using value_t = bool; using output_t = json; using interval = reelay::interval<time_t>; using interval_map = reelay::data_interval_map<time_t>; data_mgr_t manager; std::string t_name; std::string y_name; bool lastval = false; explicit dense_timed_data_formatter( const data_mgr_t& mgr, const std::string& t_str = "time", const std::string& y_str = "value") : manager(mgr), t_name(t_str), y_name(y_str) {} explicit dense_timed_data_formatter(const basic_options& options) : dense_timed_data_formatter( options.get_data_manager(), options.get_time_field_name(), options.get_value_field_name()) {} inline output_t now(time_t now) { return json({{t_name, now}}); } inline output_t format(const interval_map& result, time_t previous, time_t now) { output_t vresult; for (const auto& intv : result) { bool value = (intv.second != manager->zero()); if (lastval != value or now == 0) { vresult.push_back(json({{t_name, intv.first.lower()}, {y_name, value}})); lastval = value; } } return vresult; } }; } //namespace reelay
1,732
C++
.h
51
29.705882
81
0.668465
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,837
discrete_timed_json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json/discrete_timed_json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/json.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename ValueT> struct discrete_timed_formatter<TimeT, ValueT, json, false> { using time_t = TimeT; using value_t = ValueT; using output_t = json; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; value_t lastval = std::numeric_limits<value_t>::lowest(); std::string t_name; std::string y_name; explicit discrete_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) {} explicit discrete_timed_formatter(const basic_options& options) : discrete_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) {} inline output_t now(time_t now) { return json({{t_name, now}}); } inline output_t format(value_t result, time_t now) { return json({{y_name, result}}); } }; } // namespace reelay
1,336
C++
.h
38
32.026316
76
0.701632
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,838
dense_timed_json_formatter.hpp
doganulus_reelay/include/reelay/formatters/json/dense_timed_json_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/json.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT> struct dense_timed_formatter<TimeT, bool, json> { using time_t = TimeT; using value_t = bool; using output_t = json; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; std::string t_name; std::string y_name; bool lastval = false; explicit dense_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) {} explicit dense_timed_formatter(const basic_options& options) : dense_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) {} inline output_t now(time_t now) { return json({{t_name, now}}); } output_t format(const interval_set& result, time_t previous, time_t now) { if (now == 0) { return _init_0(result, previous, now); } else if (previous == 0) { return _init_1(result, previous, now); } else { return _format(result, previous, now); } } output_t _init_0(const interval_set& result, time_t previous, time_t now) { // This code takes care of the special case of time zero // HERE: time_t now = 0 return std::vector<reelay::json>(); } output_t _init_1(const interval_set& result, time_t previous, time_t now) { // This code takes care of the special case of the first segment // The variable `lastval` is meaningless for the first segment // HERE: The first segment ranges from previous=0 to now auto vresult = std::vector<reelay::json>(); if (result.empty()) { vresult.push_back(json({{t_name, previous}, {y_name, false}})); lastval = false; } else { if (result.begin()->lower() != previous) { vresult.push_back(json({{t_name, previous}, {y_name, false}})); lastval = false; } for (const auto& intv : result) { vresult.push_back(json({{t_name, intv.lower()}, {y_name, true}})); lastval = true; if (intv.upper() != now) { vresult.push_back(json({{t_name, intv.upper()}, {y_name, false}})); lastval = false; } } } return vresult; } inline output_t _format( const interval_set& result, time_t previous, time_t now) { // This code constitutes the main operation such that // + do output two events per interval in the set // + take care empty interval set (meaning all false) // + do not output if it is the same value with the last value (lastval) // + do not output for the current point (now) as it may be not finished auto vresult = std::vector<reelay::json>(); if (result.empty()) { if (lastval) { vresult.push_back(json({{t_name, previous}, {y_name, false}})); lastval = false; } } else { for (const auto& intv : result) { if (not lastval) { vresult.push_back(json({{t_name, intv.lower()}, {y_name, true}})); lastval = true; } if (intv.upper() != now) { vresult.push_back(json({{t_name, intv.upper()}, {y_name, false}})); lastval = false; } } } return vresult; } }; } //namespace reelay
3,612
C++
.h
100
30.72
78
0.625322
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,839
dense_timed_robustness_python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python/dense_timed_robustness_python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/options.hpp" #include "reelay/pybind11.hpp" namespace reelay { template<typename TimeT, typename ValueT> struct dense_timed_robustness_formatter<TimeT, ValueT, pybind11::object> { using time_t = TimeT; using value_t = ValueT; using output_t = pybind11::object; using interval = reelay::interval<time_t>; using interval_map = reelay::robustness_interval_map<time_t, value_t>; std::string t_name; std::string y_name; value_t lastval = false; explicit dense_timed_robustness_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) { } explicit dense_timed_robustness_formatter(const basic_options& options) : dense_timed_robustness_formatter( options.get_time_field_name(), options.get_value_field_name()) { } inline output_t now(time_t now) { return pybind11::dict(pybind11::arg(t_name.c_str()) = now); } output_t format(const interval_map& result, time_t previous, time_t now) { auto vresult = pybind11::list(); for(const auto& intv : result) { if(lastval != intv.second or now == 0) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.first.lower(), pybind11::arg(y_name.c_str()) = intv.second)); lastval = intv.second; } } return vresult; } }; } // namespace reelay
1,746
C++
.h
52
29.615385
74
0.685119
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,840
condensing_python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python/condensing_python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/options.hpp" #include "reelay/pybind11.hpp" namespace reelay { template<typename TimeT, typename ValueT> struct discrete_timed_formatter<TimeT, ValueT, pybind11::object, true> { using time_t = TimeT; using value_t = ValueT; using output_t = pybind11::object; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; value_t lastval = std::numeric_limits<value_t>::lowest(); std::string t_name; std::string y_name; explicit discrete_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) { } explicit discrete_timed_formatter(const basic_options& options) : discrete_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) { } inline output_t now(time_t now) { return pybind11::dict(pybind11::arg(t_name.c_str()) = now); } output_t format(value_t result, time_t now) { if(result != lastval or now == 0) { lastval = result; return pybind11::dict( pybind11::arg(t_name.c_str()) = now, pybind11::arg(y_name.c_str()) = result); } else { lastval = result; return pybind11::dict(); } } }; } // namespace reelay
1,622
C++
.h
52
27.442308
74
0.67864
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,841
discrete_timed_python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python/discrete_timed_python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/options.hpp" #include "reelay/pybind11.hpp" namespace reelay { template<typename TimeT, typename ValueT> struct discrete_timed_formatter<TimeT, ValueT, pybind11::object, false> { using time_t = TimeT; using value_t = ValueT; using output_t = pybind11::object; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; value_t lastval = std::numeric_limits<value_t>::lowest(); std::string t_name; std::string y_name; explicit discrete_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) { } explicit discrete_timed_formatter(const basic_options& options) : discrete_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) { } inline output_t now(time_t now) { return pybind11::dict(pybind11::arg(t_name.c_str()) = now); } output_t format(value_t result, time_t now) { return pybind11::dict(pybind11::arg(y_name.c_str()) = result); } }; } // namespace reelay
1,425
C++
.h
43
30.023256
74
0.705325
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,842
dense_timed_data_python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python/dense_timed_data_python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/options.hpp" #include "reelay/pybind11.hpp" namespace reelay { template<typename TimeT, typename ValueT> struct dense_timed_data_formatter<TimeT, ValueT, pybind11::object> { using time_t = TimeT; using value_t = ValueT; using output_t = pybind11::object; using interval = reelay::interval<time_t>; using interval_map = reelay::data_interval_map<time_t>; data_mgr_t manager; std::string t_name; std::string y_name; bool lastval = false; explicit dense_timed_data_formatter( const data_mgr_t& mgr, const std::string& t_str = "time", const std::string& y_str = "value") : manager(mgr), t_name(t_str), y_name(y_str) { } explicit dense_timed_data_formatter(const basic_options& options) : dense_timed_data_formatter( options.get_data_manager(), options.get_time_field_name(), options.get_value_field_name()) { } inline output_t now(time_t now) { return pybind11::dict(pybind11::arg(t_name.c_str()) = now); } inline output_t format( const interval_map& result, time_t previous, time_t now) { auto vresult = pybind11::list(); for(const auto& intv : result) { bool value = (intv.second != manager->zero()); if(lastval != value or now == 0) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.first.lower(), pybind11::arg(y_name.c_str()) = value)); lastval = value; } } return vresult; } }; } // namespace reelay
1,867
C++
.h
59
27.338983
70
0.667038
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,843
dense_timed_python_formatter.hpp
doganulus_reelay/include/reelay/formatters/python/dense_timed_python_formatter.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include "reelay/formatters/formatter.hpp" #include "reelay/intervals.hpp" #include "reelay/options.hpp" #include "reelay/pybind11.hpp" namespace reelay { template<typename TimeT, typename ValueT> struct dense_timed_formatter<TimeT, ValueT, pybind11::object> { using time_t = TimeT; using value_t = ValueT; using output_t = pybind11::object; using interval = reelay::interval<time_t>; using interval_set = reelay::interval_set<time_t>; std::string t_name; std::string y_name; bool lastval = false; explicit dense_timed_formatter( const std::string& t_str = "time", const std::string& y_str = "value") : t_name(t_str), y_name(y_str) { } explicit dense_timed_formatter(const basic_options& options) : dense_timed_formatter( options.get_time_field_name(), options.get_value_field_name()) { } inline output_t now(time_t now) { return pybind11::dict(pybind11::arg(t_name.c_str()) = now); } output_t format(const interval_set& result, time_t previous, time_t now) { if(now == 0) { return _init_0(result, previous, now); } else if(previous == 0) { return _init_1(result, previous, now); } else { return _format(result, previous, now); } } output_t _init_0(const interval_set& result, time_t previous, time_t now) { // This code takes care of the special case of time zero // HERE: time_t now = 0 return pybind11::list(); } output_t _init_1(const interval_set& result, time_t previous, time_t now) { // This code takes care of the special case of the first segment // The variable `lastval` is meaningless for the first segment // HERE: The first segment ranges from previous=0 to now auto vresult = pybind11::list(); if(result.empty()) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = previous, pybind11::arg(y_name.c_str()) = false)); lastval = false; } else { if(result.begin()->lower() != previous) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = previous, pybind11::arg(y_name.c_str()) = false)); lastval = false; } for(const auto& intv : result) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.lower(), pybind11::arg(y_name.c_str()) = true)); lastval = true; if(intv.upper() != now) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.upper(), pybind11::arg(y_name.c_str()) = false)); lastval = false; } } } return vresult; } output_t _format(const interval_set& result, time_t previous, time_t now) { // This code constitutes the main operation such that // + do output two events per interval in the set // + take care empty interval set (meaning all false over the period) // + do not output if it is the same value with the last value (lastval) // + do not output for the current point (now) as it may be not finished auto vresult = pybind11::list(); if(result.empty()) { if(lastval) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = previous, pybind11::arg(y_name.c_str()) = false)); lastval = false; } } else { for(const auto& intv : result) { if(not lastval) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.lower(), pybind11::arg(y_name.c_str()) = true)); lastval = true; } if(intv.upper() != now) { vresult.append(pybind11::dict( pybind11::arg(t_name.c_str()) = intv.upper(), pybind11::arg(y_name.c_str()) = false)); lastval = false; } } } return vresult; } }; } // namespace reelay
4,179
C++
.h
125
27.52
78
0.616567
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,844
abstract_monitor.hpp
doganulus_reelay/include/reelay/monitors/abstract_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once namespace reelay { template <typename InputT, typename OutputT> struct abstract_monitor { using input_type = InputT; using output_type = OutputT; virtual ~abstract_monitor() {} virtual output_type update(const input_type& obj) = 0; virtual output_type now() = 0; }; }
546
C++
.h
18
28.166667
70
0.728489
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,845
dense_timed_monitor.hpp
doganulus_reelay/include/reelay/monitors/dense_timed_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/dense_timed_network.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename InputT, typename OutputT> struct dense_timed_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = bool; using input_type = InputT; using output_type = OutputT; using type = dense_timed_monitor<time_type, input_type, output_type>; using network_t = dense_timed_network<time_type, input_type>; using formatter_t = dense_timed_formatter<time_type, value_type, output_type>; dense_timed_monitor() = default; explicit dense_timed_monitor(const network_t &n, const formatter_t &f) : network(n), formatter(f) {} output_type now() override { return formatter.now(network.current); } output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result, network.previous, network.current); } static type make(const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return type(net, formatter); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return std::make_shared<type>(net, formatter); } private: network_t network; formatter_t formatter; }; } // namespace reelay
1,918
C++
.h
51
34.54902
80
0.734232
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,846
dense_timed_robustness_0_monitor.hpp
doganulus_reelay/include/reelay/monitors/dense_timed_robustness_0_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/dense_timed_robustness_0_network.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename ValueT, typename InputT, typename OutputT> struct dense_timed_robustness_0_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = ValueT; using input_type = InputT; using output_type = OutputT; using type = dense_timed_robustness_0_monitor< time_type, value_type, input_type, output_type>; using network_t = dense_timed_robustness_0_network<time_type, value_type, input_type>; using formatter_t = dense_timed_robustness_formatter<time_type, value_type, output_type>; dense_timed_robustness_0_monitor() = default; explicit dense_timed_robustness_0_monitor( const network_t &n, const formatter_t &f) : network(n), formatter(f) {} output_type now() override { return formatter.now(network.current); } output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result, network.previous, network.current); } static type make(const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return type(net, formatter); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return std::make_shared<type>(net, formatter); } private: network_t network; formatter_t formatter; }; } // namespace reelay
2,080
C++
.h
56
33.767857
78
0.73161
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,847
discrete_timed_data_monitor.hpp
doganulus_reelay/include/reelay/monitors/discrete_timed_data_monitor.hpp
#ifndef REELAY_MONITORS_DISCRETE_TIMED_DATA_MONITOR_HPP #define REELAY_MONITORS_DISCRETE_TIMED_DATA_MONITOR_HPP /* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include <utility> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/discrete_timed_data_network.hpp" // #include "reelay/options.hpp" namespace reelay { template < typename TimeT, typename InputT, typename OutputT, bool condensing = true> struct discrete_timed_data_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = bool; using input_type = InputT; using output_type = OutputT; using type = discrete_timed_data_monitor< TimeT, InputT, OutputT, condensing>; using base_output_type = data_set_t; using node_type = discrete_timed_node<base_output_type, time_type>; using state_type = discrete_timed_state<input_type, base_output_type, time_type>; using network_t = discrete_timed_data_network<time_type, input_type>; using formatter_t = discrete_timed_formatter<time_type, value_type, output_type, condensing>; discrete_timed_data_monitor() = default; explicit discrete_timed_data_monitor( data_mgr_t mgr, const network_t &n, const formatter_t &f) : manager(std::move(mgr)), network(n), formatter(f) {} output_type now() override { return formatter.now(network.now()); } output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result != manager->zero(), network.now()); } static type make(const std::string &pattern, const basic_options &options) { auto mgr = options.get_data_manager(); auto net = network_t::make(pattern, options); auto fmt = formatter_t(options); return type(mgr, net, fmt); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto mgr = options.get_data_manager(); auto net = network_t::make(pattern, options); auto fmt = formatter_t(options); return std::make_shared<type>(mgr, net, fmt); } private: data_mgr_t manager; network_t network; formatter_t formatter; }; } // namespace reelay #endif
2,514
C++
.h
68
33.573529
81
0.724876
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,848
monitor.hpp
doganulus_reelay/include/reelay/monitors/monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <type_traits> // #include "reelay/monitors/abstract_monitor.hpp" namespace reelay { template <typename InputT, typename OutputT> struct monitor { using input_type = InputT; using output_type = OutputT; using type = monitor<input_type, output_type>; using impl_type = abstract_monitor<input_type, output_type>; output_type now() { return pimpl->now(); } output_type update(const input_type& obj) { return pimpl->update(obj); } monitor() {} monitor(std::shared_ptr<impl_type> pointer) : pimpl(pointer) {} private: std::shared_ptr<impl_type> pimpl; }; } // namespace reelay
903
C++
.h
31
26.612903
70
0.719258
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,849
dense_timed_data_monitor.hpp
doganulus_reelay/include/reelay/monitors/dense_timed_data_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/dense_timed_data_network.hpp" // #include "reelay/options.hpp" namespace reelay { template <typename TimeT, typename InputT, typename OutputT> struct dense_timed_data_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = bool; using input_type = InputT; using output_type = OutputT; using type = dense_timed_data_monitor<time_type, input_type, output_type>; using network_t = dense_timed_data_network<time_type, input_type>; using formatter_t = dense_timed_data_formatter<time_type, value_type, output_type>; dense_timed_data_monitor() = default; explicit dense_timed_data_monitor( const data_mgr_t mgr, const network_t &n, const formatter_t &f) : manager(mgr), network(n), formatter(f) {} output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result, network.previous, network.current); } output_type now() override { return formatter.now(network.current); } static type make(const std::string &pattern, const basic_options &options) { auto mgr = options.get_data_manager(); auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return type(mgr, net, formatter); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto mgr = options.get_data_manager(); auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return std::make_shared<type>(mgr, net, formatter); } private: data_mgr_t manager; network_t network; formatter_t formatter; }; } // namespace reelay
2,124
C++
.h
57
33.964912
78
0.726521
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,850
discrete_timed_robustness_monitor.hpp
doganulus_reelay/include/reelay/monitors/discrete_timed_robustness_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/discrete_timed_robustness_network.hpp" // // #include "reelay/options.hpp" namespace reelay { template < typename TimeT, typename ValueT, typename InputT, typename OutputT, bool condensing = true> struct discrete_timed_robustness_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = ValueT; using input_type = InputT; using output_type = OutputT; using type = discrete_timed_robustness_monitor< time_type, value_type, input_type, output_type, condensing>; using network_t = discrete_timed_robustness_network<time_type, value_type, input_type>; using formatter_t = discrete_timed_formatter< time_type, value_type, output_type, condensing>; discrete_timed_robustness_monitor() = default; explicit discrete_timed_robustness_monitor( const network_t &n, const formatter_t &f) : network(n), formatter(f) {} output_type now() override { return formatter.now(network.now()); } output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result, network.now()); } static type make(const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return type(net, formatter); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return std::make_shared<type>(net, formatter); } private: network_t network; formatter_t formatter; }; } // namespace reelay
2,120
C++
.h
59
32.491525
78
0.729228
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,851
discrete_timed_monitor.hpp
doganulus_reelay/include/reelay/monitors/discrete_timed_monitor.hpp
/* * Copyright (c) 2019-2023 Dogan Ulus * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <memory> #include <string> #include "reelay/formatters/formatter.hpp" #include "reelay/monitors/abstract_monitor.hpp" #include "reelay/networks/discrete_timed_network.hpp" // #include "reelay/options.hpp" namespace reelay { template < typename TimeT, typename InputT, typename OutputT, bool condensing = true> struct discrete_timed_monitor final : public abstract_monitor<InputT, OutputT> { using time_type = TimeT; using value_type = bool; using input_type = InputT; using output_type = OutputT; using type = discrete_timed_monitor< TimeT, InputT, OutputT, condensing>; using node_type = discrete_timed_node<value_type, time_type>; using state_type = discrete_timed_state<input_type, value_type, time_type>; using network_type = discrete_timed_network<time_type, input_type>; using network_t = discrete_timed_network<time_type, input_type>; using formatter_t = discrete_timed_formatter<time_type, value_type, output_type, condensing>; discrete_timed_monitor() = default; explicit discrete_timed_monitor(const network_t &n, const formatter_t &f) : network(n), formatter(f) {} output_type update(const input_type &args) override { auto result = network.update(args); return formatter.format(result, network.now()); } output_type now() override { return formatter.now(network.now()); } static type make(const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return type(net, formatter); } static std::shared_ptr<type> make_shared( const std::string &pattern, const basic_options &options) { auto net = network_t::make(pattern, options); auto formatter = formatter_t(options); return std::make_shared<type>(net, formatter); } private: network_t network; formatter_t formatter; }; } // namespace reelay
2,195
C++
.h
59
33.847458
81
0.729029
doganulus/reelay
33
5
3
MPL-2.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,852
retekess_ook_t112.cpp
baycom_rps/src/retekess_ook_t112.cpp
#include "main.h" /* Sync-Pulse = 1: 220us / 0:6480us 2 x 110 + 59 x 110 = 6710 Sync-Pulse-Data-Start = 6710us Data-0 = 1: 330us / 0:990us 3 x 110 + 9 x 110 = 1320 Data-1 = 1: 990us / 0:330us 9 x 110 + 1 x 110 = 1320 Data-Data-Start = 1320us (3030 Bit/s) LSB First 61 + 24*12 = 349 bits = 43.625 bytes / Frame Frame: 13 bit System ID 10 bit Pager Number 1 bit cancel Repeat frame 12 times */ typedef union { struct { unsigned int system_id : 13; unsigned int pager_num : 10; unsigned int cancel : 1; } s; uint8_t b8[3]; } retekess_ook_t; typedef enum { TX_IDLE = 0, TX_START, TX_BIT } tx_state_t; typedef struct { volatile tx_state_t state = TX_IDLE; uint8_t buffer[64]; volatile int bits = 349; volatile int batch_counter = 12; volatile int bit_counter = 0; } retekess_transmitter_t; static retekess_transmitter_t tx; static void IRAM_ATTR onTimer() { switch (tx.state) { case TX_IDLE: break; case TX_START: tx.state = TX_BIT; tx.bit_counter = 0; break; case TX_BIT: digitalWrite(LoRa_DIO2, bitset_lsb_first(tx.buffer, tx.bit_counter++)); if (tx.bit_counter == tx.bits) { tx.batch_counter--; if (tx.batch_counter) { tx.bit_counter = 0; } else { tx.state = TX_IDLE; } } break; default: break; } } static int symbol_sync(uint8_t *data, int start) { bitset_lsb_first(data, start + 0, 1); bitset_lsb_first(data, start + 1, 1); for (int i = 0; i < 59; i++) { bitset_lsb_first(data, start + i + 2, 0); } return 61; } static int symbol_zero(uint8_t *data, int start) { for (int i = 0; i < 3; i++) { bitset_lsb_first(data, start + i, 1); } for (int i = 0; i < 9; i++) { bitset_lsb_first(data, start + i + 3, 0); } return 12; } static int symbol_one(uint8_t *data, int start) { for (int i = 0; i < 9; i++) { bitset_lsb_first(data, start + i, 1); } for (int i = 0; i < 3; i++) { bitset_lsb_first(data, start + i + 9, 0); } return 12; } static int retekess_ook_t112_prepare(uint8_t *raw, retekess_ook_t *payload) { int pos = 0; pos += symbol_sync(raw, 0); for (int i = 0; i < 24; i++) { if (bitset_lsb_first(payload->b8, i)) { #ifdef DEBUG printf("1"); #endif pos += symbol_one(raw, pos); } else { #ifdef DEBUG printf("0"); #endif pos += symbol_zero(raw, pos); } } #ifdef DEBUG printf("\nraw: "); for (int i = 0; i < pos; i++) { printf("%d", bitset_lsb_first(raw, i)); } printf("\nsymbol built\n"); #endif return pos; } int retekess_ook_t112_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type, bool cancel) { retekess_ook_t p; p.s.system_id = system_id; p.s.pager_num = pager_number; p.s.cancel = cancel; dbg("system_id: %d pager_num: %d cancel: %d tx_frequency: %.4f\n", system_id, pager_number, cancel, tx_frequency); int len = retekess_ook_t112_prepare(tx.buffer, &p); timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 1000000 / 9100, true); timerAlarmEnable(timer); fsk.setOutputPower(tx_power); fsk.setFrequency(tx_frequency); fsk.setOOK(true); fsk.transmitDirect(); tx.batch_counter = 12; tx.bits = len; tx.state = TX_START; while (1) { dbg("tx.state : %d\n", tx.state); dbg("tx.batch_counter : %d\n", tx.batch_counter); dbg("tx.bit_counter : %d\n", tx.bit_counter); bool done = false; if (tx.state == TX_IDLE) { done = true; } if (done) { break; } usleep(100000); } fsk.standby(); timerAlarmDisable(timer); timerDetachInterrupt(timer); return 0; }
4,206
C++
.cpp
144
22.777778
83
0.549049
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,853
retekess_ook_td161.cpp
baycom_rps/src/retekess_ook_td161.cpp
#include "main.h" /* Modulation Modulation: OOK Carrier frequency: 433.92 MHz Baud rate: 5000 0 Symbol: 0001 1 Symbol: 1110 Packet structure P A S A L Y G E S E R T R T E ID T M HTO Y HTO 030 0 000 0000 Pager-ID (3 Nibbles): 0xHTO (BCD-coded) System-ID (3 Nibbles): 0xHTO (BCD-coded) Alert-Type (1 Nibble): 0 Paging: 999: Switch all pagers off 1 Programming: Step 1: Page 000, Step 2: Page XXX, Abort: Page F10 (1510) 2 Alert-Config: (B)eep (V)ibrate (L)ED blink 1: B 2: V 3: L 4: BV 5: VL 6: BL 7: BVL 3: Alert-Time: Seconds (1-999) 4: Alert-Repeat-Time: Seconds (1-999) Repeat frame 30 times */ typedef enum { TX_IDLE = 0, TX_START, TX_BIT } tx_state_t; typedef struct { volatile tx_state_t state = TX_IDLE; uint8_t buffer[64]; volatile int bits = 0; volatile int batch_counter = 0; volatile int bit_counter = 0; } retekess_transmitter_t; static retekess_transmitter_t tx; static void IRAM_ATTR onTimer() { switch (tx.state) { case TX_IDLE: break; case TX_START: tx.state = TX_BIT; tx.bit_counter = 0; break; case TX_BIT: digitalWrite(LoRa_DIO2, bitset_lsb_first(tx.buffer, tx.bit_counter++)); if (tx.bit_counter == tx.bits) { tx.batch_counter--; if (tx.batch_counter) { tx.bit_counter = 0; } else { tx.state = TX_IDLE; } } break; default: break; } } static int symbol_zero(uint8_t *data, int start) { bitset_lsb_first(data, start, 1); for (int i = 0; i < 3; i++) { bitset_lsb_first(data, start + i + 1, 0); } return 4; } static int symbol_one(uint8_t *data, int start) { for (int i = 0; i < 3; i++) { bitset_lsb_first(data, start + i, 1); } bitset_lsb_first(data, start + 3, 0); return 4; } static int symbol_off(uint8_t *data, int start) { for (int i = 0; i < 4; i++) { bitset_lsb_first(data, start + i, 0); } return 4; } static int retekess_ook_td161_prepare(uint8_t *raw, int system_id, int pager_number, int alert_type) { int pos = 0; uint8_t frame[9]; int system_id_bcd = bcd(system_id); int pager_number_bcd = bcd(pager_number); memset(frame, 0, sizeof(frame)); frame[0] = (pager_number_bcd)&0xf; frame[1] = (pager_number_bcd >> 4) & 0xf; frame[2] = (pager_number_bcd >> 8) & 0xf; frame[3] = alert_type & 0xf; frame[4] = (system_id_bcd)&0xf; frame[5] = (system_id_bcd >> 4) & 0xf; frame[6] = (system_id_bcd >> 8) & 0xf; #ifdef DEBUG printf("\nframe: "); for (int i = 0; i < sizeof(frame); i++) { printf("%02x ", frame[i]); } #endif for (int i = 0; i < 9; i++) { for (int b = 0; b < 4; b++) { if (bitset_lsb_first(frame + i, b)) { pos += symbol_one(raw, pos); } else { pos += symbol_zero(raw, pos); } } } for (int i = 0; i < 7; i++) { pos += symbol_off(raw, pos); } #ifdef DEBUG printf("\nraw %d bits: ", pos); for (int i = 0; i < pos; i++) { printf("%d", bitset_lsb_first(raw, i)); } printf("\nsymbol built\n"); #endif return pos; } int retekess_ook_td161_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type) { dbg("system_id: %d pager_num: %d alert_type: %d tx_frequency: %.4f\n", system_id, pager_number, alert_type, tx_frequency); int len = retekess_ook_td161_prepare(tx.buffer, system_id, pager_number, alert_type); timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 1000000 / 5000, true); timerAlarmEnable(timer); fsk.setOutputPower(tx_power); fsk.setFrequency(tx_frequency); fsk.setOOK(true); fsk.transmitDirect(); tx.batch_counter = 30; tx.bits = len; tx.state = TX_START; while (1) { dbg("tx.state : %d\n", tx.state); dbg("tx.batch_counter : %d\n", tx.batch_counter); dbg("tx.bit_counter : %d\n", tx.bit_counter); bool done = false; if (tx.state == TX_IDLE) { done = true; } if (done) { break; } usleep(100000); } fsk.standby(); timerAlarmDisable(timer); timerDetachInterrupt(timer); return 0; }
4,630
C++
.cpp
165
21.690909
83
0.554078
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,854
util.cpp
baycom_rps/src/util.cpp
#include "main.h" int bitset_lsb_first(uint8_t *data, int bitpos, int value, bool reverse) { int bytepos = bitpos >> 3; bitpos &= 7; if(reverse) { bitpos = 7 - bitpos; } uint8_t mask = 1 << bitpos; switch (value) { case 0: data[bytepos] &= ~mask; break; case 1: data[bytepos] |= mask; break; default: break; } return data[bytepos] & mask ? 1 : 0; } int bitset_msb_first(uint8_t *data, int bitpos, int value) { return bitset_lsb_first(data, bitpos, value, true); } int bcd(int number, int *hundreds, int *tens, int *ones) { int h = number / 100; int t = (number - h * 100) / 10; int o = number - h * 100 - t * 10; if(hundreds) *hundreds = h; if(tens) *tens = t; if(ones) *ones = o; return h << 8 | t << 4 | o; } int reversenibble(int number) { return (number & 8) >> 3 | (number & 4) >> 1 | (number & 2) << 1 | (number & 1) << 3; } float range_check(float val, float min, float max) { if(val < min) return min; if(val > max) return max; return val; }
1,147
C++
.cpp
41
22.195122
74
0.537693
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,855
main.cpp
baycom_rps/src/main.cpp
#include "main.h" settings_t cfg; bool eth_connected = false; static EOTAUpdate *updater; void WiFiEvent(WiFiEvent_t event) { dbg("WiFiEvent: %d\n", event); switch (event) { case ARDUINO_EVENT_ETH_START: dbg("ETH Started\n"); // set eth hostname here ETH.setHostname(cfg.wifi_hostname); break; case ARDUINO_EVENT_ETH_CONNECTED: dbg("ETH Connected\n"); break; case ARDUINO_EVENT_ETH_GOT_IP: info("ETH MAC: %s, IPv4: %s (%s, %dMbps)\n", ETH.macAddress().c_str(), ETH.localIP().toString().c_str(), ETH.fullDuplex() ? "FULL_DUPLEX" : "HALF_DUPLEX", ETH.linkSpeed()); case ARDUINO_EVENT_WIFI_STA_GOT_IP: if (!eth_connected) { if (event == ARDUINO_EVENT_WIFI_STA_GOT_IP) { info("WiFi MAC: %s, IPv4: %s\n", WiFi.macAddress().c_str(), WiFi.localIP().toString().c_str()); } #ifdef HAS_DISPLAY display.setFont(ArialMT_Plain_10); display.drawString(64, 54, "IP: " + WiFi.localIP().toString()); d(); #endif if (!MDNS.begin(cfg.wifi_hostname)) { err("MDNS responder failed to start\n"); } eth_connected = true; #ifdef LED_BUILTIN digitalWrite(LED_BUILTIN, 0); #endif } break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: WiFi.reconnect(); case ARDUINO_EVENT_ETH_DISCONNECTED: dbg("ETH Disconnected\n"); // eth_connected = false; break; case ARDUINO_EVENT_ETH_STOP: dbg("ETH Stopped\n"); // eth_connected = false; break; default: break; } } void setup() { Serial.begin(115200); display_setup(); info("Version: %s, Version Number: %d, CFG Number: %d\n", VERSION_STR, VERSION_NUMBER, cfg_ver_num); info("Initializing ... "); EEPROM.begin(EEPROM_SIZE); read_config(); WiFi.onEvent(WiFiEvent); buttons_setup(); pinMode(GPIO_NUM_0, INPUT_PULLUP); #ifdef LED_BUILTIN pinMode(LED_BUILTIN, OUTPUT); #endif #ifdef HAS_DISPLAY display.init(); display.flipScreenVertically(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_10); display.clear(); display.drawString(64, 4, "Restaurant Paging Service"); display.drawString(64, 14, "Version: " + String(VERSION_STR)); String modeStr = ""; switch (cfg.wifi_opmode) { case 0: modeStr = "AP"; break; case 1: modeStr = "STA"; break; case 2: modeStr = "ETH"; break; } display.drawString(64, 24, "Mode: " + modeStr); if (cfg.wifi_opmode < 2) { display.drawString(64, 34, "SSID: " + String(cfg.wifi_ssid)); } display.drawString(64, 44, "NAME: " + String(cfg.wifi_hostname)); d(); #endif updater = new EOTAUpdate(cfg.ota_path, VERSION_NUMBER, 3600000UL, "RPS/" VERSION_STR); pager_setup(); if (cfg.wifi_opmode == OPMODE_ETH_CLIENT) { #ifdef LILYGO_POE pinMode(NRST, OUTPUT); for(int i=0;i<4;i++) { digitalWrite(NRST, i&1); delay(200); } #endif ETH.begin(); // ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE); } else if (cfg.wifi_opmode == OPMODE_WIFI_STATION) { WiFi.disconnect(); WiFi.setAutoReconnect(true); WiFi.setHostname(cfg.wifi_hostname); WiFi.setSleep(cfg.wifi_powersave); WiFi.mode(WIFI_STA); IPAddress myIP; IPAddress myGW; IPAddress myNM; IPAddress myDNS; myIP.fromString(cfg.ip_addr); myGW.fromString(cfg.ip_gw); myNM.fromString(cfg.ip_netmask); myDNS.fromString(cfg.ip_dns); WiFi.config(myIP, myGW, myNM, myDNS); WiFi.begin(cfg.wifi_ssid, cfg.wifi_secret); info("\n"); } else if (cfg.wifi_opmode == OPMODE_WIFI_ACCESSPOINT) { WiFi.softAP(cfg.wifi_ssid, cfg.wifi_secret); IPAddress IP = WiFi.softAPIP(); info("AP IP address: %s\n", IP.toString().c_str()); #ifdef HAS_DISPLAY display.setFont(ArialMT_Plain_10); for (int x = 0; x < 128; x++) { for (int y = 0; y < 20; y++) { display.clearPixel(x, y + 24); } } display.drawString( 64, 24, "WIFI: " + String((cfg.wifi_opmode == OPMODE_WIFI_STATION) ? "STA" : "AP")); display.drawString(64, 34, "SSID: " + String(cfg.wifi_ssid)); display.drawString(64, 54, "IP: " + IP.toString()); d(); #endif } webserver_setup(); } void power_off(int state) { #ifdef HAS_DISPLAY if (state & 1) { display.clear(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_16); display.drawString(64, 32, "Power off."); d(); } #endif if (state & 2) { #ifdef HAS_DISPLAY display.clear(); digitalWrite(OLED_RST, LOW); // low to reset OLED #endif #ifdef HELTEC digitalWrite(Vext, HIGH); #endif esp_deep_sleep_start(); } } void wifi_loop() { static unsigned long last_blink = 0; static int count = 0; if (!eth_connected && millis() < 30000) { if (cfg.wifi_opmode == OPMODE_WIFI_STATION && cfg.wifi_ap_fallback == 1 && WiFi.status() != WL_CONNECTED && count > 60) { uint8_t mac[10]; WiFi.macAddress(mac); sprintf(cfg.wifi_ssid, "RPS-%02X%02X%02X", mac[3], mac[4], mac[5]); warn("\nFailed to connect to SSID %s falling back to AP mode\n", cfg.wifi_ssid); cfg.wifi_secret[0] = 0; cfg.wifi_opmode = OPMODE_WIFI_ACCESSPOINT; WiFi.disconnect(); WiFi.softAP(cfg.wifi_ssid, cfg.wifi_secret); IPAddress IP = WiFi.softAPIP(); info("AP IP address: %s\n", IP.toString().c_str()); } if ((millis() - last_blink) > 500) { last_blink = millis(); count++; #ifdef LED_BUILTIN digitalWrite(LED_BUILTIN, count&1); #endif info("%d\n", count); } } } void loop() { #ifdef HAS_DISPLAY display_loop(); #endif wifi_loop(); buttons_loop(); if (cfg.ota_path[0] && cfg.wifi_opmode && eth_connected) { updater->CheckAndUpdate(); } }
6,758
C++
.cpp
205
24.165854
92
0.544453
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,856
cfg.cpp
baycom_rps/src/cfg.cpp
#include "main.h" void write_config(void) { EEPROM.writeBytes(0, &cfg, sizeof(cfg)); EEPROM.commit(); } void read_config(void) { EEPROM.readBytes(0, &cfg, sizeof(cfg)); if (cfg.version != cfg_ver_num) { if (cfg.version == 0xff) { uint8_t mac[10]; WiFi.macAddress(mac); sprintf(cfg.wifi_ssid, "RPS-%02X%02X%02X", mac[3], mac[4], mac[5]); strcpy(cfg.wifi_secret, ""); strcpy(cfg.wifi_hostname, cfg.wifi_ssid); cfg.wifi_opmode = OPMODE_WIFI_ACCESSPOINT; cfg.wifi_powersave = false; cfg.restaurant_id = 0x0; cfg.system_id = 0x1; cfg.alert_type = 0x1; cfg.default_mode = 0x0; cfg.pocsag_baud = 1200; cfg.tx_current_limit = 240; cfg.tx_power = 17; cfg.tx_deviation = 3.5; cfg.tx_frequency = 446.15625; } if(cfg.version == 0xff || cfg.version < 9) { cfg.pocsag_tx_deviation = 4.5; cfg.pocsag_tx_frequency = 446.15625; cfg.retekess_tx_frequency = 433.92; cfg.retekess_system_id = 200; cfg.multi_pager_types = 0; } if(cfg.version == 0xff || cfg.version < 10) { cfg.retekess_tx_deviation = 35; } if(cfg.version == 0xff || cfg.version < 11) { cfg.retekess_alert_type = 0; } if(cfg.version == 0xff || cfg.version < 12) { cfg.display_timeout = 5000; } if(cfg.version == 0xff || cfg.ota_path[0] == 0xff) { cfg.ota_path[0] = 0; } if(cfg.ip_addr[0] == 0xff || cfg.ip_gw[0] == 0xff || cfg.ip_netmask[0] == 0xff || cfg.ip_dns[0] == 0xff) { cfg.ip_addr[0] = 0; cfg.ip_gw[0] = 0; cfg.ip_netmask[0] = 0; cfg.ip_dns[0] = 0; } cfg.version = cfg_ver_num; write_config(); } info("Settings:\n"); info("cfg version : %d\n", cfg.version); info("display_timeout : %ld\n", cfg.display_timeout); info("ssid : %s\n", cfg.wifi_ssid); info("wifi_secret : %s\n", cfg.wifi_secret); info("wifi_hostname : %s\n", cfg.wifi_hostname); info("wifi_opmode : %d\n", cfg.wifi_opmode); info("wifi_powersave : %d\n", cfg.wifi_powersave); info("wifi_ap_fallback: %d\n", cfg.wifi_ap_fallback); info("ip_addr : %s\n", cfg.ip_addr); info("ip_gw : %s\n", cfg.ip_gw); info("ip_netmask : %s\n", cfg.ip_netmask); info("ip_dns : %s\n", cfg.ip_dns); info("ota_path : %s\n", cfg.ota_path); info("restaurant_id : %d\n", cfg.restaurant_id); info("system_id : %d\n", cfg.system_id); info("alert_type : %d\n", cfg.alert_type); info("default_mode : %d\n", cfg.default_mode); info("pocsag_baud : %d\n", cfg.pocsag_baud); info("tx_power : %ddBm\n", cfg.tx_power); info("tx_current_limit: %dmA\n", cfg.tx_current_limit); info("lr_tx_frequency : %.6fMHz\n", cfg.tx_frequency); info("lr_tx_deviation : %.1fkHz\n", cfg.tx_deviation); info("pocsag_tx_frequency : %.6fMHz\n", cfg.pocsag_tx_frequency); info("pocsag_tx_deviation : %.1fkHz\n", cfg.pocsag_tx_deviation); info("retekess_tx_frequency: %.6fMHz\n", cfg.retekess_tx_frequency); info("retekess_tx_deviation: %.1fkHz\n", cfg.retekess_tx_deviation); info("retekess_system_id : %d\n", cfg.retekess_system_id); info("retekess_alert_type : %d\n", cfg.retekess_alert_type); info("multi_pager_types : %d\n", cfg.multi_pager_types); } String get_settings(void) { DynamicJsonDocument json(1024); json["version"] = VERSION_STR; json["alert_type"] = cfg.alert_type; json["wifi_hostname"] = cfg.wifi_hostname; json["restaurant_id"] = cfg.restaurant_id; json["system_id"] = cfg.system_id; json["wifi_ssid"] = cfg.wifi_ssid; json["wifi_opmode"] = cfg.wifi_opmode; json["wifi_ap_fallback"] = cfg.wifi_ap_fallback; json["wifi_powersave"] = cfg.wifi_powersave; json["wifi_secret"] = cfg.wifi_secret; json["tx_frequency"] = String(cfg.tx_frequency,5); json["tx_deviation"] = cfg.tx_deviation; json["pocsag_tx_frequency"] = String(cfg.pocsag_tx_frequency,5); json["pocsag_tx_deviation"] = cfg.pocsag_tx_deviation; json["retekess_tx_frequency"] = String(cfg.retekess_tx_frequency,5); json["retekess_tx_deviation"] = cfg.retekess_tx_deviation; json["retekess_system_id"] = cfg.retekess_system_id; json["retekess_alert_type"] = cfg.retekess_alert_type; json["tx_power"] = cfg.tx_power; json["tx_current_limit"] = cfg.tx_current_limit; json["default_mode"] = cfg.default_mode; json["pocsag_baud"] = cfg.pocsag_baud; json["ota_path"] = cfg.ota_path; json["ip_addr"] = cfg.ip_addr; json["ip_gw"] = cfg.ip_gw; json["ip_netmask"] = cfg.ip_netmask; json["ip_dns"] = cfg.ip_dns; json["multi_pager_types"] = cfg.multi_pager_types; String output; serializeJson(json, output); return output; } boolean parse_settings(DynamicJsonDocument json) { if (json.containsKey("alert_type")) cfg.alert_type = json["alert_type"]; if (json.containsKey("wifi_hostname")) strncpy(cfg.wifi_hostname, json["wifi_hostname"],sizeof(cfg.wifi_hostname)); if (json.containsKey("restaurant_id")) cfg.restaurant_id = json["restaurant_id"]; if (json.containsKey("system_id")) cfg.system_id = json["system_id"]; if (json.containsKey("wifi_ssid")) strncpy(cfg.wifi_ssid, json["wifi_ssid"], sizeof(cfg.wifi_ssid)); if (json.containsKey("wifi_opmode")) cfg.wifi_opmode = json["wifi_opmode"]; if (json.containsKey("wifi_powersave")) cfg.wifi_powersave = json["wifi_powersave"]; if (json.containsKey("wifi_ap_fallback")) cfg.wifi_ap_fallback = json["wifi_ap_fallback"]; if (json.containsKey("wifi_secret")) strcpy(cfg.wifi_secret, json["wifi_secret"]); if (json.containsKey("tx_frequency")) cfg.tx_frequency = json["tx_frequency"]; if (json.containsKey("tx_deviation")) cfg.tx_deviation = json["tx_deviation"]; if (json.containsKey("pocsag_tx_frequency")) cfg.pocsag_tx_frequency = json["pocsag_tx_frequency"]; if (json.containsKey("pocsag_tx_deviation")) cfg.pocsag_tx_deviation = json["pocsag_tx_deviation"]; if (json.containsKey("retekess_tx_frequency")) cfg.retekess_tx_frequency = json["retekess_tx_frequency"]; if (json.containsKey("retekess_tx_deviation")) cfg.retekess_tx_deviation = json["retekess_tx_deviation"]; if (json.containsKey("retekess_system_id")) cfg.retekess_system_id = json["retekess_system_id"]; if (json.containsKey("retekess_alert_type")) cfg.retekess_alert_type = json["retekess_alert_type"]; if (json.containsKey("tx_power")) cfg.tx_power = json["tx_power"]; if (json.containsKey("tx_current_limit")) cfg.tx_current_limit = json["tx_current_limit"]; if (json.containsKey("pocsag_baud")) cfg.pocsag_baud = json["pocsag_baud"]; if (json.containsKey("default_mode")) cfg.default_mode = json["default_mode"]; if (json.containsKey("ota_path")) strncpy(cfg.ota_path, json["ota_path"], sizeof(cfg.ota_path)); if (json.containsKey("ip_addr")) strncpy(cfg.ip_addr, json["ip_addr"], sizeof(cfg.ip_addr)); if (json.containsKey("ip_gw")) strncpy(cfg.ip_gw, json["ip_gw"], sizeof(cfg.ip_gw)); if (json.containsKey("ip_netmask")) strncpy(cfg.ip_netmask, json["ip_netmask"], sizeof(cfg.ip_netmask)); if (json.containsKey("ip_dns")) strncpy(cfg.ip_dns, json["ip_dns"], sizeof(cfg.ip_dns)); if (json.containsKey("multi_pager_types")) cfg.multi_pager_types = json["multi_pager_types"]; write_config(); return true; } void factory_reset(int state) { #ifdef HAS_DISPLAY if (state & 1) { display.clear(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.drawString(64, 14, "FACTORY"); display.drawString(64, 42, "RESET"); d(); } #endif if (state & 2) { info("RESET Config\n"); cfg.version = 0xff; write_config(); sleep(1); ESP.restart(); } }
7,958
C++
.cpp
199
35.115578
110
0.633488
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,857
display.cpp
baycom_rps/src/display.cpp
#include "main.h" SSD1306Wire display(OLED_ADDRESS, OLED_SDA, OLED_SCL); static unsigned long displayTime = millis(); static unsigned long displayCleared = millis(); void display_setup() { #ifdef HAS_DISPLAY pinMode(OLED_RST, OUTPUT); digitalWrite(OLED_RST, LOW); // low to reset OLED delay(50); digitalWrite(OLED_RST, HIGH); // must be high to turn on OLED display.init(); #ifdef HAS_DISPLAY_UPSIDEDOWN display.flipScreenVertically(); #endif #endif } void d() { #ifdef HAS_DISPLAY displayTime = millis(); displayCleared = 0; display.display(); #endif } void display_loop() { #ifdef HAS_DISPLAY if (cfg.display_timeout > 1000 && (millis() - displayTime > cfg.display_timeout) && !displayCleared) { displayCleared = millis(); display.clear(); display.display(); } #endif }
860
C++
.cpp
32
23.1875
106
0.684083
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,858
buttons.cpp
baycom_rps/src/buttons.cpp
#include "main.h" struct Button { const uint8_t PIN; unsigned long handled; unsigned long down; unsigned long up; }; Button button1 = {GPIO_BUTTON, 0, false}; void IRAM_ATTR isr() { if (!digitalRead(GPIO_BUTTON)) { button1.handled = false; button1.down = millis(); } else { button1.up = millis(); } } void buttons_setup() { pinMode(GPIO_BUTTON, INPUT_PULLUP); attachInterrupt(button1.PIN, isr, CHANGE); } void buttons_loop() { bool released = (button1.up > button1.down) ? true : false; unsigned long diff = millis() - button1.down; // printf("down: %ld up: %ld handled: %ld released: %d, diff %d\n", // button1.down, button1.up, button1.handled, released, diff); if (button1.down) { if (diff > 10000) { if (button1.handled != 10000 && !released) { button1.handled = 10000; factory_reset(1); } if (released && button1.handled == 10000) { factory_reset(2); } } else if (diff > 1500) { if (button1.handled != 1500 && !released) { button1.handled = 1500; power_off(1); } if (released && button1.handled == 1500) { power_off(2); } } else if (diff > 100 && released && button1.handled != 100) { button1.handled = 100; button1.up = 0; button1.down = 0; #ifdef HAS_DISPLAY display.clear(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_10); display.drawString(64, 4, "Version: " + String(VERSION_STR)); display.drawString(64, 24, "SSID: " + String(cfg.wifi_ssid)); display.drawString(64, 34, "NAME: " + String(cfg.wifi_hostname)); String ipStr; if(cfg.wifi_opmode == OPMODE_ETH_CLIENT) { ipStr = ETH.localIP().toString(); } else { ipStr = WiFi.localIP().toString(); } display.drawString(64, 54, "IP: " + ipStr); d(); #endif } } }
2,193
C++
.cpp
65
24.446154
77
0.528996
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,859
pocsag.cpp
baycom_rps/src/pocsag.cpp
#include "main.h" // #define DEBUG typedef enum { TX_IDLE = 0, TX_START, TX_PREAMBLE, TX_SYNC, TX_BATCH } tx_state_t; typedef struct { uint32_t buffer[_MAXTXBATCHES * 8 * 2]; int num_batches = 0; volatile tx_state_t state = TX_IDLE; volatile int preamble_counter = 0; volatile int batch_counter = 0; volatile int cw_counter = 0; volatile int bit_counter = 0; } pocsag_transmitter_t; static pocsag_transmitter_t tx; static void IRAM_ATTR onTimer() { switch (tx.state) { case TX_IDLE: break; case TX_START: tx.preamble_counter = 576; tx.state = TX_PREAMBLE; break; case TX_PREAMBLE: tx.preamble_counter--; digitalWrite(LoRa_DIO2, !(tx.preamble_counter & 1)); if (tx.preamble_counter == 0) { tx.state = TX_SYNC; tx.bit_counter = 32; tx.batch_counter = 0; } break; case TX_SYNC: tx.bit_counter--; digitalWrite(LoRa_DIO2, !((POCSAG_SYNC >> tx.bit_counter) & 1)); if (tx.bit_counter == 0) { tx.state = TX_BATCH; tx.cw_counter = 0; tx.bit_counter = 32; } break; case TX_BATCH: tx.bit_counter--; digitalWrite( LoRa_DIO2, !((tx.buffer[tx.cw_counter + (tx.batch_counter << 4)] >> tx.bit_counter) & 1)); if (tx.bit_counter == 0) { if (tx.cw_counter == 15) { tx.batch_counter++; if (tx.batch_counter < tx.num_batches) { tx.state = TX_SYNC; tx.bit_counter = 32; } else { tx.state = TX_IDLE; } } else { tx.bit_counter = 32; tx.cw_counter++; } } break; default: break; } } inline bool even_parity(uint32_t data) { uint32_t temp = data ^ (data >> 16); temp = temp ^ (temp >> 8); temp = temp ^ (temp >> 4); temp = temp ^ (temp >> 2); temp = temp ^ (temp >> 1); return (temp & 1) ? true : false; } static uint32_t crc(uint32_t data) { uint32_t ret = data << (BCH_N - BCH_K), shreg = ret; uint32_t mask = 1L << (BCH_N - 1), coeff = BCH_POLY << (BCH_K - 1); int n = BCH_K; for (; n > 0; mask >>= 1, coeff >>= 1, n--) if (shreg & mask) shreg ^= coeff; ret ^= shreg; ret = (ret << 1) | even_parity(ret); #ifdef DEBUG dbg("BCH coder: data: %08x shreg: %08x ret: %08x\n", data, shreg, ret); #endif return ret; } static void idlefill(uint32_t *b, size_t len) { int j; for (j = 0; j < len; j++) b[j] = POCSAG_IDLE; } static int poc_beep(uint32_t *buffer, size_t len, uint32_t adr, unsigned function) { if (adr > 0x1fffffLU) return 0; idlefill(buffer, len >> 2); buffer[((adr & 7) << 1)] = crc(((adr >> 1) & 0x1ffffcLU) | (function & 3)); return 1; } static uint32_t fivetol(char *s) { static uint32_t chtab[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9}; uint32_t ret = 0; int i, j; for (i = 0; i < 5; i++) { j = (4 - i) << 2; switch (s[i]) { case 0: case ' ': ret |= 3L << j; break; case '-': ret |= 11L << j; break; case '[': ret |= 15L << j; break; case ']': ret |= 7L << j; break; case 'U': ret |= 13L << j; break; default: if ((s[i] > '0') && (s[i] <= '9')) ret |= chtab[s[i] - '0'] << j; } } return crc(ret | 0x100000UL); } static int poc_numeric(uint32_t *buffer, size_t len, uint32_t adr, unsigned function, const char *s) { unsigned i = 0, j; char msg[21]; memset(msg, 0, sizeof(msg)); memccpy(msg, s, 0, sizeof(msg) - 1); if (adr > 0x1fffffLU) return 0; idlefill(buffer, len >> 2); buffer[(j = ((adr & 7) << 1))] = crc(((adr >> 1) & 0x1ffffcLU) | (function & 3)); j++; if (msg[0]) for (i = 0; i < (((strlen(msg) - 1) / 5) + 1); i++) buffer[j + i] = fivetol(msg + i * 5); return ceil((i + j) * 1.0 / 16.0); } static bool getbit(const char *s, int bit) { int startbyte = bit / 7, startbit = bit - startbyte * 7; return !!(s[startbyte] & (1 << startbit)); } static uint32_t getword(const char *s, int word) { int start = word * 20, i; uint32_t ret = 0; for (i = 0; i < 20; i++) ret |= getbit(s, start + i) * (0x80000LU >> i); return 0x100000LU | ret; } static int poc_alphanum(uint32_t *buffer, size_t len, uint32_t adr, unsigned function, const char *s) { int i, j, l; l = strlen(s); if (adr > 0x1fffffLU) return 0; idlefill(buffer, len >> 2); buffer[(j = ((adr & 7) << 1))] = crc(((adr >> 1) & 0x1ffffcLU) | (function & 3)); j++; for (i = 0; i < (l * 7 / 20 + 1); i++) buffer[j + i] = crc(getword(s, i)); return ceil((i + j) * 1.0 / 16.0); } int pocsag_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int baud, uint32_t addr, uint8_t function, func_t telegram_type, const char *msg) { size_t len = sizeof(tx.buffer); switch (telegram_type) { case FUNC_BEEP: len = 16 * sizeof(uint32_t); tx.num_batches = poc_beep(tx.buffer, len, addr, function); break; case FUNC_NUM: tx.num_batches = poc_numeric(tx.buffer, len, addr, function, msg); break; case FUNC_ALPHA: tx.num_batches = poc_alphanum(tx.buffer, len, addr, function, msg); break; default: break; } #ifdef DEBUG dbg("POCSAG:\n"); dbg("num_batches: %d\n", tx.num_batches); for (int i = 0; i < tx.num_batches * 16; i++) { printf("%02X ", tx.buffer[i]); } printf("\n"); #endif timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 1000000 / baud, true); timerAlarmEnable(timer); fsk.setOutputPower(tx_power); fsk.setFrequency(tx_frequency); fsk.setFrequencyDeviation(tx_deviation); fsk.setOOK(false); fsk.transmitDirect(); tx.state = TX_START; while (1) { dbg("tx.state : %d\n", tx.state); dbg("tx.batch_counter : %d\n", tx.batch_counter); dbg("tx.cw_counter : %d\n", tx.cw_counter); dbg("tx.bit_counter : %d\n", tx.bit_counter); bool done = false; if (tx.state == TX_IDLE) { done = true; } if (done) { break; } usleep(100000); } fsk.standby(); timerAlarmDisable(timer); timerDetachInterrupt(timer); return 0; }
7,162
C++
.cpp
225
22.977778
79
0.487246
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,860
retekess_fsk_td164.cpp
baycom_rps/src/retekess_fsk_td164.cpp
#include "main.h" /* Modulation Modulation: 2-FSK Carrier frequency: 433.92 MHz Baud rate: 10000 Packet structure S E FF CC 20 Nibbles = 80bit Preamble Q 12 HTO 12 aaaaaaaaaaaaaaaaaaaa 12340205 4 91 030 90 0000000000 Start: 0-bit Synchronization (80bit): 0xAAAAAAAAAAAAAAAAAAAA Preamble (4 nibbles): 0x12340205 Sequence number (1 nibble): 0x0 (needs to be different from last transmission) Separator (1 nibble): 0x9 Function (1 nibble): 0x1 Paging: 1-999 0x2 programming (reprogram=1) Step 1: Page 999, Step 2: Page XXX 0x4 mute (alert_type=1) 999: mute all 000: unmute all Pager ID (3 Nibbles): 0xHTO (BCD-coded) C1 (1 Nibble) = SEQ + T + T<6?1:2 + Function C2 (1 Nibble) = H + O End (40bit): 0000000000 Repeat frame 20 times */ typedef enum { TX_IDLE = 0, TX_START, TX_BIT } tx_state_t; typedef struct { volatile tx_state_t state = TX_IDLE; uint8_t buffer[64]; volatile int bits = 0; volatile int batch_counter = 0; volatile int bit_counter = 0; } retekess_transmitter_t; static retekess_transmitter_t tx; static int rolling_code = 0; static void IRAM_ATTR onTimer() { switch (tx.state) { case TX_IDLE: break; case TX_START: tx.state = TX_BIT; tx.bit_counter = 0; digitalWrite(LoRa_DIO2, 0); break; case TX_BIT: digitalWrite(LoRa_DIO2, bitset_msb_first(tx.buffer, tx.bit_counter++)); if (tx.bit_counter == tx.bits) { tx.batch_counter--; if (tx.batch_counter) { tx.bit_counter = 0; tx.state = TX_START; } else { tx.state = TX_IDLE; } } break; default: break; } } static int retekess_fsk_td164_prepare(uint8_t *raw, int pager_number, bool mute_mode = false, bool prog_mode = false) { int hundreds; int tens; int ones; int pager_number_bcd = bcd(pager_number, &hundreds, &tens, &ones); dbg("rolling_code: %d hundreds: %d tens: %d ones: %d\n", rolling_code, hundreds, tens, ones); int i; // Sync for (i = 0; i < 10; i++) { raw[i] = 0xAA; } // Preamble raw[i++] = 0x12; raw[i++] = 0x34; raw[i++] = 0x02; raw[i++] = 0x05; // Payload rolling_code = (rolling_code + 1) % 16; raw[i++] = rolling_code << 4 | 0x9; int function = 1; if (prog_mode) function = 2; if (mute_mode) function = 4; raw[i++] = function << 4 | hundreds; raw[i++] = pager_number_bcd & 0xff; int offset = (tens < 6 ? 1 : 2) + function; dbg("checksum 1 offset: %d\n", offset); int checksum1 = (rolling_code + tens + offset) & 0xf; int checksum2 = (hundreds + ones) & 0xf; raw[i++] = (checksum1 & 0xf) << 4 | (checksum2 & 0xf); for (int j = 0; j < 5; j++) { raw[i++] = 0; } #ifdef DEBUG printf("raw bytes: "); for (int j = 0; j < i; j++) { printf("%02x ", raw[j]); } printf("\nraw %d bits: ", i*8); for (int j = 0; j < i*8; j++) { printf("%d", bitset_msb_first(raw, j)); } printf("\nsymbol built\n"); #endif return i * 8; } int retekess_fsk_td164_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type, bool reprogram) { dbg("system_id: %d pager_num: %d reprogram: %d tx_frequency: %.4f\n", system_id, pager_number, reprogram, tx_frequency); timerAttachInterrupt(timer, &onTimer, true); timerAlarmWrite(timer, 1000000 / 10000, true); timerAlarmEnable(timer); fsk.setOutputPower(tx_power); fsk.setFrequency(tx_frequency); fsk.setFrequencyDeviation(tx_deviation); fsk.setOOK(false); fsk.transmitDirect(); memset(tx.buffer, 0, sizeof(tx.buffer)); int len = retekess_fsk_td164_prepare(tx.buffer, pager_number, alert_type, reprogram); tx.batch_counter = 20; tx.bits = len; tx.state = TX_START; while (1) { dbg("tx.state : %d\n", tx.state); dbg("tx.batch_counter : %d\n", tx.batch_counter); dbg("tx.bit_counter : %d\n", tx.bit_counter); bool done = false; if (tx.state == TX_IDLE) { done = true; } if (done) { break; } usleep(100000); } fsk.standby(); timerAlarmDisable(timer); timerDetachInterrupt(timer); return 0; }
4,754
C++
.cpp
151
24.02649
83
0.559545
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,861
lrs.cpp
baycom_rps/src/lrs.cpp
#include "main.h" static size_t generate_lrs_paging_code(byte *telegram, size_t telegram_len, byte restaurant_id, byte system_id, int pager_number, byte alert_type) { if (telegram_len < 15) { return -1; } memset(telegram, 0, telegram_len); telegram[0] = 0xAA; telegram[1] = 0xAA; telegram[2] = 0xAA; telegram[3] = 0xFC; telegram[4] = 0x2D; telegram[5] = restaurant_id; telegram[6] = ((system_id << 4) & 0xf0) | ((pager_number >> 8) & 0xf); telegram[7] = pager_number; telegram[13] = alert_type; int crc = 0; for (int i = 0; i < 14; i++) { crc += telegram[i]; } crc %= 255; telegram[14] = crc; dbg("restaurant_id: %02x\n", restaurant_id); dbg("system_id : %02x\n", system_id); dbg("pager_number : %02x\n", pager_number); dbg("alert_type : %02x\n", alert_type); dbg("crc : %02x\n", crc); return 15; } static size_t generate_lrs_reprogramming_code(byte *telegram, size_t telegram_len, byte restaurant_id, byte system_id, int pager_number, byte vibrate) { if (telegram_len < 15) { return -1; } memset(telegram, 0x00, telegram_len); telegram[0] = 0xAA; telegram[1] = 0xAA; telegram[2] = 0xAA; telegram[3] = 0xBA; telegram[4] = 0x52; telegram[5] = restaurant_id; telegram[6] = ((system_id << 4) & 0xf0) | ((pager_number >> 8) & 0xf); telegram[7] = pager_number; telegram[8] = 0xff; telegram[9] = 0xff; telegram[10] = 0xff; telegram[11] = (vibrate<<4)&0x10; int crc = 0; for (int i = 0; i < 14; i++) { crc += telegram[i]; } crc %= 255; telegram[14] = crc; dbg("Reprogram pager:\n"); dbg("restaurant_id: %02x\n", restaurant_id); dbg("system_id : %02x\n", system_id); dbg("pager_number : %02x\n", pager_number); dbg("vibrate : %02x\n", vibrate); dbg("crc : %02x\n", crc); return 15; } int lrs_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type, bool reprogram_pager) { byte txbuf[64]; size_t len; fsk.packetMode(); fsk.setOutputPower(tx_power); fsk.setFrequency(tx_frequency); fsk.setFrequencyDeviation(tx_deviation); fsk.setBitRate(0.622); fsk.setEncoding(RADIOLIB_ENCODING_MANCHESTER); fsk.setPreambleLength(0); fsk.setSyncWord(NULL,0); fsk.setOOK(false); fsk.setCRC(false); if(!reprogram_pager) { len = generate_lrs_paging_code(txbuf, sizeof(txbuf), restaurant_id, system_id, pager_number, alert_type); } else { len = generate_lrs_reprogramming_code(txbuf, sizeof(txbuf), restaurant_id, system_id, pager_number, alert_type); } memcpy(txbuf + len, txbuf, len); memcpy(txbuf + len * 2, txbuf, len); int state = fsk.transmit(txbuf, len * 3); if (state == RADIOLIB_ERR_PACKET_TOO_LONG) { dbg("Packet too long!\n"); } else if (state == RADIOLIB_ERR_TX_TIMEOUT) { dbg("Timed out while transmitting!\n"); } else if (state != RADIOLIB_ERR_NONE ) { dbg("Failed to transmit packet, code %d\n", state); } return state; }
3,019
C++
.cpp
93
29.354839
169
0.652025
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,862
webserver.cpp
baycom_rps/src/webserver.cpp
#include "main.h" static AsyncWebServer server(80); static AsyncWebSocket ws("/ws"); static AsyncEventSource events("/events"); static void handleNotFound(AsyncWebServerRequest *request) { String message = "File Not Found\n\n"; message += "URI: "; message += request->url(); message += "\nMethod: "; message += (request->method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += request->args(); message += "\n"; for (uint8_t i = 0; i < request->args(); i++) { message += " " + request->argName(i) + ": " + request->arg(i) + "\n"; } request->send(404, "text/plain", message); } static void page(AsyncWebServerRequest *request) { int pager_number = -1; float tx_frequency = -1; float tx_deviation = -1; int alert_type = -1; int restaurant_id = -1; int system_id = -1; bool force = false; bool reprog = false; byte mode = cfg.default_mode; int pocsag_baud = cfg.pocsag_baud; int tx_power = cfg.tx_power; func_t pocsag_telegram_type = FUNC_BEEP; String message; bool cancel = false; int multi_pager_types = cfg.multi_pager_types; if (request->hasArg("alert_type")) { alert_type = request->arg("alert_type").toInt(); } if (request->hasArg("restaurant_id")) { restaurant_id = request->arg("restaurant_id").toInt(); } if (request->hasArg("system_id")) { system_id = request->arg("system_id").toInt(); } if (request->hasArg("force")) { force = request->arg("force").toInt(); } if (request->hasArg("reprogram")) { reprog = request->arg("reprogram").toInt(); } if (request->hasArg("cancel")) { cancel = request->arg("cancel").toInt(); } if (request->hasArg("mode")) { mode = request->arg("mode").toInt(); } if (request->hasArg("pager_number")) { pager_number = request->arg("pager_number").toInt(); if (mode == 0) { pager_number = abs(pager_number) & 0xfff; } } if (request->hasArg("tx_frequency")) { tx_frequency = request->arg("tx_frequency").toFloat(); } if (request->hasArg("tx_deviation")) { tx_deviation = request->arg("tx_deviation").toFloat(); } if (request->hasArg("tx_power")) { tx_power = request->arg("tx_power").toInt(); } if (request->hasArg("pocsag_baud")) { pocsag_baud = request->arg("pocsag_baud").toInt(); } if (request->hasArg("pocsag_telegram_type")) { pocsag_telegram_type = (func_t)request->arg("pocsag_telegram_type").toInt(); } if (request->hasArg("message")) { message = request->arg("message"); } if (request->hasArg("multi_pager_types")) { multi_pager_types = request->arg("multi_pager_types").toInt(); } if (pager_number > 0 || force) { String str = "mode: " + String(mode) + "\ntx_power: " + String(tx_power) + "\ntx_frequency: " + String(tx_frequency, 5) + "\ntx_deviation: " + String(tx_deviation) + "\npocsag_baud: " + String(pocsag_baud) + "\nrestaurant_id: " + String(restaurant_id) + "\nsystem_id: " + String(system_id) + "\nreprogram:" + String(reprog) + "\ncancel:" + String(cancel) + "\npager_number: " + String(pager_number) + "\nalert_type: " + String(alert_type) + "\npocsag_telegram_type: " + String(pocsag_telegram_type) + "\nmessage: " + message + "\nmulti_pager_types: " + String(multi_pager_types) + "\n"; AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", str); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); if (multi_pager_types) { for (int i = 0; i < 16; i++) { if (multi_pager_types & (1 << i)) { call_pager(i, tx_power, tx_frequency, tx_deviation, pocsag_baud, restaurant_id, system_id, pager_number, alert_type, reprog, pocsag_telegram_type, message.c_str(), cancel); } } } else { call_pager(mode, tx_power, tx_frequency, tx_deviation, pocsag_baud, restaurant_id, system_id, pager_number, alert_type, reprog, pocsag_telegram_type, message.c_str(), cancel); } } else { request->send(400, "text/plain", "Invalid parameters supplied"); } } void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { if (type == WS_EVT_CONNECT) { // client connected info("ws[%s][%u] connect\n", server->url(), client->id()); String str = get_settings(); client->printf("%s", str.c_str()); client->ping(); } else if (type == WS_EVT_DISCONNECT) { // client disconnected info("ws[%s][%u] disconnect: %u\n", server->url(), client->id()); } else if (type == WS_EVT_ERROR) { // error was received from the other end info("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data); } else if (type == WS_EVT_PONG) { // pong message was received (in response to a ping request maybe) info("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : ""); } else if (type == WS_EVT_DATA) { // data packet AwsFrameInfo *info = (AwsFrameInfo *)arg; if (info->final && info->index == 0 && info->len == len) { // the whole message is in a single frame and we got all of it's // data info("ws[%s][%u] %s-message[%llu]: ", server->url(), // client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", // info->len); if (info->opcode == WS_TEXT) { data[len] = 0; info("data: %s\n", (char *)data); // parse_cmd((char *)data, client); } } } } void webserver_setup() { // attach AsyncWebSocket ws.onEvent(onEvent); server.addHandler(&ws); // attach AsyncEventSource server.addHandler(&events); server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse_P( 200, "text/html", data_index_html_start, data_index_html_end - data_index_html_start - 1); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); }); server.on("/script.js", HTTP_GET, [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse_P( 200, "application/javascript", data_script_js_start, data_script_js_end - data_script_js_start - 1); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); }); server.on("/settings.json", HTTP_GET, [](AsyncWebServerRequest *request) { String output = get_settings(); AsyncWebServerResponse *response = request->beginResponse(200, "application/json", output); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); }); server.on( "/settings.json", HTTP_OPTIONS, [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse(204, "text/html"); response->addHeader("Access-Control-Allow-Origin", "*"); response->addHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); response->addHeader("Access-control-Allow-Credentials", "false"); response->addHeader("Access-control-Allow-Headers", "x-requested-with"); response->addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type"); request->send(response); }); server.on( "/settings.json", HTTP_POST, [](AsyncWebServerRequest *request) {}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) { DynamicJsonDocument json(1024); DeserializationError error = deserializeJson(json, data); info("/settings.json: post settings (%d)\n", error); if (error || !parse_settings(json)) { request->send(501, "text/plain", "deserializeJson failed"); } else { String output = get_settings(); AsyncWebServerResponse *response = request->beginResponse(200, "application/json", output); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); info("/settings.json: post settings done\n"); } }); server.on("/reboot", [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "OK"); response->addHeader("Connection", "close"); request->send(response); EEPROM.commit(); sleep(1); ESP.restart(); }); server.on("/factoryreset", [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "OK"); response->addHeader("Connection", "close"); response->addHeader("Access-Control-Allow-Origin", "*"); request->send(response); cfg.version = 0xff; write_config(); sleep(1); ESP.restart(); }); server.on("/page", page); server.onNotFound(handleNotFound); server.begin(); }
9,984
C++
.cpp
238
32.684874
79
0.562269
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,863
pager.cpp
baycom_rps/src/pager.cpp
#include "main.h" SX1276 fsk = new Module(LoRa_CS, LoRa_DIO0, LoRa_RST, LoRa_DIO1); hw_timer_t *timer = NULL; static SemaphoreHandle_t xSemaphore; int pager_setup(void) { dbg("MOSI: %d MISO: %d SCK: %d SS: %d\n", MOSI, MISO, SCK, SS); xSemaphore = xSemaphoreCreateBinary(); if ((xSemaphore) != NULL) { xSemaphoreGive(xSemaphore); } timer = timerBegin(1, 80, true); if (!timer) { err("timer setup failed\n"); return -1; } pinMode(LoRa_DIO2, OUTPUT); cfg.tx_deviation = range_check(cfg.tx_deviation, 0.1, 200); cfg.retekess_tx_deviation = range_check(cfg.retekess_tx_deviation, 0.1, 200); cfg.retekess_tx_frequency = range_check(cfg.retekess_tx_frequency, 137.0, 1020.0); cfg.tx_frequency = range_check(cfg.tx_frequency, 137.0, 1020.0); int state = fsk.beginFSK(cfg.tx_frequency); if (state != RADIOLIB_ERR_NONE) { info("beginFSK failed, code %d\n", state); } cfg.tx_current_limit = range_check(cfg.tx_current_limit, 45, 240); state |= fsk.setCurrentLimit(cfg.tx_current_limit); if (state != RADIOLIB_ERR_NONE) { info("setCurrentLimit failed, code %d\n", state); } cfg.tx_power = range_check(cfg.tx_power, 2, 20); state |= fsk.setOutputPower(cfg.tx_power, false); if (state != RADIOLIB_ERR_NONE) { info("setOutputPower failed, code %d\n", state); } if (state != RADIOLIB_ERR_NONE) { info("beginFSK failed, code %d\n", state); #ifdef HAS_DISPLAY display.clear(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_24); display.drawString(64, 14, "SX127X"); display.drawString(64, 42, "FAIL"); d(); #endif } return state; } int call_pager(byte mode, int tx_power, float tx_frequency, float tx_deviation, int pocsag_baud, int restaurant_id, int system_id, int pager_number, int alert_type, bool reprogram_pager, func_t pocsag_telegram_type, const char *message, bool cancel) { int ret = -1; xSemaphoreTake(xSemaphore, portMAX_DELAY); #ifdef HAS_DISPLAY display.clear(); display.setTextAlignment(TEXT_ALIGN_CENTER); display.setFont(ArialMT_Plain_24); if (!reprogram_pager) { if (!cancel) { display.drawString(64, 14, "Paging"); } else { display.drawString(64, 14, "Cancel"); } } else { display.drawString(64, 14, "Reprog"); } display.drawString(64, 42, String(pager_number)); d(); #endif if (restaurant_id == -1) restaurant_id = cfg.restaurant_id; switch (mode) { case 0: if (alert_type == -1) alert_type = cfg.alert_type; if (tx_frequency == -1) tx_frequency = cfg.tx_frequency; if (tx_deviation == -1) tx_deviation = cfg.tx_deviation; if (system_id == -1) system_id = cfg.system_id; ret = lrs_pager(fsk, tx_power, tx_frequency, tx_deviation, restaurant_id, system_id, pager_number, alert_type, reprogram_pager); break; case 1: if (alert_type == -1) alert_type = cfg.alert_type; if (tx_frequency == -1) tx_frequency = cfg.pocsag_tx_frequency; if (tx_deviation == -1) tx_deviation = cfg.pocsag_tx_deviation; ret = pocsag_pager(fsk, tx_power, tx_frequency, tx_deviation, pocsag_baud, pager_number, alert_type, pocsag_telegram_type, message); break; case 2: if (alert_type == -1) alert_type = cfg.retekess_alert_type; if (tx_frequency == -1) tx_frequency = cfg.retekess_tx_frequency; if (system_id == -1) system_id = cfg.retekess_system_id; ret = retekess_ook_t112_pager( fsk, tx_power, tx_frequency, tx_deviation, restaurant_id, system_id, pager_number, alert_type, cancel); break; case 3: if (alert_type == -1) alert_type = cfg.retekess_alert_type; if (tx_frequency == -1) tx_frequency = cfg.retekess_tx_frequency; if (tx_deviation == -1) tx_deviation = cfg.retekess_tx_deviation; if (system_id == -1) system_id = cfg.retekess_system_id; ret = retekess_fsk_td164_pager( fsk, tx_power, tx_frequency, tx_deviation, restaurant_id, system_id, pager_number, alert_type, reprogram_pager); break; case 4: if (alert_type == -1) alert_type = cfg.retekess_alert_type; if (tx_frequency == -1) tx_frequency = cfg.retekess_tx_frequency; if (system_id == -1) system_id = cfg.retekess_system_id; ret = retekess_ook_td161_pager(fsk, tx_power, tx_frequency, tx_deviation, restaurant_id, system_id, pager_number, alert_type); break; default: break; } xSemaphoreGive(xSemaphore); return ret; }
5,140
C++
.cpp
121
32.826446
80
0.582751
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,864
retekess_fsk_td164.h
baycom_rps/include/retekess_fsk_td164.h
#ifndef RETEKESS_FSK_TD164_H #define RETEKESS_FSK_TD164_H int retekess_fsk_td164_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type = 0, bool reprogram = false); #endif
343
C++
.h
7
35.714286
81
0.58457
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,865
cfg.h
baycom_rps/include/cfg.h
#ifndef CFG_H #define CFG_H #define EEPROM_SIZE 4096 #define OPMODE_WIFI_ACCESSPOINT 0 #define OPMODE_WIFI_STATION 1 #define OPMODE_ETH_CLIENT 2 #define cfg_ver_num 12 typedef struct { byte version; char wifi_ssid[33]; char wifi_secret[65]; char wifi_hostname[256]; byte wifi_opmode; bool wifi_powersave; float tx_frequency; float tx_deviation; int8_t tx_power; uint8_t tx_current_limit; byte restaurant_id; uint16_t system_id; byte alert_type; byte default_mode; int pocsag_baud; //Version 6 char ota_path[256]; //Version 7 bool wifi_ap_fallback; //Version 8 char ip_addr[16]; char ip_gw[16]; char ip_netmask[16]; char ip_dns[16]; //Version 9 float pocsag_tx_frequency; float pocsag_tx_deviation; float retekess_tx_frequency; uint16_t retekess_system_id; uint16_t multi_pager_types; //Version 10 float retekess_tx_deviation; //Version 11 byte retekess_alert_type; //Version 12 unsigned long display_timeout; } settings_t; void write_config(void); void read_config(void); String get_settings(void); boolean parse_settings(DynamicJsonDocument json); void factory_reset(int state); #endif
1,150
C++
.h
51
20.313725
49
0.761426
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,866
main.h
baycom_rps/include/main.h
#ifndef _MAIN_H #define _MAIN_H #include <Arduino.h> #include <WiFi.h> #include <WiFiClient.h> #include <RadioLib.h> #include <SSD1306Wire.h> #include <AsyncTCP.h> #include <ESPAsyncWebServer.h> #include <ArduinoJson.h> #include <EEPROM.h> #include <ESPmDNS.h> #include <EOTAUpdate.h> /* * ETH_CLOCK_GPIO0_IN - default: external clock from crystal oscillator * ETH_CLOCK_GPIO0_OUT - 50MHz clock from internal APLL output on GPIO0 - possibly an inverter is needed for LAN8720 * ETH_CLOCK_GPIO16_OUT - 50MHz clock from internal APLL output on GPIO16 - possibly an inverter is needed for LAN8720 * ETH_CLOCK_GPIO17_OUT - 50MHz clock from internal APLL inverted output on GPIO17 - tested with LAN8720 */ #define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT #ifdef LILYGO_POE // Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source) #define ETH_POWER_PIN 16 #else #define ETH_POWER_PIN -1 #endif // Type of the Ethernet PHY (LAN8720 or TLK110) #define ETH_TYPE ETH_PHY_LAN8720 // I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) #define ETH_ADDR 0 // Pin# of the I²C clock signal for the Ethernet PHY #define ETH_MDC_PIN 23 // Pin# of the I²C IO signal for the Ethernet PHY #define ETH_MDIO_PIN 18 #define NRST 5 #include <ETH.h> #include "version.h" #include "util.h" #include "webserver.h" #include "cfg.h" #include "display.h" #include "buttons.h" #include "lrs.h" #include "pocsag.h" #include "retekess_ook_t112.h" #include "retekess_ook_td161.h" #include "retekess_fsk_td164.h" #include "pager.h" //#define DEBUG #ifdef HELTEC #define GPIO_BUTTON GPIO_NUM_0 #define GPIO_BATTERY GPIO_NUM_37 #define OLED_ADDRESS 0x3c #define OLED_SDA 4 // GPIO4 #define OLED_SCL 15 // GPIO15 #define OLED_RST 16 // GPIO16 #define LoRa_RST 14 // GPIO 14 #define LoRa_CS 18 // GPIO 18 #define LoRa_DIO0 26 // GPIO 26 #define LoRa_DIO1 33 // GPIO 33 (Heltec v2: GPIO 35) #define LoRa_DIO2 32 // GPIO 32 (Heltec v2: GPIO 34 has to be conected to GPIO 32) #endif #ifdef OLIMEX_POE #define OLED_ADDRESS 0x3c #define OLED_SDA 36 #define OLED_SCL 36 #define OLED_RST 36 #define GPIO_BUTTON GPIO_NUM_34 #define GPIO_BATTERY GPIO_NUM_35 #define LoRa_SCK 14 // (HS2_CLK) #define LoRa_MOSO 2 // (HS2_DATA) #define LoRa_MISO 15 // (HS2_CMD) #define LoRa_CS 4 // (GPIO4) #define LoRa_RST 5 // (GPIO5) #define LoRa_DIO0 36 // (GPI36) #define LoRa_DIO1 13 // (GPIO13) #define LoRa_DIO2 16 // (GPIO16) #endif #ifdef LILYGO_POE #define OLED_ADDRESS 0x3c #define OLED_SDA 32 #define OLED_SCL 33 #define OLED_RST 34 #define GPIO_BUTTON GPIO_NUM_0 #define GPIO_BATTERY -1 #define LoRa_SCK 14 #define LoRa_MISO 2 #define LoRa_MOSI 15 #define LoRa_RST 12 #define LoRa_CS 4 #define LoRa_DIO0 16 #define Vext -1 #define PixelPin 32 #endif #ifdef DEBUG #define dbg(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #define err(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #define info(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #define warn(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #else #define dbg(format, arg...) do {} while (0) #define err(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #define info(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #define warn(format, arg...) {printf("%s:%d " format , __FILE__ , __LINE__ , ## arg);} #endif extern settings_t cfg; extern const uint8_t data_index_html_start[] asm("_binary_data_index_html_start"); extern const uint8_t data_index_html_end[] asm("_binary_data_index_html_end"); extern const uint8_t data_script_js_start[] asm("_binary_data_script_js_start"); extern const uint8_t data_script_js_end[] asm("_binary_data_script_js_end"); void power_off(int state); #endif
3,998
C++
.h
112
33.258929
118
0.685655
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,867
util.h
baycom_rps/include/util.h
#ifndef UTIL_H #define UTIL_H int bitset_lsb_first(uint8_t *data, int bitpos, int value = -1, bool reverse = false); int bitset_msb_first(uint8_t *data, int bitpos, int value = -1); int bcd(int number, int *hundreds = NULL, int *tens = NULL, int *ones = NULL); int reversenibble(int number); float range_check(float val, float min, float max); #endif
351
C++
.h
8
43
87
0.723837
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,868
pager.h
baycom_rps/include/pager.h
#ifndef PAGER_H #define PAGER_H typedef struct { int restaurant_id; int system_id; int pager_number; int alert_type; } pager_t; extern hw_timer_t *timer; extern SX1276 fsk; int pager_setup(void); int call_pager(byte mode, int tx_power, float tx_frequency, float tx_deviation, int pocsag_baud, int restaurant_id, int system_id, int pager_number, int alert_type, bool reprogram_pager, func_t pocsag_telegram_type, const char *message, bool cancel); #endif
512
C++
.h
16
27.375
79
0.698381
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,869
retekess_ook_td161.h
baycom_rps/include/retekess_ook_td161.h
#ifndef RETEKESS_OOK_TD161_H #define RETEKESS_OOK_TD161_H int retekess_ook_td161_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type); #endif
278
C++
.h
6
37.166667
78
0.652015
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,870
pocsag.h
baycom_rps/include/pocsag.h
#ifndef _POCSAG_H #define _POCSAG_H /* ---------------------------------------------------------------------- */ /* * the code used by POCSAG is a (n=31,k=21) BCH Code with dmin=5, * thus it could correct two bit errors in a 31-Bit codeword. * It is a systematic code. * The generator polynomial is: * g(x) = x^10+x^9+x^8+x^6+x^5+x^3+1 * The parity check polynomial is: * h(x) = x^21+x^20+x^18+x^16+x^14+x^13+x^12+x^11+x^8+x^5+x^3+1 * g(x) * h(x) = x^n+1 */ #define BCH_POLY 03551 /* octal */ #define BCH_N 31 #define BCH_K 21 /* * some codewords with special POCSAG meaning */ #define POCSAG_SYNC 0x7cd215d8 #define POCSAG_SYNCINFO 0x7cf21436 #define POCSAG_IDLE 0x7a89c197 #define POCSAG_SYNC_WORDS ((2000000 >> 3) << 13) #define _MAXTXBATCHES 20 typedef enum { FUNC_BEEP = 0, FUNC_NUM = 1, FUNC_ALPHA = 2 } func_t; int pocsag_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int baud, uint32_t addr, uint8_t function, func_t telegram_type, const char *msg); /* ---------------------------------------------------------------------- */ #endif /* _POCSAG_H */
1,138
C++
.h
32
33.53125
165
0.581967
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,871
lrs.h
baycom_rps/include/lrs.h
#ifndef _LRS_H #define _LRS_H int lrs_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type, bool reprogram_pager); #endif
207
C++
.h
4
51
170
0.769608
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,872
display.h
baycom_rps/include/display.h
#ifndef DISPLAY_H #define DISPLAY_H #include <SSD1306Wire.h> extern SSD1306Wire display; void display_setup(); void d(); void display_loop(); #endif
151
C++
.h
8
17.625
27
0.794326
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,873
retekess_ook_t112.h
baycom_rps/include/retekess_ook_t112.h
#ifndef RETEKESS_OOK_T112_H #define RETEKESS_OOK_T112_H int retekess_ook_t112_pager(SX1276 fsk, int tx_power, float tx_frequency, float tx_deviation, int restaurant_id, int system_id, int pager_number, int alert_type, bool cancel = false); #endif
296
C++
.h
6
40.166667
80
0.652921
baycom/rps
32
8
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,875
Arduino_LSM6DS3.h
arduino-libraries_Arduino_LSM6DS3/src/Arduino_LSM6DS3.h
/* This file is part of the Arduino_LSM6DS3 library. Copyright (c) 2019 Arduino SA. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ARDUINO_LSM6DS3_H_ #define _ARDUINO_LSM6DS3_H_ #include "LSM6DS3.h" #endif
928
C++
.h
19
46.157895
80
0.779623
arduino-libraries/Arduino_LSM6DS3
30
31
17
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,876
LSM6DS3.h
arduino-libraries_Arduino_LSM6DS3/src/LSM6DS3.h
/* This file is part of the Arduino_LSM6DS3 library. Copyright (c) 2019 Arduino SA. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <Arduino.h> #include <Wire.h> #include <SPI.h> #define LSM6DS3_ADDRESS 0x6A #define LSM6DS3_WHO_AM_I_REG 0X0F #define LSM6DS3_CTRL1_XL 0X10 #define LSM6DS3_CTRL2_G 0X11 #define LSM6DS3_STATUS_REG 0X1E #define LSM6DS3_CTRL6_C 0X15 #define LSM6DS3_CTRL7_G 0X16 #define LSM6DS3_CTRL8_XL 0X17 #define LSM6DS3_OUT_TEMP_L 0X20 #define LSM6DS3_OUTX_L_G 0X22 #define LSM6DS3_OUTX_H_G 0X23 #define LSM6DS3_OUTY_L_G 0X24 #define LSM6DS3_OUTY_H_G 0X25 #define LSM6DS3_OUTZ_L_G 0X26 #define LSM6DS3_OUTZ_H_G 0X27 #define LSM6DS3_OUTX_L_XL 0X28 #define LSM6DS3_OUTX_H_XL 0X29 #define LSM6DS3_OUTY_L_XL 0X2A #define LSM6DS3_OUTY_H_XL 0X2B #define LSM6DS3_OUTZ_L_XL 0X2C #define LSM6DS3_OUTZ_H_XL 0X2D class LSM6DS3Class { public: LSM6DS3Class(TwoWire& wire, uint8_t slaveAddress); LSM6DS3Class(SPIClass& spi, int csPin, int irqPin); virtual ~LSM6DS3Class(); int begin(); void end(); // Accelerometer virtual int readAcceleration(float& x, float& y, float& z); // Results are in g (earth gravity). virtual float accelerationSampleRate(); // Sampling rate of the sensor. virtual int accelerationAvailable(); // Check for available data from accelerometer // Gyroscope virtual int readGyroscope(float& x, float& y, float& z); // Results are in degrees/second. virtual float gyroscopeSampleRate(); // Sampling rate of the sensor. virtual int gyroscopeAvailable(); // Check for available data from gyroscope // Temperature Sensor virtual int readTemperature(float& t); // Results are in deg. C virtual float temperatureSampleRate(); // Sampling rate of the sensor. virtual int temperatureAvailable(); // Check for available data from temperature sensor protected: int readRegister(uint8_t address); int readRegisters(uint8_t address, uint8_t* data, size_t length); int writeRegister(uint8_t address, uint8_t value); private: TwoWire* _wire; SPIClass* _spi; uint8_t _slaveAddress; int _csPin; int _irqPin; SPISettings _spiSettings; }; extern LSM6DS3Class IMU_LSM6DS3; #undef IMU #define IMU IMU_LSM6DS3
3,161
C++
.h
73
40.123288
100
0.710277
arduino-libraries/Arduino_LSM6DS3
30
31
17
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,877
QC3Client.h
Crypter_QC3Client/src/QC3Client.h
#ifndef QC3CLIENT #define QC3CLIENT class QC3ClientClass { private: enum QC3Pins { //order is important!!! dp10k = 0, dn10k = 1, dp2k2 = 2, dn2k2 = 3, dp = 4, dn = 5, MAX }; uint8_t pinsInit = 0, qcInit = 0; uint8_t pins[4]; uint16_t voltageLevel = 5000; uint32_t initTimer = 0; uint8_t continuousMode = 0; void setPinVoltage(QC3Pins pin, int16_t milliVolts) { if (pin != dp && pin != dn) return; uint8_t dX10k = pins[(uint8_t)pin - 4]; uint8_t dX2k2 = pins[(uint8_t)pin - 2]; if (milliVolts == 0) { pinMode(dX2k2, OUTPUT); pinMode(dX10k, OUTPUT); digitalWrite(dX2k2, LOW); digitalWrite(dX10k, LOW); } else if (milliVolts == 3300) { pinMode(dX2k2, OUTPUT); pinMode(dX10k, OUTPUT); digitalWrite(dX2k2, HIGH); digitalWrite(dX10k, HIGH); } else if (milliVolts == 600) { pinMode(dX2k2, OUTPUT); pinMode(dX10k, OUTPUT); digitalWrite(dX2k2, LOW); digitalWrite(dX10k, HIGH); } else if (milliVolts == 2700) { //never used pinMode(dX2k2, OUTPUT); pinMode(dX10k, OUTPUT); digitalWrite(dX2k2, HIGH); digitalWrite(dX10k, LOW); } else { pinMode(dX2k2, INPUT); pinMode(dX10k, INPUT); } } public: QC3ClientClass() {} uint8_t configure(uint8_t DataPositive10k, uint8_t DataPositive2k2, uint8_t DataNegative10k, uint8_t DataNegative2k2) { if ( qcInit == 0 ) { pins[(int)QC3Pins::dp10k] = DataPositive10k; pins[(int)QC3Pins::dp2k2] = DataPositive2k2; pins[(int)QC3Pins::dn10k] = DataNegative10k; pins[(int)QC3Pins::dn2k2] = DataNegative2k2; pinsInit = 1; return 0; } else { return -1; } } uint8_t begin(uint8_t QC2Mode = 0, uint8_t blocking = 1) { if (pinsInit) { if (initTimer == 0) { setPinVoltage(dp, 600); setPinVoltage(dn, -1); if (blocking) { delay(1300); setPinVoltage(dp, 600); setPinVoltage(dn, 0); delay(100); initTimer = 1; qcInit = 3 - (!!QC2Mode); if (qcInit == 3) { //QC3 handshake setPinVoltage(dp, 600); setPinVoltage(dn, 3300); delay(100); //stabilize voltageLevel = 5000; } return 0; } initTimer = millis() + 1; // +1 to avoid millis() = 0 bug on super fast startup return 1; } else if (blocking == 0 && millis() - initTimer > 1300) { setPinVoltage(dp, 600); setPinVoltage(dn, 0); delay(100); qcInit = 3 - (!!QC2Mode); if (qcInit == 3) { //QC3 handshake setPinVoltage(dp, 600); setPinVoltage(dn, 3300); delay(100); //stabilize voltageLevel = 50; } return 0; } } else if (qcInit) { return 0; } else { return -1; } } void end() { setPinVoltage(dp, 0); setPinVoltage(dn, 0); initTimer = 0; qcInit = 0; } uint16_t setMillivolts(uint16_t millivolts) { if (qcInit && millivolts <= 12000 && millivolts >= 3600) { uint16_t normalizedMillivolts = millivolts / 100; if (normalizedMillivolts % 2) { normalizedMillivolts --; } normalizedMillivolts *= 100; if (normalizedMillivolts == voltageLevel) return voltageLevel; if (qcInit == 3) { if (continuousMode == 0) { //handshake setPinVoltage(dp, 600); setPinVoltage(dn, 3300); delay(1); continuousMode = 1; voltageLevel = 5000; } while (voltageLevel < normalizedMillivolts && voltageLevel < 12000 ) { setPinVoltage(dp, 3300); setPinVoltage(dn, 3300); delay(1); setPinVoltage(dp, 600); setPinVoltage(dn, 3300); delay(1); voltageLevel += 200; } while (voltageLevel > normalizedMillivolts && voltageLevel > 3600) { setPinVoltage(dp, 600); setPinVoltage(dn, 600); delay(1); setPinVoltage(dp, 600); setPinVoltage(dn, 3300); delay(1); voltageLevel -= 200; } } else if (qcInit == 2 && (normalizedMillivolts == 12000 || normalizedMillivolts == 9000 || normalizedMillivolts == 5000)) { switch (normalizedMillivolts) { case 12000: setPinVoltage(dp, 600); setPinVoltage(dn, 600); delay(1); voltageLevel = normalizedMillivolts; break; case 9000: setPinVoltage(dp, 3300); setPinVoltage(dn, 600); delay(1); voltageLevel = normalizedMillivolts; break; case 5000: setPinVoltage(dp, 600); setPinVoltage(dn, 0); delay(1); voltageLevel = normalizedMillivolts; break; } } else { return 0; } return voltageLevel; } return 0; } uint16_t getMillivolts(){ return voltageLevel; } }; extern QC3ClientClass QC3Client = QC3ClientClass(); #endif
5,472
C++
.h
176
21.465909
132
0.529367
Crypter/QC3Client
39
3
0
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,878
aoatransmitter.cpp
bsnet_bleaoa/src/aoatransmitter.cpp
/* * Copyright 2017 Francesco Gringoli <francesco.gringoli@unibs.it> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <uhd/types/tune_request.hpp> #include <uhd/utils/thread_priority.hpp> #include <uhd/utils/safe_main.hpp> #include <uhd/usrp/multi_usrp.hpp> #include <uhd/exception.hpp> #include <boost/program_options.hpp> #include <boost/format.hpp> #include <boost/thread.hpp> #include <iostream> #include <fstream> #include <csignal> #include <complex> #include <pthread.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include "blegenerator.hpp" namespace po = boost::program_options; static bool stop_signal_called = false; void sig_int_handler(int){stop_signal_called = true;} struct txthreadpars { uhd::usrp::multi_usrp::sptr *usrp; size_t samps_per_buff; double msdelay; int channel; }; int global_frequency = 0; void *tx_thread_routine(void *pars) { struct txthreadpars *txpar = (struct txthreadpars *) pars; uhd::usrp::multi_usrp::sptr usrp = *(txpar->usrp); const std::string cpu_format = "sc8"; size_t samps_per_buff = txpar->samps_per_buff; int channel = txpar->channel; // create a transmit streamer uhd::stream_args_t stream_args(cpu_format, cpu_format); uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args); // create the stream uhd::tx_metadata_t md; md.start_of_burst = false; md.end_of_burst = false; int counter = 0; #define ZERO_PAD_BYTES 100 std::cout << "tx start" << std::endl; int old_global_frequency = global_frequency; // generate once for ever do { std::vector<int8_t> buff = generatesamples(channel, counter, ZERO_PAD_BYTES); size_t num_tx_samps = buff.size() / 2; md.end_of_burst = true; int ssent = (int) tx_stream->send(&buff.front(), num_tx_samps, md); // std::cout << "Sent synch" << std::endl; //boost::this_thread::sleep(boost::posix_time::milliseconds(10)); // txpar->msdelay)); counter ++; if (global_frequency != old_global_frequency) { double txfreq = double(global_frequency) * 1000000; uhd::tune_request_t tune_request = uhd::tune_request_t(txfreq); usrp->set_tx_freq(tune_request); old_global_frequency = global_frequency; } else { usleep(10000); } } while(not stop_signal_called); //finished std::cout << std::endl << "tx stream done!" << std::endl << std::endl; return NULL; } bool check_locked_tx(uhd::usrp::multi_usrp::sptr usrp) { //Check Ref and LO Lock detect std::vector<std::string> sensor_names; sensor_names = usrp->get_tx_sensor_names(0); if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) { uhd::sensor_value_t lo_locked = usrp->get_tx_sensor("lo_locked",0); std::cout << boost::format("Checking TX: %s ...") % lo_locked.to_pp_string() << std::endl; UHD_ASSERT_THROW(lo_locked.to_bool()); } return true; } double ble_chan2freq(int channel) { double freq = 2402; if(channel < 11) freq = 2404 + channel * 2; else if(channel < 37) freq = 2428 + (channel - 11) * 2; else if(channel == 37) freq = 2402; else if(channel == 38) freq = 2426; else if(channel == 39) freq = 2480; else { fprintf(stderr, "Invalid channel, defaulting to 37\n"); freq = 2402; } return freq * 1e6; } /* * set up a single device for transmitting at the requested channel */ uhd::usrp::multi_usrp::sptr usrp_setup(std::string chainname, std::string args, double txgain, int blechannel) { double txfreq = ble_chan2freq(blechannel); // create a usrp device std::cout << boost::format("Setting up chain %s ") % chainname << std::endl; std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl; uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args); std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl; // lock mboard clocks std::string ref = "internal"; usrp->set_clock_source(ref); // always select the subdevice first, the channel mapping affects the other settings // if (vm.count("rxsubdev")) usrp->set_rx_subdev_spec(""); //set the sample rate for txing double txrate = 2000000; std::cout << boost::format("Setting TX Rate for %s: %f Msps...") % chainname % (txrate / 1e6) << std::endl; usrp->set_tx_rate(txrate); std::cout << boost::format("Actual TX Rate for %s: %f Msps...") % chainname % (usrp->get_tx_rate() / 1e6) << std::endl; //set the center frequency std::cout << boost::format("Setting TX Freq for %s: %f MHz...") % chainname % (txfreq / 1e6) << std::endl; uhd::tune_request_t tune_request = uhd::tune_request_t(txfreq); usrp->set_tx_freq(tune_request); std::cout << boost::format("Actual TX Freq for %s: %f MHz...") % chainname % (usrp->get_tx_freq() / 1e6) << std::endl; //set the rf gain std::cout << boost::format("Setting TX Gain for %s: %f dB...") % chainname % txgain << std::endl; usrp->set_tx_gain(txgain); std::cout << boost::format("Actual TX Gain for %s: %f dB...") % chainname % usrp->get_tx_gain() << std::endl; //set the antenna std::string txant = "J1"; usrp->set_tx_antenna(txant); return usrp; } int UHD_SAFE_MAIN(int argc, char *argv[]) { uhd::set_thread_priority_safe(); //variables to be set by po std::string args; double txgain; int channel; size_t samples_per_buffer = 10000; //setup the program options po::options_description desc("Allowed options"); desc.add_options() ("help", "help message") ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args") ("channel", po::value<int>(&channel)->default_value(37), "ble channel") ("txgain", po::value<double>(&txgain)->default_value(50), "tx gain for the RF chain") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); //print the help message if (vm.count("help")) { std::cout << boost::format("ble advertiser. %s") % desc << std::endl; std::cout << std::endl; return ~0; } uhd::usrp::multi_usrp::sptr usrp; usrp = usrp_setup("chain", args, txgain, channel); double setup_time = 1; usleep(100000); check_locked_tx(usrp); // check Ref and LO Lock detect boost::this_thread::sleep(boost::posix_time::seconds(1)); // allow for some setup time //set sigint if user wants to interrupt std::signal(SIGINT, &sig_int_handler); std::cout << "Press Ctrl + C to stop streaming..." << std::endl; pthread_t txthread; struct txthreadpars txpar; txpar.usrp = &usrp; txpar.samps_per_buff = samples_per_buffer; txpar.channel = channel; pthread_create(&txthread, NULL, tx_thread_routine, (void *) &txpar); int soc = socket(PF_INET, SOCK_DGRAM, 0); if( soc == -1 ) { fprintf(stderr, "Cannot create socket\n"); return -1; } struct sockaddr_in local, remote; local.sin_family = PF_INET; local.sin_port = htons ((short) 8082); local.sin_addr.s_addr = htonl (INADDR_ANY); if (bind (soc, (struct sockaddr*)&local, sizeof(local)) == -1) { fprintf (stderr, "Cannot bind socket\n"); close (soc); return 1; } #define BUFFER_LENGTH 1000 char buffer[BUFFER_LENGTH]; socklen_t size_remote = sizeof(remote); while (not stop_signal_called) { int retc = recvfrom(soc, buffer, BUFFER_LENGTH, 0, (struct sockaddr*) &remote, &size_remote); if (retc == -1) { fprintf(stderr, "Error receiving from socket\n"); close (soc); return 1; } int *frequency = (int *) buffer; printf("new frequency = %d\n", *frequency); global_frequency = *frequency; } pthread_join (txthread, NULL); return EXIT_SUCCESS; }
8,867
C++
.cpp
237
32.097046
102
0.635919
bsnet/bleaoa
38
12
1
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,879
blegenerator.cpp
bsnet_bleaoa/src/blegenerator.cpp
/* * Copyright 2017 by Francesco Gringoli <francesco.gringoli@unibs.it> * Copyright 2017 by Jiang Wei <jiangwei@jiangwei.org> * Copyright 2015 by Xianjun Jiao (putaoshu@gmail.com) * Copyright 2013 Florian Echtler <floe@butterbrot.org> * * This file is part of some open source application. * * Some open source application is free software: you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either * version 3 of the License, or (at your option) any later version. * * Some open source application is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the application. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <iostream> #include <complex> #define _USE_MATH_DEFINES #include <math.h> #include <inttypes.h> #include <stdint.h> #include <vector> #include <functional> #include <arpa/inet.h> #define MAX_NUM_PHY_SAMPLE 1520 #define MAX_NUM_CHAR_CMD (256) #define MAX_NUM_PHY_BYTE (47) #define SAMPLE_PER_SYMBOL 2 // #define LEN_GAUSS_FILTER (4) // pre 2, post 2 #define MAX_LE_SYMBOLS 64 #define LE_ADV_AA 0x8E89BED6 class BLESDR { public: BLESDR(); ~BLESDR(); std::vector<float> sample_for_raw_packet(size_t chan, int counter); private: std::vector<float> iqsamples; size_t byte_to_bits(uint8_t* byte, size_t len, char* bits); float* generate_gaussian_taps(unsigned samples_per_sym, unsigned L, double bt); void btle_calc_crc(void* src, uint8_t len, uint8_t* dst); void btle_whiten(uint8_t chan, uint8_t* buf, uint8_t len); int gen_sample_from_phy_bit(char *bit, float *sample, int num_bit); float tmp_phy_bit_over_sampling[MAX_NUM_PHY_SAMPLE + 2 * LEN_GAUSS_FILTER*SAMPLE_PER_SYMBOL]; float tmp_phy_bit_over_sampling1[MAX_NUM_PHY_SAMPLE]; float * gauss_coef; uint8_t chan; int srate; void dump_btle_packet(uint8_t *packet, int length); }; void BLESDR::dump_btle_packet(uint8_t *pp, int length) { for(int kk = 0; kk < length; kk ++) { printf("%02X ", pp[kk]); } printf("\n"); } BLESDR::BLESDR() : chan(37), srate(2) { gauss_coef = generate_gaussian_taps(SAMPLE_PER_SYMBOL, LEN_GAUSS_FILTER, 0.5); } BLESDR::~BLESDR() { delete gauss_coef; } size_t BLESDR::byte_to_bits(uint8_t* byte, size_t len, char* bits) { for (int j = 0; j < len; j++) { for (int i = 0; i < 8; i++) { // Mask each bit in the byte and store it bits[j * 8 + i] = (byte[j] >> i) & 1; } } return len * 8; } void BLESDR::btle_calc_crc(void* src, uint8_t len, uint8_t* dst) { uint8_t* buf = (uint8_t*)src; // initialize 24-bit shift register in "wire bit order" // dst[0] = bits 23-16, dst[1] = bits 15-8, dst[2] = bits 7-0 dst[0] = 0xAA; dst[1] = 0xAA; dst[2] = 0xAA; while (len--) { uint8_t d = *(buf++); for (uint8_t i = 1; i; i <<= 1, d >>= 1) { // save bit 23 (highest-value), left-shift the entire register by one uint8_t t = dst[0] & 0x01; dst[0] >>= 1; if (dst[1] & 0x01) dst[0] |= 0x80; dst[1] >>= 1; if (dst[2] & 0x01) dst[1] |= 0x80; dst[2] >>= 1; // if the bit just shifted out (former bit 23) and the incoming data // bit are not equal (i.e. bit_out ^ bit_in == 1) => toggle tap bits if (t != (d & 1)) { // toggle register tap bits (=XOR with 1) according to CRC polynom dst[2] ^= 0xDA; // 0b11011010 inv. = 0b01011011 ^= x^6+x^4+x^3+x+1 dst[1] ^= 0x60; // 0b01100000 inv. = 0b00000110 ^= x^10+x^9 } } } } void BLESDR::btle_whiten(uint8_t chan, uint8_t* buf, uint8_t len) { // initialize LFSR with current channel, set bit 6 uint8_t lfsr = chan | 0x40; while (len--) { uint8_t res = 0; // LFSR in "wire bit order" for (uint8_t i = 1; i; i <<= 1) { if (lfsr & 0x01) { lfsr ^= 0x88; res |= i; } lfsr >>= 1; } *(buf++) ^= res; } } std::vector<float> BLESDR::sample_for_raw_packet(size_t chan, int counter) { // second byte (packet length) covers from third byte to crc-excluded // last three bytes are CRC uint8_t packet[] = {0x40, 0x1E, 0x8A, 0xCE, 0xEE, 0xB7, 0x69, 0x88, 0x07, 0x1C, 0xB9, 0x16, 0x54, 0x2F, 0x61, 0xAC, 0xCC, 0x27, 0x45, 0x67, 0xF7, 0xDB, 0x34, 0xC4, 0x03, 0x8E, 0x5C, 0x0B, 0xAA, 0x97, 0x30, 0x56, 0x00, 0x00, 0x00}; /* 0x40, 0x14, // header 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, // adv mac address 0x02, 0x01, 0x1A, 0x0A, 0xFF, 0x4C, 0x00, // data 0x10, 0x05, 0x0A, 0x10, 0x11, 0xEB, 0x20, // data 0x00, 0x00, 0x00, // crc }; */ *(int32_t*)(packet + 12) = htonl(counter); uint8_t preamble = 0xAA; const uint32_t access_address = LE_ADV_AA; // calculate CRC over header+MAC+payload, append after payload btle_calc_crc(packet, sizeof(packet) - 3, packet + sizeof(packet) - 3); // apply whitening btle_whiten(chan, packet, sizeof(packet)); // 5 accounts for preamble + AA size_t numbits = (sizeof(packet) + 5) * 8; int offset = 0; char *bits = new char[numbits]; iqsamples.resize((numbits * SAMPLE_PER_SYMBOL + (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL)) * 2); offset = byte_to_bits(&preamble, 1, bits); offset += byte_to_bits((uint8_t*) &access_address, 4, bits + offset); offset += byte_to_bits(packet, sizeof(packet), bits + offset); int num_phy_sample = gen_sample_from_phy_bit(bits, iqsamples.data(), numbits); delete bits; return iqsamples; } int BLESDR::gen_sample_from_phy_bit(char *bit, float *sample, int num_bit) { int num_sample = (num_bit * SAMPLE_PER_SYMBOL) + (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL); int i, j; for (i = 0; i < (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL - 1); i++) { tmp_phy_bit_over_sampling[i] = 0.0; } for (i = (1 * LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL - 1 + num_bit * SAMPLE_PER_SYMBOL); i < (2 * LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL - 2 + num_bit * SAMPLE_PER_SYMBOL); i ++) { tmp_phy_bit_over_sampling[i] = 0.0; } for (i = 0; i < (num_bit * SAMPLE_PER_SYMBOL); i++) { if (i % SAMPLE_PER_SYMBOL == 0) { tmp_phy_bit_over_sampling[i + (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL - 1)] = (float)(bit[i / SAMPLE_PER_SYMBOL]) * 2.0 - 1.0; } else { tmp_phy_bit_over_sampling[i + (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL - 1)] = 0.0; } } int len_conv_result = num_sample - 1; for (i = 0; i < len_conv_result; i++) { float acc = 0; for (j = 0; j < (LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL); j++) { acc = acc + gauss_coef[(LEN_GAUSS_FILTER * SAMPLE_PER_SYMBOL) - j - 1] * tmp_phy_bit_over_sampling[i + j]; } tmp_phy_bit_over_sampling1[i] = acc; } float tmp = 0; sample[0] = cosf(tmp); sample[1] = sinf(tmp); for (i = 1; i < num_sample; i++) { tmp = tmp + (M_PI * 0.5) * tmp_phy_bit_over_sampling1[i - 1] / ((float)SAMPLE_PER_SYMBOL); sample[i * 2 + 0] = cos(tmp); sample[i * 2 + 1] = sin(tmp); } return(num_sample); } float* BLESDR::generate_gaussian_taps(unsigned samples_per_sym, unsigned L, double bt) { float* taps = new float[L*samples_per_sym]; double scale = 0; double dt = 1.0 / samples_per_sym; double s = 1.0 / (sqrt(log(2.0)) / (2 * M_PI*bt)); double t0 = -0.5 * L*samples_per_sym; double ts; for (unsigned i = 0; i < L*samples_per_sym; i++) { t0++; ts = s*dt*t0; taps[i] = exp(-0.5*ts*ts); scale += taps[i]; } for (unsigned i = 0; i < L*samples_per_sym; i++) taps[i] = taps[i] / scale; return taps; } std::vector<int8_t> generatesamples(int tx_chan, int counter, int padbytes) { BLESDR ble; std::vector<float> samples = ble.sample_for_raw_packet(tx_chan, counter); std::vector<int8_t> samples8bit; int samplen = samples.size(); samples8bit.resize(samplen + padbytes); for(int kk = 0; kk < samples8bit.size(); kk ++) { if(kk < samplen) { float sample = *(samples.data() + kk); sample = sample * 128; if(sample > 127) sample = 127; if(sample < -128) sample = -128; int8_t val = (int8_t) sample; samples8bit.data()[kk] = val; } else { samples8bit.data()[kk] = 0; } } return samples8bit; }
8,391
C++
.cpp
234
32.517094
231
0.634919
bsnet/bleaoa
38
12
1
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,880
aoareceiver.cpp
bsnet_bleaoa/src/aoareceiver.cpp
/* * Copyright 2019 Marco Cominelli * Copyright 2019 Francesco Gringoli * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <uhd/types/tune_request.hpp> #include <uhd/utils/thread_priority.hpp> #include <uhd/utils/safe_main.hpp> #include <uhd/usrp/multi_usrp.hpp> #include <boost/program_options.hpp> #include <boost/format.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <csignal> #include <boost/algorithm/string.hpp> #include <iostream> #include <complex> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #define XOR(x,y) ((x && !y) || (!x && y)) namespace po = boost::program_options; volatile static bool stop_signal = false; void sigint_handler(int) {stop_signal = true;} volatile static int counter = 0; pthread_spinlock_t lock[2]; volatile size_t bankA_nsamps, bankB_nsamps; struct proc_pars_t { std::vector<std::complex<float> *> bankA_ptrs; std::vector<std::complex<float> *> bankB_ptrs; size_t samps_per_buff; }; typedef struct MyData { size_t sn; float aoa; float amplitude[2]; } mydata_t; typedef struct Command { int type; int value; } cmd_t; volatile int do_print = 0; bool do_hop = false; bool change_gain = false; double gain, freq; unsigned int freq_inc = 0; /* * Useful commands for running experiments. * (type corresponding letters while program is running) */ void* keyboard_routine(void* pars) { while (stop_signal == false) { int c = fgetc(stdin); if (c == 'p') { // print 1 pkt info to file do_print = 1; } else if (c == 'g') { // adjust gain change_gain = true; } else if (c == 'h') { // hop to next channel (0 to 39) do_hop = true; } else if (c == 'r') { // run complete capture sleep(4); printf("\a"); // beep alert (start) for (int kk = 0; kk < 40; kk++) { do_hop = true; sleep(1); do_print = 30; while(do_print > 0) usleep(5000); } printf("\a"); // beep alert (stop) } usleep(1000); } return NULL; } inline void dewhiten(uint8_t *pdu, unsigned int length) { /* Scheme of the LFSR used for dewhitening * * 7 6 5 4 3 2 1 0 * +---+---+---+---+---+---+---+---+ * | x | 1 | c | c | c | c | c | c | * +---+---+---+---+---+---+---+---+ * * Shifting right every tick. */ uint8_t lfsr = 0x40 | (0x3f & 22); // Channel 22 hardcoded for (unsigned int byte = 0; byte < length; byte++) { for (int b = 0x01; b <= 0x80; b <<=1) { if (lfsr & 0x01) { pdu[byte] ^= b; lfsr ^= 0x88; } lfsr >>= 1; } } } uint32_t compute_crc(uint8_t *pdu, int len, uint32_t init_val) { uint32_t crc = init_val; while (len--) { for (int i = 0x01; i <= 0x80; i <<= 1) { uint32_t crc_bit_is_one = crc & 0x00000001; uint32_t pdu_bit_is_one = *pdu & i; if ( XOR(crc_bit_is_one,pdu_bit_is_one) ) { crc ^= 0x01B4C000; } crc >>= 1; } pdu++; } return crc; } void *process_routine(void *pars) { struct proc_pars_t *procpars = (struct proc_pars_t *) pars; size_t kk = 0, select_bank; size_t samps_per_buff = procpars->samps_per_buff; size_t circbuf_size = 2 * samps_per_buff; std::vector<std::complex<float> *> curr_bank; float *phasebuf0 = (float *) malloc(circbuf_size * sizeof(float)); float *phasebuf1 = (float *) malloc(circbuf_size * sizeof(float)); uint8_t *binbuf0 = (uint8_t *) malloc(circbuf_size * sizeof(uint8_t)); float *amplbuf0 = (float *) malloc(circbuf_size * sizeof(float)); size_t opposite_bank; const unsigned int srate = 2; std::vector<unsigned int> snarray; unsigned int sn; float dphase; size_t idx; float *pktphase0 = (float *) malloc(128 * sizeof(float)); float *pktphase1 = (float *) malloc(128 * sizeof(float)); mydata_t mydata; float aoa_ma = 0; FILE * fptr = fopen("angles.dat", "a"); while (stop_signal == false) { select_bank = kk++ % 2; // Acquire buffer. if (select_bank == 0) curr_bank = procpars->bankA_ptrs; else curr_bank = procpars->bankB_ptrs; pthread_spin_lock(&lock[select_bank]); std::complex<float> *buff0_ptr = curr_bank[0]; std::complex<float> *buff1_ptr = curr_bank[1]; // Compute phase and binary values for (int i = 0; i < samps_per_buff; i++) { idx = i + samps_per_buff * select_bank; // Compute phase on both channels. phasebuf0[idx] = atan2f(buff0_ptr[i].imag(), buff0_ptr[i].real()); phasebuf1[idx] = atan2f(buff1_ptr[i].imag(), buff1_ptr[i].real()); // Compute amplitude (only channel 0). amplbuf0[idx] = buff0_ptr[i].real() * buff0_ptr[i].real() + buff0_ptr[i].imag() * buff0_ptr[i].imag(); // Compute phase difference (only channel 0). dphase = (idx != 0) ? phasebuf0[idx] - phasebuf0[idx-1] : phasebuf0[0] - phasebuf0[circbuf_size-1]; // Handle phase wrapping. if (dphase > M_PI) dphase -= 2 * M_PI; else if (dphase < -M_PI) dphase += 2 * M_PI; // Discriminate bits (only channel 0). binbuf0[idx] = (dphase > 0) ? 1 : 0; } opposite_bank = (select_bank + 1) % 2; sn = 0; for (int i = 0; i < samps_per_buff; i++) { idx = i + samps_per_buff * opposite_bank; uint8_t transitions = 0; // Detect preamble. for (int c = 0; c < 8 * srate; c += srate) { if (binbuf0[(idx+c+srate)%circbuf_size] > binbuf0[(idx+c)%circbuf_size]) { transitions++; } } if (transitions != 4) continue; // not a preamble uint32_t aa = 0x00; uint32_t offset = idx + 8 * srate; for (unsigned int c = 0; c < 32 * srate; c += srate) { // note: (c >> 1) = (c/srate) since srate = 2 aa |= binbuf0[(offset + c) % circbuf_size] << (c >> 1); } if (aa != 0x8e89bed6) continue; // not our aa // Extract packet length offset = idx + (8+32) * srate; // Extract packet PDU. uint8_t length = 30+2+3; uint8_t pdu[128] = {0x00}; for (int byte = 0; byte < length; byte++) for (int b = 0; b < 8; b++) pdu[byte] |= binbuf0[(offset+(byte*8+b)*srate)%circbuf_size] << b; dewhiten(pdu, length); uint32_t crc_packet = 0, crc_computed = 0; for (int byte=0; byte<3; byte++) { int bitpos = 0; for (int b = 0x01; b <= 0x80; b <<= 1) { if (pdu[32+byte] & b) { crc_packet |= 0x01 << (byte*8+bitpos); } bitpos++; } } crc_computed = compute_crc(pdu, 32, 0x00AAAAAA); if (crc_computed != crc_packet) continue; // Discard wrong CRCs. sn = pdu[15] | (pdu[14] << 8) | (pdu[13] << 16) | (pdu[12] << 24); for (int n=0; n<128 ; n++) { pktphase0[n] = phasebuf0[(idx+(8+32+16+8)*2+n)%circbuf_size]; pktphase1[n] = phasebuf1[(idx+(8+32+16+8)*2+n)%circbuf_size]; } break; } if (sn != 0 && sn >> 20 == 0) { float unwphase0[128]; float unwphase1[128]; float avg_energy = 0; float dphasetmp; // Unwrap phase unwphase0[0] = pktphase0[0]; unwphase1[0] = pktphase1[0]; for (int n=1; n<128; n++) { // Channel 0 dphasetmp = pktphase0[n]-pktphase0[n-1]; if (dphasetmp > M_PI) dphasetmp -= 2 * M_PI; else if (dphasetmp < -M_PI) dphasetmp += 2 * M_PI; unwphase0[n] = unwphase0[n-1] + dphasetmp; // Channel 1 dphasetmp = pktphase1[n]-pktphase1[n-1]; if (dphasetmp > M_PI) dphasetmp -= 2 * M_PI; else if (dphasetmp < -M_PI) dphasetmp += 2 * M_PI; unwphase1[n] = unwphase1[n-1] + dphasetmp; } float phasediff = 0, phasediff_emulated = 0; float amplitude = 0; float phaseinc = 0; for (int n = 0; n < 8; n++) phaseinc += (unwphase0[64+n] - unwphase0[64+n-1]); phaseinc /= 8; // average phase increment phasediff_emulated = unwphase0[71] + 2*phaseinc - unwphase1[73]; for (int n = 0; n < 128; n++) { phasediff += (unwphase0[n]-unwphase1[n])/128; amplitude += amplbuf0[(idx+n)%circbuf_size] / 128; } phasediff = fmodf(phasediff, 2 * M_PI); phasediff_emulated = fmodf(phasediff, 2 * M_PI); // Handle phase wrapping. if (phasediff > M_PI) phasediff -= 2 * M_PI; else if (phasediff < -M_PI) phasediff += 2 * M_PI; // Handle phase wrapping (emulated phase). if (phasediff_emulated > M_PI) phasediff_emulated -= 2 * M_PI; else if (phasediff_emulated < -M_PI) phasediff_emulated += 2 * M_PI; float lambda = 300e6/freq; const float d = 0.06; mydata.aoa = acos((lambda * phasediff)/(2 * M_PI * d)); mydata.aoa = mydata.aoa / M_PI * 180; mydata.sn = sn; mydata.amplitude[0] = amplitude; if (isnan(mydata.aoa) == 0) { printf("\rsn: %8lu, aoa: %3.0f, ampl: %8.6f, phasediff %8.6f ", mydata.sn, mydata.aoa, amplitude, phasediff_emulated); fflush(stdout); if (do_print > 0) { fprintf(fptr, "%d %f %f %f %f %f %u\n", counter, mydata.aoa, phasediff, phasediff_emulated, amplitude, gain, freq_inc/1000000 + 2400); do_print--; counter++; } } } // Release buffer if (select_bank == 0) bankA_nsamps = 0; else bankB_nsamps = 0; pthread_spin_unlock(&lock[select_bank]); } fclose(fptr); free(amplbuf0); free(pktphase0); free(pktphase1); free(binbuf0); free(phasebuf0); free(phasebuf1); return NULL; } int UHD_SAFE_MAIN(int argc, char *argv[]) { uhd::set_thread_priority_safe(); // Variables to be set by program options. std::string args, channel_list, subdev; double rate; size_t total_num_samps; // Setup program options. po::options_description desc("Allowed options"); desc.add_options() ("help", "print this help message") ("args", po::value<std::string>(&args)->default_value(""), "USRP device arguments") ("channels", po::value<std::string>(&channel_list)->default_value("0,1"), "set channels to use (e.g. \"0\", \"0,1\")") ("freq", po::value<double>(&freq)->default_value(2450e6), "set the RF center frequency (Hz)") ("gain", po::value<double>(&gain)->default_value(30), "set RF gain of the receiving chains") ("nsamps", po::value<size_t>(&total_num_samps)->default_value(10e3), "set total number of samples to receive") ("rate", po::value<double>(&rate)->default_value(2e6), "set the sampling rate (samples per second)") ("subdev", po::value<std::string>(&subdev)->default_value("A:A A:B"), "set frontend specification") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); // Print help message; if (vm.count("help")) { std::cout << "User positioning demo using AoA features" << std::endl; std::cout << desc << std::endl; return ~0; } // Create a USRP device. std::cout << "Creating USRP device..." << std::endl; uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args); std::cout << std::endl; // Select the RX subdevice first; this mapping affects all the settings. if (vm.count("subdev")) usrp->set_rx_subdev_spec(subdev); // Set the rx sample rate on all channels. std::cout << boost::format("Setting RX rate to %f MS/s\n") % (rate/1e6); usrp->set_rx_rate(rate); std::cout << boost::format("Actual RX rate: %f MS/s.\n\n") % (usrp->get_rx_rate()/1e6); // Lock motherboard clock to internal reference source and reset time register. usrp->set_clock_source("internal"); usrp->set_time_now(uhd::time_spec_t(0.0)); std::cout << "Device timestamp set to 0.0 s." << std::endl; // Set the rx center frequency on all channels. usrp->set_rx_freq(freq, 0); usrp->set_rx_freq(freq, 1); std::cout << boost::format("Center frequency set to %f MHz.\n") % (usrp->get_rx_freq()/1e6); // Set the rx gain on all channels. usrp->set_rx_gain(gain, 0); usrp->set_rx_gain(gain, 1); std::cout << boost::format("Gain set to %.1f dB.\n\n") % (usrp->get_rx_gain()); // Set the rx antennas. usrp->set_rx_antenna("TX/RX", 0); usrp->set_rx_antenna("TX/RX", 1); // Select rx channels. std::vector<std::string> channel_strings; std::vector<size_t> channel_nums; boost::split(channel_strings, channel_list, boost::is_any_of("\"',")); for (size_t c = 0; c < channel_strings.size(); c++) { size_t chan = boost::lexical_cast<int>(channel_strings[c]); if (chan < usrp->get_rx_num_channels()) { channel_nums.push_back(boost::lexical_cast<int>(channel_strings[c])); } else { throw std::runtime_error("Invalid channel(s) specified."); } } // Create a receive streamer. // It linearly maps channels (index0 = channel0, index1 = channel1, ...) uhd::stream_args_t stream_args("fc32", "sc16"); stream_args.channels = channel_nums; uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args); // Setup streaming. std::cout << "Begin streaming samples... "; uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS); stream_cmd.num_samps = total_num_samps; stream_cmd.stream_now = false; stream_cmd.time_spec = uhd::time_spec_t(2.0); rx_stream->issue_stream_cmd(stream_cmd); // Allocate receiver buffers. // There are two banks of memory containing one register per buffer. const size_t samps_per_buff = rx_stream->get_max_num_samps(); std::vector<std::vector<std::complex<float>>> bankA_buffs( usrp->get_rx_num_channels(), std::vector<std::complex<float>> (samps_per_buff) ); std::vector<std::vector<std::complex<float>>> bankB_buffs( usrp->get_rx_num_channels(), std::vector<std::complex<float>> (samps_per_buff) ); // Create a vector of pointers to each buffer. std::vector<std::complex<float> *> bankA_ptrs; std::vector<std::complex<float> *> bankB_ptrs; for (size_t i = 0; i < bankA_buffs.size(); i++) { bankA_ptrs.push_back(&bankA_buffs[i].front()); bankB_ptrs.push_back(&bankB_buffs[i].front()); } uhd::rx_metadata_t md; // metadata will be filled in by recv() double timeout = 10.0; // timeout for recv() size_t num_acc_samps = 0; // number of accumulated samples size_t kk = 0; size_t select_bank; size_t num_rx_samps; std::vector<std::complex<float> *> curr_bank; // Initialise the spinlocks. pthread_spin_init(&lock[0], PTHREAD_PROCESS_PRIVATE); pthread_spin_init(&lock[1], PTHREAD_PROCESS_PRIVATE); // Create processing thread and keyboard input thread. pthread_t proc_thread; pthread_t keyboard_thread; struct proc_pars_t proc_pars = {bankA_ptrs, bankB_ptrs, samps_per_buff}; pthread_create(&proc_thread, NULL, process_routine, &proc_pars); pthread_create(&keyboard_thread, NULL, keyboard_routine, NULL); // Set SIGINT for stopping execution. std::signal(SIGINT, &sigint_handler); std::cout << "Press Ctrl + C to stop streaming." << std::endl; // To transmitter. int txsock = 0; struct sockaddr_in txaddr; if ((txsock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) stop_signal = true; memset (&txaddr, '0', sizeof(txaddr)); txaddr.sin_family = AF_INET; txaddr.sin_port = htons(8082); // To other receiver. int slavesock = 0; struct sockaddr_in slaveaddr; if ((slavesock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) stop_signal = true; memset (&slaveaddr, '0', sizeof(slaveaddr)); slaveaddr.sin_family = AF_INET; slaveaddr.sin_port = htons(8081); if (inet_pton(AF_INET, "192.168.0.3", &txaddr.sin_addr) <= 0) stop_signal = true; if (inet_pton(AF_INET, "192.168.0.2", &slaveaddr.sin_addr) <= 0) stop_signal = true; while (stop_signal == false) { // Select current bank. select_bank = kk++ % 2; if (select_bank == 0) curr_bank = bankA_ptrs; else curr_bank = bankB_ptrs; pthread_spin_lock(&lock[select_bank]); // Receive one block of data per channel. num_rx_samps = rx_stream->recv( curr_bank, samps_per_buff, md, timeout, false ); // Throw on all errors. if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW) { // do nothing } else if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE) { std::cout << boost::format("\nReceived %u samples.\n") % num_acc_samps; throw std::runtime_error(md.strerror()); } num_acc_samps += num_rx_samps; if (select_bank == 0) bankA_nsamps = num_rx_samps; else bankB_nsamps = num_rx_samps; pthread_spin_unlock(&lock[select_bank]); if (change_gain) { gain = fmodf(gain+10,60); usrp->set_rx_gain(gain, 0); usrp->set_rx_gain(gain, 1); std::cout << boost::format("Gain set to %.1f dB.\n") % (usrp->get_rx_gain()); change_gain = false; cmd_t command = {1, (int) gain}; sendto(slavesock, &command, sizeof(command), 0, (struct sockaddr *)&slaveaddr, sizeof(slaveaddr)); } if (do_hop) { freq = (float) ((freq_inc) % 80000000) + 2402e6; freq_inc += 2000000; usrp->set_rx_freq(freq, 0); usrp->set_rx_freq(freq, 1); std::cout << boost::format("Frequency set to %f MHz.\n") % (usrp->get_rx_freq()/1e6); do_hop = false; int freq_integer = 2400 + freq_inc/1000000; cmd_t command = {2, freq_integer}; sendto(txsock, &freq_integer, sizeof(freq_integer), 0, (struct sockaddr*)&txaddr, sizeof(txaddr)); sendto(slavesock, &command, sizeof(command), 0, (struct sockaddr *)&slaveaddr, sizeof(slaveaddr)); } } pthread_join(proc_thread, NULL); pthread_cancel(keyboard_thread); pthread_spin_destroy(&lock[0]); pthread_spin_destroy(&lock[1]); std::cout << boost::format("\nReceived %u samples.\n") % num_acc_samps; std::cout << "Done." << std::endl; return EXIT_SUCCESS; }
21,189
C++
.cpp
495
32.644444
112
0.54436
bsnet/bleaoa
38
12
1
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,882
Marlin_main.cpp
tenlog_TL-D3/Marlin/Marlin_main.cpp
/* -*- c++ -*- */ /* Reprap firmware based on Sprinter and grbl. Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm Copyright (C) 2016-2021 zyf@tenlog3d.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This firmware is a mashup between Sprinter and grbl. (https://github.com/kliment/Sprinter) (https://github.com/simen/grbl/tree) It has preliminary support for Matthew Roberts advance algorithm http://reprap.org/pipermail/reprap-dev/2011-May/003323.html */ #include "Marlin.h" #include "planner.h" #include "stepper.h" #include "temperature.h" #include "motion_control.h" #include "cardreader.h" #include "ConfigurationStore.h" #include "language.h" #include "tl_touch_screen.h" #if NUM_SERVOS > 0 //#include "Servo.h" #endif #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1 #include <SPI.h> #endif #include "avr/boot.h" void (*resetFunc)(void) = 0; // Declare reset function as address 0 // look here for descriptions of gcodes: http://linuxcnc.org/handbook/gcode/g-code.html // http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes //Implemented Codes //------------------- // G0 -> G1 // G1 - Coordinated Movement X Y Z E // G2 - CW ARC // G3 - CCW ARC // G4 - Dwell S<seconds> or P<milliseconds> // G10 - retract filament according to settings of M207 // G11 - retract recover filament according to settings of M208 // G28 - Home all Axis // G90 - Use Absolute Coordinates // G91 - Use Relative Coordinates // G92 - Set current position to cordinates given // M Codes // M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled) // M1 - Same as M0 // M17 - Enable/Power all stepper motors // M18 - Disable all stepper motors; same as M84 // M20 - List SD card // M21 - Init SD card // M22 - Release SD card // M23 - Select SD file (M23 filename.g) // M24 - Start/resume SD print // M25 - Pause SD print // M26 - Set SD position in bytes (M26 S12345) // M27 - Report SD print status // M28 - Start SD write (M28 filename.g) // M29 - Stop SD write // M30 - Delete file from SD (M30 filename.g) // M31 - Output time since last M109 or SD card start to serial // M32 - Select file and start SD print (Can be used when printing from SD card) // M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used. // M80 - Turn on Power Supply // M81 - Turn off Power Supply // M82 - Set E codes absolute (default) // M83 - Set E codes relative while in Absolute Coordinates (G90) mode // M84 - Disable steppers until next move, // or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout. // M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default) // M92 - Set axis_steps_per_unit - same syntax as G92 // M104 - Set extruder target temp // M105 - Read current temp // M106 - Fan on // M107 - Fan off // M109 - Sxxx Wait for extruder current temp to rG1each target temp. Waits only when heating // Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling // M114 - Output current position to serial port // M115 - Capabilities string // M117 - display message // M119 - Output Endstop status to serial port // M126 - Solenoid Air Valve Open (BariCUDA support by jmil) // M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil) // M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil) // M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil) // M140 - Set bed target temp // M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating // Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling // M200 - Set filament diameter // M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000) // M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!! // M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in mm/sec // M204 - Set default acceleration: S normal moves T filament only moves (M204 S3000 T7000) im mm/sec^2 also sets minimum segment time in ms (B20000) to prevent buffer underruns and M20 minimum feedrate // M205 - advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk, E=maximum E jerk // M206 - set additional homeing offset // M207 - set retract length S[positive mm] F[feedrate mm/sec] Z[additional zlift/hop] // M208 - set recover=unretract length S[positive mm surplus to the M207 S*] F[feedrate mm/sec] // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction. // M218 - set hotend offset (in mm): T<extruder_number> X<offset_on_X> Y<offset_on_Y> // M220 S<factor in percent>- set speed factor override percentage // M221 S<factor in percent>- set extrude factor override percentage // M240 - Trigger a camera to take a photograph // M250 - Set LCD contrast C<contrast value> (value 0..63) // M280 - set servo position absolute. P: servo index, S: angle or microseconds // M300 - Play beepsound S<frequency Hz> P<duration ms> // M301 - Set PID parameters P I and D // M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. // M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C) // M304 - Set bed PID parameters P I and D // M400 - Finish all moves // M500 - stores paramters in EEPROM // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. // M503 - print the current settings (from memory not from eeprom) // M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED) // M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] // M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ] // M907 - Set digital trimpot motor current using axis codes. // M908 - Control digital trimpot directly. // M350 - Set microstepping mode. // M351 - Toggle MS1 MS2 pins directly. // M928 - Start SD logging (M928 filename.g) - ended by M29 // M999 - Restart after being stopped by error // M1001 - Set & Get LanguageID // //Stepper Movement Variables //=========================================================================== //=============================imported variables============================ //=========================================================================== //=========================================================================== //=============================public variables============================= //=========================================================================== #ifdef SDSUPPORT CardReader card; #endif float homing_feedrate[] = HOMING_FEEDRATE; bool axis_relative_modes[] = AXIS_RELATIVE_MODES; int feedmultiply = 100; //100->1 200->2 int saved_feedmultiply; int extrudemultiply = 100; //100->1 200->2 float current_position[NUM_AXIS] = {0.0, 0.0, 0.0, 0.0}; float add_homeing[3] = {0, 0, 0}; float min_pos[3] = {X_MIN_POS, Y_MIN_POS, Z_MIN_POS}; float max_pos[3] = {X_MAX_POS, Y_MAX_POS, Z_MAX_POS}; // Extruder offset #if EXTRUDERS > 1 #ifndef DUAL_X_CARRIAGE #define NUM_EXTRUDER_OFFSETS 3 // only in XY plane #else #define NUM_EXTRUDER_OFFSETS 3 // 3 supports offsets in XYZ plane //By ZYF #endif float extruder_offset[NUM_EXTRUDER_OFFSETS][EXTRUDERS] = { #if defined(EXTRUDER_OFFSET_X) && defined(EXTRUDER_OFFSET_Y) #ifdef CONFIG_E2_OFFSET {0, 0}, {0, tl_Y2_OFFSET} #else EXTRUDER_OFFSET_X, EXTRUDER_OFFSET_Y #endif #endif }; #endif //EXTRUDERS > 1 uint8_t active_extruder = 0; int fanSpeed = 0; #ifdef SERVO_ENDSTOPS int servo_endstops[] = SERVO_ENDSTOPS; int servo_endstop_angles[] = SERVO_ENDSTOP_ANGLES; #endif #ifdef BARICUDA int ValvePressure = 0; int EtoPPressure = 0; #endif #ifdef FWRETRACT bool autoretract_enabled = true; bool retracted = false; float retract_length = 3, retract_feedrate = 17 * 60, retract_zlift = 0.8; float retract_recover_length = 0, retract_recover_feedrate = 8 * 60; #endif //=========================================================================== //=============================private variables============================= //=========================================================================== const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'}; static float destination[NUM_AXIS] = {0.0, 0.0, 0.0, 0.0}; static float offset[3] = {0.0, 0.0, 0.0}; static bool home_all_axis = true; static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0; static bool relative_mode = false; //Determines Absolute or Relative Coordinates static char cmdbuffer[BUFSIZE][MAX_CMD_SIZE]; static bool fromsd[BUFSIZE]; static int bufindr = 0; static int bufindw = 0; static int buflen = 0; //static int i = 0; static char serial_char; static int serial_count = 0; static boolean comment_mode = false; static char *strchr_pointer; // just a pointer to find chars in the cmd string like X, Y, Z, E, etc const int sensitive_pins[] = SENSITIVE_PINS; // Sensitive pin list for M42 //static float tt = 0; //static float bt = 0; //Inactivity shutdown variables static unsigned long previous_millis_cmd = 0; static unsigned long max_inactive_time = 0; static unsigned long stepper_inactive_time = DEFAULT_STEPPER_DEACTIVE_TIME * 1000l; unsigned long starttime = 0; unsigned long stoptime = 0; static uint8_t tmp_extruder; bool Stopped = false; #ifdef DUAL_X_CARRIAGE static bool active_extruder_parked = false; // used in mode 1 & 2 static float raised_parked_position[NUM_AXIS]; // used in mode 1 static unsigned long delayed_move_time = 0; // used in mode 1 static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2 static float duplicate_extruder_temp_offset = 0; // used in mode 2 int extruder_carriage_mode = 1; // 1=autopark mode int offset_changed = 0; #endif #ifdef HOLD_M104_TEMP float tl_hold_m104_temp[2] = {0.0,0.0}; #endif #if NUM_SERVOS > 0 Servo servos[NUM_SERVOS]; #endif #ifdef POWER_LOSS_TRIGGER_BY_PIN int iPLDetected = 0; #endif bool CooldownNoWait = true; bool target_direction; //=========================================================================== //=============================ROUTINES============================= //=========================================================================== void get_arc_coordinates(); bool setTargetedHotend(int code); void serial_echopair_P(const char *s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char *s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); } void serial_echopair_P(const char *s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); } extern "C" { extern unsigned int __bss_end; extern unsigned int __heap_start; extern void *__brkval; int freeMemory() { int free_memory; if ((int)__brkval == 0) free_memory = ((int)&free_memory) - ((int)&__bss_end); else free_memory = ((int)&free_memory) - ((int)__brkval); return free_memory; } } //adds an command to the main command buffer //thats really done in a non-safe way. //needs overworking someday void enquecommand(const char *cmd) { if (buflen < BUFSIZE) { //this is dangerous if a mixing of serial and this happsens //Why? strcpy(&(cmdbuffer[bufindw][0]), cmd); SERIAL_ECHO_START; SERIAL_ECHOPGM("enqueing \""); SERIAL_ECHO(cmdbuffer[bufindw]); SERIAL_ECHOLNPGM("\""); bufindw = (bufindw + 1) % BUFSIZE; buflen += 1; } } void enquecommand_P(const char *cmd) { if (buflen < BUFSIZE) { //this is dangerous if a mixing of serial and this happsens strcpy_P(&(cmdbuffer[bufindw][0]), cmd); SERIAL_ECHO_START; SERIAL_ECHOPGM("enqueing \""); SERIAL_ECHO(cmdbuffer[bufindw]); SERIAL_ECHOLNPGM("\""); bufindw = (bufindw + 1) % BUFSIZE; buflen += 1; } } void setup_killpin() { #if defined(POWER_LOSS_DETECT_PIN) && POWER_LOSS_DETECT_PIN > -1 pinMode(POWER_LOSS_DETECT_PIN, INPUT); #endif } void setup_photpin() { #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1 SET_OUTPUT(PHOTOGRAPH_PIN); WRITE(PHOTOGRAPH_PIN, LOW); #endif } void setup_powerhold() { #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1 SET_OUTPUT(SUICIDE_PIN); WRITE(SUICIDE_PIN, HIGH); #endif #if defined(PS_ON_PIN) && PS_ON_PIN > -1 SET_OUTPUT(PS_ON_PIN); WRITE(PS_ON_PIN, PS_ON_AWAKE); #endif } void suicide() { #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1 SET_OUTPUT(SUICIDE_PIN); WRITE(SUICIDE_PIN, LOW); #endif } int Hex2Dec(String s) { int iRet = 0; if (s == "A") iRet = 10; else if (s == "B") iRet = 11; else if (s == "C") iRet = 12; else if (s == "D") iRet = 13; else if (s == "E") iRet = 14; else if (s == "F") iRet = 15; else iRet = s.toInt(); return iRet; } String Dec2Hex(int i) { String sRet = ""; if (i == 10) sRet = "A"; else if (i == 11) sRet = "B"; else if (i == 12) sRet = "C"; else if (i == 13) sRet = "D"; else if (i == 14) sRet = "E"; else if (i == 15) sRet = "F"; else sRet = String(i); return sRet; } //this function is just for register the printer, you can disable it if you want. String gsDeviceID = ""; String get_device_id() { String strID = ""; int iAdd = 0; for (int i = 14; i < 14 + 10; i++) { String sID = String(boot_signature_byte_get(i), HEX); if (sID.length() == 1) sID = "0" + sID; strID = strID + sID; } strID.toUpperCase(); //long lAtv = CalAtv(strID); gsDeviceID = strID; for (int i = 0; i < 20; i++) { iAdd += Hex2Dec(strID.substring(i, i + 1)); } iAdd = iAdd % 0x10; String sAdd = Dec2Hex(iAdd); strID = strID + sAdd; strID.toUpperCase(); return strID; } void print_mega_device_id() { String strID = get_device_id(); TL_DEBUG_PRINT(F("[")); TL_DEBUG_PRINT(strID); TL_DEBUG_PRINT(F("|")); TL_DEBUG_PRINT(FW_STR); TL_DEBUG_PRINT(F("|")); TL_DEBUG_PRINT(F(VERSION_STRING)); TL_DEBUG_PRINT_LN(F("]")); } void servo_init() { #if (NUM_SERVOS >= 1) && defined(SERVO0_PIN) && (SERVO0_PIN > -1) servos[0].attach(SERVO0_PIN); #endif #if (NUM_SERVOS >= 2) && defined(SERVO1_PIN) && (SERVO1_PIN > -1) servos[1].attach(SERVO1_PIN); #endif #if (NUM_SERVOS >= 3) && defined(SERVO2_PIN) && (SERVO2_PIN > -1) servos[2].attach(SERVO2_PIN); #endif #if (NUM_SERVOS >= 4) && defined(SERVO3_PIN) && (SERVO3_PIN > -1) servos[3].attach(SERVO3_PIN); #endif #if (NUM_SERVOS >= 5) #error "TODO: enter initalisation code for more servos" #endif // Set position of Servo Endstops that are defined #ifdef SERVO_ENDSTOPS for (int8_t i = 0; i < 3; i++) { if (servo_endstops[i] > -1) { servos[servo_endstops[i]].write(servo_endstop_angles[i * 2 + 1]); } } #endif } ///////////////////split by zyf String getSplitValue(String data, char separator, int index) { int found = 0; int strIndex[] = { 0, -1}; int maxIndex = data.length() - 1; for (int i = 0; i <= maxIndex && found <= index; i++) { if (data.charAt(i) == separator || i == maxIndex) { found++; strIndex[0] = strIndex[1] + 1; strIndex[1] = (i == maxIndex) ? i + 1 : i; } } return found > index ? data.substring(strIndex[0], strIndex[1]) : ""; } float string2Float(String Value) { char floatbuf[32]; // make this at least big enough for the whole string Value.toCharArray(floatbuf, sizeof(floatbuf)); float fRet = atof(floatbuf); return fRet; } long lVcc = 0; void get_command_dwn() { //int dwn_command[255] = {0}; //Clear command int i = 0; while (MTLSERIAL_available() > 0) { dwn_command[i] = MTLSERIAL_read(); i++; delay(2); } } long ConvertHexLong(long command[], int Len) { long lRet = 0; if (Len == command[6] * 2) { if (Len == 2) lRet = 0x100 * command[7] + command[8]; else if (Len == 4) { lRet = lRet + 0x100 * command[9] + command[10]; lRet = lRet + 0x1000000 * command[7] + 0x10000 * command[8]; } return lRet; } } void showDWNLogo() { if (iOldLogoID > 99 && iOldLogoID < 111) { DWN_Data(0x8870, iOldLogoID - 100, 0x02); //DWN_Data(0x8870, 3, 0x02); } else DWN_Data(0x8870, 0x00, 0x02); } int RWLogo(int NewID) { if (NewID == 0) { DWN_NORFData(0x000032, 0x1032, 0x02, false); _delay_ms(500); DWN_RData(0x1032, 0x02); _delay_ms(50); } else { DWN_Data(0x1032, NewID, 4); _delay_ms(20); DWN_NORFData(0x000032, 0x1032, 0x02, true); iOldLogoID = NewID; _delay_ms(500); showDWNLogo(); } } void SAtv(int FID1, long ID, int Length) { _delay_ms(50); DWN_NORFData(0x0000 + FID1, ID, Length, false); _delay_ms(500); DWN_RData(ID, Length); _delay_ms(50); } long CalAtv(String MBCode) { long vTemp6 = 1; long vTemp0 = 0; long vTemp1 = 0; long vTemp2 = 0; long vTemp3 = 0; long vTemp4 = 0; long vTemp5 = 0; String sDev0 = "42F35B6897"; String sDev1 = "8D96B41253"; for (int vLoop0 = 0; vLoop0 < 10; vLoop0++) { String sTemp0 = MBCode.substring(vLoop0, vLoop0 + 1); String sTemp1 = MBCode.substring(19 - vLoop0, 20 - vLoop0); vTemp0 = Hex2Dec(sTemp0); vTemp1 = Hex2Dec(sTemp1); sTemp0 = sDev0.substring(vLoop0, vLoop0 + 1); sTemp1 = sDev1.substring(vLoop0, vLoop0 + 1); vTemp2 = Hex2Dec(sTemp0); vTemp3 = Hex2Dec(sTemp1); vTemp4 = vTemp0 + vTemp2; vTemp5 = vTemp1 + vTemp3; vTemp6 = vTemp6 * vTemp4 - vTemp5; if (vTemp6 < 0) vTemp6 = vTemp6 * -1; if (vTemp6 > 999999) vTemp6 = vTemp6 % 999999; } if (vTemp6 < 100000) vTemp6 = vTemp6 + 400000; return vTemp6; } void chkAtv() { static bool Showed; static bool bSet0; static bool bSet1; if (!bAtvGot1 && !bSet1) { SAtv(0x22, 0x1022, 02); bSet1 = true; } else if (!bAtvGot0 && !bSet0) { SAtv(0x02, 0x1002, 20); bSet0 = true; } else if (bAtvGot0 && bAtvGot1 && !Showed) { if (!bAtv && !Showed) { String strID = get_device_id(); String strURL = "http://auto954.com/tlauth/ts_atv3/?code=" + strID; DWN_Text(0x8860, strURL.length() + 2, strURL, false); DWN_Text(0x7600, strID.length() + 2, strID, false); DWN_Data(0x6066, 0, 4); DWN_Page(67); Showed = true; } } } int pause_T0T1 = 0; int pause_BedT = 0; int pause_T0T; int pause_T1T; void DWN_Pause(bool filamentOut) { //quickStop(); static float pause_duplicate_extruder_x_offset; static int pause_extruder_carriage_mode; if (card.sdprinting == 1) { pause_extruder_carriage_mode = extruder_carriage_mode; pause_T0T = target_temperature[0]; pause_T1T = target_temperature[1]; pause_BedT = target_temperature_bed; pause_T0T1 = active_extruder; if (filamentOut) { command_M104(0, 0); command_M104(1, 0); } if (extruder_carriage_mode == 2) pause_duplicate_extruder_x_offset = duplicate_extruder_x_offset; else pause_duplicate_extruder_x_offset = -1.0; enquecommand_P(PSTR("M1031")); //Pause //sdcard_pause(); } else if (card.sdprinting == 0) { //String sM605 = "M605 S"; String strCommand = "M605 S" + String(pause_extruder_carriage_mode); if (pause_extruder_carriage_mode == 2) strCommand = strCommand + " X" + String(pause_duplicate_extruder_x_offset); //char _Command[sizeof(strCommand)]; //strCommand.toCharArray(_Command, sizeof(_Command)); const char *_Command = strCommand.c_str(); enquecommand(_Command); //M605 _delay_ms(20); enquecommand_P(PSTR("G28 X")); _delay_ms(20); strCommand = "M1032 T" + String(pause_T0T1) + " H" + String(pause_T0T) + " I" + String(pause_T1T); _Command = strCommand.c_str(); enquecommand(_Command); //Resume } } void CheckTempError_dwn() { if (iTempErrID > 0) { bool bPO = false; #ifdef HAS_PLR_MODULE if (iTempErrID == MSG_NOZZLE_HEATING_ERROR || iTempErrID == MSG_NOZZLE_HIGH_TEMP_ERROR || iTempErrID == MSG_BED_HIGH_TEMP_ERROR) { if (b_PLR_MODULE_Detected) bPO = true; } #endif DWN_Message(iTempErrID, sTempErrMsg, bPO); if (bPO) { _delay_ms(5000); command_M81(false, false); } iTempErrID = 0; sTempErrMsg = ""; if (card.sdprinting == 1) { sdcard_stop(); } } } void Init_TLScreen_dwn() { _delay_ms(5); DWN_Language(languageID); _delay_ms(5); long iSend = tl_X2_MAX_POS * 100.0; DWN_Data(0x6018, iSend, 4); _delay_ms(5); for (int i = 0; i < 4; i++) { iSend = axis_steps_per_unit[i] * 100.0; DWN_Data(0x6010 + i * 2, iSend, 4); _delay_ms(5); } iSend = tl_Y2_OFFSET * 100.0 + 0.5; DWN_Data(0x6020, iSend, 2); _delay_ms(5); iSend = tl_Z2_OFFSET * 100.0; DWN_Data(0x6021, iSend, 2); _delay_ms(5); #ifdef FAN2_CONTROL DWN_Data(0x6023, tl_FAN2_VALUE, 2); _delay_ms(5); DWN_Data(0x6022, tl_FAN2_START_TEMP, 2); #else DWN_Data(0x6022, 0x00, 2); _delay_ms(5); DWN_Data(0x6023, 0x00, 2); #endif _delay_ms(5); #ifdef HAS_PLR_MODULE _delay_ms(5); iSend = tl_AUTO_OFF; DWN_Data(0x8012, iSend, 2); _delay_ms(5); if (b_PLR_MODULE_Detected) { DWN_Data(0x8015, 0, 2); } else { DWN_Data(0x8015, 1, 2); } #endif DWN_Data(0x8013, tl_ECO_MODE, 2); _delay_ms(5); if (!bInited) iBeepCount = 2; #ifdef FILAMENT_FAIL_DETECT DWN_Data(0x8014, tl_Filament_Detect, 2); #endif String strVersion = FW_STR; #ifdef HAS_PLR_MODULE if (b_PLR_MODULE_Detected) strVersion = strVersion + " PLR "; else strVersion = strVersion + " "; #endif strVersion = strVersion + "V " + VERSION_STRING; DWN_Text(0x7200, 32, strVersion); _delay_ms(5); iSend = b_PLR_MODULE_Detected + languageID * 2; DWN_Data(0x8803, iSend, 2); DWN_Data(0x8806, b_PLR_MODULE_Detected, 2); _delay_ms(500); #if (BEEPER > 0) SET_OUTPUT(BEEPER); WRITE(BEEPER, BEEPER_OFF); #endif } float Check_Last_Z() { float fLastZ = EEPROM_Read_Last_Z(); float fLastY = EEPROM_Read_Last_Y(); int iMode = EEPROM_Read_Last_Mode(); if (iMode == 1 || iMode == 2 || iMode == 3) { dual_x_carriage_mode = iMode; } if (fLastZ > 0.0 || fLastZ == -1.0) { float fLZ = fLastZ; if (fLastZ == -1.0) fLZ = 0.0; command_G92(X_MIN_POS, fLastY, fLZ); } return fLastZ; } //Get Data From Commport String getSerial2Data() { String strSerialdata = ""; while (MTLSERIAL_available() > 0) { strSerialdata += char(MTLSERIAL_read()); delay(2); } return strSerialdata; } /* unsigned long lScreenStart = 0; int Detect_Screen() { _delay_ms(500); TenlogScreen_begin(9600); _delay_ms(50); lScreenStart = millis(); TLSTJC_printEmptyend(); _delay_ms(50); int iTryCount = 0; TLSTJC_printconstln(F("tStatus.txt=\"Shake hands...0\"")); _delay_ms(50); TLSTJC_printconstln(F("connect")); _delay_ms(50); bool bCheckDone = false; while (!bCheckDone) { String strSerial2 = getSerial2Data(); if (strSerial2 != "") { strSerial2.replace("\r", ""); strSerial2.replace("\n", ""); String strDI = getSplitValue(strSerial2, ',', 5); bCheckDone = true; TLSTJC_printconst(F("loading.sDI.txt=\"")); TLSTJC_print(strDI.c_str()); TLSTJC_printconst(F("\"")); TLSTJC_printend(); _delay_ms(50); TLSTJC_printconstln(F("bkcmd=0")); _delay_ms(50); TLSTJC_printconstln(F("click btA,0")); return 1; } else { _delay_ms(10); } if (millis() - lScreenStart > 1000) { lScreenStart = millis(); iTryCount++; TenlogScreen_end(); _delay_ms(50); TenlogScreen_begin(9600); _delay_ms(50); TLSTJC_printEmptyend(); _delay_ms(50); TLSTJC_printconst(F("tStatus.txt=\"Shake hands...")); TLSTJC_print(String(iTryCount).c_str()); TLSTJC_printconst(F("\"")); TLSTJC_printend(); _delay_ms(50); TLSTJC_printconstln(F("connect")); _delay_ms(50); } if(iTryCount > 5) { bCheckDone = true; return 0; } } } */ //Detect touch screen.. #define TJC_BAUD 9600 #define DWN_BAUD 115200 #define ZERO(a) memset(a,0,sizeof(a)) #define NULLZERO(a) memset(a,'\0',sizeof(a)) #define DWN_HEAD0 0x5A #define DWN_HEAD1 0xA5 long tl_command[78] = {0}; void my_get_command(int ScreenType=1) { if(ScreenType == 0) ZERO(tl_command); else NULLZERO(tl_command); int i = 0; while (MTLSERIAL_available() > 0) { tl_command[i] = MTLSERIAL_read(); i++; delay(5); } } unsigned long lScreenStart = 0; //comok 1,101,TJC4024T032_011R,52,61488,D264B8204F0E1828,16777216 int Detect_Screen(){ char cmd[32]; int TryType = 1; long lBaud = TJC_BAUD; int iTryCount = 1; bool bCheckDone = false; delay(1000); bool CanTry = true; while (!bCheckDone) { if(TryType == 1){ if(CanTry){ TL_DEBUG_PRINT(F("Trying TJC... ")); TL_DEBUG_PRINT_LN(iTryCount); delay(50); TenlogScreen_end(); delay(50); TenlogScreen_begin(lBaud); delay(50); TLSTJC_printEmptyend(); delay(50); sprintf_P(cmd, PSTR("tStatus.txt=\"Shake hands... %d\""), (iTryCount+1)/2); TLSTJC_println(cmd); delay(50); TLSTJC_printconstln(F("connect")); delay(50); lScreenStart = millis(); delay(100); CanTry = false; } my_get_command(1); char SerialNo[20]; int SLoop = 0; NULLZERO(SerialNo); int iDHCount = 0; for(int i=0; i<100; i++){ if(tl_command[i] == '\0') break; if(tl_command[i] == ',') iDHCount++; if(iDHCount > 6) break; if(iDHCount > 4 && iDHCount < 6){ if((tl_command[i] > 47 && tl_command[i] < 58) || (tl_command[i] > 64 && tl_command[i] < 71)){ SerialNo[SLoop] = tl_command[i]; SLoop++; } } } if(SerialNo[0] != '\0'){ TL_DEBUG_PRINT(F("Serial.. ")); TL_DEBUG_PRINT_LN(SerialNo); } delay(50); if (strlen(SerialNo) == 16){ TLSTJC_printconst(F("loading.sDI.txt=\"")); TLSTJC_print(SerialNo); TLSTJC_printconstln(F("\"")); delay(50); TLSTJC_printconstln(F("click btA,0")); delay(50); TLSTJC_printconstln(F("bkcmd=0")); if(lBaud == 115200){ delay(50); TLSTJC_printconstln(F("bauds=9600")); delay(50); lBaud = 9600; iTryCount--; }else { bCheckDone = true; return 1; } } }else if(TryType == 0){ if(CanTry){ TL_DEBUG_PRINT(F("Trying DWN... ")); TL_DEBUG_PRINT_LN(iTryCount); delay(50); TenlogScreen_end(); delay(50); TenlogScreen_begin(DWN_BAUD); delay(50); sprintf_P(cmd, PSTR("Shake hands... %d"), iTryCount/2); DWN_Text(0x7100, 20, cmd); delay(50); DWN_Get_Ver(); lScreenStart = millis(); delay(100); CanTry = false; } my_get_command(0); if(tl_command[0] == 0x5A && tl_command[1] == 0xA5){ bCheckDone = true; return 0; } } delay(50); if (millis() - lScreenStart > 800){ CanTry = true; TryType = !TryType; iTryCount++; } if(iTryCount == 9 && TryType == 1){ if(lBaud == TJC_BAUD){ lBaud = 115200; } } else if(iTryCount > 10) { bCheckDone = true; return -1; } } return 0; } #ifdef FILAMENT_FAIL_DETECT int iFilaFail = 0; int iFilaOK = 0; void check_filament_fail() { bool bRead = digitalRead(FILAMENT_FAIL_DETECT_PIN) == FILAMENT_FAIL_DETECT_TRIGGER; if (bRead && iFilaFail > 10) { if (card.sdprinting == 1) { iFilaFail = 0; if(tl_TouchScreenType == 1){ iBeepCount = 10; TLSTJC_printconstln(F("sleep=0")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vaMID.val=6")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vaFromPageID.val=15")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vaToPageID.val=15")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vtOKValue.txt=\"M1034\"")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vtCancelValue.txt=\"M1034\"")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.vtStartValue.txt=\"M1031 O1\"")); _delay_ms(50); TLSTJC_printconstln(F("msgbox.tMessage.txt=\"Filament runout!\"")); _delay_ms(50); TLSTJC_printconstln(F("page msgbox")); _delay_ms(50); } else if(tl_TouchScreenType == 0) { DWN_Message(MSG_FILAMENT_RUNOUT, "", false); DWN_Pause(true); } } } else if (bRead) { iFilaOK = 0; iFilaFail++; } else if (!bRead && iFilaOK > 1) { iFilaOK = 0; iFilaFail = 0; } else if (!bRead) { iFilaOK++; } } #endif void loadingMessage(const String Message, const int ShowType = -1) { if(tl_TouchScreenType == 1 && (ShowType == -1 || ShowType == 1)) { TLSTJC_printconst(F("tStatus.txt=\"")); TLSTJC_printconst(Message); TLSTJC_printconstln(F("\"")); } else if (tl_TouchScreenType == 0 && (ShowType == -1 || ShowType == 0)) { DWN_Text(0x7100, 20, Message); } } void setup() { setup_killpin(); setup_powerhold(); #ifdef ENGRAVE pinMode(ENGRAVE_PIN, OUTPUT); digitalWrite(ENGRAVE_PIN, ENGRAVE_OFF); #endif MYSERIAL.begin(BAUDRATE); SERIAL_PROTOCOLLNPGM("start"); SERIAL_ECHO_START; _delay_ms(100); tl_TouchScreenType = Detect_Screen(); // check if it is tjc screen bool bPrintFinishedMSG = false; float fLastZ = 0.0; if(tl_TouchScreenType == 1) { //TenlogScreen_begin(9600); //_delay_ms(100); TLSTJC_printconstln(F("sleep=0")); _delay_ms(20); #ifdef HAS_PLR_MODULE TLSTJC_printconstln(F("main.vPFR.val=1")); _delay_ms(20); #endif TLSTJC_printconstln(F("page 0")); _delay_ms(20); } else if(tl_TouchScreenType == 0) { fLastZ = Check_Last_Z(); TenlogScreen_end(); _delay_ms(20); TenlogScreen_begin(115200); _delay_ms(20); DWN_LED(DWN_LED_ON); if (fLastZ == 0.0) { int iLoop = 0; bool bLRead = false; long lLRead = 0; while (!bLogoGot && iLoop < 5) { if (!bLRead) { RWLogo(0); bLRead = true; lLRead = millis(); } if (millis() - lLRead > 1000 && bLRead) { bLRead = false; iLoop++; } get_command_dwn(); process_command_dwn(); _delay_ms(50); } DWN_Page(DWN_P_LOADING); } else { long lTime = EEPROM_Read_Last_Time(); if (lTime > 0) { bPrintFinishedMSG = true; int hours, minutes; minutes = (lTime / 60) % 60; hours = lTime / 60 / 60; String strTime = " " + String(hours) + " h " + String(minutes) + " m"; DWN_Message(MSG_PRINT_FINISHED, strTime, false); } EEPROM_Write_Last_Z(0.0, 0.0, 0, 0); } }else if(tl_TouchScreenType == -1){ SERIAL_ECHOLNPGM("TL touch screen not detected, resetting..."); resetFunc(); } // Check startup - does nothing if bootloader sets MCUSR to 0 byte mcu = MCUSR; if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP); if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET); if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET); if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET); if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET); MCUSR = 0; SERIAL_ECHOPGM(MSG_MARLIN); SERIAL_ECHOLNPGM(VERSION_STRING); #ifdef STRING_VERSION_CONFIG_H #ifdef STRING_CONFIG_H_AUTHOR SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_CONFIGURATION_VER); SERIAL_ECHOPGM(STRING_VERSION_CONFIG_H); SERIAL_ECHOPGM(MSG_AUTHOR); SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR); SERIAL_ECHOPGM("Compiled: "); SERIAL_ECHOLNPGM(__DATE__); #endif #endif SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_FREE_MEMORY); SERIAL_ECHO(freeMemory()); SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES); SERIAL_ECHOLN((int)sizeof(block_t) * BLOCK_BUFFER_SIZE); for (int8_t i = 0; i < BUFSIZE; i++) { fromsd[i] = false; } // loads data from EEPROM if available else uses defaults (and resets step acceleration rate) Config_RetrieveSettings(); duplicate_extruder_x_offset = (tl_X2_MAX_POS - X_NOZZLE_WIDTH) / 2.0; if(tl_TouchScreenType == 0) { TL_DEBUG_PRINT(F("SN")); print_mega_device_id(); } TL_DEBUG_PRINT_LN(F("Init Screen...")); loadingMessage(F("Init Screen...")); if(tl_TouchScreenType == 0) Init_TLScreen_dwn(); else Init_TLScreen_tjc(); _delay_ms(500); loadingMessage(F("Init Temperature...")); tp_init(); // Initialize temperature loop _delay_ms(500); loadingMessage(F("Init Stepper...")); plan_init(); // Initialize planner; //watchdog_init(); st_init(); // Initialize stepper, this enables interrupts! setup_photpin(); _delay_ms(500); if(tl_TouchScreenType == 1) { loadingMessage(F("Init SD reader..."), 1); _delay_ms(500); } else { loadingMessage(F("Init SD reader..."), 0); while (!bAtv) { get_command_dwn(); process_command_dwn(); chkAtv(); _delay_ms(50); } } sd_init(); _delay_ms(1000); // wait 1sec to display the splash screen #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1 SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan #endif if(tl_TouchScreenType == 1) { TLSTJC_printconstln(F("sleep=0")); TLSTJC_printconstln(F("page main")); #ifdef POWER_LOSS_RECOVERY String sFileName = card.isPowerLoss(); sFileName = getSplitValue(sFileName, '|', 1); if (sFileName != "") { TLSTJC_printconstln(F("msgbox.vaFromPageID.val=1")); TLSTJC_printconstln(F("msgbox.vaToPageID.val=6")); TLSTJC_printconstln(F("msgbox.vtOKValue.txt=\"M1003\"")); TLSTJC_printconstln(F("msgbox.vtCancelValue.txt=\"M1004\"")); String strMessage = "" + sFileName + "?"; strMessage = "" + strMessage + ""; const char *str0 = strMessage.c_str(); TLSTJC_printconst(F("msgbox.tMessage.txt=\" Power loss detected, Resume print ")); TLSTJC_print(str0); TLSTJC_printconstln(F("\"")); strMessage = "" + sFileName + ""; str0=strMessage.c_str(); TLSTJC_printconst(F("msgbox.vtMS.txt=\"")); TLSTJC_print(str0); TLSTJC_printconstln(F("\"")); TLSTJC_printconstln(F("msgbox.vaMID.val=3")); TLSTJC_printconstln(F("page msgbox")); } #endif } else if(tl_TouchScreenType == 0) { DWN_LED(DWN_LED_ON); #ifdef POWER_LOSS_RECOVERY String sFileName = card.isPowerLoss(); String sLngFileName = getSplitValue(sFileName, '|', 0); String sShtFileName = getSplitValue(sFileName, '|', 1); if (sFileName != "") { DWN_Message(MSG_POWER_LOSS_DETECTED, sLngFileName + "?", false); } else if (!bPrintFinishedMSG) { DWN_Page(DWN_P_MAIN); _delay_ms(100); } #else if (!bPrintFinishedMSG) DWN_Page(DWN_P_MAIN); _delay_ms(100); lLEDTimeTimecount = 0; #endif //POWER_LOSS_RECOVERY if (fLastZ != 0.0) { command_G4(0.01); command_G4(0.01); command_G4(0.01); command_G4(0.01); command_G28(1, 0, 0); } } #ifdef PRINT_FROM_Z_HEIGHT PrintFromZHeightFound = true; print_from_z_target = 0.0; #endif WRITE(PS_ON_PIN, PS_ON_AWAKE); } //setup void loop() { if(tl_TouchScreenType == 1) { if (buflen < (BUFSIZE - 1)) get_command_tjc(); } else { get_command_dwn(); process_command_dwn(); } if (buflen < (BUFSIZE - 1)) get_command(); #ifdef SDSUPPORT card.checkautostart(false); #endif if (buflen) { #ifdef SDSUPPORT if (card.saving) { if (strstr_P(cmdbuffer[bufindr], PSTR("M29")) == NULL) { card.write_command(cmdbuffer[bufindr]); if (card.logging) { process_commands(); } else { SERIAL_PROTOCOLLNPGM(MSG_OK); } } else { card.closefile(); SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED); } } else { #ifdef POWER_LOSS_RECOVERY int iBPos = degTargetBed() + 0.5; #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_PRE_Write_PLR(card.sdpos, iBPos, dual_x_carriage_mode, duplicate_extruder_x_offset, feedrate); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) card.PRE_Write_PLR(card.sdpos, iBPos, dual_x_carriage_mode, duplicate_extruder_x_offset, feedrate); #endif #endif //POWER_LOSS_RECOVERY process_commands(); } #else process_commands(); #endif //SDSUPPORT buflen = (buflen - 1); bufindr = (bufindr + 1) % BUFSIZE; } //check heater every n milliseconds manage_heater(); if (tl_HEATER_FAIL) { card.closefile(); card.sdprinting = 0; } manage_inactivity(); checkHitEndstops(); if (bAtv && tl_TouchScreenType == 0 || tl_TouchScreenType == 1) tenlog_status_screen(); if(tl_TouchScreenType == 0) CheckTempError_dwn(); else CheckTempError_tjc(); } void get_command_tjc() { while (MTLSERIAL_available() > 0 && buflen < BUFSIZE) { serial_char = MTLSERIAL_read(); int iSC = (int)serial_char; if (serial_char == '\n' || iSC == -1 || serial_char == '\r' || (serial_char == ':' && comment_mode == false) || serial_count >= (MAX_CMD_SIZE - 1)) { if (!serial_count) { //if empty line comment_mode = false; //for new command return; } cmdbuffer[bufindw][serial_count] = 0; //terminate string if (!comment_mode) { comment_mode = false; //for new command fromsd[bufindw] = false; if (strchr(cmdbuffer[bufindw], 'N') != NULL) { strchr_pointer = strchr(cmdbuffer[bufindw], 'N'); gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10)); if (gcode_N != gcode_LastN + 1 && (strstr_P(cmdbuffer[bufindw], PSTR("M110")) == NULL)) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_LINE_NO); SERIAL_ERRORLN(gcode_LastN); //Serial.println(gcode_N); FlushSerialRequestResend(); serial_count = 0; return; } if (strchr(cmdbuffer[bufindw], '*') != NULL) { byte checksum = 0; byte count = 0; while (cmdbuffer[bufindw][count] != '*') checksum = checksum ^ cmdbuffer[bufindw][count++]; strchr_pointer = strchr(cmdbuffer[bufindw], '*'); if ((int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_CHECKSUM_MISMATCH); SERIAL_ERRORLN(gcode_LastN); FlushSerialRequestResend(); serial_count = 0; return; } //if no errors, continue parsing } else { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_NO_CHECKSUM); SERIAL_ERRORLN(gcode_LastN); FlushSerialRequestResend(); serial_count = 0; return; } gcode_LastN = gcode_N; //if no errors, continue parsing } else // if we don't receive 'N' but still see '*' { if ((strchr(cmdbuffer[bufindw], '*') != NULL)) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM); SERIAL_ERRORLN(gcode_LastN); serial_count = 0; return; } } if ((strchr(cmdbuffer[bufindw], 'G') != NULL)) { strchr_pointer = strchr(cmdbuffer[bufindw], 'G'); switch ((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))) { case 0: case 1: case 2: case 3: if (Stopped == false) { // If printer is stopped by an error the G[0-3] codes are ignored. #ifdef SDSUPPORT if (card.saving) break; #endif //SDSUPPORT \ //SERIAL_PROTOCOLLNPGM(MSG_OK); } else { SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); //LCD_MESSAGEPGM(MSG_STOPPED); } break; default: break; } } bufindw = (bufindw + 1) % BUFSIZE; buflen += 1; } serial_count = 0; //clear buffer } else { if (serial_char == ';' || (int)serial_char < 0 || ((int)serial_char == 104 && cmdbuffer[bufindw][0] != 'M')) { comment_mode = true; } if (!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; } } } float code_value() { return (strtod(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL)); } long code_value_long() { return (strtol(&cmdbuffer[bufindr][strchr_pointer - cmdbuffer[bufindr] + 1], NULL, 10)); } bool code_seen(char code) { strchr_pointer = strchr(cmdbuffer[bufindr], code); return (strchr_pointer != NULL); //Return True if a character was found } void command_M81(bool Loop = true, bool ShowPage = true) { #ifdef HAS_PLR_MODULE if (b_PLR_MODULE_Detected) { iBeepCount = 2; card.sdpos = 0; #if defined(SUICIDE_PIN) && SUICIDE_PIN > -1 st_synchronize(); suicide(); #elif defined(PS_ON_PIN) && PS_ON_PIN > -1 SET_OUTPUT(PS_ON_PIN); WRITE(PS_ON_PIN, PS_ON_ASLEEP); #endif if (ShowPage) if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("page shutdown")); else if(tl_TouchScreenType == 0) DWN_Page(DWN_P_SHUTDOWN); _delay_ms(100); } #endif if (Loop) { while (1) { /* Intentionally left empty */ } // Wait for reset } } void command_G4(float dwell = 0) { unsigned long codenum; //throw away variable //LCD_MESSAGEPGM(MSG_DWELL); codenum = 0; if (code_seen('P')) codenum = code_value(); // milliseconds to wait if (code_seen('S')) codenum = code_value() * 1000; // seconds to wait if (dwell > 0) codenum = dwell * 1000; st_synchronize(); codenum += millis(); // keep track of when we started waiting previous_millis_cmd = millis(); while (millis() < codenum) { manage_heater(); if (tl_HEATER_FAIL) { card.closefile(); card.sdprinting = 0; } manage_inactivity(); tenlog_status_screen(); } } void get_command() { while (MYSERIAL.available() > 0 && buflen < BUFSIZE) { serial_char = MYSERIAL.read(); if (serial_char == '\n' || serial_char == '\r' || (serial_char == ':' && comment_mode == false) || serial_count >= (MAX_CMD_SIZE - 1)) { if (!serial_count) { //if empty line comment_mode = false; //for new command return; } cmdbuffer[bufindw][serial_count] = 0; //terminate string if (!comment_mode) { comment_mode = false; //for new command fromsd[bufindw] = false; if (strchr(cmdbuffer[bufindw], 'N') != NULL) { strchr_pointer = strchr(cmdbuffer[bufindw], 'N'); gcode_N = (strtol(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL, 10)); if (gcode_N != gcode_LastN + 1 && (strstr_P(cmdbuffer[bufindw], PSTR("M110")) == NULL)) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_LINE_NO); SERIAL_ERRORLN(gcode_LastN); //Serial.println(gcode_N); FlushSerialRequestResend(); serial_count = 0; return; } if (strchr(cmdbuffer[bufindw], '*') != NULL) { byte checksum = 0; byte count = 0; while (cmdbuffer[bufindw][count] != '*') checksum = checksum ^ cmdbuffer[bufindw][count++]; strchr_pointer = strchr(cmdbuffer[bufindw], '*'); if ((int)(strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)) != checksum) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_CHECKSUM_MISMATCH); SERIAL_ERRORLN(gcode_LastN); FlushSerialRequestResend(); serial_count = 0; return; } //if no errors, continue parsing } else { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_NO_CHECKSUM); SERIAL_ERRORLN(gcode_LastN); FlushSerialRequestResend(); serial_count = 0; return; } gcode_LastN = gcode_N; //if no errors, continue parsing } else // if we don't receive 'N' but still see '*' { if ((strchr(cmdbuffer[bufindw], '*') != NULL)) { SERIAL_ERROR_START; SERIAL_ERRORPGM(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM); SERIAL_ERRORLN(gcode_LastN); serial_count = 0; return; } } if ((strchr(cmdbuffer[bufindw], 'G') != NULL)) { strchr_pointer = strchr(cmdbuffer[bufindw], 'G'); switch ((int)((strtod(&cmdbuffer[bufindw][strchr_pointer - cmdbuffer[bufindw] + 1], NULL)))) { case 0: case 1: case 2: case 3: if (Stopped == false) { // If printer is stopped by an error the G[0-3] codes are ignored. #ifdef SDSUPPORT if (card.saving) break; #endif //SDSUPPORT \ //SERIAL_PROTOCOLLNPGM(MSG_OK); } else { SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); //LCD_MESSAGEPGM(MSG_STOPPED); } break; default: break; } } bufindw = (bufindw + 1) % BUFSIZE; buflen += 1; } serial_count = 0; //clear buffer } else { if (serial_char == ';') comment_mode = true; if (!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; } } #ifdef SDSUPPORT if (card.sdprinting == 0 || serial_count != 0) { return; } while (!card.eof() && buflen < BUFSIZE) { int16_t n = card.get(); serial_char = (char)n; if (serial_char == '\n' || serial_char == '\r' || (serial_char == ':' && comment_mode == false) || serial_count >= (MAX_CMD_SIZE - 1) || n == -1) { if (card.eof()) { bool bAutoOff = false; String strPLR = ""; #ifdef HAS_PLR_MODULE if (b_PLR_MODULE_Detected) { if (tl_AUTO_OFF == 1) { strPLR = "Power off in 5 seconds."; bAutoOff = true; } } #endif //HAS_PLR_MODULE SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED); stoptime = millis(); char time[30]; long t = (stoptime - starttime) / 1000; int hours, minutes; minutes = (t / 60) % 60; hours = t / 60 / 60; sprintf_P(time, PSTR("%i hours %i minutes"), hours, minutes); SERIAL_ECHO_START; SERIAL_ECHOLN(time); //lcd_setstatus(time); if(tl_TouchScreenType == 0) { String strTime = " " + String(hours) + " h " + String(minutes) + " m"; DWN_Message(MSG_PRINT_FINISHED, strTime, bAutoOff); } else { TLSTJC_printconstln(F("sleep=0")); TLSTJC_printconstln(F("msgbox.vaFromPageID.val=1")); TLSTJC_printconstln(F("msgbox.vaToPageID.val=1")); TLSTJC_printconstln(F("msgbox.vtOKValue.txt=\"\"")); TLSTJC_printconst(F("msgbox.tMessage.txt=\"Print finished, ")); const char *str0 = String(hours).c_str(); TLSTJC_print(str0); TLSTJC_printconst(F(" house and ")); str0 = String(minutes).c_str(); TLSTJC_print(str0); TLSTJC_printconst(F(" minutes.\r\n")); if(strPLR != "") { str0 = strPLR.c_str(); TLSTJC_print(str0); } TLSTJC_printconstln(F("\"")); TLSTJC_printconstln(F("msgbox.vaMID.val=1")); String strMessage = "" + String(hours) + ":" + String(minutes) + ""; str0 = strMessage.c_str(); TLSTJC_printconst(F("msgbox.vtMS.txt=\"")); TLSTJC_print(str0); TLSTJC_printconstln(F("\"")); TLSTJC_printconstln(F("page msgbox")); } iBeepCount = 10; if (bAutoOff && b_PLR_MODULE_Detected) { card.sdprinting = 0; command_G4(5.0); command_M81(); } card.printingHasFinished(); WriteLastZYM(t); card.checkautostart(true); } if (!serial_count) { comment_mode = false; //for new command return; //if empty line } cmdbuffer[bufindw][serial_count] = 0; //terminate string // if(!comment_mode){ fromsd[bufindw] = true; buflen += 1; bufindw = (bufindw + 1) % BUFSIZE; // } comment_mode = false; //for new command serial_count = 0; //clear buffer } else { if (serial_char == ';') comment_mode = true; if (!comment_mode) cmdbuffer[bufindw][serial_count++] = serial_char; } } #endif //SDSUPPORT } #define DEFINE_PGM_READ_ANY(type, reader) \ static inline type pgm_read_any(const type *p) \ { \ return pgm_read_##reader##_near(p); \ } DEFINE_PGM_READ_ANY(float, float); DEFINE_PGM_READ_ANY(signed char, byte); #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \ static const PROGMEM type array##_P[3] = \ {X_##CONFIG, Y_##CONFIG, Z_##CONFIG}; \ static inline type array(int axis) \ { \ return pgm_read_any(&array##_P[axis]); \ } XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS); XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS); XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS); XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH); XYZ_CONSTS_FROM_CONFIG(float, home_retract_mm, HOME_RETRACT_MM); XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR); #ifdef DUAL_X_CARRIAGE #if EXTRUDERS == 1 || defined(COREXY) || !defined(X2_ENABLE_PIN) || !defined(X2_STEP_PIN) || !defined(X2_DIR_PIN) || !defined(X2_HOME_POS) || !defined(X2_MIN_POS) || !defined(X2_MAX_POS) #error "Missing or invalid definitions for DUAL_X_CARRIAGE mode." #elif !defined(X_MAX_PIN) || X_MAX_PIN < 0 #error "Missing or invalid definitions for DUAL_X_CARRIAGE mode X MAX Pin." #endif #if X_HOME_DIR != -1 || X2_HOME_DIR != 1 #error "Please use canonical x-carriage assignment" // the x-carriages are defined by their homing directions #endif #define DXC_FULL_CONTROL_MODE 0 #define DXC_AUTO_PARK_MODE 1 #define DXC_DUPLICATION_MODE 2 #define DXC_MIRROR_MODE 3 int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; static float x_home_pos(int extruder) { if (extruder == 0) return base_home_pos(X_AXIS) + add_homeing[X_AXIS]; else // In dual carriage mode the extruder offset provides an override of the // second X-carriage offset when homed - otherwise X2_HOME_POS is used. // This allow soft recalibration of the second extruder offset position without firmware reflash // (through the M218 command). #ifdef CONFIG_TL return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : tl_X2_MAX_POS; #else return (extruder_offset[X_AXIS][1] > 0) ? extruder_offset[X_AXIS][1] : X2_MAX_POS; #endif } static int x_home_dir(int extruder) { return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR; } #ifdef CONFIG_TL static float inactive_extruder_x_pos = tl_X2_MAX_POS; // used in mode 0 & 1 #else static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1 #endif #endif //DUAL_X_CARRIAGE static void axis_is_at_home(int axis) { #ifdef DUAL_X_CARRIAGE if (axis == X_AXIS) { if (active_extruder != 0) { current_position[X_AXIS] = x_home_pos(active_extruder); min_pos[X_AXIS] = X2_MIN_POS; #ifdef CONFIG_TL max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], tl_X2_MAX_POS); #else max_pos[X_AXIS] = max(extruder_offset[X_AXIS][1], X2_MAX_POS); #endif return; } else if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && active_extruder == 0) { current_position[X_AXIS] = base_home_pos(X_AXIS) + add_homeing[X_AXIS]; min_pos[X_AXIS] = base_min_pos(X_AXIS) + add_homeing[X_AXIS]; #ifdef CONFIG_TL max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + add_homeing[X_AXIS], max(extruder_offset[X_AXIS][1], tl_X2_MAX_POS) - duplicate_extruder_x_offset); #else max_pos[X_AXIS] = min(base_max_pos(X_AXIS) + add_homeing[X_AXIS], max(extruder_offset[X_AXIS][1], X2_MAX_POS) - duplicate_extruder_x_offset); #endif return; } } #endif //DUAL_X_CARRIAGE current_position[axis] = base_home_pos(axis) + add_homeing[axis]; min_pos[axis] = base_min_pos(axis) + add_homeing[axis]; max_pos[axis] = base_max_pos(axis) + add_homeing[axis]; } static void homeaxis(int axis) { #define HOMEAXIS_DO(LETTER) \ ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR == -1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR == 1)) if (axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0) { int axis_home_dir = home_dir(axis); #ifdef DUAL_X_CARRIAGE if (axis == X_AXIS) axis_home_dir = x_home_dir(active_extruder); #endif // Engage Servo endstop if enabled #ifdef SERVO_ENDSTOPS if (SERVO_ENDSTOPS[axis] > -1) { servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2]); } #endif int iR0 = 30; int iR1 = 120; int iR2 = 180; current_position[axis] = 0; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[axis] = 1.5 * max_length(axis) * axis_home_dir; feedrate = homing_feedrate[axis]; command_G4(0.005); plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / iR0, active_extruder); command_G4(0.005); st_synchronize(); current_position[axis] = 0; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[axis] = -home_retract_mm(axis) * axis_home_dir; command_G4(0.005); plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / iR1, active_extruder); command_G4(0.005); st_synchronize(); destination[axis] = 2 * home_retract_mm(axis) * axis_home_dir; feedrate = homing_feedrate[axis] / 2; command_G4(0.005); plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / iR2, active_extruder); command_G4(0.005); st_synchronize(); axis_is_at_home(axis); destination[axis] = current_position[axis]; feedrate = 0.0; endstops_hit_on_purpose(); // Retract Servo endstop if enabled #ifdef SERVO_ENDSTOPS if (SERVO_ENDSTOPS[axis] > -1) { servos[servo_endstops[axis]].write(servo_endstop_angles[axis * 2 + 1]); } #endif } } void command_G92(float XValue = -99999.0, float YValue = -99999.0, float ZValue = -99999.0, float EValue = -99999.0) //By Zyf { if (!code_seen(axis_codes[E_AXIS]) || EValue > -99999.0) st_synchronize(); for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) { if (i == E_AXIS) { current_position[i] = code_value(); plan_set_e_position(current_position[E_AXIS]); } else { current_position[i] = code_value() + add_homeing[i]; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); } } } if (EValue > -99999.0) { current_position[E_AXIS] = EValue; plan_set_e_position(current_position[E_AXIS]); } if (XValue > -99999.0) { current_position[X_AXIS] = XValue + add_homeing[X_AXIS]; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); } if (YValue > -99999.0) { current_position[Y_AXIS] = YValue + add_homeing[Y_AXIS]; plan_set_position(current_position[Y_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); } if (ZValue > -99999.0) { current_position[Z_AXIS] = ZValue + add_homeing[Z_AXIS]; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); } } #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS) void command_G28(int XHome = 0, int YHome = 0, int ZHome = 0) { //By zyf saved_feedrate = feedrate; saved_feedmultiply = feedmultiply; feedmultiply = 100; previous_millis_cmd = millis(); enable_endstops(true, -1); for (int8_t i = 0; i < NUM_AXIS; i++) { destination[i] = current_position[i]; } feedrate = 0.0; home_all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2]))) && XHome == 0 && YHome == 0 && ZHome == 0; bool bSkip = false; #ifdef PRINT_FROM_Z_HEIGHT if ((home_all_axis || code_seen(axis_codes[2]) || ZHome == 1) && !PrintFromZHeightFound && card.sdprinting == 1) { bSkip = true; } bool b_temp_PrintFromZHeightFound = PrintFromZHeightFound; #endif #if Z_HOME_DIR < 0 if ((home_all_axis || ZHome == 1 || code_seen(axis_codes[Z_AXIS])) && !bSkip) { plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[Z_AXIS] = current_position[Z_AXIS] + 7.0; feedrate = homing_feedrate[Z_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder); st_synchronize(); axis_is_at_home(Z_AXIS); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[Z_AXIS] = current_position[Z_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder); feedrate = 0.0; st_synchronize(); #ifdef TL_DUAL_Z //By zyf tl_RUN_STATUS = 1; #endif } #endif // Z_HOME_DIR < 0 #if Z_HOME_DIR > 0 // If homing away from BED do Z first if ((home_all_axis) || Zhome == 1 || (code_seen(axis_codes[Z_AXIS]))) { HOMEAXIS(Z); } #endif #ifdef PRINT_FROM_Z_HEIGHT PrintFromZHeightFound = true; #endif if ((home_all_axis) || XHome == 1 || (code_seen(axis_codes[X_AXIS]))) { #ifdef DUAL_X_CARRIAGE int tmp_extruder = active_extruder; //int tmp_extruder_carriage_mode = extruder_carriage_mode; extruder_carriage_mode = 1; active_extruder = !active_extruder; HOMEAXIS(X); inactive_extruder_x_pos = current_position[X_AXIS]; active_extruder = tmp_extruder; HOMEAXIS(X); // reset state used by the different modes //memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); //By Zyf raised_parked_position[X_AXIS] = current_position[X_AXIS]; //By zyf if ((home_all_axis) || YHome == 1 || (code_seen(axis_codes[Y_AXIS]))) raised_parked_position[Y_AXIS] = 0; //By zyf else raised_parked_position[Y_AXIS] = current_position[Y_AXIS]; raised_parked_position[Z_AXIS] = current_position[Z_AXIS]; //By zyf raised_parked_position[E_AXIS] = current_position[E_AXIS]; //By zyf delayed_move_time = 0; active_extruder_parked = true; //extruder_carriage_mode = tmp_extruder_carriage_mode; #else //!DUAL_X_CARRIAGE HOMEAXIS(X); #endif //DUAL_X_CARRIAGE #ifdef PRINT_FROM_Z_HEIGHT if (!b_temp_PrintFromZHeightFound) { command_G1(0.0); } #endif //PRINT_FROM_Z_HEIGHT } if ((home_all_axis) || YHome == 1 || (code_seen(axis_codes[Y_AXIS]))) { HOMEAXIS(Y); } #ifdef PRINT_FROM_Z_HEIGHT PrintFromZHeightFound = b_temp_PrintFromZHeightFound; #endif #if Z_HOME_DIR < 0 // If homing towards BED do Z last if ((home_all_axis || ZHome == 1 || code_seen(axis_codes[Z_AXIS])) && !bSkip) { #ifdef TL_DUAL_Z //By Zyf tl_Y_STEP_PIN = Z2_STEP_PIN; //65;//60 tl_Y_DIR_PIN = Z2_DIR_PIN; //66;//61 tl_Y_MIN_PIN = Z2_MIN_PIN; //19;//14 tl_Y_ENDSTOPS_INVERTING = Z_ENDSTOPS_INVERTING; //LOW rep_INVERT_Y_DIR = INVERT_Z_DIR; current_position[Z_AXIS] = 0; current_position[Y_AXIS] = 0; int Y_step_per_unit = axis_steps_per_unit[Y_AXIS]; axis_steps_per_unit[Y_AXIS] = axis_steps_per_unit[Z_AXIS]; plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[Z_AXIS] = 1.5 * max_length(Z_AXIS) * home_dir(Z_AXIS); destination[Y_AXIS] = 1.5 * max_length(Z_AXIS) * home_dir(Y_AXIS); feedrate = homing_feedrate[Z_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder); st_synchronize(); axis_is_at_home(Z_AXIS); axis_is_at_home(Y_AXIS); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); destination[Z_AXIS] = current_position[Z_AXIS]; destination[Y_AXIS] = current_position[Y_AXIS]; plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder); feedrate = 0.0; st_synchronize(); endstops_hit_on_purpose(); current_position[X_AXIS] = destination[X_AXIS]; current_position[Y_AXIS] = destination[Y_AXIS]; current_position[Z_AXIS] = destination[Z_AXIS]; int temp_feedrate = homing_feedrate[Y_AXIS]; HOMEAXIS(Z); axis_steps_per_unit[Y_AXIS] = Y_step_per_unit; homing_feedrate[Y_AXIS] = homing_feedrate[Z_AXIS] * 6; HOMEAXIS(Y); homing_feedrate[Y_AXIS] = temp_feedrate; tl_Y_STEP_PIN = Y_STEP_PIN; //60; tl_Y_DIR_PIN = Y_DIR_PIN; //61; tl_Y_MIN_PIN = Y_MIN_PIN; //14; tl_Y_ENDSTOPS_INVERTING = Y_ENDSTOPS_INVERTING; //HIGH rep_INVERT_Y_DIR = INVERT_Y_DIR; HOMEAXIS(Z); #else HOMEAXIS(Z); #endif //TL_DUAL_Z } #endif //Z_HOME_DIR if (code_seen(axis_codes[X_AXIS])) { if (code_value_long() != 0) { current_position[X_AXIS] = code_value() + add_homeing[0]; } } if (code_seen(axis_codes[Y_AXIS])) { if (code_value_long() != 0) { current_position[Y_AXIS] = code_value() + add_homeing[1]; } } if (code_seen(axis_codes[Z_AXIS])) { if (code_value_long() != 0) { current_position[Z_AXIS] = code_value() + add_homeing[2]; } } plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); #ifdef TL_DUAL_Z //By zyf tl_RUN_STATUS = 0; #endif #ifdef ENDSTOPS_ONLY_FOR_HOMING enable_endstops(false, -1); #endif feedrate = saved_feedrate; feedmultiply = saved_feedmultiply; previous_millis_cmd = millis(); endstops_hit_on_purpose(); } //command_G28 void command_T(int T01 = -1) { if (extruder_carriage_mode == 2 || extruder_carriage_mode == 3) { tmp_extruder = 0; active_extruder = 0; return; } if (T01 == -1) { tmp_extruder = code_value(); } else { tmp_extruder = T01; } #ifdef MIX_COLOR_TEST active_extruder = tmp_extruder; return; #endif if (tmp_extruder >= EXTRUDERS) { SERIAL_ECHO_START; SERIAL_ECHO("T"); SERIAL_ECHO(tmp_extruder); SERIAL_ECHOLN(F(MSG_INVALID_EXTRUDER)); } else { boolean make_move = false; if (code_seen('F')) { make_move = true; next_feedrate = code_value(); if (next_feedrate > 0.0) { feedrate = next_feedrate; } } #if EXTRUDERS > 1 if (tmp_extruder != active_extruder) { // Save current position to return to after applying extruder offset //memcpy(destination, current_position, sizeof(destination)); destination[X_AXIS] = current_position[X_AXIS]; //By zyf destination[Y_AXIS] = current_position[Y_AXIS]; //By zyf destination[Z_AXIS] = current_position[Z_AXIS]; //By zyf destination[E_AXIS] = current_position[E_AXIS]; //By zyf #ifdef DUAL_X_CARRIAGE //By zyf go home befor switch if (card.sdprinting != 1) { enable_endstops(true, 0); HOMEAXIS(X); enable_endstops(false, 0); } if (Stopped == false && (delayed_move_time != 0 || current_position[X_AXIS] != x_home_pos(active_extruder))) { // Park old head: 1) raise 2) move to park position 3) lower plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT, current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT, current_position[E_AXIS], homing_feedrate[Z_AXIS] / 10, active_extruder); plan_buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); st_synchronize(); } // apply Y & Z extruder offset (x offset is already used in determining home pos) #ifdef CONFIG_E2_OFFSET if (tl_Y2_OFFSET < 0.0 || tl_Y2_OFFSET > 10.0) tl_Y2_OFFSET = 5.0; if (tl_Z2_OFFSET < 0.0 || tl_Z2_OFFSET > 4.0) tl_Z2_OFFSET = 2.0; extruder_offset[Z_AXIS][0] = 0.0; //By Zyf extruder_offset[Y_AXIS][0] = 0.0; //By Zyf extruder_offset[Y_AXIS][1] = tl_Y2_OFFSET - 5.0; //By Zyf extruder_offset[Z_AXIS][1] = 2.0 - tl_Z2_OFFSET; //By Zyf #else //extruder_offset[Y_AXIS][1] = EXTRUDER_OFFSET_Y[1]; //By Zyf #endif current_position[Y_AXIS] = current_position[Y_AXIS] - extruder_offset[Y_AXIS][active_extruder] + extruder_offset[Y_AXIS][tmp_extruder]; current_position[Z_AXIS] = current_position[Z_AXIS] - extruder_offset[Z_AXIS][active_extruder] + extruder_offset[Z_AXIS][tmp_extruder]; active_extruder = tmp_extruder; // This function resets the max/min values - the current position may be overwritten below. axis_is_at_home(X_AXIS); if (dual_x_carriage_mode == DXC_FULL_CONTROL_MODE) { current_position[X_AXIS] = inactive_extruder_x_pos; inactive_extruder_x_pos = destination[X_AXIS]; } else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) { active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position if (active_extruder == 0 || active_extruder_parked) current_position[X_AXIS] = inactive_extruder_x_pos; else current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset; inactive_extruder_x_pos = destination[X_AXIS]; extruder_carriage_mode = 1; } else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // record raised toolhead position for use by unpark //memcpy(raised_parked_position, current_position, sizeof(raised_parked_position)); raised_parked_position[X_AXIS] = current_position[X_AXIS]; //By zyf raised_parked_position[Y_AXIS] = current_position[Y_AXIS]; //By zyf raised_parked_position[Z_AXIS] = current_position[Z_AXIS]; //By zyf raised_parked_position[E_AXIS] = current_position[E_AXIS]; //By zyf raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT; active_extruder_parked = true; delayed_move_time = 0; //By Zyf gohome after autopark; if(card.sdprinting != 1 || offset_changed == 1) { if(active_extruder == 1) offset_changed = 0; enable_endstops(true, 0); HOMEAXIS(X); enable_endstops(false, 0); } } #else // ! DUAL_X_CARRIAGE \ // Offset extruder (only by XY) int i; for (i = 0; i < 2; i++) { current_position[i] = current_position[i] - extruder_offset[i][active_extruder] + extruder_offset[i][tmp_extruder]; } // Set the new active extruder and position active_extruder = tmp_extruder; #endif // DUAL_X_CARRIAGE plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]); // Move to the old position if 'F' was in the parameters if (make_move && Stopped == false) { prepare_move(); } } #endif // EXTRUDERS > 1 SERIAL_ECHO_START; SERIAL_ECHO(MSG_ACTIVE_EXTRUDER); SERIAL_PROTOCOLLN((int)active_extruder); } } //command_T void command_M605(int SValue = -1) { command_T(0); st_synchronize(); if (SValue > 0 && SValue < 4) { dual_x_carriage_mode = SValue; } else if (code_seen('S')) { dual_x_carriage_mode = code_value(); } if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) { if (code_seen('X')) duplicate_extruder_x_offset = max(code_value(), X2_MIN_POS - x_home_pos(0)); if (code_seen('R')) duplicate_extruder_temp_offset = code_value(); SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); SERIAL_ECHO(" "); SERIAL_ECHO(extruder_offset[X_AXIS][0]); SERIAL_ECHO(","); SERIAL_ECHO(extruder_offset[Y_AXIS][0]); SERIAL_ECHO(" "); SERIAL_ECHO(duplicate_extruder_x_offset); SERIAL_ECHO(","); SERIAL_ECHOLN(extruder_offset[Y_AXIS][1]); } else if (dual_x_carriage_mode != DXC_FULL_CONTROL_MODE && dual_x_carriage_mode != DXC_AUTO_PARK_MODE && dual_x_carriage_mode != DXC_DUPLICATION_MODE && dual_x_carriage_mode != DXC_MIRROR_MODE) { dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE; } active_extruder_parked = false; extruder_carriage_mode = dual_x_carriage_mode; delayed_move_time = 0; } //605 void PrintStopOrFinished() { #ifdef HOLD_M104_TEMP tl_hold_m104_temp[0] = 0.0; tl_hold_m104_temp[1] = 0.0; #endif #ifdef PRINT_FROM_Z_HEIGHT PrintFromZHeightFound = true; print_from_z_target = 0.0; #endif //raised_parked_position[X_AXIS] = current_position[X_AXIS]; //By zyf raised_parked_position[Y_AXIS] = 0; //By zyf //raised_parked_position[Z_AXIS] = current_position[Z_AXIS]; //By zyf //raised_parked_position[E_AXIS] = current_position[E_AXIS]; //By zyf #ifdef POWER_RAIL_RECV EEPROM_Write_PLR(); EEPROM_PRE_Write_PLR(); #endif if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) command_T(0); } void command_G1(float XValue, float YValue, float ZValue, float EValue, int iMode) { if (Stopped == false) { //BOF By zyf if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && !axis_relative_modes[0] && !relative_mode) { float fXMin = X_MIN_POS; float fXMax = tl_X2_MAX_POS; if (active_extruder == 0) fXMax = tl_X2_MAX_POS - X_NOZZLE_WIDTH; if (active_extruder == 1) fXMin = X_MIN_POS + X_NOZZLE_WIDTH; if (code_seen(axis_codes[X_AXIS])) { float fXV = code_value(); float fRate = 1.0; if (code_seen('R')) fRate = code_value(); fXV = fXV / fRate; if (code_seen('M')) { iMode = (int)code_value(); } if ((fXV > fXMax || fXV < fXMin) && iMode == 0) { if(tl_TouchScreenType == 1) { TLSTJC_printconst(F("main.sStatus.txt=\"")); long lN = current_position[X_AXIS] * 10.0; //1 String sSend = String(lN); const char *str0 = sSend.c_str(); TLSTJC_print(str0); TLSTJC_printconst(F("|")); TLSTJC_printconst(F("\"")); TLSTJC_printend(); _delay_ms(50); TLSTJC_printconstln(F("click btReflush,0")); } return; } } } //Eof By zyf #ifdef FILAMENT_FAIL_DETECT if (code_seen('E') || EValue > -99999.0) { if (tl_Filament_Detect > 0) check_filament_fail(); } #endif get_coordinates(XValue, YValue, ZValue, EValue, iMode); // For X Y Z E F prepare_move(); //ClearToSend(); return; } } void command_M190(int SValue = -1) { #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1 unsigned long codenum; //throw away variable //LCD_MESSAGEPGM(MSG_BED_HEATING); if (code_seen('S')) { setTargetBed(code_value()); CooldownNoWait = true; } else if (code_seen('R')) { setTargetBed(code_value()); CooldownNoWait = false; } else if (SValue > -1) { setTargetBed(SValue); CooldownNoWait = true; } codenum = millis(); target_direction = isHeatingBed(); // true if heating, false if cooling card.heating = true; while (target_direction ? (isHeatingBed()) : (isCoolingBed() && (CooldownNoWait == false)) && card.isFileOpen()) { if(tl_TouchScreenType == 0) if (bHeatingStop ) break; if ((millis() - codenum) > 1000) //Print Temp Reading every 1 second while heating up. { float tt = degHotend(active_extruder); SERIAL_PROTOCOLPGM("T:"); SERIAL_PROTOCOL(tt); SERIAL_PROTOCOLPGM(" E:"); SERIAL_PROTOCOL((int)active_extruder); SERIAL_PROTOCOLPGM(" B:"); SERIAL_PROTOCOL_F(degBed(), 1); SERIAL_PROTOCOLLN(""); codenum = millis(); if(tl_TouchScreenType == 1) { String strSerial2 = getSerial2Data(); if (strSerial2 != "") { strSerial2.replace("\r", ""); strSerial2.replace("\n", ""); String strM104 = getSplitValue(strSerial2, ' ', 0); if (strM104 == "M140") { String strTemp = getSplitValue(strSerial2, ' ', 1); int iTempE; if (strTemp.substring(0, 1) == "S") iTempE = strTemp.substring(1, strTemp.length()).toInt(); setTargetBed(iTempE); } else if (strSerial2 == "M1033") { sdcard_stop(); } else if (strSerial2 == "M1031") { sdcard_pause(); } else if (strSerial2 == "M1031 O1") { } else if (strSerial2.substring(0, 5) == "M1032") { sdcard_resume(); } } } else { get_command_dwn(); process_command_dwn(); } } manage_heater(); if (tl_HEATER_FAIL) { card.closefile(); card.sdprinting = 0; } else { } manage_inactivity(); tenlog_status_screen(); } card.heating = false; //LCD_MESSAGEPGM(MSG_BED_DONE); previous_millis_cmd = millis(); #endif } void command_M104(int iT = -1, int iS = -1) { if (setTargetedHotend(104)) { return; } int iTempE; iTempE = tmp_extruder; int iSV = -1; if (code_seen('T')) iTempE = code_value(); if (iT > -1) iTempE = iT; #ifdef TO_IN_ONE iTempE = 0; #endif if (code_seen('S')) iSV = code_value(); if (iS > -1) iSV = iS; setTargetHotend(iSV, iTempE); #ifdef DUAL_X_CARRIAGE if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0) setTargetHotend1(iSV == 0.0 ? 0.0 : iSV + duplicate_extruder_temp_offset); #endif setWatch(); } void command_M109(int SValue = -1) { // M109 - Wait for extruder heater to reach target. #ifdef HOLD_M104_TEMP if(tl_hold_m104_temp[active_extruder] > 0 && card.sdprinting == 1) { SValue = tl_hold_m104_temp[active_extruder]; } #endif if(tl_TouchScreenType == 0) bHeatingStop = false; unsigned long codenum; //throw away variable if (setTargetedHotend(109)) { return; } #ifdef AUTOTEMP autotemp_enabled = false; #endif if (code_seen('S')) { #ifdef MIX_COLOR_TEST setTargetHotend(code_value(), 0); #else #ifdef HOLD_M104_TEMP if(tl_hold_m104_temp[tmp_extruder] > 0 && card.sdprinting == 1){ setTargetHotend(tl_hold_m104_temp[tmp_extruder], tmp_extruder); }else{ setTargetHotend(code_value(), tmp_extruder); } #else setTargetHotend(code_value(), tmp_extruder); #endif #endif #ifdef DUAL_X_CARRIAGE if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0) setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset); #endif CooldownNoWait = true; } else if (code_seen('R')) { #ifdef MIX_COLOR_TEST setTargetHotend(code_value(), 0); #else setTargetHotend(code_value(), tmp_extruder); #endif #ifdef DUAL_X_CARRIAGE if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0) setTargetHotend1(code_value() == 0.0 ? 0.0 : code_value() + duplicate_extruder_temp_offset); #endif CooldownNoWait = false; } if (SValue > -1) { #ifdef MIX_COLOR_TEST setTargetHotend(SValue, 0); #else setTargetHotend(SValue, tmp_extruder); #endif #ifdef DUAL_X_CARRIAGE if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0) setTargetHotend1(SValue == 0.0 ? 0.0 : SValue + duplicate_extruder_temp_offset); #endif CooldownNoWait = true; } #ifdef AUTOTEMP if (code_seen('S')) autotemp_min = code_value(); if (SValue > -1) autotemp_min = SValue; if (code_seen('B')) autotemp_max = code_value(); if (code_seen('F')) { autotemp_factor = code_value(); autotemp_enabled = true; } #endif setWatch(); codenum = millis(); /* See if we are heating up or cooling down */ target_direction = isHeatingHotend(tmp_extruder); // true if heating, false if cooling //By Zyf if (target_direction) card.heating = true; #ifdef TEMP_RESIDENCY_TIME long residencyStart; residencyStart = -1; /* continue to loop until we have reached the target temp _and_ until TEMP_RESIDENCY_TIME hasn't passed since we reached it */ while ((residencyStart == -1 || (residencyStart >= 0 && ((unsigned int)(millis() - residencyStart)) < (TEMP_RESIDENCY_TIME * 1000UL)) && card.isFileOpen()) && (target_direction ? isHeatingHotend(tmp_extruder) : (isCoolingHotend(tmp_extruder) && !CooldownNoWait))) { #else while ( (target_direction ? isHeatingHotend(tmp_extruder) : (isCoolingHotend(tmp_extruder) && !CooldownNoWait)) && card.isFileOpen()) { #endif //TEMP_RESIDENCY_TIME if(tl_TouchScreenType == 0) if (bHeatingStop) break; if ((millis() - codenum) > 1000UL) { //Print Temp Reading and remaining time every 1 second while heating up/cooling down SERIAL_PROTOCOLPGM("T:"); SERIAL_PROTOCOL_F(degHotend(tmp_extruder), 1); SERIAL_PROTOCOLPGM(" E:"); SERIAL_PROTOCOL((int)tmp_extruder); #ifdef TEMP_RESIDENCY_TIME SERIAL_PROTOCOLPGM(" W:"); if (residencyStart > -1) { codenum = ((TEMP_RESIDENCY_TIME * 1000UL) - (millis() - residencyStart)) / 1000UL; SERIAL_PROTOCOLLN(codenum); } else { SERIAL_PROTOCOLLN(F("?")); } #else SERIAL_PROTOCOLLN(""); #endif codenum = millis(); if(tl_TouchScreenType == 1) { String strSerial2 = getSerial2Data(); if (strSerial2 != "") { strSerial2.replace("\r", ""); strSerial2.replace("\n", ""); String strM104 = getSplitValue(strSerial2, ' ', 0); if (strM104 == "M104") { String strT01 = getSplitValue(strSerial2, ' ', 1); String strTemp = getSplitValue(strSerial2, ' ', 2); int iTempE; int iTemp = 0; if (strT01 == "T0") iTemp = 0; else iTemp = 1; if (strTemp.substring(0, 1) == "S") iTempE = strTemp.substring(1, strTemp.length()).toInt(); setTargetHotend(iTempE, iTemp); #ifdef DUAL_X_CARRIAGE if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0) setTargetHotend1(iTempE == 0.0 ? 0.0 : iTempE + duplicate_extruder_temp_offset); if ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 1) setTargetHotend(iTempE == 0.0 ? 0.0 : iTempE - duplicate_extruder_temp_offset, 0); #endif } else if (strSerial2 == "M1033") { sdcard_stop(); } else if (strSerial2 == "M1031") { sdcard_pause(); } else if (strSerial2 == "M1031 O1") { //sdcard_pause(1); } else if (strSerial2.substring(0, 5) == "M1032") { sdcard_resume(); } } } if(tl_TouchScreenType == 0) { get_command_dwn(); process_command_dwn(); } } manage_heater(); if (tl_HEATER_FAIL) { card.closefile(); card.sdprinting = 0; manage_inactivity(); tenlog_status_screen(); return; } manage_inactivity(); tenlog_status_screen(); #ifdef TEMP_RESIDENCY_TIME /* start/restart the TEMP_RESIDENCY_TIME timer whenever we reach target temp for the first time or when current temp falls outside the hysteresis after target temp was reached */ if ((residencyStart == -1 && target_direction && (degHotend(tmp_extruder) >= (degTargetHotend(tmp_extruder) - TEMP_WINDOW) && (dual_x_carriage_mode == DXC_AUTO_PARK_MODE || ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0 && degHotend(1) >= (degTargetHotend(0) - TEMP_WINDOW))))) || (residencyStart == -1 && !target_direction && (degHotend(tmp_extruder) <= (degTargetHotend(tmp_extruder) + TEMP_WINDOW) && (dual_x_carriage_mode == DXC_AUTO_PARK_MODE || ((dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) && tmp_extruder == 0 && degHotend(1) <= (degTargetHotend(0) + TEMP_WINDOW))) )) || (residencyStart > -1 && labs(degHotend(tmp_extruder) - degTargetHotend(tmp_extruder)) > TEMP_HYSTERESIS)) { residencyStart = millis(); } #endif //TEMP_RESIDENCY_TIME } //while card.heating = false; if (card.sdprinting != 1) { //LCD_MESSAGEPGM(MSG_HEATING_COMPLETE); } //starttime=millis(); //By Zyf No need previous_millis_cmd = millis(); } //command_M109 #ifdef POWER_LOSS_RECOVERY void command_M1003() { bool bOK = false; String sPLR = card.get_PLR(); String sLFileName = getSplitValue(sPLR, '|', 0); String sFileName = getSplitValue(sPLR, '|', 1); uint32_t lFPos = 0; int iTemp0 = 0; int iTemp1 = 0; int iFan = 0; int iT01 = 0; int iTempBed = 0; float fZ = 0.0; float fE = 0.0; float fX = 0.0; float fY = 0.0; int iMode = 0; float fXOffSet = 0.0; if (sPLR != "") { lFPos = atol(const_cast<char *>(getSplitValue(sPLR, '|', 2).c_str())); iTemp0 = getSplitValue(sPLR, '|', 3).toInt(); iTemp1 = getSplitValue(sPLR, '|', 4).toInt(); iT01 = getSplitValue(sPLR, '|', 5).toInt(); fZ = string2Float(getSplitValue(sPLR, '|', 6)); fE = string2Float(getSplitValue(sPLR, '|', 7)); iFan = getSplitValue(sPLR, '|', 8).toInt(); fX = string2Float(getSplitValue(sPLR, '|', 9)); fY = string2Float(getSplitValue(sPLR, '|', 10)); iTempBed = getSplitValue(sPLR, '|', 11).toInt(); iMode = getSplitValue(sPLR, '|', 12).toInt(); fXOffSet = string2Float(getSplitValue(sPLR, '|', 13)); if (lFPos > 2048) { bOK = true; } } if (!bOK) { if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("page main")); } else { char *fName = const_cast<char *>(sFileName.c_str()); card.openFile(fName, fName, true, lFPos); if(tl_TouchScreenType == 1) { gsPrinting = "Printing " + sLFileName; sFileName = "" + sLFileName + ""; TLSTJC_printconst(F("printing.tFileName.txt=\"")); const char *str0 = sFileName.c_str(); TLSTJC_print(str0); TLSTJC_printconstln(F("\"")); TLSTJC_printconstln(F("page printing")); } else { gsPrinting = "Printing " + sLFileName; DWN_Text(0x7500, 32, gsPrinting, true); DWN_Page(DWN_P_PRINTING); } feedrate = 4000; card.sdprinting = 2; if (iTempBed > 0) { command_M190(iTempBed); } #ifdef DUAL_X_CARRIAGE dual_x_carriage_mode = iMode; if (iTemp0 > 0) { if (dual_x_carriage_mode == DXC_DUPLICATION_MODE || dual_x_carriage_mode == DXC_MIRROR_MODE) { tmp_extruder = 0; command_M109(iTemp0); } else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { setTargetHotend(iTemp0, 0); } } if (iTemp1 > 0) { if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { setTargetHotend(iTemp0, 1); } } if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { if (iTemp0 > 0 && iT01 == 0) { active_extruder = 0; command_M109(iTemp0); } if (iTemp1 > 0 && iT01 == 1) { active_extruder = 1; command_M109(iTemp1); } } axis_is_at_home(X_AXIS); if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) { duplicate_extruder_x_offset = fXOffSet; } if (iT01 == 1 && fX < 1) fX = tl_X2_MAX_POS - 60; #else if (iTemp0 > 0) { command_M109(iTemp0); } #endif //DUAL_X_CARRIAGE //fZ = fZ + 1.0; fanSpeed = iFan; command_G92(0.0, 0.0, fZ, fE); command_G1(-99999.0, -99999.0, fZ + 15.0, fE); command_G28(1, 1, 0); #ifdef DUAL_X_CARRIAGE if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { //command_T(0); //command_T(iT01); active_extruder = iT01; float fYOS = 0.0; float fXOS = -1 * X_NOZZLE_WIDTH; if (iT01 == 1) { fYOS = 2 * (tl_Y2_OFFSET - 5.0); fXOS = tl_X2_MAX_POS; } command_G92(fXOS, fYOS, fZ + 15.0, fE); } #endif #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_Write_PLR(); EEPROM_PRE_Write_PLR(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) card.Write_PLR(); card.PRE_Write_PLR(); #endif //fZ = fZ - 1.0; command_G1(fX, fY, fZ, fE); feedrate = string2Float(getSplitValue(sPLR, '|', 13)); if (feedrate < 2000) feedrate = 4000; card.sdprinting = 0; card.startFileprint(); starttime = millis(); } } #endif //POWER_LOSS_RECOVERY void command_M502() { Config_ResetDefault(); if(tl_TouchScreenType == 0) Init_TLScreen_dwn(); else Init_TLScreen_tjc(); } void command_M1021(int SValue) { if (code_seen('S') || SValue > -1 && SValue < 4) { int iTemp = -100; if (SValue > -1 && SValue < 4) iTemp = SValue; else iTemp = code_value(); if (iTemp == 0) preheat_abs(); else if (iTemp == 1) preheat_pla(); else if (iTemp == 2) cooldown(); else if (iTemp == 3) { //disable all steppers and cool down. cooldown(); st_synchronize(); disable_e0(); disable_e1(); disable_e2(); finishAndDisableSteppers(false); } } } void process_command_dwn() { if (dwn_command[0] == 0x5A && dwn_command[1] == 0xA5) { //Header Good if(lLEDTimeTimecount >= DWN_LED_TIMEOUT) { dwn_command[0] = 0; dwn_command[1] = 0; lLEDTimeTimecount = 0; DWN_LED(DWN_LED_ON); return; } if (dwn_command[2] == 0x03 && dwn_command[3] == 0x82 && dwn_command[4] == 0x4F && dwn_command[5] == 0x4B) { bAtv = false; DWN_Page(0); } else if (dwn_command[3] == 0x83) { //Read from DWIN controller if (dwn_command[4] == 0x10 && dwn_command[5] == 0x02) { bAtvGot0 = true; String strCMD = ""; for (int i = 7; i < 7 + 20; i++) { strCMD += (char)dwn_command[i]; } strCMD.toUpperCase(); if (CalAtv(strCMD) == lAtvCode) { bAtv = true; String strID = get_device_id(); DWN_Text(0x7280, 26, "SN" + strID); } } else if (dwn_command[4] == 0x10 && dwn_command[5] == 0x22) { //get code bAtvGot1 = true; lAtvCode = ConvertHexLong(dwn_command, 4); } else if (dwn_command[4] == 0x10 && dwn_command[5] == 0x32) { //get logo id bLogoGot = true; iOldLogoID = ConvertHexLong(dwn_command, 4); showDWNLogo(); _delay_ms(50); } else if (dwn_command[4] == 0x60) { long lData = ConvertHexLong(dwn_command, 2); switch ((int)dwn_command[5]) { case 0x02: case 0x00: { int iExt = dwn_command[5] * 0.5; #ifdef HOLD_M104_TENO if(card.sdprinting == 1){ tl_hold_m104_temp[iExt] = (float)lData; } #endif command_M104(iExt, lData); } break; case 0x04: setTargetBed(lData); break; case 0x06: feedrate = 6000; command_G1((float)lData / 10.0); break; case 0x07: feedrate = 6000; command_G1(-99999.0, (float)lData / 10.0); break; case 0x08: feedrate = 6000; command_G1(-99999.0, -99999.0, (float)lData / 10.0); break; case 0x10: case 0x12: case 0x14: case 0x16: lData = ConvertHexLong(dwn_command, 4); axis_steps_per_unit[((int)dwn_command[5] - 0x10) / 2] = (float)lData / 100.0; Config_StoreSettings(); break; case 0x18: lData = ConvertHexLong(dwn_command, 4); tl_X2_MAX_POS = (float)lData / 100.0; Config_StoreSettings(); offset_changed = 1; break; case 0x20: tl_Y2_OFFSET = (float)lData / 100.0; Config_StoreSettings(); offset_changed = 1; break; case 0x21: tl_Z2_OFFSET = (float)lData / 100.0; Config_StoreSettings(); offset_changed = 1; break; case 0x23: tl_FAN2_VALUE = lData; if (tl_FAN2_VALUE > 100) tl_FAN2_VALUE = 100; Config_StoreSettings(); break; case 0x22: tl_FAN2_START_TEMP = lData; Config_StoreSettings(); break; case 0x52: feedmultiply = lData; break; case 0x41: print_from_z_target = (float)lData / 10.0; break; case 0x0A: { int iFan = (int)((float)lData / 100.0 * 256.0 + 0.5); if (iFan > 255) iFan = 255; fanSpeed = iFan; } break; case 0x70: if (lData != iOldLogoID) { RWLogo(lData); } break; case 0x66: lData = ConvertHexLong(dwn_command, 4); lAtvCode = lData; break; } } else if (dwn_command[4] == 0x50 && dwn_command[5] == 00) { long lData = ConvertHexLong(dwn_command, 2); float fTemp = 0.0; switch (lData) { case 0x07: case 0x75: if (fanSpeed > 0) fanSpeed = 0; else fanSpeed = 255; break; case 0x02: case 0x17: case 0x87: if (active_extruder == 0) command_T(1); else command_T(0); break; case 0x11: case 0x35: case 0x84: command_G4(0.001); command_G4(0.001); command_G4(0.001); command_G4(0.001); command_G28(); break; case 0x91: case 0x92: case 0x93: command_M605(lData - 0x90); break; case 0x12: command_M605(1); break; case 0x74: command_M1021(2); break; case 0x72: command_M1021(0); break; case 0x73: command_M1021(1); break; case 0x82: feedrate = 6000; command_G1(-99999.0, -99999.0, 5.0); command_G1(32.0, Y_MAX_POS - 53.0); command_G1(-99999.0, -99999.0, 0.0); break; case 0x83: feedrate = 6000; command_G1(-99999.0, -99999.0, 5.0); command_G1(tl_X2_MAX_POS - 81, Y_MAX_POS - 53.0); command_G1(-99999.0, -99999.0, 0.0); break; case 0x85: feedrate = 6000; command_G1(-99999.0, -99999.0, 5.0); command_G1(32.0, 25.0); command_G1(-99999.0, -99999.0, 0.0); break; case 0x86: feedrate = 6000; command_G1(-99999.0, -99999.0, 5.0); command_G1(tl_X2_MAX_POS - 81, 25.0); command_G1(-99999.0, -99999.0, 0.0); break; case 0xC1: iMoveRate = 1; break; case 0xC2: iMoveRate = 10; break; case 0xC3: iMoveRate = 100; break; case 0x34: feedrate = 6000; command_T(0); fTemp = (float)iMoveRate / 10.0; command_G1(fTemp, -99999.0, -99999.0, -99999.0, 1); break; case 0x33: feedrate = 6000; command_T(0); fTemp = (float)iMoveRate / 10.0; command_G1(-1.0 * fTemp, -99999.0, -99999.0, -99999.0, 1); break; case 0x31: feedrate = 6000; fTemp = (float)iMoveRate / 10.0; command_G1(-99999.0, -1.0 * fTemp, -99999.0, -99999.0, 1); break; case 0x32: feedrate = 6000; fTemp = (float)iMoveRate / 10.0; command_G1(-99999.0, fTemp, -99999.0, -99999.0, 1); break; case 0x37: feedrate = 6000; fTemp = (float)iMoveRate / 10.0; command_G1(-99999.0, -99999.0, fTemp, -99999.0, 1); break; case 0x38: feedrate = 6000; fTemp = (float)iMoveRate / 10.0; command_G1(-99999.0, -99999.0, -1.0 * fTemp, -99999.0, 1); break; case 0x39: command_T(1); fTemp = (float)iMoveRate / 10.0; feedrate = 100; command_G1(-99999.0, -99999.0, -99999.0, -1.0 * fTemp, 1); break; case 0x3A: command_T(1); fTemp = (float)iMoveRate / 10.0; feedrate = 100; command_G1(-99999.0, -99999.0, -99999.0, fTemp, 1); break; case 0x3E: command_T(0); fTemp = (float)iMoveRate / 10.0; feedrate = 100; command_G1(-99999.0, -99999.0, -99999.0, -1.0 * fTemp, 1); break; case 0x3F: command_T(0); fTemp = (float)iMoveRate / 10.0; feedrate = 100; command_G1(-99999.0, -99999.0, -99999.0, fTemp, 1); break; case 0x3B: feedrate = 6000; command_T(1); fTemp = (float)iMoveRate / 10.0; command_G1(-1.0 * fTemp, -99999.0, -99999.0, -99999.0, 1); break; case 0x3D: feedrate = 6000; command_T(1); fTemp = (float)iMoveRate / 10.0; command_G1(fTemp, -99999.0, -99999.0, -99999.0, 1); break; case 0x18: if (b_PLR_MODULE_Detected) DWN_Message(MSG_POWER_OFF, "", false); //Reset else command_M1021(3); break; case 0x29: case 0x2A: case 0x2B: case 0x2C: languageID = lData - 0x29 + 3; case 0x21: case 0x22: case 0x20: if (lData == 0x20) languageID = 2; else if (lData == 0x22 || lData == 0x21) { languageID = lData - 0x21; } //DWN_Data(0x8801, (dual_x_carriage_mode - 1) + languageID * 3, 2); DWN_Data(0x8803, b_PLR_MODULE_Detected + languageID * 2, 2); DWN_Language(languageID); Config_StoreSettings(); //Init_TLScreen(); break; case 0x25: if (!card.isFileOpen()) { DWN_Page(DWN_P_MAIN); } else { DWN_Page(DWN_P_PRINTING); } break; #ifdef HAS_PLR_MODULE case 0x23: if (b_PLR_MODULE_Detected) { tl_AUTO_OFF = !tl_AUTO_OFF; DWN_Data(0x8012, tl_AUTO_OFF, 2); Config_StoreSettings(); } break; #endif #ifdef FILAMENT_FAIL_DETECT case 0x28: tl_Filament_Detect = !tl_Filament_Detect; DWN_Data(0x8014, tl_Filament_Detect, 2); Config_StoreSettings(); //Init_TLScreen(); break; #endif case 0x27: tl_ECO_MODE = !tl_ECO_MODE; DWN_Data(0x8013, tl_ECO_MODE, 2); Config_StoreSettings(); //Init_TLScreen(); break; case 0x24: DWN_Message(MSG_RESET_DEFALT, "", false); //Reset break; case 0xD1: DWN_MessageBoxHandler(true); //Msg OK dwnMessageID = -1; break; case 0xD2: DWN_MessageBoxHandler(false); //Msg Cancel dwnMessageID = -1; break; case 0xA6: if (degTargetHotend(0) > 50) command_M104(0, 0); else command_M104(0, pause_T0T); break; case 0xA7: if (degTargetHotend(0) > 50) command_M104(1, 0); else command_M104(1, pause_T1T); break; case 0xA1: if (card.isFileOpen()) { DWN_Page(DWN_P_PRINTING); if (pause_T0T1 == 1) enquecommand_P(PSTR("T1")); else enquecommand_P(PSTR("T0")); _delay_ms(100); if (pause_BedT > 0) { String strCommand = "M140 S" + String(pause_BedT); char *_Command = strCommand.c_str(); enquecommand(_Command); } } else DWN_Page(DWN_P_TOOLS); break; case 0xA2: load_filament(0, 0); break; case 0xA3: load_filament(0, 1); break; case 0xA4: load_filament(1, 0); break; case 0xA5: load_filament(1, 1); break; case 0x05: sdcard_tlcontroller_dwn(); break; case 0x58: if (i_print_page_id > 0) { i_print_page_id--; sdcard_tlcontroller_dwn(); } break; case 0x59: if (!b_is_last_page) { i_print_page_id++; sdcard_tlcontroller_dwn(); } break; case 0x57: if (print_from_z_target) DWN_Page(DWN_P_TOOLS); else { DWN_Page(DWN_P_MAIN); } break; case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: iPrintID = lData - 0x51; if (file_name_long_list[iPrintID] != "") DWN_Message(MSG_START_PRINT, file_name_long_list[iPrintID] + "?", false); break; case 0xB1: print_from_z_target = 0.0; DWN_Page(DWN_P_TOOLS); break; case 0xB2: if (print_from_z_target == 0.0) { DWN_Message(MSG_INPUT_Z_HEIGHT, "", false); } else { sdcard_tlcontroller_dwn(); DWN_Page(DWN_P_SEL_FILE); } break; case 0x63: DWN_Message(MSG_STOP_PRINT, "", false); break; case 0x62: DWN_Pause(false); break; case 0x15: case 0x64: if (lData == 0x15 || lData == 0x64 && card.sdprinting == 0) { enquecommand_P(PSTR("M605 S1")); _delay_ms(300); enquecommand_P(PSTR("G28 X")); _delay_ms(100); if (card.isFileOpen() && card.sdprinting == 0) { DWN_Page(DWN_P_RELOAD); } } break; case 0xF1: case 0xF2: { static long lLogoBTS; if (lData == 0xF1) { lLogoBTS = millis(); } else if (lData == 0xF2) { if (millis() - lLogoBTS <= 1500 && card.sdprinting != 1) { DWN_VClick(5, 5); } } } break; case 0xE2: long lCal = CalAtv(gsDeviceID); if (lCal == lAtvCode) { DWN_Text(0x1002, 22, gsDeviceID, false); _delay_ms(5); DWN_NORFData(0x000002, 0x1002, 22, true); _delay_ms(500); DWN_Data(0x1022, lAtvCode, 4); _delay_ms(5); DWN_NORFData(0x000022, 0x1022, 2, true); _delay_ms(500); bAtv = true; } else { DWN_Data(0x6066, 6666, 4); } break; } } } dwn_command[0] = 0x00; dwn_command[1] = 0x00; } } void process_commands() { if (tl_HEATER_FAIL) { card.closefile(); card.sdprinting = 0; tl_HEATER_FAIL = false; } unsigned long codenum; //throw away variable char *starpos = NULL; if (code_seen('G')) { switch ((int)code_value()) { case 0: // G0 -> G1 case 1: // G1 command_G1(); break; case 2: // G2 - CW ARC if (Stopped == false) { get_arc_coordinates(); prepare_arc_move(true); return; } case 3: // G3 - CCW ARC if (Stopped == false) { get_arc_coordinates(); prepare_arc_move(false); return; } case 4: // G4 dwell command_G4(); break; #ifdef FWRETRACT case 10: // G10 retract if (!retracted) { destination[X_AXIS] = current_position[X_AXIS]; destination[Y_AXIS] = current_position[Y_AXIS]; destination[Z_AXIS] = current_position[Z_AXIS]; current_position[Z_AXIS] += -retract_zlift; destination[E_AXIS] = current_position[E_AXIS] - retract_length; feedrate = retract_feedrate; retracted = true; prepare_move(); } break; case 11: // G10 retract_recover if (!retracted) { destination[X_AXIS] = current_position[X_AXIS]; destination[Y_AXIS] = current_position[Y_AXIS]; destination[Z_AXIS] = current_position[Z_AXIS]; current_position[Z_AXIS] += retract_zlift; current_position[E_AXIS] += -retract_recover_length; feedrate = retract_recover_feedrate; retracted = false; prepare_move(); } break; #endif //FWRETRACT case 28: //G28 Home all Axis one at a time command_G4(0.001); command_G4(0.001); command_G4(0.001); command_G4(0.001); command_G28(); break; case 90: // G90 relative_mode = false; break; case 91: // G91 relative_mode = true; break; case 92: // G92 command_G92(); break; } //Case G Number } //Goce Seen G else if (code_seen('M')) { switch ((int)code_value()) { case 0: // M0 - Unconditional stop - Wait for user button press on LCD case 1: // M1 - Conditional stop - Wait for user button press on LCD { sdcard_pause(1); } break; case 17: //LCD_MESSAGEPGM(MSG_NO_MOVE); enable_x(); enable_y(); enable_z(); enable_e0(); enable_e1(); enable_e2(); break; #ifdef SDSUPPORT case 19: //M19 tlController list sd file { if (code_seen('S')) i_print_page_id = code_value(); sdcard_tlcontroller_tjc(); } break; case 20: // M20 - list SD card { SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST); card.ls(); SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST); } break; case 21: // M21 - init SD card card.initsd(); break; case 22: //M22 - release SD card card.release(); break; case 23: //M23 - Select file starpos = (strchr(strchr_pointer + 4, '*')); if (starpos != NULL) *(starpos - 1) = '\0'; card.openFile(strchr_pointer + 4, strchr_pointer + 4, true); break; case 24: //M24 - Start SD print card.startFileprint(); starttime = millis(); break; case 25: //M25 - Pause SD print sdcard_pause(1); break; case 26: //M26 - Set SD index if (card.cardOK && code_seen('S')) { card.setIndex(code_value_long()); } break; case 27: //M27 - Get SD status card.getStatus(); break; case 28: //M28 - Start SD write starpos = (strchr(strchr_pointer + 4, '*')); if (starpos != NULL) { char *npos = strchr(cmdbuffer[bufindr], 'N'); strchr_pointer = strchr(npos, ' ') + 1; *(starpos - 1) = '\0'; } card.openFile(strchr_pointer + 4, strchr_pointer + 4, false); break; case 29: //M29 - Stop SD write //processed in write to file routine above //card,saving = false; break; case 30: //M30 <filename> Delete File if (card.cardOK) { card.closefile(); starpos = (strchr(strchr_pointer + 4, '*')); if (starpos != NULL) { char *npos = strchr(cmdbuffer[bufindr], 'N'); strchr_pointer = strchr(npos, ' ') + 1; *(starpos - 1) = '\0'; } card.removeFile(strchr_pointer + 4); } break; case 32: //M32 - Select file and start SD print if (card.sdprinting == 1) { st_synchronize(); card.closefile(); } starpos = (strchr(strchr_pointer + 4, '*')); if (starpos != NULL) *(starpos - 1) = '\0'; card.openFile(strchr_pointer + 4, strchr_pointer + 4, true); card.startFileprint(); starttime = millis(); break; case 928: //M928 - Start SD write starpos = (strchr(strchr_pointer + 5, '*')); if (starpos != NULL) { char *npos = strchr(cmdbuffer[bufindr], 'N'); strchr_pointer = strchr(npos, ' ') + 1; *(starpos - 1) = '\0'; } card.openLogFile(strchr_pointer + 5); break; case 226: //M226 { sdcard_pause(1); } break; #endif //SDSUPPORT case 31: //M31 take time since the start of the SD print or an M109 command { stoptime = millis(); char time[30]; unsigned long t = (stoptime - starttime) / 1000; int sec, min; min = t / 60; sec = t % 60; sprintf_P(time, PSTR("%i min, %i sec"), min, sec); SERIAL_ECHO_START; SERIAL_ECHOLN(time); //lcd_setstatus(time); autotempShutdown(); } break; case 42: //M42 -Change pin status via gcode if (code_seen('S')) { int pin_status = code_value(); int pin_number = LED_PIN; if (code_seen('P') && pin_status >= 0 && pin_status <= 255) pin_number = code_value(); for (int8_t i = 0; i < (int8_t)sizeof(sensitive_pins); i++) { if (sensitive_pins[i] == pin_number) { pin_number = -1; break; } } #if defined(FAN_PIN) && FAN_PIN > -1 if (pin_number == FAN_PIN) fanSpeed = pin_status; #endif if (pin_number > -1) { pinMode(pin_number, OUTPUT); digitalWrite(pin_number, pin_status); analogWrite(pin_number, pin_status); } } break; case 104: // M104 set extruder temp { command_M104(); } break; case 140: // M140 set bed temp if (code_seen('S')) setTargetBed(code_value()); break; case 105: // M105 if (setTargetedHotend(105)) { break; } #if defined(TEMP_0_PIN) && TEMP_0_PIN > -1 SERIAL_PROTOCOLPGM("ok T:"); SERIAL_PROTOCOL_F(degHotend(0), 1); SERIAL_PROTOCOLPGM("/"); SERIAL_PROTOCOL_F(degTargetHotend(0), 1); #if defined(TEMP_1_PIN) && TEMP_1_PIN > -1 SERIAL_PROTOCOLPGM(" T1:"); SERIAL_PROTOCOL_F(degHotend(1), 1); SERIAL_PROTOCOLPGM("/"); SERIAL_PROTOCOL_F(degTargetHotend(1), 1); #endif #if defined(TEMP_BED_PIN) && TEMP_BED_PIN > -1 SERIAL_PROTOCOLPGM(" B:"); SERIAL_PROTOCOL_F(degBed(), 1); SERIAL_PROTOCOLPGM(" /"); SERIAL_PROTOCOL_F(degTargetBed(), 1); #endif //TEMP_BED_PIN #else SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS); #endif SERIAL_PROTOCOLPGM(" @:"); SERIAL_PROTOCOL(getHeaterPower(tmp_extruder)); SERIAL_PROTOCOLPGM(" B@:"); SERIAL_PROTOCOL(getHeaterPower(-1)); SERIAL_PROTOCOLLN(""); return; break; case 109: command_M109(); break; case 190: // M190 - Wait for bed heater to reach target. command_M190(); break; #if defined(FAN_PIN) && FAN_PIN > -1 case 106: //M106 Fan On { float fR = 1; int iR = 0; if (code_seen('R')) iR = code_value(); if (iR == 1) fR = 255.0 / 100.0; if (code_seen('S')) { int iV = code_value() * fR; fanSpeed = constrain(iV, 0, 255); } else { fanSpeed = 255; } } break; case 107: //M107 Fan Off fanSpeed = 0; break; #endif //FAN_PIN #ifdef BARICUDA // PWM for HEATER_1_PIN #if defined(HEATER_1_PIN) && HEATER_1_PIN > -1 case 126: //M126 valve open if (code_seen('S')) { ValvePressure = constrain(code_value(), 0, 255); } else { ValvePressure = 255; } break; case 127: //M127 valve closed ValvePressure = 0; break; #endif //HEATER_1_PIN // PWM for HEATER_2_PIN #if defined(HEATER_2_PIN) && HEATER_2_PIN > -1 case 128: //M128 valve open if (code_seen('S')) { EtoPPressure = constrain(code_value(), 0, 255); } else { EtoPPressure = 255; } break; case 129: //M129 valve closed EtoPPressure = 0; break; #endif //HEATER_2_PIN #endif #if defined(PS_ON_PIN) && PS_ON_PIN > -1 case 80: // M80 - ATX Power On SET_OUTPUT(PS_ON_PIN); //GND WRITE(PS_ON_PIN, PS_ON_AWAKE); break; #endif case 81: // M81 - ATX Power Off command_M81(false); break; case 82: axis_relative_modes[3] = false; break; case 83: axis_relative_modes[3] = true; break; case 18: //compatibility case 84: // M84 if (code_seen('S')) { stepper_inactive_time = code_value() * 1000; } else { bool all_axis = !((code_seen(axis_codes[0])) || (code_seen(axis_codes[1])) || (code_seen(axis_codes[2])) || (code_seen(axis_codes[3]))); if (all_axis) { st_synchronize(); disable_e0(); disable_e1(); disable_e2(); finishAndDisableSteppers(true); } else { st_synchronize(); if (code_seen('X')) disable_x(); if (code_seen('Y')) disable_y(); if (code_seen('Z')) disable_z(); #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS if (code_seen('E')) { disable_e0(); disable_e1(); disable_e2(); } #endif } } break; case 85: // M85 code_seen('S'); max_inactive_time = code_value() * 1000; break; case 92: // M92 { float fRate = 1.0; if (code_seen('R')) { fRate = (float)code_value(); } for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) { if (i == 3) { // E float value = code_value() / fRate; if (value < 20.0) { float factor = axis_steps_per_unit[i] / value; // increase e constants if M92 E14 is given for netfab. max_e_jerk *= factor; max_feedrate[i] *= factor; axis_steps_per_sqr_second[i] *= factor; } axis_steps_per_unit[i] = value; } else { axis_steps_per_unit[i] = code_value() / fRate; } } } Config_StoreSettings(); //By zyf } break; case 115: // M115 SERIAL_PROTOCOLPGM(MSG_M115_REPORT); break; case 117: // M117 display message starpos = (strchr(strchr_pointer + 5, '*')); if (starpos != NULL) *(starpos - 1) = '\0'; gsM117 = strchr_pointer + 5; //lcd_setstatus(strchr_pointer + 5); break; case 114: // M114 SERIAL_PROTOCOLPGM("X:"); SERIAL_PROTOCOL(current_position[X_AXIS]); SERIAL_PROTOCOLPGM("Y:"); SERIAL_PROTOCOL(current_position[Y_AXIS]); SERIAL_PROTOCOLPGM("Z:"); SERIAL_PROTOCOL(current_position[Z_AXIS]); SERIAL_PROTOCOLPGM("E:"); SERIAL_PROTOCOL(current_position[E_AXIS]); SERIAL_PROTOCOLPGM(MSG_COUNT_X); SERIAL_PROTOCOL(float(st_get_position(X_AXIS)) / axis_steps_per_unit[X_AXIS]); SERIAL_PROTOCOLPGM("Y:"); SERIAL_PROTOCOL(float(st_get_position(Y_AXIS)) / axis_steps_per_unit[Y_AXIS]); SERIAL_PROTOCOLPGM("Z:"); SERIAL_PROTOCOL(float(st_get_position(Z_AXIS)) / axis_steps_per_unit[Z_AXIS]); SERIAL_PROTOCOLLN(""); break; case 120: // M120 enable_endstops(false, -1); break; case 121: // M121 enable_endstops(true, -1); break; case 119: // M119 SERIAL_PROTOCOLLN(F(MSG_M119_REPORT)); #if defined(X_MIN_PIN) && X_MIN_PIN > -1 SERIAL_PROTOCOLPGM(MSG_X_MIN); SERIAL_PROTOCOLLN(((READ(X_MIN_PIN) ^ X_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif #if defined(X_MAX_PIN) && X_MAX_PIN > -1 SERIAL_PROTOCOLPGM(MSG_X_MAX); SERIAL_PROTOCOLLN(((READ(X_MAX_PIN) ^ X_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif #if defined(Y_MIN_PIN) && Y_MIN_PIN > -1 SERIAL_PROTOCOLPGM(MSG_Y_MIN); SERIAL_PROTOCOLLN(((READ(Y_MIN_PIN) ^ Y_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif #if defined(Y_MAX_PIN) && Y_MAX_PIN > -1 SERIAL_PROTOCOLPGM(MSG_Y_MAX); SERIAL_PROTOCOLLN(((READ(Y_MAX_PIN) ^ Y_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif #if defined(Z_MIN_PIN) && Z_MIN_PIN > -1 SERIAL_PROTOCOLPGM(MSG_Z_MIN); SERIAL_PROTOCOLLN(((READ(Z_MIN_PIN) ^ Z_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif #if defined(Z_MAX_PIN) && Z_MAX_PIN > -1 SERIAL_PROTOCOLPGM(MSG_Z_MAX); SERIAL_PROTOCOLLN(((READ(Z_MAX_PIN) ^ Z_ENDSTOPS_INVERTING) ? MSG_ENDSTOP_HIT : MSG_ENDSTOP_OPEN)); #endif break; //TODO: update for all axis, use for loop case 201: // M201 for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) { max_acceleration_units_per_sq_second[i] = code_value(); } } // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) reset_acceleration_rates(); break; #if 0 // Not used for Sprinter/grbl gen6 case 202: // M202 for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value() * axis_steps_per_unit[i]; } break; #endif case 203: // M203 max feedrate mm/sec for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) max_feedrate[i] = code_value(); } break; case 204: // M204 acclereration S normal moves T filmanent only moves { if (code_seen('S')) acceleration = code_value(); if (code_seen('T')) retract_acceleration = code_value(); } break; case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk { if (code_seen('S')) minimumfeedrate = code_value(); if (code_seen('T')) mintravelfeedrate = code_value(); if (code_seen('B')) minsegmenttime = code_value(); if (code_seen('X')) max_xy_jerk = code_value(); if (code_seen('Z')) max_z_jerk = code_value(); if (code_seen('E')) max_e_jerk = code_value(); } break; case 206: // M206 additional homeing offset for (int8_t i = 0; i < 3; i++) { if (code_seen(axis_codes[i])) add_homeing[i] = code_value(); } break; #ifdef FWRETRACT case 207: //M207 - set retract length S[positive mm] F[feedrate mm/sec] Z[additional zlift/hop] { if (code_seen('S')) { retract_length = code_value(); } if (code_seen('F')) { retract_feedrate = code_value(); } if (code_seen('Z')) { retract_zlift = code_value(); } } break; case 208: // M208 - set retract recover length S[positive mm surplus to the M207 S*] F[feedrate mm/sec] { if (code_seen('S')) { retract_recover_length = code_value(); } if (code_seen('F')) { retract_recover_feedrate = code_value(); } } break; case 209: // M209 - S<1=true/0=false> enable automatic retract detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction. { if (code_seen('S')) { int t = code_value(); switch (t) { case 0: autoretract_enabled = false; retracted = false; break; case 1: autoretract_enabled = true; retracted = false; break; default: SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND); SERIAL_ECHO(cmdbuffer[bufindr]); SERIAL_ECHOLNPGM("\""); } } } break; #endif // FWRETRACT #if EXTRUDERS > 1 case 218: // M218 - set hotend offset (in mm), T<extruder_number> X<offset_on_X> Y<offset_on_Y> { if (setTargetedHotend(218)) { break; } if (code_seen('X')) { extruder_offset[X_AXIS][tmp_extruder] = code_value(); } if (code_seen('Y')) { extruder_offset[Y_AXIS][tmp_extruder] = code_value(); } #ifdef DUAL_X_CARRIAGE if (code_seen('Z')) { extruder_offset[Z_AXIS][tmp_extruder] = code_value(); } #endif SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_HOTEND_OFFSET); for (tmp_extruder = 0; tmp_extruder < EXTRUDERS; tmp_extruder++) { SERIAL_ECHO(" "); SERIAL_ECHO(extruder_offset[X_AXIS][tmp_extruder]); SERIAL_ECHO(","); SERIAL_ECHO(extruder_offset[Y_AXIS][tmp_extruder]); #ifdef DUAL_X_CARRIAGE SERIAL_ECHO(","); SERIAL_ECHO(extruder_offset[Z_AXIS][tmp_extruder]); #endif } SERIAL_ECHOLN(""); } break; #endif case 220: // M220 S<factor in percent>- set speed factor override percentage { if (code_seen('S')) { feedmultiply = code_value(); } } break; case 221: // M221 S<factor in percent>- set extrude factor override percentage { if (code_seen('S')) { extrudemultiply = code_value(); } } break; #if NUM_SERVOS > 0 case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds { int servo_index = -1; int servo_position = 0; if (code_seen('P')) servo_index = code_value(); if (code_seen('S')) { servo_position = code_value(); if ((servo_index >= 0) && (servo_index < NUM_SERVOS)) { servos[servo_index].write(servo_position); } else { SERIAL_ECHO_START; SERIAL_ECHO("Servo "); SERIAL_ECHO(servo_index); SERIAL_ECHOLN(" out of range"); } } else if (servo_index >= 0) { SERIAL_PROTOCOL(MSG_OK); SERIAL_PROTOCOL(" Servo "); SERIAL_PROTOCOL(servo_index); SERIAL_PROTOCOL(": "); SERIAL_PROTOCOL(servos[servo_index].read()); SERIAL_PROTOCOLLN(""); } } break; #endif // NUM_SERVOS > 0 #ifdef PIDTEMP case 301: // M301 { if (code_seen('P')) Kp = code_value(); if (code_seen('I')) Ki = scalePID_i(code_value()); if (code_seen('D')) Kd = scalePID_d(code_value()); #ifdef PID_ADD_EXTRUSION_RATE if (code_seen('C')) Kc = code_value(); #endif updatePID(); SERIAL_PROTOCOL(MSG_OK); SERIAL_PROTOCOL(" p:"); SERIAL_PROTOCOL(Kp); SERIAL_PROTOCOL(" i:"); SERIAL_PROTOCOL(unscalePID_i(Ki)); SERIAL_PROTOCOL(" d:"); SERIAL_PROTOCOL(unscalePID_d(Kd)); #ifdef PID_ADD_EXTRUSION_RATE SERIAL_PROTOCOL(" c:"); //Kc does not have scaling applied above, or in resetting defaults SERIAL_PROTOCOL(Kc); #endif SERIAL_PROTOCOLLN(""); Config_StoreSettings(); } break; #endif //PIDTEMP #ifdef PIDTEMPBED case 304: // M304 { if (code_seen('P')) bedKp = code_value(); if (code_seen('I')) bedKi = scalePID_i(code_value()); if (code_seen('D')) bedKd = scalePID_d(code_value()); updatePID(); SERIAL_PROTOCOL(MSG_OK); SERIAL_PROTOCOL(" p:"); SERIAL_PROTOCOL(bedKp); SERIAL_PROTOCOL(" i:"); SERIAL_PROTOCOL(unscalePID_i(bedKi)); SERIAL_PROTOCOL(" d:"); SERIAL_PROTOCOL(unscalePID_d(bedKd)); SERIAL_PROTOCOLLN(""); } break; #endif //PIDTEMP case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/ { #if defined(PHOTOGRAPH_PIN) && PHOTOGRAPH_PIN > -1 const uint8_t NUM_PULSES = 16; const float PULSE_LENGTH = 0.01524; for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } delay(7.33); for (int i = 0; i < NUM_PULSES; i++) { WRITE(PHOTOGRAPH_PIN, HIGH); _delay_ms(PULSE_LENGTH); WRITE(PHOTOGRAPH_PIN, LOW); _delay_ms(PULSE_LENGTH); } #endif } break; #ifdef DOGLCD case 250: // M250 Set LCD contrast value: C<value> (value 0..63) { if (code_seen('C')) { lcd_setcontrast(((int)code_value()) & 63); } SERIAL_PROTOCOLPGM("lcd contrast value: "); SERIAL_PROTOCOL(lcd_contrast); SERIAL_PROTOCOLLN(""); } break; #endif #ifdef PREVENT_DANGEROUS_EXTRUDE case 302: // allow cold extrudes, or set the minimum extrude temperature { float temp = .0; if (code_seen('S')) temp = code_value(); set_extrude_min_temp(temp); } break; #endif case 303: // M303 PID autotune { float temp = 150.0; int e = 0; int c = 5; if (code_seen('E')) e = code_value(); if (e < 0) temp = 70; if (code_seen('S')) temp = code_value(); if (code_seen('C')) c = code_value(); PID_autotune(temp, e, c); } break; case 400: // M400 finish all moves { st_synchronize(); } break; case 500: // M500 Store settings in EEPROM { Config_StoreSettings(); } break; case 501: // M501 Read settings from EEPROM { Config_RetrieveSettings(); } break; case 502: // M502 Revert to default settings { command_M502(); } break; case 503: // M503 print settings currently in memory { Config_PrintSettings(); } break; #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED case 540: { if (code_seen('S')) abort_on_endstop_hit = code_value() > 0; } break; #endif #ifdef FILAMENTCHANGEENABLE case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal] { float target[4]; float lastpos[4]; target[X_AXIS] = current_position[X_AXIS]; target[Y_AXIS] = current_position[Y_AXIS]; target[Z_AXIS] = current_position[Z_AXIS]; target[E_AXIS] = current_position[E_AXIS]; lastpos[X_AXIS] = current_position[X_AXIS]; lastpos[Y_AXIS] = current_position[Y_AXIS]; lastpos[Z_AXIS] = current_position[Z_AXIS]; lastpos[E_AXIS] = current_position[E_AXIS]; //retract by E if (code_seen('E')) { target[E_AXIS] += code_value(); } else { #ifdef FILAMENTCHANGE_FIRSTRETRACT target[E_AXIS] += FILAMENTCHANGE_FIRSTRETRACT; #endif } plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //lift Z if (code_seen('Z')) { target[Z_AXIS] += code_value(); } else { #ifdef FILAMENTCHANGE_ZADD target[Z_AXIS] += FILAMENTCHANGE_ZADD; #endif } plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //move xy if (code_seen('X')) { target[X_AXIS] += code_value(); } else { #ifdef FILAMENTCHANGE_XPOS target[X_AXIS] = FILAMENTCHANGE_XPOS; #endif } if (code_seen('Y')) { target[Y_AXIS] = code_value(); } else { #ifdef FILAMENTCHANGE_YPOS target[Y_AXIS] = FILAMENTCHANGE_YPOS; #endif } plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); if (code_seen('L')) { target[E_AXIS] += code_value(); } else { #ifdef FILAMENTCHANGE_FINALRETRACT target[E_AXIS] += FILAMENTCHANGE_FINALRETRACT; #endif } plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //finish moves st_synchronize(); //disable extruder steppers so filament can be removed disable_e0(); disable_e1(); disable_e2(); delay(100); //LCD_ALERTMESSAGEPGM(MSG_FILAMENTCHANGE); uint8_t cnt = 0; while (!lcd_clicked()) { cnt++; manage_heater(); if (tl_HEATER_FAIL) { card.closefile; card.sdprinting = 0; } manage_inactivity(); tenlog_status_screen(); } //return to normal if (code_seen('L')) { target[E_AXIS] += -code_value(); } else { #ifdef FILAMENTCHANGE_FINALRETRACT target[E_AXIS] += (-1) * FILAMENTCHANGE_FINALRETRACT; #endif } current_position[E_AXIS] = target[E_AXIS]; //the long retract of L is compensated by manual filament feeding plan_set_e_position(current_position[E_AXIS]); plan_buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //should do nothing plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], target[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //move xy back plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], target[E_AXIS], feedrate / 60, active_extruder); //move z back plan_buffer_line(lastpos[X_AXIS], lastpos[Y_AXIS], lastpos[Z_AXIS], lastpos[E_AXIS], feedrate / 60, active_extruder); //final untretract } break; //M600 #endif //FILAMENTCHANGEENABLE #ifdef DUAL_X_CARRIAGE case 605: // Set dual x-carriage movement mode: // M605 S0: Full control mode. The slicer has full control over x-carriage movement // M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement // M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn // millimeters x-offset and an optional differential hotend temperature of // mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate // the first with a spacing of 100mm in the x direction and 2 degrees hotter. // // Note: the X axis should be homed after changing dual x-carriage mode. command_M605(-1); break; #endif //DUAL_X_CARRIAGE case 907: // M907 Set digital trimpot motor current using axis codes. { #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1 for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) digipot_current(i, code_value()); if (code_seen('B')) digipot_current(4, code_value()); if (code_seen('S')) for (int i = 0; i <= 4; i++) digipot_current(i, code_value()); #endif } break; case 908: // M908 Control digital trimpot directly. { #if defined(DIGIPOTSS_PIN) && DIGIPOTSS_PIN > -1 uint8_t channel, current; if (code_seen('P')) channel = code_value(); if (code_seen('S')) current = code_value(); digitalPotWrite(channel, current); #endif } break; case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers. { #if defined(X_MS1_PIN) && X_MS1_PIN > -1 if (code_seen('S')) for (int i = 0; i <= 4; i++) microstep_mode(i, code_value()); for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_mode(i, (uint8_t)code_value()); if (code_seen('B')) microstep_mode(4, code_value()); microstep_readings(); #endif } break; case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low. { #if defined(X_MS1_PIN) && X_MS1_PIN > -1 if (code_seen('S')) switch ((int)code_value()) { case 1: for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, code_value(), -1); if (code_seen('B')) microstep_ms(4, code_value(), -1); break; case 2: for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) microstep_ms(i, -1, code_value()); if (code_seen('B')) microstep_ms(4, -1, code_value()); break; } microstep_readings(); #endif } break; case 1001: //M1001 LanguageID if (code_seen('S')) { languageID = code_value(); if (languageID > 20) languageID = 20; if (languageID < 0) languageID = 0; Config_StoreSettings(); } break; case 2002: //M2002 Calibrate { TLSTJC_printconstln(F("touch_j")); } break; #ifdef POWER_LOSS_RECOVERY case 1003: //M1003 Power fail resume. //by zyf command_M1003(); break; case 1004: //M1004 cancel power fail recovery { #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_Write_PLR(); EEPROM_PRE_Write_PLR(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) card.Write_PLR(); card.PRE_Write_PLR(); #endif } break; #endif //POWER_LOSS_RECOVERY case 1011: //M1011 X2 Max mm { float fRate = 1.0; if (code_seen('R')) { fRate = (float)code_value(); } if (code_seen('S')) { tl_X2_MAX_POS = (float)code_value() / fRate; Config_StoreSettings(); offset_changed = 1; bInited = false; } } break; case 1012: //M1012 Y2 mm { float fRate = 1.0; if (code_seen('R')) { fRate = (float)code_value(); } if (code_seen('S')) { tl_Y2_OFFSET = (float)code_value() / fRate; Config_StoreSettings(); offset_changed = 1; bInited = false; } } break; case 1013: //M1013 Z2 mm { float fRate = 1.0; if (code_seen('R')) { fRate = (float)code_value(); } if (code_seen('S')) { tl_Z2_OFFSET = (float)code_value() / fRate; Config_StoreSettings(); offset_changed = 1; bInited = false; } } break; #ifdef FAN2_CONTROL case 1014: //M1014 Fan2 Value { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet > 100) iGet = 100; if (iGet < 0) iGet = 0; tl_FAN2_VALUE = iGet; Config_StoreSettings(); } } break; case 1015: //M1015 Fan2 Temp { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet > 200) iGet = 200; if (iGet < 0) iGet = 0; tl_FAN2_START_TEMP = iGet; Config_StoreSettings(); } } break; #endif #ifdef HAS_PLR_MODULE case 1016: //M1016 Auto Off { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet != 1) iGet = 0; tl_AUTO_OFF = iGet; Config_StoreSettings(); } } break; #endif case 1017: //M1017 sleep time { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet > 60) iGet = 60; if (iGet < 0) iGet = 0; tl_SLEEP_TIME = iGet; Config_StoreSettings(); } } break; #ifdef CONFIG_TL case 1019: //M1019 set nuzzle or bed heater max temp { if (code_seen('B')) { int iTemp = code_value(); tl_BED_MAXTEMP = iTemp; Config_StoreSettings(); } if (code_seen('E')) { int iTemp = code_value(); tl_HEATER_0_MAXTEMP = iTemp; tl_HEATER_1_MAXTEMP = iTemp; Config_StoreSettings(); } } break; #endif case 1021: //M1021 { command_M1021(-1); } break; case 1022: //M1022 { if (code_seen('S')) { int iSValue = code_value(); int iTValue = -1; if (code_seen('T')) { iTValue = code_value(); } if (iSValue == 0 || iSValue == 1) load_filament(iSValue, iTValue); } } break; case 1034: //M1034 { iBeepCount = 0; } break; case 1023: //M1023 filament senser { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet != 1) iGet = 0; tl_Filament_Detect = iGet; Config_StoreSettings(); } } break; case 1024: //M1024 ECO Mode { if (code_seen('S')) { int iGet = (int)code_value(); if (iGet != 1) iGet = 0; tl_ECO_MODE = iGet; Config_StoreSettings(); } } break; case 1032: //M1032 { sdcard_resume(); } break; case 1033: //M1033 { sdcard_stop(); } break; case 1031: //M1031 { sdcard_pause(); } break; case 1035: //M1035 Nozzle offset test print { Nozzle_offset_test_print(); } break; #ifdef PRINT_FROM_Z_HEIGHT case 1040: //M1040 { if (code_seen('S')) { float fValue = code_value(); if (fValue == 0) { PrintFromZHeightFound = true; } else { print_from_z_target = fValue / 10.0; PrintFromZHeightFound = false; //if(dual_x_carriage_mode == 2) // dual_x_carriage_mode = 1; } } } break; #endif //PRINT_FROM_Z_HEIGHT case 1050: { pinMode(16, OUTPUT); pinMode(17, OUTPUT); if (code_seen('S')) { int iOut = code_value(); if (iOut == 0) { digitalWrite(16, HIGH); digitalWrite(17, LOW); } else if (iOut == 1) { digitalWrite(17, HIGH); digitalWrite(16, LOW); } } } break; #ifdef ENGRAVE case 2000: //M2000 { if (code_seen('S')) { int iS = code_value(); if (iS == 1) digitalWrite(ENGRAVE_PIN, ENGRAVE_ON); else if (iS == 0) digitalWrite(ENGRAVE_PIN, ENGRAVE_OFF); } } break; #endif case 999: // M999: Restart after being stopped Stopped = false; //lcd_reset_alert_level(); gcode_LastN = Stopped_gcode_LastN; FlushSerialRequestResend(); resetFunc(); break; } } //code_seen("M") line 1328 else if (code_seen('T')) //Switch T0T1 command_T(); else { int iCmd = cmdbuffer[bufindr][0]; if(iCmd > 0) { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND); SERIAL_ECHO(iCmd); SERIAL_ECHOLNPGM("\""); } else return; } ClearToSend(); } void FlushSerialRequestResend() { //char cmdbuffer[bufindr][100]="Resend:"; MYSERIAL.flush(); SERIAL_PROTOCOLPGM(MSG_RESEND); SERIAL_PROTOCOLLN(gcode_LastN + 1); ClearToSend(); } void ClearToSend() { previous_millis_cmd = millis(); #ifdef SDSUPPORT if (fromsd[bufindr]) return; #endif //SDSUPPORT SERIAL_PROTOCOLLNPGM(MSG_OK); } #ifdef POWER_LOSS_RECOVERY void Save_Power_Loss_Status() { uint32_t lFPos = card.sdpos; int iTPos = degTargetHotend(0) + 0.5; int iTPos1 = degTargetHotend(1) + 0.5; int iFanPos = fanSpeed; int iT01 = active_extruder == 0 ? 0 : 1; int iBPos = degTargetBed() + 0.5; float fZPos = current_position[Z_AXIS]; float fEPos = current_position[E_AXIS]; float fXPos = current_position[X_AXIS]; float fYPos = current_position[Y_AXIS]; float f_feedrate = feedrate; #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_Write_PLR(lFPos, iTPos, iTPos1, iT01, fZPos, fEPos); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) card.Write_PLR(lFPos, iTPos, iTPos1, iT01, fZPos, fEPos); #endif } #endif #ifdef POWER_LOSS_TRIGGER_BY_Z_LEVEL float fLastZ = 0.0; #endif #ifdef POWER_LOSS_TRIGGER_BY_E_COUNT long lECount = POWER_LOSS_E_COUNT; #endif void get_coordinates(float XValue = -99999.0, float YValue = -99999.0, float ZValue = -99999.0, float EValue = -99999.0, int iMode = 0) //By zyf 20190716 { float fRate = 1.0; if (code_seen('R')) { fRate = (float)code_value(); } if (code_seen('M')) { iMode = (int)code_value(); } bool seen[4] = {false, false, false, false}; for (int8_t i = 0; i < NUM_AXIS; i++) { if (code_seen(axis_codes[i])) { if (iMode == 1) { destination[i] = (float)code_value() / fRate + current_position[i]; } else { destination[i] = (float)code_value() / fRate + (axis_relative_modes[i] || relative_mode) * current_position[i]; } seen[i] = true; } else { destination[i] = current_position[i]; //Are these else lines really needed? } } if (!seen[0] && !seen[1] && !seen[2] && !seen[3]) { if (XValue > -99999.0) { if (iMode == 1) destination[X_AXIS] = XValue + current_position[X_AXIS]; else destination[X_AXIS] = XValue / fRate + (axis_relative_modes[X_AXIS] || relative_mode) * current_position[X_AXIS]; } else { destination[X_AXIS] = current_position[X_AXIS]; } if (YValue > -99999.0) { if (iMode == 1) destination[Y_AXIS] = YValue + current_position[Y_AXIS]; else destination[Y_AXIS] = YValue / fRate + (axis_relative_modes[Y_AXIS] || relative_mode) * current_position[Y_AXIS]; } else { destination[Y_AXIS] = current_position[Y_AXIS]; } if (ZValue > -99999.0) { if (iMode == 1) destination[Z_AXIS] = ZValue + current_position[Z_AXIS]; else destination[Z_AXIS] = ZValue / fRate + (axis_relative_modes[Z_AXIS] || relative_mode) * current_position[Z_AXIS]; } else { destination[Z_AXIS] = current_position[Z_AXIS]; } if (EValue > -99999.0) { if (iMode == 1) destination[E_AXIS] = EValue + current_position[E_AXIS]; else destination[E_AXIS] = EValue / fRate + (axis_relative_modes[E_AXIS] || relative_mode) * current_position[E_AXIS]; } else { destination[E_AXIS] = current_position[E_AXIS]; } } #ifdef POWER_LOSS_TRIGGER_BY_Z_LEVEL if (destination[Z_AXIS] > fLastZ && card.sdprinting == 1 && card.sdpos > 2048) { fLastZ = destination[Z_AXIS]; Save_Power_Loss_Status(); } #endif #ifdef POWER_LOSS_TRIGGER_BY_E_COUNT if (destination[E_AXIS] != current_position[E_AXIS] && card.sdprinting == 1) lECount--; if (lECount <= 0 && card.sdprinting == 1 && card.sdpos > 2048) { lEcount = POWER_LOSS_E_COUNT; Save_Power_Loss_Status(); } #endif if (code_seen('F')) { next_feedrate = code_value(); if (next_feedrate > 0.0) feedrate = next_feedrate; } #ifdef FWRETRACT if (autoretract_enabled) if (!(seen[X_AXIS] || seen[Y_AXIS] || seen[Z_AXIS]) && seen[E_AXIS]) { float echange = destination[E_AXIS] - current_position[E_AXIS]; if (echange < -MIN_RETRACT) //retract { if (!retracted) { destination[Z_AXIS] += retract_zlift; //not sure why chaninging current_position negatively does not work. //if slicer retracted by echange=-1mm and you want to retract 3mm, corrrectede=-2mm additionally float correctede = -echange - retract_length; //to generate the additional steps, not the destination is changed, but inversely the current position current_position[E_AXIS] += -correctede; feedrate = retract_feedrate; retracted = true; } } else if (echange > MIN_RETRACT) //retract_recover { if (retracted) { //current_position[Z_AXIS]+=-retract_zlift; //if slicer retracted_recovered by echange=+1mm and you want to retract_recover 3mm, corrrectede=2mm additionally float correctede = -echange + 1 * retract_length + retract_recover_length; //total unretract=retract_length+retract_recover_length[surplus] current_position[E_AXIS] += correctede; //to generate the additional steps, not the destination is changed, but inversely the current position feedrate = retract_recover_feedrate; retracted = false; } } } #endif //FWRETRACT } void get_arc_coordinates() { #ifdef SF_ARC_FIX bool relative_mode_backup = relative_mode; relative_mode = true; #endif get_coordinates(); #ifdef SF_ARC_FIX relative_mode = relative_mode_backup; #endif if (code_seen('I')) { offset[0] = code_value(); } else { offset[0] = 0.0; } if (code_seen('J')) { offset[1] = code_value(); } else { offset[1] = 0.0; } } void clamp_to_software_endstops(float target[3]) { if (min_software_endstops) { if (target[X_AXIS] < min_pos[X_AXIS]) target[X_AXIS] = min_pos[X_AXIS]; if (target[Y_AXIS] < min_pos[Y_AXIS]) target[Y_AXIS] = min_pos[Y_AXIS]; if (target[Z_AXIS] < min_pos[Z_AXIS]) target[Z_AXIS] = min_pos[Z_AXIS]; } if (max_software_endstops) { if (target[X_AXIS] > max_pos[X_AXIS]) target[X_AXIS] = max_pos[X_AXIS]; if (target[Y_AXIS] > max_pos[Y_AXIS]) target[Y_AXIS] = max_pos[Y_AXIS]; if (target[Z_AXIS] > max_pos[Z_AXIS]) target[Z_AXIS] = max_pos[Z_AXIS]; } if (dual_x_carriage_mode == DXC_MIRROR_MODE) //protect headers from hitting each other when mirror mode print if (target[X_AXIS] > (tl_X2_MAX_POS - X_NOZZLE_WIDTH * 2) / 2) target[X_AXIS] = (tl_X2_MAX_POS - X_NOZZLE_WIDTH * 2) / 2; else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) //protect headers from hitting each other when DUPLICATION mode print if (target[X_AXIS] > tl_X2_MAX_POS / 2) target[X_AXIS] = tl_X2_MAX_POS / 2; } void prepare_move() { clamp_to_software_endstops(destination); previous_millis_cmd = millis(); #ifdef DUAL_X_CARRIAGE if (active_extruder_parked) { float fZRaise = 15; if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) { // move duplicate extruder into correct duplication position. //By Zyf Add 15mm Z plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS] - fZRaise, current_position[E_AXIS]); plan_buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + fZRaise, current_position[E_AXIS]); st_synchronize(); extruder_carriage_mode = 2; active_extruder_parked = false; } else if (dual_x_carriage_mode == DXC_MIRROR_MODE) { // move duplicate extruder into correct duplication position. //By Zyf Add 15mm Z plan_set_position(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS] - fZRaise, current_position[E_AXIS]); plan_buffer_line(tl_X2_MAX_POS, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + fZRaise, current_position[E_AXIS]); st_synchronize(); extruder_carriage_mode = 3; active_extruder_parked = false; } else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) // handle unparking of head { if (current_position[E_AXIS] == destination[E_AXIS]) { // this is a travel move - skit it but keep track of current position (so that it can later // be used as start of first non-travel move) if (delayed_move_time != 0xFFFFFFFFUL) { //memcpy(current_position, destination, sizeof(current_position)); current_position[X_AXIS] = destination[X_AXIS]; //By zyf current_position[Y_AXIS] = destination[Y_AXIS]; //By zyf current_position[Z_AXIS] = destination[Z_AXIS]; //By zyf current_position[E_AXIS] = destination[E_AXIS]; //By zyf if (destination[Z_AXIS] > raised_parked_position[Z_AXIS]) raised_parked_position[Z_AXIS] = destination[Z_AXIS]; delayed_move_time = millis(); //return; } } delayed_move_time = 0; plan_buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], min(max_feedrate[X_AXIS], max_feedrate[Y_AXIS]), active_extruder); plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[Z_AXIS], active_extruder); st_synchronize(); extruder_carriage_mode = 1; active_extruder_parked = false; } } #endif //DUAL_X_CARRIAGE // Do not use feedmultiply for E or Z only moves if ((current_position[X_AXIS] == destination[X_AXIS]) && (current_position[Y_AXIS] == destination[Y_AXIS])) { plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate / 60, active_extruder); } else { plan_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], feedrate * feedmultiply / 60 / 100.0, active_extruder); } for (int8_t i = 0; i < NUM_AXIS; i++) { current_position[i] = destination[i]; } } //prepare_move void prepare_arc_move(char isclockwise) { float r = hypot(offset[X_AXIS], offset[Y_AXIS]); // Compute arc radius for mc_arc // Trace the arc mc_arc(current_position, destination, offset, X_AXIS, Y_AXIS, Z_AXIS, feedrate * feedmultiply / 60 / 100.0, r, isclockwise, active_extruder); // As far as the parser is concerned, the position is now == target. In reality the // motion control system might still be processing the action and the real tool position // in any intermediate location. for (int8_t i = 0; i < NUM_AXIS; i++) { current_position[i] = destination[i]; } previous_millis_cmd = millis(); } #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1 #if defined(FAN_PIN) #if CONTROLLERFAN_PIN == FAN_PIN #error "You cannot set CONTROLLERFAN_PIN equal to FAN_PIN" #endif #endif unsigned long lastMotor = 0; //Save the time for when a motor was turned on last unsigned long lastMotorCheck = 0; void controllerFan() { if ((millis() - lastMotorCheck) >= 2500) //Not a time critical function, so we only check every 2500ms { lastMotorCheck = millis(); if (!READ(X_ENABLE_PIN) || !READ(Y_ENABLE_PIN) || !READ(Z_ENABLE_PIN) #if EXTRUDERS > 2 || !READ(E2_ENABLE_PIN) #endif #if EXTRUDER > 1 #if defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1 || !READ(X2_ENABLE_PIN) #endif || !READ(E1_ENABLE_PIN) #endif || !READ(E0_ENABLE_PIN)) //If any of the drivers are enabled... { lastMotor = millis(); //... set time to NOW so the fan will turn on } if ((millis() - lastMotor) >= (CONTROLLERFAN_SECS * 1000UL) || lastMotor == 0) //If the last time any driver was enabled, is longer since than CONTROLLERSEC... { digitalWrite(CONTROLLERFAN_PIN, 0); analogWrite(CONTROLLERFAN_PIN, 0); } else { // allows digital or PWM fan output to be used (see M42 handling) digitalWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED); analogWrite(CONTROLLERFAN_PIN, CONTROLLERFAN_SPEED); } } } #endif //By Zyf #ifdef POWER_LOSS_TRIGGER_BY_PIN bool gbPLRStatusSaved = false; bool gbPowerLoss = false; #ifdef HAS_PLR_MODULE #define DETECT_PLR_TIME 10000 bool Check_Power_Loss() { int iPLRead = digitalRead(POWER_LOSS_DETECT_PIN); if (iPLDetected > 0 && !b_PLR_MODULE_Detected && iPLRead == 0) return true; else if (iPLDetected > 0 && b_PLR_MODULE_Detected && iPLRead == 1) return true; bool bRet = false; if (millis() > DETECT_PLR_TIME && !b_PLR_MODULE_Detected && iPLRead == 0) { for (int i = 0; i < 10; i++) { iPLRead = digitalRead(POWER_LOSS_DETECT_PIN); if (iPLRead == 1) return false; } } if (iPLRead == 0) { if (millis() < DETECT_PLR_TIME && !b_PLR_MODULE_Detected) { b_PLR_MODULE_Detected = true; //USE PLR Module } else if (card.sdprinting == 1 && !b_PLR_MODULE_Detected) { //USE LM393 iPLDetected++; if (iPLDetected == 1) { bRet = true; Power_Off_Handler(true, false); if(tl_TouchScreenType == 0) DWN_Page(DWN_P_SHUTDOWN); } return true; } else if (card.sdprinting == 0 && !b_PLR_MODULE_Detected) { if(tl_TouchScreenType == 0) DWN_Page(DWN_P_SHUTDOWN); } } else { //iPLRead == 1 if (b_PLR_MODULE_Detected && iPLDetected == 0) //Has 220V detect module. { iPLDetected++; bRet = true; Power_Off_Handler(true, true); } else if (card.sdprinting == 1 && !b_PLR_MODULE_Detected && iPLDetected > 0) { if(tl_TouchScreenType == 1) { TLSTJC_printconstln(F("sleep=0")); TLSTJC_printconstln(F("page printing")); } else { DWN_Page(DWN_P_PRINTING); DWN_LED(DWN_LED_ON); } gbPLRStatusSaved = false; sei(); iPLDetected = 0; } else if (card.sdprinting == 0 && !b_PLR_MODULE_Detected && iPLDetected > 0) { if(tl_TouchScreenType == 1) { TLSTJC_printconstln(F("sleep=0")); TLSTJC_printconstln(F("page main")); } else { DWN_Page(DWN_P_MAIN); DWN_LED(DWN_LED_ON); } } } return bRet; } #else #endif void Power_Off_Handler(bool MoveX, bool M81) { if (card.sdprinting == 1 && !gbPLRStatusSaved) { cli(); // Stop interrupts digitalWrite(HEATER_BED_PIN, LOW); #if HEATER_0_PIN > 0 digitalWrite(HEATER_0_PIN, LOW); #endif #if HEATER_1_PIN > 0 digitalWrite(HEATER_1_PIN, LOW); #endif digitalWrite(FAN2_PIN, LOW); digitalWrite(FAN_PIN, LOW); //digitalWrite(PS_ON_PIN, PS_ON_ASLEEP); disable_x(); disable_y(); disable_z(); disable_e0(); disable_e1(); if (!gbPLRStatusSaved) { Save_Power_Loss_Status(); gbPLRStatusSaved = true; } uint32_t lFPos = card.sdpos; if (MoveX && lFPos > 2048) { enable_x(); for (int i = 0; i < axis_steps_per_unit[X_AXIS] * 20; i++) { bool bWrite = false; if (i % 2 == 1) { bWrite = false; } else { bWrite = true; } #ifdef DUAL_X_CARRIAGE if (extruder_carriage_mode == 2 || extruder_carriage_mode == 3) { WRITE(X_STEP_PIN, bWrite); WRITE(X2_STEP_PIN, bWrite); } else { #ifdef MIX_COLOR_TEST WRITE(X_STEP_PIN, bWrite); #else if (active_extruder == 1) WRITE(X2_STEP_PIN, bWrite); else if (active_extruder == 0) WRITE(X_STEP_PIN, bWrite); #endif } #else WRITE(X_STEP_PIN, bWrite); #endif delayMicroseconds(120); } } } if (M81 && !gbPowerLoss) { cli(); // Stop interrupts command_M81(false); //false to show shutdown screen; gbPowerLoss = true; } } #endif //POWER_LOSS_TRIGGER_BY_PIN void manage_inactivity() { if ((millis() - previous_millis_cmd) > max_inactive_time) if (max_inactive_time) kill(); if (stepper_inactive_time) { if ((millis() - previous_millis_cmd) > stepper_inactive_time) { if (blocks_queued() == false) { if (!card.isFileOpen()) { //By zyf not disable steppers when pause. disable_x(); disable_y(); disable_z(); //By zyf always lock Z; - Cancel at 20200610 disable_e0(); disable_e1(); disable_e2(); } } } } #if defined(CONTROLLERFAN_PIN) && CONTROLLERFAN_PIN > -1 controllerFan(); //Check if fan should be turned on to cool stepper drivers down #endif #ifdef EXTRUDER_RUNOUT_PREVENT if ((millis() - previous_millis_cmd) > EXTRUDER_RUNOUT_SECONDS * 1000) if (degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) { bool oldstatus = READ(E0_ENABLE_PIN); enable_e0(); float oldepos = current_position[E_AXIS]; float oldedes = destination[E_AXIS]; plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE * EXTRUDER_RUNOUT_ESTEPS / axis_steps_per_unit[E_AXIS], EXTRUDER_RUNOUT_SPEED / 60. * EXTRUDER_RUNOUT_ESTEPS / axis_steps_per_unit[E_AXIS], active_extruder); current_position[E_AXIS] = oldepos; destination[E_AXIS] = oldedes; plan_set_e_position(oldepos); previous_millis_cmd = millis(); st_synchronize(); WRITE(E0_ENABLE_PIN, oldstatus); } #endif #if defined(DUAL_X_CARRIAGE) // handle delayed move timeout if (delayed_move_time != 0 && (millis() - delayed_move_time) > 1000 && Stopped == false) { // travel moves have been received so enact them delayed_move_time = 0xFFFFFFFFUL; // force moves to be done memcpy(destination, current_position, sizeof(destination)); prepare_move(); } #endif check_axes_activity(); } void kill() { cli(); // Stop interrupts disable_heater(); disable_x(); disable_y(); disable_z(); disable_e0(); disable_e1(); disable_e2(); #if defined(PS_ON_PIN) && PS_ON_PIN > -1 //pinMode(PS_ON_PIN,INPUT); #endif SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_KILLED); //LCD_ALERTMESSAGEPGM(MSG_KILLED); suicide(); while (1) { /* Intentionally left empty */ } // Wait for reset } void Stop() { disable_heater(); if (Stopped == false) { Stopped = true; Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_ERR_STOPPED); } } bool IsStopped() { return Stopped; }; #ifdef FAST_PWM_FAN void setPwmFrequency(uint8_t pin, int val) { val &= 0x07; switch (digitalPinToTimer(pin)) { #if defined(TCCR0A) case TIMER0A: case TIMER0B: // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02)); // TCCR0B |= val; break; #endif #if defined(TCCR1A) case TIMER1A: case TIMER1B: // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); // TCCR1B |= val; break; #endif #if defined(TCCR2) case TIMER2: case TIMER2: TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12)); TCCR2 |= val; break; #endif #if defined(TCCR2A) case TIMER2A: case TIMER2B: TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22)); TCCR2B |= val; break; #endif #if defined(TCCR3A) case TIMER3A: case TIMER3B: case TIMER3C: TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32)); TCCR3B |= val; break; #endif #if defined(TCCR4A) case TIMER4A: case TIMER4B: case TIMER4C: TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42)); TCCR4B |= val; break; #endif #if defined(TCCR5A) case TIMER5A: case TIMER5B: case TIMER5C: TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52)); TCCR5B |= val; break; #endif } } #endif //FAST_PWM_FAN bool setTargetedHotend(int code) { tmp_extruder = active_extruder; if (code_seen('T')) { tmp_extruder = code_value(); if (tmp_extruder >= EXTRUDERS) { SERIAL_ECHO_START; switch (code) { case 104: SERIAL_ECHO(MSG_M104_INVALID_EXTRUDER); break; case 105: SERIAL_ECHO(MSG_M105_INVALID_EXTRUDER); break; case 109: SERIAL_ECHO(MSG_M109_INVALID_EXTRUDER); break; case 218: SERIAL_ECHO(MSG_M218_INVALID_EXTRUDER); break; } SERIAL_ECHOLN(tmp_extruder); return true; } } return false; } float feedrate_pause = 0; float ePos_pause = 0.0; void raise_Z_E(int Z, int E) { float x = current_position[X_AXIS]; float y = current_position[Y_AXIS]; float z = current_position[Z_AXIS] + Z; float e = current_position[E_AXIS] + E; feedrate = 6000; for (int i = 0; i < 10; i++) { command_G4(0.05); } if(E != 0) command_G1(-99999.0, -99999.0, z, e); else command_G1(-99999.0, -99999.0, z); /* plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], max_feedrate[X_AXIS], 1); plan_set_position(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] - Z, current_position[E_AXIS] + E); st_synchronize(); */ } #ifdef SDSUPPORT void sdcard_pause(int OValue) { #ifdef PRINT_FROM_Z_HEIGHT if (!PrintFromZHeightFound) return; #endif card.pauseSDPrint(); if(tl_TouchScreenType == 1) { TLSTJC_printconstln(F("reload.vaFromPageID.val=6")); String strMessage = String(active_extruder + 1); const char *str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.sT1T2.txt=\"")); TLSTJC_print(str0); TLSTJC_printconstln(F("\"")); _delay_ms(50); strMessage = String(target_temperature[0]); str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.vaTargetTemp0.val=")); TLSTJC_println(str0); _delay_ms(50); strMessage = String(target_temperature[1]); str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.vaTargetTemp1.val=")); TLSTJC_println(str0); _delay_ms(50); strMessage = String(int(degTargetBed() + 0.5)); str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.vaTargetBed.val=")); TLSTJC_println(str0); _delay_ms(50); strMessage = String(dual_x_carriage_mode); str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.vaMode.val=")); TLSTJC_println(str0); _delay_ms(50); if (duplicate_extruder_x_offset != DEFAULT_DUPLICATION_X_OFFSET) { strMessage = "" + String(duplicate_extruder_x_offset) + ""; str0 = strMessage.c_str(); TLSTJC_printconst(F("reload.vaMode2Offset.val=")); TLSTJC_println(str0); } else TLSTJC_printconstln(F("reload.vaMode2Offset.val=-1")); _delay_ms(50); } bool isFF = false; if (code_seen('O') || OValue == 1) { isFF = true; } if (isFF) { setTargetHotend(0, 0); //By Zyf Cool down nozzle to protect from filament Blockage setTargetHotend(0, 1); //By Zyf } ePos_pause = current_position[E_AXIS]; feedrate_pause = feedrate; #ifdef PAUSE_RAISE_Z //By Zyf raise_Z_E(15, 0); #endif } void sdcard_resume() { #ifdef PRINT_FROM_Z_HEIGHT if (!PrintFromZHeightFound) return; #endif card.sdprinting = 2; if (code_seen('T')) { int iT0 = code_value(); command_T(iT0); int iT1 = (iT0 == 0 ? 1 : 0); int iH = 0; int iI = 0; if (code_seen('H')) { iH = code_value(); } if (code_seen('I')) { iI = code_value(); } if (iT0 == 0) { //T0=0 T1=1 if (iI > 0) { command_M104(iT1, iI); } if (iH > 0) { command_M109(iH); } } else { //T0=1 T1=0 if (iH > 0) { command_M104(iT1, iH); } if (iI > 0) { command_M109(iI); } } } #ifdef PAUSE_RAISE_Z //By Zyf raise_Z_E(-15, 0); #endif if (feedrate_pause > 1000) feedrate = feedrate_pause; else feedrate = 4000; command_G92(-99999.0, -99999.0, -99999.0, ePos_pause); #ifdef FILAMENT_FAIL_DETECT iFilaFail = 0; #endif card.sdprinting = 0; card.startFileprint(); } void sdcard_stop() { for (int i = 0; i < 10; i++) command_G4(0.1); card.closefile(); setTargetHotend(0, 0); //By Zyf setTargetHotend(0, 1); //By Zyf setTargetBed(0); //By Zyf if(tl_TouchScreenType == 1) enquecommand_P((PSTR("G28 XY"))); // axis home quickStop(); card.sdprinting = 0; fanSpeed = 0; finishAndDisableSteppers(false); autotempShutdown(); WriteLastZYM(0); } void WriteLastZYM(long lTime) { if(tl_TouchScreenType == 0) { float fZ = current_position[Z_AXIS]; float fY = current_position[Y_AXIS]; //float fY = 0.0; if (fZ == 0.0) fZ = -1.0; EEPROM_Write_Last_Z(fZ, fY, dual_x_carriage_mode, lTime); resetFunc(); } } #endif //SDSUPPORT void load_filament(int LoadUnload, int TValue) { //bool bChanged = false; int iTempE = active_extruder; //float fX = current_position[X_AXIS]; if (TValue != iTempE && TValue != -1) { command_T(TValue); //bChanged = true; } if (LoadUnload == 0) { current_position[E_AXIS] += 90; plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 4, active_extruder); //20 current_position[E_AXIS] += 20; plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2, active_extruder); //20 } else if (LoadUnload == 1) { current_position[E_AXIS] += 30; plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 2, active_extruder); //20 current_position[E_AXIS] -= 120; plan_buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], 30, active_extruder); //20 } } /* Configuration settings */ int plaPreheatHotendTemp; int plaPreheatHPBTemp; int plaPreheatFanSpeed; int absPreheatHotendTemp; int absPreheatHPBTemp; int absPreheatFanSpeed; /* !Configuration settings */ void preheat_pla() { setTargetHotend0(plaPreheatHotendTemp); setTargetHotend1(plaPreheatHotendTemp); setTargetHotend2(plaPreheatHotendTemp); setTargetBed(plaPreheatHPBTemp); fanSpeed = plaPreheatFanSpeed; //lcd_return_to_status(); setWatch(); // heater sanity check timer } void preheat_abs() { setTargetHotend0(absPreheatHotendTemp); setTargetHotend1(absPreheatHotendTemp); setTargetHotend2(absPreheatHotendTemp); setTargetBed(absPreheatHPBTemp); fanSpeed = absPreheatFanSpeed; //lcd_return_to_status(); setWatch(); // heater sanity check timer } void cooldown() { setTargetHotend0(0); setTargetHotend1(0); setTargetHotend2(0); setTargetBed(0); //lcd_return_to_status(); } bool strISAscii(String str) { bool bOK = true; int iFNL = str.length(); char cFN[iFNL]; str.toCharArray(cFN, iFNL); for (int i = 0; i < iFNL - 1; i++) { if (!isAscii(cFN[i])) { bOK = false; break; } } return bOK; } char conv[8]; char *itostr2(const uint8_t &x) { //sprintf(conv,"%5.1f",x); int xx = x; conv[0] = (xx / 10) % 10 + '0'; conv[1] = (xx) % 10 + '0'; conv[2] = 0; return conv; } void sd_init() { pinMode(SDCARDDETECT, INPUT); #if (SDCARDDETECT > 0) WRITE(SDCARDDETECT, HIGH); //lcd_oldcardstatus = IS_SD_INSERTED; #endif //(SDCARDDETECT > 0) card.initsd(); } void Nozzle_offset_test_print() { if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("offset.vaStatus.val=1")); command_M190(50); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("offset.vaStatus.val=3")); command_T(1); command_M109(200); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("offset.vaStatus.val=2")); command_T(0); command_M109(200); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("offset.vaStatus.val=4")); //#define XY20E 0.59868 #define XY20E 0.6 #define EWIDTH 0.4 for (int n=1; n<2; n++) { if(n==1) { command_G28(1,1,1); feedrate = 1000; feedrate = 4000; command_G92(-99999.0,-99999.0,-99999.0,0.0); command_G1(-99999.0, -99999.0, 15, 12.0); command_G92(-99999.0,-99999.0,-99999.0,0.0); command_G1(0, 0, 15, 1.0); command_G1(X_MAX_POS/2.0-(80), 10, 0.2,0.0); feedrate = 1000; command_G1(X_MAX_POS/2.0-(80), 80, 0.2, XY20E*3.5); command_G1(X_MAX_POS/2.0-(80)+EWIDTH, 80, 0.2); command_G1(X_MAX_POS/2.0-(10)+EWIDTH, 80, 0.2, XY20E*7.0); command_G1(X_MAX_POS/2.0-(10)+EWIDTH, 80, 15.0); } command_T(0); command_G92(-99999.0,-99999.0,-99999.0,0.0); feedrate = 4000; command_G1(X_MAX_POS/2.0-(10.0+2*EWIDTH), Y_MAX_POS/2.0-(10.0+2*EWIDTH), 0.2*n); feedrate = 1000; command_G1(X_MAX_POS/2.0-(10.0+2*EWIDTH), Y_MAX_POS/2.0+(10.0+2*EWIDTH), 0.2*n, 1.0+1.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0+2*EWIDTH), Y_MAX_POS/2.0+(10.0+2*EWIDTH), 0.2*n, 1.0+2.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0+2*EWIDTH), Y_MAX_POS/2.0-(10.0+2*EWIDTH), 0.2*n, 1.0+3.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0+2*EWIDTH), Y_MAX_POS/2.0-(10.0+2*EWIDTH), 0.2*n, 1.0+4.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0+1*EWIDTH), Y_MAX_POS/2.0-(10.0+1*EWIDTH), 0.2*n); command_G1(X_MAX_POS/2.0-(10.0+1*EWIDTH), Y_MAX_POS/2.0+(10.0+1*EWIDTH), 0.2*n, 1.0+4.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0+1*EWIDTH), Y_MAX_POS/2.0+(10.0+1*EWIDTH), 0.2*n, 1.0+5.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0+1*EWIDTH), Y_MAX_POS/2.0-(10.0+1*EWIDTH), 0.2*n, 1.0+6.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0+1*EWIDTH), Y_MAX_POS/2.0-(10.0+1*EWIDTH), 0.2*n, 1.0+7.0*XY20E); command_G1(X_MAX_POS/2.0-10.0, Y_MAX_POS/2.0-10.0, 0.2*n); command_G1(X_MAX_POS/2.0-10.0, Y_MAX_POS/2.0+10.0, 0.2*n, 1.0+7.0*XY20E); command_G1(X_MAX_POS/2.0+10.0, Y_MAX_POS/2.0+10.0, 0.2*n, 1.0+8.0*XY20E); command_G1(X_MAX_POS/2.0+10.0, Y_MAX_POS/2.0-10.0, 0.2*n, 1.0+9.0*XY20E); command_G1(X_MAX_POS/2.0-10.0, Y_MAX_POS/2.0-10.0, 0.2*n, 1.0+10.0*XY20E); //if(n==1){ // command_G1(X_MAX_POS/2.0-10.0, Y_MAX_POS/2.0-10.0, 0.2*n, 1.0+10.0*XY20E-3); // command_G1(X_MAX_POS/2.0-10.0, Y_MAX_POS / 2.0-10.0, 0.2*n+15.0, 1.0+10.0*XY20E - 5); //} command_T(1); if(n==1){ feedrate = 4000; command_G92(-99999.0,-99999.0,-99999.0,0.0); command_G1(-99999.0, -99999.0,-99999.0, 12.0); command_G92(-99999.6,-99999.0,-99999.0,0.0); command_G1(X_MAX_POS, 0, 15, 1.0); command_G1(X_MAX_POS/2.0+(80), 10, 0.2,0.0); feedrate = 1000; command_G1(X_MAX_POS/2.0+(80), 80, 0.2, XY20E*3.5); command_G1(X_MAX_POS/2.0+(80)-EWIDTH, 80, 0.2); command_G1(X_MAX_POS/2.0+(10)-EWIDTH, 80, 0.2, XY20E*7.0); command_G1(X_MAX_POS/2.0+(10)-EWIDTH, 80, 15.0); } command_G92(-99999.0,-99999.0,-99999.0,0.0); feedrate = 4000; command_G1(X_MAX_POS/2.0+(10.0-3*EWIDTH), Y_MAX_POS/2.0-(10.0+2*EWIDTH), 0.2*n); feedrate = 1000; command_G1(X_MAX_POS/2.0+(10.0-3*EWIDTH), Y_MAX_POS/2.0+(10.0-3*EWIDTH), 0.2*n, 1.0+1.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-3*EWIDTH), Y_MAX_POS/2.0+(10.0-3*EWIDTH), 0.2*n, 1.0+2.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-3*EWIDTH), Y_MAX_POS/2.0-(10.0-3*EWIDTH), 0.2*n, 1.0+3.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0-3*EWIDTH), Y_MAX_POS/2.0-(10.0-3*EWIDTH), 0.2*n, 1.0+4.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0-2*EWIDTH), Y_MAX_POS/2.0-(10.0-2*EWIDTH), 0.2*n); command_G1(X_MAX_POS/2.0+(10.0-2*EWIDTH), Y_MAX_POS/2.0+(10.0-2*EWIDTH), 0.2*n, 1.0+4.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-2*EWIDTH), Y_MAX_POS/2.0+(10.0-2*EWIDTH), 0.2*n, 1.0+5.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-2*EWIDTH), Y_MAX_POS/2.0-(10.0-2*EWIDTH), 0.2*n, 1.0+6.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0-2*EWIDTH), Y_MAX_POS/2.0-(10.0-2*EWIDTH), 0.2*n, 1.0+7.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0-1*EWIDTH), Y_MAX_POS/2.0-(10.0-1*EWIDTH), 0.2*n); command_G1(X_MAX_POS/2.0+(10.0-1*EWIDTH), Y_MAX_POS/2.0+(10.0-1*EWIDTH), 0.2*n, 1.0+7.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-1*EWIDTH), Y_MAX_POS/2.0+(10.0-1*EWIDTH), 0.2*n, 1.0+8.0*XY20E); command_G1(X_MAX_POS/2.0-(10.0-1*EWIDTH), Y_MAX_POS/2.0-(10.0-1*EWIDTH), 0.2*n, 1.0+9.0*XY20E); command_G1(X_MAX_POS/2.0+(10.0-1*EWIDTH), Y_MAX_POS/2.0-(10.0-1*EWIDTH), 0.2*n, 1.0+10.0*XY20E); //if(n==1){ // command_G1(X_MAX_POS/2.0+(10.0-1*EWIDTH), Y_MAX_POS/2.0-(10.0-1*EWIDTH), 0.2*n, 1.0+10.0*XY20E-3); // command_G1(X_MAX_POS/2.0+(10.0-1*EWIDTH), Y_MAX_POS/2.0-(10.0-1*EWIDTH), 15.0, 1.0+10.0*XY20E - 5); //} } command_G1(-99999.0, Y_MAX_POS-80.0, 15.0); command_G28(1); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("offset.vaStatus.val=0")); }
201,659
C++
.cpp
5,812
24.003957
353
0.505359
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,884
tl_touch_screen.cpp
tenlog_TL-D3/Marlin/tl_touch_screen.cpp
#include "Marlin.h" #include "tl_touch_screen.h" #include "planner.h" #include "temperature.h" #include "cardreader.h" #include "ConfigurationStore.h" float fECOZ = 0; bool bECOSeted = false; String gsM117 = ""; String gsPrinting = ""; long dwn_command[255] = {0}; bool bLogoGot = false; int i_print_page_id = 0; int iDWNPageID = 0; int tenlog_status_update_delay; int tenlogScreenUpdate; int iBeepCount = 0; bool b_PLR_MODULE_Detected = false; int iMoveRate = 100; bool bInited = false; bool bHeatingStop = false; bool bAtvGot0 = false; bool bAtvGot1 = false; bool bAtv = false; int iOldLogoID = 0; long lAtvCode = 0; String file_name_list[6]={""}; String file_name_long_list[6]={""}; bool b_is_last_page = false; void tenlog_status_screen() { if (tenlog_status_update_delay) tenlog_status_update_delay--; else tenlogScreenUpdate = 1; if (tenlogScreenUpdate) { tenlogScreenUpdate = 0; if(tl_TouchScreenType == 0) tenlog_screen_update_dwn(); else tenlog_screen_update_tjc(); tenlog_status_update_delay = 7500; /* redraw the main screen every second. This is easier then trying keep track of all things that change on the screen */ } } void tenlog_screen_update_dwn() { if (!bAtv) return; DWN_Data(0x8000, isHeatingHotend(0), 2); _delay_ms(5); DWN_Data(0x8002, isHeatingHotend(1), 2); _delay_ms(5); DWN_Data(0x8004, isHeatingBed(), 2); _delay_ms(5); DWN_Data(0x6000, int(degTargetHotend(0) + 0.5), 2); _delay_ms(5); DWN_Data(0x6001, int(degHotend(0) + 0.5), 2); _delay_ms(5); DWN_Data(0x6002, int(degTargetHotend(1) + 0.5), 2); _delay_ms(5); DWN_Data(0x6003, int(degHotend(1) + 0.5), 2); _delay_ms(5); DWN_Data(0x6004, int(degTargetBed() + 0.5), 2); _delay_ms(5); DWN_Data(0x6005, int(degBed() + 0.5), 2); _delay_ms(5); if (current_position[X_AXIS] < 0) DWN_Data(0x6006, (current_position[X_AXIS] * 10.0 + 0x10000), 2); else DWN_Data(0x6006, current_position[X_AXIS] * 10.0, 2); _delay_ms(5); if (current_position[Y_AXIS] < 0) DWN_Data(0x6007, (current_position[Y_AXIS] * 10.0 + 0x10000), 2); else DWN_Data(0x6007, current_position[Y_AXIS] * 10.0, 2); _delay_ms(5); if (current_position[Z_AXIS] < 0) DWN_Data(0x6008, (current_position[Z_AXIS] * 10.0 + 0x10000), 2); else DWN_Data(0x6008, current_position[Z_AXIS] * 10.0, 2); _delay_ms(5); DWN_Data(0x602A, iMoveRate, 2); _delay_ms(5); static int siFanStatic; if (siFanStatic > 3) siFanStatic = 0; if (fanSpeed > 0) { DWN_Data(0x8010, siFanStatic, 2); siFanStatic++; } int iFan = (int)((float)fanSpeed / 256.0 * 100.0 + 0.5); if (fanSpeed == 0) DWN_Data(0x8006, 0, 2); else DWN_Data(0x8006, 1, 2); _delay_ms(5); DWN_Data(0x600A, iFan, 2); _delay_ms(5); DWN_Data(0x6052, feedmultiply, 2); _delay_ms(5); String sTime = "-- :--"; int iTimeS = 0; int iPercent = 0; if (card.sdprinting == 1) { uint16_t time = millis() / 60000 - starttime / 60000; sTime = String(itostr2(time / 60)) + " :" + String(itostr2(time % 60)); iPercent = card.percentDone(); DWN_Data(0x6051, iPercent, 2); _delay_ms(5); DWN_Data(0x8820, iPercent, 2); _delay_ms(5); } else { DWN_Data(0x6051, 0, 2); _delay_ms(5); DWN_Data(0x8820, 0, 2); _delay_ms(5); iPercent = 0; iTimeS = 1; } DWN_Data(0x8840, card.sdprinting + languageID * 3, 2); _delay_ms(5); DWN_Data(0x8842, card.sdprinting, 2); _delay_ms(5); DWN_Text(0x7540, 8, sTime); _delay_ms(5); DWN_Data(0x8841, iTimeS, 2); _delay_ms(5); static int iECOBedT; if (current_position[Z_AXIS] >= ECO_HEIGHT && !bECOSeted && card.sdprinting == 1 && tl_ECO_MODE == 1) { int iTB = degTargetBed(); if(iTB > 0) iECOBedT = iTB; setTargetBed(0); bECOSeted = true; } else if (current_position[Z_AXIS] >= ECO_HEIGHT && card.sdprinting == 1 && tl_ECO_MODE == 0 && bECOSeted && iECOBedT > 0) { setTargetBed(iECOBedT); bECOSeted = false; } if (current_position[Z_AXIS] <= ECO_HEIGHT && bECOSeted) { bECOSeted = false; } static int siCM; int iCM; if (dual_x_carriage_mode == 2) { iCM = 3; } else if (dual_x_carriage_mode == 3) { iCM = 4; } else if (dual_x_carriage_mode == 1) { static bool bAPMNozzle; bAPMNozzle = !bAPMNozzle; if (active_extruder == 0 && bAPMNozzle) { iCM = 1; } else if (active_extruder == 1 && bAPMNozzle) { iCM = 2; } else if (!bAPMNozzle) { iCM = 0; } } if (siCM != iCM) { DWN_Data(0x8800, iCM, 2); _delay_ms(5); } siCM = iCM; int iMode = (dual_x_carriage_mode - 1) + languageID * 3; DWN_Data(0x8801, iMode, 2); DWN_Data(0x8804, (dual_x_carriage_mode - 1), 2); _delay_ms(5); int iAN = active_extruder + languageID * 2; DWN_Data(0x8802, iAN, 2); // is for UI V1.3.6 DWN_Data(0x8805, active_extruder, 2); _delay_ms(5); if (gsM117 != "" && gsM117 != "Printing...") { //Do not display "Printing..." String sPrinting = ""; static int icM117; if (icM117 > 0) { icM117--; } if (icM117 == 0) { sPrinting = gsM117; icM117 = 60; } else if (icM117 == 30) { sPrinting = gsPrinting; } if (icM117 == 30 || icM117 == 0 || icM117 == 60) { //Switch message every 30 secounds DWN_Text(0x7500, 32, sPrinting, true); } } DWN_Data(0x6041, (long)(print_from_z_target * 10.0), 2); _delay_ms(5); if (iDWNPageID == DWN_P_PRINTING && !card.isFileOpen()) { //DWN_Page(DWN_P_MAIN); } else if (iDWNPageID == DWN_P_MAIN && card.sdprinting == 1) { DWN_Page(DWN_P_PRINTING); } if (lLEDTimeTimecount <= DWN_LED_TIMEOUT) { lLEDTimeTimecount++; } if (lLEDTimeTimecount == DWN_LED_TIMEOUT) { DWN_LED(DWN_LED_OFF); lLEDTimeTimecount++; if (iDWNPageID != DWN_P_MAIN && !card.isFileOpen()) { DWN_Page(DWN_P_MAIN); } else if (iDWNPageID != DWN_P_PRINTING && card.isFileOpen()) { DWN_Page(DWN_P_PRINTING); } } if (iBeepCount >= 0) { #if (BEEPER > 0) if (iBeepCount % 2 == 1) { WRITE(BEEPER, BEEPER_ON); } else { WRITE(BEEPER, BEEPER_OFF); } #endif iBeepCount--; } if (!bInited) { Init_TLScreen_dwn(); bInited = true; } } /* Start Print 0 Print finished 1 Power Off 2 Power Loss Detected 3 Reset Default 4 Stop Print 5 Filament runout! 6 input Z height 7 Nozzle heating error 8 Nozzle High temp error 9 Nozzle Low Temp error 10 Bed High temp error 11 Bed Low temp error 12 */ void DWN_Message(const int MsgID, const String sMsg, const bool PowerOff) { dwnMessageID = MsgID; int iSend = dwnMessageID + languageID * 13; if (dwnMessageID == 13) iSend = 3 + languageID * 13; DWN_Data(0x9052, dwnMessageID, 2); DWN_Data(0x9050, iSend, 2); _delay_ms(5); DWN_Text(0x7000, 32, sMsg); _delay_ms(5); if (PowerOff == 0) iSend = 0; else iSend = PowerOff + languageID; DWN_Data(0x8830, iSend, 2); _delay_ms(5); DWN_Page(DWN_P_MSGBOX); } int iPrintID = -1; void DWN_MessageBoxHandler(const bool ISOK) { switch (dwnMessageID) { case MSG_RESET_DEFALT: if (card.isFileOpen()) { DWN_Page(DWN_P_SETTING_PRINTING); } else { DWN_Page(DWN_P_SETTING_MAIN); } if (ISOK) command_M502(); break; case MSG_POWER_OFF: if (ISOK) command_M81(false); else DWN_Page(DWN_P_TOOLS); break; case MSG_START_PRINT: if (ISOK) { if (file_name_list[iPrintID] != "") { if (print_from_z_target > 0) PrintFromZHeightFound = false; else PrintFromZHeightFound = true; if (card.sdprinting == 1) { st_synchronize(); card.closefile(); } const char *str0 = file_name_list[iPrintID].c_str(); const char *str1 = file_name_long_list[iPrintID].c_str(); feedrate = 4000; card.openFile(str1, str0, true); card.startFileprint(); starttime = millis(); DWN_Page(DWN_P_PRINTING); gsPrinting = "Printing " + file_name_long_list[iPrintID]; DWN_Text(0x7500, 32, gsPrinting, true); } } else { if (print_from_z_target > 0) DWN_Page(DWN_P_SEL_Z_FILE); else DWN_Page(DWN_P_SEL_FILE); } break; case MSG_PRINT_FINISHED: DWN_Page(DWN_P_MAIN); break; case MSG_STOP_PRINT: if (ISOK) { DWN_Text(0x7000, 32, F(" Stopping, Pls wait...")); quickStop(); bHeatingStop = true; enquecommand_P(PSTR("M1033")); } else DWN_Page(DWN_P_PRINTING); break; case MSG_INPUT_Z_HEIGHT: DWN_Page(DWN_P_PRINTZ); break; case MSG_NOZZLE_HEATING_ERROR: case MSG_NOZZLE_HIGH_TEMP_ERROR: case MSG_NOZZLE_LOW_TEMP_ERROR: case MSG_BED_HIGH_TEMP_ERROR: case MSG_BED_LOW_TEMP_ERROR: sdcard_stop(); break; case MSG_FILAMENT_RUNOUT: enquecommand_P(PSTR("M605 S1")); _delay_ms(300); enquecommand_P(PSTR("G28 X")); _delay_ms(100); if (card.isFileOpen() && card.sdprinting == 0) DWN_Page(DWN_P_RELOAD); break; case MSG_POWER_LOSS_DETECTED: bAtv = true; if (ISOK) { command_M1003(); } else { DWN_Page(DWN_P_MAIN); #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_Write_PLR(); EEPROM_PRE_Write_PLR(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) card.Write_PLR(); card.PRE_Write_PLR(); #endif } break; } } void CheckTempError_tjc() { if (iTempErrID > 0) { String strMessage = sTempErrMsg; TLSTJC_printconstln(F("sleep=0")); TLSTJC_printconstln(F("msgbox.vaFromPageID.val=1")); TLSTJC_printconstln(F("msgbox.vaToPageID.val=1")); TLSTJC_printconst(F("msgbox.vaMID.val=")); strMessage = "" + String(iTempErrID) + ""; const char *str1 = strMessage.c_str(); TLSTJC_println(str1); TLSTJC_printconst(F("msgbox.vtMS.txt=\"")); strMessage = " " + sShortErrMsg + ""; str1 = strMessage.c_str(); TLSTJC_print(str1); TLSTJC_printconstln(F("\"")); sShortErrMsg = ""; TLSTJC_printconst(F("msgbox.tMessage.txt=\"")); strMessage = "" + strMessage + ""; str1 = strMessage.c_str(); TLSTJC_print(str1); TLSTJC_printconstln(F("\"")); TLSTJC_printconstln(F("page msgbox")); #ifdef HAS_PLR_MODULE if (iTempErrID == MSG_NOZZLE_HEATING_ERROR || iTempErrID == MSG_NOZZLE_HIGH_TEMP_ERROR || iTempErrID == MSG_BED_HIGH_TEMP_ERROR) { _delay_ms(5000); command_M81(false, false); } #endif iTempErrID = 0; } } void Init_TLScreen_tjc() { _delay_ms(20); TLSTJC_printconst(F("main.vLanguageID.val=")); TLSTJC_print(String(languageID).c_str()); TLSTJC_printend(); _delay_ms(20); long iSend = tl_X2_MAX_POS * 100.0; TLSTJC_printconst(F("setting.xX2.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); TLSTJC_printconst(F("offset.xX2.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_Y2_OFFSET * 100.0; TLSTJC_printconst(F("setting.xY2.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); TLSTJC_printconst(F("offset.xY2.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_Z2_OFFSET * 100.0; TLSTJC_printconst(F("setting.xZ2.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = axis_steps_per_unit[0] * 100.0; TLSTJC_printconst(F("setting.xXs.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = axis_steps_per_unit[1] * 100.0; TLSTJC_printconst(F("setting.xYs.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = axis_steps_per_unit[2] * 100.0; TLSTJC_printconst(F("setting.xZs.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = axis_steps_per_unit[3] * 100.0; TLSTJC_printconst(F("setting.xEs.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); #ifdef FAN2_CONTROL iSend = tl_FAN2_VALUE; TLSTJC_printconst(F("setting.nF2s.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); #else TLSTJC_printconstln(F("setting.nF2s.val=0")); #endif _delay_ms(20); #ifdef FAN2_CONTROL iSend = tl_FAN2_START_TEMP; TLSTJC_printconst(F("setting.nF2t.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); #else TLSTJC_printconstln(F("setting.nF2t.val=0")); #endif _delay_ms(20); iSend = tl_X2_MAX_POS * 10.0; TLSTJC_printconst(F("main.vXMax.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = Y_MAX_POS * 10.0; TLSTJC_printconst(F("main.vYMax.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = Z_MAX_POS * 10.0; TLSTJC_printconst(F("main.vZMax.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_HEATER_0_MAXTEMP; TLSTJC_printconst(F("main.vTempMax.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_BED_MAXTEMP; TLSTJC_printconst(F("main.vTempMaxBed.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); #ifdef HAS_PLR_MODULE if (b_PLR_MODULE_Detected) TLSTJC_printconstln(F("main.vPFR.val=1")); else TLSTJC_printconstln(F("main.vPFR.val=0")); _delay_ms(20); iSend = tl_AUTO_OFF; TLSTJC_printconst(F("setting.cAutoOff.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); #endif //HAS_PLR_MODULE iSend = tl_Filament_Detect; TLSTJC_printconst(F("setting.cFilaSensor.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_ECO_MODE; TLSTJC_printconst(F("setting.cECOMode.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); iSend = tl_SLEEP_TIME; TLSTJC_printconst(F("setting.nSleep.val=")); TLSTJC_print(String(iSend).c_str()); TLSTJC_printend(); _delay_ms(20); // TLSTJC_printconstln(F("sleep=0")); iBeepCount = 2; String strDate = __DATE__; TLSTJC_printconst(F("about.tVer.txt=\"")); TLSTJC_printconst(F(FW_STR)); #ifdef HAS_PLR_MODULE if (b_PLR_MODULE_Detected) TLSTJC_printconst(F(" PLR ")); else TLSTJC_printconst(F(" ")); #endif _delay_ms(20); TLSTJC_printconst(F("V ")); TLSTJC_printconst(F(VERSION_STRING)); TLSTJC_printconstln(F("\"")); _delay_ms(20); TLSTJC_printconstln(F("bkcmd=0")); _delay_ms(20); // #if (BEEPER > 0) SET_OUTPUT(BEEPER); WRITE(BEEPER, BEEPER_OFF); #endif } void tenlog_screen_update_tjc() { String strAll = "main.sStatus.txt=\""; long lN = current_position[X_AXIS] * 10.0; //1 String sSend = String(lN); strAll = strAll + sSend + "|"; //6 lN = current_position[Y_AXIS] * 10.0; //2 sSend = String(lN); strAll = strAll + sSend + "|"; //12 lN = current_position[Z_AXIS] * 10.0; //3 sSend = String(lN); strAll = strAll + sSend + "|"; //18 lN = current_position[E_AXIS] * 10.0; //4 sSend = String(lN); strAll = strAll + "|"; //do not sent E Position //19 //strAll = strAll + sSend + "|"; lN = int(degTargetHotend(0) + 0.5); //5 sSend = String(lN); strAll = strAll + sSend + "|"; //23 lN = int(degHotend(0) + 0.5); //6 sSend = String(lN); strAll = strAll + sSend + "|"; //27 lN = int(degTargetHotend(1) + 0.5); //7 sSend = String(lN); strAll = strAll + sSend + "|"; //31 lN = int(degHotend(1) + 0.5); //8 sSend = String(lN); strAll = strAll + sSend + "|"; //35 lN = int(degTargetBed() + 0.5); //9 sSend = String(lN); strAll = strAll + sSend + "|"; //3 lN = int(degBed() + 0.5); //10 sSend = String(lN); strAll = strAll + sSend + "|"; lN = fanSpeed * 100.0 / 255.0 + 0.5; //11 sSend = String(lN); strAll = strAll + sSend + "|"; lN = feedmultiply; //12 sSend = String(lN); strAll = strAll + sSend + "|"; int iPercent = 0; if (card.sdprinting == 1) //13 { strAll = strAll + "1|"; lN = card.percentDone(); iPercent = card.percentDone(); sSend = String(lN); //14 strAll = strAll + sSend + "|"; } else if (card.sdprinting == 0) { strAll = strAll + "0|0|"; } else if (card.sdprinting == 2) { strAll = strAll + "2|0|"; } lN = active_extruder; //15 sSend = String(lN); strAll = strAll + sSend + "|"; lN = dual_x_carriage_mode; //16 sSend = String(lN); strAll = strAll + sSend + "|"; //lN=dual_x_carriage_mode; //17 time if (IS_SD_PRINTING) { uint16_t time = millis() / 60000 - starttime / 60000; sSend = String(itostr2(time / 60)) + ":" + String(itostr2(time % 60)); strAll = strAll + sSend + "|"; } else { strAll = strAll + "00:00|"; } if (card.isFileOpen()) { //18 is file open strAll = strAll + "1|"; } else { strAll = strAll + "0|"; } if (isHeatingHotend(0)) { //19 is heating nozzle 0 strAll = strAll + "1|"; } else { strAll = strAll + "0|"; } if (isHeatingHotend(1)) { //20 is heating nozzle 1 strAll = strAll + "1|"; } else { strAll = strAll + "0|"; } if (isHeatingBed()) { //21 is heating Bed strAll = strAll + "1|"; } else { strAll = strAll + "0|"; } strAll = strAll + "\""; const char *strAll0 = strAll.c_str(); TLSTJC_println(strAll0); static int iECOBedT; if (current_position[Z_AXIS] >= ECO_HEIGHT && !bECOSeted && iPercent > 1 && tl_ECO_MODE == 1) { iECOBedT = degTargetBed(); setTargetBed(0); bECOSeted = true; } else if (current_position[Z_AXIS] >= ECO_HEIGHT && tl_ECO_MODE == 0 && bECOSeted && iECOBedT > 0) { setTargetBed(iECOBedT); } if (current_position[Z_AXIS] <= ECO_HEIGHT && bECOSeted) { bECOSeted = false; } if (gsM117 != "" && gsM117 != "Printing...") { //Do not display "Printing..." static int icM117; if (icM117 > 0) { icM117--; } if (icM117 == 0) { _delay_ms(50); TLSTJC_printconst(F("printing.tM117.txt=\"")); String strM117 = "" + gsM117 + ""; const char *strM1170 = strM117.c_str(); TLSTJC_println(strM1170); TLSTJC_printconstln(F("\"")); icM117 = 60; } else if (icM117 == 30) { _delay_ms(50); TLSTJC_printconstln(F("printing.tM117.txt=\"\"")); _delay_ms(50); } } _delay_ms(50); TLSTJC_printconstln(F("click btReflush,0")); if (iBeepCount >= 0) { #if (BEEPER > 0) if (iBeepCount % 2 == 1) { WRITE(BEEPER, BEEPER_ON); } else { WRITE(BEEPER, BEEPER_OFF); } #endif iBeepCount--; } if (!bInited) { Init_TLScreen_tjc(); bInited = true; } } void sdcard_tlcontroller_dwn() { card.initsd(); _delay_ms(50); uint16_t fileCnt = card.getnrfilenames(); card.getWorkDirName(); if (card.filename[0] == '/') { } else { } if (i_print_page_id == 0) { DWN_Data(0x8810, 1, 2); } else { DWN_Data(0x8810, 0, 2); } int iFileID = 0; //Clear the boxlist for (int i = 0; i < 6; i++) { DWN_Text(0x7300 + i * 0x30, 32, ""); file_name_list[i] = ""; file_name_long_list[i] = ""; } for (uint16_t i = 0; i < fileCnt; i++) { card.getfilename(fileCnt - 1 - i); String strFN = String(card.filename); if (!card.filenameIsDir && strFN.length() > 0) { if (strISAscii(strFN)) { strFN = String(card.longFilename); strFN.toLowerCase(); String strLFN = strFN; iFileID++; if (iFileID >= (i_print_page_id)*6 + 1 && iFileID <= (i_print_page_id + 1) * 6) { int iFTemp = iFileID - (i_print_page_id)*6; strFN = String(card.filename); strFN.toLowerCase(); if (strLFN == "") strLFN = strFN; DWN_Text(0x7300 + (iFTemp - 1) * 0x30, 32, strLFN.c_str()); file_name_list[iFTemp - 1] = strFN.c_str(); file_name_long_list[iFTemp - 1] = strLFN.c_str(); } } } } if ((i_print_page_id + 1) * 6 >= iFileID) { DWN_Data(0x8811, 1, 2); b_is_last_page = true; } else { DWN_Data(0x8811, 0, 2); b_is_last_page = false; } } void sdcard_tlcontroller_tjc() { uint16_t fileCnt = card.getnrfilenames(); card.getWorkDirName(); if (card.filename[0] == '/') { } else { } if (i_print_page_id == 0) { TLSTJC_printconstln(F("vis btUp,0")); } else { TLSTJC_printconstln(F("vis btUp,1")); } int iFileID = 0; //Clear the boxlist for (int i = 1; i < 7; i++) { TLSTJC_print("select_file.tL"); TLSTJC_print(String(i).c_str()); TLSTJC_print(".txt=\"\""); TLSTJC_printend(); TLSTJC_print("select_file.sL"); TLSTJC_print(String(i).c_str()); TLSTJC_print(".txt=\"\""); TLSTJC_printend(); } for (uint16_t i = 0; i < fileCnt; i++) { card.getfilename(fileCnt - 1 - i); //card.getfilename(i); // card.getfilename(fileCnt-1-i); //By Zyf sort by time desc String strFN = String(card.filename); // + " | " + String(card.filename); if (!card.filenameIsDir && strFN.length() > 0) { if (strISAscii(strFN)) { strFN = String(card.longFilename); strFN.toLowerCase(); String strLFN = strFN; iFileID++; if (iFileID >= (i_print_page_id)*6 + 1 && iFileID <= (i_print_page_id + 1) * 6) { strFN = String(card.filename); strFN.toLowerCase(); if (strLFN == "") strLFN = strFN; int iFTemp = iFileID - (i_print_page_id)*6; TLSTJC_print("select_file.tL"); TLSTJC_print(String(iFTemp).c_str()); TLSTJC_print(".txt=\""); strLFN.toLowerCase(); TLSTJC_print(strLFN.c_str()); TLSTJC_print("\""); TLSTJC_printend(); TLSTJC_print("select_file.sL"); TLSTJC_print(String(iFTemp).c_str()); TLSTJC_print(".txt=\""); TLSTJC_print(strFN.c_str()); TLSTJC_print("\""); TLSTJC_printend(); } //MENU_ITEM(sdfile, MSG_CARD_MENU, card.filename, card.longFilename); } } } TLSTJC_printconst(F("select_file.vPageID.val=")); TLSTJC_print(String(i_print_page_id).c_str()); TLSTJC_printend(); if ((i_print_page_id + 1) * 6 >= iFileID) { TLSTJC_printconstln(F("vis btDown,0")); } else { TLSTJC_printconstln(F("vis btDown,1")); } }
25,639
C++
.cpp
896
21.340402
163
0.534366
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,885
cardreader.cpp
tenlog_TL-D3/Marlin/cardreader.cpp
#include "Marlin.h" #include "cardreader.h" #include "stepper.h" #include "temperature.h" #include "language.h" #include "ConfigurationStore.h" #ifdef SDSUPPORT CardReader::CardReader() { filesize = 0; sdpos = 0; sdprinting = 0; cardOK = false; saving = false; logging = false; autostart_atmillis = 0; workDirDepth = 0; memset(workDirParents, 0, sizeof(workDirParents)); autostart_stilltocheck = true; //the sd start is delayed, because otherwise the serial cannot answer fast enought to make contact with the hostsoftware. lastnr = 0; //power to SD reader #if SDPOWER > -1 SET_OUTPUT(SDPOWER); WRITE(SDPOWER, HIGH); #endif //SDPOWER autostart_atmillis = millis() + 5000; } char *createFilename(char *buffer, const dir_t &p) //buffer>12characters { char *pos = buffer; for (uint8_t i = 0; i < 11; i++) { if (p.name[i] == ' ') continue; if (i == 8) { *pos++ = '.'; } *pos++ = p.name[i]; } *pos++ = 0; return buffer; } void CardReader::lsDive(const char *prepend, SdFile parent) { dir_t p; uint8_t cnt = 0; while (parent.readDir(p, longFilename) > 0) { if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) // hence LS_SerialPrint { char path[13 * 2]; char lfilename[13]; createFilename(lfilename, p); path[0] = 0; if (strlen(prepend) == 0) //avoid leading / if already in prepend { strcat(path, "/"); } strcat(path, prepend); strcat(path, lfilename); strcat(path, "/"); //Serial.print(path); SdFile dir; if (!dir.open(parent, lfilename, O_READ)) { if (lsAction == LS_SerialPrint) { SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_SD_CANT_OPEN_SUBDIR); SERIAL_ECHOLN(lfilename); } } lsDive(path, dir); //close done automatically by destructor of SdFile } else { if (p.name[0] == DIR_NAME_FREE) break; if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.' || p.name[0] == '_') continue; if (longFilename[0] != '\0' && (longFilename[0] == '.' || longFilename[0] == '_')) continue; if (p.name[0] == '.') { if (p.name[1] != '.') continue; } if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; filenameIsDir = DIR_IS_SUBDIR(&p); if (!filenameIsDir) { if (p.name[8] != 'G') continue; if (p.name[9] == '~') continue; } //if(cnt++!=nr) continue; createFilename(filename, p); if (lsAction == LS_SerialPrint) { SERIAL_PROTOCOL(prepend); SERIAL_PROTOCOLLN(filename); } else if (lsAction == LS_Count) { nrFiles++; } else if (lsAction == LS_GetFilename) { if (cnt == nrFiles) return; cnt++; //SERIAL_PROTOCOL(prepend); //SERIAL_PROTOCOLLN(filename); } } } } void CardReader::ls() { lsAction = LS_SerialPrint; if (lsAction == LS_Count) nrFiles = 0; root.rewind(); lsDive("", root); } void CardReader::initsd() { cardOK = false; if (root.isOpen()) root.close(); #ifdef SDSLOW if (!card.init(SPI_HALF_SPEED, SDSS)) #else if (!card.init(SPI_FULL_SPEED, SDSS)) #endif { //if (!card.init(SPI_HALF_SPEED,SDSS)) SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_SD_INIT_FAIL); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("tStatus.txt=\"SD Card not detected\"")); else if(tl_TouchScreenType == 0) DWN_Text(0x7100, 20, F("SD Card not detected")); } else if (!volume.init(&card)) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_SD_VOL_INIT_FAIL); } else if (!root.openRoot(&volume)) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_SD_OPENROOT_FAIL); } else { cardOK = true; SERIAL_ECHO_START; SERIAL_ECHOLNPGM(MSG_SD_CARD_OK); if(tl_TouchScreenType == 1) TLSTJC_printconstln(F("tStatus.txt=\"SD card OK\"")); else if(tl_TouchScreenType = 0) DWN_Text(0x7100, 20, F("SD card OK")); } workDir = root; curDir = &root; } void CardReader::setroot() { /*if(!workDir.openRoot(&volume)) { SERIAL_ECHOLNPGM(MSG_SD_WORKDIR_FAIL); }*/ workDir = root; curDir = &workDir; } void CardReader::release() { sdprinting = 0; cardOK = false; } void CardReader::startFileprint() { if (cardOK) { sdprinting = 1; } } void CardReader::pauseSDPrint() { if (sdprinting == 1) sdprinting = 0; } void CardReader::openLogFile(char *name) { logging = true; openFile(name, name, false); //By zyf } void CardReader::openFile(char *lngName, char *name, bool read, uint32_t startPos) //By zyf { if (!cardOK) return; file.close(); sdprinting = 0; SdFile myDir; curDir = &root; char *fname = name; char *dirname_start, *dirname_end; if (name[0] == '/') { dirname_start = strchr(name, '/') + 1; while (dirname_start > 0) { dirname_end = strchr(dirname_start, '/'); //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name)); //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name)); if (dirname_end > 0 && dirname_end > dirname_start) { char subdirname[13]; strncpy(subdirname, dirname_start, dirname_end - dirname_start); subdirname[dirname_end - dirname_start] = 0; SERIAL_ECHOLN(subdirname); if (!myDir.open(curDir, subdirname, O_READ)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOLLNPGM("."); sdprinting = 0; return; } else { //SERIAL_ECHOLN(subdirname); } curDir = &myDir; dirname_start = dirname_end + 1; } else // the reminder after all /fsa/fdsa/ is the filename { fname = dirname_start; //SERIAL_ECHOLN("remaider"); //SERIAL_ECHOLN(fname); break; } } } else //relative path { curDir = &workDir; //SERIAL_PROTOCOL(workDir); } if (read) { if (file.open(curDir, fname, O_READ)) { filesize = file.fileSize(); SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLPGM(MSG_SD_SIZE); SERIAL_PROTOCOLLN(filesize); //By Zyf #ifdef POWER_LOSS_RECOVERY if (startPos > 0) { //SERIAL_PROTOCOLPGM("Print From "); //SERIAL_PROTOCOLLN(startPos); sdpos = startPos; setIndex(sdpos); } else { sdpos = 0; } #else sdpos = 0; #endif SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED); //lcd_setstatus(fname); #ifdef POWER_LOSS_RECOVERY String strFName = fname; String strLFName = lngName; writeLastFileName(strLFName, strFName); #if defined(POWER_LOSS_SAVE_TO_EEPROM) EEPROM_Write_PLR(); EEPROM_PRE_Write_PLR(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) Write_PLR(); PRE_Write_PLR(); #endif #endif } else { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); sdprinting = 0; } } else { //write if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } else { saving = true; SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE); SERIAL_PROTOCOLLN(name); //lcd_setstatus(fname); } } } void CardReader::removeFile(char *name) { if (!cardOK) return; file.close(); sdprinting = 0; SdFile myDir; curDir = &root; char *fname = name; char *dirname_start, *dirname_end; if (name[0] == '/') { dirname_start = strchr(name, '/') + 1; while (dirname_start > 0) { dirname_end = strchr(dirname_start, '/'); //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name)); //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name)); if (dirname_end > 0 && dirname_end > dirname_start) { char subdirname[13]; strncpy(subdirname, dirname_start, dirname_end - dirname_start); subdirname[dirname_end - dirname_start] = 0; SERIAL_ECHOLN(subdirname); if (!myDir.open(curDir, subdirname, O_READ)) { SERIAL_PROTOCOLPGM("open failed, File: "); SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOLLNPGM("."); return; } else { //SERIAL_ECHOLN("dive ok"); } curDir = &myDir; dirname_start = dirname_end + 1; } else // the reminder after all /fsa/fdsa/ is the filename { fname = dirname_start; //SERIAL_ECHOLN("remaider"); //SERIAL_ECHOLN(fname); break; } } } else //relative path { curDir = &workDir; } if (file.remove(curDir, fname)) { SERIAL_PROTOCOLPGM("File deleted:"); SERIAL_PROTOCOL(fname); sdpos = 0; } else { SERIAL_PROTOCOLPGM("Deletion failed, File: "); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } } void CardReader::getStatus() { if (cardOK) { SERIAL_PROTOCOLPGM(MSG_SD_PRINTING_BYTE); SERIAL_PROTOCOL(sdpos); SERIAL_PROTOCOLPGM("/"); SERIAL_PROTOCOLLN(filesize); } else { SERIAL_PROTOCOLLNPGM(MSG_SD_NOT_PRINTING); } } void CardReader::write_command(char *buf) { char *begin = buf; char *npos = 0; char *end = buf + strlen(buf) - 1; file.writeError = false; if ((npos = strchr(buf, 'N')) != NULL) { begin = strchr(npos, ' ') + 1; end = strchr(npos, '*') - 1; } end[1] = '\r'; end[2] = '\n'; end[3] = '\0'; file.write(begin); if (file.writeError) { SERIAL_ERROR_START; SERIAL_ERRORLNPGM(MSG_SD_ERR_WRITE_TO_FILE); } } void CardReader::checkautostart(bool force) { if (!force) { if (!autostart_stilltocheck) return; if (autostart_atmillis < millis()) return; } autostart_stilltocheck = false; if (!cardOK) { initsd(); if (!cardOK) //fail return; } char autoname[30]; sprintf_P(autoname, PSTR("auto%i.g"), lastnr); for (int8_t i = 0; i < (int8_t)strlen(autoname); i++) autoname[i] = tolower(autoname[i]); dir_t p; root.rewind(); bool found = false; while (root.readDir(p, NULL) > 0) { for (int8_t i = 0; i < (int8_t)strlen((char *)p.name); i++) p.name[i] = tolower(p.name[i]); if (p.name[9] != '~') //skip safety copies if (strncmp((char *)p.name, autoname, 5) == 0) { char cmd[30]; sprintf_P(cmd, PSTR("M23 %s"), autoname); enquecommand(cmd); enquecommand_P(PSTR("M24")); found = true; } } if (!found) lastnr = -1; else lastnr++; } void CardReader::closefile() { file.sync(); file.close(); saving = false; logging = false; } void CardReader::getfilename(const uint8_t nr) { curDir = &workDir; lsAction = LS_GetFilename; nrFiles = nr; curDir->rewind(); lsDive("", *curDir); } uint16_t CardReader::getnrfilenames() { curDir = &workDir; lsAction = LS_Count; nrFiles = 0; curDir->rewind(); lsDive("", *curDir); //SERIAL_ECHOLN(nrFiles); return nrFiles; } void CardReader::chdir(const char *relpath) { SdFile newfile; SdFile *parent = &root; if (workDir.isOpen()) parent = &workDir; if (!newfile.open(*parent, relpath, O_READ)) { SERIAL_ECHO_START; SERIAL_ECHOPGM(MSG_SD_CANT_ENTER_SUBDIR); SERIAL_ECHOLN(relpath); } else { if (workDirDepth < MAX_DIR_DEPTH) { for (int d = ++workDirDepth; d--;) workDirParents[d + 1] = workDirParents[d]; workDirParents[0] = *parent; } workDir = newfile; } //SERIAL_ECHOLN(relpath); } void CardReader::updir() { if (workDirDepth > 0) { --workDirDepth; workDir = workDirParents[0]; int d; for (int d = 0; d < workDirDepth; d++) workDirParents[d] = workDirParents[d + 1]; } } void CardReader::printingHasFinished() { st_synchronize(); quickStop(); file.close(); sdprinting = 0; finishAndDisableSteppers(true); //By Zyf autotempShutdown(); } #ifdef POWER_LOSS_RECOVERY void CardReader::writeLastFileName(String LFName, String Value) { if (!cardOK) return; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLN.TXT"; bool bFileExists = false; if (tf_file.open(*parent, tff, O_READ)) { bFileExists = true; tf_file.close(); } String sContent = ""; char cAll[150]; char cContent[50]; sContent = LFName + "|"; sContent += Value; sContent.toCharArray(cContent, 50); sprintf_P(cAll, PSTR("%s"), cContent); const char *arrFileContentNew = cAll; uint8_t O_TF = O_CREAT | O_EXCL | O_WRITE; if (bFileExists) O_TF = O_WRITE | O_TRUNC; if (tf_file.open(*parent, tff, O_TF)) { tf_file.write(arrFileContentNew); tf_file.close(); } else { } } ///////////////////split String CardReader::getSplitValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length() - 1; for (int i = 0; i <= maxIndex && found <= index; i++) { if (data.charAt(i) == separator || i == maxIndex) { found++; strIndex[0] = strIndex[1] + 1; strIndex[1] = (i == maxIndex) ? i + 1 : i; } } return found > index ? data.substring(strIndex[0], strIndex[1]) : ""; } String CardReader::isPowerLoss() { if (!cardOK) return ""; String sRet = ""; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLN.TXT"; //Read File if (tf_file.open(*parent, tff, O_READ)) { int16_t fS = tf_file.fileSize() + 1; char buf[255]; char dim1[] = "\n"; char *dim = dim1; int16_t n = tf_file.fgets(buf, fS, dim); String strFileContent = ""; for (int i = 0; i < fS; i++) { if (buf[i] != '\0') strFileContent += buf[i]; } if (strFileContent != "") sRet = strFileContent; } tf_file.close(); if (sRet != "") { uint32_t lFPos = 0; #if defined(POWER_LOSS_SAVE_TO_EEPROM) lFPos = EEPROM_Read_PLR_0(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) lFPos = Read_PLR_0(); #endif if (lFPos < 2048) sRet = ""; } else { //TL_DEBUG_PRINT_LN(F("PLR File open fail.")); } return sRet; } String CardReader::get_PLR() { if (!cardOK) return ""; String sRet = ""; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLN.TXT"; //Read File if (tf_file.open(*parent, tff, O_READ)) { int16_t fS = tf_file.fileSize() + 1; char buf[255]; char dim1[] = "\n"; char *dim = dim1; int16_t n = tf_file.fgets(buf, fS, dim); String strFileContent = ""; for (int i = 0; i < fS; i++) { if (buf[i] != '\0') strFileContent += buf[i]; } if (strFileContent != "") { sRet = strFileContent; } } tf_file.close(); if (sRet != "") { String strRet = ""; #if defined(POWER_LOSS_SAVE_TO_EEPROM) strRet = EEPROM_Read_PLR(); #elif defined(POWER_LOSS_SAVE_TO_SDCARD) strRet = Read_PLR(); #endif sRet = sRet + "|" + strRet; } return sRet; } #ifdef POWER_LOSS_SAVE_TO_SDCARD void CardReader::Write_PLR(uint32_t lFPos, int iTPos, int iTPos1, int iT01, float fZPos, float fEPos) { #ifdef POWER_LOSS_TRIGGER_BY_Z_LEVER if (lFPos == 0) fLastZ = 0.0; #endif #ifdef POWER_LOSS_TRIGGER_BY_E_COUNT if (lFPos == 0) lECount = POWER_LOSS_E_COUNT; #endif if (!cardOK) return; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLR.TXT"; bool bFileExists = false; if (tf_file.open(*parent, tff, O_READ)) { bFileExists = true; tf_file.close(); } String sContent = ""; char cAll[150]; char cContent[15] = ""; char cLine[15]; const char *arrFileContentNew; uint32_t lFPos0 = sdpos; if (lFPos > 2048 && sdprinting == 1) { sContent.toCharArray(cContent, 12); float fValue = 0.0; ///////////// 0 = file Pos sContent = lFPos0; sContent.toCharArray(cContent, 12); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 1 = Temp0 Pos sContent = iTPos; sContent.toCharArray(cContent, 10); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 2 = Temp1 Pos sContent = iTPos1; sContent.toCharArray(cContent, 10); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 3 = T0T1 sContent = iT01; sContent.toCharArray(cContent, 10); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 4 = Z Pos fValue = fZPos; dtostrf(fValue, 1, 2, cContent); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 5 = E Pos fValue = fEPos; dtostrf(fValue, 1, 2, cContent); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); arrFileContentNew = cAll; } else { arrFileContentNew = "0"; } uint8_t O_TF = O_CREAT | O_EXCL | O_WRITE; if (bFileExists) O_TF = O_WRITE | O_TRUNC; if (tf_file.open(*parent, tff, O_TF)) { tf_file.write(arrFileContentNew); tf_file.close(); } else { //TL_DEBUG_PRINT_LN(F("Write Value Err ")); } } bool b_PRE_Write_PLR_Done = false; void CardReader::PRE_Write_PLR(uint32_t lFPos, int iBPos, int i_dual_x_carriage_mode, float f_duplicate_extruder_x_offset, float f_feedrate) { if (!cardOK) return; SdFile tf_file; SdFile *parent = &root; const char *tff = "PPLR.TXT"; bool bFileExists = false; if (tf_file.open(*parent, tff, O_READ)) { bFileExists = true; tf_file.close(); } String sContent = ""; char cAll[150]; char cContent[15]; char cLine[15]; const char *arrFileContentNew; if (lFPos > 2048 && sdprinting == 1 && !b_PRE_Write_PLR_Done) { float fValue = 0.0; ///////////// 0 = Bed Temp sContent = iBPos; sContent.toCharArray(cContent, 10); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 1 = dual_x_carriage_mode sContent = dual_x_carriage_mode; sContent.toCharArray(cContent, 10); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); /////////////// 2 = duplicate_extruder_x_offset fValue = f_duplicate_extruder_x_offset; dtostrf(fValue, 1, 2, cContent); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); ///////////// 3 = feedrate fValue = f_feedrate; dtostrf(fValue, 1, 2, cContent); sprintf_P(cLine, PSTR("%s|"), cContent); strcat(cAll, cLine); arrFileContentNew = cAll; uint8_t O_TF = O_CREAT | O_EXCL | O_WRITE; if (bFileExists) O_TF = O_WRITE | O_TRUNC; if (tf_file.open(*parent, tff, O_TF)) { tf_file.write(arrFileContentNew); tf_file.close(); } else { //TL_DEBUG_PRINT_LN(F("New Value Err ")); } b_PRE_Write_PLR_Done = true; } } uint32_t CardReader::Read_PLR_0() { uint32_t lRet = 0; if (!cardOK) return 0; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLR.TXT"; //Read File if (tf_file.open(*parent, tff, O_READ)) { int16_t fS = tf_file.fileSize() + 1; char buf[255]; char dim1[] = "\n"; char *dim = dim1; int16_t n = tf_file.fgets(buf, fS, dim); String strFileContent = ""; for (int i = 0; i < fS; i++) { if (buf[i] != '\0') strFileContent += buf[i]; } if (strFileContent != "") { lRet = atol(const_cast<char *>(getSplitValue(strFileContent, '|', 0).c_str())); } } tf_file.close(); return lRet; } String CardReader::Read_PLR() { String sRet = ""; uint32_t lFP = 0; if (!cardOK) return ""; SdFile tf_file; SdFile *parent = &root; const char *tff = "PLR.TXT"; String strFileContent = ""; //Read File if (tf_file.open(*parent, tff, O_READ)) { int16_t fS = tf_file.fileSize() + 1; char buf[255]; char dim1[] = "\n"; char *dim = dim1; int16_t n = tf_file.fgets(buf, fS, dim); for (int i = 0; i < fS; i++) { if (buf[i] != '\0') strFileContent += buf[i]; } if (strFileContent != "") { lFP = atol(const_cast<char *>(getSplitValue(strFileContent, '|', 0).c_str())); } } tf_file.close(); if (lFP > 2048) { const char *tff = "PPLR.TXT"; String strFileContent1 = ""; //Read File if (tf_file.open(*parent, tff, O_READ)) { int16_t fS = tf_file.fileSize() + 1; char buf[255]; char dim1[] = "\n"; char *dim = dim1; int16_t n = tf_file.fgets(buf, fS, dim); for (int i = 0; i < fS; i++) { if (buf[i] != '\0') strFileContent1 += buf[i]; } if (strFileContent1 != "") { String sFC = strFileContent; sRet = sFC + "255|0|0|" + strFileContent1; } } tf_file.close(); } return sRet; } #endif //#ifdef POWER_LOSS_SAVE_TO_SDCARD #endif //POWER_LOSS_RECOVERY #endif //SDSUPPORT
25,389
C++
.cpp
893
19.180291
157
0.494596
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,886
ConfigurationStore.cpp
tenlog_TL-D3/Marlin/ConfigurationStore.cpp
#include "Marlin.h" #include "planner.h" #include "temperature.h" #include "ConfigurationStore.h" void _EEPROM_writeData(int &pos, uint8_t *value, uint8_t size) { do { eeprom_write_byte((unsigned char *)pos, *value); pos++; value++; } while (--size); } #define EEPROM_WRITE_VAR(pos, value) _EEPROM_writeData(pos, (uint8_t *)&value, sizeof(value)) void _EEPROM_readData(int &pos, uint8_t *value, uint8_t size) { do { *value = eeprom_read_byte((unsigned char *)pos); pos++; value++; } while (--size); } #define EEPROM_READ_VAR(pos, value) _EEPROM_readData(pos, (uint8_t *)&value, sizeof(value)) //====================================================================================== #define EEPROM_OFFSET 100 // IMPORTANT: Whenever there are changes made to the variables stored in EEPROM // in the functions below, also increment the version number. This makes sure that // the default values are used whenever there is a change to the data, to prevent // wrong data being written to the variables. // ALSO: always make sure the variables in the Store and retrieve sections are in the same order. #define EEPROM_VERSION "V08" #ifdef EEPROM_SETTINGS void EEPROM_Write_Last_Z(float Z, float Y, int DXCMode, long lTime) { int i = 450; float fZOld = EEPROM_Read_Last_Z(); if (fZOld != Z) EEPROM_WRITE_VAR(i, Z); i = 454; float fYOld = EEPROM_Read_Last_Y(); if (fYOld != Y && Y != 0.0) EEPROM_WRITE_VAR(i, Y); i = 458; int iMOld = EEPROM_Read_Last_Mode(); if (iMOld != DXCMode) EEPROM_WRITE_VAR(i, DXCMode); i = 462; long lTimeOld = EEPROM_Read_Last_Time(); if (lTime != lTimeOld) EEPROM_WRITE_VAR(i, lTime); } float EEPROM_Read_Last_Z() { float Z; int i = 450; EEPROM_READ_VAR(i, Z); return Z; } float EEPROM_Read_Last_Y() { float Y; int i = 454; EEPROM_READ_VAR(i, Y); return Y; } int EEPROM_Read_Last_Mode() { int Mode; int i = 458; EEPROM_READ_VAR(i, Mode); return Mode; } long EEPROM_Read_Last_Time() { long Time; int i = 462; EEPROM_READ_VAR(i, Time); return Time; } #ifdef POWER_LOSS_SAVE_TO_EEPROM bool b_PRE_Write_PLR_Done = false; void EEPROM_PRE_Write_PLR(uint32_t lFPos, int iBPos, int i_dual_x_carriage_mode, float f_duplicate_extruder_x_offset, float f_feedrate) { if (lFPos > 2048 && !b_PRE_Write_PLR_Done) { int i = 350; EEPROM_WRITE_VAR(i, iBPos); EEPROM_WRITE_VAR(i, i_dual_x_carriage_mode); EEPROM_WRITE_VAR(i, f_duplicate_extruder_x_offset); EEPROM_WRITE_VAR(i, f_feedrate); b_PRE_Write_PLR_Done = true; } else if (lFPos == 0) { b_PRE_Write_PLR_Done = false; } } void EEPROM_Write_PLR(uint32_t lFPos, int iTPos, int iTPos1, int iT01, float fZPos, float fEPos) { int i = 300; EEPROM_WRITE_VAR(i, lFPos); if (lFPos > 2048) { EEPROM_WRITE_VAR(i, iTPos); EEPROM_WRITE_VAR(i, iTPos1); EEPROM_WRITE_VAR(i, iT01); EEPROM_WRITE_VAR(i, fZPos); EEPROM_WRITE_VAR(i, fEPos); } } uint32_t EEPROM_Read_PLR_0() { uint32_t lFPos; int i = 300; EEPROM_READ_VAR(i, lFPos); return lFPos; } String EEPROM_Read_PLR() { String strRet = ""; uint32_t lFPos; int iTPos; int iTPos1; int iFanPos = 200; int iT01; int iBPos; float fZPos; float fEPos; float fXPos = 0.0; float fYPos = 0.0; int i_dual_x_carriage_mode; float f_duplicate_extruder_x_offset; float f_feedrate; int i = 300; EEPROM_READ_VAR(i, lFPos); EEPROM_READ_VAR(i, iTPos); EEPROM_READ_VAR(i, iTPos1); EEPROM_READ_VAR(i, iT01); EEPROM_READ_VAR(i, fZPos); EEPROM_READ_VAR(i, fEPos); i = 350; EEPROM_READ_VAR(i, iBPos); EEPROM_READ_VAR(i, i_dual_x_carriage_mode); EEPROM_READ_VAR(i, f_duplicate_extruder_x_offset); EEPROM_READ_VAR(i, f_feedrate); // 1FPos 2TPos 3TPos1 4T01 5ZPos 6EPos 7FanPos 8XPos 9YPos 10BPos 11DXCM 12DEXO 13Feedrate strRet = String(lFPos) + "|" + String(iTPos) + "|" + String(iTPos1) + "|" + String(iT01) + "|" + String(fZPos) + "|" + String(fEPos) + "|" + String(iFanPos) + "|" + String(fXPos) + "|" + String(fYPos) + "|" + String(iBPos) + "|" + String(i_dual_x_carriage_mode) + "|" + String(f_duplicate_extruder_x_offset) + "|" + String(f_feedrate); return strRet; } #endif //POWER_LOSS_SAVE_TO_EEPROM void Config_StoreSettings() { char ver[4] = "000"; int i = EEPROM_OFFSET; EEPROM_WRITE_VAR(i, ver); // invalidate data first EEPROM_WRITE_VAR(i, axis_steps_per_unit); EEPROM_WRITE_VAR(i, max_feedrate); EEPROM_WRITE_VAR(i, max_acceleration_units_per_sq_second); EEPROM_WRITE_VAR(i, acceleration); EEPROM_WRITE_VAR(i, retract_acceleration); EEPROM_WRITE_VAR(i, minimumfeedrate); EEPROM_WRITE_VAR(i, mintravelfeedrate); EEPROM_WRITE_VAR(i, minsegmenttime); EEPROM_WRITE_VAR(i, max_xy_jerk); EEPROM_WRITE_VAR(i, max_z_jerk); EEPROM_WRITE_VAR(i, max_e_jerk); EEPROM_WRITE_VAR(i, add_homeing); /* //#ifndef ULTIPANEL int plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP; int plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP; int plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED; int absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP; int absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP; int absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED; //#endif */ EEPROM_WRITE_VAR(i, plaPreheatHotendTemp); EEPROM_WRITE_VAR(i, plaPreheatHPBTemp); EEPROM_WRITE_VAR(i, plaPreheatFanSpeed); EEPROM_WRITE_VAR(i, absPreheatHotendTemp); EEPROM_WRITE_VAR(i, absPreheatHPBTemp); EEPROM_WRITE_VAR(i, absPreheatFanSpeed); #ifdef PIDTEMP EEPROM_WRITE_VAR(i, Kp); EEPROM_WRITE_VAR(i, Ki); EEPROM_WRITE_VAR(i, Kd); #else float dummy = 3000.0f; EEPROM_WRITE_VAR(i, dummy); dummy = 0.0f; EEPROM_WRITE_VAR(i, dummy); EEPROM_WRITE_VAR(i, dummy); #endif #ifdef CONFIG_TL EEPROM_WRITE_VAR(i, tl_X2_MAX_POS); //By Zyf #endif #ifdef CONFIG_E2_OFFSET EEPROM_WRITE_VAR(i, tl_Y2_OFFSET); //By Zyf EEPROM_WRITE_VAR(i, tl_Z2_OFFSET); //By Zyf #endif #ifdef FAN2_CONTROL EEPROM_WRITE_VAR(i, tl_FAN2_VALUE); //By Zyf EEPROM_WRITE_VAR(i, tl_FAN2_START_TEMP); //By Zyf #endif EEPROM_WRITE_VAR(i, languageID); //By Zyf #ifdef HAS_PLR_MODULE EEPROM_WRITE_VAR(i, tl_AUTO_OFF); //By Zyf #endif EEPROM_WRITE_VAR(i, tl_SLEEP_TIME); //By Zyf EEPROM_WRITE_VAR(i, tl_ECO_MODE); //By Zyf #ifdef CONFIG_TL //EEPROM_WRITE_VAR(i, tl_INVERT_X_DIR); //By Zyf //EEPROM_WRITE_VAR(i, tl_INVERT_Y_DIR); //By Zyf //rep_INVERT_Y_DIR = tl_INVERT_Y_DIR; //EEPROM_WRITE_VAR(i, tl_INVERT_Z_DIR); //By Zyf //EEPROM_WRITE_VAR(i, tl_INVERT_E0_DIR); //By Zyf //EEPROM_WRITE_VAR(i, tl_INVERT_E1_DIR); //By Zyf EEPROM_WRITE_VAR(i, tl_HEATER_0_MAXTEMP); //By Zyf EEPROM_WRITE_VAR(i, tl_HEATER_1_MAXTEMP); //By Zyf EEPROM_WRITE_VAR(i, tl_BED_MAXTEMP); //By Zyf #endif #ifdef FILAMENT_FAIL_DETECT EEPROM_WRITE_VAR(i, tl_Filament_Detect); #endif #ifndef DOGLCD int lcd_contrast = 32; #endif EEPROM_WRITE_VAR(i, lcd_contrast); char ver2[4] = EEPROM_VERSION; i = EEPROM_OFFSET; EEPROM_WRITE_VAR(i, ver2); // validate data SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Settings Stored"); } #endif //EEPROM_SETTINGS #ifdef EEPROM_CHITCHAT void Config_PrintSettings() { // Always have this function, even with EEPROM_SETTINGS disabled, the current values will be shown SERIAL_ECHO_START; SERIAL_ECHOPGM("Steps per unit:"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M92 X", axis_steps_per_unit[0]); SERIAL_ECHOPAIR(" Y", axis_steps_per_unit[1]); SERIAL_ECHOPAIR(" Z", axis_steps_per_unit[2]); SERIAL_ECHOPAIR(" E", axis_steps_per_unit[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Maximum feedrates (mm/s):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M203 X", max_feedrate[0]); SERIAL_ECHOPAIR(" Y", max_feedrate[1]); SERIAL_ECHOPAIR(" Z", max_feedrate[2]); SERIAL_ECHOPAIR(" E", max_feedrate[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Maximum Acceleration (mm/s2):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M201 X", max_acceleration_units_per_sq_second[0]); SERIAL_ECHOPAIR(" Y", max_acceleration_units_per_sq_second[1]); SERIAL_ECHOPAIR(" Z", max_acceleration_units_per_sq_second[2]); SERIAL_ECHOPAIR(" E", max_acceleration_units_per_sq_second[3]); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Acceleration: S=acceleration, T=retract acceleration"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M204 S", acceleration); SERIAL_ECHOPAIR(" T", retract_acceleration); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Advanced variables: S=Min feedrate (mm/s), T=Min travel feedrate (mm/s), B=minimum segment time (ms), X=maximum XY jerk (mm/s), Z=maximum Z jerk (mm/s), E=maximum E jerk (mm/s)"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M205 S", minimumfeedrate); SERIAL_ECHOPAIR(" T", mintravelfeedrate); SERIAL_ECHOPAIR(" B", minsegmenttime); SERIAL_ECHOPAIR(" X", max_xy_jerk); SERIAL_ECHOPAIR(" Z", max_z_jerk); SERIAL_ECHOPAIR(" E", max_e_jerk); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Home offset (mm):"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M206 X", add_homeing[0]); SERIAL_ECHOPAIR(" Y", add_homeing[1]); SERIAL_ECHOPAIR(" Z", add_homeing[2]); SERIAL_ECHOLN(""); #ifdef PIDTEMP SERIAL_ECHO_START; SERIAL_ECHOPGM("PID settings:"); SERIAL_ECHO_START; SERIAL_ECHOPAIR(" M301 P", Kp); SERIAL_ECHOPAIR(" I", unscalePID_i(Ki)); SERIAL_ECHOPAIR(" D", unscalePID_d(Kd)); SERIAL_ECHOLN(""); #endif #ifdef CONFIG_TL SERIAL_ECHO_START; SERIAL_ECHOPGM("Secondery Max Pos:"); SERIAL_ECHOPAIR("X2:", tl_X2_MAX_POS); SERIAL_ECHOLN(""); #endif #ifdef CONFIG_E2_OFFSET SERIAL_ECHO_START; SERIAL_ECHOPGM("Extender Offset:"); SERIAL_ECHOPAIR("Y2:", tl_Y2_OFFSET); SERIAL_ECHOLN(""); SERIAL_ECHO_START; SERIAL_ECHOPGM("Extender Offset:"); SERIAL_ECHOPAIR("Z2:", tl_Z2_OFFSET); SERIAL_ECHOLN(""); #endif #ifdef HAS_PLR_MODULE //TL_DEBUG_PRINT("Auto Power Off:"); //TL_DEBUG_PRINT_LN(tl_AUTO_OFF); //By Zyf #endif } #endif #ifdef EEPROM_SETTINGS void Config_RetrieveSettings() { int i = EEPROM_OFFSET; char stored_ver[4]; char ver[4] = EEPROM_VERSION; EEPROM_READ_VAR(i, stored_ver); //read stored version // SERIAL_ECHOLN("Version: [" << ver << "] Stored version: [" << stored_ver << "]"); if (strncmp(ver, stored_ver, 3) == 0) { // version number match EEPROM_READ_VAR(i, axis_steps_per_unit); EEPROM_READ_VAR(i, max_feedrate); EEPROM_READ_VAR(i, max_acceleration_units_per_sq_second); // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner) reset_acceleration_rates(); EEPROM_READ_VAR(i, acceleration); EEPROM_READ_VAR(i, retract_acceleration); EEPROM_READ_VAR(i, minimumfeedrate); EEPROM_READ_VAR(i, mintravelfeedrate); EEPROM_READ_VAR(i, minsegmenttime); EEPROM_READ_VAR(i, max_xy_jerk); EEPROM_READ_VAR(i, max_z_jerk); EEPROM_READ_VAR(i, max_e_jerk); EEPROM_READ_VAR(i, add_homeing); /* //#ifndef ULTIPANEL int plaPreheatHotendTemp, plaPreheatHPBTemp, plaPreheatFanSpeed; int absPreheatHotendTemp, absPreheatHPBTemp, absPreheatFanSpeed; //#endif */ EEPROM_READ_VAR(i, plaPreheatHotendTemp); EEPROM_READ_VAR(i, plaPreheatHPBTemp); EEPROM_READ_VAR(i, plaPreheatFanSpeed); EEPROM_READ_VAR(i, absPreheatHotendTemp); EEPROM_READ_VAR(i, absPreheatHPBTemp); EEPROM_READ_VAR(i, absPreheatFanSpeed); #ifndef PIDTEMP float Kp, Ki, Kd; #endif // do not need to scale PID values as the values in EEPROM are already scaled EEPROM_READ_VAR(i, Kp); EEPROM_READ_VAR(i, Ki); EEPROM_READ_VAR(i, Kd); #ifdef CONFIG_TL EEPROM_READ_VAR(i, tl_X2_MAX_POS); // by zyf #endif #ifdef CONFIG_E2_OFFSET EEPROM_READ_VAR(i, tl_Y2_OFFSET); // by zyf EEPROM_READ_VAR(i, tl_Z2_OFFSET); // by zyf #endif #ifdef FAN2_CONTROL EEPROM_READ_VAR(i, tl_FAN2_VALUE); // by zyf EEPROM_READ_VAR(i, tl_FAN2_START_TEMP); // by zyf #endif EEPROM_READ_VAR(i, languageID); // by zyf #ifdef HAS_PLR_MODULE EEPROM_READ_VAR(i, tl_AUTO_OFF); // by zyf #endif EEPROM_READ_VAR(i, tl_SLEEP_TIME); // by zyf EEPROM_READ_VAR(i, tl_ECO_MODE); // by zyf #ifdef CONFIG_TL /* EEPROM_READ_VAR(i, tl_INVERT_X_DIR); // by zyf EEPROM_READ_VAR(i, tl_INVERT_Y_DIR); // by zyf EEPROM_READ_VAR(i, tl_INVERT_Z_DIR); // by zyf EEPROM_READ_VAR(i, tl_INVERT_E0_DIR); // by zyf EEPROM_READ_VAR(i, tl_INVERT_E1_DIR); // by zyf */ #ifdef TL_DUAL_Z rep_INVERT_Y_DIR = INVERT_Y_DIR; #endif EEPROM_READ_VAR(i, tl_HEATER_0_MAXTEMP); // by zyf EEPROM_READ_VAR(i, tl_HEATER_1_MAXTEMP); // by zyf EEPROM_READ_VAR(i, tl_BED_MAXTEMP); // by zyf if (tl_HEATER_0_MAXTEMP < 250) tl_HEATER_0_MAXTEMP = 250; if (tl_HEATER_1_MAXTEMP < 250) tl_HEATER_1_MAXTEMP = 250; if (tl_BED_MAXTEMP < 80) tl_BED_MAXTEMP = 80; #endif #ifdef FILAMENT_FAIL_DETECT EEPROM_READ_VAR(i, tl_Filament_Detect); #endif #ifndef DOGLCD int lcd_contrast; #endif EEPROM_READ_VAR(i, lcd_contrast); // Call updatePID (similar to when we have processed M301) updatePID(); SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Stored settings retrieved"); } else { Config_ResetDefault(); } Config_PrintSettings(); } #endif void Config_ResetDefault() { float tmp1[] = DEFAULT_AXIS_STEPS_PER_UNIT; float tmp2[] = DEFAULT_MAX_FEEDRATE; long tmp3[] = DEFAULT_MAX_ACCELERATION; for (short i = 0; i < 4; i++) { axis_steps_per_unit[i] = tmp1[i]; max_feedrate[i] = tmp2[i]; max_acceleration_units_per_sq_second[i] = tmp3[i]; } // steps per sq second need to be updated to agree with the units per sq second reset_acceleration_rates(); acceleration = DEFAULT_ACCELERATION; retract_acceleration = DEFAULT_RETRACT_ACCELERATION; minimumfeedrate = DEFAULT_MINIMUMFEEDRATE; minsegmenttime = DEFAULT_MINSEGMENTTIME; mintravelfeedrate = DEFAULT_MINTRAVELFEEDRATE; max_xy_jerk = DEFAULT_XYJERK; max_z_jerk = DEFAULT_ZJERK; max_e_jerk = DEFAULT_EJERK; add_homeing[0] = add_homeing[1] = add_homeing[2] = 0; plaPreheatHotendTemp = PLA_PREHEAT_HOTEND_TEMP; plaPreheatHPBTemp = PLA_PREHEAT_HPB_TEMP; plaPreheatFanSpeed = PLA_PREHEAT_FAN_SPEED; absPreheatHotendTemp = ABS_PREHEAT_HOTEND_TEMP; absPreheatHPBTemp = ABS_PREHEAT_HPB_TEMP; absPreheatFanSpeed = ABS_PREHEAT_FAN_SPEED; #ifdef DOGLCD lcd_contrast = DEFAULT_LCD_CONTRAST; #endif #ifdef PIDTEMP Kp = DEFAULT_Kp; Ki = scalePID_i(DEFAULT_Ki); Kd = scalePID_d(DEFAULT_Kd); // call updatePID (similar to when we have processed M301) updatePID(); #ifdef PID_ADD_EXTRUSION_RATE Kc = DEFAULT_Kc; #endif //PID_ADD_EXTRUSION_RATE #endif //PIDTEMP #ifdef CONFIG_TL tl_X2_MAX_POS = X2_MAX_POS; /* tl_INVERT_X_DIR = INVERT_X_DIR; tl_INVERT_Y_DIR = INVERT_Y_DIR; tl_INVERT_Z_DIR = INVERT_Z_DIR; tl_INVERT_E0_DIR = INVERT_E0_DIR; tl_INVERT_E1_DIR = INVERT_E1_DIR; */ #ifdef TL_DUAL_Z rep_INVERT_Y_DIR = INVERT_Y_DIR; #endif tl_HEATER_0_MAXTEMP = HEATER_0_MAXTEMP; tl_HEATER_1_MAXTEMP = HEATER_1_MAXTEMP; tl_BED_MAXTEMP = BED_MAXTEMP; #endif #ifdef CONFIG_E2_OFFSET tl_Y2_OFFSET = 5.0; tl_Z2_OFFSET = 2.0; #endif #ifdef FAN2_CONTROL tl_FAN2_VALUE = 80; tl_FAN2_START_TEMP = 80; #endif languageID = 0; tl_ECO_MODE = 0; #ifdef FILAMENT_FAIL_DETECT tl_Filament_Detect = 1; #endif tl_SLEEP_TIME = 0; #ifdef HAS_PLR_MODULE tl_AUTO_OFF = 0; #endif SERIAL_ECHO_START; SERIAL_ECHOLNPGM("Hardcoded Default Settings Loaded"); Config_StoreSettings(); //By Zyf save after reset }
16,784
C++
.cpp
498
28.893574
339
0.641261
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,889
temperature.h
tenlog_TL-D3/Marlin/temperature.h
/* temperature.h - temperature controller Part of Marlin Copyright (c) 2011 Erik van der Zalm Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef temperature_h #define temperature_h #include "Marlin.h" #include "tl_touch_screen.h" #include "planner.h" #ifdef PID_ADD_EXTRUSION_RATE #include "stepper.h" #endif // public functions void tp_init(); //initialise the heating void manage_heater(); //it is critical that this is called periodically. // low level conversion routines // do not use these routines and variables outside of temperature.cpp extern int target_temperature[EXTRUDERS]; extern float current_temperature[EXTRUDERS]; extern int target_temperature_bed; extern float current_temperature_bed; #ifdef TEMP_SENSOR_1_AS_REDUNDANT extern float redundant_temperature; #endif #ifdef PIDTEMP extern float Kp, Ki, Kd, Kc; float scalePID_i(float i); float scalePID_d(float d); float unscalePID_i(float i); float unscalePID_d(float d); #endif #ifdef PIDTEMPBED extern float bedKp, bedKi, bedKd; #endif //high level conversion routines, for use outside of temperature.cpp //inline so that there is no performance decrease. //deg=degreeCelsius FORCE_INLINE float degHotend(uint8_t extruder) { return current_temperature[extruder]; }; FORCE_INLINE float degBed() { return current_temperature_bed; }; FORCE_INLINE float degTargetHotend(uint8_t extruder) { return target_temperature[extruder]; }; FORCE_INLINE float degTargetBed() { return target_temperature_bed; }; FORCE_INLINE void setTargetHotend(const float &celsius, uint8_t extruder) { if (extruder == 0) { if (celsius > tl_HEATER_0_MAXTEMP) return; } else if (extruder == 1) { if (celsius > tl_HEATER_1_MAXTEMP) return; } target_temperature[extruder] = celsius; }; FORCE_INLINE void setTargetBed(const float &celsius) { if (celsius < tl_BED_MAXTEMP + 1) target_temperature_bed = celsius; }; FORCE_INLINE bool isHeatingHotend(uint8_t extruder) { return target_temperature[extruder] > current_temperature[extruder]; }; FORCE_INLINE bool isHeatingBed() { return target_temperature_bed > current_temperature_bed; }; FORCE_INLINE bool isCoolingHotend(uint8_t extruder) { return target_temperature[extruder] < current_temperature[extruder]; }; FORCE_INLINE bool isCoolingBed() { return target_temperature_bed < current_temperature_bed; }; #define degHotend0() degHotend(0) #define degTargetHotend0() degTargetHotend(0) #define setTargetHotend0(_celsius) setTargetHotend((_celsius), 0) #define isHeatingHotend0() isHeatingHotend(0) #define isCoolingHotend0() isCoolingHotend(0) #if EXTRUDERS > 1 #define degHotend1() degHotend(1) #define degTargetHotend1() degTargetHotend(1) #define setTargetHotend1(_celsius) setTargetHotend((_celsius), 1) #define isHeatingHotend1() isHeatingHotend(1) #define isCoolingHotend1() isCoolingHotend(1) #else #define setTargetHotend1(_celsius) \ do \ { \ } while (0) #endif #if EXTRUDERS > 2 #define degHotend2() degHotend(2) #define degTargetHotend2() degTargetHotend(2) #define setTargetHotend2(_celsius) setTargetHotend((_celsius), 2) #define isHeatingHotend2() isHeatingHotend(2) #define isCoolingHotend2() isCoolingHotend(2) #else #define setTargetHotend2(_celsius) \ do \ { \ } while (0) #endif #if EXTRUDERS > 3 #error Invalid number of extruders #endif int getHeaterPower(int heater); void disable_heater(); void setWatch(); void updatePID(); FORCE_INLINE void autotempShutdown() { #ifdef AUTOTEMP if (autotemp_enabled) { autotemp_enabled = false; if (degTargetHotend(active_extruder) > autotemp_min) setTargetHotend(0, active_extruder); } #endif } void PID_autotune(float temp, int extruder, int ncycles); #endif
4,472
C++
.h
148
27.837838
73
0.748138
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,532,891
pins.h
tenlog_TL-D3/Marlin/pins.h
#ifndef PINS_H #define PINS_H #define X_MS1_PIN -1 #define X_MS2_PIN -1 #define Y_MS1_PIN -1 #define Y_MS2_PIN -1 #define Z_MS1_PIN -1 #define Z_MS2_PIN -1 #define E0_MS1_PIN -1 #define E0_MS2_PIN -1 #define E1_MS1_PIN -1 #define E1_MS2_PIN -1 #define DIGIPOTSS_PIN -1 /**************************************************************************************** * Arduino Mega pin assignment * ****************************************************************************************/ #define KNOWN_BOARD 1 //////////////////FIX THIS////////////// #ifndef __AVR_ATmega1280__ #ifndef __AVR_ATmega2560__ #error Oops! Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu. #endif #endif // uncomment one of the following lines for RAMPS v1.3 or v1.0, comment both for v1.2 or 1.1 // #define RAMPS_V_1_3 // #define RAMPS_V_1_0 #define LARGE_FLASH true #define X_STEP_PIN 54 #define X_DIR_PIN 55 #define X_ENABLE_PIN 38 #define X_MIN_PIN 3 #define X_MAX_PIN 2 //Ori 2 By zyf #define Y_STEP_PIN 60 #define Y_DIR_PIN 61 #define Y_ENABLE_PIN 56 #define Y_MIN_PIN 14 //Ori 14 by zyf #define Y_MAX_PIN -1 //15 #define Z_STEP_PIN 46 #define Z_DIR_PIN 48 #define Z_ENABLE_PIN 62 #define Z_MIN_PIN 18 //#define Z_MAX_PIN 19 #ifdef TL_DUAL_Z //By Zyf #define Z2_STEP_PIN 65 #define Z2_DIR_PIN 66 #define Z2_ENABLE_PIN 64 #define Z2_MIN_PIN 19 #endif #ifdef P2P1 #define E1_STEP_PIN 26 #define E1_DIR_PIN 28 #define E1_ENABLE_PIN 24 #define E0_STEP_PIN 57 #define E0_DIR_PIN 58 #define E0_ENABLE_PIN 59 #else #define E0_STEP_PIN 26 #define E0_DIR_PIN 28 #define E0_ENABLE_PIN 24 #define E1_STEP_PIN 57 #define E1_DIR_PIN 58 #define E1_ENABLE_PIN 59 #endif #define SDPOWER -1 #define SDSS 53 #define LED_PIN 13 #define FAN_PIN 9 // (Sprinter config) #define PS_ON_PIN 40 //zyf 40 //PF1 #if defined(POWER_LOSS_RECOVERY) #ifdef HAS_PLR_MODULE #define POWER_LOSS_DETECT_PIN 32 //zyf 32 //PF2 #else #define POWER_LOSS_DETECT_PIN 32 #endif #else #define POWER_LOSS_DETECT_PIN -1 #endif //POWER_LOSS_RECOVERY #define HEATER_2_PIN -1 #define TEMP_2_PIN -1 // ANALOG NUMBERING #ifdef P2P1 #ifdef ELECTROMAGNETIC_VALVE #define HEATER_1_PIN -1 #define HEATER_0_PIN -1 #define ELECTROMAGNETIC_VALVE_1_PIN 10 #define ELECTROMAGNETIC_VALVE_0_PIN 11 #else #define HEATER_1_PIN 10 #define HEATER_0_PIN 11 #endif #ifdef MIX_COLOR_TEST #define TEMP_1_PIN 15 // ANALOG NUMBERING #else #define TEMP_1_PIN 13 //13 ANALOG NUMBERING #endif #define TEMP_0_PIN 15 //15 by zyf // ANALOG NUMBERING #else #define HEATER_0_PIN 10 #define HEATER_1_PIN 11 #define TEMP_0_PIN 13 // ANALOG NUMBERING #define TEMP_1_PIN 15 //15 by zyf // ANALOG NUMBERING #endif #define HEATER_BED_PIN 8 // by zyf // BED #define TEMP_BED_PIN 14 // by zyf // ANALOG NUMBERING //14 #ifdef NUM_SERVOS #define SERVO0_PIN 11 #if NUM_SERVOS > 1 #define SERVO1_PIN 6 #endif #if NUM_SERVOS > 2 #define SERVO2_PIN 5 #endif #if NUM_SERVOS > 3 #define SERVO3_PIN 4 #endif #endif #define BEEPER 23 #define BEEPER_OFF LOW #define BEEPER_ON HIGH #define LCD_PINS_RS -1 #define LCD_PINS_ENABLE -1 #define LCD_PINS_D4 -1 #define LCD_PINS_D5 -1 #define LCD_PINS_D6 -1 #define LCD_PINS_D7 -1 #define SDCARDDETECT 49 #ifndef SDSUPPORT // these pins are defined in the SD library if building with SD support #define MAX_SCK_PIN 52 #define MAX_MISO_PIN 50 #define MAX_MOSI_PIN 51 #define MAX6675_SS 53 #else #define MAX6675_SS 49 #endif #ifndef KNOWN_BOARD #error Unknown MOTHERBOARD value in configuration.h #endif //List of pins which to ignore when asked to change by gcode, 0 and 1 are RX and TX, do not mess with those! #define _E0_PINS E0_STEP_PIN, E0_DIR_PIN, E0_ENABLE_PIN, HEATER_0_PIN, #if EXTRUDERS > 1 #define _E1_PINS E1_STEP_PIN, E1_DIR_PIN, E1_ENABLE_PIN, HEATER_1_PIN, #else #define _E1_PINS #endif #if EXTRUDERS > 2 #define _E2_PINS E2_STEP_PIN, E2_DIR_PIN, E2_ENABLE_PIN, HEATER_2_PIN, #else #define _E2_PINS #endif #ifdef X_STOP_PIN #if X_HOME_DIR < 0 #define X_MIN_PIN X_STOP_PIN #define X_MAX_PIN -1 #else #define X_MIN_PIN -1 #define X_MAX_PIN X_STOP_PIN #endif #endif #ifdef Y_STOP_PIN #if Y_HOME_DIR < 0 #define Y_MIN_PIN Y_STOP_PIN #define Y_MAX_PIN -1 #else #define Y_MIN_PIN -1 #define Y_MAX_PIN Y_STOP_PIN #endif #endif #ifdef Z_STOP_PIN #if Z_HOME_DIR < 0 #define Z_MIN_PIN Z_STOP_PIN #define Z_MAX_PIN -1 #else #define Z_MIN_PIN -1 #define Z_MAX_PIN Z_STOP_PIN #endif #endif #ifdef DISABLE_MAX_ENDSTOPS #define X_MAX_PIN -1 #define Y_MAX_PIN -1 #define Z_MAX_PIN -1 #endif #ifdef DISABLE_X_MAX_ENDSTOPS #define X_MAX_PIN -1 #endif #ifdef DISABLE_Y_MAX_ENDSTOPS #define Y_MAX_PIN -1 #endif #ifdef DISABLE_Z_MAX_ENDSTOPS #define Z_MAX_PIN -1 #endif #ifdef DISABLE_MIN_ENDSTOPS #define X_MIN_PIN -1 #define Y_MIN_PIN -1 #define Z_MIN_PIN -1 #endif #define SENSITIVE_PINS \ { \ 0, 1, X_STEP_PIN, X_DIR_PIN, X_ENABLE_PIN, X_MIN_PIN, X_MAX_PIN, Y_STEP_PIN, Y_DIR_PIN, Y_ENABLE_PIN, Y_MIN_PIN, Y_MAX_PIN, Z_STEP_PIN, Z_DIR_PIN, Z_ENABLE_PIN, Z_MIN_PIN, Z_MAX_PIN, PS_ON_PIN, \ HEATER_BED_PIN, FAN_PIN, \ _E0_PINS _E1_PINS _E2_PINS \ analogInputToDigitalPin(TEMP_0_PIN), \ analogInputToDigitalPin(TEMP_1_PIN), analogInputToDigitalPin(TEMP_2_PIN), analogInputToDigitalPin(TEMP_BED_PIN) \ } #endif
6,513
C++
.h
205
28.229268
204
0.571222
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,892
ConfigurationStore.h
tenlog_TL-D3/Marlin/ConfigurationStore.h
#ifndef CONFIG_STORE_H #define CONFIG_STORE_H #include "Configuration.h" void Config_ResetDefault(); #ifdef EEPROM_CHITCHAT void Config_PrintSettings(); #else FORCE_INLINE void Config_PrintSettings() { } #endif #ifdef EEPROM_SETTINGS void Config_StoreSettings(); void Config_RetrieveSettings(); #ifdef POWER_LOSS_SAVE_TO_EEPROM void EEPROM_Write_PLR(uint32_t lFPos = 0, int iTPos = 0, int iTPos1 = 0, int iT01 = 0, float fZPos = 0.0, float fEPos = 0.0); void EEPROM_PRE_Write_PLR(uint32_t lFPos = 0, int iBPos = 0, int i_dual_x_carriage_mode = 0, float f_duplicate_extruder_x_offset = 0.0, float f_feedrate = 0.0); uint32_t EEPROM_Read_PLR_0(); String EEPROM_Read_PLR(); #endif //POWER_LOSS_SAVE_TO_EEPROM #else FORCE_INLINE void Config_StoreSettings() { } FORCE_INLINE void Config_RetrieveSettings() { Config_ResetDefault(); Config_PrintSettings(); } #endif void EEPROM_Write_Last_Z(float Z, float Y, int DXCMode, long lTime); float EEPROM_Read_Last_Z(); float EEPROM_Read_Last_Y(); int EEPROM_Read_Last_Mode(); long EEPROM_Read_Last_Time(); #endif //CONFIG_STORE_H
1,161
C++
.h
36
28.638889
168
0.703307
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,893
Configuration.h
tenlog_TL-D3/Marlin/Configuration.h
#ifndef CONFIGURATION_H #define CONFIGURATION_H #include "Configuration_tenlog.h" #include "Configuration_xy.h" #include "Configuration_adv.h" #include "thermistortables.h" #endif //__CONFIGURATION_H
204
C++
.h
7
27.571429
33
0.813472
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,895
tl_touch_screen.h
tenlog_TL-D3/Marlin/tl_touch_screen.h
#ifndef TL_TOUCH_SCREEN_H #define TL_TOUCH_SCREEN_H #include "Arduino.h" //Setting for DWIN touch screen #define DWN_P_LOADING 21 #define DWN_P_MAIN 41 #define DWN_P_TOOLS 43 #define DWN_P_ABOUT 31 #define DWN_P_SETTING_MAIN 45 #define DWN_P_SETTING_PRINTING 69 #define DWN_P_MOVE 47 #define DWN_P_SEL_Z_FILE 49 #define DWN_P_SEL_FILE 70 #define DWN_P_PRINTING 0x33 #define DWN_P_TEMP 53 #define DWN_P_MODE 57 #define DWN_P_RELOAD 59 #define DWN_P_SHUTDOWN 61 #define DWN_P_PRINTZ 63 #define DWN_P_MSGBOX 14 #define DWN_TXT_VERSION 0x10 #define DWN_TXT_LOADING 0x00 #define DWN_TXT_FILE0 0x51 #define DWN_TXT_PRINTFILE 0x20 #define DWN_TXT_PERCENT 0x21 #define DWN_LED_ON 74 #define DWN_LED_OFF 03 #define DWN_LED_TIMEOUT 300 #define MSG_START_PRINT 0 #define MSG_PRINT_FINISHED 1 #define MSG_POWER_OFF 2 #define MSG_POWER_LOSS_DETECTED 3 #define MSG_RESET_DEFALT 4 #define MSG_STOP_PRINT 5 #define MSG_FILAMENT_RUNOUT 6 #define MSG_INPUT_Z_HEIGHT 7 #define MSG_NOZZLE_HEATING_ERROR 8 #define MSG_NOZZLE_HIGH_TEMP_ERROR 9 #define MSG_NOZZLE_LOW_TEMP_ERROR 10 #define MSG_BED_HIGH_TEMP_ERROR 11 #define MSG_BED_LOW_TEMP_ERROR 12 void tenlog_status_screen(); void TenlogScreen_begin(const long boud); void TenlogScreen_end(); void DWN_MessageBoxHandler(bool ISOK); void DWN_LED(int LED) ; void DWN_Get_Ver(); void DWN_Page(int ID); void DWN_Text(long ID, int Len, String s, bool Center = false); void DWN_Language(int ID); void DWN_Data(long ID, long Data, int DataLen); void process_command_dwn(); void DWN_Message(int MsgID, String sMsg, bool PowerOff); void DWN_NORFData(long NorID, long ID, int Lenth, bool WR); void DWN_RData(long ID, int DataLen); void DWN_VClick(int X, int Y); void tenlog_screen_update_dwn(); void tenlog_screen_update_tjc(); void Init_TLScreen_tjc(); void Init_TLScreen_dwn(); void CheckTempError_tjc(); void TLSTJC_println(const char s[]); void TLSTJC_printconstln(const String s); void TLSTJC_printconst(const String s); void TLSTJC_print(const char s[]); void TLSTJC_printend(); void TLSTJC_printEmptyend(); void get_command_dwn(); void get_command_tjc(); void get_command(); void process_commands(); void manage_inactivity(); void sdcard_tlcontroller_tjc(); void sdcard_tlcontroller_dwn(); extern int i_print_page_id; extern bool b_is_last_page; extern String file_name_list[6]; extern String file_name_long_list[6]; extern int iDWNPageID; static float feedrate = 1500.0, next_feedrate, saved_feedrate; extern int iPrintID; extern String gsM117; extern String gsPrinting; extern long dwn_command[255]; extern bool bLogoGot; extern int tenlog_status_update_delay; extern int tenlogScreenUpdate; extern int iBeepCount ; extern bool b_PLR_MODULE_Detected ; extern int iMoveRate ; extern bool bInited ; extern bool bHeatingStop ; extern bool bAtvGot0 ; extern bool bAtvGot1; extern bool bAtv; extern int iOldLogoID; extern long lAtvCode; #endif //TL_TOUCH_SCREEN_H
2,910
C++
.h
98
28.479592
63
0.792189
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,896
Sd2PinMap.h
tenlog_TL-D3/Marlin/Sd2PinMap.h
/* Arduino SdFat Library * Copyright (C) 2010 by William Greiman * * This file is part of the Arduino SdFat Library * * This Library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Arduino SdFat Library. If not, see * <http://www.gnu.org/licenses/>. */ // Warning this file was generated by a program. #include "Marlin.h" #ifdef SDSUPPORT #ifndef Sd2PinMap_h #define Sd2PinMap_h #include <avr/io.h> //------------------------------------------------------------------------------ /** struct for mapping digital pins */ struct pin_map_t { volatile uint8_t *ddr; volatile uint8_t *pin; volatile uint8_t *port; uint8_t bit; }; //------------------------------------------------------------------------------ #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) // Mega // Two Wire (aka I2C) ports uint8_t const SDA_PIN = 20; // D1 uint8_t const SCL_PIN = 21; // D0 #undef MOSI_PIN #undef MISO_PIN // SPI port uint8_t const SS_PIN = 53; // B0 uint8_t const MOSI_PIN = 51; // B2 uint8_t const MISO_PIN = 50; // B3 uint8_t const SCK_PIN = 52; // B1 static const pin_map_t digitalPinMap[] = { {&DDRE, &PINE, &PORTE, 0}, // E0 0 {&DDRE, &PINE, &PORTE, 1}, // E1 1 {&DDRE, &PINE, &PORTE, 4}, // E4 2 {&DDRE, &PINE, &PORTE, 5}, // E5 3 {&DDRG, &PING, &PORTG, 5}, // G5 4 {&DDRE, &PINE, &PORTE, 3}, // E3 5 {&DDRH, &PINH, &PORTH, 3}, // H3 6 {&DDRH, &PINH, &PORTH, 4}, // H4 7 {&DDRH, &PINH, &PORTH, 5}, // H5 8 {&DDRH, &PINH, &PORTH, 6}, // H6 9 {&DDRB, &PINB, &PORTB, 4}, // B4 10 {&DDRB, &PINB, &PORTB, 5}, // B5 11 {&DDRB, &PINB, &PORTB, 6}, // B6 12 {&DDRB, &PINB, &PORTB, 7}, // B7 13 {&DDRJ, &PINJ, &PORTJ, 1}, // J1 14 {&DDRJ, &PINJ, &PORTJ, 0}, // J0 15 {&DDRH, &PINH, &PORTH, 1}, // H1 16 {&DDRH, &PINH, &PORTH, 0}, // H0 17 {&DDRD, &PIND, &PORTD, 3}, // D3 18 {&DDRD, &PIND, &PORTD, 2}, // D2 19 {&DDRD, &PIND, &PORTD, 1}, // D1 20 {&DDRD, &PIND, &PORTD, 0}, // D0 21 {&DDRA, &PINA, &PORTA, 0}, // A0 22 {&DDRA, &PINA, &PORTA, 1}, // A1 23 {&DDRA, &PINA, &PORTA, 2}, // A2 24 {&DDRA, &PINA, &PORTA, 3}, // A3 25 {&DDRA, &PINA, &PORTA, 4}, // A4 26 {&DDRA, &PINA, &PORTA, 5}, // A5 27 {&DDRA, &PINA, &PORTA, 6}, // A6 28 {&DDRA, &PINA, &PORTA, 7}, // A7 29 {&DDRC, &PINC, &PORTC, 7}, // C7 30 {&DDRC, &PINC, &PORTC, 6}, // C6 31 {&DDRC, &PINC, &PORTC, 5}, // C5 32 {&DDRC, &PINC, &PORTC, 4}, // C4 33 {&DDRC, &PINC, &PORTC, 3}, // C3 34 {&DDRC, &PINC, &PORTC, 2}, // C2 35 {&DDRC, &PINC, &PORTC, 1}, // C1 36 {&DDRC, &PINC, &PORTC, 0}, // C0 37 {&DDRD, &PIND, &PORTD, 7}, // D7 38 {&DDRG, &PING, &PORTG, 2}, // G2 39 {&DDRG, &PING, &PORTG, 1}, // G1 40 {&DDRG, &PING, &PORTG, 0}, // G0 41 {&DDRL, &PINL, &PORTL, 7}, // L7 42 {&DDRL, &PINL, &PORTL, 6}, // L6 43 {&DDRL, &PINL, &PORTL, 5}, // L5 44 {&DDRL, &PINL, &PORTL, 4}, // L4 45 {&DDRL, &PINL, &PORTL, 3}, // L3 46 {&DDRL, &PINL, &PORTL, 2}, // L2 47 {&DDRL, &PINL, &PORTL, 1}, // L1 48 {&DDRL, &PINL, &PORTL, 0}, // L0 49 {&DDRB, &PINB, &PORTB, 3}, // B3 50 {&DDRB, &PINB, &PORTB, 2}, // B2 51 {&DDRB, &PINB, &PORTB, 1}, // B1 52 {&DDRB, &PINB, &PORTB, 0}, // B0 53 {&DDRF, &PINF, &PORTF, 0}, // F0 54 {&DDRF, &PINF, &PORTF, 1}, // F1 55 {&DDRF, &PINF, &PORTF, 2}, // F2 56 {&DDRF, &PINF, &PORTF, 3}, // F3 57 {&DDRF, &PINF, &PORTF, 4}, // F4 58 {&DDRF, &PINF, &PORTF, 5}, // F5 59 {&DDRF, &PINF, &PORTF, 6}, // F6 60 {&DDRF, &PINF, &PORTF, 7}, // F7 61 {&DDRK, &PINK, &PORTK, 0}, // K0 62 {&DDRK, &PINK, &PORTK, 1}, // K1 63 {&DDRK, &PINK, &PORTK, 2}, // K2 64 {&DDRK, &PINK, &PORTK, 3}, // K3 65 {&DDRK, &PINK, &PORTK, 4}, // K4 66 {&DDRK, &PINK, &PORTK, 5}, // K5 67 {&DDRK, &PINK, &PORTK, 6}, // K6 68 {&DDRK, &PINK, &PORTK, 7} // K7 69 }; //------------------------------------------------------------------------------ #elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega1284P__) // Sanguino // Two Wire (aka I2C) ports uint8_t const SDA_PIN = 17; // C1 uint8_t const SCL_PIN = 18; // C2 // SPI port uint8_t const SS_PIN = 4; // B4 uint8_t const MOSI_PIN = 5; // B5 uint8_t const MISO_PIN = 6; // B6 uint8_t const SCK_PIN = 7; // B7 static const pin_map_t digitalPinMap[] = { {&DDRB, &PINB, &PORTB, 0}, // B0 0 {&DDRB, &PINB, &PORTB, 1}, // B1 1 {&DDRB, &PINB, &PORTB, 2}, // B2 2 {&DDRB, &PINB, &PORTB, 3}, // B3 3 {&DDRB, &PINB, &PORTB, 4}, // B4 4 {&DDRB, &PINB, &PORTB, 5}, // B5 5 {&DDRB, &PINB, &PORTB, 6}, // B6 6 {&DDRB, &PINB, &PORTB, 7}, // B7 7 {&DDRD, &PIND, &PORTD, 0}, // D0 8 {&DDRD, &PIND, &PORTD, 1}, // D1 9 {&DDRD, &PIND, &PORTD, 2}, // D2 10 {&DDRD, &PIND, &PORTD, 3}, // D3 11 {&DDRD, &PIND, &PORTD, 4}, // D4 12 {&DDRD, &PIND, &PORTD, 5}, // D5 13 {&DDRD, &PIND, &PORTD, 6}, // D6 14 {&DDRD, &PIND, &PORTD, 7}, // D7 15 {&DDRC, &PINC, &PORTC, 0}, // C0 16 {&DDRC, &PINC, &PORTC, 1}, // C1 17 {&DDRC, &PINC, &PORTC, 2}, // C2 18 {&DDRC, &PINC, &PORTC, 3}, // C3 19 {&DDRC, &PINC, &PORTC, 4}, // C4 20 {&DDRC, &PINC, &PORTC, 5}, // C5 21 {&DDRC, &PINC, &PORTC, 6}, // C6 22 {&DDRC, &PINC, &PORTC, 7}, // C7 23 {&DDRA, &PINA, &PORTA, 7}, // A7 24 {&DDRA, &PINA, &PORTA, 6}, // A6 25 {&DDRA, &PINA, &PORTA, 5}, // A5 26 {&DDRA, &PINA, &PORTA, 4}, // A4 27 {&DDRA, &PINA, &PORTA, 3}, // A3 28 {&DDRA, &PINA, &PORTA, 2}, // A2 29 {&DDRA, &PINA, &PORTA, 1}, // A1 30 {&DDRA, &PINA, &PORTA, 0} // A0 31 }; //------------------------------------------------------------------------------ #elif defined(__AVR_ATmega32U4__) // Teensy 2.0 // Two Wire (aka I2C) ports uint8_t const SDA_PIN = 6; // D1 uint8_t const SCL_PIN = 5; // D0 // SPI port uint8_t const SS_PIN = 0; // B0 uint8_t const MOSI_PIN = 2; // B2 uint8_t const MISO_PIN = 3; // B3 uint8_t const SCK_PIN = 1; // B1 static const pin_map_t digitalPinMap[] = { {&DDRB, &PINB, &PORTB, 0}, // B0 0 {&DDRB, &PINB, &PORTB, 1}, // B1 1 {&DDRB, &PINB, &PORTB, 2}, // B2 2 {&DDRB, &PINB, &PORTB, 3}, // B3 3 {&DDRB, &PINB, &PORTB, 7}, // B7 4 {&DDRD, &PIND, &PORTD, 0}, // D0 5 {&DDRD, &PIND, &PORTD, 1}, // D1 6 {&DDRD, &PIND, &PORTD, 2}, // D2 7 {&DDRD, &PIND, &PORTD, 3}, // D3 8 {&DDRC, &PINC, &PORTC, 6}, // C6 9 {&DDRC, &PINC, &PORTC, 7}, // C7 10 {&DDRD, &PIND, &PORTD, 6}, // D6 11 {&DDRD, &PIND, &PORTD, 7}, // D7 12 {&DDRB, &PINB, &PORTB, 4}, // B4 13 {&DDRB, &PINB, &PORTB, 5}, // B5 14 {&DDRB, &PINB, &PORTB, 6}, // B6 15 {&DDRF, &PINF, &PORTF, 7}, // F7 16 {&DDRF, &PINF, &PORTF, 6}, // F6 17 {&DDRF, &PINF, &PORTF, 5}, // F5 18 {&DDRF, &PINF, &PORTF, 4}, // F4 19 {&DDRF, &PINF, &PORTF, 1}, // F1 20 {&DDRF, &PINF, &PORTF, 0}, // F0 21 {&DDRD, &PIND, &PORTD, 4}, // D4 22 {&DDRD, &PIND, &PORTD, 5}, // D5 23 {&DDRE, &PINE, &PORTE, 6} // E6 24 }; //------------------------------------------------------------------------------ #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) // Teensy++ 1.0 & 2.0 // Two Wire (aka I2C) ports uint8_t const SDA_PIN = 1; // D1 uint8_t const SCL_PIN = 0; // D0 // SPI port uint8_t const SS_PIN = 20; // B0 uint8_t const MOSI_PIN = 22; // B2 uint8_t const MISO_PIN = 23; // B3 uint8_t const SCK_PIN = 21; // B1 static const pin_map_t digitalPinMap[] = { {&DDRD, &PIND, &PORTD, 0}, // D0 0 {&DDRD, &PIND, &PORTD, 1}, // D1 1 {&DDRD, &PIND, &PORTD, 2}, // D2 2 {&DDRD, &PIND, &PORTD, 3}, // D3 3 {&DDRD, &PIND, &PORTD, 4}, // D4 4 {&DDRD, &PIND, &PORTD, 5}, // D5 5 {&DDRD, &PIND, &PORTD, 6}, // D6 6 {&DDRD, &PIND, &PORTD, 7}, // D7 7 {&DDRE, &PINE, &PORTE, 0}, // E0 8 {&DDRE, &PINE, &PORTE, 1}, // E1 9 {&DDRC, &PINC, &PORTC, 0}, // C0 10 {&DDRC, &PINC, &PORTC, 1}, // C1 11 {&DDRC, &PINC, &PORTC, 2}, // C2 12 {&DDRC, &PINC, &PORTC, 3}, // C3 13 {&DDRC, &PINC, &PORTC, 4}, // C4 14 {&DDRC, &PINC, &PORTC, 5}, // C5 15 {&DDRC, &PINC, &PORTC, 6}, // C6 16 {&DDRC, &PINC, &PORTC, 7}, // C7 17 {&DDRE, &PINE, &PORTE, 6}, // E6 18 {&DDRE, &PINE, &PORTE, 7}, // E7 19 {&DDRB, &PINB, &PORTB, 0}, // B0 20 {&DDRB, &PINB, &PORTB, 1}, // B1 21 {&DDRB, &PINB, &PORTB, 2}, // B2 22 {&DDRB, &PINB, &PORTB, 3}, // B3 23 {&DDRB, &PINB, &PORTB, 4}, // B4 24 {&DDRB, &PINB, &PORTB, 5}, // B5 25 {&DDRB, &PINB, &PORTB, 6}, // B6 26 {&DDRB, &PINB, &PORTB, 7}, // B7 27 {&DDRA, &PINA, &PORTA, 0}, // A0 28 {&DDRA, &PINA, &PORTA, 1}, // A1 29 {&DDRA, &PINA, &PORTA, 2}, // A2 30 {&DDRA, &PINA, &PORTA, 3}, // A3 31 {&DDRA, &PINA, &PORTA, 4}, // A4 32 {&DDRA, &PINA, &PORTA, 5}, // A5 33 {&DDRA, &PINA, &PORTA, 6}, // A6 34 {&DDRA, &PINA, &PORTA, 7}, // A7 35 {&DDRE, &PINE, &PORTE, 4}, // E4 36 {&DDRE, &PINE, &PORTE, 5}, // E5 37 {&DDRF, &PINF, &PORTF, 0}, // F0 38 {&DDRF, &PINF, &PORTF, 1}, // F1 39 {&DDRF, &PINF, &PORTF, 2}, // F2 40 {&DDRF, &PINF, &PORTF, 3}, // F3 41 {&DDRF, &PINF, &PORTF, 4}, // F4 42 {&DDRF, &PINF, &PORTF, 5}, // F5 43 {&DDRF, &PINF, &PORTF, 6}, // F6 44 {&DDRF, &PINF, &PORTF, 7} // F7 45 }; //------------------------------------------------------------------------------ #elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || defined(__AVR_ATmega328P__) // 168 and 328 Arduinos // Two Wire (aka I2C) ports uint8_t const SDA_PIN = 18; // C4 uint8_t const SCL_PIN = 19; // C5 // SPI port uint8_t const SS_PIN = 10; // B2 uint8_t const MOSI_PIN = 11; // B3 uint8_t const MISO_PIN = 12; // B4 uint8_t const SCK_PIN = 13; // B5 static const pin_map_t digitalPinMap[] = { {&DDRD, &PIND, &PORTD, 0}, // D0 0 {&DDRD, &PIND, &PORTD, 1}, // D1 1 {&DDRD, &PIND, &PORTD, 2}, // D2 2 {&DDRD, &PIND, &PORTD, 3}, // D3 3 {&DDRD, &PIND, &PORTD, 4}, // D4 4 {&DDRD, &PIND, &PORTD, 5}, // D5 5 {&DDRD, &PIND, &PORTD, 6}, // D6 6 {&DDRD, &PIND, &PORTD, 7}, // D7 7 {&DDRB, &PINB, &PORTB, 0}, // B0 8 {&DDRB, &PINB, &PORTB, 1}, // B1 9 {&DDRB, &PINB, &PORTB, 2}, // B2 10 {&DDRB, &PINB, &PORTB, 3}, // B3 11 {&DDRB, &PINB, &PORTB, 4}, // B4 12 {&DDRB, &PINB, &PORTB, 5}, // B5 13 {&DDRC, &PINC, &PORTC, 0}, // C0 14 {&DDRC, &PINC, &PORTC, 1}, // C1 15 {&DDRC, &PINC, &PORTC, 2}, // C2 16 {&DDRC, &PINC, &PORTC, 3}, // C3 17 {&DDRC, &PINC, &PORTC, 4}, // C4 18 {&DDRC, &PINC, &PORTC, 5} // C5 19 }; #else // defined(__AVR_ATmega1280__) #error unknown chip #endif // defined(__AVR_ATmega1280__) //------------------------------------------------------------------------------ static const uint8_t digitalPinCount = sizeof(digitalPinMap) / sizeof(pin_map_t); uint8_t badPinNumber(void) __attribute__((error("Pin number is too large or not a constant"))); static inline __attribute__((always_inline)) bool getPinMode(uint8_t pin) { if (__builtin_constant_p(pin) && pin < digitalPinCount) { return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1; } else { return badPinNumber(); } } static inline __attribute__((always_inline)) void setPinMode(uint8_t pin, uint8_t mode) { if (__builtin_constant_p(pin) && pin < digitalPinCount) { if (mode) { *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit; } else { *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit); } } else { badPinNumber(); } } static inline __attribute__((always_inline)) bool fastDigitalRead(uint8_t pin) { if (__builtin_constant_p(pin) && pin < digitalPinCount) { return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1; } else { return badPinNumber(); } } static inline __attribute__((always_inline)) void fastDigitalWrite(uint8_t pin, uint8_t value) { if (__builtin_constant_p(pin) && pin < digitalPinCount) { if (value) { *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit; } else { *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit); } } else { badPinNumber(); } } #endif // Sd2PinMap_h #endif
13,257
C++
.h
361
32.00277
96
0.498172
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,897
Configuration_adv.h
tenlog_TL-D3/Marlin/Configuration_adv.h
#ifndef CONFIGURATION_ADV_H #define CONFIGURATION_ADV_H //=========================================================================== //=============================Thermal Settings ============================ //=========================================================================== #ifdef BED_LIMIT_SWITCHING #define BED_HYSTERESIS 2 //only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS #endif #define BED_CHECK_INTERVAL 5000 //ms between checks in bang-bang control //// Heating sanity check: // This waits for the watchperiod in milliseconds whenever an M104 or M109 increases the target temperature // If the temperature has not increased at the end of that period, the target temperature is set to zero. // It can be reset with another M104/M109. This check is also only triggered if the target temperature and the current temperature // differ by at least 2x WATCH_TEMP_INCREASE #define WATCH_TEMP_PERIOD 60000 //40 seconds #define WATCH_TEMP_INCREASE 10 //Heat up at least 15 degree in 40 seconds #ifdef WATCH_TEMP_PERIOD #define WATCH_TEMP_PERIOD_FALL 5000 //10 seconds #define WATCH_TEMP_FALL 30 //Temp fall down 20 degree in 10 seconds. #endif #ifdef PIDTEMP // this adds an experimental additional term to the heatingpower, proportional to the extrusion speed. // if Kc is choosen well, the additional required power due to increased melting should be compensated. #define PID_ADD_EXTRUSION_RATE #ifdef PID_ADD_EXTRUSION_RATE #define DEFAULT_Kc (1) //heatingpower=Kc*(e_speed) #endif #endif //automatic temperature: The hot end target temperature is calculated by all the buffered lines of gcode. //The maximum buffered steps/sec of the extruder motor are called "se". //You enter the autotemp mode by a M109 S<mintemp> T<maxtemp> F<factor> // the target temperature is set to mintemp+factor*se[steps/sec] and limited by mintemp and maxtemp // you exit the value by any M109 without F* // Also, if the temperature is set to a value <mintemp, it is not changed by autotemp. // on an ultimaker, some initial testing worked with M109 S215 B260 F1 in the start.gcode //#define AUTOTEMP #ifdef AUTOTEMP #define AUTOTEMP_OLDWEIGHT 0.98 #endif // extruder run-out prevention. //if the machine is idle, and the temperature over MINTEMP, every couple of SECONDS some filament is extruded //#define EXTRUDER_RUNOUT_PREVENT #define EXTRUDER_RUNOUT_MINTEMP 190 #define EXTRUDER_RUNOUT_SECONDS 30. #define EXTRUDER_RUNOUT_ESTEPS 14. //mm filament #define EXTRUDER_RUNOUT_SPEED 1500. //extrusion speed #define EXTRUDER_RUNOUT_EXTRUDE 100 //These defines help to calibrate the AD595 sensor in case you get wrong temperature measurements. //The measured temperature is defined as "actualTemp = (measuredTemp * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET" #define TEMP_SENSOR_AD595_OFFSET 0.0 #define TEMP_SENSOR_AD595_GAIN 1.0 //This is for controlling a fan to cool down the stepper drivers //it will turn on when any driver is enabled //and turn off after the set amount of seconds from last driver being disabled again #define CONTROLLERFAN_PIN -1 //Pin used for the fan to cool controller (-1 to disable) #define CONTROLLERFAN_SECS 60 //How many seconds, after all motors were disabled, the fan should run #define CONTROLLERFAN_SPEED 255 // == full speed // When first starting the main fan, run it at full speed for the // given number of milliseconds. This gets the fan spinning reliably // before setting a PWM value. (Does not work with software PWM for fan on Sanguinololu) //#define FAN_KICKSTART_TIME 100 // Extruder cooling fans // Configure fan pin outputs to automatically turn on/off when the associated // extruder temperature is above/below EXTRUDER_AUTO_FAN_TEMPERATURE. // Multiple extruders can be assigned to the same pin in which case // the fan will turn on when any selected extruder is above the threshold. #define EXTRUDER_0_AUTO_FAN_PIN -1 #define EXTRUDER_1_AUTO_FAN_PIN -1 #define EXTRUDER_2_AUTO_FAN_PIN -1 #define EXTRUDER_AUTO_FAN_TEMPERATURE 50 #define EXTRUDER_AUTO_FAN_SPEED 255 // == full speed //=========================================================================== //=============================Mechanical Settings=========================== //=========================================================================== #define ENDSTOPS_ONLY_FOR_HOMING // If defined the endstops will only be used for homing //// AUTOSET LOCATIONS OF LIMIT SWITCHES //// Added by ZetaPhoenix 09-15-2012 #ifdef MANUAL_HOME_POSITIONS // Use manual limit switch locations #define X_HOME_POS MANUAL_X_HOME_POS #define Y_HOME_POS MANUAL_Y_HOME_POS #define Z_HOME_POS MANUAL_Z_HOME_POS #else //Set min/max homing switch positions based upon homing direction and min/max travel limits //X axis #if X_HOME_DIR == -1 #ifdef BED_CENTER_AT_0_0 #define X_HOME_POS X_MAX_LENGTH * -0.5 #else #define X_HOME_POS X_MIN_POS #endif //BED_CENTER_AT_0_0 #else #ifdef BED_CENTER_AT_0_0 #define X_HOME_POS X_MAX_LENGTH * 0.5 #else #define X_HOME_POS X_MAX_POS #endif //BED_CENTER_AT_0_0 #endif //X_HOME_DIR == -1 //Y axis #if Y_HOME_DIR == -1 #ifdef BED_CENTER_AT_0_0 #define Y_HOME_POS Y_MAX_LENGTH * -0.5 #else #define Y_HOME_POS Y_MIN_POS #endif //BED_CENTER_AT_0_0 #else #ifdef BED_CENTER_AT_0_0 #define Y_HOME_POS Y_MAX_LENGTH * 0.5 #else #define Y_HOME_POS Y_MAX_POS #endif //BED_CENTER_AT_0_0 #endif //Y_HOME_DIR == -1 // Z axis #if Z_HOME_DIR == -1 //BED_CENTER_AT_0_0 not used #define Z_HOME_POS Z_MIN_POS #else #define Z_HOME_POS Z_MAX_POS #endif //Z_HOME_DIR == -1 #endif //End auto min/max positions //END AUTOSET LOCATIONS OF LIMIT SWITCHES -ZP //#define Z_LATE_ENABLE // Enable Z the last moment. Needed if your Z driver overheats. // A single Z stepper driver is usually used to drive 2 stepper motors. // Uncomment this define to utilize a separate stepper driver for each Z axis motor. // Only a few motherboards support this, like RAMPS, which have dual extruder support (the 2nd, often unused, extruder driver is used // to control the 2nd Z axis stepper motor). The pins are currently only defined for a RAMPS motherboards. // On a RAMPS (or other 5 driver) motherboard, using this feature will limit you to using 1 extruder. //#define Z_DUAL_STEPPER_DRIVERS #ifdef Z_DUAL_STEPPER_DRIVERS #undef EXTRUDERS #define EXTRUDERS 1 #endif // Enable this for dual x-carriage printers. // A dual x-carriage design has the advantage that the inactive extruder can be parked which // prevents hot-end ooze contaminating the print. It also reduces the weight of each x-carriage // allowing faster printing speeds. #ifdef DUAL_X_CARRIAGE // Configuration for second X-carriage // Note: the first x-carriage is defined as the x-carriage which homes to the minimum endstop; // the second x-carriage always homes to the maximum endstop. // However: In this mode the EXTRUDER_OFFSET_X value for the second extruder provides a software // override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops // without modifying the firmware (through the "M218 T1 X???" command). // Remember: you should set the second extruder x-offset to 0 in your slicer. // Pins for second x-carriage stepper driver (defined here to avoid further complicating pins.h) #define X2_STEP_PIN 36 #define X2_DIR_PIN 34 #define X2_ENABLE_PIN 30 // There are a few selectable movement modes for dual x-carriages using M605 S<mode> // Mode 0: Full control. The slicer has full control over both x-carriages and can achieve optimal travel results // as long as it supports dual x-carriages. (M605 S0) // Mode 1: Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so // that additional slicer support is not required. (M605 S1) // Mode 2: Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all // actions of the first x-carriage. This allows the printer to print 2 arbitrary items at // once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm]) // This is the default power-up mode which can be later using M605. #define DEFAULT_DUAL_X_CARRIAGE_MODE 1 // As the x-carriages are independent we can now account for any relative Z offset #define EXTRUDER1_Z_OFFSET 0.0 // z offset relative to extruder 0 // Default settings in "Auto-park Mode" #define TOOLCHANGE_PARK_ZLIFT 0 // the distance to raise Z axis when parking an extruder //By Zyf 0.2 #define TOOLCHANGE_UNPARK_ZLIFT 0 // the distance to raise Z axis when unparking an extruder //By zyf // Default x offset in duplication mode (typically set to half print bed width) #endif ///////////////////////////////////////////////////////////DUAL_X_CARRIAGE //homing hits the endstop, then retracts by this distance, before it tries to slowly bump again: #define X_HOME_RETRACT_MM 3 #define Z_HOME_RETRACT_MM 0.5 #define Y_HOME_RETRACT_MM 3 #define AXIS_RELATIVE_MODES \ { \ false, false, false, false \ } #define MAX_STEP_FREQUENCY 40000 // Max step frequency for Ultimaker (5000 pps / half step) //By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step. #define INVERT_X_STEP_PIN false #define INVERT_Y_STEP_PIN false #define INVERT_Z_STEP_PIN false #define INVERT_E_STEP_PIN false //default stepper release if idle #define DEFAULT_STEPPER_DEACTIVE_TIME 5 //By zyf #define DEFAULT_MINIMUMFEEDRATE 0.0 // 5 by zyf minimum feedrate #define DEFAULT_MINTRAVELFEEDRATE 0.0 // 15 By zyf // minimum time in microseconds that a movement needs to take if the buffer is emptied. #define DEFAULT_MINSEGMENTTIME 20000 // If defined the movements slow down when the look ahead buffer is only half full #define SLOWDOWN // Frequency limit // See nophead's blog for more info // Not working O //#define XY_FREQUENCY_LIMIT 15 // Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end // of the buffer and all stops. This should not be much greater than zero and should only be changed // if unwanted behavior is observed on a user's machine when running at very slow speeds. #define MINIMUM_PLANNER_SPEED 0.05 // (mm/sec) // MS1 MS2 Stepper Driver Microstepping mode table #define MICROSTEP1 LOW, LOW #define MICROSTEP2 HIGH, LOW #define MICROSTEP4 LOW, HIGH #define MICROSTEP8 HIGH, HIGH #define MICROSTEP16 HIGH, HIGH // Microstep setting (Only functional when stepper driver microstep pins are connected to MCU. #define MICROSTEP_MODES \ { \ 16, 16, 16, 16, 16 \ } // [1,2,4,8,16] // Motor Current setting (Only functional when motor driver current ref pins are connected to a digital trimpot on supported boards) #define DIGIPOT_MOTOR_CURRENT \ { \ 135, 135, 135, 135, 135 \ } // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A) //=========================================================================== //=============================Additional Features=========================== //=========================================================================== #define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the z enabled so your bed stays in place. // The hardware watchdog should reset the Microcontroller disabling all outputs, in case the firmware gets stuck and doesn't do temperature regulation. //#define USE_WATCHDOG // Enable the option to stop SD printing when hitting and endstops, needs to be enabled from the LCD menu when this option is enabled. //#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED // Arc interpretation settings: #define MM_PER_ARC_SEGMENT 1 #define N_ARC_CORRECTION 25 const unsigned int dropsegments = 5; //everything with less than this number of steps will be ignored as move and joined with the next movement // If you are using a RAMPS board or cheap E-bay purchased boards that do not detect when an SD card is inserted // You can get round this by connecting a push button or single throw switch to the pin defined as SDCARDCARDDETECT // in the pins.h file. When using a push button pulling the pin to ground this will need inverted. This setting should // be commented out otherwise #define SDCARDDETECTINVERTED #ifdef ULTIPANEL #undef SDCARDDETECTINVERTED #endif // Power Signal Control Definitions // By default use ATX definition #ifndef POWER_SUPPLY #define POWER_SUPPLY 2 #endif // 1 = ATX #if (POWER_SUPPLY == 1) #define PS_ON_AWAKE LOW #define PS_ON_ASLEEP HIGH #endif // 2 = X-Box 360 203W #if (POWER_SUPPLY == 2) #define PS_ON_AWAKE HIGH #define PS_ON_ASLEEP LOW #endif //=========================================================================== //=============================Buffers ============================ //=========================================================================== // The number of linear motions that can be in the plan at any give time. // THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2, i.g. 8,16,32 because shifts and ors are used to do the ringbuffering. #if defined SDSUPPORT #define BLOCK_BUFFER_SIZE 16 //16 By ZYF // SD,LCD,Buttons take more memory, block buffer needs to be smaller #else #define BLOCK_BUFFER_SIZE 16 // maximize block buffer #endif //The ASCII buffer for recieving from the serial: #define MAX_CMD_SIZE 96 #define BUFSIZE 4 // Firmware based and LCD controled retract // M207 and M208 can be used to define parameters for the retraction. // The retraction can be called by the slicer using G10 and G11 // until then, intended retractions can be detected by moves that only extrude and the direction. // the moves are than replaced by the firmware controlled ones. // #define FWRETRACT //ONLY PARTIALLY TESTED #define MIN_RETRACT 0.1 //minimum extruded mm to accept a automatic gcode retraction attempt //adds support for experimental filament exchange support M600; requires display #ifdef ULTIPANEL //#define FILAMENTCHANGEENABLE #ifdef FILAMENTCHANGEENABLE #define FILAMENTCHANGE_XPOS 3 #define FILAMENTCHANGE_YPOS 3 #define FILAMENTCHANGE_ZADD 10 #define FILAMENTCHANGE_FIRSTRETRACT -2 #define FILAMENTCHANGE_FINALRETRACT -100 #endif #endif //=========================================================================== //============================= Define Defines ============================ //=========================================================================== #if EXTRUDERS > 1 && defined TEMP_SENSOR_1_AS_REDUNDANT #error "You cannot use TEMP_SENSOR_1_AS_REDUNDANT if EXTRUDERS > 1" #endif #if TEMP_SENSOR_0 > 0 #define THERMISTORHEATER_0 TEMP_SENSOR_0 #define HEATER_0_USES_THERMISTOR #endif #if TEMP_SENSOR_1 > 0 #define THERMISTORHEATER_1 TEMP_SENSOR_1 #define HEATER_1_USES_THERMISTOR #endif #if TEMP_SENSOR_2 > 0 #define THERMISTORHEATER_2 TEMP_SENSOR_2 #define HEATER_2_USES_THERMISTOR #endif #if TEMP_SENSOR_BED > 0 #define THERMISTORBED TEMP_SENSOR_BED #define BED_USES_THERMISTOR #endif #if TEMP_SENSOR_0 == -1 #define HEATER_0_USES_AD595 #endif #if TEMP_SENSOR_1 == -1 #define HEATER_1_USES_AD595 #endif #if TEMP_SENSOR_2 == -1 #define HEATER_2_USES_AD595 #endif #if TEMP_SENSOR_BED == -1 #define BED_USES_AD595 #endif #if TEMP_SENSOR_0 == -2 #define HEATER_0_USES_MAX6675 #endif #if TEMP_SENSOR_0 == 0 #undef HEATER_0_MINTEMP #undef HEATER_0_MAXTEMP #endif #if TEMP_SENSOR_1 == 0 #undef HEATER_1_MINTEMP #undef HEATER_1_MAXTEMP #endif #if TEMP_SENSOR_2 == 0 #undef HEATER_2_MINTEMP #undef HEATER_2_MAXTEMP #endif #if TEMP_SENSOR_BED == 0 #undef BED_MINTEMP #undef BED_MAXTEMP #endif #endif //__CONFIGURATION_ADV_H
15,786
C++
.h
329
46.647416
151
0.709906
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
1,532,898
Configuration_xy.h
tenlog_TL-D3/Marlin/Configuration_xy.h
#ifndef CONFIGURATION_XY_H #define CONFIGURATION_XY_H // This configuration file contains the basic settings. // Advanced settings can be found in Configuration_adv.h // BASIC SETTINGS: select your board type, temperature sensor type, axis scaling, and endstop configuration // User-specified version info of this build to display in [Pronterface, etc] terminal window during // startup. Implementation of an idea by Prof Braino to inform user that any changes made to this // build by the user have been successfully uploaded into firmware. #define STRING_VERSION_CONFIG_H __DATE__ " " __TIME__ // build date and time #define STRING_CONFIG_H_AUTHOR "Tenlog" // Who made the changes. #define PROTOCOL_VERSION "1.0.0" // SERIAL_PORT selects which serial port should be used for communication with the host. // This allows the connection of wireless adapters (for instance) to non-default port pins. // Serial port 0 is still used by the Arduino bootloader regardless of this setting. #define SERIAL_PORT 0 // This determines the communication speed of the printer #define BAUDRATE 115200 //#define BAUDRATE 115200 //// The following define selects which electronics board you have. Please choose the one that matches your setup // 10 = Gen7 custom (Alfons3 Version) "https://github.com/Alfons3/Generation_7_Electronics" // 11 = Gen7 v1.1, v1.2 = 11 // 12 = Gen7 v1.3 // 13 = Gen7 v1.4 // 3 = MEGA/RAMPS up to 1.2 = 3 // 33 = RAMPS 1.3 / 1.4 (Power outputs: Extruder, Fan, Bed) // 34 = RAMPS 1.3 / 1.4 (Power outputs: Extruder0, Extruder1, Bed) // 4 = Duemilanove w/ ATMega328P pin assignment // 5 = Gen6 // 51 = Gen6 deluxe // 6 = Sanguinololu < 1.2 // 62 = Sanguinololu 1.2 and above // 63 = Melzi // 64 = STB V1.1 // 65 = Azteeg X1 // 66 = Melzi with ATmega1284 (MaKr3d version) // 7 = Ultimaker // 71 = Ultimaker (Older electronics. Pre 1.5.4. This is rare) // 77 = 3Drag Controller // 8 = Teensylu // 80 = Rumba // 81 = Printrboard (AT90USB1286) // 82 = Brainwave (AT90USB646) // 9 = Gen3+ // 70 = Megatronics // 701= Megatronics v2.0 // 702= Minitronics v1.0 // 90 = Alpha OMCA board // 91 = Final OMCA board // 301 = Rambo // 21 = Elefu Ra Board (v3) #ifndef MOTHERBOARD #define MOTHERBOARD 34 #endif // Define this to set a custom name for your generic Mendel, // This defines the number of extruders #define EXTRUDERS 2 //// The following define selects which power supply you have. Please choose the one that matches your setup // 1 = ATX // 2 = X-Box 360 203Watts (the blue wire connected to PS_ON and the red wire to VCC) #define POWER_SUPPLY 2 //=========================================================================== //=============================Thermal Settings ============================ //=========================================================================== // //--NORMAL IS 4.7kohm PULLUP!-- 1kohm pullup can be used on hotend sensor, using correct resistor and table // //// Temperature sensor settings: // -2 is thermocouple with MAX6675 (only for sensor 0) // -1 is thermocouple with AD595 // 0 is not used // 1 is 100k thermistor - best choice for EPCOS 100k (4.7k pullup) // 2 is 200k thermistor - ATC Semitec 204GT-2 (4.7k pullup) // 3 is mendel-parts thermistor (4.7k pullup) // 4 is 10k thermistor !! do not use it for a hotend. It gives bad resolution at high temp. !! // 5 is 100K thermistor - ATC Semitec 104GT-2 (Used in ParCan) (4.7k pullup) // 6 is 100k EPCOS - Not as accurate as table 1 (created using a fluke thermocouple) (4.7k pullup) // 7 is 100k Honeywell thermistor 135-104LAG-J01 (4.7k pullup) // 8 is 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) // 9 is 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) // 10 is 100k RS thermistor 198-961 (4.7k pullup) // 20 is the PT100 circuit // 60 is 100k Maker's Tool Works Kapton Bed Thermister // // 1k ohm pullup tables - This is not normal, you would have to have changed out your 4.7k for 1k // (but gives greater accuracy and more stable PID) // 51 is 100k thermistor - EPCOS (1k pullup) // 52 is 200k thermistor - ATC Semitec 204GT-2 (1k pullup) // 55 is 100k thermistor - ATC Semitec 104GT-2 (Used in ParCan) (1k pullup) #define TEMP_SENSOR_0 1 #define TEMP_SENSOR_1 1 #define TEMP_SENSOR_2 0 #define TEMP_SENSOR_BED 1 // This makes temp sensor 1 a redundant sensor for sensor 0. If the temperatures difference between these sensors is to high the print will be aborted. //#define TEMP_SENSOR_1_AS_REDUNDANT #define MAX_REDUNDANT_TEMP_SENSOR_DIFF 10 // Actual temperature must be close to target for this long before M109 returns success #define TEMP_RESIDENCY_TIME 3 // (seconds) //10 //By Zyf #define TEMP_HYSTERESIS 3 // (degC) range of +/- temperatures considered "close" to the target one 3 #define TEMP_WINDOW 1 // (degC) Window around target to start the residency timer x degC early. // The minimal temperature defines the temperature below which the heater will not be enabled It is used // to check that the wiring to the thermistor is not broken. // Otherwise this would lead to the heater being powered on all the time. #define HEATER_0_MINTEMP 1 #define HEATER_1_MINTEMP 1 #define HEATER_2_MINTEMP 1 #define BED_MINTEMP 1 // When temperature exceeds max temp, your heater will be switched off. // This feature exists to protect your hotend from overheating accidentally, but *NOT* from thermistor short/failure! // You should use MINTEMP for thermistor short/failure protection. #define HEATER_0_MAXTEMP 320 #define HEATER_1_MAXTEMP 320 #define HEATER_2_MAXTEMP 320 #define BED_MAXTEMP 120 // If your bed has low resistance e.g. .6 ohm and throws the fuse you can duty cycle it to reduce the // average current. The value should be an integer and the heat bed will be turned on for 1 interval of // HEATER_BED_DUTY_CYCLE_DIVIDER intervals. //#define HEATER_BED_DUTY_CYCLE_DIVIDER 4 // PID settings: // Comment the following line to disable PID and enable bang-bang. #define PIDTEMP #define BANG_MAX 255 // limits current to nozzle while in bang-bang mode; 255=full current #define PID_MAX 255 // limits current to nozzle while PID is active (see PID_FUNCTIONAL_RANGE below); 255=full current #ifdef PIDTEMP //#define PID_DEBUG // Sends debug data to the serial port. //#define PID_OPENLOOP 1 // Puts PID in open loop. M104/M140 sets the output power from 0 to PID_MAX #define PID_FUNCTIONAL_RANGE 10 // If the temperature difference between the target temperature and the actual temperature // is more then PID_FUNCTIONAL_RANGE then the PID will be shut off and the heater will be set to min/max. #define PID_INTEGRAL_DRIVE_MAX 255 //limit for the integral term #define K1 0.95 //smoothing factor within the PID #define PID_dT ((16.0 * 8.0) / (F_CPU / 64.0 / 256.0)) //sampling period of the temperature routine // If you are using a preconfigured hotend then you can use one of the value sets by uncommenting it #define DEFAULT_Kp 22.23 #define DEFAULT_Ki 1.61 #define DEFAULT_Kd 76.95 #endif // PIDTEMP // Bed Temperature Control // Select PID or bang-bang with PIDTEMPBED. If bang-bang, BED_LIMIT_SWITCHING will enable hysteresis // // Uncomment this to enable PID on the bed. It uses the same frequency PWM as the extruder. // If your PID_dT above is the default, and correct for your hardware/configuration, that means 7.689Hz, // which is fine for driving a square wave into a resistive load and does not significantly impact you FET heating. // This also works fine on a Fotek SSR-10DA Solid State Relay into a 250W heater. // If your configuration is significantly different than this and you don't understand the issues involved, you probably // shouldn't use bed PID until someone else verifies your hardware works. // If this is enabled, find your own PID constants below. //#define PIDTEMPBED // //#define BED_LIMIT_SWITCHING // This sets the max power delivered to the bed, and replaces the HEATER_BED_DUTY_CYCLE_DIVIDER option. // all forms of bed control obey this (PID, bang-bang, bang-bang with hysteresis) // setting this to anything other than 255 enablfes a form of PWM to the bed just like HEATER_BED_DUTY_CYCLE_DIVIDER did, // so you shouldn't use it unless you are OK with PWM on your bed. (see the comment on enabling PIDTEMPBED) #define MAX_BED_POWER 255 // limits duty cycle to bed; 255=full current #ifdef PIDTEMPBED //120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) //from FOPDT model - kp=.39 Tp=405 Tdead=66, Tc set to 79.2, aggressive factor of .15 (vs .1, 1, 10) #define DEFAULT_bedKp 10.00 #define DEFAULT_bedKi .023 #define DEFAULT_bedKd 305.4 //120v 250W silicone heater into 4mm borosilicate (MendelMax 1.5+) //from pidautotune // #define DEFAULT_bedKp 97.1 // #define DEFAULT_bedKi 1.41 // #define DEFAULT_bedKd 1675.16 // FIND YOUR OWN: "M303 E-1 C8 S90" to run autotune on the bed at 90 degreesC for 8 cycles. #endif // PIDTEMPBED //this prevents dangerous Extruder moves, i.e. if the temperature is under the limit //can be software-disabled for whatever purposes by #define PREVENT_DANGEROUS_EXTRUDE //if PREVENT_DANGEROUS_EXTRUDE is on, you can still disable (uncomment) very long bits of extrusion separately. #define PREVENT_LENGTHY_EXTRUDE #define EXTRUDE_MINTEMP 180 #define EXTRUDE_MAXLENGTH (X_MAX_LENGTH + Y_MAX_LENGTH) //prevent extrusion of very large distances. //=========================================================================== //=============================Mechanical Settings=========================== //=========================================================================== // Uncomment the following line to enable CoreXY kinematics // #define COREXY // coarse Endstop Settings #define ENDSTOPPULLUPS // Comment this out (using // at the start of the line) to disable the endstop pullup resistors #ifdef ENDSTOPPULLUPS #define ENDSTOPPULLUP_XMAX #define ENDSTOPPULLUP_YMAX #define ENDSTOPPULLUP_ZMAX #define ENDSTOPPULLUP_XMIN #define ENDSTOPPULLUP_YMIN #define ENDSTOPPULLUP_ZMIN #endif //#define DISABLE_MAX_ENDSTOPS //#define DISABLE_X_MAX_ENDSTOPS #define DISABLE_Y_MAX_ENDSTOPS #define DISABLE_Z_MAX_ENDSTOPS //#define DISABLE_MIN_ENDSTOPS // Disable max endstops for compatibility with endstop checking routine #if defined(COREXY) && !defined(DISABLE_MAX_ENDSTOPS) #define DISABLE_MAX_ENDSTOPS #endif // For Inverting Stepper Enable Pins (Active Low) use 0, Non Inverting (Active High) use 1 #define X_ENABLE_ON 0 #define Y_ENABLE_ON 0 #define Z_ENABLE_ON 0 #define E_ENABLE_ON 0 // For all extruders // Disables axis when it's not being used. #define DISABLE_X false #define DISABLE_Y false #define DISABLE_Z false #define DISABLE_E false // For all extruders // ENDSTOP SETTINGS: // Sets direction of endstops when homing; 1=MAX, -1=MIN #define X_HOME_DIR -1 #define Y_HOME_DIR -1 #define Z_HOME_DIR -1 #define min_software_endstops true // If true, axis won't move to coordinates less than HOME_POS. #define max_software_endstops true // If true, axis won't move to coordinates greater than the defined lengths below. // Travel limits after homing #define Y_MIN_POS 0 #define Z_MIN_POS 0 #define X_MAX_LENGTH (X_MAX_POS - X_MIN_POS) #define Y_MAX_LENGTH (Y_MAX_POS - Y_MIN_POS) #define Z_MAX_LENGTH (Z_MAX_POS - Z_MIN_POS) // The position of the homing switches //#define MANUAL_HOME_POSITIONS // If defined, MANUAL_*_HOME_POS below will be used //#define BED_CENTER_AT_0_0 // If defined, the center of the bed is at (X=0, Y=0) //Manual homing switch locations: // For deltabots this means top and center of the cartesian print volume. #define MANUAL_X_HOME_POS 0 #define MANUAL_Y_HOME_POS 0 #define MANUAL_Z_HOME_POS 0 //#define MANUAL_Z_HOME_POS 402 // For delta: Distance between nozzle and print surface after homing. //// MOVEMENT SETTINGS #define NUM_AXIS 4 // The axis order in all axis related arrays is X, Y, Z, E #define HOMING_FEEDRATE \ { \ 1500, 1000, 500, 0 \ } // set the homing speeds (mm/min) 3000 3000 400 // default settings // Offset of the extruders (uncomment if using more than one and relying on firmware to position when changing). // The offset has to be X=0, Y=0 for the extruder 0 hotend (default extruder). // For the other hotends it is their distance from the extruder 0 hotend. #define EXTRUDER_OFFSET_X \ { \ 0.0, 0.0 \ } // (in mm) for each extruder, offset of the hotend on the X axis #define EXTRUDER_OFFSET_Y \ { \ 0.0, 0.7 \ } // (in mm) for each extruder, offset of the hotend on the Y axis // The speed change that does not require acceleration (i.e. the software might assume it can be done instantaneously) //by zyf #define DEFAULT_XYJERK 10.0 // (mm/sec) #define DEFAULT_ZJERK 0.3 // (mm/sec) #define DEFAULT_EJERK 5.0 // (mm/sec) /* //old #define DEFAULT_XYJERK 20.0 // (mm/sec) #define DEFAULT_ZJERK 0.4 // (mm/sec) #define DEFAULT_EJERK 5.0 // (mm/sec) */ //=========================================================================== //=============================Additional Features=========================== //=========================================================================== // EEPROM // the microcontroller can store settings in the EEPROM, e.g. max velocity... // M500 - stores paramters in EEPROM // M501 - reads parameters from EEPROM (if you need reset them after you changed them temporarily). // M502 - reverts to the default "factory settings". You still need to store them in EEPROM afterwards if you want to. //define this to enable eeprom support #define EEPROM_SETTINGS //to disable EEPROM Serial responses and decrease program space by ~1700 byte: comment this out: // please keep turned on if you can. #define EEPROM_CHITCHAT // Preheat Constants #define PLA_PREHEAT_HOTEND_TEMP 200 #define PLA_PREHEAT_HPB_TEMP 0 #define PLA_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 #define ABS_PREHEAT_HOTEND_TEMP 220 #define ABS_PREHEAT_HPB_TEMP 35 #define ABS_PREHEAT_FAN_SPEED 0 // Insert Value between 0 and 255 #define SDSUPPORT // Increase the FAN pwm frequency. Removes the PWM noise but increases heating in the FET/Arduino //#define FAST_PWM_FAN // Use software PWM to drive the fan, as for the heaters. This uses a very low frequency // which is not ass annoying as with the hardware PWM. On the other hand, if this frequency // is too low, you should also increment SOFT_PWM_SCALE. //#define FAN_SOFT_PWM // Incrementing this by 1 will double the software PWM frequency, // affecting heaters, and the fan if FAN_SOFT_PWM is enabled. // However, control resolution will be halved for each increment; // at zero value, there are 128 effective control positions. #define SOFT_PWM_SCALE 0 // M240 Triggers a camera by emulating a Canon RC-1 Remote // Data from: http://www.doc-diy.net/photo/rc-1_hacked/ // #define PHOTOGRAPH_PIN 23 // SF send wrong arc g-codes when using Arc Point as fillet procedure //#define SF_ARC_FIX // Support for the BariCUDA Paste Extruder. //#define BARICUDA /*********************************************************************\ * R/C SERVO support * Sponsored by TrinityLabs, Reworked by codexmas **********************************************************************/ // Number of servos // // If you select a configuration below, this will receive a default value and does not need to be set manually // set it manually if you have more servos than extruders and wish to manually control some // leaving it undefined or defining as 0 will disable the servo subsystem // If unsure, leave commented / disabled // //#define NUM_SERVOS 3 // Servo index starts with 0 for M280 command // Servo Endstops // // This allows for servo actuated endstops, primary usage is for the Z Axis to eliminate calibration or bed height changes. // Use M206 command to correct for switch height offset to actual nozzle height. Store that setting with M500. // //#define SERVO_ENDSTOPS {-1, -1, 0} // Servo index for X, Y, Z. Disable with -1 //#define SERVO_ENDSTOP_ANGLES {0,0, 0,0, 70,0} // X,Y,Z Axis Extend and Retract angles //if #define ECO_HEIGHT 5 #endif //__CONFIGURATION_XY_H
16,242
C++
.h
319
49.579937
151
0.711648
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,899
fastio.h
tenlog_TL-D3/Marlin/fastio.h
/* This code contibuted by Triffid_Hunter and modified by Kliment why double up on these macros? see http://gcc.gnu.org/onlinedocs/cpp/Stringification.html */ #ifndef _FASTIO_ARDUINO_H #define _FASTIO_ARDUINO_H #include <avr/io.h> /* utility functions */ #ifndef MASK /// MASKING- returns \f$2^PIN\f$ #define MASK(PIN) (1 << PIN) #endif /* magic I/O routines now you can simply SET_OUTPUT(STEP); WRITE(STEP, 1); WRITE(STEP, 0); */ /// Read a pin #define _READ(IO) ((bool)(DIO##IO##_RPORT & MASK(DIO##IO##_PIN))) /// write to a pin // On some boards pins > 0x100 are used. These are not converted to atomic actions. An critical section is needed. #define _WRITE_NC(IO, v) \ do \ { \ if (v) \ { \ DIO##IO##_WPORT |= MASK(DIO##IO##_PIN); \ } \ else \ { \ DIO##IO##_WPORT &= ~MASK(DIO##IO##_PIN); \ }; \ } while (0) #define _WRITE_C(IO, v) \ do \ { \ if (v) \ { \ CRITICAL_SECTION_START; \ { \ DIO##IO##_WPORT |= MASK(DIO##IO##_PIN); \ } \ CRITICAL_SECTION_END; \ } \ else \ { \ CRITICAL_SECTION_START; \ { \ DIO##IO##_WPORT &= ~MASK(DIO##IO##_PIN); \ } \ CRITICAL_SECTION_END; \ } \ } while (0) #define _WRITE(IO, v) \ do \ { \ if (&(DIO##IO##_RPORT) >= (uint8_t *)0x100) \ { \ _WRITE_C(IO, v); \ } \ else \ { \ _WRITE_NC(IO, v); \ }; \ } while (0) /// toggle a pin #define _TOGGLE(IO) \ do \ { \ DIO##IO##_RPORT = MASK(DIO##IO##_PIN); \ } while (0) /// set pin as input #define _SET_INPUT(IO) \ do \ { \ DIO##IO##_DDR &= ~MASK(DIO##IO##_PIN); \ } while (0) /// set pin as output #define _SET_OUTPUT(IO) \ do \ { \ DIO##IO##_DDR |= MASK(DIO##IO##_PIN); \ } while (0) /// check if pin is an input #define _GET_INPUT(IO) ((DIO##IO##_DDR & MASK(DIO##IO##_PIN)) == 0) /// check if pin is an output #define _GET_OUTPUT(IO) ((DIO##IO##_DDR & MASK(DIO##IO##_PIN)) != 0) /// check if pin is an timer #define _GET_TIMER(IO) ((DIO ## IO ## _PWM) // why double up on these macros? see http://gcc.gnu.org/onlinedocs/cpp/Stringification.html /// Read a pin wrapper #define READ(IO) _READ(IO) /// Write to a pin wrapper #define WRITE(IO, v) _WRITE(IO, v) /// toggle a pin wrapper #define TOGGLE(IO) _TOGGLE(IO) /// set pin as input wrapper #define SET_INPUT(IO) _SET_INPUT(IO) /// set pin as output wrapper #define SET_OUTPUT(IO) _SET_OUTPUT(IO) /// check if pin is an input wrapper #define GET_INPUT(IO) _GET_INPUT(IO) /// check if pin is an output wrapper #define GET_OUTPUT(IO) _GET_OUTPUT(IO) /// check if pin is an timer wrapper #define GET_TIMER(IO) _GET_TIMER(IO) /* ports and functions added as necessary or if I feel like it- not a comprehensive list! */ #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__) // UART #define RXD DIO0 #define TXD DIO1 // SPI #define SCK DIO13 #define MISO DIO12 #define MOSI DIO11 #define SS DIO10 // TWI (I2C) #define SCL AIO5 #define SDA AIO4 // timers and PWM #define OC0A DIO6 #define OC0B DIO5 #define OC1A DIO9 #define OC1B DIO10 #define OC2A DIO11 #define OC2B DIO3 #define DEBUG_LED AIO5 /* pins */ #define DIO0_PIN PIND0 #define DIO0_RPORT PIND #define DIO0_WPORT PORTD #define DIO0_DDR DDRD #define DIO0_PWM NULL #define DIO1_PIN PIND1 #define DIO1_RPORT PIND #define DIO1_WPORT PORTD #define DIO1_DDR DDRD #define DIO1_PWM NULL #define DIO2_PIN PIND2 #define DIO2_RPORT PIND #define DIO2_WPORT PORTD #define DIO2_DDR DDRD #define DIO2_PWM NULL #define DIO3_PIN PIND3 #define DIO3_RPORT PIND #define DIO3_WPORT PORTD #define DIO3_DDR DDRD #define DIO3_PWM &OCR2B #define DIO4_PIN PIND4 #define DIO4_RPORT PIND #define DIO4_WPORT PORTD #define DIO4_DDR DDRD #define DIO4_PWM NULL #define DIO5_PIN PIND5 #define DIO5_RPORT PIND #define DIO5_WPORT PORTD #define DIO5_DDR DDRD #define DIO5_PWM &OCR0B #define DIO6_PIN PIND6 #define DIO6_RPORT PIND #define DIO6_WPORT PORTD #define DIO6_DDR DDRD #define DIO6_PWM &OCR0A #define DIO7_PIN PIND7 #define DIO7_RPORT PIND #define DIO7_WPORT PORTD #define DIO7_DDR DDRD #define DIO7_PWM NULL #define DIO8_PIN PINB0 #define DIO8_RPORT PINB #define DIO8_WPORT PORTB #define DIO8_DDR DDRB #define DIO8_PWM NULL #define DIO9_PIN PINB1 #define DIO9_RPORT PINB #define DIO9_WPORT PORTB #define DIO9_DDR DDRB #define DIO9_PWM NULL #define DIO10_PIN PINB2 #define DIO10_RPORT PINB #define DIO10_WPORT PORTB #define DIO10_DDR DDRB #define DIO10_PWM NULL #define DIO11_PIN PINB3 #define DIO11_RPORT PINB #define DIO11_WPORT PORTB #define DIO11_DDR DDRB #define DIO11_PWM &OCR2A #define DIO12_PIN PINB4 #define DIO12_RPORT PINB #define DIO12_WPORT PORTB #define DIO12_DDR DDRB #define DIO12_PWM NULL #define DIO13_PIN PINB5 #define DIO13_RPORT PINB #define DIO13_WPORT PORTB #define DIO13_DDR DDRB #define DIO13_PWM NULL #define DIO14_PIN PINC0 #define DIO14_RPORT PINC #define DIO14_WPORT PORTC #define DIO14_DDR DDRC #define DIO14_PWM NULL #define DIO15_PIN PINC1 #define DIO15_RPORT PINC #define DIO15_WPORT PORTC #define DIO15_DDR DDRC #define DIO15_PWM NULL #define DIO16_PIN PINC2 #define DIO16_RPORT PINC #define DIO16_WPORT PORTC #define DIO16_DDR DDRC #define DIO16_PWM NULL #define DIO17_PIN PINC3 #define DIO17_RPORT PINC #define DIO17_WPORT PORTC #define DIO17_DDR DDRC #define DIO17_PWM NULL #define DIO18_PIN PINC4 #define DIO18_RPORT PINC #define DIO18_WPORT PORTC #define DIO18_DDR DDRC #define DIO18_PWM NULL #define DIO19_PIN PINC5 #define DIO19_RPORT PINC #define DIO19_WPORT PORTC #define DIO19_DDR DDRC #define DIO19_PWM NULL #define DIO20_PIN PINC6 #define DIO20_RPORT PINC #define DIO20_WPORT PORTC #define DIO20_DDR DDRC #define DIO20_PWM NULL #define DIO21_PIN PINC7 #define DIO21_RPORT PINC #define DIO21_WPORT PORTC #define DIO21_DDR DDRC #define DIO21_PWM NULL #undef PB0 #define PB0_PIN PINB0 #define PB0_RPORT PINB #define PB0_WPORT PORTB #define PB0_DDR DDRB #define PB0_PWM NULL #undef PB1 #define PB1_PIN PINB1 #define PB1_RPORT PINB #define PB1_WPORT PORTB #define PB1_DDR DDRB #define PB1_PWM NULL #undef PB2 #define PB2_PIN PINB2 #define PB2_RPORT PINB #define PB2_WPORT PORTB #define PB2_DDR DDRB #define PB2_PWM NULL #undef PB3 #define PB3_PIN PINB3 #define PB3_RPORT PINB #define PB3_WPORT PORTB #define PB3_DDR DDRB #define PB3_PWM &OCR2A #undef PB4 #define PB4_PIN PINB4 #define PB4_RPORT PINB #define PB4_WPORT PORTB #define PB4_DDR DDRB #define PB4_PWM NULL #undef PB5 #define PB5_PIN PINB5 #define PB5_RPORT PINB #define PB5_WPORT PORTB #define PB5_DDR DDRB #define PB5_PWM NULL #undef PB6 #define PB6_PIN PINB6 #define PB6_RPORT PINB #define PB6_WPORT PORTB #define PB6_DDR DDRB #define PB6_PWM NULL #undef PB7 #define PB7_PIN PINB7 #define PB7_RPORT PINB #define PB7_WPORT PORTB #define PB7_DDR DDRB #define PB7_PWM NULL #undef PC0 #define PC0_PIN PINC0 #define PC0_RPORT PINC #define PC0_WPORT PORTC #define PC0_DDR DDRC #define PC0_PWM NULL #undef PC1 #define PC1_PIN PINC1 #define PC1_RPORT PINC #define PC1_WPORT PORTC #define PC1_DDR DDRC #define PC1_PWM NULL #undef PC2 #define PC2_PIN PINC2 #define PC2_RPORT PINC #define PC2_WPORT PORTC #define PC2_DDR DDRC #define PC2_PWM NULL #undef PC3 #define PC3_PIN PINC3 #define PC3_RPORT PINC #define PC3_WPORT PORTC #define PC3_DDR DDRC #define PC3_PWM NULL #undef PC4 #define PC4_PIN PINC4 #define PC4_RPORT PINC #define PC4_WPORT PORTC #define PC4_DDR DDRC #define PC4_PWM NULL #undef PC5 #define PC5_PIN PINC5 #define PC5_RPORT PINC #define PC5_WPORT PORTC #define PC5_DDR DDRC #define PC5_PWM NULL #undef PC6 #define PC6_PIN PINC6 #define PC6_RPORT PINC #define PC6_WPORT PORTC #define PC6_DDR DDRC #define PC6_PWM NULL #undef PC7 #define PC7_PIN PINC7 #define PC7_RPORT PINC #define PC7_WPORT PORTC #define PC7_DDR DDRC #define PC7_PWM NULL #undef PD0 #define PD0_PIN PIND0 #define PD0_RPORT PIND #define PD0_WPORT PORTD #define PD0_DDR DDRD #define PD0_PWM NULL #undef PD1 #define PD1_PIN PIND1 #define PD1_RPORT PIND #define PD1_WPORT PORTD #define PD1_DDR DDRD #define PD1_PWM NULL #undef PD2 #define PD2_PIN PIND2 #define PD2_RPORT PIND #define PD2_WPORT PORTD #define PD2_DDR DDRD #define PD2_PWM NULL #undef PD3 #define PD3_PIN PIND3 #define PD3_RPORT PIND #define PD3_WPORT PORTD #define PD3_DDR DDRD #define PD3_PWM &OCR2B #undef PD4 #define PD4_PIN PIND4 #define PD4_RPORT PIND #define PD4_WPORT PORTD #define PD4_DDR DDRD #define PD4_PWM NULL #undef PD5 #define PD5_PIN PIND5 #define PD5_RPORT PIND #define PD5_WPORT PORTD #define PD5_DDR DDRD #define PD5_PWM &OCR0B #undef PD6 #define PD6_PIN PIND6 #define PD6_RPORT PIND #define PD6_WPORT PORTD #define PD6_DDR DDRD #define PD6_PWM &OCR0A #undef PD7 #define PD7_PIN PIND7 #define PD7_RPORT PIND #define PD7_WPORT PORTD #define PD7_DDR DDRD #define PD7_PWM NULL #endif /* _AVR_ATmega{168,328,328P}__ */ #if defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__) || defined(__AVR_ATmega1284P__) // UART #define RXD DIO8 #define TXD DIO9 #define RXD0 DIO8 #define TXD0 DIO9 #define RXD1 DIO10 #define TXD1 DIO11 // SPI #define SCK DIO7 #define MISO DIO6 #define MOSI DIO5 #define SS DIO4 // TWI (I2C) #define SCL DIO16 #define SDA DIO17 // timers and PWM #define OC0A DIO3 #define OC0B DIO4 #define OC1A DIO13 #define OC1B DIO12 #define OC2A DIO15 #define OC2B DIO14 #define DEBUG_LED DIO0 /* pins */ #define DIO0_PIN PINB0 #define DIO0_RPORT PINB #define DIO0_WPORT PORTB #define DIO0_DDR DDRB #define DIO0_PWM NULL #define DIO1_PIN PINB1 #define DIO1_RPORT PINB #define DIO1_WPORT PORTB #define DIO1_DDR DDRB #define DIO1_PWM NULL #define DIO2_PIN PINB2 #define DIO2_RPORT PINB #define DIO2_WPORT PORTB #define DIO2_DDR DDRB #define DIO2_PWM NULL #define DIO3_PIN PINB3 #define DIO3_RPORT PINB #define DIO3_WPORT PORTB #define DIO3_DDR DDRB #define DIO3_PWM OCR0A #define DIO4_PIN PINB4 #define DIO4_RPORT PINB #define DIO4_WPORT PORTB #define DIO4_DDR DDRB #define DIO4_PWM OCR0B #define DIO5_PIN PINB5 #define DIO5_RPORT PINB #define DIO5_WPORT PORTB #define DIO5_DDR DDRB #define DIO5_PWM NULL #define DIO6_PIN PINB6 #define DIO6_RPORT PINB #define DIO6_WPORT PORTB #define DIO6_DDR DDRB #define DIO6_PWM NULL #define DIO7_PIN PINB7 #define DIO7_RPORT PINB #define DIO7_WPORT PORTB #define DIO7_DDR DDRB #define DIO7_PWM NULL #define DIO8_PIN PIND0 #define DIO8_RPORT PIND #define DIO8_WPORT PORTD #define DIO8_DDR DDRD #define DIO8_PWM NULL #define DIO9_PIN PIND1 #define DIO9_RPORT PIND #define DIO9_WPORT PORTD #define DIO9_DDR DDRD #define DIO9_PWM NULL #define DIO10_PIN PIND2 #define DIO10_RPORT PIND #define DIO10_WPORT PORTD #define DIO10_DDR DDRD #define DIO10_PWM NULL #define DIO11_PIN PIND3 #define DIO11_RPORT PIND #define DIO11_WPORT PORTD #define DIO11_DDR DDRD #define DIO11_PWM NULL #define DIO12_PIN PIND4 #define DIO12_RPORT PIND #define DIO12_WPORT PORTD #define DIO12_DDR DDRD #define DIO12_PWM OCR1B #define DIO13_PIN PIND5 #define DIO13_RPORT PIND #define DIO13_WPORT PORTD #define DIO13_DDR DDRD #define DIO13_PWM OCR1A #define DIO14_PIN PIND6 #define DIO14_RPORT PIND #define DIO14_WPORT PORTD #define DIO14_DDR DDRD #define DIO14_PWM OCR2B #define DIO15_PIN PIND7 #define DIO15_RPORT PIND #define DIO15_WPORT PORTD #define DIO15_DDR DDRD #define DIO15_PWM OCR2A #define DIO16_PIN PINC0 #define DIO16_RPORT PINC #define DIO16_WPORT PORTC #define DIO16_DDR DDRC #define DIO16_PWM NULL #define DIO17_PIN PINC1 #define DIO17_RPORT PINC #define DIO17_WPORT PORTC #define DIO17_DDR DDRC #define DIO17_PWM NULL #define DIO18_PIN PINC2 #define DIO18_RPORT PINC #define DIO18_WPORT PORTC #define DIO18_DDR DDRC #define DIO18_PWM NULL #define DIO19_PIN PINC3 #define DIO19_RPORT PINC #define DIO19_WPORT PORTC #define DIO19_DDR DDRC #define DIO19_PWM NULL #define DIO20_PIN PINC4 #define DIO20_RPORT PINC #define DIO20_WPORT PORTC #define DIO20_DDR DDRC #define DIO20_PWM NULL #define DIO21_PIN PINC5 #define DIO21_RPORT PINC #define DIO21_WPORT PORTC #define DIO21_DDR DDRC #define DIO21_PWM NULL #define DIO22_PIN PINC6 #define DIO22_RPORT PINC #define DIO22_WPORT PORTC #define DIO22_DDR DDRC #define DIO22_PWM NULL #define DIO23_PIN PINC7 #define DIO23_RPORT PINC #define DIO23_WPORT PORTC #define DIO23_DDR DDRC #define DIO23_PWM NULL #define DIO24_PIN PINA7 #define DIO24_RPORT PINA #define DIO24_WPORT PORTA #define DIO24_DDR DDRA #define DIO24_PWM NULL #define DIO25_PIN PINA6 #define DIO25_RPORT PINA #define DIO25_WPORT PORTA #define DIO25_DDR DDRA #define DIO25_PWM NULL #define DIO26_PIN PINA5 #define DIO26_RPORT PINA #define DIO26_WPORT PORTA #define DIO26_DDR DDRA #define DIO26_PWM NULL #define DIO27_PIN PINA4 #define DIO27_RPORT PINA #define DIO27_WPORT PORTA #define DIO27_DDR DDRA #define DIO27_PWM NULL #define DIO28_PIN PINA3 #define DIO28_RPORT PINA #define DIO28_WPORT PORTA #define DIO28_DDR DDRA #define DIO28_PWM NULL #define DIO29_PIN PINA2 #define DIO29_RPORT PINA #define DIO29_WPORT PORTA #define DIO29_DDR DDRA #define DIO29_PWM NULL #define DIO30_PIN PINA1 #define DIO30_RPORT PINA #define DIO30_WPORT PORTA #define DIO30_DDR DDRA #define DIO30_PWM NULL #define DIO31_PIN PINA0 #define DIO31_RPORT PINA #define DIO31_WPORT PORTA #define DIO31_DDR DDRA #define DIO31_PWM NULL #define AIO0_PIN PINA0 #define AIO0_RPORT PINA #define AIO0_WPORT PORTA #define AIO0_DDR DDRA #define AIO0_PWM NULL #define AIO1_PIN PINA1 #define AIO1_RPORT PINA #define AIO1_WPORT PORTA #define AIO1_DDR DDRA #define AIO1_PWM NULL #define AIO2_PIN PINA2 #define AIO2_RPORT PINA #define AIO2_WPORT PORTA #define AIO2_DDR DDRA #define AIO2_PWM NULL #define AIO3_PIN PINA3 #define AIO3_RPORT PINA #define AIO3_WPORT PORTA #define AIO3_DDR DDRA #define AIO3_PWM NULL #define AIO4_PIN PINA4 #define AIO4_RPORT PINA #define AIO4_WPORT PORTA #define AIO4_DDR DDRA #define AIO4_PWM NULL #define AIO5_PIN PINA5 #define AIO5_RPORT PINA #define AIO5_WPORT PORTA #define AIO5_DDR DDRA #define AIO5_PWM NULL #define AIO6_PIN PINA6 #define AIO6_RPORT PINA #define AIO6_WPORT PORTA #define AIO6_DDR DDRA #define AIO6_PWM NULL #define AIO7_PIN PINA7 #define AIO7_RPORT PINA #define AIO7_WPORT PORTA #define AIO7_DDR DDRA #define AIO7_PWM NULL #undef PA0 #define PA0_PIN PINA0 #define PA0_RPORT PINA #define PA0_WPORT PORTA #define PA0_DDR DDRA #define PA0_PWM NULL #undef PA1 #define PA1_PIN PINA1 #define PA1_RPORT PINA #define PA1_WPORT PORTA #define PA1_DDR DDRA #define PA1_PWM NULL #undef PA2 #define PA2_PIN PINA2 #define PA2_RPORT PINA #define PA2_WPORT PORTA #define PA2_DDR DDRA #define PA2_PWM NULL #undef PA3 #define PA3_PIN PINA3 #define PA3_RPORT PINA #define PA3_WPORT PORTA #define PA3_DDR DDRA #define PA3_PWM NULL #undef PA4 #define PA4_PIN PINA4 #define PA4_RPORT PINA #define PA4_WPORT PORTA #define PA4_DDR DDRA #define PA4_PWM NULL #undef PA5 #define PA5_PIN PINA5 #define PA5_RPORT PINA #define PA5_WPORT PORTA #define PA5_DDR DDRA #define PA5_PWM NULL #undef PA6 #define PA6_PIN PINA6 #define PA6_RPORT PINA #define PA6_WPORT PORTA #define PA6_DDR DDRA #define PA6_PWM NULL #undef PA7 #define PA7_PIN PINA7 #define PA7_RPORT PINA #define PA7_WPORT PORTA #define PA7_DDR DDRA #define PA7_PWM NULL #undef PB0 #define PB0_PIN PINB0 #define PB0_RPORT PINB #define PB0_WPORT PORTB #define PB0_DDR DDRB #define PB0_PWM NULL #undef PB1 #define PB1_PIN PINB1 #define PB1_RPORT PINB #define PB1_WPORT PORTB #define PB1_DDR DDRB #define PB1_PWM NULL #undef PB2 #define PB2_PIN PINB2 #define PB2_RPORT PINB #define PB2_WPORT PORTB #define PB2_DDR DDRB #define PB2_PWM NULL #undef PB3 #define PB3_PIN PINB3 #define PB3_RPORT PINB #define PB3_WPORT PORTB #define PB3_DDR DDRB #define PB3_PWM OCR0A #undef PB4 #define PB4_PIN PINB4 #define PB4_RPORT PINB #define PB4_WPORT PORTB #define PB4_DDR DDRB #define PB4_PWM OCR0B #undef PB5 #define PB5_PIN PINB5 #define PB5_RPORT PINB #define PB5_WPORT PORTB #define PB5_DDR DDRB #define PB5_PWM NULL #undef PB6 #define PB6_PIN PINB6 #define PB6_RPORT PINB #define PB6_WPORT PORTB #define PB6_DDR DDRB #define PB6_PWM NULL #undef PB7 #define PB7_PIN PINB7 #define PB7_RPORT PINB #define PB7_WPORT PORTB #define PB7_DDR DDRB #define PB7_PWM NULL #undef PC0 #define PC0_PIN PINC0 #define PC0_RPORT PINC #define PC0_WPORT PORTC #define PC0_DDR DDRC #define PC0_PWM NULL #undef PC1 #define PC1_PIN PINC1 #define PC1_RPORT PINC #define PC1_WPORT PORTC #define PC1_DDR DDRC #define PC1_PWM NULL #undef PC2 #define PC2_PIN PINC2 #define PC2_RPORT PINC #define PC2_WPORT PORTC #define PC2_DDR DDRC #define PC2_PWM NULL #undef PC3 #define PC3_PIN PINC3 #define PC3_RPORT PINC #define PC3_WPORT PORTC #define PC3_DDR DDRC #define PC3_PWM NULL #undef PC4 #define PC4_PIN PINC4 #define PC4_RPORT PINC #define PC4_WPORT PORTC #define PC4_DDR DDRC #define PC4_PWM NULL #undef PC5 #define PC5_PIN PINC5 #define PC5_RPORT PINC #define PC5_WPORT PORTC #define PC5_DDR DDRC #define PC5_PWM NULL #undef PC6 #define PC6_PIN PINC6 #define PC6_RPORT PINC #define PC6_WPORT PORTC #define PC6_DDR DDRC #define PC6_PWM NULL #undef PC7 #define PC7_PIN PINC7 #define PC7_RPORT PINC #define PC7_WPORT PORTC #define PC7_DDR DDRC #define PC7_PWM NULL #undef PD0 #define PD0_PIN PIND0 #define PD0_RPORT PIND #define PD0_WPORT PORTD #define PD0_DDR DDRD #define PD0_PWM NULL #undef PD1 #define PD1_PIN PIND1 #define PD1_RPORT PIND #define PD1_WPORT PORTD #define PD1_DDR DDRD #define PD1_PWM NULL #undef PD2 #define PD2_PIN PIND2 #define PD2_RPORT PIND #define PD2_WPORT PORTD #define PD2_DDR DDRD #define PD2_PWM NULL #undef PD3 #define PD3_PIN PIND3 #define PD3_RPORT PIND #define PD3_WPORT PORTD #define PD3_DDR DDRD #define PD3_PWM NULL #undef PD4 #define PD4_PIN PIND4 #define PD4_RPORT PIND #define PD4_WPORT PORTD #define PD4_DDR DDRD #define PD4_PWM NULL #undef PD5 #define PD5_PIN PIND5 #define PD5_RPORT PIND #define PD5_WPORT PORTD #define PD5_DDR DDRD #define PD5_PWM NULL #undef PD6 #define PD6_PIN PIND6 #define PD6_RPORT PIND #define PD6_WPORT PORTD #define PD6_DDR DDRD #define PD6_PWM OCR2B #undef PD7 #define PD7_PIN PIND7 #define PD7_RPORT PIND #define PD7_WPORT PORTD #define PD7_DDR DDRD #define PD7_PWM OCR2A #endif /* _AVR_ATmega{644,644P,644PA}__ */ #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) // UART #define RXD DIO0 #define TXD DIO1 // SPI #define SCK DIO52 #define MISO DIO50 #define MOSI DIO51 #define SS DIO53 // TWI (I2C) #define SCL DIO21 #define SDA DIO20 // timers and PWM #define OC0A DIO13 #define OC0B DIO4 #define OC1A DIO11 #define OC1B DIO12 #define OC2A DIO10 #define OC2B DIO9 #define OC3A DIO5 #define OC3B DIO2 #define OC3C DIO3 #define OC4A DIO6 #define OC4B DIO7 #define OC4C DIO8 #define OC5A DIO46 #define OC5B DIO45 #define OC5C DIO44 // change for your board #define DEBUG_LED DIO21 /* pins */ #define DIO0_PIN PINE0 #define DIO0_RPORT PINE #define DIO0_WPORT PORTE #define DIO0_DDR DDRE #define DIO0_PWM NULL #define DIO1_PIN PINE1 #define DIO1_RPORT PINE #define DIO1_WPORT PORTE #define DIO1_DDR DDRE #define DIO1_PWM NULL #define DIO2_PIN PINE4 #define DIO2_RPORT PINE #define DIO2_WPORT PORTE #define DIO2_DDR DDRE #define DIO2_PWM &OCR3BL #define DIO3_PIN PINE5 #define DIO3_RPORT PINE #define DIO3_WPORT PORTE #define DIO3_DDR DDRE #define DIO3_PWM &OCR3CL #define DIO4_PIN PING5 #define DIO4_RPORT PING #define DIO4_WPORT PORTG #define DIO4_DDR DDRG #define DIO4_PWM &OCR0B #define DIO5_PIN PINE3 #define DIO5_RPORT PINE #define DIO5_WPORT PORTE #define DIO5_DDR DDRE #define DIO5_PWM &OCR3AL #define DIO6_PIN PINH3 #define DIO6_RPORT PINH #define DIO6_WPORT PORTH #define DIO6_DDR DDRH #define DIO6_PWM &OCR4AL #define DIO7_PIN PINH4 #define DIO7_RPORT PINH #define DIO7_WPORT PORTH #define DIO7_DDR DDRH #define DIO7_PWM &OCR4BL #define DIO8_PIN PINH5 #define DIO8_RPORT PINH #define DIO8_WPORT PORTH #define DIO8_DDR DDRH #define DIO8_PWM &OCR4CL #define DIO9_PIN PINH6 #define DIO9_RPORT PINH #define DIO9_WPORT PORTH #define DIO9_DDR DDRH #define DIO9_PWM &OCR2B #define DIO10_PIN PINB4 #define DIO10_RPORT PINB #define DIO10_WPORT PORTB #define DIO10_DDR DDRB #define DIO10_PWM &OCR2A #define DIO11_PIN PINB5 #define DIO11_RPORT PINB #define DIO11_WPORT PORTB #define DIO11_DDR DDRB #define DIO11_PWM NULL #define DIO12_PIN PINB6 #define DIO12_RPORT PINB #define DIO12_WPORT PORTB #define DIO12_DDR DDRB #define DIO12_PWM NULL #define DIO13_PIN PINB7 #define DIO13_RPORT PINB #define DIO13_WPORT PORTB #define DIO13_DDR DDRB #define DIO13_PWM &OCR0A #define DIO14_PIN PINJ1 #define DIO14_RPORT PINJ #define DIO14_WPORT PORTJ #define DIO14_DDR DDRJ #define DIO14_PWM NULL #define DIO15_PIN PINJ0 #define DIO15_RPORT PINJ #define DIO15_WPORT PORTJ #define DIO15_DDR DDRJ #define DIO15_PWM NULL #define DIO16_PIN PINH1 #define DIO16_RPORT PINH #define DIO16_WPORT PORTH #define DIO16_DDR DDRH #define DIO16_PWM NULL #define DIO17_PIN PINH0 #define DIO17_RPORT PINH #define DIO17_WPORT PORTH #define DIO17_DDR DDRH #define DIO17_PWM NULL #define DIO18_PIN PIND3 #define DIO18_RPORT PIND #define DIO18_WPORT PORTD #define DIO18_DDR DDRD #define DIO18_PWM NULL #define DIO19_PIN PIND2 #define DIO19_RPORT PIND #define DIO19_WPORT PORTD #define DIO19_DDR DDRD #define DIO19_PWM NULL #define DIO20_PIN PIND1 #define DIO20_RPORT PIND #define DIO20_WPORT PORTD #define DIO20_DDR DDRD #define DIO20_PWM NULL #define DIO21_PIN PIND0 #define DIO21_RPORT PIND #define DIO21_WPORT PORTD #define DIO21_DDR DDRD #define DIO21_PWM NULL #define DIO22_PIN PINA0 #define DIO22_RPORT PINA #define DIO22_WPORT PORTA #define DIO22_DDR DDRA #define DIO22_PWM NULL #define DIO23_PIN PINA1 #define DIO23_RPORT PINA #define DIO23_WPORT PORTA #define DIO23_DDR DDRA #define DIO23_PWM NULL #define DIO24_PIN PINA2 #define DIO24_RPORT PINA #define DIO24_WPORT PORTA #define DIO24_DDR DDRA #define DIO24_PWM NULL #define DIO25_PIN PINA3 #define DIO25_RPORT PINA #define DIO25_WPORT PORTA #define DIO25_DDR DDRA #define DIO25_PWM NULL #define DIO26_PIN PINA4 #define DIO26_RPORT PINA #define DIO26_WPORT PORTA #define DIO26_DDR DDRA #define DIO26_PWM NULL #define DIO27_PIN PINA5 #define DIO27_RPORT PINA #define DIO27_WPORT PORTA #define DIO27_DDR DDRA #define DIO27_PWM NULL #define DIO28_PIN PINA6 #define DIO28_RPORT PINA #define DIO28_WPORT PORTA #define DIO28_DDR DDRA #define DIO28_PWM NULL #define DIO29_PIN PINA7 #define DIO29_RPORT PINA #define DIO29_WPORT PORTA #define DIO29_DDR DDRA #define DIO29_PWM NULL #define DIO30_PIN PINC7 #define DIO30_RPORT PINC #define DIO30_WPORT PORTC #define DIO30_DDR DDRC #define DIO30_PWM NULL #define DIO31_PIN PINC6 #define DIO31_RPORT PINC #define DIO31_WPORT PORTC #define DIO31_DDR DDRC #define DIO31_PWM NULL #define DIO32_PIN PINC5 #define DIO32_RPORT PINC #define DIO32_WPORT PORTC #define DIO32_DDR DDRC #define DIO32_PWM NULL #define DIO33_PIN PINC4 #define DIO33_RPORT PINC #define DIO33_WPORT PORTC #define DIO33_DDR DDRC #define DIO33_PWM NULL #define DIO34_PIN PINC3 #define DIO34_RPORT PINC #define DIO34_WPORT PORTC #define DIO34_DDR DDRC #define DIO34_PWM NULL #define DIO35_PIN PINC2 #define DIO35_RPORT PINC #define DIO35_WPORT PORTC #define DIO35_DDR DDRC #define DIO35_PWM NULL #define DIO36_PIN PINC1 #define DIO36_RPORT PINC #define DIO36_WPORT PORTC #define DIO36_DDR DDRC #define DIO36_PWM NULL #define DIO37_PIN PINC0 #define DIO37_RPORT PINC #define DIO37_WPORT PORTC #define DIO37_DDR DDRC #define DIO37_PWM NULL #define DIO38_PIN PIND7 #define DIO38_RPORT PIND #define DIO38_WPORT PORTD #define DIO38_DDR DDRD #define DIO38_PWM NULL #define DIO39_PIN PING2 #define DIO39_RPORT PING #define DIO39_WPORT PORTG #define DIO39_DDR DDRG #define DIO39_PWM NULL #define DIO40_PIN PING1 #define DIO40_RPORT PING #define DIO40_WPORT PORTG #define DIO40_DDR DDRG #define DIO40_PWM NULL #define DIO41_PIN PING0 #define DIO41_RPORT PING #define DIO41_WPORT PORTG #define DIO41_DDR DDRG #define DIO41_PWM NULL #define DIO42_PIN PINL7 #define DIO42_RPORT PINL #define DIO42_WPORT PORTL #define DIO42_DDR DDRL #define DIO42_PWM NULL #define DIO43_PIN PINL6 #define DIO43_RPORT PINL #define DIO43_WPORT PORTL #define DIO43_DDR DDRL #define DIO43_PWM NULL #define DIO44_PIN PINL5 #define DIO44_RPORT PINL #define DIO44_WPORT PORTL #define DIO44_DDR DDRL #define DIO44_PWM &OCR5CL #define DIO45_PIN PINL4 #define DIO45_RPORT PINL #define DIO45_WPORT PORTL #define DIO45_DDR DDRL #define DIO45_PWM &OCR5BL #define DIO46_PIN PINL3 #define DIO46_RPORT PINL #define DIO46_WPORT PORTL #define DIO46_DDR DDRL #define DIO46_PWM &OCR5AL #define DIO47_PIN PINL2 #define DIO47_RPORT PINL #define DIO47_WPORT PORTL #define DIO47_DDR DDRL #define DIO47_PWM NULL #define DIO48_PIN PINL1 #define DIO48_RPORT PINL #define DIO48_WPORT PORTL #define DIO48_DDR DDRL #define DIO48_PWM NULL #define DIO49_PIN PINL0 #define DIO49_RPORT PINL #define DIO49_WPORT PORTL #define DIO49_DDR DDRL #define DIO49_PWM NULL #define DIO50_PIN PINB3 #define DIO50_RPORT PINB #define DIO50_WPORT PORTB #define DIO50_DDR DDRB #define DIO50_PWM NULL #define DIO51_PIN PINB2 #define DIO51_RPORT PINB #define DIO51_WPORT PORTB #define DIO51_DDR DDRB #define DIO51_PWM NULL #define DIO52_PIN PINB1 #define DIO52_RPORT PINB #define DIO52_WPORT PORTB #define DIO52_DDR DDRB #define DIO52_PWM NULL #define DIO53_PIN PINB0 #define DIO53_RPORT PINB #define DIO53_WPORT PORTB #define DIO53_DDR DDRB #define DIO53_PWM NULL #define DIO54_PIN PINF0 #define DIO54_RPORT PINF #define DIO54_WPORT PORTF #define DIO54_DDR DDRF #define DIO54_PWM NULL #define DIO55_PIN PINF1 #define DIO55_RPORT PINF #define DIO55_WPORT PORTF #define DIO55_DDR DDRF #define DIO55_PWM NULL #define DIO56_PIN PINF2 #define DIO56_RPORT PINF #define DIO56_WPORT PORTF #define DIO56_DDR DDRF #define DIO56_PWM NULL #define DIO57_PIN PINF3 #define DIO57_RPORT PINF #define DIO57_WPORT PORTF #define DIO57_DDR DDRF #define DIO57_PWM NULL #define DIO58_PIN PINF4 #define DIO58_RPORT PINF #define DIO58_WPORT PORTF #define DIO58_DDR DDRF #define DIO58_PWM NULL #define DIO59_PIN PINF5 #define DIO59_RPORT PINF #define DIO59_WPORT PORTF #define DIO59_DDR DDRF #define DIO59_PWM NULL #define DIO60_PIN PINF6 #define DIO60_RPORT PINF #define DIO60_WPORT PORTF #define DIO60_DDR DDRF #define DIO60_PWM NULL #define DIO61_PIN PINF7 #define DIO61_RPORT PINF #define DIO61_WPORT PORTF #define DIO61_DDR DDRF #define DIO61_PWM NULL #define DIO62_PIN PINK0 #define DIO62_RPORT PINK #define DIO62_WPORT PORTK #define DIO62_DDR DDRK #define DIO62_PWM NULL #define DIO63_PIN PINK1 #define DIO63_RPORT PINK #define DIO63_WPORT PORTK #define DIO63_DDR DDRK #define DIO63_PWM NULL #define DIO64_PIN PINK2 #define DIO64_RPORT PINK #define DIO64_WPORT PORTK #define DIO64_DDR DDRK #define DIO64_PWM NULL #define DIO65_PIN PINK3 #define DIO65_RPORT PINK #define DIO65_WPORT PORTK #define DIO65_DDR DDRK #define DIO65_PWM NULL #define DIO66_PIN PINK4 #define DIO66_RPORT PINK #define DIO66_WPORT PORTK #define DIO66_DDR DDRK #define DIO66_PWM NULL #define DIO67_PIN PINK5 #define DIO67_RPORT PINK #define DIO67_WPORT PORTK #define DIO67_DDR DDRK #define DIO67_PWM NULL #define DIO68_PIN PINK6 #define DIO68_RPORT PINK #define DIO68_WPORT PORTK #define DIO68_DDR DDRK #define DIO68_PWM NULL #define DIO69_PIN PINK7 #define DIO69_RPORT PINK #define DIO69_WPORT PORTK #define DIO69_DDR DDRK #define DIO69_PWM NULL #undef PA0 #define PA0_PIN PINA0 #define PA0_RPORT PINA #define PA0_WPORT PORTA #define PA0_DDR DDRA #define PA0_PWM NULL #undef PA1 #define PA1_PIN PINA1 #define PA1_RPORT PINA #define PA1_WPORT PORTA #define PA1_DDR DDRA #define PA1_PWM NULL #undef PA2 #define PA2_PIN PINA2 #define PA2_RPORT PINA #define PA2_WPORT PORTA #define PA2_DDR DDRA #define PA2_PWM NULL #undef PA3 #define PA3_PIN PINA3 #define PA3_RPORT PINA #define PA3_WPORT PORTA #define PA3_DDR DDRA #define PA3_PWM NULL #undef PA4 #define PA4_PIN PINA4 #define PA4_RPORT PINA #define PA4_WPORT PORTA #define PA4_DDR DDRA #define PA4_PWM NULL #undef PA5 #define PA5_PIN PINA5 #define PA5_RPORT PINA #define PA5_WPORT PORTA #define PA5_DDR DDRA #define PA5_PWM NULL #undef PA6 #define PA6_PIN PINA6 #define PA6_RPORT PINA #define PA6_WPORT PORTA #define PA6_DDR DDRA #define PA6_PWM NULL #undef PA7 #define PA7_PIN PINA7 #define PA7_RPORT PINA #define PA7_WPORT PORTA #define PA7_DDR DDRA #define PA7_PWM NULL #undef PB0 #define PB0_PIN PINB0 #define PB0_RPORT PINB #define PB0_WPORT PORTB #define PB0_DDR DDRB #define PB0_PWM NULL #undef PB1 #define PB1_PIN PINB1 #define PB1_RPORT PINB #define PB1_WPORT PORTB #define PB1_DDR DDRB #define PB1_PWM NULL #undef PB2 #define PB2_PIN PINB2 #define PB2_RPORT PINB #define PB2_WPORT PORTB #define PB2_DDR DDRB #define PB2_PWM NULL #undef PB3 #define PB3_PIN PINB3 #define PB3_RPORT PINB #define PB3_WPORT PORTB #define PB3_DDR DDRB #define PB3_PWM NULL #undef PB4 #define PB4_PIN PINB4 #define PB4_RPORT PINB #define PB4_WPORT PORTB #define PB4_DDR DDRB #define PB4_PWM &OCR2A #undef PB5 #define PB5_PIN PINB5 #define PB5_RPORT PINB #define PB5_WPORT PORTB #define PB5_DDR DDRB #define PB5_PWM NULL #undef PB6 #define PB6_PIN PINB6 #define PB6_RPORT PINB #define PB6_WPORT PORTB #define PB6_DDR DDRB #define PB6_PWM NULL #undef PB7 #define PB7_PIN PINB7 #define PB7_RPORT PINB #define PB7_WPORT PORTB #define PB7_DDR DDRB #define PB7_PWM &OCR0A #undef PC0 #define PC0_PIN PINC0 #define PC0_RPORT PINC #define PC0_WPORT PORTC #define PC0_DDR DDRC #define PC0_PWM NULL #undef PC1 #define PC1_PIN PINC1 #define PC1_RPORT PINC #define PC1_WPORT PORTC #define PC1_DDR DDRC #define PC1_PWM NULL #undef PC2 #define PC2_PIN PINC2 #define PC2_RPORT PINC #define PC2_WPORT PORTC #define PC2_DDR DDRC #define PC2_PWM NULL #undef PC3 #define PC3_PIN PINC3 #define PC3_RPORT PINC #define PC3_WPORT PORTC #define PC3_DDR DDRC #define PC3_PWM NULL #undef PC4 #define PC4_PIN PINC4 #define PC4_RPORT PINC #define PC4_WPORT PORTC #define PC4_DDR DDRC #define PC4_PWM NULL #undef PC5 #define PC5_PIN PINC5 #define PC5_RPORT PINC #define PC5_WPORT PORTC #define PC5_DDR DDRC #define PC5_PWM NULL #undef PC6 #define PC6_PIN PINC6 #define PC6_RPORT PINC #define PC6_WPORT PORTC #define PC6_DDR DDRC #define PC6_PWM NULL #undef PC7 #define PC7_PIN PINC7 #define PC7_RPORT PINC #define PC7_WPORT PORTC #define PC7_DDR DDRC #define PC7_PWM NULL #undef PD0 #define PD0_PIN PIND0 #define PD0_RPORT PIND #define PD0_WPORT PORTD #define PD0_DDR DDRD #define PD0_PWM NULL #undef PD1 #define PD1_PIN PIND1 #define PD1_RPORT PIND #define PD1_WPORT PORTD #define PD1_DDR DDRD #define PD1_PWM NULL #undef PD2 #define PD2_PIN PIND2 #define PD2_RPORT PIND #define PD2_WPORT PORTD #define PD2_DDR DDRD #define PD2_PWM NULL #undef PD3 #define PD3_PIN PIND3 #define PD3_RPORT PIND #define PD3_WPORT PORTD #define PD3_DDR DDRD #define PD3_PWM NULL #undef PD4 #define PD4_PIN PIND4 #define PD4_RPORT PIND #define PD4_WPORT PORTD #define PD4_DDR DDRD #define PD4_PWM NULL #undef PD5 #define PD5_PIN PIND5 #define PD5_RPORT PIND #define PD5_WPORT PORTD #define PD5_DDR DDRD #define PD5_PWM NULL #undef PD6 #define PD6_PIN PIND6 #define PD6_RPORT PIND #define PD6_WPORT PORTD #define PD6_DDR DDRD #define PD6_PWM NULL #undef PD7 #define PD7_PIN PIND7 #define PD7_RPORT PIND #define PD7_WPORT PORTD #define PD7_DDR DDRD #define PD7_PWM NULL #undef PE0 #define PE0_PIN PINE0 #define PE0_RPORT PINE #define PE0_WPORT PORTE #define PE0_DDR DDRE #define PE0_PWM NULL #undef PE1 #define PE1_PIN PINE1 #define PE1_RPORT PINE #define PE1_WPORT PORTE #define PE1_DDR DDRE #define PE1_PWM NULL #undef PE2 #define PE2_PIN PINE2 #define PE2_RPORT PINE #define PE2_WPORT PORTE #define PE2_DDR DDRE #define PE2_PWM NULL #undef PE3 #define PE3_PIN PINE3 #define PE3_RPORT PINE #define PE3_WPORT PORTE #define PE3_DDR DDRE #define PE3_PWM &OCR3AL #undef PE4 #define PE4_PIN PINE4 #define PE4_RPORT PINE #define PE4_WPORT PORTE #define PE4_DDR DDRE #define PE4_PWM &OCR3BL #undef PE5 #define PE5_PIN PINE5 #define PE5_RPORT PINE #define PE5_WPORT PORTE #define PE5_DDR DDRE #define PE5_PWM &OCR3CL #undef PE6 #define PE6_PIN PINE6 #define PE6_RPORT PINE #define PE6_WPORT PORTE #define PE6_DDR DDRE #define PE6_PWM NULL #undef PE7 #define PE7_PIN PINE7 #define PE7_RPORT PINE #define PE7_WPORT PORTE #define PE7_DDR DDRE #define PE7_PWM NULL #undef PF0 #define PF0_PIN PINF0 #define PF0_RPORT PINF #define PF0_WPORT PORTF #define PF0_DDR DDRF #define PF0_PWM NULL #undef PF1 #define PF1_PIN PINF1 #define PF1_RPORT PINF #define PF1_WPORT PORTF #define PF1_DDR DDRF #define PF1_PWM NULL #undef PF2 #define PF2_PIN PINF2 #define PF2_RPORT PINF #define PF2_WPORT PORTF #define PF2_DDR DDRF #define PF2_PWM NULL #undef PF3 #define PF3_PIN PINF3 #define PF3_RPORT PINF #define PF3_WPORT PORTF #define PF3_DDR DDRF #define PF3_PWM NULL #undef PF4 #define PF4_PIN PINF4 #define PF4_RPORT PINF #define PF4_WPORT PORTF #define PF4_DDR DDRF #define PF4_PWM NULL #undef PF5 #define PF5_PIN PINF5 #define PF5_RPORT PINF #define PF5_WPORT PORTF #define PF5_DDR DDRF #define PF5_PWM NULL #undef PF6 #define PF6_PIN PINF6 #define PF6_RPORT PINF #define PF6_WPORT PORTF #define PF6_DDR DDRF #define PF6_PWM NULL #undef PF7 #define PF7_PIN PINF7 #define PF7_RPORT PINF #define PF7_WPORT PORTF #define PF7_DDR DDRF #define PF7_PWM NULL #undef PG0 #define PG0_PIN PING0 #define PG0_RPORT PING #define PG0_WPORT PORTG #define PG0_DDR DDRG #define PG0_PWM NULL #undef PG1 #define PG1_PIN PING1 #define PG1_RPORT PING #define PG1_WPORT PORTG #define PG1_DDR DDRG #define PG1_PWM NULL #undef PG2 #define PG2_PIN PING2 #define PG2_RPORT PING #define PG2_WPORT PORTG #define PG2_DDR DDRG #define PG2_PWM NULL #undef PG3 #define PG3_PIN PING3 #define PG3_RPORT PING #define PG3_WPORT PORTG #define PG3_DDR DDRG #define PG3_PWM NULL #undef PG4 #define PG4_PIN PING4 #define PG4_RPORT PING #define PG4_WPORT PORTG #define PG4_DDR DDRG #define PG4_PWM NULL #undef PG5 #define PG5_PIN PING5 #define PG5_RPORT PING #define PG5_WPORT PORTG #define PG5_DDR DDRG #define PG5_PWM &OCR0B #undef PG6 #define PG6_PIN PING6 #define PG6_RPORT PING #define PG6_WPORT PORTG #define PG6_DDR DDRG #define PG6_PWM NULL #undef PG7 #define PG7_PIN PING7 #define PG7_RPORT PING #define PG7_WPORT PORTG #define PG7_DDR DDRG #define PG7_PWM NULL #undef PH0 #define PH0_PIN PINH0 #define PH0_RPORT PINH #define PH0_WPORT PORTH #define PH0_DDR DDRH #define PH0_PWM NULL #undef PH1 #define PH1_PIN PINH1 #define PH1_RPORT PINH #define PH1_WPORT PORTH #define PH1_DDR DDRH #define PH1_PWM NULL #undef PH2 #define PH2_PIN PINH2 #define PH2_RPORT PINH #define PH2_WPORT PORTH #define PH2_DDR DDRH #define PH2_PWM NULL #undef PH3 #define PH3_PIN PINH3 #define PH3_RPORT PINH #define PH3_WPORT PORTH #define PH3_DDR DDRH #define PH3_PWM &OCR4AL #undef PH4 #define PH4_PIN PINH4 #define PH4_RPORT PINH #define PH4_WPORT PORTH #define PH4_DDR DDRH #define PH4_PWM &OCR4BL #undef PH5 #define PH5_PIN PINH5 #define PH5_RPORT PINH #define PH5_WPORT PORTH #define PH5_DDR DDRH #define PH5_PWM &OCR4CL #undef PH6 #define PH6_PIN PINH6 #define PH6_RPORT PINH #define PH6_WPORT PORTH #define PH6_DDR DDRH #define PH6_PWM &OCR2B #undef PH7 #define PH7_PIN PINH7 #define PH7_RPORT PINH #define PH7_WPORT PORTH #define PH7_DDR DDRH #define PH7_PWM NULL #undef PJ0 #define PJ0_PIN PINJ0 #define PJ0_RPORT PINJ #define PJ0_WPORT PORTJ #define PJ0_DDR DDRJ #define PJ0_PWM NULL #undef PJ1 #define PJ1_PIN PINJ1 #define PJ1_RPORT PINJ #define PJ1_WPORT PORTJ #define PJ1_DDR DDRJ #define PJ1_PWM NULL #undef PJ2 #define PJ2_PIN PINJ2 #define PJ2_RPORT PINJ #define PJ2_WPORT PORTJ #define PJ2_DDR DDRJ #define PJ2_PWM NULL #undef PJ3 #define PJ3_PIN PINJ3 #define PJ3_RPORT PINJ #define PJ3_WPORT PORTJ #define PJ3_DDR DDRJ #define PJ3_PWM NULL #undef PJ4 #define PJ4_PIN PINJ4 #define PJ4_RPORT PINJ #define PJ4_WPORT PORTJ #define PJ4_DDR DDRJ #define PJ4_PWM NULL #undef PJ5 #define PJ5_PIN PINJ5 #define PJ5_RPORT PINJ #define PJ5_WPORT PORTJ #define PJ5_DDR DDRJ #define PJ5_PWM NULL #undef PJ6 #define PJ6_PIN PINJ6 #define PJ6_RPORT PINJ #define PJ6_WPORT PORTJ #define PJ6_DDR DDRJ #define PJ6_PWM NULL #undef PJ7 #define PJ7_PIN PINJ7 #define PJ7_RPORT PINJ #define PJ7_WPORT PORTJ #define PJ7_DDR DDRJ #define PJ7_PWM NULL #undef PK0 #define PK0_PIN PINK0 #define PK0_RPORT PINK #define PK0_WPORT PORTK #define PK0_DDR DDRK #define PK0_PWM NULL #undef PK1 #define PK1_PIN PINK1 #define PK1_RPORT PINK #define PK1_WPORT PORTK #define PK1_DDR DDRK #define PK1_PWM NULL #undef PK2 #define PK2_PIN PINK2 #define PK2_RPORT PINK #define PK2_WPORT PORTK #define PK2_DDR DDRK #define PK2_PWM NULL #undef PK3 #define PK3_PIN PINK3 #define PK3_RPORT PINK #define PK3_WPORT PORTK #define PK3_DDR DDRK #define PK3_PWM NULL #undef PK4 #define PK4_PIN PINK4 #define PK4_RPORT PINK #define PK4_WPORT PORTK #define PK4_DDR DDRK #define PK4_PWM NULL #undef PK5 #define PK5_PIN PINK5 #define PK5_RPORT PINK #define PK5_WPORT PORTK #define PK5_DDR DDRK #define PK5_PWM NULL #undef PK6 #define PK6_PIN PINK6 #define PK6_RPORT PINK #define PK6_WPORT PORTK #define PK6_DDR DDRK #define PK6_PWM NULL #undef PK7 #define PK7_PIN PINK7 #define PK7_RPORT PINK #define PK7_WPORT PORTK #define PK7_DDR DDRK #define PK7_PWM NULL #undef PL0 #define PL0_PIN PINL0 #define PL0_RPORT PINL #define PL0_WPORT PORTL #define PL0_DDR DDRL #define PL0_PWM NULL #undef PL1 #define PL1_PIN PINL1 #define PL1_RPORT PINL #define PL1_WPORT PORTL #define PL1_DDR DDRL #define PL1_PWM NULL #undef PL2 #define PL2_PIN PINL2 #define PL2_RPORT PINL #define PL2_WPORT PORTL #define PL2_DDR DDRL #define PL2_PWM NULL #undef PL3 #define PL3_PIN PINL3 #define PL3_RPORT PINL #define PL3_WPORT PORTL #define PL3_DDR DDRL #define PL3_PWM &OCR5AL #undef PL4 #define PL4_PIN PINL4 #define PL4_RPORT PINL #define PL4_WPORT PORTL #define PL4_DDR DDRL #define PL4_PWM &OCR5BL #undef PL5 #define PL5_PIN PINL5 #define PL5_RPORT PINL #define PL5_WPORT PORTL #define PL5_DDR DDRL #define PL5_PWM &OCR5CL #undef PL6 #define PL6_PIN PINL6 #define PL6_RPORT PINL #define PL6_WPORT PORTL #define PL6_DDR DDRL #define PL6_PWM NULL #undef PL7 #define PL7_PIN PINL7 #define PL7_RPORT PINL #define PL7_WPORT PORTL #define PL7_DDR DDRL #define PL7_PWM NULL #endif #if defined(__AVR_AT90USB1287__) || defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__) // SPI #define SCK DIO9 #define MISO DIO11 #define MOSI DIO10 #define SS DIO8 // change for your board #define DEBUG_LED DIO31 /* led D5 red */ /* pins */ #define DIO0_PIN PINA0 #define DIO0_RPORT PINA #define DIO0_WPORT PORTA #define DIO0_PWM NULL #define DIO0_DDR DDRA #define DIO1_PIN PINA1 #define DIO1_RPORT PINA #define DIO1_WPORT PORTA #define DIO1_PWM NULL #define DIO1_DDR DDRA #define DIO2_PIN PINA2 #define DIO2_RPORT PINA #define DIO2_WPORT PORTA #define DIO2_PWM NULL #define DIO2_DDR DDRA #define DIO3_PIN PINA3 #define DIO3_RPORT PINA #define DIO3_WPORT PORTA #define DIO3_PWM NULL #define DIO3_DDR DDRA #define DIO4_PIN PINA4 #define DIO4_RPORT PINA #define DIO4_WPORT PORTA #define DIO4_PWM NULL #define DIO4_DDR DDRA #define DIO5_PIN PINA5 #define DIO5_RPORT PINA #define DIO5_WPORT PORTA #define DIO5_PWM NULL #define DIO5_DDR DDRA #define DIO6_PIN PINA6 #define DIO6_RPORT PINA #define DIO6_WPORT PORTA #define DIO6_PWM NULL #define DIO6_DDR DDRA #define DIO7_PIN PINA7 #define DIO7_RPORT PINA #define DIO7_WPORT PORTA #define DIO7_PWM NULL #define DIO7_DDR DDRA #define DIO8_PIN PINB0 #define DIO8_RPORT PINB #define DIO8_WPORT PORTB #define DIO8_PWM NULL #define DIO8_DDR DDRB #define DIO9_PIN PINB1 #define DIO9_RPORT PINB #define DIO9_WPORT PORTB #define DIO9_PWM NULL #define DIO9_DDR DDRB #define DIO10_PIN PINB2 #define DIO10_RPORT PINB #define DIO10_WPORT PORTB #define DIO10_PWM NULL #define DIO10_DDR DDRB #define DIO11_PIN PINB3 #define DIO11_RPORT PINB #define DIO11_WPORT PORTB #define DIO11_PWM NULL #define DIO11_DDR DDRB #define DIO12_PIN PINB4 #define DIO12_RPORT PINB #define DIO12_WPORT PORTB #define DIO12_PWM NULL #define DIO12_DDR DDRB #define DIO13_PIN PINB5 #define DIO13_RPORT PINB #define DIO13_WPORT PORTB #define DIO13_PWM NULL #define DIO13_DDR DDRB #define DIO14_PIN PINB6 #define DIO14_RPORT PINB #define DIO14_WPORT PORTB #define DIO14_PWM NULL #define DIO14_DDR DDRB #define DIO15_PIN PINB7 #define DIO15_RPORT PINB #define DIO15_WPORT PORTB #define DIO15_PWM NULL #define DIO15_DDR DDRB #define DIO16_PIN PINC0 #define DIO16_RPORT PINC #define DIO16_WPORT PORTC #define DIO16_PWM NULL #define DIO16_DDR DDRC #define DIO17_PIN PINC1 #define DIO17_RPORT PINC #define DIO17_WPORT PORTC #define DIO17_PWM NULL #define DIO17_DDR DDRC #define DIO18_PIN PINC2 #define DIO18_RPORT PINC #define DIO18_WPORT PORTC #define DIO18_PWM NULL #define DIO18_DDR DDRC #define DIO19_PIN PINC3 #define DIO19_RPORT PINC #define DIO19_WPORT PORTC #define DIO19_PWM NULL #define DIO19_DDR DDRC #define DIO20_PIN PINC4 #define DIO20_RPORT PINC #define DIO20_WPORT PORTC #define DIO20_PWM NULL #define DIO20_DDR DDRC #define DIO21_PIN PINC5 #define DIO21_RPORT PINC #define DIO21_WPORT PORTC #define DIO21_PWM NULL #define DIO21_DDR DDRC #define DIO22_PIN PINC6 #define DIO22_RPORT PINC #define DIO22_WPORT PORTC #define DIO22_PWM NULL #define DIO22_DDR DDRC #define DIO23_PIN PINC7 #define DIO23_RPORT PINC #define DIO23_WPORT PORTC #define DIO23_PWM NULL #define DIO23_DDR DDRC #define DIO24_PIN PIND0 #define DIO24_RPORT PIND #define DIO24_WPORT PORTD #define DIO24_PWM NULL #define DIO24_DDR DDRD #define DIO25_PIN PIND1 #define DIO25_RPORT PIND #define DIO25_WPORT PORTD #define DIO25_PWM NULL #define DIO25_DDR DDRD #define DIO26_PIN PIND2 #define DIO26_RPORT PIND #define DIO26_WPORT PORTD #define DIO26_PWM NULL #define DIO26_DDR DDRD #define DIO27_PIN PIND3 #define DIO27_RPORT PIND #define DIO27_WPORT PORTD #define DIO27_PWM NULL #define DIO27_DDR DDRD #define DIO28_PIN PIND4 #define DIO28_RPORT PIND #define DIO28_WPORT PORTD #define DIO28_PWM NULL #define DIO28_DDR DDRD #define DIO29_PIN PIND5 #define DIO29_RPORT PIND #define DIO29_WPORT PORTD #define DIO29_PWM NULL #define DIO29_DDR DDRD #define DIO30_PIN PIND6 #define DIO30_RPORT PIND #define DIO30_WPORT PORTD #define DIO30_PWM NULL #define DIO30_DDR DDRD #define DIO31_PIN PIND7 #define DIO31_RPORT PIND #define DIO31_WPORT PORTD #define DIO31_PWM NULL #define DIO31_DDR DDRD #define DIO32_PIN PINE0 #define DIO32_RPORT PINE #define DIO32_WPORT PORTE #define DIO32_PWM NULL #define DIO32_DDR DDRE #define DIO33_PIN PINE1 #define DIO33_RPORT PINE #define DIO33_WPORT PORTE #define DIO33_PWM NULL #define DIO33_DDR DDRE #define DIO34_PIN PINE2 #define DIO34_RPORT PINE #define DIO34_WPORT PORTE #define DIO34_PWM NULL #define DIO34_DDR DDRE #define DIO35_PIN PINE3 #define DIO35_RPORT PINE #define DIO35_WPORT PORTE #define DIO35_PWM NULL #define DIO35_DDR DDRE #define DIO36_PIN PINE4 #define DIO36_RPORT PINE #define DIO36_WPORT PORTE #define DIO36_PWM NULL #define DIO36_DDR DDRE #define DIO37_PIN PINE5 #define DIO37_RPORT PINE #define DIO37_WPORT PORTE #define DIO37_PWM NULL #define DIO37_DDR DDRE #define DIO38_PIN PINE6 #define DIO38_RPORT PINE #define DIO38_WPORT PORTE #define DIO38_PWM NULL #define DIO38_DDR DDRE #define DIO39_PIN PINE7 #define DIO39_RPORT PINE #define DIO39_WPORT PORTE #define DIO39_PWM NULL #define DIO39_DDR DDRE #define AIO0_PIN PINF0 #define AIO0_RPORT PINF #define AIO0_WPORT PORTF #define AIO0_PWM NULL #define AIO0_DDR DDRF #define AIO1_PIN PINF1 #define AIO1_RPORT PINF #define AIO1_WPORT PORTF #define AIO1_PWM NULL #define AIO1_DDR DDRF #define AIO2_PIN PINF2 #define AIO2_RPORT PINF #define AIO2_WPORT PORTF #define AIO2_PWM NULL #define AIO2_DDR DDRF #define AIO3_PIN PINF3 #define AIO3_RPORT PINF #define AIO3_WPORT PORTF #define AIO3_PWM NULL #define AIO3_DDR DDRF #define AIO4_PIN PINF4 #define AIO4_RPORT PINF #define AIO4_WPORT PORTF #define AIO4_PWM NULL #define AIO4_DDR DDRF #define AIO5_PIN PINF5 #define AIO5_RPORT PINF #define AIO5_WPORT PORTF #define AIO5_PWM NULL #define AIO5_DDR DDRF #define AIO6_PIN PINF6 #define AIO6_RPORT PINF #define AIO6_WPORT PORTF #define AIO6_PWM NULL #define AIO6_DDR DDRF #define AIO7_PIN PINF7 #define AIO7_RPORT PINF #define AIO7_WPORT PORTF #define AIO7_PWM NULL #define AIO7_DDR DDRF #define DIO40_PIN PINF0 #define DIO40_RPORT PINF #define DIO40_WPORT PORTF #define DIO40_PWM NULL #define DIO40_DDR DDRF #define DIO41_PIN PINF1 #define DIO41_RPORT PINF #define DIO41_WPORT PORTF #define DIO41_PWM NULL #define DIO41_DDR DDRF #define DIO42_PIN PINF2 #define DIO42_RPORT PINF #define DIO42_WPORT PORTF #define DIO42_PWM NULL #define DIO42_DDR DDRF #define DIO43_PIN PINF3 #define DIO43_RPORT PINF #define DIO43_WPORT PORTF #define DIO43_PWM NULL #define DIO43_DDR DDRF #define DIO44_PIN PINF4 #define DIO44_RPORT PINF #define DIO44_WPORT PORTF #define DIO44_PWM NULL #define DIO44_DDR DDRF #define DIO45_PIN PINF5 #define DIO45_RPORT PINF #define DIO45_WPORT PORTF #define DIO45_PWM NULL #define DIO45_DDR DDRF #define DIO46_PIN PINF6 #define DIO46_RPORT PINF #define DIO46_WPORT PORTF #define DIO46_PWM NULL #define DIO46_DDR DDRF #define DIO47_PIN PINF7 #define DIO47_RPORT PINF #define DIO47_WPORT PORTF #define DIO47_PWM NULL #define DIO47_DDR DDRF #undef PA0 #define PA0_PIN PINA0 #define PA0_RPORT PINA #define PA0_WPORT PORTA #define PA0_PWM NULL #define PA0_DDR DDRA #undef PA1 #define PA1_PIN PINA1 #define PA1_RPORT PINA #define PA1_WPORT PORTA #define PA1_PWM NULL #define PA1_DDR DDRA #undef PA2 #define PA2_PIN PINA2 #define PA2_RPORT PINA #define PA2_WPORT PORTA #define PA2_PWM NULL #define PA2_DDR DDRA #undef PA3 #define PA3_PIN PINA3 #define PA3_RPORT PINA #define PA3_WPORT PORTA #define PA3_PWM NULL #define PA3_DDR DDRA #undef PA4 #define PA4_PIN PINA4 #define PA4_RPORT PINA #define PA4_WPORT PORTA #define PA4_PWM NULL #define PA4_DDR DDRA #undef PA5 #define PA5_PIN PINA5 #define PA5_RPORT PINA #define PA5_WPORT PORTA #define PA5_PWM NULL #define PA5_DDR DDRA #undef PA6 #define PA6_PIN PINA6 #define PA6_RPORT PINA #define PA6_WPORT PORTA #define PA6_PWM NULL #define PA6_DDR DDRA #undef PA7 #define PA7_PIN PINA7 #define PA7_RPORT PINA #define PA7_WPORT PORTA #define PA7_PWM NULL #define PA7_DDR DDRA #undef PB0 #define PB0_PIN PINB0 #define PB0_RPORT PINB #define PB0_WPORT PORTB #define PB0_PWM NULL #define PB0_DDR DDRB #undef PB1 #define PB1_PIN PINB1 #define PB1_RPORT PINB #define PB1_WPORT PORTB #define PB1_PWM NULL #define PB1_DDR DDRB #undef PB2 #define PB2_PIN PINB2 #define PB2_RPORT PINB #define PB2_WPORT PORTB #define PB2_PWM NULL #define PB2_DDR DDRB #undef PB3 #define PB3_PIN PINB3 #define PB3_RPORT PINB #define PB3_WPORT PORTB #define PB3_PWM NULL #define PB3_DDR DDRB #undef PB4 #define PB4_PIN PINB4 #define PB4_RPORT PINB #define PB4_WPORT PORTB #define PB4_PWM NULL #define PB4_DDR DDRB #undef PB5 #define PB5_PIN PINB5 #define PB5_RPORT PINB #define PB5_WPORT PORTB #define PB5_PWM NULL #define PB5_DDR DDRB #undef PB6 #define PB6_PIN PINB6 #define PB6_RPORT PINB #define PB6_WPORT PORTB #define PB6_PWM NULL #define PB6_DDR DDRB #undef PB7 #define PB7_PIN PINB7 #define PB7_RPORT PINB #define PB7_WPORT PORTB #define PB7_PWM NULL #define PB7_DDR DDRB #undef PC0 #define PC0_PIN PINC0 #define PC0_RPORT PINC #define PC0_WPORT PORTC #define PC0_PWM NULL #define PC0_DDR DDRC #undef PC1 #define PC1_PIN PINC1 #define PC1_RPORT PINC #define PC1_WPORT PORTC #define PC1_PWM NULL #define PC1_DDR DDRC #undef PC2 #define PC2_PIN PINC2 #define PC2_RPORT PINC #define PC2_WPORT PORTC #define PC2_PWM NULL #define PC2_DDR DDRC #undef PC3 #define PC3_PIN PINC3 #define PC3_RPORT PINC #define PC3_WPORT PORTC #define PC3_PWM NULL #define PC3_DDR DDRC #undef PC4 #define PC4_PIN PINC4 #define PC4_RPORT PINC #define PC4_WPORT PORTC #define PC4_PWM NULL #define PC4_DDR DDRC #undef PC5 #define PC5_PIN PINC5 #define PC5_RPORT PINC #define PC5_WPORT PORTC #define PC5_PWM NULL #define PC5_DDR DDRC #undef PC6 #define PC6_PIN PINC6 #define PC6_RPORT PINC #define PC6_WPORT PORTC #define PC6_PWM NULL #define PC6_DDR DDRC #undef PC7 #define PC7_PIN PINC7 #define PC7_RPORT PINC #define PC7_WPORT PORTC #define PC7_PWM NULL #define PC7_DDR DDRC #undef PD0 #define PD0_PIN PIND0 #define PD0_RPORT PIND #define PD0_WPORT PORTD #define PD0_PWM NULL #define PD0_DDR DDRD #undef PD1 #define PD1_PIN PIND1 #define PD1_RPORT PIND #define PD1_WPORT PORTD #define PD1_PWM NULL #define PD1_DDR DDRD #undef PD2 #define PD2_PIN PIND2 #define PD2_RPORT PIND #define PD2_WPORT PORTD #define PD2_PWM NULL #define PD2_DDR DDRD #undef PD3 #define PD3_PIN PIND3 #define PD3_RPORT PIND #define PD3_WPORT PORTD #define PD3_PWM NULL #define PD3_DDR DDRD #undef PD4 #define PD4_PIN PIND4 #define PD4_RPORT PIND #define PD4_WPORT PORTD #define PD4_PWM NULL #define PD4_DDR DDRD #undef PD5 #define PD5_PIN PIND5 #define PD5_RPORT PIND #define PD5_WPORT PORTD #define PD5_PWM NULL #define PD5_DDR DDRD #undef PD6 #define PD6_PIN PIND6 #define PD6_RPORT PIND #define PD6_WPORT PORTD #define PD6_PWM NULL #define PD6_DDR DDRD #undef PD7 #define PD7_PIN PIND7 #define PD7_RPORT PIND #define PD7_WPORT PORTD #define PD7_PWM NULL #define PD7_DDR DDRD #undef PE0 #define PE0_PIN PINE0 #define PE0_RPORT PINE #define PE0_WPORT PORTE #define PE0_PWM NULL #define PE0_DDR DDRE #undef PE1 #define PE1_PIN PINE1 #define PE1_RPORT PINE #define PE1_WPORT PORTE #define PE1_PWM NULL #define PE1_DDR DDRE #undef PE2 #define PE2_PIN PINE2 #define PE2_RPORT PINE #define PE2_WPORT PORTE #define PE2_PWM NULL #define PE2_DDR DDRE #undef PE3 #define PE3_PIN PINE3 #define PE3_RPORT PINE #define PE3_WPORT PORTE #define PE3_PWM NULL #define PE3_DDR DDRE #undef PE4 #define PE4_PIN PINE4 #define PE4_RPORT PINE #define PE4_WPORT PORTE #define PE4_PWM NULL #define PE4_DDR DDRE #undef PE5 #define PE5_PIN PINE5 #define PE5_RPORT PINE #define PE5_WPORT PORTE #define PE5_PWM NULL #define PE5_DDR DDRE #undef PE6 #define PE6_PIN PINE6 #define PE6_RPORT PINE #define PE6_WPORT PORTE #define PE6_PWM NULL #define PE6_DDR DDRE #undef PE7 #define PE7_PIN PINE7 #define PE7_RPORT PINE #define PE7_WPORT PORTE #define PE7_PWM NULL #define PE7_DDR DDRE #undef PF0 #define PF0_PIN PINF0 #define PF0_RPORT PINF #define PF0_WPORT PORTF #define PF0_PWM NULL #define PF0_DDR DDRF #undef PF1 #define PF1_PIN PINF1 #define PF1_RPORT PINF #define PF1_WPORT PORTF #define PF1_PWM NULL #define PF1_DDR DDRF #undef PF2 #define PF2_PIN PINF2 #define PF2_RPORT PINF #define PF2_WPORT PORTF #define PF2_PWM NULL #define PF2_DDR DDRF #undef PF3 #define PF3_PIN PINF3 #define PF3_RPORT PINF #define PF3_WPORT PORTF #define PF3_PWM NULL #define PF3_DDR DDRF #undef PF4 #define PF4_PIN PINF4 #define PF4_RPORT PINF #define PF4_WPORT PORTF #define PF4_PWM NULL #define PF4_DDR DDRF #undef PF5 #define PF5_PIN PINF5 #define PF5_RPORT PINF #define PF5_WPORT PORTF #define PF5_PWM NULL #define PF5_DDR DDRF #undef PF6 #define PF6_PIN PINF6 #define PF6_RPORT PINF #define PF6_WPORT PORTF #define PF6_PWM NULL #define PF6_DDR DDRF #undef PF7 #define PF7_PIN PINF7 #define PF7_RPORT PINF #define PF7_WPORT PORTF #define PF7_PWM NULL #define PF7_DDR DDRF #endif #if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) // UART #define RXD DIO0 #define TXD DIO1 // SPI #define SCK DIO10 #define MISO DIO12 #define MOSI DIO11 #define SS DIO16 // TWI (I2C) #define SCL DIO17 #define SDA DIO18 // timers and PWM #define OC0A DIO9 #define OC0B DIO4 #define OC1A DIO7 #define OC1B DIO8 #define OC2A DIO6 #define OC3A DIO5 #define OC3B DIO2 #define OC3C DIO3 // change for your board #define DEBUG_LED DIO46 /* pins */ #define DIO0_PIN PINE0 #define DIO0_RPORT PINE #define DIO0_WPORT PORTE #define DIO0_DDR DDRE #define DIO0_PWM NULL #define DIO1_PIN PINE1 #define DIO1_RPORT PINE #define DIO1_WPORT PORTE #define DIO1_DDR DDRE #define DIO1_PWM NULL #define DIO2_PIN PINE4 #define DIO2_RPORT PINE #define DIO2_WPORT PORTE #define DIO2_DDR DDRE #define DIO2_PWM &OCR3BL #define DIO3_PIN PINE5 #define DIO3_RPORT PINE #define DIO3_WPORT PORTE #define DIO3_DDR DDRE #define DIO3_PWM &OCR3CL #define DIO4_PIN PING5 #define DIO4_RPORT PING #define DIO4_WPORT PORTG #define DIO4_DDR DDRG #define DIO4_PWM &OCR0B #define DIO5_PIN PINE3 #define DIO5_RPORT PINE #define DIO5_WPORT PORTE #define DIO5_DDR DDRE #define DIO5_PWM &OCR3AL #define DIO6_PIN PINB4 #define DIO6_RPORT PINB #define DIO6_WPORT PORTB #define DIO6_DDR DDRB #define DIO6_PWM &OCR2AL #define DIO7_PIN PINB5 #define DIO7_RPORT PINB #define DIO7_WPORT PORTB #define DIO7_DDR DDRB #define DIO7_PWM &OCR1AL #define DIO8_PIN PINB6 #define DIO8_RPORT PINB #define DIO8_WPORT PORTB #define DIO8_DDR DDRB #define DIO8_PWM &OCR1BL #define DIO9_PIN PINB7 #define DIO9_RPORT PINB #define DIO9_WPORT PORTB #define DIO9_DDR DDRB #define DIO9_PWM &OCR0AL #define DIO10_PIN PINB1 #define DIO10_RPORT PINB #define DIO10_WPORT PORTB #define DIO10_DDR DDRB #define DIO10_PWM NULL #define DIO11_PIN PINB2 #define DIO11_RPORT PINB #define DIO11_WPORT PORTB #define DIO11_DDR DDRB #define DIO11_PWM NULL #define DIO12_PIN PINB3 #define DIO12_RPORT PINB #define DIO12_WPORT PORTB #define DIO12_DDR DDRB #define DIO12_PWM NULL #define DIO13_PIN PINE2 #define DIO13_RPORT PINE #define DIO13_WPORT PORTE #define DIO13_DDR DDRE #define DIO13_PWM NULL #define DIO14_PIN PINE6 #define DIO14_RPORT PINE #define DIO14_WPORT PORTE #define DIO14_DDR DDRE #define DIO14_PWM NULL #define DIO15_PIN PINE7 #define DIO15_RPORT PINE #define DIO15_WPORT PORTE #define DIO15_DDR DDRE #define DIO15_PWM NULL #define DIO16_PIN PINB0 #define DIO16_RPORT PINB #define DIO16_WPORT PORTB #define DIO16_DDR DDRB #define DIO16_PWM NULL #define DIO17_PIN PIND0 #define DIO17_RPORT PIND #define DIO17_WPORT PORTD #define DIO17_DDR DDRD #define DIO17_PWM NULL #define DIO18_PIN PIND1 #define DIO18_RPORT PIND #define DIO18_WPORT PORTD #define DIO18_DDR DDRD #define DIO18_PWM NULL #define DIO19_PIN PIND2 #define DIO19_RPORT PIND #define DIO19_WPORT PORTD #define DIO19_DDR DDRD #define DIO19_PWM NULL #define DIO20_PIN PIND3 #define DIO20_RPORT PIND #define DIO20_WPORT PORTD #define DIO20_DDR DDRD #define DIO20_PWM NULL #define DIO21_PIN PIND4 #define DIO21_RPORT PIND #define DIO21_WPORT PORTD #define DIO21_DDR DDRD #define DIO21_PWM NULL #define DIO22_PIN PIND5 #define DIO22_RPORT PIND #define DIO22_WPORT PORTD #define DIO22_DDR DDRD #define DIO22_PWM NULL #define DIO23_PIN PIND6 #define DIO23_RPORT PIND #define DIO23_WPORT PORTD #define DIO23_DDR DDRD #define DIO23_PWM NULL #define DIO24_PIN PIND7 #define DIO24_RPORT PIND #define DIO24_WPORT PORTD #define DIO24_DDR DDRD #define DIO24_PWM NULL #define DIO25_PIN PING0 #define DIO25_RPORT PING #define DIO25_WPORT PORTG #define DIO25_DDR DDRG #define DIO25_PWM NULL #define DIO26_PIN PING1 #define DIO26_RPORT PING #define DIO26_WPORT PORTG #define DIO26_DDR DDRG #define DIO26_PWM NULL #define DIO27_PIN PING2 #define DIO27_RPORT PING #define DIO27_WPORT PORTG #define DIO27_DDR DDRG #define DIO27_PWM NULL #define DIO28_PIN PING3 #define DIO28_RPORT PING #define DIO28_WPORT PORTG #define DIO28_DDR DDRG #define DIO28_PWM NULL #define DIO29_PIN PING4 #define DIO29_RPORT PING #define DIO29_WPORT PORTG #define DIO29_DDR DDRG #define DIO29_PWM NULL #define DIO30_PIN PINC0 #define DIO30_RPORT PINC #define DIO30_WPORT PORTC #define DIO30_DDR DDRC #define DIO30_PWM NULL #define DIO31_PIN PINC1 #define DIO31_RPORT PINC #define DIO31_WPORT PORTC #define DIO31_DDR DDRC #define DIO31_PWM NULL #define DIO32_PIN PINC2 #define DIO32_RPORT PINC #define DIO32_WPORT PORTC #define DIO32_DDR DDRC #define DIO32_PWM NULL #define DIO33_PIN PINC3 #define DIO33_RPORT PINC #define DIO33_WPORT PORTC #define DIO33_DDR DDRC #define DIO33_PWM NULL #define DIO34_PIN PINC4 #define DIO34_RPORT PINC #define DIO34_WPORT PORTC #define DIO34_DDR DDRC #define DIO34_PWM NULL #define DIO35_PIN PINC5 #define DIO35_RPORT PINC #define DIO35_WPORT PORTC #define DIO35_DDR DDRC #define DIO35_PWM NULL #define DIO36_PIN PINC6 #define DIO36_RPORT PINC #define DIO36_WPORT PORTC #define DIO36_DDR DDRC #define DIO36_PWM NULL #define DIO37_PIN PINC7 #define DIO37_RPORT PINC #define DIO37_WPORT PORTC #define DIO37_DDR DDRC #define DIO37_PWM NULL #define DIO38_PIN PINA0 #define DIO38_RPORT PINA #define DIO38_WPORT PORTA #define DIO38_DDR DDRA #define DIO38_PWM NULL #define DIO39_PIN PINA1 #define DIO39_RPORT PINA #define DIO39_WPORT PORTA #define DIO39_DDR DDRA #define DIO39_PWM NULL #define DIO40_PIN PINA2 #define DIO40_RPORT PINA #define DIO40_WPORT PORTA #define DIO40_DDR DDRA #define DIO40_PWM NULL #define DIO41_PIN PINA3 #define DIO41_RPORT PINA #define DIO41_WPORT PORTA #define DIO41_DDR DDRA #define DIO41_PWM NULL #define DIO42_PIN PINA4 #define DIO42_RPORT PINA #define DIO42_WPORT PORTA #define DIO42_DDR DDRA #define DIO42_PWM NULL #define DIO43_PIN PINA5 #define DIO43_RPORT PINA #define DIO43_WPORT PORTA #define DIO43_DDR DDRA #define DIO43_PWM NULL #define DIO44_PIN PINA6 #define DIO44_RPORT PINA #define DIO44_WPORT PORTA #define DIO44_DDR DDRA #define DIO44_PWM NULL #define DIO45_PIN PINA7 #define DIO45_RPORT PINA #define DIO45_WPORT PORTA #define DIO45_DDR DDRA #define DIO45_PWM NULL #define DIO46_PIN PINF0 #define DIO46_RPORT PINF #define DIO46_WPORT PORTF #define DIO46_DDR DDRF #define DIO46_PWM NULL #define DIO47_PIN PINF1 #define DIO47_RPORT PINF #define DIO47_WPORT PORTF #define DIO47_DDR DDRF #define DIO47_PWM NULL #define DIO48_PIN PINF2 #define DIO48_RPORT PINF #define DIO48_WPORT PORTF #define DIO48_DDR DDRF #define DIO48_PWM NULL #define DIO49_PIN PINF3 #define DIO49_RPORT PINF #define DIO49_WPORT PORTF #define DIO49_DDR DDRF #define DIO49_PWM NULL #define DIO50_PIN PINF4 #define DIO50_RPORT PINF #define DIO50_WPORT PORTF #define DIO50_DDR DDRF #define DIO50_PWM NULL #define DIO51_PIN PINF5 #define DIO51_RPORT PINF #define DIO51_WPORT PORTF #define DIO51_DDR DDRF #define DIO51_PWM NULL #define DIO52_PIN PINF6 #define DIO52_RPORT PINF #define DIO52_WPORT PORTF #define DIO52_DDR DDRF #define DIO52_PWM NULL #define DIO53_PIN PINF7 #define DIO53_RPORT PINF #define DIO53_WPORT PORTF #define DIO53_DDR DDRF #define DIO53_PWM NULL #undef PA0 #define PA0_PIN PINA0 #define PA0_RPORT PINA #define PA0_WPORT PORTA #define PA0_DDR DDRA #define PA0_PWM NULL #undef PA1 #define PA1_PIN PINA1 #define PA1_RPORT PINA #define PA1_WPORT PORTA #define PA1_DDR DDRA #define PA1_PWM NULL #undef PA2 #define PA2_PIN PINA2 #define PA2_RPORT PINA #define PA2_WPORT PORTA #define PA2_DDR DDRA #define PA2_PWM NULL #undef PA3 #define PA3_PIN PINA3 #define PA3_RPORT PINA #define PA3_WPORT PORTA #define PA3_DDR DDRA #define PA3_PWM NULL #undef PA4 #define PA4_PIN PINA4 #define PA4_RPORT PINA #define PA4_WPORT PORTA #define PA4_DDR DDRA #define PA4_PWM NULL #undef PA5 #define PA5_PIN PINA5 #define PA5_RPORT PINA #define PA5_WPORT PORTA #define PA5_DDR DDRA #define PA5_PWM NULL #undef PA6 #define PA6_PIN PINA6 #define PA6_RPORT PINA #define PA6_WPORT PORTA #define PA6_DDR DDRA #define PA6_PWM NULL #undef PA7 #define PA7_PIN PINA7 #define PA7_RPORT PINA #define PA7_WPORT PORTA #define PA7_DDR DDRA #define PA7_PWM NULL #undef PB0 #define PB0_PIN PINB0 #define PB0_RPORT PINB #define PB0_WPORT PORTB #define PB0_DDR DDRB #define PB0_PWM NULL #undef PB1 #define PB1_PIN PINB1 #define PB1_RPORT PINB #define PB1_WPORT PORTB #define PB1_DDR DDRB #define PB1_PWM NULL #undef PB2 #define PB2_PIN PINB2 #define PB2_RPORT PINB #define PB2_WPORT PORTB #define PB2_DDR DDRB #define PB2_PWM NULL #undef PB3 #define PB3_PIN PINB3 #define PB3_RPORT PINB #define PB3_WPORT PORTB #define PB3_DDR DDRB #define PB3_PWM NULL #undef PB4 #define PB4_PIN PINB4 #define PB4_RPORT PINB #define PB4_WPORT PORTB #define PB4_DDR DDRB #define PB4_PWM &OCR2A #undef PB5 #define PB5_PIN PINB5 #define PB5_RPORT PINB #define PB5_WPORT PORTB #define PB5_DDR DDRB #define PB5_PWM NULL #undef PB6 #define PB6_PIN PINB6 #define PB6_RPORT PINB #define PB6_WPORT PORTB #define PB6_DDR DDRB #define PB6_PWM NULL #undef PB7 #define PB7_PIN PINB7 #define PB7_RPORT PINB #define PB7_WPORT PORTB #define PB7_DDR DDRB #define PB7_PWM &OCR0A #undef PC0 #define PC0_PIN PINC0 #define PC0_RPORT PINC #define PC0_WPORT PORTC #define PC0_DDR DDRC #define PC0_PWM NULL #undef PC1 #define PC1_PIN PINC1 #define PC1_RPORT PINC #define PC1_WPORT PORTC #define PC1_DDR DDRC #define PC1_PWM NULL #undef PC2 #define PC2_PIN PINC2 #define PC2_RPORT PINC #define PC2_WPORT PORTC #define PC2_DDR DDRC #define PC2_PWM NULL #undef PC3 #define PC3_PIN PINC3 #define PC3_RPORT PINC #define PC3_WPORT PORTC #define PC3_DDR DDRC #define PC3_PWM NULL #undef PC4 #define PC4_PIN PINC4 #define PC4_RPORT PINC #define PC4_WPORT PORTC #define PC4_DDR DDRC #define PC4_PWM NULL #undef PC5 #define PC5_PIN PINC5 #define PC5_RPORT PINC #define PC5_WPORT PORTC #define PC5_DDR DDRC #define PC5_PWM NULL #undef PC6 #define PC6_PIN PINC6 #define PC6_RPORT PINC #define PC6_WPORT PORTC #define PC6_DDR DDRC #define PC6_PWM NULL #undef PC7 #define PC7_PIN PINC7 #define PC7_RPORT PINC #define PC7_WPORT PORTC #define PC7_DDR DDRC #define PC7_PWM NULL #undef PD0 #define PD0_PIN PIND0 #define PD0_RPORT PIND #define PD0_WPORT PORTD #define PD0_DDR DDRD #define PD0_PWM NULL #undef PD1 #define PD1_PIN PIND1 #define PD1_RPORT PIND #define PD1_WPORT PORTD #define PD1_DDR DDRD #define PD1_PWM NULL #undef PD2 #define PD2_PIN PIND2 #define PD2_RPORT PIND #define PD2_WPORT PORTD #define PD2_DDR DDRD #define PD2_PWM NULL #undef PD3 #define PD3_PIN PIND3 #define PD3_RPORT PIND #define PD3_WPORT PORTD #define PD3_DDR DDRD #define PD3_PWM NULL #undef PD4 #define PD4_PIN PIND4 #define PD4_RPORT PIND #define PD4_WPORT PORTD #define PD4_DDR DDRD #define PD4_PWM NULL #undef PD5 #define PD5_PIN PIND5 #define PD5_RPORT PIND #define PD5_WPORT PORTD #define PD5_DDR DDRD #define PD5_PWM NULL #undef PD6 #define PD6_PIN PIND6 #define PD6_RPORT PIND #define PD6_WPORT PORTD #define PD6_DDR DDRD #define PD6_PWM NULL #undef PD7 #define PD7_PIN PIND7 #define PD7_RPORT PIND #define PD7_WPORT PORTD #define PD7_DDR DDRD #define PD7_PWM NULL #undef PE0 #define PE0_PIN PINE0 #define PE0_RPORT PINE #define PE0_WPORT PORTE #define PE0_DDR DDRE #define PE0_PWM NULL #undef PE1 #define PE1_PIN PINE1 #define PE1_RPORT PINE #define PE1_WPORT PORTE #define PE1_DDR DDRE #define PE1_PWM NULL #undef PE2 #define PE2_PIN PINE2 #define PE2_RPORT PINE #define PE2_WPORT PORTE #define PE2_DDR DDRE #define PE2_PWM NULL #undef PE3 #define PE3_PIN PINE3 #define PE3_RPORT PINE #define PE3_WPORT PORTE #define PE3_DDR DDRE #define PE3_PWM &OCR3AL #undef PE4 #define PE4_PIN PINE4 #define PE4_RPORT PINE #define PE4_WPORT PORTE #define PE4_DDR DDRE #define PE4_PWM &OCR3BL #undef PE5 #define PE5_PIN PINE5 #define PE5_RPORT PINE #define PE5_WPORT PORTE #define PE5_DDR DDRE #define PE5_PWM &OCR3CL #undef PE6 #define PE6_PIN PINE6 #define PE6_RPORT PINE #define PE6_WPORT PORTE #define PE6_DDR DDRE #define PE6_PWM NULL #undef PE7 #define PE7_PIN PINE7 #define PE7_RPORT PINE #define PE7_WPORT PORTE #define PE7_DDR DDRE #define PE7_PWM NULL #undef PF0 #define PF0_PIN PINF0 #define PF0_RPORT PINF #define PF0_WPORT PORTF #define PF0_DDR DDRF #define PF0_PWM NULL #undef PF1 #define PF1_PIN PINF1 #define PF1_RPORT PINF #define PF1_WPORT PORTF #define PF1_DDR DDRF #define PF1_PWM NULL #undef PF2 #define PF2_PIN PINF2 #define PF2_RPORT PINF #define PF2_WPORT PORTF #define PF2_DDR DDRF #define PF2_PWM NULL #undef PF3 #define PF3_PIN PINF3 #define PF3_RPORT PINF #define PF3_WPORT PORTF #define PF3_DDR DDRF #define PF3_PWM NULL #undef PF4 #define PF4_PIN PINF4 #define PF4_RPORT PINF #define PF4_WPORT PORTF #define PF4_DDR DDRF #define PF4_PWM NULL #undef PF5 #define PF5_PIN PINF5 #define PF5_RPORT PINF #define PF5_WPORT PORTF #define PF5_DDR DDRF #define PF5_PWM NULL #undef PF6 #define PF6_PIN PINF6 #define PF6_RPORT PINF #define PF6_WPORT PORTF #define PF6_DDR DDRF #define PF6_PWM NULL #undef PF7 #define PF7_PIN PINF7 #define PF7_RPORT PINF #define PF7_WPORT PORTF #define PF7_DDR DDRF #define PF7_PWM NULL #undef PG0 #define PG0_PIN PING0 #define PG0_RPORT PING #define PG0_WPORT PORTG #define PG0_DDR DDRG #define PG0_PWM NULL #undef PG1 #define PG1_PIN PING1 #define PG1_RPORT PING #define PG1_WPORT PORTG #define PG1_DDR DDRG #define PG1_PWM NULL #undef PG2 #define PG2_PIN PING2 #define PG2_RPORT PING #define PG2_WPORT PORTG #define PG2_DDR DDRG #define PG2_PWM NULL #undef PG3 #define PG3_PIN PING3 #define PG3_RPORT PING #define PG3_WPORT PORTG #define PG3_DDR DDRG #define PG3_PWM NULL #undef PG4 #define PG4_PIN PING4 #define PG4_RPORT PING #define PG4_WPORT PORTG #define PG4_DDR DDRG #define PG4_PWM NULL #undef PG5 #define PG5_PIN PING5 #define PG5_RPORT PING #define PG5_WPORT PORTG #define PG5_DDR DDRG #define PG5_PWM &OCR0B #endif #ifndef DIO0_PIN #error pins for this chip not defined in arduino.h! If you write an appropriate pin definition and have this firmware work on your chip, please submit a pull request #endif #endif /* _FASTIO_ARDUINO_H */
66,455
C++
.h
2,926
21.549556
165
0.784873
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,900
language.h
tenlog_TL-D3/Marlin/language.h
#ifndef LANGUAGE_H #define LANGUAGE_H // NOTE: IF YOU CHANGE THIS FILE / MERGE THIS FILE WITH CHANGES // // ==> ALWAYS TRY TO COMPILE MARLIN WITH/WITHOUT "ULTIPANEL" / "ULTRALCD" / "SDSUPPORT" #define IN "Configuration.h" // ==> ALSO TRY ALL AVAILABLE "LANGUAGE_CHOICE" OPTIONS // Languages // 1 English // 2 Polish // 3 French // 4 German // 5 Spanish // 6 Russian // 7 Italian // 8 Portuguese // 9 Finnish #ifndef LANGUAGE_CHOICE #define LANGUAGE_CHOICE 1 // Pick your language from the list above #endif #define MACHINE_NAME "TL 3D Printer" #define FIRMWARE_URL "https://www.github.com/tenlog" #define STRINGIFY_(n) #n #define STRINGIFY(n) STRINGIFY_(n) #if LANGUAGE_CHOICE == 1 // LCD Menu Messages #define WELCOME_MSG MACHINE_NAME " Ready." #define MSG_SD_INSERTED "Card inserted" #define MSG_SD_REMOVED "Card removed" #define MSG_MAIN "Main" #define MSG_AUTOSTART "Autostart" #define MSG_DISABLE_STEPPERS "Disable Steppers" #define MSG_AUTO_HOME "Auto Home" #define MSG_SET_ORIGIN "Set Origin" #define MSG_PREHEAT_PLA "Preheat PLA" #define MSG_PREHEAT_PLA_SETTINGS "Preheat PLA Conf" #define MSG_PREHEAT_ABS "Preheat ABS" #define MSG_PREHEAT_ABS_SETTINGS "Preheat ABS Conf" #define MSG_COOLDOWN "Cooldown" #define MSG_EXTRUDE "Extrude" #define MSG_RETRACT "Retract" #define MSG_MOVE_AXIS "Move Axis" #define MSG_SPEED "Speed" #define MSG_NOZZLE "Nozzle" #define MSG_NOZZLE1 "Nozzle2" #define MSG_NOZZLE2 "Nozzle3" #define MSG_BED "Bed" #define MSG_FAN_SPEED "Fan speed" #define MSG_FLOW "Flow" #define MSG_CONTROL "Control" #define MSG_MIN " \002 Min" #define MSG_MAX " \002 Max" #define MSG_FACTOR " \002 Fact" #define MSG_AUTOTEMP "Autotemp" #define MSG_ON "On " #define MSG_OFF "Off" #define MSG_PID_P "PID-P" #define MSG_PID_I "PID-I" #define MSG_PID_D "PID-D" #define MSG_PID_C "PID-C" #define MSG_ACC "Accel" #define MSG_VXY_JERK "Vxy-jerk" #define MSG_VZ_JERK "Vz-jerk" #define MSG_VE_JERK "Ve-jerk" #define MSG_VMAX "Vmax " #define MSG_X "x" #define MSG_Y "y" #define MSG_Z "z" #define MSG_E "e" #define MSG_VMIN "Vmin" #define MSG_VTRAV_MIN "VTrav min" #define MSG_AMAX "Amax " #define MSG_A_RETRACT "A-retract" #define MSG_XSTEPS "Xs./mm" #define MSG_YSTEPS "Ys./mm" #define MSG_ZSTEPS "Zs./mm" #define MSG_ESTEPS "Es./mm" #define MSG_RECTRACT "Rectract" #define MSG_TEMPERATURE "Temperature" #define MSG_MOTION "Motion" #define MSG_CONTRAST "LCD contrast" #define MSG_STORE_EPROM "Store memory" #define MSG_LOAD_EPROM "Load memory" #define MSG_RESTORE_FAILSAFE "Restore Failsafe" #define MSG_REFRESH "Refresh" #define MSG_WATCH "Info screen" #define MSG_PREPARE "Prepare" #define MSG_TUNE "Tune" #define MSG_PAUSE_PRINT "Pause Print" #define MSG_RESUME_PRINT "Resume Print" #define MSG_STOP_PRINT_1 "Stop Print" #define MSG_CARD_MENU "Print from SD" #define MSG_NO_CARD "No Card" #define MSG_DWELL "Sleep..." #define MSG_USERWAIT "Wait for user..." #define MSG_RESUMING "Resuming print" #define MSG_NO_MOVE "No move." #define MSG_KILLED "KILLED. " #define MSG_STOPPED "STOPPED. " #define MSG_CONTROL_RETRACT "Retract mm" #define MSG_CONTROL_RETRACTF "Retract F" #define MSG_CONTROL_RETRACT_ZLIFT "Hop mm" #define MSG_CONTROL_RETRACT_RECOVER "UnRet +mm" #define MSG_CONTROL_RETRACT_RECOVERF "UnRet F" #define MSG_AUTORETRACT "AutoRetr." #define MSG_FILAMENTCHANGE "Change filament" #define MSG_INIT_SDCARD "Init. SD-Card" #define MSG_CNG_SDCARD "Change SD-Card" #define MSG_POWER_FAIL_RESUME "Power fail resume" #define MSG_POWER_FAIL_RESUME_0 "Power fail resume..." #define MSG_LOAD_FILAMENT "Load Filament" #define MSG_UNLOAD_FILAMENT "Unload Filament" // Serial Console Messages #define MSG_Enqueing "enqueing \"" #define MSG_POWERUP "PowerUp" #define MSG_EXTERNAL_RESET " External Reset" #define MSG_BROWNOUT_RESET " Brown out Reset" #define MSG_WATCHDOG_RESET " Watchdog Reset" #define MSG_SOFTWARE_RESET " Software Reset" #define MSG_MARLIN "Marlin " #define MSG_AUTHOR " | Author: " #define MSG_CONFIGURATION_VER " Last Updated: " #define MSG_FREE_MEMORY " Free Memory: " #define MSG_PLANNER_BUFFER_BYTES " PlannerBufferBytes: " #define MSG_OK "ok" #define MSG_FILE_SAVED "Done saving file." #define MSG_ERR_LINE_NO "Line Number is not Last Line Number+1, Last Line: " #define MSG_ERR_CHECKSUM_MISMATCH "checksum mismatch, Last Line: " #define MSG_ERR_NO_CHECKSUM "No Checksum with line number, Last Line: " #define MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM "No Line Number with checksum, Last Line: " #define MSG_FILE_PRINTED "Done printing file" #define MSG_BEGIN_FILE_LIST "Begin file list" #define MSG_END_FILE_LIST "End file list" #define MSG_M104_INVALID_EXTRUDER "M104 Invalid extruder " #define MSG_M105_INVALID_EXTRUDER "M105 Invalid extruder " #define MSG_M218_INVALID_EXTRUDER "M218 Invalid extruder " #define MSG_ERR_NO_THERMISTORS "No thermistors - no temperature" #define MSG_M109_INVALID_EXTRUDER "M109 Invalid extruder " #define MSG_HEATING "Heating..." #define MSG_HEATING_COMPLETE "Heating done." #define MSG_BED_HEATING "Bed Heating." #define MSG_BED_DONE "Bed done." #define MSG_M115_REPORT "FIRMWARE_NAME:Marlin V1; Sprinter/grbl mashup for gen6 FIRMWARE_URL:" FIRMWARE_URL " PROTOCOL_VERSION:" PROTOCOL_VERSION " MACHINE_TYPE:" MACHINE_NAME " EXTRUDER_COUNT:" STRINGIFY(EXTRUDERS) "\n" #define MSG_COUNT_X " Count X: " #define MSG_ERR_KILLED "Printer halted. kill() called!" #define MSG_ERR_STOPPED "Printer stopped due to errors. Fix the error and use M999 to restart. (Temperature is reset. Set it after restarting)" #define MSG_RESEND "Resend: " #define MSG_UNKNOWN_COMMAND "Unknown command: \"" #define MSG_ACTIVE_EXTRUDER "Active Extruder: " #define MSG_INVALID_EXTRUDER "Invalid extruder" #define MSG_X_MIN "x_min: " #define MSG_X_MAX "x_max: " #define MSG_Y_MIN "y_min: " #define MSG_Y_MAX "y_max: " #define MSG_Z_MIN "z_min: " #define MSG_Z_MAX "z_max: " #define MSG_M119_REPORT "Reporting endstop status" #define MSG_ENDSTOP_HIT "TRIGGERED" #define MSG_ENDSTOP_OPEN "open" #define MSG_HOTEND_OFFSET "Hotend offsets:" #define MSG_SD_CANT_OPEN_SUBDIR "Cannot open subdir" #define MSG_SD_INIT_FAIL "SD init fail" #define MSG_SD_VOL_INIT_FAIL "volume.init failed" #define MSG_SD_OPENROOT_FAIL "openRoot failed" #define MSG_SD_CARD_OK "SD card ok" #define MSG_SD_WORKDIR_FAIL "workDir open failed" #define MSG_SD_OPEN_FILE_FAIL "open failed, File: " #define MSG_SD_FILE_OPENED "File opened: " #define MSG_SD_SIZE " Size: " #define MSG_SD_FILE_SELECTED "File selected" #define MSG_SD_WRITE_TO_FILE "Writing to file: " #define MSG_SD_PRINTING_BYTE "SD printing byte " #define MSG_SD_NOT_PRINTING "Not SD printing" #define MSG_SD_ERR_WRITE_TO_FILE "error writing to file" #define MSG_SD_CANT_ENTER_SUBDIR "Cannot enter subdir: " #define MSG_STEPPER_TOO_HIGH "Steprate too high: " #define MSG_ENDSTOPS_HIT "endstops hit: " #define MSG_ERR_COLD_EXTRUDE_STOP " cold extrusion prevented" #define MSG_ERR_LONG_EXTRUDE_STOP " too long extrusion prevented" #endif #endif // ifndef LANGUAGE_H
6,955
C++
.h
180
37.561111
220
0.759947
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,901
planner.h
tenlog_TL-D3/Marlin/planner.h
/* planner.h - buffers movement commands and manages the acceleration profile plan Part of Grbl Copyright (c) 2009-2011 Simen Svale Skogsrud Copyright (C) 2016-2019 zyf@tenlog3d.com Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ // This module is to be considered a sub-module of stepper.c. Please don't include // this file from any other module. #ifndef planner_h #define planner_h #include "Marlin.h" // This struct is used when buffering the setup for each linear movement "nominal" values are as specified in // the source g-code and may never actually be reached if acceleration management is active. typedef struct { // Fields used by the bresenham algorithm for tracing the line long steps_x, steps_y, steps_z, steps_e; // Step count along each axis unsigned long step_event_count; // The number of step events required to complete this block long accelerate_until; // The index of the step event on which to stop acceleration long decelerate_after; // The index of the step event on which to start decelerating long acceleration_rate; // The acceleration rate used for acceleration calculation unsigned char direction_bits; // The direction bit set for this block (refers to *_DIRECTION_BIT in config.h) unsigned char active_extruder; // Selects the active extruder // Fields used by the motion planner to manage acceleration // float speed_x, speed_y, speed_z, speed_e; // Nominal mm/sec for each axis float nominal_speed; // The nominal speed for this block in mm/sec float entry_speed; // Entry speed at previous-current junction in mm/sec float max_entry_speed; // Maximum allowable junction entry speed in mm/sec float millimeters; // The total travel of this block in mm float acceleration; // acceleration mm/sec^2 unsigned char recalculate_flag; // Planner flag to recalculate trapezoids on entry junction unsigned char nominal_length_flag; // Planner flag for nominal speed always reached // Settings for the trapezoid generator unsigned long nominal_rate; // The nominal step rate for this block in step_events/sec unsigned long initial_rate; // The jerk-adjusted step rate at start of block unsigned long final_rate; // The minimal rate at exit unsigned long acceleration_st; // acceleration steps/sec^2 unsigned long fan_speed; #ifdef BARICUDA unsigned long valve_pressure; unsigned long e_to_p_pressure; #endif volatile char busy; } block_t; // Initialize the motion plan subsystem void plan_init(); // Add a new linear movement to the buffer. x, y and z is the signed, absolute target position in // millimaters. Feed rate specifies the speed of the motion. void plan_buffer_line(const float &x, const float &y, const float &z, const float &e, float feed_rate, const uint8_t &extruder); // Set position. Used for G92 instructions. void plan_set_position(const float &x, const float &y, const float &z, const float &e); void plan_set_e_position(const float &e); void check_axes_activity(); uint8_t movesplanned(); //return the nr of buffered moves #ifdef CONFIG_TL extern float tl_X2_MAX_POS; /* extern bool tl_INVERT_X_DIR; extern bool tl_INVERT_Y_DIR; extern bool tl_INVERT_Z_DIR; extern bool tl_INVERT_E0_DIR; extern bool tl_INVERT_E1_DIR; */ extern int tl_HEATER_0_MAXTEMP; extern int tl_HEATER_1_MAXTEMP; extern int tl_BED_MAXTEMP; #endif extern bool tl_HEATER_FAIL; #ifdef CONFIG_E2_OFFSET extern float tl_Y2_OFFSET; extern float tl_Z2_OFFSET; #endif #ifdef FAN2_CONTROL extern int tl_FAN2_VALUE; extern int tl_FAN2_START_TEMP; #endif #ifdef HAS_PLR_MODULE extern int tl_AUTO_OFF; #endif #ifdef TL_DUAL_Z extern int tl_RUN_STATUS; extern int tl_Y_STEP_PIN; extern int tl_Y_DIR_PIN; extern int tl_Y_MIN_PIN; extern int tl_Y_ENDSTOPS_INVERTING; extern bool rep_INVERT_Y_DIR; #endif extern int tl_TouchScreenType; extern int languageID; extern int tl_SLEEP_TIME; extern int iTempErrID; extern String sTempErrMsg; extern String sShortErrMsg; extern int tl_ECO_MODE; //only for dwn screen extern int dwnMessageID; extern long lLEDTimeTimecount; #ifdef PRINT_FROM_Z_HEIGHT extern bool PrintFromZHeightFound; extern float print_from_z_target; #endif #ifdef FILAMENT_FAIL_DETECT extern int tl_Filament_Detect; #endif extern unsigned long minsegmenttime; extern float max_feedrate[4]; // set the max speeds extern float axis_steps_per_unit[4]; extern unsigned long max_acceleration_units_per_sq_second[4]; // Use M201 to override by software extern float minimumfeedrate; extern float acceleration; // Normal acceleration mm/s^2 THIS IS THE DEFAULT ACCELERATION for all moves. M204 SXXXX extern float retract_acceleration; // mm/s^2 filament pull-pack and push-forward while standing still in the other axis M204 TXXXX extern float max_xy_jerk; //speed than can be stopped at once, if i understand correctly. extern float max_z_jerk; extern float max_e_jerk; extern float mintravelfeedrate; extern unsigned long axis_steps_per_sqr_second[NUM_AXIS]; #ifdef AUTOTEMP extern bool autotemp_enabled; extern float autotemp_max; extern float autotemp_min; extern float autotemp_factor; #endif extern block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions extern volatile unsigned char block_buffer_head; // Index of the next block to be pushed extern volatile unsigned char block_buffer_tail; // Called when the current block is no longer needed. Discards the block and makes the memory // availible for new blocks. FORCE_INLINE void plan_discard_current_block() { if (block_buffer_head != block_buffer_tail) { block_buffer_tail = (block_buffer_tail + 1) & (BLOCK_BUFFER_SIZE - 1); } } // Gets the current block. Returns NULL if buffer empty FORCE_INLINE block_t *plan_get_current_block() { if (block_buffer_head == block_buffer_tail) { return (NULL); } block_t *block = &block_buffer[block_buffer_tail]; block->busy = true; return (block); } // Gets the current block. Returns NULL if buffer empty FORCE_INLINE bool blocks_queued() { if (block_buffer_head == block_buffer_tail) { return false; } else return true; } #ifdef PREVENT_DANGEROUS_EXTRUDE void set_extrude_min_temp(float temp); #endif void reset_acceleration_rates(); #endif
6,991
C++
.h
170
39.111765
134
0.754308
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,902
stepper.h
tenlog_TL-D3/Marlin/stepper.h
/* stepper.h - stepper motor driver: executes motion plans of planner.c using the stepper motors Part of Grbl Copyright (c) 2009-2011 Simen Svale Skogsrud Copyright (C) 2016-2019 zyf@tenlog3d.com Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. */ #ifndef stepper_h #define stepper_h #include "planner.h" #if EXTRUDERS > 2 #define WRITE_E_STEP(v) \ { \ if (current_block->active_extruder == 2) \ { \ WRITE(E2_STEP_PIN, v); \ } \ else \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_STEP_PIN, v); \ } \ else \ { \ WRITE(E0_STEP_PIN, v); \ } \ } \ } #define NORM_E_DIR() \ { \ if (current_block->active_extruder == 2) \ { \ WRITE(E2_DIR_PIN, !INVERT_E2_DIR); \ } \ else \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, !INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, !INVERT_E0_DIR); \ } \ } \ } #define REV_E_DIR() \ { \ if (current_block->active_extruder == 2) \ { \ WRITE(E2_DIR_PIN, INVERT_E2_DIR); \ } \ else \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, INVERT_E0_DIR); \ } \ } \ } #elif EXTRUDERS > 1 #ifndef DUAL_X_CARRIAGE #define WRITE_E_STEP(v) \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_STEP_PIN, v); \ } \ else \ { \ WRITE(E0_STEP_PIN, v); \ } \ } #define NORM_E_DIR() \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, !INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, !INVERT_E0_DIR); \ } \ } #define REV_E_DIR() \ { \ if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, INVERT_E0_DIR); \ } \ } #else extern int extruder_carriage_mode; #define WRITE_E_STEP(v) \ { \ if (extruder_carriage_mode == 2 || extruder_carriage_mode == 3) \ { \ WRITE(E0_STEP_PIN, v); \ WRITE(E1_STEP_PIN, v); \ } \ else if (current_block->active_extruder == 1) \ { \ WRITE(E1_STEP_PIN, v); \ } \ else \ { \ WRITE(E0_STEP_PIN, v); \ } \ } #define NORM_E_DIR() \ { \ if (extruder_carriage_mode == 2 || extruder_carriage_mode == 3) \ { \ WRITE(E0_DIR_PIN, !INVERT_E0_DIR); \ WRITE(E1_DIR_PIN, !INVERT_E1_DIR); \ } \ else if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, !INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, !INVERT_E0_DIR); \ } \ } #define REV_E_DIR() \ { \ if (extruder_carriage_mode == 2 || extruder_carriage_mode == 3) \ { \ WRITE(E0_DIR_PIN, INVERT_E0_DIR); \ WRITE(E1_DIR_PIN, INVERT_E1_DIR); \ } \ else if (current_block->active_extruder == 1) \ { \ WRITE(E1_DIR_PIN, INVERT_E1_DIR); \ } \ else \ { \ WRITE(E0_DIR_PIN, INVERT_E0_DIR); \ } \ } #endif #else #define WRITE_E_STEP(v) WRITE(E0_STEP_PIN, v) #define NORM_E_DIR() WRITE(E0_DIR_PIN, !INVERT_E0_DIR) #define REV_E_DIR() WRITE(E0_DIR_PIN, INVERT_E0_DIR) #endif #ifdef ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED extern bool abort_on_endstop_hit; #endif // Initialize and start the stepper motor subsystem void st_init(); // Block until all buffered steps are executed void st_synchronize(); // Set current position in steps void st_set_position(const long &x, const long &y, const long &z, const long &e); void st_set_e_position(const long &e); // Get current position in steps long st_get_position(uint8_t axis); // The stepper subsystem goes to sleep when it runs out of things to execute. Call this // to notify the subsystem that it is time to go to work. void st_wake_up(); void checkHitEndstops(); //call from somwhere to create an serial error message with the locations the endstops where hit, in case they were triggered void endstops_hit_on_purpose(); //avoid creation of the message, i.e. after homeing and before a routine call of checkHitEndstops(); void enable_endstops(bool check, int Axis); // Enable/disable endstop checking void checkStepperErrors(); //Print errors detected by the stepper void finishAndDisableSteppers(bool Finished); extern block_t *current_block; // A pointer to the block currently being traced void quickStop(); void digitalPotWrite(int address, int value); void microstep_ms(uint8_t driver, int8_t ms1, int8_t ms2); void microstep_mode(uint8_t driver, uint8_t stepping); void digipot_init(); void digipot_current(uint8_t driver, int current); void microstep_init(); void microstep_readings(); #endif
9,743
C++
.h
195
45.789744
157
0.339351
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,903
thermistortables.h
tenlog_TL-D3/Marlin/thermistortables.h
#ifndef THERMISTORTABLES_H_ #define THERMISTORTABLES_H_ #include "Marlin.h" #define OVERSAMPLENR 16 #if (THERMISTORHEATER_0 == 1) || (THERMISTORHEATER_1 == 1) || (THERMISTORHEATER_2 == 1) || (THERMISTORBED == 1) //100k thermistor const short temptable_1[][2] PROGMEM = { {23 * OVERSAMPLENR, 300}, {25 * OVERSAMPLENR, 295}, {27 * OVERSAMPLENR, 290}, {28 * OVERSAMPLENR, 285}, {31 * OVERSAMPLENR, 280}, {33 * OVERSAMPLENR, 275}, {35 * OVERSAMPLENR, 270}, {38 * OVERSAMPLENR, 265}, {41 * OVERSAMPLENR, 260}, {44 * OVERSAMPLENR, 255}, {48 * OVERSAMPLENR, 250}, {52 * OVERSAMPLENR, 245}, {56 * OVERSAMPLENR, 240}, {61 * OVERSAMPLENR, 235}, {66 * OVERSAMPLENR, 230}, {71 * OVERSAMPLENR, 225}, {78 * OVERSAMPLENR, 220}, {84 * OVERSAMPLENR, 215}, {92 * OVERSAMPLENR, 210}, {100 * OVERSAMPLENR, 205}, {109 * OVERSAMPLENR, 200}, {120 * OVERSAMPLENR, 195}, {131 * OVERSAMPLENR, 190}, {143 * OVERSAMPLENR, 185}, {156 * OVERSAMPLENR, 180}, {171 * OVERSAMPLENR, 175}, {187 * OVERSAMPLENR, 170}, {205 * OVERSAMPLENR, 165}, {224 * OVERSAMPLENR, 160}, {245 * OVERSAMPLENR, 155}, {268 * OVERSAMPLENR, 150}, {293 * OVERSAMPLENR, 145}, {320 * OVERSAMPLENR, 140}, {348 * OVERSAMPLENR, 135}, {379 * OVERSAMPLENR, 130}, {411 * OVERSAMPLENR, 125}, {445 * OVERSAMPLENR, 120}, {480 * OVERSAMPLENR, 115}, {516 * OVERSAMPLENR, 110}, {553 * OVERSAMPLENR, 105}, {591 * OVERSAMPLENR, 100}, {628 * OVERSAMPLENR, 95}, {665 * OVERSAMPLENR, 90}, {702 * OVERSAMPLENR, 85}, {737 * OVERSAMPLENR, 80}, {770 * OVERSAMPLENR, 75}, {801 * OVERSAMPLENR, 70}, {830 * OVERSAMPLENR, 65}, {857 * OVERSAMPLENR, 60}, {881 * OVERSAMPLENR, 55}, {903 * OVERSAMPLENR, 50}, {922 * OVERSAMPLENR, 45}, {939 * OVERSAMPLENR, 40}, {954 * OVERSAMPLENR, 35}, {966 * OVERSAMPLENR, 30}, {977 * OVERSAMPLENR, 25}, {985 * OVERSAMPLENR, 20}, {993 * OVERSAMPLENR, 15}, {999 * OVERSAMPLENR, 10}, {1004 * OVERSAMPLENR, 5}, {1008 * OVERSAMPLENR, 0} //safety }; #endif #if (THERMISTORHEATER_0 == 2) || (THERMISTORHEATER_1 == 2) || (THERMISTORHEATER_2 == 2) || (THERMISTORBED == 2) //200k bed thermistor const short temptable_2[][2] PROGMEM = { //200k ATC Semitec 204GT-2 //Verified by linagee. Source: http://shop.arcol.hu/static/datasheets/thermistors.pdf // Calculated using 4.7kohm pullup, voltage divider math, and manufacturer provided temp/resistance {1 * OVERSAMPLENR, 848}, {30 * OVERSAMPLENR, 300}, //top rating 300C {34 * OVERSAMPLENR, 290}, {39 * OVERSAMPLENR, 280}, {46 * OVERSAMPLENR, 270}, {53 * OVERSAMPLENR, 260}, {63 * OVERSAMPLENR, 250}, {74 * OVERSAMPLENR, 240}, {87 * OVERSAMPLENR, 230}, {104 * OVERSAMPLENR, 220}, {124 * OVERSAMPLENR, 210}, {148 * OVERSAMPLENR, 200}, {176 * OVERSAMPLENR, 190}, {211 * OVERSAMPLENR, 180}, {252 * OVERSAMPLENR, 170}, {301 * OVERSAMPLENR, 160}, {357 * OVERSAMPLENR, 150}, {420 * OVERSAMPLENR, 140}, {489 * OVERSAMPLENR, 130}, {562 * OVERSAMPLENR, 120}, {636 * OVERSAMPLENR, 110}, {708 * OVERSAMPLENR, 100}, {775 * OVERSAMPLENR, 90}, {835 * OVERSAMPLENR, 80}, {884 * OVERSAMPLENR, 70}, {924 * OVERSAMPLENR, 60}, {955 * OVERSAMPLENR, 50}, {977 * OVERSAMPLENR, 40}, {993 * OVERSAMPLENR, 30}, {1004 * OVERSAMPLENR, 20}, {1012 * OVERSAMPLENR, 10}, {1016 * OVERSAMPLENR, 0}, }; #endif #if (THERMISTORHEATER_0 == 3) || (THERMISTORHEATER_1 == 3) || (THERMISTORHEATER_2 == 3) || (THERMISTORBED == 3) //mendel-parts const short temptable_3[][2] PROGMEM = { {1 * OVERSAMPLENR, 864}, {21 * OVERSAMPLENR, 300}, {25 * OVERSAMPLENR, 290}, {29 * OVERSAMPLENR, 280}, {33 * OVERSAMPLENR, 270}, {39 * OVERSAMPLENR, 260}, {46 * OVERSAMPLENR, 250}, {54 * OVERSAMPLENR, 240}, {64 * OVERSAMPLENR, 230}, {75 * OVERSAMPLENR, 220}, {90 * OVERSAMPLENR, 210}, {107 * OVERSAMPLENR, 200}, {128 * OVERSAMPLENR, 190}, {154 * OVERSAMPLENR, 180}, {184 * OVERSAMPLENR, 170}, {221 * OVERSAMPLENR, 160}, {265 * OVERSAMPLENR, 150}, {316 * OVERSAMPLENR, 140}, {375 * OVERSAMPLENR, 130}, {441 * OVERSAMPLENR, 120}, {513 * OVERSAMPLENR, 110}, {588 * OVERSAMPLENR, 100}, {734 * OVERSAMPLENR, 80}, {856 * OVERSAMPLENR, 60}, {938 * OVERSAMPLENR, 40}, {986 * OVERSAMPLENR, 20}, {1008 * OVERSAMPLENR, 0}, {1018 * OVERSAMPLENR, -20}}; #endif #if (THERMISTORHEATER_0 == 4) || (THERMISTORHEATER_1 == 4) || (THERMISTORHEATER_2 == 4) || (THERMISTORBED == 4) //10k thermistor const short temptable_4[][2] PROGMEM = { {1 * OVERSAMPLENR, 430}, {54 * OVERSAMPLENR, 137}, {107 * OVERSAMPLENR, 107}, {160 * OVERSAMPLENR, 91}, {213 * OVERSAMPLENR, 80}, {266 * OVERSAMPLENR, 71}, {319 * OVERSAMPLENR, 64}, {372 * OVERSAMPLENR, 57}, {425 * OVERSAMPLENR, 51}, {478 * OVERSAMPLENR, 46}, {531 * OVERSAMPLENR, 41}, {584 * OVERSAMPLENR, 35}, {637 * OVERSAMPLENR, 30}, {690 * OVERSAMPLENR, 25}, {743 * OVERSAMPLENR, 20}, {796 * OVERSAMPLENR, 14}, {849 * OVERSAMPLENR, 7}, {902 * OVERSAMPLENR, 0}, {955 * OVERSAMPLENR, -11}, {1008 * OVERSAMPLENR, -35}}; #endif #if (THERMISTORHEATER_0 == 5) || (THERMISTORHEATER_1 == 5) || (THERMISTORHEATER_2 == 5) || (THERMISTORBED == 5) //100k ParCan thermistor (104GT-2) const short temptable_5[][2] PROGMEM = { // ATC Semitec 104GT-2 (Used in ParCan) // Verified by linagee. Source: http://shop.arcol.hu/static/datasheets/thermistors.pdf // Calculated using 4.7kohm pullup, voltage divider math, and manufacturer provided temp/resistance {1 * OVERSAMPLENR, 713}, {17 * OVERSAMPLENR, 300}, //top rating 300C {20 * OVERSAMPLENR, 290}, {23 * OVERSAMPLENR, 280}, {27 * OVERSAMPLENR, 270}, {31 * OVERSAMPLENR, 260}, {37 * OVERSAMPLENR, 250}, {43 * OVERSAMPLENR, 240}, {51 * OVERSAMPLENR, 230}, {61 * OVERSAMPLENR, 220}, {73 * OVERSAMPLENR, 210}, {87 * OVERSAMPLENR, 200}, {106 * OVERSAMPLENR, 190}, {128 * OVERSAMPLENR, 180}, {155 * OVERSAMPLENR, 170}, {189 * OVERSAMPLENR, 160}, {230 * OVERSAMPLENR, 150}, {278 * OVERSAMPLENR, 140}, {336 * OVERSAMPLENR, 130}, {402 * OVERSAMPLENR, 120}, {476 * OVERSAMPLENR, 110}, {554 * OVERSAMPLENR, 100}, {635 * OVERSAMPLENR, 90}, {713 * OVERSAMPLENR, 80}, {784 * OVERSAMPLENR, 70}, {846 * OVERSAMPLENR, 60}, {897 * OVERSAMPLENR, 50}, {937 * OVERSAMPLENR, 40}, {966 * OVERSAMPLENR, 30}, {986 * OVERSAMPLENR, 20}, {1000 * OVERSAMPLENR, 10}, {1010 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 6) || (THERMISTORHEATER_1 == 6) || (THERMISTORHEATER_2 == 6) || (THERMISTORBED == 6) // 100k Epcos thermistor const short temptable_6[][2] PROGMEM = { {1 * OVERSAMPLENR, 350}, {28 * OVERSAMPLENR, 250}, //top rating 250C {31 * OVERSAMPLENR, 245}, {35 * OVERSAMPLENR, 240}, {39 * OVERSAMPLENR, 235}, {42 * OVERSAMPLENR, 230}, {44 * OVERSAMPLENR, 225}, {49 * OVERSAMPLENR, 220}, {53 * OVERSAMPLENR, 215}, {62 * OVERSAMPLENR, 210}, {71 * OVERSAMPLENR, 205}, //fitted graphically {78 * OVERSAMPLENR, 200}, //fitted graphically {94 * OVERSAMPLENR, 190}, {102 * OVERSAMPLENR, 185}, {116 * OVERSAMPLENR, 170}, {143 * OVERSAMPLENR, 160}, {183 * OVERSAMPLENR, 150}, {223 * OVERSAMPLENR, 140}, {270 * OVERSAMPLENR, 130}, {318 * OVERSAMPLENR, 120}, {383 * OVERSAMPLENR, 110}, {413 * OVERSAMPLENR, 105}, {439 * OVERSAMPLENR, 100}, {484 * OVERSAMPLENR, 95}, {513 * OVERSAMPLENR, 90}, {607 * OVERSAMPLENR, 80}, {664 * OVERSAMPLENR, 70}, {781 * OVERSAMPLENR, 60}, {810 * OVERSAMPLENR, 55}, {849 * OVERSAMPLENR, 50}, {914 * OVERSAMPLENR, 45}, {914 * OVERSAMPLENR, 40}, {935 * OVERSAMPLENR, 35}, {954 * OVERSAMPLENR, 30}, {970 * OVERSAMPLENR, 25}, {978 * OVERSAMPLENR, 22}, {1008 * OVERSAMPLENR, 3}, {1023 * OVERSAMPLENR, 0} //to allow internal 0 degrees C }; #endif #if (THERMISTORHEATER_0 == 7) || (THERMISTORHEATER_1 == 7) || (THERMISTORHEATER_2 == 7) || (THERMISTORBED == 7) // 100k Honeywell 135-104LAG-J01 const short temptable_7[][2] PROGMEM = { {1 * OVERSAMPLENR, 941}, {19 * OVERSAMPLENR, 362}, {37 * OVERSAMPLENR, 299}, //top rating 300C {55 * OVERSAMPLENR, 266}, {73 * OVERSAMPLENR, 245}, {91 * OVERSAMPLENR, 229}, {109 * OVERSAMPLENR, 216}, {127 * OVERSAMPLENR, 206}, {145 * OVERSAMPLENR, 197}, {163 * OVERSAMPLENR, 190}, {181 * OVERSAMPLENR, 183}, {199 * OVERSAMPLENR, 177}, {217 * OVERSAMPLENR, 171}, {235 * OVERSAMPLENR, 166}, {253 * OVERSAMPLENR, 162}, {271 * OVERSAMPLENR, 157}, {289 * OVERSAMPLENR, 153}, {307 * OVERSAMPLENR, 149}, {325 * OVERSAMPLENR, 146}, {343 * OVERSAMPLENR, 142}, {361 * OVERSAMPLENR, 139}, {379 * OVERSAMPLENR, 135}, {397 * OVERSAMPLENR, 132}, {415 * OVERSAMPLENR, 129}, {433 * OVERSAMPLENR, 126}, {451 * OVERSAMPLENR, 123}, {469 * OVERSAMPLENR, 121}, {487 * OVERSAMPLENR, 118}, {505 * OVERSAMPLENR, 115}, {523 * OVERSAMPLENR, 112}, {541 * OVERSAMPLENR, 110}, {559 * OVERSAMPLENR, 107}, {577 * OVERSAMPLENR, 105}, {595 * OVERSAMPLENR, 102}, {613 * OVERSAMPLENR, 99}, {631 * OVERSAMPLENR, 97}, {649 * OVERSAMPLENR, 94}, {667 * OVERSAMPLENR, 92}, {685 * OVERSAMPLENR, 89}, {703 * OVERSAMPLENR, 86}, {721 * OVERSAMPLENR, 84}, {739 * OVERSAMPLENR, 81}, {757 * OVERSAMPLENR, 78}, {775 * OVERSAMPLENR, 75}, {793 * OVERSAMPLENR, 72}, {811 * OVERSAMPLENR, 69}, {829 * OVERSAMPLENR, 66}, {847 * OVERSAMPLENR, 62}, {865 * OVERSAMPLENR, 59}, {883 * OVERSAMPLENR, 55}, {901 * OVERSAMPLENR, 51}, {919 * OVERSAMPLENR, 46}, {937 * OVERSAMPLENR, 41}, {955 * OVERSAMPLENR, 35}, {973 * OVERSAMPLENR, 27}, {991 * OVERSAMPLENR, 17}, {1009 * OVERSAMPLENR, 1}, {1023 * OVERSAMPLENR, 0} //to allow internal 0 degrees C }; #endif #if (THERMISTORHEATER_0 == 71) || (THERMISTORHEATER_1 == 71) || (THERMISTORHEATER_2 == 71) || (THERMISTORBED == 71) // 100k Honeywell 135-104LAF-J01 // R0 = 100000 Ohm // T0 = 25 ��C // Beta = 3974 // R1 = 0 Ohm // R2 = 4700 Ohm const short temptable_71[][2] PROGMEM = { {35 * OVERSAMPLENR, 300}, {51 * OVERSAMPLENR, 270}, {54 * OVERSAMPLENR, 265}, {58 * OVERSAMPLENR, 260}, {59 * OVERSAMPLENR, 258}, {61 * OVERSAMPLENR, 256}, {63 * OVERSAMPLENR, 254}, {64 * OVERSAMPLENR, 252}, {66 * OVERSAMPLENR, 250}, {67 * OVERSAMPLENR, 249}, {68 * OVERSAMPLENR, 248}, {69 * OVERSAMPLENR, 247}, {70 * OVERSAMPLENR, 246}, {71 * OVERSAMPLENR, 245}, {72 * OVERSAMPLENR, 244}, {73 * OVERSAMPLENR, 243}, {74 * OVERSAMPLENR, 242}, {75 * OVERSAMPLENR, 241}, {76 * OVERSAMPLENR, 240}, {77 * OVERSAMPLENR, 239}, {78 * OVERSAMPLENR, 238}, {79 * OVERSAMPLENR, 237}, {80 * OVERSAMPLENR, 236}, {81 * OVERSAMPLENR, 235}, {82 * OVERSAMPLENR, 234}, {84 * OVERSAMPLENR, 233}, {85 * OVERSAMPLENR, 232}, {86 * OVERSAMPLENR, 231}, {87 * OVERSAMPLENR, 230}, {89 * OVERSAMPLENR, 229}, {90 * OVERSAMPLENR, 228}, {91 * OVERSAMPLENR, 227}, {92 * OVERSAMPLENR, 226}, {94 * OVERSAMPLENR, 225}, {95 * OVERSAMPLENR, 224}, {97 * OVERSAMPLENR, 223}, {98 * OVERSAMPLENR, 222}, {99 * OVERSAMPLENR, 221}, {101 * OVERSAMPLENR, 220}, {102 * OVERSAMPLENR, 219}, {104 * OVERSAMPLENR, 218}, {106 * OVERSAMPLENR, 217}, {107 * OVERSAMPLENR, 216}, {109 * OVERSAMPLENR, 215}, {110 * OVERSAMPLENR, 214}, {112 * OVERSAMPLENR, 213}, {114 * OVERSAMPLENR, 212}, {115 * OVERSAMPLENR, 211}, {117 * OVERSAMPLENR, 210}, {119 * OVERSAMPLENR, 209}, {121 * OVERSAMPLENR, 208}, {123 * OVERSAMPLENR, 207}, {125 * OVERSAMPLENR, 206}, {126 * OVERSAMPLENR, 205}, {128 * OVERSAMPLENR, 204}, {130 * OVERSAMPLENR, 203}, {132 * OVERSAMPLENR, 202}, {134 * OVERSAMPLENR, 201}, {136 * OVERSAMPLENR, 200}, {139 * OVERSAMPLENR, 199}, {141 * OVERSAMPLENR, 198}, {143 * OVERSAMPLENR, 197}, {145 * OVERSAMPLENR, 196}, {147 * OVERSAMPLENR, 195}, {150 * OVERSAMPLENR, 194}, {152 * OVERSAMPLENR, 193}, {154 * OVERSAMPLENR, 192}, {157 * OVERSAMPLENR, 191}, {159 * OVERSAMPLENR, 190}, {162 * OVERSAMPLENR, 189}, {164 * OVERSAMPLENR, 188}, {167 * OVERSAMPLENR, 187}, {170 * OVERSAMPLENR, 186}, {172 * OVERSAMPLENR, 185}, {175 * OVERSAMPLENR, 184}, {178 * OVERSAMPLENR, 183}, {181 * OVERSAMPLENR, 182}, {184 * OVERSAMPLENR, 181}, {187 * OVERSAMPLENR, 180}, {190 * OVERSAMPLENR, 179}, {193 * OVERSAMPLENR, 178}, {196 * OVERSAMPLENR, 177}, {199 * OVERSAMPLENR, 176}, {202 * OVERSAMPLENR, 175}, {205 * OVERSAMPLENR, 174}, {208 * OVERSAMPLENR, 173}, {212 * OVERSAMPLENR, 172}, {215 * OVERSAMPLENR, 171}, {219 * OVERSAMPLENR, 170}, {237 * OVERSAMPLENR, 165}, {256 * OVERSAMPLENR, 160}, {300 * OVERSAMPLENR, 150}, {351 * OVERSAMPLENR, 140}, {470 * OVERSAMPLENR, 120}, {504 * OVERSAMPLENR, 115}, {538 * OVERSAMPLENR, 110}, {552 * OVERSAMPLENR, 108}, {566 * OVERSAMPLENR, 106}, {580 * OVERSAMPLENR, 104}, {594 * OVERSAMPLENR, 102}, {608 * OVERSAMPLENR, 100}, {622 * OVERSAMPLENR, 98}, {636 * OVERSAMPLENR, 96}, {650 * OVERSAMPLENR, 94}, {664 * OVERSAMPLENR, 92}, {678 * OVERSAMPLENR, 90}, {712 * OVERSAMPLENR, 85}, {745 * OVERSAMPLENR, 80}, {758 * OVERSAMPLENR, 78}, {770 * OVERSAMPLENR, 76}, {783 * OVERSAMPLENR, 74}, {795 * OVERSAMPLENR, 72}, {806 * OVERSAMPLENR, 70}, {818 * OVERSAMPLENR, 68}, {829 * OVERSAMPLENR, 66}, {840 * OVERSAMPLENR, 64}, {850 * OVERSAMPLENR, 62}, {860 * OVERSAMPLENR, 60}, {870 * OVERSAMPLENR, 58}, {879 * OVERSAMPLENR, 56}, {888 * OVERSAMPLENR, 54}, {897 * OVERSAMPLENR, 52}, {905 * OVERSAMPLENR, 50}, {924 * OVERSAMPLENR, 45}, {940 * OVERSAMPLENR, 40}, {955 * OVERSAMPLENR, 35}, {967 * OVERSAMPLENR, 30}, {970 * OVERSAMPLENR, 29}, {972 * OVERSAMPLENR, 28}, {974 * OVERSAMPLENR, 27}, {976 * OVERSAMPLENR, 26}, {978 * OVERSAMPLENR, 25}, {980 * OVERSAMPLENR, 24}, {982 * OVERSAMPLENR, 23}, {984 * OVERSAMPLENR, 22}, {985 * OVERSAMPLENR, 21}, {987 * OVERSAMPLENR, 20}, {995 * OVERSAMPLENR, 15}, {1001 * OVERSAMPLENR, 10}, {1006 * OVERSAMPLENR, 5}, {1010 * OVERSAMPLENR, 0}, }; #endif #if (THERMISTORHEATER_0 == 8) || (THERMISTORHEATER_1 == 8) || (THERMISTORHEATER_2 == 8) || (THERMISTORBED == 8) // 100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) const short temptable_8[][2] PROGMEM = { {1 * OVERSAMPLENR, 704}, {54 * OVERSAMPLENR, 216}, {107 * OVERSAMPLENR, 175}, {160 * OVERSAMPLENR, 152}, {213 * OVERSAMPLENR, 137}, {266 * OVERSAMPLENR, 125}, {319 * OVERSAMPLENR, 115}, {372 * OVERSAMPLENR, 106}, {425 * OVERSAMPLENR, 99}, {478 * OVERSAMPLENR, 91}, {531 * OVERSAMPLENR, 85}, {584 * OVERSAMPLENR, 78}, {637 * OVERSAMPLENR, 71}, {690 * OVERSAMPLENR, 65}, {743 * OVERSAMPLENR, 58}, {796 * OVERSAMPLENR, 50}, {849 * OVERSAMPLENR, 42}, {902 * OVERSAMPLENR, 31}, {955 * OVERSAMPLENR, 17}, {1008 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 9) || (THERMISTORHEATER_1 == 9) || (THERMISTORHEATER_2 == 9) || (THERMISTORBED == 9) // 100k GE Sensing AL03006-58.2K-97-G1 (4.7k pullup) const short temptable_9[][2] PROGMEM = { {1 * OVERSAMPLENR, 936}, {36 * OVERSAMPLENR, 300}, {71 * OVERSAMPLENR, 246}, {106 * OVERSAMPLENR, 218}, {141 * OVERSAMPLENR, 199}, {176 * OVERSAMPLENR, 185}, {211 * OVERSAMPLENR, 173}, {246 * OVERSAMPLENR, 163}, {281 * OVERSAMPLENR, 155}, {316 * OVERSAMPLENR, 147}, {351 * OVERSAMPLENR, 140}, {386 * OVERSAMPLENR, 134}, {421 * OVERSAMPLENR, 128}, {456 * OVERSAMPLENR, 122}, {491 * OVERSAMPLENR, 117}, {526 * OVERSAMPLENR, 112}, {561 * OVERSAMPLENR, 107}, {596 * OVERSAMPLENR, 102}, {631 * OVERSAMPLENR, 97}, {666 * OVERSAMPLENR, 92}, {701 * OVERSAMPLENR, 87}, {736 * OVERSAMPLENR, 81}, {771 * OVERSAMPLENR, 76}, {806 * OVERSAMPLENR, 70}, {841 * OVERSAMPLENR, 63}, {876 * OVERSAMPLENR, 56}, {911 * OVERSAMPLENR, 48}, {946 * OVERSAMPLENR, 38}, {981 * OVERSAMPLENR, 23}, {1005 * OVERSAMPLENR, 5}, {1016 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 10) || (THERMISTORHEATER_1 == 10) || (THERMISTORHEATER_2 == 10) || (THERMISTORBED == 10) // 100k RS thermistor 198-961 (4.7k pullup) const short temptable_10[][2] PROGMEM = { {1 * OVERSAMPLENR, 929}, {36 * OVERSAMPLENR, 299}, {71 * OVERSAMPLENR, 246}, {106 * OVERSAMPLENR, 217}, {141 * OVERSAMPLENR, 198}, {176 * OVERSAMPLENR, 184}, {211 * OVERSAMPLENR, 173}, {246 * OVERSAMPLENR, 163}, {281 * OVERSAMPLENR, 154}, {316 * OVERSAMPLENR, 147}, {351 * OVERSAMPLENR, 140}, {386 * OVERSAMPLENR, 134}, {421 * OVERSAMPLENR, 128}, {456 * OVERSAMPLENR, 122}, {491 * OVERSAMPLENR, 117}, {526 * OVERSAMPLENR, 112}, {561 * OVERSAMPLENR, 107}, {596 * OVERSAMPLENR, 102}, {631 * OVERSAMPLENR, 97}, {666 * OVERSAMPLENR, 91}, {701 * OVERSAMPLENR, 86}, {736 * OVERSAMPLENR, 81}, {771 * OVERSAMPLENR, 76}, {806 * OVERSAMPLENR, 70}, {841 * OVERSAMPLENR, 63}, {876 * OVERSAMPLENR, 56}, {911 * OVERSAMPLENR, 48}, {946 * OVERSAMPLENR, 38}, {981 * OVERSAMPLENR, 23}, {1005 * OVERSAMPLENR, 5}, {1016 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 11) || (THERMISTORHEATER_1 == 11) || (THERMISTORHEATER_2 == 11) || (THERMISTORBED == 11) // QU-BD silicone bed QWG-104F-3950 thermistor const short temptable_11[][2] PROGMEM = { {1 * OVERSAMPLENR, 938}, {31 * OVERSAMPLENR, 314}, {41 * OVERSAMPLENR, 290}, {51 * OVERSAMPLENR, 272}, {61 * OVERSAMPLENR, 258}, {71 * OVERSAMPLENR, 247}, {81 * OVERSAMPLENR, 237}, {91 * OVERSAMPLENR, 229}, {101 * OVERSAMPLENR, 221}, {111 * OVERSAMPLENR, 215}, {121 * OVERSAMPLENR, 209}, {131 * OVERSAMPLENR, 204}, {141 * OVERSAMPLENR, 199}, {151 * OVERSAMPLENR, 195}, {161 * OVERSAMPLENR, 190}, {171 * OVERSAMPLENR, 187}, {181 * OVERSAMPLENR, 183}, {191 * OVERSAMPLENR, 179}, {201 * OVERSAMPLENR, 176}, {221 * OVERSAMPLENR, 170}, {241 * OVERSAMPLENR, 165}, {261 * OVERSAMPLENR, 160}, {281 * OVERSAMPLENR, 155}, {301 * OVERSAMPLENR, 150}, {331 * OVERSAMPLENR, 144}, {361 * OVERSAMPLENR, 139}, {391 * OVERSAMPLENR, 133}, {421 * OVERSAMPLENR, 128}, {451 * OVERSAMPLENR, 123}, {491 * OVERSAMPLENR, 117}, {531 * OVERSAMPLENR, 111}, {571 * OVERSAMPLENR, 105}, {611 * OVERSAMPLENR, 100}, {641 * OVERSAMPLENR, 95}, {681 * OVERSAMPLENR, 90}, {711 * OVERSAMPLENR, 85}, {751 * OVERSAMPLENR, 79}, {791 * OVERSAMPLENR, 72}, {811 * OVERSAMPLENR, 69}, {831 * OVERSAMPLENR, 65}, {871 * OVERSAMPLENR, 57}, {881 * OVERSAMPLENR, 55}, {901 * OVERSAMPLENR, 51}, {921 * OVERSAMPLENR, 45}, {941 * OVERSAMPLENR, 39}, {971 * OVERSAMPLENR, 28}, {981 * OVERSAMPLENR, 23}, {991 * OVERSAMPLENR, 17}, {1001 * OVERSAMPLENR, 9}, {1021 * OVERSAMPLENR, -27}}; #endif #if (THERMISTORHEATER_0 == 13) || (THERMISTORHEATER_1 == 13) || (THERMISTORHEATER_2 == 13) || (THERMISTORBED == 13) // Hisens thermistor B25/50 =3950 +/-1% const short temptable_13[][2] PROGMEM = { {22.5 * OVERSAMPLENR, 300}, {24.125 * OVERSAMPLENR, 295}, {25.875 * OVERSAMPLENR, 290}, {27.8125 * OVERSAMPLENR, 285}, {29.9375 * OVERSAMPLENR, 280}, {32.25 * OVERSAMPLENR, 275}, {34.8125 * OVERSAMPLENR, 270}, {37.625 * OVERSAMPLENR, 265}, {40.6875 * OVERSAMPLENR, 260}, {44.0625 * OVERSAMPLENR, 255}, {47.75 * OVERSAMPLENR, 250}, {51.8125 * OVERSAMPLENR, 245}, {56.3125 * OVERSAMPLENR, 240}, {61.25 * OVERSAMPLENR, 235}, {66.75 * OVERSAMPLENR, 230}, {72.8125 * OVERSAMPLENR, 225}, {79.5 * OVERSAMPLENR, 220}, {87 * OVERSAMPLENR, 215}, {95.3125 * OVERSAMPLENR, 210}, {104.1875 * OVERSAMPLENR, 205}, {112.75 * OVERSAMPLENR, 200}, {123.125 * OVERSAMPLENR, 195}, {135.75 * OVERSAMPLENR, 190}, {148.3125 * OVERSAMPLENR, 185}, {163.8125 * OVERSAMPLENR, 180}, {179 * OVERSAMPLENR, 175}, {211.125 * OVERSAMPLENR, 170}, {216.125 * OVERSAMPLENR, 165}, {236.5625 * OVERSAMPLENR, 160}, {258.5 * OVERSAMPLENR, 155}, {279.875 * OVERSAMPLENR, 150}, {305.375 * OVERSAMPLENR, 145}, {333.25 * OVERSAMPLENR, 140}, {362.5625 * OVERSAMPLENR, 135}, {393.6875 * OVERSAMPLENR, 130}, {425 * OVERSAMPLENR, 125}, {460.625 * OVERSAMPLENR, 120}, {495.1875 * OVERSAMPLENR, 115}, {530.875 * OVERSAMPLENR, 110}, {567.25 * OVERSAMPLENR, 105}, {601.625 * OVERSAMPLENR, 100}, {637.875 * OVERSAMPLENR, 95}, {674.5625 * OVERSAMPLENR, 90}, {710 * OVERSAMPLENR, 85}, {744.125 * OVERSAMPLENR, 80}, {775.9375 * OVERSAMPLENR, 75}, {806.875 * OVERSAMPLENR, 70}, {835.1875 * OVERSAMPLENR, 65}, {861.125 * OVERSAMPLENR, 60}, {884.375 * OVERSAMPLENR, 55}, {904.5625 * OVERSAMPLENR, 50}, {923.8125 * OVERSAMPLENR, 45}, {940.375 * OVERSAMPLENR, 40}, {954.625 * OVERSAMPLENR, 35}, {966.875 * OVERSAMPLENR, 30}, {977.0625 * OVERSAMPLENR, 25}, {986 * OVERSAMPLENR, 20}, {993.375 * OVERSAMPLENR, 15}, {999.5 * OVERSAMPLENR, 10}, {1004.5 * OVERSAMPLENR, 5}, {1008.5 * OVERSAMPLENR, 0} }; #endif #if (THERMISTORHEATER_0 == 20) || (THERMISTORHEATER_1 == 20) || (THERMISTORHEATER_2 == 20) || (THERMISTORBED == 20) // PT100 with INA826 amp on Ultimaker v2.0 electronics /* The PT100 in the Ultimaker v2.0 electronics has a high sample value for a high temperature. This does not match the normal thermistor behaviour so we need to set the following defines */ #if (THERMISTORHEATER_0 == 20) #define HEATER_0_RAW_HI_TEMP 16383 #define HEATER_0_RAW_LO_TEMP 0 #endif #if (THERMISTORHEATER_1 == 20) #define HEATER_1_RAW_HI_TEMP 16383 #define HEATER_1_RAW_LO_TEMP 0 #endif #if (THERMISTORHEATER_2 == 20) #define HEATER_2_RAW_HI_TEMP 16383 #define HEATER_2_RAW_LO_TEMP 0 #endif #if (THERMISTORBED == 20) #define HEATER_BED_RAW_HI_TEMP 16383 #define HEATER_BED_RAW_LO_TEMP 0 #endif const short temptable_20[][2] PROGMEM = { {0 * OVERSAMPLENR, 0}, {227 * OVERSAMPLENR, 1}, {236 * OVERSAMPLENR, 10}, {245 * OVERSAMPLENR, 20}, {253 * OVERSAMPLENR, 30}, {262 * OVERSAMPLENR, 40}, {270 * OVERSAMPLENR, 50}, {279 * OVERSAMPLENR, 60}, {287 * OVERSAMPLENR, 70}, {295 * OVERSAMPLENR, 80}, {304 * OVERSAMPLENR, 90}, {312 * OVERSAMPLENR, 100}, {320 * OVERSAMPLENR, 110}, {329 * OVERSAMPLENR, 120}, {337 * OVERSAMPLENR, 130}, {345 * OVERSAMPLENR, 140}, {353 * OVERSAMPLENR, 150}, {361 * OVERSAMPLENR, 160}, {369 * OVERSAMPLENR, 170}, {377 * OVERSAMPLENR, 180}, {385 * OVERSAMPLENR, 190}, {393 * OVERSAMPLENR, 200}, {401 * OVERSAMPLENR, 210}, {409 * OVERSAMPLENR, 220}, {417 * OVERSAMPLENR, 230}, {424 * OVERSAMPLENR, 240}, {432 * OVERSAMPLENR, 250}, {440 * OVERSAMPLENR, 260}, {447 * OVERSAMPLENR, 270}, {455 * OVERSAMPLENR, 280}, {463 * OVERSAMPLENR, 290}, {470 * OVERSAMPLENR, 300}, {478 * OVERSAMPLENR, 310}, {485 * OVERSAMPLENR, 320}, {493 * OVERSAMPLENR, 330}, {500 * OVERSAMPLENR, 340}, {507 * OVERSAMPLENR, 350}, {515 * OVERSAMPLENR, 360}, {522 * OVERSAMPLENR, 370}, {529 * OVERSAMPLENR, 380}, {537 * OVERSAMPLENR, 390}, {544 * OVERSAMPLENR, 400}, {614 * OVERSAMPLENR, 500}, {681 * OVERSAMPLENR, 600}, {744 * OVERSAMPLENR, 700}, {805 * OVERSAMPLENR, 800}, {862 * OVERSAMPLENR, 900}, {917 * OVERSAMPLENR, 1000}, {968 * OVERSAMPLENR, 1100}}; #endif #if (THERMISTORHEATER_0 == 51) || (THERMISTORHEATER_1 == 51) || (THERMISTORHEATER_2 == 51) || (THERMISTORBED == 51) // 100k EPCOS (WITH 1kohm RESISTOR FOR PULLUP, R9 ON SANGUINOLOLU! NOT FOR 4.7kohm PULLUP! THIS IS NOT NORMAL!) // Verified by linagee. // Calculated using 1kohm pullup, voltage divider math, and manufacturer provided temp/resistance // Advantage: Twice the resolution and better linearity from 150C to 200C const short temptable_51[][2] PROGMEM = { {1 * OVERSAMPLENR, 350}, {190 * OVERSAMPLENR, 250}, //top rating 250C {203 * OVERSAMPLENR, 245}, {217 * OVERSAMPLENR, 240}, {232 * OVERSAMPLENR, 235}, {248 * OVERSAMPLENR, 230}, {265 * OVERSAMPLENR, 225}, {283 * OVERSAMPLENR, 220}, {302 * OVERSAMPLENR, 215}, {322 * OVERSAMPLENR, 210}, {344 * OVERSAMPLENR, 205}, {366 * OVERSAMPLENR, 200}, {390 * OVERSAMPLENR, 195}, {415 * OVERSAMPLENR, 190}, {440 * OVERSAMPLENR, 185}, {467 * OVERSAMPLENR, 180}, {494 * OVERSAMPLENR, 175}, {522 * OVERSAMPLENR, 170}, {551 * OVERSAMPLENR, 165}, {580 * OVERSAMPLENR, 160}, {609 * OVERSAMPLENR, 155}, {638 * OVERSAMPLENR, 150}, {666 * OVERSAMPLENR, 145}, {695 * OVERSAMPLENR, 140}, {722 * OVERSAMPLENR, 135}, {749 * OVERSAMPLENR, 130}, {775 * OVERSAMPLENR, 125}, {800 * OVERSAMPLENR, 120}, {823 * OVERSAMPLENR, 115}, {845 * OVERSAMPLENR, 110}, {865 * OVERSAMPLENR, 105}, {884 * OVERSAMPLENR, 100}, {901 * OVERSAMPLENR, 95}, {917 * OVERSAMPLENR, 90}, {932 * OVERSAMPLENR, 85}, {944 * OVERSAMPLENR, 80}, {956 * OVERSAMPLENR, 75}, {966 * OVERSAMPLENR, 70}, {975 * OVERSAMPLENR, 65}, {982 * OVERSAMPLENR, 60}, {989 * OVERSAMPLENR, 55}, {995 * OVERSAMPLENR, 50}, {1000 * OVERSAMPLENR, 45}, {1004 * OVERSAMPLENR, 40}, {1007 * OVERSAMPLENR, 35}, {1010 * OVERSAMPLENR, 30}, {1013 * OVERSAMPLENR, 25}, {1015 * OVERSAMPLENR, 20}, {1017 * OVERSAMPLENR, 15}, {1018 * OVERSAMPLENR, 10}, {1019 * OVERSAMPLENR, 5}, {1020 * OVERSAMPLENR, 0}, {1021 * OVERSAMPLENR, -5}}; #endif #if (THERMISTORHEATER_0 == 52) || (THERMISTORHEATER_1 == 52) || (THERMISTORHEATER_2 == 52) || (THERMISTORBED == 52) // 200k ATC Semitec 204GT-2 (WITH 1kohm RESISTOR FOR PULLUP, R9 ON SANGUINOLOLU! NOT FOR 4.7kohm PULLUP! THIS IS NOT NORMAL!) // Verified by linagee. Source: http://shop.arcol.hu/static/datasheets/thermistors.pdf // Calculated using 1kohm pullup, voltage divider math, and manufacturer provided temp/resistance // Advantage: More resolution and better linearity from 150C to 200C const short temptable_52[][2] PROGMEM = { {1 * OVERSAMPLENR, 500}, {125 * OVERSAMPLENR, 300}, //top rating 300C {142 * OVERSAMPLENR, 290}, {162 * OVERSAMPLENR, 280}, {185 * OVERSAMPLENR, 270}, {211 * OVERSAMPLENR, 260}, {240 * OVERSAMPLENR, 250}, {274 * OVERSAMPLENR, 240}, {312 * OVERSAMPLENR, 230}, {355 * OVERSAMPLENR, 220}, {401 * OVERSAMPLENR, 210}, {452 * OVERSAMPLENR, 200}, {506 * OVERSAMPLENR, 190}, {563 * OVERSAMPLENR, 180}, {620 * OVERSAMPLENR, 170}, {677 * OVERSAMPLENR, 160}, {732 * OVERSAMPLENR, 150}, {783 * OVERSAMPLENR, 140}, {830 * OVERSAMPLENR, 130}, {871 * OVERSAMPLENR, 120}, {906 * OVERSAMPLENR, 110}, {935 * OVERSAMPLENR, 100}, {958 * OVERSAMPLENR, 90}, {976 * OVERSAMPLENR, 80}, {990 * OVERSAMPLENR, 70}, {1000 * OVERSAMPLENR, 60}, {1008 * OVERSAMPLENR, 50}, {1013 * OVERSAMPLENR, 40}, {1017 * OVERSAMPLENR, 30}, {1019 * OVERSAMPLENR, 20}, {1021 * OVERSAMPLENR, 10}, {1022 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 55) || (THERMISTORHEATER_1 == 55) || (THERMISTORHEATER_2 == 55) || (THERMISTORBED == 55) // 100k ATC Semitec 104GT-2 (Used on ParCan) (WITH 1kohm RESISTOR FOR PULLUP, R9 ON SANGUINOLOLU! NOT FOR 4.7kohm PULLUP! THIS IS NOT NORMAL!) // Verified by linagee. Source: http://shop.arcol.hu/static/datasheets/thermistors.pdf // Calculated using 1kohm pullup, voltage divider math, and manufacturer provided temp/resistance // Advantage: More resolution and better linearity from 150C to 200C const short temptable_55[][2] PROGMEM = { {1 * OVERSAMPLENR, 500}, {76 * OVERSAMPLENR, 300}, {87 * OVERSAMPLENR, 290}, {100 * OVERSAMPLENR, 280}, {114 * OVERSAMPLENR, 270}, {131 * OVERSAMPLENR, 260}, {152 * OVERSAMPLENR, 250}, {175 * OVERSAMPLENR, 240}, {202 * OVERSAMPLENR, 230}, {234 * OVERSAMPLENR, 220}, {271 * OVERSAMPLENR, 210}, {312 * OVERSAMPLENR, 200}, {359 * OVERSAMPLENR, 190}, {411 * OVERSAMPLENR, 180}, {467 * OVERSAMPLENR, 170}, {527 * OVERSAMPLENR, 160}, {590 * OVERSAMPLENR, 150}, {652 * OVERSAMPLENR, 140}, {713 * OVERSAMPLENR, 130}, {770 * OVERSAMPLENR, 120}, {822 * OVERSAMPLENR, 110}, {867 * OVERSAMPLENR, 100}, {905 * OVERSAMPLENR, 90}, {936 * OVERSAMPLENR, 80}, {961 * OVERSAMPLENR, 70}, {979 * OVERSAMPLENR, 60}, {993 * OVERSAMPLENR, 50}, {1003 * OVERSAMPLENR, 40}, {1010 * OVERSAMPLENR, 30}, {1015 * OVERSAMPLENR, 20}, {1018 * OVERSAMPLENR, 10}, {1020 * OVERSAMPLENR, 0}}; #endif #if (THERMISTORHEATER_0 == 60) || (THERMISTORHEATER_1 == 60) || (THERMISTORHEATER_2 == 60) || (THERMISTORBED == 60) // Maker's Tool Works Kapton Bed Thermister // ./createTemperatureLookup.py --r0=100000 --t0=25 --r1=0 --r2=4700 --beta=3950 // r0: 100000 // t0: 25 // r1: 0 (parallel with rTherm) // r2: 4700 (series with rTherm) // beta: 3950 // min adc: 1 at 0.0048828125 V // max adc: 1023 at 4.9951171875 V const short temptable_60[][2] PROGMEM = { {51 * OVERSAMPLENR, 272}, {61 * OVERSAMPLENR, 258}, {71 * OVERSAMPLENR, 247}, {81 * OVERSAMPLENR, 237}, {91 * OVERSAMPLENR, 229}, {101 * OVERSAMPLENR, 221}, {131 * OVERSAMPLENR, 204}, {161 * OVERSAMPLENR, 190}, {191 * OVERSAMPLENR, 179}, {231 * OVERSAMPLENR, 167}, {271 * OVERSAMPLENR, 157}, {311 * OVERSAMPLENR, 148}, {351 * OVERSAMPLENR, 140}, {381 * OVERSAMPLENR, 135}, {411 * OVERSAMPLENR, 130}, {441 * OVERSAMPLENR, 125}, {451 * OVERSAMPLENR, 123}, {461 * OVERSAMPLENR, 122}, {471 * OVERSAMPLENR, 120}, {481 * OVERSAMPLENR, 119}, {491 * OVERSAMPLENR, 117}, {501 * OVERSAMPLENR, 116}, {511 * OVERSAMPLENR, 114}, {521 * OVERSAMPLENR, 113}, {531 * OVERSAMPLENR, 111}, {541 * OVERSAMPLENR, 110}, {551 * OVERSAMPLENR, 108}, {561 * OVERSAMPLENR, 107}, {571 * OVERSAMPLENR, 105}, {581 * OVERSAMPLENR, 104}, {591 * OVERSAMPLENR, 102}, {601 * OVERSAMPLENR, 101}, {611 * OVERSAMPLENR, 100}, {621 * OVERSAMPLENR, 98}, {631 * OVERSAMPLENR, 97}, {641 * OVERSAMPLENR, 95}, {651 * OVERSAMPLENR, 94}, {661 * OVERSAMPLENR, 92}, {671 * OVERSAMPLENR, 91}, {681 * OVERSAMPLENR, 90}, {691 * OVERSAMPLENR, 88}, {701 * OVERSAMPLENR, 87}, {711 * OVERSAMPLENR, 85}, {721 * OVERSAMPLENR, 84}, {731 * OVERSAMPLENR, 82}, {741 * OVERSAMPLENR, 81}, {751 * OVERSAMPLENR, 79}, {761 * OVERSAMPLENR, 77}, {771 * OVERSAMPLENR, 76}, {781 * OVERSAMPLENR, 74}, {791 * OVERSAMPLENR, 72}, {801 * OVERSAMPLENR, 71}, {811 * OVERSAMPLENR, 69}, {821 * OVERSAMPLENR, 67}, {831 * OVERSAMPLENR, 65}, {841 * OVERSAMPLENR, 63}, {851 * OVERSAMPLENR, 62}, {861 * OVERSAMPLENR, 60}, {871 * OVERSAMPLENR, 57}, {881 * OVERSAMPLENR, 55}, {891 * OVERSAMPLENR, 53}, {901 * OVERSAMPLENR, 51}, {911 * OVERSAMPLENR, 48}, {921 * OVERSAMPLENR, 45}, {931 * OVERSAMPLENR, 42}, {941 * OVERSAMPLENR, 39}, {951 * OVERSAMPLENR, 36}, {961 * OVERSAMPLENR, 32}, {981 * OVERSAMPLENR, 23}, {991 * OVERSAMPLENR, 17}, {1001 * OVERSAMPLENR, 9}, {1008 * OVERSAMPLENR, 0}, }; #endif #if (THERMISTORBED == 12) //100k 0603 SMD Vishay NTCS0603E3104FXT (4.7k pullup) (calibrated for Makibox hot bed) const short temptable_12[][2] PROGMEM = { {35 * OVERSAMPLENR, 180}, //top rating 180C {211 * OVERSAMPLENR, 140}, {233 * OVERSAMPLENR, 135}, {261 * OVERSAMPLENR, 130}, {290 * OVERSAMPLENR, 125}, {328 * OVERSAMPLENR, 120}, {362 * OVERSAMPLENR, 115}, {406 * OVERSAMPLENR, 110}, {446 * OVERSAMPLENR, 105}, {496 * OVERSAMPLENR, 100}, {539 * OVERSAMPLENR, 95}, {585 * OVERSAMPLENR, 90}, {629 * OVERSAMPLENR, 85}, {675 * OVERSAMPLENR, 80}, {718 * OVERSAMPLENR, 75}, {758 * OVERSAMPLENR, 70}, {793 * OVERSAMPLENR, 65}, {822 * OVERSAMPLENR, 60}, {841 * OVERSAMPLENR, 55}, {875 * OVERSAMPLENR, 50}, {899 * OVERSAMPLENR, 45}, {926 * OVERSAMPLENR, 40}, {946 * OVERSAMPLENR, 35}, {962 * OVERSAMPLENR, 30}, {977 * OVERSAMPLENR, 25}, {987 * OVERSAMPLENR, 20}, {995 * OVERSAMPLENR, 15}, {1001 * OVERSAMPLENR, 10}, {1010 * OVERSAMPLENR, 0}, {1023 * OVERSAMPLENR, -40}, }; #endif // Pt1000 and Pt100 handling // // Rt=R0*(1+a*T+b*T*T) [for T>0] // a=3.9083E-3, b=-5.775E-7 #define PtA 3.9083E-3 #define PtB -5.775E-7 #define PtRt(T, R0) ((R0) * (1.0 + (PtA) * (T) + (PtB) * (T) * (T))) #define PtAdVal(T, R0, Rup) (short)(1024 / (Rup / PtRt(T, R0) + 1)) #define PtLine(T, R0, Rup) {PtAdVal(T, R0, Rup) * OVERSAMPLENR, T}, #if (THERMISTORHEATER_0 == 110) || (THERMISTORHEATER_1 == 110) || (THERMISTORHEATER_2 == 110) || (THERMISTORBED == 110) // Pt100 with 1k0 pullup const short temptable_110[][2] PROGMEM = { // only few values are needed as the curve is very flat PtLine(0, 100, 1000) PtLine(50, 100, 1000) PtLine(100, 100, 1000) PtLine(150, 100, 1000) PtLine(200, 100, 1000) PtLine(250, 100, 1000) PtLine(300, 100, 1000)}; #endif #if (THERMISTORHEATER_0 == 147) || (THERMISTORHEATER_1 == 147) || (THERMISTORHEATER_2 == 147) || (THERMISTORBED == 147) // Pt100 with 4k7 pullup const short temptable_147[][2] PROGMEM = { // only few values are needed as the curve is very flat PtLine(0, 100, 4700) PtLine(50, 100, 4700) PtLine(100, 100, 4700) PtLine(150, 100, 4700) PtLine(200, 100, 4700) PtLine(250, 100, 4700) PtLine(300, 100, 4700)}; #endif #if (THERMISTORHEATER_0 == 1010) || (THERMISTORHEATER_1 == 1010) || (THERMISTORHEATER_2 == 1010) || (THERMISTORBED == 1010) // Pt1000 with 1k0 pullup const short temptable_1010[][2] PROGMEM = { PtLine(0, 1000, 1000) PtLine(25, 1000, 1000) PtLine(50, 1000, 1000) PtLine(75, 1000, 1000) PtLine(100, 1000, 1000) PtLine(125, 1000, 1000) PtLine(150, 1000, 1000) PtLine(175, 1000, 1000) PtLine(200, 1000, 1000) PtLine(225, 1000, 1000) PtLine(250, 1000, 1000) PtLine(275, 1000, 1000) PtLine(300, 1000, 1000)}; #endif #if (THERMISTORHEATER_0 == 1047) || (THERMISTORHEATER_1 == 1047) || (THERMISTORHEATER_2 == 1047) || (THERMISTORBED == 1047) // Pt1000 with 4k7 pullup const short temptable_1047[][2] PROGMEM = { // only few values are needed as the curve is very flat PtLine(0, 1000, 4700) PtLine(50, 1000, 4700) PtLine(100, 1000, 4700) PtLine(150, 1000, 4700) PtLine(200, 1000, 4700) PtLine(250, 1000, 4700) PtLine(300, 1000, 4700)}; #endif #define _TT_NAME(_N) temptable_##_N #define TT_NAME(_N) _TT_NAME(_N) #ifdef THERMISTORHEATER_0 #define HEATER_0_TEMPTABLE TT_NAME(THERMISTORHEATER_0) #define HEATER_0_TEMPTABLE_LEN (sizeof(HEATER_0_TEMPTABLE) / sizeof(*HEATER_0_TEMPTABLE)) #else #ifdef HEATER_0_USES_THERMISTOR #error No heater 0 thermistor table specified #else // HEATER_0_USES_THERMISTOR #define HEATER_0_TEMPTABLE NULL #define HEATER_0_TEMPTABLE_LEN 0 #endif // HEATER_0_USES_THERMISTOR #endif //Set the high and low raw values for the heater, this indicates which raw value is a high or low temperature #ifndef HEATER_0_RAW_HI_TEMP #ifdef HEATER_0_USES_THERMISTOR //In case of a thermistor the highest temperature results in the lowest ADC value #define HEATER_0_RAW_HI_TEMP 0 #define HEATER_0_RAW_LO_TEMP 16383 #else //In case of an thermocouple the highest temperature results in the highest ADC value #define HEATER_0_RAW_HI_TEMP 16383 #define HEATER_0_RAW_LO_TEMP 0 #endif #endif #ifdef THERMISTORHEATER_1 #define HEATER_1_TEMPTABLE TT_NAME(THERMISTORHEATER_1) #define HEATER_1_TEMPTABLE_LEN (sizeof(HEATER_1_TEMPTABLE) / sizeof(*HEATER_1_TEMPTABLE)) #else #ifdef HEATER_1_USES_THERMISTOR #error No heater 1 thermistor table specified #else // HEATER_1_USES_THERMISTOR #define HEATER_1_TEMPTABLE NULL #define HEATER_1_TEMPTABLE_LEN 0 #endif // HEATER_1_USES_THERMISTOR #endif //Set the high and low raw values for the heater, this indicates which raw value is a high or low temperature #ifndef HEATER_1_RAW_HI_TEMP #ifdef HEATER_1_USES_THERMISTOR //In case of a thermistor the highest temperature results in the lowest ADC value #define HEATER_1_RAW_HI_TEMP 0 #define HEATER_1_RAW_LO_TEMP 16383 #else //In case of an thermocouple the highest temperature results in the highest ADC value #define HEATER_1_RAW_HI_TEMP 16383 #define HEATER_1_RAW_LO_TEMP 0 #endif #endif #ifdef THERMISTORHEATER_2 #define HEATER_2_TEMPTABLE TT_NAME(THERMISTORHEATER_2) #define HEATER_2_TEMPTABLE_LEN (sizeof(HEATER_2_TEMPTABLE) / sizeof(*HEATER_2_TEMPTABLE)) #else #ifdef HEATER_2_USES_THERMISTOR #error No heater 2 thermistor table specified #else // HEATER_2_USES_THERMISTOR #define HEATER_2_TEMPTABLE NULL #define HEATER_2_TEMPTABLE_LEN 0 #endif // HEATER_2_USES_THERMISTOR #endif //Set the high and low raw values for the heater, this indicates which raw value is a high or low temperature #ifndef HEATER_2_RAW_HI_TEMP #ifdef HEATER_2_USES_THERMISTOR //In case of a thermistor the highest temperature results in the lowest ADC value #define HEATER_2_RAW_HI_TEMP 0 #define HEATER_2_RAW_LO_TEMP 16383 #else //In case of an thermocouple the highest temperature results in the highest ADC value #define HEATER_2_RAW_HI_TEMP 16383 #define HEATER_2_RAW_LO_TEMP 0 #endif #endif #ifdef THERMISTORBED #define BEDTEMPTABLE TT_NAME(THERMISTORBED) #define BEDTEMPTABLE_LEN (sizeof(BEDTEMPTABLE) / sizeof(*BEDTEMPTABLE)) #else #ifdef BED_USES_THERMISTOR #error No bed thermistor table specified #endif // BED_USES_THERMISTOR #endif //Set the high and low raw values for the heater, this indicates which raw value is a high or low temperature #ifndef HEATER_BED_RAW_HI_TEMP #ifdef BED_USES_THERMISTOR //In case of a thermistor the highest temperature results in the lowest ADC value #define HEATER_BED_RAW_HI_TEMP 0 #define HEATER_BED_RAW_LO_TEMP 16383 #else //In case of an thermocouple the highest temperature results in the highest ADC value #define HEATER_BED_RAW_HI_TEMP 16383 #define HEATER_BED_RAW_LO_TEMP 0 #endif #endif #endif //THERMISTORTABLES_H_
39,590
C++
.h
1,137
30.074758
170
0.626058
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,904
Marlin.h
tenlog_TL-D3/Marlin/Marlin.h
// Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware. // Licence: GPL #ifndef MARLIN_H #define MARLIN_H #define FORCE_INLINE __attribute__((always_inline)) inline #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <util/delay.h> #include <avr/pgmspace.h> #include <avr/eeprom.h> #include <avr/interrupt.h> #include "fastio.h" #include "Configuration.h" #include "pins.h" #ifndef AT90USB #define HardwareSerial_h // trick to disable the standard HWserial #endif #include "Arduino.h" #if (ARDUINO >= 100) #else //#include "WProgram.h" //Arduino < 1.0.0 does not define this, so we need to do it ourselfs #define analogInputToDigitalPin(p) ((p) + A0) #endif #include "MarlinSerial.h" #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif #include "WString.h" #ifdef AT90USB #define MYSERIAL Serial #else #define MYSERIAL MSerial #endif #define SERIAL_PROTOCOL(x) MYSERIAL.print(x); #define SERIAL_PROTOCOL_F(x, y) MYSERIAL.print(x, y); #define SERIAL_PROTOCOLPGM(x) serialprintPGM(PSTR(x)); #define SERIAL_PROTOCOLLN(x) \ { \ MYSERIAL.print(x); \ MYSERIAL.write('\n'); \ } #define SERIAL_PROTOCOLLNPGM(x) \ { \ serialprintPGM(PSTR(x)); \ MYSERIAL.write('\n'); \ } //Zyf Print #define TL_DEBUG_PRINT(x) (MYSERIAL.print(x)) #define TL_DEBUG_PRINT_LN(x) (MYSERIAL.print(x), MYSERIAL.write('\n')) const char errormagic[] PROGMEM = "Error:"; const char echomagic[] PROGMEM = "echo:"; #define SERIAL_ERROR_START serialprintPGM(errormagic); #define SERIAL_ERROR(x) SERIAL_PROTOCOL(x) #define SERIAL_ERRORPGM(x) SERIAL_PROTOCOLPGM(x) #define SERIAL_ERRORLN(x) SERIAL_PROTOCOLLN(x) #define SERIAL_ERRORLNPGM(x) SERIAL_PROTOCOLLNPGM(x) #define SERIAL_ECHO_START serialprintPGM(echomagic); #define SERIAL_ECHO(x) SERIAL_PROTOCOL(x) #define SERIAL_ECHOPGM(x) SERIAL_PROTOCOLPGM(x) #define SERIAL_ECHOLN(x) SERIAL_PROTOCOLLN(x) #define SERIAL_ECHOLNPGM(x) SERIAL_PROTOCOLLNPGM(x) #define SERIAL_ECHOPAIR(name, value) (serial_echopair_P(PSTR(name), (value))) void serial_echopair_P(const char *s_P, float v); void serial_echopair_P(const char *s_P, double v); void serial_echopair_P(const char *s_P, unsigned long v); //things to write to serial from Programmemory. saves 400 to 2k of RAM. FORCE_INLINE void serialprintPGM(const char *str) { char ch = pgm_read_byte(str); while (ch) { MYSERIAL.write(ch); ch = pgm_read_byte(++str); } } bool MTLSERIAL_available(); int MTLSERIAL_read(); #if defined(DUAL_X_CARRIAGE) && defined(X_ENABLE_PIN) && X_ENABLE_PIN > -1 && defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1 #define enable_x() \ do \ { \ WRITE(X_ENABLE_PIN, X_ENABLE_ON); \ WRITE(X2_ENABLE_PIN, X_ENABLE_ON); \ } while (0) #define enable_x0() \ do \ { \ WRITE(X_ENABLE_PIN, X_ENABLE_ON); \ } while (0) #define enable_x1() \ do \ { \ WRITE(X2_ENABLE_PIN, X_ENABLE_ON); \ } while (0) #define disable_x() \ do \ { \ WRITE(X_ENABLE_PIN, !X_ENABLE_ON); \ WRITE(X2_ENABLE_PIN, !X_ENABLE_ON); \ } while (0) #define disable_x0() \ do \ { \ WRITE(X_ENABLE_PIN, !X_ENABLE_ON); \ } while (0) #define disable_x1() \ do \ { \ WRITE(X2_ENABLE_PIN, !X_ENABLE_ON); \ } while (0) #elif defined(X_ENABLE_PIN) && X_ENABLE_PIN > -1 #define enable_x() WRITE(X_ENABLE_PIN, X_ENABLE_ON) #define disable_x() WRITE(X_ENABLE_PIN, !X_ENABLE_ON) #else #define enable_x() ; #define disable_x() ; #endif #if defined(Y_ENABLE_PIN) && Y_ENABLE_PIN > -1 #define enable_y() WRITE(Y_ENABLE_PIN, Y_ENABLE_ON) #define disable_y() WRITE(Y_ENABLE_PIN, !Y_ENABLE_ON) #else #define enable_y() ; #define disable_y() ; #endif #if defined(Z_ENABLE_PIN) && Z_ENABLE_PIN > -1 #ifdef Z_DUAL_STEPPER_DRIVERS #define enable_z() \ { \ WRITE(Z_ENABLE_PIN, Z_ENABLE_ON); \ WRITE(Z2_ENABLE_PIN, Z_ENABLE_ON); \ } #define disable_z() \ { \ WRITE(Z_ENABLE_PIN, !Z_ENABLE_ON); \ WRITE(Z2_ENABLE_PIN, !Z_ENABLE_ON); \ } #elif defined(TL_DUAL_Z) //By zyf #define enable_z() \ { \ WRITE(Z_ENABLE_PIN, Z_ENABLE_ON); \ WRITE(Z2_ENABLE_PIN, Z_ENABLE_ON); \ } #define disable_z() \ { \ WRITE(Z_ENABLE_PIN, !Z_ENABLE_ON); \ WRITE(Z2_ENABLE_PIN, !Z_ENABLE_ON); \ } #else #define enable_z() WRITE(Z_ENABLE_PIN, Z_ENABLE_ON) #define disable_z() WRITE(Z_ENABLE_PIN, !Z_ENABLE_ON) #endif #else #define enable_z() ; #define disable_z() ; #endif #if defined(E0_ENABLE_PIN) && (E0_ENABLE_PIN > -1) #define enable_e0() WRITE(E0_ENABLE_PIN, E_ENABLE_ON) #define disable_e0() WRITE(E0_ENABLE_PIN, !E_ENABLE_ON) #else #define enable_e0() /* nothing */ #define disable_e0() /* nothing */ #endif #if (EXTRUDERS > 1) && defined(E1_ENABLE_PIN) && (E1_ENABLE_PIN > -1) #define enable_e1() WRITE(E1_ENABLE_PIN, E_ENABLE_ON) #define disable_e1() WRITE(E1_ENABLE_PIN, !E_ENABLE_ON) #else #define enable_e1() /* nothing */ #define disable_e1() /* nothing */ #endif #if (EXTRUDERS > 2) && defined(E2_ENABLE_PIN) && (E2_ENABLE_PIN > -1) #define enable_e2() WRITE(E2_ENABLE_PIN, E_ENABLE_ON) #define disable_e2() WRITE(E2_ENABLE_PIN, !E_ENABLE_ON) #else #define enable_e2() /* nothing */ #define disable_e2() /* nothing */ #endif enum AxisEnum { X_AXIS = 0, Y_AXIS = 1, Z_AXIS = 2, E_AXIS = 3 }; void FlushSerialRequestResend(); void ClearToSend(); void get_coordinates(float XValue, float YValue, float ZValue, float EValue, int iMode); void prepare_move(); void kill(); void Stop(); bool IsStopped(); void enquecommand(const char *cmd); //put an ascii command at the end of the current buffer. void enquecommand_P(const char *cmd); //put an ascii command at the end of the current buffer, read from flash void prepare_arc_move(char isclockwise); void clamp_to_software_endstops(float target[3]); void command_G1(float XValue = -99999.0, float YValue = -99999.0, float ZValue = -99999.0, float EValue = -99999.0, int iMode = 0); void PrintStopOrFinished(); void command_G4(float dwell = 0); void command_M81(bool Loop = true, bool ShowPage = true); #ifdef POWER_LOSS_RECOVERY #ifdef POWER_LOSS_TRIGGER_BY_PIN bool Check_Power_Loss(); #endif void Power_Off_Handler(bool MoveX = true, bool M81 = true); void Save_Power_Loss_Status(); #endif #ifdef FAST_PWM_FAN void setPwmFrequency(uint8_t pin, int val); #endif #ifndef CRITICAL_SECTION_START #define CRITICAL_SECTION_START \ unsigned char _sreg = SREG; \ cli(); #define CRITICAL_SECTION_END SREG = _sreg; #endif //CRITICAL_SECTION_START //float raised_parked_position[4]; // used in mode 1 extern float homing_feedrate[]; extern bool axis_relative_modes[]; extern int feedmultiply; extern int extrudemultiply; // Sets extrude multiply factor (in percent) extern float current_position[NUM_AXIS]; extern float add_homeing[3]; extern float min_pos[3]; extern float max_pos[3]; extern int fanSpeed; #ifdef DUAL_X_CARRIAGE extern int dual_x_carriage_mode; #endif #ifdef BARICUDA extern int ValvePressure; extern int EtoPPressure; #endif #ifdef FAN_SOFT_PWM extern unsigned char fanSpeedSoftPwm; #endif #ifdef FWRETRACT extern bool autoretract_enabled; extern bool retracted; extern float retract_length, retract_feedrate, retract_zlift; extern float retract_recover_length, retract_recover_feedrate; #endif extern unsigned long starttime; extern unsigned long stoptime; // Handling multiple extruders pins extern uint8_t active_extruder; extern int plaPreheatHotendTemp; extern int plaPreheatHPBTemp; extern int plaPreheatFanSpeed; extern int absPreheatHotendTemp; extern int absPreheatHPBTemp; extern int absPreheatFanSpeed; void preheat_abs(); void preheat_pla(); void cooldown(); bool strISAscii(String str); void sd_init(); void sdcard_pause(int OValue = 0); void sdcard_resume(); void sdcard_stop(); void raise_Z_E(int Z, int E); void Nozzle_offset_test_print(); void command_M104(int iT = -1, int iS = -1); void load_filament(int LoadUnLoad, int TValue); void command_G92(float XValue = -99999.0, float YValue = -99999.0, float ZValue = -99999.0, float EValue = -99999.0); void command_G28(int XHome = 0, int YHome = 0, int ZHome = 0); void command_T(int T01 = -1); void command_M502(); void command_M1003(); void WriteLastZYM(long lTime); char *itostr2(const uint8_t &x); #endif //MARLIN_H
9,172
C++
.h
277
31.288809
131
0.652833
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,905
Configuration_tenlog.h
tenlog_TL-D3/Marlin/Configuration_tenlog.h
#ifndef CONFIGURATION_TL_H #define CONFIGURATION_TL_H //Powered by tenlog3dprinter.com /* BOF UPDATE LOG 20191006: TL_TJC_CONTROLLER done 20191102: FILAMENT_FAIL_DETECT done 20191120: POWER_LOSS_RECOVERY done 20191219: PRINT_FROM_Z_HEIGHT done 20200807: BEEPER Done 20200814: Support 2225 driver 20200825: fix bug: show qr code when start up 20200915: Version: 1.0.8 auto detect plr hardware module. add VERSION string on about screen. 20200909: Add pt100 temp sensor. // canceled. 20201009: D5 ZMax is 610 20201015 Fix bug: DUPLICATION MODE & Mirror Mode E2 not finished the last several gcode lines when sd printing. version 1.0.9 20201022 Turn off beeper when SD Printing. delete 2225 driver in hex files. add y mechanical switch. version 1.0.10 20201110 Bug: when active extruder is T1, extruder crash in duplication mode. 20201202 Bug: pause when printing E2, resume heat E1; fixed. DWIN screen controller finished.(QR Code can be switched off) 20201203 ECO mode done 20201204 filament senser can be switch off (if you want). Version 1.0.13 20201212 Fix some bugs 20201217 Bug fixed: PLR, begin if E2, wrong Y Offset. Version 1.0.14 20201220 Unvisable auto poweroff in setting page if no PLR Module detected(need UI v:1.3.3). Use LM393 to detect power loss. Version 1.0.15 20201231 Reduce data transmission of DWIN touch screen. Version 1.0.16 DWIN UI Version 1.3.4 20210112 DWIN UI Spanish language enabled. Version 1.0.17 Need DWIN UI V1.3.6 Do not support DWIN UI Below 1.3.6 20210128 Multi language enabled (only for DWIN UI), now we support English, Chinese, Spanish, French, German, Italian and Japanses, more language is comming soon. DWN UI V 1.3.7 Fix some UI bugs. Add DWN Screen saver function Need DWIN UI V 1.3.7 Version 1.0.18 Disabled beeper for TJC UI 20210313 TJC New UI(like DWIN) V1.2.8 (some function need firmware v1.0.19) Fix Some bugs. DWIN UI V1.3.8 Version 1.0.19 20210319 Delete some unsued code. 20210329 Support M117 command (Only in printing page).(TJC UI Need v1.2.9) TJC UI V 1.2.9 Fix some bugs. Version 1.0.20 Show SN at start up. 20210401 TJC UI V1.2.9 R Means Rotate 180 degrees. 20210421 Fix bugs: bugs report by Tenlog Ma at 20200420 Version 1.0.21 20210422 Upgrade M105 command, add temp of T1. 20210510 Add ELECTROMAGNETIC_VALVE control, Synchronize from E Steppers. Fix bug: axis movement disorder after print finished 20210513 Fix relative_mode bug. Accelerate Z axis homing. Version 1.0.22 20210527 Solve the abnormal noise of the front fan. Improve ELECTROMAGNETIC_VALVE function. Slow down the filament feed in speed. V 1.0.23 20210604 Stop printing immediately when click OK. Fix some bugs. V 1.0.24 20210616 Change jerk value. Release inactive E & X driver V 1.0.25 20210706 Remove chinese chareters and conver files to utf-8 V 1.0.26 20210712 cancel gohome after extruder switch when printing. e steps per mm 395 (for bmg extruder). v 1.0.27 20210728 nozzle offset test print function ok. need new ui.(TJC 1.2.13 or later, DWN not yet) V 1.0.28 20210730 use function F() for touch screen serial commands, saves about 1.5k of RAM. 20210830 Fix some bugs V 1.0.29 20210915 Auto detect TJC OR DWIN Touch Screen V 1.0.30 20211012 fix some bugs V1.0.31 20211019 fix plr module bug. V1.0.32 20211112 fix tjc-lcd shake hands bug. V1.0.34 20220222 fix tjc-lcd shake hands bug. add dwn shake hands. V1.0.35 EOF UPDATE LOG */ #define VERSION_STRING "1.0.35" //#define TL_DEBUG //#define MODEL_H2P //TL-Hands2 Pro #define MODEL_D3P //TL-D3 Pro //#define MODEL_D4P //#define MODEL_D5P //#define MODEL_D6P //#define MODEL_M3 //#define MODEL_D2P //TL-Hands2 //#define MODEL_D3S #define FILAMENT_FAIL_DETECT #define POWER_LOSS_RECOVERY #define PRINT_FROM_Z_HEIGHT //#define DRIVER_2225 #define DRIVER_2208 //Same as 2209 //#define DRIVER_4988 //////////////////////// //Raise up z when Pause; //By ZYF #define PAUSE_RAISE_Z #define TL_DUAL_Z #define X_NOZZLE_WIDTH 50 #define DUAL_X_CARRIAGE // The pullups are needed if you directly connect a mechanical endswitch between the signal and ground pins. const bool X_ENDSTOPS_INVERTING = true; const bool Y_ENDSTOPS_INVERTING = true; //Y Optical switch //const bool Y_ENDSTOPS_INVERTING = false; //Y Mechanical switch //#define MIX_COLOR_TEST //#define ELECTROMAGNETIC_VALVE //evaluation version for Profesor Shen from Jilin University #if defined(DRIVER_2208) || defined(DRIVER_2225) #define INVERT_X_DIR false #define INVERT_Z_DIR false #define INVERT_E0_DIR true #define INVERT_E1_DIR false #elif defined(DRIVER_4988) #define INVERT_X_DIR true #define INVERT_Z_DIR true #define INVERT_E0_DIR false #define INVERT_E1_DIR true #endif #if defined(DRIVER_2225) #define DEFAULT_AXIS_STEPS_PER_UNIT \ { \ 160, 160, 1600, 184 \ } #define DEFAULT_MAX_FEEDRATE \ { \ 30, 30, 2, 12 \ } // (mm/sec) #else #define DEFAULT_AXIS_STEPS_PER_UNIT \ { \ 80, 80, 800, 395 \ } #define DEFAULT_MAX_FEEDRATE \ { \ 70, 70, 6, 25 \ } // (mm/sec) #endif #if defined(MODEL_D2P) #define FW_STR "HANDS2" #define TL_SIZE_220 #define P2P1 #elif defined(MODEL_H2P) #define FW_STR "HANDS2 Pro" #define TL_SIZE_235 #define P2P1 #elif defined(MODEL_D3P) #define FW_STR "D3P" #define TL_SIZE_300 #define P2P1 #elif defined(MODEL_D3S) #define FW_STR "D3S" #define TL_SIZE_300 #elif defined(MODEL_D4P) #define FW_STR "D4P" #define TL_SIZE_400 #define P2P1 #elif defined(MODEL_D5P) #define FW_STR "D5P" #define TL_SIZE_500 #define P2P1 #elif defined(MODEL_D6P) #define FW_STR "D6P" #define TL_SIZE_600 #define P2P1 #elif defined(MODEL_M3) #define FW_STR "M3" #define TL_SIZE_250 #define P2P1 #endif #define X_MIN_POS -50 #define X2_MIN_POS 0 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage #ifdef TL_SIZE_220 #define DEFAULT_DUPLICATION_X_OFFSET 115 #define X_MAX_POS 220.0 #define Y_MAX_POS 225.0 #ifdef P2P1 #define Z_MAX_POS 260.0 #else #define Z_MAX_POS 260.0 #endif #define X2_MAX_POS 264.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_250 #undef TL_DUAL_Z #undef X_MIN_POS #undef X2_MIN_POS #define X_MIN_POS 0 #define X2_MIN_POS 50 #define DEFAULT_DUPLICATION_X_OFFSET 175 #define X_MAX_POS 300.0 #define Y_MAX_POS 200.0 #ifdef P2P1 #define Z_MAX_POS 250.0 #else #define Z_MAX_POS 250.0 #endif #define X2_MAX_POS 354.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_235 #define DEFAULT_DUPLICATION_X_OFFSET 167 #define X_MAX_POS 235.0 #define Y_MAX_POS 240.0 #ifdef P2P1 #define Z_MAX_POS 260.0 #else #define Z_MAX_POS 260.0 #endif #define X2_MAX_POS 279.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_300 #define DEFAULT_DUPLICATION_X_OFFSET 155 #define X_MAX_POS 305.0 #define Y_MAX_POS 320.0 #ifdef P2P1 #define Z_MAX_POS 360.0 #else #define Z_MAX_POS 410.0 #endif #define X2_MAX_POS 359.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_400 #define DEFAULT_DUPLICATION_X_OFFSET 205 #define X_MAX_POS 405.0 #define Y_MAX_POS 420.0 #ifdef P2P1 #define Z_MAX_POS 410.0 #else #define Z_MAX_POS 410.0 #endif #define X2_MAX_POS 454.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_500 #define DEFAULT_DUPLICATION_X_OFFSET 255 #define X_MAX_POS 505.0 #define Y_MAX_POS 520.0 #ifdef P2P1 #define Z_MAX_POS 610.0 #else #define Z_MAX_POS 610.0 #endif #define X2_MAX_POS 554.0 // set maximum to the distance between toolheads when both heads are homed #endif #ifdef TL_SIZE_600 #define DEFAULT_DUPLICATION_X_OFFSET 305 #define X_MAX_POS 605.0 #define Y_MAX_POS 620.0 #ifdef P2P1 #define Z_MAX_POS 610.0 #else #define Z_MAX_POS 610.0 #endif #define X2_MAX_POS 654.0 // set maximum to the distance between toolheads when both heads are homed #endif #define FAN2_CONTROL #ifdef FAN2_CONTROL #define FAN2_PIN 5 #endif #ifdef TL_DUAL_Z #if defined(DRIVER_2208) || defined(DRIVER_2225) #define INVERT_Y_DIR true #else #define INVERT_Y_DIR false #endif const bool Z_ENDSTOPS_INVERTING = true; #else #define INVERT_Y_DIR true const bool Z_ENDSTOPS_INVERTING = true; #endif #ifdef POWER_LOSS_RECOVERY #define HAS_PLR_MODULE #define POWER_LOSS_SAVE_TO_EEPROM #define POWER_LOSS_TRIGGER_BY_PIN #if !defined(POWER_LOSS_TRIGGER_BY_PIN) #define POWER_LOSS_TRIGGER_BY_Z_LEVEL #if !defined(POWER_LOSS_TRIGGER_BY_Z_LEVEL) #define POWER_LOSS_TRIGGER_BY_E_COUNT #ifdef POWER_LOSS_TRIGGER_BY_E_COUNT #define POWER_LOSS_E_COUNT 100 #endif #endif #endif #ifndef POWER_LOSS_SAVE_TO_EEPROM #define POWER_LOSS_SAVE_TO_SDCARD #endif #if !defined(POWER_LOSS_TRIGGER_BY_PIN) //prevent eeprom damage #undef POWER_LOSS_SAVE_TO_EEPROM #define POWER_LOSS_SAVE_TO_SDCARD #endif #endif #ifdef FILAMENT_FAIL_DETECT #define FILAMENT_FAIL_DETECT_PIN 15 #define FILAMENT_FAIL_DETECT_TRIGGER LOW #endif #define DEFAULT_MAX_ACCELERATION \ { \ 500, 500, 100, 1000 \ } // 800 800 160 1600 500 500 100 1000 X, Y, Z, E maximum start speed for accelerated moves. E default values are good for skeinforge 40+, for older versions raise them a lot. #define DEFAULT_ACCELERATION 500 // X, Y, Z and E max acceleration in mm/s^2 for printing moves #define DEFAULT_RETRACT_ACCELERATION 500 // X, Y, Z and E max acceleration in mm/s^2 for retracts #define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position #define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position #define CONFIG_TL //By zyf #define CONFIG_E2_OFFSET //By Zyf //#define ENGRAVE #ifdef ENGRAVE #define ENGRAVE_ON 0 #define ENGRAVE_OFF 1 #define ENGRAVE_PIN 37 #endif //Test for Chen... //#define HOLD_M104_TEMP #endif //CONFIGURATION_TL_H
10,867
C++
.h
335
28.886567
206
0.696112
tenlog/TL-D3
38
48
26
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,906
app_httpd.cpp
eben80_ESP32-CAM-Print-Monitor/app_httpd.cpp
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //URL details: // /control?var=framesize&val=0 #include "esp_http_server.h" #include "esp_camera.h" #include "Arduino.h" #define ledPin 4 //Pin for built-in LED flash #define RELAY_PIN 13 //Relay Pin for Printer Mains Relay //Start Config // String verNum = "V0.9"; uint8_t debugmsg = 1; //Debug Serial Messages int PrintSerial_Speed = 250000; //Speed for Serial connection to Printer - Ender 3 default is 115200 #define SERIAL1_RXPIN 14 //Serial Pin for PrinterSerial #define SERIAL1_TXPIN 15 //Serial Pin for PrinterSerial String abortString = "M117 Print Aborted\nM25\nM410\nG91\nG0 Z10\n\nG0 E-5\nM400\nG90\nM104 S0\nM140 S0\nM106 S0\nG0 X0 Y220\nM18\n"; //GCode for doing an aborting a print. //End Config #ifdef __cplusplus extern "C" { #endif uint8_t temprature_sens_read(); #ifdef __cplusplus } #endif uint8_t temprature_sens_read(); unsigned char h2int(char c) { if (c >= '0' && c <= '9') { return ((unsigned char)c - '0'); } if (c >= 'a' && c <= 'f') { return ((unsigned char)c - 'a' + 10); } if (c >= 'A' && c <= 'F') { return ((unsigned char)c - 'A' + 10); } return (0); } String urldecode(String str) { String encodedString = ""; char c; char code0; char code1; for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (c == '+') { encodedString += ' '; } else if (c == '%') { i++; code0 = str.charAt(i); i++; code1 = str.charAt(i); c = (h2int(code0) << 4) | h2int(code1); encodedString += c; } else { encodedString += c; } yield(); } return encodedString; } static const char PROGMEM INDEX2_HTML[] = R"rawliteral( <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>ESP32-CAM Print Monitor</title> <style> body{font-family:Arial,Helvetica,sans-serif;background:#181818;color:#efefef;font-size:16px}h2{font-size:18px}#menu,section.main{flex-direction:column}section.main{display:flex}#menu{display:none;flex-wrap:nowrap;min-width:340px;background:#666;padding:8px;border-radius:4px;margin-top:-10px;margin-right:10px}#content{display:flex;flex-wrap:wrap;align-items:stretch}figure{padding:0;margin:0;-webkit-margin-before:0;margin-block-start:0;-webkit-margin-after:0;margin-block-end:0;-webkit-margin-start:0;margin-inline-start:0;-webkit-margin-end:0;margin-inline-end:0}figure img{display:block;width:100%;height:auto;border-radius:4px;margin-top:8px}@media (min-width:800px) and (orientation:landscape){#content{display:flex;flex-wrap:nowrap;align-items:stretch}figure img{display:block;max-width:100%;max-height:calc(100vh - 40px);width:auto;height:auto}figure{padding:0;margin:0;-webkit-margin-before:0;margin-block-start:0;-webkit-margin-after:0;margin-block-end:0;-webkit-margin-start:0;margin-inline-start:0;-webkit-margin-end:0;margin-inline-end:0}}section#buttons{display:flex;flex-wrap:nowrap;justify-content:space-between}#nav-toggle{cursor:pointer;display:block}#nav-toggle-cb{outline:0;opacity:0;width:0;height:0}#nav-toggle-cb:checked+#menu{display:flex;width:100%;max-width:780px}.input-group{display:flex;flex-wrap:nowrap;line-height:22px;margin:5px 0}.input-group>label{display:inline-block;padding-right:10px;min-width:47%}.input-group input,.input-group select{flex-grow:1}.range-max,.range-min{display:inline-block;padding:0 5px}button{display:block;margin:5px;padding:0 12px;border:0;line-height:28px;cursor:pointer;color:#fff;background:#ff3034;border-radius:5px;font-size:16px;outline:0}button:hover{background:#ff494d}button:active{background:#f21c21}button.disabled{cursor:default;background:#a0a0a0}input[type=range]{-webkit-appearance:none;width:100%;height:22px;background:#363636;cursor:pointer;margin:0}input[type=range]:focus{outline:0}input[type=range]::-webkit-slider-runnable-track{width:100%;height:2px;cursor:pointer;background:#efefef;border-radius:0;border:0 solid #efefef}input[type=range]::-webkit-slider-thumb{border:1px solid transparent;height:22px;width:22px;border-radius:50px;background:#ff3034;cursor:pointer;-webkit-appearance:none;margin-top:-11.5px}input[type=range]:focus::-webkit-slider-runnable-track{background:#efefef}input[type=range]::-moz-range-track{width:100%;height:2px;cursor:pointer;background:#efefef;border-radius:0;border:0 solid #efefef}input[type=range]::-moz-range-thumb{border:1px solid transparent;height:22px;width:22px;border-radius:50px;background:#ff3034;cursor:pointer}input[type=range]::-ms-track{width:100%;height:2px;cursor:pointer;background:0 0;border-color:transparent;color:transparent}input[type=range]::-ms-fill-lower{background:#efefef;border:0 solid #efefef;border-radius:0}input[type=range]::-ms-fill-upper{background:#efefef;border:0 solid #efefef;border-radius:0}input[type=range]::-ms-thumb{border:1px solid transparent;width:22px;border-radius:50px;background:#ff3034;cursor:pointer;height:2px}input[type=range]:focus::-ms-fill-lower{background:#efefef}input[type=range]:focus::-ms-fill-upper{background:#363636}.switch{line-height:22px;font-size:16px}.switch input{outline:0;opacity:0;width:0;height:0}.slider,.slider:before{width:50px;height:22px;border-radius:22px;display:inline-block}.slider:before{border-radius:50%;top:3px;position:absolute;content:"";height:15px;width:15px;left:4px;bottom:4px;background-color:#fff;-webkit-transition:.4s;transition:.4s}input:checked+.slider{background-color:#2196f3}input:checked+.slider:before{-webkit-transform:translateX(26px);-ms-transform:translateX(26px);transform:translateX(26px)}select{border:1px solid #363636;font-size:14px;height:22px;outline:0;border-radius:5px}.image-container{position:relative;min-width:160px}.abortbtn,.powerbtn{position:absolute;right:5px;top:5px;background-color:rgba(255,48,52,.5);color:#fff;text-align:center}.powerbtn{top:40px}.bedtemp,.elapsedtime,.exttemp,.proglabel,.cputemp{font-family:Arial,Helvetica,sans-serif;font-size:10px;position:absolute;left:5px;top:5px;background-color:rgba(140,114,114,.5);color:#fff;text-align:center}.bedtemp,.elapsedtime,.exttemp{top:23px}.bedtemp,.exttemp{top:40px}.bedtemp{top:60px}.cputemp{top:80px}.hidden{display:none}.lightsw{position:absolute;right:5px;top:85px;text-align:center;font-family:Arial,Helvetica,sans-serif}.streamsw{position:absolute;right:5px;top:130px;text-align:center;font-family:Arial,Helvetica,sans-serif}.switch{position:relative;display:inline-block;width:60px;height:34px}.slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#ccc;-webkit-transition:.4s;transition:.4s}input:focus+.slider{box-shadow:0 0 1px #2196f3}.slider.round{border-radius:34px}.slider.round:before{border-radius:50%} </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> function load() { var refreshrate = 60000; var myCookie = getCookie("refreshrate"); if (myCookie == null) { document.cookie = "refreshrate=60000;expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/"; // do cookie doesn't exist stuff; } else { refreshrate = getCookie("refreshrate"); $("#refreshrate").val(refreshrate); // do cookie exists stuff } change(); check(); var inst = setInterval(change, refreshrate); var query = setInterval(check, refreshrate); function change() { $.ajax({ url: "status", method: "GET", success: function(data) { var temperature = data.temperature; var elem = document.getElementById("cpu-temp"); elem.innerHTML = 'CPU: ' + Number.parseFloat(temperature).toFixed(2) + ' &#8451'; }, error: function(data) { console.log("Data Error - status"); console.log(data); } }); console.log("change executed"); } function check() { $.ajax({ url: "control?var=query&val=1", method: "GET", success: function(data2) { var progress = data2.progress; var exttemp = data2.exttemp; var bedtemp = data2.bedtemp; var elapsedt = data2.elapsedt; // var version = data2.ver; var proglabel = document.getElementById("prog-label"); proglabel.innerHTML = 'Progress: ' + progress + ' %'; var exttemplabel = document.getElementById("ext-temp"); exttemplabel.innerHTML = 'Extruder: ' + exttemp + ' &#8451'; var bedtemplabel = document.getElementById("bed-temp"); bedtemplabel.innerHTML = 'Bed: ' + bedtemp + ' &#8451'; var elapsedlabel = document.getElementById("elapsed-time"); elapsedlabel.innerHTML = 'Elapsed Time: ' + elapsedt; // $('#vernum').val(version); }, error: function(data2) { console.log("Data Error - query"); console.log (data2); } }); console.log("check executed refresh=" + refreshrate); } $('#lighttoggle').change(function() { if (document.getElementById('lighttoggle').checked) { $.ajax({ type: 'GET', url: 'control?var=light&val=1', success: function(data) {} }); } else { $.ajax({ type: 'GET', url: 'control?var=light&val=0', success: function(data) {} }); } }); $('#refreshrate').change(function() { refreshrate = document.getElementById('refreshrate').value; document.cookie = "refreshrate=" + refreshrate + ";expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/"; clearInterval(inst); inst = setInterval(change, refreshrate); clearInterval(query); query = setInterval(check, refreshrate); }); $('#streamtoggle').change(function() { if (document.getElementById('streamtoggle').checked) { document.getElementById('stream').src = window.location.protocol + "//" + window.location.hostname + ":9601/stream"; } else { window.stop document.getElementById('stream').src = "https://www.mapme.ga/ESP32-CAM-PM.jpg"; } }); function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } } // because unescape has been deprecated, replaced with decodeURI //return unescape(dc.substring(begin + prefix.length, end)); return decodeURI(dc.substring(begin + prefix.length, end)); } } </script> <script> function abortClicked() { var x; if (confirm("Are you sure you want to abort the print?") == true) { $.ajax({ url: 'control?var=abort&val=1', method: "GET", success: function(data) { }, error: function(data) { console.log("Data Error - abort"); } }); } else { x = "You pressed Cancel!"; } return x; } function rebootClicked() { var x; if (confirm("Are you sure you want to reboot the ESP?") == true) { $.get('control?var=reboot&val=1'); } else { x = "You pressed Cancel!"; } return x; } function powerClicked() { var x; if (confirm("Are you sure you want to power cycle the printer?") == true) { $.ajax({ url: 'control?var=shutdown&val=1', method: "GET", success: function(data) { }, error: function(data) { console.log("Data Error - shutdown"); } }); } else { x = "You pressed Cancel!"; } return x; } function sendClicked() { var x; if (document.getElementById('gcode').value.length > 0) { x = document.getElementById('gcode').value + '\n'; x = encodeURI(x); console.log(x); document.getElementById('sendButton').disabled = true; $.ajax({ url: 'control?var=command&val=' + x, method: "GET", success: function(data3) { var cmdresponse = data3.cmdresponse; console.log(cmdresponse); document.getElementById('gcode').value = ""; document.getElementById('gcode').placeholder = cmdresponse; document.getElementById('sendButton').disabled = false; }, error: function(data) { console.log("Data Error - gcode command"); document.getElementById('sendButton').disabled = false; } }); } else { alert("No command entered.."); } } </script> </head> <body onload="load()"> <section class="main"> <div id="content"> <figure> <div id="stream-container" class="image-container" width="800" height="600"> <button class="abortbtn" id="abort-btn" onclick="abortClicked()">Abort</button> <button class="powerbtn" id="power-btn" onclick="powerClicked()">Power</button> <div class="lightsw" id="light-sw"> <label class="switch"> <input type="checkbox" id ="lighttoggle"> <span class="slider round"></span><br/> Light </label> </div> <div class="streamsw" id="stream-sw"> <label class="switch"> <input type="checkbox" id ="streamtoggle"> <span class="slider round"></span><br/> Stream </label> </div> <div class="proglabel" id="prog-label">Progress: Reading... </div> <div class="elapsedtime" id="elapsed-time">Elapsed time: Reading... </div> <div class="exttemp" id="ext-temp">Extruder: Reading... </div> <div class="bedtemp" id="bed-temp">Bed: Reading... </div> <div class="cputemp" id="cpu-temp">CPU: Reading... </div> <img id="stream" src="https://www.mapme.ga/ESP32-CAM-PM.jpg"> </div> </figure> </div> </section> <textarea id="gcode" rows="2" cols="40"></textarea><button id="sendButton" onclick="sendClicked()" placeholder="Enter GCode.." style="display:inline-block;">Send Code</button> <div id="logo"> <label for="nav-toggle-cb" id="nav-toggle">&#9776;&nbsp;&nbsp;Toggle settings</label> </div> <div id="sidebar"> <input type="checkbox" id="nav-toggle-cb"> <nav id="menu"> <div class="input-group" id="framesize-group"> <label for="refreshrate">Refresh Rate</label> <select id="refreshrate" class="default-action"> <option value="120000">120 seconds</option> <option value="60000" selected="selected">60 seconds</option> <option value="30000">30 seconds</option> <option value="20000">20 seconds</option> <option value="10000">10 seconds</option> <option value="3000">3 seconds</option> </select> </div> <section id="buttons"> <button id="rebootbtn" onclick="rebootClicked()">Reboot ESP</button> </section> </nav> </div> </body> </html> )rawliteral"; /////////// typedef struct { httpd_req_t *req; size_t len; } jpg_chunking_t; #define PART_BOUNDARY "123456789000000000000987654321" static const char *_STREAM_CONTENT_TYPE = "multipart/x-mixed-replace;boundary=" PART_BOUNDARY; static const char *_STREAM_BOUNDARY = "\r\n--" PART_BOUNDARY "\r\n"; static const char *_STREAM_PART = "Content-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n"; httpd_handle_t stream_httpd = NULL; httpd_handle_t camera_httpd = NULL; static int8_t light_enabled = 0; static int8_t aborted = 0; static int8_t shutdown = 0; static size_t jpg_encode_stream(void *arg, size_t index, const void *data, size_t len) { jpg_chunking_t *j = (jpg_chunking_t *)arg; if (!index) { j->len = 0; } if (httpd_resp_send_chunk(j->req, (const char *)data, len) != ESP_OK) { return 0; } j->len += len; return len; } static esp_err_t stream_handler(httpd_req_t *req) { camera_fb_t *fb = NULL; esp_err_t res = ESP_OK; size_t _jpg_buf_len = 0; uint8_t *_jpg_buf = NULL; char *part_buf[256]; //used to be 64 res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE); if (res != ESP_OK) { return res; } httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); while (true) { fb = esp_camera_fb_get(); if (!fb) { Serial.println("Camera capture failed"); res = ESP_FAIL; } else { if (fb->width > 400) { if (fb->format != PIXFORMAT_JPEG) { bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len); esp_camera_fb_return(fb); fb = NULL; if (!jpeg_converted) { Serial.println("JPEG compression failed"); res = ESP_FAIL; } } else { _jpg_buf_len = fb->len; _jpg_buf = fb->buf; } } } if (res == ESP_OK) { size_t hlen = snprintf((char *)part_buf, 256, _STREAM_PART, _jpg_buf_len); res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen); } if (res == ESP_OK) { res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len); } if (res == ESP_OK) { res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY)); } if (fb) { esp_camera_fb_return(fb); fb = NULL; _jpg_buf = NULL; } else if (_jpg_buf) { free(_jpg_buf); _jpg_buf = NULL; } if (res != ESP_OK) { Serial.println(res); break; } } return res; } static esp_err_t cmd_handler(httpd_req_t *req) { HardwareSerial PrintSerial(1); PrintSerial.begin(PrintSerial_Speed, SERIAL_8N1, SERIAL1_RXPIN, SERIAL1_TXPIN); PrintSerial.setRxBufferSize(15000); char *buf; size_t buf_len; char variable[32] = { 0, }; char value[32] = { 0, }; buf_len = httpd_req_get_url_query_len(req) + 1; if (buf_len > 1) { buf = (char *)malloc(buf_len); if (!buf) { httpd_resp_send_500(req); return ESP_FAIL; } if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { if (httpd_query_key_value(buf, "var", variable, sizeof(variable)) == ESP_OK && httpd_query_key_value(buf, "val", value, sizeof(value)) == ESP_OK) { if (debugmsg) { // Serial.println(value); } } else { free(buf); httpd_resp_send_404(req); return ESP_FAIL; } } else { free(buf); httpd_resp_send_404(req); return ESP_FAIL; } free(buf); } else { httpd_resp_send_404(req); return ESP_FAIL; } int val = atoi(value); sensor_t *s = esp_camera_sensor_get(); int res = 0; if (!strcmp(variable, "framesize")) { if (s->pixformat == PIXFORMAT_JPEG) res = s->set_framesize(s, (framesize_t)val); } else if (!strcmp(variable, "quality")) res = s->set_quality(s, val); else if (!strcmp(variable, "contrast")) res = s->set_contrast(s, val); else if (!strcmp(variable, "brightness")) res = s->set_brightness(s, val); else if (!strcmp(variable, "saturation")) res = s->set_saturation(s, val); else if (!strcmp(variable, "gainceiling")) res = s->set_gainceiling(s, (gainceiling_t)val); else if (!strcmp(variable, "colorbar")) res = s->set_colorbar(s, val); else if (!strcmp(variable, "awb")) res = s->set_whitebal(s, val); else if (!strcmp(variable, "agc")) res = s->set_gain_ctrl(s, val); else if (!strcmp(variable, "aec")) res = s->set_exposure_ctrl(s, val); else if (!strcmp(variable, "hmirror")) res = s->set_hmirror(s, val); else if (!strcmp(variable, "vflip")) res = s->set_vflip(s, val); else if (!strcmp(variable, "awb_gain")) res = s->set_awb_gain(s, val); else if (!strcmp(variable, "agc_gain")) res = s->set_agc_gain(s, val); else if (!strcmp(variable, "aec_value")) res = s->set_aec_value(s, val); else if (!strcmp(variable, "aec2")) res = s->set_aec2(s, val); else if (!strcmp(variable, "dcw")) res = s->set_dcw(s, val); else if (!strcmp(variable, "bpc")) res = s->set_bpc(s, val); else if (!strcmp(variable, "wpc")) res = s->set_wpc(s, val); else if (!strcmp(variable, "raw_gma")) res = s->set_raw_gma(s, val); else if (!strcmp(variable, "lenc")) res = s->set_lenc(s, val); else if (!strcmp(variable, "special_effect")) res = s->set_special_effect(s, val); else if (!strcmp(variable, "wb_mode")) res = s->set_wb_mode(s, val); else if (!strcmp(variable, "ae_level")) { Serial.printf("var="); Serial.printf(variable); res = s->set_ae_level(s, val); Serial.printf(" valvar="); Serial.print(val); } else if (!strcmp(variable, "light")) { light_enabled = val; if (light_enabled) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } } else if (!strcmp(variable, "reboot")) { // light_enabled = val; if (val) { if (debugmsg) { Serial.println("Restarting ESP"); } ESP.restart(); } else { // digitalWrite(ledPin, LOW); } } else if (!strcmp(variable, "query")) { String a, part1, part2, exttemp, bedtemp, elapsedt, firstHalf, secondHalf; float progress, part1long, part2long; int ind1, bedindex, lastindex, extindex, lastind; if (debugmsg) { Serial.println("Start query"); } PrintSerial.print("M27\n"); //SD printing byte XXXXXX/XXXXXXX if (debugmsg) { Serial.println("M27 Sent"); } delay(700); while (PrintSerial.available()) { a = PrintSerial.readStringUntil('\n'); // read the incoming data as string if (a.startsWith("SD printing byte ")) { //Printing progress response if (debugmsg) { Serial.println("Printing progress Triggered"); Serial.println(a); } a.remove(0, 17); ind1; ind1 = a.indexOf('/'); part1 = a.substring(0, ind1); part2 = a.substring(ind1 + 1); part1long = part1.toFloat(); part2long = part2.toFloat(); progress = (part1long / part2long) * 100; } else if (a.startsWith("ok T")) { //Temperature response if (debugmsg) { Serial.println("Temperature response Triggered"); Serial.println(a); } a.remove(0, 5); bedindex = a.indexOf(":"); secondHalf = a.substring(bedindex, a.length()); secondHalf.remove(0, 1); lastindex = secondHalf.indexOf(" "); secondHalf.remove(lastindex); extindex = a.indexOf(" "); firstHalf = a; firstHalf.remove(extindex); // a.remove(tempstring); if (debugmsg) { Serial.println("Ext temp:" + firstHalf); Serial.println("Bed temp:" + secondHalf); } exttemp = firstHalf; bedtemp = secondHalf; } else if (a.startsWith("echo")) { if (debugmsg) { Serial.println("Elapsed Time Response Triggered"); Serial.println(a); } lastind = a.lastIndexOf(":"); a.remove(0, lastind); a.remove(0, 2); elapsedt = a; } else { if (debugmsg) { Serial.println("Unknown response: " + a); } } } PrintSerial.print("M31\n"); //echo: Print time: XXh XXm XXs if (debugmsg) { Serial.println("M31 Sent"); } delay(700); while (PrintSerial.available()) { a = PrintSerial.readStringUntil('\n'); // read the incoming data as string if (a.startsWith("SD printing byte ")) { //Printing progress response if (debugmsg) { Serial.println("Printing progress Triggered"); Serial.println(a); } a.remove(0, 17); ind1; ind1 = a.indexOf('/'); part1 = a.substring(0, ind1); part2 = a.substring(ind1 + 1); part1long = part1.toFloat(); part2long = part2.toFloat(); progress = (part1long / part2long) * 100; } else if (a.startsWith("ok T")) { //Temperature response if (debugmsg) { Serial.println("Temperature response Triggered"); Serial.println(a); } a.remove(0, 5); bedindex = a.indexOf(":"); secondHalf = a.substring(bedindex, a.length()); // Serial.println("secondHalf" + secondHalf); secondHalf.remove(0, 1); lastindex = secondHalf.indexOf(" "); secondHalf.remove(lastindex); extindex = a.indexOf(" "); firstHalf = a; firstHalf.remove(extindex); // a.remove(tempstring); if (debugmsg) { Serial.println("Ext temp:" + firstHalf); Serial.println("Bed temp:" + secondHalf); } exttemp = firstHalf; bedtemp = secondHalf; } else if (a.startsWith("echo")) { if (debugmsg) { Serial.println("Elapsed Time Response Triggered"); Serial.println(a); } lastind = a.lastIndexOf(":"); a.remove(0, lastind); a.remove(0, 2); elapsedt = a; } else { if (debugmsg) { Serial.println("Unknown response: " + a); } } } PrintSerial.print("M105\n"); //ok T:XXX.XX /XXX.XX B:XXX.XX /XXX.XX @:XXX B@:XXX if (debugmsg) { Serial.println("M105 Sent"); } delay(700); while (PrintSerial.available()) { a = PrintSerial.readStringUntil('\n'); // read the incoming data as string if (a.startsWith("SD printing byte ")) { //Printing progress response if (debugmsg) { Serial.println("Printing progress Triggered"); Serial.println(a); } a.remove(0, 17); ind1; ind1 = a.indexOf('/'); part1 = a.substring(0, ind1); part2 = a.substring(ind1 + 1); part1long = part1.toFloat(); part2long = part2.toFloat(); progress = (part1long / part2long) * 100; } else if (a.startsWith("ok T")) { //Temperature response if (debugmsg) { Serial.println("Temperature response Triggered"); Serial.println(a); } a.remove(0, 5); bedindex = a.indexOf(":"); secondHalf = a.substring(bedindex, a.length()); // Serial.println("secondHalf" + secondHalf); secondHalf.remove(0, 1); lastindex = secondHalf.indexOf(" "); secondHalf.remove(lastindex); extindex = a.indexOf(" "); firstHalf = a; firstHalf.remove(extindex); // a.remove(tempstring); if (debugmsg) { Serial.println("Ext temp:" + firstHalf); Serial.println("Bed temp:" + secondHalf); } exttemp = firstHalf; bedtemp = secondHalf; } else if (a.startsWith("echo")) { if (debugmsg) { Serial.println("Elapsed Time Response Triggered"); Serial.println(a); } lastind = a.lastIndexOf(":"); a.remove(0, lastind); a.remove(0, 2); elapsedt = a; } else { if (debugmsg) { Serial.println("Unknown response: " + a); } } } static char json_response2[1024]; char *p = json_response2; *p++ = '{'; p += sprintf(p, "\"progress\":\"%.2f\",", progress); p += sprintf(p, "\"exttemp\":\"%s\",", exttemp.c_str()); p += sprintf(p, "\"bedtemp\":\"%s\",", bedtemp.c_str()); p += sprintf(p, "\"elapsedt\":\"%s\"", elapsedt.c_str()); // p += sprintf(p, "\"ver\":\"%s\"", verNum.c_str()); *p++ = '}'; *p++ = 0; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, json_response2, strlen(json_response2)); } else if (!strcmp(variable, "abort")) { aborted = val; if (aborted) { if (debugmsg) { Serial.println("Sending Abort Start"); } PrintSerial.print(abortString); PrintSerial.print("M117 Heaters off, going HOME\n"); if (debugmsg) { Serial.println("Sending Abort Complete"); } } else { } } else if (!strcmp(variable, "shutdown")) { // shutdown = val; if (!shutdown) { if (debugmsg) { Serial.println("Power Off"); } digitalWrite(RELAY_PIN, HIGH); shutdown = 1; } else if (shutdown) { if (debugmsg) { Serial.println("Power On"); } digitalWrite(RELAY_PIN, LOW); shutdown = 0; } } else if (!strcmp(variable, "command")) { String cmdText = value; cmdText = urldecode(cmdText); PrintSerial.print(cmdText); if (debugmsg) { Serial.print(cmdText + " Command Sent\n"); } delay(2000); String cmdResponse = ""; String cmdConcat = ""; bool breakOuterLoop = false; for (;;) { uint32_t timeout = 5000; uint32_t start = millis(); if (breakOuterLoop) { if (debugmsg) { Serial.println("Breaking outer loop..."); } break; } if (PrintSerial.available() >= 1) { while (PrintSerial.available()) { cmdResponse = PrintSerial.readStringUntil('\n'); if (debugmsg) { Serial.println(cmdResponse + " " + PrintSerial.available()); if (!PrintSerial.available()) { Serial.println("Buffer Empty..."); } } cmdResponse = cmdResponse + "\\n"; cmdConcat = cmdConcat + cmdResponse; if (!PrintSerial.available()) { breakOuterLoop = true; break; } if (cmdResponse.indexOf("ok") != -1) { if (debugmsg) { Serial.println("ok reached..."); } breakOuterLoop = true; break; } while ((PrintSerial.available() < 20) && ((millis()-start) < timeout)) { delay(100); } } } } static char json_response2[4096]; char *p = json_response2; *p++ = '{'; p += sprintf(p, "\"cmdresponse\":\"%s\"", cmdConcat.c_str()); *p++ = '}'; *p++ = 0; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, json_response2, strlen(json_response2)); } else { res = -1; } if (res) { return httpd_resp_send_500(req); } httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, NULL, 0); if (debugmsg) { Serial.printf("Command issued"); } } static esp_err_t status_handler(httpd_req_t *req) { static char json_response[1024]; sensor_t *s = esp_camera_sensor_get(); char *p = json_response; *p++ = '{'; p += sprintf(p, "\"temperature\":%f", (temprature_sens_read() - 32) / 1.8); *p++ = '}'; *p++ = 0; httpd_resp_set_type(req, "application/json"); httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*"); return httpd_resp_send(req, json_response, strlen(json_response)); if (debugmsg) { Serial.printf("Status sent"); } } static esp_err_t index_handler(httpd_req_t *req) { httpd_resp_set_type(req, "text/html"); if (debugmsg) { Serial.printf("Index loading"); } return httpd_resp_send(req, (const char *)INDEX2_HTML, strlen(INDEX2_HTML)); } void startCameraServer() { httpd_config_t config = HTTPD_DEFAULT_CONFIG(); httpd_uri_t index_uri = { .uri = "/", .method = HTTP_GET, .handler = index_handler, .user_ctx = NULL}; httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_handler, .user_ctx = NULL}; httpd_uri_t cmd_uri = { .uri = "/control", .method = HTTP_GET, .handler = cmd_handler, .user_ctx = NULL}; httpd_uri_t stream_uri = { .uri = "/stream", .method = HTTP_GET, .handler = stream_handler, .user_ctx = NULL}; Serial.printf("Starting web server on port: '%d'\n", config.server_port); if (httpd_start(&camera_httpd, &config) == ESP_OK) { httpd_register_uri_handler(camera_httpd, &index_uri); httpd_register_uri_handler(camera_httpd, &cmd_uri); httpd_register_uri_handler(camera_httpd, &status_uri); } config.server_port += 1; config.ctrl_port += 1; config.server_port = 9601; //stream port + also change this in the html-source in this file // config.ctrl_port =8081; Serial.printf("Starting stream server on stream port: '%d'\n", config.server_port); if (httpd_start(&stream_httpd, &config) == ESP_OK) { httpd_register_uri_handler(stream_httpd, &stream_uri); } }
39,703
C++
.cpp
1,010
27.59604
4,855
0.516355
eben80/ESP32-CAM-Print-Monitor
36
7
3
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,907
settings.cpp
Photonsters_Universal-Photon-Network-Controller/settings.cpp
#include "settings.h" double pingTimeOut = 100; double replyTimeout = 2000; wxString ipAddress = wxString("192.168.1.222"); double port = 3000; double pollingInterval = 1000; wxArrayString StaticIPList; bool enableLogging=true; void saveLog(LOG_TYPE Type,wxString Message) { if(!enableLogging) return; wxString ini_Directory = wxStandardPaths::Get().GetUserConfigDir() + wxFileName::GetPathSeparator() + wxString("PhotonTool"); if(!wxDir::Exists(ini_Directory)) //create directory if it doesn't exist wxDir::Make(ini_Directory); wxString log_filename = wxStandardPaths::Get().GetUserConfigDir() + wxFileName::GetPathSeparator() + wxString("PhotonTool")+ wxFileName::GetPathSeparator() + wxString(_("run.LOG")); wxTextFile logFile(log_filename); bool fileOpened=false; if(wxFileExists(log_filename)) fileOpened = logFile.Open(); else fileOpened = logFile.Create(); if(fileOpened) { wxString logType=wxString("\t[Information]\t"); if(Type==LOG_ERROR) logType=wxString("\t[Error]\t"); else if(Type==LOG_WARNING) logType=wxString("\t[Warning]\t"); else if(Type==LOG_EXCEPTION) logType=wxString("\t[Exception]\t"); else if(Type==LOG_INFORMATION) logType=wxString("\t[Information]\t"); wxLongLong utc_time = wxGetUTCTimeMillis(); wxDateTime utc_dt(utc_time); unsigned short milisec = utc_dt.GetMillisecond(); wxString ms = wxString::Format("%u", milisec); //Convert the milisecond to string if(ms.Length()==1) ms=wxString("00")+ms; else if(ms.Length()==2) ms=wxString("0")+ms; logFile.AddLine(utc_dt.Format("%a %d:%B:%Y %I:%M:%S:")+ ms +utc_dt.Format(" %p") + logType + Message); } logFile.Write(); logFile.Close(); }
1,882
C++
.cpp
46
34.434783
185
0.648118
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,908
SettingsDialog.cpp
Photonsters_Universal-Photon-Network-Controller/SettingsDialog.cpp
#include "SettingsDialog.h" //(*InternalHeaders(SettingsDialog) #include <wx/artprov.h> #include <wx/bitmap.h> #include <wx/image.h> #include <wx/intl.h> #include <wx/string.h> //*) #include <wx/textdlg.h> #include <wx/tokenzr.h> #include <wx/dynarray.h> #include "settings.h" #include "NewFrame.h" bool IsIPAddress(wxString ipaddr) { wxStringTokenizer quads(ipaddr.Trim(), "."); if (quads.CountTokens() != 4) return false; wxString quad; while (quads.HasMoreTokens()) { quad = quads.GetNextToken(); if(!quad.IsNumber()) return false; long value; if(!quad.ToLong(&value)) return false; else { if ((value < 0) || (value > 255)) return false; } } return true; } //(*IdInit(SettingsDialog) const long SettingsDialog::ID_STATICTEXT1 = wxNewId(); const long SettingsDialog::ID_STATICTEXT2 = wxNewId(); const long SettingsDialog::ID_STATICTEXT3 = wxNewId(); const long SettingsDialog::ID_STATICTEXT4 = wxNewId(); const long SettingsDialog::ID_TEXTCTRL1 = wxNewId(); const long SettingsDialog::ID_TEXTCTRL2 = wxNewId(); const long SettingsDialog::ID_TEXTCTRL3 = wxNewId(); const long SettingsDialog::ID_TEXTCTRL4 = wxNewId(); const long SettingsDialog::ID_BUTTON1 = wxNewId(); const long SettingsDialog::ID_BUTTON2 = wxNewId(); const long SettingsDialog::ID_STATICTEXT5 = wxNewId(); const long SettingsDialog::ID_LISTBOX1 = wxNewId(); const long SettingsDialog::ID_BITMAPBUTTON1 = wxNewId(); const long SettingsDialog::ID_BITMAPBUTTON2 = wxNewId(); const long SettingsDialog::ID_CHECKBOX1 = wxNewId(); const long SettingsDialog::ID_PANEL1 = wxNewId(); //*) BEGIN_EVENT_TABLE(SettingsDialog,wxDialog) //(*EventTable(SettingsDialog) //*) END_EVENT_TABLE() NewFrame *parentFrame=NULL; SettingsDialog::SettingsDialog(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size) { //(*Initialize(SettingsDialog) Create(parent, wxID_ANY, _("Settings"), wxDefaultPosition, wxDefaultSize, wxCAPTION|wxDEFAULT_DIALOG_STYLE|wxCLOSE_BOX, _T("wxID_ANY")); SetClientSize(wxSize(321,281)); SetMaxSize(wxSize(25,-1)); btnAddIP = new wxPanel(this, ID_PANEL1, wxPoint(0,0), wxSize(320,280), wxTAB_TRAVERSAL, _T("ID_PANEL1")); StaticText1 = new wxStaticText(btnAddIP, ID_STATICTEXT1, _("Ping Timeout in ms :"), wxPoint(16,16), wxDefaultSize, 0, _T("ID_STATICTEXT1")); StaticText2 = new wxStaticText(btnAddIP, ID_STATICTEXT2, _("Reply Timeout in ms :"), wxPoint(16,41), wxDefaultSize, 0, _T("ID_STATICTEXT2")); StaticText3 = new wxStaticText(btnAddIP, ID_STATICTEXT3, _("Polling Interval in ms :"), wxPoint(16,66), wxDefaultSize, 0, _T("ID_STATICTEXT3")); StaticText4 = new wxStaticText(btnAddIP, ID_STATICTEXT4, _("Connection Port :"), wxPoint(16,89), wxDefaultSize, 0, _T("ID_STATICTEXT4")); txtPingTimeout = new wxTextCtrl(btnAddIP, ID_TEXTCTRL1, _("100"), wxPoint(160,16), wxSize(148,21), 0, wxTextValidator(wxFILTER_DIGITS), _T("ID_TEXTCTRL1")); txtReplyTimeout = new wxTextCtrl(btnAddIP, ID_TEXTCTRL2, _("2000"), wxPoint(160,40), wxSize(148,21), 0, wxTextValidator(wxFILTER_DIGITS), _T("ID_TEXTCTRL2")); txtPollingInterval = new wxTextCtrl(btnAddIP, ID_TEXTCTRL3, _("1000"), wxPoint(160,64), wxSize(148,21), 0, wxTextValidator(wxFILTER_DIGITS), _T("ID_TEXTCTRL3")); txtConnectionPort = new wxTextCtrl(btnAddIP, ID_TEXTCTRL4, _("3000"), wxPoint(160,88), wxSize(148,21), 0, wxTextValidator(wxFILTER_DIGITS), _T("ID_TEXTCTRL4")); btnSettingsCancel = new wxButton(btnAddIP, ID_BUTTON1, _("Cancel"), wxPoint(224,248), wxSize(83,23), 0, wxDefaultValidator, _T("ID_BUTTON1")); btnSettingsOK = new wxButton(btnAddIP, ID_BUTTON2, _("OK"), wxPoint(128,248), wxSize(83,23), 0, wxDefaultValidator, _T("ID_BUTTON2")); StaticText5 = new wxStaticText(btnAddIP, ID_STATICTEXT5, _("Static IP List : "), wxPoint(16,113), wxDefaultSize, 0, _T("ID_STATICTEXT5")); listIPList = new wxListBox(btnAddIP, ID_LISTBOX1, wxPoint(160,112), wxSize(148,120), 0, 0, wxLB_MULTIPLE, wxDefaultValidator, _T("ID_LISTBOX1")); BitmapButtonAddIP = new wxBitmapButton(btnAddIP, ID_BITMAPBUTTON1, wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_NEW")),wxART_BUTTON), wxPoint(128,208), wxSize(25,25), wxBU_AUTODRAW|wxSIMPLE_BORDER, wxDefaultValidator, _T("ID_BITMAPBUTTON1")); BitmapButtonAddIP->SetMinSize(wxSize(25,25)); BitmapButtonAddIP->SetMaxSize(wxSize(25,25)); BitmapButtonAddIP->SetToolTip(_("Add IP to list")); BitmapButtonDeleteIP = new wxBitmapButton(btnAddIP, ID_BITMAPBUTTON2, wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_DELETE")),wxART_BUTTON), wxPoint(128,180), wxSize(25,25), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_BITMAPBUTTON2")); BitmapButtonDeleteIP->SetMinSize(wxSize(25,25)); BitmapButtonDeleteIP->SetMaxSize(wxSize(25,25)); BitmapButtonDeleteIP->SetToolTip(_("Delete IP From list")); chkEnableLogging = new wxCheckBox(btnAddIP, ID_CHECKBOX1, _("Log Enable"), wxPoint(16,253), wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1")); chkEnableLogging->SetValue(true); Center(); Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&SettingsDialog::OnbtnSettingsCancelClick); Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&SettingsDialog::OnbtnSettingsOKClick); Connect(ID_BITMAPBUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&SettingsDialog::OnBitmapButtonAddIPClick); Connect(ID_BITMAPBUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&SettingsDialog::OnBitmapButtonDeleteIPClick); Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&SettingsDialog::OnClose); //*) parentFrame =(NewFrame*) parent; parentFrame->readSettings(); txtPingTimeout->SetValue(wxString::Format(wxT("%d"), (int)pingTimeOut)); txtReplyTimeout->SetValue(wxString::Format(wxT("%d"), (int)replyTimeout)); txtPollingInterval->SetValue(wxString::Format(wxT("%d"), (int)pollingInterval)); txtConnectionPort->SetValue(wxString::Format(wxT("%d"), (int)port)); if(StaticIPList.GetCount()>0) { listIPList->Clear(); for(unsigned int i=0;i<StaticIPList.GetCount();i++) { listIPList->Append(StaticIPList[i].Trim()); } } chkEnableLogging->SetValue(enableLogging); } SettingsDialog::~SettingsDialog() { //(*Destroy(SettingsDialog) //*) } void SettingsDialog::OnbtnSettingsOKClick(wxCommandEvent& event) { double value; if(txtPingTimeout->GetValue().ToDouble(&value)){ pingTimeOut = value; } else {pingTimeOut = 250;} if(txtReplyTimeout->GetValue().ToDouble(&value)){ replyTimeout = value; } else {replyTimeout = 2000;} if(txtPollingInterval->GetValue().ToDouble(&value)){ pollingInterval = value; } else {pollingInterval = 1000;} if(txtConnectionPort->GetValue().ToDouble(&value)){ port = value; } else {port = 3000;} if(chkEnableLogging->IsChecked()){enableLogging=true;} else {enableLogging=false;} StaticIPList.clear(); for(unsigned int i=0;i<listIPList->GetCount();i++) { wxString data = listIPList->GetString(i); if(IsIPAddress(data)) { StaticIPList.Add(data); } } parentFrame->saveSettings(); parentFrame->btnSettings->Enable(); AcceptAndClose(); } void SettingsDialog::OnbtnSettingsCancelClick(wxCommandEvent& event) { parentFrame->btnSettings->Enable(); AcceptAndClose(); //Destroy(); } void SettingsDialog::OnClose(wxCloseEvent& event) { parentFrame->btnSettings->Enable(); AcceptAndClose(); } void SettingsDialog::OnBitmapButtonAddIPClick(wxCommandEvent& event) { wxTextEntryDialog *dlg = new wxTextEntryDialog(this, "Enter the IP address that you wist to add","IP input", ""); if (dlg->ShowModal() == wxID_OK) { if(IsIPAddress(dlg->GetValue())) listIPList->Append(dlg->GetValue()); } //return dlg.GetValue() dlg->Destroy(); } void SettingsDialog::OnBitmapButtonDeleteIPClick(wxCommandEvent& event) { wxArrayInt selection; listIPList->GetSelections(selection); if(selection.GetCount()>0) { StaticIPList.clear(); for(unsigned int i=0;i<listIPList->GetCount();i++) { if(selection.Index(i)== wxNOT_FOUND) //the current index is not one of the indices choosen to be deleted { StaticIPList.Add(listIPList->GetString(i)); } } listIPList->Clear(); for (unsigned int i = 0;i<StaticIPList.GetCount();i++) { listIPList->Append(StaticIPList[i].Trim()); } } }
8,555
C++
.cpp
179
43.821229
260
0.720574
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,909
ping.cpp
Photonsters_Universal-Photon-Network-Controller/ping.cpp
#include "wx/process.h" #include <wx/string.h> #include "ping.h" bool pingPrinter(wxString ipAddress,int Timeout) { #if defined(__WINDOWS__) wxString cmd = wxString::Format("ping -n 1 -w %d -l 32 ", Timeout) + ipAddress; #else wxString cmd = wxString::Format("ping -c 1 -W %d -s 32 ", Timeout) + ipAddress; #endif wxArrayString output, errors; int code = wxExecute(cmd, output, errors); if(code!=0) return false; for(unsigned int i=0;i<output.GetCount();i++) { wxString line = output.Item(i); // line =line; //printf("%s",(char*)( line.mb_str().data())); #if defined(__WINDOWS__) if(line.Contains(wxString("timed out")) || line.Contains(wxString("host unreachable"))) { //printf("Ping Failed"); return false; } #else if(line.Find(wxString("packet loss"))!=wxNOT_FOUND) { wxString loss = line.BeforeLast('%').AfterLast(','); double value; if(loss.ToDouble(&value)) { if(value==0) return true; else return false; } } #endif } return true; }
1,288
C++
.cpp
42
21.357143
99
0.514469
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,910
NewFrame.cpp
Photonsters_Universal-Photon-Network-Controller/NewFrame.cpp
#include "NewFrame.h" #include <wx/intl.h> #include <wx/tokenzr.h> #include <wx/file.h> #include <wx/process.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/fileconf.h> #include <wx/dir.h> #include <wx/filefn.h> #include <wx/process.h> #include <wx/artprov.h> #include <wx/arrstr.h> #ifndef __WINDOWS__ #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #endif #include <stdlib.h> #include <exception> #include "MyThread.h" #include "ping.h" #include "settings.h" #include "SettingsDialog.h" #define RECV_BUFFER_LENGTH 1290 wxDatagramSocket *sock; wxIPV4address *addrPeer; uint8_t receivedBuf[RECV_BUFFER_LENGTH]; wxUint32 numRead = -1; bool isRunning = false; DisplayProcess* m_running; DEFINE_EVENT_TYPE(wxEVT_READTHREAD) MyThread::MyThread(wxEvtHandler* pParent) : wxThread(wxTHREAD_DETACHED), m_pParent(pParent) { //pass parameters into the thread //addrLocal1 //m_param = param; //sock.SetRefData(s); } void* MyThread::Entry() { try { wxCommandEvent evt(wxEVT_READTHREAD, GetId()); //can be used to set some identifier for the data memset(&receivedBuf[0], 0, sizeof(receivedBuf)); isRunning = true; //if (sock->IsConnected()) //{ if (sock->IsOk()) { sock->SetTimeout((long)(replyTimeout / 1000)+1); sock->RecvFrom(*addrPeer, receivedBuf, RECV_BUFFER_LENGTH); numRead = sock->LastCount(); } //} evt.SetInt(0); isRunning = false; //whatever data your thread calculated, to be returned to GUI //evt.SetClientData((void*)temp); wxPostEvent(m_pParent, evt); return 0; } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); isRunning = true; return 0; } } MyThread *sockThread; class GcodeCommandClass { private: wxString cmd; wxString params; public: GcodeCommandClass(wxString Command = "", wxString Parameters = "") { cmd = Command; params = Parameters; } wxString getCommand() { return cmd; } wxString getParameter() { return params; } void setCommand(wxString Command) { cmd = Command; } void setParameter(wxString Parameters) { params = Parameters; } wxString getGcodeCmd(wxString Delimater = " ") { return cmd + Delimater + params; } bool isCmd(wxString Command) { if (cmd.CmpNoCase(Command) == 0) return true; return false; } }; GcodeCommandClass gcodeCmd; bool DisplayProcess::HasInput() // The following methods are adapted from the exec sample. This one manages the stream redirection { m_parent->isPingRunning=true; char c; bool hasInput = false; // The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang // Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString while (IsInputAvailable()) // If there's std input { wxMemoryBuffer buf; do { c = GetInputStream()->GetC(); // Get a char from the input if (GetInputStream()->Eof()) break; // Check we've not just overrun buf.AppendByte(c); if (c==wxT('\n')) break; // If \n, break to print the line } while (IsInputAvailable()); // Unless \n, loop to get another char wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8 m_parent->processInput(line); // Either there's a full line in 'line', or we've run out of input. Either way, print it hasInput = true; } while (IsErrorAvailable()) { wxMemoryBuffer buf; do { c = GetErrorStream()->GetC(); if (GetErrorStream()->Eof()) break; buf.AppendByte(c); if (c==wxT('\n')) break; } while (IsErrorAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); m_parent->processInput(line); hasInput = true; } return hasInput; } void DisplayProcess::OnTerminate(int pid, int status) // When the subprocess has finished, show the rest of the output, then an exit message { while (HasInput()); wxString exitmessage; if (!status) exitmessage = _("Success\n"); else exitmessage = _("Process failed\n"); m_parent->exitstatus = status; // Tell the dlg what the exit status was, in case caller is interested m_parent->isPingRunning=false; m_parent->ProcessPollTimer.Stop(); m_running = NULL; m_parent->getPrintStatus(); delete this; } // -------------------------------------------------------------------------- // resources // -------------------------------------------------------------------------- // the application icon //#ifndef wxHAS_IMAGES_IN_RESOURCES //#include "../sample.xpm" //#endif //(*IdInit(NewFrame) const long NewFrame::ID_STATICBOX1 = wxNewId(); const long NewFrame::ID_STATICTEXT1 = wxNewId(); const long NewFrame::ID_BUTTON1 = wxNewId(); const long NewFrame::ID_STATICTEXT2 = wxNewId(); const long NewFrame::ID_STATICBOX2 = wxNewId(); const long NewFrame::ID_BUTTON2 = wxNewId(); const long NewFrame::ID_BUTTON3 = wxNewId(); const long NewFrame::ID_BUTTON4 = wxNewId(); const long NewFrame::ID_GAUGE1 = wxNewId(); const long NewFrame::ID_STATICTEXT3 = wxNewId(); const long NewFrame::ID_STATICBOX3 = wxNewId(); const long NewFrame::ID_BUTTON5 = wxNewId(); const long NewFrame::ID_BUTTON6 = wxNewId(); const long NewFrame::ID_BUTTON7 = wxNewId(); const long NewFrame::ID_BUTTON8 = wxNewId(); const long NewFrame::ID_GAUGE2 = wxNewId(); const long NewFrame::ID_LISTCTRL1 = wxNewId(); const long NewFrame::ID_BUTTON9 = wxNewId(); const long NewFrame::ID_BITMAPBUTTON1 = wxNewId(); const long NewFrame::ID_COMBOBOX1 = wxNewId(); const long NewFrame::ID_PANEL1 = wxNewId(); const long NewFrame::ID_TIMER1 = wxNewId(); const long NewFrame::ID_STATUSBAR1 = wxNewId(); const long NewFrame::ID_TIMER2 = wxNewId(); const long NewFrame::ID_TIMER3 = wxNewId(); //*) // -------------------------------------------------------------------------- // constants // -------------------------------------------------------------------------- // IDs for the controls and the menu commands // -------------------------------------------------------------------------- // event tables and other macros for wxWidgets // -------------------------------------------------------------------------- wxBEGIN_EVENT_TABLE(NewFrame, wxFrame) //(*EventTable(NewFrame) //*) EVT_COMMAND(wxID_ANY, wxEVT_READTHREAD, NewFrame::OnMyThread) wxEND_EVENT_TABLE() wxIMPLEMENT_APP(MyApp); // ========================================================================== // implementation // ========================================================================== // -------------------------------------------------------------------------- // the application class // -------------------------------------------------------------------------- bool MyApp::OnInit() { if (!wxApp::OnInit()) return false; // Create the main application window NewFrame *frame = new NewFrame((wxFrame *)NULL, wxID_ANY, _("Photon Network Controller"), wxDefaultPosition, wxSize(300, 200)); #if defined(__WINDOWS__) frame->SetIcon(wxICON(aaaa)); #elif defined(__WXGTK__) char path[PATH_MAX ]; char dest[PATH_MAX]; memset(dest,0,sizeof(dest)); pid_t pid = getpid(); sprintf(path, "/proc/%d/exe", pid); ssize_t PathLen = readlink( path, dest, PATH_MAX ); if(PathLen!=-1) frame->SetIcon(wxIcon(wxString::Format(wxT("%s.xpm"), dest))); #endif // defined // Show it frame->Show(true); // success return true; } // -------------------------------------------------------------------------- // main frame // -------------------------------------------------------------------------- // frame constructor NewFrame::NewFrame(wxFrame* parent, wxWindowID id, wxString title, const wxPoint& pos, const wxSize& size) { // HICON hIcon; // hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(2)); // SetClassLong(hWnd, GCL_HICON, (LONG) hIcon); // The new icon // PostMessage (hWnd, WM_SETICON, ICON_BIG, (LPARAM) hIcon); //(*Initialize(NewFrame) Create(parent, wxID_ANY, _("Photon Network Controller"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxMINIMIZE_BOX, _T("wxID_ANY")); SetClientSize(wxSize(334,491)); Panel1 = new wxPanel(this, ID_PANEL1, wxPoint(224,320), wxSize(334,488), wxTAB_TRAVERSAL, _T("ID_PANEL1")); StaticBox1 = new wxStaticBox(Panel1, ID_STATICBOX1, _("Connection Settings"), wxPoint(8,8), wxSize(320,80), 0, _T("ID_STATICBOX1")); StaticText1 = new wxStaticText(Panel1, ID_STATICTEXT1, _("IP Address"), wxPoint(16,28), wxDefaultSize, 0, _T("ID_STATICTEXT1")); btnConnect = new wxButton(Panel1, ID_BUTTON1, _("Connect"), wxPoint(235,54), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON1")); lblStatus = new wxStaticText(Panel1, ID_STATICTEXT2, _("Not Connected"), wxPoint(16,60), wxDefaultSize, 0, _T("ID_STATICTEXT2")); StaticBox2 = new wxStaticBox(Panel1, ID_STATICBOX2, _("Print Status"), wxPoint(8,96), wxSize(320,112), 0, _T("ID_STATICBOX2")); btnStart = new wxButton(Panel1, ID_BUTTON2, _("Start"), wxPoint(16,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON2")); btnPause = new wxButton(Panel1, ID_BUTTON3, _("Pause"), wxPoint(127,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON3")); btnStop = new wxButton(Panel1, ID_BUTTON4, _("Stop"), wxPoint(235,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON4")); PrintProgress = new wxGauge(Panel1, ID_GAUGE1, 1000, wxPoint(16,170), wxSize(304,24), 0, wxDefaultValidator, _T("ID_GAUGE1")); lblPercentDone = new wxStaticText(Panel1, ID_STATICTEXT3, _("Percent Done"), wxPoint(16,152), wxDefaultSize, 0, _T("ID_STATICTEXT3")); StaticBox3 = new wxStaticBox(Panel1, ID_STATICBOX3, _("Files"), wxPoint(8,216), wxSize(320,251), 0, _T("ID_STATICBOX3")); btnDelete = new wxButton(Panel1, ID_BUTTON5, _("Delete"), wxPoint(16,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON5")); btnRefresh = new wxButton(Panel1, ID_BUTTON6, _("Refresh"), wxPoint(125,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON6")); btnUpload = new wxButton(Panel1, ID_BUTTON7, _("Upload"), wxPoint(235,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON7")); btnDownload = new wxButton(Panel1, ID_BUTTON8, _("Download"), wxPoint(235,432), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON8")); progressFile = new wxGauge(Panel1, ID_GAUGE2, 100, wxPoint(16,433), wxSize(212,24), 0, wxDefaultValidator, _T("ID_GAUGE2")); ListCtrl1 = new wxListCtrl(Panel1, ID_LISTCTRL1, wxPoint(16,232), wxSize(304,152), wxLC_REPORT|wxLC_SINGLE_SEL|wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_LISTCTRL1")); btnSettings = new wxButton(Panel1, ID_BUTTON9, _("Settings"), wxPoint(127,54), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON9")); btnSearchPrinter = new wxBitmapButton(Panel1, ID_BITMAPBUTTON1, wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FIND")),wxART_BUTTON), wxPoint(296,23), wxSize(25,25), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_BITMAPBUTTON1")); btnSearchPrinter->SetMinSize(wxSize(25,25)); btnSearchPrinter->SetToolTip(_("Search for printer")); comboIP = new wxComboBox(Panel1, ID_COMBOBOX1, wxEmptyString, wxPoint(127,24), wxSize(160,26), 0, 0, 0, wxDefaultValidator, _T("ID_COMBOBOX1")); PollTimer.SetOwner(this, ID_TIMER1); StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1")); int __wxStatusBarWidths_1[1] = { -10 }; int __wxStatusBarStyles_1[1] = { wxSB_NORMAL }; StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1); StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1); SetStatusBar(StatusBar1); WatchDogTimer.SetOwner(this, ID_TIMER2); ProcessPollTimer.SetOwner(this, ID_TIMER3); Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnConnectClick); Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnStartClick); Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnPauseClick); Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnStopClick); Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnDeleteClick); Connect(ID_BUTTON6,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnRefreshClick); Connect(ID_BUTTON7,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnUploadClick); Connect(ID_BUTTON8,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnDownloadClick); Connect(ID_BUTTON9,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnSettingsClick); Connect(ID_BITMAPBUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnSearchPrinterClick); Connect(ID_TIMER1,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnPollTimerTrigger); Connect(ID_TIMER2,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnWatchDogTimerTrigger); Connect(ID_TIMER3,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnProcessPollTimerTrigger); //*) //#if defined(__WXGTK__) //SetClientSize(wxSize(334, 470)); //#else SetClientSize(wxSize(334,470)); #ifdef __WINDOWS__ comboIP->SetPosition(wxPoint(127, 24)); #else comboIP->SetPosition(wxPoint(127, 23)); #endif setStatusMessages(_("Not Connected"), "", ""); readSettings(); } wxArrayString GetNetworkAddresses() { wxArrayString array; #ifndef __WINDOWS__ // host name is a valid entry array.Add(wxGetFullHostName()); // now get all the IP addresses bool result = false; struct hostent* currentHost = NULL; char hostName[_POSIX_HOST_NAME_MAX]; int hostResult = gethostname(hostName, sizeof (hostName) - 1); // null terminate hostName[sizeof(hostName) / sizeof(char) - 1] = '\0'; if (hostResult == 0) { currentHost = gethostbyname(hostName); if (NULL != currentHost) { result = true; } } if (result) { for (int i = 0 ; currentHost->h_addr_list[i] != NULL ; ++i) { char *inoutString = inet_ntoa(*(struct in_addr*)(currentHost->h_addr_list[i])); // add the IP address array.Add(wxString((char*) &inoutString[0], wxConvLocal)); } } #else // win32 int i = 0; WSAData wsaData; struct hostent *phe = NULL; if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { goto end; } char ac[80]; if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) { goto end; } phe = gethostbyname(ac); if (phe == 0) { goto end; } for (i = 0 ; phe->h_addr_list[i] != 0 ; ++i) { struct in_addr addr; memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); char *address = inet_ntoa(addr); // add the IP address array.Add(wxString((char*) &address[0], wxConvLocal)); } end: WSACleanup(); #endif // if all above fail, then fallback to wxWidgets //if (array.GetCount() == 0) //{ // array.Add(this->GetCurrentIPAddress()); //} return array; } wxString convertSize(size_t size) { const char *SIZES[] = { _("Bytes"), _("KB"), _("MB"), _("GB") }; unsigned int div = 0; size_t rem = 0; while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES)) { rem = (size % 1024); div++; size /= 1024; } double size_d = (float)size + (float)rem / 1024.0; wxString result; unsigned int FileSize = round(size_d); result.Printf("%d %s", FileSize, SIZES[div]); return result; } double getValue(wxString str, wxString prefix, double default_val, wxString ahead) { try { int startIndex = 0; if (ahead != "") { startIndex = str.Find(ahead); if (startIndex != -1) { startIndex += ahead.Length(); } } int index = str.substr(startIndex).Find(prefix); if (index != wxNOT_FOUND) { index += prefix.Length(); int length = 0; //char* chArray = str.ToCharArray(); char* chArray = (char*)malloc(sizeof(char)*(str.Length())); strcpy(chArray, (const char*)str.mb_str(wxConvUTF8)); for (unsigned int i = index; i < str.Length(); i++) { char ch = chArray[i]; if (((ch < '0') || (ch > '9')) && ((ch != '.') && (ch != '-'))) { break; } length++; } if (length > 0) { double value; if (!str.substr(index, length).ToDouble(&value)) return -1; else return value; } return default_val; } return default_val; } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); return default_val; } } wxString getStringValue(wxString str, wxString prefix, wxString default_val, wxString ahead) { try { int startIndex = 0; if (ahead != "") { startIndex = str.Find(ahead); if (startIndex != -1) { startIndex += ahead.Length(); } } int index = str.substr(startIndex).Find(prefix); if (index != wxNOT_FOUND) { index += prefix.Length(); wxString tempstr = str.substr(index); int len = tempstr.Find(' '); if (len == wxNOT_FOUND) return tempstr.Trim(); else return tempstr.substr(0, len).Trim(); } return default_val; } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); return default_val; } } double getValue(wxString str, wxString prefix, double default_val) { return getValue(str, prefix, default_val, ""); } NewFrame::~NewFrame() { //(*Destroy(NewFrame) //*) } void NewFrame::processInput(wxString input) { if (input.IsEmpty()) return; if(pingFailed) //if you have determined that the ping has already failed then just skip rest of the function return; wxString line = input.Trim(); #if defined(__WINDOWS__) if(line.Contains(wxString("timed out")) || line.Contains(wxString("host unreachable"))) { //printf("Ping Failed"); saveLog(LOG_INFORMATION,_("Ping Failed.")); pingFailed=true; } #else if(line.Find(wxString("packet loss"))!=wxNOT_FOUND) { wxString loss = line.BeforeLast('%').AfterLast(','); double value; if(loss.ToDouble(&value)) { if(value!=0) { saveLog(LOG_INFORMATION,_("Ping Failed.")); pingFailed=true; } } } #endif } bool NewFrame::connectToPrinter(wxString hostname) { if(pingPrinter(hostname,(int)pingTimeOut)) { wxIPV4address addrLocal; addrLocal.Hostname(); sock = new wxDatagramSocket(addrLocal); //wxDatagramSocket sock(addrLocal); if (!sock->IsOk()) { wxMessageBox(_("Failed to create UDP socket."), _("Error"), wxICON_ERROR); saveLog(LOG_INFORMATION,_("Failed to create UDP socket.")); return false; } //wxIPV4address addrPeer; //if (addrPeer != NULL) //{ // free(addrPeer); // addrPeer = NULL; //} addrPeer = new wxIPV4address; addrPeer->Hostname(hostname); addrPeer->Service(port); isconnected = false; startList = false; endList = false; fileCount = 0; photonFile = NULL; photonFileName = wxEmptyString; photonFilePath = wxEmptyString; beforeByte = 0; frameNum = 0; numDownloadRetries = 0; downloadStarted = false; downloadFileLength = -1; downloadFileCurrentLength = -1; btnStart->Enable(); PollTimer.Stop(); WatchDogTimer.Stop(); saveLog(LOG_INFORMATION,_("Connected to printer running at IP ")+hostname); return true; } else { wxMessageBox(_("The address cannot be reached."), _("Error"), wxICON_ERROR); saveLog(LOG_INFORMATION,_("The address ") + hostname + _(" cannot be reached.")); return false; } } void NewFrame::disconnectFromPrinter() { try { if (isRunning) { sockThread->Kill(); //free(sockThread); sockThread = NULL; isRunning = false; } if(sock->IsOk()) sock->Close(); //if (addrPeer != NULL) //{ // free(addrPeer); // addrPeer = NULL; //} isconnected = false; startList = false; endList = false; fileCount = 0; photonFile = NULL; photonFileName = wxEmptyString; photonFilePath = wxEmptyString; beforeByte = 0; frameNum = 0; numDownloadRetries = 0; downloadStarted = false; downloadFileLength = -1; downloadFileCurrentLength = -1; PollTimer.Stop(); WatchDogTimer.Stop(); setStatusMessages(_("Not Connected"), "", ""); btnConnect->SetLabel(_("Connect")); lblStatus->SetLabel(_("Not Connected")); lblPercentDone->SetLabel(_("Percent Done")); clearListControl(); progressFile->SetValue(0); PrintProgress->SetValue(0); btnStart->Disable(); saveLog(LOG_INFORMATION,_("Printer Disconnected")); } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } } void NewFrame::setStatusMessages(wxString message1, wxString message2, wxString message3) { if (message1 != "prev") msges[0] = message1; if (message2 != "prev") msges[1] = message2; if (message3 != "prev") msges[2] = message3; SetStatusText(msges[0] + " " + msges[1] + " " + msges[2], 0); saveLog(LOG_INFORMATION,msges[0] + " " + msges[1] + " " + msges[2]); } void NewFrame::sendCmdToPrinter(wxString cmd) { try { memset(&receivedBuf[0], 0, sizeof(receivedBuf)); wxUint32 sendSize = cmd.Length(); char* tempBuffer = (char*)malloc(sizeof(char)*(2 + sendSize)); strcpy(tempBuffer, (const char*)cmd.mb_str(wxConvUTF8)); // buf will now contain the command tempBuffer[sendSize] = '\0'; tempBuffer[sendSize + 1] = '\0'; saveLog(LOG_INFORMATION,wxString::Format(wxT("Send to printer \"%s\""), tempBuffer)); WatchDogTimer.Start(replyTimeout, true); if (sock->SendTo(*addrPeer, tempBuffer, sendSize).LastCount() != sendSize) { wxMessageBox(_("Failed to send data"), _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,_("Failed to send data")); return; } free(tempBuffer); } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); wxMessageBox(_("Failed to send data"), _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,_("Failed to send data")); } } void NewFrame::sendCmdToPrinter(uint8_t* cmd, unsigned int sendSize) { try { memset(&receivedBuf[0], 0, sizeof(receivedBuf)); WatchDogTimer.Start(replyTimeout, true); if (sock->SendTo(*addrPeer, cmd, sendSize).LastCount() != sendSize) { wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,_("Failed to send data")); return; } } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,_("Failed to send data")); } } void NewFrame::broadcastOverUDP(wxString broadCastHost,uint8_t* cmd, unsigned int sendSize) { try { wxIPV4address m_LocalAddress; m_LocalAddress.AnyAddress(); m_LocalAddress.Service(3001); // port on which we listen // Create the socket m_Listen_Socket = new wxDatagramSocket(m_LocalAddress, wxSOCKET_REUSEADDR); if (m_Listen_Socket->Error()) { wxLogError(_("Could not open Datagram Socket")); saveLog(LOG_ERROR,_("Could not open Datagram Socket")); return; } else { /////////////////////////////////////////////////////////////////////////// // To send to a broadcast address, you must enable SO_BROADCAST socket // option, in plain C this is: // int enabled = 1; // setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &enabled, sizeof(enabled)); // where sockfd is the socket descriptor (See http://linux.die.net/man/2/setsockopt) // See also boxcarmiba Wed Aug 02, 2006 // at https://forums.wxwidgets.org/viewtopic.php?t=9410 static int enabled = 1; m_Listen_Socket->SetOption(SOL_SOCKET, SO_BROADCAST, &enabled, sizeof(enabled)); /////////////////////////////////////////////////////////////////////////// // Specify a broadcast IP, in this case "Limited Broadcast" on the local network: free(m_BroadCastAddress); m_BroadCastAddress = NULL; m_BroadCastAddress = new wxIPV4address; m_BroadCastAddress->Hostname(broadCastHost); m_BroadCastAddress->Service(3000); // Use same socket created for listening for sending: m_Listen_Socket->SendTo(*m_BroadCastAddress, cmd, sendSize); if (m_Listen_Socket->Error()) { //wxLogMessage(_T("SendTo Error: %d"), m_Listen_Socket->LastError()); saveLog(LOG_ERROR,wxString::Format(wxT("SendTo Error: %d"), m_Listen_Socket->LastError())); } saveLog(LOG_INFORMATION,wxString::Format(wxT("Send broadcast message to %s"), broadCastHost)); } } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,_("Failed to send data")); } } wxArrayString NewFrame::getBlockingBroadcastReply(wxString broadcastHostname) { wxArrayString ipArray; try { wxIPV4address Peer; wxString host; unsigned int itemIndex = 0; wxString beforeString = comboIP->GetValue(); do { memset(&receivedBuf[0], 0, sizeof(receivedBuf)); m_Listen_Socket->SetTimeout(2); m_Listen_Socket->Read(&receivedBuf, sizeof(receivedBuf)); m_Listen_Socket->GetPeer(Peer); host = Peer.IPAddress(); if (host != "255.255.255.255" && host!= broadcastHostname) { wxString name = getStringValue(receivedBuf, "NAME:", "00_NO_NAME_00", ""); if (name != "00_NO_NAME_00") { ipArray.Add(host); saveLog(LOG_INFORMATION,wxString::Format(wxT("Received reply from IP %s"), host)); //comboIP->Insert(host, itemIndex); //comboIP->SetValue(host); itemIndex++; } } } while (m_Listen_Socket->IsData()); m_Listen_Socket->Close(); free(m_Listen_Socket); m_Listen_Socket = NULL; } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } return ipArray; } void NewFrame::getAsyncReply() { try { //free(sockThread); //sockThread = NULL; sockThread = new MyThread(this); sockThread->Create(); sockThread->Run(); } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } } void NewFrame::getBlockingReply() { try { memset(&receivedBuf[0], 0, sizeof(receivedBuf)); sock->SetTimeout((long)(replyTimeout / 1000)); numRead = sock->RecvFrom(*addrPeer, receivedBuf, sizeof(receivedBuf)).LastCount(); saveLog(LOG_INFORMATION,_("Received data from Printer. Blocking receive")); WatchDogTimer.Stop(); } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } } void NewFrame::clearListControl() { ListCtrl1->ClearAll(); ListCtrl1->DeleteAllColumns(); //The two lines below is only needed for GCC under windows. It works fine without this in all other OSes ListCtrl1->~wxListCtrl(); ListCtrl1 = new wxListCtrl(Panel1, ID_LISTCTRL1, wxPoint(16, 232), wxSize(304, 152), wxLC_REPORT | wxLC_SINGLE_SEL | wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_LISTCTRL1")); //Under Windows GCC the list fails to redraw after deleting items in it. The above workaround is the easiest way to fix that issue //comment them out for better performance under other platforms } void NewFrame::handleResponse() { WatchDogTimer.Stop(); saveLog(LOG_INFORMATION,_("Received data from Printer. Async receive")); if (gcodeCmd.isCmd("M4002")) //Gcode to read version info from printer { wxString tempStr = receivedBuf; if (tempStr.Length() <= 0) return; lblStatus->SetLabel(_("Connected")); btnConnect->SetLabel(_("Disconnect")); isconnected = true; setStatusMessages(tempStr.substr(3).Trim(), "", ""); isConnected = true; while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); updatefileList(); PollTimer.Start(300); //Get printer status if possible saveLog(LOG_INFORMATION,_("Received version information from printer. Reply for M4002")); } else if (gcodeCmd.isCmd("M20")) //Gcode to read the filelist { wxString receivedText = receivedBuf; receivedText.Trim(); if (!receivedText.Contains("Begin file list")) { if (!startList) //if the file listing has not started then read again { getAsyncReply(); } else { if (!receivedText.Contains("End file list")) //File listing has not ended { wxStringTokenizer temp(receivedText, " "); wxString temp1 = ""; while (temp.HasMoreTokens()) { wxString token = temp.GetNextToken(); temp1 = temp1 + token + " "; if (temp.CountTokens() == 1) break; } wxString token = temp.GetNextToken(); long value; if (token.ToLong(&value)) { if (value > 0) { ListCtrl1->InsertItem(fileCount, wxString((char)(fileCount + 49))); ListCtrl1->SetItem(fileCount, 1, temp1); ListCtrl1->SetItem(fileCount, 2, convertSize(value)); fileCount++; } } else { ListCtrl1->InsertItem(fileCount, wxString((char)(fileCount + 49))); ListCtrl1->SetItem(fileCount, 1, temp1); ListCtrl1->SetItem(fileCount, 2, _("Unknown")); fileCount++; } getAsyncReply(); } else { startList = false; //File list ended don't read any more lines endList = true; saveLog(LOG_INFORMATION,_("Received File list from printer. Reply for M20")); } } } else { startList = true; //File Listing just Started endList = false; clearListControl(); ListCtrl1->AppendColumn(_("Num"), wxLIST_FORMAT_LEFT, 50); ListCtrl1->AppendColumn(_("File Name"), wxLIST_FORMAT_LEFT, 175); ListCtrl1->AppendColumn(_("Size"), wxLIST_FORMAT_LEFT, 75); fileCount = 0; getAsyncReply(); } if (endList) //Received end of file list in the last command so now clean up rest of the receive buffer { getBlockingReply(); } //else if (endList>=1) //{ //get rid of extra messages from the sockets buffer as it will confuse the program //} } else if (gcodeCmd.isCmd("M6030")) //Gcode to Start Printing { ispaused = false; isPrinting = true; btnPause->Enable(); btnStart->Disable(); btnStop->Enable(); gcodeCmd.setCommand("M27"); gcodeCmd.setParameter(""); beforeByte = 0; frameNum = 0; PollTimer.Start(pollingInterval); setStatusMessages("prev", _("Printing"), ""); PrintProgress->SetValue(0); saveLog(LOG_INFORMATION,_("Start printing. Reply to M6030")); //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); } else if (gcodeCmd.isCmd("M6032")) //Gcode to Download File { if (!downloadStarted) //If the download has not started do the following check { wxString receivedText = receivedBuf; receivedText.Trim(); wxString errorIfAny = isError(receivedText); if (errorIfAny.Length() <= 0) //No error so we can proceed to the actual file download { downloadFileLength = getValue(receivedText, "L:", -1); if (downloadFileLength>0) //it is a valid file with a positive file length { downloadStarted = true; //Se this flag that way you know the download has started and we need to process the incoming data. } else { gcodeCmd.setCommand("M22"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } } else { if (numDownloadRetries == 0) //retry only once by sending a M22 { numDownloadRetries++; gcodeCmd.setCommand("M22"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } else //It errored out after one retry just give up and show the error message { wxMessageBox(errorIfAny, _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,errorIfAny); } } } if (downloadStarted) //Download has started. Issue the M3000 command to start the download process { saveLog(LOG_INFORMATION,_("Start downloading file.")); while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); if (downloadFileCurrentLength<downloadFileLength) //Should be but still check if that's the case or not { progressFile->SetValue(0); downloadFileCurrentLength = 0; gcodeCmd.setCommand("M3000"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } else { gcodeCmd.setCommand("M22"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } } //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); } else if (gcodeCmd.isCmd("M3000")) //Gcode to start downlading data from the printer or request resend of corrupted data { if (downloadFileCurrentLength < downloadFileLength) //there is still more data left to be read { if ((numRead >= 6) && ((uint8_t)(receivedBuf[numRead - 1]) == 0x83)) { unsigned int maxValue = 0; maxValue = (maxValue << 8) + receivedBuf[numRead - 3]; maxValue = (maxValue << 8) + receivedBuf[numRead - 4]; maxValue = (maxValue << 8) + receivedBuf[numRead - 5]; maxValue = (maxValue << 8) + receivedBuf[numRead - 6]; if (maxValue == downloadFileCurrentLength) { uint8_t checkSum = 0; // This is the checksum for (unsigned int i = 0; i < (numRead - 2); i++) checkSum = (uint8_t)(checkSum ^ receivedBuf[i]); if (checkSum == receivedBuf[numRead - 2]) // if the calculated checksum is the same as the one we received from the printer { //Write this data to file photonFile->Write(receivedBuf, numRead - 6); downloadFileCurrentLength += numRead - 6; progressFile->SetValue((int)((100 * downloadFileCurrentLength) / downloadFileLength)); progressFile->Update(); gcodeCmd.setCommand("M3000"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } else //request resend { gcodeCmd.setCommand("M3001"); gcodeCmd.setParameter(wxString('I') + wxString::Format(wxT("%lld"), downloadFileCurrentLength)); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } } else //request resend { gcodeCmd.setCommand("M3001"); gcodeCmd.setParameter(wxString('I') + wxString::Format(wxT("%lld"), downloadFileCurrentLength)); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } } else { downloadStarted = false; numDownloadRetries++; gcodeCmd.setCommand("M22"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } } else { numDownloadRetries = 0; //just to ensure that it closes the file and updates the flag; gcodeCmd.setCommand("M22"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); } else if (gcodeCmd.isCmd("M22")) //Gcode to Stop downloading file { if (numDownloadRetries == 1) //Request file re download if and only if it's retry number 1. In case of no retry i.e. 0 finish the process and in case of more than one i.e. >1 just give up and show an error message { gcodeCmd.setCommand("M6032"); // The gcode parameter should be same as before which is the file name sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } else { photonFile->Flush(); photonFile->Close(); if (downloadFileCurrentLength >= downloadFileLength) { wxMessageBox(_("Download finished."), _("Information"), wxOK | wxICON_INFORMATION | wxCENTER); saveLog(LOG_INFORMATION,_("Download finished.")); } else { wxMessageBox(_("Failed to download file. Please retry"), _("Warning"), wxOK | wxICON_EXCLAMATION | wxCENTER); saveLog(LOG_WARNING,_("Failed to download file. Please retry")); } downloadStarted = false; downloadFileLength = -1; downloadFileCurrentLength = -1; } //do Nothing //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); } else if (gcodeCmd.isCmd("M25")) //Gcode to Pause Printing { ispaused = true; isPrinting = false; btnPause->SetLabel(_("Resume")); btnPause->Update(); PollTimer.Stop(); setStatusMessages("prev", _("Paused"), ""); saveLog(LOG_INFORMATION,_("Pause printing. Reply to M25")); //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); } else if (gcodeCmd.isCmd("M27")) //Gcode for getting print status { wxString receivedText = receivedBuf; while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); wxString errorIfAny = isError(receivedText); if (errorIfAny.Length() <= 0) { saveLog(LOG_INFORMATION,_("Get status message from printer. Reply to M27")); PollTimer.Start(pollingInterval); wxStringTokenizer temp(receivedText.Trim(), " "); wxString token; while (temp.HasMoreTokens()) //get to the last token that is the received message. it should have the format bytes_printed/total_bytes token = temp.GetNextToken(); wxStringTokenizer temp1(token.Trim(), "/"); unsigned long bytesPrinted = 0; unsigned long totalBytes = 0; temp1.GetNextToken().ToCULong(&bytesPrinted); temp1.GetNextToken().ToCULong(&totalBytes); if (beforeByte<bytesPrinted) { frameNum++; beforeByte = bytesPrinted; } //wxMessageBox(token + wxString::Format(wxT(" -- %ld/%ld"), bytesPrinted,totalBytes),"Information",wxOK|wxICON_INFORMATION|wxCENTER); double percentDone = ((bytesPrinted * 1000) / totalBytes); if (percentDone >= 1000) { PollTimer.Stop(); btnStart->Enable(); btnStop->Disable(); btnPause->Disable(); setStatusMessages("prev", _("Print finished"), "prev"); lblPercentDone->SetLabel(wxString(_("Percent Done : 100"))); PrintProgress->SetValue(1000); PrintProgress->Update(); } else { lblPercentDone->SetLabel(wxString(_("Percent Done : ")) + wxString::Format(wxT("%d"), (int)round(percentDone / 10))); PrintProgress->SetValue((int)round(percentDone)); PrintProgress->Update(); setStatusMessages("prev", _("Printing"), "prev"); } } else { PollTimer.Stop(); setStatusMessages("prev", _("Not Printing"), ""); } gcodeCmd.setCommand("M114"); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); //wxMessageBox(wxString::Format(wxT("%s"), receivedText),"Information",wxOK|wxICON_INFORMATION|wxCENTER); } else if (gcodeCmd.isCmd("M24")) //Gcode to resume Printing { ispaused = false; isPrinting = true; btnPause->SetLabel("Pause"); btnPause->Update(); gcodeCmd.setCommand("M27"); gcodeCmd.setParameter(""); PollTimer.Start(pollingInterval); setStatusMessages("prev", _("Printing"), ""); saveLog(LOG_INFORMATION,_("Resume printing. Reply to M24")); } else if (gcodeCmd.isCmd("M114")) //Query Z { wxString receivedText = receivedBuf; double zPosition = getValue(receivedText, "Z:", -1); while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); saveLog(LOG_INFORMATION,_("Query the Z height. Reply to M114")); setStatusMessages("prev", "prev", wxString::Format(wxT(" Z = %.2f mm"), zPosition)); } else if (gcodeCmd.isCmd("M33")) //Stopping a print { wxString receivedText = receivedBuf; while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); wxString errorIfAny = isError(receivedText); if (errorIfAny.Length() <= 0) { gcodeCmd.setCommand("M29"); gcodeCmd.setParameter(""); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } else { wxMessageBox(errorIfAny, _("Error"), wxICON_ERROR); saveLog(LOG_ERROR,errorIfAny); } } else if (gcodeCmd.isCmd("M29")) //Stopping a print or a file upload { //gcodeCmd.setCommand("G90, G0"); //gcodeCmd.setParameter("Z 150 F300"); //sendCmdToPrinter(gcodeCmd.getGcodeCmd()); wxString receivedText = receivedBuf; if (receivedText.Length()>8) //Don't show the OK N:6 message that you get on stopping of a print { wxMessageBox(wxString::Format(wxT("%s"), receivedText), _("Information"), wxOK | wxICON_INFORMATION | wxCENTER); saveLog(LOG_INFORMATION,wxString::Format(wxT("%s"), receivedText)); } else { setStatusMessages("prev", _("Stopped"), ""); btnPause->Disable(); btnStart->Enable(); btnStop->Enable(); ispaused = false; isPrinting = false; PollTimer.Stop(); saveLog(LOG_INFORMATION,_("Stop printing. Reply to M29")); } while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); updatefileList(); } else if (gcodeCmd.isCmd("M30")) //Delete a file { //gcodeCmd.setCommand("G90, G0"); //gcodeCmd.setParameter("Z 150 F300"); //sendCmdToPrinter(gcodeCmd.getGcodeCmd()); wxString receivedText = receivedBuf; wxMessageBox(wxString::Format(wxT("%s"), receivedText), _("Information"), wxOK | wxICON_INFORMATION | wxCENTER); saveLog(LOG_INFORMATION,wxString::Format(wxT("%s"), receivedText)); while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program getBlockingReply(); saveLog(LOG_INFORMATION,_("Delete a File. Reply to M30")); updatefileList(); } else if (gcodeCmd.isCmd("M28")) //Uploading a File { wxString receivedText = receivedBuf; //wxMessageBox(wxString::Format(wxT("%s"), receivedText)); saveLog(LOG_INFORMATION,_("Upload a File. Reply to M28")); int chunckSize = 0x500; uint8_t *buffer = (uint8_t*)malloc((chunckSize + 6) * sizeof(uint8_t)); ssize_t index = 0; if (receivedText.Find("resend") != wxNOT_FOUND) { long resend_index = getValue(receivedText, "resend ", -1); photonFile->Seek(resend_index, wxFromStart); } if (photonFile->Tell() < photonFile->Length()) { unsigned int position = photonFile->Tell(); index = photonFile->Read(buffer, chunckSize); if (index != wxInvalidOffset) { uint8_t num8 = 0; buffer[index] = (uint8_t)position & 0xFF; buffer[index + 1] = (uint8_t)((position >> 8) & 0xFF); buffer[index + 2] = (uint8_t)((position >> 16) & 0xFF); buffer[index + 3] = (uint8_t)((position >> 24) & 0xFF); for (int i = 0; i < (index + 4); i++) { num8 = (uint8_t)(num8 ^ buffer[i]); } buffer[index + 4] = num8; buffer[index + 5] = 0x83; sendCmdToPrinter(buffer, index + 6); free(buffer); progressFile->SetValue((int)((100 * photonFile->Tell()) / photonFile->Length())); getAsyncReply(); } } else { photonFile->Close(); gcodeCmd.setCommand("M29"); gcodeCmd.setParameter(""); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } } } wxString NewFrame::isError(wxString response) { if (response.Trim().substr(0, 6).Contains("Error:")) { wxStringTokenizer temp(response.Trim(), ":"); wxString token; while (temp.HasMoreTokens()) //get to the last token that is the error message token = temp.GetNextToken(); return token; } else return ""; } void NewFrame::getVersion() { gcodeCmd.setCommand("M4002"); //receiver.Send(Encoding.ASCII.GetBytes(gcodeCmd), gcodeCmd.Length); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); //wxString s = getBlockingReply(); //return s.Trim().substr(3); } void NewFrame::updatefileList() { gcodeCmd.setCommand("M20"); fileCount = 0; sendCmdToPrinter(gcodeCmd.getCommand()); endList = false; startList = false; getAsyncReply(); } void NewFrame:: saveSettings() { wxString ini_Directory = wxStandardPaths::Get().GetUserConfigDir() + wxFileName::GetPathSeparator() + wxString("PhotonTool"); if(!wxDir::Exists(ini_Directory)) //create directory if it doesn't exist wxDir::Make(ini_Directory); wxString ini_filename = wxStandardPaths::Get().GetUserConfigDir() + wxFileName::GetPathSeparator() + wxString("PhotonTool")+ wxFileName::GetPathSeparator() + wxString(_("Settings.INI")); wxFileConfig *config = new wxFileConfig( "", "", ini_filename); wxString ipList=wxEmptyString; for (unsigned int i = 0; i < comboIP->GetCount();i++) { if (comboIP->GetString(i).Trim() != ipAddress.Trim()) { if(StaticIPList.Index(comboIP->GetString(i).Trim())==wxNOT_FOUND) ipList = wxString(',') + comboIP->GetString(i).Trim() +ipList; } } ipList = ipAddress + ipList; config->Write( wxT("IP"), ipAddress ); config->Write(wxT("IPList"), ipList); ipList=wxEmptyString; for (unsigned int i = 0; i < StaticIPList.GetCount();i++) { if(i==0) ipList = StaticIPList[i].Trim(); else ipList = ipList + wxString(',') + StaticIPList[i].Trim(); } config->Write(wxT("StaticIPList"), ipList); config->Write(wxT("pingTimeOut"),pingTimeOut); config->Write(wxT("replyTimeout"),replyTimeout); config->Write(wxT("port"),port); config->Write(wxT("pollingInterval"),pollingInterval); saveLog(LOG_INFORMATION,_("Save All settings.")); if(enableLogging) config->Write(wxT("enableLogging"),1); else config->Write(wxT("enableLogging"),0); config->Flush(); delete config; } void NewFrame:: readSettings() { wxString ini_filename = wxStandardPaths::Get().GetUserConfigDir() + wxFileName::GetPathSeparator() + wxString("PhotonTool")+ wxFileName::GetPathSeparator() + wxString(_("Settings.INI")); if(wxFileExists(ini_filename)) { wxFileConfig *config = new wxFileConfig( "", "", ini_filename); config->Read(wxT("IP"),&ipAddress,"192.168.1.222"); wxString ipList = wxEmptyString; config->Read(wxT("IPList"), &ipList, "192.168.1.222"); config->Read(wxT("pingTimeOut"),&pingTimeOut,100); config->Read(wxT("replyTimeout"),&replyTimeout,2000); config->Read(wxT("port"),&port,3000); config->Read(wxT("pollingInterval"),&pollingInterval,1000); double tempRead=0; config->Read(wxT("enableLogging"),&tempRead,1); if(tempRead==1) enableLogging=true; else enableLogging=false; comboIP->Clear(); int ipIndex = 0; wxStringTokenizer temp(ipList, ","); while (temp.HasMoreTokens()) { wxString token = temp.GetNextToken(); if(IsIPAddress(token)) { comboIP->Insert(token, ipIndex); ipIndex++; } } ipList = wxEmptyString; config->Read(wxT("StaticIPList"), &ipList, wxEmptyString); if(ipList.Length()>4) { StaticIPList.clear(); wxStringTokenizer temp(ipList, ","); while (temp.HasMoreTokens()) { wxString token = temp.GetNextToken(); if(IsIPAddress(token)) { StaticIPList.Add(token); comboIP->Append(token); } } } comboIP->SetValue(ipAddress); delete config; saveLog(LOG_INFORMATION,_("Read All settings.")); } else comboIP->SetValue("192.168.1.222"); } void NewFrame::OnbtnConnectClick(wxCommandEvent& event) { //wxMessageBox(_("Connect to Printer\n"), _("About Connect"), wxOK | wxICON_INFORMATION, this); if(!IsIPAddress(comboIP->GetValue())) { wxMessageBox(_("Not a valid IP address"), _("Error"), wxOK | wxICON_ERROR | wxCENTER); saveLog(LOG_ERROR,_("Not a valid IP address")); return; } if (!isconnected) //Connect to the printer if it not connected { if(connectToPrinter(comboIP->GetValue())) { getVersion(); ipAddress = addrPeer->IPAddress(); saveSettings(); //PollTimer.Start(300); //query the print status after 300ms. for some reason it doesn't work if you query it right after connection. } } else { disconnectFromPrinter(); } //wxLogMessage("received %s",s); //sendCmdToPrinter("M27"); //getAsyncReply(); } void NewFrame::OnbtnStartClick(wxCommandEvent& event) { //wxMessageBox(_("Start a print\n"), _("About Start"), wxOK | wxICON_INFORMATION, this); long lSelectedItem = ListCtrl1->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); //wxMessageBox(wxString::Format(wxT("Sel = %d"), lSelectedItem)); if (lSelectedItem != wxNOT_FOUND) { //wxMessageBox(ListCtrl1->GetItemText(lSelectedItem,1)); //sprintf(gcodeCmd,"M6030 ':%s'",ListCtrl1->GetItemText(lSelectedItem,1).mb_str().data()); gcodeCmd.setCommand("M6030"); gcodeCmd.setParameter(wxString("\':") + ListCtrl1->GetItemText(lSelectedItem, 1).Trim() + wxString("\'")); //wxMessageBox(wxString::Format(wxT("%s"), gcodeCmd.getGcodeCmd())); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } else { wxMessageBox(_("Please select a file before starting a print."), _("Warning"), wxOK | wxICON_EXCLAMATION | wxCENTER); saveLog(LOG_INFORMATION,_("Please select a file before starting a print.")); } } void NewFrame::OnbtnPauseClick(wxCommandEvent& event) { //wxMessageBox(_("Pause a print\n"), _("About Pause"), wxOK | wxICON_INFORMATION, this); PollTimer.Stop(); if (ispaused) { gcodeCmd.setCommand("M24"); } else { gcodeCmd.setCommand("M25"); } sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } void NewFrame::OnbtnStopClick(wxCommandEvent& event) { //wxMessageBox(_("Stop a print\n"), _("About Stop"), wxOK | wxICON_INFORMATION, this); int answer = wxMessageBox(_("Want to stop the current print?"), _("Confirm"), wxYES_NO | wxICON_QUESTION | wxCENTER, this); if (answer == wxYES) { PollTimer.Stop(); gcodeCmd.setCommand("M33"); gcodeCmd.setParameter("I5"); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } } void NewFrame::OnbtnDeleteClick(wxCommandEvent& event) { //wxMessageBox(_("Delete a file\n"), _("About Delete"), wxOK | wxICON_INFORMATION, this); long lSelectedItem = ListCtrl1->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); //wxMessageBox(wxString::Format(wxT("Sel = %d"), lSelectedItem)); if (lSelectedItem != wxNOT_FOUND) { int answer = wxMessageBox(wxString(_("Are you sure you want to permanently delete ")) + ListCtrl1->GetItemText(lSelectedItem, 1).Trim() + wxString(_('?')), _("Confirm"), wxYES_NO | wxICON_QUESTION | wxCENTER, this); if (answer == wxYES) { gcodeCmd.setCommand("M30"); gcodeCmd.setParameter(ListCtrl1->GetItemText(lSelectedItem, 1).Trim()); //wxMessageBox(wxString::Format(wxT("%s"), gcodeCmd.getGcodeCmd())); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } } else { wxMessageBox(_("Please select a file to delete."), _("Warning"), wxOK | wxICON_EXCLAMATION | wxCENTER); saveLog(LOG_INFORMATION,_("Delete clicked without selecting a file")); } } void NewFrame::AsyncPingPrinter(wxString ipAddress,int Timeout) { #if defined(__WINDOWS__) wxString command = wxString::Format("ping -n 1 -w %d -l 32 ", Timeout) + ipAddress; #else wxString command = wxString::Format("ping -c 1 -W %d -s 32 ", Timeout) + ipAddress; #endif if (command.IsEmpty()) return; DisplayProcess* process = new DisplayProcess(this); // Make a new Process, the sort with built-in redirection long pid = wxExecute(command, wxEXEC_ASYNC | wxEXEC_MAKE_GROUP_LEADER, process); // Try & run the command. pid of 0 means failed if (!pid) { wxLogError(_("Execution of '%s' failed."), command.c_str()); delete process; } else { // Store the pid in case Cancel is pressed if (m_running==NULL) // If it's not null, there's already a running process { isPingRunning=true; process->SetPid(pid); ProcessPollTimer.Start(100); // Tell the timer to create idle events every 1/10th sec m_running = process; // Store the process } // Start the timer to poll for output } } void NewFrame::OnbtnRefreshClick(wxCommandEvent& event) { //wxMessageBox(_("Refresh file list\n"), _("About Refresh"), wxOK | wxICON_INFORMATION, this); updatefileList(); } void NewFrame::OnbtnUploadClick(wxCommandEvent& event) { wxFileDialog *OpenDialog = new wxFileDialog(this, _("Choose a file to upload"), wxEmptyString, wxEmptyString, _("All files (*.*)|*.*"), wxFD_OPEN, wxDefaultPosition);//change the filter to .photon files if (OpenDialog->ShowModal() == wxID_OK) // if the user click "Open" instead of "cancel" { photonFilePath = OpenDialog->GetPath(); photonFileName = OpenDialog->GetFilename(); photonFile = new wxFile(photonFilePath, wxFile::OpenMode::read); gcodeCmd.setCommand("M28"); gcodeCmd.setParameter(photonFileName); progressFile->SetValue(0); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); saveLog(LOG_INFORMATION,wxString::Format("Upload file %s", photonFileName)); //wxMessageBox(CurrentDocPath); } } void NewFrame::OnbtnDownloadClick(wxCommandEvent& event) { long lSelectedItem = ListCtrl1->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (lSelectedItem != wxNOT_FOUND) { wxFileDialog *SaveDialog = new wxFileDialog(this, _("Save downloaded file as . . ."), wxEmptyString, ListCtrl1->GetItemText(lSelectedItem, 1).Trim(), _("All files (*.*)|*.*"), wxFD_SAVE, wxDefaultPosition);//change the filter to .photon files if (SaveDialog->ShowModal() == wxID_OK) // if the user click "Save" instead of "cancel" { downloadStarted = false; downloadFileLength = -1; downloadFileCurrentLength = -1; progressFile->SetValue(0); photonFilePath = SaveDialog->GetPath(); photonFileName = SaveDialog->GetFilename(); photonFile = new wxFile(photonFilePath, wxFile::OpenMode::write); if (photonFile->IsOpened()) //if opening of the file succeded { gcodeCmd.setCommand("M6032"); gcodeCmd.setParameter(wxString('\'') + ListCtrl1->GetItemText(lSelectedItem, 1).Trim() + wxString('\'')); progressFile->SetValue(0); sendCmdToPrinter(gcodeCmd.getGcodeCmd()); getAsyncReply(); } else { wxMessageBox(_("Failed to write file. Make sure you have write access."), _("Error"), wxOK | wxICON_ERROR | wxCENTER); saveLog(LOG_INFORMATION,_("Failed to write file. Make sure you have write access.")); } } } else { wxMessageBox(_("Please select a file to download."), _("Warning"), wxOK | wxICON_EXCLAMATION | wxCENTER); saveLog(LOG_INFORMATION,_("Download clicked without selecting a file.")); } } void NewFrame::OnMyThread(wxCommandEvent& event) { //wxLogMessage("Received %s, %d", receivedBuf, numRead); saveLog(LOG_INFORMATION,_("Async Callback from networking thread.")); handleResponse(); } void NewFrame::getPrintStatus() { if(!pingFailed) //Get status of the printer if it is still connected i.e. the ping didn't fail { gcodeCmd.setCommand("M27"); gcodeCmd.setParameter(""); sendCmdToPrinter(gcodeCmd.getCommand()); getAsyncReply(); } else { PollTimer.Stop(); try { disconnectFromPrinter(); wxMessageBox(_("Lost connection to the printer."), _("Error"), wxOK | wxICON_ERROR | wxCENTER); saveLog(LOG_INFORMATION,_("Lost connection to the printer.")); } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } } } void NewFrame::OnPollTimerTrigger(wxTimerEvent& event) { if(!isPingRunning) //make sure a previous ping is not already running { if(m_running!=NULL) { delete m_running; m_running=NULL; } pingFailed=false; //assume the ping is not going to fail isPingRunning=true; AsyncPingPrinter(addrPeer->IPAddress(),(int)pingTimeOut); } else { saveLog(LOG_WARNING,_("Still running a previous Ping.")); } } void NewFrame::OnWatchDogTimerTrigger(wxTimerEvent& event) { try { if (isRunning) { //sockThread->Kill(); //free(sockThread); //sockThread = NULL; isRunning = false; if(sock->IsOk()) sock->Close(); //if (addrPeer != NULL) //{ // free(addrPeer); // addrPeer = NULL; //} isconnected = false; startList = false; endList = false; fileCount = 0; photonFile = NULL; photonFileName = wxEmptyString; photonFilePath = wxEmptyString; beforeByte = 0; frameNum = 0; numDownloadRetries = 0; downloadStarted = false; downloadFileLength = -1; downloadFileCurrentLength = -1; PollTimer.Stop(); WatchDogTimer.Stop(); setStatusMessages(_("Not Connected"), "", ""); btnConnect->SetLabel(_("Connect")); lblStatus->SetLabel(_("Not Connected")); lblPercentDone->SetLabel(_("Percent Done")); clearListControl(); progressFile->SetValue(0); PrintProgress->SetValue(0); int replyTimeoutSeconds = (int)(replyTimeout/1000); wxMessageBox(_("Failed to receive any response from the printer in ") + wxString::Format(wxT("%d"), replyTimeoutSeconds) + _(" Seconds.\nPlease try re-connecting"), _("Error"), wxOK | wxICON_ERROR | wxCENTER); saveLog(LOG_INFORMATION,_("Failed to receive any response from the printer in ") + wxString::Format(wxT("%d"), replyTimeoutSeconds) + _(" Seconds.\nPlease try re-connecting")); } } catch (std::exception &e) { saveLog(LOG_EXCEPTION,wxString(e.what())); } } void NewFrame::OnbtnSettingsClick(wxCommandEvent& event) { SettingsDialog *dlg = new SettingsDialog(this); dlg->Show(); btnSettings->Disable(); saveLog(LOG_INFORMATION,_("Show Settings Dialog.")); } void NewFrame::OnProcessPollTimerTrigger(wxTimerEvent& WXUNUSED(event)) { wxWakeUpIdle(); } void NewFrame::OnbtnSearchPrinterClick(wxCommandEvent& event) { setStatusMessages("Searching for printers. Please Wait . . .", "", ""); wxArrayString res = GetNetworkAddresses(); wxArrayString broadcastAddresses; wxString boradcastIP = wxEmptyString; for (unsigned i = 0;i < res.Count();i++) { wxString temp = res.Item(i); wxStringTokenizer tempToken(temp, "."); wxString temp1 = ""; unsigned int count = 0; while (tempToken.HasMoreTokens()) { wxString token = tempToken.GetNextToken(); if (count == 0) temp1 = token; else temp1 = temp1 + wxString('.') + token; count++; if (count == 2) { broadcastAddresses.Add(temp1 + wxString(".255.255")); //Create boradcast IPs by replacing the last 16 bits with 255.255 broadcastAddresses.Add(temp1 + wxString(".1.255")); //This seems to work if I want to search from a virtual machine } else if (count == 3) broadcastAddresses.Add(temp1 + wxString(".255")); //Also create boradcast IPs by replacing the last 8 bits with 255 } } wxArrayString destination; // new empty wxArrayString for (unsigned int i = 0; i < broadcastAddresses.GetCount(); i++) { const wxString &s = broadcastAddresses[i]; if (destination.Index(s) == wxNOT_FOUND) destination.Add(s); } broadcastAddresses = destination; // copy the data back to the old array wxArrayString printerIPsFound; for (unsigned int i = 0;i < broadcastAddresses.Count();i++) { wxString boradcastIP = broadcastAddresses.Item(i); broadcastOverUDP(boradcastIP, (uint8_t*)"M99999", 7); wxArrayString printerIPs = getBlockingBroadcastReply(boradcastIP); for (unsigned int i = 0; i < printerIPs.GetCount(); i++) { const wxString &s = printerIPs[i]; if (printerIPsFound.Index(s) == wxNOT_FOUND) printerIPsFound.Add(s); } } if (printerIPsFound.Count() > 0) { setStatusMessages(wxString::Format(wxT("Found %d printer(s)"), (int)(printerIPsFound.Count())), "", ""); wxString beforeString = comboIP->GetValue(); comboIP->Clear(); for (unsigned int i = 0;i < printerIPsFound.Count();i++) { comboIP->Insert(printerIPsFound.Item(i), i); comboIP->SetValue(printerIPsFound.Item(i)); } if (beforeString.Length() > 4) { comboIP->SetValue(beforeString); } } else { setStatusMessages(_("No printers discovered"), "", ""); wxMessageBox(_("No printers detected in the network.\nHowever you can still connect to a printer if its IP address is accesible"), _("Information"), wxOK | wxICON_INFORMATION | wxCENTER); saveLog(LOG_INFORMATION,_("No printers discovered")); } }
67,685
C++
.cpp
1,745
30.995415
250
0.593217
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,911
SettingsDialog.h
Photonsters_Universal-Photon-Network-Controller/SettingsDialog.h
#ifndef SETTINGSDIALOG_H #define SETTINGSDIALOG_H //(*Headers(SettingsDialog) #include <wx/bmpbuttn.h> #include <wx/button.h> #include <wx/checkbox.h> #include <wx/dialog.h> #include <wx/listbox.h> #include <wx/panel.h> #include <wx/stattext.h> #include <wx/textctrl.h> //*) bool IsIPAddress(wxString); class SettingsDialog: public wxDialog { public: SettingsDialog(wxWindow* parent,wxWindowID id=wxID_ANY,const wxPoint& pos=wxDefaultPosition,const wxSize& size=wxDefaultSize); virtual ~SettingsDialog(); //(*Declarations(SettingsDialog) wxBitmapButton* BitmapButtonAddIP; wxBitmapButton* BitmapButtonDeleteIP; wxButton* btnSettingsCancel; wxButton* btnSettingsOK; wxCheckBox* chkEnableLogging; wxListBox* listIPList; wxPanel* btnAddIP; wxStaticText* StaticText1; wxStaticText* StaticText2; wxStaticText* StaticText3; wxStaticText* StaticText4; wxStaticText* StaticText5; wxTextCtrl* txtConnectionPort; wxTextCtrl* txtPingTimeout; wxTextCtrl* txtPollingInterval; wxTextCtrl* txtReplyTimeout; //*) protected: //(*Identifiers(SettingsDialog) static const long ID_STATICTEXT1; static const long ID_STATICTEXT2; static const long ID_STATICTEXT3; static const long ID_STATICTEXT4; static const long ID_TEXTCTRL1; static const long ID_TEXTCTRL2; static const long ID_TEXTCTRL3; static const long ID_TEXTCTRL4; static const long ID_BUTTON1; static const long ID_BUTTON2; static const long ID_STATICTEXT5; static const long ID_LISTBOX1; static const long ID_BITMAPBUTTON1; static const long ID_BITMAPBUTTON2; static const long ID_CHECKBOX1; static const long ID_PANEL1; //*) private: //(*Handlers(SettingsDialog) void OnbtnSettingsOKClick(wxCommandEvent& event); void OnbtnSettingsCancelClick(wxCommandEvent& event); void OnClose(wxCloseEvent& event); void OnBitmapButtonAddIPClick(wxCommandEvent& event); void OnBitmapButtonDeleteIPClick(wxCommandEvent& event); //*) DECLARE_EVENT_TABLE() }; #endif
1,996
C++
.h
66
27.666667
128
0.796981
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,912
settings.h
Photonsters_Universal-Photon-Network-Controller/settings.h
#pragma once #include <wx/string.h> #include <wx/arrstr.h> #include <wx/textfile.h> #include <wx/stdpaths.h> #include <wx/filename.h> #include <wx/fileconf.h> #include <wx/dir.h> #include <wx/utils.h> #include <wx/datetime.h> #include <wx/time.h> extern double pingTimeOut; extern double replyTimeout; extern wxString ipAddress; extern double port; extern double pollingInterval; extern wxArrayString StaticIPList; extern bool enableLogging; enum LOG_TYPE { LOG_ERROR, LOG_WARNING, LOG_INFORMATION,LOG_EXCEPTION }; void saveLog(LOG_TYPE, wxString);
552
C++
.h
20
26.5
72
0.796226
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,913
NewFrame.h
Photonsters_Universal-Photon-Network-Controller/NewFrame.h
// For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ # pragma hdrstop #endif // for all others, include the necessary headers #ifndef WX_PRECOMP # include "wx/wx.h" #endif #include "wx/url.h" #include "wx/sstream.h" #include <wx/process.h> //(*Headers(NewFrame) #include <wx/bmpbuttn.h> #include <wx/button.h> #include <wx/combobox.h> #include <wx/frame.h> #include <wx/gauge.h> #include <wx/listctrl.h> #include <wx/panel.h> #include <wx/statbox.h> #include <wx/stattext.h> #include <wx/statusbr.h> #include <wx/timer.h> //*) #include <wx/file.h> // Define a new application type class MyApp : public wxApp { public: virtual bool OnInit() wxOVERRIDE; }; // Define a new frame type: this is going to be our main frame class NewFrame : public wxFrame { public: NewFrame(wxFrame* parent, wxWindowID id = wxID_ANY, const wxString Title = "", const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); virtual ~NewFrame(); void saveSettings(); void readSettings(); void processInput(wxString); void getPrintStatus(); //(*Declarations(NewFrame) wxBitmapButton* btnSearchPrinter; wxButton* btnConnect; wxButton* btnDelete; wxButton* btnDownload; wxButton* btnPause; wxButton* btnRefresh; wxButton* btnSettings; wxButton* btnStart; wxButton* btnStop; wxButton* btnUpload; wxComboBox* comboIP; wxGauge* PrintProgress; wxGauge* progressFile; wxListCtrl* ListCtrl1; wxPanel* Panel1; wxStaticBox* StaticBox1; wxStaticBox* StaticBox2; wxStaticBox* StaticBox3; wxStaticText* StaticText1; wxStaticText* lblPercentDone; wxStaticText* lblStatus; wxStatusBar* StatusBar1; wxTimer PollTimer; wxTimer ProcessPollTimer; wxTimer WatchDogTimer; //*) //static wxString[5] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB"}; bool ispaused = false; bool isPrinting = false; double progressBefore = -9999; int framenumber = 0; bool isConnected = false; int tickCount = 0; wxString msges[3]; int exitstatus; bool isPingRunning=false; protected: //(*Identifiers(NewFrame) static const long ID_STATICBOX1; static const long ID_STATICTEXT1; static const long ID_BUTTON1; static const long ID_STATICTEXT2; static const long ID_STATICBOX2; static const long ID_BUTTON2; static const long ID_BUTTON3; static const long ID_BUTTON4; static const long ID_GAUGE1; static const long ID_STATICTEXT3; static const long ID_STATICBOX3; static const long ID_BUTTON5; static const long ID_BUTTON6; static const long ID_BUTTON7; static const long ID_BUTTON8; static const long ID_GAUGE2; static const long ID_LISTCTRL1; static const long ID_BUTTON9; static const long ID_BITMAPBUTTON1; static const long ID_COMBOBOX1; static const long ID_PANEL1; static const long ID_TIMER1; static const long ID_STATUSBAR1; static const long ID_TIMER2; static const long ID_TIMER3; //*) private: //(*Handlers(NewFrame) void OnbtnConnectClick(wxCommandEvent& event); void OnbtnStartClick(wxCommandEvent& event); void OnbtnPauseClick(wxCommandEvent& event); void OnbtnStopClick(wxCommandEvent& event); void OnbtnDeleteClick(wxCommandEvent& event); void OnbtnRefreshClick(wxCommandEvent& event); void OnbtnUploadClick(wxCommandEvent& event); void OnbtnDownloadClick(wxCommandEvent& event); void OnPollTimerTrigger(wxTimerEvent& event); void OnWatchDogTimerTrigger(wxTimerEvent& event); void OnbtnSettingsClick(wxCommandEvent& event); void OnProcessPollTimerTrigger(wxTimerEvent& event); void OnbtnSearchPrinterClick(wxCommandEvent& event); //*) void getAsyncReply(); void OnMyThread(wxCommandEvent& event); void OnProcessTerm( wxProcessEvent& event ); void getVersion(); void getBlockingReply(); void handleResponse(); void sendCmdToPrinter(wxString); void broadcastOverUDP(wxString,uint8_t*, unsigned int); wxArrayString getBlockingBroadcastReply(wxString); void sendCmdToPrinter(uint8_t*, unsigned int); void updatefileList(); bool connectToPrinter(wxString); void disconnectFromPrinter(); void setStatusMessages(wxString, wxString, wxString); wxString isError(wxString); void clearListControl(); void AsyncPingPrinter(wxString,int); void OnProcessTimer(wxTimerEvent&); bool isconnected = false; bool startList = false; bool endList = false; int fileCount = 0; wxFile* photonFile; wxString photonFileName; wxString photonFilePath; unsigned int beforeByte = 0; unsigned int frameNum = 0; unsigned int numDownloadRetries = 0; bool downloadStarted = false; ssize_t downloadFileLength = -1; ssize_t downloadFileCurrentLength = -1; bool pingFailed=false; wxIPV4address *m_BroadCastAddress; // For broadcast sending wxIPV4address m_LocalAddress; // For listening wxDatagramSocket* m_Listen_Socket; DECLARE_EVENT_TABLE() }; class DisplayProcess : public wxProcess // Executes a command, displaying output in a textctrl. Adapted from the exec sample { // Very similar to MyPipedProcess in Tools.cpp, but enough differences to make derivation difficult public: DisplayProcess(NewFrame* parentFrame): wxProcess(wxPROCESS_REDIRECT) { m_parent = parentFrame; }; bool HasInput(); void SetPid(long pid) { m_pid = pid; } protected: void OnTerminate(int pid, int status); long m_pid; // Stores the process's pid, in case we want to kill it bool m_WasCancelled; NewFrame* m_parent; };
5,767
C++
.h
179
28.240223
160
0.728674
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,914
MyThread.h
Photonsters_Universal-Photon-Network-Controller/MyThread.h
#ifndef MYTHREAD_H #define MYTHREAD_H #include <wx/thread.h> #include <wx/event.h> #include "wx/socket.h" BEGIN_DECLARE_EVENT_TYPES() DECLARE_EVENT_TYPE(wxEVT_READTHREAD, -1) END_DECLARE_EVENT_TYPES() class MyThread : public wxThread { public: MyThread(wxEvtHandler* pParent); private: void* Entry(); protected: wxEvtHandler * m_pParent; }; #endif
356
C++
.h
18
18.333333
40
0.783784
Photonsters/Universal-Photon-Network-Controller
36
6
9
GPL-3.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,915
FTmodulatorDialog.cpp
essej_freqtweak/src/FTmodulatorDialog.cpp
/* ** Copyright (C) 2004 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #if HAVE_CONFIG_H #include <config.h> #endif #include <wx/wx.h> #include <wx/listctrl.h> #include <iostream> using namespace std; #include "FTmodulatorDialog.hpp" #include "FTmodulatorManager.hpp" #include "FTioSupport.hpp" #include "FTmainwin.hpp" #include "FTdspManager.hpp" #include "FTprocI.hpp" #include "FTmodulatorI.hpp" #include "FTprocessPath.hpp" #include "FTspectralEngine.hpp" #include "FTmodulatorGui.hpp" #include <sigc++/sigc++.h> using namespace sigc; enum { ID_AddButton=8000, ID_PopupMenu, ID_EditMenuItem, ID_RemoveMenuItem, ID_ChannelList, ID_ClearButton }; enum { ID_AddModulatorBase = 9000, ID_AddModulatorChannelBase = 9100, ID_AddModulatorChannelMax = 9110 }; BEGIN_EVENT_TABLE(FTmodulatorDialog, wxFrame) EVT_CLOSE(FTmodulatorDialog::onClose) EVT_IDLE(FTmodulatorDialog::OnIdle) EVT_SIZE (FTmodulatorDialog::onSize) EVT_PAINT (FTmodulatorDialog::onPaint) EVT_BUTTON (ID_ClearButton, FTmodulatorDialog::onClearButton) EVT_COMMAND_RANGE(ID_AddModulatorChannelBase, ID_AddModulatorChannelMax, wxEVT_COMMAND_BUTTON_CLICKED, FTmodulatorDialog::onAddButton) END_EVENT_TABLE() class FTaddmodObject : public wxObject { public: FTaddmodObject(int ind) : index(ind) {} int index; }; FTmodulatorDialog::FTmodulatorDialog(FTmainwin * parent, wxWindowID id, const wxString & title, const wxPoint& pos, const wxSize& size, long style, const wxString& name ) : wxFrame(parent, id, title, pos, size, style, name), _clickedChannel(-1), _mainwin(parent) { init(); } FTmodulatorDialog::~FTmodulatorDialog() { } void FTmodulatorDialog::onSize(wxSizeEvent &ev) { _justResized = true; ev.Skip(); } void FTmodulatorDialog::onPaint(wxPaintEvent &ev) { if (_justResized) { //int width,height; _justResized = false; // for (int i=0; i < _channelCount; ++i) // { // _channelLists[i]->GetClientSize(&width, &height); // _channelLists[i]->SetColumnWidth(0, width); // } } ev.Skip(); } void FTmodulatorDialog::init() { wxBoxSizer * mainsizer = new wxBoxSizer(wxVERTICAL); //wxStaticText * statText; _channelSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer * rowsizer = new wxBoxSizer(wxHORIZONTAL); wxButton *addButt = new wxButton(this, ID_AddModulatorChannelBase, wxT("Add Modulator...")); rowsizer->Add (addButt, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 4); rowsizer->Add (2,1,1); wxButton *clearButt = new wxButton(this, ID_ClearButton, wxT("Remove All")); rowsizer->Add (clearButt, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 4); mainsizer->Add (rowsizer, 0, wxALL|wxEXPAND); _channelScroller = new wxScrolledWindow(this, -1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER); _channelSizer = new wxBoxSizer(wxVERTICAL); _channelScroller->SetSizer(_channelSizer); _channelScroller->SetAutoLayout(true); _channelScroller->SetScrollRate (10, 30); _channelScroller->EnableScrolling (true, true); mainsizer->Add (_channelScroller, 1, wxEXPAND|wxALL, 3); wxMenuItem * item; _popupMenu = new wxMenu(); int itemid = ID_AddModulatorBase; FTmodulatorManager::ModuleList mlist; FTmodulatorManager::instance()->getAvailableModules(mlist); int modnum = 0; for (FTmodulatorManager::ModuleList::iterator moditer = mlist.begin(); moditer != mlist.end(); ++moditer) { item = new wxMenuItem(_popupMenu, itemid, wxString::FromAscii ((*moditer)->getName().c_str())); _popupMenu->Append (item); Connect( itemid, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &FTmodulatorDialog::onAddModulator, (wxObject *) (new FTaddmodObject(modnum++))); itemid++; } refreshState(); SetAutoLayout( TRUE ); mainsizer->Fit( this ); mainsizer->SetSizeHints( this ); SetSizer( mainsizer ); // this->SetSizeHints(200,100); } void FTmodulatorDialog::refreshState() { // first time only FTioSupport * iosup = FTioSupport::instance(); FTprocessPath * procpath; for (int i=0; i < iosup->getActivePathCount(); ++i) { procpath = iosup->getProcessPath(i); if (procpath) { FTspectralEngine *engine = procpath->getSpectralEngine(); engine->ModulatorAdded.connect( sigc::bind (sigc::mem_fun(*this, &FTmodulatorDialog::onModulatorAdded), i)); vector<FTmodulatorI*> modlist; modlist.clear(); engine->getModulators (modlist); for (vector<FTmodulatorI*>::iterator iter=modlist.begin(); iter != modlist.end(); ++iter) { FTmodulatorI * mod = (*iter); appendModGui (mod, false); } } } _channelScroller->Layout(); _channelScroller->SetScrollRate(10,30); // if (_lastSelected >= 0 && _lastSelected < _targetList->GetItemCount()) { // _targetList->SetItemState (_lastSelected, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); // } } void FTmodulatorDialog::appendModGui(FTmodulatorI * mod, bool layout) { FTmodulatorGui *modgui = new FTmodulatorGui(FTioSupport::instance(), mod, _channelScroller, -1); modgui->RemovalRequest.connect (sigc::bind (sigc::mem_fun(*this, &FTmodulatorDialog::onModulatorDeath), mod)); mod->GoingAway.connect ( sigc::mem_fun(*this, &FTmodulatorDialog::onModulatorDeath)); _modulatorGuis[mod] = modgui; _channelSizer->Add(modgui, 0, wxEXPAND|wxALL, 1); if (layout) { _channelScroller->SetClientSize(_channelScroller->GetClientSize()); _channelScroller->Layout(); // _channelScroller->SetScrollbars(1,1,10,30); } } void FTmodulatorDialog::onClose(wxCloseEvent & ev) { if (!ev.CanVeto()) { Destroy(); } else { ev.Veto(); Show(false); } } void FTmodulatorDialog::onClearButton (wxCommandEvent &ev) { // remove all modulators for (int i=0; i < FTioSupport::instance()->getActivePathCount(); i++) { FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(i); if (procpath) { FTspectralEngine *engine = procpath->getSpectralEngine(); engine->clearModulators (); } } } void FTmodulatorDialog::onAddButton (wxCommandEvent &ev) { wxWindow * source = (wxWindow *) ev.GetEventObject(); _clickedChannel = ev.GetId() - ID_AddModulatorChannelBase; wxRect pos = source->GetRect(); PopupMenu(_popupMenu, pos.x, pos.y + pos.height); } void FTmodulatorDialog::onAddModulator (wxCommandEvent &ev) { FTaddmodObject * mobj = (FTaddmodObject *)ev.m_callbackUserData; if (!mobj) return; FTmodulatorI * protomod = FTmodulatorManager::instance()->getModuleByIndex(mobj->index); //cerr << "add modulator: " << (unsigned) protomod << " clicked chan: " << _clickedChannel << " " << (unsigned) this << endl; if (protomod) { FTmodulatorI * mod = protomod->clone(); mod->initialize(); appendModGui (mod, true); // you can change its channel later FTprocessPath * procpath = FTioSupport::instance()->getProcessPath(0); if (procpath) { FTspectralEngine *engine = procpath->getSpectralEngine(); engine->appendModulator (mod); // refreshState(); } } } void FTmodulatorDialog::OnIdle(wxIdleEvent &ev) { if (_deadGuis.size() > 0) { for (list<FTmodulatorGui*>::iterator iter = _deadGuis.begin(); iter != _deadGuis.end(); ++iter) { (*iter)->Destroy(); } _deadGuis.clear(); } ev.Skip(); } void FTmodulatorDialog::onModulatorDeath (FTmodulatorI * mod) { //cerr << "mod death: " << mod->getName() << endl; if (_modulatorGuis.find (mod) != _modulatorGuis.end()) { //cerr << "deleting modgui" << endl; FTmodulatorGui * modgui = _modulatorGuis[mod]; _channelSizer->Detach ((wxSizer*)modgui); modgui->Show(false); _channelScroller->SetClientSize(_channelScroller->GetClientSize()); _channelScroller->Layout(); //_channelScroller->SetScrollbars(1,1,10,30); _deadGuis.push_back(modgui); _modulatorGuis.erase(mod); ::wxWakeUpIdle(); } } void FTmodulatorDialog::onModulatorAdded (FTmodulatorI * mod, int channel) { if (_modulatorGuis.find(mod) == _modulatorGuis.end()) { FTprocessPath * procpath = FTioSupport::instance()->getProcessPath (channel); if (procpath) { // FTspectralEngine *engine = procpath->getSpectralEngine(); appendModGui (mod, true); } } }
8,910
C++
.cpp
264
30.893939
135
0.73371
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,916
FTprocGate.cpp
essej_freqtweak/src/FTprocGate.cpp
/* ** Copyright (C) 2003 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #include "FTprocGate.hpp" #include "FTutils.hpp" FTprocGate::FTprocGate (nframes_t samprate, unsigned int fftn) : FTprocI("Gate", samprate, fftn) , _dbAdjust(-37.0) { _confname = "Gate"; } FTprocGate::FTprocGate (const FTprocGate & other) : FTprocI (other._name, other._sampleRate, other._fftN) , _dbAdjust(other._dbAdjust) { _confname = "Gate"; } void FTprocGate::initialize() { // create filters _filter = new FTspectrumModifier("Gate Bottom", "gate", 0, FTspectrumModifier::DB_MODIFIER, GATE_SPECMOD, _fftN/2, -90.0); _filter->setRange(-90.0, 0.0); //_gateFilter->reset(); _filter->setBypassed(true); // by default _invfilter = new FTspectrumModifier("Gate", "inverse_gate", 0, FTspectrumModifier::DB_MODIFIER, GATE_SPECMOD, _fftN/2, 0.0); _invfilter->setRange(-90.0, 0.0); _invfilter->setBypassed(true); // by default _filterlist.push_back(_invfilter); _filterlist.push_back(_filter); _inited = true; } FTprocGate::~FTprocGate() { if (!_inited) return; _filterlist.clear(); delete _filter; delete _invfilter; } void FTprocGate::process (fft_data *data, unsigned int fftn) { if (!_inited || _filter->getBypassed()) { return; } float *filter = _filter->getValues(); float *invfilter = _invfilter->getValues(); float power; float db; int fftn2 = (fftn+1) >> 1; // only allow data through if power is above threshold power = (data[0] * data[0]); db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors if (db < filter[0] || db > invfilter[0]) { data[0] = 0.0; } for (int i = 1; i < fftn2-1; i++) { power = (data[i] * data[i]) + (data[fftn-i] * data[fftn-i]); db = FTutils::powerLogScale (power, 0.0000000) + _dbAdjust; // total fudge factors if (db < filter[i] || db > invfilter[i]) { //printf ("db %g\n", db); data[i] = data[fftn-i] = 0.0; } } }
2,657
C++
.cpp
80
30.975
125
0.697647
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,917
FTmodRotate.cpp
essej_freqtweak/src/FTmodRotate.cpp
/* ** Copyright (C) 2004 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #include "FTmodRotate.hpp" #include <cstdlib> #include <cstdio> #include <iostream> using namespace std; using namespace PBD; FTmodRotate::FTmodRotate (nframes_t samplerate, unsigned int fftn) : FTmodulatorI ("Rotate", "Rotate", samplerate, fftn) { } FTmodRotate::FTmodRotate (const FTmodRotate & other) : FTmodulatorI ("Rotate", "Rotate", other._sampleRate, other._fftN) { } void FTmodRotate::initialize() { _lastframe = 0; _rate = new Control (Control::FloatType, "rate", "Rate", "Hz/sec"); _rate->_floatLB = -((float) _sampleRate); _rate->_floatUB = (float) _sampleRate; _rate->setValue (0.0f); _controls.push_back (_rate); _minfreq = new Control (Control::FloatType, "min_freq", "Min Freq", "Hz"); _minfreq->_floatLB = 0.0; _minfreq->_floatUB = _sampleRate / 2; _minfreq->setValue (_minfreq->_floatLB); _controls.push_back (_minfreq); _maxfreq = new Control (Control::FloatType, "max_freq", "Max Freq", "Hz"); _maxfreq->_floatLB = 0.0; _maxfreq->_floatUB = _sampleRate / 2; _maxfreq->setValue (_maxfreq->_floatUB); _controls.push_back (_maxfreq); // _dimension = new Control (Control::EnumType, "Target", ""); // _dimension->_enumList.push_back("Frequency"); // _dimension->_enumList.push_back("Value"); // _dimension->setValue ("Frequency"); // _controls.push_back (_dimension); _tmpfilt = new float[_fftN]; _inited = true; } FTmodRotate::~FTmodRotate() { if (!_inited) return; _controls.clear(); delete _rate; delete _minfreq; delete _maxfreq; } void FTmodRotate::setFFTsize (unsigned int fftn) { _fftN = fftn; if (_inited) { delete _tmpfilt; _tmpfilt = new float[_fftN]; } } void FTmodRotate::modulate (nframes_t current_frame, fft_data * fftdata, unsigned int fftn, sample_t * timedata, nframes_t nframes) { TentativeLockMonitor lm (_specmodLock, __LINE__, __FILE__); if (!lm.locked() || !_inited || _bypassed) return; float rate = 1.0; float ub,lb; float * filter; int len; int i,j; float minfreq = 0.0, maxfreq = 0.0; int minbin, maxbin; double hzperbin; // in hz/sec _rate->getValue (rate); _minfreq->getValue (minfreq); _maxfreq->getValue (maxfreq); if (minfreq >= maxfreq) { return; } hzperbin = _sampleRate / (double) fftn; // shiftval (bins) = deltasamples / (samp/sec) * (hz/sec) / (hz/bins) // bins = sec * hz/sec int shiftval = (int) (((current_frame - _lastframe) / (double) _sampleRate) * rate / hzperbin); if (current_frame != _lastframe && shiftval != 0) { // fprintf (stderr, "shift at %lu : samps=%g s*c=%g s*e=%g \n", (unsigned long) current_frame, samps, (current_frame/samps), ((current_frame + nframes)/samps) ); for (SpecModList::iterator iter = _specMods.begin(); iter != _specMods.end(); ++iter) { FTspectrumModifier * sm = (*iter); if (sm->getBypassed()) continue; // cerr << "shiftval is: " << shiftval // << " hz/bin: " << hzperbin // << " rate: " << rate << endl; filter = sm->getValues(); sm->getRange(lb, ub); len = (int) sm->getLength(); minbin = (int) ((minfreq*2/ _sampleRate) * len); maxbin = (int) ((maxfreq*2/ _sampleRate) * len); len = maxbin - minbin; if (len <= 0) { continue; } int shiftbins = (abs(shiftval) % len) * (shiftval > 0 ? 1 : -1); // fprintf(stderr, "shifting %d %d:%d at %lu\n", shiftbins, minbin, maxbin, (unsigned long) current_frame); if (shiftbins > 0) { // shiftbins is POSITIVE, shift right // store last shiftbins for (i=maxbin-shiftbins; i < maxbin; i++) { _tmpfilt[i] = filter[i]; } for ( i=maxbin-1; i >= minbin + shiftbins; i--) { filter[i] = filter[i-shiftbins]; } for (j=maxbin-shiftbins, i=minbin; i < minbin + shiftbins; i++, j++) { filter[i] = _tmpfilt[j]; } } else if (shiftbins < 0) { // shiftbins is NEGATIVE, shift left // store last shiftbins // store first shiftbins for (i=minbin; i < minbin-shiftbins; i++) { _tmpfilt[i] = filter[i]; } for (i=minbin; i < maxbin + shiftbins; i++) { filter[i] = filter[i-shiftbins]; } for (j=minbin, i=maxbin+shiftbins; i < maxbin; i++, j++) { filter[i] = _tmpfilt[j]; } } sm->setDirty(true); } _lastframe = current_frame; } }
5,087
C++
.cpp
150
30.726667
166
0.656676
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,918
pix_button.cpp
essej_freqtweak/src/pix_button.cpp
/* ** Copyright (C) 2004 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #include <wx/wx.h> #include <iostream> #include "pix_button.hpp" enum { ID_EditMenuOp = 9000, ID_DefaultMenuOp, ID_BindMenuOp }; using namespace JLCui; using namespace std; BEGIN_EVENT_TABLE(PixButton, wxWindow) EVT_SIZE(PixButton::OnSize) EVT_PAINT(PixButton::OnPaint) EVT_MOUSE_EVENTS(PixButton::OnMouseEvents) EVT_MENU (ID_BindMenuOp , PixButton::on_menu_events) END_EVENT_TABLE() PixButton::PixButton(wxWindow * parent, wxWindowID id, bool bindable, const wxPoint& pos, const wxSize& size) : wxWindow(parent, id, pos, size) { _bgcolor = *wxBLACK; _bgbrush.SetColour (_bgcolor); _bstate = Normal; _estate = Outside; _backing_store = 0; _active = false; if (bindable) { _popup_menu = new wxMenu(wxT("")); //_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_EditMenuOp, wxT("Edit"))); //_popup_menu->Append ( new wxMenuItem(_popup_menu, ID_DefaultMenuOp, wxT("Set to default"))); //_popup_menu->AppendSeparator(); _popup_menu->Append ( new wxMenuItem(_popup_menu, ID_BindMenuOp, wxT("Learn MIDI Binding"))); } else { _popup_menu = 0; } SetBackgroundColour (_bgcolor); SetThemeEnabled(false); update_size(); } PixButton::~PixButton() { _memdc.SelectObject(wxNullBitmap); if (_backing_store) { delete _backing_store; } } void PixButton::set_normal_bitmap (const wxBitmap & bm) { if (!bm.Ok()) return; _normal_bitmap = bm; SetSizeHints (bm.GetWidth(), bm.GetHeight()); SetClientSize (bm.GetWidth(), bm.GetHeight()); Refresh(false); } void PixButton::set_focus_bitmap (const wxBitmap & bm) { if (!bm.Ok()) return; _focus_bitmap = bm; SetSizeHints (bm.GetWidth(), bm.GetHeight()); SetClientSize (bm.GetWidth(), bm.GetHeight()); Refresh(false); } void PixButton::set_selected_bitmap (const wxBitmap & bm) { if (!bm.Ok()) return; _selected_bitmap = bm; SetSizeHints (bm.GetWidth(), bm.GetHeight()); SetClientSize (bm.GetWidth(), bm.GetHeight()); Refresh(false); } void PixButton::set_disabled_bitmap (const wxBitmap & bm) { if (!bm.Ok()) return; _disabled_bitmap = bm; SetSizeHints (bm.GetWidth(), bm.GetHeight()); SetClientSize (bm.GetWidth(), bm.GetHeight()); Refresh(false); } void PixButton::set_active_bitmap (const wxBitmap & bm) { if (!bm.Ok()) return; _active_bitmap = bm; SetSizeHints (bm.GetWidth(), bm.GetHeight()); SetClientSize (bm.GetWidth(), bm.GetHeight()); Refresh(false); } void PixButton::set_bg_color (const wxColour & col) { _bgcolor = col; _bgbrush.SetColour (col); SetBackgroundColour (col); Refresh(false); } void PixButton::set_active(bool flag) { if (_active != flag) { _active = flag; Refresh(false); } } void PixButton::update_size() { GetClientSize(&_width, &_height); if (_width > 0 && _height > 0) { _memdc.SelectObject (wxNullBitmap); if (_backing_store) { delete _backing_store; } _backing_store = new wxBitmap(_width, _height); _memdc.SelectObject(*_backing_store); } } void PixButton::OnSize(wxSizeEvent & event) { update_size(); event.Skip(); } void PixButton::OnPaint(wxPaintEvent & event) { wxPaintDC pdc(this); if (!_backing_store) { return; } draw_area(_memdc); pdc.Blit(0, 0, _width, _height, &_memdc, 0, 0); } static inline int get_mouse_up_button(const wxMouseEvent &ev) { if (ev.LeftUp()) return (int) PixButton::LeftButton; else if (ev.MiddleUp()) return (int) PixButton::MiddleButton; else if (ev.RightUp()) return (int) PixButton::RightButton; else return 0; } static inline int get_mouse_button(const wxMouseEvent &ev) { if (ev.ButtonDown()) { if (ev.LeftDown()) return (int) PixButton::LeftButton; else if (ev.MiddleDown()) return (int) PixButton::MiddleButton; else if (ev.RightDown()) return (int) PixButton::RightButton; else return 0; } else if (ev.ButtonUp()) { if (ev.LeftUp()) return (int) PixButton::LeftButton; else if (ev.MiddleUp()) return (int) PixButton::MiddleButton; else if (ev.RightUp()) return (int) PixButton::RightButton; else return 0; } else return 0; } void PixButton::OnMouseEvents (wxMouseEvent &ev) { if (!IsEnabled()) { ev.Skip(); return; } if (ev.Moving()) { // do nothing } else if (ev.RightDown()) { if (_popup_menu) { this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY()); } else { pressed (get_mouse_button(ev)); // emit } } else if (ev.RightUp()) { //this->PopupMenu ( _popup_menu, ev.GetX(), ev.GetY()); released (get_mouse_button(ev)); // emit } else if (ev.ButtonDown()) { if (!(ev.MiddleDown() && ev.ControlDown())) { _bstate = Selected; pressed (get_mouse_button(ev)); // emit CaptureMouse(); Refresh(false); } } else if (ev.ButtonUp()) { _bstate = Normal; ReleaseMouse(); released (get_mouse_button(ev)); // emit wxPoint pt = ev.GetPosition(); wxRect bounds = GetRect(); pt.x += bounds.x; pt.y += bounds.y; if (bounds.Contains(pt)) { clicked (get_mouse_button(ev)); // emit if (ev.MiddleUp() && ev.ControlDown()) { bind_request(); // emit } } Refresh(false); } else if (ev.ButtonDClick()) { _bstate = Selected; pressed (get_mouse_button(ev)); // emit Refresh(false); } else if (ev.Entering()) { _estate = Inside; enter(); // emit Refresh(false); } else if (ev.Leaving()) { _estate = Outside; leave(); // emit Refresh(false); } ev.Skip(); } void PixButton::on_menu_events (wxCommandEvent &ev) { if (ev.GetId() == ID_BindMenuOp) { bind_request(); // emit } } void PixButton::draw_area(wxDC & dc) { dc.SetBackground(_bgbrush); dc.Clear(); if (!IsEnabled()) { dc.DrawBitmap (_disabled_bitmap, 0, 0); } else if (_active) { dc.DrawBitmap (_active_bitmap, 0, 0); } else { switch (_bstate) { case Normal: if (_estate == Outside) { dc.DrawBitmap (_normal_bitmap, 0, 0); } else { dc.DrawBitmap (_focus_bitmap, 0, 0); } break; case Selected: dc.DrawBitmap (_selected_bitmap, 0, 0); break; case Disabled: dc.DrawBitmap (_disabled_bitmap, 0, 0); break; } } }
6,796
C++
.cpp
272
22.580882
109
0.691676
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,532,919
FTmainwin.cpp
essej_freqtweak/src/FTmainwin.cpp
/* ** Copyright (C) 2002 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #if HAVE_CONFIG_H #include <config.h> #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWindows headers #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/sashwin.h> #include <wx/spinctrl.h> #include <wx/notebook.h> #include <wx/string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdint.h> #include <string> using namespace std; #include "FTmainwin.hpp" #include "FTspectragram.hpp" #include "FTioSupport.hpp" #include "FTprocessPath.hpp" #include "FTprocI.hpp" #include "FTspectralEngine.hpp" #include "FTactiveBarGraph.hpp" #include "FTportSelectionDialog.hpp" #include "FTspectrumModifier.hpp" #include "FTconfigManager.hpp" #include "FTupdateToken.hpp" #include "FTprocOrderDialog.hpp" #include "FTpresetBlendDialog.hpp" #include "FTmodulatorDialog.hpp" #include "FThelpWindow.hpp" #include "pix_button.hpp" using namespace JLCui; #include "version.h" #include "ftlogo.xpm" //#include "images/bypass.xpm" //#include "images/bypass_active.xpm" //#include "images/link.xpm" //#include "images/link_active.xpm" #include "pixmap_includes.hpp" // ---------------------------------------------------------------------------- // event tables and other macros for wxWindows // ---------------------------------------------------------------------------- // IDs for the controls and the menu commands enum WindowIds { // menu items FT_QuitMenu = 1, FT_AboutMenu, FT_ProcModMenu, FT_PresetBlendMenu, FT_ModulatorMenu, FT_HelpTipsMenu, FT_InputButtonId, FT_OutputButtonId, FT_InSpecTypeId, FT_OutSpecTypeId, FT_BypassBase = 100, FT_InSpecLabelId = 130, FT_OutSpecLabelId, FT_LabelBase = 150, FT_LinkBase = 180, FT_FreqBinsChoiceId = 210, FT_OverlapChoiceId, FT_WindowingChoiceId, FT_TimescaleSliderId, FT_FreqScaleChoiceId, FT_RowPanelId, FT_RowPanel, FT_BypassId, FT_MuteId, FT_GainSlider, FT_GainSpin, FT_MixSlider, FT_PathCountChoice, FT_StoreButton, FT_LoadButton, FT_PresetCombo, FT_PlotSpeedChoiceId, FT_PlotSuperSmoothId, FT_MixLinkedButton, FT_IOreconnectButton, FT_IOdisconnectButton, FT_IOnameText, FT_GridBase = 500, FT_GridSnapBase = 530, FT_MaxDelayChoiceId = 560, FT_TempoSpinId, FT_RestorePortCheckId }; DEFINE_LOCAL_EVENT_TYPE (FT_EVT_TITLEMENU_COMMAND); IMPLEMENT_DYNAMIC_CLASS(FTtitleMenuEvent, wxCommandEvent); // the event tables connect the wxWindows events with the functions (event // handlers) which process them. It can be also done at run-time, but for the // simple menu events like this the static method is much simpler. BEGIN_EVENT_TABLE(FTmainwin, wxFrame) // EVT_SIZE(FTmainwin::OnSize) EVT_MENU(FT_QuitMenu, FTmainwin::OnQuit) EVT_MENU(FT_AboutMenu, FTmainwin::OnAbout) EVT_MENU(FT_HelpTipsMenu, FTmainwin::OnAbout) EVT_MENU(FT_ProcModMenu, FTmainwin::OnProcMod) EVT_MENU(FT_PresetBlendMenu, FTmainwin::OnPresetBlend) EVT_MENU(FT_ModulatorMenu, FTmainwin::OnModulatorDialog) EVT_IDLE(FTmainwin::OnIdle) EVT_CLOSE(FTmainwin::OnClose) EVT_BUTTON(FT_InputButtonId, FTmainwin::handleInputButton) EVT_BUTTON(FT_OutputButtonId, FTmainwin::handleOutputButton) EVT_BUTTON(FT_LinkBase, FTmainwin::handleLinkButtons) EVT_BUTTON(FT_BypassBase, FTmainwin::handleBypassButtons) EVT_CHOICE(FT_FreqBinsChoiceId, FTmainwin::handleChoices) EVT_CHOICE(FT_OverlapChoiceId, FTmainwin::handleChoices) EVT_CHOICE(FT_WindowingChoiceId, FTmainwin::handleChoices) EVT_CHOICE(FT_PlotSpeedChoiceId, FTmainwin::handleChoices) EVT_CHECKBOX(FT_PlotSuperSmoothId, FTmainwin::handleChoices) EVT_CHOICE(FT_MaxDelayChoiceId, FTmainwin::handleChoices) EVT_CHOICE(FT_PathCountChoice, FTmainwin::handlePathCount) EVT_COMMAND_SCROLL(FT_MixSlider, FTmainwin::handleMixSlider) EVT_SPINCTRL(FT_GainSpin, FTmainwin::handleGain) EVT_SASH_DRAGGED(FT_RowPanelId, FTmainwin::handleSashDragged) EVT_BUTTON(FT_InSpecLabelId, FTmainwin::handleLabelButtons) EVT_BUTTON(FT_LabelBase, FTmainwin::handleLabelButtons) EVT_BUTTON(FT_OutSpecLabelId, FTmainwin::handleLabelButtons) EVT_BUTTON(FT_InSpecTypeId, FTmainwin::handlePlotTypeButtons) EVT_BUTTON(FT_OutSpecTypeId, FTmainwin::handlePlotTypeButtons) EVT_CHECKBOX(FT_BypassId, FTmainwin::handleBypassButtons) EVT_CHECKBOX(FT_MuteId, FTmainwin::handleBypassButtons) EVT_BUTTON(FT_StoreButton, FTmainwin::handleStoreButton) EVT_BUTTON(FT_LoadButton, FTmainwin::handleLoadButton) EVT_CHECKBOX(FT_MixLinkedButton, FTmainwin::handleLinkButtons) EVT_BUTTON(FT_IOreconnectButton, FTmainwin::handleIOButtons) EVT_BUTTON(FT_IOdisconnectButton, FTmainwin::handleIOButtons) EVT_BUTTON(FT_GridBase, FTmainwin::handleGridButtons) EVT_BUTTON(FT_GridSnapBase, FTmainwin::handleGridButtons) EVT_SPINCTRL(FT_TempoSpinId, FTmainwin::handleSpins) EVT_TITLEMENU_COMMAND (0, FTmainwin::handleTitleMenuCmd) END_EVENT_TABLE() // ---------------------------------------------------------------------------- // main frame // ---------------------------------------------------------------------------- FTmainwin::FTmainwin(int startpath, const wxString& title, const wxString& rcdir, const wxPoint& pos, const wxSize& size) : wxFrame((wxFrame *)NULL, -1, title, pos, size), _startpaths(startpath), _inspecShown(true), _outspecShown(true), _linkedMix(true), _updateMS(10), _superSmooth(false), _refreshMS(200), _pathCount(startpath), _configManager(static_cast<const char *> (rcdir.fn_str())), _procmodDialog(0), _blendDialog(0), _modulatorDialog(0), _titleFont(10, wxDEFAULT, wxNORMAL, wxBOLD), _titleAltFont(10, wxDEFAULT, wxSLANT, wxBOLD), _buttFont(10, wxDEFAULT, wxNORMAL, wxNORMAL) { _eventTimer = new FTupdateTimer(this); _refreshTimer = new FTrefreshTimer(this); for (int i=0; i < FT_MAXPATHS; i++) { _processPath[i] = 0; _updateTokens[i] = new FTupdateToken(); } buildGui(); } void FTmainwin::normalizeFontSize(wxFont & fnt, int height, wxString fitstr) { int fontw, fonth, desch, lead, lasth=0; GetTextExtent(fitstr, &fontw, &fonth, &desch, &lead, &fnt); //printf ("Text extent for %s: %d %d %d %d sz: %d\n", fitstr.c_str(), fontw, desch, lead, fonth, fnt.GetPointSize()); while (fonth > height ) { fnt.SetPointSize(fnt.GetPointSize() - 1); GetTextExtent(fitstr, &fontw, &fonth, &desch, &lead, &fnt); //printf ("Text extent for buttfont: %d %d %d %d sz: %d\n", fontw, fonth, desch, lead, fnt.GetPointSize()); if (lasth == fonth) break; // safety lasth = fonth; } } void FTmainwin::buildGui() { _bwidth = 22; _labwidth = 74; _bheight = 24; _rowh = 68; normalizeFontSize(_buttFont, _bheight-8, wxT("BA")); normalizeFontSize(_titleFont, _bheight-8, wxT("EQ")); normalizeFontSize(_titleAltFont, _bheight-8, wxT("EQ")); // set the frame icon //SetIcon(wxICON(mondrian)); // create a menu bar wxMenu *menuFile = new wxMenu(wxT(""), wxMENU_TEAROFF); menuFile->Append(FT_ProcModMenu, wxT("&DSP Modules...\tCtrl-P"), wxT("Configure DSP modules")); menuFile->Append(FT_ModulatorMenu, wxT("&Modulators...\tCtrl-M"), wxT("Configure Modulations")); menuFile->Append(FT_PresetBlendMenu, wxT("Preset &Blend...\tCtrl-B"), wxT("Blend multiple presets")); menuFile->AppendSeparator(); menuFile->Append(FT_QuitMenu, wxT("&Quit\tCtrl-Q"), wxT("Quit this program")); // now append the freshly created menu to the menu bar... wxMenuBar *menuBar = new wxMenuBar(); menuBar->Append(menuFile, wxT("&Control")); wxMenu *menuHelp = new wxMenu(wxT(""), wxMENU_TEAROFF); menuHelp->Append(FT_HelpTipsMenu, wxT("&Usage Tips...\tCtrl-H"), wxT("Show Usage Tips window")); menuHelp->Append(FT_AboutMenu, wxT("&About...\tCtrl-A"), wxT("Show about dialog")); menuBar->Append(menuHelp, wxT("&Help")); // ... and attach this menu bar to the frame SetMenuBar(menuBar); #if wxUSE_STATUSBAR // create a status bar just for fun (with 3 panes) CreateStatusBar(3); SetStatusText(wxT("FreqTweak"), 0); #endif // wxUSE_STATUSBAR // terrible! _defaultBg = GetBackgroundColour(); //_activeBg.Set (254,185,55); _activeBg.Set (246,229,149); // get processPaths from jacksupport FTioSupport * iosup = FTioSupport::instance(); for (int i=0; i < _startpaths; i++) { // add to io support instance _processPath[i] = iosup->setProcessPathActive (i, true); } wxBoxSizer *mainsizer = new wxBoxSizer(wxVERTICAL); // overall controls wxNotebook * ctrlbook = new wxNotebook(this,-1, wxDefaultPosition, wxSize(-1, 70)); // preset panel wxPanel * configpanel = new wxPanel (ctrlbook, -1); wxBoxSizer *configSizer = new wxBoxSizer(wxHORIZONTAL); _presetCombo = new wxComboBox (configpanel, FT_PresetCombo, wxT(""), wxDefaultPosition, wxSize(200,-1), 0, 0, wxCB_SORT); configSizer->Add( _presetCombo, 0, wxALL|wxALIGN_CENTER, 2); wxButton *storeButt = new wxButton(configpanel, FT_StoreButton, wxT("Store")); configSizer->Add( storeButt, 0, wxALL|wxALIGN_CENTER, 2); wxButton *loadButt = new wxButton(configpanel, FT_LoadButton, wxT("Load")); configSizer->Add( loadButt, 0, wxALL|wxALIGN_CENTER, 2); _restorePortsCheck = new wxCheckBox(configpanel, FT_RestorePortCheckId, wxT("Restore Ports")); configSizer->Add( _restorePortsCheck, 0, wxALL|wxALIGN_CENTER, 2); configpanel->SetAutoLayout(TRUE); configSizer->Fit( configpanel ); configpanel->SetSizer(configSizer); ctrlbook->AddPage ( (wxNotebookPage *) configpanel, wxT("Presets"), true); //mainsizer->Add (configSizer, 0, wxALL|wxEXPAND, 1); wxPanel * fftpanel = new wxPanel(ctrlbook, -1); wxStaticText *stattext; //wxBoxSizer *specCtrlSizer = new wxStaticBoxSizer(new wxStaticBox(fftpanel, -1, "FFT Params"), wxHORIZONTAL); wxBoxSizer *specCtrlSizer = new wxBoxSizer(wxHORIZONTAL); stattext = new wxStaticText(fftpanel, -1, wxT("Freq Bands")); specCtrlSizer->Add (stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _freqBinsChoice = new wxChoice(fftpanel, FT_FreqBinsChoiceId); const int * fftbins = FTspectralEngine::getFFTSizes(); for (int i=0; i < FTspectralEngine::getFFTSizeCount(); i++) { _freqBinsChoice->Append(wxString::Format(wxT("%d"), fftbins[i] / 2), (void *) ((intptr_t)fftbins[i])); } specCtrlSizer->Add(_freqBinsChoice, 0, wxALL|wxALIGN_CENTER, 2); stattext = new wxStaticText(fftpanel, -1, wxT("Overlap")); specCtrlSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _overlapChoice = new wxChoice(fftpanel, FT_OverlapChoiceId); _overlapChoice->Append(wxT("0 %"), (void *) 1); _overlapChoice->Append(wxT("50 %"), (void *) 2); _overlapChoice->Append(wxT("75 %"), (void *) 4); _overlapChoice->Append(wxT("87.5 %"), (void *) 8); _overlapChoice->Append(wxT("93.75 %"), (void *) 16); _overlapChoice->SetSelection(2); // hack specCtrlSizer->Add(_overlapChoice, 0, wxALL|wxALIGN_CENTER, 2); stattext = new wxStaticText(fftpanel, -1, wxT("Window")); specCtrlSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _windowingChoice = new wxChoice(fftpanel, FT_WindowingChoiceId, wxDefaultPosition, wxSize(100,-1)); const char ** winstrs = FTspectralEngine::getWindowStrings(); for (int i=0; i < FTspectralEngine::getWindowStringsCount(); i++) { #if wxUSE_WCHAR_T wchar_t wstr[1024]; // FIXME: no idea how good this size is wxMB2WC (wstr, winstrs[i], 1024); _windowingChoice->Append(wstr); #else _windowingChoice->Append(winstrs[i]); #endif } _windowingChoice->SetSelection(0); specCtrlSizer->Add(_windowingChoice, 0, wxALL|wxALIGN_CENTER, 2); fftpanel->SetAutoLayout(TRUE); specCtrlSizer->Fit( fftpanel ); fftpanel->SetSizer(specCtrlSizer); ctrlbook->AddPage ( (wxNotebookPage *) fftpanel, wxT("FFT")); // plot page wxPanel * plotpanel = new wxPanel (ctrlbook, -1); wxBoxSizer *plotSizer = new wxBoxSizer(wxHORIZONTAL); stattext = new wxStaticText(plotpanel, -1, wxT("Speed")); plotSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _plotSpeedChoice = new wxChoice(plotpanel, FT_PlotSpeedChoiceId, wxDefaultPosition, wxSize(100,-1)); _plotSpeedChoice->Append(wxT("Turtle"), (void *) FTspectralEngine::SPEED_TURTLE); _plotSpeedChoice->Append(wxT("Slow"), (void *) FTspectralEngine::SPEED_SLOW); _plotSpeedChoice->Append(wxT("Medium"), (void *) FTspectralEngine::SPEED_MED); _plotSpeedChoice->Append(wxT("Fast"), (void *) FTspectralEngine::SPEED_FAST); //_plotSpeedChoice->SetSelection(2); // hack plotSizer->Add(_plotSpeedChoice, 0, wxALL|wxALIGN_CENTER, 2); _superSmoothCheck = new wxCheckBox (plotpanel, FT_PlotSuperSmoothId, wxT("Extra smooth but expensive")); _superSmoothCheck->SetValue(false); plotSizer->Add (_superSmoothCheck, 0, wxALL|wxALIGN_CENTER, 2); plotpanel->SetAutoLayout(TRUE); plotSizer->Fit( plotpanel ); plotpanel->SetSizer(plotSizer); ctrlbook->AddPage ( (wxNotebookPage *) plotpanel, wxT("Plots"), false); // IO page wxPanel * iopanel = new wxPanel (ctrlbook, -1); wxBoxSizer *ioSizer = new wxBoxSizer(wxHORIZONTAL); stattext = new wxStaticText(iopanel, -1, wxT("JACK-Name")); ioSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _ioNameText = new wxTextCtrl (iopanel, FT_IOnameText, wxT(""), wxDefaultPosition, wxSize(150,-1)); ioSizer->Add (_ioNameText, 0, wxALL|wxALIGN_CENTER, 2); wxButton * reconnButton = new wxButton(iopanel, FT_IOreconnectButton, wxT("Reconnect As")); ioSizer->Add (reconnButton, 0, wxALL|wxALIGN_CENTER, 2); wxButton * disconnButton = new wxButton(iopanel, FT_IOdisconnectButton, wxT("Disconnect")); ioSizer->Add (disconnButton, 0, wxALL|wxALIGN_CENTER, 2); iopanel->SetAutoLayout(TRUE); ioSizer->Fit( iopanel ); iopanel->SetSizer(ioSizer); ctrlbook->AddPage ( (wxNotebookPage *) iopanel, wxT("I/O"), false); // time/memory page wxPanel * timepanel = new wxPanel (ctrlbook, -1); wxBoxSizer *timeSizer = new wxBoxSizer(wxHORIZONTAL); stattext = new wxStaticText(timepanel, -1, wxT("Max Delay Time")); timeSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _maxDelayChoice = new wxChoice(timepanel, FT_MaxDelayChoiceId, wxDefaultPosition, wxSize(100,-1)); _maxDelayChoice->Append(wxT("0.5 sec")); _delayList.push_back (0.5); _maxDelayChoice->Append(wxT("1 sec")); _delayList.push_back (1.0); _maxDelayChoice->Append(wxT("2.5 sec")); _delayList.push_back (2.5); _maxDelayChoice->Append(wxT("5 sec")); _delayList.push_back (5.0); _maxDelayChoice->Append(wxT("10 sec")); _delayList.push_back (10.0); _maxDelayChoice->Append(wxT("20 sec")); _delayList.push_back (20.0); timeSizer->Add(_maxDelayChoice, 0, wxALL|wxALIGN_CENTER, 2); stattext = new wxStaticText(timepanel, -1, wxT("Tempo")); timeSizer->Add ( stattext, 0, wxALIGN_CENTER|wxLEFT, 4); _tempoSpinCtrl = new wxSpinCtrl(timepanel, FT_TempoSpinId, wxT("120"), wxDefaultPosition, wxSize(65,-1), wxSP_ARROW_KEYS, 1, 300, 120); timeSizer->Add(_tempoSpinCtrl, 0, wxALL|wxALIGN_CENTER, 2); timepanel->SetAutoLayout(TRUE); timeSizer->Fit( timepanel ); timepanel->SetSizer(timeSizer); ctrlbook->AddPage ( (wxNotebookPage *) timepanel, wxT("Time") , false); wxBoxSizer *booksizer = new wxBoxSizer (wxHORIZONTAL); booksizer->Add (ctrlbook, 1, wxALL, 0); wxStaticBitmap * logobit = new wxStaticBitmap(this, -1, wxBitmap(ftlogo_xpm)); //wxStaticBitmap * logobit = new wxStaticBitmap(this, -1, wxBitmap(ftlogo1_xpm)); //wxStaticBitmap * logobit = new wxStaticBitmap(this, -1, wxBitmap(ftlogo2_xpm)); booksizer->Add (logobit, 0, wxALIGN_BOTTOM); mainsizer->Add ( booksizer, 0, wxALL|wxEXPAND, 2 ); //_rowPanel = new wxPanel(this, -1); _rowPanel = new wxScrolledWindow(this, FT_RowPanel, wxDefaultPosition, wxDefaultSize, wxVSCROLL|wxHSCROLL|wxSUNKEN_BORDER); _rowPanel->SetBackgroundColour(wxColour(20,20,20)); _rowPanel->SetThemeEnabled(false); // ASSUME we have at least one spectral engine FTspectralEngine * sengine = _processPath[0]->getSpectralEngine(); vector<FTprocI *> procmods; sengine->getProcessorModules (procmods); wxBoxSizer *mainvsizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer *tmpsizer, *tmpsizer2; _uppersizer = new wxBoxSizer(wxHORIZONTAL); _inspecsizer = new wxBoxSizer(wxHORIZONTAL); _inspecSash = new wxSashLayoutWindow(_rowPanel, FT_RowPanelId, wxDefaultPosition, wxSize(-1,_rowh)); _inspecSash->SetBackgroundColour(*wxBLACK); _inspecSash->SetThemeEnabled(false); _inspecPanel = new wxPanel(_inspecSash, -1); _inspecPanel->SetBackgroundColour(*wxBLACK); _inspecPanel->SetThemeEnabled(false); _inspecSash->SetSashVisible(wxSASH_BOTTOM, true); _rowItems.push_back( _inspecSash); // create master link and bypass buttons _inspecLabelButton = new wxButton(_inspecPanel, FT_InSpecLabelId, wxT("In Spectra"), wxDefaultPosition, wxSize(_labwidth,_bheight)); _inspecLabelButton->SetBackgroundColour(*wxBLACK); _inspecLabelButton->SetForegroundColour(*wxWHITE); _inspecLabelButton->SetThemeEnabled(false); _inspecLabelButton->SetFont(_titleFont); _inspecLabelButton->SetToolTip(wxT("Hide In Spectra")); wxLayoutConstraints * constr; // create alts _inspecLabelButtonAlt = new wxButton(_rowPanel, FT_InSpecLabelId, wxT("In Spectra"), wxDefaultPosition, wxSize(_labwidth,_bheight)); _inspecLabelButtonAlt->SetBackgroundColour(*wxBLACK); _inspecLabelButtonAlt->SetForegroundColour(*wxWHITE); _inspecLabelButtonAlt->SetThemeEnabled(false); _inspecLabelButtonAlt->SetFont(_titleAltFont); _inspecLabelButtonAlt->SetToolTip(wxT("Show In Spectra")); _inspecLabelButtonAlt->Show(false); constr = new wxLayoutConstraints; constr->left.SameAs (_rowPanel, wxLeft, 2); constr->width.Absolute (_labwidth); constr->top.SameAs (_rowPanel, wxTop); constr->height.Absolute (_bheight); _inspecLabelButtonAlt->SetConstraints(constr); _bypassAllCheck = new wxCheckBox(this, FT_BypassId, wxT("Bypass All"), wxDefaultPosition, wxSize(_labwidth,_bheight+3)); _bypassAllCheck->SetFont(_buttFont); _muteAllCheck = new wxCheckBox(this, FT_MuteId, wxT("Mute All"), wxDefaultPosition, wxSize(_labwidth,_bheight+3)); _muteAllCheck->SetFont(_buttFont); _linkMixCheck = new wxCheckBox(this, FT_MixLinkedButton, wxT("Link Mix"), wxDefaultPosition, wxSize(_labwidth,_bheight+3)); _linkMixCheck->SetFont(_buttFont); _pathCountChoice = new wxChoice(this, FT_PathCountChoice, wxDefaultPosition, wxSize(_labwidth,-1)); for (int i=0; i < FT_MAXPATHS; i++) { _pathCountChoice->Append(wxString::Format(wxT("%d chan"), i+1), (void *) ((intptr_t)(i+1))); } _pathCountChoice->SetStringSelection(wxString::Format(wxT("%d chan"), _startpaths)); // spec types buttons PixButton * pixbutt; pixbutt = _inspecSpecTypeAllButton = new PixButton(_inspecPanel, FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecSpecTypeAllButton->SetFont(_buttFont); _inspecSpecTypeAllButton->SetToolTip (wxT("Spectrogram Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(specplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(specplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(specplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(specplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(specplot_active_xpm)); pixbutt = _inspecPlotSolidTypeAllButton = new PixButton(_inspecPanel, FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecPlotSolidTypeAllButton->SetFont(_buttFont); _inspecPlotSolidTypeAllButton->SetToolTip (wxT("Filled Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(barplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(barplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(barplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(barplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(barplot_active_xpm)); pixbutt = _inspecPlotLineTypeAllButton = new PixButton(_inspecPanel, FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecPlotLineTypeAllButton->SetFont(_buttFont); _inspecPlotLineTypeAllButton->SetToolTip (wxT("Line Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(lineplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(lineplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(lineplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(lineplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(lineplot_active_xpm)); // uppersizer tmpsizer = new wxBoxSizer(wxVERTICAL); tmpsizer->Add (_pathCountChoice, 0, wxALL, 1); tmpsizer->Add (1,4, 0); tmpsizer->Add (_bypassAllCheck, 0, wxALL, 1 ); _uppersizer->Add(tmpsizer, 0, wxEXPAND); mainvsizer->Add(_uppersizer, 0, wxLEFT|wxRIGHT|wxBOTTOM|wxEXPAND, 2); // input spectragram tmpsizer = new wxBoxSizer(wxVERTICAL); tmpsizer->Add (_inspecLabelButton, 0, wxALL , 1); tmpsizer2 = new wxBoxSizer(wxHORIZONTAL); tmpsizer2->Add (_inspecSpecTypeAllButton, 0, wxALL, 1); tmpsizer2->Add (_inspecPlotLineTypeAllButton, 0, wxALL, 1); tmpsizer2->Add (_inspecPlotSolidTypeAllButton, 0, wxALL, 1); tmpsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 0); _inspecsizer->Add (tmpsizer, 0, wxALL|wxEXPAND, 0); _inspecPanel->SetAutoLayout(TRUE); _inspecsizer->Fit( _inspecPanel ); _inspecPanel->SetSizer(_inspecsizer); wxLayoutConstraints *inspecConst = new wxLayoutConstraints; inspecConst->top.SameAs (_rowPanel, wxTop, 2); inspecConst->left.SameAs (_rowPanel, wxLeft, 2); inspecConst->right.SameAs (_rowPanel, wxRight, 2); inspecConst->height.AsIs(); _inspecSash->SetConstraints(inspecConst); //_inspecSash->Show(false); // NOTE: need to create and push this onto rowItems // before calling pushProcRow _outspecsizer = new wxBoxSizer(wxHORIZONTAL); _lowersizer = new wxBoxSizer(wxHORIZONTAL); _outspecSash = new wxSashLayoutWindow(_rowPanel, FT_RowPanelId, wxDefaultPosition, wxSize(-1,_rowh)); _outspecPanel = new wxPanel(_outspecSash, -1); _outspecPanel->SetBackgroundColour(*wxBLACK); _outspecPanel->SetThemeEnabled(false); _outspecSash->SetSashVisible(wxSASH_BOTTOM, true); _rowItems.push_back (_outspecSash); wxWindow *lastsash = _inspecSash; int rowcnt=0; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { // if the group is different from the last // make a new row for it if (filts[m]->getGroup() == lastgroup) { continue; } lastgroup = filts[m]->getGroup(); pushProcRow (filts[m]); lastsash = _rowSashes[rowcnt]; rowcnt++; } } //_mashsizer = new wxBoxSizer(wxHORIZONTAL); // _gatesizer = new wxBoxSizer(wxHORIZONTAL); // _freqsizer = new wxBoxSizer(wxHORIZONTAL); // _delaysizer = new wxBoxSizer(wxHORIZONTAL); // _feedbsizer = new wxBoxSizer(wxHORIZONTAL); //printf ("subrowpanel cnt = %d\n", _subrowPanels.size()); _outspecLabelButton = new wxButton(_outspecPanel, FT_OutSpecLabelId, wxT("Out Spectra"), wxDefaultPosition, wxSize(_labwidth,_bheight)); _outspecLabelButton->SetBackgroundColour(*wxBLACK); _outspecLabelButton->SetForegroundColour(*wxWHITE); _outspecLabelButton->SetThemeEnabled(false); _outspecLabelButton->SetFont(_titleFont); _outspecLabelButton->SetToolTip(wxT("Hide Out Spectra")); _outspecLabelButtonAlt = new wxButton(_rowPanel, FT_OutSpecLabelId, wxT("Out Spectra"), wxDefaultPosition, wxSize(_labwidth,_bheight)); _outspecLabelButtonAlt->SetFont(_titleAltFont); _outspecLabelButtonAlt->SetToolTip(wxT("Show Out Spectra")); _outspecLabelButtonAlt->SetBackgroundColour(*wxBLACK); _outspecLabelButtonAlt->SetForegroundColour(*wxWHITE); //_outspecLabelButtonAlt->SetThemeEnabled(false); _outspecLabelButtonAlt->Show(false); constr = new wxLayoutConstraints; constr->left.SameAs (_rowPanel, wxLeft, 2); constr->width.Absolute (_labwidth); constr->height.Absolute (_bheight); constr->top.SameAs (_outspecSash, wxTop); _outspecLabelButtonAlt->SetConstraints(constr); // @@@@@@@ pixbutt = _outspecSpecTypeAllButton = new PixButton(_outspecPanel, FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecSpecTypeAllButton->SetFont(_buttFont); _outspecSpecTypeAllButton->SetToolTip (wxT("Spectrogram Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(specplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(specplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(specplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(specplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(specplot_active_xpm)); pixbutt = _outspecPlotSolidTypeAllButton = new PixButton(_outspecPanel, FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecPlotSolidTypeAllButton->SetFont(_buttFont); _outspecPlotSolidTypeAllButton->SetToolTip (wxT("Filled Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(barplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(barplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(barplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(barplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(barplot_active_xpm)); pixbutt = _outspecPlotLineTypeAllButton = new PixButton(_outspecPanel, FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecPlotLineTypeAllButton->SetFont(_buttFont); _outspecPlotLineTypeAllButton->SetToolTip (wxT("Line Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(lineplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(lineplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(lineplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(lineplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(lineplot_active_xpm)); // output spectragram tmpsizer = new wxBoxSizer(wxVERTICAL); tmpsizer->Add (_outspecLabelButton, 0, wxALL , 1); tmpsizer2 = new wxBoxSizer(wxHORIZONTAL); tmpsizer2->Add (_outspecSpecTypeAllButton, 1, wxALL, 1); tmpsizer2->Add (_outspecPlotLineTypeAllButton, 1, wxALL, 1); tmpsizer2->Add (_outspecPlotSolidTypeAllButton, 1, wxALL, 1); tmpsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 0); _outspecsizer->Add (tmpsizer, 0, wxALL|wxEXPAND, 0); _outspecPanel->SetAutoLayout(TRUE); _outspecsizer->Fit( _outspecPanel ); _outspecPanel->SetSizer(_outspecsizer); wxLayoutConstraints *outspecConst = new wxLayoutConstraints; outspecConst->left.SameAs (_rowPanel, wxLeft, 2); outspecConst->right.SameAs (_rowPanel, wxRight, 2); outspecConst->top.SameAs (lastsash, wxBottom, 2); outspecConst->height.AsIs(); _outspecSash->SetConstraints(outspecConst); //_outspecSash->Show(false); _rowPanel->SetAutoLayout(TRUE); mainvsizer->Add (_rowPanel, 1, wxLEFT|wxRIGHT|wxBOTTOM|wxEXPAND, 2); // lowersizer tmpsizer = new wxBoxSizer(wxVERTICAL); tmpsizer->Add (1,10,0); tmpsizer->Add (_muteAllCheck, 0, wxALL, 1); tmpsizer->Add (_linkMixCheck, 0, wxALL, 1); _lowersizer->Add(tmpsizer, 0, wxEXPAND); mainvsizer->Add(_lowersizer, 0, wxLEFT|wxRIGHT|wxBOTTOM|wxEXPAND, 2); for (int i=0; i < _startpaths; i++) { // add to io support instance //_processPath[i] = iosup->setProcessPathActive (i, true); if (!_processPath[i]) continue; FTspectralEngine * engine = _processPath[i]->getSpectralEngine(); // set default freqbin _freqBinsChoice->SetStringSelection(wxString::Format(wxT("%d"), engine->getFFTsize()/2)); engine->setUpdateToken (_updateTokens[i]); createPathStuff (i); engine->setTempo (_tempoSpinCtrl->GetValue()); // purely for saving if (i > 0) { // link everything to first vector<FTprocI *> newprocmods; engine->getProcessorModules (newprocmods); for (unsigned int n=0; n < newprocmods.size(); ++n) { FTprocI *pm = newprocmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); for (unsigned int m=0; m < filts.size(); ++m) { filts[m]->link (procmods[n]->getFilter(m)); } } } } rebuildPresetCombo(); mainsizer->Add(mainvsizer, 1, wxALL|wxEXPAND, 0); SetAutoLayout( TRUE ); // set frame to minimum size mainsizer->Fit( this ); // don't allow frame to get smaller than what the sizers tell ye mainsizer->SetSizeHints( this ); SetSizer( mainsizer ); rowpanelScrollSize(); //wxToolTip::Enable(true); // force a nice minimum size this->SetSizeHints(453,281); // set timer _eventTimer->Start(_updateMS, FALSE); _refreshTimer->Start(_refreshMS, FALSE); } void FTmainwin::pushProcRow(FTspectrumModifier *specmod) { wxSashLayoutWindow * lastsash; if (_rowSashes.size() == 0) { lastsash = _inspecSash; } else { lastsash = _rowSashes.back(); } wxBoxSizer *rowsizer = new wxBoxSizer(wxHORIZONTAL); _rowSizers.push_back (rowsizer); wxSashLayoutWindow * sash = new wxSashLayoutWindow(_rowPanel, FT_RowPanelId, wxDefaultPosition, wxSize(-1,_rowh)); sash->SetBackgroundColour(wxColour(20,20,20)); sash->SetThemeEnabled(false); _rowSashes.push_back (sash); wxPanel * rpanel = new wxPanel(sash, -1); rpanel->SetBackgroundColour(*wxBLACK); rpanel->SetThemeEnabled(false); _rowPanels.push_back (rpanel); sash->SetSashVisible(wxSASH_BOTTOM, true); // need to insert this as second to last wxWindow * lastrow = _rowItems.back(); _rowItems.pop_back(); _rowItems.push_back (sash); _rowItems.push_back (lastrow); string name = specmod->getName(); // main label button wxButton *labbutt = new FTtitleButton(this, false, rpanel, FT_LabelBase, wxString::FromAscii (name.c_str()), wxDefaultPosition, wxSize(_labwidth,_bheight)); labbutt->SetFont(_titleFont); labbutt->SetToolTip(wxString(wxT("Hide ")) + wxString::FromAscii (name.c_str()) + wxT("\nRight-click for menu")); _labelButtons.push_back (labbutt); // alt label button wxButton * altlab = new FTtitleButton(this, true, _rowPanel, FT_LabelBase, wxString::FromAscii (name.c_str()), wxDefaultPosition, wxSize(_labwidth,_bheight)); altlab->SetFont(_titleAltFont); altlab->SetToolTip(wxString(wxT("Show ")) + wxString::FromAscii (name.c_str()) + wxT("\nRight-click for menu")); altlab->Show(false); wxLayoutConstraints * constr = new wxLayoutConstraints; constr->left.SameAs (_rowPanel, wxLeft, 2); constr->width.Absolute (_labwidth); constr->height.Absolute (_bheight); constr->top.SameAs (sash, wxTop); altlab->SetConstraints(constr); _altLabelButtons.push_back (altlab); // link all button PixButton * pixbutt; PixButton * linkallbutt = pixbutt = new PixButton(rpanel, FT_LinkBase, false, wxDefaultPosition, wxSize(_bwidth,_bheight)); linkallbutt->SetFont(_buttFont); linkallbutt->SetToolTip (wxT("Link All")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::link_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(link_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(link_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(link_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(link_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(link_active_xpm)); _linkAllButtons.push_back (linkallbutt); // bypass all button PixButton * bypallbutt = pixbutt = new PixButton(rpanel, FT_BypassBase, false, wxDefaultPosition, wxSize(_bwidth,_bheight)); bypallbutt->SetFont(_buttFont); bypallbutt->SetToolTip (wxT("Bypass All")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::bypass_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(bypass_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(bypass_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(bypass_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(bypass_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(bypass_active_xpm)); _bypassAllButtons.push_back (bypallbutt); // Grid buttons PixButton * gridbutt = pixbutt = new PixButton (rpanel, FT_GridBase, false, wxDefaultPosition, wxSize(_bwidth,_bheight)); gridbutt->SetFont(_buttFont); gridbutt->SetToolTip (wxT("Toggle Grid\nRight-click to Adjust")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::grid_clicked_events), pixbutt)); pixbutt->pressed.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::grid_pressed_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(grid_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(grid_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(grid_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(grid_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(grid_active_xpm)); _gridButtons.push_back (gridbutt); // GridSnap buttons PixButton * gridsnbutt = pixbutt = new PixButton (rpanel, FT_GridSnapBase, false, wxDefaultPosition, wxSize(_bwidth,_bheight)); gridsnbutt->SetFont(_buttFont); gridsnbutt->SetToolTip (wxT("Toggle Grid Snap")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::grid_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(gridsnap_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(gridsnap_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(gridsnap_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(gridsnap_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(gridsnap_active_xpm)); _gridSnapButtons.push_back (gridsnbutt); // main row stuff wxBoxSizer * rowbuttsizer = new wxBoxSizer(wxVERTICAL); rowbuttsizer->Add (labbutt, 0, wxALL , 1); wxBoxSizer * tmpsizer2 = new wxBoxSizer(wxHORIZONTAL); tmpsizer2->Add (bypallbutt, 0, wxALL, 1); tmpsizer2->Add (linkallbutt, 0, wxALL, 1); rowbuttsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 0); tmpsizer2 = new wxBoxSizer(wxHORIZONTAL); tmpsizer2->Add (gridbutt, 0, wxALL, 1); tmpsizer2->Add (gridsnbutt, 0, wxALL, 1); rowbuttsizer->Add (tmpsizer2, 0, wxALL|wxEXPAND, 0); _rowButtSizers.push_back ( rowbuttsizer); rowsizer->Add (rowbuttsizer, 0, wxALL|wxEXPAND, 0); rpanel->SetAutoLayout(TRUE); rowsizer->Fit( rpanel ); rpanel->SetSizer(rowsizer); wxLayoutConstraints *rowconst = new wxLayoutConstraints; rowconst->left.SameAs (_rowPanel, wxLeft, 2); rowconst->right.SameAs (_rowPanel, wxRight, 2); rowconst->top.SameAs (lastsash, wxBottom, 2); rowconst->height.AsIs(); sash->SetConstraints(rowconst); // construct initial arrays FTactiveBarGraph ** bgraphs = new FTactiveBarGraph*[FT_MAXPATHS]; for (int n=0; n < FT_MAXPATHS; ++n) bgraphs[n] = 0; _barGraphs.push_back (bgraphs); wxPanel ** srpanels = new wxPanel*[FT_MAXPATHS]; for (int n=0; n < FT_MAXPATHS; ++n) srpanels[n] = 0; _subrowPanels.push_back (srpanels); PixButton ** bybuttons = new PixButton*[FT_MAXPATHS]; for (int n=0; n < FT_MAXPATHS; ++n) bybuttons[n] = 0; _bypassButtons.push_back (bybuttons); PixButton ** linkbuttons = new PixButton*[FT_MAXPATHS]; for (int n=0; n < FT_MAXPATHS; ++n) linkbuttons[n] = 0; _linkButtons.push_back (linkbuttons); } void FTmainwin::popProcRow() { // remove the last row of stuff wxWindow * top = _rowSashes.back(); //wxSizer * topsizer = _rowSizers.back(); //wxPanel * rpanel = _rowPanels.back(); // pop all the stuff we pushed before _rowSizers.pop_back(); _rowSashes.pop_back(); _rowPanels.pop_back(); // need to pop the second to last off _rowItems.pop_back(); _rowItems.pop_back(); _rowItems.push_back(_outspecSash); _labelButtons.pop_back(); _bypassAllButtons.pop_back(); _linkAllButtons.pop_back(); _rowButtSizers.pop_back(); _gridButtons.pop_back(); _gridSnapButtons.pop_back(); // owned by _rowPanel wxButton * altbutt = _altLabelButtons.back(); altbutt->SetConstraints(NULL); altbutt->Destroy(); _altLabelButtons.pop_back(); FTactiveBarGraph **bgraphs = _barGraphs.back(); delete [] bgraphs; _barGraphs.pop_back(); wxPanel **srpanels = _subrowPanels.back(); delete [] srpanels; _subrowPanels.pop_back(); PixButton **bybuttons = _bypassButtons.back(); delete [] bybuttons; _bypassButtons.pop_back(); PixButton **linkbuttons = _linkButtons.back(); delete [] linkbuttons; _linkButtons.pop_back(); wxLayoutConstraints * outspecConst = _outspecSash->GetConstraints(); if (_rowSashes.size() > 0) { outspecConst->top.SameAs (_rowSashes.back(), wxBottom, 2); _outspecLabelButtonAlt->GetConstraints()->top.Below(_rowSashes.back(), 2); } else { outspecConst->top.SameAs (_inspecSash, wxBottom, 2); _outspecLabelButtonAlt->GetConstraints()->top.Below(_inspecSash, 2); } // this should destroy all the wx windows and stuff top->SetConstraints(NULL); top->Destroy(); _rowPanel->Layout(); rowpanelScrollSize(); } // void FTmainwin::OnSize(wxSizeEvent &event) // { // // rowpanelScrollSize(); // event.Skip(); // } void FTmainwin::removePathStuff(int i, bool deactivate) { FTspectralEngine * engine = _processPath[i]->getSpectralEngine(); if (deactivate) { // deactivate it by the io thread FTioSupport::instance()->setProcessPathActive(i, false); _processPath[i] = 0; } vector<FTprocI *> procmods; engine->getProcessorModules (procmods); _uppersizer->Remove(i+1); _inspecsizer->Remove(i+1); for (unsigned int n=0; n < _rowSizers.size(); ++n) { _rowSizers[n]->Remove (i+1); _subrowPanels[n][i]->Destroy(); _rowSizers[n]->Layout(); } // unsigned int rowcnt = 0; // for (unsigned int n=0; n < procmods.size(); ++n) // { // FTprocI *pm = procmods[n]; // vector<FTspectrumModifier *> filts; // pm->getFilters (filts); // int lastgroup=-1; // for (unsigned int m=0; m < filts.size(); ++m) // { // if (filts[m]->getGroup() == lastgroup) { // continue; // } // lastgroup = filts[m]->getGroup(); // _rowSizers[rowcnt]->Remove (i+1); // _subrowPanels[rowcnt][i]->Destroy(); // _rowSizers[rowcnt]->Layout(); // rowcnt++; // } // } _outspecsizer->Remove(i+1); _lowersizer->Remove(i+1); _upperPanels[i]->Destroy(); _inspecPanels[i]->Destroy(); _outspecPanels[i]->Destroy(); _lowerPanels[i]->Destroy(); _uppersizer->Layout(); _inspecsizer->Layout(); _outspecsizer->Layout(); _lowersizer->Layout(); } void FTmainwin::createPathStuff(int i) { wxBoxSizer * buttsizer, *tmpsizer, *tmpsizer2; wxStaticText *stattext; FTspectralEngine * engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); _upperPanels[i] = new wxPanel(this, -1); _lowerPanels[i] = new wxPanel(this, -1); _inspecPanels[i] = new wxPanel(_inspecPanel, -1); _inspecPanels[i]->SetBackgroundColour(*wxBLACK); _inspecPanels[i]->SetThemeEnabled(false); int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { wxPanel ** rowpanels = 0; FTactiveBarGraph **bargraphs = 0; if (filts[m]->getGroup() != lastgroup) { rowcnt++; rowpanels = _subrowPanels[rowcnt]; bargraphs = _barGraphs[rowcnt]; rowpanels[i] = new wxPanel (_rowPanels[rowcnt], -1); rowpanels[i]->SetBackgroundColour(*wxBLACK); rowpanels[i]->SetThemeEnabled(false); bargraphs[i] = new FTactiveBarGraph(this, rowpanels[i], -1); bargraphs[i]->setSpectrumModifier (filts[m]); bargraphs[i]->setBypassed (filts[m]->getBypassed()); bargraphs[i]->setTempo(_tempoSpinCtrl->GetValue()); lastgroup = filts[m]->getGroup(); } else { // assign nth filter to already created plot // TODO: support more than 2 rowpanels = _subrowPanels[rowcnt]; bargraphs = _barGraphs[rowcnt]; bargraphs[i]->setTopSpectrumModifier (filts[m]); continue; } buttsizer = new wxBoxSizer(wxVERTICAL); PixButton * pixbutt; pixbutt = new PixButton(rowpanels[i], FT_BypassBase, false, wxDefaultPosition, wxSize(_bwidth, -1)); pixbutt->set_normal_bitmap (wxBitmap(bypass_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(bypass_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(bypass_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(bypass_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(bypass_active_xpm)); _bypassButtons[rowcnt][i] = pixbutt; //buttsizer->Add ( _bypassButtons[rowcnt][i] = new wxButton(rowpanels[i], FT_BypassBase, wxT("B"), // wxDefaultPosition, wxSize(_bwidth,-1)), 1, 0,0); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::bypass_clicked_events), pixbutt)); buttsizer->Add (pixbutt, 0, 0, 0); //buttsizer->Add ( _bypassButtons[rowcnt][i] = new wxButton(rowpanels[i], FT_BypassBase, wxT("B"), // wxDefaultPosition, wxSize(_bwidth,-1)), 1, 0,0); _bypassButtons[rowcnt][i]->SetFont(_buttFont); _bypassButtons[rowcnt][i]->SetToolTip(wxT("Toggle Bypass")); pixbutt = new PixButton(rowpanels[i], FT_LinkBase, false, wxDefaultPosition, wxSize(_bwidth, -1)); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::link_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(link_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(link_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(link_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(link_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(link_active_xpm)); _linkButtons[rowcnt][i] = pixbutt; //buttsizer->Add ( _linkButtons[rowcnt][i] = new wxButton(rowpanels[i], FT_LinkBase, wxT("L"), // wxDefaultPosition, wxSize(_bwidth,-1)), 0, wxTOP,3); buttsizer->Add (_linkButtons[rowcnt][i], 0, wxTOP, 3); _linkButtons[rowcnt][i]->SetFont(_buttFont); _linkButtons[rowcnt][i]->SetToolTip(wxT("Link")); tmpsizer = new wxBoxSizer(wxHORIZONTAL); tmpsizer->Add ( buttsizer, 0, wxALL|wxEXPAND, 1); tmpsizer->Add ( bargraphs[i], 1, wxALL|wxEXPAND, 1); rowpanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( rowpanels[i] ); rowpanels[i]->SetSizer(tmpsizer); _rowSizers[rowcnt]->Insert (i+1, rowpanels[i], 1, wxLEFT|wxEXPAND, 4); } } _outspecPanels[i] = new wxPanel(_outspecPanel, -1); _outspecPanels[i]->SetBackgroundColour(*wxBLACK); _outspecPanels[i]->SetThemeEnabled(false); wxStaticBox *inbox = new wxStaticBox(_upperPanels[i], -1, wxString::Format(wxT("Input %d"), i+1)); wxStaticBox *outbox = new wxStaticBox(_lowerPanels[i], -1, wxString::Format(wxT("Output %d"), i+1)); // plots and active graphs _inputSpectragram[i] = new FTspectragram(this, _inspecPanels[i], -1); _inputSpectragram[i]->setDataLength((unsigned int)engine->getFFTsize() >> 1); _outputSpectragram[i] = new FTspectragram(this, _outspecPanels[i], -1); _outputSpectragram[i]->setDataLength((unsigned int)engine->getFFTsize() >> 1); // I/O buttons _inputButton[i] = new wxButton(_upperPanels[i], (int) FT_InputButtonId, wxT("No Input"), wxDefaultPosition, wxSize(-1,-1)); _outputButton[i] = new wxButton(_lowerPanels[i], (int) FT_OutputButtonId, wxT("No Output"), wxDefaultPosition, wxSize(-1,-1)); _bypassCheck[i] = new wxCheckBox(_upperPanels[i], (int) FT_BypassId, wxT("Bypass"), wxDefaultPosition, wxSize(-1,-1)); _muteCheck[i] = new wxCheckBox(_lowerPanels[i], (int) FT_MuteId, wxT("Mute"), wxDefaultPosition, wxSize(-1,-1)); // input area { tmpsizer = new wxStaticBoxSizer (inbox, wxVERTICAL); tmpsizer->Add (_inputButton[i], 0, wxBOTTOM|wxEXPAND, 1); tmpsizer2 = new wxBoxSizer (wxHORIZONTAL); tmpsizer2->Add (_bypassCheck[i], 1, wxRIGHT|wxALIGN_CENTRE_VERTICAL, 3); stattext = new wxStaticText(_upperPanels[i], -1, wxT("Gain (dB)"), wxDefaultPosition, wxDefaultSize); tmpsizer2->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 0); //_gainSlider[i] = new wxSlider(this, FT_GainSlider, 0, -70, 10); //tmpsizer2->Add (_gainSlider[i], 1, wxALL|wxALIGN_CENTRE_VERTICAL, 1); _gainSpinCtrl[i] = new wxSpinCtrl(_upperPanels[i], FT_GainSpin, wxT("0"), wxDefaultPosition, wxSize(65,-1), wxSP_ARROW_KEYS, -70, 10, 0); tmpsizer2->Add (_gainSpinCtrl[i], 0, wxLEFT, 4); tmpsizer->Add (tmpsizer2, 0, wxTOP|wxEXPAND, 1); _upperPanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( _upperPanels[i] ); _upperPanels[i]->SetSizer(tmpsizer); _uppersizer->Insert (i+1, _upperPanels[i], 1, wxLEFT, 3); } // input spec { buttsizer = new wxBoxSizer(wxVERTICAL); PixButton * pixbutt; pixbutt = _inspecSpecTypeButton[i] = new PixButton(_inspecPanels[i], FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecSpecTypeButton[i]->SetFont(_buttFont); _inspecSpecTypeButton[i]->SetToolTip(wxT("Spectrogram Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(specplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(specplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(specplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(specplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(specplot_active_xpm)); buttsizer->Add ( _inspecSpecTypeButton[i], 0, wxALL , 1); pixbutt = _inspecPlotLineTypeButton[i] = new PixButton(_inspecPanels[i], FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecPlotLineTypeButton[i]->SetFont(_buttFont); _inspecPlotLineTypeButton[i]->SetToolTip(wxT("Line Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(lineplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(lineplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(lineplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(lineplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(lineplot_active_xpm)); buttsizer->Add ( _inspecPlotLineTypeButton[i], 0, wxALL , 1); pixbutt = _inspecPlotSolidTypeButton[i] = new PixButton(_inspecPanels[i], FT_InSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _inspecPlotSolidTypeButton[i]->SetFont(_buttFont); _inspecPlotSolidTypeButton[i]->SetToolTip(wxT("Filled Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(barplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(barplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(barplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(barplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(barplot_active_xpm)); buttsizer->Add ( _inspecPlotSolidTypeButton[i], 0, wxALL ,1); tmpsizer = new wxBoxSizer(wxHORIZONTAL); tmpsizer->Add ( buttsizer, 0, wxALL|wxEXPAND, 0); tmpsizer->Add ( _inputSpectragram[i], 1, wxALL|wxEXPAND, 1); _inspecPanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( _inspecPanels[i] ); _inspecPanels[i]->SetSizer(tmpsizer); _inspecsizer->Insert (i+1, _inspecPanels[i], 1, wxLEFT|wxEXPAND, 4); } // output spec { buttsizer = new wxBoxSizer(wxVERTICAL); PixButton * pixbutt; pixbutt = _outspecSpecTypeButton[i] = new PixButton(_outspecPanels[i], FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecSpecTypeButton[i]->SetFont(_buttFont); _outspecSpecTypeButton[i]->SetToolTip(wxT("Spectrogram Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(specplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(specplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(specplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(specplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(specplot_active_xpm)); buttsizer->Add ( _outspecSpecTypeButton[i], 0, wxALL,1); pixbutt = _outspecPlotLineTypeButton[i] = new PixButton(_outspecPanels[i], FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecPlotLineTypeButton[i]->SetFont(_buttFont); _outspecPlotLineTypeButton[i]->SetToolTip(wxT("Line Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(lineplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(lineplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(lineplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(lineplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(lineplot_active_xpm)); buttsizer->Add ( _outspecPlotLineTypeButton[i], 0, wxALL, 1); pixbutt = _outspecPlotSolidTypeButton[i] = new PixButton(_outspecPanels[i], FT_OutSpecTypeId, false, wxDefaultPosition, wxSize(_bwidth, _bheight)); _outspecPlotSolidTypeButton[i]->SetFont(_buttFont); _outspecPlotSolidTypeButton[i]->SetToolTip(wxT("Filled Plot")); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::plot_clicked_events), pixbutt)); pixbutt->set_normal_bitmap (wxBitmap(barplot_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(barplot_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(barplot_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(barplot_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(barplot_active_xpm)); buttsizer->Add ( _outspecPlotSolidTypeButton[i], 0, wxALL, 1); tmpsizer = new wxBoxSizer(wxHORIZONTAL); tmpsizer->Add ( buttsizer, 0, wxALL|wxEXPAND, 0); tmpsizer->Add ( _outputSpectragram[i], 1, wxALL|wxEXPAND, 1); _outspecPanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( _outspecPanels[i] ); _outspecPanels[i]->SetSizer(tmpsizer); _outspecsizer->Insert (i+1, _outspecPanels[i], 1, wxLEFT|wxEXPAND, 4); } // output stuff { tmpsizer = new wxStaticBoxSizer (outbox, wxVERTICAL); tmpsizer2 = new wxBoxSizer (wxHORIZONTAL); tmpsizer2->Add (_muteCheck[i], 1, wxRIGHT, 5); stattext = new wxStaticText(_lowerPanels[i], -1, wxT("Dry"), wxDefaultPosition, wxDefaultSize); tmpsizer2->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 1); _mixSlider[i] = new wxSlider(_lowerPanels[i], FT_MixSlider, 1000, 0, 1000); tmpsizer2->Add (_mixSlider[i], 2, wxALL|wxALIGN_CENTRE_VERTICAL, 1); stattext = new wxStaticText(_lowerPanels[i], -1, wxT("Wet"), wxDefaultPosition, wxDefaultSize); tmpsizer2->Add (stattext, 0, wxALL|wxALIGN_CENTRE_VERTICAL, 1); tmpsizer->Add (tmpsizer2, 0, wxBOTTOM|wxEXPAND, 1); tmpsizer->Add(_outputButton[i], 0, wxEXPAND|wxTOP, 1); _lowerPanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( _lowerPanels[i] ); _lowerPanels[i]->SetSizer(tmpsizer); _lowersizer->Insert (i+1, _lowerPanels[i], 1, wxLEFT, 3); } engine->setUpdateToken (_updateTokens[i]); } void FTmainwin::rowpanelScrollSize() { //int mw, mh; //int w, h; //int vw, vh; //GetClientSize(&mw, &mh); //_rowPanel->GetClientSize(&w, &h); //_rowPanel->GetVirtualSize(&vw, &vh); // calculate virtual full height of rowpanel int realh = 0; for (unsigned int i=0; i < _rowItems.size(); i++) { // printf ("rowpanelsize: %d %d\n", i, _rowItems.size()); realh += _rowItems[i]->GetSize().GetHeight() + 2; } //printf ("rowpanel size %d %d %d %d realh %d\n", w, h, vw, vh, realh); _rowPanel->SetScrollbars(1, 1, 0, realh); } void FTmainwin::updateDisplay() { FTioSupport *iosup = FTioSupport::instance(); const char ** portnames = 0; bool inspec=true, inplotline=true, inplotsolid=true; bool outspec=true, outplotline=true, outplotsolid=true; bool bypassed=true, muted=true, linked, active; vector<bool> bypvec(_rowSizers.size(), true); vector<bool> linkvec(_rowSizers.size(), true); vector<bool> gridvec(_rowSizers.size(), true); vector<bool> gridsnapvec(_rowSizers.size(), true); for (int i=0; i<_pathCount; i++) { if (!_processPath[i]) continue; // update port button labels portnames = iosup->getConnectedInputPorts(i); if (portnames) { _inputButton[i]->SetLabel (wxString::FromAscii (portnames[0])); free(portnames); } else { _inputButton[i]->SetLabel (wxT("No Input")); } portnames = iosup->getConnectedOutputPorts(i); if (portnames) { _outputButton[i]->SetLabel (wxString::FromAscii (portnames[0])); free(portnames); } else { _outputButton[i]->SetLabel (wxT("No Output")); } // update bypass and link buttons FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() == lastgroup) { // the first of any group will do continue; } lastgroup = filts[m]->getGroup(); //_bypassButtons[rowcnt][i]->SetBackgroundColour ((filts[m]->getBypassed() ? (_activeBg) : (_defaultBg))); _bypassButtons[rowcnt][i]->set_active (filts[m]->getBypassed()); if (bypvec[rowcnt] && !filts[m]->getBypassed()) bypvec[rowcnt] = false; linked = ( filts[m]->getLink()!=0 || filts[m]->getLinkedFrom().size() > 0); //_linkButtons[rowcnt][i]->SetBackgroundColour ((linked ? (_activeBg) : (_defaultBg))); _linkButtons[rowcnt][i]->set_active (linked); if (linkvec[rowcnt] && i!=0 && !linked) linkvec[rowcnt] = false; if (gridvec[rowcnt] && !_barGraphs[rowcnt][i]->getGridLines()) gridvec[rowcnt] = false; if (gridsnapvec[rowcnt] && !_barGraphs[rowcnt][i]->getGridSnap()) gridsnapvec[rowcnt] = false; if (_barGraphs[rowcnt][i]->getTempo() != engine->getTempo()) { _barGraphs[rowcnt][i]->setTempo(engine->getTempo()); } rowcnt++; } } _bypassCheck[i]->SetValue(engine->getBypassed()); if (!engine->getBypassed()) bypassed = false; _muteCheck[i]->SetValue(engine->getMuted()); if (!engine->getMuted()) muted = false; // sliders and stuff _gainSpinCtrl[i]->SetValue ((int) (20 * FTutils::fast_log10 ( engine->getInputGain() ))); _mixSlider[i]->SetValue ((int) ( engine->getMixRatio() * 1000 )); // plots active = _inputSpectragram[i]->getPlotType()==FTspectragram::SPECTRAGRAM; _inspecSpecTypeButton[i]->set_active (active); if (inspec && !active) inspec = false; active = _inputSpectragram[i]->getPlotType()==FTspectragram::AMPFREQ_SOLID; _inspecPlotSolidTypeButton[i]->set_active (active); if (inplotsolid && !active) inplotsolid = false; active = _inputSpectragram[i]->getPlotType()==FTspectragram::AMPFREQ_LINES; _inspecPlotLineTypeButton[i]->set_active (active); if (inplotline && !active) inplotline = false; active = _outputSpectragram[i]->getPlotType()==FTspectragram::SPECTRAGRAM; _outspecSpecTypeButton[i]->set_active(active); if (outspec && !active) outspec = false; active = _outputSpectragram[i]->getPlotType()==FTspectragram::AMPFREQ_SOLID; _outspecPlotSolidTypeButton[i]->set_active(active); if (outplotsolid && !active) outplotsolid = false; active = _outputSpectragram[i]->getPlotType()==FTspectragram::AMPFREQ_LINES; _outspecPlotLineTypeButton[i]->set_active(active); if (outplotline && !active) outplotline = false; } for (unsigned int n=0; n < _bypassAllButtons.size(); ++n) { _bypassAllButtons[n]->set_active (bypvec[n]); _linkAllButtons[n]->set_active (linkvec[n]); _gridButtons[n]->set_active (gridvec[n]); _gridSnapButtons[n]->set_active (gridsnapvec[n]); } _bypassAllCheck->SetValue (bypassed); _muteAllCheck->SetValue (muted); _linkMixCheck->SetValue (_linkedMix); _inspecSpecTypeAllButton->set_active (inspec); _inspecPlotLineTypeAllButton->set_active (inplotline); _inspecPlotSolidTypeAllButton->set_active (inplotsolid); _outspecSpecTypeAllButton->set_active (outspec); _outspecPlotLineTypeAllButton->set_active (outplotline); _outspecPlotSolidTypeAllButton->set_active (outplotsolid); _pathCountChoice->SetSelection(_pathCount - 1); if (_processPath[0]) { FTspectralEngine * engine = _processPath[0]->getSpectralEngine(); if (engine->getUpdateSpeed() == FTspectralEngine::SPEED_TURTLE) _plotSpeedChoice->SetSelection(0); else if (engine->getUpdateSpeed() == FTspectralEngine::SPEED_SLOW) _plotSpeedChoice->SetSelection(1); else if (engine->getUpdateSpeed() == FTspectralEngine::SPEED_MED) _plotSpeedChoice->SetSelection(2); else if (engine->getUpdateSpeed() == FTspectralEngine::SPEED_FAST) _plotSpeedChoice->SetSelection(3); _windowingChoice->SetSelection(engine->getWindowing()); const int * fftbins = FTspectralEngine::getFFTSizes(); for (int i=0; i < FTspectralEngine::getFFTSizeCount(); i++) { if (fftbins[i] == engine->getFFTsize()) { _freqBinsChoice->SetSelection(i); break; } } // hack for (int i=0; i < 5; i++) { if (engine->getOversamp() == 1<<i) { _overlapChoice->SetSelection(i); break; } } for (unsigned int i=0; i < _delayList.size(); ++i) { if (engine->getMaxDelay() == _delayList[i]) { _maxDelayChoice->SetSelection(i); break; } } _tempoSpinCtrl->SetValue(engine->getTempo()); } _ioNameText->SetValue (wxString::FromAscii (iosup->getName())); // reset timer just in case _updateMS = 10; // start small _eventTimer->Stop(); _eventTimer->Start(_updateMS, FALSE); } // event handlers void FTmainwin::handleInputButton(wxCommandEvent &event) { wxObject *source = event.GetEventObject(); wxString label(wxT("No Input")); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; if (source == _inputButton[i]) { FTportSelectionDialog *dial = new FTportSelectionDialog(this, wxNewId(), i, FTportSelectionDialog::INPUT, wxT("Input Port Selection")); dial->update(); dial->SetSize(wxSize(190,190)); dial->CentreOnParent(); if (dial->ShowModal() == wxID_OK) { std::vector<wxString> pnames = dial->getSelectedPorts(); FTioSupport::instance()->disconnectPathInput(i, NULL); // disconnect all for (unsigned j=0; j<pnames.size(); j++) { FTioSupport::instance()->connectPathInput(i, pnames[j].mb_str()); } } dial->Close(); } } updateDisplay(); } void FTmainwin::handleOutputButton(wxCommandEvent &event) { wxObject *source = event.GetEventObject(); wxString label(wxT("No Output")); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; if (source == _outputButton[i]) { FTportSelectionDialog *dial = new FTportSelectionDialog(this, wxNewId(), i, FTportSelectionDialog::OUTPUT, wxT("Output Port Selection")); dial->update(); dial->SetSize(wxSize(190,190)); dial->CentreOnParent(); if (dial->ShowModal() == wxID_OK) { std::vector<wxString> pnames = dial->getSelectedPorts(); FTioSupport::instance()->disconnectPathOutput(i, NULL); // disconnect all for (unsigned j=0; j<pnames.size(); j++) { FTioSupport::instance()->connectPathOutput(i, pnames[j].mb_str()); } } dial->Close(); } } updateDisplay(); } void FTmainwin::bypass_clicked_events (int button, PixButton * source) { bool alldone = false; for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; bool done = false; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() != lastgroup) { rowcnt++; lastgroup = filts[m]->getGroup(); } if (source == _bypassButtons[rowcnt][i]) { filts[m]->setBypassed ( ! filts[m]->getBypassed() ); _barGraphs[rowcnt][i]->setBypassed (filts[m]->getBypassed()); _bypassButtons[rowcnt][i]->set_active(filts[m]->getBypassed()); alldone = done = true; } else if (source == _bypassAllButtons[rowcnt]) { filts[m]->setBypassed ( !_bypassAllButtons[rowcnt]->get_active()); _barGraphs[rowcnt][i]->setBypassed (filts[m]->getBypassed()); done = true; } } if (done) break; } if (alldone) break; } updateDisplay(); } void FTmainwin::handleBypassButtons (wxCommandEvent &event) { wxObject *source = event.GetEventObject(); bool alldone = false; for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; bool done = false; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() != lastgroup) { rowcnt++; lastgroup = filts[m]->getGroup(); } // if (source == _bypassButtons[rowcnt][i]) // { // filts[m]->setBypassed ( ! filts[m]->getBypassed() ); // _barGraphs[rowcnt][i]->setBypassed (filts[m]->getBypassed()); // alldone = done = true; // } // if (source == _bypassAllButtons[rowcnt]) { // filts[m]->setBypassed ( _bypassAllButtons[rowcnt]->GetBackgroundColour() != _activeBg); // _barGraphs[rowcnt][i]->setBypassed (filts[m]->getBypassed()); // done = true; // } if (source == _bypassAllCheck) { engine->setBypassed( _bypassAllCheck->GetValue()); if (engine->getBypassed()) { _updateTokens[i]->setIgnore(true); } else { _updateTokens[i]->setIgnore(false); } done = true; break; } else if (source == _bypassCheck[i]) { engine->setBypassed( _bypassCheck[i]->GetValue()); if (engine->getBypassed()) { _updateTokens[i]->setIgnore(true); } else { _updateTokens[i]->setIgnore(false); } alldone = done = true; break; } else if (source == _muteAllCheck) { engine->setMuted( _muteAllCheck->GetValue()); done = true; break; } else if (source == _muteCheck[i]) { engine->setMuted( _muteCheck[i]->GetValue()); done = alldone = true; break; } } if (done) break; } if (alldone) break; } updateDisplay(); } void FTmainwin::handlePlotTypeButtons (wxCommandEvent &event) { wxObject *source = event.GetEventObject(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; if (source == _inspecSpecTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); break; } else if (source == _inspecPlotSolidTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); break; } else if (source == _inspecPlotLineTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); break; } else if (source == _outspecSpecTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); break; } else if (source == _outspecPlotSolidTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); break; } else if (source == _outspecPlotLineTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); break; } // all, don't break else if (source == _inspecSpecTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); } else if (source == _inspecPlotSolidTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); } else if (source == _inspecPlotLineTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); } else if (source == _outspecSpecTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); } else if (source == _outspecPlotSolidTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); } else if (source == _outspecPlotLineTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); } } updateDisplay(); } void FTmainwin::plot_clicked_events (int button, PixButton * source) { for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; if (source == _inspecSpecTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); break; } else if (source == _inspecPlotSolidTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); break; } else if (source == _inspecPlotLineTypeButton[i]) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); break; } else if (source == _outspecSpecTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); break; } else if (source == _outspecPlotSolidTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); break; } else if (source == _outspecPlotLineTypeButton[i]) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); break; } // all, don't break else if (source == _inspecSpecTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); } else if (source == _inspecPlotSolidTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); } else if (source == _inspecPlotLineTypeAllButton) { _inputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); } else if (source == _outspecSpecTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::SPECTRAGRAM); } else if (source == _outspecPlotSolidTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_SOLID); } else if (source == _outspecPlotLineTypeAllButton) { _outputSpectragram[i]->setPlotType (FTspectragram::AMPFREQ_LINES); } } updateDisplay(); } void FTmainwin::link_clicked_events (int button, PixButton * source) { vector<FTprocI *> firstprocmods; bool alldone = false; for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); bool done = false; vector<FTprocI *> procmods; engine->getProcessorModules (procmods); if (i==0) { engine->getProcessorModules (firstprocmods); } int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() != lastgroup) { rowcnt++; lastgroup = filts[m]->getGroup(); } if (source == _linkButtons[rowcnt][i]) { FTlinkMenu *menu = new FTlinkMenu (_linkButtons[rowcnt][i], this, engine, filts[m]->getSpecModifierType(), n, m); _linkButtons[rowcnt][i]->PopupMenu (menu, 0, 0); alldone = done = true; break; } else if (source == _linkAllButtons[rowcnt]) { if (_linkAllButtons[rowcnt]->get_active()) { // unlink filts[m]->unlink(); } else if (i != 0) { // link to first path (unless we are the first) filts[m]->link (firstprocmods[n]->getFilter(m)); } else { // unlink we are the master filts[m]->unlink(); } updateGraphs(0, filts[m]->getSpecModifierType()); done = true; } } if (done) break; } if (alldone) break; // if (source == _linkMixButton) { // // toggle it // _linkedMix = (_linkMixButton->GetBackgroundColour() != _activeBg); // } } updateDisplay(); } void FTmainwin::handleLinkButtons (wxCommandEvent &event) { wxObject *source = event.GetEventObject(); vector<FTprocI *> firstprocmods; bool alldone = false; for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); bool done = false; vector<FTprocI *> procmods; engine->getProcessorModules (procmods); if (i==0) { engine->getProcessorModules (firstprocmods); } int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() != lastgroup) { rowcnt++; lastgroup = filts[m]->getGroup(); } if (source == _linkAllButtons[rowcnt]) { if (_linkAllButtons[rowcnt]->GetBackgroundColour() == _activeBg) { // unlink filts[m]->unlink(); } else if (i != 0) { // link to first path (unless we are the first) filts[m]->link (firstprocmods[n]->getFilter(m)); } else { // unlink we are the master filts[m]->unlink(); } updateGraphs(0, filts[m]->getSpecModifierType()); done = true; } } if (done) break; } if (alldone) break; if (source == _linkMixCheck) { // toggle it _linkedMix = (_linkMixCheck->GetValue()); } } updateDisplay(); } void FTmainwin::handleTitleMenuCmd (FTtitleMenuEvent & ev) { if (ev.ready) { // recieved from title menu selections if (ev.cmdType == FTtitleMenuEvent::RemoveEvt) { doRemoveRow(ev.target); } else if (ev.cmdType == FTtitleMenuEvent::ExpandEvt || ev.cmdType == FTtitleMenuEvent::MinimizeEvt) { doMinimizeExpand(ev.target); } } else { _pendingTitleEvents.push_back ((FTtitleMenuEvent *) ev.Clone()); } } void FTmainwin::doRemoveRow (wxWindow * source) { if (source == _inspecLabelButton || source == _inspecLabelButtonAlt || source == _outspecLabelButton || source == _outspecLabelButtonAlt) { return; } FTspectralEngine *engine = _processPath[0]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; int itemi = -1; bool done = false; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() == lastgroup) { continue; // first fill do } lastgroup = filts[m]->getGroup(); if (source == _labelButtons[rowcnt] || source == _altLabelButtons[rowcnt]) { itemi = (int) n; done = true; } rowcnt++; } if (done) break; } if (itemi >= 0) { //suspendProcessing(); FTioSupport * iosup = FTioSupport::instance(); // do this for every active process path FTprocessPath * procpath; for (int i=0; i < iosup->getActivePathCount(); ++i) { procpath = iosup->getProcessPath(i); if (!procpath) break; engine = procpath->getSpectralEngine(); engine->removeProcessorModule ((unsigned int) itemi); } rebuildDisplay(false); //restoreProcessing(); if (_procmodDialog && _procmodDialog->IsShown()) { _procmodDialog->refreshState(); } } } void FTmainwin::handleLabelButtons (wxCommandEvent &event) { wxWindow *source = (wxWindow *) event.GetEventObject(); doMinimizeExpand (source); } void FTmainwin::doMinimizeExpand (wxWindow * source) { // remove sash from rowsizer and replace with button int itemi=-1; wxWindow * hidewin=0, *showwin=0; if (source == _inspecLabelButton || source == _inspecLabelButtonAlt) { if (_inspecSash->IsShown()) { hidewin = _inspecSash; showwin = _inspecLabelButtonAlt; itemi = 0; } else { hidewin = _inspecLabelButtonAlt; showwin = _inspecSash; itemi = 0; } } else if (source == _outspecLabelButton || source == _outspecLabelButtonAlt) { if (_outspecSash->IsShown()) { hidewin = _outspecSash; showwin = _outspecLabelButtonAlt; itemi = _rowItems.size()-1; } else { hidewin = _outspecLabelButtonAlt; showwin = _outspecSash; itemi = _rowItems.size()-1; } } else { for (unsigned int n=0; n < _labelButtons.size(); ++n) { if (source == _labelButtons[n] || source == _altLabelButtons[n]) { if (_rowSashes[n]->IsShown()) { hidewin = _rowSashes[n]; showwin = _altLabelButtons[n]; itemi = n+1; } else { hidewin = _altLabelButtons[n]; showwin = _rowSashes[n]; itemi = n+1; } break; } } } minimizeRow (showwin, hidewin, itemi, true); updateAllExtra(); } void FTmainwin::minimizeRow (wxWindow * showwin, wxWindow * hidewin, int itemi, bool layout) { if (hidewin && showwin) { hidewin->Show(false); _rowItems[itemi] = showwin; if (itemi > 0) { _rowItems[itemi]->GetConstraints()->top.Below(_rowItems[itemi-1], 2); } if (itemi < (int) _rowItems.size()-1) { _rowItems[itemi+1]->GetConstraints()->top.Below(_rowItems[itemi], 2); } showwin->Show(true); if (layout) { _rowPanel->Layout(); rowpanelScrollSize(); } } } void FTmainwin::handleSpins (wxSpinEvent &event) { wxObject *source = event.GetEventObject(); if (source == _tempoSpinCtrl) { int tval = _tempoSpinCtrl->GetValue(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; // set tempo of all, just in case for (unsigned int n=0; n < _barGraphs.size(); ++n) { _barGraphs[n][i]->setTempo (tval); } _processPath[i]->getSpectralEngine()->setTempo (tval); // purely for saving } } } void FTmainwin::handleChoices (wxCommandEvent &event) { wxObject *source = event.GetEventObject(); if (source == _freqBinsChoice) { int sel = _freqBinsChoice->GetSelection(); // MUST bypass and wait until not working suspendProcessing(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); // unset all specmods for safety for (unsigned int n=0; n < _barGraphs.size(); ++n) { _barGraphs[n][i]->setSpectrumModifier(0); _barGraphs[n][i]->setTopSpectrumModifier(0); } engine->setFFTsize ((FTspectralEngine::FFT_Size) (intptr_t) _freqBinsChoice->GetClientData(sel) ); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); // reset all the activeplots int rowcnt=-1; // preincremented for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() != lastgroup) { rowcnt++; lastgroup = filts[m]->getGroup(); _barGraphs[rowcnt][i]->setSpectrumModifier(filts[m]); } else { _barGraphs[rowcnt][i]->setTopSpectrumModifier(filts[m]); } } } _inputSpectragram[i]->setDataLength((unsigned int)_processPath[i]->getSpectralEngine()->getFFTsize() >> 1); _outputSpectragram[i]->setDataLength((unsigned int)_processPath[i]->getSpectralEngine()->getFFTsize() >> 1); } restoreProcessing(); updateGraphs(0, ALL_SPECMOD); } else if (source == _overlapChoice) { int sel = _overlapChoice->GetSelection(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; _processPath[i]->getSpectralEngine()->setOversamp( (intptr_t) _overlapChoice->GetClientData(sel) ); } } else if (source == _windowingChoice) { int sel = _windowingChoice->GetSelection(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; _processPath[i]->getSpectralEngine()->setWindowing( (FTspectralEngine::Windowing) sel ); } } else if (source == _plotSpeedChoice) { int sel = _plotSpeedChoice->GetSelection(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; _processPath[i]->getSpectralEngine()->setUpdateSpeed( (FTspectralEngine::UpdateSpeed) (intptr_t) _plotSpeedChoice->GetClientData(sel) ); if (i==0) { _updateMS = 10; // start small _eventTimer->Stop(); _eventTimer->Start(_updateMS, FALSE); } } } else if (source == _superSmoothCheck) { _superSmooth = _superSmoothCheck->GetValue(); if (_superSmooth) { _updateMS = 10; // start small _eventTimer->Stop(); _eventTimer->Start(_updateMS, FALSE); } } else if (source == _maxDelayChoice) { int sel = _maxDelayChoice->GetSelection(); if (sel >= (int) _delayList.size()) return; float maxdelay = _delayList[sel]; // MUST bypass and wait until not working suspendProcessing(); // set the max delay for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; _processPath[i]->getSpectralEngine()->setMaxDelay (maxdelay); // TODO: restore delay graph for (unsigned int n=0; n < _barGraphs.size(); ++n) { _barGraphs[n][i]->refreshBounds(); } } restoreProcessing(); updateGraphs(0, DELAY_SPECMOD); } } void FTmainwin::grid_clicked_events (int button, PixButton * source) { for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; bool done = false; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { // master gridlines buttons if (filts[m]->getGroup() == lastgroup) { continue; // first fill do } lastgroup = filts[m]->getGroup(); if (source == _gridButtons[rowcnt]) { _barGraphs[rowcnt][i]->setGridLines (!_gridButtons[rowcnt]->get_active()); done = true; } else if (source == _gridSnapButtons[rowcnt]) { _barGraphs[rowcnt][i]->setGridSnap (!_gridSnapButtons[rowcnt]->get_active()); done = true; } rowcnt++; } if (done) break; } } updateDisplay(); } void FTmainwin::handleGridButtons (wxCommandEvent &event) { wxObject *source = event.GetEventObject(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; bool done = false; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { // master gridlines buttons if (filts[m]->getGroup() == lastgroup) { continue; // first fill do } lastgroup = filts[m]->getGroup(); if (source == _gridButtons[rowcnt]) { _barGraphs[rowcnt][i]->setGridLines (_gridButtons[rowcnt]->GetBackgroundColour() != _activeBg); done = true; } else if (source == _gridSnapButtons[rowcnt]) { _barGraphs[rowcnt][i]->setGridSnap (_gridSnapButtons[rowcnt]->GetBackgroundColour() != _activeBg); done = true; } rowcnt++; } if (done) break; } } updateDisplay(); } void FTmainwin::handleGridButtonMouse (wxMouseEvent &event) { } void FTmainwin::grid_pressed_events (int button, PixButton * source) { if (button != PixButton::RightButton) return; vector<FTactiveBarGraph*> graphs; FTspectrumModifier::ModifierType mtype = FTspectrumModifier::NULL_MODIFIER; for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine * engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; bool done = false; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (filts[m]->getGroup() == lastgroup) { continue; // first will do } lastgroup = filts[m]->getGroup(); if (source == _gridButtons[rowcnt]) { mtype = filts[m]->getModifierType(); graphs.push_back (_barGraphs[rowcnt][i]); done = true; break; } rowcnt++; } if (done) break; } } if (graphs.size() > 0) { FTgridMenu *menu = new FTgridMenu (source, this, graphs, mtype); source->PopupMenu (menu, 0, source->GetSize().GetHeight()); delete menu; } } void FTmainwin::handleTitleButtonMouse (wxMouseEvent &event, bool minimized) { wxWindow *source = (wxWindow *) event.GetEventObject(); FTtitleMenu *menu = new FTtitleMenu (source, this, minimized); source->PopupMenu (menu, 0, source->GetSize().GetHeight()); delete menu; // now repost pending title events // XXX: we do this because one of the actions // actually deletes the source of this event, // and the first pending event was posted in the popupmenu's idle // context. what a pain. for (vector<FTtitleMenuEvent *>::iterator evt = _pendingTitleEvents.begin(); evt != _pendingTitleEvents.end() ; ++evt) { (*evt)->ready = true; GetEventHandler ()->AddPendingEvent (*(*evt)); delete (*evt); } _pendingTitleEvents.clear(); event.Skip(); } void FTmainwin::handleIOButtons (wxCommandEvent &event) { FTioSupport *iosup = FTioSupport::instance(); if (event.GetId() == FT_IOreconnectButton) { if (! iosup->isInited() || (_ioNameText->GetValue() != wxString::FromAscii (iosup->getName()))) { fprintf(stderr, "Reconnecting as %s...\n", static_cast<const char *>(_ioNameText->GetValue().mb_str())); iosup->stopProcessing(); wxThread::Sleep(200); iosup->close(); iosup->setName (static_cast<const char *> (_ioNameText->GetValue().mb_str())); if (iosup->init()) { if (iosup->startProcessing()) { iosup->reinit(); } } updateDisplay(); } } else if (event.GetId() == FT_IOdisconnectButton) { if (iosup->isInited()) { iosup->stopProcessing(); wxThread::Sleep(200); iosup->close(); } } } void FTmainwin::rebuildDisplay(bool dolink) { wxWindow *lastsash = _inspecSash; int rowcnt=0; FTspectralEngine * engine = _processPath[0]->getSpectralEngine(); vector<FTprocI *> pmods; engine->getProcessorModules (pmods); int initrows = _rowSizers.size(); for (unsigned int n=0; n < pmods.size(); ++n) { FTprocI *pm = pmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { // if the group is different from the last // make a new row for it if (filts[m]->getGroup() == lastgroup) { continue; } lastgroup = filts[m]->getGroup(); if (rowcnt >= initrows) { // we need to make new stuff pushProcRow(filts[m]); lastsash = _rowSashes[rowcnt]; } else { wxSashLayoutWindow * sash = _rowSashes[rowcnt]; // main label button string name = filts[m]->getName(); _labelButtons[rowcnt]->SetLabel (wxString::FromAscii (name.c_str())); _labelButtons[rowcnt]->SetToolTip(wxString(wxT("Hide ")) + wxString::FromAscii (name.c_str())); // alt label button _altLabelButtons[rowcnt]->SetLabel (wxString::FromAscii (name.c_str())); _altLabelButtons[rowcnt]->SetToolTip(wxString(wxT("Hide ")) + wxString::FromAscii (name.c_str())); lastsash = sash; } rowcnt++; } } if (rowcnt < (int) _rowSizers.size()) { // we need to pop some rows off int diff = _rowSizers.size() - rowcnt; for (int i=0; i < diff; i++) { //printf ("pop a row off: %d\n", diff); popProcRow(); } } else { //_outspecSash->GetConstraints()->top.SameAs (lastsash, wxBottom, 2); _outspecSash->GetConstraints()->top.Below (lastsash, 2); _outspecLabelButtonAlt->GetConstraints()->top.Below(lastsash, 2); _rowPanel->Layout(); rowpanelScrollSize(); } for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; // shouldnt happen engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); // change the plot stuff _inputSpectragram[i]->setDataLength((unsigned int)engine->getFFTsize() >> 1); _outputSpectragram[i]->setDataLength((unsigned int)engine->getFFTsize() >> 1); int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { wxPanel ** rowpanels = 0; FTactiveBarGraph **bargraphs = 0; bool newrow = false; if (filts[m]->getGroup() != lastgroup) { rowcnt++; rowpanels = _subrowPanels[rowcnt]; bargraphs = _barGraphs[rowcnt]; if (!bargraphs[i]) { // only if brand new row rowpanels[i] = new wxPanel (_rowPanels[rowcnt], -1); rowpanels[i]->SetBackgroundColour(*wxBLACK); rowpanels[i]->SetThemeEnabled(false); bargraphs[i] = new FTactiveBarGraph(this, rowpanels[i], -1); newrow = true; } bargraphs[i]->setSpectrumModifier (filts[m]); bargraphs[i]->setTopSpectrumModifier (0); bargraphs[i]->setBypassed (filts[m]->getBypassed()); bargraphs[i]->setTempo(_tempoSpinCtrl->GetValue()); bargraphs[i]->readExtra(filts[m]); bargraphs[i]->refreshBounds(); XMLNode * extra = filts[m]->getExtraNode(); XMLProperty * prop; // get stuff from extra node if ((prop = extra->property ("height"))) { wxString val(wxString::FromAscii (prop->value().c_str())); unsigned long newh; if (val.ToULong (&newh)) { wxLayoutConstraints *cnst = _rowSashes[rowcnt]->GetConstraints(); if (newh < 36) newh = 36; cnst->height.Absolute (newh); } } if ((prop = extra->property ("minimized"))) { wxString val(wxString::FromAscii (prop->value().c_str())); unsigned long newh; if (val.ToULong (&newh)) { if (newh) { // minimize minimizeRow (_altLabelButtons[rowcnt], _rowSashes[rowcnt], rowcnt+1, false); } else { // un-minimize minimizeRow (_rowSashes[rowcnt], _altLabelButtons[rowcnt], rowcnt+1, false); } } } if (dolink) { // link it to first filts[m]->link (pmods[n]->getFilter(m)); } lastgroup = filts[m]->getGroup(); } else { // assign nth filter to already created plot // TODO: support more than 2 rowpanels = _subrowPanels[rowcnt]; bargraphs = _barGraphs[rowcnt]; bargraphs[i]->setTopSpectrumModifier (filts[m]); bargraphs[i]->readExtra(filts[m]); bargraphs[i]->refreshBounds(); if (dolink) { // link it to first filts[m]->link (pmods[n]->getFilter(m)); } continue; } if (newrow) { wxBoxSizer * buttsizer = new wxBoxSizer(wxVERTICAL); PixButton * pixbutt; pixbutt = new PixButton(rowpanels[i], FT_BypassBase, false, wxDefaultPosition, wxSize(_bwidth, -1)); pixbutt->set_normal_bitmap (wxBitmap(bypass_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(bypass_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(bypass_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(bypass_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(bypass_active_xpm)); _bypassButtons[rowcnt][i] = pixbutt; //buttsizer->Add ( _bypassButtons[rowcnt][i] = new wxButton(rowpanels[i], FT_BypassBase, wxT("B"), // wxDefaultPosition, wxSize(_bwidth,-1)), 1, 0,0); pixbutt->clicked.connect (sigc::bind (sigc::mem_fun(*this, &FTmainwin::bypass_clicked_events), pixbutt)); buttsizer->Add (pixbutt, 0, 0, 0); _bypassButtons[rowcnt][i]->SetFont(_buttFont); _bypassButtons[rowcnt][i]->SetToolTip(wxT("Toggle Bypass")); pixbutt = new PixButton(rowpanels[i], FT_LinkBase, false, wxDefaultPosition, wxSize(_bwidth, -1)); pixbutt->set_normal_bitmap (wxBitmap(link_normal_xpm)); pixbutt->set_selected_bitmap (wxBitmap(link_selected_xpm)); pixbutt->set_focus_bitmap (wxBitmap(link_focus_xpm)); pixbutt->set_disabled_bitmap (wxBitmap(link_disabled_xpm)); pixbutt->set_active_bitmap (wxBitmap(link_active_xpm)); _linkButtons[rowcnt][i] = pixbutt; //buttsizer->Add ( _linkButtons[rowcnt][i] = new wxButton(rowpanels[i], FT_LinkBase, wxT("L"), // wxDefaultPosition, wxSize(_bwidth,-1)), 0, wxTOP,3); buttsizer->Add (_linkButtons[rowcnt][i], 0, wxTOP, 3); _linkButtons[rowcnt][i]->SetFont(_buttFont); _linkButtons[rowcnt][i]->SetToolTip(wxT("Link")); wxBoxSizer * tmpsizer = new wxBoxSizer(wxHORIZONTAL); tmpsizer->Add ( buttsizer, 0, wxALL|wxEXPAND, 1); tmpsizer->Add ( bargraphs[i], 1, wxALL|wxEXPAND, 1); rowpanels[i]->SetAutoLayout(TRUE); tmpsizer->Fit( rowpanels[i] ); rowpanels[i]->SetSizer(tmpsizer); _rowSizers[rowcnt]->Insert (i+1, rowpanels[i], 1, wxLEFT|wxEXPAND, 4); _rowSizers[rowcnt]->Layout(); } } } } //_rowPanel->Layout(); //rowpanelScrollSize(); updateGraphs(0, ALL_SPECMOD); updateDisplay(); if (_blendDialog) { _blendDialog->refreshState(); } } void FTmainwin::handlePathCount (wxCommandEvent &event) { int newcnt = _pathCountChoice->GetSelection() + 1; changePathCount (newcnt, true); } void FTmainwin::changePathCount (int newcnt, bool rebuild, bool ignorelink) { FTioSupport *iosup = FTioSupport::instance(); // change path count if (newcnt < _pathCount) { // get rid of the some for (int i=_pathCount-1; i >= newcnt; i--) { if (!_processPath[i]) continue; // shouldnt happen // remove all stuff // processpath deactivateed in here too removePathStuff(i); } } else if (newcnt > _pathCount) { if (rebuild) { // rebuild first with smaller number rebuildDisplay(!ignorelink); } // add some for (int i=_pathCount; i < newcnt; i++) { // add to io support instance _processPath[i] = iosup->setProcessPathActive (i, true); createPathStuff(i); } } _pathCount = iosup->getActivePathCount(); //printf ("new path cnt = %d\n", _pathCount); if (rebuild) { rebuildDisplay(!ignorelink); } else { updateDisplay(); } } void FTmainwin::updateAllExtra () { FTspectralEngine * engine; // go through each specfilt and get its sash constraint height for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; // shouldnt happen engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); int rowcnt=-1; // preincremented below for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { FTactiveBarGraph **bargraphs = 0; if (filts[m]->getGroup() != lastgroup) { rowcnt++; bargraphs = _barGraphs[rowcnt]; FTactiveBarGraph * graph = bargraphs[i]; wxSashLayoutWindow * sash = _rowSashes[rowcnt]; wxLayoutConstraints *cnst = sash->GetConstraints(); XMLNode * extra = filts[m]->getExtraNode(); extra->add_property ("height", std::string (wxString::Format(wxT("%d"), cnst->height.GetValue()).mb_str())); extra->add_property ("minimized", std::string (wxString::Format(wxT("%d"), (int) !sash->IsShown()).mb_str())); //printf ("updating extra for %s : shown %d\n", filts[m]->getName().c_str(), (int) sash->IsShown()); graph->writeExtra (filts[m]); lastgroup = filts[m]->getGroup(); } else { continue; } } } } } void FTmainwin::handleSashDragged (wxSashEvent &event) { wxObject *source = event.GetEventObject(); wxSashLayoutWindow *sash = (wxSashLayoutWindow *) source; if (event.GetDragStatus() == wxSASH_STATUS_OK) { wxLayoutConstraints *cnst = sash->GetConstraints(); wxRect bounds = event.GetDragRect(); int newh = bounds.height; if (newh < 36) newh = 36; cnst->height.Absolute (newh); _rowPanel->Layout(); rowpanelScrollSize(); // update all extra settings updateAllExtra(); } } void FTmainwin::handleGain (wxSpinEvent &event) { wxObject *source = event.GetEventObject(); for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); if (source == _gainSpinCtrl[i]) { // db scale float gain = pow(10, _gainSpinCtrl[i]->GetValue() / 20.0); // printf ("new gain is %g\n", gain); engine->setInputGain(gain); } } } void FTmainwin::handleMixSlider (wxScrollEvent &event) { wxObject *source = event.GetEventObject(); float newval = 1.0; for (int i=0; i < _pathCount; i++) { if (_mixSlider[i] == source) { newval = _mixSlider[i]->GetValue() / 1000.0; break; } } for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine *engine = _processPath[i]->getSpectralEngine(); if (_linkedMix || source == _mixSlider[i]) { // 0 -> 1000 engine->setMixRatio( newval); _mixSlider[i]->SetValue( (int) (newval * 1000.0)); } } } void FTmainwin::OnProcMod (wxCommandEvent &event) { // popup our procmod dsp dialog if (!_procmodDialog) { _procmodDialog = new FTprocOrderDialog(this, -1, wxT("DSP Modules")); _procmodDialog->SetSize(372,228); } _procmodDialog->refreshState(); _procmodDialog->Show(true); } void FTmainwin::OnPresetBlend (wxCommandEvent &event) { // popup our preset blend dialog if (!_blendDialog) { _blendDialog = new FTpresetBlendDialog(this, &_configManager, -1, wxT("Preset Blend")); _blendDialog->SetSize(372,228); } _blendDialog->refreshState(); _blendDialog->Show(true); } void FTmainwin::OnModulatorDialog (wxCommandEvent &event) { // popup our modulator dialog if (!_modulatorDialog) { _modulatorDialog = new FTmodulatorDialog(this, -1, wxT("Modulations")); _modulatorDialog->SetSize(450,350); } //_modulatorDialog->refreshState(); _modulatorDialog->Show(true); } void FTmainwin::OnQuit(wxCommandEvent& WXUNUSED(event)) { // TRUE is to force the frame to close Close(TRUE); } void FTmainwin::OnAbout(wxCommandEvent& event) { if (event.GetId() == FT_AboutMenu) { wxString msg(wxString(wxT("FreqTweak ")) + wxString::FromAscii (freqtweak_version) + wxT(" brought to you by Jesse Chappell")); wxMessageBox(msg, wxT("About FreqTweak"), wxOK | wxICON_INFORMATION, this); } else if (event.GetId() == FT_HelpTipsMenu) { FThelpWindow *helpwin = new FThelpWindow(this, -1, wxT("Usage Tips")); helpwin->Show(true); } } void FTmainwin::OnIdle(wxIdleEvent &event) { //printf("OnIdle\n"); if (_superSmooth) { ::wxWakeUpIdle(); } } void FTmainwin::OnClose(wxCloseEvent &event) { cleanup(); event.Skip(); } void FTmainwin::cleanup () { // save default preset _configManager.storeSettings ("", true); //printf ("cleaning up\n"); FTioSupport::instance()->close(); } void FTmainwin::checkEvents() { for (int i=0; i < _pathCount; i++) { if ( ! _updateTokens[i]->getIgnore()) { if (_updateTokens[i]->getUpdated(false)) { updatePlot (i); } else { // auto calibrate _eventTimer->Stop(); _eventTimer->Start(++_updateMS, FALSE); // printf("%d\n", _updateMS); } } } } void FTmainwin::checkRefreshes() { // TODO smartness updateGraphs(0, ALL_SPECMOD, true); } void FTmainwin::updatePlot (int plotid) { FTspectralEngine *engine = _processPath[plotid]->getSpectralEngine(); if (_inspecSash->IsShown()) { const float *inpower = engine->getRunningInputPower(); _inputSpectragram[plotid]->plotNextData(inpower, engine->getFFTsize() >> 1); } if (_outspecSash->IsShown()) { const float *outpower = engine->getRunningOutputPower(); _outputSpectragram[plotid]->plotNextData(outpower, engine->getFFTsize() >> 1); } } void FTmainwin::updateGraphs(FTactiveBarGraph *exclude, SpecModType smtype, bool refreshonly) { for (int i=0; i < _pathCount; i++) { if (!_processPath[i]) continue; FTspectralEngine * engine = _processPath[i]->getSpectralEngine(); vector<FTprocI *> procmods; engine->getProcessorModules (procmods); unsigned int rowcnt=0; bool done = false; for (unsigned int n=0; n < procmods.size(); ++n) { FTprocI *pm = procmods[n]; vector<FTspectrumModifier *> filts; pm->getFilters (filts); int lastgroup = -1; for (unsigned int m=0; m < filts.size(); ++m) { if (rowcnt >= _rowSashes.size()) { done = true; break; } if (filts[m]->getGroup() == lastgroup) { continue; // first will do } lastgroup = filts[m]->getGroup(); // prevent too many updates if ((!_rowSashes[rowcnt]->IsShown()) || (refreshonly && !filts[m]->getDirty())) { //cerr << "skipping " << filts[m]->getName() << " dirty: " << filts[m]->getDirty() << " refre: " << refreshonly<< endl; rowcnt++; continue; } if (smtype == ALL_SPECMOD) { //printf ("refreshing %08x\n", (unsigned) _barGraphs[rowcnt][i]); if (refreshonly) { _barGraphs[rowcnt][i]->Refresh(FALSE); } else { _barGraphs[rowcnt][i]->recalculate(); } } else if (filts[m]->getSpecModifierType() == smtype && _barGraphs[rowcnt][i] != exclude) { _barGraphs[rowcnt][i]->Refresh(FALSE); // may not be done //done = true; //break; } rowcnt++; } if (done) break; } } } void FTmainwin::updatePosition(const wxString &freqstr, const wxString &valstr) { wxStatusBar * statBar = GetStatusBar(); if (statBar) { statBar->SetStatusText(freqstr, 1); statBar->SetStatusText(valstr, 2); } } void FTmainwin::handleStoreButton (wxCommandEvent &event) { updateAllExtra(); DEBUGOUT ("store button pressed" << std::endl); _configManager.storeSettings (std::string (_presetCombo->GetValue().mb_str())); if (_blendDialog && _blendDialog->IsShown()) { _blendDialog->refreshState(); } rebuildPresetCombo(); } void FTmainwin::handleLoadButton (wxCommandEvent &event) { DEBUGOUT ("load button pressed" << std::endl); loadPreset (_presetCombo->GetValue().c_str()); } void FTmainwin::loadPreset (const wxString &name, bool uselast) { suspendProcessing(); bool success = _configManager.loadSettings (std::string (name.mb_str()), _restorePortsCheck->GetValue(), uselast); if (success) { _presetCombo->SetValue(name); rebuildPresetCombo(); // this rebuilds changePathCount ( FTioSupport::instance()->getActivePathCount() , true, true); if (_procmodDialog && _procmodDialog->IsShown()) { _procmodDialog->refreshState(); } if (_modulatorDialog && _modulatorDialog->IsShown()) { // _modulatorDialog->refreshState(); } if (_blendDialog && _blendDialog->IsShown()) { _blendDialog->refreshState(name, true, wxT(""), true); } } restoreProcessing(); } void FTmainwin::rebuildPresetCombo() { list<string> namelist = _configManager.getSettingsNames(); wxString selected = _presetCombo->GetValue(); _presetCombo->Clear(); _presetCombo->Append(wxT("")); for (list<string>::iterator name=namelist.begin(); name != namelist.end(); ++name) { _presetCombo->Append(wxString::FromAscii (name->c_str())); } if ( _presetCombo->FindString(selected) >= 0) { _presetCombo->SetValue(selected); } } void FTmainwin::suspendProcessing() { // for (int i=0; i < _pathCount; i++) { // if (!_processPath[i]) continue; // _bypassArray[i] = _processPath[i]->getSpectralEngine()->getBypassed(); // _processPath[i]->getSpectralEngine()->setBypassed(true); // } FTioSupport::instance()->setProcessingBypassed (true); //printf ("suspended before sleep\n"); wxThread::Sleep(250); // sleep to let the process callback get around to the beginning //printf ("suspended after sleep\n"); } void FTmainwin::restoreProcessing() { // restore bypass state // for (int i=0; i < _pathCount; i++) { // if (!_processPath[i]) continue; // _processPath[i]->getSpectralEngine()->setBypassed(_bypassArray[i]); // } FTioSupport::instance()->setProcessingBypassed (false); //printf ("restored\n"); } // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ FTlinkMenu::FTlinkMenu (wxWindow * parent, FTmainwin *win, FTspectralEngine *specengine, SpecModType stype, unsigned int procmodnum, unsigned int filtnum) : wxMenu(), _mwin(win), _specengine(specengine), _stype(stype), _procmodnum(procmodnum), _filtnum(filtnum) { FTspectrumModifier *linkedto = 0; int itemid = 1000; FTspectrumModifier *tempfilt, *thisfilt; FTspectralEngine *tempengine; thisfilt = _specengine->getProcessorModule(procmodnum)->getFilter(filtnum); linkedto = thisfilt->getLink(); for (int i=0; i < FT_MAXPATHS; i++) { if (!_mwin->_processPath[i] || _mwin->_processPath[i]->getSpectralEngine()==_specengine) continue; wxMenuItem * item = 0; tempengine = _mwin->_processPath[i]->getSpectralEngine(); tempfilt = tempengine->getProcessorModule(procmodnum)->getFilter(filtnum); if (linkedto == tempfilt || thisfilt->isLinkedFrom(tempfilt)) { item = new wxMenuItem(this, itemid, wxString::Format(wxT("* Path %d *"), i+1)); } else { item = new wxMenuItem(this, itemid, wxString::Format(wxT("Path %d"), i+1)); } this->Connect( itemid, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &FTlinkMenu::OnLinkItem, new SpecModObject(tempengine)); if (item) { this->Append(item); itemid++; } } // add unlink item wxMenuItem * item = new wxMenuItem(this, itemid, wxT("Unlink")); this->Connect( itemid, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &FTlinkMenu::OnUnlinkItem); this->AppendSeparator (); this->Append (item); } void FTlinkMenu::OnLinkItem(wxCommandEvent &event) { SpecModObject * smobj = (SpecModObject *) event.m_callbackUserData; // this is disaster waiting to happen :) // we need to link all the filters in the same group to their corresponding ones //int group = _specengine->getProcessorModule(_procmodnum)->getFilter(_filtnum)->getGroup(); vector<FTspectrumModifier*> sfilts, dfilts; _specengine->getProcessorModule(_procmodnum)->getFilters (sfilts); smobj->specm->getProcessorModule(_procmodnum)->getFilters (dfilts); for (unsigned int m=0; m < dfilts.size(); ++m) { //if (dfilts[m]->getGroup() == group) { sfilts[m]->link (dfilts[m]); //} } wxMenuItem *item = (wxMenuItem *) event.GetEventObject(); if (item) { this->Disconnect( item->GetId(), wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &FTlinkMenu::OnLinkItem, smobj); } _mwin->updateGraphs(0, _stype); delete smobj; } void FTlinkMenu::OnUnlinkItem(wxCommandEvent &event) { _specengine->getProcessorModule(_procmodnum)->getFilter(_filtnum)->unlink(); wxMenuItem *item = (wxMenuItem *) event.GetEventObject(); if (item) { this->Disconnect( item->GetId(), wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) (wxCommandEventFunction) &FTlinkMenu::OnLinkItem); } _mwin->updateGraphs(0, _stype); } BEGIN_EVENT_TABLE(FTgridMenu, wxMenu) EVT_MENU_RANGE (0, 20, FTgridMenu::OnSelectItem) END_EVENT_TABLE() FTgridMenu::FTgridMenu (wxWindow * parent, FTmainwin *win, vector<FTactiveBarGraph *> & graphlist, FTspectrumModifier::ModifierType mtype) : wxMenu(), _mwin(win), _graphlist(graphlist), _mtype(mtype) { wxMenuItem * item = 0; vector<wxString> gridunits = graphlist[0]->getGridChoiceStrings(); unsigned int gindex = graphlist[0]->getGridChoice(); int itemid = 0; for (vector<wxString>::iterator gridi = gridunits.begin(); gridi != gridunits.end(); ++gridi) { if ( (*gridi).empty()) { // add separator AppendSeparator(); itemid++; } else if ((int)gindex == itemid) { item = new wxMenuItem(this, itemid++, (*gridi) + wxT(" *")); Append (item); } else { item = new wxMenuItem(this, itemid++, *gridi); Append (item); } } } void FTgridMenu::OnSelectItem(wxCommandEvent &event) { wxMenuItem *item = (wxMenuItem *) event.GetEventObject(); if (item) { for (vector<FTactiveBarGraph*>::iterator gr = _graphlist.begin(); gr != _graphlist.end(); ++gr) { (*gr)->setGridChoice (event.GetId()); } } } BEGIN_EVENT_TABLE(FTgridButton, wxButton) EVT_RIGHT_DOWN (FTgridButton::handleMouse) END_EVENT_TABLE() FTgridButton::FTgridButton(FTmainwin * mwin, wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxButton(parent, id, label, pos, size, style, validator, name), _mainwin(mwin) { } void FTgridButton::handleMouse(wxMouseEvent &event) { if (event.RightDown()) { _mainwin->handleGridButtonMouse(event); } event.Skip(); } BEGIN_EVENT_TABLE(FTtitleMenu, wxMenu) EVT_MENU_RANGE (0, 20, FTtitleMenu::OnSelectItem) END_EVENT_TABLE() enum { ID_TitleExpand = 0, ID_TitleMinimize, ID_TitleRemove }; FTtitleMenu::FTtitleMenu (wxWindow * parent, FTmainwin *win, bool minimized) : wxMenu(), _mwin(win), _parent(parent) { wxMenuItem * item = 0; if (minimized) { item = new wxMenuItem(this, ID_TitleExpand, wxT("Expand")); } else { item = new wxMenuItem(this, ID_TitleMinimize, wxT("Minimize")); } Append (item); Append (new wxMenuItem(this, ID_TitleRemove, wxT("Remove"))); } void FTtitleMenu::OnSelectItem(wxCommandEvent &event) { int id = event.GetId(); if (id == ID_TitleRemove) { FTtitleMenuEvent tev (0, FTtitleMenuEvent::RemoveEvt, _parent); _mwin->GetEventHandler()->AddPendingEvent (tev); //_mwin->doRemoveRow(_parent); } else if (id == ID_TitleMinimize) { FTtitleMenuEvent tev (0, FTtitleMenuEvent::MinimizeEvt, _parent); _mwin->GetEventHandler()->AddPendingEvent (tev); //_mwin->doMinimizeExpand(_parent); } else if (id == ID_TitleExpand) { FTtitleMenuEvent tev (0, FTtitleMenuEvent::ExpandEvt, _parent); _mwin->GetEventHandler()->AddPendingEvent (tev); //_mwin->doMinimizeExpand(_parent); } } BEGIN_EVENT_TABLE(FTtitleButton, wxButton) EVT_RIGHT_DOWN (FTtitleButton::handleMouse) END_EVENT_TABLE() FTtitleButton::FTtitleButton(FTmainwin * mwin, bool minimized, wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) : wxButton(parent, id, label, pos, size, style, validator, name), _mainwin(mwin), _minimized(minimized) { SetForegroundColour(*wxWHITE); SetBackgroundColour(wxColour(50,50,50)); SetThemeEnabled(false); } void FTtitleButton::handleMouse(wxMouseEvent &event) { if (event.RightDown()) { _mainwin->handleTitleButtonMouse(event, _minimized); } event.Skip(); }
109,709
C++
.cpp
2,832
34.808969
149
0.698402
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,920
FTportSelectionDialog.cpp
essej_freqtweak/src/FTportSelectionDialog.cpp
/* ** Copyright (C) 2002 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #if HAVE_CONFIG_H #include <config.h> #endif #include <wx/wx.h> #include "FTportSelectionDialog.hpp" #include "FTjackSupport.hpp" #define DESELECTALLID 3241 BEGIN_EVENT_TABLE(FTportSelectionDialog, wxDialog) EVT_BUTTON(wxID_OK, FTportSelectionDialog::OnOK) EVT_BUTTON(DESELECTALLID, FTportSelectionDialog::OnDeselectAll) END_EVENT_TABLE() FTportSelectionDialog::FTportSelectionDialog(wxWindow * parent, wxWindowID id, int pathIndex, PortType ptype, const wxString & title, const wxPoint& pos, const wxSize& size, long style, const wxString& name ) : wxDialog(parent, id, title, pos, size, style, name) , _pathIndex(pathIndex), _portType(ptype) { init(); } void FTportSelectionDialog::init() { // FTjackSupport * iosup = FTjackSupport::instance(); wxBoxSizer * mainsizer = new wxBoxSizer(wxVERTICAL); _listBox = new wxListBox(this, wxNewId(), wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_MULTIPLE); wxButton * deselbutt = new wxButton(this, DESELECTALLID, wxT("Deselect All")); mainsizer->Add(deselbutt, 0, wxALL, 3); mainsizer->Add(_listBox, 1, wxALL|wxEXPAND, 3); // button bar wxBoxSizer * buttSizer = new wxBoxSizer(wxHORIZONTAL); wxButton *okButton = new wxButton(this, wxID_OK, wxT("OK")); wxButton *cancButton = new wxButton(this, wxID_CANCEL, wxT("Cancel")); buttSizer->Add(okButton, 0, wxRIGHT, 10); buttSizer->Add(cancButton, 0, wxLEFT, 10); mainsizer->Add(buttSizer, 0, wxALL|wxEXPAND, 4); SetAutoLayout( TRUE ); mainsizer->Fit( this ); mainsizer->SetSizeHints( this ); SetSizer( mainsizer ); } void FTportSelectionDialog::update() { // get ports from jack const char ** availports = 0; const char ** connports = 0; const char * noportname = 0; FTioSupport * iosup = FTioSupport::instance(); if (_portType == INPUT) { availports = iosup->getInputConnectablePorts(_pathIndex); connports = iosup->getConnectedInputPorts(_pathIndex); noportname = iosup->getOutputPortName(_pathIndex); } else if (_portType == OUTPUT) { availports = iosup->getOutputConnectablePorts(_pathIndex); connports = iosup->getConnectedOutputPorts(_pathIndex); noportname = iosup->getInputPortName(_pathIndex); } _listBox->Clear(); if (availports) { for (int i=0; availports[i]; i++) { if (noportname && wxString::FromAscii(availports[i]).Cmp(wxString::FromAscii (noportname)) != 0) { _listBox->Append (wxString::FromAscii(availports[i]), (void *) 0); } } free (availports); for (unsigned int i=0; i < _listBox->GetCount(); i++) { _listBox->Deselect(i); } if (connports) { for (int i=0; connports[i]; i++) { int n = _listBox->FindString(wxString::FromAscii (connports[i])); //printf ("connport = %s find is %d\n", connports[i], n); if (n >= 0) _listBox->SetSelection (n, TRUE); } free(connports); } } } std::vector<wxString> FTportSelectionDialog::getSelectedPorts() { int n = _selectedPorts.GetCount(); std::vector<wxString> pnames; for (int i=0; i < n; i++) { pnames.push_back(wxString(_selectedPorts.Item(i).GetData())); } return pnames; } void FTportSelectionDialog::OnDeselectAll(wxCommandEvent &event) { for (unsigned int i=0; i < _listBox->GetCount(); i++) { _listBox->Deselect(i); } } void FTportSelectionDialog::OnOK(wxCommandEvent &event) { // get selection from listbox wxArrayInt selarr; int n = _listBox->GetSelections(selarr); _selectedPorts.Clear(); for (int i=0; i < n; i++) { _selectedPorts.Add(_listBox->GetString(selarr[i])); } if (IsModal()) { EndModal(wxID_OK); } else { SetReturnCode(wxID_OK); Show(0); } }
4,458
C++
.cpp
132
30.810606
109
0.716561
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,921
FTjackSupport.cpp
essej_freqtweak/src/FTjackSupport.cpp
/* ** Copyright (C) 2002 Jesse Chappell <jesse@essej.net> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ** */ #if HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <string> #include <list> using namespace std; #include "FTjackSupport.hpp" #include "FTprocessPath.hpp" #include "FTspectralEngine.hpp" #include "FTtypes.hpp" #include <jack/jack.h> struct jack_lat_data { PathInfo *tmppath; FTprocessPath * ppath; }; jack_lat_data _tmp_data; void latency_cb (jack_latency_callback_mode_t mode, void *arg) { jack_latency_range_t range; jack_nframes_t latency = ((jack_lat_data *)arg)->ppath->getSpectralEngine()->getLatency(); if (mode == JackCaptureLatency) { jack_port_get_latency_range ( ((jack_lat_data *)arg)->tmppath->inputport, mode, &range); range.min += latency; range.max += latency; jack_port_set_latency_range ( ((jack_lat_data *)arg)->tmppath->outputport, mode, &range); } else { jack_port_get_latency_range ( ((jack_lat_data *)arg)->tmppath->outputport, mode, &range); range.min += latency; range.max += latency; jack_port_set_latency_range ( ((jack_lat_data *)arg)->tmppath->inputport, mode, &range); } } FTjackSupport::FTjackSupport(const char * name, const char * dir) : _inited(false), _jackClient(0), _activePathCount(0), _activated(false), _bypassed(false) { // init process path info for (int i=0; i < FT_MAXPATHS; i++) { _pathInfos[i] = 0; } _name = name; _jackserv = dir; } FTjackSupport::~FTjackSupport() { printf ("jack support destruct\n"); // init process path info for (int i=0; i < FT_MAXPATHS; i++) { if (_pathInfos[i]) { delete _pathInfos[i]; } } if (_inited && _jackClient) { close(); //jack_client_close ( _jackClient ); } } /** * Initialize and connect to jack server. * Returns false if failed */ bool FTjackSupport::init() { #ifdef HAVE_JACK_CLIENT_OPEN jack_options_t options = JackNullOption; jack_status_t status; const char *server_name = NULL; if (!_jackserv.empty()) { server_name = _jackserv.c_str(); } // jack_client_name = client_name; /* might be reset below */ if (_name.empty()) { _name = "freqtweak"; } _jackClient = jack_client_open (_name.c_str(), options, &status, server_name); if (!_jackClient) { fprintf (stderr, "JACK Error: No good client name or JACK server %s not running?\n", _jackserv.c_str()); _inited = false; return false; } if (status & JackServerStarted) { fprintf(stderr,"JACK server started\n"); } if (status & JackNameNotUnique) { _name = jack_get_client_name (_jackClient); } #else char namebuf[100]; /* try to become a client of the JACK server */ if (_name.empty()) { // find a name predictably for (int i=1; i < 10; i++) { snprintf(namebuf, sizeof(namebuf)-1, "freqtweak_%d", i); if ((_jackClient = jack_client_new (namebuf)) != 0) { _name = namebuf; break; } } } else { // try the passed name, or base a predictable name from it if ((_jackClient = jack_client_new (_name.c_str())) == 0) { for (int i=1; i < 10; i++) { snprintf(namebuf, sizeof(namebuf)-1, "%s_%d", _name.c_str(), i); if ((_jackClient = jack_client_new (namebuf)) != 0) { _name = namebuf; break; } } } } if (!_jackClient) { fprintf (stderr, "JACK Error: No good client name or JACK server not running?\n"); _inited = false; return false; } #endif /* tell the JACK server to call `process()' whenever there is work to be done. */ jack_set_process_callback (_jackClient, FTjackSupport::processCallback, 0); /* tell the JACK server to call `srate()' whenever the sample rate of the system changes. */ jack_set_sample_rate_callback (_jackClient, FTjackSupport::srateCallback, 0); /* tell the JACK server to call `jack_shutdown()' if it ever shuts down, either entirely, or if it just decides to stop calling us. */ jack_on_shutdown (_jackClient, FTjackSupport::jackShutdown, 0); /* display the current sample rate. once the client is activated (see below), you should rely on your own sample rate callback (see above) for this value. */ _sampleRate = jack_get_sample_rate (_jackClient); //printf ("engine sample rate: %lu\n", _sampleRate); _inited = true; return true; } bool FTjackSupport::startProcessing() { if (!_jackClient) return false; if (jack_activate (_jackClient)) { fprintf (stderr, "Error: cannot activate jack client!\n"); return false; } _activated = true; return true; } bool FTjackSupport::stopProcessing() { if (!_jackClient) return false; // load up latest port connections for possible restoring for (int i=0; i < _activePathCount; ++i) { const char ** ports; if ((ports = getConnectedInputPorts (i)) != NULL) free (ports); if ((ports = getConnectedOutputPorts (i)) != NULL) free (ports); } if (jack_deactivate (_jackClient)) { fprintf (stderr, "Error: cannot deactivate jack client!\n"); return false; } //printf ("deactivated jack\n"); _activated = false; return true; } bool FTjackSupport::close() { if (_inited && _jackClient) { stopProcessing(); jack_client_close ( _jackClient ); _jackClient = 0; _inited = false; return true; } return false; } FTprocessPath * FTjackSupport::setProcessPathActive (int index, bool active) { if (!_inited || !_jackClient) return 0; char nbuf[30]; PathInfo *tmppath; FTprocessPath * ppath; if (index >=0 && index < FT_MAXPATHS) { if (_pathInfos[index]) { tmppath = _pathInfos[index]; ppath = tmppath->procpath; if (active) { if (tmppath->active) { //already active, do nothing return ppath; } } else { if (tmppath->active) { // detach ports jack_port_unregister (_jackClient, tmppath->inputport); jack_port_unregister (_jackClient, tmppath->outputport); // just mark it inactive but not destroy it tmppath->active = false; _activePathCount--; //we are not deleting old one, we reuse it later if necessary } return 0; } } else { // it is a new one, construct new processPath if (active) { tmppath = new PathInfo(); ppath = new FTprocessPath(); } else { return NULL; } } _tmp_data.tmppath = tmppath; _tmp_data.ppath = ppath; // it only gets here if it is brand new, or going from inactive->active sprintf(nbuf,"in_%d", index + 1); tmppath->inputport = jack_port_register (_jackClient, nbuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); sprintf(nbuf,"out_%d", index + 1); tmppath->outputport = jack_port_register (_jackClient, nbuf, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); //jack_port_set_latency (tmppath->outputport, ppath->getSpectralEngine()->getLatency()); jack_set_latency_callback (_jackClient, latency_cb, &_tmp_data); tmppath->procpath = ppath; tmppath->active = true; _pathInfos[index] = tmppath; ppath->setId (index); _activePathCount++; return ppath; } return NULL; } const char * FTjackSupport::getInputPortName(int index) { if (index >=0 && index < FT_MAXPATHS) { if (_pathInfos[index]) { return jack_port_name(_pathInfos[index]->inputport); } } return NULL; } const char * FTjackSupport::getOutputPortName(int index) { if (index >=0 && index < FT_MAXPATHS) { if (_pathInfos[index]) { return jack_port_name(_pathInfos[index]->outputport); } } return NULL; } bool FTjackSupport::connectPathInput (int index, const char *inname) { if (!_jackClient) return false; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { if (jack_connect (_jackClient, inname, jack_port_name(_pathInfos[index]->inputport))) { fprintf (stderr, "JACK error: cannot connect input port: %s -> %s\n", inname, jack_port_name(_pathInfos[index]->inputport)); return false; } _pathInfos[index]->inconn_list.push_back (inname); return true; } return false; } bool FTjackSupport::connectPathOutput (int index, const char *outname) { if (!_jackClient) return false; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { if (jack_connect (_jackClient, jack_port_name(_pathInfos[index]->outputport), outname)) { fprintf (stderr, "JACK error: cannot connect output port: %s -> %s\n", jack_port_name(_pathInfos[index]->outputport), outname); return false; } _pathInfos[index]->outconn_list.push_back (outname); return true; } return false; } bool FTjackSupport::disconnectPathInput (int index, const char *inname) { if (!_jackClient) return false; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { if (inname) { if (jack_disconnect (_jackClient, inname, jack_port_name(_pathInfos[index]->inputport))) { fprintf (stderr, "cannot disconnect input port\n"); return false; } _pathInfos[index]->inconn_list.remove (inname); return true; } else { // disconnect all from our input port const char ** portnames = jack_port_get_connections (_pathInfos[index]->inputport); if (portnames) { for (int i=0; portnames[i]; i++) { jack_disconnect (_jackClient, portnames[i], jack_port_name(_pathInfos[index]->inputport)); } free(portnames); } _pathInfos[index]->inconn_list.clear(); return true; } } return false; } bool FTjackSupport::disconnectPathOutput (int index, const char *outname) { if (!_jackClient) return false; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { if (outname) { if (jack_disconnect (_jackClient, jack_port_name(_pathInfos[index]->outputport), outname)) { fprintf (stderr, "cannot disconnect output ports\n"); return false; } _pathInfos[index]->outconn_list.remove (outname); return true; } else { // disconnect all from our output port const char ** portnames = jack_port_get_connections (_pathInfos[index]->outputport); if (portnames) { for (int i=0; portnames[i]; i++) { jack_disconnect (_jackClient, jack_port_name(_pathInfos[index]->outputport), portnames[i]); } free(portnames); } _pathInfos[index]->outconn_list.clear(); return true; } } return false; } const char ** FTjackSupport::getInputConnectablePorts (int index) { const char ** portnames = NULL; if (!_jackClient) return NULL; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { //char regexstr[100]; // anything but our own output port //snprintf(regexstr, 99, "^(%s)", jack_port_name (_pathInfos[index]->outputport) ); portnames = jack_get_ports( _jackClient, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput); } return portnames; } const char ** FTjackSupport::getOutputConnectablePorts (int index) { const char ** portnames = NULL; if (!_jackClient) return NULL; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { //char regexstr[100]; // anything but our own input port //snprintf(regexstr, 99, "^(%s)", jack_port_name (_pathInfos[index]->inputport) ); portnames = jack_get_ports( _jackClient, NULL, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput); } return portnames; } const char ** FTjackSupport::getConnectedInputPorts(int index) { const char ** portnames = NULL; if (!_jackClient) return NULL; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { //char regexstr[100]; // anything but our own input port //snprintf(regexstr, 99, "^(%s)", jack_port_name (_pathInfos[index]->inputport) ); portnames = jack_port_get_connections( _pathInfos[index]->inputport); _pathInfos[index]->inconn_list.clear(); if (portnames) { for (int i=0; portnames[i]; i++) { _pathInfos[index]->inconn_list.push_back (portnames[i]); } } } return portnames; } const char ** FTjackSupport::getConnectedOutputPorts(int index) { const char ** portnames = NULL; if (!_jackClient) return NULL; if (index >=0 && index < FT_MAXPATHS && _pathInfos[index]) { //char regexstr[100]; // anything but our own input port //snprintf(regexstr, 99, "^(%s)", jack_port_name (_pathInfos[index]->inputport) ); portnames = jack_port_get_connections( _pathInfos[index]->outputport); _pathInfos[index]->outconn_list.clear(); if (portnames) { for (int i=0; portnames[i]; i++) { _pathInfos[index]->outconn_list.push_back (portnames[i]); } } } return portnames; } const char ** FTjackSupport::getPhysicalInputPorts() { const char ** portnames = NULL; if (!_jackClient) return NULL; if ((portnames = jack_get_ports (_jackClient, NULL, NULL, JackPortIsPhysical|JackPortIsOutput)) == NULL) { fprintf(stderr, "Cannot find any physical capture ports"); } return portnames; } const char ** FTjackSupport::getPhysicalOutputPorts() { const char ** portnames = NULL; if (!_jackClient) return NULL; if ((portnames = jack_get_ports (_jackClient, NULL, NULL, JackPortIsPhysical|JackPortIsInput)) == NULL) { fprintf(stderr, "Cannot find any physical playback ports"); } return portnames; } nframes_t FTjackSupport::getTransportFrame() { if (!_jackClient) return 0; if (jack_transport_query (_jackClient, 0) == JackTransportRolling) { return jack_get_current_transport_frame (_jackClient); } else { return jack_frame_time (_jackClient); } } bool FTjackSupport::inAudioThread() { if (_jackClient && (pthread_self() == jack_client_thread_id (_jackClient))) { return true; } return false; } void FTjackSupport::setProcessingBypassed (bool val) { if (_bypassed != val) { // TODO: flag some sort of cross-fade ramp _bypassed = val; } } bool FTjackSupport::reinit (bool rebuild) { // assume that activePathCount is in the previous state // assume that the _pathInfos contain valid lists of connected ports // and active flags //printf ("reinit\n"); if (!_jackClient) return false; for (int i=0; i < FT_MAXPATHS; i++) { if (_pathInfos[i] && _pathInfos[i]->active) { if (rebuild) { _pathInfos[i]->active = false; setProcessPathActive (i, true); } // reconnect to ports list<string> inlist (_pathInfos[i]->inconn_list); // copy _pathInfos[i]->inconn_list.clear(); for (list<string>::iterator port = inlist.begin(); port != inlist.end(); ++port) { // only do it if the port is not one of ours // those interconnected ports within ourself are added // only once below jack_port_t * tport = jack_port_by_name(_jackClient, (*port).c_str()); if ( tport && ! jack_port_is_mine ( _jackClient, tport)) { //fprintf(stderr, "reconnecting to input: %s\n", port.c_str()); connectPathInput ( i, (*port).c_str() ); } } list<string> outlist (_pathInfos[i]->outconn_list); // copy _pathInfos[i]->outconn_list.clear(); for (list<string>::iterator port = outlist.begin(); port != outlist.end(); ++port) { //fprintf(stderr, "reconnecting to output: %s\n", port.c_str()); connectPathOutput ( i, (*port).c_str() ); } } } return true; } /** static callbacks **/ int FTjackSupport::processCallback (jack_nframes_t nframes, void *arg) { FTjackSupport * jsup = (FTjackSupport *) FTioSupport::instance(); PathInfo * tmppath; // do processing for each path for (int i=0; i < FT_MAXPATHS; i++) { if (jsup->_pathInfos[i] && jsup->_pathInfos[i]->active) { tmppath = jsup->_pathInfos[i]; sample_t *in = (sample_t *) jack_port_get_buffer (tmppath->inputport, nframes); sample_t *out = (sample_t *) jack_port_get_buffer (tmppath->outputport, nframes); if (jsup->_bypassed) { if (in != out) { memcpy (out, in, nframes * sizeof(sample_t)); } } else { tmppath->procpath->processData(in, out, nframes); } } } return 0; } int FTjackSupport::srateCallback (jack_nframes_t nframes, void *arg) { FTjackSupport * jsup = (FTjackSupport *) FTioSupport::instance(); for (int i=0; i < FT_MAXPATHS; i++) { if (jsup->_pathInfos[i]) { jsup->_pathInfos[i]->procpath->setSampleRate(nframes); } } return 0; } void FTjackSupport::jackShutdown (void *arg) { FTjackSupport * jsup = (FTjackSupport *) FTioSupport::instance(); fprintf (stderr, "Jack shut us down!\n"); jsup->_inited = false; jsup->_jackClient = 0; /* //jsup->close(); fprintf (stderr, "Trying to reconnect....\n"); if (jsup->init()) { if (jsup->startProcessing()) { jsup->reinit (); } } */ } // This isn't in use yet. int FTjackSupport::portsChanged (jack_port_id_t port, int blah, void *arg) { FTjackSupport * jsup = (FTjackSupport *) FTioSupport::instance(); fprintf (stderr, "Ports changed on us!\n"); jsup->_portsChanged = true; return 0; }
17,464
C++
.cpp
571
27.315236
109
0.682089
essej/freqtweak
34
4
3
GPL-2.0
9/20/2024, 10:43:54 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false