├── Dockerfile.cross-build-x64-arm64
├── Dockerfile.cross-build-x64-arm64-musl
├── DbusTest
├── SMSModel
│ ├── SmsCodeModel.cs
│ └── SmsContentModel.cs
├── appsettings.json
├── DbusSmsForward.csproj
├── SourceGenerationContext.cs
├── Helper
│ ├── HttpHelper.cs
│ └── ConfigHelper.cs
├── appsettingsModel.cs
├── SendMethod
│ ├── SendByPushPlus.cs
│ ├── SendByBark.cs
│ ├── SendByDingTalkBot.cs
│ ├── SendByShell.cs
│ ├── SendByEmail.cs
│ ├── SendByTelegramBot.cs
│ └── SendByWeComApplication.cs
├── Program.cs
├── ProcessSmsContent
│ └── GetSmsContentCode.cs
├── ProcessUserChoise
│ └── ProcessChoise.cs
└── ModemManagerHelper.cs
├── DbusSmsForward.sln
├── README.md
├── .gitattributes
└── .gitignore
/Dockerfile.cross-build-x64-arm64:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-2.0-cross-arm64
2 | COPY --from=mcr.microsoft.com/dotnet/sdk:10.0.101-azurelinux3.0-amd64 /usr/share/dotnet /usr/share/dotnet
3 | RUN if [ -e /usr/bin/dotnet ]; then rm /usr/bin/dotnet; fi
4 | RUN ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
5 | ENV DOTNET_NOLOGO=true
6 |
--------------------------------------------------------------------------------
/Dockerfile.cross-build-x64-arm64-musl:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/dotnet-buildtools/prereqs:azurelinux-3.0-net10.0-cross-arm64-musl
2 | COPY --from=mcr.microsoft.com/dotnet/sdk:10.0.101-azurelinux3.0-amd64 /usr/share/dotnet /usr/share/dotnet
3 | RUN if [ -e /usr/bin/dotnet ]; then rm /usr/bin/dotnet; fi
4 | RUN ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
5 | ENV DOTNET_NOLOGO=true
6 |
--------------------------------------------------------------------------------
/DbusTest/SMSModel/SmsCodeModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DbusSmsForward.SMSModel
8 | {
9 | public class SmsCodeModel
10 | {
11 | public bool HasCode { get; set; }
12 | public string CodeFrom { get; set; }
13 | public string CodeValue { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/DbusTest/SMSModel/SmsContentModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DbusSmsForward.SMSModel
8 | {
9 | public class SmsContentModel
10 | {
11 | public string TelNumber { get; set; }
12 | public string SmsContent { get; set; }
13 | public string SmsDate { get; set; }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/DbusTest/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "appSettings": {
3 | "EmailConfig": {
4 | "smtpHost": "",
5 | "smtpPort": "",
6 | "enableSSL": "",
7 | "emailKey": "",
8 | "sendEmail": "",
9 | "reciveEmail": ""
10 | },
11 | "PushPlusConfig": {
12 | "pushPlusToken": ""
13 | },
14 | "DingTalkConfig": {
15 | "DingTalkAccessToken": "",
16 | "DingTalkSecret": ""
17 | },
18 | "BarkConfig": {
19 | "BarkUrl": "",
20 | "BarkKey": ""
21 | },
22 | "WeComApplicationConfig": {
23 | "WeChatQYID": "",
24 | "WeChatQYApplicationID": "",
25 | "WeChatQYApplicationSecret": ""
26 | },
27 | "TGBotConfig": {
28 | "IsEnableCustomTGBotApi": "",
29 | "CustomTGBotApi": "",
30 | "TGBotToken": "",
31 | "TGBotChatID": ""
32 | },
33 | "ShellConfig": {
34 | "ShellPath": ""
35 | },
36 | "SmsCodeKey": "验证码±verification±code±인증±代码±随机码",
37 | "ForwardIgnoreStorageType": "sm",
38 | "DeviceName": ""
39 | }
40 | }
--------------------------------------------------------------------------------
/DbusSmsForward.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.5.33530.505
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbusSmsForward", "DbusTest\DbusSmsForward.csproj", "{FDF431F9-11F0-4EEC-AE1A-72A875087986}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {FDF431F9-11F0-4EEC-AE1A-72A875087986}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {FDF431F9-11F0-4EEC-AE1A-72A875087986}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {FDF431F9-11F0-4EEC-AE1A-72A875087986}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {FDF431F9-11F0-4EEC-AE1A-72A875087986}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {98BDE03E-0B50-4652-8111-3B1076B339A2}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/DbusTest/DbusSmsForward.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | linux-musl-arm64
6 | net10.0
7 | enable
8 | disable
9 | true
10 | true
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 | Always
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/DbusTest/SourceGenerationContext.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.SettingModel;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Text.Encodings.Web;
7 | using System.Text.Json;
8 | using System.Text.Json.Nodes;
9 | using System.Text.Json.Serialization;
10 | using System.Threading.Tasks;
11 |
12 | namespace DbusSmsForward
13 | {
14 | [JsonSourceGenerationOptions(WriteIndented = true)]
15 | [JsonSerializable(typeof(JsonObject))]
16 | [JsonSerializable(typeof(appsettingsModel))]
17 | internal partial class SourceGenerationContext : JsonSerializerContext
18 | {
19 | static SourceGenerationContext() => Default = new SourceGenerationContext(CreateJsonSerializerOptions(Default));
20 | private static JsonSerializerOptions CreateJsonSerializerOptions(SourceGenerationContext context)
21 | {
22 | JsonSerializerOptions options = new(context.GeneratedSerializerOptions!)
23 | {
24 | PropertyNamingPolicy = null,
25 | WriteIndented = true,
26 | PropertyNameCaseInsensitive = true,
27 | Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
28 | };
29 | return options;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/DbusTest/Helper/HttpHelper.cs:
--------------------------------------------------------------------------------
1 | using System.Net;
2 | using System.Text;
3 | using System.Text.Json.Nodes;
4 |
5 | namespace DbusSmsForward.Helper
6 | {
7 | public class HttpHelper
8 | {
9 | public static string HttpGet(string Url)
10 | {
11 | HttpClientHandler handler = new HttpClientHandler();
12 | handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
13 | using (HttpClient client = new HttpClient(handler))
14 | {
15 | HttpResponseMessage response = client.GetAsync(Url).Result;
16 | response.EnsureSuccessStatusCode();
17 | string responseBody = response.Content.ReadAsStringAsync().Result;
18 | return responseBody;
19 | }
20 | }
21 |
22 | public static string Post(string url, JsonObject obj)
23 | {
24 | HttpClientHandler handler = new HttpClientHandler();
25 | handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
26 |
27 | using (HttpClient client = new HttpClient(handler))
28 | {
29 | var content = new StringContent(obj.ToString(), Encoding.UTF8, "application/json");
30 | HttpResponseMessage response = client.PostAsync(url, content).Result;
31 | response.EnsureSuccessStatusCode();
32 | string responseBody = response.Content.ReadAsStringAsync().Result;
33 | return responseBody;
34 | }
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DbusSmsForward
2 | 用于部分随身wifi刷了Debian后的短信的Email、PushPlus、企业微信自建应用、TG机器人、钉钉机器人消息转发、Bark推送转发以及短信发送,通过监听dbus实时获取新接收的短信并转发以及调用dbus发送短信
3 |
4 | # 使用教程
5 |
6 | 1.输入
7 | sudo apt install libicu67
8 | 安装libicu
9 |
10 | 2.解压程序至你需要的文件夹下
11 |
12 | 3.输入
13 | sudo chmod -R 777 DbusSmsForward
14 | 配置程序可执行权限
15 |
16 | 4.输入
17 | sudo ./DbusSmsForward
18 | 运行程序
19 |
20 | 5.根据提示配置相关邮箱信息
21 |
22 | 6.带参数运行跳过程序初始的运行模式选择以达到快速运行程序
23 |
24 | 输入
25 | sudo ./DbusSmsForward -fE
26 | 跳过运行模式选择直接进入邮箱转发模式
27 |
28 | 输入
29 | sudo ./DbusSmsForward -fP
30 | 跳过运行模式选择直接进入PushPlus转发模式
31 |
32 | 输入
33 | sudo ./DbusSmsForward -fW
34 | 跳过运行模式选择直接进入企业微信转发模式
35 |
36 | 输入
37 | sudo ./DbusSmsForward -fT
38 | 跳过运行模式选择直接进入TGBot转发模式
39 |
40 | 输入
41 | sudo ./DbusSmsForward -fD
42 | 跳过运行模式选择直接进入钉钉转发模式
43 |
44 | 输入
45 | sudo ./DbusSmsForward -fB
46 | 跳过运行模式选择直接进入Bark转发模式
47 |
48 | 输入
49 | sudo ./DbusSmsForward -fS
50 | 跳过运行模式选择直接进入Shell转发模式
51 |
52 | 输入
53 | sudo ./DbusSmsForward -fE -fP -fD
54 | 可同时将接收的短信转发到email、pushplus和钉钉机器人,转发哪几个渠道取决于你添加的-f\*指令
55 |
56 | 输入
57 | sudo ./DbusSmsForward -sS
58 | 跳过运行模式选择直接进入短信发送界面
59 |
60 | # 编译linux-arm64的native aot版本
61 |
62 | 拉取最新源码,进入程序根目录,使用docker进行交叉编译
63 |
64 | docker build --pull -t cross-build-arm64 -f Dockerfile.cross-build-x64-arm64 .
65 |
66 | docker run --rm -it -v $(pwd):/source -w /source cross-build-arm64 dotnet publish -a arm64 -o app-arm64 -p:SysRoot=/crossrootfs/arm64 -p:LinkerFlavor=lld
67 |
68 | # 编译linux-musl-arm64的native aot版本
69 |
70 | 拉取最新源码,进入程序根目录,使用docker进行交叉编译
71 |
72 | docker build --pull -t cross-build-arm64-musl -f Dockerfile.cross-build-x64-arm64-musl .
73 |
74 | docker run --rm -it -v $(pwd):/source -w /source cross-build-arm64-musl dotnet publish -a musl-arm64 -o app-arm64-musl -p:SysRoot=/crossrootfs/arm64 -p:LinkerFlavor=lld
75 |
76 | # 参考
77 |
78 | 1. [ModemManager API document](https://www.freedesktop.org/software/ModemManager/api/latest/)
79 | 2. [Tmds.DBus](https://github.com/tmds/Tmds.DBus)
80 |
--------------------------------------------------------------------------------
/DbusTest/appsettingsModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DbusSmsForward.SettingModel
8 | {
9 | public class appsettingsModel
10 | {
11 | public Appsettings appSettings { get; set; }
12 | }
13 |
14 | public class Appsettings
15 | {
16 | public Emailconfig EmailConfig { get; set; }
17 | public Pushplusconfig PushPlusConfig { get; set; }
18 | public Dingtalkconfig DingTalkConfig { get; set; }
19 | public Barkconfig BarkConfig { get; set; }
20 | public Wecomapplicationconfig WeComApplicationConfig { get; set; }
21 | public TGBotConfig TGBotConfig { get; set; }
22 | public ShellConfig ShellConfig { get; set; }
23 | public string SmsCodeKey { get; set; }
24 | public string ForwardIgnoreStorageType { get; set; }
25 | public string DeviceName { get; set; }
26 | }
27 |
28 | public class Emailconfig
29 | {
30 | public string smtpHost { get; set; }
31 | public string smtpPort { get; set; }
32 | public string enableSSL { get; set; }
33 | public string emailKey { get; set; }
34 | public string sendEmail { get; set; }
35 | public string reciveEmail { get; set; }
36 | }
37 |
38 | public class Pushplusconfig
39 | {
40 | public string pushPlusToken { get; set; }
41 | }
42 |
43 | public class Dingtalkconfig
44 | {
45 | public string DingTalkAccessToken { get; set; }
46 | public string DingTalkSecret { get; set; }
47 | }
48 |
49 | public class Barkconfig
50 | {
51 | public string BarkUrl { get; set; }
52 | public string BarkKey { get; set; }
53 | }
54 |
55 | public class Wecomapplicationconfig
56 | {
57 | public string WeChatQYID { get; set; }
58 | public string WeChatQYApplicationID { get; set; }
59 | public string WeChatQYApplicationSecret { get; set; }
60 | }
61 |
62 | public class TGBotConfig
63 | {
64 | public string IsEnableCustomTGBotApi { get; set; }
65 | public string CustomTGBotApi { get; set; }
66 | public string TGBotToken { get; set; }
67 | public string TGBotChatID { get; set; }
68 | }
69 |
70 | public class ShellConfig
71 | {
72 | public string ShellPath { get; set; }
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByPushPlus.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.SettingModel;
4 | using DbusSmsForward.SMSModel;
5 | using System.Text.Json;
6 | using System.Text.Json.Nodes;
7 |
8 | namespace DbusSmsForward.SendMethod
9 | {
10 | public static class SendByPushPlus
11 | {
12 | public static void SetupPushPlusInfo()
13 | {
14 | appsettingsModel result = new appsettingsModel();
15 | ConfigHelper.GetSettings(ref result);
16 | string pushPlusToken = result.appSettings.PushPlusConfig.pushPlusToken;
17 | if (string.IsNullOrEmpty(pushPlusToken))
18 | {
19 | Console.WriteLine("首次运行请输入PushPlusToken:");
20 | pushPlusToken = Console.ReadLine().Trim();
21 | result.appSettings.PushPlusConfig.pushPlusToken = pushPlusToken;
22 | ConfigHelper.UpdateSettings(ref result);
23 | }
24 | result = null;
25 |
26 | }
27 |
28 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
29 | {
30 | appsettingsModel result = new appsettingsModel();
31 | ConfigHelper.GetSettings(ref result);
32 | string pushPlusToken = result.appSettings.PushPlusConfig.pushPlusToken;
33 | result = null;
34 | string pushPlusUrl = "http://www.pushplus.plus/send/";
35 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
36 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
37 |
38 | JsonObject obj = new JsonObject();
39 | obj.Add("token", pushPlusToken);
40 | obj.Add("title", (string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + " ") + "短信转发" + smsmodel.TelNumber);
41 | obj.Add("content", body);
42 | obj.Add("topic","");
43 | string msgresult = HttpHelper.Post(pushPlusUrl, obj);
44 | //JObject jsonObjresult = JObject.Parse(msgresult);
45 | JsonObject jsonObjresult = JsonSerializer.Deserialize(msgresult, SourceGenerationContext.Default.JsonObject);
46 | string code = jsonObjresult["code"].ToString();
47 | string errmsg = jsonObjresult["msg"].ToString();
48 | if (code == "200")
49 | {
50 | Console.WriteLine("pushplus转发成功");
51 | }
52 | else
53 | {
54 | Console.WriteLine(errmsg);
55 | }
56 |
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/DbusTest/Helper/ConfigHelper.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.SettingModel;
2 | using System;
3 | using System.Net;
4 | using System.Text.Json;
5 |
6 | namespace DbusSmsForward.Helper
7 | {
8 | public static class ConfigHelper
9 | {
10 |
11 | public static void GetSettings(ref appsettingsModel result)
12 | {
13 | string settinsgFileName = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
14 | if (File.Exists(settinsgFileName))
15 | {
16 | var config = File.ReadAllText(settinsgFileName);
17 | result = JsonSerializer.Deserialize(config, SourceGenerationContext.Default.appsettingsModel);
18 | }
19 | }
20 |
21 | public static void UpdateSettings(ref appsettingsModel result)
22 | {
23 | var updatedJson = JsonSerializer.Serialize(result, SourceGenerationContext.Default.appsettingsModel);
24 | string settinsgFileName = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
25 | File.WriteAllText(settinsgFileName, updatedJson);
26 | }
27 |
28 | public static bool JudgeIsForwardIgnore(uint storage)
29 | {
30 | appsettingsModel result = new appsettingsModel();
31 | GetSettings(ref result);
32 | string forwardStorageType = result.appSettings.ForwardIgnoreStorageType;
33 | result = null;
34 | uint storageTypeNum = 100;
35 | if (forwardStorageType == "unknown" && storage == 0)
36 | {
37 | return true;
38 | }
39 | else if (forwardStorageType == "sm" && storage == 1)
40 | {
41 | return true;
42 | }
43 | else if (forwardStorageType == "me" && storage == 2)
44 | {
45 | return true;
46 | }
47 | else if (forwardStorageType == "mt" && storage == 3)
48 | {
49 | return true;
50 | }
51 | else if (forwardStorageType == "sr" && storage == 4)
52 | {
53 | return true;
54 | }
55 | else if (forwardStorageType == "bm" && storage == 5)
56 | {
57 | return true;
58 | }
59 | else if (forwardStorageType == "ta" && storage == 6)
60 | {
61 | storageTypeNum = 6;
62 | }
63 | return false;
64 | }
65 |
66 | public static string GetDeviceHostName()
67 | {
68 | try
69 | {
70 | return Dns.GetHostName();
71 | }
72 | catch
73 | {
74 | try
75 | {
76 | return Environment.MachineName;
77 | }
78 | catch
79 | {
80 | return string.Empty;
81 | }
82 | }
83 | }
84 | }
85 |
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByBark.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.SettingModel;
4 | using DbusSmsForward.SMSModel;
5 | using System.Text.Json;
6 |
7 | namespace DbusSmsForward.SendMethod
8 | {
9 | public static class SendByBark
10 | {
11 | public static void SetupBarkInfo()
12 | {
13 | appsettingsModel result = new appsettingsModel();
14 | ConfigHelper.GetSettings(ref result);
15 | string BarkUrl = result.appSettings.BarkConfig.BarkUrl;
16 | string BrakKey = result.appSettings.BarkConfig.BarkKey;
17 |
18 | if (string.IsNullOrEmpty(BarkUrl) && string.IsNullOrEmpty(BrakKey))
19 | {
20 | Console.WriteLine("首次运行请输入Bark服务器地址:");
21 | BarkUrl = Console.ReadLine().Trim();
22 | result.appSettings.BarkConfig.BarkUrl = BarkUrl;
23 | Console.WriteLine("首次运行请输入Bark推送key");
24 | BrakKey = Console.ReadLine().Trim();
25 | result.appSettings.BarkConfig.BarkKey = BrakKey;
26 | ConfigHelper.UpdateSettings(ref result);
27 | }
28 | result = null;
29 | }
30 |
31 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
32 | {
33 | try
34 | {
35 | appsettingsModel result = new appsettingsModel();
36 | ConfigHelper.GetSettings(ref result);
37 | string BarkUrl = result.appSettings.BarkConfig.BarkUrl;
38 | string BrakKey = result.appSettings.BarkConfig.BarkKey;
39 | result = null;
40 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
41 |
42 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
43 |
44 | string url = BarkUrl + "/" + BrakKey + "/";
45 | url += System.Web.HttpUtility.UrlEncode(body);
46 | url += "?group=" + smsmodel.TelNumber + "&title="+ (string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + " ") + "短信转发" + smsmodel.TelNumber+(string.IsNullOrEmpty(codeResult.CodeValue) ?"":"&autoCopy=1©="+ codeResult.CodeValue);
47 | string msgresult = HttpHelper.HttpGet(url);
48 | //JsonObject jsonObjresult = JObject.Parse(msgresult);
49 | var jsonObjresult = JsonSerializer.Deserialize(msgresult, SourceGenerationContext.Default.JsonObject);
50 | string status = jsonObjresult["code"].ToString();
51 | if (status == "200")
52 | {
53 | Console.WriteLine("Bark转发成功");
54 | }
55 | else
56 | {
57 | Console.WriteLine(jsonObjresult["code"].ToString());
58 | Console.WriteLine(jsonObjresult["message"].ToString());
59 | }
60 | }
61 | catch(Exception ex)
62 | {
63 | Console.WriteLine(ex);
64 | }
65 |
66 | }
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/DbusTest/Program.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ModemHelper;
3 | using DbusSmsForward.ProcessUserChoise;
4 | using DbusSmsForward.SettingModel;
5 | using DbusSmsForward.SMSModel;
6 |
7 |
8 | ModemManagerHelper mmhelper=new ModemManagerHelper();
9 | string startGuideChoiseNum = "";
10 | List sendMethodGuideChoiseNumArray= new List();
11 | foreach (var s1 in args)
12 | {
13 | if (s1 == "-fE")
14 | {
15 | startGuideChoiseNum = "1";
16 | sendMethodGuideChoiseNumArray.Add("1");
17 | }
18 | else if (s1 == "-fP")
19 | {
20 | startGuideChoiseNum = "1";
21 | sendMethodGuideChoiseNumArray.Add("2");
22 | }
23 | else if (s1 == "-fW")
24 | {
25 | startGuideChoiseNum = "1";
26 | sendMethodGuideChoiseNumArray.Add("3");
27 | }
28 | else if (s1 == "-fT")
29 | {
30 | startGuideChoiseNum = "1";
31 | sendMethodGuideChoiseNumArray.Add("4");
32 | }
33 | else if (s1 == "-fD")
34 | {
35 | startGuideChoiseNum = "1";
36 | sendMethodGuideChoiseNumArray.Add("5");
37 | }
38 | else if (s1 == "-fB")
39 | {
40 | startGuideChoiseNum = "1";
41 | sendMethodGuideChoiseNumArray.Add("6");
42 | }
43 | else if (s1 == "-fS")
44 | {
45 | startGuideChoiseNum = "1";
46 | sendMethodGuideChoiseNumArray.Add("7");
47 | }
48 | else if (s1 == "-sS")
49 | {
50 | startGuideChoiseNum = "2";
51 | }
52 | }
53 | string StartGuideResult = ProcessChoise.onStartGuide(startGuideChoiseNum);
54 | if (StartGuideResult == "1")
55 | {
56 | appsettingsModel result = new appsettingsModel();
57 | ConfigHelper.GetSettings(ref result);
58 | string DeviceName = result.appSettings.DeviceName;
59 |
60 | if (string.IsNullOrEmpty(DeviceName))
61 | {
62 | Console.WriteLine("初次运行是否需要设置转发设备名称?(留空回车则默认动态读取设备主机名):");
63 | DeviceName = Console.ReadLine().Trim();
64 | if (string.IsNullOrEmpty(DeviceName))
65 | {
66 | result.appSettings.DeviceName = "*Host*Name*";
67 | }
68 | else
69 | {
70 | result.appSettings.DeviceName = DeviceName;
71 | }
72 | }
73 | ConfigHelper.UpdateSettings(ref result);
74 | result = null;
75 |
76 | List> actionList= ProcessChoise.sendMethodGuide(sendMethodGuideChoiseNumArray);
77 | mmhelper.SetSendMethodList(actionList);
78 | Console.WriteLine("正在运行. 按下 Ctrl-C 停止.");
79 | var tcs = new TaskCompletionSource();
80 | var task = tcs.Task;
81 | await task;
82 |
83 | }
84 | else if(StartGuideResult == "2")
85 | {
86 | string telNumber = string.Empty, smsText=string.Empty;
87 | sendSms(ref telNumber,ref smsText);
88 | Console.WriteLine("短信创建成功,是否发送?(1.发送短信,其他按键退出程序)");
89 | string sendChoise = Console.ReadLine();
90 | if (sendChoise == "1")
91 | {
92 | if (mmhelper.SendSms(telNumber, smsText).Result)
93 | {
94 | Console.WriteLine("短信已发送");
95 | }
96 | else
97 | {
98 | Console.WriteLine("短信发送失败");
99 | }
100 | }
101 | }
102 |
103 |
104 |
105 | void sendSms(ref string telNumber,ref string smsText)
106 | {
107 | Console.WriteLine("请输入收信号码:");
108 | telNumber = Console.ReadLine();
109 | Console.WriteLine("请输入短信内容");
110 | smsText = Console.ReadLine();
111 |
112 | }
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByDingTalkBot.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using System.Security.Cryptography;
3 | using System.Text;
4 | using System.Web;
5 | using DbusSmsForward.SMSModel;
6 | using DbusSmsForward.ProcessSmsContent;
7 | using System.Text.Json;
8 | using System.Text.Json.Nodes;
9 | using DbusSmsForward.SettingModel;
10 |
11 | namespace DbusSmsForward.SendMethod
12 | {
13 | public class SendByDingTalkBot
14 | {
15 | private const string DING_TALK_BOT_URL = "https://oapi.dingtalk.com/robot/send?access_token=";
16 |
17 | public static void SetupDingtalkBotMsg()
18 | {
19 | appsettingsModel result = new appsettingsModel();
20 | ConfigHelper.GetSettings(ref result);
21 | string DingTalkAccessToken = result.appSettings.DingTalkConfig.DingTalkAccessToken;
22 | string DingTalkSecret = result.appSettings.DingTalkConfig.DingTalkSecret;
23 |
24 | if (string.IsNullOrEmpty(DingTalkAccessToken) && string.IsNullOrEmpty(DingTalkSecret))
25 | {
26 | Console.WriteLine("首次运行请输入钉钉机器人AccessToken:");
27 | DingTalkAccessToken = Console.ReadLine().Trim();
28 | result.appSettings.DingTalkConfig.DingTalkAccessToken = DingTalkAccessToken;
29 | Console.WriteLine("请输入钉钉机器人加签secret:");
30 | DingTalkSecret = Console.ReadLine().Trim();
31 | result.appSettings.DingTalkConfig.DingTalkSecret = DingTalkSecret;
32 | ConfigHelper.UpdateSettings(ref result);
33 | }
34 | result = null;
35 | }
36 |
37 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
38 | {
39 | appsettingsModel result = new appsettingsModel();
40 | ConfigHelper.GetSettings(ref result);
41 | string dingTalkAccessToken = result.appSettings.DingTalkConfig.DingTalkAccessToken;
42 | string dingTalkSecret = result.appSettings.DingTalkConfig.DingTalkSecret;
43 | result = null;
44 | string url = DING_TALK_BOT_URL + dingTalkAccessToken;
45 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
46 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
47 |
48 | long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
49 | string sign = addSign(timestamp, dingTalkSecret);
50 | url += $"×tamp={timestamp}&sign={sign}";
51 |
52 | JsonObject msgContent = new()
53 | {
54 | { "content", (string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + "\n") + "短信转发\n" + body }
55 | };
56 |
57 | JsonObject msgObj = new()
58 | {
59 | { "msgtype", "text" },
60 | { "text", msgContent }
61 | };
62 |
63 | string resultResp = HttpHelper.Post(url, msgObj);
64 | //JObject jsonObjresult = JObject.Parse(resultResp);
65 | JsonObject jsonObjresult = JsonSerializer.Deserialize(resultResp, SourceGenerationContext.Default.JsonObject);
66 | string errcode1 = jsonObjresult["errcode"].ToString();
67 | string errmsg1 = jsonObjresult["errmsg"].ToString();
68 | if (errcode1 == "0" && errmsg1 == "ok")
69 | {
70 | Console.WriteLine("钉钉转发成功");
71 | }
72 | else
73 | {
74 | Console.WriteLine(errmsg1);
75 | }
76 | }
77 |
78 | public static string addSign(long timestamp ,string secret)
79 | {
80 | string secret1 = secret;
81 | string stringToSign = timestamp + "\n" + secret1;
82 | var encoding = new ASCIIEncoding();
83 | byte[] keyByte = encoding.GetBytes(secret1);
84 | byte[] messageBytes = encoding.GetBytes(stringToSign);
85 | using (var hmacsha256 = new HMACSHA256(keyByte))
86 | {
87 | byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
88 | return HttpUtility.UrlEncode(Convert.ToBase64String(hashmessage), Encoding.UTF8);
89 | }
90 | }
91 |
92 | public static string Base64Encrypt(string input, Encoding encode)
93 | {
94 | return Convert.ToBase64String(encode.GetBytes(input));
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByShell.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.SettingModel;
4 | using DbusSmsForward.SMSModel;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Diagnostics;
8 | using System.Text;
9 | using System.Text.Json;
10 | using System.Text.Json.Nodes;
11 | using System.Xml;
12 |
13 | namespace DbusSmsForward.SendMethod
14 | {
15 | public static class SendByShell
16 | {
17 | public static void SetupCustomShellInfo()
18 | {
19 | appsettingsModel result = new appsettingsModel();
20 | ConfigHelper.GetSettings(ref result);
21 | string shellPath = result.appSettings.ShellConfig.ShellPath;
22 | if (string.IsNullOrEmpty(shellPath))
23 | {
24 | Console.WriteLine("首次运行请输入自定义shell脚本路径:");
25 | shellPath = Console.ReadLine().Trim();
26 | result.appSettings.ShellConfig.ShellPath = shellPath;
27 | ConfigHelper.UpdateSettings(ref result);
28 | }
29 | result = null;
30 | }
31 |
32 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
33 | {
34 | appsettingsModel result = new appsettingsModel();
35 | ConfigHelper.GetSettings(ref result);
36 | string shellPath = result.appSettings.ShellConfig.ShellPath;
37 | result = null;
38 |
39 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
40 | string[] arguments =
41 | {
42 | smsmodel.TelNumber,
43 | smsmodel.SmsDate,
44 | smsmodel.SmsContent,
45 | codeResult.CodeValue,
46 | codeResult.CodeFrom,
47 | devicename
48 | };
49 |
50 | ProcessStartInfo startInfo = new ProcessStartInfo
51 | {
52 | FileName = shellPath,
53 | UseShellExecute = false, // 不直接使用操作系统shell启动
54 | CreateNoWindow = true, // 不创建新窗口
55 | RedirectStandardOutput = true, // 可以重定向输出
56 | RedirectStandardError = true // 可以重定向错误
57 | };
58 | foreach (var arg in arguments)
59 | {
60 | startInfo.ArgumentList.Add(arg);
61 | }
62 |
63 | // 启动进程
64 | using (Process process = new Process())
65 | {
66 | process.StartInfo = startInfo;
67 |
68 | // 可以捕获输出(如果需要)
69 | process.OutputDataReceived += (sender, e) =>
70 | {
71 | if (!string.IsNullOrEmpty(e.Data))
72 | Console.WriteLine($"输出: {e.Data}");
73 | };
74 |
75 | process.ErrorDataReceived += (sender, e) =>
76 | {
77 | if (!string.IsNullOrEmpty(e.Data))
78 | Console.WriteLine($"错误: {e.Data}");
79 | };
80 |
81 | bool started = process.Start();
82 |
83 | if (started)
84 | {
85 | // 开始异步读取输出
86 | process.BeginOutputReadLine();
87 | process.BeginErrorReadLine();
88 |
89 | // 等待进程完成(可以设置超时时间)
90 | bool exited = process.WaitForExit(30000); // 30秒超时
91 |
92 | if (exited)
93 | {
94 | int exitCode = process.ExitCode;
95 |
96 | if (exitCode == 0)
97 | {
98 | Console.WriteLine("\nShell调用成功");
99 | }
100 | else
101 | {
102 | Console.WriteLine($"\nShell调用失败,退出代码: {exitCode}");
103 | }
104 | }
105 | else
106 | {
107 | Console.WriteLine("\nShell调用超时");
108 | process.Kill(); // 强制终止进程
109 | }
110 | }
111 | else
112 | {
113 | Console.WriteLine("\n无法启动Shell进程");
114 | }
115 | }
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByEmail.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.SMSModel;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.Helper;
4 | using DbusSmsForward.SettingModel;
5 | using MimeKit;
6 | using MailKit.Net.Smtp;
7 |
8 | namespace DbusSmsForward.SendMethod
9 | {
10 | public static class SendByEmail
11 | {
12 | public static void SetupEmailInfo()
13 | {
14 | appsettingsModel result = new appsettingsModel();
15 | ConfigHelper.GetSettings(ref result);
16 | string smtpHost = result.appSettings.EmailConfig.smtpHost;
17 | string smtpPort = result.appSettings.EmailConfig.smtpPort;
18 | string emailKey = result.appSettings.EmailConfig.emailKey;
19 | string sendEmail = result.appSettings.EmailConfig.sendEmail;
20 | string reciveEmail = result.appSettings.EmailConfig.reciveEmail;
21 | if (string.IsNullOrEmpty(smtpHost) && string.IsNullOrEmpty(smtpPort) && string.IsNullOrEmpty(emailKey) && string.IsNullOrEmpty(sendEmail) && string.IsNullOrEmpty(reciveEmail))
22 | {
23 | Console.WriteLine("首次运行请输入邮箱转发相关配置信息\n请输入smtp地址:");
24 | smtpHost = Console.ReadLine().Trim();
25 | result.appSettings.EmailConfig.smtpHost = smtpHost;
26 |
27 | Console.WriteLine("请输入smtp端口:");
28 | smtpPort = Console.ReadLine().Trim();
29 | result.appSettings.EmailConfig.smtpPort = smtpPort;
30 | string sslEnableInput = string.Empty;
31 | do
32 | {
33 | Console.WriteLine("是否需要启用ssl(1.启用 2.不启用)");
34 | sslEnableInput = Console.ReadLine().Trim();
35 | } while (!(sslEnableInput == "1" || sslEnableInput == "2"));
36 | if (sslEnableInput == "1")
37 | {
38 | result.appSettings.EmailConfig.enableSSL = "true";
39 | }
40 | else
41 | {
42 | result.appSettings.EmailConfig.enableSSL = "false";
43 | }
44 | Console.WriteLine("请输入邮箱密钥:");
45 | emailKey = Console.ReadLine().Trim();
46 | result.appSettings.EmailConfig.emailKey = emailKey;
47 |
48 | Console.WriteLine("请输入发件邮箱:");
49 | sendEmail = Console.ReadLine().Trim();
50 | result.appSettings.EmailConfig.sendEmail = sendEmail;
51 |
52 | Console.WriteLine("请输入收件邮箱:");
53 | reciveEmail = Console.ReadLine().Trim();
54 | result.appSettings.EmailConfig.reciveEmail = reciveEmail;
55 |
56 | ConfigHelper.UpdateSettings(ref result);
57 | }
58 | result = null;
59 | }
60 |
61 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
62 | {
63 | appsettingsModel result = new appsettingsModel();
64 | ConfigHelper.GetSettings(ref result);
65 | string smtpHost = result.appSettings.EmailConfig.smtpHost;
66 | string smtpPort = result.appSettings.EmailConfig.smtpPort;
67 | bool enableSSL = Convert.ToBoolean(result.appSettings.EmailConfig.enableSSL);
68 | string emailKey = result.appSettings.EmailConfig.emailKey;
69 | string sendEmail = result.appSettings.EmailConfig.sendEmail;
70 | string reciveEmail = result.appSettings.EmailConfig.reciveEmail;
71 | result = null;
72 | var message = new MimeMessage();
73 | message.From.Add(new MailboxAddress("SMSForwad", sendEmail));
74 | message.To.Add(new MailboxAddress("", reciveEmail));
75 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
76 | SmsCodeModel codeResult= GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
77 |
78 | message.Subject = (string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + " ") + "短信转发" + smsmodel.TelNumber;
79 | message.Body = new TextPart("plain")
80 | {
81 | Text = body
82 | };
83 | using (var client = new SmtpClient())
84 | {
85 | client.Connect(smtpHost, Convert.ToInt32(smtpPort), enableSSL);
86 | client.Authenticate(sendEmail, emailKey);
87 | client.Send(message);
88 | client.Disconnect(true);
89 | }
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByTelegramBot.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.SettingModel;
4 | using DbusSmsForward.SMSModel;
5 | using System.Text.Json;
6 | using System.Text.Json.Nodes;
7 |
8 | namespace DbusSmsForward.SendMethod
9 | {
10 | public static class SendByTelegramBot
11 | {
12 | public static void SetupTGBotInfo()
13 | {
14 | appsettingsModel result = new appsettingsModel();
15 | ConfigHelper.GetSettings(ref result);
16 | string TGBotToken = result.appSettings.TGBotConfig.TGBotToken;
17 | string TGBotChatID = result.appSettings.TGBotConfig.TGBotChatID;
18 | string IsEnableCustomTGBotApi = result.appSettings.TGBotConfig.IsEnableCustomTGBotApi;
19 | string CustomTGBotApi = result.appSettings.TGBotConfig.CustomTGBotApi;
20 |
21 | if (string.IsNullOrEmpty(TGBotToken) || string.IsNullOrEmpty(TGBotChatID) || string.IsNullOrEmpty(IsEnableCustomTGBotApi))
22 | {
23 | Console.WriteLine("首次运行请输入TG机器人Token:");
24 | TGBotToken = Console.ReadLine().Trim();
25 | result.appSettings.TGBotConfig.TGBotToken = TGBotToken;
26 | Console.WriteLine("请输入机器人要转发到的ChatId");
27 | TGBotChatID = Console.ReadLine().Trim();
28 | result.appSettings.TGBotConfig.TGBotChatID = TGBotChatID;
29 |
30 | string customApiEnableInput=string.Empty;
31 | do
32 | {
33 | Console.WriteLine("是否需要使用自定义api(1.使用 2.不使用)");
34 | customApiEnableInput= Console.ReadLine().Trim();
35 | } while (!(customApiEnableInput=="1"|| customApiEnableInput == "2"));
36 | if(customApiEnableInput=="1")
37 | {
38 | IsEnableCustomTGBotApi = "true";
39 | result.appSettings.TGBotConfig.IsEnableCustomTGBotApi = IsEnableCustomTGBotApi;
40 | Console.WriteLine("请输入机器人自定义api(格式https://xxx.abc.com)");
41 | CustomTGBotApi= Console.ReadLine().Trim();
42 | result.appSettings.TGBotConfig.CustomTGBotApi = CustomTGBotApi;
43 | }
44 | else
45 | {
46 | IsEnableCustomTGBotApi = "false";
47 | result.appSettings.TGBotConfig.IsEnableCustomTGBotApi = IsEnableCustomTGBotApi;
48 | }
49 | ConfigHelper.UpdateSettings(ref result);
50 | }
51 | result = null;
52 |
53 | }
54 |
55 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
56 | {
57 | appsettingsModel result = new appsettingsModel();
58 | ConfigHelper.GetSettings(ref result);
59 | string TGBotToken = result.appSettings.TGBotConfig.TGBotToken;
60 | string TGBotChatID = result.appSettings.TGBotConfig.TGBotChatID;
61 | string IsEnableCustomTGBotApi = result.appSettings.TGBotConfig.IsEnableCustomTGBotApi;
62 | string CustomTGBotApi = result.appSettings.TGBotConfig.CustomTGBotApi;
63 | result = null;
64 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
65 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
66 | string url = "";
67 | if (IsEnableCustomTGBotApi=="true")
68 | {
69 | url = CustomTGBotApi;
70 | }
71 | else
72 | {
73 | url = "https://api.telegram.org";
74 | }
75 | url+= "/bot" + TGBotToken + "/sendMessage?chat_id=" + TGBotChatID + "&text=";
76 | url += System.Web.HttpUtility.UrlEncode((string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + "\n") + "短信转发\n" + body);
77 | string msgresult = HttpHelper.HttpGet(url);
78 | JsonObject jsonObjresult = JsonSerializer.Deserialize(msgresult, SourceGenerationContext.Default.JsonObject);
79 | string status = jsonObjresult["ok"].ToString();
80 | if (status.ToLower() == "true")
81 | {
82 | Console.WriteLine("TGBot转发成功");
83 | }
84 | else
85 | {
86 | Console.WriteLine(jsonObjresult["error_code"].ToString());
87 | Console.WriteLine(jsonObjresult["description"].ToString());
88 | }
89 |
90 | }
91 |
92 |
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/DbusTest/SendMethod/SendByWeComApplication.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.ProcessSmsContent;
3 | using DbusSmsForward.SettingModel;
4 | using DbusSmsForward.SMSModel;
5 | using System.Text.Json;
6 | using System.Text.Json.Nodes;
7 |
8 | namespace DbusSmsForward.SendMethod
9 | {
10 | public class SendByWeComApplication
11 | {
12 | public static void SetupWeComInfo()
13 | {
14 | appsettingsModel result = new appsettingsModel();
15 | ConfigHelper.GetSettings(ref result);
16 | string corpid = result.appSettings.WeComApplicationConfig.WeChatQYID;
17 | string appsecret = result.appSettings.WeComApplicationConfig.WeChatQYApplicationSecret;
18 | string appid = result.appSettings.WeComApplicationConfig.WeChatQYApplicationID;
19 |
20 | if (string.IsNullOrEmpty(corpid) && string.IsNullOrEmpty(appsecret) && string.IsNullOrEmpty(appid))
21 | {
22 | Console.WriteLine("首次运行请输入企业ID:");
23 | corpid = Console.ReadLine().Trim();
24 | result.appSettings.WeComApplicationConfig.WeChatQYID = corpid;
25 |
26 | Console.WriteLine("请输入自建应用ID:");
27 | appid = Console.ReadLine().Trim();
28 | result.appSettings.WeComApplicationConfig.WeChatQYApplicationID = appid;
29 |
30 | Console.WriteLine("请输入自建应用密钥:");
31 | appsecret = Console.ReadLine().Trim();
32 | result.appSettings.WeComApplicationConfig.WeChatQYApplicationSecret = appsecret;
33 |
34 | ConfigHelper.UpdateSettings(ref result);
35 | }
36 | result = null;
37 |
38 | }
39 |
40 | public static void SendSms(SmsContentModel smsmodel, string body, string devicename)
41 | {
42 | appsettingsModel configResult = new appsettingsModel();
43 | ConfigHelper.GetSettings(ref configResult);
44 | string corpid = configResult.appSettings.WeComApplicationConfig.WeChatQYID;
45 | string corpsecret = configResult.appSettings.WeComApplicationConfig.WeChatQYApplicationSecret;
46 | string agentid = configResult.appSettings.WeComApplicationConfig.WeChatQYApplicationID;
47 | configResult = null;
48 |
49 | string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
50 | string result = HttpHelper.HttpGet(url);
51 | //JsonObject jsonObj = JsonObject.Parse(result);
52 | JsonObject jsonObj = JsonSerializer.Deserialize(result, SourceGenerationContext.Default.JsonObject);
53 | string errcode = jsonObj["errcode"].ToString();
54 | string errmsg = jsonObj["errmsg"].ToString();
55 | //string SmsCodeStr = GetSmsContentCode.GetSmsCodeStr(smsmodel.SmsContent);
56 | SmsCodeModel codeResult = GetSmsContentCode.GetSmsCodeModel(smsmodel.SmsContent);
57 |
58 | if (errcode == "0" && errmsg == "ok")
59 | {
60 | string access_token = jsonObj["access_token"].ToString();
61 | JsonObject obj = new JsonObject();
62 | JsonObject obj1 = new JsonObject();
63 | obj.Add("touser", "@all");
64 | obj.Add("toparty", "");
65 | obj.Add("totag", "");
66 | obj.Add("msgtype", "text");
67 | obj.Add("agentid", agentid);
68 | obj1.Add("content", (string.IsNullOrEmpty(codeResult.CodeValue) ? "" : codeResult.CodeValue + "\n")+"短信转发\n" + body);
69 | obj.Add("text", obj1);
70 | obj.Add("safe", 0);
71 | obj.Add("enable_id_trans", 0);
72 | obj.Add("enable_duplicate_check", 0);
73 | obj.Add("duplicate_check_interval", 1800);
74 | string msgurl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + access_token;
75 | string msgresult = HttpHelper.Post(msgurl, obj);
76 | //JsonObject jsonObjresult = JsonObject.Parse(msgresult);
77 | //JsonObject jsonObjresult = JsonSerializer.Deserialize(msgresult);
78 | JsonObject jsonObjresult = JsonSerializer.Deserialize(msgresult, SourceGenerationContext.Default.JsonObject);
79 | string errcode1 = jsonObjresult["errcode"].ToString();
80 | string errmsg1 = jsonObjresult["errmsg"].ToString();
81 | if (errcode1 == "0" && errmsg1 == "ok")
82 | {
83 | Console.WriteLine("企业微信转发成功");
84 | }
85 | else
86 | {
87 | Console.WriteLine(errmsg1);
88 | }
89 | }
90 | else
91 | {
92 | Console.WriteLine(errmsg);
93 | }
94 |
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/DbusTest/ProcessSmsContent/GetSmsContentCode.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.SettingModel;
3 | using DbusSmsForward.SMSModel;
4 | using System.Text.RegularExpressions;
5 |
6 | namespace DbusSmsForward.ProcessSmsContent
7 | {
8 | public static class GetSmsContentCode
9 | {
10 | public static string GetSmsCodeStr(string smscontent)
11 | {
12 | SmsCodeModel smsCodeModel = new SmsCodeModel();
13 | smsCodeModel = GetSmsCodeModel(smscontent);
14 | if (smsCodeModel.HasCode)
15 | {
16 | return smsCodeModel.CodeFrom + smsCodeModel.CodeValue;
17 | }
18 | else
19 | {
20 | return "";
21 | }
22 | }
23 | public static SmsCodeModel GetSmsCodeModel(string smscontent)
24 | {
25 | SmsCodeModel smsCodeModel = new SmsCodeModel();
26 | string newsmscontent=string.Empty;
27 |
28 | if (JudgeSmsContentHasCode(smscontent,out newsmscontent))
29 | {
30 | string smscode= GetCode(newsmscontent).Trim();
31 | if (string.IsNullOrEmpty(smscode))
32 | {
33 | smsCodeModel.HasCode = false;
34 | }
35 | else
36 | {
37 | smsCodeModel.HasCode = true;
38 | smsCodeModel.CodeValue = smscode;
39 | smsCodeModel.CodeFrom = GetCodeSmsFrom(smscontent);
40 | }
41 | }
42 | else
43 | {
44 | smsCodeModel.HasCode = false;
45 | }
46 | return smsCodeModel;
47 | }
48 | public static bool JudgeSmsContentHasCode(string smscontent,out string newsmscontent)
49 | {
50 | appsettingsModel result = new appsettingsModel();
51 | ConfigHelper.GetSettings(ref result);
52 | string codeKeyStr = result.appSettings.SmsCodeKey;
53 | result = null;
54 | string[] flagStrList = {};
55 | try
56 | {
57 | flagStrList = codeKeyStr.Split("±");
58 | }
59 | catch (Exception ex)
60 | {
61 | Console.WriteLine("配置文件中自定义验证码关键词格式有误,已使用默认关键词“验证码”");
62 | flagStrList.Append("验证码");
63 | }
64 |
65 | foreach (string flag in flagStrList)
66 | {
67 | if (smscontent.IndexOf(flag) > -1)
68 | {
69 | newsmscontent = smscontent.Replace(flag, " "+flag+" ");
70 | return true;
71 | }
72 | }
73 | newsmscontent=string.Empty;
74 | return false;
75 | }
76 | public static string GetCode(string smscontent)
77 | {
78 | string pattern = @"\b[A-Za-z0-9]{4,7}\b";
79 | MatchCollection SmsCodeMatches = Regex.Matches(smscontent, pattern);
80 | if (SmsCodeMatches.Count()> 1)
81 | {
82 | int maxDigits = 0;
83 | string maxDigitsString = "";
84 | foreach (Match match in SmsCodeMatches)
85 | {
86 | string currentString = match.Value;
87 | int digitCount = CountDigits(currentString);
88 | if (digitCount > maxDigits)
89 | {
90 | maxDigits = digitCount;
91 | maxDigitsString = currentString;
92 | }
93 | }
94 | return maxDigitsString;
95 | }
96 | else if (SmsCodeMatches.Count()==1)
97 | {
98 | return SmsCodeMatches[0].Value;
99 | }
100 | else
101 | {
102 | return "";
103 | }
104 | }
105 | public static string GetCodeSmsFrom(string smscontent)
106 | {
107 | string pattern = @"^\【(.*?)\】";
108 | Match match = Regex.Match(smscontent, pattern);
109 | if (match.Success)
110 | {
111 | return match.Value;
112 | }
113 | else
114 | {
115 | string pattern1 = @"【([^【】]+)】$";
116 | Match match1 = Regex.Match(smscontent, pattern1);
117 | if (match1.Success)
118 | {
119 | return match1.Value;
120 | }
121 | }
122 | return "";
123 | }
124 | public static int CountDigits(string input)
125 | {
126 | int count = 0;
127 | foreach (char c in input)
128 | {
129 | if (char.IsDigit(c))
130 | {
131 | count++;
132 | }
133 | }
134 | return count;
135 | }
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/DbusTest/ProcessUserChoise/ProcessChoise.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.SendMethod;
2 | using DbusSmsForward.SMSModel;
3 | using System.Collections.Generic;
4 |
5 | namespace DbusSmsForward.ProcessUserChoise
6 | {
7 | public static class ProcessChoise
8 | {
9 | public static string onStartGuide(string chooseOption)
10 | {
11 | if (string.IsNullOrEmpty(chooseOption))
12 | {
13 | Console.WriteLine("请选择运行模式:1为短信转发模式,2为发短信模式");
14 | chooseOption = Console.ReadLine();
15 | }
16 | if (chooseOption == "1" || chooseOption == "2")
17 | {
18 | return chooseOption;
19 | }
20 | else
21 | {
22 | Console.WriteLine("请输入1或2");
23 | return onStartGuide("");
24 | }
25 |
26 | }
27 |
28 | public static List> sendMethodGuide(List chooseOptions)
29 | {
30 | if(chooseOptions.Count() == 0)
31 | {
32 | Console.WriteLine("请选择转发渠道:1.邮箱转发,2.pushplus转发,3.企业微信转发,4.TG机器人转发,5.钉钉转发,6.Bark转发,7.自定义shell转发,同时转发多渠道请以空格分割编号(举例:1 2 3 5)");
33 | chooseOptions.Add(Console.ReadLine());
34 | return sendMethodGuide(chooseOptions);
35 | }
36 | else if (chooseOptions.Count() >= 1)
37 | {
38 |
39 | if (chooseOptions.Count() == 1 && chooseOptions[0].IndexOf(" ") > -1)
40 | {
41 | string chooseOption = chooseOptions[0];
42 | List newChooseOptions = chooseOption.Split(" ").ToList();
43 | return sendMethodGuide(newChooseOptions);
44 | }
45 | else
46 | {
47 | if (JudgeChooseIsValid(chooseOptions,true))
48 | {
49 | List> actions = new List>();
50 | foreach (var chooseOption in chooseOptions)
51 | {
52 | if (chooseOption == "1")
53 | {
54 | SendByEmail.SetupEmailInfo();
55 | actions.Add(SendByEmail.SendSms);
56 | }
57 | if (chooseOption == "2")
58 | {
59 | SendByPushPlus.SetupPushPlusInfo();
60 | actions.Add(SendByPushPlus.SendSms);
61 | }
62 | if (chooseOption == "3")
63 | {
64 | SendByWeComApplication.SetupWeComInfo();
65 | actions.Add(SendByWeComApplication.SendSms);
66 | }
67 | if (chooseOption == "4")
68 | {
69 | SendByTelegramBot.SetupTGBotInfo();
70 | actions.Add(SendByTelegramBot.SendSms);
71 | }
72 | if (chooseOption == "5")
73 | {
74 | SendByDingTalkBot.SetupDingtalkBotMsg();
75 | actions.Add(SendByDingTalkBot.SendSms);
76 | }
77 | if (chooseOption == "6")
78 | {
79 | SendByBark.SetupBarkInfo();
80 | actions.Add(SendByBark.SendSms);
81 | }
82 | if (chooseOption == "7")
83 | {
84 | SendByShell.SetupCustomShellInfo();
85 | actions.Add(SendByShell.SendSms);
86 | }
87 | }
88 | return actions;
89 | }
90 | else
91 | {
92 | Console.WriteLine("请输入1或2或3或4或5或6或7");
93 | return sendMethodGuide(new List());
94 | }
95 | }
96 | }
97 | return new List>();
98 | }
99 | public static bool JudgeChooseIsValid(List chooseOptions,bool isCheckAll=false)
100 | {
101 | if (isCheckAll)
102 | {
103 | return chooseOptions.Where(a => a == "1" || a == "2" || a == "3" || a == "4" || a == "5" || a == "6" || a == "7").Count() == chooseOptions.Count();
104 | }
105 | else
106 | {
107 | return chooseOptions.Where(a => a == "1" || a == "2" || a == "3" || a == "4" || a == "5" || a == "6" || a == "7").Count() > 0;
108 | }
109 | }
110 |
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
364 | /app-arm64
365 | /app-arm64-musl
366 |
--------------------------------------------------------------------------------
/DbusTest/ModemManagerHelper.cs:
--------------------------------------------------------------------------------
1 | using DbusSmsForward.Helper;
2 | using DbusSmsForward.SettingModel;
3 | using DbusSmsForward.SMSModel;
4 | using ModemManager1.DBus;
5 | using System.Collections.Generic;
6 | using System.Diagnostics;
7 | using System.Globalization;
8 | using System.Text.Json;
9 | using Tmds.DBus.Protocol;
10 |
11 | namespace DbusSmsForward.ModemHelper
12 | {
13 | public class ModemManagerHelper
14 | {
15 | private readonly Lock _modemObjectPathListLockObject = new();
16 | public Dictionary>> _modemObjectPathList = new Dictionary>>();
17 | public string _modemObjectPathNowUse = "";
18 | public string qmiPathNowUse = "";
19 | public string _modemManagerObjectPath = "/org/freedesktop/ModemManager1";
20 | public string? systemBusAddress = Address.System;
21 | public string baseService = "org.freedesktop.ModemManager1";
22 | public List> smsSendMethodList = new List>();
23 | public string deviceUidNowUse = "";
24 | private readonly Lock _subscribeSmsPathListLockObject = new();
25 | public Dictionary SubscribeSmsPathList=new Dictionary();
26 |
27 | public ModemManagerHelper()
28 | {
29 | if (!string.IsNullOrEmpty(systemBusAddress))
30 | {
31 | InitLoadModemObjectPathList();
32 | WatchModems();
33 | }
34 | }
35 |
36 | public void InitLoadModemObjectPathList()
37 | {
38 | lock (_modemObjectPathListLockObject)
39 | {
40 | _modemObjectPathList = GetModemsPathList().Result;
41 | }
42 | if (_modemObjectPathList.Count == 1)
43 | {
44 | SetNowUsedModemPath(_modemObjectPathList.First().Key);
45 | }
46 | if (_modemObjectPathList.Count == 0)
47 | {
48 | SetNowUsedModemPath(null);
49 | }
50 | foreach (var item in _modemObjectPathList)
51 | {
52 | SubscribeSms(item.Key);
53 | }
54 | }
55 |
56 | public void SetSendMethodList(List> SendMethodList)
57 | {
58 | smsSendMethodList = SendMethodList;
59 | }
60 |
61 | public void SetNowUsedModemPath(string modemObjectPathNowUse)
62 | {
63 | _modemObjectPathNowUse = modemObjectPathNowUse;
64 | if (string.IsNullOrEmpty(_modemObjectPathNowUse))
65 | {
66 | qmiPathNowUse = "";
67 | deviceUidNowUse = "";
68 | }
69 | else
70 | {
71 | qmiPathNowUse = GetQMIDevice().Result;
72 | deviceUidNowUse = GetDevice().Result;
73 | }
74 |
75 | }
76 |
77 | public void WatchModems()
78 | {
79 |
80 | Task.Run(async () =>
81 | {
82 | try
83 | {
84 | using (var connection = new Connection(systemBusAddress))
85 | {
86 | await connection.ConnectAsync();
87 | var service = new ModemManager1Service(connection, baseService);
88 | var objectManager = service.CreateObjectManager(_modemManagerObjectPath);
89 | //Console.WriteLine($"Subscribing for modem RemovedChanges");
90 | await objectManager.WatchInterfacesRemovedAsync(
91 | async (Exception? ex, (ObjectPath ObjectPath, string[] Interfaces) change) =>
92 | {
93 | if (ex is null)
94 | {
95 | //Console.WriteLine("modem has been removed,modem path:" + change.ObjectPath.ToString());
96 | InitLoadModemObjectPathList();
97 | if (!string.IsNullOrEmpty(_modemObjectPathNowUse))
98 | {
99 | DisableAndEnableModem().Wait();
100 | }
101 | }
102 | });
103 | var tcs = new TaskCompletionSource();
104 | var task = tcs.Task;
105 | await task;
106 | }
107 | }
108 | catch (Exception ex)
109 | {
110 | Console.WriteLine(ex);
111 | }
112 | });
113 | Task.Run(async () =>
114 | {
115 | try
116 | {
117 | using (var connection = new Connection(systemBusAddress))
118 | {
119 | await connection.ConnectAsync();
120 | var service = new ModemManager1Service(connection, baseService);
121 | var objectManager = service.CreateObjectManager(_modemManagerObjectPath);
122 | //Console.WriteLine($"Subscribing for modem AddedChanges");
123 | await objectManager.WatchInterfacesAddedAsync(
124 | async (Exception? ex, (ObjectPath ObjectPath, Dictionary> InterfacesAndProperties) change) =>
125 | {
126 | if (ex is null)
127 | {
128 | //Console.WriteLine("new modem added,modem path:" + change.ObjectPath.ToString());
129 | InitLoadModemObjectPathList();
130 | if (!string.IsNullOrEmpty(_modemObjectPathNowUse))
131 | {
132 | DisableAndEnableModem().Wait();
133 | }
134 | }
135 | });
136 | var tcs = new TaskCompletionSource();
137 | var task = tcs.Task;
138 | await task;
139 | }
140 | }
141 | catch (Exception ex)
142 | {
143 | Console.WriteLine(ex);
144 | }
145 | });
146 |
147 | }
148 |
149 | public void SubscribeSms(string path)
150 | {
151 | Task.Run(async () =>
152 | {
153 | try
154 | {
155 | if ((!SubscribeSmsPathList.ContainsKey(path) || (SubscribeSmsPathList.ContainsKey(path) && !SubscribeSmsPathList[path]))&& _modemObjectPathList.ContainsKey(path))
156 | {
157 | if (SubscribeSmsPathList.ContainsKey(path))
158 | {
159 | lock (_subscribeSmsPathListLockObject)
160 | {
161 | SubscribeSmsPathList[path] = true;
162 | }
163 | }
164 | else
165 | {
166 | lock (_subscribeSmsPathListLockObject)
167 | {
168 | SubscribeSmsPathList.Add(path, true);
169 | }
170 | }
171 | //SetMsgDefaultStorageToME(path);
172 | using (var connection = new Connection(systemBusAddress))
173 | {
174 | await connection.ConnectAsync();
175 | var service = new ModemManager1Service(connection, baseService);
176 | var messaging = service.CreateMessaging(path);
177 | //Console.WriteLine($"add subscribe sms for modem path:" + path);
178 | await messaging.WatchAddedAsync(
179 | async (Exception? ex, (ObjectPath Path, bool Received) change) =>
180 | {
181 | if (ex is null)
182 | {
183 | if (change.Received)
184 | {
185 | try
186 | {
187 | var smsPath = change.Path;
188 | var service = new ModemManager1Service(connection, baseService);
189 | var sms = service.CreateSms(smsPath);
190 | var smsState = await sms.GetStateAsync();
191 | if (smsState == 2 || smsState == 3)
192 | {
193 | uint Storage = await sms.GetStorageAsync();
194 | if (!ConfigHelper.JudgeIsForwardIgnore(Storage))
195 | {
196 | string telNum = await sms.GetNumberAsync();
197 | //string smsDate = (await sms.GetTimestampAsync()).Replace("T", " ").Replace("+08:00", " ");
198 |
199 | DateTimeOffset dto = DateTimeOffset.Parse(await sms.GetTimestampAsync(), null, DateTimeStyles.RoundtripKind);
200 | // 转换为本地时间
201 | DateTime localTime = dto.LocalDateTime;
202 | string smsDate = localTime.ToString("yyyy-MM-dd HH:mm:ss");
203 | int tryCount = 0;
204 | do
205 | {
206 | smsState = await sms.GetStateAsync();
207 | Thread.Sleep(100);
208 | } while (smsState == 2 && tryCount < 300);
209 |
210 | if (smsState == 3)
211 | {
212 | appsettingsModel result = new appsettingsModel();
213 | ConfigHelper.GetSettings(ref result);
214 | string DeviceName = result.appSettings.DeviceName;
215 | result = null;
216 | if (string.IsNullOrEmpty(DeviceName) || DeviceName== "*Host*Name*")
217 | {
218 | DeviceName= ConfigHelper.GetDeviceHostName();
219 | }
220 |
221 | string smsContent = await sms.GetTextAsync();
222 | SmsContentModel smsmodel = new SmsContentModel();
223 | smsmodel.TelNumber = telNum;
224 | smsmodel.SmsDate = smsDate;
225 | smsmodel.SmsContent = smsContent;
226 | string body = "发信电话:" + telNum + "\n" + "时间:" + smsDate + "\n" + "转发设备:" + DeviceName + "\n" + "短信内容:" + smsContent;
227 | Console.WriteLine("smspath " + smsPath);
228 | if (smsSendMethodList.Count() > 0)
229 | {
230 | //Console.WriteLine("转发方法数量"+smsSendMethodList.Count());
231 | foreach (var action in smsSendMethodList)
232 | {
233 | action.Invoke(smsmodel, body, DeviceName);
234 | }
235 | }
236 | }
237 | else
238 | {
239 | Console.WriteLine("smspath:" + change.Path + " 接收超时,转发取消");
240 | }
241 | }
242 | }
243 | }
244 | catch (Exception ex2)
245 | {
246 | Console.WriteLine("GetSmsError" + ex2.Message);
247 | }
248 |
249 | }
250 | }
251 | else
252 | {
253 | Console.WriteLine(ex);
254 | }
255 | });
256 | Task task = Task.Run(() =>
257 | {
258 | var modem = service.CreateModem(path);
259 |
260 | do
261 | {
262 | try
263 | {
264 | var Manufacturer = modem.GetManufacturerAsync().Result;
265 | Manufacturer = null;
266 | Thread.Sleep(1000);
267 | }
268 | catch (Exception ex)
269 | {
270 | break;
271 | }
272 |
273 | } while (SubscribeSmsPathList.ContainsKey(path) && SubscribeSmsPathList[path] && _modemObjectPathList.ContainsKey(path));
274 | if (SubscribeSmsPathList.ContainsKey(path))
275 | {
276 | lock (_subscribeSmsPathListLockObject)
277 | {
278 | SubscribeSmsPathList[path] = false;
279 | }
280 | }
281 | });
282 | await task;
283 | //Console.WriteLine($"remove subscribe sms for modem path:" + path);
284 | }
285 | }
286 |
287 | }
288 | catch (Exception ex)
289 | {
290 | Console.WriteLine(ex);
291 | Console.WriteLine($"remove subscribe sms for modem path:" + path);
292 | }
293 |
294 |
295 | });
296 |
297 | }
298 |
299 | public async Task SendSms(string telNum, string smsContent)
300 | {
301 | try
302 | {
303 | using (var connection = new Connection(Address.System))
304 | {
305 | await connection.ConnectAsync();
306 | var service = new ModemManager1Service(connection, baseService);
307 | var messaging = service.CreateMessaging(_modemObjectPathNowUse);
308 | var sendsmsPath = await messaging.CreateAsync(new Dictionary { { "text", smsContent }, { "number", telNum } });
309 | var sms = service.CreateSms(sendsmsPath);
310 | await sms.SendAsync();
311 | return true;
312 | }
313 | }
314 | catch (Exception ex)
315 | {
316 | Console.WriteLine(ex);
317 | return false;
318 | }
319 | }
320 |
321 | public async Task>>> GetModemsPathList()
322 | {
323 | try
324 | {
325 | await ScanDevices();
326 | using (var connection = new Connection(systemBusAddress))
327 | {
328 | await connection.ConnectAsync();
329 | var service = new ModemManager1Service(connection, baseService);
330 | var objectManager = service.CreateObjectManager(_modemManagerObjectPath);
331 | return await objectManager.GetManagedObjectsAsync();
332 | }
333 | }
334 | catch (Exception ex)
335 | {
336 | Console.WriteLine(ex);
337 | }
338 | return new Dictionary>>();
339 | }
340 |
341 | public async Task ScanDevices()
342 | {
343 | try
344 | {
345 | using (var connection = new Connection(systemBusAddress))
346 | {
347 | await connection.ConnectAsync();
348 | var service = new ModemManager1Service(connection, baseService);
349 | var modemManager = service.CreateModemManager1(_modemManagerObjectPath);
350 | await modemManager.ScanDevicesAsync();
351 | modemManager = null;
352 | service = null;
353 | }
354 | }
355 | catch (Exception ex)
356 | {
357 | if (!(ex.Message.IndexOf("unsupported") >-1))
358 | {
359 | Console.WriteLine("ScanDevices失败" + ex.Message);
360 | }
361 | }
362 | }
363 |
364 | public async Task GetManufacturer(string? path = null)
365 | {
366 | try
367 | {
368 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
369 | using (var connection = new Connection(systemBusAddress))
370 | {
371 | await connection.ConnectAsync();
372 | var service = new ModemManager1Service(connection, baseService);
373 | var modem = service.CreateModem(actUsePath);
374 | var Manufacturer = await modem.GetManufacturerAsync();
375 | modem = null;
376 | service = null;
377 | return Manufacturer;
378 | }
379 | }
380 | catch (Exception ex)
381 | {
382 | Console.WriteLine(ex);
383 | return string.Empty;
384 | }
385 | }
386 |
387 | public async Task JudgeCanGetStatus(string? path = null)
388 | {
389 | try
390 | {
391 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
392 | using (var connection = new Connection(systemBusAddress))
393 | {
394 | await connection.ConnectAsync();
395 | var service = new ModemManager1Service(connection, baseService);
396 | var modem = service.CreateSimple(actUsePath);
397 | var status = await modem.GetStatusAsync();
398 | modem = null;
399 | service = null;
400 | return true;
401 | }
402 | }
403 | catch (Exception ex)
404 | {
405 | //Console.WriteLine(ex);
406 | return false;
407 | }
408 | }
409 |
410 | public async Task DisableAndEnableModem(string? path = null)
411 | {
412 | try
413 | {
414 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
415 | if (!string.IsNullOrEmpty(actUsePath))
416 | {
417 | using (var connection = new Connection(systemBusAddress))
418 | {
419 | await connection.ConnectAsync();
420 | var service = new ModemManager1Service(connection, baseService);
421 | var modem = service.CreateModem(actUsePath);
422 | try
423 | {
424 | await modem.EnableAsync(false);
425 | Thread.Sleep(200);
426 | await modem.EnableAsync(true);
427 | }
428 | catch (Exception e)
429 | {
430 | Console.WriteLine(e);
431 | }
432 | }
433 | }
434 | else
435 | {
436 | Console.WriteLine("DisableAndEnableModem:actUsePath为空");
437 | }
438 | }
439 | catch (Exception ex)
440 | {
441 | Console.WriteLine(ex);
442 | }
443 | }
444 |
445 | public async Task InhibitModemDevice(string uid, bool inhibit)
446 | {
447 | try
448 | {
449 | Console.WriteLine("device:" + uid);
450 | using (var connection = new Connection(systemBusAddress))
451 | {
452 | await connection.ConnectAsync();
453 | var service = new ModemManager1Service(connection, baseService);
454 | var modemManager = service.CreateModemManager1(_modemManagerObjectPath);
455 | await modemManager.InhibitDeviceAsync(uid, inhibit);
456 | modemManager = null;
457 | service = null;
458 | }
459 | }
460 | catch (Exception ex)
461 | {
462 | Console.WriteLine("InhibitModemDevice失败" + ex);
463 | }
464 | }
465 |
466 | public async Task GetDevice(string? path = null)
467 | {
468 | try
469 | {
470 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
471 | using (var connection = new Connection(systemBusAddress))
472 | {
473 | await connection.ConnectAsync();
474 | var service = new ModemManager1Service(connection, baseService);
475 | var modem = service.CreateModem(actUsePath);
476 | var device = await modem.GetDeviceAsync();
477 | modem = null;
478 | service = null;
479 | return device;
480 | }
481 | }
482 | catch (Exception ex)
483 | {
484 | Console.WriteLine(ex);
485 | return string.Empty;
486 | }
487 | }
488 |
489 | public async Task GetQMIDevice(string? path = null)
490 | {
491 | try
492 | {
493 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
494 | using (var connection = new Connection(systemBusAddress))
495 | {
496 | await connection.ConnectAsync();
497 | var service = new ModemManager1Service(connection, baseService);
498 | var modem = service.CreateModem(actUsePath);
499 | var Ports = await modem.GetPortsAsync();
500 | foreach (var port in Ports)
501 | {
502 | if (port.Item2 == 6)
503 | {
504 | return "/dev/" + port.Item1;
505 | }
506 | }
507 | return "";
508 | }
509 | }
510 | catch (Exception ex)
511 | {
512 | Console.WriteLine(ex);
513 | return string.Empty;
514 | }
515 | }
516 |
517 |
518 | public async Task GetModel(string? path = null)
519 | {
520 | try
521 | {
522 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
523 | using (var connection = new Connection(systemBusAddress))
524 | {
525 | await connection.ConnectAsync();
526 | var service = new ModemManager1Service(connection, baseService);
527 | var modem = service.CreateModem(actUsePath);
528 | var Model = await modem.GetModelAsync();
529 | modem = null;
530 | service = null;
531 | return Model;
532 | }
533 | }
534 | catch (Exception ex)
535 | {
536 | Console.WriteLine(ex);
537 | return string.Empty;
538 | }
539 | }
540 | public async Task GetRevision(string? path = null)
541 | {
542 | try
543 | {
544 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
545 | using (var connection = new Connection(systemBusAddress))
546 | {
547 | await connection.ConnectAsync();
548 | var service = new ModemManager1Service(connection, baseService);
549 | var modem = service.CreateModem(actUsePath);
550 | var Revision = await modem.GetRevisionAsync();
551 | modem = null;
552 | service = null;
553 | return Revision;
554 | }
555 | }
556 | catch (Exception ex)
557 | {
558 | Console.WriteLine(ex);
559 | return string.Empty;
560 | }
561 | }
562 | public async Task GetSignalQuality(string? path = null)
563 | {
564 | try
565 | {
566 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
567 | using (var connection = new Connection(systemBusAddress))
568 | {
569 | await connection.ConnectAsync();
570 | var service = new ModemManager1Service(connection, baseService);
571 | var modem = service.CreateModem(actUsePath);
572 | var SignalQuality = await modem.GetSignalQualityAsync();
573 | modem = null;
574 | service = null;
575 | return SignalQuality.Item1.ToString();
576 | }
577 | }
578 | catch (Exception ex)
579 | {
580 | Console.WriteLine(ex);
581 | return string.Empty;
582 | }
583 | }
584 | public async Task GetOwnNumbers(string? path = null)
585 | {
586 | try
587 | {
588 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
589 | using (var connection = new Connection(systemBusAddress))
590 | {
591 | await connection.ConnectAsync();
592 | var service = new ModemManager1Service(connection, baseService);
593 | var modem = service.CreateModem(actUsePath);
594 | var OwnNumbers = await modem.GetOwnNumbersAsync();
595 | modem = null;
596 | service = null;
597 | return OwnNumbers;
598 | }
599 | }
600 | catch (Exception ex)
601 | {
602 | Console.WriteLine(ex);
603 | return [];
604 | }
605 | }
606 |
607 | public async Task GetPrimarySimSlot(string? path = null)
608 | {
609 | try
610 | {
611 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
612 | using (var connection = new Connection(systemBusAddress))
613 | {
614 | await connection.ConnectAsync();
615 | var service = new ModemManager1Service(connection, baseService);
616 | var modem = service.CreateModem(actUsePath);
617 | var PrimarySimSlot = await modem.GetPrimarySimSlotAsync();
618 | return PrimarySimSlot;
619 | }
620 | }
621 | catch (Exception ex)
622 | {
623 | Console.WriteLine(ex);
624 | return null;
625 | }
626 | }
627 |
628 | public async Task GetICCID(string? path = null)
629 | {
630 | try
631 | {
632 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
633 | using (var connection = new Connection(systemBusAddress))
634 | {
635 | await connection.ConnectAsync();
636 | var service = new ModemManager1Service(connection, baseService);
637 | var modem = service.CreateModem(actUsePath);
638 | var simpath = await modem.GetSimAsync();
639 | var sim = service.CreateSim(simpath);
640 | var iccid = await sim.GetSimIdentifierAsync();
641 | modem = null;
642 | service = null;
643 | return iccid;
644 | }
645 | }
646 | catch (Exception ex)
647 | {
648 | Console.WriteLine(ex);
649 | return string.Empty;
650 | }
651 | }
652 |
653 | public async Task GetImei(string? path = null)
654 | {
655 | try
656 | {
657 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
658 | using (var connection = new Connection(systemBusAddress))
659 | {
660 | await connection.ConnectAsync();
661 | var service = new ModemManager1Service(connection, baseService);
662 | var modem3gpp = service.CreateModem3gpp(actUsePath);
663 | var Imei = await modem3gpp.GetImeiAsync();
664 | modem3gpp = null;
665 | service = null;
666 | return Imei;
667 | }
668 | }
669 | catch (Exception ex)
670 | {
671 | Console.WriteLine(ex);
672 | return string.Empty;
673 | }
674 | }
675 | public async Task GetOperatorCode(string? path = null)
676 | {
677 | try
678 | {
679 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
680 | using (var connection = new Connection(systemBusAddress))
681 | {
682 | await connection.ConnectAsync();
683 | var service = new ModemManager1Service(connection, baseService);
684 | var modem3gpp = service.CreateModem3gpp(actUsePath);
685 | var OperatorCode = await modem3gpp.GetOperatorCodeAsync();
686 | modem3gpp = null;
687 | service = null;
688 | return OperatorCode;
689 | }
690 | }
691 | catch (Exception ex)
692 | {
693 | Console.WriteLine(ex);
694 | return string.Empty;
695 | }
696 | }
697 | public async Task GetOperatorName(string? path = null)
698 | {
699 | try
700 | {
701 | string actUsePath = path == null ? _modemObjectPathNowUse : path;
702 | using (var connection = new Connection(systemBusAddress))
703 | {
704 | await connection.ConnectAsync();
705 | var service = new ModemManager1Service(connection, baseService);
706 | var modem3gpp = service.CreateModem3gpp(actUsePath);
707 | var OperatorName = await modem3gpp.GetOperatorNameAsync();
708 | modem3gpp = null;
709 | service = null;
710 | return OperatorName;
711 | }
712 | }
713 | catch (Exception ex)
714 | {
715 | Console.WriteLine(ex);
716 | return string.Empty;
717 | }
718 | }
719 |
720 | public async Task SetMsgDefaultStorageToME(string path)
721 | {
722 | try
723 | {
724 | using (var connection = new Connection(systemBusAddress))
725 | {
726 | await connection.ConnectAsync();
727 | var service = new ModemManager1Service(connection, baseService);
728 | var messaging = service.CreateMessaging(path);
729 | await messaging.SetDefaultStorageAsync(2);
730 | }
731 | }
732 | catch (Exception ex)
733 | {
734 | Console.WriteLine(ex);
735 | }
736 | }
737 | public bool RestartModem()
738 | {
739 | string qmiPath = GetQMIDevice().Result;
740 | uint? simslot = GetPrimarySimSlot().Result;
741 | string usedDevice = deviceUidNowUse;
742 | if (simslot.HasValue)
743 | {
744 | if (simslot.Value == 0)
745 | {
746 | simslot += 1;
747 | }
748 | ProcessStartInfo startInfo = new ProcessStartInfo
749 | {
750 | FileName = "qmicli",
751 | Arguments = @$"-d {qmiPath} -p --uim-sim-power-off={simslot}",
752 | RedirectStandardOutput = true,
753 | RedirectStandardError = true,
754 | UseShellExecute = false
755 | };
756 | using (Process process = Process.Start(startInfo))
757 | {
758 | if (process != null)
759 | {
760 | string output = process.StandardOutput.ReadToEnd();
761 | string error = process.StandardError.ReadToEnd();
762 | process.WaitForExit();
763 | if (process.ExitCode != 0)
764 | {
765 | Console.WriteLine(error);
766 | return false;
767 | }
768 | }
769 | else
770 | {
771 | Console.WriteLine("Failed to exec qmicli");
772 | return false;
773 | }
774 | }
775 | ProcessStartInfo startInfo2 = new ProcessStartInfo
776 | {
777 | FileName = "qmicli",
778 | Arguments = @$"-d {qmiPath} -p --uim-sim-power-on={simslot}",
779 | RedirectStandardOutput = true,
780 | RedirectStandardError = true,
781 | UseShellExecute = false
782 | };
783 | using (Process process = Process.Start(startInfo2))
784 | {
785 | if (process != null)
786 | {
787 | string output = process.StandardOutput.ReadToEnd();
788 | string error = process.StandardError.ReadToEnd();
789 | process.WaitForExit();
790 | if (process.ExitCode != 0)
791 | {
792 | Console.WriteLine(error);
793 | return false;
794 | }
795 | }
796 | else
797 | {
798 | Console.WriteLine("Failed to exec qmicli");
799 | return false;
800 | }
801 | }
802 | if (JudgeCanGetStatus().Result)
803 | {
804 | DisableAndEnableModem().Wait();
805 | }
806 | Thread.Sleep(200);
807 | if (JudgeCanGetStatus().Result)
808 | {
809 | InhibitModemDevice(usedDevice, true).Wait();
810 | Thread.Sleep(200);
811 | InhibitModemDevice(usedDevice, false).Wait();
812 | }
813 |
814 | return true;
815 |
816 | }
817 | else
818 | {
819 | return false;
820 | }
821 | }
822 |
823 | }
824 |
825 | }
826 |
--------------------------------------------------------------------------------