куча изменений, но зато теперь сохраняются настройки QoS и есть алгоритм сохранения параметров в API

This commit is contained in:
Vladislav Ostapov 2024-11-11 17:35:25 +03:00
parent 435f215118
commit cb9d412c8e
10 changed files with 398 additions and 77 deletions

View File

@ -6,6 +6,42 @@ std::shared_mutex mtx;
TSID sid_counter { 0 };
std::map<TSID, std::unique_ptr<system_client>> clients;
EXTERNC CP_Result CP_SetQoSSettings(TSID sid, const std::string &qos_settings_json, bool is_enable){
std::shared_lock lock(mtx);
try
{
if (clients.find(sid) == clients.end())
return ERROR;
auto resp = clients[sid]->send_set_qos_settings_json(qos_settings_json, is_enable);
if (resp == response_type::error)
return ERROR;
return OK;
}
catch(const std::exception& e)
{
return ERROR;
}
}
EXTERNC CP_Result CP_GetQoSSettings(TSID sid, std::string &qos_settings_json, bool &is_enable){
std::shared_lock lock(mtx);
try
{
if (clients.find(sid) == clients.end())
return ERROR;
auto resp = clients[sid]->send_get_qos_settings_json(qos_settings_json, is_enable);
if (resp == response_type::error)
return ERROR;
return OK;
}
catch(const std::exception& e)
{
return ERROR;
}
}
EXTERNC CP_Result CP_SetBUC_LNB_settings(TSID sid, buc_lnb_settings &settings){
std::shared_lock lock(mtx);
@ -25,6 +61,7 @@ EXTERNC CP_Result CP_SetBUC_LNB_settings(TSID sid, buc_lnb_settings &settings){
return ERROR;
}
}
EXTERNC CP_Result CP_GetBUC_LNB_settings(TSID sid, buc_lnb_settings &settings){
std::shared_lock lock(mtx);
try

View File

@ -433,6 +433,16 @@ void system_client::data_received(const std::vector<uint8_t> & data)
}
break;
}
case cmd_type::get_qos_settings_json:
{
if (cmd.rsp == response_type::ok)
{
cmd_qos_settings value;
iarchive(value);
data_from_serv = value;
}
break;
}
default: break;
}
@ -705,6 +715,40 @@ response_type system_client::send_get_qos_params(std::string &node, const name_c
return result;
}
response_type system_client::send_set_qos_settings_json(const std::string &json_string, bool is_enable){
std::scoped_lock lock(cmd_in_progress_mtx);
uint32_t curr_id { ++cmd_id };
cmd_header cmd_qos_header{curr_id, cmd_type::set_qos_settings_json};
cmd_qos_settings qos_settings{json_string, is_enable};
send_to_socket(cmd_qos_header, qos_settings);
std::any data_to_serv;
auto result = wait_for_response(curr_id, cmd_type::set_qos_settings, data_to_serv);
return result;
}
response_type system_client::send_get_qos_settings_json(std::string &json_string, bool &is_enable){
std::scoped_lock lock(cmd_in_progress_mtx);
uint32_t curr_id { ++cmd_id };
cmd_header cmd_qos_header{curr_id, cmd_type::get_qos_settings_json};
cmd_qos_settings qos_settings{json_string, is_enable};
send_to_socket(cmd_qos_header, qos_settings);
std::any data_from_serv;
auto result = wait_for_response(curr_id, cmd_type::get_qos_settings_json, data_from_serv);
if (data_from_serv.has_value())
{
json_string = std::any_cast<cmd_qos_settings>(data_from_serv).json_string;
is_enable = std::any_cast<cmd_qos_settings>(data_from_serv).is_enable;
}
return result;
}
response_type system_client::send_set_10g_config(const cmd_10g_config & _10g_config, std::string &value)
{
std::scoped_lock lock(cmd_in_progress_mtx);

View File

@ -70,6 +70,8 @@ public:
response_type send_set_qos_params(const std::string &node, const name_classes_qos & class_qos);
response_type send_get_qos_params(std::string &node, const name_classes_qos & class_qos);
response_type send_set_qos_settings_json(const std::string &json_string, bool is_enable);
response_type send_get_qos_settings_json(std::string &json_string, bool &is_enable);
void set_stdout_callback(std::function<void(const char *, uint32_t)> cb);
void abort();

View File

@ -390,7 +390,9 @@ enum class cmd_type
get_modulator_settings = 37,
get_demodulator_settings = 38,
set_lnb_buc_settings = 39,
get_lnb_buc_settings = 40
get_lnb_buc_settings = 40,
set_qos_settings_json = 41,
get_qos_settings_json = 42
};
struct cmd_lbq_params
@ -565,7 +567,15 @@ struct cmd_get_acm_param
archive(enable, max_attenuation, max_modcod, min_attenuation, min_modcod, snr_treashold, enable_auto_atten, snr_treashold_acm, period_pack);
}
};
struct cmd_qos_settings{
std::string json_string;
bool is_enable;
template<class Archive>
void serialize(Archive & archive)
{
archive(json_string, is_enable);
}
};
struct cmd_set_qos_settings
{
std::string node;

View File

@ -1,6 +1,7 @@
#ifndef __CONTROL_PROTO_COMMANDS__
#define __CONTROL_PROTO_COMMANDS__
#include <stdint.h>
#include <iostream>
#include <string>
@ -175,6 +176,8 @@ struct buc_lnb_settings
EXTERNC CP_Result CP_SetBUC_LNB_settings(TSID sid, buc_lnb_settings &settings);
EXTERNC CP_Result CP_GetBUC_LNB_settings(TSID sid, buc_lnb_settings &settings);
EXTERNC CP_Result CP_SetQoSSettings(TSID sid, const std::string &qos_settings_json, bool is_enable);
EXTERNC CP_Result CP_GetQoSSettings(TSID sid, std::string &qos_settings_json, bool &is_enable);
EXTERNC CP_Result CP_GetModulatorParams(TSID sid, const char *modulator_param, uint32_t *value);

View File

@ -11,7 +11,6 @@
#include <boost/log/utility/setup/formatter_parser.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/ssl/context.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <cstddef>
#include <memory>
@ -101,9 +100,6 @@ public:
api->startDaemon();
auth.users.emplace_back(std::make_shared<http::auth::User>("admin"));
sf->registerFile(INDEX_HTML, mime_types::text_html, false);
sf->registerFile(LOGIN_HTML, mime_types::text_html, false);
sf->registerFile(FAVICON_ICO, mime_types::image_png, true);
sf->registerFile(KROKODIL_GIF, mime_types::image_gif, true);
sf->registerFile(VUE_JS, mime_types::javascript, true);
@ -115,6 +111,9 @@ public:
constexpr bool allowCacheCss = true;
#endif
sf->registerFile(INDEX_HTML, mime_types::text_html, allowCacheCss);
sf->registerFile(LOGIN_HTML, mime_types::text_html, allowCacheCss);
sf->registerFile(STYLE_CSS, mime_types::text_css, allowCacheCss);
sf->registerFile(FIELDS_CSS, mime_types::text_css, allowCacheCss);
}
@ -177,18 +176,6 @@ public:
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/js/vue.js", [this](const auto& req, auto& rep) { boost::ignore_unused(req); sf->serve(VUE_JS, rep); }));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/vid/video_2024-11-06_15-49-35.mp4", [this](const auto& req, auto& rep) { boost::ignore_unused(req); sf->serve(KB_MP4, rep); }));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/statistics", [](const auto& req, auto& rep) {
if (req.method != "GET") {
http::server::stockReply(http::server::bad_request, rep);
}
rep.status = http::server::ok;
rep.headers.clear();
rep.headers.push_back({.name = "Content-Type", .value = toString(mime_types::json)});
const char* json = R"({"key":"value"})";
rep.content.insert(rep.content.end(), json, json + strlen(json));
}));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/get/statistics", [this](const auto& req, auto& rep) {
if (req.method != "GET") {
http::server::stockReply(http::server::bad_request, rep);
@ -203,6 +190,20 @@ public:
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
}));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/get/settings", [this](const auto& req, auto& rep) {
if (req.method != "GET") {
http::server::stockReply(http::server::bad_request, rep);
}
rep.status = http::server::ok;
rep.headers.clear();
rep.headers.push_back({.name = "Content-Type", .value = toString(mime_types::json)});
std::string result = R"({"settings":)";
result += api->loadSettings();
result += "}";
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
}));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/resetPacketStatistics", [this](const auto& req, auto& rep) {
if (req.method != "POST") {
http::server::stockReply(http::server::bad_request, rep);
@ -216,19 +217,36 @@ public:
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
}));
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/get/settings", [this](const auto& req, auto& rep) {
if (req.method != "GET") {
s.resources.emplace_back(std::make_unique<http::resource::GenericResource>("/api/set/qos", [this](const auto& req, auto& rep) {
if (req.method != "POST") {
http::server::stockReply(http::server::bad_request, rep);
}
rep.status = http::server::ok;
rep.headers.clear();
rep.headers.push_back({.name = "Content-Type", .value = toString(mime_types::json)});
std::string result = R"({"settings":)";
result += api->loadSettings();
result += "}";
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
try {
std::stringstream ss;
ss.str(std::string(req.payload.begin(), req.payload.end()));
boost::property_tree::ptree pt;
read_json(ss, pt);
api->setQosSettings(pt);
std::string result = R"({"settings":)";
result += api->loadSettings();
result += "}";
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
} catch (std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "WebHandle(/api/set/qos): Can't set QoS settings: " << e.what();
const std::string result = R"({"status":"error"})";
rep.content.insert(rep.content.end(), result.c_str(), result.c_str() + result.size());
}
}));
}
~ServerResources() = default;

View File

@ -7,6 +7,8 @@
#include <shared_mutex>
#include <boost/thread.hpp>
#include <boost/log/trivial.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "../dependencies/control_system/common/protocol_commands.h"
@ -20,16 +22,16 @@ private:
void updateStatistics() {
modulator_state modulator{};
CP_GetModulatorState(sid, modulator);
demodulator_state demodulator{};
CP_GetDemodulatorState(sid, demodulator);
device_state device{};
std::lock_guard lock(this->cpApiMutex);
CP_GetModulatorState(sid, modulator);
CP_GetDemodulatorState(sid, demodulator);
CP_GetDeviceState(sid, device);
{
std::lock_guard lock(this->stateMutex);
std::lock_guard lock2(this->stateMutex);
this->modState = modulator;
this->demodState = demodulator;
this->devState = device;
@ -38,20 +40,22 @@ private:
void updateSettings() {
modulator_settings mod{};
CP_GetModulatorSettings(sid, mod);
// uint32_t modulatorModcod;
// CP_GetModulatorParams(sid, "modcod", &modulatorModcod);
demodulator_settings demod{};
CP_GetDemodulatorSettings(sid, demod);
ACM_parameters_serv_ acm{};
CP_GetAcmParams(sid, &acm);
DPDI_parmeters dpdi{};
CP_GetDpdiParams(sid, &dpdi);
buc_lnb_settings bucLnb{};
std::lock_guard lock(this->cpApiMutex);
CP_GetModulatorSettings(sid, mod);
CP_GetDemodulatorSettings(sid, demod);
CP_GetAcmParams(sid, &acm);
CP_GetDpdiParams(sid, &dpdi);
CP_GetBUC_LNB_settings(sid, bucLnb);
{
std::lock_guard lock(this->settingsMutex);
std::lock_guard lock2(this->settingsMutex);
this->modSettings = mod;
this->demodSettings = demod;
this->acmSettings = acm;
@ -60,6 +64,17 @@ private:
}
}
void updateQos() {
bool tmp1; std::string tmp2;
std::scoped_lock lock{this->cpApiMutex};
CP_GetQoSSettings(this->sid, tmp2, tmp1);
{
std::lock_guard lock2(this->qosSettingsMutex);
this->qosEnabled = tmp1;
this->qosClassesJson = tmp2;
}
}
void run() {
// это демон, который в бесконечном цикле опрашивает API
@ -67,12 +82,14 @@ private:
int64_t lastUpdate;
int64_t periodMs;
bool checkNeedUpdate(int64_t now) {
std::function<void()> callback;
bool checkNeedUpdate(int64_t now) const {
// тут нет смысла спать меньше чем на 20мс, поэтому можно разрешить чтение на некоторое время раньше
return now - lastUpdate >= (periodMs - 20);
}
int64_t getNextUpdate(int64_t now) {
int64_t getNextUpdate(int64_t now) const {
if (checkNeedUpdate(now)) {
return 0;
}
@ -81,40 +98,57 @@ private:
}
};
IntervalUpdate_t statUpdate{.lastUpdate = 0, .periodMs = CACHE_STATISTICS_UPDATE_MS};
IntervalUpdate_t settingsUpdate{.lastUpdate = 0, .periodMs = CACHE_SETTINGS_UPDATE_MS};
while (true) {
auto now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
if (statUpdate.checkNeedUpdate(now)) {
statUpdate.lastUpdate = now;
IntervalUpdate_t updaters[] = {
// обновление статистики
{.lastUpdate = 0, .periodMs = CACHE_STATISTICS_UPDATE_MS, .callback = [this]() {
try {
updateStatistics();
this->updateStatistics();
BOOST_LOG_TRIVIAL(debug) << "api_driver::TerminalApiDaemon::updateStatistics(): success update!";
} catch (std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "api_driver::TerminalApiDaemon::updateStatistics(): " << e.what();
}
now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
}
if (settingsUpdate.checkNeedUpdate(now)) {
settingsUpdate.lastUpdate = now;
}},
// обновление кеша настроек
{.lastUpdate = 0, .periodMs = CACHE_SETTINGS_UPDATE_MS, .callback = [this]() {
try {
updateSettings();
this->updateSettings();
BOOST_LOG_TRIVIAL(debug) << "api_driver::TerminalApiDaemon::updateSettings(): success update!";
} catch (std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "api_driver::TerminalApiDaemon::updateSettings(): " << e.what();
}
now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
}},
// обновление кеша QoS
{.lastUpdate = 0, .periodMs = CACHE_QOS_UPDATE_MS, .callback = [this]() {
try {
this->updateQos();
BOOST_LOG_TRIVIAL(debug) << "api_driver::TerminalApiDaemon::updateQos(): success update!";
} catch (std::exception& e) {
BOOST_LOG_TRIVIAL(error) << "api_driver::TerminalApiDaemon::updateQos(): " << e.what();
}
}}
};
while (true) {
int64_t sleepTime = 60000; // минута по-умолчанию
auto now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
for (auto& u: updaters) {
if (u.checkNeedUpdate(now)) {
u.lastUpdate = now;
u.callback();
now = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
}
sleepTime = std::min(sleepTime, u.getNextUpdate(now));
}
auto sleepTime = statUpdate.getNextUpdate(now);
sleepTime = std::min(sleepTime, settingsUpdate.getNextUpdate(now));
if (sleepTime > 0) {
boost::this_thread::sleep_for(boost::chrono::duration(boost::chrono::milliseconds(sleepTime)));
}
}
}
std::mutex cpApiMutex;
std::shared_mutex stateMutex;
modulator_state modState{};
demodulator_state demodState{};
@ -127,8 +161,14 @@ private:
DPDI_parmeters dpdiSettings{};
buc_lnb_settings bucLnbSettings{};
std::shared_mutex qosSettingsMutex;
bool qosEnabled;
std::string qosClassesJson;
public:
explicit TerminalApiDaemon(TSID sid): sid(sid), daemon([this]() { this->run(); }) {}
explicit TerminalApiDaemon(TSID sid): sid(sid), daemon([this]() { this->run(); }), qosEnabled(false) {
this->qosClassesJson = "{}";
}
/**
* Получение статистики, копирует текущие значения в структуры, переданные по указателю. Если передан пустой указатель, копирования не произойдет.
@ -159,6 +199,26 @@ public:
}
}
void getQosSettings(bool& isEnabled, std::string& json) {
std::shared_lock lock(this->settingsMutex);
isEnabled = this->qosEnabled;
json = this->qosClassesJson;
}
void setQosSettings(bool enabled, const std::string& str, bool readback = true) {
std::lock_guard lock(this->cpApiMutex);
CP_SetQoSSettings(this->sid, str, enabled);
if (readback) {
bool tmp1; std::string tmp2;
CP_GetQoSSettings(this->sid, tmp2, tmp1);
{
std::lock_guard lock2(this->qosSettingsMutex);
this->qosEnabled = tmp1;
this->qosClassesJson = tmp2;
}
}
}
~TerminalApiDaemon() {
try {
daemon.interrupt();
@ -404,12 +464,27 @@ std::string api_driver::ApiDriver::loadSettings() const {
result << ",\n\"serviceSettings.refClk10M\":" << boolAsStr(bucLnb.is_ref_10MHz_output);
result << ",\"serviceSettings.autoStart\":" << boolAsStr(bucLnb.is_save_current_state);
bool qosEnabled = false; std::string qosClasses;
daemon->getQosSettings(qosEnabled, qosClasses);
result << ",\n\"qos.enabled\":" << boolAsStr(qosEnabled);
result << ",\"qos.profile\":" << qosClasses;
result << "}";
return result.str();
}
api_driver::ApiDriver::~ApiDriver() = default;
void api_driver::ApiDriver::setQosSettings(boost::property_tree::ptree &pt) {
bool enabled = pt.get<bool>("en");
pt.erase("en");
std::ostringstream oss;
write_json(oss, pt);
this->daemon->setQosSettings(enabled, oss.str());
}
bool api_driver::ApiDriver::getIsCinC() const {
modulator_settings s{};
daemon->getSettings(&s, nullptr, nullptr, nullptr, nullptr);

View File

@ -3,6 +3,7 @@
#include <memory>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <terminal_api/ControlProtoCInterface.h>
@ -10,6 +11,7 @@ namespace api_driver {
constexpr int CACHE_STATISTICS_UPDATE_MS = 500;
constexpr int CACHE_SETTINGS_UPDATE_MS = 5000;
constexpr int CACHE_QOS_UPDATE_MS = 5000;
class TerminalApiDaemon;
@ -40,6 +42,8 @@ namespace api_driver {
~ApiDriver();
void setQosSettings(boost::property_tree::ptree & pt);
private:
TSID sid{0};
unsigned int access{0};

View File

@ -106,7 +106,7 @@ label * {
label {
margin: 1em 0.5em;
/*display: block;*/
display: block;
/*background: var(--bg-selected);*/
color: var(--text-color2);
}

View File

@ -349,7 +349,7 @@
<input v-model="param.cinc.position.station.longitude" type="number"/>
</label>
<label v-show="param.cinc.mode === 'positional'">
<span>Долгота спутника</span>
<span>Подспутниковая точка</span>
<input v-model="param.cinc.position.satelliteLongitude" type="number"/>
</label>
@ -443,7 +443,7 @@
<span class="summary-actions">
<label>
<span class="toggle-input">
<input type="checkbox" v-model="qosClass.isDisabled" />
<input type="checkbox" v-model="qosClass.isEnabled" />
<span class="slider"></span>
</span>
</label>
@ -472,7 +472,7 @@
<span class="summary-actions">
<label>
<span class="toggle-input">
<input type="checkbox" v-model="filter.isDisabled" />
<input type="checkbox" v-model="filter.isEnabled" />
<span class="slider"></span>
</span>
</label>
@ -517,19 +517,15 @@
</template>
<button class="action-button" @click="settingsSubmitQoS()">Применить <span class="submit-spinner" v-show="submitStatus.qos"></span></button>
<p>
Эти настройки пока недоступны, но скоро разработчик это поправит. А пока купи разработчику банку <strike>пива</strike> колы)
</p>
<video preload="auto" controls style="max-width: 100%">
<source src="/vid/video_2024-11-06_15-49-35.mp4" type="video/mp4" />
</video>
</div>
<div class="tabs-body-item" v-if="activeTab === 'admin'">
<p>
Эти настройки пока недоступны, но скоро разработчик это поправит. А пока смотри на крокодила
Эти настройки пока недоступны, но скоро разработчик это поправит. А пока смотри на крокодила, или купи разработчику банку <strike>пива</strike> колы для ускорения процесса)
</p>
<img loading="lazy" src="/images/krokodil_vzryvaetsya_hd.gif" alt="krokodil">
<video preload="auto" controls style="max-width: 100%">
<source src="/vid/video_2024-11-06_15-49-35.mp4" type="video/mp4" />
</video>
</div>
<p>Последнее обновление статистики: {{ lastUpdateTime }}</p>
</div>
@ -636,10 +632,6 @@
return { modulation: 'qpsk', speed: '1/4' }
}
Vue.component('qos-component-root', {
template: ""
})
const app = new Vue({
el: '#app',
data: {
@ -857,10 +849,12 @@
},
settingsSubmitRxTx() {
if (this.submitStatus.rxTx) { return }
this.submitStatus.rxTx = true
},
settingsSubmitCinC() {
if (this.submitStatus.cinc) { return }
this.submitStatus.cinc = true
},
@ -875,7 +869,7 @@
"serviceSettings.refClk10M": this.param.serviceSettings.refClk10M,
"serviceSettings.autoStart": this.param.serviceSettings.autoStart
}
fetch('/api/applyBucLnbSettings', {
fetch('/api/set/bucLnb', {
method: 'POST',
body: JSON.stringify(query)
}).then(() => {
@ -885,21 +879,79 @@
},
settingsSubmitQoS() {
if (this.submitStatus.qos) { return }
this.submitStatus.qos = true
function _translateQosClass(trafficClass, qc) {
let res = {
cir: qc['cir'],
description: qc['description'],
filters: []
}
if (trafficClass === 'cd') {
res.pir = qc.pir
}
if (!qc.isEnabled) {
res.disabled = true
}
for (const fi in qc.filters) {
let filter = {}
if (qc['filters'][fi].vlan !== "") { filter['vlan'] = qc['filters'][fi].vlan }
if (qc['filters'][fi].proto !== "") { filter['proto'] = qc['filters'][fi].proto }
if (qc['filters'][fi].sport !== "") { filter['sport'] = qc['filters'][fi].sport }
if (qc['filters'][fi].dport !== "") { filter['dport'] = qc['filters'][fi].dport }
if (qc['filters'][fi].ip_src !== "") { filter['ip.src'] = qc['filters'][fi].ip_src }
if (qc['filters'][fi].ip_dest !== "") { filter['ip.dest'] = qc['filters'][fi].ip_dest }
if (qc['filters'][fi].dscp !== "") { filter['dscp'] = qc['filters'][fi].dscp }
if (Object.keys(filter).length === 0) { continue }
if (!qc.filters[fi].isEnabled) { filter['disabled'] = true }
res.filters.push(filter)
}
return res
}
let query = {
"en": this.qos.en,
"rt1": [],
"rt2": [],
"rt3": [],
"cd": []
}
for (let i = 0; i < this.qos.rt1.length; i++) { query.rt1.push(_translateQosClass('rt', this.qos.rt1[i])) }
for (let i = 0; i < this.qos.rt2.length; i++) { query.rt2.push(_translateQosClass('rt', this.qos.rt2[i])) }
for (let i = 0; i < this.qos.rt3.length; i++) { query.rt3.push(_translateQosClass('rt', this.qos.rt3[i])) }
for (let i = 0; i < this.qos.cd.length; i++) { query.cd.push(_translateQosClass('rt', this.qos.cd[i])) }
console.log(query)
fetch('/api/set/qos', {
method: 'POST',
body: JSON.stringify(query)
}).then(async (response) => {
this.submitStatus.qos = false
this.updateQosSettings(await response.json())
})
},
performUpdateSettings() {
performUpdateSettings(reloadParts) {
const doFetchSettings = async () => {
let d = await fetch("/api/get/settings")
this.updateSettings(await d.json())
let vals = await d.json()
if (reloadParts !== undefined) {
if (reloadParts.indexOf('rxtx')) { this.updateRxTxSettings(vals) }
if (reloadParts.indexOf('cinc')) { this.updateCincSettings(vals) }
if (reloadParts.indexOf('buclnb')) { this.updateBucLnbSettings(vals) }
if (reloadParts.indexOf('qos')) { this.updateQosSettings(vals) }
} else {
this.updateSettings(vals)
}
}
doFetchSettings().then(() => {})
},
updateSettings(vals) {
this.settingFetchComplete = true
updateRxTxSettings(vals) {
this.submitStatus.rxTx = false
this.param.general.isCinC = vals["settings"]["general.isCinC"]
this.param.general.txEn = vals["settings"]["general.txEn"]
this.param.general.modulatorMode = vals["settings"]["general.modulatorMode"]
@ -939,7 +991,10 @@
this.param.rx.rolloff = vals["settings"]["rx.rolloff"]
this.param.rx.cymRate = vals["settings"]["rx.cymRate"]
this.param.rx.centerFreq = vals["settings"]["rx.centerFreq"]
},
updateCincSettings(vals) {
this.submitStatus.cinc = false
this.param.cinc.mode = vals["settings"]["cinc.mode"]
this.param.cinc.searchBandwidth = vals["settings"]["cinc.searchBandwidth"]
this.param.cinc.position.station.latitude = vals["settings"]["cinc.position.station.latitude"]
@ -947,7 +1002,10 @@
this.param.cinc.position.satelliteLongitude = vals["settings"]["cinc.position.satelliteLongitude"]
this.param.cinc.delayMin = vals["settings"]["cinc.delayMin"]
this.param.cinc.delayMax = vals["settings"]["cinc.delayMax"]
},
updateBucLnbSettings(vals) {
this.submitStatus.bucLnb = false
this.param.buc.refClk10M = vals["settings"]["buc.refClk10M"]
this.param.buc.powering = vals["settings"]["buc.powering"]
this.param.lnb.refClk10M = vals["settings"]["lnb.refClk10M"]
@ -956,12 +1014,76 @@
this.param.serviceSettings.autoStart = vals["settings"]["serviceSettings.autoStart"]
},
updateQosSettings(vals) {
this.submitStatus.qos = false
this.qos.en = vals["settings"]["qos.enabled"]
const qosProfile = vals["settings"]["qos.profile"]
if (qosProfile !== null && qosProfile !== undefined) {
this.qos.rt1 = [] // .splice(0, this.qos.rt1.length)
this.qos.rt2 = [] // .splice(0, this.qos.rt2.length)
this.qos.rt3 = [] // .splice(0, this.qos.rt3.length)
this.qos.cd = [] // .splice(0, this.qos.cd.length)
for (let trafficClass in qosProfile) {
if (['rt1', 'rt2', 'rt3', 'cd'].indexOf(trafficClass) < 0) {
continue
}
if (Array.isArray(qosProfile[trafficClass])) {
for (let i = 0; i < qosProfile[trafficClass].length; i++) {
const qc = qosProfile[trafficClass][i]
let result = {
isEnabled: !qc.hasOwnProperty('disabled'),
cir: qc['cir'],
pir: 0,
description: qc['description'],
filters: []
}
if (trafficClass === 'cd') {
if (qc['pir']) {
result.pir = qc['pir']
}
}
for (let fi = 0; fi < qc['filters'].length; fi++) {
result.filters.push({
isEnabled: !qc['filters'][fi].hasOwnProperty('disabled'),
vlan: qc['filters'][fi].hasOwnProperty('vlan') ? qc['filters'][fi]['vlan'] : '',
proto: qc['filters'][fi].hasOwnProperty('proto') ? qc['filters'][fi]['proto'] : '',
sport: qc['filters'][fi].hasOwnProperty('sport') ? qc['filters'][fi]['sport'] : '',
dport: qc['filters'][fi].hasOwnProperty('dport') ? qc['filters'][fi]['dport'] : '',
ip_src: qc['filters'][fi].hasOwnProperty('ip.src') ? qc['filters'][fi]['ip.src'] : '',
ip_dest: qc['filters'][fi].hasOwnProperty('ip.dest') ? qc['filters'][fi]['ip.dest'] : '',
dscp: qc['filters'][fi].hasOwnProperty('dscp') ? qc['filters'][fi]['dscp'] : ''
})
}
switch (trafficClass) {
case 'rt1': this.qos.rt1.push(result); break
case 'rt2': this.qos.rt2.push(result); break
case 'rt3': this.qos.rt3.push(result); break
case 'cd': this.qos.cd.push(result); break
}
}
}
}
}
},
updateSettings(vals) {
this.settingFetchComplete = true
this.updateRxTxSettings(vals)
this.updateCincSettings(vals)
this.updateBucLnbSettings(vals)
this.updateQosSettings(vals)
},
// addQosClass()
qosAddClass(name) {
let res = {
isDisabled: false,
isEnabled: true,
cir: 0,
pir: 0,
description: "",
filters: []
}
switch (name) {
@ -974,7 +1096,7 @@
qosClassAddRule(name, index) {
let rule = {
isDisabled: false,
isEnabled: true,
vlan: "",
proto: "",
sport: "",
@ -1014,6 +1136,9 @@
let result = ""
let isFirst = true;
for (const key in filter) {
if (key === "isEnabled") {
continue
}
if (!filter[key]) {
continue
}
@ -1035,6 +1160,9 @@
result = ""
isFirst = true;
for (const key in filter) {
if (key === "isEnabled") {
continue
}
if (!filter[key]) {
continue
}