repo_id stringlengths 6 101 | size int64 367 5.14M | file_path stringlengths 2 269 | content stringlengths 367 5.14M |
|---|---|---|---|
281677160/openwrt-package | 2,518 | luci-app-natter2/luasrc/model/cbi/natter2/base.lua | m = Map("natter2", translate("Natter v2"),
translate("Expose your port behind full-cone NAT to the Internet")
.. [[<br /><br /><a href="https://github.com/MikeWang000000/Natter">]]
.. translate("Project")
.. [[</a>]]
)
s = m:section(TypedSection, "base")
s.addremove = false
s.anonymous = true
local function check_file(e)
return luci.sys.exec('ls "%s" 2> /dev/null' % e) ~= "" and true or false
end
enable = s:option(Flag, "enable", translate("Enable"))
enable.default = 0
if check_file("/tmp/natter2_nat_type") then
natter_nat_type_tcp = luci.sys.exec ("grep TCP /tmp/natter2_nat_type")
natter_nat_type_udp = luci.sys.exec ("grep UDP /tmp/natter2_nat_type")
nat_check = s:option (Button, "nat_check", translate("Check NAT Status"), translate("") .. "<br><br>" .. natter_nat_type_tcp .. "<br><br>" .. natter_nat_type_udp)
else
nat_check = s:option (Button, "nat_check", translate("Check NAT Status"), translate("Tips")
.. [[<br />]] .. translate("After clicking Exec button, please wait for the luci to refresh"))
end
nat_check.inputtitle = translate("Exec")
nat_check.write = function()
luci.sys.call ("sh /usr/share/luci-app-natter2/nat-check.sh")
luci.http.redirect(luci.dispatcher.build_url("admin", "network", "natter2", "base"))
end
tmp_path = s:option(Value, "tmp_path", translate("Tmp Path"))
tmp_path.default = "/tmp/natter2"
tmp_path.placeholder = "/tmp/natter2"
tmp_path.rmempty = false
s = m:section(TypedSection, "instances", translate("Instances"), translate("Setting up multiple instances"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s.extedit = luci.dispatcher.build_url("admin", "network", "natter2", "instances", "%s")
function s.create(...)
local e=TypedSection.create(...)
if e then
luci.http.redirect(s.extedit%e)
return
end
end
enable_instance = s:option(Flag, "enable_instance", translate("Enable"))
enable_instance.default = 1
enable_instance.width = "5%"
remark = s:option(DummyValue,"remark",translate("Remark"))
remark.width = "5%"
protocol = s:option(DummyValue,"protocol",translate("Protocol"))
remark.width = "5%"
tmp_public_port = s:option(DummyValue, "tmp_public_port", translate("Public Port"))
remark.width = "5%"
target_address = s:option(DummyValue, "target_address", translate("Target Address"))
remark.width = "5%"
target_port = s:option(DummyValue, "target_port", translate("Target Port"))
remark.width = "5%"
notify_path = s:option(DummyValue, "notify_path", translate("Notify Script Path"))
remark.width = "5%"
return m
|
281677160/openwrt-package | 2,403 | luci-app-natter2/po/zh_Hans/natter2.po | msgid "Natter v2"
msgstr "Natter v2 测试版"
msgid "Base Settings"
msgstr "基础设置"
msgid "Log"
msgstr "日志"
msgid "Expose your port behind full-cone NAT to the Internet"
msgstr "将 FullCone NAT (NAT 1) 后的端口,打洞暴露至互联网"
msgid "Project"
msgstr "项目地址"
msgid "Enable"
msgstr "启用"
msgid "Check NAT Status"
msgstr "NAT 类型检测"
msgid "Proxy programs may affect NAT types"
msgstr "代理程序可能会影响 NAT 类型"
msgid "Tmp Path"
msgstr "临时路径"
msgid "Instances"
msgstr "实例"
msgid "Setting up multiple instances"
msgstr "设置多个实例"
msgid "Remark"
msgstr "备注"
msgid "Public Port"
msgstr "公开端口"
msgid "Target Address"
msgstr "目标地址"
msgid "Target Port"
msgstr "目标端口"
msgid "Notify Script Path"
msgstr "通知脚本路径"
msgid "Enable Stun Server"
msgstr "自定义 STUN 服务器"
msgid "STUN Server"
msgstr "STUN 服务器"
msgid "Enable Keepalive Server"
msgstr "自定义保活服务器"
msgid "Keepalive Server"
msgstr "保活服务器"
msgid "Interval (Seconds)"
msgstr "保活间隔(秒)"
msgid "The number of seconds between keepalive"
msgstr "每次保活的间隔秒数"
msgid "Enable Bonding Options"
msgstr "启用绑定"
msgid "Bonding Interface"
msgstr "绑定接口"
msgid "Bonding Port"
msgstr "绑定端口"
msgid "Enable Forwarding Options"
msgstr "启用转发"
msgid "Forwarding to internal devices"
msgstr "转发至内部设备"
msgid "Forwarding Method"
msgstr "转发方式"
msgid "Instructions for forwarding method"
msgstr "转发方式说明"
msgid "socket (Not Recommended)"
msgstr "Socket(内置, 不推荐)"
msgid "iptables (Recommended)"
msgstr "iptables(防火墙, 推荐)"
msgid "nftables (Recommended)"
msgstr "nftables(防火墙, 推荐)"
msgid "Target Address"
msgstr "目标地址"
msgid "Target Port"
msgstr "目标端口"
msgid "Enable Forwarding Retry"
msgstr "自动重试"
msgid "Retry until the target port is open"
msgstr "重试直至目标端口开放"
msgid "Enable Quit"
msgstr "自动退出"
msgid "Exit immediately when the mapping address changes"
msgstr "映射地址改变时立即退出"
msgid "Time to wait before starting this instance"
msgstr "启动该实例前等待的时间"
msgid "Enable Notify Script"
msgstr "启用通知脚本"
msgid "Instructions for using the notification script"
msgstr "通知脚本说明"
msgid "Start delay (Seconds)"
msgstr "启动延时(秒)"
msgid "Log Level"
msgstr "日志级别"
msgid "Normal"
msgstr "正常"
msgid "Verbose"
msgstr "详细"
msgid "Instructions"
msgstr "使用说明"
msgid "Using customized STUN server"
msgstr "使用自定义的 STUN 服务器"
msgid "Using customized Keepalive server"
msgstr "使用自定义的保活服务器"
msgid "Tips"
msgstr "提示"
msgid "After clicking Exec button, please wait for the luci to refresh"
msgstr "点击执行后,请耐心等待页面自动刷新"
|
281677160/openwrt-package | 3,557 | luci-app-natter2/root/etc/init.d/natter2 | #!/bin/sh /etc/rc.common
START=98
script_path="/usr/share/natter2/natter.py"
start_service() {
local basic_list="enable tmp_path"
local instance_list="enable_instance id remark protocol enable_stun_server \
stun_server enable_keepalive_server keepalive_server \
interval enable_bonding bonding_interface bonding_port \
enable_forwarding forwarding_method target_address target_port \
enable_forwarding_retry enable_quit delay log_level enable_notify \
notify_path"
for i in $basic_list
do
local eval $i="$(uci_get_by_type base 0 $i)"
done ; unset i
if [ "$enable" == 1 ]
then
mkdir -p ${tmp_path}
mkdir -p /var/etc/natter2
for u in $(seq 0 $(($(uci show natter2 2> /dev/null | egrep '@instances\[[0-9]\]+=instances' | wc -l) - 1)))
do
for i in $instance_list
do
local eval $i="$(uci_get_by_type instances $u $i)"
# echo "$i : $(uci_get_by_type instances $u $i)"
done ; unset i
[ "$enable_instance" != 1 ] && continue
script_command=""
[ "$protocol" == udp ] && script_command="$script_command -u"
if [ "$enable_stun_server" == 1 ]
then
for i in $stun_server
do
script_command="$script_command -s $i"
done ; unset i
fi
[ "$enable_keepalive_server" == 1 ] && script_command="$script_command -h $keepalive_server"
[ "$interval" ] && script_command="$script_command -k $interval"
if [ "$enable_bonding" == 1 ]
then
[ "$bonding_interface" ] && script_command="$script_command -i $bonding_interface"
[ "$bonding_port" ] && script_command="$script_command -b $bonding_port"
fi
if [ "$enable_forwarding" == 1 ]
then
[ "$forwarding_method" ] && script_command="$script_command -m $forwarding_method"
[ "$target_address" ] && script_command="$script_command -t $target_address"
[ "$target_port" ] && script_command="$script_command -p $target_port"
[ "$enable_forwarding_retry" == 1 ] && script_command="$script_command -r"
fi
[ "$enable_quit" == 1 ] && script_command="$script_command -q"
[ "$log_level" == "verbose" ] && script_command="$script_command -v"
if [ "$enable_notify" == 1 ]
then
echo "$notify_path" > /var/etc/natter2/${id}-notify
var_file=/var/etc/natter2/${id}-${u}-1
else
var_file=/var/etc/natter2/${id}-${u}-0
fi
log_file=${tmp_path}/natter2-${id}.log
cp -a /usr/share/luci-app-natter2/notify-base.sh $var_file
chmod +x $var_file
# echo "log_file: $log_file"
# echo "var_file: $var_file"
sleep $delay
for i in $(ps -efww | grep "$script_path" | grep -v grep | grep -v $$ | grep "$id" | awk '{print $1}')
do
kill -9 "$i" 2> /dev/null
done
nohup $(command -v python) "$script_path" $script_command -e $var_file > "$log_file" 2>&1 &
for i in $instance_list
do
unset $(echo $i)
done ; unset i
unset script_command
done ; unset u
else
stop_service
fi
}
stop_service() {
echo "Stopping Natter2 ..."
for i in $(ps -efww | grep "$script_path" | grep -v grep | grep -v $$ | awk '{print $1}')
do
kill -9 "$i" 2> /dev/null
done
rm -r "$tmp_path" 2> /dev/null
for u in $(seq 0 $(($(uci show natter2 2> /dev/null | egrep '@instances\[[0-9]\]+=instances' | wc -l) - 1)))
do
uci set natter2.@instances[$u].tmp_public_port=""
uci commit natter2
done
rm -f /tmp/natter2_nat_type
}
restart() {
stop_service
start_service
}
service_triggers() {
procd_add_reload_trigger "natter2"
}
uci_get_by_type() {
local ret=$(uci get natter2.@$1[$2].$3 2>/dev/null)
echo ${ret:=$4}
}
|
281677160/openwrt-package | 5,736 | luci-app-timecontrol/luci-app-nft-timecontrol/luasrc/model/cbi/timecontrol.lua | -- Copyright 2022-2023 sirpdboy <herboy2008@gmail.com>
-- Licensed to the public under the Apache License 2.0.
local sys = require "luci.sys"
local ifaces = sys.net:devices()
local WADM = require "luci.tools.webadmin"
local ipc = require "luci.ip"
local a, t, e
a = Map("timecontrol", translate("Internet time control"))
a.description = translate("Users can limit their internet usage time through MAC and IP, with available IP ranges such as 192.168.110.00 to 192.168.10.200")..translate("Suggested feedback:")..translate("<a href=\'' target=\'_blank\'></a>")
a.template = "timecontrol/index"
t = a:section(TypedSection, "timecontrol")
t.anonymous = true
e = t:option(DummyValue, "timecontrol_status", translate("Status"))
e.template = "timecontrol/timecontrol"
e.value = translate("Collecting data...")
e = t:option(ListValue, "list_type",translate("Control mode"), translate("blacklist:Block the networking of the target address,whitelist:Only allow networking for the target address and block all other addresses."))
e.rmempty = false
e:value("blacklist", translate("blacklist"))
-- e:value("whitelist", translate("whitelist"))
e.default = "blacklist"
e = t:option(ListValue, "chain",translate("Control intensity"), translate("Pay attention to strong control: machines under control will not be able to connect to the software router backend!"))
e.rmempty = false
-- e:value("forward", translate("Ordinary forwarding control"))
e:value("input", translate("Strong inbound control"))
e.default = "input"
t = a:section(TypedSection, "device")
t.template = "cbi/tblsection"
t.anonymous = true
t.addremove = true
comment = t:option(Value, "comment", translate("Comment"))
comment.size = 8
e = t:option(Flag, "enable", translate("Enabled"))
e.rmempty = false
e.size = 4
ip = t:option(Value, "mac", translate("IP/MAC"))
ip.size = 8
-- 替换原有的 get_devices() 函数
local function get_devices()
local devices = {}
local seen_ips = {}
local ubus = require "ubus"
local conn = ubus.connect()
-- 辅助函数:尝试获取主机名
local function get_hostname(ip)
-- 方法1: 使用 nslookup
local f = io.popen("nslookup "..ip.." 2>/dev/null | grep 'name =' | cut -d'=' -f2 | sed 's/\\.$//'")
if f then
local name = f:read("*l")
f:close()
if name and name ~= "" then
return name:match("^%s*(.-)%s*$") -- 去除前后空格
end
end
-- 方法2: 读取 /tmp/dhcp.leases
local leases_file = io.open("/tmp/dhcp.leases", "r")
if leases_file then
for line in leases_file:lines() do
local mac, ip_lease, _, hostname = line:match("^(%S+)%s+(%S+)%s+(%S+)%s+(%S+)")
if ip_lease == ip and hostname ~= "*" then
leases_file:close()
return hostname
end
end
leases_file:close()
end
return "unknown"
end
-- 1. 从DHCP租约获取设备
if conn then
local leases = conn:call("dhcp", "ipv4leases", {}) or {}
for _, lease in ipairs(leases) do
if lease.ipaddr and lease.mac then
local hostname = lease.hostname or get_hostname(lease.ipaddr)
devices[#devices+1] = {
ip = lease.ipaddr,
mac = lease.mac:upper(), -- 统一转为大写
hostname = hostname,
display = string.format("%s (%s) - %s", lease.ipaddr, lease.mac:upper(), hostname)
}
seen_ips[lease.ipaddr] = true
end
end
conn:close()
end
-- 2. 从ARP表获取设备(使用ip neigh命令)
local arp_cmd = io.popen("ip -4 neigh show dev br-lan 2>/dev/null")
if arp_cmd then
for line in arp_cmd:lines() do
local ip_addr, mac = line:match("^(%S+)%s+.+%s+(%S+)%s+")
if ip_addr and mac and mac ~= "00:00:00:00:00:00" and not seen_ips[ip_addr] then
mac = mac:upper() -- 统一MAC地址格式
local hostname = get_hostname(ip_addr)
devices[#devices+1] = {
ip = ip_addr,
mac = mac,
hostname = hostname,
display = string.format("%s (%s) - %s", ip_addr, mac, hostname)
}
seen_ips[ip_addr] = true
end
end
arp_cmd:close()
end
-- 按IP地址排序设备列表
table.sort(devices, function(a, b) return a.ip < b.ip end)
return devices
end
-- 添加设备选项
local devices = get_devices()
for _, dev in ipairs(devices) do
ip:value(dev.ip, dev.display)
end
function validate_time(self, value, section)
local hh, mm, ss
hh, mm, ss = string.match(value, "^(%d?%d):(%d%d)$")
hh = tonumber(hh)
mm = tonumber(mm)
if hh and mm and hh <= 23 and mm <= 59 then
return value
else
return nil, "Time HH:MM or space"
end
end
e = t:option(Value, "timestart", translate("Start control time"))
e.placeholder = '00:00'
e.default = '00:00'
e.validate = validate_time
e.rmempty = true
e.size = 4
e = t:option(Value, "timeend", translate("Stop control time"))
e.placeholder = '00:00'
e.default = '00:00'
e.validate = validate_time
e.rmempty = true
e.size = 4
week=t:option(Value,"week",translate("Week Day(1~7)"))
week.rmempty = true
week:value('0',translate("Everyday"))
week:value(1,translate("Monday"))
week:value(2,translate("Tuesday"))
week:value(3,translate("Wednesday"))
week:value(4,translate("Thursday"))
week:value(5,translate("Friday"))
week:value(6,translate("Saturday"))
week:value(7,translate("Sunday"))
week:value('1,2,3,4,5',translate("Workday"))
week:value('6,7',translate("Rest Day"))
week.default='0'
week.size = 6
return a
|
281677160/openwrt-package | 1,740 | luci-app-timecontrol/luci-app-nft-timecontrol/po/zh_Hans/timecontrol.po | msgid "Control"
msgstr "管控"
msgid "Timecontrol"
msgstr "时间控制"
msgid "Internet time control"
msgstr "上网时间控制"
msgid "Enabled"
msgstr "启用"
msgid "Monday"
msgstr "周一"
msgid "Tuesday"
msgstr "周二"
msgid "Wednesday"
msgstr "周三"
msgid "Thursday"
msgstr "周四"
msgid "Friday"
msgstr "周五"
msgid "Saturday"
msgstr "周六"
msgid "Sunday"
msgstr "周日"
msgid "Not running"
msgstr "未运行"
msgid "Running"
msgstr "运行中"
msgid "Users can limit their internet usage time through MAC and IP, with available IP ranges such as 192.168.110.00 to 192.168.10.200"
msgstr "可以通过MAC,IP限制用户上网时间,可用IP范围如:192.168.10.100-192.168.10.200."
msgid "IP/MAC"
msgstr "IP/MAC"
msgid "Comment"
msgstr "备注"
msgid "Start control time"
msgstr "起控时间"
msgid "Stop control time"
msgstr "停控时间"
msgid "Week Day(1~7)"
msgstr "星期(1~7)"
msgid "Suggested feedback:"
msgstr "建议反馈:"
msgid "Control mode"
msgstr "控制模式"
msgid "Block the networking of the target address."
msgstr "阻止目标地址的联网."
msgid "Only allow networking for the target address and block all other addresses."
msgstr "仅允许目标地址的联网,阻止其他所有地址."
msgid "blacklist:Block the networking of the target address,whitelist:Only allow networking for the target address and block all other addresses."
msgstr "黑名单模式:阻止目标地址的联网,白名单模式:仅允许目标地址的联网,阻止其他所有地址."
msgid "blacklist"
msgstr "黑名单模式"
msgid "whitelist"
msgstr "白名单模式"
msgid "Rest Day"
msgstr "休息日"
msgid "Workday"
msgstr "工作日"
msgid "Automatic settings"
msgstr "自动设置"
msgid "Ordinary forwarding control"
msgstr "普通转发管控"
msgid "Strong inbound control"
msgstr "强力入站管控"
msgid "Control intensity"
msgstr "管控强度"
msgid "Pay attention to strong control: machines under control will not be able to connect to the software router backend!"
msgstr "注意强力管控:被管控的机器将无法连接上软路由后台!"
|
281677160/openwrt-package | 2,916 | luci-app-onliner/luasrc/view/onliner/onliner.htm | <%#
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2011 Jo-Philipp Wich <jow@openwrt.org>
Licensed to the public under the Apache License 2.0.
-%>
<%
local util = require "luci.util"
local function online_data()
local rv = { }
local fd = util.execi('/usr/bin/awk \'BEGIN{while ((getline < "/tmp/dhcp.leases") > 0){a[$2]=$4;}while ((getline < "/proc/net/arp") > 0){if (!a[$4]){a[$4]="\?";}if (match($3,"0x[26]")){"ping -q -c 1 "$1" &";if (b[$4]){b[$4]=b[$4]"/"$1;}else{b[$4]=$1;}c[$4]=$6;}}while (("ip -6 neighbor show | grep -v fe80" | getline) > 0){if (b[$5]) {"ping -q -c 1 "$1" &";b[$5]=b[$5]"/"$1;}}for (mac in b){print(a[mac],b[mac],mac,c[mac]);}}\' ')
while true do
local ln = fd()
if ln == nil then break end
local name,ip,mac,dev = ln:match("^(%S+) (%S+) (%S+) (%S+)")
if mac and ip and name and dev then
rv[#rv+1] = {
hostname = name,
device = dev,
macaddr = mac,
ipaddr = ip
}
end
end
return rv
end
if luci.http.formvalue("status") == "1" then
local rv = {
onlines = online_data()
}
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
return
end
-%>
<%+header%>
<script type="text/javascript" src="<%=resource%>/cbi.js?v=git-19.271.33176-b099749"></script>
<script type="text/javascript">//<![CDATA[
var npoll = 1;
XHR.poll(5, '<%=REQUEST_URI%>', { status: 1 },
function(x, info)
{
var ls = document.getElementById('online_status_table');
if (ls)
{
/* clear all rows */
while( ls.rows.length > 1 )
ls.rows[0].parentNode.deleteRow(1);
for( var i = 0; i < info.onlines.length; i++ )
{
var tr = ls.rows[0].parentNode.insertRow(-1);
tr.className = 'cbi-section-table-row cbi-rowstyle-' + ((i % 2) + 1);
tr.insertCell(-1).innerHTML = info.onlines[i].hostname ? info.onlines[i].hostname : '?';
tr.insertCell(-1).innerHTML = info.onlines[i].ipaddr.split("/").join("<br>");
tr.insertCell(-1).innerHTML = info.onlines[i].macaddr;
tr.insertCell(-1).innerHTML = info.onlines[i].device;
}
if( ls.rows.length == 1 )
{
var tr = ls.rows[0].parentNode.insertRow(-1);
tr.className = 'cbi-section-table-row';
var td = tr.insertCell(-1);
td.colSpan = 4;
td.innerHTML = '<em><br /><%:当前无用户在线%></em>';
}
}
}
);
//]]></script>
<h2 name="content"><%:Status%></h2>
<fieldset class="cbi-section">
<legend><%:在线用户%></legend>
<table class="cbi-section-table" id="online_status_table">
<tr class="cbi-section-table-titles">
<th class="cbi-section-table-cell"><%:Hostname%></th>
<th class="cbi-section-table-cell"><%:IP Address%></th>
<th class="cbi-section-table-cell"><%:MAC Address%></th>
<th class="cbi-section-table-cell"><%:Interface%></th>
</tr>
<tr class="cbi-section-table-row">
<td colspan="4"><em><br /><%:Collecting data...%></em></td>
</tr>
</table>
</fieldset>
<%+footer%> |
281677160/openwrt-package | 23,312 | luci-app-onliner/luasrc/view/onliner/display.htm | <%#
Copyright 2017 Jo-Philipp Wich <jo@mein.io>
Licensed to the public under the Apache License 2.0.
-%>
<% css = [[
#chartjs-tooltip {
opacity: 0;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
padding: 3px;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
z-index: 200;
}
#chartjs-tooltip.above {
-webkit-transform: translate(-50%, -100%);
transform: translate(-50%, -100%);
}
#chartjs-tooltip.above:before {
border: solid;
border-color: #111 transparent;
border-color: rgba(0, 0, 0, .8) transparent;
border-width: 8px 8px 0 8px;
bottom: 1em;
content: "";
display: block;
left: 50%;
top: 100%;
position: absolute;
z-index: 99;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
table {
border: 1px solid #999;
border-collapse: collapse;
margin: 0 0 2px !important;
}
th, td, table table td {
border: 1px solid #999;
text-align: right;
padding: 1px 3px !important;
white-space: nowrap;
}
tbody td {
border-bottom-color: #ccc;
}
tbody td:nth-last-child(4) {
width: 10%;
}
tbody td:nth-last-child(3) {
width: 10%;
}
tbody td:nth-last-child(2) {
width: 10%;
}
tbody td:nth-last-child(1) {
width: 10%;
}
tbody td[rowspan] {
border-bottom-color: #999;
}
tbody tr:last-child td {
border-bottom-color: #999;
}
.kpi {
display: inline-block;
vertical-align: top;
}
.kpi ul {
list-style: none;
}
.kpi li {
margin: 10px;
display: none;
}
.kpi big {
font-weight: bold;
}
#detail-bubble {
position: absolute;
opacity: 0;
visibility: hidden;
}
#detail-bubble.in {
opacity: 1;
visibility: visible;
transition: opacity 0.5s;
}
#detail-bubble > div {
border: 1px solid #ccc;
border-radius: 2px;
padding: 5px;
background: #fcfcfc;
}
#detail-bubble .head {
text-align: center;
white-space: nowrap;
position: relative;
}
#detail-bubble .head .dismiss {
top: 0;
right: 0;
width: 20px;
line-height: 20px;
text-align: center;
text-decoration: none;
font-weight: bold;
color: #000;
position: absolute;
font-size: 20px;
}
#detail-bubble .kpi {
margin: 40px 5px 5px;
font-size: smaller;
text-align: left;
}
#detail-bubble .kpi ul {
margin: 0;
}
#bubble-arrow {
border: 1px solid #ccc;
border-width: 1px 0 0 1px;
background: #fcfcfc;
width: 15px;
height: 15px;
position: absolute;
left: 0;
top: -8px;
transform: rotate(45deg);
margin: 0 0 0 -8px;
}
tr.active > td {
border-bottom: 2px solid red;
}
tr.active > td.active {
border: 2px solid red;
border-bottom: none;
}
td.detail {
border: 2px solid red;
border-top: none;
opacity: 0;
transition: opacity 0.5s;
}
td.detail.in {
opacity: 1;
}
th.hostname,
td.hostname {
text-align: left;
}
]] -%>
<%+header%>
<script type="text/javascript" src="<%=resource%>/cbi.js?v=git-19.338.43082-9e87e69"></script>
<script type="text/javascript" src="<%=resource%>/nlbw.chart.min.js?v=git-19.338.43082-9e87e69"></script>
<script type="text/javascript">//<![CDATA[
var chartRegistry = {},
trafficPeriods = [],
trafficData = { columns: [], data: [] },
hostNames = {},
hostInfo = <%=luci.util.serialize_json(luci.sys.net.host_hints())%>,
ouiData = [];
function off(elem)
{
var val = [0, 0];
do {
if (!isNaN(elem.offsetLeft) && !isNaN(elem.offsetTop)) {
val[0] += elem.offsetLeft;
val[1] += elem.offsetTop;
}
}
while ((elem = elem.offsetParent) != null);
return val;
}
Chart.defaults.global.customTooltips = function(tooltip) {
var tooltipEl = document.getElementById('chartjs-tooltip');
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.setAttribute('id', 'chartjs-tooltip');
document.body.appendChild(tooltipEl);
}
if (!tooltip) {
if (tooltipEl.row)
tooltipEl.row.style.backgroundColor = '';
tooltipEl.style.opacity = 0;
return;
}
var pos = off(tooltip.chart.canvas);
tooltipEl.className = tooltip.yAlign;
tooltipEl.innerHTML = tooltip.text[0];
tooltipEl.style.opacity = 1;
tooltipEl.style.left = pos[0] + tooltip.x + 'px';
tooltipEl.style.top = pos[1] + tooltip.y - tooltip.caretHeight - tooltip.caretPadding + 'px';
var row = tooltip.text[1],
hue = tooltip.text[2];
if (row && !isNaN(hue)) {
row.style.backgroundColor = 'hsl(%u, 100%%, 80%%)'.format(hue);
tooltipEl.row = row;
}
};
Chart.defaults.global.tooltipFontSize = 10;
Chart.defaults.global.tooltipTemplate = function(tip) {
tip.label[0] = tip.label[0].format(tip.value);
return tip.label;
};
function kpi(id, val1, val2, val3)
{
var e = document.getElementById(id);
if (val1 && val2 && val3)
e.innerHTML = '<%:%s, %s and %s%>'.format(val1, val2, val3);
else if (val1 && val2)
e.innerHTML = '<%:%s and %s%>'.format(val1, val2);
else if (val1)
e.innerHTML = val1;
e.parentNode.style.display = val1 ? 'list-item' : '';
}
function query(filter, group, order)
{
var keys = [], columns = {}, records = {}, result = [];
if (typeof(group) !== 'function' && typeof(group) !== 'object')
group = ['mac'];
for (var i = 0; i < trafficData.columns.length; i++)
columns[trafficData.columns[i]] = i;
for (var i = 0; i < trafficData.data.length; i++) {
var record = trafficData.data[i];
if (typeof(filter) === 'function' && filter(columns, record) !== true)
continue;
var key;
if (typeof(group) === 'function') {
key = group(columns, record);
}
else {
key = [];
for (var j = 0; j < group.length; j++)
if (columns.hasOwnProperty(group[j]))
key.push(record[columns[group[j]]]);
key = key.join(',');
}
if (!records.hasOwnProperty(key)) {
var rec = {};
for (var col in columns)
rec[col] = record[columns[col]];
records[key] = rec;
result.push(rec);
}
else {
records[key].conns += record[columns.conns];
records[key].rx_bytes += record[columns.rx_bytes];
records[key].rx_pkts += record[columns.rx_pkts];
records[key].tx_bytes += record[columns.tx_bytes];
records[key].tx_pkts += record[columns.tx_pkts];
}
}
if (typeof(order) === 'function')
result.sort(order);
return result;
}
function oui(mac) {
var m, l = 0, r = ouiData.length / 3 - 1;
var mac1 = parseInt(mac.replace(/[^a-fA-F0-9]/g, ''), 16);
while (l <= r) {
m = l + Math.floor((r - l) / 2);
var mask = (0xffffffffffff -
(Math.pow(2, 48 - ouiData[m * 3 + 1]) - 1));
var mac1_hi = ((mac1 / 0x10000) & (mask / 0x10000)) >>> 0;
var mac1_lo = ((mac1 & 0xffff) & (mask & 0xffff)) >>> 0;
var mac2 = parseInt(ouiData[m * 3], 16);
var mac2_hi = (mac2 / 0x10000) >>> 0;
var mac2_lo = (mac2 & 0xffff) >>> 0;
if (mac1_hi === mac2_hi && mac1_lo === mac2_lo)
return ouiData[m * 3 + 2];
if (mac2_hi > mac1_hi ||
(mac2_hi === mac1_hi && mac2_lo > mac1_lo))
r = m - 1;
else
l = m + 1;
}
return null;
}
var bakdataold;
var bakdatanew;
function fetchData(period)
{
XHR.poll(2,'<%=url("admin/nlbw/data")%>', { period: period, group_by: 'family,mac,ip,layer7' }, function(xhr, res) {
if (res !== null && typeof(res) === 'object' && typeof(res.columns) === 'object' && typeof(res.data) === 'object')
trafficData = res;
trafficData["data"].sort();
bakdatanew = JSON.parse(JSON.stringify(trafficData["data"]));
if (bakdataold){
var j=0;
var k=j;
var ll=bakdataold.length;
for (i=0,l=trafficData["data"].length; i<l ; i++){
one=trafficData["data"][i];
for (j=k;j<ll;j++){
if (one[0]==bakdataold[j][0] && one[1]==bakdataold[j][1] && one[2]==bakdataold[j][2] && one[3]==bakdataold[j][3] && one[4]==bakdataold[j][4] ){
one[5]=(one[5]-bakdataold[j][5])/2;
one[6]=(one[6]-bakdataold[j][6])/2;
one[7]=(one[7]-bakdataold[j][7])/2;
one[8]=(one[8]-bakdataold[j][8])/2;
one[9]=(one[9]-bakdataold[j][9])/2;
k=j+1;
break;
}
}
}
}
bakdataold=bakdatanew;
var addrs = query(null, ['ip'], null);
var ipAddrs = [];
for (var i = 0; i < addrs.length; i++)
if (ipAddrs.indexOf(addrs[i].ip) < 0)
ipAddrs.push(addrs[i].ip);
if (hostNames.length == 0){
XHR.get('<%=url("admin/nlbw/ptr")%>/' + ipAddrs.join('/'), null, function(xhr, res) {
if (res !== null && typeof(res) === 'object')
hostNames = res;
});
}
renderHostData();
renderLayer7Data();
renderIPv6Data();
});
XHR.poll(5,'<%=url([[admin]], [[status]], [[onliner]], [[setnlbw]])%>', null, function(xhr, res) {
});
}
function switchTab(tab)
{
bubbleDismiss();
return cbi_t_switch('nlbw', tab);
}
function renderHostDetail()
{
var key = this.getAttribute('href').substr(1),
col = this.getAttribute('data-col'),
label = this.getAttribute('data-label'),
bubble = document.getElementById('detail-bubble'),
arrow = document.getElementById('bubble-arrow'),
table = document.getElementById('bubble-table');
bubbleDismiss();
var detailData = query(
function(c, r) {
return ((r[c.mac] === key || r[c.ip] === key) &&
(r[c.rx_bytes] > 0 || r[c.tx_bytes] > 0));
},
[col],
function(r1, r2) {
return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
}
);
var rxData = [], txData = [];
table.innerHTML = '<tr>' +
'<th>%s</th>'.format(label || col) +
'<th><%:Conn.%></th>' +
'<th colspan="2"><%:Down. (Bytes / Pkts.)%></th>' +
'<th colspan="2"><%:Up. (Bytes / Pkts.)%></th>' +
'</tr>';
for (var i = 0; i < detailData.length; i++) {
var rec = detailData[i],
row = table.insertRow(-1);
row.insertCell(-1).innerHTML = rec[col] || '<%:other%>';
row.insertCell(-1).innerHTML = "%1000.2m".format(rec.conns);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.rx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.rx_pkts);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.tx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.tx_pkts);
rxData.push({
label: ['%s: %%1024.2mB'.format(rec[col] || '<%:other%>'), row],
value: rec.rx_bytes
});
txData.push({
label: ['%s: %%1024.2mB'.format(rec[col] || '<%:other%>'), row],
value: rec.tx_bytes
});
}
var mac = key.toUpperCase();
var name = hostInfo.hasOwnProperty(mac) ? hostInfo[mac].name : null;
if (!name)
for (var i = 0; i < detailData.length; i++)
if ((name = hostNames[detailData[i].ip]) !== undefined)
break;
if (mac !== '00:00:00:00:00:00') {
kpi('bubble-hostname', name);
kpi('bubble-vendor', oui(mac));
}
else {
kpi('bubble-hostname');
kpi('bubble-vendor');
}
var tr = this.parentNode.parentNode,
xy = off(tr),
xy2 = off(this);
bubble.style.width = tr.offsetWidth + 'px';
bubble.style.left = xy[0] + 'px';
bubble.style.top = (xy[1] + tr.offsetHeight) + 'px';
arrow.style.left = Math.floor(xy2[0] + this.offsetWidth / 2 - xy[0]) + 'px';
bubble.className = 'in';
return false;
}
function formatHostname(dns)
{
if (dns === undefined || dns === null || dns === '')
return '-';
dns = dns.split('.')[0];
if (dns.length > 12)
return '<span title="%q">%q</span>'.format(dns, dns);
return '%h'.format(dns);
}
function renderHostData()
{
var trafData = [], connData = [];
var rx_total = 0, tx_total = 0, conn_total = 0;
var table = document.getElementById('host-data');
var hostData = query(
function(c, r) {
return (r[c.rx_bytes] > 0 || r[c.tx_bytes] > 0);
},
['mac'],
//function(c, r) {
// return (r[c.mac] !== '00:00:00:00:00:00') ? r[c.mac] : r[c.ip];
//},
function(r1, r2) {
return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
}
);
while (table.rows.length > 1)
table.deleteRow(1);
for (var i = 0; i < hostData.length; i++) {
var row = table.insertRow(-1),
cell = row.insertCell(-1),
rec = hostData[i],
mac = rec.mac.toUpperCase(),
key = (mac !== '00:00:00:00:00:00') ? mac : rec.ip,
dns = hostInfo[mac] ? hostInfo[mac].name : null;
var link1 = document.createElement('a');
link1.onclick = renderHostDetail;
link1.href = '#' + rec.mac;
link1.setAttribute('data-col', 'ip');
link1.setAttribute('data-label', '<%:Source IP%>');
link1.innerHTML = (mac !== '00:00:00:00:00:00') ? mac : '<%:other%>';
var link2 = document.createElement('a');
link2.onclick = renderHostDetail;
link2.href = '#' + rec.mac;
link2.setAttribute('data-col', 'layer7');
link2.setAttribute('data-label', '<%:Protocol%>');
link2.innerHTML = "%1000.2m".format(rec.conns);
cell.innerHTML = formatHostname(dns);
cell.className = 'hostname';
row.insertCell(-1).appendChild(link1);
row.insertCell(-1).appendChild(link2);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.rx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.rx_pkts);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.tx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.tx_pkts);
trafData.push({
value: rec.rx_bytes + rec.tx_bytes,
label: ["%s: %%.2mB".format(key), row]
});
connData.push({
value: rec.conns,
label: ["%s: %%.2m".format(key), row]
});
rx_total += rec.rx_bytes;
tx_total += rec.tx_bytes;
conn_total += rec.conns;
}
if (table.rows.length === 1) {
var cell = table.insertRow(-1).insertCell(-1);
cell.setAttribute('colspan', 6);
cell.innerHTML = '<em><%:No data recorded yet.%> <a href="<%=url("admin/nlbw/commit")%>"><%:Force reload…%></a></em>';
}
kpi('rx-total', '%1024.2mB'.format(rx_total));
kpi('tx-total', '%1024.2mB'.format(tx_total));
kpi('conn-total', '%1000m'.format(conn_total));
kpi('host-total', '%u'.format(hostData.length));
}
function renderLayer7Data()
{
var rxData = [], txData = [];
var topConn = [[0],[0],[0]], topRx = [[0],[0],[0]], topTx = [[0],[0],[0]];
var table = document.getElementById('layer7-data');
var layer7Data = query(
null, ['layer7'],
function(r1, r2) {
return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
}
);
while (table.rows.length > 1)
table.deleteRow(1);
for (var i = 0, c = 0; i < layer7Data.length; i++) {
var rec = layer7Data[i],
row = table.insertRow(-1);
rxData.push({
value: rec.rx_bytes,
label: ["%s: %%.2mB".format(rec.layer7 || '<%:other%>'), row]
});
txData.push({
value: rec.tx_bytes,
label: ["%s: %%.2mB".format(rec.layer7 || '<%:other%>'), row]
});
row.insertCell(-1).innerHTML = rec.layer7 || '<%:other%>';
row.insertCell(-1).innerHTML = "%1000m".format(rec.conns);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.rx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.rx_pkts);
row.insertCell(-1).innerHTML = "%1024.2mB".format(rec.tx_bytes);
row.insertCell(-1).innerHTML = "%1000.2mP".format(rec.tx_pkts);
if (rec.layer7) {
topRx.push([rec.rx_bytes, rec.layer7]);
topTx.push([rec.tx_bytes, rec.layer7]);
topConn.push([rec.conns, rec.layer7]);
}
}
if (table.rows.length === 1) {
var cell = table.insertRow(-1).insertCell(-1);
cell.setAttribute('colspan', 6);
cell.innerHTML = '<em><%:No data recorded yet.%> <a href="<%=url("admin/nlbw/commit")%>"><%:Force reload…%></a></em>';
}
topRx.sort(function(a, b) { return b[0] - a[0] });
topTx.sort(function(a, b) { return b[0] - a[0] });
topConn.sort(function(a, b) { return b[0] - a[0] });
kpi('layer7-total', layer7Data.length);
kpi('layer7-most-rx', topRx[0][1], topRx[1][1], topRx[2][1]);
kpi('layer7-most-tx', topTx[0][1], topTx[1][1], topTx[2][1]);
kpi('layer7-most-conn', topConn[0][1], topConn[1][1], topConn[2][1]);
}
function renderIPv6Data()
{
var table = document.getElementById('ipv6-data'),
col = { },
rx4_total = 0,
tx4_total = 0,
rx6_total = 0,
tx6_total = 0,
v4_total = 0,
v6_total = 0,
ds_total = 0,
families = { },
records = { };
ipv6Data = query(
null, ['family', 'mac'],
function(r1, r2) {
return ((r2.rx_bytes + r2.tx_bytes) - (r1.rx_bytes + r1.tx_bytes));
}
);
for (var i = 0, c = 0; i < ipv6Data.length; i++) {
var rec = ipv6Data[i],
mac = rec.mac.toUpperCase(),
ip = rec.ip,
fam = families[mac] || 0,
recs = records[mac] || {};
if (rec.family == 4) {
rx4_total += rec.rx_bytes;
tx4_total += rec.tx_bytes;
fam |= 1;
}
else {
rx6_total += rec.rx_bytes;
tx6_total += rec.tx_bytes;
fam |= 2;
}
recs[rec.family] = rec;
records[mac] = recs;
families[mac] = fam;
}
for (var mac in families) {
switch (families[mac])
{
case 3:
ds_total++;
break;
case 2:
v6_total++;
break;
case 1:
v4_total++;
break;
}
}
while (table.rows.length > 1)
table.deleteRow(1);
for (var mac in records) {
if (mac === '00:00:00:00:00:00')
continue;
var row = table.insertRow(-1),
cell1 = row.insertCell(-1),
cell2 = row.insertCell(-1),
dns = hostInfo[mac] ? hostInfo[mac].name : null,
rec4 = records[mac][4],
rec6 = records[mac][6];
cell1.setAttribute('rowspan', 2);
cell1.innerHTML = formatHostname(dns);
cell1.className = 'hostname';
cell2.setAttribute('rowspan', 2);
cell2.innerHTML = mac;
row.insertCell(-1).innerHTML = 'IPv4';
row.insertCell(-1).innerHTML = rec4 ? "%1024.2mB".format(rec4.rx_bytes) : '-';
row.insertCell(-1).innerHTML = rec4 ? "%1000.2mP".format(rec4.rx_pkts) : '-';
row.insertCell(-1).innerHTML = rec4 ? "%1024.2mB".format(rec4.tx_bytes) : '-';
row.insertCell(-1).innerHTML = rec4 ? "%1000.2mP".format(rec4.tx_pkts) : '-';
row = table.insertRow(-1);
row.insertCell(-1).innerHTML = 'IPv6';
row.insertCell(-1).innerHTML = rec6 ? "%1024.2mB".format(rec6.rx_bytes) : '-';
row.insertCell(-1).innerHTML = rec6 ? "%1000.2mP".format(rec6.rx_pkts) : '-';
row.insertCell(-1).innerHTML = rec6 ? "%1024.2mB".format(rec6.tx_bytes) : '-';
row.insertCell(-1).innerHTML = rec6 ? "%1000.2mP".format(rec6.tx_pkts) : '-';
}
if (table.rows.length === 1) {
var cell = table.insertRow(-1).insertCell(-1);
cell.setAttribute('colspan', 7);
cell.innerHTML = '<em><%:No data recorded yet.%> <a href="<%=url("admin/nlbw/commit")%>"><%:Force reload…%></a></em>';
}
var shareData = [], hostsData = [];
if (rx4_total > 0 || tx4_total > 0)
shareData.push({
value: rx4_total + tx4_total,
label: ["IPv4: %.2mB"],
color: 'hsl(140, 100%, 50%)'
});
if (rx6_total > 0 || tx6_total > 0)
shareData.push({
value: rx6_total + tx6_total,
label: ["IPv6: %.2mB"],
color: 'hsl(180, 100%, 50%)'
});
if (v4_total > 0)
hostsData.push({
value: v4_total,
label: ["<%:%d IPv4-only hosts%>"],
color: 'hsl(140, 100%, 50%)'
});
if (v6_total > 0)
hostsData.push({
value: v6_total,
label: ["<%:%d IPv6-only hosts%>"],
color: 'hsl(180, 100%, 50%)'
});
if (ds_total > 0)
hostsData.push({
value: ds_total,
label: ["<%:%d dual-stack hosts%>"],
color: 'hsl(50, 100%, 50%)'
});
kpi('ipv6-hosts', '%.2f%%'.format(100 / (ds_total + v4_total + v6_total) * (ds_total + v6_total)));
kpi('ipv6-share', '%.2f%%'.format(100 / (rx4_total + rx6_total + tx4_total + tx6_total) * (rx6_total + tx6_total)));
kpi('ipv6-rx', '%1024.2mB'.format(rx6_total));
kpi('ipv6-tx', '%1024.2mB'.format(tx6_total));
}
function bubbleDismiss()
{
var bubble = document.getElementById('detail-bubble');
bubble.className = '';
document.body.appendChild(bubble);
return false;
}
//]]></script>
<h2 name="content"><%:Netlink Bandwidth Monitor%></h2>
<div id="detail-bubble">
<span id="bubble-arrow"></span>
<div>
<div class="head">
<a class="dismiss" href="#" onclick="this.blur(); return bubbleDismiss()">×</a>
<div class="kpi">
<ul>
<li><%_Hostname: <big id="bubble-hostname">example.org</big>%></li>
<li><%_Vendor: <big id="bubble-vendor">Example Corp.</big>%></li>
</ul>
</div>
</div>
<table id="bubble-table"></table>
</div>
</div>
<ul class="cbi-tabmenu">
<li id="tab.nlbw.traffic" class="cbi-tab"><a href="#" onclick="return switchTab('traffic')"><%:Traffic Distribution%></a></li>
<li id="tab.nlbw.layer7" class="cbi-tab-disabled"><a href="#" onclick="return switchTab('layer7')"><%:Application Protocols%></a></li>
<li id="tab.nlbw.ipv6" class="cbi-tab-disabled"><a href="#" onclick="return switchTab('ipv6')"><%:IPv6%></a></li>
</ul>
<div class="cbi-section" id="container.nlbw.traffic">
<div>
<div class="kpi">
<ul>
<li><%_<big id="host-total">0</big> hosts%></li>
<li><%_<big id="rx-total">0</big> download%></li>
<li><%_<big id="tx-total">0</big> upload%></li>
<li><%_<big id="conn-total">0</big> connections%></li>
</ul>
</div>
</div>
<table id="host-data">
<tr>
<th width="20%" class="hostname"><%:Host%></th>
<th width="10%"><%:MAC%></th>
<th width="10%"><%:Connections%></th>
<th width="20%" colspan="2"><%:Download (Bytes / Packets)%></th>
<th width="20%" colspan="2"><%:Upload (Bytes / Packets)%></th>
</tr>
</table>
</div>
<div class="cbi-section" id="container.nlbw.layer7" style="display:none">
<div>
<div class="kpi">
<ul>
<li><%_<big id="layer7-total">0</big> different application protocols%></li>
<li><%_<big id="layer7-most-rx">0</big> cause the most download%></li>
<li><%_<big id="layer7-most-tx">0</big> cause the most upload%></li>
<li><%_<big id="layer7-most-conn">0</big> cause the most connections%></li>
</ul>
</div>
</div>
<table id="layer7-data">
<tr>
<th width="10%"><%:Application%></th>
<th width="10%"><%:Connections%></th>
<th width="30%" colspan="2"><%:Download (Bytes / Packets)%></th>
<th width="30%" colspan="2"><%:Upload (Bytes / Packets)%></th>
</tr>
</table>
</div>
<div class="cbi-section" id="container.nlbw.ipv6" style="display:none">
<div>
<div class="kpi">
<ul>
<li><%_<big id="ipv6-hosts">0%</big> IPv6 support rate among hosts%></li>
<li><%_<big id="ipv6-share">0%</big> of the total traffic is IPv6%></li>
<li><%_<big id="ipv6-rx">0B</big> total IPv6 download%></li>
<li><%_<big id="ipv6-tx">0B</big> total IPv6 upload%></li>
</ul>
</div>
</div>
<table id="ipv6-data">
<tr>
<th width="20%" class="hostname"><%:Host%></th>
<th width="10%"><%:MAC%></th>
<th width="10%"><%:Family%></th>
<th width="20%" colspan="2"><%:Download (Bytes / Packets)%></th>
<th width="20%" colspan="2"><%:Upload (Bytes / Packets)%></th>
</tr>
</table>
</div>
<script type="text/javascript">//<![CDATA[
cbi_t_add('nlbw', 'traffic');
cbi_t_add('nlbw', 'layer7');
cbi_t_add('nlbw', 'ipv6');
cbi_t_add('nlbw', 'export');
fetchData('');
XHR.get('<%=url("admin/nlbw/list")%>', null, function(xhr, res) {
xhr.open('GET', 'https://raw.githubusercontent.com/jow-/oui-database/master/oui.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
try { res = JSON.parse(xhr.responseText); }
catch(e) { res = null; }
if (res !== null && typeof(res) === 'object' && (res.length % 3) === 0)
ouiData = res;
}
};
xhr.send(null);
});
XHR.get('<%=url("admin/nlbw/ptr")%>/' + ipAddrs.join('/'), null, function(xhr, res) {
if (res !== null && typeof(res) === 'object')
hostNames = res;
});
//]]></script>
<%+footer%>
|
281677160/openwrt-package | 1,919 | luci-app-autoipsetadder/luasrc/controller/autoipsetadder.lua | module("luci.controller.autoipsetadder",package.seeall)
local io = require "io"
local fs=require"nixio.fs"
local sys=require"luci.sys"
local uci=require"luci.model.uci".cursor()
function index()
entry({"admin","services","autoipsetadder"},firstchild(),_("autoipsetadder"),30).dependent=true
entry({"admin","services","autoipsetadder","autoipsetadder"},cbi("autoipsetadder"),_("Base Setting"),1)
entry({"admin","services","autoipsetadder","status"},call("act_status")).leaf=true
entry({"admin", "services", "autoipsetadder", "getlog"}, call("get_log"))
entry({"admin", "services", "autoipsetadder", "dodellog"}, call("do_del_log"))
entry({"admin", "services", "autoipsetadder", "debugip"}, call("do_debug_ip"))
end
function act_status()
local e={}
e.running=luci.sys.call("pgrep -f /usr/bin/autoipsetadder/autoaddlist.sh >/dev/null")==0
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function do_del_log()
local logfile=uci:get("autoipsetadder","autoipsetadder","logfile") or "/tmp/addlist.log"
nixio.fs.writefile(logfile,"")
luci.http.prepare_content("application/json")
luci.http.write('')
end
function do_debug_ip()
luci.http.prepare_content("text/plain; charset=utf-8")
local a=sys.exec("/usr/bin/autoipsetadder/debugip.sh")
if (a=="") then
a="noproblem"
end
luci.http.write(a)
end
function get_log()
local logfile,fdp
logfile=uci:get("autoipsetadder","autoipsetadder","logfile") or "/tmp/addlist.log"
luci.http.prepare_content("text/plain; charset=utf-8")
if not fs.access(logfile) then
luci.http.write("")
return
end
if fs.access("/var/run/lucilogreload") then
fdp=0
fs.remove("/var/run/lucilogreload")
else
fdp=tonumber(fs.readfile("/var/run/lucilogpos")) or 0
end
local f=io.open(logfile, "r+")
f:seek("set",fdp)
local a=f:read(2048000) or ""
fdp=f:seek()
fs.writefile("/var/run/lucilogpos",tostring(fdp))
f:close()
luci.http.write(a)
end |
281677160/openwrt-package | 2,190 | luci-app-autoipsetadder/luasrc/view/autoipsetadder/check.htm | <%+cbi/valueheader%>
<%uci=require"luci.model.uci".cursor()%>
<%nixio=require"nixio"%>
<%if uci:get("autoipsetadder","autoipsetadder","enabled")=="1" then%>
<textarea id="cbid.logview.1.conf" class="cbi-input-textarea" style="width: 100%;display:inline" data-update="change" rows="10" cols="60" readonly="readonly" > </textarea>
<input type="checkbox" value="reverse" onclick=" return reverselog()" style="vertical-align:middle;height: auto;" checked><%:reverse%></input>
<input type="button" class="cbi-button cbi-button-apply" id="apply_update_button" value="dellog" onclick=" return apply_del_log() "/>
<input type="button" class="cbi-button cbi-button-apply" id="apply_update_button" value="debug" onclick=" return debug_ip() "/>
<textarea id="cbid.logview.2.conf" class="cbi-input-textarea" style="width: 100%;display:none" data-update="change" rows="10" cols="60" readonly="readonly" > </textarea>
<script type="text/javascript">//<![CDATA[
var islogreverse = true;
function apply_del_log(){
XHR.get('<%=url([[admin]], [[services]], [[autoipsetadder]], [[dodellog]])%>',null,function(x, data){
var lv = document.getElementById('cbid.logview.1.conf');
lv.innerHTML="";
}
);
return
}
function reverselog(){
var lv = document.getElementById('cbid.logview.1.conf');
lv.innerHTML=lv.innerHTML.split('\n').reverse().join('\n')
if (islogreverse){
islogreverse=false;
}else{
islogreverse=true;
}
return
}
function debug_ip(){
var lv2 = document.getElementById('cbid.logview.2.conf');
lv2.style.display="inline"
XHR.get('<%=url([[admin]], [[services]], [[autoipsetadder]], [[debugip]])%>',null,function(x, data){
var lv2 = document.getElementById('cbid.logview.2.conf');
lv2.innerHTML = x.responseText;
}
);
return
}
function poll_check(){
XHR.poll(3, '<%=url([[admin]], [[services]], [[autoipsetadder]], [[getlog]])%>', null,
function(x, data) {
var lv = document.getElementById('cbid.logview.1.conf');
if (x.responseText && lv) {
if (islogreverse){
lv.innerHTML = x.responseText.split('\n').reverse().join('\n')+lv.innerHTML;
}else{
lv.innerHTML += x.responseText;
}
}
}
);}
poll_check();
//]]>
</script>
<%end%>
<%+cbi/valuefooter%> |
281677160/openwrt-package | 2,782 | luci-app-autoipsetadder/luasrc/model/cbi/autoipsetadder.lua | require("luci.sys")
require("luci.util")
local fs=require"nixio.fs"
local uci=require"luci.model.uci".cursor()
local m,s,o
m = Map("autoipsetadder", translate("ipsetautoadder"))
m.description = translate("自动将联不通的域名加入ipset")
m:section(SimpleSection).template = "autoipsetadder/status"
s = m:section(TypedSection, "autoipsetadder")
s.anonymous=true
s.addremove=false
---- enable
o = s:option(Flag, "enabled", translate("启用"))
o.default = 0
o.rmempty = false
---- logview
o=s:option(TextValue, "show", "日志")
o.template = "autoipsetadder/check"
---- logpath
o = s:option(Value, "logfile", translate("Runtime log file"))
o.datatype = "string"
o.default="/tmp/addlist.log"
o.optional = false
o.validate=function(self, value)
if fs.stat(value,"type")=="dir" then
fs.rmdir(value)
end
if fs.stat(value,"type")=="dir" then
if m.message then
m.message =m.message.."\nerror!log file is a dir"
else
m.message ="error!log file is a dir"
end
return nil
end
return value
end
---- dnsmasq log
o = s:option(Value, "dnslogfile", translate("dnsmasq log file"))
o.datatype = "string"
o.optional = false
o.default="/tmp/dnsmasq.log"
o.validate=function(self, value)
if fs.stat(value,"type")=="dir" then
fs.rmdir(value)
end
if fs.stat(value,"type")=="dir" then
if m.message then
m.message =m.message.."\nerror!log file is a dir"
else
m.message ="error!log file is a dir"
end
return nil
end
return value
end
---- crontab
o = s:option(MultiValue, "crontab", translate("Crontab task"),translate("Please change time and args in crontab"))
o:value("autodeldnslog",translate("Auto del dnsmasq log"))
o:value("autotaillog",translate("Auto tail runtime log"))
o.widget = "checkbox"
o.default = "autodeldnslog autotaillog"
o.rmempty= true
o = s:option(MultiValue, "config", translate("the way add to gfwlist"))
o:value("nochina",translate("no china ip"))
o:value("pingadd",translate("5ping loss1-4"))
o:value("packetpass",translate("packet >12 pass"))
o.widget = "checkbox"
o.default = "nochina pingadd packetpass"
o.rmempty=true
---- apply
nixio.fs.writefile("/var/run/lucilogreload","")
function m.on_commit(map)
local ucitracktest=uci:get("autoipsetadder","autoipsetadder","ucitracktest")
if ucitracktest=="1" then
return
elseif ucitracktest=="0" then
io.popen("/etc/init.d/autoipsetadder reload &")
else
if (fs.access("/var/run/AdGucitest")) then
uci:set("autoipsetadder","autoipsetadder","ucitracktest","0")
io.popen("/etc/init.d/autoipsetadder reload &")
else
fs.writefile("/var/run/AdGucitest","")
if (ucitracktest=="2") then
uci:set("autoipsetadder","autoipsetadder","ucitracktest","1")
else
uci:set("autoipsetadder","autoipsetadder","ucitracktest","2")
end
end
uci:save("autoipsetadder")
uci:commit("autoipsetadder")
end
end
return m
|
281677160/openwrt-package | 4,061 | luci-app-autoipsetadder/root/etc/init.d/autoipsetadder | #!/bin/sh /etc/rc.common
USE_PROCD=1
START=99
STOP=01
CRON_FILE=/etc/crontabs/root
CONFIGURATION=autoipsetadder
EXTRA_COMMANDS="test_crontab"
EXTRA_HELP="
test_crontab"
set_dnsmasq_log()
{
sed -i '/log-facility/d' /etc/dnsmasq.conf
sed -i '/log-queries/d' /etc/dnsmasq.conf
uci set dhcp.@dnsmasq[0].logfacility='/tmp/dnsmasq.log'
uci delete dhcp.@dnsmasq[0].logqueries
echo log-queries >> /etc/dnsmasq.conf
uci commit dhcp
/etc/init.d/dnsmasq reload
}
stop_dnsmasq_log()
{
sed -i '/log-queries/d' /etc/dnsmasq.conf
uci delete dhcp.@dnsmasq[0].logfacility
uci commit dhcp
/etc/init.d/dnsmasq reload
}
reload_service()
{
rm -f /var/run/AdGucitest 2>/dev/null
kill $(cat /var/run/autoipsetadder.pid)
start
}
service_triggers() {
procd_add_reload_trigger "$CONFIGURATION"
}
start_service() {
# Reading config
config_load "${CONFIGURATION}"
mkdir -p /tmp/run/autoipsetadder
local enabled
config_get_bool enabled $CONFIGURATION enabled 0
do_crontab
if [ "$enabled" == "1" ]; then
set_dnsmasq_log
procd_open_instance
procd_set_param respawn
# pass config to script on start
procd_set_param command sh /usr/bin/autoipsetadder/autoaddlist.sh
procd_close_instance
echo "autoipsetadder turn on"
echo "enabled=$enabled"
else
stop_dnsmasq_log
echo "autoipsetadder turn off"
echo "enabled=$enabled"
fi
}
stop_service()
{
config_load "${CONFIGURATION}"
stop_dnsmasq_log
do_crontab
kill $(cat /var/run/autoipsetadder.pid)
echo "autoipsetadder turn off"
echo "enabled="$enabled""
}
do_crontab(){
config_get_bool enabled $CONFIGURATION enabled 0
#config_get logfile $CONFIGURATION logfile "/tmp/addlist.log"
#config_get dnslogfile $CONFIGURATION dnslogfile "/tmp/dnsmasq.log"
config_get crontab $CONFIGURATION crontab ""
cronreload=0
findstr="echo qingkong > \$(uci get autoipsetadder.autoipsetadder.dnslogfile)"
default="0 * * * * echo qingkong > \$(uci get autoipsetadder.autoipsetadder.dnslogfile)"
#[ -n "$lastdnslogfile" ] && findstr="echo qingkong > $lastdnslogfile" && [ "$lastdnslogfile" != "$dnslogfile" ] && replace="${lastdnslogfile//\//\\/}/${dnslogfile//\//\\/}"
[ "$enabled" == "0" ] || [ "${crontab//autodeldnslog/}" == "$crontab" ] && cronenable=0 || cronenable=1
crontab_editor
#[ "$lastdnslogfile" != "$dnslogfile" ] && uci set autoipsetadder.autoipsetadder.lastdnslogfile="$dnslogfile" && commit=1
findstr="/usr/bin/autoipsetadder/tailto.sh [0-9]* \$(uci get autoipsetadder.autoipsetadder.logfile)"
default="0 0 * * * /usr/bin/autoipsetadder/tailto.sh 2000 \$(uci get autoipsetadder.autoipsetadder.logfile)"
#[ -n "$lastlogfile" ] && findstr="/usr/bin/autoipsetadder/tailto.sh [0-9]* $lastlogfile" && [ "$lastlogfile" != "$logfile" ] && replace="${lastlogfile//\//\\/}/${logfile//\//\\/}"
[ "$enabled" == "0" ] || [ "${crontab//autotaillog/}" == "$crontab" ] && cronenable=0 || cronenable=1
crontab_editor
#[ -n "$logfile" ] && [ "$lastlogfile" != "$logfile" ] && uci set autoipsetadder.autoipsetadder.lastlogfile="$logfile" && commit=1
[ "$cronreload" -gt 0 ] && /etc/init.d/cron restart
#[ "$commit" -gt 0 ] && uci commit autoipsetadder
}
crontab_editor(){
local testline reload
local line="$(grep "$findstr" $CRON_FILE)"
[ -n "$replace" ] && [ -n "$line" ] && eval testline="\${line//$replace}" && [ "$testline" != "$line" ] && line="$testline" && reload="1" && replace=""
if [ "${line:0:1}" != "#" ]; then
if [ $cronenable -eq 1 ]; then
[ -z "$line" ] && line="$default" && reload="1"
if [ -n "$reload" ]; then
sed -i "\,$findstr,d" $CRON_FILE
echo "$line" >> $CRON_FILE
cronreload=$((cronreload+1))
fi
elif [ -n "$line" ]; then
sed -i "\,$findstr,d" $CRON_FILE
echo "#$line" >> $CRON_FILE
cronreload=$((cronreload+1))
fi
else
if [ $cronenable -eq 1 ]; then
sed -i "\,$findstr,d" $CRON_FILE
echo "${line:1}" >> $CRON_FILE
cronreload=$((cronreload+1))
elif [ -z "$reload" ]; then
sed -i "\,$findstr,d" $CRON_FILE
echo "$line" >> $CRON_FILE
fi
fi
}
test_crontab(){
config_load "${CONFIGURATION}"
do_crontab
}
|
281677160/openwrt-package | 8,099 | luci-app-supervisord/luasrc/controller/supervisord.lua | module("luci.controller.supervisord", package.seeall)
function index()
if not nixio.fs.access("/etc/config/supervisord") then return end
entry({"admin", "services", "supervisord"}, cbi("supervisord"), _("Supervisord"), 95).dependent = true
entry({"admin", "services", "supervisord", "status"}, call("status")).leaf = true
entry({"admin", "services", "supervisord", "getver"}, call("getver")).leaf = true
entry({"admin", "services", "supervisord", "update"}, call("update")).leaf = true
entry({"admin", "services", "supervisord", "gettask"}, call("gettask")).leaf = true
entry({"admin", "services", "supervisord", "starttask"}, call("starttask")).leaf = true
entry({"admin", "services", "supervisord", "restarttask"}, call("restarttask")).leaf = true
entry({"admin", "services", "supervisord", "stoptask"}, call("stoptask")).leaf = true
entry({"admin", "services", "supervisord", "removetask"}, call("removetask")).leaf = true
entry({"admin", "services", "supervisord", "addtask"}, call("addtask")).leaf = true
entry({"admin", "services", "supervisord", "savetask"}, call("savetask")).leaf = true
entry({"admin", "services", "supervisord", "getlog"}, call("getlog")).leaf = true
end
function Split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function status()
local e = {}
e.running = luci.sys.call("ps | grep supervisord | grep -v grep >/dev/null") == 0
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function getver()
local e = {}
local c=luci.model.uci.cursor()
local d=c:get("supervisord", "main", "filepath")
e.nowver=luci.sys.exec(d .. " version")
e.newver=luci.sys.exec("uclient-fetch -qO- 'https://api.github.com/repos/ochinchina/supervisord/releases/latest' | jsonfilter -e '@.tag_name'")
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function update()
local e = {}
local c=luci.model.uci.cursor()
local d=c:get("supervisord", "main", "filepath")
local version = luci.http.formvalue('version')
local arch = nixio.uname().machine or ""
version = version:gsub("\n", "")
if nixio.fs.access("/usr/lib/os-release") then
LEDE_BOARD = luci.sys.exec("echo -n $(grep 'LEDE_BOARD' /usr/lib/os-release | awk -F '[\\042\\047]' '{print $2}')")
end
if nixio.fs.access("/etc/openwrt_release") then
DISTRIB_TARGET = luci.sys.exec("echo -n $(grep 'DISTRIB_TARGET' /etc/openwrt_release | awk -F '[\\042\\047]' '{print $2}')")
end
arch=luci.util.trim(arch)
if arch == "x86_64" then
arch = "64-bit"
end
filename = "supervisord_" .. version:gsub("v", "") .. "_Linux_" .. arch .. ".tar.gz"
nixio.fs.remove("/tmp/" .. filename)
u=c:get("supervisord", "main", "usechinamirror")
e.error=luci.sys.call("uclient-fetch -qO- -O '/tmp/" .. filename .. "' '" .. u .. "https://github.com/ochinchina/supervisord/releases/download/" .. version .. "/" .. filename .. "'")
if e.error == 0 then
e.error=luci.sys.exec("tar -xzvf '/tmp/" .. filename .. "' -C /tmp")
if e.error then
e.error=nixio.fs.mover("/tmp/" .. filename:gsub(".tar.gz", "") .. "/supervisord", d)
if e.error then
e.error=0
sysupgrade=nixio.fs.readfile("/etc/sysupgrade.conf")
if not sysupgrade:find(d) then
sysupgrade=sysupgrade .. '\n' .. d
nixio.fs.writefile ("/etc/sysupgrade.conf", sysupgrade)
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
else
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
else
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
end
function gettask()
local e = {}
local name = luci.http.formvalue('name')
local data = luci.sys.exec("supervisord ctl status " .. name)
e.status=string.gsub(string.sub(data, 34, 50), " ", "")
e.description=string.sub(data, 51)
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function starttask()
local e = {}
local name = luci.http.formvalue('name')
local data = luci.sys.exec("supervisord ctl start " .. name)
if string.find(data,"started") ~= nil then
e.code=1
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function restarttask()
local e = {}
local name = luci.http.formvalue('name')
local data = luci.sys.exec("supervisord ctl stop " .. name .. " && supervisord ctl start " .. name)
if string.find(data,"started") ~= nil then
e.code=1
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function stoptask()
local e = {}
local name = luci.http.formvalue('name')
local data = luci.sys.exec("supervisord ctl stop " .. name)
if string.find(data,"stopped") ~= nil then
e.code=1
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function removetask()
local e = {}
local name = luci.http.formvalue('name')
e.code=nixio.fs.remove('/etc/supervisord/program/' .. name .. '.ini')
if e.code then
luci.sys.call("supervisord ctl reload")
e.code=1
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function addtask()
local e = {}
local name = luci.http.formvalue('name')
if nixio.fs.access('/etc/supervisord/program/' .. name .. '.ini') then
e.code=2
luci.http.prepare_content("application/json")
luci.http.write_json(e)
return
end
file=nixio.fs.readfile("/etc/supervisord/program/templates")
file=file:gsub("demo", name)
e.code=nixio.fs.writefile('/etc/supervisord/program/' .. name .. '.ini', file)
if e.code then
luci.sys.call("supervisord ctl reload")
e.code=1
e.data=file
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function savetask()
local e = {}
local name = luci.http.formvalue('name')
local data = luci.http.formvalue('data')
data = data:gsub("\r\n?", "\n")
file = '/etc/supervisord/program/' .. name .. '.ini'
e.code=nixio.fs.writefile (file, data)
if e.code then
sysupgrade=nixio.fs.readfile("/etc/sysupgrade.conf")
if not sysupgrade:find(file) then
sysupgrade=sysupgrade .. '\n' .. file
end
backupfile=data:match("backupfile=([%a%d%p]+)")
backupfile=Split(backupfile, "||")
for k, v in ipairs(backupfile) do
if not sysupgrade:find(v:gsub("%p", "%%%1")) then
sysupgrade=sysupgrade .. '\n' .. v
end
end
nixio.fs.writefile ("/etc/sysupgrade.conf", sysupgrade)
luci.sys.call("supervisord ctl reload")
e.code=1
else
e.code=0
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function getlog()
local e = {}
local name = luci.http.formvalue('name')
if name=="main" then
local data = nixio.fs.readfile ('/etc/supervisord/supervisord.conf')
data = string.match(data, "logfile=([%a%d%p]+)")
e.data=nixio.fs.readfile (data)
else
local data = nixio.fs.readfile ('/etc/supervisord/program/' .. name .. '.ini')
data = string.match(data, "stdout_logfile=([%a%d%p]+)")
e.data=nixio.fs.readfile (data)
end
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end |
281677160/openwrt-package | 8,555 | luci-app-supervisord/luasrc/view/supervisord/list.htm | <%local fs = require "nixio.fs"%>
<%+cbi/valueheader%>
<div class="cbi-section-node">
<table class="cbi-section-table" id="task-list">
<tbody>
<tr class="cbi-section-table-titles">
<th class="cbi-section-table-cell" style="width:120px!important"><%:Name%></th>
<th class="cbi-section-table-cell" style="width:120px!important"><%:Versions%></th>
<th class="cbi-section-table-cell" style="width:100px!important"><%:Status%></th>
<th class="cbi-section-table-cell" style="width:300px!important"><%:Description%></th>
<th class="cbi-section-table-cell"><%:Configuration File%></th>
<th class="cbi-section-table-cell" style="width:355px!important"><%:Action%></th>
</tr>
<% for _,item in pairs(self.list) do %>
<tr class="cbi-section-table-row" id="<%=item[2]:gsub('/etc/supervisord/program/', ""):gsub('.ini', "")%>-main">
<td class="cbi-value-field">
<%=item[1]%>
</td>
<td class="cbi-value-field">
<%=item[3]%>
</td>
<td class="cbi-value-field" id="<%=item[1]%>-status">
</td>
<td class="cbi-value-field" id="<%=item[1]%>-description">
</td>
<td class="cbi-value-field">
<textarea class="cbi-input-textarea" id="<%=item[1]%>-text" rows="15" wrap="off"><%=fs.readfile(item[2])%></textarea>
</td>
<td class="cbi-value-field">
<input class="cbi-button cbi-input-apply" style="font-size: 100%;background-color: green!important;" type="button" id="<%=item[1]%>-start" disabled
onclick="actions('starttask','<%=item[1]%>')" value="<%:Start%>" size="0">
<input class="cbi-button cbi-input-remove" style="font-size: 100%;background-color: #333333!important;" type="button" id="<%=item[1]%>-stop" disabled
onclick="actions('stoptask','<%=item[1]%>')" value="<%:Stop%>" size="0">
<input class="cbi-button cbi-input-apply" style="font-size: 100%;" type="button"
onclick="actions('restarttask','<%=item[1]%>')" value="<%:Reboot%>" size="0">
<input class="cbi-button cbi-input-remove" style="font-size: 100%;" type="button"
onclick="actions('savetask','<%=item[2]:gsub('/etc/supervisord/program/', ''):gsub('.ini', '')%>')" value="<%:Save%>" size="0">
<input class="cbi-button cbi-button-remove" style="font-size: 100%;" type="button"
onclick="actions('removetask','<%=item[2]:gsub('/etc/supervisord/program/', ''):gsub('.ini', '')%>')" value="<%:Delete%>" size="0">
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="cbi-section-create">
<input type="text" class="cbi-section-create-name" id="addtext" value="" maxlength="20" size="0">
<input class="cbi-button cbi-button-add" onclick="addtask()" type="button" value="<%:Add%>" size="0">
</div>
</div>
<script type="text/javascript">
<% for _,item in pairs(self.list) do -%>
XHR.poll(5, '<%=url([[admin]], [[services]], [[supervisord]], [[gettask]])%>', {name: '<%=item[1]%>'},
function(x, data) {
const st = document.getElementById('<%=item[1]%>-status');
const des = document.getElementById('<%=item[1]%>-description');
if (data) {
st.innerHTML = data.status;
if (data.status == "Exited" || data.status == "Backoff"){
st.style.color="red"
document.getElementById('<%=item[1]%>-start').disabled = false;
document.getElementById('<%=item[1]%>-stop').disabled = true;
}else{
st.style.color="green"
document.getElementById('<%=item[1]%>-start').disabled = true;
document.getElementById('<%=item[1]%>-stop').disabled = false;
}
des.innerHTML = data.description;
}
}
)
<% end %>
function addtask(){
const name = document.getElementById("addtext").value
const isletter = /^[a-zA-Z]+$/.test(name);
if (!isletter) {
alert("<%:Only letters can be used for names!%>")
return
}
if (name.length > 20) {
alert("<%:Cannot exceed 20 characters!%>")
return
}
XHR.get('<%=url([[admin]], [[services]], [[supervisord]], [[addtask]])%>', {name: name},
function(x, data) {
if (data.code == 0) {
alert("<%:Creation failed. Please try again!%>")
return
}else if (data.code == 1){
const currentRows = document.getElementById("task-list").rows.length;
const insertTr = document.getElementById("task-list").insertRow(currentRows);
insertTr.className = 'cbi-section-table-row';
insertTr.id = name + '-main';
insertTr.innerHTML = "<td class='cbi-value-field'>"+name+"</td><td class='cbi-value-field' id='"+name+"-status'></td><td class='cbi-value-field' id='"+name+"-description'></td><td class='cbi-value-field'><textarea class='cbi-input-textarea' id='"+name+"-text' rows='15' wrap='off'>"+data.data+"</textarea></td><td class='cbi-value-field'><input class='cbi-button cbi-input-apply' style='font-size: 100%;background-color: green!important;' type='button' id='"+name+"-start' disabled onclick='actions("starttask",""+name+"")' value='<%:Start%>' size='0'><input class='cbi-button cbi-input-remove' style='font-size: 100%;background-color: #333333!important;' type='button' id='"+name+"-stop' disabled onclick='actions("stoptask",""+name+"")' value='<%:Stop%>' size='0'><input class='cbi-button cbi-input-apply' style='font-size: 100%;' type='button' onclick='actions("restarttask",""+name+"")' value='<%:Reboot%>' size='0'><input class='cbi-button cbi-input-remove' style='font-size: 100%;' type='button' onclick='actions("savetask",""+name+"")' value='<%:Save%>' size='0'><input class='cbi-button cbi-button-remove' style='font-size: 100%;' type='button' onclick='actions("removetask",""+name+"")' value='<%:Delete%>' size='0'></td>";
document.getElementById("addtext").value="";
XHR.poll(5, '<%=url([[admin]], [[services]], [[supervisord]], [[gettask]])%>', {name: name},
function(x, data) {
const st = document.getElementById(name + '-status');
const des = document.getElementById(name + '-description');
if (data) {
st.innerHTML = data.status;
if (data.status == "Exited" || data.status == "Backoff"){
st.style.color="red"
document.getElementById(name + '-start').disabled = false;
document.getElementById(name + '-stop').disabled = true;
}else{
st.style.color="green"
document.getElementById(name + '-start').disabled = true;
document.getElementById(name + '-stop').disabled = false;
}
des.innerHTML = data.description;
}
}
)
}else if (data.code == 2){
alert("<%:A task with this name already exists!%>")
return
}
}
)
}
function actions(mode,name){
if (mode=="savetask"){
const x = new XHR()
x.post('<%=url([[admin]], [[services]], [[supervisord]], [[savetask]])%>', {name: name, data: $('#' + name + '-text').val()},
function(x) {
if (JSON.parse(x.response).code) {
alert("<%:Save success!%>")
}else{
alert("<%:Save failed!%>")
}
}
)
}else{
if (mode=="removetask") {
const ret=confirm("<%:Are you sure you want to delete this task?%>")
if (!ret) return
}
XHR.get('<%=url([[admin]], [[services]], [[supervisord]], [[mode]])%>'.replace("mode",mode), {name: name},
function(x, data) {
if (data.code) {
if (mode == "starttask"){
document.getElementById(name + '-start').disabled = true;
document.getElementById(name + '-stop').disabled = false;
}
if (mode == "stoptask"){
document.getElementById(name + '-start').disabled = false;
document.getElementById(name + '-stop').disabled = true;
}
if (mode == "removetask"){
document.getElementById(name + '-main').remove();
}
}
}
)
}
}
</script>
<%+cbi/valuefooter%> |
281677160/openwrt-package | 2,265 | luci-app-supervisord/luasrc/view/supervisord/version.htm | <%+cbi/valueheader%>
<label class="cbi-value-title"><%= translate("Update the core") %></label>
<div class="cbi-value-field">
<input class="btn cbi-button cbi-button-reload" id="update" type="button" size="0" onclick="check_version()" value="<%:Collecting data...%>" />
<div class="cbi-value-description">
<span class="cbi-value-helpicon"><img src="/luci-static/resources/cbi/help.gif" alt="帮助"></span>
<%:If repeated failures occur, you can download the binaries for the corresponding schemas at the following url.%>
</br>
<%:https://github.com/ochinchina/supervisord/releases%>
</br>
<%:Unpack the package and place it in the top path.%>
</br>
<%:The author binary version number may not have changed.%>
</br>
<%:If you successfully update, the refresh page is still lower than the latest version.%>
</br>
<%:This is normal.%>
</div>
</div>
<script type="text/javascript">
function getver() {
XHR.get('<%=url([[admin]], [[services]], [[supervisord]], [[getver]])%>', null,
function(x, data) {
const tb = document.getElementById('update');
if (data && tb) {
if (data.newver) {
tb.value = '<%:Local version is %>' + data.nowver + '<%:, New version is %>' + data.newver;
tb.setAttribute('newver', data.newver);
}else{
tb.value = '<%:The check failed. Please try again%>';
}
}
}
);
}
getver()
function check_version() {
const tb = document.getElementById('update');
const newver= tb.getAttribute("newver")
if (newver){
tb.disabled = true;
XHR.get('<%=url([[admin]], [[services]], [[supervisord]], [[update]])%>', {version: newver}, (x, r) => {
if (r.error == 0) {
tb.disabled = false;
tb.value = '<%:Local version is %>' + newver + '<%:, New version is %>' + newver;
} else {
tb.disabled = false;
tb.value = '<%:The update failed. Please try again%>';
}
});
}else{
getver()
}
}
</script>
<%+cbi/valuefooter%> |
281677160/openwrt-package | 1,194 | luci-app-supervisord/luasrc/view/supervisord/log.htm | <%local fs = require "nixio.fs"%>
<%+cbi/valueheader%>
<div class="cbi-value">
<label class="cbi-value-title">
<p style="color: red">日记列表</p>
</label>
<div class="cbi-value-field">
<select class="cbi-input-select" size="1">
<option value="main">supervisord</option>
<% for _,item in pairs(self.list) do %>
<option value="<%=item[2]:gsub('/etc/supervisord/program/', ''):gsub('.ini', '')%>">
<%=item[2]:gsub('/etc/supervisord/program/', ''):gsub('.ini', '')%>
</option>
<% end %>
</select>
</div>
</div>
<textarea class="cbi-input-textarea" id="log-text" rows="30" wrap="off" readonly></textarea>
<script type="text/javascript">
getlog('main')
$(".cbi-input-select").change(function (e) {
getlog($(this).val())
});
function getlog(name) {
XHR.get('<%=url([[admin]], [[services]], [[supervisord]], [[getlog]])%>', {name: name},
function (x, data) {
if (data.data) {
document.getElementById("log-text").value = data.data;
}
}
)
}
</script>
<%+cbi/valuefooter%> |
281677160/openwrt-package | 2,340 | luci-app-supervisord/luasrc/model/cbi/supervisord.lua | local fs = require "nixio.fs"
local sys = require "luci.sys"
local m = Map("supervisord",translate("Supervisord"), translate("A golang development process management") .. [[<br /><br /><a href="https://github.com/sundaqiang/openwrt-packages" target="_blank"></a>]])
m:section(SimpleSection).template = "supervisord/index"
s = m:section(TypedSection, "supervisord")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Configuration File"))
s:tab("list", translate("Task List"))
s:tab("log", translate("Log List"))
f = s:taboption("general", Flag, "enabled", translate("Enabled"))
f.rmempty = false
v = s:taboption("general", Value, "filepath", translate("File Path"))
v.rmempty = false
v = s:taboption("general", Flag, "usechinamirror", translate("Use China Mirror"))
v.rmempty = false
b = s:taboption("general", Button, "")
b.template = "supervisord/version"
file=s:taboption("advanced", TextValue, "")
file.template = "cbi/tvalue"
file.rows = 15
file.wrap = "off"
file.rmempty = false
l=s:taboption("list", DummyValue, "")
l.template = "supervisord/list"
l.list={}
index=1
for filelist in fs.dir("/etc/supervisord/program") do
if filelist:find(".ini$") ~= nil then
name=fs.readfile("/etc/supervisord/program/" .. filelist)
l.list[index]={}
l.list[index][1]=name:match("program:(%a+)")
l.list[index][2]="/etc/supervisord/program/" .. filelist
local cmd=name:match("directory=([%a%d%p ]+)") .. "/" .. name:match("getversions=([%a%d%p ]+)")
l.list[index][3]=sys.exec(cmd)
index=index+1
end
end
g=s:taboption("log", DummyValue, "")
g.template = "supervisord/log"
g.list=l.list
function s.create(self,section)
return TypedSection.create(self,section)
end
function s.remove(self,section)
return TypedSection.remove(self,section)
end
function sync_value_to_file(self, section, value, file)
value = value:gsub("\r\n?", "\n")
local old_value = fs.readfile(file)
if value ~= old_value then
fs.writefile(file, value)
self.map:set(section, "amend", "1")
end
end
function file.cfgvalue(self,section)
return fs.readfile("/etc/supervisord/supervisord.conf") or ""
end
function file.write(self, section, value)
sync_value_to_file(self, section, value, "/etc/supervisord/supervisord.conf")
end
return m |
281677160/openwrt-package | 1,544 | luci-app-supervisord/po/zh_Hans/supervisord.po | msgid "Supervisord"
msgstr "进程管理器"
msgid "A golang development process management"
msgstr "一款golang开发的进程管理"
msgid "General Settings"
msgstr "基础设置"
msgid "Configuration File"
msgstr "配置文件"
msgid "Task List"
msgstr "任务列表"
msgid "Log List"
msgstr "日志列表"
msgid "Enabled"
msgstr "启用"
msgid "File Path"
msgstr "文件路径"
msgid "Use China Mirror"
msgstr "使用中国镜像"
msgid "Update the core"
msgstr "更新核心"
msgid "If repeated failures occur, you can download the binaries for the corresponding schemas at the following url."
msgstr "如果重复失败,您可以从以下url下载对应模式的二进制文件。"
msgid "Unpack the package and place it in the top path."
msgstr "解压后并将其放置在上方设置的路径中。"
msgid "The author binary version number may not have changed."
msgstr "作者二进制版本号可能没有改变。"
msgid "If you successfully update, the refresh page is still lower than the latest version."
msgstr "如果更新成功,刷新页面仍然低于最新版本。"
msgid "This is normal."
msgstr "这是正常的。"
msgid "Local version is"
msgstr "本地版本是"
msgid ", New version is"
msgstr ",最新版本是"
msgid "The check failed. Please try again"
msgstr "检查失败。请再试一次"
msgid "The update failed. Please try again"
msgstr "更新失败。请再试一次"
msgid "Versions"
msgstr "版本"
msgid "Only letters can be used for names!"
msgstr "只有字母可以用来命名!"
msgid "Cannot exceed 20 characters!"
msgstr "不能超过20个字符!"
msgid "Creation failed. Please try again!"
msgstr "创建失败了。请再试一次!"
msgid "A task with this name already exists!"
msgstr "已经存在此名称的任务!"
msgid "Save success!"
msgstr "保存成功!"
msgid "Save failed!"
msgstr "保存失败!"
msgid "Are you sure you want to delete this task?"
msgstr "您确定要删除该任务吗?" |
281677160/openwrt-package | 1,106 | luci-app-supervisord/root/etc/init.d/supervisord | #!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org
START=90
get_config() {
config_get_bool enabled $1 enabled 0
config_get_bool amend $1 amend 0
config_get filepath $1 filepath /usr/bin/supervisord
}
start() {
config_load supervisord
config_foreach get_config supervisord
[ $enabled -eq 0 ] && exit 0
$filepath -c /etc/supervisord/supervisord.conf -d
}
stop() {
config_load supervisord
config_foreach get_config supervisord
$filepath ctl shutdown
}
reload() {
config_load supervisord
config_foreach get_config supervisord
[ $enabled -eq 0 ] && logger -t supervisord disabled to stop && stop && exit 0
status=$(ps | grep supervisord | grep -v grep | grep -v luci | grep -v init | grep -v version | wc -l)
[ $status -eq 0 ] && logger -t supervisord unstarted to start && start && exit 0
if [ $amend -eq 1 ]; then
logger -t supervisord amend to restart
stop
sleep 1
uci set supervisord.main.amend=0
uci commit supervisord
start
else
logger -t supervisord fixed to reload
$filepath ctl reload
fi
}
|
281677160/openwrt-package | 910 | luci-app-supervisord/root/etc/supervisord/program/templates | ;更多参数查看https://github.com/ochinchina/supervisord/
;程序名称,没事别乱改
[program:demo]
;程序启动命令,必须
;command=xxxxx
command=
;执行命令的路径,必须
;directory=/usr/bin
directory=
;需要备份文件的完整路径,多个文件以||分割,必须
;backupfile=/usr/bin/xxxxx||/etc/yyyyy
backupfile=
;获取版本号命令,必须
;getversions=xxxxx version
getversions=
;在supervisord启动的时候也自动启动
autostart=true
;启动10秒后没有异常退出,就表示进程正常启动了,默认为1秒
startsecs=10
;程序退出后自动重启,可选值:[unexpected,true,false]
;默认为unexpected,表示进程意外杀死后才重启
autorestart=true
;启动失败自动重试次数,默认是3
startretries=3
;用哪个用户启动进程,默认是root
user=root
;进程启动优先级,默认999,值小的优先启动
priority=999
;把stderr重定向到stdout,默认false
redirect_stderr=true
;stdout日志文件大小,默认1MB
stdout_logfile_maxbytes=1MB
;stdout日志文件备份数,默认是10
stdout_logfile_backups=10
;stdout日志文件,需要注意当指定目录不存在时无法正常启动,所以需手动创建目录
stdout_logfile=/var/log/demo.log
;日志的级别
loglevel=info
;默认为false,进程被杀死时,是否向这个进程组发送stop信号,包括子进程
stopasgroup=false
;默认为false,向进程组发送kill信号,包括子进程
killasgroup=false
|
281677160/openwrt-package | 2,243 | luci-app-qmodem/scripts/update_support_list.py | import json
import sys
def generate_markdown(result):
# 生成 Markdown 格式
markdown_output = []
for vendor, models in result.items():
markdown_output.append(f"# {vendor}")
markdown_output.append("Model | Platform | USB | PCIe ")
markdown_output.append("--- | --- | --- | ---")
for model, support in models.items():
markdown_output.append(f"{model} | {support['platform']} |{support['usb']} | {support['pcie']}")
markdown_output.append("") # 空行分隔
return markdown_output
def generate_github_release_notes(result):
# 生成 GitHub 发布说明格式
release_notes = []
for vendor, models in result.items():
release_notes.append(f"## {vendor}")
for model, support in models.items():
release_notes.append(f"- {model}: USB - {support['usb']}, PCIe - {support['pcie']}")
release_notes.append("")
return release_notes
if __name__ == "__main__":
prefix = sys.argv[1] if len(sys.argv) > 1 else 'support_list'
file_name = sys.argv[2] if len(sys.argv) > 2 else 'application/qmodem/files/usr/share/qmodem/modem_support.json'
# 加载 JSON 数据
with open(file_name, 'r') as file:
data = json.load(file)
# 初始化结果字典
result = {}
# 遍历 USB 和 PCIe 数据
for interface_type in ['usb', 'pcie']:
for model, details in data['modem_support'][interface_type].items():
vendor = details.get('manufacturer', 'unknown').lower()
platform = details.get('platform', 'unknown').lower()
modes = ','.join(details.get('modes', []))
support = f"✔ {interface_type}({modes})"
if vendor not in result:
result[vendor] = {}
if model not in result[vendor]:
result[vendor][model] = {'usb': '✘', 'pcie': '✘'}
result[vendor][model][interface_type] = support
result[vendor][model]['platform'] = platform
markdown_output = generate_markdown(result)
release_notes = generate_github_release_notes(result)
with open(f"{prefix}.md", 'w') as f:
f.write("\n".join(markdown_output))
with open(f"{prefix}_release_notes.md", 'w') as f:
f.write("\n".join(release_notes))
|
281677160/openwrt-package | 2,407 | luci-app-qmodem/luci/luci-app-qmodem-hc/luasrc/controller/qmodem_hc.lua | module("luci.controller.qmodem_hc", package.seeall)
local http = require "luci.http"
local fs = require "nixio.fs"
local json = require("luci.jsonc")
function index()
--sim卡配置
entry({"admin", "modem", "qmodem", "modem_sim"}, cbi("qmodem_hc/modem_sim"), luci.i18n.translate("SIM Config"), 23).leaf = true
entry({"admin", "modem", "qmodem", "set_sim"}, call("setSIM"), nil).leaf = true
entry({"admin", "modem", "qmodem", "get_sim"}, call("getSIM"), nil).leaf = true
end
function getSimSlot(sim_path)
local sim_slot = fs.readfile(sim_path)
local current_slot = string.match(sim_slot, "%d")
if current_slot == "0" then
return "SIM2"
else
return "SIM1"
end
end
function shell(command)
local odpall = io.popen(command)
local odp = odpall:read("*a")
odpall:close()
return odp
end
function getNextBootSlot()
local fw_print_cmd = "fw_printenv -n sim2"
local nextboot_slot = shell(fw_print_cmd)
if nextboot_slot == "" then
return "SIM1"
else
return "SIM2"
end
end
function writeJsonResponse(current_slot, nextboot_slot)
local result_json = {}
result_json["current_slot"] = current_slot
result_json["nextboot_slot"] = nextboot_slot
luci.http.prepare_content("application/json")
luci.http.write_json(result_json)
end
function getSIM()
local sim_path = "/sys/class/gpio/sim/value"
local current_slot = getSimSlot(sim_path)
local nextboot_slot = getNextBootSlot()
writeJsonResponse(current_slot, nextboot_slot)
end
function setSIM()
local sim_gpio = "/sys/class/gpio/sim/value"
local modem_gpio = "/sys/class/gpio/4g/value"
local sim_slot = http.formvalue("slot")
local pre_detect = getSimSlot(sim_gpio)
local reset_module = 1
if pre_detect == sim_slot then
reset_module = 0
end
if sim_slot == "SIM1" then
sysfs_cmd = "echo 1 >"..sim_gpio
fw_setenv_cmd = "fw_setenv sim2"
elseif sim_slot == "SIM2" then
sysfs_cmd = "echo 0 >"..sim_gpio
fw_setenv_cmd = "fw_setenv sim2 1"
end
shell(sysfs_cmd)
shell(fw_setenv_cmd)
if reset_module == 1 then
shell("echo 0 >"..modem_gpio)
os.execute("sleep 1")
shell("echo 1 >"..modem_gpio)
end
local current_slot = getSimSlot(sim_gpio)
local nextboot_slot = getNextBootSlot()
writeJsonResponse(current_slot, nextboot_slot)
end
|
281677160/openwrt-package | 1,798 | luci-app-qmodem/luci/luci-app-qmodem-hc/luasrc/view/qmodem_hc/modem_sim.htm |
<script>
function set_sim_view(slot){
let sim_current_slot = slot["current_slot"];
let sim_nextboot_slot = slot["nextboot_slot"];
sim_current_view = document.getElementById("sim_slot_current");
sim_nextboot_view = document.getElementById("sim_slot_nextboot");
sim_current_view.innerHTML = sim_current_slot;
sim_nextboot_view.innerHTML = sim_nextboot_slot;
}
function set_sim(){
select = document.getElementById("sim_slot_select");
slot = select.value;
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "set_sim")%>', {"slot": slot },
function (x, data) {
set_sim_view(data);
}
);
}
window.onload=function(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_sim")%>', null,
function (x, data) {
set_sim_view(data);
}
);
}
</script>
<!-- 设置SIM卡槽 -->
<div class="cbi-section" >
<table class="table cbi-section-table">
<tbody id="sim_slot_setting">
<tr class="tr cbi-section-table-titles anonymous">
<th>
<%:SIM Slot%>|<%:Now%>
</th>
<th>
<%:SIM Slot%>|<%:Next Boot%>
</th>
<th>
<%:SIM Slot%>|<%:Setting%>
</th>
</tr>
<tr class="tr">
<td class="td" style="width: auto;">
<span id="sim_slot_current"></span>
</td>
<td class="td cbi-value-field">
<span id="sim_slot_nextboot"></span>
</td>
<td class="td cbi-value-field">
<select name="sim_slot_select" id="sim_slot_select" class="cbi-input-select">
<option value="SIM1"><%:SIM1 (Close to power)%></option>
<option value="SIM2"><%:SIM2 (Away from power)%></option>
</select>
</td>
</tr>
</tbody>
</table>
<input type="button" class="cbi-button-apply" onclick="set_sim()" value="<%:Set SIM%>">
</div>
|
281677160/openwrt-package | 1,035 | luci-app-qmodem/luci/luci-app-qmodem-hc/luasrc/model/cbi/qmodem_hc/modem_sim.lua | m = Map("qmodem_hc_sim", translate("SIM Settings"))
uci = require "luci.model.uci".cursor()
s = m:section(NamedSection,"main","main", translate("SIM Settings"))
s.anonymous = true
s.addremove = false
sim_auto_switch = s:option(Flag, "sim_auto_switch", translate("SIM Auto Switch"))
sim_auto_switch.default = "0"
detect_interval = s:option(Value, "detect_interval", translate("Network Detect Interval"))
detect_interval.default = 15
judge_time = s:option(Value, "judge_time", translate("Network Down Judge Times"))
judge_time.default = 5
ping_dest = s:option(DynamicList, "ping_dest", translate("Ping Destination"))
o = s:option(ListValue, "modem_config", translate("Modem Config"))
uci:foreach("qmodem", "modem-device",
function(s)
if s then
o:value(s['.name'])
end
end
)
-- o.description = translate("Please enter the WWAN interface name")
-- o.template = "cbi/network_netlist"
-- o.widget = "optional"
o.nocreate = true
m:section(SimpleSection).template = "qmodem_hc/modem_sim"
return m
|
281677160/openwrt-package | 5,596 | luci-app-qmodem/luci/luci-app-qmodem-hc/root/usr/share/qmodem/modem_sim.sh | #!/bin/sh
. /lib/functions.sh
. /usr/share/qmodem/modem_util.sh
sim_gpio="/sys/class/gpio/sim/value"
modem_gpio="/sys/class/gpio/4g/value"
debug=0
debug_log()
{
[ "$debug" -eq 1 ] && echo $1
}
# get detect config
load_detect_config()
{
config_load qmodem_hc_sim
config_get ping_dest main ping_dest
config_get judge_time main judge_time 5
config_get detect_interval main detect_interval 10
config_get modem_config main modem_config
[ -z "$modem_config" ] && get_first_avalible_config
debug_log "ping_dest:$ping_dest"
debug_log "judge_time:$judge_time"
debug_log "detect_interval:$detect_interval"
debug_log "modem_config:$modem_config"
}
_enabled_config()
{
cfg=$1
local state
config_get state $cfg state
[ -n "$state" ] && [ "$state" != "disabled" ] && modem_config=$cfg
}
get_first_avalible_config()
{
config_load qmodem
config_foreach _enabled_config modem-device
}
reboot_modem() {
echo 0 > $modem_gpio
sleep 1
echo 1 > $modem_gpio
}
switch_sim() {
if [ -f $sim_gpio ]; then
sim_status=$(cat $sim_gpio)
if [ "$sim_status" -eq 0 ]; then
echo 1 > $sim_gpio
else
echo 0 > $sim_gpio
fi
reboot_modem
logger -t modem_sim "switch sim from $sim_status to $(cat $sim_gpio)"
fi
}
_get_netdev() {
local modemconfig
config_load modemconfig $1 modem_config
[ "$modemconfig" != "$target_modemconfig" ] && return 1
config_get netdev $1 ifname
}
get_associa_netdev() {
config_load network
target_modemconfig=$1
config_foreach _get_netdev interface
unset target_modemconfig
}
ping_monitor() {
#ping_dest为空则不进行ping检测 ,如果有多个,用空格隔开
has_success=0
for dest in $ping_dest; do
ping -c 1 -W 1 $dest -I $netdev > /dev/null
if [ $? -eq 0 ]; then
return 1
fi
done
return 0
}
at_sim_monitor() {
ttydev=$1
#检查sim卡状态,有sim卡则返回1
expect="+CPIN: READY"
result=$(at $ttydev "AT+CPIN?" | grep -o "$expect")
debug_log $result
if [ -n "$result" ]; then
return 1
fi
return 0
}
at_dial_monitor() {
ttydev=$1
pdp_index=$2
#检查dial状态,有dial则返回1
[ -z "$pdp_index" ] && pdp_index=1
at_cmd="AT+CGPADDR=$pdp_index"
expect="+CGPADDR:"
result=$(at $ttydev $at_cmd | grep "$expect")
debug_log $result
if [ -n "$result" ];then
ipv6=$(echo $result | grep -oE "\b([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}\b")
ipv4=$(echo $result | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
disallow_ipv4="0.0.0.0"
#remove the disallow ip
if [ "$ipv4" == "$disallow_ipv4" ];then
ipv4=""
fi
if [ -n "$ipv4" ] || [ -n "$ipv6" ];then
return 1
fi
fi
return 0
}
precheck()
{
config_load qmodem
modem_config=$1
config_get state $modem_config state
# is empty or is disabled
config_get at_port $modem_config at_port
config_get enable_dial $modem_config enable_dial 0
config_get pdp_index $modem_config pdp_index 1
config_get global_en main enable_dial 0
debug_log "state:$state"
debug_log "at_port:$at_port"
debug_log "enable_dial:$enable_dial"
debug_log "pdp_index:$pdp_index"
debug_log "global_en:$global_en"
[ -z "$state" ] || [ "$state" == "disabled" ] && return 1
[ "$global_en" == "0" ] && return 1
[ -z "$enable_dial" ] || [ "$enable_dial" == "0" ] && return 1
[ -z "$at_port" ] && return 1
[ ! -e "$at_port" ] && return 1
return 0
}
main_loop()
{
while true;do
precheck $modem_config
if [ $? -eq 1 ];then
sleep $detect_interval
continue
fi
get_associa_netdev $modem_config
if [ -n "$ping_dest" ]; then
ping_monitor
ping_result=$?
fi
if [ -n "$at_port" ] && [ -n "$pdp_index" ];then
at_dial_monitor $at_port $pdp_index
dial_result=$?
fi
if [ -n "$at_port" ]; then
at_sim_monitor $at_port
sim_result=$?
fi
debug_log "ping_result:$ping_result dial_result:$dial_result sim_result:$sim_result"
if [ -n "$ping_dest" ];then
#策略:ping成功则重置fail_times,否则fail_times累加
[ -z "$dial_result" ] && dial_result=1
[ -z "$sim_result" ] && sim_result=1
fail_total=$((3 - $ping_result - $dial_result - $sim_result))
if [ $ping_result -eq 1 ]; then
fail_times=0
else
fail_times=$(($fail_times + $fail_total))
fi
#如果失败次数超过judge_time * 3则切卡 切卡后等待3分钟
else
#策略 无ping则检测拨号和sim卡状态,拨号成功则重置fail_times,否则fail_times累加
[ -z "$dial_result" ] && dial_result=1
[ -z "$sim_result" ] && sim_result=1
fail_total=$((2 - $dial_result - $sim_result))
if [ $dial_result -eq 1 ]; then
fail_times=0
else
fail_times=$(($fail_times + $fail_total))
fi
fi
logger -t modem_sim "ping_result:$ping_result dial_result:$dial_result sim_result:$sim_result fail_times:$fail_times fail_total:$fail_total fail_times:$fail_times"
if [ $fail_times -ge $(($judge_time * 2)) ]; then
switch_sim
fail_times=0
sleep 240
fi
sleep $detect_interval
done
}
if [ ! "$debug" -eq 1 ]; then
sleep 180
fi
load_detect_config
main_loop
|
281677160/openwrt-package | 2,181 | luci-app-qmodem/luci/luci-app-qmodem-mwan/luasrc/model/cbi/qmodem/mwan_config.lua |
local d = require "luci.dispatcher"
local uci = luci.model.uci.cursor()
local sys = require "luci.sys"
local script_path="/usr/share/qmodem/"
m = Map("qmodem_mwan")
m.title = translate("Mwan Config")
m.description = translate("Check and modify the mwan configuration")
s = m:section(NamedSection, "global", "global")
s.anonymous = true
s.addremove = false
enable_mwan = s:option(Flag, "enable_mwan", translate("Enable MWAN"))
sticky = s:option(Flag,"sticky_mode",translate("sticky mode"))
sticky.default = 0
sticky.description = translate("same source ip address will always use the same wan interface")
sticky_timeout = s:option(Value,"sticky_timeout",translate("sticky timeout"))
sticky_timeout.default = 300
sticky_timeout.datatype = "uinteger"
sticky_timeout:depends("sticky_mode",1)
s = m:section(TypedSection, "ipv4", translate("IPV4 Config"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
member_interface = s:option(Value, "member_interface", translate("Interface"))
member_interface.rmempty = true
uci:foreach("network", "interface", function(s)
if s[".name"] ~= "loopback" and s[".name"] ~= "lan" then
member_interface:value(s[".name"])
end
end)
o = s:option(DynamicList, 'member_track_ip', translate('Track IP'))
o.datatype = 'host'
member_priority = s:option(Value, "member_priority", translate("Priority"))
member_priority.rmempty = true
member_priority.datatype = "range(1, 255)"
member_priority.default = 1
member_priority.description = translate("Set the priority for the load balancing member. A higher priority value gives precedence to this member when distributing traffic. The range is from 1 to 255. 1 is the highest priority")
-- member_priority:depends("member_interface", "")
member_weight = s:option(Value, "member_weight", translate("Weight"))
member_weight.rmempty = true
member_weight.datatype = "range(1, 255)"
member_weight.default = 1
member_weight.description = translate("Set the weight for the load balancing member. A higher weight means more traffic will be assigned to this member. The default value is 1, with a range from 1 to 255.")
-- member_weight:depends("member_interface", "")
return m
|
281677160/openwrt-package | 1,196 | luci-app-qmodem/luci/luci-app-qmodem-mwan/po/zh_Hans/modem_mwan.po | #model/modem_mwan.lua
msgid "same source ip address will always use the same wan interface"
msgstr "相同的源IP地址将在一定时间内始终使用相同的WAN接口"
msgid "Check and modify the mwan configuration"
msgstr "检查和修改mwan配置"
msgid "sticky mode"
msgstr "粘性模式"
msgid "sticky timeout"
msgstr "粘性超时"
msgid "Track IP"
msgstr "跟踪IP"
msgid "Interface"
msgstr "成员接口"
msgid "Priority"
msgstr "成员优先级"
msgid "Weight"
msgstr "成员权重"
msgid "Mwan Config"
msgstr "多WAN配置"
msgid "IPV4 Config"
msgstr "IPV4配置"
msgid "Enable MWAN"
msgstr "启用MWAN"
msgid "Set the weight for the load balancing member. A higher weight means more traffic will be assigned to this member. The default value is 1, with a range from 1 to 255."
msgstr "设置负载均衡成员的权重。权重越高,该成员被分配到的流量越多。默认值为1,范围为1到255。"
msgid "Set the priority for the load balancing member. A higher priority value gives precedence to this member when distributing traffic. The range is from 1 to 255. 1 is the highest priority"
msgstr "设置负载均衡成员的优先级。当分发流量时,优先级值越高,该成员越优先。范围是1到255。1是最高优先级。"
msgid "Priority determines the order of member selection, while weight determines the traffic distribution ratio among members with the same priority."
msgstr "优先级决定成员选择的顺序,而权重决定具有相同优先级的成员之间流量分配比率。"
|
281677160/openwrt-package | 3,273 | luci-app-qmodem/luci/luci-app-qmodem-mwan/root/usr/share/qmodem/modem_mwan.sh | #! /bin/sh
. /lib/functions.sh
append_if(){
interface=$1
track_ip=$2
uci batch <<EOF
set mwan3.$interface=interface
set mwan3.$interface.enabled=1
set mwan3.$interface.family="$family"
set mwan3.$interface.track_method=ping
set mwan3.$interface.reliability='1'
set mwan3.$interface.count='1'
set mwan3.$interface.size='56'
set mwan3.$interface.max_ttl='60'
set mwan3.$interface.timeout='4'
set mwan3.$interface.interval='10'
set mwan3.$interface.failure_interval='5'
set mwan3.$interface.recovery_interval='5'
set mwan3.$interface.down='5'
set mwan3.$interface.up='5'
set mwan3.$interface.keep_failure_interval='1'
set mwan3.$interface.add_by=modem
delete mwan3.$interface.track_ip
EOF
if [ -n "$track_ip" ]; then
for ip in $track_ip; do
uci add_list mwan3.$interface.track_ip=$ip
done
fi
}
add_mwan3_member()
{
interface=$1
metric=$2
weight=$3
member_name=$4
uci batch <<EOF
set mwan3.$member_name=member
set mwan3.$member_name.interface=$interface
set mwan3.$member_name.metric=$metric
set mwan3.$member_name.weight=$weight
set mwan3.$member_name.add_by=modem
EOF
}
remove_member()
{
config_load mwan3
config_foreach remove_member_cb member
}
remove_member_cb()
{
local add_by
config_get add_by $1 add_by
if [ "$add_by" = "modem" ]; then
uci delete mwan3.$1
fi
}
append_mwan3_policy_member()
{
uci add_list mwan3.$1.use_member=$2
}
init_mwan3_policy()
{
policy_name=$1
uci batch <<EOF
set mwan3.$policy_name=policy
set mwan3.$policy_name.last_resort='default'
set mwan3.$policy_name.add_by=modem
delete mwan3.$policy_name.use_member
EOF
}
flush_config(){
config_load mwan3
config_foreach remove_cb interface
config_foreach remove_cb member
config_foreach remove_cb policy
config_foreach remove_cb rule
}
remove_cb(){
local add_by
config_get add_by $1 add_by
if [ "$add_by" = "modem" ]; then
uci delete mwan3.$1
fi
}
gen_rule()
{
use_policy=$1
rule_name=${family}_rule
uci batch <<EOF
set mwan3.$rule_name=rule
set mwan3.$rule_name.family="$family"
set mwan3.$rule_name.sticky=$sticky_mode
set mwan3.$rule_name.proto='all'
set mwan3.$rule_name.use_policy=$use_policy
set mwan3.$rule_name.add_by=modem
EOF
if [ -n "$sticky_timeout" ]; then
uci set mwan3.$rule_name.timeout=$sticky_timeout
fi
}
handle_config()
{
config_get interface $1 member_interface
config_get priority $1 member_priority
config_get weight $1 member_weight
config_get track_ip $1 member_track_ip
echo $1
append_if $interface "$track_ip"
add_mwan3_member $interface $priority $weight m$interface
append_mwan3_policy_member $family m$interface
}
/etc/init.d/mwan3 stop
flush_config
uci commit mwan3
config_load qmodem_mwan
family=$1
case $2 in
"start")
config_get sticky_mode global sticky_mode 0
config_get sticky_timeout global sticky_timeout
echo $sticky_mode $sticky_timeout
init_mwan3_policy $family
config_foreach handle_config $family
gen_rule $family
;;
"stop")
rule_name=${family}_rule
uci delete mwan3.$rule_name
;;
esac
uci commit mwan3
/etc/init.d/mwan3 start
|
281677160/openwrt-package | 1,191 | luci-app-qmodem/luci/luci-app-qmodem-mwan/root/etc/uci-defaults/99-setup-mwan | #!/bin/sh
. /lib/functions.sh
. /lib/functions/uci-defaults.sh
. /lib/functions/system.sh
modem_settings()
{
local board="$1"
case $board in
HC,HC-G80)
add_ipv4_config "1_1_1" 2 1
add_ipv4_config "1_1_4" 2 1
add_ipv4_config "2_1" 1 1
uci commit qmodem_mwan
;;
ailf,gs2410)
add_ipv4_config "5g0" 1 1
add_ipv4_config "5g1" 1 1
add_ipv4_config "4g0" 30 1
add_ipv4_config "4g1" 30 1
add_ipv4_config "4g2" 30 1
add_ipv4_config "4g3" 30 1
uci commit qmodem_mwan
;;
huasifei,ws3006)
add_ipv4_config "5g0" 10 1
add_ipv4_config "5g1" 10 1
add_ipv4_config "4g0" 10 1
add_ipv4_config "4g1" 10 1
add_ipv4_config "4g2" 10 1
add_ipv4_config "4g3" 10 1
uci commit qmodem_mwan
;;
esac
}
add_ipv4_config(){
local interface_name="$1"
cfg=$(uci add qmodem_mwan ipv4)
uci batch<<-EOF >/dev/null
set qmodem_mwan.$cfg.member_interface=$interface_name
set qmodem_mwan.$cfg.member_priority=$2
set qmodem_mwan.$cfg.member_weight=$3
add_list qmodem_mwan.$cfg.member_track_ip='119.29.29.29'
add_list qmodem_mwan.$cfg.member_track_ip='taobao.com'
add_list qmodem_mwan.$cfg.member_track_ip='baidu.com'
EOF
}
board=$(board_name)
modem_settings $board
exit 0
|
281677160/openwrt-package | 2,262 | luci-app-qmodem/luci/luci-app-qmodem/htdocs/luci-static/resources/view/status/include/11_modem.js | 'use strict';
'require baseclass';
'require rpc';
var callModemInfo = rpc.declare({
object: 'modem_ctrl',
method: 'info'
});
function progressbar(value, max, min, unit) {
var value = parseInt(value) || 0,
max = parseInt(max) || 100,
min = parseInt(min) || 0,
unit = unit || '',
pc = Math.floor((100 / (max - min)) * (value - min));
return E('div', {
'class': 'cbi-progressbar',
'title': '%s / %s%s (%d%%)'.format(value, max, unit,pc)
}, E('div', { 'style': 'width:%.2f%%'.format(pc) }));
}
return baseclass.extend({
title: _('Modem Info'),
load: function() {
return Promise.all([
L.resolveDefault(callModemInfo(), {}),
]);
},
render: function(data) {
var table = E('table', { 'class': 'table' });
try {
var infos = data[0].info
var fields = [];
for (let modem_info of infos) {
var info = modem_info.modem_info;
for (var entry of info) {
var full_name = entry.full_name;
if (entry.value == null) {
continue
}
if ((entry.class == 'Base Information') ||(entry.class == '"SIM Information"') || (entry.class == 'Cell Information' && entry.type == 'progress_bar')) {
fields.push(_(full_name));
fields.push(entry);
}
}
if (fields.length == 0) {
table.appendChild(E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '100%' }, [ _('No modem information available') ])
]));
return table;
}
}
for (var i = 0; i < fields.length; i += 2) {
let entry, type, value;
entry = fields[i + 1];
type = entry.type;
if (type == 'progress_bar') {
value = E('td', { 'class': 'td left' }, [
(entry.value != null) ? progressbar(entry.value, entry.max_value, entry.min_value, entry.unit) : '?'
])
} else {
value = E('td', { 'class': 'td left' }, [ (fields[i + 1] != null) ? entry.value : '?' ])
}
table.appendChild(E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '33%' }, [ fields[i] ]),
value
]));
}
return table;
}
catch (e) {
table.appendChild(E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td left', 'width': '100%' }, [ _('No modem information available') ])
]));
return table;
}
}
});
|
281677160/openwrt-package | 6,223 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/controller/qmodem.lua | -- Copyright 2024 Siriling <siriling@qq.com>
-- Copyright 2024 FJR <fjrcn@outlook.com>
module("luci.controller.qmodem", package.seeall)
local http = require "luci.http"
local fs = require "nixio.fs"
local json = require("luci.jsonc")
uci = luci.model.uci.cursor()
local script_path="/usr/share/qmodem/"
local run_path="/tmp/run/qmodem/"
local modem_ctrl = "/usr/share/qmodem/modem_ctrl.sh "
function index()
if not nixio.fs.access("/etc/config/qmodem") then
return
end
entry({"admin", "modem"}, firstchild(), _("Modem"), 25).dependent=false
entry({"admin", "modem", "qmodem"}, alias("admin", "modem", "qmodem", "modem_info"), luci.i18n.translate("QModem"), 100).dependent = true
--模块信息
entry({"admin", "modem", "qmodem", "modem_info"}, template("qmodem/modem_info"), luci.i18n.translate("QModem Information"),2).leaf = true
entry({"admin", "modem", "qmodem", "get_modem_cfg"}, call("getModemCFG"), nil).leaf = true
entry({"admin", "modem", "qmodem", "modem_ctrl"}, call("modemCtrl")).leaf = true
--拨号配置
entry({"admin", "modem", "qmodem", "dial_overview"},cbi("qmodem/dial_overview"),luci.i18n.translate("Dial Overview"),3).leaf = true
entry({"admin", "modem", "qmodem", "dial_config"}, cbi("qmodem/dial_config")).leaf = true
entry({"admin", "modem", "qmodem", "modems_dial_overview"}, call("getOverviews"), nil).leaf = true
--模块调试
entry({"admin", "modem", "qmodem", "modem_debug"},template("qmodem/modem_debug"),luci.i18n.translate("Advance Modem Settings"),4).leaf = true
entry({"admin", "modem", "qmodem", "send_at_command"}, call("sendATCommand"), nil).leaf = true
--Qmodem设置
entry({"admin", "modem", "qmodem", "settings"}, cbi("qmodem/settings"), luci.i18n.translate("QModem Settings"),100).leaf = true
entry({"admin", "modem", "qmodem", "slot_config"}, cbi("qmodem/slot_config")).leaf = true
entry({"admin", "modem", "qmodem", "modem_config"}, cbi("qmodem/modem_config")).leaf = true
end
--[[
@Description 执行Shell脚本
@Params
command sh命令
]]
function shell(command)
local odpall = io.popen(command)
local odp = odpall:read("*a")
odpall:close()
return odp
end
function translate_modem_info(result)
modem_info = result["modem_info"]
response = {}
for k,entry in pairs(modem_info) do
if type(entry) == "table" then
key = entry["key"]
full_name = entry["full_name"]
if full_name then
full_name = luci.i18n.translate(full_name)
elseif key then
full_name = luci.i18n.translate(key)
end
entry["full_name"] = full_name
if entry["class"] then
entry["class"] = luci.i18n.translate(entry["class"])
end
table.insert(response, entry)
end
end
return response
end
function modemCtrl()
local action = http.formvalue("action")
local cfg_id = http.formvalue("cfg")
local params = http.formvalue("params")
local translate = http.formvalue("translate")
if params then
result = shell(modem_ctrl..action.." "..cfg_id.." ".."\""..params.."\"")
else
result = shell(modem_ctrl..action.." "..cfg_id)
end
if translate == "1" then
modem_more_info = json.parse(result)
modem_more_info = translate_modem_info(modem_more_info)
result = json.stringify(modem_more_info)
end
luci.http.prepare_content("application/json")
luci.http.write(result)
end
--[[
@Description 执行AT命令
@Params
at_port AT串口
at_command AT命令
]]
function at(at_port,at_command)
local command="source "..script_path.."modem_util.sh && at "..at_port.." "..at_command
local result=shell(command)
result=string.gsub(result, "\r", "")
return result
end
--[[
@Description 获取模组信息
]]
function getOverviews()
-- 获取所有模组
local modems={}
local logs={}
uci:foreach("qmodem", "modem-device", function (modem_device)
section_name = modem_device[".name"]
modem_name = modem_device["name"] or luci.i18n.translate("Unknown")
alias = modem_device["alias"]
modem_state = modem_device["state"]
if modem_state == "disabled" then
return
end
--模组信息部分
cmd = modem_ctrl.."base_info "..section_name
result = shell(cmd)
json_result = json.parse(result) or "{}"
modem_info = json_result["modem_info"]
tmp_info = {}
if alias then
title = alias .. "("..modem_name..")"
else
title = modem_name
end
name = {
type = "plain_text",
key = "name",
value = title
}
table.insert(tmp_info, name)
for k,v in pairs(modem_info) do
full_name = v["full_name"]
if full_name then
v["full_name"] = luci.i18n.translate(full_name)
end
table.insert(tmp_info, v)
end
table.insert(modems, tmp_info)
--拨号日志部分
log_path = run_path..section_name.."_dir/dial_log"
if fs.access(log_path) then
log_msg = fs.readfile(log_path)
modem_log = {}
modem_log["log_msg"] = log_msg
modem_log["section_name"] = section_name
if alias then
modem_log["name"] = alias .. "("..modem_name..")"
else
modem_log["name"] = modem_name
end
table.insert(logs, modem_log)
end
end)
-- 设置值
local data={}
data["modems"]=modems
data["logs"]=logs
luci.http.prepare_content("application/json")
luci.http.write_json(data)
end
function getModemCFG()
local cfgs={}
local translation={}
uci:foreach("qmodem", "modem-device", function (modem_device)
modem_state = modem_device["state"]
if modem_state == "disabled" then
return
end
--获取模组的备注
local network=modem_device["modem"]
local alias=modem_device["alias"]
local config_name=modem_device[".name"]
--设置模组AT串口
local cfg = modem_device[".name"]
local at_port=modem_device["at_port"]
local name=modem_device["name"]:upper()
local config = {}
if alias then
config["name"] = alias .. "("..name..")"
else
config["name"] = name
end
config["at_port"] = at_port
config["cfg"] = cfg
table.insert(cfgs, config)
end)
-- 设置值
local data={}
data["cfgs"]=cfgs
data["translation"]=translation
-- 写入Web界面
luci.http.prepare_content("application/json")
luci.http.write_json(data)
end
function sendATCommand()
local at_port = http.formvalue("port")
local at_command = http.formvalue("command")
local response={}
if at_port and at_command then
response["response"]=at(at_port,at_command)
response["time"]=os.date("%Y-%m-%d %H:%M:%S")
end
-- 写入Web界面
luci.http.prepare_content("application/json")
luci.http.write_json(response)
end
|
281677160/openwrt-package | 14,088 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/view/qmodem/modem_info.htm | <%+header%>
<style type="text/css">
#warning_message_box {
margin: 1rem;
padding: 1rem;
height: auto;
}
.table {
display: table;
}
.compat-progressbar {
border: 1px solid var(--border-color-high,var(--progressbarColor,var(--background-color)));
border-radius: 3px;
position: relative;
min-width: 170px;
height: 8px;
margin: 1.4em 0 4px 0;
background: var(--background-color-medium,var(--progressbarColor));
}
.compat-progressbar > div {
background: var(--progressbar, var(--primary, var(--primary-color-medium)));
height: 100%;
transition: width .25s ease-in;
width: 0%;
border-radius: 2px;
}
.compat-progressbar::before {
position: absolute;
top: -1.4em;
left: 0;
content: attr(title);
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<script>
function hasCssClass(className) {
// 获取所有样式表
const styleSheets = document.styleSheets;
// 遍历每个样式表
for (let i = 0; i < styleSheets.length; i++) {
const rules = styleSheets[i].cssRules || styleSheets[i].rules; // 兼容不同浏览器
// 遍历每个样式规则
for (let j = 0; j < rules.length; j++) {
if (rules[j].selectorText && rules[j].selectorText.includes(className)) {
return true; // 找到定义,返回 true
}
}
}
return false; // 没有找到定义,返回 false
}
const progressbar_className = hasCssClass('.cbi-progressbar') ? 'cbi-progressbar' : 'compat-progressbar';
class LuciTable{
constructor(){
this.rows = [];
this.tbody;
this.fieldset;
this.init_table();
}
init_table(){
//create a luci fieldset (class cbi-section)
var fieldset = document.createElement('fieldset');
fieldset.className="cbi-section";
//set fieldset Header name
var legend = document.createElement('legend');
var title_span = document.createElement('h2');
title_span.className="panel-title"
//init table
var table = document.createElement('table');
var tbody = document.createElement('tbody');
tbody.style.width = "100%";
table.className="table"
//save
this.fieldset = fieldset;
this.tbody = tbody
this.title_span = title_span
this.legend = legend
fieldset.appendChild(legend);
fieldset.appendChild(title_span);
table.appendChild(tbody)
fieldset.appendChild(table)
}
new_tr(data,index){
var type = data.type;
switch(type){
case "plain_text":
var key,value,full_name;
key = data.key;
value = data.value;
full_name = data.full_name ? data.full_name : key;
this.rows[index].left.innerHTML = full_name;
this.rows[index].right.innerHTML = value;
if (value == null || value == "") {
this.rows[index].row.style.display = "none";
}
else{
this.rows[index].row.style.display = "";
}
break;
case "progress_bar":
var key,title,min,max,precentage,full_name;
key = data.key;
full_name = data.full_name ? data.full_name : key;
title = `(${data.value}/${data.max_value}${data.unit})`
min = data.min_value;
max = data.max_value;
precentage = (data.value - min) / (max - min) * 100;
this.rows[index].left.innerHTML = full_name;
var progress_bar = document.createElement('div')
progress_bar.className = progressbar_className;
progress_bar.title = title;
var progress_bar_bar = document.createElement('div')
progress_bar_bar.setAttribute("style","width:"+precentage+"%")
progress_bar.appendChild(progress_bar_bar)
this.rows[index].right.innerHTML = ""
this.rows[index].right.appendChild(progress_bar)
break;
}
}
set title(value){
this.legend.innerHTML = value;
this.title_span.innerHTML = value;
}
set object_data(value){
var row_length = this.rows.length;
var value_length = Object.keys(value).length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.classList.add("left")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("td")
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
var index = 0;
for (var key in value) {
this.rows[index].left.innerHTML = key;
this.rows[index].right.innerHTML = value[key];
index++;
}
}
set array_data(value){
var row_length = this.rows.length;
var value_length = value.length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("td")
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
for (let i = 0; i < value.length; i++) {
this.new_tr(value[i],i);
}
}
set data(value){
if (value == null) {
return;
}
if (Array.isArray(value)) {
this.array_data = value;
}
else{
this.object_data = value;
}
}
}
class ModemInfo {
constructor() {
this.data = null;
this.cfg_id = null;
this.modem_cfg_list = [];
this.tables = {};
this.cbi_map = document.querySelector('.cbi-map');
this.init_warning_message_box();
this.modem_selector = document.getElementById('modem_selector');
this.create_modem_cfg_selector();
this.update_modem_cfg_list();
}
init_warning_message_box()
{
var warning_message_box,title,message_box;
warning_message_box = document.createElement('div');
warning_message_box.className = "alert-message alert-danger";
warning_message_box.id = "warning_message_box";
title=document.createElement('strong');
title.innerHTML = "<%:Warning!%>";
message_box=document.createElement('div');
message_box.id = "warning_message";
warning_message_box.style.display = "none";
warning_message_box.appendChild(title);
warning_message_box.appendChild(message_box);
this.cbi_map.appendChild(warning_message_box);
this.message_box = message_box;
this.warning_message_box = warning_message_box;
}
warning_message(node_list)
{
this.warning_message_box.style.display = "";
this.message_box.innerHTML = ""
this.message_box.appendChild(node_list);
}
hide_warning_message()
{
this.warning_message_box.style.display = "none";
}
create_modem_cfg_selector(){
var selector = document.createElement('select');
selector.addEventListener('change', (event) => {
this.update();
this.cfg_id = event.target.value;
console.log(this.cfg_id);
});
this.modem_selector.appendChild(selector);
this.selector = selector;
this.poll_info();
}
poll_info(){
if (this.cfg_id == null){
return;
}
XHR.poll(10,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',{
"cfg": this.cfg_id,
"action": "info",
"translate": "1"
}, (x,data) => {
this.view = data;
});
}
update(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',{
"cfg": this.cfg_id,
"action": "info",
"translate": "1"
}, (x,data) => {
this.view = data;
});
}
update_modem_cfg_list(){
XHR.poll(5,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_modem_cfg")%>',{},(x,data)=>{
var new_cfg_list = [];
var cfgs = data.cfgs;
for (let i = 0; i < cfgs.length; i++) {
var cfg = cfgs[i];
var name = cfg.name;
var value = cfg.cfg;
new_cfg_list.push({"value":value,"name":name});
}
if (new_cfg_list != this.modem_cfg_list) {
this.cfg_options = new_cfg_list;
}
});
}
set cfg_options(value){
var longger = this.modem_cfg_list.length > value.length ? this.modem_cfg_list : value;
if (longger.length == 0) {
return;
}
for (let i = 0; i < longger.length; i++) {
var option = this.selector.options[i];
if (i < value.length) {
if (i >= this.selector.options.length) {
option = document.createElement('option');
this.selector.appendChild(option);
}
option.value = value[i].value;
option.innerHTML = value[i].name;
}
else{
this.selector.removeChild(option);
}
}
this.cfg_id = this.selector.value;
this.modem_cfg_list = value;
this.update();
}
set view(data){
this.data = data;
if (data == null) {
return;
}
var keys = []
var tables_map = {}
var warning_message = [];
for (let entry of data){
let class_name,full_name,value,type;
class_name = entry.class;
if (entry.type == "warning_message") {
warning_message.push(entry);
continue;
}
if (tables_map[class_name] == null) {
tables_map[class_name] = []
}
tables_map[class_name].push(entry);
}
for (let class_name in tables_map) {
if (this.tables[class_name] == null) {
this.tables[class_name] = new LuciTable();
this.cbi_map.appendChild(this.tables[class_name].fieldset);
}
this.tables[class_name].title = class_name;
this.tables[class_name].data = tables_map[class_name];
}
for (let table in this.tables) {
if (tables_map[table] == null) {
this.cbi_map.removeChild(this.tables[table].fieldset);
delete this.tables[table];
}
}
if (warning_message.length > 0) {
for (let i = 0; i < warning_message.length; i++) {
let entry = warning_message[i];
let full_name = entry.full_name ? entry.full_name : entry.key;
let node = document.createElement('p');
node.innerHTML = full_name + entry.value;
this.warning_message(node);
}
}
else{
this.hide_warning_message();
}
}
}
window.onload = function(){
const modem_info = new ModemInfo();
}
</script>
<div>
<div class="cbi-map">
<fieldset class="cbi-section">
<table class="table">
<tbody>
<tr class="tr">
<td class="td" width="33%"><%:Modem Name%></td>
<td class="td" id="modem_selector">
</td>
</tr>
</tbody>
</table>
</fieldset>
</div>
</div>
<%+footer%>
|
281677160/openwrt-package | 38,464 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/view/qmodem/modem_debug.htm | <%+header%>
<script>
class ModemConfig {
constructor(cfg_id,title){
this.cfg_id = cfg_id;
this.init_view = false;
this.cbi_map = document.querySelector('.cbi-map');
this.fieldset = this.create_fieldset(title);
this.cbi_map.appendChild(this.fieldset);
}
update(){
console.log("update");
if (this.cb_update) {
this.cb_update();
}
}
pause(){
console.log("pause");
}
get_config(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',
{
"cfg": this.cfg_id,
"action": this.get_action
},
(x, data) => {
if (this.config_name){
this.config = data[this.config_name];
}
else {
this.config = data;
}
if (this.cb_get) {
this.cb_get(data);
}
}
);
}
set_config(config){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',
{
"cfg": this.cfg_id,
"action": this.set_action,
"params": JSON.stringify(config)
},
(x, data) => {
if (this.config_name){
this.config = data[this.config_name];
}
else {
this.config = data;
}
if (this.cb_set) {
this.cb_set(data);
}
}
);
}
create_fieldset(title){
var fieldset = document.createElement('fieldset');
fieldset.className = "cbi-section";
var legend = document.createElement('legend');
legend.innerHTML = title;
fieldset.appendChild(legend);
return fieldset;
}
createInput(name,value,hint){
var input = document.createElement('input');
input.type = "text";
input.name = name;
input.value = value;
input.placeholder = hint;
return input;
}
createBTN(name,cb){
var btn = document.createElement('input');
btn.type = "button";
btn.classList.add("cbi-button");
btn.value = name;
btn.addEventListener('click',cb);
return btn;
}
createRadio(name,value){
var radio = document.createElement('input');
radio.type = "radio";
radio.name = name;
radio.value = value;
return radio;
}
createCheckbox(value){
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = value;
return checkbox;
}
createTable(){
let table,tbody;
table = document.createElement('table');
table.classList.add("cbi-section-table");
table.classList.add("table");
tbody = document.createElement('tbody');
table.appendChild(tbody);
return table;
}
createDroplist(dict){
var select = document.createElement('select');
for (let key in dict) {
var option = document.createElement('option');
option.value = key;
option.innerHTML = dict[key];
select.appendChild(option);
}
return select;
}
createInputWithDatalist(name,hint,dict) {
// 创建输入框
var input = document.createElement('input');
input.setAttribute('list', name); // 设置 list 属性以关联 datalist
input.name = name;
input.placeholder = hint;
// 创建 datalist
var datalist = document.createElement('datalist');
datalist.id = name;
// 添加选项到 datalist
for (let key in dict) {
var option = document.createElement('option');
option.value = key;
datalist.appendChild(option);
}
return { input, datalist }; // 返回包含输入框和 datalist 的对象
}
createDroplistWithInput(name, hint, dict) {
var input = this.createInput("","",hint);
var selector = this.createDroplist(dict);
var prevous_selected = "";
var input_tips = "<%:Lost focus to save%>";
var selector_tips = "<%:Double Click or Right Click to Edit%>";
var input_descr = this.createDescription(input_tips);
var selector_descr = this.createDescription(selector_tips);
input.style.display = "none";
input_descr.style.display = "none";
selector.style.width = "100%";
selector.style.minWidth = "auto";
// add event to selector
selector.addEventListener('change', function(event) {
if (event.target.value.length == 0){
input.style.display = "";
selector.style.display = "none";
input_descr.style.display = "";
selector_descr.style.display = "none";
input.value = prevous_selected;
input.focus();
}
else {
input.style.display = "none";
selector.style.display = "";
input_descr.style.display = "none";
selector_descr.style.display = "";
prevous_selected = event.target.value;
}
});
// add event listener to seletor : right click or long press or double click: show input
selector.addEventListener('contextmenu', function(event) {
event.preventDefault();
input.style.display = "";
selector.style.display = "none";
input_descr.style.display = "";
selector_descr.style.display = "none";
input.value = prevous_selected;
input.focus();
});
// add event listener to seletor : hover: show tooltip
selector.addEventListener('mouseover', function(event) {
selector.title = selector_tips;
});
selector.addEventListener('dblclick', function(event) {
input.style.display = "";
selector.style.display = "none";
input_descr.style.display = "";
selector_descr.style.display = "none";
input.value = prevous_selected;
input.focus();
});
// add event listener to input : hover: show tooltip
input.addEventListener('mouseover', function(event) {
input.title = input_tips;
});
input.addEventListener('blur', function(event) {
if (event.target.value.length > 0) {
//clear user input option
for (let option of selector.options) {
if (option.type == "userInput") {
selector.removeChild(option);
}
}
for (let option of selector.options) {
if (option.value == event.target.value) {
selector.value = event.target.value;
selector.dispatchEvent(new Event('change'));
return;
}
}
var option = document.createElement('option');
option.value = event.target.value;
option.innerHTML = event.target.value;
option.type = "userInput";
selector.appendChild(option);
selector.value = event.target.value;
selector.dispatchEvent(new Event('change'));
}
else {
if (prevous_selected){
selector.value = prevous_selected;
selector.dispatchEvent(new Event('change'));
}
else{
//select first not null option
for (let option of selector.options) {
if (option.value.length > 0) {
selector.value = option.value;
selector.dispatchEvent(new Event('change'));
return;
}
}
selector.dispatchEvent(new Event('change'));
}
}
})
input.descr = input_descr;
selector.descr = selector_descr;
return { input, selector };
}
createTD(innerHTML){
var td = document.createElement('td');
td.classList.add("cbi-section-table-cell");
td.classList.add("td");
td.classList.add("left");
if (innerHTML) {
td.innerHTML = innerHTML;
}
return td;
}
createTH(innerHTML){
var th = document.createElement('th');
th.classList.add("cbi-section-table-cell");
th.classList.add("th");
if (innerHTML) {
th.innerHTML = innerHTML;
}
return th;
}
createTR(){
var tr = document.createElement('tr');
tr.classList.add("cbi-section-table-row");
tr.classList.add("tr");
return tr;
}
createDescription(innerHTML){
var div = document.createElement('div');
div.classList.add("cbi-section-descr");
div.innerHTML = innerHTML;
return div;
}
createTRHeader(){
var tr = document.createElement('div');
tr.classList.add("tr");
tr.classList.add("cbi-section-table-titles");
tr.classList.add("anonymous");
return tr;
}
init_table(){
var table = this.createTable();
this.fieldset.appendChild(table);
this.tbody = table.querySelector('tbody');
}
hide(){
this.fieldset.style.display = "none";
this.pause();
}
show(){
this.fieldset.style.display = "block";
console.log("show");
this.update();
}
}
//锁频功能
class Lockband extends ModemConfig{
constructor(cfg_id){
super(cfg_id,"<%:Lock Band%>");
this.config_name = "lockband";
this.get_action = "get_lockband";
this.set_action = "set_lockband";
this.lockband_config = {};
this.checkboxes = {};
this.available_bandid = {};
this.band_class_map = {};
this.init_table();
this.cb_get = (data) => {
this.render();
}
this.cb_set = (data) => {
this.get_config();
}
}
set lock(config){
var band_class = config.band_class;
var band_id = config.band_id;
if (!this.lockband_config[band_class].includes(band_id)){
this.lockband_config[band_class].push(band_id)
}
this.checkboxes[band_class][band_id].checked = true;
}
set unlock(config){
var band_class = config.band_class;
var band_id = config.band_id;
this.lockband_config[band_class] = this.lockband_config[band_class].filter(x => x != band_id);
//set checkbox
this.checkboxes[band_class][band_id].checked = false;
}
createCheckbox(band_class,band_name,band_id){
let checkbox = document.createElement('input');
checkbox.classList = ["cbi-input-checkbox"];
checkbox.type = "checkbox";
checkbox.value = band_id;
checkbox.setAttribute("display-band",band_name);
checkbox.addEventListener("change",() => {
if (checkbox.checked){
this.lock = { "band_class": band_class, "band_id": band_id };
}
else{
this.unlock = { "band_class": band_class, "band_id": band_id };
}
});
this.checkboxes[band_class][band_id] = checkbox;
if (this.lockband_config[band_class].includes(band_id)) {
this.lock = { "band_class": band_class, "band_id": band_id };
}
}
createcheckboxes(band_class){
var band = this.config[band_class];
var available_band = band.available_band;
var lock_band = band.lock_band;
this.lockband_config[band_class] = lock_band;
if ( available_band.length == 0) {
return;
}
if (this.checkboxes[band_class] == undefined) {
this.checkboxes[band_class] = {};
}
if (this.available_bandid[band_class] == undefined) {
this.available_bandid[band_class] = [];
}
for (let band_cfg of available_band) {
let band_name = band_cfg.band_name;
let band_id = band_cfg.band_id;
if (this.available_bandid[band_class].includes(band_id) == false) {
this.available_bandid[band_class].push(band_id);
}
this.createCheckbox(band_class,band_name,band_id);
}
}
submit(band_class)
{
var sorted = this.lockband_config[band_class].sort();
var config = '';
for (let band_id of sorted) {
config += band_id + ",";
}
var lockband_cfg = {
"band_class": band_class,
"lock_band": config.slice(0,-1)
}
var cfg_string = JSON.stringify(lockband_cfg);
this.set_config(cfg_string);
}
select_all(band_class){
//if all selected, then unselect all
let lockall = this.lockband_config[band_class].length != this.available_bandid[band_class].length;
for (let band_id of this.available_bandid[band_class]) {
if (lockall) {
this.lock = { "band_class": band_class, "band_id": band_id };
}
else{
this.unlock = { "band_class": band_class, "band_id": band_id };
}
}
}
render() {
for (let band_class in this.band_class_map){
if (this.config[band_class] == undefined) {
this.band_class_map[band_class].header.style.display = "none";
this.band_class_map[band_class].tr.style.display = "none";
this.band_class_map[band_class].select_all_btn.style.display = "none";
this.band_class_map[band_class].submit_btn.style.display = "none";
}
else{
this.band_class_map[band_class].header.style.display = "";
this.band_class_map[band_class].tr.style.display = "";
this.band_class_map[band_class].select_all_btn.style.display = "";
this.band_class_map[band_class].submit_btn
}
}
for (let band_class in this.config) {
let header, tr, td, select_all_btn, submit_btn;
this.createcheckboxes(band_class);
if (this.band_class_map[band_class] == undefined)
{
this.createBandTable(band_class);
}
header = this.band_class_map[band_class].header;
tr = this.band_class_map[band_class].tr;
select_all_btn = this.band_class_map[band_class].select_all_btn;
submit_btn = this.band_class_map[band_class].submit_btn
td = document.createElement('td');
td.classList.add("cbi-section-table-cell");
td.classList.add("td")
td.style.display = "flex";
td.style.flexWrap = "wrap";
//clear tr
while (tr.firstChild) {
tr.removeChild(tr.firstChild);
}
tr.appendChild(td);
for (let checkbox in this.checkboxes[band_class]) {
let display_value = this.checkboxes[band_class][checkbox].getAttribute("display-band");
let span = document.createElement('span');
span.innerHTML = display_value;
let band_container=document.createElement('span');
band_container.classList.add("band-container");
band_container.appendChild(this.checkboxes[band_class][checkbox]);
band_container.appendChild(span);
td.appendChild(band_container);
}
}
}
createBandTable(band_class){
let tr_header, th, tr, td, select_all_btn, submit_btn;
tr_header = document.createElement('div');
tr_header.className = "tr cbi-section-table-titles anonymous";
th = document.createElement('div');
th.className = "th cbi-section-table-cell";
th.innerHTML = band_class;
tr_header.appendChild(th);
tr = document.createElement('tr');
tr.className = "tr cbi-section-table-row";
select_all_btn = this.createBTN("<%:Select All%>", () => {
this.select_all(band_class);
});
submit_btn = this.createBTN("<%:Submit%>", () => {
this.submit(band_class);
});
this.band_class_map[band_class] = {
"header": tr_header,
"tr": tr,
"select_all_btn": select_all_btn,
"submit_btn": submit_btn
}
this.tbody.appendChild(tr_header);
this.tbody.appendChild(tr);
this.tbody.appendChild(select_all_btn);
this.tbody.appendChild(submit_btn);
}
update() {
console.log(JSON.stringify(this.lockband_config));
console.log(JSON.stringify(this.available_bandid));
console.log(JSON.stringify(this.band_class_map));
console.log(JSON.stringify(this.config));
this.get_config();
}
}
class RatPrefer extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:Rat Prefer%>");
this.config_name = "network_prefer";
this.get_action = "get_network_prefer";
this.set_action = "set_network_prefer";
this.selected_rat = [];
this.available_rat = [];
this.init_table();
this.create_submit_btn();
}
cb_get(data){
//clear selected_rat
this.selected_rat = [];
//clear available_rat
this.available_rat = [];
for (let key in this.config){
if (this.config[key] == 1) {
this.selected_rat.push(key);
}
this.available_rat.push(key);
}
this.render_checkbox();
this.render_current_mode();
}
cb_set(data){
this.get_config();
}
render_current_mode(){
let selected_mode = []
for (let rat in this.config) {
if (this.config[rat] == 1) {
selected_mode.push(rat);
}
}
this.current_mode = selected_mode.join(',');
this.current_mode_td.innerHTML = this.current_mode;
}
render_checkbox(){
if (this.init_view == false) {
this.init_ele();
this.init_view = true;
}
this.createCheckboxes();
}
create_submit_btn(){
var submit_btn = this.createBTN("<%:Submit%>",() => {
this.submit();
});
this.fieldset.appendChild(submit_btn);
}
createCheckbox(rat){
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = rat;
checkbox.addEventListener('change',() => {
if (checkbox.checked) {
this.selected_rat.push(rat);
}
else{
this.selected_rat = this.selected_rat.filter(x => x != rat);
}
});
return checkbox;
}
createCheckboxes(){
//clear select_td
while (this.select_td.firstChild) {
this.select_td.removeChild(this.select_td.firstChild);
}
var network_prefer = this.config;
for (let rat of this.available_rat) {
var checkbox = this.createCheckbox(rat);
if (this.selected_rat.includes(rat)) {
checkbox.checked = true;
}
var span = document.createElement('span');
span.innerHTML = rat;
this.select_td.appendChild(checkbox);
this.select_td.appendChild(span);
}
}
update(){
this.get_config();
}
submit(){
this.set_config(JSON.stringify(this.selected_rat));
}
init_ele(){
var header_tr,current_mode_th,select_th,setting_tr,current_mode_td,select_td;
header_tr = this.createTRHeader();
current_mode_th = this.createTH("<%:Current Mode%>");
select_th = this.createTH("<%:Setting%>");
setting_tr = this.createTR();
current_mode_td = this.createTD();
select_td = this.createTD();
header_tr.appendChild(current_mode_th);
header_tr.appendChild(select_th);
setting_tr.appendChild(current_mode_td);
setting_tr.appendChild(select_td);
this.tbody.appendChild(header_tr);
this.tbody.appendChild(setting_tr);
this.current_mode_td = current_mode_td;
this.select_td = select_td;
}
}
class DialMode extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:Dial Mode%>");
this.config_name = "";
this.get_action = "get_mode";
this.set_action = "set_mode";
this.avalibale_mode = [];
this.selected_mode = null;
this.init_table();
this.td_map = {
"current_mode": null,
"radio_div": null,
}
this.cb_get = (data) => {
this.render();
}
this.cb_set = (data) => {
this.get_config();
}
}
render(){
if (this.td_map["current_mode"] == null) {
this.init_ele();
}
if (this.config.disable_mode_btn == 0 || this.config.disable_mode_btn == undefined) {
this.mode_btn.disabled = false;
}
else{
this.mode_btn.disabled = true;
}
for (let key in this.config.mode){
if (this.avalibale_mode.includes(key) == false)
{
this.avalibale_mode.push(key);
}
if (this.config.mode[key] == 1) {
this.selected_mode = key;
this.td_map.current_mode.innerHTML = key;
}
}
this.create_mode_radio();
}
init_ele(){
var radio_div_th, current_mode_th, radio_div, current_mode, header_tr, setting_tr;
header_tr = document.createElement('div');
header_tr.className = "tr cbi-section-table-titles anonymous";
radio_div_th = document.createElement('div');
radio_div_th.className = "th cbi-section-table-cell";
radio_div_th.innerHTML = "<%:Dial Mode%>";
current_mode_th = document.createElement('div');
current_mode_th.className = "th cbi-section-table-cell";
current_mode_th.innerHTML = "<%:Current Mode%>";
setting_tr = document.createElement('div');
setting_tr.className = "tr cbi-section-table-row";
radio_div = document.createElement('div');
radio_div.className = "td cbi-section-table-cell left";
current_mode = document.createElement('div');
current_mode.className = "td cbi-section-table-cell left";
header_tr.appendChild(current_mode_th);
header_tr.appendChild(radio_div_th);
setting_tr.appendChild(current_mode);
setting_tr.appendChild(radio_div);
this.tbody.appendChild(header_tr);
this.tbody.appendChild(setting_tr);
this.td_map["radio_div"] = radio_div;
this.td_map["current_mode"] = current_mode;
this.mode_btn = this.createBTN("<%:Submit%>",() => {
this.set_config(this.selected_mode);
});
this.tbody.appendChild(this.mode_btn);
}
create_mode_radio(){
while (this.td_map.radio_div.firstChild) {
this.td_map.radio_div.removeChild(this.td_map.radio_div.firstChild);
}
for (let mode of this.avalibale_mode) {
let radio = this.createRadio("mode",mode);
if (mode == this.selected_mode) {
radio.checked = true;
}
radio.addEventListener('change',() => {
this.selected_mode = mode;
});
let span = document.createElement('span');
span.innerHTML = mode;
//clear radio_div
this.td_map.radio_div.appendChild(radio);
this.td_map.radio_div.appendChild(span);
}
}
update(){
this.get_config();
}
}
class NeighborCell extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:Neighbor Cell%>");
this.config_name = "neighborcell";
this.get_action = "get_neighborcell";
this.set_action = "set_neighborcell";
this.task = null;
this.init_nc_table();
}
scan_neighborcell(){
this.get_config();
}
// pause(){
// if (this.task != null) {
// clearInterval(this.task);
// }
// }
// update(){
// this.task = setInterval(() => {
// this.get_config();
// },10000);
// }
nr_options(){
if (this.rat_input.selectedIndex == 0) {
this.band_tr.style.display = "none";
this.scs_tr.style.display = "none";
}
else{
this.band_tr.style.display = "";
this.scs_tr.style.display = "";
}
}
init_nc_table(){
var neighborcell_table,setting_table,status_table ;
neighborcell_table = this.createTable();
status_table = this.createTable();
setting_table = this.createTable();
this.fieldset.appendChild(neighborcell_table);
this.fieldset.appendChild(status_table);
this.fieldset.appendChild(setting_table);
this.neighborcell_table = neighborcell_table.querySelector('tbody');
this.status_table = status_table.querySelector('tbody');
this.setting_table = setting_table.querySelector('tbody');
var pci_tr,arfcn_tr,band_tr,scs_tr,header,td,td1,th,pci_input,arfcn_input,band_input,scs_input,rat_input,rat_tr;
var status_th,status_trh;
header = this.createTRHeader();
th = this.createTH("<%:Lock Cell Setting%>");
header.appendChild(th);
rat_input = this.createDroplist({0:"LTE",1:"NR"});
rat_tr = this.createTR();
td = this.createTD("<%:RAT%>");
td1 = this.createTD();
td1.appendChild(rat_input);
rat_tr.appendChild(td);
rat_tr.appendChild(td1);
pci_tr = this.createTR();
td = this.createTD("<%:PCI%>");
pci_input = this.createInput("pci","");
td1 = this.createTD();
td1.appendChild(pci_input);
pci_tr.appendChild(td);
pci_tr.appendChild(td1);
arfcn_tr = this.createTR();
td = this.createTD("<%:ARFCN%>");
arfcn_input = this.createInput("arfcn","");
td1 = this.createTD();
td1.appendChild(arfcn_input);
arfcn_tr.appendChild(td);
arfcn_tr.appendChild(td1);
band_tr = this.createTR();
td = this.createTD("<%:Band%>");
band_input = this.createInput("band","");
td1 = this.createTD();
td1.appendChild(band_input);
band_tr.appendChild(td);
band_tr.appendChild(td1);
scs_tr = this.createTR();
td = this.createTD("<%:SCS%>");
scs_input = this.createDroplist({0:"15KHZ",1:"30KHZ"});
td1 = this.createTD();
td1.appendChild(scs_input);
scs_tr.appendChild(td);
scs_tr.appendChild(td1);
status_th = this.createTH("<%:Status%>");
status_trh = this.createTRHeader();
status_trh.appendChild(status_th);
this.status_table.appendChild(status_trh);
this.pci_input = pci_input;
this.arfcn_input = arfcn_input;
this.band_input = band_input;
this.scs_input = scs_input;
this.rat_input = rat_input;
this.band_tr = band_tr;
this.scs_tr = scs_tr;
this.band_tr.style.display = "none";
this.scs_tr.style.display = "none";
this.rat_input.addEventListener('change',()=>{
this.nr_options();
});
var submit_btn = this.createBTN("<%:Submit%>",() => {
var config = {
"rat": this.rat_input.selectedIndex,
"pci": this.pci_input.value,
"arfcn": this.arfcn_input.value,
"band": this.band_input.value,
"scs": this.scs_input.selectedIndex
}
this.set_config(JSON.stringify(config));
});
//add scan button
var scan_btn = this.createBTN("<%:Scan%>",() => {
this.scan_neighborcell();
});
this.setting_table.appendChild(header);
this.setting_table.appendChild(rat_tr);
this.setting_table.appendChild(pci_tr);
this.setting_table.appendChild(arfcn_tr);
this.setting_table.appendChild(band_tr);
this.setting_table.appendChild(scs_tr);
this.setting_table.appendChild(scan_btn);
this.setting_table.appendChild(submit_btn);
}
render_neighborcell(){
//clear neighborcell_table
while (this.neighborcell_table.querySelector("tr")) {
let remove = this.neighborcell_table.querySelector("tr")
this.neighborcell_table.removeChild(remove);
}
var nr,lte,tr_left
nr = this.config.NR;
lte = this.config.LTE;
for (let cell_info of nr) {
this.create_nc_tr(1,cell_info);
}
for (let cell_info of lte) {
this.create_nc_tr(0,cell_info);
}
}
render_status(){
//clear status_table
while (this.status_table.querySelector("tr")) {
this.status_table.removeChild(this.status_table.querySelector("tr"));
}
var status = this.config.lockcell_status;
for (let key in status) {
if (status[key] != ""){
this.create_status_tr(key + ":" + status[key].toUpperCase());
}
}
}
create_status_tr(status){
var tr = this.createTR();
var td = this.createTD(status);
tr.appendChild(td);
this.status_table.appendChild(tr);
}
create_nc_tr(rat,cell_info){
if (rat == 0) {
var text = "LTE:";
}
else{
var text = "NR:";
}
for (let key in cell_info) {
if (cell_info[key] != ""){
text += key + ":" + cell_info[key] + " ";
}
}
let tr_left = this.createTD(text);
let tr_right = this.create_copy_btn_td(rat,cell_info);
let tr = this.createTR();
tr.appendChild(tr_left);
tr.appendChild(tr_right);
this.neighborcell_table.appendChild(tr);
}
create_copy_btn_td(rat,cell_info){
var copy_btn = this.createBTN("<%:Copy%>",() => {
this.pci_input.value = cell_info.pci;
this.arfcn_input.value = cell_info.arfcn;
this.band_input.value = cell_info.band;
this.rat_input.selectedIndex = rat;
this.nr_options()
});
var td = document.createElement('td');
td.className = "td cbi-section-table-cell left";
td.setAttribute("width","10%");
td.appendChild(copy_btn);
return td;
}
cb_get(){
this.render_neighborcell();
this.render_status();
}
}
class IMEI extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:Set IMEI%>");
this.config_name = "imei";
this.get_action = "get_imei";
this.set_action = "set_imei";
this.render();
}
render(){
this.imei_input = this.createInput("imei",this.config);
this.imei_btn = this.createBTN("<%:Submit%>",() => {
this.set_config(this.imei_input.value);
});
this.fieldset.appendChild(this.imei_input);
this.fieldset.appendChild(this.imei_btn);
}
cb_get(){
this.imei_input.value = this.config;
}
cb_set(){
this.imei_input.value = this.config;
}
update(){
this.get_config();
}
}
class RebootModem extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:Reboot Modem%>");
this.config_name = "reboot_caps";
this.get_action = "get_reboot_caps";
this.set_action = "do_reboot";
this.render();
}
cb_get(){
this.soft_reboot_btn.disabled = !this.config.soft_reboot_caps;
this.hard_reboot_btn.disabled = !this.config.hard_reboot_caps;
}
render(){
this.soft_reboot_btn = this.createBTN("<%:Soft Reboot%>",() => {
this.set_config('{"method":"soft"}');
});
this.hard_reboot_btn = this.createBTN("<%:Hard Reboot%>",() => {
this.set_config('{"method":"hard"}');
});
this.fieldset.appendChild(this.soft_reboot_btn);
this.fieldset.appendChild(document.createElement("br"));
this.fieldset.appendChild(this.hard_reboot_btn);
}
update(){
this.get_config();
}
}
class AtDebug extends ModemConfig {
constructor(cfg_id){
super(cfg_id,"<%:AT Debug%>");
this.config_name = "at_cfg";
this.get_action = "get_at_cfg";
this.set_action = "send_at";
this.at_port=null;
this.last_choice_cmd = null;
this.render();
}
render(){
this.textarea = document.createElement('textarea');
this.textarea.style.width = "100%";
this.textarea.style.height = "600px";
this.textarea.readOnly = true;
this.at_btn = this.createBTN("<%:Send%>",() => {
let payload = {
"at": this.at_input,
"port": this.at_port
}
this.set_config(JSON.stringify(payload));
//append input to textarea
this.textarea.value += this.at_input + " >> " + this.at_port + "\n";
});
this.clear_btn = this.createBTN("<%:Clear%>",() => {
this.textarea.value = "";
});
this.clear_port_btn = this.createBTN("<%:Clear AT Port%>",() => {
this.at_port_selector.value = "";
this.at_port_selector.dispatchEvent(new Event('change'));
});
this.clear_cmd_btn = this.createBTN("<%:Clear AT Command%>",() => {
this.cmd_prompt_selector.value = "";
this.cmd_prompt_selector.dispatchEvent(new Event('change'));
});
var { input , selector } = this.createDroplistWithInput("at_port_selector","<%:Select Port%>" );
selector.addEventListener("change",(event) => {
this.at_port = event.target.value;
});
this.at_port_selector = selector;
this.at_port_input = input;
var { input , selector } = this.createDroplistWithInput("cmd_prompt","<%:Input AT Command%>" );
selector.addEventListener('change',(event) => {
this.at_input = event.target.value;
});
this.cmd_prompt = input;
this.cmd_prompt_selector = selector;
var table = this.createTable();
this.fieldset.appendChild(table);
var tr,td_l,td_r;
tr = this.createTR();
td_l = this.createTD("<%:AT Port%>:");
td_r = this.createTD();
td_r.style.width = "70%";
td_r.appendChild(this.at_port_selector);
td_r.appendChild(this.at_port_selector.descr);
td_r.appendChild(this.at_port_input);
td_r.appendChild(this.at_port_input.descr);
tr.appendChild(td_l);
tr.appendChild(td_r);
table.appendChild(tr);
tr = this.createTR();
td_l = this.createTD("<%:AT Command%>:");
td_r = this.createTD();
td_r.appendChild(this.cmd_prompt_selector);
td_r.appendChild(this.cmd_prompt);
td_r.appendChild(this.cmd_prompt.descr);
td_r.appendChild(this.cmd_prompt_selector.descr);
tr.appendChild(td_l);
tr.appendChild(td_r);
table.appendChild(tr);
tr = this.createTR();
td_l = this.createTD();
let span = document.createElement('span');
span.classList.add("flex_container");
td_l.setAttribute("colspan",2);
span.appendChild(this.at_btn);
span.appendChild(this.clear_port_btn);
span.appendChild(this.clear_cmd_btn);
td_l.appendChild(span);
tr.appendChild(td_l);
table.appendChild(tr);
this.fieldset.appendChild(table);
this.fieldset.appendChild(this.textarea);
this.fieldset.appendChild(this.clear_btn);
}
cb_get(){
//clear ports
while (this.at_port_selector.firstChild) {
this.at_port_selector.removeChild(this.at_port_selector.firstChild);
}
//clear cmds
while (this.cmd_prompt_selector.firstChild) {
this.cmd_prompt_selector.removeChild(this.cmd_prompt_selector.firstChild);
}
//empty option
var empty_option1=document.createElement("option");
empty_option1.value = "";
empty_option1.innerHTML = "<%:-- custom ---%>";
var empty_option2=document.createElement("option");
empty_option2.value = "";
empty_option2.innerHTML = "<%:-- custom ---%>";
this.cmd_prompt_selector.appendChild(empty_option1);
this.at_port_selector.appendChild(empty_option2);
var ports=this.config.ports;
var other_ttys=this.config.other_ttys;
var valid_ports=this.config.valid_ports;
var using_port=this.config.using_port;
var cmds = this.config.cmds;
//append empty option to at_port_selector
for (let port of other_ttys) {
let select;
let displayport = port;
if (ports.includes(port) == false) {
displayport += "<%:(Not belong to this modem)%>";
}
else{
if (valid_ports.includes(port) == false) {
displayport += "<%:(invalid)%>";
}
else{
displayport += "<%:(valid)%>";
}
if (port == using_port) {
displayport += "<%:(using)%>";
select = true;
}
}
var option = document.createElement('option');
option.value = port;
option.innerHTML = displayport;
if (select) {
option.selected = true;
this.at_port = port;
}
this.at_port_selector.appendChild(option);
}
for (let cmd of cmds) {
var option = document.createElement('option');
option.value = cmd.value;
option.innerHTML = cmd.name;
this.cmd_prompt_selector.appendChild(option);
}
this.cmd_prompt_selector.dispatchEvent(new Event('change'));
this.at_port_selector.dispatchEvent(new Event('change'));
}
cb_update(){
//clear 2 input
this.at_port_selector.value = "";
this.cmd_prompt.value = "";
this.get_config();
}
cb_set(){
//append response to textarea
this.textarea.value += this.config.res + "<<EOF\n";
}
}
class Select_Modem {
constructor(){
this.modem_selector = document.getElementById('modem_selector');
this.cfg_id = null;
this.modem_cfg_list = [];
this.create_modem_cfg_selector();
this.update_modem_cfg_list();
}
create_modem_cfg_selector() {
var selector = document.createElement('select');
selector.addEventListener('change', (event) => {
this.cfg_id = event.target.value;
this.update_cfg_id(this.cfg_id);
});
this.modem_selector.appendChild(selector);
this.selector = selector;
}
update_modem_cfg_list() {
XHR.poll(5, '<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_modem_cfg")%>', {}, (x, data) => {
var new_cfg_list = [];
var cfgs = data.cfgs;
for (let i = 0; i < cfgs.length; i++) {
var cfg = cfgs[i];
var name = cfg.name;
var value = cfg.cfg;
new_cfg_list.push({ "value": value, "name": name });
}
if (JSON.stringify(new_cfg_list) != JSON.stringify(this.modem_cfg_list)) {
this.cfg_options = new_cfg_list;
}
});
}
set cfg_options(value) {
var longger = this.modem_cfg_list.length > value.length ? this.modem_cfg_list : value;
if (longger.length == 0) {
return;
}
for (let i = 0; i < longger.length; i++) {
var option = this.selector.options[i];
if (i < value.length) {
if (i >= this.selector.options.length) {
option = document.createElement('option');
this.selector.appendChild(option);
}
option.value = value[i].value;
option.innerHTML = value[i].name;
}
else {
this.selector.removeChild(option);
}
}
this.cfg_id = this.selector.value;
this.modem_cfg_list = value;
this.update_cfg_id(this.cfg_id);
}
}
class TabMenu extends Select_Modem {
functions = {
"DialMode": {"class": DialMode, "name":"<%:Dial Mode%>"},
"RatPrefer": {"class": RatPrefer, "name":"<%:Rat Prefer%>"},
"IMEI": {"class": IMEI, "name": "<%:Set IMEI%>"},
"NeighborCell": {"class": NeighborCell, "name": "<%:Neighbor Cell%>"},
"LockBand": {"class": Lockband, "name":"<%:Lock Band%>"},
"RebootModem": {"class": RebootModem, "name":"<%:Reboot Modem%>"},
"AtDebug": {"class": AtDebug, "name":"<%:AT Debug%>"}
}
constructor(){
super();
this.cbi_map = document.querySelector('.cbi-map');
this.class_map = {};
this.datatabs = [];
this.disabled_features = [];
this.hotplug_elements = [];
//this.create_tabmenu();
}
update_cfg_id(cfg_id){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>', { "cfg": cfg_id , "action" : "get_disabled_features"}, (x, data) => {
//clear class_map
this.disabled_features = data.disabled_features ? data.disabled_features : [];
//delete tabmenu
for (let element of this.hotplug_elements){
element.parentNode.removeChild(element);
}
this.class_map = {};
this.datatabs = [];
this.hotplug_elements = [];
this.create_tabmenu();
for (let key in this.class_map) {
this.class_map[key].cfg_id = cfg_id;
this.class_map[key].get_config();
}
//check if all datatab not selected
for (let tab of this.datatabs) {
if (tab.className == "cbi-tab") {
this.switch_tab(tab);
return;
}
}
this.switch_tab(this.datatabs[0]);
});
}
create_tabmenu(){
//add support function to tabmenu
var tabmenu = document.createElement('ul');
this.hotplug_elements.push(tabmenu);
tabmenu.className = "cbi-tabmenu";
for (let key in this.functions) {
if (this.disabled_features.includes(key)) {
continue;
}
var li = document.createElement('li');
li.className = "cbi-tab-disabled";
li.innerHTML = this.functions[key].name;
li.setAttribute("data-tab", key);
li.addEventListener('click', (event) => {
this.switch_tab(event.target)
});
tabmenu.appendChild(li);
this.datatabs.push(li);
}
this.cbi_map.appendChild(tabmenu);
}
switch_tab(target){
target.className = "cbi-tab";
target.style.display = "";
var datatab = target.getAttribute("data-tab");
for (let i = 0; i < this.datatabs.length; i++) {
if (this.datatabs[i] != target) {
this.datatabs[i].className = "cbi-tab-disabled";
}
}
if (this.class_map[datatab] == undefined) {
this.class_map[datatab] = new this.functions[datatab].class(this.cfg_id);
this.hotplug_elements.push(this.class_map[datatab].fieldset);
}
for (let key in this.class_map) {
this.class_map[key].hide();
}
this.class_map[datatab].show();
}
}
window.onload = function(){
var tabmenu = new TabMenu();
}
</script>
<style>
.cbi-tabmenu li {
padding: 0.5rem;
}
.band-container {
display: flex;
margin-top: 1rem;
align-items: center;
min-width: 15%;
}
.flex_container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
</style>
<div class="cbi-map">
<fieldset class="cbi-section">
<table class="table">
<tbody>
<tr class="tr">
<td class="td" width="33%"><%:Modem Name%></td>
<td class="td" id="modem_selector">
</td>
</tr>
</tbody>
</table>
</fieldset>
</div>
<%+footer%>
|
281677160/openwrt-package | 9,022 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/view/qmodem/dial_overview.htm | <script type="text/javascript">//<![CDATA[
class LuciField {
constructor(classList,title){
this.classList=classList;
this.newLuciField();
this.title=title;
}
newLuciField(){
var field=document.createElement("fieldset");
for (var class_name of this.classList)
{
field.classList.add(class_name);
}
var h3title = document.createElement("h3")
field.appendChild(h3title);
this.h3title=h3title;
this.field=field;
}
set title(t){
this.h3title.innerHTML=t;
if (t != "")
{
this.h3title.style.display="";
}
else
{
this.h3title.style.display="none";
}
}
}
class LuciBtn {
constructor(classList,value,callback){
var btn=document.createElement("input");
var base_classList = ["cbi-button","btn"];
this.classList=base_classList.concat(classList);
for (var class_name of this.classList)
{
btn.classList.add(class_name);
}
btn.setAttribute('type','button');
btn.setAttribute('value',value);
btn.addEventListener('click',callback);
this.btn=btn;
}
}
class ModemState
{
constructor(){
this.modem_state_div = document.createElement('div');
this.modem_state_div.classList.add("modem_status_box");
this.connect_state = -1;
}
update(modem_datas){
var entrys = [];
this.connect_state = -1;
for (var entry of modem_datas)
{
//handle special entry
if (entry.key=="connect_status")
{
var state = '';
var css = '';
switch (entry.value)
{
case 'Yes':
entry.value = '<%:Connected%>';
this.connect_state = 1;
break;
case 'No':
entry.value = '<%:Disconnected%>';
this.connect_state = 0;
break;
default:
entry.value = '<%:Unknown%>';
this.connect_state = -1;
break;
}
}
entrys.push(entry);
}
this.render(entrys);
}
render(entrys){
this.modem_state_div.innerHTML = "";
switch (this.connect_state)
{
case 1:
this.modem_state_div.classList.add("alert-message","success");
break;
case 0:
this.modem_state_div.classList.add("alert-message","danger");
break;
default:
this.modem_state_div.classList.add("alert-message","warning");
break;
}
for (var entry of entrys)
{
var key,value,full_name;
key=entry.key;
value=entry.value;
full_name=entry.full_name;
if (key == "connect_status" || key == "name" )
{
var div = document.createElement('div');
var strong = document.createElement('strong');
strong.innerHTML = value.toUpperCase();
div.appendChild(strong);
}
else
{
var div = document.createElement('div');
var strong = document.createElement('strong');
var span = document.createElement('span');
strong.innerHTML = full_name + ": ";
span.innerHTML = value;
div.appendChild(strong);
div.appendChild(span);
}
this.modem_state_div.appendChild(div);
}
}
}
class ModemLog {
constructor(section_name){
this.modem_log_div = document.createElement('div');
this.modem_log_div.style.display = "none";
this.modem_logmsg_textarea = document.createElement('textarea');
this.modem_logmsg_textarea.setAttribute('readonly','readonly');
this.modem_logmsg_textarea.setAttribute('rows','20');
this.modem_logmsg_textarea.setAttribute('maxlength','160');
var download_btn = new LuciBtn(["cbi-button-link"],"<%:Download%>",() => {
this.download();
}).btn;
var clear_btn = new LuciBtn(["cbi-button-reset"],"<%:Clear%>",() => {
this.clear();
}).btn;
var btns_div = document.createElement('div');
btns_div.appendChild(download_btn);
btns_div.appendChild(clear_btn);
this.btns_div = btns_div;
this.modem_log_div.appendChild(this.modem_logmsg_textarea);
this.modem_log_div.appendChild(this.btns_div);
this.section_name = section_name;
this.scroll_top = -1;
}
download(){
var file_name = this.section_name+"_dial_log.txt";
var file_content = this.log_msg;
var blob = new Blob([file_content], {type: "text/plain;charset=utf-8"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = file_name;
a.click();
}
clear(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>', {"action":"clear_dial_log","cfg":this.section_name},
function(x, data)
{
var state = data.result.state;
if (state == "1")
{
this.log_msg = "";
this.render();
}
}
);
}
update(log_msg){
this.scroll_top = this.modem_logmsg_textarea.scrollTop;
this.log_msg = log_msg;
this.render();
this.modem_logmsg_textarea.scrollTop = this.scroll_top;
}
render(){
this.modem_logmsg_textarea.innerHTML=this.log_msg;
}
}
class ModemDialOverview {
constructor(){
this.modem_state_field=new LuciField(["cbi-section","cbi-section-modem-state"],"<%:Modem Status%>").field;
this.modem_log_tab_data_field = document.createElement('div');
this.modem_log_tab_menu_field = document.createElement('ul');
this.modem_log_tab_menu_field.classList.add("tabs")
this.modem_log_field=new LuciField(["cbi-section","cbi-section-modem-log"],"<%:Modem Log%>").field;
this.modems_state = [];
this.modems_logs = {};
this.modems_logs_menu = {};
this.activated_section = "";
this.modem_log_field.appendChild(this.modem_log_tab_menu_field);
this.modem_log_field.appendChild(this.modem_log_tab_data_field);
this.maincontent = document.getElementById("maincontent");
this.maincontent.appendChild(this.modem_state_field);
this.maincontent.appendChild(this.modem_log_field);
this.poll();
}
activate()
{
for (var section_name in this.modems_logs)
{
if (section_name == this.activated_section)
{
this.modems_logs[section_name].modem_log_div.style.display = "";
this.modems_logs_menu[section_name].classList.add("active");
}
else
{
this.modems_logs[section_name].modem_log_div.style.display = "none";
this.modems_logs_menu[section_name].classList.remove("active");
}
}
}
poll()
{
XHR.poll(5,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modems_dial_overview")%>',{},
(x,data)=>{
this.update_modems_state(data.modems);
this.update_modems_log(data.logs);
});
}
update_modems_state(modems){
for (var i in modems)
{
var modem_info = modems[i];
if (this.modems_state[i]==null)
{
this.modems_state[i]=new ModemState();
this.modem_state_field.appendChild(this.modems_state[i].modem_state_div);
}
this.modems_state[i].update(modem_info);
}
if (this.modems_state.length> modems.length)
{
for (var i = modems.length; i < this.modems_state.length; i++)
{
this.modem_state_field.removeChild(this.modems_state[i].modem_state_div);
delete this.modems_state[i];
}
}
}
update_modems_log(logs){
var menus = [];
for (var log of logs)
{
var section_name,modem_name,log_msg;
section_name = log.section_name;
modem_name = log.name;
log_msg = log.log_msg;
menus.push(section_name);
if ( this.modems_logs[section_name]==null )
{
this.modems_logs[section_name]=new ModemLog(section_name);
let a = document.createElement('a');
let li = document.createElement('li');
let s = section_name;
li.appendChild(a);
a.href = "#";
a.innerHTML = modem_name.toUpperCase();
a.addEventListener('click',() => {
this.activate_tab = s;
});
this.modems_logs_menu[section_name]=li;
this.modem_log_tab_menu_field.appendChild(li);
this.modem_log_tab_data_field.appendChild(this.modems_logs[section_name].modem_log_div);
}
this.modems_logs[section_name].update(log_msg);
}
this.update_modems_log_menu();
//remove the log that not exist
for (var section_name in this.modems_logs)
{
if (menus.indexOf(section_name)==-1)
{
this.modem_log_tab_menu_field.removeChild(this.modems_logs_menu[section_name]);
this.modem_log_tab_data_field.removeChild(this.modems_logs[section_name].modem_log_div);
delete this.modems_logs[section_name];
delete this.modems_logs_menu[section_name];
}
}
}
update_modems_log_menu(){
if (this.activated_section == "")
{
this.activate_tab = Object.keys(this.modems_logs)[0];
}
}
set activate_tab(section_name){
this.activated_section = section_name;
this.activate();
}
}
window.onload = function(){
var modem_dial_overview = new ModemDialOverview();
}
</script>
<style type="text/css">
/* AT命令响应 */
textarea {
background:#373737;
border:none;
color:#FFF;
width: 100%;
border-top-width: 2px;
padding-top: 12px;
}
/* 加载中样式 */
#modem_status_view img {
vertical-align: middle;
}
.modem_status_box {
display: inline-block;
margin: 1rem;
padding: 1rem;
width: 16rem;
float: left;
line-height: 125%;
}
</style>
|
281677160/openwrt-package | 5,770 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/model/cbi/qmodem/modem_config.lua | local modem_cfg = require "luci.model.cbi.qmodem.modem_cfg"
-- Helper function to load slot paths
local function load_slots(path, exclude_pattern)
local slots = {}
local handle = io.popen("ls " .. path)
for line in handle:lines() do
if not exclude_pattern or not line:match(exclude_pattern) then
table.insert(slots, line)
end
end
handle:close()
return slots
end
-- Helper function to populate options dynamically from a table
local function populate_options(option, values)
for key, value in pairs(values) do
option:value(key, value)
end
end
-- Map and Section setup
m = Map("qmodem", translate("Modem Configuration"))
m.redirect = luci.dispatcher.build_url("admin", "modem", "qmodem", "settings")
s = m:section(NamedSection, arg[1], "modem-device", "")
local slot_name = arg[1]
-- Load slot paths
local usb_slot_list = load_slots("/sys/bus/usb/devices/", "usb%d+")
local pcie_slot_list = load_slots("/sys/bus/pci/devices/")
-- Fixed Device Flag
is_fixed_device = s:option(Flag, "is_fixed_device", translate("Fixed Device"))
is_fixed_device.description = translate("If the device is fixed, it will not update when the device is connected or disconnected.")
is_fixed_device.default = "0"
-- Slot Path
path = s:option(ListValue, "slot", translate("Slot Path"))
for _, v in ipairs(usb_slot_list) do
local uci_name = v:gsub("[%.:%-]", "_")
if uci_name == slot_name then
path:value("/sys/bus/usb/devices/" .. v .. "/", v .. "[usb]")
end
end
for _, v in ipairs(pcie_slot_list) do
local uci_name = v:gsub("[%.:%-]", "_")
if uci_name == slot_name then
path:value("/sys/bus/pci/devices/" .. v .. "/", v .. "[pcie]")
end
end
-- Interface Type
data_interface = s:option(ListValue, "data_interface", translate("Interface Type"))
data_interface:value("usb", translate("USB"))
data_interface:value("pcie", translate("PCIe"))
-- Alias
alias = s:option(Value, "alias", translate("Alias"))
alias.description = translate("Alias for the modem, used for identification.")
alias.rmempty = true
alias.default = ""
alias.placeholder = translate("Enter alias name")
-- Modem Model
name = s:option(Value, "name", translate("Modem Model"))
name.cfgvalue = function(t, n)
return Value.cfgvalue(t, n) or "-"
end
-- Soft Reboot
soft_reboot = s:option(Flag, "soft_reboot", translate("Soft Reboot"))
soft_reboot.default = "0"
-- PDP Context Index
pdp_index = s:option(Value, "pdp_index", translate("PDP Context Index"))
pdp_index.default = "1"
-- Manufacturer (Loaded from modem_cfg.lua)
manufacturer = s:option(ListValue, "manufacturer", translate("Manufacturer"))
populate_options(manufacturer, modem_cfg.manufacturers)
-- Platform (Loaded from modem_cfg.lua)
platform = s:option(ListValue, "platform", translate("Platform"))
populate_options(platform, modem_cfg.platforms)
-- AT Port
at_port = s:option(Value, "at_port", translate("AT Port"))
at_port.description = translate("AT command port for modem communication.")
-- Supported Modes (Loaded from modem_cfg.lua)
modes = s:option(DynamicList, "modes", translate("Supported Modes"))
populate_options(modes, modem_cfg.modes)
-- Enable Flag
enabled = s:option(Flag, "enabled", translate("Enable"))
enabled.default = "1"
disabled_features = s:option(DynamicList, "disabled_features", translate("Disabled Features"))
disabled_features.description = translate("Select features to disable for this modem.")
populate_options(disabled_features, modem_cfg.disabled_features)
-- Band Configurations
local band_options = {
{ name = "wcdma_band", label = "WCDMA Band", placeholder = "Enter WCDMA band" },
{ name = "lte_band", label = "LTE Band", placeholder = "Enter LTE band" },
{ name = "nsa_band", label = "NSA Band", placeholder = "Enter NSA band" },
{ name = "sa_band", label = "SA Band", placeholder = "Enter SA band" },
}
for _, band in ipairs(band_options) do
local option = s:option(Value, band.name, translate(band.label))
option.description = translate(band.label .. " configuration, e.g., 1/2/3")
option.placeholder = translate(band.placeholder)
option.cfgvalue = function(t, n)
return Value.cfgvalue(t, n) or "null"
end
end
pre_dial_delay = s:option(Value, "pre_dial_delay", translate("Pre Dial Delay")..translate(" (beta)"))
pre_dial_delay.description = translate("Delay of executing AT command before dialing, in seconds."..translate("(still in beta))"))
pre_dial_delay.placeholder = translate("Enter delay in seconds")
pre_dial_delay.default = "0"
pre_dial_delay.datatype = "uinteger"
pre_dial_delay.rmempty = true
pre_add_delay = s:option(Value, "post_init_delay", translate("Post Init Delay")..translate(" (beta)"))
pre_add_delay.description = translate("Delay of executing AT command after modem initialization, in seconds."..translate("(still in beta))"))
pre_add_delay.placeholder = translate("Enter delay in seconds")
pre_add_delay.default = "0"
pre_add_delay.datatype = "uinteger"
pre_add_delay.rmempty = true
pre_add_at_cmds = s:option(DynamicList, "post_init_at_cmds", translate("Post Init AT Commands")..translate(" (beta)"))
pre_add_at_cmds.description = translate("AT commands to execute after modem initialization."..translate("(still in beta))"))
pre_add_at_cmds.placeholder = translate("Enter AT commands")
pre_add_at_cmds.datatype = "string"
pre_add_at_cmds.rmempty = true
pre_dial_at_cmds = s:option(DynamicList, "pre_dial_at_cmds", translate("Pre Dial AT Commands")..translate(" (beta)"))
pre_dial_at_cmds.description = translate("AT commands to execute before dialing."..translate("(still in beta))"))
pre_dial_at_cmds.placeholder = translate("Enter AT commands")
pre_dial_at_cmds.datatype = "string"
pre_dial_at_cmds.rmempty = true
return m
|
281677160/openwrt-package | 2,826 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/model/cbi/qmodem/dial_overview.lua | local d = require "luci.dispatcher"
local sys = require "luci.sys"
m = Map("qmodem")
m.title = translate("Dial Overview")
--全局配置
s = m:section(NamedSection, "main", "main", translate("Global Config"))
s.anonymous = true
s.addremove = false
o = s:option(Flag, "enable_dial", translate("Enable Dial")..translate("(Global)"))
o.rmempty = false
o = s:option(Button, "reload_dial", translate("Restart Dial Service"))
o.inputstyle = "apply"
o.write = function()
sys.call("/etc/init.d/qmodem_network restart > /dev/null 2>&1")
luci.http.redirect(d.build_url("admin", "modem", "qmodem", "dial_overview"))
end
s = m:section(TypedSection, "modem-device", translate("Config List"))
s.addremove = ture
s.template = "cbi/tblsection"
s.extedit = d.build_url("admin", "modem", "qmodem", "dial_config", "%s")
o = s:option(Flag, "enable_dial", translate("Enable Dial"))
o.width = "5%"
o.rmempty = false
restart_btn = s:option(Button, "_redial", translate("ReDial"))
restart_btn.inputstyle = "remove"
function restart_btn.write(self, section)
sys.call("/etc/init.d/qmodem_network redial "..section.." > /dev/null 2>&1")
luci.http.redirect(d.build_url("admin", "modem", "qmodem", "dial_overview"))
end
o = s:option(DummyValue, "name", translate("Modem Model"))
o.cfgvalue = function(t, n)
local name = (Value.cfgvalue(t, n) or "")
return name:upper()
end
o = s:option(DummyValue, "alias", translate("Modem Alias"))
o.cfgvalue = function(t, n)
local alias = (Value.cfgvalue(t, n) or "-")
return alias
end
o = s:option(DummyValue, "state", translate("Modem Status"))
o.cfgvalue = function(t, n)
if Value.cfgvalue(t,n) == nil then
return translate("Unknown")
end
return translate(Value.cfgvalue(t, n):upper() or "-")
end
o = s:option(DummyValue, "pdp_type", translate("PDP Type"))
o.cfgvalue = function(t, n)
local pdp_type = (Value.cfgvalue(t, n) or "")
if pdp_type == "ipv4v6" then
pdp_type = translate("IPv4/IPv6")
else
pdp_type = pdp_type:gsub("_","/"):upper():gsub("V","v")
end
return pdp_type
end
o = s:option(DummyValue, "apn", translate("APN"))
o.cfgvalue = function(t, n)
local apn = (Value.cfgvalue(t, n) or "")
if apn == "" then
apn = translate("Auto Choose")
end
return apn
end
remove_btn = s:option(Button, "_remove", translate("Remove Modem"))
remove_btn.inputstyle = "remove"
function remove_btn.write(self, section)
local shell
shell="/usr/share/qmodem/modem_scan.sh remove "..section
luci.sys.call(shell)
--refresh the page
luci.http.redirect(d.build_url("admin", "modem", "qmodem", "dial_overview"))
end
-- 添加模块拨号日志
m:append(Template("qmodem/dial_overview"))
m.on_after_commit = function(self)
sys.call("/etc/init.d/qmodem_network reload > /dev/null 2>&1")
end
return m
|
281677160/openwrt-package | 9,048 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/model/cbi/qmodem/dial_config.lua | local dispatcher = require "luci.dispatcher"
local uci = require "luci.model.uci".cursor()
local http = require "luci.http"
m = Map("qmodem", translate("Modem Configuration"))
m.redirect = dispatcher.build_url("admin", "modem", "qmodem","dial_overview")
s = m:section(NamedSection, arg[1], "modem-device", "")
s.addremove = false
s.dynamic = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
--------general--------
-- 是否启用
enable = s:taboption("general", Flag, "enable_dial", translate("Enable Dial"))
enable.default = "0"
enable.rmempty = false
-- 别名
alias = s:taboption("general", Value, "alias", translate("Modem Alias"))
alias.rmempty = true
-- AT串口
at_port = s:taboption("general",Value, "at_port", translate("AT Port"))
sms_at_port = s:taboption("general",Value, "sms_at_port", translate("SMS AT Port"))
sms_at_port.rmempty = true
override_at_port = s:taboption("general", Value, "override_at_port", translate("Override AT Port"))
override_at_port.rmempty = true
valid_at_ports = uci:get("qmodem",arg[1],"valid_at_ports")
avalible_ports = uci:get("qmodem",arg[1],"ports")
dns_list = s:taboption("general", DynamicList, "dns_list", translate("DNS"))
dns_list.description = translate("If the DNS server is not set, it will use the DNS server leased by the operator.")
if valid_at_ports == nil then
valid_at_ports = {}
end
if avalible_ports == nil then
avalible_ports = {}
end
for i1,v1 in ipairs(avalible_ports) do
valid=false
for i2,v2 in ipairs(valid_at_ports) do
if v1 == v2 then
valid=true
end
end
if not valid then
msg = v1 .. translate("(Not PASS)")
else
msg = v1 .. translate("(PASSED)")
end
at_port:value(v1,msg)
sms_at_port:value(v1,msg)
override_at_port:value(v1,msg)
end
use_ubus = s:taboption("general",Flag, "use_ubus",translate("Use Ubus"))
use_ubus.default = "0"
at_port.placeholder = translate("Not null")
at_port.rmempty = false
force_set_apn = s:taboption("advanced", Flag, "force_set_apn", translate("Force Set APN"))
force_set_apn.description = translate("If enabled, the APN will be set even if it matches the current configuration.(only works with tom modified version of quectel-cm)")
force_set_apn.default = "0"
bridge_mode = s:taboption("advanced", Flag, "en_bridge", translate("Bridge Mode"))
bridge_mode.description = translate("Caution: Only avalible for quectel sdx 5G Modem.")
bridge_mode.default = "0"
do_not_add_dns = s:taboption("advanced", Flag, "do_not_add_dns", translate("Do Not modify resolv.conf"))
do_not_add_dns.description = translate("quectel-CM will append the DNS server to the resolv.conf file by default.if you do not want to modify the resolv.conf file, please check this option.")
do_not_add_dns.default = "0"
ra_master = s:taboption("advanced", Flag, "ra_master", translate("RA Master"))
ra_master.description = translate("Caution: Enabling this option will make it the IPV6 RA Master, and only one interface can be configured as such.")
ra_master.default = "0"
extend_prefix = s:taboption("advanced", Flag, "extend_prefix", translate("Extend Prefix"))
extend_prefix.description = translate("Once checking, the prefix will be apply to lan zone")
extend_prefix.default = "0"
-- 软重启
soft_reboot = s:taboption("advanced", Flag, "soft_reboot", translate("Soft Reboot"))
soft_reboot.description = translate("enable modem soft reboot")
soft_reboot.default = "0"
-- pdp_index
pdp_index = s:taboption("advanced", Value, "pdp_index", translate("PDP Context Index"))
-- 网络类型
pdp_type= s:taboption("advanced", ListValue, "pdp_type", translate("PDP Type"))
pdp_type.default = "ipv4v6"
pdp_type.rmempty = false
pdp_type:value("ip", translate("IPv4"))
pdp_type:value("ipv6", translate("IPv6"))
pdp_type:value("ipv4v6", translate("IPv4/IPv6"))
-- 接入点
apn = s:taboption("advanced", Value, "apn", translate("APN"))
apn.default = ""
apn.rmempty = true
apn:value("", translate("Auto Choose"))
apn:value("cmnet", translate("China Mobile (CN)"))
apn:value("3gnet", translate("China Unicom (CN)"))
apn:value("ctnet", translate("China Telecom (CN)"))
apn:value("cbnet", translate("China Broadcast (CN)"))
apn:value("5gscuiot", translate("Skytone (CN)"))
-- Switzerland (CH)
apn:value("gprs.swisscom.ch", translate("Swisscom (CH)"))
apn:value("internet", "Salt (CH), Sunrise (CH), O2 (DE), 1&1 (DE)")
-- Germany (DE)
apn:value("web.vodafone.de", translate("Vodafone (DE)"))
apn:value("internet.telekom", translate("Telekom (DE)"))
apn:value("internet.eplus.de", translate("E-Plus (DE)"))
-- Austria (AT)
apn:value("A1.net", translate("A1 (AT)"))
apn:value("drei.at", translate("Drei (AT)"))
apn:value("internet.t-mobile.at", translate("Magenta (AT)"))
-- Philippines (PH)
apn:value("http.globe.com.ph", translate("Globe Prepaid (PH)"))
apn:value("internet.globe.com.ph", translate("Globe Postpaid (PH)"))
apn:value("internet", translate("Smart Communications (PH)"))
apn:value("internet.dito.ph", translate("Dito Telecomunity (PH)"))
-- Malaysia (MY)
apn:value("celcom3g", translate("Celcom (MY)"))
apn:value("diginet", translate("DiGi (MY)"))
apn:value("unet", translate("Maxis | Hotlink (MY)"))
apn:value("hos", translate("Maxis UT (MY)"))
apn:value("yes4g", translate("YES (MY)"))
apn:value("my3g", translate("UMobile (MY)"))
apn:value("unifi", translate("Unifi (MY)"))
-- Russia (RU)
apn:value("internet.beeline.ru", translate("Beeline (RU)"))
apn:value("internet.mts.ru", translate("MTS (RU)"))
apn:value("internet", translate("Megafon (RU)"))
apn:value("internet.tele2.ru", translate("Tele2 (RU)"))
apn:value("internet.yota", translate("Yota (RU)"))
apn:value("m.tinkoff", translate("T-mobile (RU)"))
apn:value("internet.rtk.ru", translate("Rostelecom (RU)"))
apn:value("internet.sberbank-tele.com", translate("Sber Mobile (RU)"))
auth = s:taboption("advanced", ListValue, "auth", translate("Authentication Type"))
auth.default = "none"
auth.rmempty = false
auth:value("none", translate("NONE"))
auth:value("MsChapV2", translate("MsChapV2"))
auth:value("pap", "PAP")
auth:value("chap", "CHAP")
username = s:taboption("advanced", Value, "username", translate("PAP/CHAP Username"))
username.rmempty = true
username:depends("auth", "both")
username:depends("auth", "pap")
username:depends("auth", "chap")
password = s:taboption("advanced", Value, "password", translate("PAP/CHAP Password"))
password.rmempty = true
password.password = true
password:depends("auth", "both")
password:depends("auth", "pap")
password:depends("auth", "chap")
pincode = s:taboption("advanced", Value, "pincode", translate("PIN Code"))
pincode.description = translate("If the PIN code is not set, leave it blank.")
--卡2
apn = s:taboption("advanced", Value, "apn2", translate("APN").." 2")
apn.description = translate("If slot 2 config is not set,will use slot 1 config.")
apn.default = ""
apn.rmempty = true
apn:value("", translate("Auto Choose"))
apn:value("cmnet", translate("China Mobile (CN)"))
apn:value("3gnet", translate("China Unicom (CN)"))
apn:value("ctnet", translate("China Telecom (CN)"))
apn:value("cbnet", translate("China Broadcast (CN)"))
apn:value("5gscuiot", translate("Skytone (CN)"))
-- Switzerland (CH)
apn:value("gprs.swisscom.ch", translate("Swisscom (CH)"))
apn:value("internet", "Salt (CH), Sunrise (CH), O2 (DE), 1&1 (DE)")
-- Germany (DE)
apn:value("web.vodafone.de", translate("Vodafone (DE)"))
apn:value("internet.telekom", translate("Telekom (DE)"))
apn:value("internet.eplus.de", translate("E-Plus (DE)"))
-- Austria (AT)
apn:value("A1.net", translate("A1 (AT)"))
apn:value("drei.at", translate("Drei (AT)"))
apn:value("internet.t-mobile.at", translate("Magenta (AT)"))
-- Philippines (PH)
apn:value("http.globe.com.ph", translate("Globe Prepaid (PH)"))
apn:value("internet.globe.com.ph", translate("Globe Postpaid (PH)"))
apn:value("internet", translate("Smart Communications (PH)"))
apn:value("internet.dito.ph", translate("Dito Telecomunity (PH)"))
-- Malaysia (MY)
apn:value("celcom3g", translate("Celcom (MY)"))
apn:value("diginet", translate("DiGi (MY)"))
apn:value("unet", translate("Maxis | Hotlink (MY)"))
apn:value("hos", translate("Maxis UT (MY)"))
apn:value("yes4g", translate("YES (MY)"))
apn:value("my3g", translate("UMobile (MY)"))
apn:value("unifi", translate("Unifi (MY)"))
-- Russia (RU)
apn:value("internet.beeline.ru", translate("Beeline (RU)"))
apn:value("internet.mts.ru", translate("MTS (RU)"))
apn:value("internet", translate("Megafon (RU)"))
apn:value("internet.tele2.ru", translate("Tele2 (RU)"))
apn:value("internet.yota", translate("Yota (RU)"))
apn:value("m.tinkoff", translate("T-mobile (RU)"))
apn:value("internet.rtk.ru", translate("Rostelecom (RU)"))
apn:value("internet.sberbank-tele.com", translate("Sber Mobile (RU)"))
metric = s:taboption("advanced", Value, "metric", translate("Metric"))
metric.description = translate("The metric value is used to determine the priority of the route. The smaller the value, the higher the priority. Cannot duplicate.")
metric.default = "10"
return m
|
28softwares/rest-nodejs-starter | 11,517 | src/routes/routes.ts | /* tslint:disable */
/* eslint-disable */
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import type { TsoaRoute } from '@tsoa/runtime';
import { fetchMiddlewares, ExpressTemplateService } from '@tsoa/runtime';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { UserController } from './../controllers/user/user.controller';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { MediaController } from './../controllers/media/media.controller';
import type {
Request as ExRequest,
Response as ExResponse,
RequestHandler,
Router,
} from 'express';
const multer = require('multer');
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
const models: TsoaRoute.Models = {
MediaType: {
dataType: 'refEnum',
enums: [
'PROFILE_IMAGE',
'PRODUCT_IMAGE',
'CAROUSEL_IMAGE',
'STORE_LOGO',
'BLOG_THUMBNAIL',
],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
UserLoginType: {
dataType: 'refEnum',
enums: ['TRADITIONAL', 'GOOOGLE'],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
UserDetail: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
user: { ref: 'User', required: true },
address: { dataType: 'string', required: true },
profileImage: { ref: 'Media', required: true },
avatar: { dataType: 'string' },
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
TokenEnum: {
dataType: 'refEnum',
enums: ['REFRESH_TOKEN'],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
User: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
fullName: { dataType: 'string', required: true },
email: { dataType: 'string', required: true },
password: { dataType: 'string', required: true },
phone: { dataType: 'string' },
isVerified: { dataType: 'boolean', required: true },
loginType: { ref: 'UserLoginType', required: true },
userDetails: { ref: 'UserDetail', required: true },
token: { ref: 'Token', required: true },
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
AdminPermission: {
dataType: 'refEnum',
enums: ['CAROUSEL', 'PRODUCT', 'USERS', 'ORDERS', 'LOGS'],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
Role: {
dataType: 'refEnum',
enums: ['ADMIN', 'USER', 'SUPER_ADMIN', 'NONE'],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
Token: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
token: { dataType: 'string', required: true },
type: { ref: 'TokenEnum', required: true },
user: { ref: 'User', required: true },
admin: { ref: 'Admin', required: true },
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
LogAction: {
dataType: 'refEnum',
enums: [
'ADD_CAROUSEL',
'UPDATE_CAROUSEL',
'DELETE_CAROUSEL',
'ADD_PRODUCT',
'UPDATE_PRODUCT',
'DELETE_PRODUCT',
'ADD_CATEGORY',
'UPDATE_CATEGORY',
'DELETE_CATEGORY',
],
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
Admin: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
name: { dataType: 'string', required: true },
email: { dataType: 'string', required: true },
password: { dataType: 'string', required: true },
permissions: {
dataType: 'array',
array: { dataType: 'refEnum', ref: 'AdminPermission' },
required: true,
},
phoneNumber: { dataType: 'string', required: true },
isActive: { dataType: 'boolean', required: true },
role: { ref: 'Role', required: true },
token: { ref: 'Token', required: true },
logs: {
dataType: 'array',
array: { dataType: 'refObject', ref: 'Log' },
required: true,
},
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
Log: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
action: { ref: 'LogAction', required: true },
actionBy: { ref: 'Admin', required: true },
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
Media: {
dataType: 'refObject',
properties: {
id: { dataType: 'string', required: true },
createdAt: { dataType: 'datetime', required: true },
deletedAt: { dataType: 'datetime', required: true },
mimeType: { dataType: 'string', required: true },
name: { dataType: 'string', required: true },
mediaType: { ref: 'MediaType', required: true },
path: {
dataType: 'union',
subSchemas: [{ dataType: 'string' }, { dataType: 'undefined' }],
required: true,
},
isThumbnail: { dataType: 'boolean', required: true },
userDetail: { ref: 'UserDetail', required: true },
},
additionalProperties: false,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
};
const templateService = new ExpressTemplateService(models, {
noImplicitAdditionalProperties: 'throw-on-extras',
bodyCoercion: true,
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
export function RegisterRoutes(
app: Router,
opts?: { multer?: ReturnType<typeof multer> },
) {
// ###########################################################################################################
// NOTE: If you do not see routes for all of your controllers in this file, then you might not have informed tsoa of where to look
// Please look into the "controllerPathGlobs" config option described in the readme: https://github.com/lukeautry/tsoa
// ###########################################################################################################
const upload = opts?.multer || multer({ limits: { fileSize: 8388608 } });
app.post(
'/user',
...fetchMiddlewares<RequestHandler>(UserController),
...fetchMiddlewares<RequestHandler>(UserController.prototype.registerUser),
async function UserController_registerUser(
request: ExRequest,
response: ExResponse,
next: any,
) {
const args: Record<string, TsoaRoute.ParameterSchema> = {};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = templateService.getValidatedArgs({
args,
request,
response,
});
const controller = new UserController();
await templateService.apiHandler({
methodName: 'registerUser',
controller,
response,
next,
validatedArgs,
successStatus: undefined,
});
} catch (err) {
return next(err);
}
},
);
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.post(
'/media',
upload.fields([
{
name: 'file',
maxCount: 1,
},
]),
...fetchMiddlewares<RequestHandler>(MediaController),
...fetchMiddlewares<RequestHandler>(MediaController.prototype.upload),
async function MediaController_upload(
request: ExRequest,
response: ExResponse,
next: any,
) {
const args: Record<string, TsoaRoute.ParameterSchema> = {
req: { in: 'request', name: 'req', required: true, dataType: 'object' },
file: {
in: 'formData',
name: 'file',
required: true,
dataType: 'file',
},
mediaType: {
in: 'formData',
name: 'mediaType',
required: true,
dataType: 'string',
},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = templateService.getValidatedArgs({
args,
request,
response,
});
const controller = new MediaController();
await templateService.apiHandler({
methodName: 'upload',
controller,
response,
next,
validatedArgs,
successStatus: undefined,
});
} catch (err) {
return next(err);
}
},
);
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
|
28softwares/rest-nodejs-starter | 1,150 | src/config/env.config.ts | import dotenv from 'dotenv';
import path from 'path';
export enum Environment {
DEVELOPMENT = 'DEVELOPMENT',
PRODUCTION = 'PRODUCTION',
TEST = 'TEST',
}
dotenv.config({ path: path.resolve(process.cwd(), '.env') });
class DotenvConfig {
// APP
static PORT = process.env.PORT;
static NODE_ENV = process.env.NODE_ENV;
// DB
static DB_TYPE = process.env.DB_TYPE || 'postgres';
static DB_HOST = process.env.DB_HOST;
static DB_PORT = process.env.DB_PORT || 5432;
static DB_USERNAME = process.env.DB_USERNAME;
static DB_PASSWORD = process.env.DB_PASSWORD;
static DB_NAME = process.env.DB_NAME;
// MAIL
static MAIL_HOST = process.env.MAIL_HOST;
static MAIL_USER = process.env.MAIL_USER;
static MAIL_PASSWORD = process.env.MAIL_PASSWORD;
// LOG
static LOG_LEVEL = process.env.LOG_LEVEL;
// URL
static FRONTEND_BASE_URL = process.env.FRONTEND_BASE_URL;
static BASE_URL = process.env.BASE_URL;
static MEDIA_TEMP_PATH = process.env.MEDIA_TEMP_PATH!;
// MEDIA
static MEDIA_UPLOAD_PATH = process.env.MEDIA_UPLOAD_PATH;
static TEMP_FOLDER_PATH = process.env.TEMP_FOLDER_PATH!;
}
export { DotenvConfig };
|
281677160/openwrt-package | 4,552 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/model/cbi/qmodem/settings.lua | local sys = require "luci.sys"
local d = require "luci.dispatcher"
m = Map("qmodem")
m.title = translate("QModem Setting")
this_page = d.build_url("admin", "modem", "qmodem", "settings")
s = m:section(NamedSection, "main", "main", translate("Modem Probe setting"))
at_tool = s:option(Flag, "at_tool", translate("Alternative AT Tools"))
at_tool.description = translate("If enabled, using alternative AT Tools")
start_delay = s:option(Value, "start_delay", translate("Delay Start"))
start_delay.description = translate("Units:seconds")
start_delay.datatype = "and(uinteger,min(0),max(99))"
start_delay.default = "0"
block_auto_probe = s:option(Flag, "block_auto_probe", translate("Block Auto Probe/Remove"))
block_auto_probe.description = translate("If enabled, the modem auto scan will be blocked.")
enable_pcie_scan = s:option(Flag, "enable_pcie_scan", translate("Enable PCIE Scan"))
enable_pcie_scan.description = translate("Once enabled, the PCIe ports will be scanned on every boot.")
enable_usb_scan = s:option(Flag, "enable_usb_scan",translate("Enable USB Scan"))
enable_usb_scan.description = translate("Once enabled, the USB ports will be scanned on every boot.")
try_vendor_preset_usb = s:option(Flag,"try_preset_usb",translate("Try Preset USB Port"))
try_vendor_preset_usb.description = translate("Attempt to use pre-configured USB settings from the cpe vendor.")
try_vendor_preset_pcie = s:option(Flag,"try_preset_pcie",translate("Try Preset PCIE Port"))
try_vendor_preset_pcie.description = translate("Attempt to use pre-configured PCIE settings from the cpe vendor.")
o = s:option(Button, "scan_pcie", translate("Scan PCIE Manually"))
o.inputstyle = "apply"
o.write = function()
sys.call("/usr/share/qmodem/modem_scan.sh scan 0 pcie > /dev/null 2>&1")
luci.http.redirect(this_page)
end
o = s:option(Button, "scan_usb", translate("Scan USB Manually"))
o.inputstyle = "apply"
o.write = function()
sys.call("/usr/share/qmodem/modem_scan.sh scan 0 usb > /dev/null 2>&1")
luci.http.redirect(this_page)
end
o = s:option(Button, "scan_all", translate("Scan ALL Manually"))
o.inputstyle = "apply"
o.write = function()
sys.call("/usr/share/qmodem/modem_scan.sh scan > /dev/null 2>&1")
luci.http.redirect(this_page)
end
s = m:section(TypedSection, "modem-slot", translate("Modem Slot Config List"))
s.addremove = true
s.template = "cbi/tblsection"
s.extedit = d.build_url("admin", "modem", "qmodem", "slot_config", "%s")
s.sectionhead = translate("Config Name")
slot_type = s:option(DummyValue, "type", translate("Slot Type"))
slot_type.cfgvalue = function(t, n)
local name = translate(Value.cfgvalue(t, n) or "-")
return name:upper()
end
slot_path = s:option(DummyValue, "slot", translate("Slot Path"))
slot_path.cfgvalue = function(t, n)
local path = (Value.cfgvalue(t, n) or "-")
return path
end
default_alias = s:option(DummyValue, "alias", translate("Default Alias"))
default_alias.cfgvalue = function(t, n)
local alias = (Value.cfgvalue(t, n) or "-")
return alias
end
s = m:section(TypedSection, "modem-device", translate("Modem Config List"))
s.addremove = true
s.template = "cbi/tblsection"
s.template_addremove = "qmodem/modem_config_add"
s.extedit = d.build_url("admin", "modem", "qmodem", "modem_config", "%s")
s.sectionhead = translate("Config Name")
local pcie_slots = io.popen("ls /sys/bus/pci/devices/")
local pcie_slot_list = {}
for line in pcie_slots:lines() do
table.insert(pcie_slot_list, line)
end
pcie_slots:close()
local usb_slots = io.popen("ls /sys/bus/usb/devices/")
local usb_slot_list = {}
for line in usb_slots:lines() do
if not line:match("usb%d+") then
table.insert(usb_slot_list, line)
end
end
usb_slots:close()
local avalibale_name_list = {}
for i,v in ipairs(pcie_slot_list) do
local uci_name = v:gsub("%.", "_"):gsub(":", "_"):gsub("-", "_")
avalibale_name_list[uci_name] = v.."[pcie]"
end
for i,v in ipairs(usb_slot_list) do
local uci_name = v:gsub("%.", "_"):gsub(":", "_"):gsub("-", "_")
avalibale_name_list[uci_name] = v.."[usb]"
end
s.avalibale_name = avalibale_name_list
slot_type = s:option(DummyValue, "name", translate("Modem Model"))
slot_type.cfgvalue = function(t, n)
local name = translate(Value.cfgvalue(t, n) or "-")
return name:upper()
end
path = s:option(DummyValue, "path", translate("Slot Path"))
default_alias = s:option(DummyValue, "alias", translate("Alias"))
default_alias.cfgvalue = function(t, n)
local alias = (Value.cfgvalue(t, n) or "-")
return alias
end
return m
|
28softwares/rest-nodejs-starter | 1,025 | src/middlewares/adminPermission.middleware.ts | import { Role } from '../constants/appConstant';
import { AdminPermission } from '../entities/admin/Admin.entity';
import express from 'express';
const verifyAdminPermissions = (permission: AdminPermission) => {
return async (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
if (
!req.user &&
!(req.user.role === Role.ADMIN || req.user.role === Role.SUPER_ADMIN)
) {
return res.status(403).json({
message: 'Permission not Allowed',
data: null,
});
}
//allowed all actions to SUPERADMIN
if (req.user.role === Role.SUPER_ADMIN) {
return next();
}
console.log('req.user.permissions', req.user.permissions);
if (!req.user.permissions.includes(permission)) {
return res.status(403).json({
message: `${permission} is not allowed to this admin, Contact your superadmin for permission`,
data: null,
});
}
return next();
};
};
export default verifyAdminPermissions;
|
28softwares/rest-nodejs-starter | 1,044 | src/middlewares/errorhandler.middleware.ts | import { NextFunction, Request, Response } from 'express';
import { AppError } from '../utils/appError.util';
import { ValidateError } from 'tsoa';
import multer from 'multer';
import messages from '../constants/messages.constants';
const errorHandler = (
error: any,
req: Request,
res: Response,
_next: NextFunction,
) => {
if (error instanceof AppError) {
return res.status(+error?.statusCode || 400).json({
sucess: false,
message: error?.message ?? 'Internal server error',
data: null,
});
}
if (error instanceof ValidateError) {
return res.status(400).json({
message: 'Validation Failed',
details: error?.fields,
});
}
if (error instanceof multer.MulterError) {
return res.status(400).json({
message: 'File Size Exceeded. Please upload within 8MB',
details: error.message,
});
}
console.log('Error', error);
return res.status(500).json({
success: false,
message: messages.serverError,
data: null,
});
};
export default errorHandler;
|
281677160/openwrt-package | 2,493 | luci-app-qmodem/luci/luci-app-qmodem/luasrc/model/cbi/qmodem/slot_config.lua | m = Map("qmodem", translate("Slot Configuration"))
m.redirect = luci.dispatcher.build_url("admin", "modem", "qmodem","settings")
s = m:section(NamedSection, arg[1], "modem-slot", "")
slot_type = s:option(ListValue, "type", translate("Slot Type"))
slot_type:value("usb", translate("USB"))
slot_type:value("pcie", translate("PCIE"))
slot = s:option(Value, "slot", translate("Slot ID"))
local pcie_slots = io.popen("ls /sys/bus/pci/devices/")
for line in pcie_slots:lines() do
slot:value(line,line.."[pcie]")
end
pcie_slots:close()
sim_led = s:option(Value, "sim_led", translate("SIM LED"))
sim_led.rmempty = true
net_led = s:option(Value, "net_led", translate("NET LED"))
net_led.rmempty = true
local leds = io.popen("ls /sys/class/leds/")
for line in leds:lines() do
net_led:value(line,line)
sim_led:value(line,line)
end
ethernet_5g = s:option(Value, "ethernet_5g", translate("Enable 5G Ethernet"))
ethernet_5g.rmempty = true
ethernet_5g.description = translate("For 5G modules using the Ethernet PHY connection, please specify the network interface name. (e.g., eth0, eth1)")
local net = io.popen("ls /sys/class/net/")
for line in net:lines() do
ethernet_5g:value(line,line)
end
net:close()
default_alias = s:option(Value, "alias", translate("Default Alias"))
default_alias.description = translate("After setting this option, the first module loaded into this slot will automatically be assigned this default alias.")
associated_usb = s:option(Value, "associated_usb", translate("Associated USB"))
associated_usb.rmempty = true
associated_usb.description = translate("For M.2 slots with both PCIe and USB support, specify the associated USB port (for ttyUSB access)")
associated_usb:depends("type", "pcie")
local usb_slots = io.popen("ls /sys/bus/usb/devices/")
for line in usb_slots:lines() do
if not line:match("usb%d+") then
slot:value(line,line.."[usb]")
associated_usb:value(line,line)
end
end
default_metric = s:option(Value, "default_metric", translate("Default Metric"))
default_metric.rmempty = true
default_metric.description = translate("The first module loaded into this slot will automatically be assigned this default metric.")
default_metric.datatype = "range(1, 255)"
pwr_gpio = s:option(Value, "gpio", translate("Power GPIO"))
pwr_gpio.rmempty = true
gpio_down = s:option(Value,"gpio_down",translate("GPIO Down Value"))
gpio_up = s:option(Value,"gpio_up",translate("GPIO Up Value"))
usb_slots:close()
return m
|
28softwares/rest-nodejs-starter | 1,422 | src/middlewares/index.ts | import express, { urlencoded } from 'express';
import swaggerUi from 'swagger-ui-express';
import { RegisterRoutes } from '../routes/routes';
import errorHandler from '../middlewares/errorhandler.middleware';
import { DotenvConfig, Environment } from '../config/env.config';
import cors from 'cors';
import swaggerDocument from '../../public/swagger.json';
import compression from 'compression';
import { rateLimit } from 'express-rate-limit';
export const configMiddleware = (app: express.Application) => {
app.use(express.json(), cors({ origin: '*' }), compression());
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 10 minutes
max: 1000, // Limit each IP to 1000 requests per `window` (here, per 10 minutes).
standardHeaders: 'draft-7', // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header
legacyHeaders: false, // Disable the `X-RateLimit-*` headers.
// store: ... , // Redis, Memcached, etc. See below.
});
app.use(limiter);
app.use(cors());
app.use(
urlencoded({
extended: true,
}),
);
if (DotenvConfig.NODE_ENV === Environment.DEVELOPMENT) {
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use('/swagger-json', (req, res) => res.send(swaggerUi));
}
app.use(express.static('data'));
app.use(express.static(DotenvConfig.MEDIA_UPLOAD_PATH!));
RegisterRoutes(app);
app.use(errorHandler);
};
|
28softwares/rest-nodejs-starter | 1,037 | src/middlewares/validator.middleware.ts | import { plainToClass } from 'class-transformer';
import { ValidationError, validate } from 'class-validator';
import { Request, Response, NextFunction } from 'express';
export class RequestValidator {
static validate = (classInstance: any) => {
return async (req: Request, res: Response, next: NextFunction) => {
const convertedObject = plainToClass(classInstance, req.body);
await validate(convertedObject).then((errors: ValidationError[]) => {
if (errors.length > 0) {
const rawErrors: string[] = [];
for (const errorItem of errors) {
//for nested ..
if (errorItem.children) {
for (const i of errorItem.children) {
rawErrors.push(...Object.values(i.constraints ?? ''));
}
}
// for non-nested.
rawErrors.push(...Object.values(errorItem.constraints ?? ''));
}
next(res.status(500).json({ errors: rawErrors[0] }));
}
});
next();
};
};
}
|
281677160/openwrt-package | 13,881 | luci-app-qmodem/luci/luci-app-qmodem/po/zh_Hans/qmodem.po | #controller/qmodem.lua
msgid "QModem"
msgstr "QWRT模组管理"
msgid "QModem Information"
msgstr "模组信息"
msgid "Dial Overview"
msgstr "拨号概览"
msgid "Advance Modem Settings"
msgstr "高级模组设置"
msgid "QModem Setting"
msgstr "QModem 设置"
# model/cbi/dial_config.lua
msgid "Modem Configuration"
msgstr "模组配置"
msgid "General Settings"
msgstr "一般设置"
msgid "Advanced Settings"
msgstr "高级设置"
msgid "Enable Dial"
msgstr "启用拨号"
msgid "Modem Alias"
msgstr "模组别名"
msgid "AT Port"
msgstr "AT端口"
msgid "SMS AT Port"
msgstr "短信AT端口"
msgid "If the DNS server is not set, it will use the DNS server leased by the operator."
msgstr "如果未设置DNS服务器,会使用运营商提供的DNS服务器"
msgid "Bridge Mode"
msgstr "桥接模式"
msgid "Caution: Only avalible for quectel sdx 5G Modem."
msgstr "警告:仅支持移远高通5G模组"
msgid "Do Not modify resolv.conf"
msgstr "不修改resolv.conf"
msgid "quectel-CM will append the DNS server to the resolv.conf file by default.if you do not want to modify the resolv.conf file, please check this option."
msgstr "quectel-CM默认会将DNS服务器追加到resolv.conf文件中,如果不想修改resolv.conf文件,请勾选此选项"
msgid "RA Master"
msgstr "作为RA上游"
msgid "Caution: Enabling this option will make it the IPV6 RA Master, and only one interface can be configured as such."
msgstr "警告:启用此选项将使其成为IPV6 RA Master,只能配置一个接口为RA Master"
msgid "Extend Prefix"
msgstr "扩展前缀"
msgid "Once checking, the prefix will be apply to lan zone"
msgstr "启用后,该接口的前缀会被通告至Lan区域"
msgid "enable modem soft reboot"
msgstr "启用模组软重启"
msgid "PDP Type"
msgstr "PDP类型"
msgid "Auto Choose"
msgstr "自动选择"
msgid "China Mobile (CN)"
msgstr "中国移动 (CN)"
msgid "China Unicom (CN)"
msgstr "中国联通 (CN)"
msgid "China Telecom (CN)"
msgstr "中国电信 (CN)"
msgid "China Broadcast (CN)"
msgstr "中国广电 (CN)"
msgid "Skytone (CN)"
msgstr "天际通 (CN)"
msgid "Sunrise (CH)"
msgstr "Sunrise (CH)"
msgid "Swisscom(CH)"
msgstr "Swisscom (CH)"
msgid "Salt (CH)"
msgstr "Salt (CH)"
msgid "Vodafone (DE)"
msgstr "Vodafone (DE)"
msgid "Telekom (DE)"
msgstr "Telekom (DE)"
msgid "O2 (DE)"
msgstr "O2 (DE)"
msgid "E-Plus (DE)"
msgstr "E-Plus (DE)"
msgid "1&1 (DE)"
msgstr "1&1 (DE)"
msgid "A1 (AT)"
msgstr "A1 (AT)"
msgid "Drei (AT)"
msgstr "Drei (AT)"
msgid "Magenta (AT)"
msgstr "Magenta (AT)"
msgid "Authentication Type"
msgstr "认证类型"
msgid "None"
msgstr "无"
msgid "PAP"
msgstr "PAP认证"
msgid "CHAP"
msgstr "CHAP认证"
msgid "PAP/CHAP (both)"
msgstr "PAP/CHAP认证"
msgid "PAP/CHAP Username"
msgstr "PAP/CHAP 用户名"
msgid "PAP/CHAP Password"
msgstr "PAP/CHAP 密码"
msgid "PIN Code"
msgstr "Pin码"
msgid "If the PIN code is not set, leave it blank."
msgstr "如果未设置PIN码,请留空。"
msgid "If solt 2 config is not set,will use slot 1 config."
msgstr "如果卡2的设置为空,会使用卡1的设置"
msgid "The metric value is used to determine the priority of the route. The smaller the value, the higher the priority. Cannot duplicate."
msgstr "路由优先级,越小的数字优先级越高。不可以和其他接口重复"
#odel/cbi/dial_overview.lua
msgid "Dial Overview"
msgstr "拨号总览"
msgid "Global Config"
msgstr "全局设置"
msgid "Enable Dial"
msgstr "启用拨号"
msgid "(Global)"
msgstr "(全局)"
msgid "Restart Dial Service"
msgstr "重启拨号服务"
msgid "Config List"
msgstr "配置列表"
msgid "Modem Model"
msgstr "模组型号"
msgid "Modem Alias"
msgstr "模组别名"
msgid "Modem Status"
msgstr "模组状态"
msgid "ReDial"
msgstr "重拨"
msgid "Remove Modem"
msgstr "移除模组"
# model/cbi/settings.lua
msgid "QModem Settings"
msgstr "QModem设置"
msgid "Modem Probe setting"
msgstr "模组加载设置"
msgid "Block Auto Probe/Remove"
msgstr "禁用自动加载/移除模组"
msgid "If enabled, the modem auto scan will be blocked."
msgstr "开启后自动扫描模组服务会关闭"
msgid "Enable PCIE Scan"
msgstr "启用PCIe模组扫描"
msgid "Once enabled, the PCIe ports will be scanned on every boot."
msgstr "如果启用了,每次开机会扫描PCIe接口"
msgid "Enable USB Scan"
msgstr "启用USB模组扫描"
msgid "Once enabled, the USB ports will be scanned on every boot."
msgstr "如果启用了,每次开机会扫描USB接口"
msgid "Try Preset USB Port"
msgstr "监控预设的USB端口"
msgid "Attempt to use pre-configured USB settings from the cpe vendor."
msgstr "尝试使用预设USB端口"
msgid "Try Preset PCIE Port"
msgstr "监控预设的PCIe端口"
msgid "Attempt to use pre-configured PCIE settings from the cpe vendor."
msgstr "尝试使用预设PCIe端口"
msgid "Scan ALL Manually"
msgstr "手动扫描所有"
msgid "Scan PCIE Manually"
msgstr "手动扫描PCIe"
msgid "Scan USB Manually"
msgstr "手动扫描USB"
msgid "Modem Slot Config List"
msgstr "模组插槽配置列表"
msgid "Slot Type"
msgstr "插槽类型"
msgid "Slot Path"
msgstr "插槽路径"
msgid "Config Name"
msgstr "配置名称"
# model/cbi/slot_config.lua
msgid "Slot Configuration"
msgstr "插槽配置"
msgid "Slot Type"
msgstr "插槽类型"
msgid "Slot ID"
msgstr "插槽ID"
msgid "SIM LED"
msgstr "SIM卡指示灯"
msgid "NET LED"
msgstr "网络指示灯"
msgid "Enable 5G Ethernet"
msgstr "启用5G转网口"
msgid "For 5G modules using the Ethernet PHY connection, please specify the network interface name. (e.g., eth0, eth1)"
msgstr "如果模组使用PHY连接,请指定网卡名称(如eth1 eth2)"
msgid "Associated USB"
msgstr "关联的USB"
msgid "For M.2 slots with both PCIe and USB support, specify the associated USB port (for ttyUSB access)"
msgstr "如果M.2接口同时提供pcie和usb,请关联usb(用于使用usb tty接口)"
msgid "The first module loaded into this slot will automatically be assigned this default metric."
msgstr "该插槽加载的第一个模块将会自动分配该默认的跃点。"
# view/qmodem/dial_overview.htm
msgid "Connected"
msgstr "已连接"
msgid "Disconnected"
msgstr "未连接"
msgid "Unknown"
msgstr "未知"
msgid "Download"
msgstr "下载"
msgid "Clear"
msgstr "清除"
msgid "Modem Status"
msgstr "模组状态"
msgid "Modem Log"
msgstr "模组日志"
# view/qmodem/modem_debug.htm
msgid "Lock Band"
msgstr "锁频"
msgid "Select All"
msgstr "全选"
msgid "Submit"
msgstr "提交"
msgid "Rat Prefer"
msgstr "制式偏好"
msgid "Current Mode"
msgstr "当前模式"
msgid "Setting"
msgstr "设置"
msgid "Dial Mode"
msgstr "拨号模式"
msgid "Neighbor Cell"
msgstr "邻区"
msgid "Lock Cell Setting"
msgstr "锁频设置"
msgid "RAT"
msgstr "制式"
msgid "PCI"
msgstr "物理小区ID(PCI)"
msgid "ARFCN"
msgstr "频点(ARFCN)"
msgid "TAC"
msgstr "TAC"
msgid "Band"
msgstr "频段"
msgid "SCS"
msgstr "子载波间隔(SCS)"
msgid "Status"
msgstr "状态"
msgid "Copy"
msgstr "复制"
msgid "Set IMEI"
msgstr "设置IMEI"
msgid "Modem Name"
msgstr "模组名称"
msgid "Warning!"
msgstr "警告!"
# root/usr/share/qmodem/fibocom.sh
msgid "Voltage"
msgstr "电压"
msgid "Temperature"
msgstr "温度"
msgid "Manufacturer"
msgstr "制造商"
msgid "SIM Status"
msgstr "SIM 状态"
msgid "Internet Service Provider"
msgstr "互联网服务提供商"
msgid "SIM Slot"
msgstr "SIM 插槽"
msgid "SIM Number"
msgstr "SIM 卡号码"
msgid "International Mobile Equipment Identity"
msgstr "国际移动设备身份(IMEI)"
msgid "International Mobile Subscriber Identity"
msgstr "国际移动用户身份(IMSI)"
msgid "Integrate Circuit Card Identity"
msgstr "集成电路卡身份(ICCID)"
msgid "Network Type"
msgstr "网络类型"
msgid "Channel Quality Indicator for Uplink"
msgstr "上行链路信道质量指示器(CQI)"
msgid "Channel Quality Indicator for Downlink"
msgstr "下行链路信道质量指示器(CQI)"
msgid "Access Maximum Bit Rate for Uplink"
msgstr "上行链路最大比特率"
msgid "Access Maximum Bit Rate for Downlink"
msgstr "下行链路最大比特率"
msgid "Transmit Rate"
msgstr "发送速率"
msgid "Receive Rate"
msgstr "接收速率"
msgid "Network Mode"
msgstr "网络模式"
msgid "Mobile Country Code"
msgstr "移动国家代码(MCC)"
msgid "Mobile Network Code"
msgstr "移动网络代码(MNC)"
msgid "Duplex Mode"
msgstr "双工模式"
msgid "Physical Cell ID"
msgstr "物理小区 ID(PCI)"
msgid "Tracking area code of cell served by neighbor Enb"
msgstr "邻近 eNB 服务的小区跟踪区代码(TAC)"
msgid "Absolute Radio-Frequency Channel Number"
msgstr "绝对射频信道编号(ARRCN)"
msgid "Band"
msgstr "频段"
msgid "Reference Signal Received Power"
msgstr "参考信号接收功率(RSRP)"
msgid "Reference Signal Received Quality"
msgstr "参考信号接收质量(RSRQ)"
msgid "Signal to Interference plus Noise Ratio Bandwidth"
msgstr "信号与干扰加噪声比带宽(SINRB)"
msgid "Received Signal Level"
msgstr "接收信号水平(RSL)"
msgid "SCS"
msgstr "子载波间隔(SCS)"
msgid "Serving Cell Receive Level"
msgstr "服务小区接收水平(SCRL)"
msgid "E-UTRA Absolute Radio Frequency Channel Number"
msgstr "E-UTRA 绝对射频信道编号(ARFCN)"
msgid "Freq band indicator"
msgstr "频段指示器(FBI)"
msgid "UL Bandwidth"
msgstr "上行带宽"
msgid "DL Bandwidth"
msgstr "下行带宽"
msgid "Received Signal Strength Indicator"
msgstr "接收信号强度指示器(RSSI)"
msgid "Radio Signal Strength Noise Ratio"
msgstr "无线信号强度噪声比(RSSNR)"
msgid "Channel Quality Indicator"
msgstr "信道质量指示器(CQI)"
msgid "TX Power"
msgstr "发射功率"
msgid "Location Area Code"
msgstr "位置区域代码"
msgid "Speech Code"
msgstr "语音编码"
msgid "Ec/No"
msgstr "Ec/No"
msgid "Ec/Io"
msgstr "Ec/Io"
msgid "Spreading Factor"
msgstr "扩频因子"
msgid "Compression Mode"
msgstr "压缩模式"
msgid "RxLev"
msgstr "接收电平"
# root/usr/share/qmodem/generic.sh
msgid "SIM Error,Error code:"
msgstr "SIM 错误,错误代码:"
msgid "warning"
msgstr "警告"
msgid "Connect Status"
msgstr "连接状态"
msgid "Cell Information"
msgstr "基站信息"
msgid "Base Information"
msgstr "基本信息"
msgid "Network Information"
msgstr "网络信息"
msgid "SIM Information"
msgstr "SIM卡信息"
# modem_state
msgid "ENABLED"
msgstr "已启用"
msgid "DISABLED"
msgstr "已禁用"
msgid "TTL Config"
msgstr "TTL配置"
msgid "Default Alias"
msgstr "默认别名"
msgid "After setting this option, the first module loaded into this slot will automatically be assigned this default alias."
msgstr "设置后,首次加载来此该插槽的模组会自动分配该默认别名"
msgid "Modem"
msgstr "移动网络"
msgid "Reboot Modem"
msgstr "重启模组"
msgid "Soft Reboot"
msgstr "软重启"
msgid "Hard Reboot"
msgstr "硬重启"
msgid "Power GPIO"
msgstr "电源 GPIO"
msgid "GPIO Down Value"
msgstr "GPIO 关闭值"
msgid "GPIO Up Value"
msgstr "GPIO 开启值"
msgid "Default Metric"
msgstr "默认跃点"
msgid "AT Debug"
msgstr "AT 调试"
msgid "(using)"
msgstr "(使用中)"
msgid "(valid)"
msgstr "(有效)"
msgid "(invalid)"
msgstr "(无效)"
msgid "(Not belong to this modem)"
msgstr "(不属于此模组)"
msgid "Send"
msgstr "发送"
msgid "Clear"
msgstr "清除"
msgid "Select Port"
msgstr "选择端口"
msgid "Input AT Command"
msgstr "输入AT命令"
msgid "AT Command"
msgstr "AT 命令"
msgid "Double Click or Right Click to Edit"
msgstr "双击或右键编辑"
msgid "Lost focus to save"
msgstr "失去焦点保存"
msgid "Clear AT Port"
msgstr "清空AT端口"
msgid "Clear AT Command"
msgstr "清空AT命令"
# view/qmodem/modem_config.htm
msgid "Fixed Device"
msgstr "固定设备"
msgid "If the device is fixed, it will not be update when the device is connected or disconnected."
msgstr "如果设备是固定的,则在设备连接或断开时不会更新。"
msgid "Slot Path"
msgstr "插槽路径"
msgid "Interface Type"
msgstr "接口类型"
msgid "USB"
msgstr "USB"
msgid "PCIe"
msgstr "PCIe"
msgid "Alias"
msgstr "别名"
msgid "Alias for the modem, used for identification."
msgstr "调制解调器的别名,用于标识。"
msgid "Enter alias name"
msgstr "输入别名"
msgid "Modem Model"
msgstr "调制解调器型号"
msgid "PDP Context Index"
msgstr "PDP上下文序号"
msgid "Manufacturer"
msgstr "制造商"
msgid "Quectel"
msgstr "移远"
msgid "Sierra Wireless"
msgstr "Sierra无线"
msgid "Fibocom"
msgstr "广和通"
msgid "Meig"
msgstr "美格"
msgid "Neoway"
msgstr "有方"
msgid "Telit"
msgstr "泰利特"
msgid "Platform"
msgstr "平台"
msgid "lte"
msgstr "LTE"
msgid "lte12"
msgstr "LTE12"
msgid "qualcomm"
msgstr "高通"
msgid "mediatek"
msgstr "联发科"
msgid "unisoc"
msgstr "紫光展锐"
msgid "intel"
msgstr "英特尔"
msgid "AT Port"
msgstr "AT端口"
msgid "AT command port for modem communication."
msgstr "用于调制解调器通信的AT命令端口。"
msgid "Supported Modes"
msgstr "支持的模式"
msgid "ECM"
msgstr "ECM"
msgid "MBIM"
msgstr "MBIM"
msgid "QMI"
msgstr "QMI"
msgid "NCM"
msgstr "NCM"
msgid "Enable"
msgstr "启用"
msgid "WCDMA Band"
msgstr "WCDMA频段"
msgid "WCDMA band configuration, e.g., 1/2/3"
msgstr "WCDMA频段配置,例如:1/2/3"
msgid "Enter WCDMA band"
msgstr "输入WCDMA频段"
msgid "LTE Band"
msgstr "LTE频段"
msgid "LTE band configuration, e.g., 1/2/3"
msgstr "LTE频段配置,例如:1/2/3"
msgid "Enter LTE band"
msgstr "输入LTE频段"
msgid "NSA Band"
msgstr "NSA频段"
msgid "NSA band configuration, e.g., 1/2/3"
msgstr "NSA频段配置,例如:1/2/3"
msgid "Enter NSA band"
msgstr "输入NSA频段"
msgid "SA Band"
msgstr "SA频段"
msgid "SA band configuration, e.g., 1/2/3"
msgstr "SA频段配置,例如:1/2/3"
msgid "Enter SA band"
msgstr "输入SA频段"
msgid "Modem Config List"
msgstr "模组配置列表"
msgid "Please Select"
msgstr "请选择"
msgid "Quectel"
msgstr "移远通信"
msgid "Simcom"
msgstr "芯讯通"
msgid "Sierra Wireless"
msgstr "Sierra无线"
msgid "Fibocom"
msgstr "广和通"
msgid "LTE"
msgstr "LTE"
msgid "LTE12"
msgstr "LTE12"
msgid "Qualcomm"
msgstr "高通"
msgid "MediaTek"
msgstr "联发科"
msgid "Unisoc"
msgstr "紫光展锐"
msgid "Intel"
msgstr "英特尔"
msgid "ECM"
msgstr "ECM模式"
msgid "MBIM"
msgstr "MBIM模式"
msgid "QMI"
msgstr "QMI模式"
msgid "NCM"
msgstr "NCM模式"
msgid "RNDIS"
msgstr "RNDIS模式"
msgid "Dial Mode"
msgstr "拨号模式"
msgid "Rat Prefer"
msgstr "网络制式优先"
msgid "Set IMEI"
msgstr "设置IMEI"
msgid "Neighbor Cell"
msgstr "邻小区信息"
msgid "Lock Band"
msgstr "锁频段"
msgid "Reboot Modem"
msgstr "重启调制解调器"
msgid "AT Debug"
msgstr "AT调试"
msgid "Post Init Delay"
msgstr "初始化延时"
msgid "Delay of executing AT command after modem initialization, in seconds."
msgstr "模组初始化后执行AT命令的延迟时间,以秒为单位。"
msgid "Enter delay in seconds"
msgstr "输入延时(秒)"
msgid "Post Init AT Commands"
msgstr "初始化后AT命令"
msgid "AT commands to execute after modem initialization."
msgstr "模组初始化后执行的AT命令。"
msgid "Enter AT commands"
msgstr "输入AT命令"
msgid "Pre Dial Delay"
msgstr "拨号前延时"
msgid "Delay of executing AT command before dialing, in seconds."
msgstr "拨号前执行AT命令的延迟时间,以秒为单位。"
msgid "Pre Dial AT Commands"
msgstr "拨号前AT命令"
msgid "AT commands to execute before dialing."
msgstr "拨号前执行的AT命令。"
msgid "(still in beta)"
msgstr "(仍在测试中)"
msgid "(beta)"
msgstr "(测试)"
msgid "Alternative AT Tools"
msgstr "使用替代的AT工具"
msgid "If enabled, using alternative AT Tools"
msgstr "如果启用了,会使用另外替代的AT工具查询模块信息"
msgid "Delay Start"
msgstr "开机时延时启动(扫描)"
msgid "Units:seconds"
msgstr "单位:秒"
msgid "Override AT Port"
msgstr "覆盖AT端口"
msgid "If no DNS server is set, the DNS server provided by the operator will be used"
msgstr "如果未设置DNS服务器,会使用运营商提供的DNS服务器"
msgid "Use Ubus"
msgstr "使用Ubus"
msgid "Force Set APN"
msgstr "强制设置APN"
msgid "If enabled, the APN will be set even if it matches the current configuration.(only works with tom modified version of quectel-cm)"
msgstr "如果启用,即使APN与当前配置匹配也会设置APN。(仅适用于tom修改版的quectel-cm)"
msgid "If slot 2 config is not set,will use slot 1 config."
msgstr "如果未设置插槽2配置,将使用插槽1配置。"
|
281677160/openwrt-package | 12,202 | luci-app-qmodem/luci/luci-app-qmodem/po/ru/modem.po | #controller/qmodem.lua
msgid "QModem"
msgstr "QModem"
msgid "QModem Information"
msgstr "Информация о QModem"
msgid "Dial Overview"
msgstr "Обзор набора"
msgid "Advance Modem Settings"
msgstr "Расширенные настройки модема"
msgid "QModem Setting"
msgstr "Настройки QModem"
# model/cbi/dial_config.lua
msgid "Modem Configuration"
msgstr "Конфигурация модема"
msgid "General Settings"
msgstr "Общие настройки"
msgid "Advanced Settings"
msgstr "Расширенные настройки"
msgid "Enable Dial"
msgstr "Включить набор"
msgid "Modem Alias"
msgstr "Псевдоним модема"
msgid "AT Port"
msgstr "AT порт"
msgid "SMS AT Port"
msgstr "SMS AT порт"
msgid "RA Master"
msgstr "RA мастер"
msgid "Caution: Enabling this option will make it the IPV6 RA Master, and only one interface can be configured as such."
msgstr "Внимание: Включение этой опции сделает его IPV6 RA мастером, и только один интерфейс может быть настроен как таковой."
msgid "Extend Prefix"
msgstr "Расширить префикс"
msgid "Once checking, the prefix will be apply to lan zone"
msgstr "После проверки префикс будет применен к зоне lan"
msgid "PDP Type"
msgstr "Тип PDP"
msgid "Auto Choose"
msgstr "Авто выбор"
msgid "China Mobile (CN)"
msgstr "Китайский мобильный (CN)"
msgid "China Unicom (CN)"
msgstr "Китайский Юником (CN)"
msgid "China Telecom (CN)"
msgstr "Китайский Телеком (CN)"
msgid "China Broadcast (CN)"
msgstr "Китайское вещание (CN)"
msgid "Skytone (CN)"
msgstr "Скайтон (CN)"
msgid "Swisscom (CH)"
msgstr "Swisscom (CH)"
msgid "Sunrise (CH)"
msgstr "Sunrise (CH)"
msgid "Salt (CH)"
msgstr "Salt (CH)"
msgid "Vodafone (DE)"
msgstr "Vodafone (DE)"
msgid "Telekom (DE)"
msgstr "Telekom (DE)"
msgid "O2 (DE)"
msgstr "O2 (DE)"
msgid "E-Plus (DE)"
msgstr "E-Plus (DE)"
msgid "1&1 (DE)"
msgstr "1&1 (DE)"
msgid "A1 (AT)"
msgstr "A1 (AT)"
msgid "Drei (AT)"
msgstr "Drei (AT)"
msgid "Magenta (AT)"
msgstr "Magenta (AT)"
msgid "Beeline (RU)"
msgstr "Билайн (RU)"
msgid "MTS (RU)"
msgstr "МТС (RU)"
msgid "Megafon (RU)"
msgstr "Мегафон (RU)"
msgid "Tele2 (RU)"
msgstr "Теле2 (RU)"
msgid "Yota (RU)"
msgstr "Йота (RU)"
msgid "T-mobile (RU)"
msgstr "Тинькофф Мобайл (RU)"
msgid "Rostelecom (RU)"
msgstr "Ростелеком (RU)"
msgid "Sber Mobile (RU)"
msgstr "СберМобайл (RU)"
msgid "Authentication Type"
msgstr "Тип аутентификации"
msgid "None"
msgstr "Нет"
msgid "PAP"
msgstr "PAP"
msgid "CHAP"
msgstr "CHAP"
msgid "PAP/CHAP (both)"
msgstr "PAP/CHAP (оба)"
msgid "PAP/CHAP Username"
msgstr "Имя пользователя PAP/CHAP"
msgid "PAP/CHAP Password"
msgstr "Пароль PAP/CHAP"
msgid "PIN Code"
msgstr "Код PIN"
msgid "If the PIN code is not set, leave it blank."
msgstr "Если код PIN не установлен, оставьте его пустым."
msgid "If solt 2 config is not set,will use slot 1 config."
msgstr "Если конфигурация слота 2 не установлена, будет использоваться конфигурация слота 1."
msgid "The metric value is used to determine the priority of the route. The smaller the value, the higher the priority. Cannot duplicate."
msgstr "Значение метрики используется для определения приоритета маршрута. Чем меньше значение, тем выше приоритет. Не может дублироваться."
#odel/cbi/dial_overview.lua
msgid "Dial Overview"
msgstr "Обзор набора"
msgid "Global Config"
msgstr "Глобальная конфигурация"
msgid "Enable Dial"
msgstr "Включить набор"
msgid "(Global)"
msgstr "(Глобально)"
msgid "Restart Dial Service"
msgstr "Перезапустить службу набора"
msgid "Config List"
msgstr "Список конфигураций"
msgid "Modem Model"
msgstr "Модель модема"
msgid "Modem Alias"
msgstr "Псевдоним модема"
msgid "Modem Status"
msgstr "Статус модема"
msgid "Remove Modem"
msgstr "Удалить модем"
# model/cbi/settings.lua
msgid "QModem Settings"
msgstr "Настройки QModem"
msgid "Modem Probe setting"
msgstr "Настройка зонда модема"
msgid "Block Auto Probe/Remove"
msgstr "Блокировать авто зондирование/удаление"
msgid "If enabled, the modem auto scan will be blocked."
msgstr "Если включено, автосканирование модема будет заблокировано."
msgid "Enable PCIE Scan"
msgstr "Включить сканирование PCIE"
msgid "Once enabled, the PCIe ports will be scanned on every boot."
msgstr "После включения порты PCIe будут сканироваться при каждой загрузке."
msgid "Enable USB Scan"
msgstr "Включить сканирование USB"
msgid "Once enabled, the USB ports will be scanned on every boot."
msgstr "После включения порты USB будут сканироваться при каждой загрузке."
msgid "Try Preset USB Port"
msgstr "Попробовать предустановленный USB порт"
msgid "Attempt to use pre-configured USB settings from the cpe vendor."
msgstr "Попытка использовать предварительно настроенные параметры USB от поставщика CPE."
msgid "Try Preset PCIE Port"
msgstr "Попробовать предустановленный порт PCIE"
msgid "Attempt to use pre-configured PCIE settings from the cpe vendor."
msgstr "Попытка использовать предварительно настроенные параметры PCIE от поставщика CPE."
msgid "Scan ALL Manually"
msgstr "Сканировать ВСЕ вручную"
msgid "Scan PCIE Manually"
msgstr "Сканировать PCIE вручную"
msgid "Scan USB Manually"
msgstr "Сканировать USB вручную"
msgid "Modem Slot Config List"
msgstr "Список конфигураций слотов модема"
msgid "Slot Type"
msgstr "Тип слота"
msgid "Slot Path"
msgstr "Путь слота"
msgid "Config Name"
msgstr "Имя конфигурации"
# model/cbi/slot_config.lua
msgid "Slot Configuration"
msgstr "Конфигурация слота"
msgid "Slot Type"
msgstr "Тип слота"
msgid "Slot ID"
msgstr "ID слота"
msgid "SIM LED"
msgstr "Светодиод SIM"
msgid "NET LED"
msgstr "Светодиод NET"
msgid "Enable 5G Ethernet"
msgstr "Включить 5G Ethernet"
msgid "For 5G modules using the Ethernet PHY connection, please specify the network interface name. (e.g., eth0, eth1)"
msgstr "Для 5G модулей, использующих соединение Ethernet PHY, укажите имя сетевого интерфейса. (например, eth0, eth1)"
msgid "Associated USB"
msgstr "Ассоциированный USB"
msgid "For M.2 slots with both PCIe and USB support, specify the associated USB port (for ttyUSB access)"
msgstr "Для слотов M.2 с поддержкой как PCIe, так и USB укажите ассоциированный USB порт (для доступа к ttyUSB)"
# view/qmodem/dial_overview.htm
msgid "Connected"
msgstr "Подключено"
msgid "Disconnected"
msgstr "Отключено"
msgid "Unknown"
msgstr "Неизвестно"
msgid "Download"
msgstr "Скачать"
msgid "Clear"
msgstr "Очистить"
msgid "Modem Status"
msgstr "Статус модема"
msgid "Modem Log"
msgstr "Журнал модема"
# view/qmodem/modem_debug.htm
msgid "Lock Band"
msgstr "Заблокировать диапазон"
msgid "Select All"
msgstr "Выбрать все"
msgid "Submit"
msgstr "Отправить"
msgid "Rat Prefer"
msgstr "Предпочтение RAT"
msgid "Current Mode"
msgstr "Текущий режим"
msgid "Setting"
msgstr "Настройка"
msgid "Dial Mode"
msgstr "Режим набора"
msgid "Neighbor Cell"
msgstr "Соседняя ячейка"
msgid "Lock Cell Setting"
msgstr "Настройка блокировки ячейки"
msgid "RAT"
msgstr "RAT"
msgid "PCI"
msgstr "PCI"
msgid "ARFCN"
msgstr "ARFCN"
msgid "TAC"
msgstr "TAC"
msgid "Band"
msgstr "Диапазон"
msgid "SCS"
msgstr "SCS"
msgid "Status"
msgstr "Статус"
msgid "Copy"
msgstr "Копировать"
msgid "Set IMEI"
msgstr "Установить IMEI"
msgid "Modem Name"
msgstr "Имя модема"
msgid "Warning!"
msgstr "Предупреждение!"
# root/usr/share/qmodem/fibocom.sh
msgid "Voltage"
msgstr "Напряжение"
msgid "Temperature"
msgstr "Температура"
msgid "Manufacturer"
msgstr "Производитель"
msgid "SIM Status"
msgstr "Статус SIM"
msgid "Internet Service Provider"
msgstr "Интернет-провайдер"
msgid "SIM Slot"
msgstr "Слот SIM"
msgid "SIM Number"
msgstr "Номер SIM"
msgid "International Mobile Equipment Identity"
msgstr "Международный идентификатор мобильного оборудования"
msgid "International Mobile Subscriber Identity"
msgstr "Международный идентификатор мобильного абонента"
msgid "Integrate Circuit Card Identity"
msgstr "Идентификатор интегральной схемы"
msgid "Network Type"
msgstr "Тип сети"
msgid "Channel Quality Indicator for Uplink"
msgstr "Индикатор качества канала для восходящей связи"
msgid "Channel Quality Indicator for Downlink"
msgstr "Индикатор качества канала для нисходящей связи"
msgid "Access Maximum Bit Rate for Uplink"
msgstr "Максимальная скорость передачи данных для восходящей связи"
msgid "Access Maximum Bit Rate for Downlink"
msgstr "Максимальная скорость передачи данных для нисходящей связи"
msgid "Transmit Rate"
msgstr "Скорость передачи"
msgid "Receive Rate"
msgstr "Скорость приема"
msgid "Network Mode"
msgstr "Режим сети"
msgid "Mobile Country Code"
msgstr "Код мобильной страны"
msgid "Mobile Network Code"
msgstr "Код мобильной сети"
msgid "Duplex Mode"
msgstr "Дуплексный режим"
msgid "Physical Cell ID"
msgstr "Физический ID ячейки"
msgid "Tracking area code of cell served by neighbor Enb"
msgstr "Код зоны отслеживания ячейки, обслуживаемой соседним Enb"
msgid "Absolute Radio-Frequency Channel Number"
msgstr "Абсолютный номер радиочастотного канала"
msgid "Band"
msgstr "Диапазон"
msgid "Reference Signal Received Power"
msgstr "Мощность принимаемого сигнала"
msgid "Reference Signal Received Quality"
msgstr "Качество принимаемого сигнала"
msgid "Signal to Interference plus Noise Ratio Bandwidth"
msgstr "Соотношение сигнала к помехам и шуму по полосе частот"
msgid "Received Signal Level"
msgstr "Уровень принимаемого сигнала"
msgid "SCS"
msgstr "SCS"
msgid "Serving Cell Receive Level"
msgstr "Уровень приема обслуживаемой ячейки"
msgid "E-UTRA Absolute Radio Frequency Channel Number"
msgstr "Абсолютный номер радиочастотного канала E-UTRA"
msgid "Freq band indicator"
msgstr "Индикатор частотного диапазона"
msgid "UL Bandwidth"
msgstr "Ширина полосы UL"
msgid "DL Bandwidth"
msgstr "Ширина полосы DL"
msgid "Received Signal Strength Indicator"
msgstr "Индикатор уровня принимаемого сигнала"
msgid "Radio Signal Strength Noise Ratio"
msgstr "Соотношение шумов радиосигнала"
msgid "Channel Quality Indicator"
msgstr "Индикатор качества канала"
msgid "TX Power"
msgstr "Мощность передачи"
msgid "Location Area Code"
msgstr "Код зоны расположения"
msgid "Speech Code"
msgstr "Код речи"
msgid "Ec/No"
msgstr "Ec/No"
msgid "Ec/Io"
msgstr "Ec/Io"
msgid "Spreading Factor"
msgstr "Коэффициент расширения"
msgid "Compression Mode"
msgstr "Режим сжатия"
msgid "RxLev"
msgstr "RxLev"
# root/usr/share/qmodem/generic.sh
msgid "SIM Error,Error code:"
msgstr "Ошибка SIM, код ошибки:"
msgid "warning"
msgstr "предупреждение"
msgid "Connect Status"
msgstr "Статус подключения"
msgid "Cell Information"
msgstr "Информация о ячейке"
msgid "Base Information"
msgstr "Базовая информация"
msgid "Network Information"
msgstr "Информация о сети"
msgid "SIM Information"
msgstr "Информация о SIM"
# modem_state
msgid "ENABLED"
msgstr "ВКЛЮЧЕНО"
msgid "DISABLED"
msgstr "ВЫКЛЮЧЕНО"
msgid "TTL Config"
msgstr "Конфигурация TTL"
msgid "Default Alias"
msgstr "Псевдоним по умолчанию"
msgid "After setting this option, the first module loaded into this slot will automatically be assigned this default alias."
msgstr "После установки этой опции первый модуль, загруженный в этот слот, будет автоматически назначен этому псевдониму по умолчанию."
msgid "Modem"
msgstr "Модем"
msgid "Reboot Modem"
msgstr "Перезагрузить модем"
msgid "Soft Reboot"
msgstr "Мягкая перезагрузка"
msgid "Hard Reboot"
msgstr "Жесткая перезагрузка"
msgid "Power GPIO"
msgstr "Питание GPIO"
msgid "GPIO Down Value"
msgstr "Значение GPIO вниз"
msgid "GPIO Up Value"
msgstr "Значение GPIO вверх"
msgid "Default Metric"
msgstr "Метрика по умолчанию"
msgid "AT Debug"
msgstr "Отладка AT"
msgid "(using)"
msgstr "(используется)"
msgid "(valid)"
msgstr "(действительно)"
msgid "(invalid)"
msgstr "(недействительно)"
msgid "(Not belong to this modem)"
msgstr "(Не принадлежит этому модему)"
msgid "Send"
msgstr "Отправить"
msgid "Clear"
msgstr "Очистить"
msgid "Select Port"
msgstr "Выбрать порт"
msgid "Input AT Command"
msgstr "Введите команду AT"
msgid "AT Command"
msgstr "Команда AT"
msgid "Double Click or Right Click to Edit"
msgstr "Дважды щелкните или щелкните правой кнопкой мыши, чтобы редактировать"
msgid "Lost focus to save"
msgstr "Потеря фокуса для сохранения"
msgid "Clear AT Port"
msgstr "Очистить AT порт"
msgid "Clear AT Command"
msgstr "Очистить команду AT"
|
28softwares/rest-nodejs-starter | 1,177 | src/utils/pageAndLimit.ts | import appConstants from '../constants/appConstant';
import { PaginatedInput } from '../interfaces/queryInterface';
export interface Pagination {
page: number;
limit: number;
}
export const paginateResponse = <T>(
dataTotalCount: [T[], number],
limit: number | string | undefined,
page: number | string | undefined,
) => {
const [data, total] = dataTotalCount;
page = parseInt(page?.toString() ?? '1');
limit = parseInt(limit?.toString() ?? '0');
const lastPage = Math.ceil(total / limit);
const nextPage = page + 1 > lastPage ? null : page + 1;
const prevPage = page - 1 < 1 ? null : page - 1;
return {
data,
pagination: {
count: total,
currentPage: page,
nextPage: nextPage,
prevPage: prevPage,
lastPage: lastPage,
},
};
};
export const skipTakeMaker = (paginationInput: PaginatedInput) => {
// if undefined set default value
paginationInput.page = paginationInput.page || appConstants.DEFAULT_PAGE;
paginationInput.limit = paginationInput.limit || appConstants.DEFAULT_LIMIT;
const skip = (paginationInput.page - 1) * paginationInput.limit;
return { skip, take: paginationInput.limit };
};
|
28softwares/rest-nodejs-starter | 1,155 | src/utils/appError.util.ts | import { StatusCodes } from '../constants/statusCode';
export class AppError extends Error {
statusCode: number;
isOperational: boolean;
status: string;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
static badRequest(message: string) {
return new AppError(message, StatusCodes.BAD_REQUEST);
}
static unAuthorized(message: string) {
return new AppError(message, StatusCodes.UNAUTHORIZED);
}
static forbidden(message: string) {
return new AppError(message, StatusCodes.FORBIDDEN);
}
static notFound(message: string) {
return new AppError(message, StatusCodes.NOT_FOUND);
}
static conflict(message: string) {
return new AppError(message, StatusCodes.CONFLICT);
}
static internalServerError(message: string) {
return new AppError(message, StatusCodes.INTERNAL_SERVER_ERROR);
}
static alreadyExists(message: string) {
return new AppError(message, StatusCodes.CONFLICT);
}
}
|
28softwares/rest-nodejs-starter | 1,326 | src/utils/email.util.ts | import nodemailer from 'nodemailer';
import { DotenvConfig } from '../config/env.config';
// import tokenService from "../services/token/token.service";
export enum MailType {
RESET_PASSWORD = 'RESET_PASSWORD',
LOGIN_OTP = 'LOGIN_OTP',
}
class EmailUtil {
private transporter;
constructor() {
this.transporter = nodemailer.createTransport({
host: DotenvConfig.MAIL_HOST,
auth: {
user: DotenvConfig.MAIL_USER,
pass: DotenvConfig.MAIL_PASSWORD,
},
});
}
async sendMail(to: string, mailType: MailType) {
const { subject, body } = await this.getTemplate(to, mailType);
await this.transporter.sendMail({
from: DotenvConfig.MAIL_USER,
to,
subject,
text: body,
html: body,
});
}
private async getTemplate(email: string, mailType: MailType) {
let subject, body;
switch (mailType) {
case MailType.RESET_PASSWORD: {
// const token = await tokenService.createResetPasswordToken(email);
const token = 'abc';
const link = `${DotenvConfig.FRONTEND_BASE_URL}/reset-password?token=${token}`;
subject = 'Reset password';
body = `Your Reset Link is <b><a href=${link}>${link}</a></b>`;
break;
}
}
return { subject, body };
}
}
export default new EmailUtil();
|
281677160/openwrt-package | 10,323 | luci-app-qmodem/luci/luci-app-qmodem/po/template/qmodem.po | #controller/qmodem.lua
msgid "QModem"
msgstr ""
msgid "QModem Information"
msgstr ""
msgid "Dial Overview"
msgstr ""
msgid "Advance Modem Settings"
msgstr ""
msgid "QModem Setting"
msgstr ""
# model/cbi/dial_config.lua
msgid "Modem Configuration"
msgstr ""
msgid "General Settings"
msgstr ""
msgid "Advanced Settings"
msgstr ""
msgid "Enable Dial"
msgstr ""
msgid "Modem Alias"
msgstr ""
msgid "AT Port"
msgstr ""
msgid "SMS AT Port"
msgstr ""
msgid "RA Master"
msgstr ""
msgid "Caution: Enabling this option will make it the IPV6 RA Master, and only one interface can be configured as such."
msgstr ""
msgid "Extend Prefix"
msgstr ""
msgid "Once checking, the prefix will be apply to lan zone"
msgstr ""
msgid "enable modem soft reboot"
msgstr ""
msgid "PDP Type"
msgstr ""
msgid "Auto Choose"
msgstr ""
msgid "China Mobile (CN)"
msgstr ""
msgid "China Unicom (CN)"
msgstr ""
msgid "China Telecom (CN)"
msgstr ""
msgid "China Broadcast (CN)"
msgstr ""
msgid "Skytone (CN)"
msgstr ""
msgid "Sunrise (CH)"
msgstr ""
msgid "Swisscom (CH)"
msgstr ""
msgid "Salt (CH)"
msgstr "Salt (CH)"
msgid "Vodafone (DE)"
msgstr ""
msgid "Telekom (DE)"
msgstr ""
msgid "O2 (DE)"
msgstr ""
msgid "E-Plus (DE)"
msgstr ""
msgid "1&1 (DE)"
msgstr ""
msgid "A1 (AT)"
msgstr ""
msgid "Drei (AT)"
msgstr ""
msgid "Magenta (AT)"
msgstr ""
msgid "T-Mobile (AT)"
msgstr ""
msgid "Authentication Type"
msgstr ""
msgid "None"
msgstr ""
msgid "PAP"
msgstr ""
msgid "CHAP"
msgstr ""
msgid "PAP/CHAP (both)"
msgstr ""
msgid "PAP/CHAP Username"
msgstr ""
msgid "PAP/CHAP Password"
msgstr ""
msgid "PIN Code"
msgstr ""
msgid "If the PIN code is not set, leave it blank."
msgstr ""
msgid "If solt 2 config is not set,will use slot 1 config."
msgstr ""
msgid "The metric value is used to determine the priority of the route. The smaller the value, the higher the priority. Cannot duplicate."
msgstr ""
#odel/cbi/dial_overview.lua
msgid "Dial Overview"
msgstr ""
msgid "Global Config"
msgstr ""
msgid "Enable Dial"
msgstr ""
msgid "(Global)"
msgstr ""
msgid "Restart Dial Service"
msgstr ""
msgid "Config List"
msgstr ""
msgid "Modem Model"
msgstr ""
msgid "Modem Alias"
msgstr ""
msgid "Modem Status"
msgstr ""
msgid "Remove Modem"
msgstr ""
# model/cbi/settings.lua
msgid "QModem Settings"
msgstr ""
msgid "Modem Probe setting"
msgstr ""
msgid "Block Auto Probe/Remove"
msgstr ""
msgid "If enabled, the modem auto scan will be blocked."
msgstr ""
msgid "Enable PCIE Scan"
msgstr ""
msgid "Once enabled, the PCIe ports will be scanned on every boot."
msgstr ""
msgid "Enable USB Scan"
msgstr ""
msgid "Once enabled, the USB ports will be scanned on every boot."
msgstr ""
msgid "Try Preset USB Port"
msgstr ""
msgid "Attempt to use pre-configured USB settings from the cpe vendor."
msgstr ""
msgid "Try Preset PCIE Port"
msgstr ""
msgid "Attempt to use pre-configured PCIE settings from the cpe vendor."
msgstr ""
msgid "Scan ALL Manually"
msgstr ""
msgid "Scan PCIE Manually"
msgstr ""
msgid "Scan USB Manually"
msgstr ""
msgid "Modem Slot Config List"
msgstr ""
msgid "Slot Type"
msgstr ""
msgid "Slot Path"
msgstr ""
msgid "Config Name"
msgstr ""
# model/cbi/slot_config.lua
msgid "Slot Configuration"
msgstr ""
msgid "Slot Type"
msgstr ""
msgid "Slot ID"
msgstr ""
msgid "SIM LED"
msgstr ""
msgid "NET LED"
msgstr ""
msgid "Enable 5G Ethernet"
msgstr ""
msgid "For 5G modules using the Ethernet PHY connection, please specify the network interface name. (e.g., eth0, eth1)"
msgstr ""
msgid "Associated USB"
msgstr ""
msgid "For M.2 slots with both PCIe and USB support, specify the associated USB port (for ttyUSB access)"
msgstr ""
# view/qmodem/dial_overview.htm
msgid "Connected"
msgstr ""
msgid "Disconnected"
msgstr ""
msgid "Unknown"
msgstr ""
msgid "Download"
msgstr ""
msgid "Clear"
msgstr ""
msgid "Modem Status"
msgstr ""
msgid "Modem Log"
msgstr ""
# view/qmodem/modem_debug.htm
msgid "Lock Band"
msgstr ""
msgid "Select All"
msgstr ""
msgid "Submit"
msgstr ""
msgid "Rat Prefer"
msgstr ""
msgid "Current Mode"
msgstr ""
msgid "Setting"
msgstr ""
msgid "Dial Mode"
msgstr ""
msgid "Neighbor Cell"
msgstr ""
msgid "Lock Cell Setting"
msgstr ""
msgid "RAT"
msgstr ""
msgid "PCI"
msgstr ""
msgid "ARFCN"
msgstr ""
msgid "TAC"
msgstr ""
msgid "Band"
msgstr ""
msgid "SCS"
msgstr ""
msgid "Status"
msgstr ""
msgid "Copy"
msgstr ""
msgid "Set IMEI"
msgstr ""
msgid "Modem Name"
msgstr ""
msgid "Warning!"
msgstr ""
# root/usr/share/qmodem/fibocom.sh
msgid "Voltage"
msgstr ""
msgid "Temperature"
msgstr ""
msgid "Manufacturer"
msgstr ""
msgid "SIM Status"
msgstr ""
msgid "Internet Service Provider"
msgstr ""
msgid "SIM Slot"
msgstr ""
msgid "SIM Number"
msgstr ""
msgid "International Mobile Equipment Identity"
msgstr ""
msgid "International Mobile Subscriber Identity"
msgstr ""
msgid "Integrate Circuit Card Identity"
msgstr ""
msgid "Network Type"
msgstr ""
msgid "Channel Quality Indicator for Uplink"
msgstr ""
msgid "Channel Quality Indicator for Downlink"
msgstr ""
msgid "Access Maximum Bit Rate for Uplink"
msgstr ""
msgid "Access Maximum Bit Rate for Downlink"
msgstr ""
msgid "Transmit Rate"
msgstr ""
msgid "Receive Rate"
msgstr ""
msgid "Network Mode"
msgstr ""
msgid "Mobile Country Code"
msgstr ""
msgid "Mobile Network Code"
msgstr ""
msgid "Duplex Mode"
msgstr ""
msgid "Physical Cell ID"
msgstr ""
msgid "Tracking area code of cell served by neighbor Enb"
msgstr ""
msgid "Absolute Radio-Frequency Channel Number"
msgstr ""
msgid "Band"
msgstr ""
msgid "Reference Signal Received Power"
msgstr ""
msgid "Reference Signal Received Quality"
msgstr ""
msgid "Signal to Interference plus Noise Ratio Bandwidth"
msgstr ""
msgid "Received Signal Level"
msgstr ""
msgid "SCS"
msgstr ""
msgid "Serving Cell Receive Level"
msgstr ""
msgid "E-UTRA Absolute Radio Frequency Channel Number"
msgstr ""
msgid "Freq band indicator"
msgstr ""
msgid "UL Bandwidth"
msgstr ""
msgid "DL Bandwidth"
msgstr ""
msgid "Received Signal Strength Indicator"
msgstr ""
msgid "Radio Signal Strength Noise Ratio"
msgstr ""
msgid "Channel Quality Indicator"
msgstr ""
msgid "TX Power"
msgstr ""
msgid "Location Area Code"
msgstr ""
msgid "Speech Code"
msgstr ""
msgid "Ec/No"
msgstr ""
msgid "Ec/Io"
msgstr ""
msgid "Spreading Factor"
msgstr ""
msgid "Compression Mode"
msgstr ""
msgid "RxLev"
msgstr ""
# root/usr/share/qmodem/generic.sh
msgid "SIM Error,Error code:"
msgstr ""
msgid "warning"
msgstr ""
msgid "Connect Status"
msgstr ""
msgid "Cell Information"
msgstr ""
msgid "Base Information"
msgstr ""
msgid "Network Information"
msgstr ""
msgid "SIM Information"
msgstr ""
# modem_state
msgid "ENABLED"
msgstr ""
msgid "DISABLED"
msgstr ""
msgid "TTL Config"
msgstr ""
msgid "Default Alias"
msgstr ""
msgid "After setting this option, the first module loaded into this slot will automatically be assigned this default alias."
msgstr ""
msgid "Modem"
msgstr ""
msgid "Reboot Modem"
msgstr ""
msgid "Soft Reboot"
msgstr ""
msgid "Hard Reboot"
msgstr ""
msgid "Power GPIO"
msgstr ""
msgid "GPIO Down Value"
msgstr ""
msgid "GPIO Up Value"
msgstr ""
msgid "Default Metric"
msgstr ""
msgid "AT Debug"
msgstr ""
msgid "(using)"
msgstr ""
msgid "(valid)"
msgstr ""
msgid "(invalid)"
msgstr ""
msgid "(Not belong to this modem)"
msgstr ""
msgid "Send"
msgstr ""
msgid "Clear"
msgstr ""
msgid "Select Port"
msgstr ""
msgid "Input AT Command"
msgstr ""
msgid "AT Command"
msgstr ""
msgid "Double Click or Right Click to Edit"
msgstr ""
msgid "Lost focus to save"
msgstr ""
msgid "Clear AT Port"
msgstr ""
msgid "Clear AT Command"
msgstr ""
# view/qmodem/modem_config.htm
msgid "Fixed Device"
msgstr "固定设备"
msgid "If the device is fixed, it will not be update when the device is connected or disconnected."
msgstr "如果设备是固定的,则在设备连接或断开时不会更新。"
msgid "Slot Path"
msgstr "插槽路径"
msgid "Interface Type"
msgstr "接口类型"
msgid "USB"
msgstr "USB"
msgid "PCIe"
msgstr "PCIe"
msgid "Alias"
msgstr "别名"
msgid "Alias for the modem, used for identification."
msgstr "调制解调器的别名,用于标识。"
msgid "Enter alias name"
msgstr "输入别名"
msgid "Modem Model"
msgstr "调制解调器型号"
msgid "PDP Context Index"
msgstr "PDP上下文序号"
msgid "Manufacturer"
msgstr "制造商"
msgid "Quectel"
msgstr "移远"
msgid "Sierra Wireless"
msgstr "Sierra无线"
msgid "Fibocom"
msgstr "广和通"
msgid "Meig"
msgstr "美格"
msgid "Neoway"
msgstr "有方"
msgid "Telit"
msgstr "泰利特"
msgid "Platform"
msgstr "平台"
msgid "lte"
msgstr "LTE"
msgid "lte12"
msgstr "LTE12"
msgid "qualcomm"
msgstr "高通"
msgid "mediatek"
msgstr "联发科"
msgid "unisoc"
msgstr "紫光展锐"
msgid "intel"
msgstr "英特尔"
msgid "AT Port"
msgstr "AT端口"
msgid "AT command port for modem communication."
msgstr "用于调制解调器通信的AT命令端口。"
msgid "Supported Modes"
msgstr "支持的模式"
msgid "ECM"
msgstr "ECM"
msgid "MBIM"
msgstr "MBIM"
msgid "QMI"
msgstr "QMI"
msgid "NCM"
msgstr "NCM"
msgid "Enable"
msgstr "启用"
msgid "WCDMA Band"
msgstr "WCDMA频段"
msgid "WCDMA band configuration, e.g., 1/2/3"
msgstr "WCDMA频段配置,例如:1/2/3"
msgid "Enter WCDMA band"
msgstr "输入WCDMA频段"
msgid "LTE Band"
msgstr "LTE频段"
msgid "LTE band configuration, e.g., 1/2/3"
msgstr "LTE频段配置,例如:1/2/3"
msgid "Enter LTE band"
msgstr "输入LTE频段"
msgid "NSA Band"
msgstr "NSA频段"
msgid "NSA band configuration, e.g., 1/2/3"
msgstr "NSA频段配置,例如:1/2/3"
msgid "Enter NSA band"
msgstr "输入NSA频段"
msgid "SA Band"
msgstr "SA频段"
msgid "SA band configuration, e.g., 1/2/3"
msgstr "SA频段配置,例如:1/2/3"
msgid "Enter SA band"
msgstr "输入SA频段"
msgid "Modem Config List"
msgstr "模组配置列表"
msgid "Please Select"
msgstr "请选择"
msgid "Quectel"
msgstr "移远通信"
msgid "Simcom"
msgstr "芯讯通"
msgid "Sierra Wireless"
msgstr "Sierra无线"
msgid "Fibocom"
msgstr "广和通"
msgid "LTE"
msgstr "LTE"
msgid "LTE12"
msgstr "LTE12"
msgid "Qualcomm"
msgstr "高通"
msgid "MediaTek"
msgstr "联发科"
msgid "Unisoc"
msgstr "紫光展锐"
msgid "Intel"
msgstr "英特尔"
msgid "ECM"
msgstr "ECM模式"
msgid "MBIM"
msgstr "MBIM模式"
msgid "QMI"
msgstr "QMI模式"
msgid "NCM"
msgstr "NCM模式"
msgid "RNDIS"
msgstr "RNDIS模式"
msgid "Dial Mode"
msgstr "拨号模式"
msgid "Rat Prefer"
msgstr "网络制式优先"
msgid "Set IMEI"
msgstr "设置IMEI"
msgid "Neighbor Cell"
msgstr "邻小区信息"
msgid "Lock Band"
msgstr "锁频段"
msgid "Reboot Modem"
msgstr "重启调制解调器"
msgid "AT Debug"
msgstr "AT调试"
|
281677160/openwrt-package | 1,450 | luci-app-qmodem/luci/luci-app-qmodem-ttl/root/etc/init.d/qmodem_ttl | #!/bin/sh /etc/rc.common
START=95
STOP=13
USE_PROCD=1
. /usr/share/libubox/jshn.sh
. /lib/functions.sh
start_service()
{
config_load 'qmodem_ttl'
config_get enable 'main' 'enable' '0'
if [ "$enable" == 0 ]; then
return
fi
set_if_ttl
}
set_if_ttl()
{
config_get ttl 'main' 'ttl'
IPT="iptables"
IPT6="ip6tables"
logger -t modem_ttl "Ovrewirte TTL from br-lan to $ttl"
comment="modem_ttl"
touch /etc/firewall.d/qmodem_ttl
echo "$IPT -t mangle -A POSTROUTING -j TTL --ttl-set $ttl -m comment --comment $comment" >> /etc/firewall.d/qmodem_ttl
echo "$IPT6 -t mangle -A POSTROUTING -j HL --hl-set $ttl -m comment --comment $comment" >> /etc/firewall.d/qmodem_ttl
/etc/firewall.d/qmodem_ttl
/etc/init.d/firewall restart
[ -d /sys/kernel/debug/ecm/ ] && /etc/init.d/qca-nss-ecm stop
[ -d /sys/module/shortcut_fe_cm ] && rmmod shortcut_fe_cm
[ -d /sys/module/fast_classifier ] && rmmod fast_classifier
}
stop_service(){
local kernel_version=$(uname -r)
rm -f /etc/firewall.d/qmodem_ttl
[ -f /etc/init.d/qca-nss-ecm ] && /etc/init.d/qca-nss-ecm start
[ -e "/lib/modules/$kernel_version/shortcut-fe-cm.ko" ] && modprobe shortcut-fe-cm
[ -e "/lib/modules/$kernel_version/fast-classifier.ko" ] && modprobe fast-classifier
/etc/init.d/firewall restart
}
service_triggers()
{
procd_add_reload_trigger "qmodem_ttl"
}
reload_service()
{
stop
start
}
|
281677160/openwrt-package | 2,009 | luci-app-qmodem/luci/luci-app-qmodem-sms/luasrc/controller/qmodem_sms.lua | module("luci.controller.qmodem_sms", package.seeall)
local http = require "luci.http"
local fs = require "nixio.fs"
local json = require("luci.jsonc")
local modem_ctrl = "/usr/share/qmodem/modem_ctrl.sh "
function shell(command)
local odpall = io.popen(command)
local odp = odpall:read("*a")
odpall:close()
return odp
end
function index()
--sim卡配置
entry({"admin", "modem", "qmodem", "modem_sms"},template("modem_sms/modem_sms"), luci.i18n.translate("SMS"), 11).leaf = true
entry({"admin", "modem", "qmodem", "send_sms"}, call("sendSMS"), nil).leaf = true
entry({"admin", "modem", "qmodem", "get_sms"}, call("getSMS"), nil).leaf = true
entry({"admin", "modem", "qmodem", "delete_sms"}, call("delSMS"), nil).leaf = true
entry({"admin", "modem", "qmodem", "sms_forward"}, cbi("qmodem_sms/sms_forward"), luci.i18n.translate("SMS Forward"), 12).leaf = true
entry({"admin", "modem", "qmodem", "sms_forward_extedit"}, cbi("qmodem_sms/sms_forward_extedit")).leaf = true
end
function getSMS()
local cfg_id = http.formvalue("cfg")
response = shell(modem_ctrl .. "get_sms " .. cfg_id)
http.prepare_content("application/json")
http.write(response)
end
function sendSMS()
local cfg_id = http.formvalue("cfg")
local pdu = http.formvalue("pdu")
if pdu then
response = shell(modem_ctrl .. "send_raw_pdu " .. cfg_id .. " \"" .. pdu .. "\"")
else
local phone_number = http.formvalue("phone_number")
local message_content = http.formvalue("message_content")
json_cmd = string.format('{\\"phone_number\\":\\"%s\\",\\"message_content\\":\\"%s\\"}', phone_number, message_content)
response = shell(modem_ctrl .. "send_sms " .. cfg_id .." \"".. json_cmd .. "\"")
end
http.prepare_content("application/json")
http.write(response)
end
function delSMS()
local cfg_id = http.formvalue("cfg")
local index = http.formvalue("index")
response = shell(modem_ctrl .. "delete_sms " .. cfg_id .. " \"" ..index.."\"")
http.prepare_content("application/json")
http.write(response)
end
|
28softwares/rest-nodejs-starter | 1,549 | src/constants/appConstant.ts | export default {
APP_NAME: '',
// Pagination
DEFAULT_PAGE: 1,
DEFAULT_LIMIT: 30,
};
export enum Environment {
DEVELOPMENT = 'DEVELOPMENT',
PRODUCTION = 'PRODUCTION',
TEST = 'TEST',
}
export enum UserLoginType {
TRADITIONAL = 'TRADITIONAL', //register using email and password,
GOOGLE = 'GOOOGLE',
}
export enum MediaType {
PROFILE_IMAGE = 'PROFILE_IMAGE',
PRODUCT_IMAGE = 'PRODUCT_IMAGE',
CAROUSEL_IMAGE = 'CAROUSEL_IMAGE',
STORE_LOGO = 'STORE_LOGO',
BLOG_THUMBNAIL = 'BLOG_THUMBNAIL',
}
export enum Role {
ADMIN = 'ADMIN',
USER = 'USER',
SUPER_ADMIN = 'SUPER_ADMIN',
NONE = 'NONE',
}
export enum TokenEnum {
REFRESH_TOKEN = 'REFRESH_TOKEN',
}
export enum OrderStatus {
INITIAL = 'INITIAL', //when order is created but payment is not done
PENDING = 'PENDING', //when payment is done, and under the review of admin
SHIPPED = 'SHIPPED', //shipped by merchant
CANCELLED = 'CANCELLED', //cancelled by admin
RECIVED = 'RECEIVED', // received by user
CANCELLED_BY_USER = 'CANCELLED_BY_USER', //cancelled by user
}
export enum PaymentStatus {
PENDING = 'PENDING',
SUCCEEDED = 'SUCCEEDED',
BLOCKED = 'BLOCKED',
CANCELED = 'CANCELED',
REFUND = 'REFUND',
FAILED = 'FAILED',
}
export enum STRIPE_PAYMENT_STATUS {
CANCELED = 'payment_intent.canceled',
CREATED = 'payment_intent.created',
PARTIALLY_FUNDED = 'payment_intent.partially_funded',
FAILED = 'payment_intent.payment_failed',
REQUIRES_ACTION = 'payment_intent.requires_action',
SUCCEEDED = 'payment_intent.succeeded',
}
|
28softwares/rest-nodejs-starter | 1,618 | src/constants/messages.constants.ts | const messages = {
serverError: 'Internal Server Error',
invalidCredentials: 'Invalid Credentials',
invalidToken: 'Invalid Token',
tokenExpired: 'Token Expired',
invalidEmail: 'Invalid Email',
emailAlreadyExists: 'Email Already Exists',
invalidPassword: 'Invalid Password',
welcomeMessage: 'Welcome to the United Natation Development Program API',
dataFetched: 'Data Fetched Successfully',
dataUpdated: 'Data Updated Successfully',
dataInserted: 'Data Inserted Successfully',
dataDeleted: 'Data Deleted Successfully',
adminCreated: 'Admin Created Successfully',
adminNotFound: 'Admin Not Found',
permissionsUpdate: 'Permissions Update Successfully',
passwordStrength:
'Password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one number and one special character',
invalidAuth: 'Invalid email or password',
validLogin: 'Logged in Successfully',
unAuthorized: 'You are not authorized to perform this action',
mediaUploaded: 'Media Uploaded Successfully',
invalidContactNumber: 'Invalid Contact Number',
invalidProjectId: 'Invalid Project',
actionCompleted: 'Action completed successfully',
contactNumberExist: 'Contact Number Already Exist',
adminDeleted: 'Admin Deleted Successfully',
invalidDateFormat: 'Invalid Date Format',
invalidProject: 'Invalid Project',
invalidRequest: 'Invalid Request',
invalidDate: 'Date should be in format mm/dd/yyyy',
};
export const categoryMessage = {
cannotDeleteDueToSubcategory:
'This category consists subcategory so it cannot delete',
};
export default messages;
|
281677160/openwrt-package | 34,455 | luci-app-qmodem/luci/luci-app-qmodem-sms/luasrc/view/modem_sms/modem_sms.htm | <%+header%>
<script>
var pduParser = {};
pduParser.parse = function(pdu) {
//Cursor points to the last octet we've read.
var cursor = 0;
var buffer = new Buffer(pdu.slice(0,4), 'hex');
var smscSize = buffer[0];
var smscType = buffer[1].toString(16);
cursor = (smscSize*2+2);
var smscNum = pduParser.deSwapNibbles(pdu.slice(4, cursor));
var buffer = new Buffer(pdu.slice(cursor,cursor+6), 'hex');
cursor += 6;
var smsDeliver = buffer[0];
var smsDeliverBits = ("00000000"+parseInt(smsDeliver).toString(2)).slice(-8);
var udhi = smsDeliverBits.slice(1,2) === "1";
var senderSize = buffer[1];
if(senderSize % 2 === 1)
senderSize++;
var senderType = parseInt(buffer[2]).toString(16)
var encodedSender = pdu.slice(cursor, cursor + senderSize);
var senderNum;
if (senderType === '91') {
senderNum = pduParser.deSwapNibbles(encodedSender);
} else if (senderType === 'd0') {
senderNum = this.decode7Bit(encodedSender).replace(/\0/g, '');
} else {
console.error('unsupported sender type.');
}
cursor += senderSize;
var protocolIdentifier = pdu.slice(cursor, cursor+2);
cursor += 2;
var dataCodingScheme = pdu.slice(cursor, cursor+2);
cursor = cursor+2;
var encoding = pduParser.detectEncoding(dataCodingScheme);
var timestamp = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+14));
var time = new Date;
time.setUTCFullYear('20'+timestamp.slice(0,2));
time.setUTCMonth(timestamp.slice(2,4)-1);
time.setUTCDate(timestamp.slice(4,6));
time.setUTCHours(timestamp.slice(6,8));
time.setUTCMinutes(timestamp.slice(8,10));
time.setUTCSeconds(timestamp.slice(10,12));
var firstTimezoneOctet = parseInt(timestamp.slice(12,13));
var binary = ("0000"+firstTimezoneOctet.toString(2)).slice(-4);
var factor = binary.slice(0,1) === '1' ? 1 : -1;
var binary = '0'+binary.slice(1, 4);
var firstTimezoneOctet = parseInt(binary, 2).toString(10);
var timezoneDiff = parseInt(firstTimezoneOctet + timestamp.slice(13, 14));
var time = new Date(time.getTime() + (timezoneDiff * 15 * 1000 * 60 * factor));
cursor += 14;
var dataLength = parseInt(pdu.slice(cursor, cursor+2), 16).toString(10);
cursor += 2;
if(udhi) { //User-Data-Header-Indicator: means there's some User-Data-Header.
var udhLength = pdu.slice(cursor, cursor+2);
var iei = pdu.slice(cursor+2, cursor+4);
if(iei == "00") { //Concatenated sms.
var headerLength = pdu.slice(cursor+4, cursor+6);
var referenceNumber = pdu.slice(cursor+6, cursor+8);
var parts = pdu.slice(cursor+8, cursor+10);
var currentPart = pdu.slice(cursor+10, cursor+12);
}
if(iei == "08") { //Concatenaded sms with a two-bytes reference number
var headerLength = pdu.slice(cursor+4, cursor+6);
var referenceNumber = pdu.slice(cursor+6, cursor+10);
var parts = pdu.slice(cursor+10, cursor+12);
var currentPart = pdu.slice(cursor+12, cursor+14);
}
if(encoding === '16bit')
if(iei == '00')
cursor += (udhLength-2)*4;
else if(iei == '08')
cursor += ((udhLength-2)*4)+2;
else
cursor += (udhLength-2)*2;
}
if(encoding === '16bit')
var text = pduParser.decode16Bit(pdu.slice(cursor), dataLength);
else if(encoding === '7bit')
var text = pduParser.decode7Bit(pdu.slice(cursor), dataLength);
else if(encoding === '8bit')
var text = ''; //TODO
var data = {
'smsc' : smscNum,
'smsc_type' : smscType,
'sender' : senderNum,
'sender_type' : senderType,
'encoding' : encoding,
'time' : time,
'text' : text
};
if(udhi) {
data['udh'] = {
'length' : udhLength,
'iei' : iei,
};
if(iei == '00' || iei == '08') {
data['udh']['reference_number'] = referenceNumber;
data['udh']['parts'] = parseInt(parts);
data['udh']['current_part'] = parseInt(currentPart);
}
}
return data;
}
pduParser.detectEncoding = function(dataCodingScheme) {
var binary = ('00000000'+(parseInt(dataCodingScheme, 16).toString(2))).slice(-8);
if(binary == '00000000')
return '7bit';
if(binary.slice(0, 2) === '00') {
var compressed = binary.slice(2, 1) === '1';
var bitsHaveMeaning = binary.slice(3, 1) === '1';
if(binary.slice(4,6) === '00')
return '7bit';
if(binary.slice(4,6) === '01')
return '8bit';
if(binary.slice(4,6) === '10')
return '16bit';
}
}
pduParser.decode16Bit = function(data, length) {
//We are getting ucs2 characters.
var ucs2 = '';
for(var i = 0;i<=data.length;i=i+4) {
ucs2 += String.fromCharCode("0x"+data[i]+data[i+1]+data[i+2]+data[i+3]);
}
return ucs2;
}
pduParser.deSwapNibbles = function(nibbles) {
var out = '';
for(var i = 0; i< nibbles.length; i=i+2) {
if(nibbles[i] === 'F') //Dont consider trailing F.
out += parseInt(nibbles[i+1], 16).toString(10);
else
out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
}
return out;
}
pduParser.decode7Bit = function(code, count) {
//We are getting 'septeps'. We should decode them.
var binary = '';
for(var i = 0; i<code.length;i++)
binary += ('0000'+parseInt(code.slice(i,i+1), 16).toString(2)).slice(-4);
var bin = Array();
var cursor = 0;
var fromPrevious = '';
var i = 0;
while(binary[i]) {
var remaining = 7 - fromPrevious.length;
var toNext = 8 - remaining;
bin[i] = binary.slice(cursor+toNext, cursor+toNext+remaining) + fromPrevious;
var fromPrevious = binary.slice(cursor, cursor+toNext);
if(toNext === 8)
fromPrevious = '';
else
cursor += 8;
i++;
}
var ascii = '';
for(i in bin)
ascii += String.fromCharCode(parseInt(bin[i], 2));
return ascii;
}
pduParser.encode7Bit = function(ascii) {
//We should create septeps now.
var octets = new Array();
for(var i = 0; i<ascii.length; i++)
octets.push(('0000000'+(ascii.charCodeAt(i).toString(2))).slice(-7));
for(var i in octets) {
var i = parseInt(i);
var freeSpace = 8 - octets[i].length;
if(octets[i+1] && freeSpace !== 8) {
octets[i] = octets[i+1].slice(7-freeSpace) + octets[i];
octets[i+1] = octets[i+1].slice(0, 7-freeSpace);
}
}
var hex = '';
for(i in octets)
if(octets[i].length > 0)
hex += ('00'+(parseInt(octets[i], 2).toString(16))).slice(-2);
return hex;
}
//TODO: TP-Validity-Period (Delivery)
pduParser.generate = function(message) {
var pdu = '00';
var parts = 1;
if(message.encoding === '16bit' && message.text.length > 70)
parts = message.text.length / 66;
else if(message.encoding === '7bit' && message.text.length > 160)
parts = message.text.length / 153;
parts = Math.ceil(parts);
TPMTI = 1;
TPRD = 4;
TPVPF = 8;
TPSRR = 32;
TPUDHI = 64;
TPRP = 128;
var submit = TPMTI;
if(parts > 1) //UDHI
submit = submit | TPUDHI;
submit = submit | TPSRR;
pdu += submit.toString(16);
pdu += '00'; //TODO: Reference Number;
var receiverSize = ('00'+(parseInt(message.receiver.length, 10).toString(16))).slice(-2);
var receiver = pduParser.swapNibbles(message.receiver);
var receiverType = 81; //TODO: NOT-Hardcoded PDU generation. Please note that Hamrah1 doesnt work if we set it to 91 (International).
pdu += receiverSize.toString(16) + receiverType + receiver;
pdu += '00'; //TODO TP-PID
if(message.encoding === '16bit')
pdu += '08';
else if(message.encoding === '7bit')
pdu += '00';
var pdus = new Array();
var csms = randomHexa(2); // CSMS allows to give a reference to a concatenated message
for(var i=0; i< parts; i++) {
pdus[i] = pdu;
if(message.encoding === '16bit') {
/* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
* for 66 UCS2 characters instead of 70 */
if(parts === 1)
var length = 70;
else
var length = 66;
} else if(message.encoding === '7bit') {
/* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
* for 153 ASCII characters instead of 160 */
if(parts === 1)
var length = 160;
else
var length = 153;
}
var text = message.text.slice(i*length, (i*length)+length);
if(message.encoding === '16bit') {
user_data = pduParser.encode16Bit(text);
var size = (user_data.length / 2);
if(parts > 1)
size += 6; //6 is the number of data headers we append.
} else if(message.encoding === '7bit') {
user_data = pduParser.encode7Bit(text);
var size = user_data.length / 2;
}
pdus[i] += ('00'+parseInt(size).toString(16)).slice(-2);
if(parts > 1) {
pdus[i] += '05';
pdus[i] += '00';
pdus[i] += '03';
pdus[i] += csms;
pdus[i] += ('00'+parts.toString(16)).slice(-2);
pdus[i] += ('00'+(i+1).toString(16)).slice(-2);
}
pdus[i] += user_data;
}
return pdus;
}
pduParser.encode16Bit = function(text) {
var out = '';
for(var i = 0; i<text.length;i++) {
out += ('0000'+(parseInt(text.charCodeAt(i), 10).toString(16))).slice(-4);
}
return out;
}
pduParser.swapNibbles = function(nibbles) {
var out = '';
for(var i = 0; i< nibbles.length; i=i+2) {
if(typeof(nibbles[i+1]) === 'undefined') // Add a trailing F.
out += 'F'+parseInt(nibbles[i], 16).toString(10);
else
out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
}
return out;
}
pduParser.parseStatusReport = function(pdu) {
//Cursor points to the last octet we've read.
var cursor = 0;
var smscSize = parseInt(pdu.slice(0, 2), 16);
cursor += 2;
var smscType = parseInt(pdu.slice(cursor, cursor+2), 16);
cursor += 2;
var smscNum = pduParser.deSwapNibbles(pdu.slice(cursor, (smscSize*2)+2));
cursor = (smscSize*2+2);
var header = parseInt(pdu.slice(cursor,cursor+2));
cursor += 2;
var reference = parseInt(pdu.slice(cursor,cursor+2), 16);
cursor += 2;
var senderSize = parseInt(pdu.slice(cursor,cursor+2), 16);
if(senderSize % 2 === 1)
senderSize++;
cursor += 2;
var senderType = parseInt(pdu.slice(cursor,cursor+2));
cursor += 2;
var sender = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+senderSize));
var status = pdu.slice(-2);
return {
smsc:smscNum,
reference:reference,
sender:sender,
status:status
}
}
function randomHexa(size)
{
var text = "";
var possible = "0123456789ABCDEF";
for( var i=0; i < size; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
class LuciTable{
constructor(){
this.rows = [];
this.tbody;
this.fieldset;
this.init_table();
}
init_table(){
//create a luci fieldset (class cbi-section)
var fieldset = document.createElement('fieldset');
fieldset.className="cbi-section";
//set fieldset Header name
var legend = document.createElement('legend');
var title_span = document.createElement('span');
title_span.className="panel-title"
//init table
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className="table"
//save
this.fieldset = fieldset;
this.tbody = tbody
this.title_span = title_span
this.legend = legend
fieldset.appendChild(legend);
fieldset.appendChild(title_span);
table.appendChild(tbody)
fieldset.appendChild(table)
}
new_tr(data,index){
var type = data.type;
var col = data.col;
var left = data.left;
var right = data.right;
//clear the row
this.rows[index].left.innerHTML = "";
this.rows[index].right.innerHTML = "";
//set the row
this.rows[index].left.appendChild(left);
this.rows[index].right.appendChild(right);
if (right == null || right == "") {
this.rows[index].row.style.display = "none";
}
else{
this.rows[index].row.style.display = "";
}
}
set title(value){
this.legend.innerHTML = value;
this.title_span.innerHTML = value;
}
set object_data(value){
var row_length = this.rows.length;
var value_length = Object.keys(value).length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("td");
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
var index = 0;
for (var key in value) {
this.rows[index].left.innerHTML = key;
this.rows[index].right.innerHTML = value[key];
index++;
}
}
set array_data(value){
var row_length = this.rows.length;
var value_length = value.length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("sms_recv_content")
cell_right.classList.add("td")
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
for (let i = 0; i < value.length; i++) {
this.new_tr(value[i],i);
}
}
set data(value){
if (value == null) {
return;
}
if (Array.isArray(value)) {
this.array_data = value;
}
else{
this.object_data = value;
}
}
}
class ModemSMS {
constructor() {
this.data = null;
this.cfg_id = null;
this.modem_cfg_list = [];
this.sms_recvbox_table = new LuciTable();
this.sms_send_table = new LuciTable();
this.sms_storage_table = new LuciTable();
this.sms_send_table.title = "<%:Send SMS%>";
this.cbi_map = document.querySelector('.cbi-map');
this.cbi_map.appendChild(this.sms_storage_table.fieldset);
this.cbi_map.appendChild(this.sms_recvbox_table.fieldset);
this.cbi_map.appendChild(this.sms_send_table.fieldset);
this.modem_selector = document.getElementById('modem_selector');
this.create_modem_cfg_selector();
this.update_modem_cfg_list();
this.init_send_table_view();
this.init_msg_box();
this.init_sms_storage_table();
}
init_sms_storage_table() {
const createOption = (value, text, disabled = false, selected = false) => {
const opt = document.createElement('option');
opt.value = value;
opt.innerHTML = text;
opt.disabled = disabled;
opt.selected = selected;
return opt;
};
const reading_storage = document.createElement('select');
const writing_storage = document.createElement('select');
const etc_storage = document.createElement('select');
const set_storage_btn = document.createElement('input');
set_storage_btn.type = "button";
set_storage_btn.value = "Set";
set_storage_btn.onclick = () => this.set_sms_storage();
const opt_mt = createOption("ME", "<%: Mobile equipment message storage %>");
const opt_sm = createOption("SM", "<%: (U)SIM message storage %>");
const opt_loading = createOption("Loading", "<%: Loading... %>", true, true);
const storages = [reading_storage, writing_storage, etc_storage];
storages.forEach(storage => {
storage.appendChild(opt_mt.cloneNode(true));
storage.appendChild(opt_sm.cloneNode(true));
storage.appendChild(opt_loading.cloneNode(true));
storage.options[2].selected = true;
});
const data = [
{ "col": 2, "left": document.createTextNode("<%: Reading Storage%>"), "right": reading_storage },
{ "col": 2, "left": document.createTextNode("<%: Writing Storage%>"), "right": writing_storage },
{ "col": 2, "left": document.createTextNode("<%: ETC Storage%>"), "right": etc_storage },
{ "col": 2, "left": document.createTextNode("<%: Set Storage%>"), "right": set_storage_btn }
];
this.sms_storage_table.title = "<%:SMS Storage%>";
this.sms_storage_table.data = data;
this.reading_storage = reading_storage;
this.writing_storage = writing_storage;
this.etc_storage = etc_storage;
this.opt_mt1 = storages[0].querySelector('option[value="ME"]');
this.opt_sm1 = storages[0].querySelector('option[value="SM"]');
this.opt_mt2 = storages[1].querySelector('option[value="ME"]');
this.opt_sm2 = storages[1].querySelector('option[value="SM"]');
this.opt_mt3 = storages[2].querySelector('option[value="ME"]');
this.opt_sm3 = storages[2].querySelector('option[value="SM"]');
}
init_msg_box()
{
var warn_msg_box = document.createElement('div');
warn_msg_box.className = "cbi-section";
var warn_msg = document.createElement('div');
warn_msg.className = "alert";
warn_msg_box.appendChild(warn_msg);
this.cbi_map.appendChild(warn_msg_box);
this.warn_msg_box = warn_msg_box;
//hide
this.warn_msg_box.style.display = "none";
}
warn_msg(msg,timeout){
this.warn_msg_box.style.display = "";
this.warn_msg_box.classList.add("alert-warning");
this.warn_msg_box.firstChild.innerHTML = msg;
setTimeout(()=>{
this.warn_msg_box.style.display = "none";
this.warn_msg_box.classList.remove("alert-warning");
},timeout);
}
log_msg(msg,timeout){
this.warn_msg_box.style.display = "";
this.warn_msg_box.classList.add("alert-info");
this.warn_msg_box.firstChild.innerHTML = msg;
setTimeout(()=>{
this.warn_msg_box.style.display = "none";
this.warn_msg_box.classList.remove("alert-info");
},timeout);
}
create_modem_cfg_selector(){
var selector = document.createElement('select');
selector.addEventListener('change', (event) => {
this.update();
this.cfg_id = event.target.value;
console.log(this.cfg_id);
});
this.modem_selector.appendChild(selector);
this.selector = selector;
this.poll_info();
}
send(){
//if content contain non-ascii char, use raw pdu
var content = this.message_content.value;
var is_ascii = /^[\x00-\x7F]*$/.test(content);
if (is_ascii) {
this.send_raw_pdu();
}
else{
this.send_raw_pdu();
}
}
send_gsm(){
var phone_number = this.phone_number.value;
var message_content = this.message_content.value;
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "send_sms")%>',{
"cfg": this.cfg_id,
"phone_number": phone_number,
"message_content": message_content,
},(x,data)=>{
this.update();
data.result.status == 1 ? this.log_msg("<%:Send SMS Success%>",3000) : this.warn_msg("<%:Send SMS Failed%>",3000);
});
}
send_raw_pdu(){
var pdu = pduParser.generate(
{
text: this.message_content.value,
encoding: "16bit",
receiver: this.phone_number.value,
}
)
//if pdu is array,send first pdu
if (Array.isArray(pdu)) {
pdu = pdu[0];
}
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "send_sms")%>',{
"cfg": this.cfg_id,
"pdu": pdu,
},(x,data)=>{
this.update();
data.result.status == 1 ? this.log_msg("<%:Send SMS Success%>",3000) : this.warn_msg("<%:Send SMS Failed%>",3000);
});
}
set_sms_storage(){
let payload;
let mem1,mem2,mem3;
mem1 = this.reading_storage.value;
mem2 = this.writing_storage.value;
mem3 = this.etc_storage.value;
payload = {
"mem1": mem1,
"mem2": mem2,
"mem3": mem3,
}
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>', {
"cfg": this.cfg_id,
"action":"set_sms_storage",
"params": JSON.stringify(JSON.stringify(payload))
},(x,data)=>{
this.update();
});
}
lock(){
var delete_btns = document.querySelectorAll('input[value="<%:Delete%>"]');
for (let btn of delete_btns) {
console.log(btn);
btn.disabled = true;
}
}
release(){
var delete_btns = document.querySelectorAll('input[value="<%:Delete%>"]');
for (let btn of delete_btns) {
btn.disabled = false;
}
}
init_send_table_view(){
let phone_number,message_content,send_button,send_raw_pdu_button;
phone_number = document.createElement('input');
phone_number.type = "text";
message_content = document.createElement('textarea');
message_content.rows = 5;
message_content.cols = 50;
send_button = document.createElement('input');
send_button.type = "button";
send_button.value = "<%:Send%>";
send_button.addEventListener('click',()=>{
this.send();
});
this.phone_number = phone_number;
this.message_content = message_content;
this.sms_send_table.data = [
{
"col": 2,
"left": document.createTextNode("<%:Phone Number%>"),
"right": phone_number,
},
{
"col": 2,
"left": document.createTextNode("<%:Message Content%>"),
"right": message_content,
},
{
"col": 2,
"left": document.createTextNode("<%:Send%>"),
"right": send_button,
}
];
}
poll_info(){
if (this.cfg_id == null){
return;
}
XHR.poll(10,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_sms")%>',{
"cfg": this.cfg_id,
}, (x,data) => {
this.combine_messages(data);
});
}
update(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_sms")%>',{
"cfg": this.cfg_id,
}, (x,data) => {
this.combine_messages(data);
this.update_sms_capabilities(data);
});
}
update_modem_cfg_list(){
XHR.poll(5,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_modem_cfg")%>',{},(x,data)=>{
var new_cfg_list = [];
var cfgs = data.cfgs;
for (let i = 0; i < cfgs.length; i++) {
var cfg = cfgs[i];
var name = cfg.name;
var value = cfg.cfg;
new_cfg_list.push({"value":value,"name":name});
}
if (new_cfg_list != this.modem_cfg_list) {
this.cfg_options = new_cfg_list;
}
});
}
combine_messages(data){
var messages,reference_table,msgs;
messages = []
reference_table = {}
msgs = data.msg;
for ( let msg of msgs){
let part,total,index,reference,sender,timestamp,content;
if (msg.reference){
reference = `${msg.reference}.${msg.sender}`;
if (reference in reference_table){
reference_table[reference].push(msg);
}
else{
reference_table[reference] = [msg];
}
}
else{
msg.index = [msg.index]
messages.push(msg);
}
}
//combile the messages in reference_table
for (let key in reference_table){
let reference_msgs = reference_table[key];
let total = reference_msgs[0].total;
let part = [];
let content = "";
let sender = reference_msgs[0].sender;
let timestamp = reference_msgs[0].timestamp;
let index = [];
reference_msgs.sort((a,b)=>{
return a.part - b.part;
});
for (let reference_msg of reference_msgs){
content += reference_msg.content;
part.push(reference_msg.part);
index.push(reference_msg.index);
}
messages.push({
"sender":sender,
"timestamp":timestamp,
"content":content,
"part":part,
"total":total,
"index":index,
});
}
messages.sort((a,b)=>{
//filter timestamp space and / :
let at,bt
at = a.timestamp;
bt = b.timestamp;
if (typeof at == "string") {
at = at.replace(/ /g,"");
bt = bt.replace(/ /g,"");
at = at.replace(/\//g,"");
bt = bt.replace(/\//g,"");
at = at.replace(/:/g,"");
bt = bt.replace(/:/g,"");
}
return bt - at;
});
this.view = messages;
}
update_sms_capabilities(data) {
const sms_capabilities = data.sms_capabilities;
const storages = [
{ mem: sms_capabilities.mem1, storage: this.reading_storage, opts: ['opt_mt1', 'opt_sm1'] },
{ mem: sms_capabilities.mem2, storage: this.writing_storage, opts: ['opt_mt2', 'opt_sm2'] },
{ mem: sms_capabilities.mem3, storage: this.etc_storage, opts: ['opt_mt3', 'opt_sm3'] }
];
const updateStorage = (mem, storage, mtOpt, smOpt) => {
let mt = "", sm = "";
if (mem === "MT" || mem === "ME") {
if (storage.value === "Loading") storage.value = "ME";
mt = "[<%:Using%>]";
} else if (mem === "SM") {
if (storage.value === "Loading") storage.value = "SM";
sm = "[<%:Using%>]";
} else {
storage.value = "Loading";
}
this[mtOpt].innerHTML = mt + me_message_text;
this[smOpt].innerHTML = sm + sm_message_text;
};
const me_message_text = sms_capabilities.ME.used
? `<%: Mobile equipment message storage %> <%: (Used/Total) %>(${sms_capabilities.ME.used}/${sms_capabilities.ME.total})`
: "<%: Mobile equipment message storage %>";
const sm_message_text = sms_capabilities.SM.used
? `<%: (U)SIM message storage %> <%: (Used/Total) %>(${sms_capabilities.SM.used}/${sms_capabilities.SM.total})`
: "<%: (U)SIM message storage %>";
storages.forEach(({ mem, storage, opts }) => updateStorage(mem, storage, opts[0], opts[1]));
}
set cfg_options(value){
var longger = this.modem_cfg_list.length > value.length ? this.modem_cfg_list : value;
if (longger.length == 0) {
return;
}
for (let i = 0; i < longger.length; i++) {
var option = this.selector.options[i];
if (i < value.length) {
if (i >= this.selector.options.length) {
option = document.createElement('option');
this.selector.appendChild(option);
}
option.value = value[i].value;
option.innerHTML = value[i].name;
}
else{
this.selector.removeChild(option);
}
}
this.cfg_id = this.selector.value;
this.modem_cfg_list = value;
this.update();
}
set view(data){
this.data = data;
if (data == null) {
return;
}
var enties = []
var msgs = data;
for (let msg of msgs){
let sender,timestamp,content,part,total,index;
sender = msg.sender;
if (typeof(msg.timestamp) == "number") {
timestamp = new Date(msg.timestamp*1000).toISOString()
}
else{
timestamp = msg.timestamp;
}
content = msg.content;
part = msg.part;
total = msg.total;
index = msg.index;
let sender_strong,timestamp_strong,content_strong,part_strong,total_strong,delete_btn;
let left,right;
left = document.createElement('div');
right = document.createElement('div');
delete_btn = document.createElement('input');
delete_btn.type = "button";
delete_btn.value = "<%:Delete%>";
delete_btn.addEventListener('click',()=>{
this.lock();
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "delete_sms")%>',{
"cfg": this.cfg_id,
"index": index.sort((a,b)=>{return b-a}).join(" "),
},(x,data)=>{
this.update();
this.release
});
});
sender_strong = document.createElement('strong');
sender_strong.innerHTML = `<%:Sender%>: ${sender}`;
timestamp_strong = document.createElement('strong');
timestamp_strong.innerHTML = `<%:Timestamp%>: ${timestamp}`;
content_strong = document.createElement('strong');
content_strong.innerHTML = `<%:Content%>: ${content}`;
left.appendChild(sender_strong);
left.appendChild(document.createElement('br'));
left.appendChild(timestamp_strong);
left.appendChild(document.createElement('br'));
left.appendChild(delete_btn);
right.appendChild(content_strong);
if (part != null) {
part_strong = document.createElement('strong');
part_strong.innerHTML = `(${part}/${total})`;
right.appendChild(document.createElement('br'));
right.appendChild(part_strong);
}
enties.push({
"col" : 2,
"left" : left,
"right" : right
});
}
this.sms_recvbox_table.data = enties;
this.sms_recvbox_table.title = "SMS";
}
}
window.onload = function(){
const getSMS = new ModemSMS();
}
</script>
<style>
.sms_recv_content {
text-align: left;
word-wrap: break-word;
white-space: normal;
overflow-wrap: break-word;
}
</style>
<div>
<div class="cbi-map">
<fieldset class="cbi-section">
<table class="table">
<tbody>
<tr class="tr">
<td class="td" width="33%"><%:Modem Name%></td>
<td class="td" id="modem_selector">
</td>
</tr>
</tbody>
</table>
</fieldset>
</div>
</div>
<%+footer%>
|
28softwares/rest-nodejs-starter | 1,968 | src/seeder/admin.seed.ts | import { AppDataSource } from '../config/database.config';
import { Role } from '../constants/appConstant';
import { Admin, AdminPermission } from '../entities/admin/Admin.entity';
import BcryptService from '../utils/bcrypt.util';
const ADMINS = [
{
name: 'Admin',
email: 'admin@gmail.com',
password: 'Admin@123',
role: Role.ADMIN,
phoneNumber: '981111111',
permissions: [AdminPermission.CAROUSEL],
isActive: true,
},
{
name: 'Super Admin',
email: 'superadmin@gmail.com',
password: 'SuperAdmin@123',
role: Role.SUPER_ADMIN,
phoneNumber: '980000099',
isActive: true,
//for superadmin, permission checking is bypassed.; so no need for seeding of permission list.
},
];
const AdminRepo = AppDataSource.getRepository(Admin);
const args = process.argv[2];
if (!args) {
throw new Error('Please provide an argument');
}
// * for seed admin login credentials
const addAdmin = async () => {
for (const i of ADMINS) {
try {
const admin = AdminRepo.create({
...i,
role: i.role,
password: i.password,
});
await AdminRepo.save(admin);
} catch (error: any) {
console.log('Failed to seed admin', error);
return;
}
console.log('Admin seeded successfully');
}
AppDataSource.destroy();
process.exit(0);
};
// * for remove all admin login credentials
const removeAllAdmin = async () => {
try {
await AdminRepo.createQueryBuilder().delete().execute();
} catch (error: any) {
console.log('Failed to delete admin', error);
process.exit(1);
}
console.log('Admin remove successfully');
AppDataSource.destroy();
process.exit(0);
};
AppDataSource.initialize()
.then(() => {
if (args === 'add') {
addAdmin();
} else if (args === 'remove') {
removeAllAdmin();
} else {
console.log('Please provide an argument');
}
})
.catch((err) => {
console.log(err);
process.exit(1);
});
|
28softwares/rest-nodejs-starter | 2,162 | src/entities/user/user.entity.ts | import {
AfterInsert,
AfterLoad,
AfterUpdate,
BeforeInsert,
BeforeUpdate,
Column,
Entity,
OneToMany,
OneToOne,
} from 'typeorm';
import { CommonEntity } from '../common/common.entity';
import { MediaType, UserLoginType } from '../../constants/appConstant';
import { Token } from '../token/Token.entity';
import { migrateMedia } from '../../utils/media/migrateMedia';
import { DotenvConfig } from '../../config/env.config';
import BcryptService from '../../utils/bcrypt.util';
import { UserDetail } from './UserDetail.entity';
@Entity({
name: 'user',
})
export class User extends CommonEntity {
@Column({
type: 'varchar',
length: 255,
nullable: false,
})
fullName: string;
@Column({
name: 'email',
type: 'varchar',
length: 255,
nullable: false,
})
email: string;
@Column({
name: 'password',
type: 'text',
nullable: false,
select: false,
})
password: string;
@Column({
name: 'phone',
type: 'varchar',
length: 255,
nullable: true, //for google auth it could be null
})
phone?: string;
@Column({
name: 'is_verified',
type: 'boolean',
default: false,
nullable: false,
})
isVerified: boolean;
@Column({
type: 'enum',
enum: UserLoginType,
default: UserLoginType.TRADITIONAL,
})
loginType: UserLoginType;
@OneToOne(() => UserDetail, (detail) => detail.user)
userDetails: UserDetail;
@OneToMany(() => Token, (token) => token.user)
token: Token;
@AfterInsert()
@AfterUpdate()
async migrateMedia() {
console.log('this', this);
//migrate thumbnail
if (this.userDetails?.profileImage) {
await migrateMedia(
MediaType.PROFILE_IMAGE,
this.userDetails.profileImage.name,
this.id,
);
}
}
@AfterLoad()
async appendMediaPath() {
if (this.userDetails?.profileImage) {
this.userDetails.profileImage.path = `${DotenvConfig.BASE_URL}/user/${this.id}/${this.userDetails.profileImage?.name}`;
}
}
@BeforeInsert()
@BeforeUpdate()
async hashPassword() {
if (this.password) this.password = await BcryptService.hash(this.password);
}
}
|
281677160/openwrt-package | 5,451 | luci-app-qmodem/luci/luci-app-qmodem-sms/luasrc/model/cbi/qmodem_sms/sms_forward_extedit.lua | local uci = require "luci.model.uci".cursor()
local dispatcher = require "luci.dispatcher"
local fs = require "nixio.fs"
local json = require "luci.jsonc"
m = Map("sms_daemon", translate("SMS Forward Advanced Configuration"))
m.redirect = dispatcher.build_url("admin", "modem", "qmodem", "sms_forward")
-- 添加说明信息
m.description = translate("Advanced SMS Forward configuration with type-specific options.")
-- SMS转发实例配置
s2 = m:section(NamedSection, arg[1], "sms_forward_instance",translate("SMS Forward Instances"))
s2.addremove = true
s2.anonymous = false
-- 实例启用开关
instance_enable = s2:option(Flag, "enable", translate("Enable"))
instance_enable.default = "0"
-- 监听端口
listen_port = s2:option(ListValue, "listen_port", translate("Modem Port"))
listen_port.rmempty = false
-- 获取可用的AT端口
uci:foreach("qmodem", "modem-device", function(section)
local ports = section.ports or {}
local valid_ports = section.valid_at_ports or {}
if type(ports) == "table" then
for _, port in ipairs(ports) do
local valid = false
if type(valid_ports) == "table" then
for _, valid_port in ipairs(valid_ports) do
if port == valid_port then
valid = true
break
end
end
end
local display_name = port
if valid then
display_name = port .. " (" .. translate("VALID") .. ")"
else
display_name = port .. " (" .. translate("INVALID") .. ")"
end
listen_port:value(port, display_name)
end
end
end)
-- 如果没有找到端口,添加常见的端口选项
if next(listen_port.keylist) == nil then
for i = 0, 7 do
listen_port:value("/dev/ttyUSB" .. i, "/dev/ttyUSB" .. i)
end
for i = 0, 3 do
listen_port:value("/dev/ttyACM" .. i, "/dev/ttyACM" .. i)
end
end
-- 轮询间隔
poll_interval = s2:option(Value, "poll_interval", translate("Poll Interval"))
poll_interval.datatype = "range(15,600)"
poll_interval.default = "30"
poll_interval.description = translate("Polling interval in seconds (15-600)")
-- API类型
api_type = s2:option(ListValue, "api_type", translate("API Type"))
api_type:value("tgbot", translate("Telegram Bot"))
api_type:value("webhook", translate("Webhook"))
api_type:value("serverchan", translate("ServerChan"))
api_type:value("pushdeer", translate("PushDeer"))
api_type:value("custom_script", translate("Custom Script"))
-- 删除已转发短信选项
delete_after_forward = s2:option(Flag, "delete_after_forward", translate("Delete After Forward"))
delete_after_forward.default = "0"
delete_after_forward.description = translate("Delete SMS messages from modem after successful forwarding. This helps keep the modem's SMS storage clean but messages will be permanently removed.")
-- Telegram Bot 配置
tg_bot_token = s2:option(Value, "tg_bot_token", translate("Bot Token"))
tg_bot_token:depends("api_type", "tgbot")
tg_bot_token.placeholder = "123456:ABC-DEF1234ghIkl"
tg_chat_id = s2:option(Value, "tg_chat_id", translate("Chat ID"))
tg_chat_id:depends("api_type", "tgbot")
tg_chat_id.placeholder = "123456789"
-- Webhook 配置
webhook_url = s2:option(Value, "webhook_url", translate("Webhook URL"))
webhook_url:depends("api_type", "webhook")
webhook_url.placeholder = "https://example.com/webhook"
webhook_headers = s2:option(Value, "webhook_headers", translate("Headers (optional)"))
webhook_headers:depends("api_type", "webhook")
webhook_headers.placeholder = "Authorization: Bearer token"
-- ServerChan 配置
serverchan_token = s2:option(Value, "serverchan_token", translate("Token"))
serverchan_token:depends("api_type", "serverchan")
serverchan_token.placeholder = "SCT123456TCxyz..."
serverchan_token.description = translate("ServerChan API token from https://sctapi.ftqq.com")
serverchan_channel = s2:option(Value, "serverchan_channel", translate("Channel (optional)"))
serverchan_channel:depends("api_type", "serverchan")
serverchan_channel.placeholder = "9|66"
serverchan_channel.description = translate("Message channel, use | to separate multiple channels")
serverchan_noip = s2:option(Flag, "serverchan_noip", translate("Hide IP"))
serverchan_noip:depends("api_type", "serverchan")
serverchan_noip.description = translate("Hide caller IP address")
serverchan_openid = s2:option(Value, "serverchan_openid", translate("OpenID (optional)"))
serverchan_openid:depends("api_type", "serverchan")
serverchan_openid.placeholder = "openid1,openid2"
serverchan_openid.description = translate("OpenID for message forwarding, use comma to separate multiple IDs")
-- PushDeer 配置
pushdeer_push_key = s2:option(Value, "pushdeer_push_key", translate("Push Key"))
pushdeer_push_key:depends("api_type", "pushdeer")
pushdeer_push_key.placeholder = "PDU123456T..."
pushdeer_push_key.description = translate("PushDeer Push Key from http://pushdeer.com")
pushdeer_endpoint = s2:option(Value, "pushdeer_endpoint", translate("API Endpoint (optional)"))
pushdeer_endpoint:depends("api_type", "pushdeer")
pushdeer_endpoint.placeholder = "https://api2.pushdeer.com"
pushdeer_endpoint.description = translate("Custom PushDeer API endpoint, leave empty to use default")
-- Custom Script 配置
custom_script_path = s2:option(Value, "custom_script_path", translate("Script Path"))
custom_script_path:depends("api_type", "custom_script")
custom_script_path.placeholder = "/usr/bin/my_sms_script.sh"
return m
|
281677160/openwrt-package | 4,782 | luci-app-qmodem/luci/luci-app-qmodem-sms/luasrc/model/cbi/qmodem_sms/sms_forward.lua | local uci = require "luci.model.uci".cursor()
local dispatcher = require "luci.dispatcher"
local fs = require "nixio.fs"
m = Map("sms_daemon", translate("SMS Forward Configuration"))
m.redirect = dispatcher.build_url("admin", "modem", "qmodem", "sms_forward")
-- 添加说明信息
m.description = translate("SMS Forward Daemon allows automatic forwarding of SMS messages to various APIs.")
-- 检查sms_forwarder守护进程是否存在
local daemon_exists = fs.access("/usr/bin/sms_forwarder")
if not daemon_exists then
s_warning = m:section(SimpleSection)
s_warning.template = "cbi/nullsection"
local warning_html = "<div class='alert-message warning'>" ..
"<strong>" .. translate("Warning") .. ":</strong> " ..
translate("SMS Forwarder binary not found at /usr/bin/sms_forwarder. Please install the sms_forwarder package.") ..
"</div>"
s_warning.render = function(self, section)
return warning_html
end
end
-- SMS转发总开关
s = m:section(NamedSection, "sms_forward", "sms_forward", translate("SMS Forward Service"))
s.addremove = false
enable = s:option(Flag, "enable", translate("Enable SMS Forward Service"))
enable.default = "0"
enable.rmempty = false
enable.description = translate("Enable the SMS forward daemon service. When enabled, the daemon will start automatically.")
-- 全局配置选项
log_level = s:option(ListValue, "log_level", translate("Log Level"))
log_level:value("error", translate("Error"))
log_level:value("warning", translate("Warning"))
log_level:value("info", translate("Information"))
log_level:value("debug", translate("Debug"))
log_level.default = "info"
log_level.description = translate("Set the logging verbosity level for the SMS daemon.")
-- SMS转发实例配置
s2 = m:section(TypedSection, "sms_forward_instance", translate("SMS Forward Instances"))
s2.addremove = true
s2.anonymous = false
s2.template = "cbi/tblsection"
s2.extedit = dispatcher.build_url("admin", "modem", "qmodem", "sms_forward_extedit", "%s")
s2.description = translate("Configure multiple SMS forward instances. Each instance can monitor a different modem port and forward to different APIs.")
-- 实例启用开关
instance_enable = s2:option(Flag, "enable", translate("Enable"))
instance_enable.width = "8%"
instance_enable.default = "0"
-- 监听端口
listen_port = s2:option(ListValue, "listen_port", translate("Modem Port"))
listen_port.width = "18%"
listen_port.rmempty = false
-- 获取可用的AT端口
uci:foreach("qmodem", "modem-device", function(section)
local ports = section.ports or {}
local valid_ports = section.valid_at_ports or {}
if type(ports) == "table" then
for _, port in ipairs(ports) do
local valid = false
if type(valid_ports) == "table" then
for _, valid_port in ipairs(valid_ports) do
if port == valid_port then
valid = true
break
end
end
end
local display_name = port
if valid then
display_name = port .. " (" .. translate("VALID") .. ")"
else
display_name = port .. " (" .. translate("INVALID") .. ")"
end
listen_port:value(port, display_name)
end
end
end)
-- 如果没有找到端口,添加常见的端口选项
if next(listen_port.keylist) == nil then
for i = 0, 7 do
listen_port:value("/dev/ttyUSB" .. i, "/dev/ttyUSB" .. i)
end
for i = 0, 3 do
listen_port:value("/dev/ttyACM" .. i, "/dev/ttyACM" .. i)
end
end
-- 轮询间隔
poll_interval = s2:option(Value, "poll_interval", translate("Poll Interval"))
poll_interval.width = "12%"
poll_interval.datatype = "range(15,600)"
poll_interval.default = "30"
poll_interval.description = translate("Polling interval in seconds (15-600)")
-- API类型
api_type = s2:option(ListValue, "api_type", translate("API Type"))
api_type.width = "15%"
api_type:value("tgbot", translate("Telegram Bot"))
api_type:value("webhook", translate("Webhook"))
api_type:value("serverchan", translate("ServerChan"))
api_type:value("pushdeer", translate("PushDeer"))
api_type:value("custom_script", translate("Custom Script"))
-- 删除已转发短信选项
delete_after_forward = s2:option(Flag, "delete_after_forward", translate("Delete After Forward"))
delete_after_forward.width = "12%"
delete_after_forward.default = "0"
delete_after_forward.description = translate("Delete SMS messages from modem after successful forwarding")
if fs.stat("/tmp/sms_forwarder_combined.json") then
--读取 /tmp/sms_forwarder_combined.json 的内容并展示(只读)
c = s:option(TextValue, "_c", translate("SMS Forwarder Configuration"))
c.readonly = true
c.rows = 15
v = fs.readfile("/tmp/sms_forwarder_combined.json")
c.cfgvalue = function()
return v
end
end
return m
|
28softwares/rest-nodejs-starter | 1,360 | src/entities/admin/Admin.entity.ts | import { BeforeInsert, BeforeUpdate, Column, Entity, OneToMany } from 'typeorm';
import { Role } from '../../constants/appConstant';
import { CommonEntity } from '../common/common.entity';
import { Token } from '../token/Token.entity';
import BcryptService from '../../utils/bcrypt.util';
import { Log } from '../log/Log.entity';
export enum AdminPermission {
'CAROUSEL' = 'CAROUSEL',
'PRODUCT' = 'PRODUCT',
'USERS' = 'USERS',
'ORDERS' = 'ORDERS',
'LOGS' = 'LOGS',
}
@Entity({
name: 'admin',
})
export class Admin extends CommonEntity {
@Column({
name: 'name',
})
name: string;
@Column({
name: 'email',
})
email: string;
@Column({
name: 'password',
select: false,
})
password: string;
@Column({ type: 'simple-array', default: [] })
permissions: AdminPermission[];
@Column({
name: 'phone_number',
nullable: true,
})
phoneNumber: string;
@Column({ type: 'boolean', default: true })
isActive: boolean;
@Column({
name: 'role',
type: 'enum',
enum: Role,
default: Role.ADMIN,
})
role: Role;
@OneToMany(() => Token, (token) => token.admin)
token: Token;
@OneToMany(() => Log, (log) => log.actionBy)
logs: Log[];
@BeforeInsert()
@BeforeUpdate()
async hashPassword() {
if (this.password) this.password = await BcryptService.hash(this.password);
}
}
|
28softwares/rest-nodejs-starter | 1,236 | src/entities/media/media.entity.ts | import { BeforeRemove, Column, Entity, ManyToOne, OneToOne } from 'typeorm';
import { CommonEntity } from '../common/common.entity';
import { UserDetail } from '../user/UserDetail.entity';
import { MediaType } from '../../constants/appConstant';
import { deleteFile } from '../../utils/media/migrateMedia';
import { PathUtil } from '../../utils/media/mediaPath';
@Entity()
export class Media extends CommonEntity {
@Column({ name: 'mime_type' })
mimeType: string;
@Column({ name: 'file_name' })
name: string; //it holds file name later we will append full image path
@Column({
enum: MediaType,
type: 'enum',
})
mediaType: MediaType;
path: string | undefined;
@Column({ type: 'boolean', default: false })
isThumbnail: boolean;
@OneToOne(() => UserDetail, (detail) => detail.profileImage, {
onDelete: 'CASCADE',
})
userDetail: UserDetail;
@BeforeRemove()
async deleteFile() {
switch (this.mediaType) {
case MediaType.BLOG_THUMBNAIL:
console.log('Blog Thumbnail');
console.log(PathUtil.generateMediaPathForBlog(this.id) + this.name);
await deleteFile(
PathUtil.generateMediaPathForBlog(this.id) + this.name,
);
break;
}
}
}
|
28softwares/rest-nodejs-starter | 2,467 | src/controllers/media/media.controller.ts | import express from 'express';
import {
Controller,
FormField,
Post,
Route,
Request,
UploadedFile,
} from 'tsoa';
import path from 'path';
import fs from 'fs';
import mediaService from '../../services/media/media.service';
import { DotenvConfig } from '../../config/env.config';
import { MediaType } from '../../constants/appConstant';
@Route('media')
class MediaController extends Controller {
@Post('/')
async upload(
@Request() req: express.Request,
@UploadedFile() file: Express.Multer.File,
@FormField() mediaType: string,
) {
//enum => array. (values)
const validMediaTypeList = Object.values(MediaType);
if (!validMediaTypeList.includes(mediaType as MediaType)) {
return {
status: 'error',
message: 'Invalid Media Type',
};
}
const validateResponse = this.validate(mediaType as MediaType, file);
if (validateResponse !== true) return validateResponse;
// upload.
//generate file name;
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
const ext = path.extname(file.originalname);
const updatedFileName = uniqueSuffix + ext;
if (!fs.existsSync(DotenvConfig.TEMP_FOLDER_PATH)) {
fs.mkdirSync(DotenvConfig.TEMP_FOLDER_PATH);
}
fs.writeFileSync(
path.resolve(DotenvConfig.TEMP_FOLDER_PATH, updatedFileName),
file.buffer,
);
const res = await mediaService.uploadSingle(
mediaType as MediaType,
file.mimetype,
updatedFileName,
);
return res;
}
//
private validate(mediaType: MediaType, file: Express.Multer.File) {
let acceptedExtensions: string[] = [];
let fileSize: number = 0;
//
switch (mediaType) {
case MediaType.PROFILE_IMAGE:
acceptedExtensions = ['.jpeg', '.png'];
fileSize = 1024 * 1024 * 1; // 1MB
break;
default:
}
//extension validation.
if (!acceptedExtensions.includes(path.extname(file.originalname))) {
return {
status: 'error',
message:
'File extension not supported. Supported extensions are : ' +
acceptedExtensions.toString(),
};
}
//fileSize validation.
if (file.size > fileSize) {
return {
status: 'error',
message:
'File size exceeded. Maximum size is : ' +
fileSize / (1024 * 1024) +
' MB',
};
}
return true;
}
}
export { MediaController };
|
281677160/openwrt-package | 3,627 | luci-app-qmodem/luci/luci-app-qmodem-sms/po/zh_Hans/modem_sms.po | #modem_sms.htm
msgid "Sender"
msgstr "发信人"
msgid "Timestamp"
msgstr "时间戳"
msgid "Content"
msgstr "内容"
msgid "Send SMS"
msgstr "发送短信"
msgid "Send"
msgstr "发送"
msgid "Delete"
msgstr "删除"
msgid "SMS"
msgstr "短信"
msgid "Message Content"
msgstr "短信内容"
msgid "Phone Number"
msgstr "电话号码"
msgid "Send SMS Failed"
msgstr "发送短信失败"
msgid "Send SMS Success"
msgstr "发送短信成功"
msgid "SMS Storage"
msgstr "短信存储"
msgid "Set Storage"
msgstr "设置存储"
msgid "ETC Storage"
msgstr "ETC存储"
msgid "Writing Storage"
msgstr "写入存储"
msgid "Reading Storage"
msgstr "读取存储"
msgid "Loading..."
msgstr "加载中..."
msgid "(U)SIM message storage"
msgstr "(U)SIM短信存储"
msgid "Mobile equipment message storage"
msgstr "移动设备短信存储"
msgid "Using"
msgstr "使用中"
msgid "(Used/Total)"
msgstr "(已用/总可用)"
msgid "Set"
msgstr "设置"
msgid "SMS Forward"
msgstr "短信转发"
msgid "SMS Forward Configuration"
msgstr "短信转发配置"
msgid "SMS Forward Service"
msgstr "短信转发服务"
msgid "Enable SMS Forward Service"
msgstr "启用短信转发服务"
msgid "SMS Forward Instances"
msgstr "短信转发实例"
msgid "Instance Name"
msgstr "实例名称"
msgid "Listen Port"
msgstr "监听端口"
msgid "Poll Interval (seconds)"
msgstr "轮询间隔(秒)"
msgid "Minimum 15 seconds, maximum 10 minutes"
msgstr "最少15秒,最多10分钟"
msgid "Forward API Type"
msgstr "转发API类型"
msgid "API Configuration"
msgstr "API配置"
msgid "ServerChat"
msgstr "ServerChat"
msgid "Telegram Bot"
msgstr "Telegram机器人"
msgid "Generic Webhook"
msgstr "通用Webhook"
msgid "Custom Script"
msgstr "自定义脚本"
msgid "PushDeer"
msgstr "PushDeer"
msgid "Push Key"
msgstr "推送密钥"
msgid "Delete After Forward"
msgstr "转发后删除"
msgid "Delete SMS messages from modem after successful forwarding"
msgstr "转发成功后从调制解调器中删除短信"
msgid "Delete SMS messages from modem after successful forwarding. This helps keep the modem's SMS storage clean but messages will be permanently removed."
msgstr "转发成功后从调制解调器中删除短信。这有助于保持调制解调器的短信存储空间整洁,但短信将被永久删除。"
msgid "PushDeer Push Key from http://pushdeer.com"
msgstr "从 http://pushdeer.com 获取的推送密钥"
msgid "API Endpoint (optional)"
msgstr "API接口地址(可选)"
msgid "Custom PushDeer API endpoint, leave empty to use default"
msgstr "自定义PushDeer API接口地址,留空使用默认地址"
msgid "JSON format configuration. Examples:<br/>"
msgstr "JSON格式配置。示例:<br/>"
msgid "Recommended to enable for SMS forwarding service and better AT command performance."
msgstr "推荐启用以获得更好的短信转发服务和AT命令性能。"
msgid "SMS Forward Service Status"
msgstr "短信转发服务状态"
msgid "Current Status"
msgstr "当前状态"
msgid "Running"
msgstr "运行中"
msgid "Stopped"
msgstr "已停止"
msgid "Loading..."
msgstr "加载中..."
msgid "Start Service"
msgstr "启动服务"
msgid "Stop Service"
msgstr "停止服务"
msgid "Restart Service"
msgstr "重启服务"
msgid "Enable the SMS forward daemon service. When enabled, the daemon will start automatically."
msgstr "启用短信转发守护进程服务。启用后,守护进程将自动启动。"
msgid "Log Level"
msgstr "日志级别"
msgid "Set the logging verbosity level for the SMS daemon."
msgstr "设置短信守护进程的日志详细级别。"
msgid "Configure multiple SMS forward instances. Each instance can monitor a different modem port and forward to different APIs."
msgstr "配置多个短信转发实例。每个实例可以监控不同的调制解调器端口并转发到不同的API。"
msgid "Enable"
msgstr "启用"
msgid "Modem Port"
msgstr "调制解调器端口"
msgid "Poll Interval"
msgstr "轮询间隔"
msgid "API Type"
msgstr "API类型"
msgid "Polling interval in seconds (15-600)"
msgstr "轮询间隔(秒)(15-600)"
msgid "SMS Forward Advanced Configuration"
msgstr "短信转发高级配置"
msgid "Advanced SMS Forward configuration with type-specific options."
msgstr "具有特定类型选项的高级短信转发配置。"
msgid "SMS Forwarder Configuration"
msgstr "短信转发器配置"
msgid "SMS Forward Daemon allows automatic forwarding of SMS messages to various APIs."
msgstr "短信转发器允许自动将短信转发到各种API。"
|
28softwares/rest-nodejs-starter | 3,269 | src/utils/media/migrateMedia.ts | // migrate media from temp to uploads dir
import { Path } from 'tsoa';
import { MediaType } from '../../constants/appConstant';
import { PathUtil } from './mediaPath';
import fs from 'fs-extra';
export const deleteFile = async (path: string) => {
if (fs.existsSync(path)) {
await fs.unlink(path, () => {
console.log('file deleted');
});
}
};
export const checkCreateDir = (path: string) => {
if (!fs.existsSync(path)) {
fs.mkdirSync(path, { recursive: true });
//enable all permission
fs.chmodSync(path, 0o777);
}
};
/**
*
* @param mediaType type of media (eg. PRODUCT_IMAGE, STORE_IMAGE)
* @param fileName name of file )( name of media)
* @param id //whose media is this, (like product, store)
*/
export const migrateMedia = async (
mediaType: MediaType,
fileName: string,
id: string,
) => {
switch (mediaType) {
case MediaType.STORE_LOGO: {
const storeGeneratedPath = PathUtil.generateMediaPathForStore(id);
checkCreateDir(storeGeneratedPath);
//migrate store media
fs.move(
`${storeGeneratedPath}/${fileName}`,
`${storeGeneratedPath}/${fileName}`,
(err) => {
if (err) {
console.log('Error while moving file', err);
}
},
);
break;
}
case MediaType.PRODUCT_IMAGE: {
const productGeneratedPath = PathUtil.generateMediaPathForProduct(id);
checkCreateDir(productGeneratedPath);
//migrate store media
fs.move(
`${PathUtil.TEMP_FOLDER_PATH}/${fileName}`,
`${productGeneratedPath}/${fileName}`,
(err) => {
if (err) {
console.log('Error while moving file', err);
}
},
);
break;
}
case MediaType.PROFILE_IMAGE: {
const profileGeneratedPath = PathUtil.generateMediaPathForProfile(id);
checkCreateDir(profileGeneratedPath);
//migrate user media
console.log('fileName', fileName);
console.log(`${PathUtil.TEMP_FOLDER_PATH}/${fileName}`);
console.log(`${profileGeneratedPath}/${fileName}`);
fs.move(
`${PathUtil.TEMP_FOLDER_PATH}/${fileName}`,
`${profileGeneratedPath}/${fileName}`,
(err) => {
if (err) {
console.log('Error while moving file', err);
}
},
);
break;
}
case MediaType.CAROUSEL_IMAGE: {
const carouselImagePath = PathUtil.generateMediaPathForCrousel(id);
checkCreateDir(carouselImagePath);
//migrate crousel image
fs.move(
`${PathUtil.TEMP_FOLDER_PATH}/${fileName}`,
`${carouselImagePath}/${fileName}`,
(err) => {
if (err) {
console.log('Error while moving file', err);
}
},
);
break;
}
case MediaType.BLOG_THUMBNAIL: {
const blogThumbnailPath = PathUtil.generateMediaPathForBlog(id);
checkCreateDir(blogThumbnailPath);
//migrate blog thumbnail
fs.move(
`${PathUtil.TEMP_FOLDER_PATH}/${fileName}`,
`${blogThumbnailPath}/${fileName}`,
(err) => {
if (err) {
console.log('Error while moving file', err);
}
},
);
break;
}
default:
break;
}
};
|
28softwares/rest-nodejs-starter | 1,549 | src/utils/media/mediaValidation.ts | import { MediaType } from '../../constants/appConstant';
import { AppError } from '../appError.util';
class MediaValidate {
constructor(private error = AppError) {}
validate(fileLength: number, memetype: string, mediaType: MediaType) {
let acceptedExtensions: string[] = [];
let acceptedFileSize: number = 0;
switch (mediaType) {
case MediaType.PRODUCT_IMAGE:
case MediaType.CAROUSEL_IMAGE:
acceptedExtensions = ['image/png', 'image/jpg', 'image/jpeg'];
acceptedFileSize = 1024 * 1024 * 2; // 2 MB
break;
case MediaType.STORE_LOGO:
acceptedExtensions = ['image/png', 'image/jpg', 'image/jpeg'];
acceptedFileSize = 1024 * 1024 * 1; // 1 MB
break;
case MediaType.PROFILE_IMAGE:
acceptedExtensions = ['image/png', 'image/jpg', 'image/jpeg'];
acceptedFileSize = 1024 * 1024 * 1; // 1 MB
break;
case MediaType.BLOG_THUMBNAIL:
acceptedExtensions = ['image/png', 'image/jpg', 'image/jpeg'];
acceptedFileSize = 1024 * 1024 * 1; // 1 MB
break;
}
if (!acceptedExtensions.includes(memetype)) {
throw this.error.badRequest(
'Invalid file extension. Allowed extensions are : ' +
acceptedExtensions.toString(),
);
}
if (fileLength > acceptedFileSize) {
throw AppError.badRequest(
'File size exceed. Its limit is : ' +
acceptedFileSize / (1024 * 1024) +
' MB',
);
}
return true;
}
}
export default new MediaValidate();
|
281677160/openwrt-package | 14,903 | luci-app-qmodem/application/qmodem/files/usr/lib/lua/luci/view/admin_status/index/modem_overview.htm | <style type="text/css">
#warning_message_box {
margin: 1rem;
padding: 1rem;
height: auto;
}
.table {
display: table;
}
.compat-progressbar {
border: 1px solid var(--border-color-high,var(--progressbarColor,var(--background-color)));
border-radius: 3px;
position: relative;
min-width: 170px;
height: 8px;
margin: 1.4em 0 4px 0;
background: var(--background-color-medium,var(--progressbarColor));
}
.compat-progressbar > div {
background: var(--progressbar, var(--primary, var(--primary-color-medium)));
height: 100%;
transition: width .25s ease-in;
width: 0%;
border-radius: 2px;
}
.compat-progressbar::before {
position: absolute;
top: -1.4em;
left: 0;
content: attr(title);
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<script>
function hasCssClass(className) {
// 获取所有样式表
const styleSheets = document.styleSheets;
// 遍历每个样式表
for (let i = 0; i < styleSheets.length; i++) {
const rules = styleSheets[i].cssRules || styleSheets[i].rules; // 兼容不同浏览器
// 遍历每个样式规则
for (let j = 0; j < rules.length; j++) {
if (rules[j].selectorText && rules[j].selectorText.includes(className)) {
return true; // 找到定义,返回 true
}
}
}
return false; // 没有找到定义,返回 false
}
const progressbar_className = hasCssClass('.cbi-progressbar') ? 'cbi-progressbar' : 'compat-progressbar';
class LuciTable{
constructor(){
this.rows = [];
this.tbody;
this.fieldset;
this.init_table();
}
init_table(){
//create a luci fieldset (class cbi-section)
var fieldset = document.createElement('fieldset');
fieldset.className="cbi-section";
//set fieldset Header name
var legend = document.createElement('legend');
var title_span = document.createElement('h2');
title_span.className="panel-title"
//init table
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className="table"
//save
this.fieldset = fieldset;
this.tbody = tbody
this.title_span = title_span
this.legend = legend
fieldset.appendChild(legend);
fieldset.appendChild(title_span);
table.appendChild(tbody)
fieldset.appendChild(table)
}
new_tr(data,index){
var type = data.type;
switch(type){
case "plain_text":
var key,value,full_name;
key = data.key;
value = data.value;
full_name = data.full_name ? data.full_name : key;
this.rows[index].left.innerHTML = full_name;
this.rows[index].right.innerHTML = value;
if (value == null || value == "") {
this.rows[index].row.style.display = "none";
}
else{
this.rows[index].row.style.display = "";
}
break;
case "progress_bar":
var key,title,min,max,precentage,full_name;
key = data.key;
full_name = data.full_name ? data.full_name : key;
title = `(${data.value}/${data.max_value}${data.unit})`
min = data.min_value;
max = data.max_value;
precentage = (data.value - min) / (max - min) * 100;
this.rows[index].left.innerHTML = full_name;
var progress_bar = document.createElement('div')
progress_bar.className = progressbar_className
progress_bar.title = title;
var progress_bar_bar = document.createElement('div')
progress_bar_bar.setAttribute("style","width:"+precentage+"%")
progress_bar.appendChild(progress_bar_bar)
this.rows[index].right.innerHTML = ""
this.rows[index].right.appendChild(progress_bar)
break;
}
}
set title(value){
this.legend.innerHTML = value;
this.title_span.innerHTML = value;
}
set object_data(value){
var row_length = this.rows.length;
var value_length = Object.keys(value).length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("td")
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
var index = 0;
for (var key in value) {
this.rows[index].left.innerHTML = key;
this.rows[index].right.innerHTML = value[key];
index++;
}
}
set array_data(value){
var row_length = this.rows.length;
var value_length = value.length;
if (row_length < value_length) {
for ( let i = row_length; i < value_length; i++) {
let row = document.createElement('tr');
row.className = "tr"
let cell_left = document.createElement('td');
cell_left.classList.add("td")
cell_left.setAttribute("width","33%")
let cell_right = document.createElement('td');
cell_right.classList.add("td")
row.appendChild(cell_left);
row.appendChild(cell_right);
this.tbody.appendChild(row);
var row_dict = {
"row":row,
"left":cell_left,
"right":cell_right,
}
this.rows.push(row_dict);
}
}
else if(row_length > value_length){
for (let i = value_length; i < row_length; i++) {
this.tbody.removeChild(this.rows[i].row);
}
this.rows = this.rows.slice(0,value_length);
}
for (let i = 0; i < value.length; i++) {
this.new_tr(value[i],i);
}
}
set data(value){
if (value == null) {
return;
}
if (Array.isArray(value)) {
this.array_data = value;
}
else{
this.object_data = value;
}
}
}
class ModemInfo {
constructor(cfg_id) {
this.data = null;
this.cfg_id = null;
this.modem_cfg_list = [];
this.tables = {};
this.cbi_map = document.getElementById("modem_" + cfg_id)
this.init_warning_message_box();
this.cfg_id = cfg_id;
}
init_warning_message_box()
{
var warning_message_box,title,message_box;
warning_message_box = document.createElement('div');
warning_message_box.className = "alert-message alert-danger";
warning_message_box.id = "warning_message_box";
title=document.createElement('strong');
title.innerHTML = "<%:Warning!%>";
message_box=document.createElement('div');
message_box.id = "warning_message";
warning_message_box.style.display = "none";
warning_message_box.appendChild(title);
warning_message_box.appendChild(message_box);
this.cbi_map.appendChild(warning_message_box);
this.message_box = message_box;
this.warning_message_box = warning_message_box;
}
warning_message(node_list)
{
this.warning_message_box.style.display = "";
this.message_box.innerHTML = ""
this.message_box.appendChild(node_list);
}
hide_warning_message()
{
this.warning_message_box.style.display = "none";
}
poll_info(){
if (this.cfg_id == null){
return;
}
XHR.poll(10,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',{
"cfg": this.cfg_id,
"action": "info",
"translate": "1"
}, (x,data) => {
this.view = data;
});
}
update(){
XHR.get('<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "modem_ctrl")%>',{
"cfg": this.cfg_id,
"action": "info",
"translate": "1"
}, (x,data) => {
this.view = data;
});
}
update_modem_cfg_list(){
XHR.poll(5,'<%=luci.dispatcher.build_url("admin", "modem", "qmodem", "get_modem_cfg")%>',{},(x,data)=>{
var new_cfg_list = [];
var cfgs = data.cfgs;
for (let i = 0; i < cfgs.length; i++) {
var cfg = cfgs[i];
var name = cfg.name;
var value = cfg.cfg;
new_cfg_list.push({"value":value,"name":name});
}
if (new_cfg_list != this.modem_cfg_list) {
this.cfg_options = new_cfg_list;
}
});
}
set cfg_options(value){
var longger = this.modem_cfg_list.length > value.length ? this.modem_cfg_list : value;
if (longger.length == 0) {
return;
}
for (let i = 0; i < longger.length; i++) {
var option = this.selector.options[i];
if (i < value.length) {
if (i >= this.selector.options.length) {
option = document.createElement('option');
this.selector.appendChild(option);
}
option.value = value[i].value;
option.innerHTML = value[i].name;
}
else{
this.selector.removeChild(option);
}
}
this.cfg_id = this.selector.value;
this.modem_cfg_list = value;
this.update();
}
set view(data){
this.data = data;
if (data == null) {
return;
}
var keys = []
var tables_map = {}
var warning_message = [];
for (let entry of data){
let class_name,class_no_translate,full_name,value,type;
class_no_translate = entry.class_origin;
class_name = this.cfg_id + " <%:Base Information%>";
if (entry.type == "warning_message") {
continue;
}
if (class_no_translate != "Base Information" && entry.type != "progress_bar"){
continue
}
if (tables_map[class_name] == null) {
tables_map[class_name] = []
}
tables_map[class_name].push(entry);
}
for (let class_name in tables_map) {
if (this.tables[class_name] == null) {
this.tables[class_name] = new LuciTable();
this.cbi_map.appendChild(this.tables[class_name].fieldset);
}
this.tables[class_name].title = class_name;
this.tables[class_name].data = tables_map[class_name];
}
for (let table in this.tables) {
if (tables_map[table] == null) {
this.cbi_map.removeChild(this.tables[table].fieldset);
delete this.tables[table];
}
}
if (warning_message.length > 0) {
for (let i = 0; i < warning_message.length; i++) {
let entry = warning_message[i];
let full_name = entry.full_name ? entry.full_name : entry.key;
let node = document.createElement('p');
node.innerHTML = full_name + entry.value;
this.warning_message(node);
}
}
else{
this.hide_warning_message();
}
}
}
</script>
<%
local uci = luci.model.uci.cursor()
modem_configs = {}
local modem = uci:foreach("qmodem", "modem-device",function(s)
table.insert(modem_configs,s[".name"])
end)
for _,v in ipairs(modem_configs) do
%>
<div id="modem_<%=v%>">
</div>
<script>
const modem_info_<%=v%> = new ModemInfo("<%=v%>");
modem_info_<%=v%>.poll_info();
modem_info_<%=v%>.update();
</script>
<%
end
%>
|
281677160/openwrt-package | 1,726 | luci-app-qmodem/application/qmodem/files/usr/libexec/rpcd/modem_ctrl | #!/bin/sh
. /lib/functions.sh
info()
{
state=$(uci get qmodem.$1.state)
if [ "$state" = "disabled" ]; then
return
fi
info=$(/usr/share/qmodem/modem_ctrl.sh info $1)
json_array=$(echo $json_array | jq ". += [ $info ]")
}
sim_info()
{
state=$(uci get qmodem.$1.state)
if [ "$state" = "disabled" ]; then
return
fi
/usr/share/qmodem/modem_ctrl.sh sim_info $1
}
base_info()
{
state=$(uci get modem.$1.state)
if [ "$state" = "disabled" ]; then
return
fi
/usr/share/qmodem/modem_ctrl.sh base_info $1
}
network_info()
{
state=$(uci get qmodem.$1.state)
if [ "$state" = "disabled" ]; then
return
fi
/usr/share/qmodem/modem_ctrl.sh network_info $1
}
cell_info()
{
state=$(uci get qmodem.$1.state)
if [ "$state" = "disabled" ]; then
return
fi
/usr/share/qmodem/modem_ctrl.sh cell_info $1
}
case "$1" in
list)
echo '{ "info": { }, "base_info": { }, "failme": {} }'
;;
call)
case "$2" in
"info")
json_array="[]"
config_load qmodem
config_foreach info modem-device
echo "{\"info\":$json_array}"
;;
"base_info")
config_load qmodem
config_foreach base_info modem-device
;;
"sim_info")
config_load qmodem
config_foreach sim_info modem-device
;;
"network_info")
config_load qmodem
config_foreach network_info modem-device
;;
"cell_info")
config_load qmodem
config_foreach cell_info modem-device
;;
esac
;;
esac
|
281677160/openwrt-package | 1,068 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/modem_hook.sh | #!/bin/sh
. /lib/functions.sh
config_name="qmodem"
config_section=$1
init_type=$2
case $init_type in
post_init)
# pre-add at commands
cfg_prefix="post_init"
debug_subject="post_init"
;;
pre_dial)
# pre-dial at commands
cfg_prefix="pre_dial"
debug_subject="pre_dial"
;;
*)
m_debug "init_type error"
exit 1
;;
esac
_execute_ats(){
command=$1
res=$(at $at_port $command | tr -d '\r')
m_debug "execute_ats $config_section: $command $at_port"
m_debug "execute_ats_result $config_section: $res"
}
. /usr/share/qmodem/modem_util.sh
config_load ${config_name}
config_get ${cfg_prefix}_delay $config_section delay
config_get at_port $config_section at_port
if [ -f "$at_port" ] || [ -z "$at_port" ]; then
m_debug "$config_section:at_port is not set or not a file"
m_debug "at_port $config_section: $at_port"
exit 1
fi
if [ -n "$delay" ]; then
sleep $delay
fi
config_list_foreach $config_section ${cfg_prefix}_at_cmds _execute_ats
|
281677160/openwrt-package | 14,005 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/generic.sh | #!/bin/sh
SCRIPT_DIR="/usr/share/qmodem"
source /usr/share/libubox/jshn.sh
source "${SCRIPT_DIR}/modem_util.sh"
add_plain_info_entry()
{
key=$1
value=$2
key_full_name=$3
class_overwrite=$4
if [ -n "$class_overwrite" ]; then
class="$class_overwrite"
fi
json_add_object ""
json_add_string key "$key"
json_add_string value "$value"
json_add_string "full_name" "$key_full_name"
json_add_string "type" "plain_text"
if [ -n "$class" ]; then
json_add_string "class" "$class"
json_add_string "class_origin" "$class"
fi
json_close_object
}
add_warning_message_entry()
{
key=$1
value=$2
key_full_name=$3
class_overwrite=$4
if [ -n "$class_overwrite" ]; then
class="$class_overwrite"
fi
json_add_object ""
json_add_string key "$key"
json_add_string value "$value"
json_add_string "full_name" "$key_full_name"
json_add_string "type" "warning_message"
json_add_string "class" "warning"
json_add_string "class_origin" "warning"
json_close_object
}
add_bar_info_entry()
{
key=$1
value=$2
key_full_name=$3
min_value=$4
max_value=$5
unit=$6
class_overwrite=$7
if [ -n "$class_overwrite" ]; then
class="$class_overwrite"
fi
json_add_object ""
json_add_string key "$key"
json_add_string value "$value"
json_add_string min_value "$min_value"
json_add_string max_value "$max_value"
json_add_string "full_name" "$key_full_name"
json_add_string "unit" "$unit"
json_add_string "type" "progress_bar"
if [ -n "$class" ]; then
json_add_string "class" "$class"
json_add_string "class_origin" "$class"
fi
json_close_object
}
add_speed_entry()
{
rate=$1
type=$2
if [ -z "$rate" ]; then
return
fi
rate=`rate_convert $rate`
case $type in
"rx")
add_plain_info_entry "Rx Rate" "$rate" "Transmit Rate"
;;
"tx")
add_plain_info_entry "Tx Rate" "$rate" "Receive Rate"
;;
*)
return
;;
esac
}
add_avalible_band_entry()
{
band_id=$1
band_name=$2
json_add_object ""
json_add_string band_id "$band_id"
json_add_string band_name "$band_name"
json_add_string "type" "avalible_band"
json_close_object
}
get_driver()
{
for i in $(find $modem_path -name driver);do
lsfile=$(ls -l $i)
type=${lsfile:0:1}
if [ "$type" == "l" ];then
link=$(basename $(ls -l $i | awk '{print $11}'))
case $link in
"mtk_t7xx")
mode="mtk_pcie"
break
;;
"qmi_wwan"*)
mode="qmi"
break
;;
"cdc_mbim")
mode="mbim"
break
;;
"cdc_ncm")
mode="ncm"
break
;;
"cdc_ether")
mode="ecm"
break
;;
"rndis_host")
mode="rndis"
break
;;
"mhi_netdev")
mode="mhi"
break
;;
*)
if [ -z "$mode" ]; then
mode="unknown"
fi
;;
esac
fi
done
echo $mode
}
get_dns()
{
[ -z "$pdp_index" ] && {
pdp_index="1"
}
local public_dns1_ipv4="223.5.5.5"
local public_dns2_ipv4="119.29.29.29"
local public_dns1_ipv6="2400:3200::1" #下一代互联网北京研究中心:240C::6666,阿里:2400:3200::1,腾讯:2402:4e00::
local public_dns2_ipv6="2402:4e00::"
#获取DNS地址
at_command="AT+GTDNS=${pdp_index}"
local response=$(at ${at_port} ${at_command} | grep "+GTDNS: ")
local ipv4_dns1=$(echo "${response}" | awk -F'"' '{print $2}' | awk -F',' '{print $1}')
[ -z "$ipv4_dns1" ] && {
ipv4_dns1="${public_dns1_ipv4}"
}
local ipv4_dns2=$(echo "${response}" | awk -F'"' '{print $4}' | awk -F',' '{print $1}')
[ -z "$ipv4_dns2" ] && {
ipv4_dns2="${public_dns2_ipv4}"
}
local ipv6_dns1=$(echo "${response}" | awk -F'"' '{print $2}' | awk -F',' '{print $2}')
[ -z "$ipv6_dns1" ] && {
ipv6_dns1="${public_dns1_ipv6}"
}
local ipv6_dns2=$(echo "${response}" | awk -F'"' '{print $4}' | awk -F',' '{print $2}')
[ -z "$ipv6_dns2" ] && {
ipv6_dns2="${public_dns2_ipv6}"
}
json_add_object "dns"
json_add_string "ipv4_dns1" "$ipv4_dns1"
json_add_string "ipv4_dns2" "$ipv4_dns2"
json_add_string "ipv6_dns1" "$ipv6_dns1"
json_add_string "ipv6_dns2" "$ipv6_dns2"
json_close_object
}
get_sim_status()
{
local sim_status
case $1 in
"")
sim_status="miss"
sim_state_code=0
;;
*"ERROR"*)
sim_status="miss"
sim_state_code=0
;;
*"READY"*)
sim_status="ready"
sim_state_code=1
;;
*"SIM PIN"*)
sim_status="MT is waiting SIM PIN to be given"
sim_state_code=2
;;
*"SIM PUK"*)
sim_status="MT is waiting SIM PUK to be given"
sim_state_code=3
;;
*"PH-FSIM PIN"*)
sim_status="MT is waiting phone-to-SIM card password to be given"
sim_state_code=4
;;
*"PH-FSIM PIN"*)
sim_status="MT is waiting phone-to-very first SIM card password to be given"
sim_state_code=5
;;
*"PH-FSIM PUK"*)
sim_status="MT is waiting phone-to-very first SIM card unblocking password to be given"
sim_state_code=6
;;
*"SIM PIN2"*)
sim_status="MT is waiting SIM PIN2 to be given"
sim_state_code=7
;;
*"SIM PUK2"*)
sim_status="MT is waiting SIM PUK2 to be given"
sim_state_code=8
;;
*"PH-NET PIN"*)
sim_status="MT is waiting network personalization password to be given"
sim_state_code=9
;;
*"PH-NET PUK"*)
sim_status="MT is waiting network personalization unblocking password to be given"
sim_state_code=10
;;
*"PH-NETSUB PIN"*)
sim_status="MT is waiting network subset personalization password to be given"
sim_state_code=11
;;
*"PH-NETSUB PUK"*)
sim_status="MT is waiting network subset personalization unblocking password to be given"
sim_state_code=12
;;
*"PH-SP PIN"*)
sim_status="MT is waiting service provider personalization password to be given"
sim_state_code=13
;;
*"PH-SP PUK"*)
sim_status="MT is waiting service provider personalization unblocking password to be given"
sim_state_code=14
;;
*"PH-CORP PIN"*)
sim_status="MT is waiting corporate personalization password to be given"
sim_state_code=16
;;
*"PH-CORP PUK"*)
sim_status="MT is waiting corporate personalization unblocking password to be given"
sim_state_code=17
;;
*)
sim_status="unknown"
sim_state_code=99
;;
esac
echo "$sim_status"
}
#获取信号强度指示
# $1:信号强度指示数字
get_rssi()
{
local rssi
case $1 in
"99") rssi="unknown" ;;
* ) rssi=$((2 * $1 - 113)) ;;
esac
echo "$rssi"
}
#获取网络类型
# $1:网络类型数字
get_rat()
{
local rat
case $1 in
"0"|"1"|"3"|"8") rat="GSM" ;;
"2"|"4"|"5"|"6"|"9"|"10") rat="WCDMA" ;;
"7") rat="LTE" ;;
"11"|"12") rat="NR" ;;
esac
echo "${rat}"
}
#获取连接状态
#return raw data
get_connect_status()
{
connect_status="No"
driver=$(get_driver)
if [ "$driver" = "mtk_pcie" ]; then
mbim_port=$(echo "$at_port" | sed 's/at/mbim/g')
local config=$(umbim -d $mbim_port config)
local ipv4=$(echo "$config" | grep "ipv4address:" | awk '{print $2}' | cut -d'/' -f1)
local ipv6=$(echo "$config" | grep "ipv6address:" | awk '{print $2}' | cut -d'/' -f1)
disallow_ipv4="0.0.0.0"
if [ -n "$ipv4" ] && [ "$ipv4" != "$disallow_ipv4" ] || [ -n "$ipv6" ] && [ "$ipv6" != "::" ]; then
connect_status="Yes"
fi
else
at_cmd="AT+CGACT?"
expect="+CGACT:"
result=`at $at_port $at_cmd | grep $expect|tr '\r' '\n'`
for pdp_index in `echo "$result" | tr -d "\r" | awk -F'[,:]' '$3 == 1 {print $2}'`; do
at_cmd="AT+CGPADDR=%s"
at_cmd=$(printf "$at_cmd" "$pdp_index")
expect="+CGPADDR:"
result=$(at $at_port $at_cmd | grep $expect)
if [ -n "$result" ];then
ipv6=$(echo $result | grep -oE "\b([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}\b")
ipv4=$(echo $result | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
disallow_ipv4="0.0.0.0"
#remove the disallow ip
if [ "$ipv4" == "$disallow_ipv4" ];then
ipv4=""
fi
fi
if [ -n "$ipv4" ] || [ -n "$ipv6" ];then
connect_status="Yes"
break
else
connect_status="No"
fi
done
fi
add_plain_info_entry "connect_status" "$connect_status" "Connect Status"
}
#获取移远模组信息
# $1:AT串口
# $2:平台
# $3:连接定义
get_info()
{
#基本信息
base_info
#SIM卡信息
sim_info
if [ "$sim_status" != "ready" ]; then
add_warning_message_entry "sim_status" "$sim_status" "SIM Error,Error code:" "warning"
return
fi
#网络信息
network_info
if [ "$connect_status" != "Yes" ]; then
return
fi
#小区信息
cell_info
return
}
soft_reboot()
{
at_command="AT+CFUN=1,1"
at $at_port $at_command
}
hard_reboot()
{
#get power_gpio_pin
source /lib/functions.sh
config_load qmodem
config_foreach get_gpio_by_slot modem-slot
gpio="/sys/class/gpio/$gpio/value"
[ ! -f "$gpio" ] || [ -z "$gpio_up" ] || [ -z "$gpio_down" ] && {
soft_reboot
m_debug "gpio not found, failback to soft reboot"
return
}
echo $gpio_down > $gpio
sleep 1
echo $gpio_up > $gpio
}
get_gpio_by_slot()
{
local cfg="$1"
config_get slot "$cfg" slot
if [ "$modem_slot" = "$slot" ];then
config_get gpio "$cfg" gpio
config_get gpio_up "$cfg" gpio_up
config_get gpio_down "$cfg" gpio_down
fi
}
get_reboot_caps()
{
source /lib/functions.sh
config_load qmodem
config_foreach get_gpio_by_slot modem-slot
json_init
json_add_object "reboot_caps"
json_add_int "soft_reboot_caps" "1"
if [ -n "$gpio" ] && [ -n "$gpio_up" ] && [ -n "$gpio_down" ];then
json_add_int "hard_reboot_caps" "1"
else
json_add_int "hard_reboot_caps" "0"
fi
json_close_object
json_dump
}
rate_convert()
{
#check if bc is installed
is_bc_installed=$(which bc)
local rate=$1
rate_units="bps Kbps Mbps Gbps"
if [ -z "$is_bc_installed" ]; then
for i in $(seq 0 3); do
if [ $rate -lt 1024 ]; then
break
fi
rate=$(($rate / 1024))
done
else
for i in $(seq 0 3); do
if [ $(echo "$rate < 1024" | bc) -eq 1 ]; then
break
fi
rate=$(echo "scale=2; $rate / 1024" | bc)
done
fi
echo "$rate `echo $rate_units | cut -d ' ' -f $(($i+1))`"
}
get_modem_disabled_features()
{
. /lib/functions.sh
config_load qmodem
config_list_foreach $config_section disabled_features _add_disabled_features
}
get_sms_capabilities() {
local res sms_cap
res=$(at $at_port "AT+CPMS?" | grep "CPMS:" | xargs)
[ -z "$res" ] && return
sms_cap=${res##*+CPMS:}
set -- $(echo "$sms_cap" | tr ',' ' ')
local mem1=$1 used1=$2 total1=$3
local mem2=$4 used2=$5 total2=$6
local mem3=$7 used3=$8 total3=$9
json_add_object "sms_capabilities"
json_add_string "mem1" "$mem1"
json_add_string "mem2" "$mem2"
json_add_string "mem3" "$mem3"
json_add_object "ME"
json_close_object
json_add_object "SM"
json_close_object
for idx in 1 2 3; do
eval "mem=\$mem$idx"
eval "used=\$used$idx"
eval "total=\$total$idx"
case "$mem" in
"SM")
json_select "SM"
;;
"MT"|"ME")
json_select "ME"
;;
*)
continue
;;
esac
json_add_string "used" "$used"
json_add_string "total" "$total"
json_close_object
done
}
set_sms_storage()
{
mem1=$(echo $1 | jq -r '.mem1')
mem2=$(echo $1 | jq -r '.mem2')
mem3=$(echo $1 | jq -r '.mem3')
json_add_string "raw" "$1"
if [ -z "$mem1" ] || [ -z "$mem2" ]; then
return
fi
if [ "$mem3" == "Loading" ];then
res=$(at $at_port "AT+CPMS=\"$mem1\",\"$mem2\"")
else
res=$(at $at_port "AT+CPMS=\"$mem1\",\"$mem2\",\"$mem3\"")
fi
json_select "result"
json_add_string "result" "$res"
}
get_global_disabled_features()
{
. /lib/functions.sh
config_load qmodem
config_list_foreach main disabled_features _add_disabled_features
}
_add_disabled_features()
{
json_add_string "" "$1"
}
_copyright()
{
json_add_object "copyright"
json_add_string "Vendor" "${_Vendor}"
json_add_string "Author" "${_Author}"
json_add_string "Maintainer" "${_Maintainer}"
json_close_object
}
|
281677160/openwrt-package | 18,805 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/modem_scan.sh | #/bin/sh
action=$1
config=$2
slot_type=$3
modem_support=$(cat /usr/share/qmodem/modem_support.json)
debug_subject="modem_scan"
source /lib/functions.sh
source /usr/share/qmodem/modem_util.sh
exec_post_init()
{
section_name=$1
/usr/share/qmodem/modem_hook.sh $section_name post_init
}
get_associate_usb()
{
target_slot=$1
config_load qmodem
config_foreach _get_associated_usb_by_path modem-slot
}
get_default_alias()
{
target_slot=$1
config_load qmodem
config_foreach _get_default_alias_by_slot
}
get_default_metric()
{
target_slot=$1
config_load qmodem
config_foreach _get_default_metric_by_slot
}
_get_associated_usb_by_path()
{
local cfg="$1"
m_debug $target_slot
config_get _get_slot $cfg slot
if [ "$target_slot" == "$_get_slot" ];then
config_get associated_usb $cfg associated_usb
m_debug \[$target_slot\]associated_usb:$associated_usb
fi
}
_get_default_alias_by_slot()
{
local cfg="$1"
config_get _get_slot $cfg slot
if [ "$target_slot" == "$_get_slot" ];then
config_get default_alias $cfg alias
fi
}
_get_default_metric_by_slot()
{
local cfg="$1"
config_get _get_slot $cfg slot
if [ "$target_slot" == "$_get_slot" ];then
config_get default_metric $cfg default_metric
fi
}
scan()
{
local slot_type=$1
if [ "$slot_type" == "usb" ] || [ -z "$slot_type" ];then
scan_usb
usb_slots=$(echo $usb_slots | uniq )
for slot in $usb_slots; do
slot_type="usb"
add $slot
done
fi
if [ "$slot_type" == "pcie" ] || [ -z "$slot_type" ];then
scan_pcie
pcie_slots=$(echo $pcie_slots | uniq )
for slot in $pcie_slots; do
slot_type="pcie"
add $slot
done
fi
}
scan_usb()
{
usb_net_device_prefixs="usb eth wwan"
usb_slots=""
for usb_net_device_prefix in $usb_net_device_prefixs; do
usb_netdev=$(ls /sys/class/net | grep -E "${usb_net_device_prefix}")
for netdev in $usb_netdev; do
netdev_path=$(readlink -f "/sys/class/net/$netdev/device/")
[ -z "$netdev_path" ] && continue
[ -z "$(echo $netdev_path | grep usb)" ] && continue
usb_slot=$(basename $(dirname $netdev_path))
m_debug "netdev_path: $netdev_path usb slot: $usb_slot"
[ -z "$usb_slots" ] && usb_slots="$usb_slot" || usb_slots="$usb_slots $usb_slot"
done
done
}
scan_pcie()
{
#beta
m_debug "scan_pcie"
echo 1 > /sys/bus/pci/rescan
sleep 1
pcie_net_device_prefixs="rmnet wwan"
pcie_slots=""
for pcie_net_device_prefix in $pcie_net_device_prefixs; do
pcie_netdev=$(ls /sys/class/net | grep -E "${pcie_net_device_prefix}")
for netdev in $pcie_netdev; do
netdev_path=$(readlink -f "/sys/class/net/$netdev/device/")
[ -z "$netdev_path" ] && continue
[ -z "$(echo $netdev_path | grep pci)" ] && continue
# pcie_slot=$(basename $(dirname $netdev_path))
pcie_slot=$(echo "$netdev_path" | tr '/' '\n' | grep -E '^[0-9a-fA-F]{4}:[0-9a-fA-F:.]+$' | tail -n1)
[ "$pcie_slot" == "net" ] && continue
m_debug "netdev_path: $netdev_path pcie slot: $pcie_slot"
[ -z "$pcie_slots" ] && pcie_slots="$pcie_slot" || pcie_slots="$pcie_slots $pcie_slot"
done
done
}
scan_pcie_slot_interfaces()
{
local slot=$1
local slot_path="/sys/bus/pci/devices/$slot"
net_devices=""
dun_devices=""
[ ! -d "$slot_path" ] && return
local short_slot_name=`echo ${slot:2:-2} |tr ":" "."`
local slot_interfaces=$(ls $slot_path | grep -E "_*${short_slot_name}_")
for interface in $slot_interfaces; do
unset device
unset dun_device
interface_driver_path="$slot_path/$interface/driver"
[ ! -d "$interface_driver_path" ] && continue
interface_driver=$(basename $(readlink $interface_driver_path))
[ -z "$interface_driver" ] && continue
case $interface_driver in
mhi_netdev)
net_path="$slot_path/$interface/net"
[ ! -d "$net_path" ] && continue
device=$(ls $net_path)
[ -z "$net_devices" ] && net_devices="$device" || net_devices="$net_devices $device"
;;
mhi_uci_q)
dun_device=$(ls "$slot_path/$interface/mhi_uci_q" | grep mhi_DUN)
[ -z "$dun_device" ] && continue
dun_device_path="$slot_path/$interface/mhi_uci_q/$dun_device"
[ ! -d "$dun_device_path" ] && continue
dun_device_path=$(readlink -f "$dun_device_path")
[ ! -d "$dun_device_path" ] && continue
dun_device=$(basename "$dun_device_path")
[ -z "$dun_device" ] && continue
[ -z "$dun_devices" ] && dun_devices="$dun_device" || dun_devices="$dun_devices $dun_device"
;;
esac
done
interface_mhi_path="$slot_path/mhi0"
if [ ! -z "$interface_mhi_path" ]; then
wwan0_path="$slot_path/mhi0/wwan/wwan0"
if [ -d "$wwan0_path" ];then
dun_device=$(ls "$wwan0_path" | grep wwan0at0)
[ ! -z "$dun_device" ] && dun_device_path="$wwan0_path/$dun_device"
[ ! -z "$dun_device_path" ] && dun_devices=$(basename "$dun_device_path")
fi
fi
#mt_t7xx device
wwan_path="$slot_path/wwan"
if [ -d "$wwan_path" ]; then
net_devices=$(ls "$wwan_path" | grep -E "wwan[0-9]")
devices_path="$wwan_path/$net_devices"
if [ -d "$devices_path" ];then
mbim_devices=$(ls "$devices_path" | grep -E "wwan[0-9]mbim[0-9]")
dun_devices=$(ls "$devices_path" | grep -E "wwan[0-9]at[0-9]")
fi
fi
m_debug "net_devices: $net_devices dun_devices: $dun_devices"
at_ports="$dun_devices"
[ -n "$net_devices" ] && get_associate_usb $slot
if [ -n "$associated_usb" ] && [ -d "/sys/bus/usb/devices/$associated_usb" ]; then
echo checking associated_usb: $associated_usb
local assoc_usb_path="/sys/bus/usb/devices/$associated_usb"
local slot_interfaces=$(ls $assoc_usb_path | grep -E "$associated_usb:[0-9]\.[0-9]+")
echo checking slot_interfaces: $slot_interfaces
for interface in $slot_interfaces; do
unset device
unset ttyUSB_device
unset ttyACM_device
interface_driver_path="$assoc_usb_path/$interface/driver"
[ ! -d "$interface_driver_path" ] && continue
interface_driver=$(basename $(readlink $interface_driver_path))
[ -z "$interface_driver" ] && continue
case $interface_driver in
option|\
cdc_acm|\
usbserial_generic|\
usbserial)
ttyUSB_device=$(ls "$assoc_usb_path/$interface/" | grep ttyUSB)
ttyACM_device=$(ls "$assoc_usb_path/$interface/" | grep ttyACM)
[ -z "$ttyUSB_device" ] && [ -z "$ttyACM_device" ] && continue
[ -n "$ttyUSB_device" ] && device="$ttyUSB_device"
[ -n "$ttyACM_device" ] && device="$ttyACM_device"
[ -z "$tty_devices" ] && tty_devices="$device" || tty_devices="$tty_devices $device"
;;
esac
done
at_ports="$dun_devices $tty_devices"
fi
validate_at_port
}
scan_usb_slot_interfaces()
{
local slot=$1
local slot_path="/sys/bus/usb/devices/$slot"
net_devices=""
tty_devices=""
[ ! -d "$slot_path" ] && return
local slot_interfaces=$(ls $slot_path | grep -E "$slot:[0-9]\.[0-9]+")
for interface in $slot_interfaces; do
unset device
unset ttyUSB_device
unset ttyACM_device
interface_driver_path="$slot_path/$interface/driver"
[ ! -d "$interface_driver_path" ] && continue
interface_driver=$(basename $(readlink $interface_driver_path))
[ -z "$interface_driver" ] && continue
local if_port=$(echo "$interface" | grep -oE "[0-9]+\.[0-9]+$" || echo "")
case $interface_driver in
option|\
cdc_acm|\
usbserial_generic|\
usbserial)
ttyUSB_device=$(ls "$slot_path/$interface/" | grep ttyUSB)
ttyACM_device=$(ls "$slot_path/$interface/" | grep ttyACM)
[ -z "$ttyUSB_device" ] && [ -z "$ttyACM_device" ] && continue
[ -n "$ttyUSB_device" ] && device="$ttyUSB_device"
[ -n "$ttyACM_device" ] && device="$ttyACM_device"
local should_include=1
if [ $include_mode -eq 1 ]; then
should_include=0
for included_port in $include_ports; do
if [ -n "$if_port" ] && [ "$included_port" = "$if_port" ]; then
should_include=1
break
fi
done
fi
if [ $should_include -eq 1 ]; then
[ -z "$tty_devices" ] && tty_devices="$device" || tty_devices="$tty_devices $device"
fi
;;
qmi_wwan*|\
cdc_mbim|\
*cdc_ncm|\
cdc_ether|\
rndis_host)
net_path="$slot_path/$interface/net"
[ ! -d "$net_path" ] && continue
device=$(ls $net_path)
[ -z "$net_devices" ] && net_devices="$device" || net_devices="$net_devices $device"
;;
esac
done
m_debug "net_devices: $net_devices tty_devices: $tty_devices"
at_ports="$tty_devices"
validate_at_port
}
validate_at_port()
{
valid_at_ports=""
for at_port in $at_ports; do
dev_path="/dev/$at_port"
[ ! -e "$dev_path" ] && continue
res=$(fastat $dev_path "ATI")
[ -z "$res" ] && continue
!(echo "$res" | grep -qE 'OK|ATI') && continue
valid_at_port="$at_port"
[ -z "$valid_at_ports" ] && valid_at_ports="$valid_at_port" || valid_at_ports="$valid_at_ports $valid_at_port"
done
}
match_config()
{
local name=$(echo $1 | sed 's/\r//g' | tr 'A-Z' 'a-z')
[[ "$name" = *"nl668"* ]] && name="nl668"
[[ "$name" = *"nl678"* ]] && name="nl678"
[[ "$name" = *"em120k"* ]] && name="em120k"
#FM350-GL-00 5G Module
[[ "$name" = *"fm350-gl"* ]] && name="fm350-gl"
#FM190W-GL 5G Module
[[ "$name" = *"fm190w-gl"* ]] && name="fm190w-gl"
#RM500U-CNV
[[ "$name" = *"rm500u-cn"* ]] && name="rm500u-cn"
[[ "$name" = *"rm500u-ea"* ]] && name="rm500u-ea"
#t99w175
[[ "$name" = *"mv31-w"* ]] || [[ "$name" = *"T99W175"* ]] && name="t99w175"
[[ "$name" = *"T99W373"* ]] && name="t99w373"
[[ "$name" = *"dp25-42843-47"* ]] && name="t99w640"
[[ "$name" = *"SIM8380G"* ]] && name="SIM8380G-M2"
#rg200u-cn
[[ "$name" = *"rg200u-cn"* ]] && name="rg200u-cn"
#nu313-m2
[[ "$name" = *"nu313-m2"* ]] && name="srm821"
#nari-m601
[[ "$name" = *"m601"* ]] && name="n510m"
modem_config=$(echo $modem_support | jq '.modem_support."'$slot_type'"."'$name'"')
[ "$modem_config" == "null" ] && return
[ -z "$modem_config" ] && return
modem_name=$name
manufacturer=$(echo $modem_config | jq -r ".manufacturer")
platform=$(echo $modem_config | jq -r ".platform")
suggest_pdp_index=$(echo $modem_config | jq -r ".pdp_index")
modes=$(echo $modem_config | jq -r ".modes[]")
wcdma_available_band=$(echo $modem_config | jq -r ".wcdma_band")
lte_available_band=$(echo $modem_config | jq -r ".lte_band")
nsa_available_band=$(echo $modem_config | jq -r ".nsa_band")
sa_available_band=$(echo $modem_config | jq -r ".sa_band")
}
get_modem_model()
{
local at_port=$1
sleep 1
cgmm=$(at $at_port "AT+CGMM")
sleep 1
cgmm_1=$(at $at_port "AT+CGMM?")
name_1=$(echo -e "$cgmm" |grep "+CGMM: " | awk -F': ' '{print $2}')
name_2=$(echo -e "$cgmm_1" |grep "+CGMM: " | awk -F'"' '{print $2} '| cut -d ' ' -f 1)
name_3=$(echo -e "$cgmm" | sed -n '2p')
name_4=$(echo -e "$cgmm" | sed -n '3p')
name_5=$(echo -e "$cgmm" |grep "+CGMM: " | awk -F'"' '{print $2} '| cut -d ' ' -f 1)
modem_name=""
[ -n "$name_1" ] && match_config "$name_1"
[ -n "$name_2" ] && [ -z "$modem_name" ] && match_config "$name_2"
[ -n "$name_3" ] && [ -z "$modem_name" ] && match_config "$name_3"
[ -n "$name_4" ] && [ -z "$modem_name" ] && match_config "$name_4"
[ -n "$name_5" ] && [ -z "$modem_name" ] && match_config "$name_5"
[ -z "$modem_name" ] && return 1
return 0
}
add()
{
local slot=$1
lock -n /tmp/lock/modem_add_$slot
[ $? -eq 0 ] || return
#slot_type is usb or pcie
#section name is replace slot .:- with _
section_name=$(echo $slot | sed 's/[\.:-]/_/g')
is_exist=$(uci -q get qmodem.$section_name)
is_fixed_device=$(uci -q get qmodem.${section_name}.fixed_device)
if [ "$is_fixed_device" == "1" ];then
m_debug "modem $modem_name slot $slot slot_type $slot_type is fixed device, skip"
lock -u /tmp/lock/modem_add_$slot
exec_post_init $section_name
return
fi
case $slot_type in
"usb")
scan_usb_slot_interfaces $slot
modem_path="/sys/bus/usb/devices/$slot/"
;;
"pcie")
#under test
scan_pcie_slot_interfaces $slot
modem_path="/sys/bus/pci/devices/$slot/"
;;
esac
#if no netdev return
[ -z "$net_devices" ] && lock -u /tmp/lock/modem_add_$slot && return
for trys in $(seq 1 3);do
for at_port in $valid_at_ports; do
m_debug "try at port $at_port;time $trys"
get_modem_model "/dev/$at_port"
[ $? -eq 0 ] && break || modem_name=""
done
[ -n "$modem_name" ] && break
sleep 1
done
[ -z "$modem_name" ] && lock -u /tmp/lock/modem_add_$slot && return
m_debug "add modem $modem_name slot $slot slot_type $slot_type"
if [ -n "$is_exist" ]; then
#network at_port state name 不变,则不需要重启网络
orig_network=$(uci -q get qmodem.$section_name.network)
orig_at_port=$(uci -q get qmodem.$section_name.at_port)
orig_state=$(uci -q get qmodem.$section_name.state)
orig_name=$(uci -q get qmodem.$section_name.name)
uci -q del qmodem.$section_name.modes
uci -q del qmodem.$section_name.valid_at_ports
uci -q del qmodem.$section_name.tty_devices
uci -q del qmodem.$section_name.net_devices
uci -q del qmodem.$section_name.ports
uci -q set qmodem.$section_name.state="enabled"
else
#aqcuire lock
lock /tmp/lock/modem_add
unset default_alias
unset default_metric
get_default_alias $slot
get_default_metric $slot
modem_count=$(uci -q get qmodem.main.modem_count)
[ -z "$modem_count" ] && modem_count=0
modem_count=$(($modem_count+1))
uci set qmodem.main.modem_count=$modem_count
uci set qmodem.$section_name=modem-device
[ -n "$default_alias" ] && uci set qmodem.${section_name}.alias="$default_alias"
uci commit qmodem
lock -u /tmp/lock/modem_add
#release lock
metric=$(($modem_count+10))
[ -n "$default_metric" ] && metric=$default_metric
uci batch << EOF
set qmodem.$section_name.path="$modem_path"
set qmodem.$section_name.data_interface="$slot_type"
set qmodem.$section_name.enable_dial="1"
set qmodem.$section_name.soft_reboot="1"
set qmodem.$section_name.extend_prefix="1"
set qmodem.$section_name.pdp_type="ipv4v6"
set qmodem.$section_name.state="enabled"
set qmodem.$section_name.metric=$metric
EOF
fi
uci batch <<EOF
set qmodem.$section_name.name=$modem_name
set qmodem.$section_name.network=$net_devices
set qmodem.$section_name.manufacturer=$manufacturer
set qmodem.$section_name.platform=$platform
set qmodem.$section_name.suggest_pdp_index=$pdp_index
EOF
[ -n "$wcdma_available_band" ] && uci set qmodem.$section_name.wcdma_band=$wcdma_available_band
[ -n "$lte_available_band" ] && uci set qmodem.$section_name.lte_band=$lte_available_band
[ -n "$nsa_available_band" ] && uci set qmodem.$section_name.nsa_band=$nsa_available_band
[ -n "$sa_available_band" ] && uci set qmodem.$section_name.sa_band=$sa_available_band
for mode in $modes; do
uci add_list qmodem.$section_name.modes=$mode
done
for at_port in $valid_at_ports; do
uci add_list qmodem.$section_name.valid_at_ports="/dev/$at_port"
uci set qmodem.$section_name.at_port="/dev/$at_port"
done
for at_port in $at_ports; do
uci add_list qmodem.$section_name.ports="/dev/$at_port"
done
[ "$option_driver" == "1" ] && uci set qmodem.$section_name.option_driver="1"
uci commit qmodem
mkdir -p /var/run/qmodem/${section_name}_dir
lock -u /tmp/lock/modem_add_$slot
#增加预初始化脚本
exec_post_init $section_name
#判断是否重启网络
[ -n "$is_exist" ] && [ "$orig_network" == "$net_devices" ] && [ "$orig_at_port" == "/dev/$at_port" ] && [ "$orig_state" == "enabled" ] && [ "$orig_name" == "$modem_name" ] && return
/etc/init.d/qmodem_network restart
}
remove()
{
section_name=$1
m_debug "remove $section_name"
is_exist=$(uci -q get qmodem.$section_name)
[ -z "$is_exist" ] && return
lock /tmp/lock/modem_remove
modem_count=$(uci -q get qmodem.main.modem_count)
[ -z "$modem_count" ] && modem_count=0
modem_count=$(($modem_count-1))
uci set qmodem.main.modem_count=$modem_count
uci commit qmodem
uci batch <<EOF
del qmodem.${section_name}
del network.${section_name}
del network.${section_name}v6
del dhcp.${section_name}
commit network
commit dhcp
commit qmodem
EOF
lock -u /tmp/lock/modem_remove
}
disable()
{
local slot=$1
section_name=$(echo $slot | sed 's/[\.:-]/_/g')
#reorder to first
uci reorder qmodem.$section_name="1"
uci set qmodem.$section_name.state="disabled"
uci commit qmodem
}
case $action in
"add")
debug_subject="modem_scan_add"
add $config $slot_type
;;
"remove")
debug_subject="modem_scan_remove"
remove $config
;;
"disable")
debug_subject="modem_scan_disable"
disable $config
;;
"scan")
debug_subject="modem_scan_scan"
[ -n "$config" ] && delay=$config && sleep $delay
lock -n /tmp/lock/modem_scan
[ $? -eq 1 ] && exit 0
scan $slot_type
lock -u /tmp/lock/modem_scan
;;
esac
|
281677160/openwrt-package | 33,778 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/modem_dial.sh | #!/bin/sh
source /lib/functions.sh
#运行目录
MODEM_RUNDIR="/var/run/qmodem"
SCRIPT_DIR="/usr/share/qmodem"
modem_config=$1
mkdir -p "${MODEM_RUNDIR}/${modem_config}_dir"
log_file="${MODEM_RUNDIR}/${modem_config}_dir/dial_log"
debug_subject="modem_dial"
source "${SCRIPT_DIR}/generic.sh"
touch $log_file
exec_pre_dial()
{
section=$1
/usr/share/qmodem/modem_hook.sh $section pre_dial
}
get_led()
{
config_foreach get_led_by_slot modem-slot
}
get_led_by_slot()
{
local cfg="$1"
config_get slot "$cfg" slot
if [ "$modem_slot" = "$slot" ];then
config_get sim_led "$cfg" sim_led
config_get net_led "$cfg" net_led
fi
}
get_associate_ethernet_by_path()
{
local cfg="$1"
config_get slot "$cfg" slot
config_get ethernet "$cfg" ethernet
if [ "$modem_slot" = "$slot" ];then
config_get ethernet_5g "$cfg" ethernet_5g
fi
}
set_led()
{
local type=$1
local modem_config=$2
local value=$3
get_led "$modem_slot"
case $type in
sim)
[ -z "$sim_led" ] && return
echo $value > /sys/class/leds/$sim_led/brightness
;;
net)
[ -z "$net_led" ] && return
cfg_name=$(echo $net_led |tr ":" "_")
uci batch << EOF
set system.n${cfg_name}=led
set system.n${cfg_name}.name=${modem_slot}_net_indicator
set system.n${cfg_name}.sysfs=${net_led}
set system.n${cfg_name}.trigger=netdev
set system.n${cfg_name}.dev=${modem_netcard}
set system.n${cfg_name}.mode="link tx rx"
commit system
EOF
/etc/init.d/led restart
;;
esac
}
unlock_sim()
{
pin=$1
sim_lock_file="/var/run/qmodem/${modem_config}_dir/pincode"
lock ${sim_lock_file}.lock
if [ -f $sim_lock_file ] && [ "$pin" == "$(cat $sim_lock_file)"];then
m_debug "pin code is already try"
else
res=$(at "$at_port" "AT+CPIN=\"$pin\"")
case "$?" in
0)
m_debug "unlock sim card with pin code $pin success"
;;
*)
echo $pin > $sim_lock_file
m_debug "info" "unlock sim card with pin code $pin failed,block try until nextboot"
;;
esac
fi
lock -u ${sim_lock_file}.lock
}
get_platform_suggest_pdp_index()
{
case $manufacturer in
quectel)
case $platform in
lte)
echo 3
;;
*)
echo 1
;;
esac
;;
fibocom)
case $platform in
mediatek)
echo 3
;;
*)
echo 1
;;
esac
;;
*)
echo 1
;;
esac
}
update_config()
{
config_load qmodem
config_get state $modem_config state
config_get enable_dial $modem_config enable_dial
config_get modem_path $modem_config path
config_get dial_tool $modem_config dial_tool
config_get pdp_type $modem_config pdp_type
config_get network_bridge $modem_config network_bridge
config_get metric $modem_config metric
config_get at_port $modem_config at_port
config_get manufacturer $modem_config manufacturer
config_get platform $modem_config platform
config_get force_set_apn $modem_config force_set_apn
config_get pdp_index $modem_config pdp_index
[ -n "$pdp_index" ] && userset_pdp_index="1" || userset_pdp_index="0"
config_get suggest_pdp_index $modem_config suggest_pdp_index
[ -z "$suggest_pdp_index"] && suggest_pdp_index=$(get_platform_suggest_pdp_index)
[ -z "$pdp_index" ] && pdp_index=$suggest_pdp_index
config_get ra_master $modem_config ra_master
config_get extend_prefix $modem_config extend_prefix
config_get en_bridge $modem_config en_bridge
config_get do_not_add_dns $modem_config do_not_add_dns
config_get dns_list $modem_config dns_list
config_get global_dial main enable_dial
# config_get ethernet_5g u$modem_config ethernet 转往口获取命令更新,待测试
config_foreach get_associate_ethernet_by_path modem-slot
modem_slot=$(basename $modem_path)
config_get alias $modem_config alias
driver=$(get_driver)
update_sim_slot
case $sim_slot in
1)
config_get apn $modem_config apn "auto"
config_get username $modem_config username
config_get password $modem_config password
config_get auth $modem_config auth
config_get pincode $modem_config pincode
;;
2)
config_get apn $modem_config apn2
config_get username $modem_config username2
config_get password $modem_config password2
config_get auth $modem_config auth2
config_get pincode $modem_config pincode2
[ -z "$apn" ] && config_get apn $modem_config apn "auto"
[ -z "$username" ] && config_get username $modem_config username
[ -z "$password" ] && config_get password $modem_config password
[ -z "$auth" ] && config_get auth $modem_config auth
[ -z "$pin" ] && config_get pincode $modem_config pincode
;;
*)
config_get apn $modem_config apn
config_get username $modem_config username
config_get password $modem_config password
config_get auth $modem_config auth
config_get pincode $modem_config pincode
;;
esac
modem_net=$(find $modem_path -name net |tail -1)
modem_netcard=$(ls $modem_net)
interface_name=$modem_config
[ -n "$alias" ] && interface_name=$alias
interface6_name=${interface_name}v6
}
check_dial_prepare()
{
cpin=$(at "$at_port" "AT+CPIN?")
get_sim_status "$cpin"
[ "$manufacturer" = "neoway" ] && {
local res
res=$(at $at_port 'AT+SIMCROSS=1,1;$MYCCID' | grep -q "ERROR")
if [ $? -ne 0 ]; then
sim_state_code="1"
else
sim_state_code="0"
fi
}
case $sim_state_code in
"0")
m_debug "info sim card is miss"
;;
"1")
m_debug "info sim card is ready"
sim_fullfill=1
;;
"2")
m_debug "pin code required"
[ -n "$pincode" ] && unlock_sim $pincode
;;
*)
m_debug "info sim card state is $sim_state_code"
;;
esac
if [ "$sim_fullfill" = "1" ];then
set_led "sim" $modem_config 255
else
set_led "sim" $modem_config 0
fi
if [ -n "$modem_netcard" ] && [ -d "/sys/class/net/$modem_netcard" ];then
netdev_fullfill=1
else
netdev_fullfill=0
fi
if [ "$enable_dial" = "1" ] && [ "$sim_fullfill" = "1" ] && [ "$state" != "disabled" ] ;then
config_fullfill=1
fi
if [ "$config_fullfill" = "1" ] && [ "$sim_fullfill" = "1" ] && [ "$netdev_fullfill" = "1" ] ;then
at "$at_port" "AT+CFUN=1"
return 1
else
return 0
fi
}
check_ip()
{
case $manufacturer in
"simcom")
case $platform in
"qualcomm")
check_ip_command="AT+CGPADDR=6"
;;
esac
;;
"neoway")
case $platform in
"unisoc")
check_ip_command="AT+CGPADDR=1"
;;
esac
;;
*)
check_ip_command="AT+CGPADDR=$pdp_index"
;;
esac
if [ "$driver" = "mtk_pcie" ]; then
mbim_port=$(echo "$at_port" | sed 's/at/mbim/g')
local config=$(umbim -d $mbim_port config)
ipaddr=$(echo "$config" | grep "ipv4address:" | awk '{print $2}' | cut -d'/' -f1)
ipaddr="$ipaddr $(echo "$config" | grep "ipv6address:" | awk '{print $2}' | cut -d'/' -f1)"
else
ipaddr=$(at "$at_port" "$check_ip_command" | grep +CGPADDR:)
fi
if [ -n "$ipaddr" ];then
ipv6=$(echo $ipaddr | grep -oE "\b([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}\b")
ipv4=$(echo $ipaddr | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b")
if [ "$manufacturer" = "simcom" ];then
ipv4=$(echo $ipaddr | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | grep -v "0\.0\.0\.0" | head -n 1)
ipv6=$(echo $ipaddr | grep -oE "\b([0-9a-fA-F]{0,4}.){2,7}[0-9a-fA-F]{0,4}\b")
fi
disallow_ipv4="0.0.0.0"
#remove the disallow ip
if [ "$ipv4" == *"$disallow_ipv4"* ];then
ipv4=""
fi
connection_status=0
if [ -n "$ipv4" ];then
connection_status=1
fi
if [ -n "$ipv6" ];then
connection_status=2
fi
if [ -n "$ipv4" ] && [ -n "$ipv6" ];then
connection_status=3
fi
else
connection_status="-1"
m_debug "at port response unexpected $ipaddr"
fi
}
append_to_fw_zone()
{
local fw_zone=$1
local if_name=$2
source /etc/os-release
local os_version=${VERSION_ID:0:2}
if [ "$os_version" -le 21 ];then
has_ifname=0
origin_line=$(uci -q get firewall.@zone[${fw_zone}].network)
for i in $origin_line
do
if [ "$i" = "$if_name" ];then
has_ifname=1
fi
done
if [ -n "$origin_line" ] && [ "$has_ifname" -eq 0 ];then
uci set firewall.@zone[${fw_zone}].network="${origin_line} ${if_name}"
elif [ -z "$origin_line" ];then
uci set firewall.@zone[${fw_zone}].network="${if_name}"
fi
else
uci add_list firewall.@zone[${fw_zone}].network=${if_name}
fi
}
set_if()
{
fw_reload_flag=0
dhcp_reload_flag=0
network_reload_flag=0
#check if exist
proto="dhcp"
protov6="dhcpv6"
case $manufacturer in
"quectel")
case $platform in
"unisoc")
case $driver in
"mbim")
proto="none"
protov6="none"
;;
esac
;;
esac
;;
"fibocom")
case $platform in
"mediatek")
proto="static"
protov6="dhcpv6"
;;
esac
;;
esac
case $pdp_type in
"ip")
env4="1"
env6="0"
;;
"ipv6")
env4="0"
env6="1"
;;
"ipv4v6")
env4="1"
env6="1"
;;
esac
interface=$(uci -q get network.$interface_name)
interfacev6=$(uci -q get network.$interface6_name)
if [ "$env4" -eq 1 ];then
if [ -z "$inetrface" ];then
uci set network.${interface_name}=interface
uci set network.${interface_name}.modem_config="${modem_config}"
uci set network.${interface_name}.proto="${proto}"
uci set network.${interface_name}.defaultroute='1'
uci set network.${interface_name}.metric="${metric}"
uci del network.${interface_name}.dns
if [ -n "$dns_list" ];then
uci set network.${interface_name}.peerdns='0'
for dns in $dns_list;do
uci add_list network.${interface_name}.dns="${dns}"
done
else
uci del network.${interface_name}.peerdns
fi
local num=$(uci show firewall | grep "name='wan'" | wc -l)
local wwan_num=$(uci -q get firewall.@zone[$num].network | grep -w "${interface_name}" | wc -l)
if [ "$wwan_num" = "0" ]; then
append_to_fw_zone $num ${interface_name}
fi
network_reload_flag=1
firewall_reload_flag=1
m_debug "create interface $interface_name with proto $proto and metric $metric"
fi
else
if [ -n "$interface" ];then
uci delete network.${interface_name}
network_reload_flag=1
m_debug "delete interface $interface_name"
fi
fi
if [ "$env6" -eq 1 ];then
if [ -z "$interfacev6" ];then
uci set network.lan.ipv6='1'
uci set network.lan.ip6assign='64'
uci set network.${interface6_name}='interface'
uci set network.${interface6_name}.modem_config="${modem_config}"
uci set network.${interface6_name}.proto="${protov6}"
uci set network.${interface6_name}.ifname="@${interface_name}"
uci set network.${interface6_name}.device="@${interface_name}"
uci set network.${interface6_name}.metric="${metric}"
local wwan6_num=$(uci -q get firewall.@zone[$num].network | grep -w "${interface6_name}" | wc -l)
if [ "$wwan6_num" = "0" ]; then
append_to_fw_zone $num ${interface6_name}
fi
network_reload_flag=1
firewall_reload_flag=1
m_debug "create interface $interface6_name with proto $protov6 and metric $metric"
fi
if [ "$ra_master" = "1" ];then
uci set dhcp.${interface6_name}='dhcp'
uci set dhcp.${interface6_name}.interface="${interface6_name}"
uci set dhcp.${interface6_name}.ra='relay'
uci set dhcp.${interface6_name}.ndp='relay'
uci set dhcp.${interface6_name}.master='1'
uci set dhcp.${interface6_name}.ignore='1'
uci set dhcp.lan.ra='relay'
uci set dhcp.lan.ndp='relay'
uci set dhcp.lan.dhcpv6='relay'
dhcp_reload_flag=1
elif [ "$extend_prefix" = "1" ];then
uci set network.${interface6_name}.extendprefix=1
dhcpv6=$(uci -q get dhcp.${interface6_name})
if [ -n "$dhcpv6" ];then
uci delete dhcp.${interface6_name}
dhcp_reload_flag=1
fi
else
dhcpv6=$(uci -q get dhcp.${interface6_name})
if [ -n "$dhcpv6" ];then
uci delete dhcp.${interface6_name}
dhcp_reload_flag=1
fi
fi
else
if [ -n "$interfacev6" ];then
uci delete network.${interface6_name}
network_reload_flag=1
dhcpv6=$(uci -q get dhcp.${interface6_name})
if [ -n "$dhcpv6" ];then
dhcp_reload_flag=1
fi
m_debug "delete interface $interface6_name"
fi
fi
if [ "$network_reload_flag" -eq 1 ];then
uci commit network
ifup ${interface_name}
ifup ${interface6_name}
m_debug "network reload"
fi
if [ "$firewall_reload_flag" -eq 1 ];then
uci commit firewall
/etc/init.d/firewall restart
m_debug "firewall reload"
fi
if [ "$dhcp_reload_flag" -eq 1 ];then
uci commit dhcp
/etc/init.d/dhcp restart
m_debug "dhcp reload"
fi
set_modem_netcard=$modem_netcard
if [ -z "$set_modem_netcard" ];then
m_debug "no netcard found"
fi
ethernet_check=$(handle_5gethernet)
if [ -n "$ethernet_check" ] && [ -n "/sys/class/net/$ethernet_5g" ] && [ -n "$ethernet_5g" ];then
set_modem_netcard=$ethernet_5g
fi
#set led
set_led "net" $modem_config $set_modem_netcard
origin_netcard=$(uci -q get network.$interface_name.ifname)
origin_device=$(uci -q get network.$interface_name.device)
origin_metric=$(uci -q get network.$interface_name.metric)
origin_proto=$(uci -q get network.$interface_name.proto)
if [ "$origin_netcard" == "$set_modem_netcard" ] && [ "$origin_device" == "$set_modem_netcard" ] && [ "$origin_metric" == "$metric" ] && [ "$origin_proto" == "$proto" ];then
m_debug "interface $interface_name already set to $set_modem_netcard"
else
uci set network.${interface_name}.ifname="${set_modem_netcard}"
uci set network.${interface_name}.device="${set_modem_netcard}"
uci set network.${interface_name}.modem_config="${modem_config}"
if [ "$env4" -eq 1 ];then
uci set network.${interface_name}.proto="${proto}"
uci set network.${interface_name}.metric="${metric}"
fi
if [ "$env6" -eq 1 ];then
uci set network.${interface6_name}.proto="${protov6}"
uci set network.${interface6_name}.metric="${metric}"
fi
uci commit network
ifup ${interface_name}
m_debug "set interface $interface_name to $set_modem_netcard"
fi
}
flush_if()
{
# uci delete network.${interface_name}
# uci delete network.${interface6_name}
# uci delete dhcp.${interface6_name}
# uci commit network
# uci commit dhcp
# set_led "net" $modem_config
# set_led "sim" $modem_config 0
# m_debug "delete interface $interface_name"
config_load network
remove_target="$modem_config"
config_foreach flush_ip_cb "interface"
set_led "net" $modem_config
set_led "sim" $modem_config 0
m_debug "delete interface $interface_name"
uci commit network
uci commit dhcp
}
flush_ip_cb()
{
local network_cfg=$1
local bind_modem_config
config_get bind_modem_config "$network_cfg" modem_config
if [ "$remove_target" = "$bind_modem_config" ];then
uci delete network.$network_cfg
fi
}
dial(){
update_config
m_debug "modem_path=$modem_path,driver=$driver,interface=$interface_name,at_port=$at_port,using_sim_slot:$sim_slot,dns_list:$dns_list"
while [ "$dial_prepare" != 1 ] ; do
sleep 5
update_config
check_dial_prepare
dial_prepare=$?
done
set_if
m_debug "dialing $modem_path driver $driver"
exec_pre_dial $modem_config
case $driver in
"qmi")
qmi_dial
;;
"mbim")
mbim_dial
;;
"mhi")
mhi_dial
;;
"ncm")
at_dial_monitor
;;
"ecm")
at_dial_monitor
;;
"rndis")
at_dial_monitor
;;
"mtk_pcie")
at_dial_monitor
;;
*)
mbim_dial
;;
esac
}
wwan_hang()
{
m_debug "wwan_hang"
}
ecm_hang()
{
case "$manufacturer" in
"quectel")
at_command="AT+QNETDEVCTL=$pdp_index,2,1"
;;
"fibocom")
case "$platform" in
"mediatek")
at_command="AT+CGACT=0,$pdp_index"
;;
*)
at_command="AT+GTRNDIS=0,$pdp_index"
;;
esac
;;
"meig")
at_command='AT$QCRMCALL=0,0,3,2,'$pdp_index
;;
"huawei")
at_command="AT^NDISDUP=0,0"
;;
"neoway")
delay=3
at_command='AT$MYUSBNETACT=0,0'
;;
*)
at_command="ATI"
;;
esac
fastat "${at_port}" "${at_command}"
[ -n "$delay" ] && sleep "$delay"
}
hang()
{
m_debug "hang up $modem_path driver $driver"
case $driver in
"ncm")
ecm_hang
;;
"ecm")
ecm_hang
;;
"rndis")
ecm_hang
;;
"qmi")
wwan_hang
;;
"mbim")
wwan_hang
;;
"mhi")
wwan_hang
;;
esac
flush_if
}
mbim_dial(){
if [ -z "$apn" ];then
apn="auto"
fi
qmi_dial
}
mhi_dial()
{
qmi_dial
}
qmi_dial()
{
cmd_line="quectel-CM"
[ -e "/usr/bin/quectel-CM-M" ] && cmd_line="quectel-CM-M" && tom_modified=1
case $pdp_type in
"ip") cmd_line="$cmd_line -4" ;;
"ipv6") cmd_line="$cmd_line -6" ;;
"ipv4v6") cmd_line="$cmd_line -4 -6" ;;
*) cmd_line="$cmd_line -4 -6" ;;
esac
if [ "$network_bridge" = "1" ]; then
cmd_line="$cmd_line -b"
fi
if [ -n "$pdp_index" ] && [ "$userset_pdp_index" = "1" ]; then
cmd_line="$cmd_line -n $pdp_index"
fi
if [ "$manufacturer" = "telit" ];then
test_apn="cbnet"
[ "$apn" = "cbnet" ] && test_apn="auto"
$cmd_line -s $test_apn &
telit_cmd_pid=$!
sleep 1
kill $telit_cmd_pid 2>/dev/null
wait $telit_cmd_pid 2>/dev/null
fi
if [ -n "$apn" ]; then
cmd_line="$cmd_line -s $apn"
fi
if [ -n "$username" ]; then
cmd_line="$cmd_line $username"
fi
if [ -n "$password" ]; then
cmd_line="$cmd_line $password"
fi
if [ "$auth" != "none" ]; then
cmd_line="$cmd_line $auth"
fi
if [ -n "$modem_netcard" ]; then
qmi_if=$modem_netcard
#if is wwan* ,use the first part of the name
if [[ "$modem_netcard" = "wwan"* ]];then
qmi_if=$(echo "$modem_netcard" | cut -d_ -f1)
fi
#if is rmnet* ,use the first part of the name
if [[ "$modem_netcard" = "rmnet"* ]];then
qmi_if=$(echo "$modem_netcard" | cut -d. -f1)
fi
cmd_line="${cmd_line} -i ${qmi_if}"
fi
if [ "$en_bridge" = "1" ];then
cmd_line="${cmd_line} -b"
fi
if [ "$do_not_add_dns" = "1" ];then
cmd_line="${cmd_line} -D"
fi
if [ -e "/usr/bin/quectel-CM-M" ];then
[ -n "$metric" ] && cmd_line="$cmd_line -d -M $metric"
[ "$force_set_apn" == "1" ] && cmd_line="$cmd_line -F"
else
[ -n "$metric" ] && cmd_line="$cmd_line"
fi
cmd_line="$cmd_line -f $log_file"
while true; do
m_debug "dialing: $cmd_line"
$cmd_line
m_debug "quectel-CM exited, retrying dial"
done
}
at_dial()
{
if [ -z "$apn" ];then
apn="auto"
fi
if [ -z "$pdp_type" ];then
pdp_type="IP"
fi
local at_command='AT+COPS=0,0'
tmp=$(at "${at_port}" "${at_command}")
pdp_type=$(echo $pdp_type | tr 'a-z' 'A-Z')
case $manufacturer in
"quectel")
case $platform in
"hisilicon")
at_command="AT+QNETDEVCTL=1,1,1"
cgdcont_command=""
;;
*)
at_command="AT+QNETDEVCTL=$pdp_index,3,1"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\",\"$apn\""
;;
esac
;;
"fibocom")
case $platform in
"mediatek")
delay=3
[ "$apn" = "auto" ] && apn="cbnet"
at_command="AT+CGACT=1,$pdp_index"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\",\"$apn\""
;;
"lte")
at_command="AT+GTRNDIS=1,$pdp_index"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\",\"$apn\""
if [ -n "$auth" ]; then
case $auth in
"pap")
auth_num=1 ;;
"chap")
auth_num=2 ;;
"auto"|"both"|"MsChapV2")
auth_num=3 ;;
*)
auth_num=0 ;;
esac
if [ -n "$username" ] || [ -n "$password" ] && [ "$auth_num" != "0" ] ; then
ppp_auth_command="AT+MGAUTH=$pdp_index,$auth_num,\"$username\",\"$password\""
fi
fi
;;
"unisoc")
at_command="AT+GTRNDIS=1,$pdp_index"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\",\"$apn\""
if [ -n "$auth" ]; then
case $auth in
"pap")
auth_num=1 ;;
"chap")
auth_num=2 ;;
"auto"|"both"|"MsChapV2")
auth_num=3 ;;
*)
auth_num=0 ;;
esac
if [ -n "$username" ] || [ -n "$password" ] && [ "$auth_num" != "0" ] ; then
ppp_auth_command="AT+MGAUTH=$pdp_index,$auth_num,\"$username\",\"$password\""
fi
fi
esac
;;
"huawei")
case $platform in
"hisilicon")
at_command="AT^NDISDUP=1,$pdp_index"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\""
;;
esac
;;
"simcom")
case $platform in
"qualcomm")
local cnmp=$(at ${at_port} "AT+CNMP?" | grep "+CNMP:" | sed 's/+CNMP: //g' | sed 's/\r//g')
at_command="AT+CNMP=$cnmp;+CNWINFO=1"
cgdcont_command="AT+CGDCONT=1,\"$pdp_type\",\"$apn\""
;;
esac
;;
"meig")
case $platform in
"qualcomm")
at_command='AT$QCRMCALL=1,0,3,2,'$pdp_index
cgdcont_command="AT+CGDCONT=1,\"$pdp_type\",\"$apn\""
;;
esac
;;
"neoway")
case $platform in
"unisoc")
at_command='AT$MYUSBNETACT=0,1'
cgdcont_command="AT+CGDCONT=1,\"$pdp_type\",\"$apn\""
;;
esac
;;
"telit")
case $platform in
"qualcomm")
at_command="AT#ICMAUTOCONN=1,$pdp_index"
cgdcont_command="AT+CGDCONT=$pdp_index,\"$pdp_type\",\"$apn\""
;;
esac
;;
esac
m_debug "dialing: vendor:$manufacturer; platform:$platform; driver:$driver; apn:$apn; command:$at_command"
m_debug "dial_cmd: $at_command; cgdcont_cmd: $cgdcont_command; ppp_auth_cmd: $ppp_auth_command"
case $driver in
"mtk_pcie")
mbim_port=$(echo "$at_port" | sed 's/at/mbim/g')
rf_status=$(umbim -d $mbim_port radio|sed -n 's/.*swradiostate: *//p')
[ "$rf_status" = "off" ] && umbim -d $mbim_port radio on
umbim -d $mbim_port disconnect
sleep 1
umbim -d $mbim_port connect 0 --apn $apn
;;
*)
at "${at_port}" "${cgdcont_command}"
[ -n "$ppp_auth_command" ] && at "${at_port}" "$ppp_auth_command"
at "$at_port" "$at_command"
;;
esac
}
ip_change_fm350()
{
m_debug "ip_change_fm350"
local public_dns1_ipv4="223.5.5.5"
local public_dns2_ipv4="119.29.29.29"
local netmask="255.255.255.0"
if [ "$driver" = "mtk_pcie" ]; then
mbim_port=$(echo "$at_port" | sed 's/at/mbim/g')
local config=$(umbim -d $mbim_port config)
ipv4_config=$(echo "$config" | grep "ipv4address:" | awk '{print $2}' | cut -d'/' -f1)
gateway=$(echo "$config" | grep "ipv4gateway:" | awk '{print $2}')
ipv4_dns1=$(echo "$config" | grep "ipv4dnsserver:" | head -n 1 | awk '{print $2}')
ipv4_dns2=$(echo "$config" | grep "ipv4dnsserver:" | tail -n 1 | awk '{print $2}')
[ -z "$ipv4_dns1" ] && ipv4_dns1="$public_dns1_ipv4"
[ -z "$ipv4_dns2" ] && ipv4_dns2="$public_dns2_ipv4"
# m_debug "umbim config: ipv4=$ipv4_config, gateway=$gateway, netmask=$netmask, dns1=$ipv4_dns1, dns2=$ipv4_dns2"
else
at_command="AT+CGPADDR=$pdp_index"
response=$(at ${at_port} ${at_command})
ipv4_config=$(echo "$response" | grep "+CGPADDR:" | grep -o '"[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+"' | head -1 | tr -d '"')
gateway="${ipv4_config%.*}.1"
response=$(at ${at_port} "AT+GTDNS=$pdp_index")
ipv4_dns=$(echo "$response" | grep "+GTDNS:" | head -1)
ipv4_dns1=$(echo "$ipv4_dns" | grep -o '"[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+"' | head -1 | tr -d '"')
ipv4_dns2=$(echo "$ipv4_dns" | grep -o '"[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+"' | tail -1 | tr -d '"')
[ -z "$ipv4_dns1" ] && ipv4_dns1="$public_dns1_ipv4"
[ -z "$ipv4_dns2" ] && ipv4_dns2="$public_dns2_ipv4"
uci_ipv4=$(uci -q get network.$interface_name.ipaddr)
fi
uci set network.${interface_name}.proto='static'
uci set network.${interface_name}.ipaddr="${ipv4_config}"
uci set network.${interface_name}.netmask="${netmask}"
uci set network.${interface_name}.gateway="${gateway}"
uci set network.${interface_name}.peerdns='0'
uci -q del network.${interface_name}.dns
uci add_list network.${interface_name}.dns="${ipv4_dns1}"
uci add_list network.${interface_name}.dns="${ipv4_dns2}"
uci commit network
ifdown ${interface_name}
ifup ${interface_name}
m_debug "set interface $interface_name to $ipv4_config"
}
handle_5gethernet()
{
case $manufacturer in
"quectel")
case $platform in
"qualcomm")
quectel_qualcomm_ethernet
;;
"unisoc")
quectel_unisoc_ethernet
;;
esac
;;
esac
}
quectel_unisoc_ethernet()
{
case "$driver" in
"ncm"|\
"ecm"|\
"rndis")
check_ethernet_cmd="AT+QCFG=\"ethernet\""
time=0
while [ $time -lt 5 ]; do
result=$(at $at_port $check_ethernet_cmd | grep "+QCFG:")
if [ -n "$result" ]; then
if [ -n "$(echo $result | grep "ethernet\",1")" ]; then
echo "1"
m_debug "5G Ethernet mode is enabled"
break
fi
fi
sleep 5
time=$((time+1))
done
;;
esac
}
quectel_qualcomm_ethernet()
{
case "$driver" in
"mbim")
eth_driver_at="AT+QETH=\"eth_driver\""
data_interface_at="AT+QCFG=\"data_interface\""
ehter_driver_expect="\"r8125\",1"
data_interface_expect="\"data_interface\",1"
time=0
while [ $time -lt 5 ]; do
eth_driver_result=$(at $at_port $eth_driver_at | grep "+QETH:")
time=$(($time+1))
sleep 1
if [ -n "$eth_driver_result" ];then
break
fi
done
time=0
while [ $time -lt 5 ]; do
data_interface_result=$(at $at_port $data_interface_at | grep "+QCFG:")
time=$(($time+1))
sleep 1
if [ -n "$data_interface_result" ];then
break
fi
done
eth_driver_pass=$(echo $eth_driver_result | grep "$ehter_driver_expect")
data_interface_pass=$(echo $data_interface_result | grep "$data_interface_expect")
if [ -n "$eth_driver_pass" ] && [ -n "$data_interface_pass" ];then
echo "1"
m_debug "5G Ethernet mode is enabled"
fi
;;
esac
}
handle_ip_change()
{
export ipv4
export ipv6
export connection_status
m_debug "ip changed from $ipv6_cache,$ipv4_cache to $ipv6,$ipv4"
case $manufacturer in
"fibocom")
case $platform in
"mediatek")
ip_change_fm350
;;
esac
;;
esac
}
check_logfile_line()
{
local line=$(wc -l $log_file | awk '{print $1}')
if [ $line -gt 300 ];then
echo "" > $log_file
m_debug "log file line is over 300,clear it"
fi
}
unexpected_response_count=0
at_dial_monitor()
{
at_dial
ipv4_cache=$ipv4
ipv6_cache=$ipv6
sleep 5
while true; do
check_ip
case $connection_status in
0)
at_dial
sleep 3
;;
-1)
unexpected_response_count=$((unexpected_response_count+1))
if [ $unexpected_response_count -gt 3 ]; then
at_dial
unexpected_response_count=0
fi
sleep 5
;;
*)
if [ "$ipv4" != "$ipv4_cache" ] || [ "$ipv6" != "$ipv6_cache" ]; then
handle_ip_change
ipv4_cache=$ipv4
ipv6_cache=$ipv6
fi
pdp_type=$(echo $pdp_type | tr 'A-Z' 'a-z')
if [ "$pdp_type" = "ipv4v6" ]; then
local ifup_time=$(ubus call network.interface.$interface6_name status 2>/dev/null | jsonfilter -e '@.uptime' 2>/dev/null || echo 0)
local origin_device=$(uci -q get network.$interface_name.device 2>/dev/null || echo "")
[ "$ifup_time" -lt 5 ] && continue
rdisc6 $origin_device &
ndisc6 fe80::1 $origin_device &
fi
sleep 15
;;
esac
check_logfile_line
done
}
case "$2" in
"hang")
debug_subject="modem_hang"
update_config
hang;;
"dial")
case "$state" in
"disabled")
debug_subject="modem_hang"
hang;;
*)
dial;;
esac
esac
|
281677160/openwrt-package | 3,767 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/modem_util.sh | #!/bin/sh
# Copyright (C) 2024 Tom <fjrcn@outlook.com>
at()
{
local at_port=$1
local new_str="${2/[$]/$}"
local atcmd="${new_str/\"/\"}"
[ "$clear_buffer" == "1" ] && options="$options -M"
#过滤空行
if [ "$(uci get qmodem.main.at_tool 2>/dev/null)" == "1" ]; then
sms_tool_q -d $at_port at "$atcmd"
else
tom_modem $use_ubus_flag -d $at_port -o a -c "$atcmd" $options
fi
}
fastat()
{
local at_port=$1
local new_str="${2/[$]/$}"
local atcmd="${new_str/\"/\"}"
#过滤空行
if [ "$(uci get qmodem.main.at_tool 2>/dev/null)" == "1" ]; then
sms_tool_q -t 1 -d $at_port at "$atcmd"
else
tom_modem -d $at_port -o a -c "$atcmd" -t 1
fi
}
log2file()
{
local subject="$1"
local msg="$2"
local path="$3"
#打印日志
local update_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "[${update_time}] ${subject}:${msg} " >> "${path}"
}
log2sys()
{
local subject="$1"
local msg="$2"
logger -t "$subject" "$msg"
}
m_debug ()
{
[ -z "$debug_subject" ] && subject="modem_util" || subject="$debug_subject"
[ -n "$direct_debug" ] && echo "$subject" "$1"
if [ -n "$log_file" ];then
log2file "$subject" "$1" "$log_file"
else
log2sys "$subject" "$1"
fi
}
update_sim_slot()
{
. /lib/functions.sh
board=$(board_name)
case $board in
HC,HC-G80*)
sim_pin="/sys/class/gpio/sim/value"
sim_pin_value=$(cat $sim_pin)
[ "$sim_pin_value" == "0" ] && sim_slot="2" || sim_slot="1"
#电平高表示SIM卡在卡槽1,电平低表示SIM卡在卡槽2
debug "update_sim_slot:sim_slot=$sim_slot"
;;
ailf,gs2410|\
huasifei,ws3006)
sim_pin="/sys/class/gpio/dual_sim/value"
#电平高则都在卡槽1,电平低则需要使用at查询
[ "$(cat $sim_pin)" == "1" ] && sim_slot="1" || at_get_slot
;;
*)
at_get_slot
;;
esac
}
at_get_slot()
{
case $vendor in
"quectel")
at_res=$(at $at_port AT+QSIMDET? |grep +QSIMDET: |awk -F: '{print $2}')
case "$at_res" in
"1")
sim_slot="1"
;;
"2")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
"fibocom")
at_res=$(at $at_port AT+GTDUALSIM? |grep +GTDUALSIM: |awk -F: '{print $2}')
case $at_res in
"0")
sim_slot="1"
;;
"1")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
"simcom")
at_res=$(at $at_port AT+SMSIMCFG? | grep "+SMSIMCFG:" | awk -F',' '{print $2}' | sed 's/\r//g')
case $at_res in
"1")
sim_slot="1"
;;
"2")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
"meig")
at_res=$(at $at_port AT^SIMSLOT? | grep "\^SIMSLOT:" | awk -F': ' '{print $2}' | awk -F',' '{print $2}')
case $at_res in
"1")
sim_slot="1"
;;
"0")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
"neoway")
at_res=$(at $at_port 'AT+SIMCROSS?' | grep "+SIMCROSS:" | awk -F'[ ,]' '{print $2}' | sed 's/\r//g')
case $at_res in
"1")
sim_slot="1"
;;
"2")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
"telit")
at_res=$(at $at_port AT#QSS? | grep "#QSS:" | awk -F',' '{print $3}' | sed 's/\r//g')
case $at_res in
"0")
sim_slot="1"
;;
"1")
sim_slot="2"
;;
*)
sim_slot="1"
;;
*)
sim_slot="1"
;;
esac
;;
*)
at_q_res=$(at $at_port AT+QSIMDET? |grep +QSIMDET: |awk -F: '{print $2}')
at_f_res=$(at $at_port AT+GTDUALSIM? |grep +GTDUALSIM: |awk -F: '{print $2}')
[ "$at_q_res" == "1" ] && sim_slot="1" && return
[ "$at_q_res" == "2" ] && sim_slot="2" && return
[ "$at_f_res" == "0" ] && sim_slot="1" && return
[ "$at_f_res" == "1" ] && sim_slot="2" && return
sim_slot="1"
;;
esac
}
|
281677160/openwrt-package | 8,998 | luci-app-qmodem/application/qmodem/files/usr/share/qmodem/modem_ctrl.sh | #!/bin/sh
source /usr/share/libubox/jshn.sh
method=$1
config_section=$2
at_port=$(uci get qmodem.$config_section.at_port)
override_at_port=$(uci get qmodem.$config_section.override_at_port)
[ -n "$override_at_port" ] && at_port=$override_at_port
uci -q get qmodem.$config_section.sms_at_port >/dev/null && sms_at_port=$(uci get qmodem.$config_section.sms_at_port)
vendor=$(uci get qmodem.$config_section.manufacturer)
platform=$(uci get qmodem.$config_section.platform)
pdp_index=$(uci get qmodem.$config_section.pdp_index)
[ -z "$pdp_index" ] && pdp_index=$(uci get qmodem.$config_section.suggest_pdp_index)
use_ubus=$(uci get qmodem.$config_section.use_ubus)
modem_path=$(uci get qmodem.$config_section.path)
modem_slot=$(basename $modem_path)
[ -z "$pdp_index" ] && {
pdp_index="1"
}
[ $use_ubus -eq 1 ] && use_ubus_flag="-u"
#please update dynamic_load.json to add new vendor
vendor_script_prefix="/usr/share/qmodem/vendor"
dynamic_load_json="$vendor_script_prefix/dynamic_load.json"
vendor_file="${vendor_script_prefix}/`jq -r --arg vendor $vendor '.[$vendor]' $dynamic_load_json`"
if [ -z "$vendor" ] || [ ! -f "$vendor_file" ]; then
logger -t modem_ctrl "vendor $vendor not support"
. /usr/share/qmodem/generic.sh
fi
. $vendor_file
try_cache() {
cache_timeout=$1
cache_file=$2
function_name=$3
current_time=$(date +%s)
file_time=$(stat -t $cache_file | awk '{print $14}')
[ -z "$file_time" ] && file_time=0
if [ ! -f $cache_file ] || [ $(($current_time - $file_time)) -gt $cache_timeout ]; then
touch $cache_file
json_add_array modem_info
$function_name
json_close_array
json_dump > $cache_file
return 1
else
cat $cache_file
exit 0
fi
}
get_sms(){
[ -n "$sms_at_port" ] && at_port=$sms_at_port
cache_timeout=$1
cache_file=$2
current_time=$(date +%s)
file_time=$(stat -t $cache_file | awk '{print $14}')
[ -z "$file_time" ] && file_time=0
get_sms_capabilities
if [ ! -f $cache_file ] || [ $(($current_time - $file_time)) -gt $cache_timeout ]; then
touch $cache_file
#sms_tool_q -d $at_port -j recv > $cache_file
tom_modem $use_ubus_flag -d $at_port -o r > $cache_file
echo $(cat $cache_file ; json_dump) | jq -s 'add'
else
echo $(cat $cache_file ; json_dump) | jq -s 'add'
fi
}
get_at_cfg(){
json_add_object at_cfg
duns=$(ls /dev/mhi_DUN*)
ttys=$(ls /dev/ttyUSB*)
ttyacms=$(ls /dev/ttyACM*)
wwanNatN=$(ls /dev/wwan* |grep -E wwan[0-9]at[0-9])
all_ttys="$duns $ttys $ttyacms $wwanNatN"
json_add_array other_ttys
for tty in $all_ttys; do
[ -n "$tty" ] && json_add_string "" "$tty"
done
json_close_array
json_add_array ports
ports=$(uci get qmodem.$config_section.ports)
for port in $ports; do
json_add_string "" "$port"
done
json_close_array
json_add_array valid_ports
v_ports=$(uci get qmodem.$config_section.valid_at_ports)
for port in $v_ports; do
json_add_string "" "$port"
done
json_close_array
override_at_port=$(uci get qmodem.$config_section.override_at_port)
at_port=$(uci get qmodem.$config_section.at_port)
[ -n "$override_at_port" ] && at_port=$override_at_port
json_add_string using_port "$at_port"
json_add_array cmds
# Determine language and select appropriate AT commands file
lang=$(uci get luci.main.lang 2>/dev/null || echo "en")
case "$lang" in
zh*|cn|auto)
at_commands_file="/usr/share/qmodem/at_commands_zh.json"
;;
*)
at_commands_file="/usr/share/qmodem/at_commands_en.json"
;;
esac
# Fallback to default file if language-specific file doesn't exist
[ ! -f "$at_commands_file" ] && at_commands_file="/usr/share/qmodem/at_commands.json"
general_cmd=$(jq -rc '.general[]|to_entries| .[] | @sh "key=\(.key) value=\(.value)"' "$at_commands_file")
platform_cmd=$(jq -rc ".${vendor}.${platform}[]|to_entries| .[] | @sh \"key=\(.key) value=\(.value)\"" "$at_commands_file")
[ -z "$platform_cmd" ] && platform_cmd=$(jq -rc ".$vendor.general[]|to_entries| .[] | @sh \"key=\(.key) value=\(.value)\"" "$at_commands_file")
cmds=$(echo -e "$general_cmd\n$platform_cmd")
IFS=$'\n'
for cmd in $cmds; do
json_add_object cmd
eval $cmd
json_add_string "name" "$key"
json_add_string "value" "$value"
json_close_object
done
json_close_array
json_close_object
json_dump
unset IFS
}
#会初始化一个json对象 命令执行结果会保存在json对象中
json_init
json_add_object result
json_close_object
case $method in
"base_info")
cache_file="/tmp/cache_$1_$2"
try_cache 10 $cache_file base_info
;;
"cell_info")
cache_file="/tmp/cache_$1_$2"
try_cache 10 $cache_file cell_info
;;
"clear_dial_log")
json_select result
log_file="/var/run/qmodem/${config_section}_dir/dial_log"
[ -f $log_file ] && echo "" > $log_file && json_add_string status "1" || json_add_string status "0"
json_close_object
;;
"delete_sms")
json_select result
index=$3
[ -n "$sms_at_port" ] && at_port=$sms_at_port
for i in $index; do
tom_modem $use_ubus_flag -d $at_port -o d -i $i
touch /tmp/cache_sms_$2
if [ "$?" == 0 ]; then
json_add_string status "1"
json_add_string "index$i" "tom_modem $use_ubus_flag -d $at_port -o d -i $i"
else
json_add_string status "0"
fi
done
json_close_object
rm -rf /tmp/cache_sms_$2
;;
"do_reboot")
reboot_method=$(echo $3 |jq -r '.method')
echo $3 > /tmp/555/reboot
case $reboot_method in
"hard")
hard_reboot
;;
"soft")
soft_reboot
;;
esac
;;
"get_at_cfg")
get_at_cfg
exit
;;
"get_copyright")
_copyright
;;
"get_disabled_features")
json_add_array disabled_features
vendor_get_disabled_features
get_modem_disabled_features
get_global_disabled_features
json_close_array
;;
"get_dns")
get_dns
;;
"get_imei")
get_imei
;;
"get_lockband")
get_lockband
;;
"get_mode")
get_mode
;;
"get_neighborcell")
get_neighborcell
;;
"get_network_prefer")
get_network_prefer
;;
"get_reboot_caps")
get_reboot_caps
exit
;;
"get_sms")
get_sms 10 /tmp/cache_sms_$2
exit
;;
"info")
cache_file="/tmp/cache_$1_$2"
try_cache 10 $cache_file get_info
;;
"network_info")
cache_file="/tmp/cache_$1_$2"
try_cache 10 $cache_file network_info
;;
"send_at")
cmd=$(echo "$3" | jq -r '.at')
port=$(echo "$3" | jq -r '.port')
res=$(at $port $cmd)
json_add_object at_cfg
if [ "$?" == 0 ]; then
json_add_string status "1"
json_add_string cmd "at $port $cmd"
json_add_string "res" "$res"
else
json_add_string status "0"
fi
;;
"send_raw_pdu")
cmd=$3
[ -n "$sms_at_port" ] && at_port=$sms_at_port
res=$(tom_modem $use_ubus_flag -d $at_port -o s -p "$cmd")
json_select result
if [ "$?" == 0 ]; then
json_add_string status "1"
json_add_string cmd "tom_modem $use_ubus_flag -d $at_port -o s -p \"$cmd\""
json_add_string "res" "$res"
else
json_add_string status "0"
fi
;;
"send_sms")
cmd_json=$3
phone_number=$(echo $cmd_json | jq -r '.phone_number')
message_content=$(echo $cmd_json | jq -r '.message_content')
[ -n "$sms_at_port" ] && at_port=$sms_at_port
sms_tool_q -d $at_port send "$phone_number" "$message_content" > /dev/null
json_select result
if [ "$?" == 0 ]; then
json_add_string status "1"
json_add_string cmd "sms_tool_q -d $at_port send \"$phone_number\" \"$message_content\""
json_add_string "cmd_json" "$cmd_json"
else
json_add_string status "0"
fi
json_close_object
;;
"set_imei")
set_imei $3
;;
"set_lockband")
set_lockband $3
;;
"set_mode")
set_mode $3
;;
"set_neighborcell")
set_neighborcell $3
;;
"set_network_prefer")
set_network_prefer $3
;;
"set_sms_storage")
set_sms_storage $3
;;
"sim_info")
cache_file="/tmp/cache_$1_$2"
try_cache 10 $cache_file sim_info
;;
esac
json_dump
|
281677160/openwrt-package | 3,714 | luci-app-qmodem/application/qmodem/files/etc/init.d/qmodem_init | #!/bin/sh /etc/rc.common
START=80
STOP=30
USE_PROCD=1
. /lib/functions.sh
start_service() {
config_load qmodem
config_foreach _mk_rundir modem-device
config_get block_auto_probe main block_auto_probe 0
config_get enable_pcie_scan main enable_pcie_scan 0
config_get enable_usb_scan main enable_usb_scan 0
config_get try_preset_usb main try_preset_usb 1
config_get try_preset_pcie main try_preset_pcie 1
#once enabled, skip all check or scan
[ "$block_auto_probe" -eq 1 ] && return
#enabled by default
if [ "$try_preset_pcie" -eq 1 ];then
_try_vendor_preset_pcie
fi
if [ "$try_preset_usb" -eq 1 ];then
_try_vendor_preset_usb
fi
#not enabled by default
if [ "$enable_usb_scan" -eq 1 ];then
_scan_usb
fi
if [ "$enable_pcie_scan" -eq 1 ];then
_scan_pcie
fi
}
boot() {
local delay=$(uci -q get qmodem.main.start_delay || echo 0)
if [ "$delay" -gt 0 ]; then
logger "Delay QModem Boot init scan for $delay S"
sleep $delay
/usr/share/qmodem/modem_scan.sh scan >/dev/null 2>&1 &
fi
start
}
_try_vendor_preset_usb()
{
config_foreach _try_usb_device modem-device
config_foreach _try_usb_slot modem-slot
}
_try_vendor_preset_pcie()
{
config_foreach _try_pcie_device modem-device
config_foreach _try_pcie_slot modem-slot
}
_try_pcie_slot()
{
config_get type "$1" type
[ "$type" == "pcie" ] && _try_slot $1
}
_try_usb_slot()
{
config_get type "$1" type
[ "$type" == "usb" ] && _try_slot $1
}
_try_usb_device()
{
config_get data_interface $1 data_interface
[ "$data_interface" == "usb" ] && _try_device
}
_try_pcie_device()
{
config_get data_interface $1 data_interface
[ "$data_interface" == "pcie" ] && _try_device
}
_scan_usb()
{
procd_open_instance "scan_usb"
#delay 15 second ,scan all usb device
procd_set_param command "ash" "/usr/share/qmodem/modem_scan.sh" "scan" "15" "usb"
procd_close_instance
}
_scan_pcie()
{
procd_open_instance "scan_pcie"
#delay 15 second ,scan all pcie device
procd_set_param command "ash" "/usr/share/qmodem/modem_scan.sh" "scan" "15" "pcie"
procd_close_instance
}
_mk_rundir()
{
modem_cfg="$1"
mkdir -p "/var/run/qmodem/${modem_cfg}_dir"
}
_try_slot()
{
config_get slot "$1" slot
config_get type "$1" type
case "$type" in
usb)
path="/sys/bus/usb/devices/${slot}"
;;
pcie)
path="/sys/bus/pci/devices/${slot}"
;;
esac
if [ -d "$path" ]; then
logger -t modem_init "try modem $1"
procd_open_instance "try_$1"
procd_set_param command "ash" "/usr/share/qmodem/modem_scan.sh" "add" "$slot" "$type"
procd_close_instance
else
/usr/share/qmodem/modem_scan.sh disable "$slot"
fi
}
_try_device()
{
config_get path "$1" path
config_get type "$1" type
config_get network "$1" network
case "$type" in
usb)
path="/sys/bus/usb/devices/${path}"
;;
pcie)
path="/sys/bus/pci/devices/${path}"
;;
esac
if [ ! -d "$path" ]; then
/usr/share/qmodem/modem_scan.sh disable "$1"
return
fi
# if device_path not parent of netdevice_path,then disable device path an scan again
netdevice_path=`readlink -f /sys/class/net/$network/device/`
device_path=`readlink -f $path`
is_parent=`echo "$device_path" | grep -q "^$netdevice_path"`
if [ -z "$is_parent" ] || [ ! -d "$netdevice_path" ]; then
/usr/share/qmodem/modem_scan.sh disable "$1"
/usr/share/qmodem/modem_scan.sh add "$path" "$slot"
fi
}
|
281677160/openwrt-package | 2,269 | luci-app-qmodem/application/qmodem/files/etc/init.d/qmodem_network | #!/bin/sh /etc/rc.common
START=99
STOP=13
USE_PROCD=1
service="$(basename ${basescript:-$initscript})"
#脚本目录
SCRIPT_DIR="/usr/share/qmodem"
#运行目录
MODEM_RUNDIR="/var/run/qmodem"
extra_command "dial" "<modem_cfg> run dial script"
extra_command "hang" "<modem_cfg> run hang script"
extra_command "redial" "<modem_cfg> stop previous dial script. run hang script. and run dial script"
extra_command "modem_status" "<modem_cfg> Check dial script status"
service_triggers()
{
procd_add_reload_trigger "qmodem"
}
start_service(){
force_stop=0
mkdir -p $MODEM_RUNDIR
update_modem
}
stop_service(){
force_stop=1
update_modem
}
reload_service()
{
force_stop=0
mkdir -p $MODEM_RUNDIR
sleep 1
update_modem
}
update_modem(){
config_load qmodem
config_get g_enabled main enable_dial
config_foreach _update_modem modem-device
}
dial()
{
rc_procd _dial $1
}
hang()
{
_hang $1
}
modem_status()
{
_modem_status $1
}
redial()
{
hang $1
dial $1
}
_update_modem()
{
local target
target=1
config_get enabled $1 enable_dial
config_get state $1 state
if [ "$state" = "disabled" ] || [ "$enabled" = "0" ] || [ "$g_enabled" = "0" ] || [ "$force_stop" = "1" ];then
target=0
fi
data=$(_procd_ubus_call list | jq -r ".$service.instances.modem_$1")
[ "$data" == "null" ] && current_status=0 || current_status=1
logger -t qmodem_network "cfg:$1 current:$current_status;target:$target "
if [ "$current_status" != "$target" ];then
[ "$target" -eq 1 ] && dial $1 || hang $1
logger -t qmodem_network "update modem cfg: $1 dial:$target"
fi
}
_dial()
{
procd_open_instance "modem_$1"
procd_set_param command "/usr/share/qmodem/modem_dial.sh" "$1" dial
procd_set_param respawn 120 15 10
procd_close_instance
logger -t qmodem_network "Modem $1 Start Dial Now"
}
_hang()
{
procd_kill $service "modem_$1"
/usr/share/qmodem/modem_dial.sh "$1" hang
logger -t qmodem_network "Modem $1 Stop Dial and Hang"
}
_modem_status()
{
local instances="modem_$1"
local data
data=$(_procd_ubus_call list | jq -r ".$service.instances.$instances")
[ "$data" == "null" ] && echo "$instances Not Running" || echo "$data"
}
|
281677160/openwrt-package | 5,049 | luci-app-qmodem/application/qmodem/files/etc/uci-defaults/99-add-5g-handler | #!/bin/sh
. /lib/functions.sh
. /lib/functions/uci-defaults.sh
. /lib/functions/system.sh
modem_settings()
{
local board="$1"
case $board in
arcadyan,aw1000)
#usb slot
uci set qmodem.usb0="modem-slot"
uci set qmodem.usb0.slot="4-1"
uci set qmodem.usb0.type="usb"
uci set qmodem.usb0.net_led="ipq::led9"
uci set qmodem.usb0.sim_led="ipq::led2"
uci set qmodem.usb0.alias="wwan0"
#pcie slot
uci set qmodem.pcie0="modem-slot"
uci set qmodem.pcie0.slot="0000:01:00.0"
uci set qmodem.pcie0.type="pcie"
uci set qmodem.pcie0.net_led="ipq::led9"
uci set qmodem.pcie0.sim_led="ipq::led2"
uci set qmodem.pcie0.associated_usb='4-1'
uci set qmodem.pcie0.alias="wwan1"
uci commit qmodem
;;
hiveton,h5000m)
#usb slot
uci set qmodem.usb0="modem-slot"
uci set qmodem.usb0.slot="2-1"
uci set qmodem.usb0.type="usb"
uci set qmodem.usb0.alias="USB"
uci set qmodem.main.enable_pcie_scan='0'
uci set qmodem.main.start_delay='9'
uci commit qmodem
;;
HC,HC-G80*)
#mini pci slot
uci set qmodem.mini_pci="modem-slot"
uci set qmodem.mini_pci.slot="1-1.4"
uci set qmodem.mini_pci.type="usb"
#m.2 slot (usb2.0)
uci set qmodem.m2_u2="modem-slot"
uci set qmodem.m2_u2.slot="1-1.1"
uci set qmodem.m2_u2.type="usb"
uci set qmodem.m2_u2.ethernet_5g="cpewan0"
#m.2 slot (usb3.0)
uci set qmodem.m2_u3="modem-slot"
uci set qmodem.m2_u3.slot="2-1"
uci set qmodem.m2_u3.type="usb"
uci set qmodem.m2_u3.ethernet_5g="cpewan0"
uci commit qmodem
;;
ailf,gs2410|\
huasifei,ws3006)
#m2 usb3.0
#(slot 2)
add_usb_slot_cfg "5g1" "2-1.2" "5g1" "green:5g2" "green:sim2" "m2_reset_2" "1" "0" "5"
#(slot 1)
add_usb_slot_cfg "5g0" "2-1.4" "5g0" "green:5g1" "green:sim1" "m2_reset_1" "1" "0" "6"
#m2 usb2.0
#(slot 2)
add_usb_slot_cfg "4g3" "1-1.1" "4g3" "green:5g2" "green:sim2" "m2_reset_2" "1" "0" "20"
#(slot 1)
add_usb_slot_cfg "4g2" "1-1.4" "4g2" "green:5g1" "green:5g1" "m2_reset_1" "1" "0" "21"
#mini pci slot
#(slot 2)
add_usb_slot_cfg "4g1" "1-1.2" "4g1" "green:5g2" "green:sim2" "" "" "" "22"
#(slot 1)
add_usb_slot_cfg "4g0" "1-1.3" "4g0" "green:5g1" "green:sim1" "" "" "" "23"
uci commit qmodem
;;
huasifei,ws3009)
#m2 usb3.0
#(slot 2)
add_usb_slot_cfg "5g1" "2-1.2" "5g1" "green:network1" "" "m2_reset_1" "1" "0" "5"
#(slot 1)
add_usb_slot_cfg "5g0" "2-1.4" "5g0" "green:network2" "" "m2_reset_1" "1" "0" "6"
#(slot 2)
add_usb_slot_cfg "5g2" "2-1.1" "5g2" "green:network3" "" "m2_reset_2" "1" "0" "7"
#m2/pcie usb2.0
#(slot 1)
add_usb_slot_cfg "4g0" "1-1.3" "4g0" "green:network1" "" "" "" "" "20"
#(slot 2)
add_usb_slot_cfg "4g1" "1-1.4" "4g3" "green:network2" "" "" "" "" "21"
#(slot 3)
add_usb_slot_cfg "4g2" "1-1.1" "4g4" "green:network3" "" "" "" "" "22"
uci commit qmodem
;;
sagemcom,5866t)
add_usb_slot_cfg "5g_usb" "1-1" "5g_usb" "LED5_G" "LED4_G" "" "" "" "10"
add_pcie_slot_cfg "5g_pcie" "0000:01:00.0" "5g_pcie" "LED5_G" "LED4_G" "1-1" "" "" "" "10"
uci commit qmodem
;;
cyber,cyber3588-aib)
add_usb_slot_cfg "5g_usb0" "8-1" "5g_usb0" "blue:status" "green:status" "" "" "" "10"
add_pcie_slot_cfg "5g_pcie0" "0001:11:00.0" "5g_pcie0" "blue:status" "green:status" "8-1" "" "" "" "10"
uci commit qmodem
;;
mt7981,stx1170-gsw)
add_usb_slot_cfg "5g_usb0" "2-1" "5g_usb0" "" "" "" "" "" "10"
uci commit qmodem
;;
esac
}
add_usb_slot_cfg()
{
cfg=$1
cfg_slot=$2
alias=$3
net_led=$4
sim_led=$5
gpio=$6
gpio_up=$7
gpio_down=$8
default_metric=$9
uci set qmodem.${cfg}=modem-slot
uci set qmodem.${cfg}.type=usb
[ -n "$cfg_slot" ] && uci set qmodem.${cfg}.slot=${cfg_slot}
[ -n "$net_led" ] && uci set qmodem.${cfg}.net_led=${net_led}
[ -n "$alias" ] && uci set qmodem.${cfg}.alias=${alias}
[ -n "$sim_led" ] && uci set qmodem.${cfg}.sim_led=${sim_led}
[ -n "$associated_usb" ] && uci set qmodem.${cfg}.associated_usb=${associated_usb}
[ -n "$gpio" ] && uci set qmodem.${cfg}.gpio=${gpio}
[ -n "$gpio_up" ] && uci set qmodem.${cfg}.gpio_up=${gpio_up}
[ -n "$gpio_down" ] && uci set qmodem.${cfg}.gpio_down=${gpio_down}
[ -n "$default_metric" ] && uci set qmodem.${cfg}.default_metric=${default_metric}
}
add_pcie_slot_cfg()
{
cfg=$1
cfg_slot=$2
alias=$3
net_led=$4
sim_led=$5
associated_usb=$6
gpio=$7
gpio_up=$8
gpio_down=${9}
default_metric=${10}
uci set qmodem.${cfg}=modem-slot
uci set qmodem.${cfg}.type=pcie
[ -n "$cfg_slot" ] && uci set qmodem.${cfg}.slot=${cfg_slot}
[ -n "$net_led" ] && uci set qmodem.${cfg}.net_led=${net_led}
[ -n "$alias" ] && uci set qmodem.${cfg}.alias=${alias}
[ -n "$sim_led" ] && uci set qmodem.${cfg}.sim_led=${sim_led}
[ -n "$associated_usb" ] && uci set qmodem.${cfg}.associated_usb=${associated_usb}
[ -n "$gpio" ] && uci set qmodem.${cfg}.gpio=${gpio}
[ -n "$gpio_up" ] && uci set qmodem.${cfg}.gpio_up=${gpio_up}
[ -n "$gpio_down" ] && uci set qmodem.${cfg}.gpio_down=${gpio_down}
[ -n "$default_metric" ] && uci set qmodem.${cfg}.default_metric=${default_metric}
}
board=$(board_name)
modem_settings $board
exit 0
|
281677160/openwrt-package | 2,093 | luci-app-qmodem/application/qmodem/files/etc/hotplug.d/net/20-modem-net | #!/bin/sh
# Copyright (C) 2024 Tom <fjrcn@outlook.com>
manual=$(uci -q get qmodem.main.block_auto_probe)
[ "${manual}" -eq 1 ] && exit
logger -t modem_hotplug "net slot: ${DEVPATH} action: ${ACTION}"
#网络设备名称不存在,退出
[ -z "${INTERFACE}" ] && exit
#网络设备路径不存在,退出
[ -z "${DEVPATH}" ] && exit
slot_path=$(readlink -f "/sys/${DEVPATH}/device")
[ -z "${slot_path}" ] && exit
slot=$(basename "$(dirname "${slot_path}")")
if [ -d "/sys/bus/usb/devices/${slot}" ]; then
slot_type="usb"
elif [ -d "/sys/bus/pci/devices/${slot}" ]; then
slot_type="pcie"
else
exit
fi
if [ "${slot_type}" = "usb" ]; then
vendor_file="/sys/bus/usb/devices/${slot}/idVendor"
product_file="/sys/bus/usb/devices/${slot}/idProduct"
if [ -f "${vendor_file}" ] && [ -f "${product_file}" ]; then
slot_vid=$(cat "${vendor_file}")
slot_pid=$(cat "${product_file}")
if [ -n "$slot_vid" ] && [ -n "$slot_pid" ]; then
modem_port_rule=$(cat /usr/share/qmodem/modem_port_rule.json)
modem_port_config=$(echo $modem_port_rule | jq '.modem_port_rule."'$slot_type'"."'$slot_vid:$slot_pid'"')
if [ "$modem_port_config" != "null" ] && [ -n "$modem_port_config" ]; then
config_modem_name=$(echo $modem_port_config | jq -r '.name')
include_ports=$(echo $modem_port_config | jq -r '.include[]')
[ -n "$include_ports" ] && {
logger -t modem_hotplug "using special config for $config_modem_name($slot_vid:$slot_pid) with ports: $include_ports"
echo "$slot_vid $slot_pid" > /sys/bus/usb-serial/drivers/option1/new_id 2>/dev/null ||
logger -t modem_hotplug "failed to set option driver"
}
fi
else
logger -t modem_hotplug "Unable to read VID/PID from device: $slot"
fi
fi
fi
logger -t modem_hotplug "net slot: ${slot} action: ${ACTION} slot_type: ${slot_type}"
case "${ACTION}" in
add)
/usr/share/qmodem/modem_scan.sh add "${slot}" "${slot_type}"
;;
esac
|
281677160/openwrt-package | 3,752 | luci-app-qmodem/application/tom_modem/src/modem_types.h |
#ifndef _MODEM_TYPES_H_
#define _MODEM_TYPES_H_
#include <stdio.h>
#include <termios.h>
#include <time.h>
//options
#define AT_CMD_S 'c'
#define TTY_DEV_S 'd'
#define BAUD_RATE_S 'b'
#define DATA_BITS_S 'B'
#define PARITY_S 'P'
#define STOP_BITS_S 'S'
#define FLOW_CONTROL_S 'F'
#define TIMEOUT_S 't'
#define OPERATION_S 'o'
#define DEBUG_S 'D'
#define SMS_PDU_S 'p'
#define SMS_INDEX_S 'i'
#define GREEDY_READ_S 'g'
#define USE_UBUS_S 'u'
#define AT_CMD_L "at_cmd"
#define TTY_DEV_L "tty_dev"
#define BAUD_RATE_L "baud_rate"
#define DATA_BITS_L "data_bits"
#define PARITY_L "parity"
#define STOP_BITS_L "stop_bits"
#define FLOW_CONTROL_L "flow_control"
#define TIMEOUT_L "timeout"
#define OPERATION_L "operation"
#define DEBUG_L "debug"
#define SMS_PDU_L "sms_pdu"
#define SMS_INDEX_L "sms_index"
#define GREEDY_READ_L "greedy_read"
#define USE_UBUS_L "use_ubus"
//operations
#define AT_OP_S 'a'
#define AT_OP_L "at"
#define BINARY_AT_OP_S 'b'
#define BINARY_AT_OP_L "binary_at"
#define SMS_READ_OP_S 'r'
#define SMS_READ_OP_L "sms_read"
#define SMS_SEND_OP_S 's'
#define SMS_SEND_OP_L "sms_send"
#define SMS_DELETE_OP_S 'd'
#define SMS_DELETE_OP_L "sms_delete"
#define SMS_UNREAD_OP_S 'u'
#define SMS_UNREAD_OP_L "unread_sms"
#define SMS_MARK_READ_OP_S 'm'
#define SMS_MARK_READ_OP_L "mark_read"
#define AT_SENDONLY_OP_S 'o'
#define AT_SENDONLY_OP_L "at_sendonly"
#ifdef USE_SEMAPHORE
#define CLEANUP_SEMAPHORE_OP_S 'C'
#define CLEANUP_SEMAPHORE_OP_L "cleanup"
#endif
#define SET_READ_STORAGE "AT+CPMS=\"%s\""
#define SET_PDU_FORMAT "AT+CMGF=0"
#define READ_ALL_SMS "AT+CMGL=4"
#define READ_UNREAD_SMS "AT+CMGL=0"
#define MARK_SMS_READ "AT+CMGR=%d"
#define SEND_SMS "AT+CMGS=%d\r\n"
#define DELETE_SMS "AT+CMGD=%d"
#define SMS_BUF_SIZE 65536
#define LINE_BUF 1024
#define SMS_LIST_SIZE 128
#define COMMON_BUF_SIZE 65536
#define PHONE_NUMBER_SIZE 64
#define SMS_TEXT_SIZE 256
#define SMS_PDU_STR_SIZE 512
#define SMS_PDU_HEX_SIZE 512
// Transport layer enumeration
typedef enum {
TRANSPORT_TTY = 0,
TRANSPORT_UBUS = 1
} transport_type_t;
// at_tool profile
typedef struct _PROFILE {
// AT command
// TTY device
// Baud rate
// Data bits
// Parity
// Stop bits
// Flow control
// Timeout
// operation
// debug mode
char *at_cmd;
char *tty_dev;
int baud_rate;
int data_bits;
char *parity;
int stop_bits;
char *flow_control;
int timeout;
int op;
int debug;
char *sms_pdu;
int sms_index;
int greedy_read;
transport_type_t transport; // Choose between TTY and UBUS
void *transport_ctx; // Transport-specific context
} PROFILE_T;
typedef struct _FDS {
int tty_fd;
struct termios old_termios;
FILE *fdi;
FILE *fdo;
} FDS_T;
typedef struct _SMS {
int sms_index;
int sms_lenght;
int ref_number;
int segment_number;
time_t timestamp;
int total_segments;
int type;
char *sender;
char *sms_text;
char *sms_pdu;
} SMS_T;
typedef struct _AT_MESSAGE {
char *message;
int len;
} AT_MESSAGE_T;
enum ERROR_CODES {
COMM_ERROR = -1,
SUCCESS = 0,
KEYWORD_NOT_MATCH,
TIMEOUT_WAITING_NEWLINE,
INVALID_PARAM,
INVALID_HEX,
UNKNOWN_ERROR,
BUFFER_OVERFLOW,
};
enum SMS_CHARSET {
SMS_CHARSET_7BIT,
SMS_CHARSET_UCS2
};
enum OPTIONS {
AT_CMD,
TTY_DEV,
BAUD_RATE,
DATA_BITS,
PARITY,
STOP_BITS,
FLOW_CONTROL,
TIMEOUT,
OPERATION,
DEBUG,
SMS_PDU,
SMS_INDEX,
GREEDY_READ,
USE_UBUS
};
enum OPERATIONS {
NULL_OP,
AT_OP,
BINARY_AT_OP,
SMS_READ_OP,
SMS_SEND_OP,
SMS_DELETE_OP,
SMS_UNREAD_OP,
SMS_MARK_READ_OP,
AT_SENDONLY_OP,
CLEANUP_SEMAPHORE_OP
};
#endif
|
281677160/openwrt-package | 8,415 | luci-app-qmodem/application/tom_modem/src/operations.c | #include "operations.h"
int at(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
char *response_text = NULL;
if (profile->at_cmd == NULL)
{
err_msg("AT command is empty");
return INVALID_PARAM;
}
int result = transport_send_at_with_response(transport, profile, profile->at_cmd, NULL, 0, &response_text);
if (response_text) {
user_msg("%s", response_text);
free(response_text);
}
return result;
}
int binary_at(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
char *response_text = NULL;
if (profile->at_cmd == NULL)
{
err_msg("AT command is empty");
return INVALID_PARAM;
}
if (strlen(profile->at_cmd) % 2 != 0)
{
err_msg("Invalid AT command length");
return INVALID_PARAM;
}
// Send as raw hex command
int result = transport_send_at_with_response(transport, profile, profile->at_cmd, "OK", 1, &response_text);
if (response_text) {
user_msg("%s", response_text);
free(response_text);
}
return result;
}
int sms_delete(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
if (profile->sms_index < 0)
{
err_msg("SMS index is empty");
return INVALID_PARAM;
}
char delete_sms_cmd[32];
snprintf(delete_sms_cmd, 32, DELETE_SMS, profile->sms_index);
int result = transport_send_at_with_response(transport, profile, delete_sms_cmd, "OK", 0, NULL);
if (result != SUCCESS) {
dbg_msg("Error deleting SMS, error code: %d", result);
}
return result;
}
int sms_read(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
SMS_T *sms_list[SMS_LIST_SIZE];
SMS_T *sms;
char *response_text = NULL;
int result;
// Set PDU format
result = transport_send_at_with_response(transport, profile, SET_PDU_FORMAT, "OK", 0, NULL);
if (result != SUCCESS)
{
dbg_msg("Error setting PDU format, error code: %d", result);
return result;
}
dbg_msg("Set PDU format success");
// Read all SMS
result = transport_send_at_with_response(transport, profile, READ_ALL_SMS, "OK", 0, &response_text);
if (result != SUCCESS)
{
dbg_msg("Error reading SMS, error code: %d", result);
return result;
}
if (response_text)
{
char *line = strtok(response_text, "\n");
int sms_count = 0;
while (line != NULL)
{
if (strncmp(line, "+CMGL:", 6) == 0)
{
sms = (SMS_T *)malloc(sizeof(SMS_T));
memset(sms, 0, sizeof(SMS_T));
char *pdu = strtok(NULL, "\n");
sms->sms_pdu = (char *)malloc(strlen(pdu));
sms->sender = (char *)malloc(PHONE_NUMBER_SIZE);
sms->sms_text = (char *)malloc(SMS_TEXT_SIZE);
sms->sms_index = get_sms_index(line);
memcpy(sms->sms_pdu, pdu, strlen(pdu));
int sms_len = decode_pdu(sms);
if (sms_len > 0)
{
sms_list[sms_count] = sms;
sms_count++;
}
else
{
dbg_msg("Error decoding SMS in line: %s", line);
destroy_sms(sms);
}
}
line = strtok(NULL, "\n");
}
display_sms_in_json(sms_list, sms_count);
free(response_text);
}
dbg_msg("Read SMS success");
return SUCCESS;
}
int sms_send(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
if (profile->sms_pdu == NULL) {
err_msg("SMS PDU is empty");
return INVALID_PARAM;
}
int pdu_len = strlen(profile->sms_pdu);
int pdu_expected_len = (pdu_len) / 2 - 1;
char send_sms_cmd[32];
char pdu_hex[512];
char send_sms_cmd2[514];
int result;
int ascii_code;
// Set PDU format
result = transport_send_at_with_response(transport, profile, SET_PDU_FORMAT, "OK", 0, NULL);
if (result != SUCCESS) {
dbg_msg("Error setting PDU format, error code: %d", result);
return result;
}
dbg_msg("Set PDU format success");
snprintf(send_sms_cmd, 32, SEND_SMS, pdu_expected_len);
for (int i = 0; i < pdu_len; i++) {
//将字符串转换成字符串对应的十六进制的字符串
ascii_code = profile->sms_pdu[i];
snprintf(pdu_hex + (i * 2), 3, "%02X", ascii_code);
}
pdu_hex[pdu_len * 2] = '\0'; // Add the end of transmission character
snprintf(send_sms_cmd2, 514, "%s%s", pdu_hex, "1A"); // Append Ctrl+Z to indicate end of SMS
// Send first AT command and wait for > prompt
transport_send_at_only(transport, profile, send_sms_cmd, 0);
dbg_msg("Send SMS command: %s", send_sms_cmd);
dbg_msg("Write PDU command: %s", send_sms_cmd2);
usleep(10000); // 10ms delay
// Send PDU data and wait for +CMGS response
result = transport_send_at_with_response(transport, profile, send_sms_cmd2, "+CMGS:", 1, NULL);
if (result != SUCCESS) {
dbg_msg("Error sending SMS PDU, error code: %d", result);
return result;
}
return SUCCESS;
}
int sms_read_unread(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
SMS_T *sms_list[SMS_LIST_SIZE];
SMS_T *sms;
char *response_text = NULL;
int result;
// Set PDU format
result = transport_send_at_with_response(transport, profile, SET_PDU_FORMAT, "OK", 0, NULL);
if (result != SUCCESS)
{
dbg_msg("Error setting PDU format, error code: %d", result);
return result;
}
dbg_msg("Set PDU format success");
// Read unread SMS only
result = transport_send_at_with_response(transport, profile, READ_UNREAD_SMS, "OK", 0, &response_text);
if (result != SUCCESS)
{
dbg_msg("Error reading unread SMS, error code: %d", result);
return result;
}
if (response_text)
{
char *line = strtok(response_text, "\n");
int sms_count = 0;
while (line != NULL)
{
if (strncmp(line, "+CMGL:", 6) == 0)
{
sms = (SMS_T *)malloc(sizeof(SMS_T));
memset(sms, 0, sizeof(SMS_T));
char *pdu = strtok(NULL, "\n");
sms->sms_pdu = (char *)malloc(strlen(pdu));
sms->sender = (char *)malloc(PHONE_NUMBER_SIZE);
sms->sms_text = (char *)malloc(SMS_TEXT_SIZE);
sms->sms_index = get_sms_index(line);
memcpy(sms->sms_pdu, pdu, strlen(pdu));
int sms_len = decode_pdu(sms);
if (sms_len > 0)
{
sms_list[sms_count] = sms;
sms_count++;
}
else
{
dbg_msg("Error decoding SMS in line: %s", line);
destroy_sms(sms);
}
}
line = strtok(NULL, "\n");
}
display_sms_in_json(sms_list, sms_count);
free(response_text);
}
dbg_msg("Read unread SMS success");
return SUCCESS;
}
int sms_mark_read(PROFILE_T *profile, void *transport_ptr)
{
transport_t *transport = (transport_t *)transport_ptr;
char mark_read_cmd[64];
int result;
if (profile->sms_index < 0)
{
err_msg("SMS index not specified");
return INVALID_PARAM;
}
// Set PDU format
result = transport_send_at_with_response(transport, profile, SET_PDU_FORMAT, "OK", 0, NULL);
if (result != SUCCESS)
{
dbg_msg("Error setting PDU format, error code: %d", result);
return result;
}
// Mark SMS as read by reading it
snprintf(mark_read_cmd, 64, MARK_SMS_READ, profile->sms_index);
result = transport_send_at_with_response(transport, profile, mark_read_cmd, "OK", 0, NULL);
if (result != SUCCESS)
{
dbg_msg("Error marking SMS as read, error code: %d", result);
return result;
}
dbg_msg("SMS %d marked as read", profile->sms_index);
return SUCCESS;
}
|
281677160/openwrt-package | 15,373 | luci-app-qmodem/application/tom_modem/src/utils.c | #include "utils.h"
#ifdef USE_SEMAPHORE
void generate_semaphore_name(const char* filename, char* semaphore_name) {
snprintf(semaphore_name, MAX_FILENAME_LEN, "%s%s", SEMAPHORE_PREFIX, filename);
for (int i = 0; semaphore_name[i] != '\0'; i++) {
if (semaphore_name[i] == '/') {
semaphore_name[i] = '_';
}
}
}
int lock_at_port(char* filename){
char semaphore_name[MAX_FILENAME_LEN];
generate_semaphore_name(filename, semaphore_name);
dbg_msg("semaphore_name: %s", semaphore_name);
sem_t *sem = sem_open(semaphore_name, O_CREAT, 0644, 1);
if (sem == SEM_FAILED) {
perror("sem_open failed");
return -1;
}
sem_wait(sem);
return 0;
}
int unlock_at_port(char* filename){
char semaphore_name[MAX_FILENAME_LEN];
generate_semaphore_name(filename, semaphore_name);
dbg_msg("semaphore_name: %s", semaphore_name);
sem_t *sem = sem_open(semaphore_name, O_CREAT, 0644, 1);
if (sem == SEM_FAILED) {
perror("sem_open failed");
return -1;
}
sem_post(sem);
sem_close(sem);
sem_unlink(semaphore_name);
return 0;
}
#endif
static int char_to_hex(char c)
{
// convert char to hex
int is_digit, is_lower, is_upper;
is_digit = c - '0';
is_lower = c - 'a' + 10;
is_upper = c - 'A' + 10;
if (is_digit >= 0 && is_digit <= 9)
{
return is_digit;
}
else if (is_lower >= 10 && is_lower <= 15)
{
return is_lower;
}
else if (is_upper >= 10 && is_upper <= 15)
{
return is_upper;
}
else
{
return -1;
}
}
int decode_pdu(SMS_T *sms)
{
char sms_text[SMS_TEXT_SIZE] = {0};
int tp_dcs;
int skip_bytes;
int pdu_str_len;
unsigned char hex_pdu[SMS_PDU_HEX_SIZE] = {0};
pdu_str_len = strlen(sms->sms_pdu);
for (int i = 0; i < pdu_str_len; i += 2)
{
hex_pdu[i / 2] = char_to_hex(sms->sms_pdu[i]) << 4;
hex_pdu[i / 2] |= char_to_hex(sms->sms_pdu[i + 1]);
}
int sms_len = pdu_decode(hex_pdu, pdu_str_len/2,
&sms->timestamp,
sms->sender, PHONE_NUMBER_SIZE,
sms_text, SMS_TEXT_SIZE,
&tp_dcs,
&sms->ref_number,
&sms->total_segments,
&sms->segment_number,
&skip_bytes);
if (sms_len <= 0)
{
err_msg("Error decoding pdu");
return sms_len;
}
sms->sms_lenght = sms_len;
switch ((tp_dcs / 4) % 4)
{
case 0:
{
// GSM 7 bit
sms->type = SMS_CHARSET_7BIT;
int i;
i = skip_bytes;
if (skip_bytes > 0)
i = (skip_bytes * 8 + 6) / 7;
for (; i < strlen(sms_text); i++)
{
sprintf(sms->sms_text + i, "%c", sms_text[i]);
}
i++;
sprintf(sms->sms_text + i, "%c", '\0');
break;
}
case 2:
{
// UCS2
sms->type = SMS_CHARSET_UCS2;
int offset = 0;
for (int i = skip_bytes; i < SMS_TEXT_SIZE; i += 2)
{
int ucs2_char = 0x000000FF & sms_text[i + 1];
ucs2_char |= (0x0000FF00 & (sms_text[i] << 8));
unsigned char utf8_char[5];
int len = ucs2_to_utf8(ucs2_char, utf8_char);
int j;
for (j = 0; j < len; j++)
{
sprintf(sms->sms_text + offset, "%c", utf8_char[j]);
if (utf8_char[j] != '\0')
{
offset++;
}
}
}
offset++;
sprintf(sms->sms_text + offset, "%c", '\0');
break;
}
default:
break;
}
return sms_len;
}
int destroy_sms(SMS_T *sms)
{
if (sms->sms_pdu != NULL)
{
free(sms->sms_pdu);
}
if (sms->sender != NULL)
{
free(sms->sender);
}
if (sms->sms_text != NULL)
{
free(sms->sms_text);
}
free(sms);
return SUCCESS;
}
int dump_sms(SMS_T *sms)
{
dbg_msg("SMS Index: %d", sms->sms_index);
dbg_msg("SMS Text: %s", sms->sms_text);
dbg_msg("SMS Sender: %s", sms->sender);
dbg_msg("SMS Timestamp: %ld", sms->timestamp);
dbg_msg("SMS Segment: %d/%d", sms->segment_number, sms->total_segments);
return SUCCESS;
}
int match_option(char *option_name)
{
char short_option;
char *long_option;
// if start with '-' then it is an single character option
if (option_name[0] == '-' && option_name[1] != '-')
{
short_option = option_name[1];
switch (short_option)
{
case AT_CMD_S:
return AT_CMD;
case TTY_DEV_S:
return TTY_DEV;
case BAUD_RATE_S:
return BAUD_RATE;
case DATA_BITS_S:
return DATA_BITS;
case PARITY_S:
return PARITY;
case STOP_BITS_S:
return STOP_BITS;
case FLOW_CONTROL_S:
return FLOW_CONTROL;
case TIMEOUT_S:
return TIMEOUT;
case OPERATION_S:
return OPERATION;
case DEBUG_S:
return DEBUG;
case SMS_PDU_S:
return SMS_PDU;
case SMS_INDEX_S:
return SMS_INDEX;
case GREEDY_READ_S:
return GREEDY_READ;
case USE_UBUS_S:
return USE_UBUS;
default:
return -1;
}
}
if (option_name[0] == '-' && option_name[1] == '-')
{
long_option = option_name + 2;
if (strcmp(long_option, AT_CMD_L) == 0)
{
return AT_CMD;
}
else if (strcmp(long_option, TTY_DEV_L) == 0)
{
return TTY_DEV;
}
else if (strcmp(long_option, BAUD_RATE_L) == 0)
{
return BAUD_RATE;
}
else if (strcmp(long_option, DATA_BITS_L) == 0)
{
return DATA_BITS;
}
else if (strcmp(long_option, PARITY_L) == 0)
{
return PARITY;
}
else if (strcmp(long_option, STOP_BITS_L) == 0)
{
return STOP_BITS;
}
else if (strcmp(long_option, FLOW_CONTROL_L) == 0)
{
return FLOW_CONTROL;
}
else if (strcmp(long_option, TIMEOUT_L) == 0)
{
return TIMEOUT;
}
else if (strcmp(long_option, OPERATION_L) == 0)
{
return OPERATION;
}
else if (strcmp(long_option, DEBUG_L) == 0)
{
return DEBUG;
}
else if (strcmp(long_option, SMS_PDU_L) == 0)
{
return SMS_PDU;
}
else if (strcmp(long_option, SMS_INDEX_L) == 0)
{
return SMS_INDEX;
}
else if (strcmp(long_option, GREEDY_READ_L) == 0)
{
return GREEDY_READ;
}
else if (strcmp(long_option, USE_UBUS_L) == 0)
{
return USE_UBUS;
}
else
{
return -1;
}
}
// if start with '--' then it is a long option
return -1;
}
int match_operation(char *operation_name)
{
char short_op;
int opstr_len = strlen(operation_name);
if (opstr_len == 1)
{
short_op = operation_name[0];
switch (short_op)
{
case AT_OP_S:
return AT_OP;
case BINARY_AT_OP_S:
return BINARY_AT_OP;
case SMS_READ_OP_S:
return SMS_READ_OP;
case SMS_SEND_OP_S:
return SMS_SEND_OP;
case SMS_DELETE_OP_S:
return SMS_DELETE_OP;
case SMS_UNREAD_OP_S:
return SMS_UNREAD_OP;
case SMS_MARK_READ_OP_S:
return SMS_MARK_READ_OP;
case CLEANUP_SEMAPHORE_OP_S:
return CLEANUP_SEMAPHORE_OP;
default:
return INVALID_PARAM;
break;
}
}
else if (opstr_len > 1)
{
if (strcmp(operation_name, AT_OP_L) == 0)
{
return AT_OP;
}
else if (strcmp(operation_name, BINARY_AT_OP_L) == 0)
{
return BINARY_AT_OP;
}
else if (strcmp(operation_name, SMS_READ_OP_L) == 0)
{
return SMS_READ_OP;
}
else if (strcmp(operation_name, SMS_SEND_OP_L) == 0)
{
return SMS_SEND_OP;
}
else if (strcmp(operation_name, SMS_DELETE_OP_L) == 0)
{
return SMS_DELETE_OP;
}
else if (strcmp(operation_name, SMS_UNREAD_OP_L) == 0)
{
return SMS_UNREAD_OP;
}
else if (strcmp(operation_name, SMS_MARK_READ_OP_L) == 0)
{
return SMS_MARK_READ_OP;
}
else if (strcmp(operation_name, CLEANUP_SEMAPHORE_OP_L) == 0)
{
return CLEANUP_SEMAPHORE_OP;
}
else
{
return INVALID_PARAM;
}
}
return SUCCESS;
}
void escape_json(char *input, char *output)
{
char *p = input;
char *q = output;
while (*p)
{
unsigned char c = (unsigned char)*p;
if (*p == '"')
{
*q++ = '\\';
*q++ = '"';
}
else if (*p == '\\')
{
*q++ = '\\';
*q++ = '\\';
}
else if (*p == '/')
{
*q++ = '\\';
*q++ = '/';
}
else if (*p == '\b')
{
*q++ = '\\';
*q++ = 'b';
}
else if (*p == '\f')
{
*q++ = '\\';
*q++ = 'f';
}
else if (*p == '\n')
{
*q++ = '\\';
*q++ = 'n';
}
else if (*p == '\r')
{
*q++ = '\\';
*q++ = 'r';
}
else if (*p == '\t')
{
*q++ = '\\';
*q++ = 't';
}
else if (c < 0x20) // Control characters (U+0000 through U+001F)
{
*q++ = '\\';
*q++ = 'u';
*q++ = '0';
*q++ = '0';
*q++ = (c >> 4) < 10 ? '0' + (c >> 4) : 'a' + (c >> 4) - 10;
*q++ = (c & 0x0F) < 10 ? '0' + (c & 0x0F) : 'a' + (c & 0x0F) - 10;
}
else
{
*q++ = *p;
}
p++;
}
*q = '\0';
}
int usage(char* name)
{
err_msg("Usage: %s [options]", name);
err_msg("Or %s [device_path] [AT command]", name);
err_msg("Or %s [device_path] [operation]", name);
err_msg("Options:");
err_msg(" -c, --at_cmd <AT command> AT command");
err_msg(" -d, --tty_dev <TTY device> TTY device **REQUIRED**");
err_msg(" -b, --baud_rate <baud rate> Baud rate Default: 115200 Supported: 4800,9600,19200,38400,57600,115200");
err_msg(" -B, --data_bits <data bits> Data bits Default: 8 Supported: 5,6,7,8");
err_msg(" -t, --timeout <timeout> Default: 3 Timeout in seconds, if output is more than timeout, it will be ignored unless -g option is set");
err_msg(" -o, --operation <operation> Operation(at[a:defualt],binary_at[b], sms_read[r], sms_send[s], sms_delete[d], unread_sms[u], mark_read[m])");
err_msg(" -D, --debug Debug mode Default: off");
err_msg(" -p, --sms_pdu <sms pdu> SMS PDU");
err_msg(" -i, --sms_index <sms index> SMS index");
err_msg(" -g, --greedy_read Default: off, Greedy read mode, if set, each round it get new data from tty device, it will reset the timeout");
#ifdef ENABLE_UBUS_DAEMON
err_msg(" -u, --use_ubus Default: off, Use UBUS AT daemon instead of direct serial access");
#endif
#ifdef USE_SEMAPHORE
err_msg(" -C, --cleanup Semaphore cleanup");
#endif
err_msg("Example:");
err_msg(" %s -c ATI -d /dev/ttyUSB2 -b 115200 -B 8 -o at #advance at mode set bautrate and data bit", name);
err_msg(" %s -c ATI -d /dev/ttyUSB2 # normal at mode", name);
err_msg(" %s -c ATI -d /dev/ttyUSB2 -o binary_at -c 4154490D0A # means sending ATI to ttyUSB2", name);
err_msg(" %s -d /dev/mhi_DUN -o r # read sms", name);
#ifdef USE_SEMAPHORE
err_msg(" %s -d /dev/mhi_DUN -o C # force cleanup semaphore", name);
#endif
exit(-1);
}
int str_to_hex(char *str, char *hex)
{
int len = strlen(str)/2;
int high,low;
for (int i = 0; i < len; i++)
{
high = char_to_hex(str[i*2]);
low = char_to_hex(str[i*2+1]);
if (high == -1 || low == -1)
{
return INVALID_HEX;
}
hex[i] = (high << 4) | low;
dbg_msg("hex[%d]: %x", i, hex[i]);
}
return SUCCESS;
}
int get_sms_index(char *cmgl_line)
{
// Parse +CMGL: line to extract SMS index
// Format: +CMGL: <index>,<stat>,<alpha>,<length>
char *start_pos = strchr(cmgl_line, ':');
if (start_pos == NULL) {
return -1;
}
start_pos++; // Skip ':'
while (*start_pos == ' ') start_pos++; // Skip spaces
char *end_pos = strchr(start_pos, ',');
if (end_pos == NULL) {
return -1;
}
char index_str[16];
int len = end_pos - start_pos;
if (len >= sizeof(index_str)) {
return -1;
}
strncpy(index_str, start_pos, len);
index_str[len] = '\0';
return atoi(index_str);
}
void dump_profile()
{
dbg_msg("AT command: %s", s_profile.at_cmd);
dbg_msg("TTY device: %s", s_profile.tty_dev);
dbg_msg("Baud rate: %d", s_profile.baud_rate);
dbg_msg("Data bits: %d", s_profile.data_bits);
dbg_msg("Parity: %s", s_profile.parity);
dbg_msg("Stop bits: %d", s_profile.stop_bits);
dbg_msg("Flow control: %s", s_profile.flow_control);
dbg_msg("Timeout: %d", s_profile.timeout);
dbg_msg("Operation: %d", s_profile.op);
dbg_msg("Debug: %d", s_profile.debug);
dbg_msg("SMS PDU: %s", s_profile.sms_pdu);
dbg_msg("SMS index: %d", s_profile.sms_index);
dbg_msg("Greedy read: %d", s_profile.greedy_read);
dbg_msg("Transport type: %s", s_profile.transport == TRANSPORT_UBUS ? "UBUS" : "TTY");
}
int display_sms_in_json(SMS_T **sms,int num)
{
char msg_json[SMS_BUF_SIZE];
int offset;
offset = sprintf(msg_json, "{\"msg\":[");
for (int i = 0; i < num; i++)
{
char escaped_text[SMS_TEXT_SIZE];
escape_json(sms[i]->sms_text, escaped_text);
if (sms[i]->ref_number)
offset += sprintf(msg_json + offset, "{\"index\":%d,\"sender\":\"%s\",\"timestamp\":%ld,\"content\":\"%s\",\"reference\":%d,\"total\":%d,\"part\":%d},",
sms[i]->sms_index, sms[i]->sender, sms[i]->timestamp, escaped_text, sms[i]->ref_number, sms[i]->total_segments, sms[i]->segment_number);
else
offset += sprintf(msg_json + offset, "{\"index\":%d,\"sender\":\"%s\",\"timestamp\":%ld,\"content\":\"%s\"},",
sms[i]->sms_index, sms[i]->sender, sms[i]->timestamp, escaped_text);
}
//if not empty msg_json,remove the last ','
if (offset > 10)
{
offset--;
}
offset += sprintf(msg_json + offset, "]}");
user_msg("%s\n", msg_json);
return SUCCESS;
}
|
281677160/openwrt-package | 1,579 | luci-app-qmodem/application/tom_modem/src/ubus_client.h | #ifndef _UBUS_CLIENT_H_
#define _UBUS_CLIENT_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "modem_types.h"
// Check if ubus is available
#include <json-c/json.h>
#include <libubus.h>
#include <libubox/blobmsg_json.h>
// ubus AT daemon service name
#define UBUS_AT_DAEMON_SERVICE "at-daemon"
// ubus client context
typedef struct {
struct ubus_context *ctx;
int connected;
} ubus_client_t;
// AT response structure for ubus
typedef struct {
char *response;
int status;
char *end_flag_matched;
long response_time_ms;
} ubus_at_response_t;
// Function declarations
int ubus_client_init(ubus_client_t *client);
void ubus_client_cleanup(ubus_client_t *client);
int ubus_at_open_device(ubus_client_t *client, const char *device_path,
int baud_rate, int data_bits, int parity, int stop_bits);
int ubus_at_close_device(ubus_client_t *client, const char *device_path);
int ubus_send_at_command(ubus_client_t *client, const char *device_path,
const char *at_cmd, int timeout, const char *end_flag,
int is_raw, ubus_at_response_t *response);
int ubus_send_at_command_only(ubus_client_t *client, const char *device_path,
const char *at_cmd, int is_raw);
void ubus_at_response_free(ubus_at_response_t *response);
// Global ubus client functions for easy access
int init_global_ubus_client(void);
void cleanup_global_ubus_client(void);
ubus_client_t *get_global_ubus_client(void);
#endif // _UBUS_CLIENT_H_
|
281677160/openwrt-package | 6,426 | luci-app-qmodem/application/tom_modem/src/ttydevice.c | #include "ttydevice.h"
static int tty_set_device(PROFILE_T *profile, FDS_T *fds)
{
int baud_rate, data_bits;
struct termios tty;
baud_rate = profile->baud_rate;
data_bits = profile->data_bits;
if (tcgetattr(fds->tty_fd, &tty) != 0)
{
err_msg("Error getting tty attributes");
return COMM_ERROR;
}
memmove(&fds->old_termios, &tty, sizeof(struct termios));
cfmakeraw(&tty);
tty.c_cflag |= CLOCAL; // 忽略调制解调器控制线,允许本地连接
tty.c_cflag |= CREAD; // 使能接收
// clear flow control ,stop bits parity
tty.c_cflag &= ~CRTSCTS;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~PARENB;
tty.c_oflag &= ~OPOST;
tty.c_cc[VMIN] = 0;
tty.c_cc[VTIME] = 1;
// set data bits 5,6,7,8
tty.c_cflag &= ~CSIZE; // 清除数据位设置
switch (data_bits)
{
case 5:
tty.c_cflag |= CS5;
break;
case 6:
tty.c_cflag |= CS6;
break;
case 7:
tty.c_cflag |= CS7;
break;
case 8:
tty.c_cflag |= CS8;
break;
default:
tty.c_cflag |= CS8;
break;
}
// set baud rate
switch (baud_rate)
{
case 4800:
cfsetspeed(&tty, B4800);
break;
case 9600:
cfsetspeed(&tty, B9600);
break;
case 19200:
cfsetspeed(&tty, B19200);
break;
case 38400:
cfsetspeed(&tty, B38400);
break;
case 57600:
cfsetspeed(&tty, B57600);
break;
case 115200:
cfsetspeed(&tty, B115200);
break;
default:
cfsetspeed(&tty, B115200);
break;
}
if (tcsetattr(fds->tty_fd, TCSANOW, &tty) != 0)
{
err_msg("Error setting tty attributes");
return COMM_ERROR;
}
return SUCCESS;
}
int tty_open_device(PROFILE_T *profile,FDS_T *fds)
{
fds->tty_fd = open(profile->tty_dev, O_RDWR | O_NOCTTY);
if (fds->tty_fd < 0)
{
err_msg("Error opening tty device: %s", profile->tty_dev);
return COMM_ERROR;
}
if (tty_set_device(profile,fds) != 0)
{
err_msg("Error setting tty device");
return COMM_ERROR;
}
fds->tty_fd = open(profile->tty_dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
fds->fdi = fdopen(fds->tty_fd, "r");
if (setvbuf(fds->fdi , NULL, _IOFBF, 0))
{
err_msg("Error setting buffer for fdi");
return COMM_ERROR;
}
usleep(10000);
tcflush(fds->tty_fd, TCIOFLUSH);
if (fds->tty_fd >= 0)
close(fds->tty_fd);
else
return COMM_ERROR;
fds->tty_fd = open(profile->tty_dev, O_RDWR | O_NOCTTY | O_NONBLOCK);
fds->fdi = fdopen(fds->tty_fd, "r");
fds->fdo = fdopen(fds->tty_fd, "w");
if (fds->fdi == NULL || fds->fdo == NULL)
{
err_msg("Error opening file descriptor");
return COMM_ERROR;
}
if (setvbuf(fds->fdo , NULL, _IOFBF, 0))
{
err_msg("Error setting buffer for fdi");
return COMM_ERROR;
}
if (setvbuf(fds->fdi , NULL, _IOLBF, 0))
{
err_msg("Error setting buffer for fdi");
return COMM_ERROR;
}
return SUCCESS;
}
int tty_read(FILE *fdi, AT_MESSAGE_T *message, PROFILE_T *profile) {
return tty_read_keyword(fdi, message, NULL, profile);
}
int tty_read_keyword(FILE *fdi, AT_MESSAGE_T *message, char *key_word, PROFILE_T *profile) {
char tmp[LINE_BUF] = {0};
char *dynamic_buffer = NULL;
int buffer_size = 0;
int read_flag = 0;
time_t start_time = time(NULL);
int exitcode = TIMEOUT_WAITING_NEWLINE;
while (difftime(time(NULL), start_time) < profile->timeout) {
memset(tmp, 0, LINE_BUF);
if (fgets(tmp, LINE_BUF, fdi)) {
read_flag = 1;
dbg_msg("%s", tmp);
if (profile->greedy_read && strlen(tmp) > 0) {
start_time = time(NULL);
}
if (message != NULL) {
int tmp_len = strlen(tmp);
char *new_buffer = realloc(dynamic_buffer, buffer_size + tmp_len + 1);
if (!new_buffer) {
free(dynamic_buffer);
err_msg("Error: memory allocation failed");
exitcode = BUFFER_OVERFLOW;
break;
}
dynamic_buffer = new_buffer;
memcpy(dynamic_buffer + buffer_size, tmp, tmp_len);
buffer_size += tmp_len;
dynamic_buffer[buffer_size] = '\0';
}
if (strncmp(tmp, "OK", 2) == 0 ||
strncmp(tmp, "ERROR", 5) == 0 ||
strncmp(tmp, "+CMS ERROR:", 11) == 0 ||
strncmp(tmp, "+CME ERROR:", 11) == 0 ||
strncmp(tmp, "NO CARRIER", 10) == 0 ||
(key_word != NULL && strncmp(tmp, key_word, strlen(key_word)) == 0)) {
if (key_word != NULL && strncmp(tmp, key_word, strlen(key_word)) == 0) {
dbg_msg("keyword found");
exitcode = SUCCESS;
} else if (key_word == NULL) {
exitcode = SUCCESS;
} else {
exitcode = KEYWORD_NOT_MATCH;
}
break;
}
}
#ifdef EARLY_RETURN
else {
if (read_flag > 500) {
dbg_msg("early return");
exitcode = TIMEOUT_WAITING_NEWLINE;
break;
}
if (read_flag) {
read_flag++;
}
}
#endif
usleep(5000);
}
if (read_flag == 0) {
exitcode = COMM_ERROR;
}
if (message != NULL) {
message->message = dynamic_buffer;
message->len = buffer_size;
} else {
free(dynamic_buffer);
}
return exitcode;
}
int tty_write_raw(FILE *fdo, const char *input)
{
int ret;
ret = fputs(input, fdo);
fflush(fdo);
usleep(100);
if (ret < 0)
{
err_msg("Error writing to tty %d" , ret);
return COMM_ERROR;
}
return SUCCESS;
}
int tty_write(FILE *fdo, const char *input)
{
int cmd_len, ret;
char *cmd_line;
cmd_len = strlen(input) + 3;
cmd_line = (char *)malloc(cmd_len);
if (cmd_line == NULL)
{
err_msg("Error allocating memory");
return COMM_ERROR;
}
snprintf(cmd_line, cmd_len, "%s\r\n", input);
ret = tty_write_raw(fdo, cmd_line);
free(cmd_line);
return ret;
}
|
281677160/openwrt-package | 10,696 | luci-app-qmodem/application/tom_modem/src/transport.c | #include "transport.h"
#include "utils.h"
#include "operations.h"
// TTY transport operations implementation
static int tty_send_at_with_response(PROFILE_T *profile, const char *at_cmd, const char *end_flag, int is_raw, char **response_text) {
FDS_T *fds = (FDS_T *)profile->transport_ctx;
if (!fds || !fds->fdo || !fds->fdi) {
err_msg("TTY device not opened");
return COMM_ERROR;
}
int w_ret, r_ret;
AT_MESSAGE_T message = {0};
if (is_raw) {
char *binary_cmd = malloc(strlen(at_cmd) / 2 + 1);
if (!binary_cmd) {
err_msg("Memory allocation failed");
return COMM_ERROR;
}
int hex_ret = str_to_hex((char*)at_cmd, binary_cmd);
if (hex_ret) {
free(binary_cmd);
err_msg("Invalid hex string");
return INVALID_HEX;
}
w_ret = tty_write_raw(fds->fdo, binary_cmd);
free(binary_cmd);
} else {
w_ret = tty_write(fds->fdo, at_cmd);
}
if (w_ret) {
err_msg("Failed to write AT command");
return w_ret;
}
if (end_flag) {
r_ret = tty_read_keyword(fds->fdi, &message, (char*)end_flag, profile);
} else {
r_ret = tty_read(fds->fdi, &message, profile);
}
if (r_ret && r_ret != KEYWORD_NOT_MATCH) {
dbg_msg("Error reading AT response, error code: %d", r_ret);
if (message.message) {
free(message.message);
}
return r_ret;
}
if (response_text && message.message) {
*response_text = message.message;
} else if (message.message) {
free(message.message);
}
return (r_ret == KEYWORD_NOT_MATCH) ? r_ret : SUCCESS;
}
static int tty_send_at_only(PROFILE_T *profile, const char *at_cmd, int is_raw) {
FDS_T *fds = (FDS_T *)profile->transport_ctx;
if (!fds || !fds->fdo) {
err_msg("TTY device not opened");
return COMM_ERROR;
}
int w_ret;
if (is_raw) {
char *binary_cmd = malloc(strlen(at_cmd) / 2 + 1);
if (!binary_cmd) {
err_msg("Memory allocation failed");
return COMM_ERROR;
}
int hex_ret = str_to_hex((char*)at_cmd, binary_cmd);
if (hex_ret) {
free(binary_cmd);
err_msg("Invalid hex string");
return INVALID_HEX;
}
w_ret = tty_write_raw(fds->fdo, binary_cmd);
free(binary_cmd);
} else {
w_ret = tty_write(fds->fdo, at_cmd);
}
return w_ret;
}
static int tty_open_device_transport(PROFILE_T *profile, void *ctx) {
FDS_T *fds = (FDS_T *)ctx;
return tty_open_device(profile, fds);
}
static int tty_close_device_transport(PROFILE_T *profile, void *ctx) {
FDS_T *fds = (FDS_T *)ctx;
if (fds && fds->tty_fd >= 0) {
if (tcsetattr(fds->tty_fd, TCSANOW, &fds->old_termios) != 0) {
err_msg("Error restoring old tty attributes");
}
tcflush(fds->tty_fd, TCIOFLUSH);
close(fds->tty_fd);
fds->tty_fd = -1;
}
return SUCCESS;
}
const transport_ops_t tty_transport_ops = {
.send_at_with_response = tty_send_at_with_response,
.send_at_only = tty_send_at_only,
.open_device = tty_open_device_transport,
.close_device = tty_close_device_transport
};
#ifdef ENABLE_UBUS_DAEMON
// UBUS transport operations implementation
static int ubus_send_at_with_response_transport(PROFILE_T *profile, const char *at_cmd, const char *end_flag, int is_raw, char **response_text) {
ubus_client_t *client = (ubus_client_t *)profile->transport_ctx;
if (!client || !client->connected) {
err_msg("UBUS client not connected");
return COMM_ERROR;
}
ubus_at_response_t response;
int result = ubus_send_at_command(client, profile->tty_dev, at_cmd,
profile->timeout, end_flag, is_raw, &response);
if (result == 0 && response_text && response.response) {
*response_text = strdup(response.response);
}
if (result != 0) {
err_msg("UBUS AT command failed with status: %d", response.status);
ubus_at_response_free(&response);
return COMM_ERROR;
}
ubus_at_response_free(&response);
return SUCCESS;
}
static int ubus_send_at_only_transport(PROFILE_T *profile, const char *at_cmd, int is_raw) {
ubus_client_t *client = (ubus_client_t *)profile->transport_ctx;
if (!client || !client->connected) {
err_msg("UBUS client not connected");
return COMM_ERROR;
}
int result = ubus_send_at_command_only(client, profile->tty_dev, at_cmd, is_raw);
if (result != 0) {
err_msg("UBUS AT command (sendonly) failed with result: %d", result);
return COMM_ERROR;
}
return SUCCESS;
}
static int ubus_open_device_transport(PROFILE_T *profile, void *ctx) {
ubus_client_t *client = (ubus_client_t *)ctx;
// Try to open the device
int open_result = ubus_at_open_device(client, profile->tty_dev,
profile->baud_rate, profile->data_bits,
0, 1); // parity=0 (none), stopbits=1
if (open_result != 0) {
dbg_msg("Failed to open device %s via ubus", profile->tty_dev);
return COMM_ERROR;
} else {
dbg_msg("Opened device %s via ubus", profile->tty_dev);
return SUCCESS;
}
}
static int ubus_close_device_transport(PROFILE_T *profile, void *ctx) {
ubus_client_t *client = (ubus_client_t *)ctx;
return ubus_at_close_device(client, profile->tty_dev);
}
const transport_ops_t ubus_transport_ops = {
.send_at_with_response = ubus_send_at_with_response_transport,
.send_at_only = ubus_send_at_only_transport,
.open_device = ubus_open_device_transport,
.close_device = ubus_close_device_transport
};
#endif
// Global transport functions implementation
int transport_init(transport_t *transport, transport_type_t type) {
if (!transport) {
return COMM_ERROR;
}
transport->type = type;
switch (type) {
case TRANSPORT_TTY:
transport->ops = &tty_transport_ops;
transport->ctx.tty_fds = malloc(sizeof(FDS_T));
if (!transport->ctx.tty_fds) {
err_msg("Failed to allocate TTY context");
return COMM_ERROR;
}
memset(transport->ctx.tty_fds, 0, sizeof(FDS_T));
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
transport->ops = &ubus_transport_ops;
transport->ctx.ubus_client = malloc(sizeof(ubus_client_t));
if (!transport->ctx.ubus_client) {
err_msg("Failed to allocate UBUS context");
return COMM_ERROR;
}
memset(transport->ctx.ubus_client, 0, sizeof(ubus_client_t));
if (ubus_client_init(transport->ctx.ubus_client) != 0) {
err_msg("Failed to initialize UBUS client");
free(transport->ctx.ubus_client);
return COMM_ERROR;
}
break;
#endif
default:
err_msg("Unsupported transport type: %d", type);
return COMM_ERROR;
}
return SUCCESS;
}
void transport_cleanup(transport_t *transport) {
if (!transport) {
return;
}
switch (transport->type) {
case TRANSPORT_TTY:
if (transport->ctx.tty_fds) {
free(transport->ctx.tty_fds);
transport->ctx.tty_fds = NULL;
}
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
if (transport->ctx.ubus_client) {
ubus_client_cleanup(transport->ctx.ubus_client);
free(transport->ctx.ubus_client);
transport->ctx.ubus_client = NULL;
}
break;
#endif
}
}
// Unified transport operations
int transport_send_at_with_response(transport_t *transport, PROFILE_T *profile,
const char *at_cmd, const char *end_flag,
int is_raw, char **response_text) {
if (!transport || !transport->ops || !transport->ops->send_at_with_response) {
err_msg("Invalid transport or operations");
return COMM_ERROR;
}
// Set transport context in profile
switch (transport->type) {
case TRANSPORT_TTY:
profile->transport_ctx = transport->ctx.tty_fds;
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
profile->transport_ctx = transport->ctx.ubus_client;
break;
#endif
}
return transport->ops->send_at_with_response(profile, at_cmd, end_flag, is_raw, response_text);
}
int transport_send_at_only(transport_t *transport, PROFILE_T *profile,
const char *at_cmd, int is_raw) {
if (!transport || !transport->ops || !transport->ops->send_at_only) {
err_msg("Invalid transport or operations");
return COMM_ERROR;
}
// Set transport context in profile
switch (transport->type) {
case TRANSPORT_TTY:
profile->transport_ctx = transport->ctx.tty_fds;
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
profile->transport_ctx = transport->ctx.ubus_client;
break;
#endif
}
return transport->ops->send_at_only(profile, at_cmd, is_raw);
}
int transport_open_device(transport_t *transport, PROFILE_T *profile) {
if (!transport || !transport->ops || !transport->ops->open_device) {
err_msg("Invalid transport or operations");
return COMM_ERROR;
}
void *ctx = NULL;
switch (transport->type) {
case TRANSPORT_TTY:
ctx = transport->ctx.tty_fds;
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
ctx = transport->ctx.ubus_client;
break;
#endif
}
return transport->ops->open_device(profile, ctx);
}
int transport_close_device(transport_t *transport, PROFILE_T *profile) {
if (!transport || !transport->ops || !transport->ops->close_device) {
err_msg("Invalid transport or operations");
return COMM_ERROR;
}
void *ctx = NULL;
switch (transport->type) {
case TRANSPORT_TTY:
ctx = transport->ctx.tty_fds;
break;
#ifdef ENABLE_UBUS_DAEMON
case TRANSPORT_UBUS:
ctx = transport->ctx.ubus_client;
break;
#endif
}
return transport->ops->close_device(profile, ctx);
}
|
281677160/openwrt-package | 1,743 | luci-app-qmodem/application/tom_modem/src/transport.h | #ifndef _TRANSPORT_H_
#define _TRANSPORT_H_
#include "modem_types.h"
#include "ttydevice.h"
#include "utils.h"
#ifdef ENABLE_UBUS_DAEMON
#include "ubus_client.h"
#endif
// Transport operation function pointers
typedef struct {
int (*send_at_with_response)(PROFILE_T *profile, const char *at_cmd, const char *end_flag, int is_raw, char **response_text);
int (*send_at_only)(PROFILE_T *profile, const char *at_cmd, int is_raw);
int (*open_device)(PROFILE_T *profile, void *ctx);
int (*close_device)(PROFILE_T *profile, void *ctx);
} transport_ops_t;
// Transport context structure
typedef struct {
transport_type_t type;
const transport_ops_t *ops;
union {
FDS_T *tty_fds; // For TTY transport
#ifdef ENABLE_UBUS_DAEMON
ubus_client_t *ubus_client; // For UBUS transport
#endif
} ctx;
} transport_t;
// Global transport functions
int transport_init(transport_t *transport, transport_type_t type);
void transport_cleanup(transport_t *transport);
// Unified transport operations
int transport_send_at_with_response(transport_t *transport, PROFILE_T *profile,
const char *at_cmd, const char *end_flag,
int is_raw, char **response_text);
int transport_send_at_only(transport_t *transport, PROFILE_T *profile,
const char *at_cmd, int is_raw);
int transport_open_device(transport_t *transport, PROFILE_T *profile);
int transport_close_device(transport_t *transport, PROFILE_T *profile);
// TTY-specific operations
extern const transport_ops_t tty_transport_ops;
#ifdef ENABLE_UBUS_DAEMON
// UBUS-specific operations
extern const transport_ops_t ubus_transport_ops;
#endif
#endif // _TRANSPORT_H_ |
281677160/openwrt-package | 1,596 | luci-app-qmodem/application/tom_modem/src/utils.h | #ifndef _UTILS_H
#define _UTILS_H
#define USE_SEMAPHORE 1
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <termios.h>
#include <signal.h>
#include <sys/select.h>
#include <errno.h>
#include "modem_types.h"
#include "extlib/pdu.h"
#include "time.h"
#ifdef USE_SEMAPHORE
#include <semaphore.h>
#include <sys/wait.h>
#include <sys/types.h>
#define MAX_FILENAME_LEN 256
#define SEMAPHORE_PREFIX "tom_modem_lock"
typedef struct FileLock {
char filename[MAX_FILENAME_LEN];
sem_t semaphore;
} FileLock;
void generate_semaphore_name(const char* filename, char* semaphore_name);
int lock_at_port(char* filename);
int unlock_at_port(char* filename);
#endif
extern PROFILE_T s_profile;
extern FDS_T s_fds;
#define dbg_msg(fmt, args...) do { \
if (s_profile.debug) { \
fprintf(stderr, "[DBG]" fmt, ##args); \
fprintf(stderr, "\n"); \
fflush(stderr); \
} \
} while(0)
#define err_msg(fmt, args...) do { \
if (1) { \
fprintf(stderr, "[ERR]" fmt , ##args); \
fprintf(stderr, "\n"); \
fflush(stderr); \
} \
} while(0)
#define user_msg(fmt, args...) (fprintf(stdout, fmt , ##args))
int get_sms_index(char *cmgl_line);
int match_option(char *option_name);
int match_operation(char *operation_name);
int decode_pdu(SMS_T *sms);
int tty_read(FILE *fdi, AT_MESSAGE_T *message, PROFILE_T *profile);
int tty_read_keyword(FILE *fdi, AT_MESSAGE_T *message, char *key_word, PROFILE_T *profile);
int dump_sms(SMS_T *sms);
int destroy_sms(SMS_T *sms);
int display_sms_in_json(SMS_T **sms,int num);
#endif
|
281677160/openwrt-package | 7,052 | luci-app-qmodem/application/tom_modem/src/main.c | #include "main.h"
PROFILE_T s_profile; // global profile
transport_t s_transport; // global transport
int parse_user_input(int argc, char *argv[], PROFILE_T *profile)
{
int opt = 1;
int anonymous_arg = 0;
int option;
profile->sms_index = -1;
#define has_more_argv() (opt < argc ? 1 : 0)
while (opt < argc)
{
if (argv[opt][0] != '-') {
if (anonymous_arg == 0) {
profile->tty_dev = argv[opt];
}
if (anonymous_arg == 1){
profile->at_cmd = argv[opt];
}
if (anonymous_arg >= 2) {
err_msg("Too many anonymous arguments");
return INVALID_PARAM;
}
anonymous_arg++;
opt++;
continue;
}
option = match_option(argv[opt]);
if (option == -1)
{
usage(argv[0]);
return INVALID_PARAM;
}
opt++;
switch (option)
{
case AT_CMD:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->at_cmd = argv[opt++];
break;
case TTY_DEV:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->tty_dev = argv[opt++];
break;
case BAUD_RATE:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->baud_rate = atoi(argv[opt++]);
break;
case DATA_BITS:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->data_bits = atoi(argv[opt++]);
break;
case PARITY:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->parity = argv[opt++];
break;
case STOP_BITS:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->stop_bits = atoi(argv[opt++]);
break;
case FLOW_CONTROL:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->flow_control = argv[opt++];
break;
case TIMEOUT:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->timeout = atoi(argv[opt++]);
break;
case OPERATION:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->op = match_operation(argv[opt++]);
break;
case DEBUG:
profile->debug = 1;
break;
case SMS_PDU:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->sms_pdu = argv[opt++];
break;
case SMS_INDEX:
if (!has_more_argv())
{
usage(argv[0]);
return INVALID_PARAM;
}
profile->sms_index = atoi(argv[opt++]);
break;
case GREEDY_READ:
profile->greedy_read = 1;
break;
case USE_UBUS:
#ifdef ENABLE_UBUS_DAEMON
profile->transport = TRANSPORT_UBUS;
#else
err_msg("UBUS daemon support not compiled in");
return INVALID_PARAM;
#endif
break;
default:
err_msg("Invalid option: %s", argv[opt]);
break;
}
}
// default settings:
if (profile->tty_dev == NULL)
{
usage(argv[0]);
return INVALID_PARAM;
}
if (profile->baud_rate == 0 )
{
profile->baud_rate = 115200;
}
if (profile->data_bits == 0)
{
profile->data_bits = 8;
}
if (profile->timeout == 0)
{
profile->timeout = 3;
}
if (profile->op == 0 || profile->op == -1)
{
profile->op = AT_OP;
}
// Default transport is TTY
if (profile->transport != TRANSPORT_UBUS)
{
profile->transport = TRANSPORT_TTY;
}
return SUCCESS;
}
int run_op(PROFILE_T *profile, void *transport)
{
switch (profile->op)
{
case AT_OP:
return at(profile, transport);
case BINARY_AT_OP:
return binary_at(profile, transport);
case SMS_READ_OP:
return sms_read(profile, transport);
case SMS_SEND_OP:
return sms_send(profile, transport);
case SMS_DELETE_OP:
return sms_delete(profile, transport);
case SMS_UNREAD_OP:
return sms_read_unread(profile, transport);
case SMS_MARK_READ_OP:
return sms_mark_read(profile, transport);
default:
err_msg("Invalid operation");
}
return UNKNOWN_ERROR;
}
static void clean_up()
{
dbg_msg("Clean up success");
// Cleanup transport
transport_cleanup(&s_transport);
#ifdef USE_SEMAPHORE
if (s_profile.transport == TRANSPORT_TTY && unlock_at_port(s_profile.tty_dev))
{
err_msg("Failed to unlock tty device");
}
#endif
}
int main(int argc, char *argv[])
{
PROFILE_T *profile = &s_profile;
parse_user_input(argc, argv, profile);
dump_profile();
// Initialize transport layer
if (transport_init(&s_transport, profile->transport) != SUCCESS) {
err_msg("Failed to initialize transport layer");
return COMM_ERROR;
}
// Setup cleanup and signal handlers
atexit(clean_up);
signal(SIGINT, clean_up);
signal(SIGTERM, clean_up);
#ifdef USE_SEMAPHORE
if (profile->op == CLEANUP_SEMAPHORE_OP)
{
if (unlock_at_port(profile->tty_dev))
{
err_msg("Failed to unlock tty device");
}
return SUCCESS;
}
// Only use semaphore locking for TTY transport
if (profile->transport == TRANSPORT_TTY && profile->tty_dev != NULL)
{
if (lock_at_port(profile->tty_dev))
{
err_msg("Failed to lock tty device");
return COMM_ERROR;
}
}
#endif
// Open device
if (transport_open_device(&s_transport, profile) != SUCCESS)
{
err_msg("Failed to open device");
return COMM_ERROR;
}
// Run operation
if (run_op(profile, &s_transport))
{
err_msg("Failed to run operation %d", profile->op);
#ifdef USE_SEMAPHORE
if (profile->transport == TRANSPORT_TTY && unlock_at_port(profile->tty_dev))
{
err_msg("Failed to unlock tty device");
}
#endif
kill(getpid(), SIGINT);
}
dbg_msg("Exit");
return SUCCESS;
}
|
281677160/openwrt-package | 7,303 | luci-app-qmodem/application/tom_modem/src/ubus_client.c | #include "ubus_client.h"
#include "utils.h"
static ubus_client_t g_ubus_client = {0};
int ubus_client_init(ubus_client_t *client) {
if (!client) {
return -1;
}
client->ctx = ubus_connect(NULL);
if (!client->ctx) {
err_msg("Failed to connect to ubus");
return -1;
}
client->connected = 1;
dbg_msg("Connected to ubus successfully");
return 0;
}
void ubus_client_cleanup(ubus_client_t *client) {
if (client && client->ctx) {
ubus_free(client->ctx);
client->ctx = NULL;
client->connected = 0;
dbg_msg("Disconnected from ubus");
}
}
static uint32_t find_service_id(struct ubus_context *ctx, const char *service_name) {
uint32_t id;
int ret = ubus_lookup_id(ctx, service_name, &id);
if (ret != UBUS_STATUS_OK) {
err_msg("Failed to find service %s: %s", service_name, ubus_strerror(ret));
return 0;
}
return id;
}
int ubus_at_open_device(ubus_client_t *client, const char *device_path,
int baud_rate, int data_bits, int parity, int stop_bits) {
if (!client || !client->connected || !device_path) {
return -1;
}
uint32_t service_id = find_service_id(client->ctx, UBUS_AT_DAEMON_SERVICE);
if (!service_id) {
return -1;
}
struct blob_buf b = {0};
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "at_port", device_path);
blobmsg_add_u32(&b, "baudrate", baud_rate);
blobmsg_add_u32(&b, "databits", data_bits);
blobmsg_add_u32(&b, "parity", parity);
blobmsg_add_u32(&b, "stopbits", stop_bits);
int ret = ubus_invoke(client->ctx, service_id, "open", b.head, NULL, NULL, 5000);
blob_buf_free(&b);
if (ret != UBUS_STATUS_OK) {
err_msg("Failed to open AT device via ubus: %s", ubus_strerror(ret));
return -1;
}
dbg_msg("Opened AT device %s via ubus", device_path);
return 0;
}
int ubus_at_close_device(ubus_client_t *client, const char *device_path) {
if (!client || !client->connected || !device_path) {
return -1;
}
uint32_t service_id = find_service_id(client->ctx, UBUS_AT_DAEMON_SERVICE);
if (!service_id) {
return -1;
}
struct blob_buf b = {0};
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "at_port", device_path);
int ret = ubus_invoke(client->ctx, service_id, "close", b.head, NULL, NULL, 5000);
blob_buf_free(&b);
if (ret != UBUS_STATUS_OK) {
err_msg("Failed to close AT device via ubus: %s", ubus_strerror(ret));
return -1;
}
dbg_msg("Closed AT device %s via ubus", device_path);
return 0;
}
static void ubus_sendat_callback(struct ubus_request *req, int type, struct blob_attr *msg) {
ubus_at_response_t *response = (ubus_at_response_t *)req->priv;
if (!response || !msg) {
return;
}
struct blob_attr *tb[4];
static const struct blobmsg_policy response_policy[] = {
[0] = { .name = "response", .type = BLOBMSG_TYPE_STRING },
[1] = { .name = "status", .type = BLOBMSG_TYPE_STRING },
[2] = { .name = "end_flag_matched", .type = BLOBMSG_TYPE_STRING },
[3] = { .name = "response_time_ms", .type = BLOBMSG_TYPE_INT32 },
};
blobmsg_parse(response_policy, 4, tb, blob_data(msg), blob_len(msg));
if (tb[0]) {
const char *resp_str = blobmsg_get_string(tb[0]);
response->response = strdup(resp_str);
}
if (tb[1]) {
const char *status_str = blobmsg_get_string(tb[1]);
// Convert string status to integer: "success" -> 0, others -> -1
response->status = (strcmp(status_str, "success") == 0) ? 0 : -1;
}
if (tb[2]) {
const char *end_flag = blobmsg_get_string(tb[2]);
response->end_flag_matched = strdup(end_flag);
}
if (tb[3]) {
response->response_time_ms = blobmsg_get_u32(tb[3]);
}
}
int ubus_send_at_command(ubus_client_t *client, const char *device_path,
const char *at_cmd, int timeout, const char *end_flag,
int is_raw, ubus_at_response_t *response) {
if (!client || !client->connected || !device_path || !at_cmd || !response) {
return -1;
}
// Initialize response
memset(response, 0, sizeof(ubus_at_response_t));
response->status = -1;
uint32_t service_id = find_service_id(client->ctx, UBUS_AT_DAEMON_SERVICE);
if (!service_id) {
return -1;
}
struct blob_buf b = {0};
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "at_port", device_path);
//add boolean for sendonly
//blobmsg_add_u8(&b, "sendonly", 1);
if (is_raw) {
blobmsg_add_string(&b, "raw_at_content", at_cmd);
} else {
blobmsg_add_string(&b, "at_cmd", at_cmd);
}
blobmsg_add_u32(&b, "timeout", timeout);
if (end_flag && strlen(end_flag) > 0) {
blobmsg_add_string(&b, "end_flag", end_flag);
}
int ret = ubus_invoke(client->ctx, service_id, "sendat", b.head,
ubus_sendat_callback, response, timeout * 1000 + 1000);
blob_buf_free(&b);
if (ret != UBUS_STATUS_OK) {
err_msg("Failed to send AT command via ubus: %s", ubus_strerror(ret));
return -1;
}
dbg_msg("Sent AT command via ubus: %s", at_cmd);
return response->status;
}
int ubus_send_at_command_only(ubus_client_t *client, const char *device_path,
const char *at_cmd, int is_raw) {
if (!client || !client->connected || !device_path || !at_cmd) {
return -1;
}
uint32_t service_id = find_service_id(client->ctx, UBUS_AT_DAEMON_SERVICE);
if (!service_id) {
return -1;
}
struct blob_buf b = {0};
blob_buf_init(&b, 0);
blobmsg_add_string(&b, "at_port", device_path);
blobmsg_add_u8(&b, "sendonly", 1); // Set sendonly flag to true
if (is_raw) {
blobmsg_add_string(&b, "raw_at_content", at_cmd);
} else {
blobmsg_add_string(&b, "at_cmd", at_cmd);
}
blobmsg_add_u32(&b, "timeout", 1000); // Set minimal timeout for sendonly mode
int ret = ubus_invoke(client->ctx, service_id, "sendat", b.head,
NULL, NULL, 2000); // No callback needed for sendonly
blob_buf_free(&b);
if (ret != UBUS_STATUS_OK) {
err_msg("Failed to send AT command (sendonly) via ubus: %s", ubus_strerror(ret));
return -1;
}
dbg_msg("Sent AT command (sendonly) via ubus: %s", at_cmd);
return 0;
}
void ubus_at_response_free(ubus_at_response_t *response) {
if (response) {
if (response->response) {
free(response->response);
response->response = NULL;
}
if (response->end_flag_matched) {
free(response->end_flag_matched);
response->end_flag_matched = NULL;
}
}
}
// Global ubus client functions for easy access
int init_global_ubus_client(void) {
return ubus_client_init(&g_ubus_client);
}
void cleanup_global_ubus_client(void) {
ubus_client_cleanup(&g_ubus_client);
}
ubus_client_t *get_global_ubus_client(void) {
return &g_ubus_client;
}
|
281677160/openwrt-package | 1,924 | luci-app-qmodem/application/tom_modem/src/extlib/pdu_decoder.c | /*
* 2014 lovewilliam <ztong@vt.edu>
* SMS PDU Decoder
*/
#include "pdu.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
int ucs2_to_utf8 (int ucs2, unsigned char * utf8);
int sms_decode()
{
char buffer[2*SMS_MAX_PDU_LENGTH+4];
char *p = buffer;
char t[2];
int d;
do
{
t[0] = getchar();
if(t[0]=='\n')
{
break;
}
t[1] = getchar();
if(t[1]=='\n')
{
break;
}
*p = strtol(t,NULL,16);
p++;
}while(1);
time_t sms_time;
char sms_phone[40];
char sms_text[161];
int tp_dcs_type;
int ref_number;
int total_parts;
int part_number;
int skip_bytes;
int sms_text_length = pdu_decode((const unsigned char*)buffer,
sizeof(buffer),
&sms_time,
sms_phone, sizeof(sms_phone),
sms_text, sizeof(sms_text),
&tp_dcs_type,
&ref_number,
&total_parts,
&part_number,
&skip_bytes);
printf("From:%s\n",sms_phone);
printf("Textlen=%d\n",sms_text_length);
char time_data_str[64];
strftime(time_data_str,64,"%D %T", localtime(&sms_time));
printf("Date/Time:%s\n",time_data_str);
if (total_parts > 0) {
printf("Reference number: %d\n", ref_number);
printf("SMS segment %d of %d\n", part_number, total_parts);
}
switch((tp_dcs_type / 4) % 4)
{
case 0:
{
// GSM7 bit
int i = skip_bytes;
if(skip_bytes > 0) i = (skip_bytes*8+6)/7;
for(;i<sms_text_length;i++)
{
printf("%c", sms_text[i]);
}
break;
}
case 2:
{
// UCS2
for(int i = skip_bytes;i<sms_text_length;i+=2)
{
int ucs2_char = 0x000000FF&sms_text[i+1];
ucs2_char|=(0x0000FF00&(sms_text[i]<<8));
unsigned char utf8_char[5];
int len = ucs2_to_utf8(ucs2_char,utf8_char);
int j;
for(j=0;j<len;j++)
{
printf("%c",utf8_char[j]);
}
}
break;
}
default:
break;
}
printf("\n");
return 0;
}
int main()
{
return sms_decode();
}
|
281677160/openwrt-package | 1,483 | luci-app-qmodem/application/tom_modem/src/extlib/ucs2_to_utf8.c | /*
* 2014 lovewilliam <ztong@vt.edu>
* from http://www.lemoda.net/c/ucs2-to-utf8/ucs2-to-utf8.c
*/
/* Input: a Unicode code point, "ucs2".
Output: UTF-8 characters in buffer "utf8".
Return value: the number of bytes written into "utf8", or -1 if
there was an error.
This adds a zero byte to the end of the string. It assumes that the
buffer "utf8" has at least four bytes of space to write to. */
#define UNICODE_SURROGATE_PAIR -2
#define UNICODE_BAD_INPUT -1
int ucs2_to_utf8 (int ucs2, unsigned char * utf8)
{
if (ucs2 < 0x80) {
utf8[0] = ucs2;
utf8[1] = '\0';
return 1;
}
if (ucs2 >= 0x80 && ucs2 < 0x800) {
utf8[0] = (ucs2 >> 6) | 0xC0;
utf8[1] = (ucs2 & 0x3F) | 0x80;
utf8[2] = '\0';
return 2;
}
if (ucs2 >= 0x800 && ucs2 < 0xFFFF) {
if (ucs2 >= 0xD800 && ucs2 <= 0xDFFF) {
/* Ill-formed. */
return UNICODE_SURROGATE_PAIR;
}
utf8[0] = ((ucs2 >> 12) ) | 0xE0;
utf8[1] = ((ucs2 >> 6 ) & 0x3F) | 0x80;
utf8[2] = ((ucs2 ) & 0x3F) | 0x80;
utf8[3] = '\0';
return 3;
}
if (ucs2 >= 0x10000 && ucs2 < 0x10FFFF) {
/* http://tidy.sourceforge.net/cgi-bin/lxr/source/src/utf8.c#L380 */
utf8[0] = 0xF0 | (ucs2 >> 18);
utf8[1] = 0x80 | ((ucs2 >> 12) & 0x3F);
utf8[2] = 0x80 | ((ucs2 >> 6) & 0x3F);
utf8[3] = 0x80 | ((ucs2 & 0x3F));
utf8[4] = '\0';
return 4;
}
return UNICODE_BAD_INPUT;
}
|
281677160/openwrt-package | 15,015 | luci-app-qmodem/application/tom_modem/src/extlib/pdu.c | /*
* 2017 - 2021 Cezary Jackiewicz <cezary@eko.one.pl>
* 2014 lovewilliam <ztong@vt.edu>
*/
// Copyright 2011 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
//
// SMS encoding/decoding functions, which are based on examples from:
// http://www.dreamfabric.com/sms/
#include "pdu.h"
#include <string.h>
#include <time.h>
enum {
BITMASK_7BITS = 0x7F,
BITMASK_8BITS = 0xFF,
BITMASK_HIGH_4BITS = 0xF0,
BITMASK_LOW_4BITS = 0x0F,
TYPE_OF_ADDRESS_UNKNOWN = 0x81,
TYPE_OF_ADDRESS_INTERNATIONAL_PHONE = 0x91,
TYPE_OF_ADDRESS_NATIONAL_SUBSCRIBER = 0xC8,
TYPE_OF_ADDRESS_ALPHANUMERIC = 0xD0,
SMS_DELIVER_ONE_MESSAGE = 0x04,
SMS_SUBMIT = 0x11,
SMS_MAX_7BIT_TEXT_LENGTH = 160,
};
// Swap decimal digits of a number (e.g. 12 -> 21).
static unsigned char
SwapDecimalNibble(const unsigned char x)
{
return (x / 16) + ((x % 16) * 10);
}
// Encode/Decode PDU: Translate ASCII 7bit characters to 8bit buffer.
// SMS encoding example from: http://www.dreamfabric.com/sms/.
//
// 7-bit ASCII: "hellohello"
// [0]:h [1]:e [2]:l [3]:l [4]:o [5]:h [6]:e [7]:l [8]:l [9]:o
// 1101000 1100101 1101100 1101100 1101111 1101000 1100101 1101100 1101100 1101111
// | ||| ||||| | ||||||| ||||||
// /-------------/ ///-------/// /////-///// \------------\ ||||||| \\\\\\ .
// | ||| ||||| | ||||||| ||||||
// input buffer position
// 10000000 22111111 33322222 44443333 55555333 66666655 77777776 98888888 --999999
// | ||| ||||| | ||||||| ||||||
// 8bit encoded buffer
// 11101000 00110010 10011011 11111101 01000110 10010111 11011001 11101100 00110111
// E8 32 9B FD 46 97 D9 EC 37
// Encode PDU message by merging 7 bit ASCII characters into 8 bit octets.
int
EncodePDUMessage(const char* sms_text, int sms_text_length, unsigned char* output_buffer, int buffer_size)
{
// Check if output buffer is big enough.
if ((sms_text_length * 7 + 7) / 8 > buffer_size)
return -1;
int output_buffer_length = 0;
int carry_on_bits = 1;
int i = 0;
for (; i < sms_text_length - 1; ++i) {
output_buffer[output_buffer_length++] =
((sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1)) |
((sms_text[i + 1] & BITMASK_7BITS) << (8 - carry_on_bits));
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
++i;
}
}
if (i <= sms_text_length)
output_buffer[output_buffer_length++] = (sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1);
return output_buffer_length;
}
// Decode PDU message by splitting 8 bit encoded buffer into 7 bit ASCII
// characters.
int
DecodePDUMessage_GSM_7bit(const unsigned char* buffer, int buffer_length, char* output_sms_text, int sms_text_length)
{
int output_text_length = 0;
if (buffer_length > 0)
output_sms_text[output_text_length++] = BITMASK_7BITS & buffer[0];
if (sms_text_length > 1) {
int carry_on_bits = 1;
int i = 1;
for (; i < buffer_length; ++i) {
output_sms_text[output_text_length++] = BITMASK_7BITS & ((buffer[i] << carry_on_bits) | (buffer[i - 1] >> (8 - carry_on_bits)));
if (output_text_length == sms_text_length) break;
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
output_sms_text[output_text_length++] = buffer[i] & BITMASK_7BITS;
if (output_text_length == sms_text_length) break;
}
}
if (output_text_length < sms_text_length) // Add last remainder.
output_sms_text[output_text_length++] = buffer[i - 1] >> (8 - carry_on_bits);
}
return output_text_length;
}
#define GSM_7BITS_ESCAPE 0x1b
static const unsigned char gsm7bits_to_latin1[128] = {
'@', 0xa3, '$', 0xa5, 0xe8, 0xe9, 0xf9, 0xec, 0xf2, 0xc7, '\n', 0xd8, 0xf8, '\r', 0xc5, 0xe5,
0, '_', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc6, 0xe6, 0xdf, 0xc9,
' ', '!', '"', '#', 0xa4, '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
0xa1, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0xc4, 0xd6, 0xd1, 0xdc, 0xa7,
0xbf, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0xe4, 0xf6, 0xf1, 0xfc, 0xe0,
};
static const unsigned char gsm7bits_extend_to_latin1[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\f', 0, 0, 0, 0, 0,
0, 0, 0, 0, '^', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, '{', '}', 0, 0, 0, 0, 0,'\\',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '[', '~', ']', 0,
'|', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static int
G7bitToAscii(char* buffer, int buffer_length)
{
int i;
for (i = 0; i<buffer_length; i++) {
if (buffer[i] < 128) {
if (buffer[i] == GSM_7BITS_ESCAPE) {
buffer[i] = gsm7bits_extend_to_latin1[buffer[i + 1]];
memmove(&buffer[i + 1], &buffer[i + 2], buffer_length - i - 1);
buffer_length--;
} else {
buffer[i] = gsm7bits_to_latin1[buffer[i]];
}
}
}
return buffer_length;
}
#define NPC '?'
static const int latin1_to_gsm7bits[256] = {
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, 0x0a, NPC,-0x0a, 0x0d, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
0x20, 0x21, 0x22, 0x23, 0x02, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,-0x3c,-0x2f,-0x3e,-0x14, 0x11,
NPC, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,-0x28,-0x40,-0x29,-0x3d, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, 0x40, NPC, 0x01, 0x24, 0x03, NPC, 0x5f, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, 0x60,
NPC, NPC, NPC, NPC, 0x5b, 0x0e, 0x1c, 0x09, NPC, 0x1f, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, 0x5d, NPC, NPC, NPC, NPC, 0x5c, NPC, 0x0b, NPC, NPC, NPC, 0x5e, NPC, NPC, 0x1e,
0x7f, NPC, NPC, NPC, 0x7b, 0x0f, 0x1d, NPC, 0x04, 0x05, NPC, NPC, 0x07, NPC, NPC, NPC,
NPC, 0x7d, 0x08, NPC, NPC, NPC, 0x7c, NPC, 0x0c, 0x06, NPC, NPC, 0x7e, NPC, NPC, NPC,
};
static int
AsciiToG7bit(const char* buffer, int buffer_length, unsigned char* output_buffer)
{
int i, j, val;
j=0;
for (i = 0; i < buffer_length; i++) {
val = latin1_to_gsm7bits[buffer[i] & 0xFF];
if (val < 0) {
output_buffer[j++] = GSM_7BITS_ESCAPE;
output_buffer[j++] = -1*val;
} else {
if (((buffer[i] & 0xFF) & 0xE0) == 0xC0) { /* test for two byte utf8 char */
val = NPC;
i++;
} else if (((buffer[i] & 0xFF) & 0xF0) == 0xE0) { /* test for three byte utf8 char */
val = NPC;
i++;
i++;
}
output_buffer[j++] = val;
}
}
return j;
}
// Encode a digit based phone number for SMS based format.
static int
EncodePhoneNumber(const char* phone_number, unsigned char* output_buffer, int buffer_size)
{
int output_buffer_length = 0;
const int phone_number_length = strlen(phone_number);
// Check if the output buffer is big enough.
if ((phone_number_length + 1) / 2 > buffer_size)
return -1;
int i = 0;
for (; i < phone_number_length; ++i) {
if (phone_number[i] < '0' && phone_number[i] > '9')
return -1;
if (i % 2 == 0) {
output_buffer[output_buffer_length++] = BITMASK_HIGH_4BITS | (phone_number[i] - '0');
} else {
output_buffer[output_buffer_length - 1] =
(output_buffer[output_buffer_length - 1] & BITMASK_LOW_4BITS) |
((phone_number[i] - '0') << 4);
}
}
return output_buffer_length;
}
// Decode a digit based phone number for SMS based format.
static int
DecodePhoneNumber(const unsigned char* buffer, int phone_number_length, char* output_phone_number)
{
int i = 0;
for (; i < phone_number_length; ++i) {
if (i % 2 == 0)
output_phone_number[i] = (buffer[i / 2] & BITMASK_LOW_4BITS) + '0';
else
output_phone_number[i] = ((buffer[i / 2] & BITMASK_HIGH_4BITS) >> 4) + '0';
}
output_phone_number[phone_number_length] = '\0'; // Terminate C string.
return phone_number_length;
}
// Encode a SMS message to PDU
int
pdu_encode(const char* service_center_number, const char* phone_number, const char* sms_text,
unsigned char* output_buffer, int buffer_size)
{
if (buffer_size < 2)
return -1;
int output_buffer_length = 0;
// 1. Set SMS center number.
int length = 0;
if (service_center_number && strlen(service_center_number) > 0) {
output_buffer[1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
length = EncodePhoneNumber(service_center_number,
output_buffer + 2, buffer_size - 2);
if (length < 0 && length >= 254)
return -1;
length++; // Add type of address.
}
output_buffer[0] = length;
output_buffer_length = length + 1;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 2. Set type of message.
output_buffer[output_buffer_length++] = SMS_SUBMIT;
output_buffer[output_buffer_length++] = 0x00; // Message reference.
// 3. Set phone number.
output_buffer[output_buffer_length] = strlen(phone_number);
if (strlen(phone_number) < 6) {
output_buffer[output_buffer_length + 1] = TYPE_OF_ADDRESS_UNKNOWN;
} else {
output_buffer[output_buffer_length + 1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
}
length = EncodePhoneNumber(phone_number,
output_buffer + output_buffer_length + 2,
buffer_size - output_buffer_length - 2);
output_buffer_length += length + 2;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 4. Protocol identifiers.
output_buffer[output_buffer_length++] = 0x00; // TP-PID: Protocol identifier.
output_buffer[output_buffer_length++] = 0x00; // TP-DCS: Data coding scheme.
output_buffer[output_buffer_length++] = 0xB0; // TP-VP: Validity: 10 days
// 5. SMS message.
int sms_text_length = strlen(sms_text);
char sms_text_7bit[2*SMS_MAX_7BIT_TEXT_LENGTH];
sms_text_length = AsciiToG7bit(sms_text, sms_text_length, sms_text_7bit);
if (sms_text_length > SMS_MAX_7BIT_TEXT_LENGTH)
return -1;
output_buffer[output_buffer_length++] = sms_text_length;
length = EncodePDUMessage(sms_text_7bit, sms_text_length,
output_buffer + output_buffer_length,
buffer_size - output_buffer_length);
if (length < 0)
return -1;
output_buffer_length += length;
return output_buffer_length;
}
int pdu_decode(const unsigned char* buffer, int buffer_length,
time_t* output_sms_time,
char* output_sender_phone_number, int sender_phone_number_size,
char* output_sms_text, int sms_text_size,
int* tp_dcs,
int* ref_number,
int* total_parts,
int* part_number,
int* skip_bytes)
{
if (buffer_length <= 0)
return -1;
const int sms_deliver_start = 1 + buffer[0];
if (sms_deliver_start + 1 > buffer_length)
return -2;
const int user_data_header_length = (buffer[sms_deliver_start]>>4);
const int sender_number_length = buffer[sms_deliver_start + 1];
if (sender_number_length + 1 > sender_phone_number_size)
return -3; // Buffer too small to hold decoded phone number.
const int sender_type_of_address = buffer[sms_deliver_start + 2];
if (sender_type_of_address == TYPE_OF_ADDRESS_ALPHANUMERIC) {
int sender_len1 = DecodePDUMessage_GSM_7bit(buffer + sms_deliver_start + 3, (sender_number_length + 1) / 2, output_sender_phone_number, sender_number_length);
int sender_len2 = G7bitToAscii(output_sender_phone_number, sender_len1 - 1);
output_sender_phone_number[sender_len2] = 0;
} else {
DecodePhoneNumber(buffer + sms_deliver_start + 3, sender_number_length, output_sender_phone_number);
}
const int sms_pid_start = sms_deliver_start + 3 + (buffer[sms_deliver_start + 1] + 1) / 2;
// Decode timestamp.
struct tm sms_broken_time;
sms_broken_time.tm_year = 100 + SwapDecimalNibble(buffer[sms_pid_start + 2]);
sms_broken_time.tm_mon = SwapDecimalNibble(buffer[sms_pid_start + 3]) - 1;
sms_broken_time.tm_mday = SwapDecimalNibble(buffer[sms_pid_start + 4]);
sms_broken_time.tm_hour = SwapDecimalNibble(buffer[sms_pid_start + 5]);
sms_broken_time.tm_min = SwapDecimalNibble(buffer[sms_pid_start + 6]);
sms_broken_time.tm_sec = SwapDecimalNibble(buffer[sms_pid_start + 7]);
(*output_sms_time) = timegm(&sms_broken_time);
const int sms_start = sms_pid_start + 2 + 7;
if (sms_start + 1 > buffer_length) return -1; // Invalid input buffer.
int tmp;
if((user_data_header_length&0x04)==0x04) {
tmp = buffer[sms_start + 1] + 1;
*skip_bytes = tmp;
*ref_number = 0x000000FF&buffer[sms_start + tmp - 2];
*total_parts = 0x000000FF&buffer[sms_start + tmp - 1];
*part_number = 0x000000FF&buffer[sms_start + tmp];
} else {
tmp = 0;
*skip_bytes = tmp;
*ref_number = tmp;
*total_parts = tmp;
*part_number = tmp;
}
int output_sms_text_length = buffer[sms_start];
if (sms_text_size < output_sms_text_length) return -1; // Cannot hold decoded buffer.
const int sms_tp_dcs_start = sms_pid_start + 1;
*tp_dcs = buffer[sms_tp_dcs_start];
switch((*tp_dcs / 4) % 4)
{
case 0:
{
// GSM 7 bit
int decoded_sms_text_size = DecodePDUMessage_GSM_7bit(buffer + sms_start + 1, buffer_length - (sms_start + 1),
output_sms_text, output_sms_text_length);
if (decoded_sms_text_size != output_sms_text_length) return -1; // Decoder length is not as expected.
output_sms_text_length = G7bitToAscii(output_sms_text, output_sms_text_length);
break;
}
case 2:
{
// UCS2
memcpy(output_sms_text, buffer + sms_start + 1, output_sms_text_length);
break;
}
default:
break;
}
// Add a C string end.
if (output_sms_text_length < sms_text_size)
output_sms_text[output_sms_text_length] = 0;
else
output_sms_text[sms_text_size-1] = 0;
return output_sms_text_length;
}
|
281677160/openwrt-package | 1,670 | luci-app-qmodem/application/tom_modem/src/extlib/pdu.h | /*
* 2017 - 2021 Cezary Jackiewicz <cezary@eko.one.pl>
* 2014 lovewilliam <ztong@vt.edu>
*/
// Copyright 2011 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
#ifndef SMS_PDU_H_
#define SMS_PDU_H_
#include <time.h>
enum { SMS_MAX_PDU_LENGTH = 256 };
/*
* Encode an SMS message. Output the encoded message into output pdu buffer.
* Returns the length of the SMS encoded message in the output buffer or
* a negative number in case encoding failed (for example provided output buffer
* does not have enough space).
*/
int pdu_encode(const char* service_center_number, const char* phone_number, const char* text,
unsigned char* pdu, int pdu_size);
/*
* Decode an SMS message. Output the decoded message into the sms text buffer.
* Returns the length of the SMS dencoded message or a negative number in
* case encoding failed (for example provided output buffer has not enough
* space).
*/
int pdu_decode(const unsigned char* pdu, int pdu_len,
time_t* sms_time,
char* phone_number, int phone_number_size,
char* text, int text_size,
int* tp_dcs,
int* ref_number,
int* total_parts,
int* part_number,
int* skip_bytes);
int ucs2_to_utf8 (int ucs2, unsigned char * utf8);
int DecodePDUMessage_GSM_7bit(const unsigned char* buffer,
int buffer_length,
char* output_sms_text,
int sms_text_length);
int EncodePDUMessage(const char* sms_text,
int sms_text_length,
unsigned char* output_buffer,
int buffer_size);
#endif // SMS_SMS_H_
|
281677160/openwrt-package | 15,769 | luci-app-qmodem/application/sms-tool_q/src/sms_main.c | /*
* 2017 - 2024 Cezary Jackiewicz <cezary@eko.one.pl>
* 2014 lovewilliam <ztong@vt.edu>
* sms tool for various of 3G/4G/5G modem
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include "pdu_lib/pdu.h"
static void usage()
{
fprintf(stderr,
"usage: [options] send phoneNumber message\n"
" [options] recv\n"
" [options] delete msg_index | all\n"
" [options] status\n"
" [options] ussd code\n"
" [options] at command\n"
"options:\n"
"\t-b <baudrate> (default: 115200)\n"
"\t-c coding scheme (for ussd, 0 - 7BIT, 2 - UCS2, default: detect)\n"
"\t-d <tty device> (default: /dev/ttyUSB0)\n"
"\t-D debug (for ussd and at)\n"
"\t-f <date/time format> (for sms/recv)\n"
"\t-j json output (for sms/recv)\n"
"\t-R use raw input (for ussd)\n"
"\t-r use raw output (for ussd and sms/recv)\n"
"\t-s <preferred storage> (for sms/recv/status)\n"
);
exit(2);
}
static struct termios save_tio;
static int port = -1;
static const char* dev = "/dev/ttyUSB0";
static const char* storage = "";
static const char* dateformat = "%D %T";
static void setserial(int baudrate)
{
struct termios t;
if (tcgetattr(port, &t) < 0)
fprintf(stderr,"tcgetattr(%s)\n", dev);
memmove(&save_tio, &t, sizeof(t));
cfmakeraw(&t);
t.c_cflag |=CLOCAL;
t.c_cflag |=CREAD;
// data bits
t.c_cflag &=~CSIZE;
t.c_cflag |= CS8;
// parity
t.c_cflag &= ~PARENB;
// stop bits
t.c_cflag &=~CSTOPB;
// flow control
t.c_cflag &=~CRTSCTS;
t.c_oflag &=~OPOST;
t.c_cc[VMIN]=1;
switch (baudrate)
{
case 0:
break;
case 4800:
cfsetspeed(&t, B4800);
break;
case 9600:
cfsetspeed(&t, B9600);
break;
case 19200:
cfsetspeed(&t, B19200);
break;
case 38400:
cfsetspeed(&t, B38400);
break;
case 57600:
cfsetspeed(&t, B57600);
break;
case 115200:
cfsetspeed(&t, B115200);
break;
default:
fprintf(stderr,"Unsupported baudrate: %d\n", baudrate);
}
if (tcsetattr(port, TCSANOW, &t) < 0)
{
fprintf(stderr,"tcsetattr(%s)\n", dev);
}
}
static void resetserial()
{
if (tcsetattr(port, TCSANOW, &save_tio) < 0)
fprintf(stderr, "failed tcsetattr(%s): %s\n", dev, strerror(errno));
tcflush(port, TCIOFLUSH);
close(port);
}
static void timeout()
{
fprintf(stderr,"No response from modem.\n");
exit(2);
}
static int starts_with(const char* prefix, const char* str)
{
while(*prefix)
{
if (*prefix++ != *str++)
{
return 0;
}
}
return 1;
}
static int char_to_hex(char c)
{
if (isdigit(c))
return c - '0';
if (islower(c))
return 10 + c - 'a';
if (isupper(c))
return 10 + c - 'A';
return -1;
}
static void print_json_escape_char(char c1, char c2)
{
if (c1 == 0x0) {
if(c2 == '"') printf("\\\"");
else if(c2 == '\\') printf("\\\\");
else if(c2 == '\b') printf("\\b");
else if(c2 == '\n') printf("\\n");
else if(c2 == '\f') printf("\\f");
else if(c2 == '\r') printf("\\r");
else if(c2 == '\t') printf("\\t");
else if(c2 == '"') printf("\\\"");
else if(c2 == '/') printf("\\/");
else if(c2 < ' ') printf("\\u00%02x", c2);
else printf("%c", c2);
} else {
printf("\\u%02x%02x", (unsigned char)c1, (unsigned char)c2);
}
}
int main(int argc, char* argv[])
{
int ch;
int baudrate = 115200;
int rawinput = 0;
int rawoutput = 0;
int jsonoutput = 0;
int debug = 0;
int dcs = -1;
while ((ch = getopt(argc, argv, "b:c:d:Ds:f:jRr")) != -1){
switch (ch) {
case 'b': baudrate = atoi(optarg); break;
case 'c': dcs = atoi(optarg); break;
case 'd': dev = optarg; break;
case 'D': debug = 1; break;
case 's': storage = optarg; break;
case 'f': dateformat = optarg; break;
case 'j': jsonoutput = 1; break;
case 'R': rawinput = 1; break;
case 'r': rawoutput = 1; break;
default:
usage();
}
}
argv += optind; argc -= optind;
if (argc < 1)
usage();
if (!strcmp("send", argv[0]))
{
if(argc < 3)
usage();
if(strlen(argv[2]) > 160)
fprintf(stderr,"sms message too long: '%s'\n", argv[2]);
}else if (!strcmp("delete",argv[0]))
{
if(argc < 2)
usage();
}else if (!strcmp("recv", argv[0]))
{
}else if (!strcmp("status", argv[0]))
{
}else if (!strcmp("ussd", argv[0]))
{
}else if (!strcmp("at", argv[0]))
{
if(argc < 2)
usage();
}else
usage();
signal(SIGALRM,timeout);
char cmdstr[100];
char pdustr[2*SMS_MAX_PDU_LENGTH+4];
unsigned char pdu[SMS_MAX_PDU_LENGTH];
// open the port
port = open(dev, O_RDWR|O_NONBLOCK|O_NOCTTY);
if (port < 0)
fprintf(stderr,"open(%s)\n", dev);
setserial(baudrate);
atexit(resetserial);
close(port);
port = open(dev, O_RDWR|O_NOCTTY);
if (port < 0)
fprintf(stderr,"reopen(%s)\n", dev);
FILE* pf = fdopen(port, "w");
FILE* pfi = fdopen(port, "r");
if (!pf || ! pfi)
fprintf(stderr,"open port failed\n");
if(setvbuf(pf, NULL, _IOLBF, 0))
{
fprintf(stderr, "failed to make serial port linebuffered\n");
}
char buf[1024];
if (!strcmp("send", argv[0]))
{
int pdu_len = pdu_encode("", argv[1], argv[2], pdu, sizeof(pdu));
if (pdu_len < 0)
fprintf(stderr,"error encoding to PDU: %s \"%s\n", argv[1], argv[2]);
const int pdu_len_except_smsc = pdu_len - 1 - pdu[0];
snprintf(cmdstr, sizeof(cmdstr), "AT+CMGS=%d\r\n", pdu_len_except_smsc);
int i;
for (i = 0; i < pdu_len; ++i)
sprintf(pdustr+2*i, "%02X", pdu[i]);
sprintf(pdustr+2*i, "%c\r\n", 0x1A); // End PDU mode with Ctrl-Z.
fputs("AT+CMGF=0\r\n", pf);
while(fgets(buf, sizeof(buf), pfi)) {
if(starts_with("OK", buf))
break;
}
fputs(cmdstr, pf);
sleep(1);
fputs(pdustr, pf);
alarm(5);
errno = 0;
while(fgets(buf, sizeof(buf), pfi))
{
if(starts_with("+CMGS:", buf))
{
printf("sms sent sucessfully: %s", buf + 7);
return 0;
} else if(starts_with("+CMS ERROR:", buf))
{
fprintf(stderr,"sms not sent, code: %s\n", buf + 11);
} else if(starts_with("ERROR", buf))
{
fprintf(stderr,"sms not sent, command error\n");
} else if(starts_with("OK", buf))
{
return 0;
}
}
fprintf(stderr,"reading port\n");
}
if (!strcmp("recv", argv[0]))
{
alarm(10);
if (strlen(storage) > 0) {
fputs("AT+CPMS=\"", pf);
fputs(storage, pf);
fputs("\"\r\n", pf);
while(fgets(buf, sizeof(buf), pfi)) {
if(starts_with("OK", buf))
break;
}
}
fputs("AT+CMGF=0\r\n", pf);
while(fgets(buf, sizeof(buf), pfi)) {
if(starts_with("OK", buf))
break;
}
fputs("AT+CMGL=4\r\n", pf);
int idx[1024];
int count = 0;
if(jsonoutput == 1) {
printf("{\"msg\":[");
}
while(fgets(buf, sizeof buf, pfi))
{
if(starts_with("OK", buf))
break;
if(starts_with("+CMGL:", buf))
{
if(sscanf(buf, "+CMGL: %d,", &idx[count]) != 1)
{
fprintf(stderr, "unparsable CMGL response: %s\n", buf+7);
continue;
}
if(!fgets(buf, sizeof buf, pfi))
fprintf(stderr,"reading pdu %d\n", count);
if(jsonoutput == 1) {
if (count > 0) {
printf(",");
}
printf("{\"index\":%d,",idx[count]);
} else {
printf("MSG: %d\n",idx[count]);
}
++count;
if(rawoutput == 1)
{
if(jsonoutput == 1) {
printf("\"content\":\"%s\"", buf);
} else {
printf("%s\n", buf);
}
continue;
}
int l = strlen(buf);
int i;
for(i = 0; i < l; i+=2)
pdu[i/2] = 16*char_to_hex(buf[i]) + char_to_hex(buf[i+1]);
time_t sms_time;
char phone_str[40];
char sms_txt[161];
int tp_dcs_type;
int ref_number;
int total_parts;
int part_number;
int skip_bytes;
int sms_len = pdu_decode(pdu, l/2, &sms_time, phone_str, sizeof(phone_str), sms_txt, sizeof(sms_txt),&tp_dcs_type,&ref_number,&total_parts,&part_number,&skip_bytes);
if (sms_len <= 0) {
fprintf(stderr, "error decoding pdu %d: %s\n", count-1, buf);
if(jsonoutput == 1) {
printf("\"error\":\"error decoding pdu\",\"sender\":\"\",\"timestamp\":\"\",\"content\":\"\"}");
}
continue;
}
if(jsonoutput == 1) {
printf("\"sender\":\"%s\",",phone_str);
} else {
printf("From: %s\n",phone_str);
}
char time_data_str[64];
strftime(time_data_str, 64, dateformat, gmtime(&sms_time));
if(jsonoutput == 1) {
printf("\"timestamp\":\"%s\",",time_data_str);
} else {
printf("Date/Time: %s\n",time_data_str);
}
if(total_parts > 0) {
if(jsonoutput == 1) {
printf("\"reference\":%d,\"part\":%d,\"total\":%d,", ref_number, part_number, total_parts);
} else {
printf("Reference number: %d\n", ref_number);
printf("SMS segment %d of %d\n", part_number, total_parts);
}
}
if(jsonoutput == 1) {
printf("\"content\":\"");
}
switch((tp_dcs_type / 4) % 4)
{
case 0:
{
// GSM 7 bit
int i = skip_bytes;
if(skip_bytes > 0) i = (skip_bytes*8+6)/7;
for(; i<sms_len; i++)
{
if(jsonoutput == 1) {
print_json_escape_char(0x0, sms_txt[i]);
} else {
printf("%c", sms_txt[i]);
}
}
break;
}
case 2:
{
// UCS2
for(int i = skip_bytes;i<sms_len;i+=2)
{
if(jsonoutput == 1) {
print_json_escape_char(sms_txt[i],sms_txt[i+1]);
} else {
int ucs2_char = 0x000000FF&sms_txt[i+1];
ucs2_char|=(0x0000FF00&(sms_txt[i]<<8));
unsigned char utf8_char[5];
int len = ucs2_to_utf8(ucs2_char,utf8_char);
int j;
for(j=0;j<len;j++)
{
printf("%c", utf8_char[j]);
}
}
}
break;
}
default:
break;
}
if(jsonoutput == 1) {
printf("\"}");
} else {
printf("\n\n");
}
}
}
if(jsonoutput == 1) {
printf("]}\n");
}
}
if (!strcmp("delete",argv[0]))
{
int i = atoi(argv[1]);
int j = i;
if(!strcmp("all",argv[1]))
{
i = 0;
j = 49;
}
printf("delete msg from %d to %d\n",i,j);
for(;i<=j;i++)
{
fprintf(pf, "AT+CMGD=%d\r\n", i);
while(fgets(buf, sizeof buf, pfi))
{
if(starts_with("OK", buf))
{
printf("Deleted message %d\n", i);
break;
}
if(starts_with("+CMS ERROR:", buf))
{
printf("Error deleting message %d: %s\n", i, buf+12);
break;
}
}
}
}
if (!strcmp("status", argv[0]))
{
alarm(10);
if (strlen(storage) > 0) {
fputs("AT+CPMS=\"", pf);
fputs(storage, pf);
fputs("\"\r\n", pf);
while(fgets(buf, sizeof(buf), pfi)) {
if(starts_with("OK", buf))
break;
}
}
fputs("AT+CPMS?\r\n", pf);
while(fgets(buf, sizeof buf, pfi))
{
if(starts_with("+CPMS:", buf))
{
char mem1[9];
int mem1_used, mem1_total;
if(sscanf(buf, "+CPMS: \"%2s\",%d,%d,", mem1, &mem1_used, &mem1_total) != 3)
{
fprintf(stderr, "unparsable CPMS response: %s\n", buf);
break;
}
printf("Storage type: %s, used: %d, total: %d\n", mem1, mem1_used, mem1_total);
break;
}
if(starts_with("OK", buf))
{
break;
}
}
}
if (!strcmp("ussd", argv[0]))
{
enum sms_charset {
SMS_CHARSET_7BIT = 0,
SMS_CHARSET_8BIT = 1,
SMS_CHARSET_UCS2 = 2,
};
if (rawinput==1)
{
snprintf(cmdstr, sizeof(cmdstr), "AT+CUSD=1,\"%s\",15\r\n", argv[1]);
}
else
{
int pdu_len = EncodePDUMessage(argv[1], strlen(argv[1]), pdu, SMS_MAX_PDU_LENGTH);
if (pdu_len > 0)
{
if (pdu[pdu_len - 1] == 0) {pdu[pdu_len - 1] = 0x1d;}
for (int i = 0; i < pdu_len; ++i)
sprintf(pdustr+2*i, "%02X", pdu[i]);
snprintf(cmdstr, sizeof(cmdstr), "AT+CUSD=1,\"%s\",15\r\n", pdustr);
}
else
fprintf(stderr, "error encoding to PDU: %s\n", argv[1]);
}
if (debug == 1)
printf("debug: %s\n", cmdstr);
fputs(cmdstr, pf);
alarm(10);
char ussd_buf[320];
char ussd_txt[800];
int rc, multiline = 0, tp_dcs_type = 0;
while(fgets(buf, sizeof buf, pfi))
{
if(starts_with("OK", buf))
continue;
if(starts_with("+CME ERROR:", buf))
{
fprintf(stderr, "error: %s\n", buf+12);
break;
}
if(starts_with("+CUSD:", buf))
{
if (debug == 1)
printf("debug: %s\n", buf);
char tmp[8];
rc = sscanf(buf, "+CUSD:%7[^\"]\"%[^\"]\",%d", tmp, ussd_buf, &tp_dcs_type);
if(rc == 2)
{
if(rawoutput == 1)
{
multiline = 1;
rc = 3;
}
}
if(rc != 3)
{
fprintf(stderr, "unparsable CUSD response: %s\n", buf);
break;
}
if(rawoutput == 1)
{
printf("%s", ussd_buf);
if (multiline == 1)
continue;
else
{
printf("\n");
break;
}
}
int l = strlen(ussd_buf);
for(int i = 0; i < l; i+=2)
pdu[i/2] = 16*char_to_hex(ussd_buf[i]) + char_to_hex(ussd_buf[i+1]);
int upper = (tp_dcs_type & 0xf0) >> 4;
int lower = tp_dcs_type & 0xf;
int coding = -1;
if (upper == 0x3 || upper == 0x8 || (upper >= 0xA && upper <= 0xE))
coding = -1;
switch (upper)
{
case 0:
coding = SMS_CHARSET_7BIT;
break;
case 1:
if (lower == 0)
coding = SMS_CHARSET_7BIT;
if (lower == 1)
coding = SMS_CHARSET_UCS2;
break;
case 2:
if (lower <= 4)
coding = SMS_CHARSET_7BIT;
break;
case 4:
case 5:
case 6:
case 7:
if (((tp_dcs_type & 0x0c) >> 2) < 3)
coding = (enum sms_charset) ((tp_dcs_type & 0x0c) >> 2);
break;
case 9:
if (((tp_dcs_type & 0x0c) >> 2) < 3)
coding = (enum sms_charset) ((tp_dcs_type & 0x0c) >> 2);
break;
case 15:
if (lower & 0x4 == 0)
coding = SMS_CHARSET_7BIT;
break;
};
switch(dcs)
{
case SMS_CHARSET_7BIT:
{
coding = SMS_CHARSET_7BIT;
break;
}
case SMS_CHARSET_UCS2:
{
coding = SMS_CHARSET_UCS2;
break;
}
}
switch(coding)
{
case SMS_CHARSET_7BIT:
{
// GSM 7 bit
l = DecodePDUMessage_GSM_7bit(pdu, l/2, ussd_txt, sizeof(ussd_txt));
if (l > 0) {
if (l < sizeof(ussd_txt))
ussd_txt[l] = 0;
printf("%s\n", ussd_txt);
} else {
fprintf(stderr, "error decoding pdu: %s\n", ussd_buf);
}
break;
}
case SMS_CHARSET_UCS2:
{
// UCS2
// FIXME: interaction with multiline, sample PDUs needed
int utf_pos = 0;
for(int i = 0;i+1<l/2;i+=2)
{
int ucs2_char = 0x000000FF&pdu[i+1];
ucs2_char|=(0x0000FF00&(pdu[i]<<8));
utf_pos += ucs2_to_utf8(ucs2_char,&ussd_txt[utf_pos]);
}
if (utf_pos > 0) {
if (utf_pos < sizeof(ussd_txt))
ussd_txt[utf_pos] = 0;
printf("%s\n", ussd_txt);
} else {
fprintf(stderr, "error decoding pdu: %s\n", ussd_buf);
}
break;
}
default:
fprintf(stderr, "unknown coding scheme: %d\n", tp_dcs_type);
break;
}
break;
}
if (multiline == 1)
{
rc = sscanf(buf, "%[^\"]\",%d", ussd_buf, &tp_dcs_type);
if (rc == 1)
{
printf("%s", ussd_buf);
}
if (rc == 2)
{
printf("%s\n", ussd_buf);
multiline = 0;
break;
}
}
}
}
if (!strcmp("at", argv[0]))
{
alarm(5);
fputs(argv[1], pf);
fputs("\r\n", pf);
while(fgets(buf, sizeof(buf), pfi)) {
if(starts_with("OK", buf)) {
if (debug == 1)
printf("%s", buf);
exit(0);
}
if(starts_with("ERROR", buf)) {
if (debug == 1)
printf("%s", buf);
exit(1);
}
if(starts_with("COMMAND NOT SUPPORT", buf)) {
if (debug == 1)
printf("%s", buf);
exit(1);
}
if(starts_with("+CME ERROR", buf)) {
if (debug == 1)
printf("%s", buf);
exit(1);
}
printf("%s", buf);
}
}
exit(0);
}
|
281677160/openwrt-package | 1,510 | luci-app-qmodem/application/sms-tool_q/patches/0002-add_timeout_option.patch | --- a/sms_main.c 2024-10-08 23:11:01.169908895 +0800
+++ b/sms_main.c 2024-10-08 23:10:52.929909691 +0800
@@ -46,7 +46,8 @@
static const char* dev = "/dev/ttyUSB0";
static const char* storage = "";
static const char* dateformat = "%D %T";
-
+FILE* pf;
+FILE* pfi;
static void setserial(int baudrate)
{
struct termios t;
@@ -115,7 +116,9 @@
static void timeout()
{
fprintf(stderr,"No response from modem.\n");
- exit(2);
+ if (pf) fclose(pf);
+ if (pfi) fclose(pfi);
+ exit(2);
}
static int starts_with(const char* prefix, const char* str)
@@ -168,12 +171,14 @@
int rawoutput = 0;
int jsonoutput = 0;
int debug = 0;
+ int user_set_timeout = 5;
int dcs = -1;
- while ((ch = getopt(argc, argv, "b:c:d:Ds:f:jRr")) != -1){
+ while ((ch = getopt(argc, argv, "b:c:t:d:Ds:f:jRr")) != -1){
switch (ch) {
case 'b': baudrate = atoi(optarg); break;
case 'c': dcs = atoi(optarg); break;
+ case 't': user_set_timeout = atoi(optarg);break;
case 'd': dev = optarg; break;
case 'D': debug = 1; break;
case 's': storage = optarg; break;
@@ -237,8 +242,8 @@
if (port < 0)
fprintf(stderr,"reopen(%s)\n", dev);
- FILE* pf = fdopen(port, "w");
- FILE* pfi = fdopen(port, "r");
+ pf = fdopen(port, "w");
+ pfi = fdopen(port, "r");
if (!pf || ! pfi)
fprintf(stderr,"open port failed\n");
if(setvbuf(pf, NULL, _IOLBF, 0))
@@ -758,7 +763,8 @@
if (!strcmp("at", argv[0]))
{
- alarm(5);
+
+ alarm(user_set_timeout);
fputs(argv[1], pf);
fputs("\r\n", pf);
|
281677160/openwrt-package | 1,456 | luci-app-qmodem/application/sms-tool_q/patches/0001-send_raw_pdu.patch | --- a/sms_main.c 2024-10-08 23:11:01.169908895 +0800
+++ b/sms_main.c 2024-10-08 23:10:52.929909691 +0800
@@ -200,7 +200,12 @@
{
if(argc < 2)
usage();
- }else if (!strcmp("recv", argv[0]))
+ }
+ else if (!strcmp("send_raw_pdu", argv[0])){
+ if(argc < 2)
+ usage();
+ }
+ else if (!strcmp("recv", argv[0]))
{
}else if (!strcmp("status", argv[0]))
{
@@ -288,6 +293,48 @@
fprintf(stderr,"reading port\n");
}
+ if (!strcmp("send_raw_pdu", argv[0]))
+ {
+ int pdu_len;
+ int pdu_len_except_smsc;
+ char pdustr[1024];
+
+ alarm(5);
+ pdu_len_except_smsc = strlen(argv[1]) / 2 - 1;
+ sprintf(pdustr, "%s%c\r\n", argv[1],0x1A);
+ sprintf(cmdstr, "AT+CMGS=%d\r\n", pdu_len_except_smsc);
+ //set to pdu mode
+ fputs("AT+CMGF=0\r\n", pf);
+ while(fgets(buf, sizeof(buf), pfi)) {
+ if(starts_with("OK", buf))
+ break;
+ }
+ fputs(cmdstr, pf);
+ sleep(1);
+ fputs(pdustr, pf);
+
+ errno = 0;
+
+ while(fgets(buf, sizeof(buf), pfi))
+ {
+ if(starts_with("+CMGS:", buf))
+ {
+ printf("sms sent sucessfully: %s", buf + 7);
+ return 0;
+ } else if(starts_with("+CMS ERROR:", buf))
+ {
+ fprintf(stderr,"sms not sent, code: %s\n", buf + 11);
+ } else if(starts_with("ERROR", buf))
+ {
+ fprintf(stderr,"sms not sent, command error\n");
+ } else if(starts_with("OK", buf))
+ {
+ return 0;
+ }
+ }
+ fprintf(stderr,"reading port\n");
+ }
+
if (!strcmp("recv", argv[0]))
{
alarm(10);
|
281677160/openwrt-package | 1,924 | luci-app-qmodem/application/sms-tool_q/src/pdu_lib/pdu_decoder.c | /*
* 2014 lovewilliam <ztong@vt.edu>
* SMS PDU Decoder
*/
#include "pdu.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
int ucs2_to_utf8 (int ucs2, unsigned char * utf8);
int sms_decode()
{
char buffer[2*SMS_MAX_PDU_LENGTH+4];
char *p = buffer;
char t[2];
int d;
do
{
t[0] = getchar();
if(t[0]=='\n')
{
break;
}
t[1] = getchar();
if(t[1]=='\n')
{
break;
}
*p = strtol(t,NULL,16);
p++;
}while(1);
time_t sms_time;
char sms_phone[40];
char sms_text[161];
int tp_dcs_type;
int ref_number;
int total_parts;
int part_number;
int skip_bytes;
int sms_text_length = pdu_decode((const unsigned char*)buffer,
sizeof(buffer),
&sms_time,
sms_phone, sizeof(sms_phone),
sms_text, sizeof(sms_text),
&tp_dcs_type,
&ref_number,
&total_parts,
&part_number,
&skip_bytes);
printf("From:%s\n",sms_phone);
printf("Textlen=%d\n",sms_text_length);
char time_data_str[64];
strftime(time_data_str,64,"%D %T", localtime(&sms_time));
printf("Date/Time:%s\n",time_data_str);
if (total_parts > 0) {
printf("Reference number: %d\n", ref_number);
printf("SMS segment %d of %d\n", part_number, total_parts);
}
switch((tp_dcs_type / 4) % 4)
{
case 0:
{
// GSM7 bit
int i = skip_bytes;
if(skip_bytes > 0) i = (skip_bytes*8+6)/7;
for(;i<sms_text_length;i++)
{
printf("%c", sms_text[i]);
}
break;
}
case 2:
{
// UCS2
for(int i = skip_bytes;i<sms_text_length;i+=2)
{
int ucs2_char = 0x000000FF&sms_text[i+1];
ucs2_char|=(0x0000FF00&(sms_text[i]<<8));
unsigned char utf8_char[5];
int len = ucs2_to_utf8(ucs2_char,utf8_char);
int j;
for(j=0;j<len;j++)
{
printf("%c",utf8_char[j]);
}
}
break;
}
default:
break;
}
printf("\n");
return 0;
}
int main()
{
return sms_decode();
}
|
281677160/openwrt-package | 1,483 | luci-app-qmodem/application/sms-tool_q/src/pdu_lib/ucs2_to_utf8.c | /*
* 2014 lovewilliam <ztong@vt.edu>
* from http://www.lemoda.net/c/ucs2-to-utf8/ucs2-to-utf8.c
*/
/* Input: a Unicode code point, "ucs2".
Output: UTF-8 characters in buffer "utf8".
Return value: the number of bytes written into "utf8", or -1 if
there was an error.
This adds a zero byte to the end of the string. It assumes that the
buffer "utf8" has at least four bytes of space to write to. */
#define UNICODE_SURROGATE_PAIR -2
#define UNICODE_BAD_INPUT -1
int ucs2_to_utf8 (int ucs2, unsigned char * utf8)
{
if (ucs2 < 0x80) {
utf8[0] = ucs2;
utf8[1] = '\0';
return 1;
}
if (ucs2 >= 0x80 && ucs2 < 0x800) {
utf8[0] = (ucs2 >> 6) | 0xC0;
utf8[1] = (ucs2 & 0x3F) | 0x80;
utf8[2] = '\0';
return 2;
}
if (ucs2 >= 0x800 && ucs2 < 0xFFFF) {
if (ucs2 >= 0xD800 && ucs2 <= 0xDFFF) {
/* Ill-formed. */
return UNICODE_SURROGATE_PAIR;
}
utf8[0] = ((ucs2 >> 12) ) | 0xE0;
utf8[1] = ((ucs2 >> 6 ) & 0x3F) | 0x80;
utf8[2] = ((ucs2 ) & 0x3F) | 0x80;
utf8[3] = '\0';
return 3;
}
if (ucs2 >= 0x10000 && ucs2 < 0x10FFFF) {
/* http://tidy.sourceforge.net/cgi-bin/lxr/source/src/utf8.c#L380 */
utf8[0] = 0xF0 | (ucs2 >> 18);
utf8[1] = 0x80 | ((ucs2 >> 12) & 0x3F);
utf8[2] = 0x80 | ((ucs2 >> 6) & 0x3F);
utf8[3] = 0x80 | ((ucs2 & 0x3F));
utf8[4] = '\0';
return 4;
}
return UNICODE_BAD_INPUT;
}
|
281677160/openwrt-package | 15,113 | luci-app-qmodem/application/sms-tool_q/src/pdu_lib/pdu.c | /*
* 2017 - 2021 Cezary Jackiewicz <cezary@eko.one.pl>
* 2014 lovewilliam <ztong@vt.edu>
*/
// Copyright 2011 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
//
// SMS encoding/decoding functions, which are based on examples from:
// http://www.dreamfabric.com/sms/
#include "pdu.h"
#include <string.h>
#include <time.h>
#include <math.h>
enum {
BITMASK_7BITS = 0x7F,
BITMASK_8BITS = 0xFF,
BITMASK_HIGH_4BITS = 0xF0,
BITMASK_LOW_4BITS = 0x0F,
TYPE_OF_ADDRESS_UNKNOWN = 0x81,
TYPE_OF_ADDRESS_INTERNATIONAL_PHONE = 0x91,
TYPE_OF_ADDRESS_NATIONAL_SUBSCRIBER = 0xC8,
TYPE_OF_ADDRESS_ALPHANUMERIC = 0xD0,
SMS_DELIVER_ONE_MESSAGE = 0x04,
SMS_SUBMIT = 0x11,
SMS_MAX_7BIT_TEXT_LENGTH = 160,
};
// Swap decimal digits of a number (e.g. 12 -> 21).
static unsigned char
SwapDecimalNibble(const unsigned char x)
{
return (x / 16) + ((x % 16) * 10);
}
// Encode/Decode PDU: Translate ASCII 7bit characters to 8bit buffer.
// SMS encoding example from: http://www.dreamfabric.com/sms/.
//
// 7-bit ASCII: "hellohello"
// [0]:h [1]:e [2]:l [3]:l [4]:o [5]:h [6]:e [7]:l [8]:l [9]:o
// 1101000 1100101 1101100 1101100 1101111 1101000 1100101 1101100 1101100 1101111
// | ||| ||||| | ||||||| ||||||
// /-------------/ ///-------/// /////-///// \------------\ ||||||| \\\\\\ .
// | ||| ||||| | ||||||| ||||||
// input buffer position
// 10000000 22111111 33322222 44443333 55555333 66666655 77777776 98888888 --999999
// | ||| ||||| | ||||||| ||||||
// 8bit encoded buffer
// 11101000 00110010 10011011 11111101 01000110 10010111 11011001 11101100 00110111
// E8 32 9B FD 46 97 D9 EC 37
// Encode PDU message by merging 7 bit ASCII characters into 8 bit octets.
int
EncodePDUMessage(const char* sms_text, int sms_text_length, unsigned char* output_buffer, int buffer_size)
{
// Check if output buffer is big enough.
if ((sms_text_length * 7 + 7) / 8 > buffer_size)
return -1;
int output_buffer_length = 0;
int carry_on_bits = 1;
int i = 0;
for (; i < sms_text_length - 1; ++i) {
output_buffer[output_buffer_length++] =
((sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1)) |
((sms_text[i + 1] & BITMASK_7BITS) << (8 - carry_on_bits));
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
++i;
}
}
if (i <= sms_text_length)
output_buffer[output_buffer_length++] = (sms_text[i] & BITMASK_7BITS) >> (carry_on_bits - 1);
return output_buffer_length;
}
// Decode PDU message by splitting 8 bit encoded buffer into 7 bit ASCII
// characters.
int
DecodePDUMessage_GSM_7bit(const unsigned char* buffer, int buffer_length, char* output_sms_text, int sms_text_length)
{
int output_text_length = 0;
if (buffer_length > 0)
output_sms_text[output_text_length++] = BITMASK_7BITS & buffer[0];
if (sms_text_length > 1) {
int carry_on_bits = 1;
int i = 1;
for (; i < buffer_length; ++i) {
output_sms_text[output_text_length++] = BITMASK_7BITS & ((buffer[i] << carry_on_bits) | (buffer[i - 1] >> (8 - carry_on_bits)));
if (output_text_length == sms_text_length) break;
carry_on_bits++;
if (carry_on_bits == 8) {
carry_on_bits = 1;
output_sms_text[output_text_length++] = buffer[i] & BITMASK_7BITS;
if (output_text_length == sms_text_length) break;
}
}
if (output_text_length < sms_text_length) // Add last remainder.
output_sms_text[output_text_length++] = buffer[i - 1] >> (8 - carry_on_bits);
}
return output_text_length;
}
#define GSM_7BITS_ESCAPE 0x1b
static const unsigned char gsm7bits_to_latin1[128] = {
'@', 0xa3, '$', 0xa5, 0xe8, 0xe9, 0xf9, 0xec, 0xf2, 0xc7, '\n', 0xd8, 0xf8, '\r', 0xc5, 0xe5,
0, '_', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc6, 0xe6, 0xdf, 0xc9,
' ', '!', '"', '#', 0xa4, '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?',
0xa1, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 0xc4, 0xd6, 0xd1, 0xdc, 0xa7,
0xbf, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0xe4, 0xf6, 0xf1, 0xfc, 0xe0,
};
static const unsigned char gsm7bits_extend_to_latin1[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\f', 0, 0, 0, 0, 0,
0, 0, 0, 0, '^', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, '{', '}', 0, 0, 0, 0, 0,'\\',
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '[', '~', ']', 0,
'|', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static int
G7bitToAscii(char* buffer, int buffer_length)
{
int i;
for (i = 0; i<buffer_length; i++) {
if (buffer[i] < 128) {
if (buffer[i] == GSM_7BITS_ESCAPE) {
buffer[i] = gsm7bits_extend_to_latin1[buffer[i + 1]];
memmove(&buffer[i + 1], &buffer[i + 2], buffer_length - i - 1);
buffer_length--;
} else {
buffer[i] = gsm7bits_to_latin1[buffer[i]];
}
}
}
return buffer_length;
}
#define NPC '?'
static const int latin1_to_gsm7bits[256] = {
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, 0x0a, NPC,-0x0a, 0x0d, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
0x20, 0x21, 0x22, 0x23, 0x02, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,-0x3c,-0x2f,-0x3e,-0x14, 0x11,
NPC, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a,-0x28,-0x40,-0x29,-0x3d, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, 0x40, NPC, 0x01, 0x24, 0x03, NPC, 0x5f, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, NPC, 0x60,
NPC, NPC, NPC, NPC, 0x5b, 0x0e, 0x1c, 0x09, NPC, 0x1f, NPC, NPC, NPC, NPC, NPC, NPC,
NPC, 0x5d, NPC, NPC, NPC, NPC, 0x5c, NPC, 0x0b, NPC, NPC, NPC, 0x5e, NPC, NPC, 0x1e,
0x7f, NPC, NPC, NPC, 0x7b, 0x0f, 0x1d, NPC, 0x04, 0x05, NPC, NPC, 0x07, NPC, NPC, NPC,
NPC, 0x7d, 0x08, NPC, NPC, NPC, 0x7c, NPC, 0x0c, 0x06, NPC, NPC, 0x7e, NPC, NPC, NPC,
};
static int
AsciiToG7bit(const char* buffer, int buffer_length, unsigned char* output_buffer)
{
int i, j, val;
j=0;
for (i = 0; i < buffer_length; i++) {
val = latin1_to_gsm7bits[buffer[i] & 0xFF];
if (val < 0) {
output_buffer[j++] = GSM_7BITS_ESCAPE;
output_buffer[j++] = -1*val;
} else {
if (((buffer[i] & 0xFF) & 0xE0) == 0xC0) { /* test for two byte utf8 char */
val = NPC;
i++;
} else if (((buffer[i] & 0xFF) & 0xF0) == 0xE0) { /* test for three byte utf8 char */
val = NPC;
i++;
i++;
}
output_buffer[j++] = val;
}
}
return j;
}
// Encode a digit based phone number for SMS based format.
static int
EncodePhoneNumber(const char* phone_number, unsigned char* output_buffer, int buffer_size)
{
int output_buffer_length = 0;
const int phone_number_length = strlen(phone_number);
// Check if the output buffer is big enough.
if ((phone_number_length + 1) / 2 > buffer_size)
return -1;
int i = 0;
for (; i < phone_number_length; ++i) {
if (phone_number[i] < '0' && phone_number[i] > '9')
return -1;
if (i % 2 == 0) {
output_buffer[output_buffer_length++] = BITMASK_HIGH_4BITS | (phone_number[i] - '0');
} else {
output_buffer[output_buffer_length - 1] =
(output_buffer[output_buffer_length - 1] & BITMASK_LOW_4BITS) |
((phone_number[i] - '0') << 4);
}
}
return output_buffer_length;
}
// Decode a digit based phone number for SMS based format.
static int
DecodePhoneNumber(const unsigned char* buffer, int phone_number_length, char* output_phone_number)
{
int i = 0;
for (; i < phone_number_length; ++i) {
if (i % 2 == 0)
output_phone_number[i] = (buffer[i / 2] & BITMASK_LOW_4BITS) + '0';
else
output_phone_number[i] = ((buffer[i / 2] & BITMASK_HIGH_4BITS) >> 4) + '0';
}
output_phone_number[phone_number_length] = '\0'; // Terminate C string.
return phone_number_length;
}
// Encode a SMS message to PDU
int
pdu_encode(const char* service_center_number, const char* phone_number, const char* sms_text,
unsigned char* output_buffer, int buffer_size)
{
if (buffer_size < 2)
return -1;
int output_buffer_length = 0;
// 1. Set SMS center number.
int length = 0;
if (service_center_number && strlen(service_center_number) > 0) {
output_buffer[1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
length = EncodePhoneNumber(service_center_number,
output_buffer + 2, buffer_size - 2);
if (length < 0 && length >= 254)
return -1;
length++; // Add type of address.
}
output_buffer[0] = length;
output_buffer_length = length + 1;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 2. Set type of message.
output_buffer[output_buffer_length++] = SMS_SUBMIT;
output_buffer[output_buffer_length++] = 0x00; // Message reference.
// 3. Set phone number.
output_buffer[output_buffer_length] = strlen(phone_number);
if (strlen(phone_number) < 6) {
output_buffer[output_buffer_length + 1] = TYPE_OF_ADDRESS_UNKNOWN;
} else {
output_buffer[output_buffer_length + 1] = TYPE_OF_ADDRESS_INTERNATIONAL_PHONE;
}
length = EncodePhoneNumber(phone_number,
output_buffer + output_buffer_length + 2,
buffer_size - output_buffer_length - 2);
output_buffer_length += length + 2;
if (output_buffer_length + 4 > buffer_size)
return -1; // Check if it has space for four more bytes.
// 4. Protocol identifiers.
output_buffer[output_buffer_length++] = 0x00; // TP-PID: Protocol identifier.
output_buffer[output_buffer_length++] = 0x00; // TP-DCS: Data coding scheme.
output_buffer[output_buffer_length++] = 0xB0; // TP-VP: Validity: 10 days
// 5. SMS message.
int sms_text_length = strlen(sms_text);
char sms_text_7bit[2*SMS_MAX_7BIT_TEXT_LENGTH];
sms_text_length = AsciiToG7bit(sms_text, sms_text_length, sms_text_7bit);
if (sms_text_length > SMS_MAX_7BIT_TEXT_LENGTH)
return -1;
output_buffer[output_buffer_length++] = sms_text_length;
length = EncodePDUMessage(sms_text_7bit, sms_text_length,
output_buffer + output_buffer_length,
buffer_size - output_buffer_length);
if (length < 0)
return -1;
output_buffer_length += length;
return output_buffer_length;
}
int pdu_decode(const unsigned char* buffer, int buffer_length,
time_t* output_sms_time,
char* output_sender_phone_number, int sender_phone_number_size,
char* output_sms_text, int sms_text_size,
int* tp_dcs,
int* ref_number,
int* total_parts,
int* part_number,
int* skip_bytes)
{
if (buffer_length <= 0)
return -1;
const int sms_deliver_start = 1 + buffer[0];
if (sms_deliver_start + 1 > buffer_length)
return -2;
const int user_data_header_length = (buffer[sms_deliver_start]>>4);
const int sender_number_length = buffer[sms_deliver_start + 1];
if (sender_number_length + 1 > sender_phone_number_size)
return -3; // Buffer too small to hold decoded phone number.
const int sender_type_of_address = buffer[sms_deliver_start + 2];
if (sender_type_of_address == TYPE_OF_ADDRESS_ALPHANUMERIC) {
int sender_len1 = DecodePDUMessage_GSM_7bit(buffer + sms_deliver_start + 3, ceil(sender_number_length * 1.0 / 2), output_sender_phone_number, sender_number_length);
if (output_sender_phone_number[sender_len1 - 1] == '\0')
sender_len1--;
int sender_len2 = G7bitToAscii(output_sender_phone_number, sender_len1);
output_sender_phone_number[sender_len2] = 0;
} else {
DecodePhoneNumber(buffer + sms_deliver_start + 3, sender_number_length, output_sender_phone_number);
}
const int sms_pid_start = sms_deliver_start + 3 + (buffer[sms_deliver_start + 1] + 1) / 2;
// Decode timestamp.
struct tm sms_broken_time;
sms_broken_time.tm_year = 100 + SwapDecimalNibble(buffer[sms_pid_start + 2]);
sms_broken_time.tm_mon = SwapDecimalNibble(buffer[sms_pid_start + 3]) - 1;
sms_broken_time.tm_mday = SwapDecimalNibble(buffer[sms_pid_start + 4]);
sms_broken_time.tm_hour = SwapDecimalNibble(buffer[sms_pid_start + 5]);
sms_broken_time.tm_min = SwapDecimalNibble(buffer[sms_pid_start + 6]);
sms_broken_time.tm_sec = SwapDecimalNibble(buffer[sms_pid_start + 7]);
(*output_sms_time) = timegm(&sms_broken_time);
const int sms_start = sms_pid_start + 2 + 7;
if (sms_start + 1 > buffer_length) return -1; // Invalid input buffer.
int tmp;
if((user_data_header_length&0x04)==0x04) {
tmp = buffer[sms_start + 1] + 1;
*skip_bytes = tmp;
*ref_number = 0x000000FF&buffer[sms_start + tmp - 2];
*total_parts = 0x000000FF&buffer[sms_start + tmp - 1];
*part_number = 0x000000FF&buffer[sms_start + tmp];
} else {
tmp = 0;
*skip_bytes = tmp;
*ref_number = tmp;
*total_parts = tmp;
*part_number = tmp;
}
int output_sms_text_length = buffer[sms_start];
if (sms_text_size < output_sms_text_length) return -1; // Cannot hold decoded buffer.
const int sms_tp_dcs_start = sms_pid_start + 1;
*tp_dcs = buffer[sms_tp_dcs_start];
switch((*tp_dcs / 4) % 4)
{
case 0:
{
// GSM 7 bit
int decoded_sms_text_size = DecodePDUMessage_GSM_7bit(buffer + sms_start + 1, buffer_length - (sms_start + 1),
output_sms_text, output_sms_text_length);
if (decoded_sms_text_size != output_sms_text_length) return -1; // Decoder length is not as expected.
output_sms_text_length = G7bitToAscii(output_sms_text, output_sms_text_length);
break;
}
case 2:
{
// UCS2
memcpy(output_sms_text, buffer + sms_start + 1, output_sms_text_length);
break;
}
default:
break;
}
// Add a C string end.
if (output_sms_text_length < sms_text_size)
output_sms_text[output_sms_text_length] = 0;
else
output_sms_text[sms_text_size-1] = 0;
return output_sms_text_length;
}
|
281677160/openwrt-package | 1,670 | luci-app-qmodem/application/sms-tool_q/src/pdu_lib/pdu.h | /*
* 2017 - 2021 Cezary Jackiewicz <cezary@eko.one.pl>
* 2014 lovewilliam <ztong@vt.edu>
*/
// Copyright 2011 The Avalon Project Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0
// that can be found in the LICENSE file.
#ifndef SMS_PDU_H_
#define SMS_PDU_H_
#include <time.h>
enum { SMS_MAX_PDU_LENGTH = 256 };
/*
* Encode an SMS message. Output the encoded message into output pdu buffer.
* Returns the length of the SMS encoded message in the output buffer or
* a negative number in case encoding failed (for example provided output buffer
* does not have enough space).
*/
int pdu_encode(const char* service_center_number, const char* phone_number, const char* text,
unsigned char* pdu, int pdu_size);
/*
* Decode an SMS message. Output the decoded message into the sms text buffer.
* Returns the length of the SMS dencoded message or a negative number in
* case encoding failed (for example provided output buffer has not enough
* space).
*/
int pdu_decode(const unsigned char* pdu, int pdu_len,
time_t* sms_time,
char* phone_number, int phone_number_size,
char* text, int text_size,
int* tp_dcs,
int* ref_number,
int* total_parts,
int* part_number,
int* skip_bytes);
int ucs2_to_utf8 (int ucs2, unsigned char * utf8);
int DecodePDUMessage_GSM_7bit(const unsigned char* buffer,
int buffer_length,
char* output_sms_text,
int sms_text_length);
int EncodePDUMessage(const char* sms_text,
int sms_text_length,
unsigned char* output_buffer,
int buffer_size);
#endif // SMS_SMS_H_
|
281677160/openwrt-package | 1,337 | luci-app-qmodem/application/sms_forwarder/src/Makefile.local | # Cross-compile setup for ImmortalWrt
STAGING_DIR ?= $(HOME)/qwrt_works/immortalwrt/staging_dir
TARGET_DIR ?= $(STAGING_DIR)/target-aarch64_generic_musl
TOOLCHAIN_DIR ?= $(STAGING_DIR)/toolchain-aarch64_generic_gcc-13.3.0_musl
# Cross-compiler and tools
CROSS_COMPILE ?= aarch64-openwrt-linux-musl-
CC = $(TOOLCHAIN_DIR)/bin/$(CROSS_COMPILE)gcc
AR = $(TOOLCHAIN_DIR)/bin/$(CROSS_COMPILE)ar
STRIP = $(TOOLCHAIN_DIR)/bin/$(CROSS_COMPILE)strip
# Include and library paths
CFLAGS = -Wall -Wextra -std=c99 -D_GNU_SOURCE
CFLAGS += -I$(TARGET_DIR)/usr/include
CFLAGS += -I$(TARGET_DIR)/usr/include/libubox
CFLAGS += -I$(TARGET_DIR)/usr/include/json-c
CC ?= gcc
CFLAGS += -Wall -std=c99
LDFLAGS += -ljson-c
TARGET = sms_forwarder
SOURCES = main.c
LDFLAGS = -L$(TARGET_DIR)/usr/lib
LDFLAGS += -L$(TARGET_DIR)/lib
LDFLAGS += -ljson-c
all: $(TARGET)
$(TARGET): $(SOURCES)
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
debug_test: debug_test.c
$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
clean:
rm -f $(TARGET) debug_test
.PHONY: all clean
install:
scp /home/fjr/hobbies/modem_feeds/application/sms_forwarder/files/etc/init.d/sms_forwarder root@192.168.1.1:/etc/init.d/sms_forwarder
ssh root@192.168.1.1 "/etc/init.d/sms_forwarder stop"
scp sms_forwarder root@192.168.1.1:/usr/bin/sms_forwarder
ssh root@192.168.1.1 "/etc/init.d/sms_forwarder start"
|
281677160/openwrt-package | 22,252 | luci-app-qmodem/application/sms_forwarder/src/main.c | #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <json-c/json.h>
#include "sms_forwarder.h"
static volatile int g_running = 1;
static sms_forwarder_config_t g_config;
static void signal_handler(int sig) {
switch (sig) {
case SIGTERM:
case SIGINT:
syslog(LOG_INFO, "Received signal %d, shutting down", sig);
g_running = 0;
break;
case SIGCHLD:
wait(NULL);
break;
}
}
static void setup_signals() {
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGCHLD, signal_handler);
signal(SIGPIPE, SIG_IGN);
}
static int parse_config_file(const char *config_file, sms_forwarder_config_t *config) {
FILE *fp = fopen(config_file, "r");
if (!fp) {
syslog(LOG_ERR, "Cannot open config file: %s", config_file);
return -1;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *json_string = malloc(size + 1);
if (!json_string) {
fclose(fp);
syslog(LOG_ERR, "Memory allocation failed");
return -1;
}
fread(json_string, 1, size, fp);
json_string[size] = '\0';
fclose(fp);
json_object *root = json_tokener_parse(json_string);
free(json_string);
if (!root) {
syslog(LOG_ERR, "Invalid JSON in config file");
return -1;
}
// Initialize config structure
memset(config, 0, sizeof(sms_forwarder_config_t));
// Check if root is an array (new format) or object (old format)
if (json_object_is_type(root, json_type_array)) {
// New format: array of modem configurations
int array_len = json_object_array_length(root);
config->modem_count = (array_len > MAX_API_COUNT) ? MAX_API_COUNT : array_len;
for (int i = 0; i < config->modem_count; i++) {
json_object *modem_obj = json_object_array_get_idx(root, i);
if (!modem_obj) continue;
// Set defaults
config->modems[i].poll_interval = 30;
config->modems[i].delete_after_forward = 0;
config->modems[i].api_count = 0;
// Parse modem_port
json_object *obj;
const char *str_val;
if (json_object_object_get_ex(modem_obj, "modem_port", &obj)) {
str_val = json_object_get_string(obj);
if (str_val) {
strncpy(config->modems[i].modem_port, str_val, sizeof(config->modems[i].modem_port) - 1);
config->modems[i].modem_port[sizeof(config->modems[i].modem_port) - 1] = '\0';
}
}
if (json_object_object_get_ex(modem_obj, "poll_interval", &obj)) {
config->modems[i].poll_interval = json_object_get_int(obj);
}
if (json_object_object_get_ex(modem_obj, "delete_after_forward", &obj)) {
config->modems[i].delete_after_forward = json_object_get_boolean(obj);
}
// Parse apis array
json_object *apis_array;
if (json_object_object_get_ex(modem_obj, "apis", &apis_array) && json_object_is_type(apis_array, json_type_array)) {
int api_array_len = json_object_array_length(apis_array);
config->modems[i].api_count = (api_array_len > MAX_API_COUNT) ? MAX_API_COUNT : api_array_len;
for (int j = 0; j < config->modems[i].api_count; j++) {
json_object *api_obj = json_object_array_get_idx(apis_array, j);
if (!api_obj) continue;
if (json_object_object_get_ex(api_obj, "api_type", &obj)) {
str_val = json_object_get_string(obj);
if (str_val) {
strncpy(config->modems[i].apis[j].api_type, str_val, sizeof(config->modems[i].apis[j].api_type) - 1);
config->modems[i].apis[j].api_type[sizeof(config->modems[i].apis[j].api_type) - 1] = '\0';
}
}
if (json_object_object_get_ex(api_obj, "api_config", &obj)) {
const char *api_config_str = json_object_to_json_string(obj);
if (api_config_str) {
strncpy(config->modems[i].apis[j].api_config, api_config_str, sizeof(config->modems[i].apis[j].api_config) - 1);
config->modems[i].apis[j].api_config[sizeof(config->modems[i].apis[j].api_config) - 1] = '\0';
}
}
}
}
}
} else {
// Old format: single modem configuration - convert to new format
config->modem_count = 1;
config->modems[0].poll_interval = 30;
config->modems[0].delete_after_forward = 0;
config->modems[0].api_count = 1;
json_object *obj;
const char *str_val;
if (json_object_object_get_ex(root, "modem_port", &obj)) {
str_val = json_object_get_string(obj);
if (str_val) {
strncpy(config->modems[0].modem_port, str_val, sizeof(config->modems[0].modem_port) - 1);
config->modems[0].modem_port[sizeof(config->modems[0].modem_port) - 1] = '\0';
}
}
if (json_object_object_get_ex(root, "poll_interval", &obj)) {
config->modems[0].poll_interval = json_object_get_int(obj);
}
if (json_object_object_get_ex(root, "api_type", &obj)) {
str_val = json_object_get_string(obj);
if (str_val) {
strncpy(config->modems[0].apis[0].api_type, str_val, sizeof(config->modems[0].apis[0].api_type) - 1);
config->modems[0].apis[0].api_type[sizeof(config->modems[0].apis[0].api_type) - 1] = '\0';
}
}
if (json_object_object_get_ex(root, "api_config", &obj)) {
const char *api_config_str = json_object_to_json_string(obj);
if (api_config_str) {
strncpy(config->modems[0].apis[0].api_config, api_config_str, sizeof(config->modems[0].apis[0].api_config) - 1);
config->modems[0].apis[0].api_config[sizeof(config->modems[0].apis[0].api_config) - 1] = '\0';
}
}
if (json_object_object_get_ex(root, "delete_after_forward", &obj)) {
config->modems[0].delete_after_forward = json_object_get_boolean(obj);
}
}
json_object_put(root);
return 0;
}
static int check_dependencies() {
// Check if curl is available
if (system("which curl > /dev/null 2>&1") == 0) {
return USE_CURL;
}
// Check if wget is available
if (system("which wget > /dev/null 2>&1") == 0) {
return USE_WGET;
}
syslog(LOG_WARNING, "Neither curl nor wget found, only custom scripts will work");
return USE_NONE;
}
static char* read_sms_from_modem(const char *modem_port) {
char cmd[256];
snprintf(cmd, sizeof(cmd), "tom_modem -d %s -u -o u 2>/dev/null", modem_port);
FILE *fp = popen(cmd, "r");
if (!fp) {
syslog(LOG_ERR, "Failed to execute tom_modem command");
return NULL;
}
char *result = malloc(SMS_BUFFER_SIZE);
if (!result) {
pclose(fp);
syslog(LOG_ERR, "Memory allocation failed");
return NULL;
}
size_t total_read = 0;
size_t bytes_read;
while ((bytes_read = fread(result + total_read, 1, SMS_BUFFER_SIZE - total_read - 1, fp)) > 0) {
total_read += bytes_read;
if (total_read >= SMS_BUFFER_SIZE - 1) {
break;
}
}
result[total_read] = '\0';
pclose(fp);
if (total_read == 0) {
free(result);
return NULL;
}
return result;
}
static int delete_sms_from_modem(const char *modem_port, int *indices, int count) {
if (!indices || count <= 0) {
return 0;
}
for (int i = 0; i < count; i++) {
char cmd[256];
snprintf(cmd, sizeof(cmd), "tom_modem -d %s -u -o d -i %d 2>/dev/null",
modem_port, indices[i]);
int ret = system(cmd);
if (ret != 0) {
syslog(LOG_WARNING, "Failed to delete SMS at index %d from modem", indices[i]);
} else {
syslog(LOG_INFO, "Successfully deleted SMS at index %d from modem", indices[i]);
}
}
return 0;
}
static sms_message_t* parse_sms_json(const char *json_str, int *count) {
json_object *root = json_tokener_parse(json_str);
if (!root) {
syslog(LOG_ERR, "Failed to parse SMS JSON");
return NULL;
}
json_object *msg_array;
if (!json_object_object_get_ex(root, "msg", &msg_array)) {
json_object_put(root);
return NULL;
}
int array_len = json_object_array_length(msg_array);
if (array_len == 0) {
json_object_put(root);
*count = 0;
return NULL;
}
sms_message_t *messages = malloc(array_len * sizeof(sms_message_t));
if (!messages) {
json_object_put(root);
syslog(LOG_ERR, "Memory allocation failed for messages");
*count = 0;
return NULL;
}
*count = array_len;
for (int i = 0; i < array_len; i++) {
json_object *msg_obj = json_object_array_get_idx(msg_array, i);
json_object *field;
const char *str_val;
memset(&messages[i], 0, sizeof(sms_message_t));
if (json_object_object_get_ex(msg_obj, "index", &field)) {
messages[i].index = json_object_get_int(field);
}
if (json_object_object_get_ex(msg_obj, "sender", &field)) {
str_val = json_object_get_string(field);
if (str_val) {
strncpy(messages[i].sender, str_val, sizeof(messages[i].sender) - 1);
messages[i].sender[sizeof(messages[i].sender) - 1] = '\0';
}
}
if (json_object_object_get_ex(msg_obj, "timestamp", &field)) {
messages[i].timestamp = json_object_get_int64(field);
}
if (json_object_object_get_ex(msg_obj, "content", &field)) {
str_val = json_object_get_string(field);
if (str_val) {
strncpy(messages[i].content, str_val, sizeof(messages[i].content) - 1);
messages[i].content[sizeof(messages[i].content) - 1] = '\0';
}
}
if (json_object_object_get_ex(msg_obj, "reference", &field)) {
messages[i].reference = json_object_get_int(field);
}
if (json_object_object_get_ex(msg_obj, "total", &field)) {
messages[i].total = json_object_get_int(field);
}
if (json_object_object_get_ex(msg_obj, "part", &field)) {
messages[i].part = json_object_get_int(field);
}
}
json_object_put(root);
return messages;
}
static int find_and_process_sms_groups(sms_message_t *messages, int count, processed_sms_t **processed, int *processed_count) {
*processed = NULL;
*processed_count = 0;
if (!messages || count == 0) {
return 0;
}
// Track which messages have been processed
int *processed_flags = calloc(count, sizeof(int));
if (!processed_flags) {
syslog(LOG_ERR, "Memory allocation failed for processed flags");
return -1;
}
processed_sms_t *temp_processed = malloc(count * sizeof(processed_sms_t));
if (!temp_processed) {
free(processed_flags);
syslog(LOG_ERR, "Memory allocation failed for processed messages");
return -1;
}
int temp_count = 0;
// First, process single part messages
for (int i = 0; i < count; i++) {
if (processed_flags[i] || messages[i].total > 1) {
continue;
}
// Single part message
temp_processed[temp_count].content = malloc(strlen(messages[i].content) + 1);
if (!temp_processed[temp_count].content) {
syslog(LOG_ERR, "Memory allocation failed for single SMS content");
continue;
}
strcpy(temp_processed[temp_count].content, messages[i].content);
strcpy(temp_processed[temp_count].sender, messages[i].sender);
temp_processed[temp_count].timestamp = messages[i].timestamp;
temp_processed[temp_count].indices = malloc(sizeof(int));
if (temp_processed[temp_count].indices) {
temp_processed[temp_count].indices[0] = messages[i].index;
temp_processed[temp_count].index_count = 1;
} else {
temp_processed[temp_count].index_count = 0;
}
processed_flags[i] = 1;
temp_count++;
}
// Then, process multipart messages
for (int i = 0; i < count; i++) {
if (processed_flags[i] || messages[i].total <= 1) {
continue;
}
int ref = messages[i].reference;
char *sender = messages[i].sender;
int total_parts = messages[i].total;
// Collect all parts for this reference and sender
sms_message_t *parts = malloc(total_parts * sizeof(sms_message_t));
if (!parts) {
syslog(LOG_ERR, "Memory allocation failed for SMS parts");
continue;
}
int found_parts = 0;
for (int j = 0; j < count; j++) {
if (processed_flags[j]) continue;
if (messages[j].reference == ref &&
strcmp(messages[j].sender, sender) == 0 &&
messages[j].total == total_parts) {
parts[found_parts++] = messages[j];
}
}
if (found_parts == total_parts) {
// Sort parts by part number
for (int x = 0; x < found_parts - 1; x++) {
for (int y = x + 1; y < found_parts; y++) {
if (parts[x].part > parts[y].part) {
sms_message_t temp = parts[x];
parts[x] = parts[y];
parts[y] = temp;
}
}
}
// Concatenate content
int total_len = 0;
for (int k = 0; k < found_parts; k++) {
total_len += strlen(parts[k].content);
}
temp_processed[temp_count].content = malloc(total_len + 1);
if (temp_processed[temp_count].content) {
temp_processed[temp_count].content[0] = '\0';
for (int k = 0; k < found_parts; k++) {
strcat(temp_processed[temp_count].content, parts[k].content);
}
strcpy(temp_processed[temp_count].sender, parts[0].sender);
temp_processed[temp_count].timestamp = parts[0].timestamp;
// Store indices for deletion
temp_processed[temp_count].indices = malloc(found_parts * sizeof(int));
if (temp_processed[temp_count].indices) {
for (int k = 0; k < found_parts; k++) {
temp_processed[temp_count].indices[k] = parts[k].index;
}
temp_processed[temp_count].index_count = found_parts;
} else {
temp_processed[temp_count].index_count = 0;
}
// Mark all parts as processed
for (int j = 0; j < count; j++) {
if (messages[j].reference == ref &&
strcmp(messages[j].sender, sender) == 0 &&
messages[j].total == total_parts) {
processed_flags[j] = 1;
}
}
temp_count++;
}
}
free(parts);
}
free(processed_flags);
if (temp_count > 0) {
*processed = temp_processed;
*processed_count = temp_count;
} else {
free(temp_processed);
}
return 0;
}
static int execute_callback(const char *api_type, const char *api_config,
const char *sender, time_t timestamp, const char *content) {
char time_str[32];
struct tm *tm_info = localtime(×tamp);
strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", tm_info);
// Set environment variables
setenv("SMS_SENDER", sender, 1);
setenv("SMS_TIME", time_str, 1);
setenv("SMS_CONTENT", content, 1);
char script_path[256];
char cmd[512];
if (strcmp(api_type, "custom_script") == 0) {
json_object *config_obj = json_tokener_parse(api_config);
if (!config_obj) {
syslog(LOG_ERR, "Invalid API config JSON");
return -1;
}
json_object *script_obj;
if (json_object_object_get_ex(config_obj, "script_path", &script_obj)) {
strncpy(script_path, json_object_get_string(script_obj), sizeof(script_path) - 1);
}
json_object_put(config_obj);
snprintf(cmd, sizeof(cmd), "%s", script_path);
} else {
snprintf(script_path, sizeof(script_path), "/usr/bin/sms_forward_%s.sh", api_type);
snprintf(cmd, sizeof(cmd), "%s '%s'", script_path, api_config);
}
// Execute script
int ret = system(cmd);
if (ret != 0) {
syslog(LOG_ERR, "Failed to execute callback script: %s", script_path);
return -1;
}
syslog(LOG_INFO, "SMS forwarded successfully via %s", api_type);
return 0;
}
static void process_sms_messages(modem_config_t *modem_config) {
char *sms_json = read_sms_from_modem(modem_config->modem_port);
if (!sms_json) {
return;
}
int count;
sms_message_t *messages = parse_sms_json(sms_json, &count);
free(sms_json);
if (!messages || count == 0) {
return;
}
processed_sms_t *processed = NULL;
int processed_count = 0;
if (find_and_process_sms_groups(messages, count, &processed, &processed_count) == 0 && processed) {
// Process all SMS messages
for (int i = 0; i < processed_count; i++) {
int success_count = 0;
// Try to forward through all configured APIs
for (int j = 0; j < modem_config->api_count; j++) {
int ret = execute_callback(modem_config->apis[j].api_type, modem_config->apis[j].api_config,
processed[i].sender, processed[i].timestamp, processed[i].content);
if (ret == 0) {
success_count++;
}
}
// Delete SMS messages if at least one forwarding was successful and delete option is enabled
if (success_count > 0 && modem_config->delete_after_forward && processed[i].indices) {
delete_sms_from_modem(modem_config->modem_port, processed[i].indices, processed[i].index_count);
}
// Cleanup
if (processed[i].content) {
free(processed[i].content);
}
if (processed[i].indices) {
free(processed[i].indices);
}
}
free(processed);
}
free(messages);
}
int main(int argc, char *argv[]) {
printf("SMS Forwarder starting...\n");
fflush(stdout);
if (argc != 2) {
fprintf(stderr, "Usage: %s <config_file>\n", argv[0]);
return 1;
}
printf("Opening syslog...\n");
fflush(stdout);
openlog("sms_forwarder", LOG_PID, LOG_DAEMON);
printf("Parsing config file: %s\n", argv[1]);
fflush(stdout);
// Parse configuration
if (parse_config_file(argv[1], &g_config) < 0) {
syslog(LOG_ERR, "Failed to parse config file: %s", argv[1]);
printf("Failed to parse config file\n");
return 1;
}
printf("Config parsed successfully\n");
printf("Found %d modem(s) to monitor:\n", g_config.modem_count);
for (int i = 0; i < g_config.modem_count; i++) {
printf(" Modem %d: %s (poll: %ds, APIs: %d, delete: %s)\n",
i + 1, g_config.modems[i].modem_port, g_config.modems[i].poll_interval,
g_config.modems[i].api_count, g_config.modems[i].delete_after_forward ? "yes" : "no");
for (int j = 0; j < g_config.modems[i].api_count; j++) {
printf(" API %d: %s\n", j + 1, g_config.modems[i].apis[j].api_type);
}
}
fflush(stdout);
// Check dependencies
printf("Checking dependencies...\n");
fflush(stdout);
check_dependencies();
// Setup signal handlers
printf("Setting up signal handlers...\n");
fflush(stdout);
setup_signals();
syslog(LOG_INFO, "SMS Forwarder started with config: %s, monitoring %d modems", argv[1], g_config.modem_count);
printf("Entering main loop...\n");
fflush(stdout);
// Main loop
while (g_running) {
for (int i = 0; i < g_config.modem_count; i++) {
process_sms_messages(&g_config.modems[i]);
}
// Find the minimum poll interval among all modems
int min_poll_interval = g_config.modems[0].poll_interval;
for (int i = 1; i < g_config.modem_count; i++) {
if (g_config.modems[i].poll_interval < min_poll_interval) {
min_poll_interval = g_config.modems[i].poll_interval;
}
}
fflush(stdout);
sleep(min_poll_interval);
}
syslog(LOG_INFO, "SMS Forwarder stopped");
closelog();
return 0;
}
|
Subsets and Splits
PyTorch Neural Network Imports
This query filters for code examples containing a specific PyTorch import pattern, which is useful for finding code snippets that use PyTorch's neural network module but doesn't provide deeper analytical insights about the dataset.
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.