From 51f997c249cfee45b9196a8534863798f08a323b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=BD=87=E9=98=B3?= Date: Fri, 17 May 2024 14:49:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=B8=B2=E5=8F=A3=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=A1=AC=E4=BB=B6=E5=AE=A2=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AKS.EnterpriseLibrary.WebBrowser.csproj | 2 + CPF_Cef/Common/COMUtils.cs | 276 ++++- CPF_Cef/Common/Utils.cs | 21 + CPF_Cef/CusWebBrowser.cs | 42 +- CPF_Cef/FrmMain.cs | 94 +- CPF_Cef/MainModel.cs | 1033 ++++++++++++++--- CPF_Cef/Parame.cs | 25 + CPF_Cef/Program.cs | 4 +- 8 files changed, 1247 insertions(+), 250 deletions(-) create mode 100644 CPF_Cef/Common/Utils.cs create mode 100644 CPF_Cef/Parame.cs diff --git a/CPF_Cef/AKS.EnterpriseLibrary.WebBrowser.csproj b/CPF_Cef/AKS.EnterpriseLibrary.WebBrowser.csproj index b4a4f9d..9e4a5de 100644 --- a/CPF_Cef/AKS.EnterpriseLibrary.WebBrowser.csproj +++ b/CPF_Cef/AKS.EnterpriseLibrary.WebBrowser.csproj @@ -35,6 +35,8 @@ + + diff --git a/CPF_Cef/Common/COMUtils.cs b/CPF_Cef/Common/COMUtils.cs index f905d89..708e29a 100644 --- a/CPF_Cef/Common/COMUtils.cs +++ b/CPF_Cef/Common/COMUtils.cs @@ -1,11 +1,14 @@ using AKS.EnterpriseLibrary.WebBrowser; +using AksWebBrowser; using AKSWebBrowser.Commen; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using System; -using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; using System.IO.Ports; -using System.Linq; using System.Text; -using System.Threading; using System.Threading.Tasks; using System.Timers; using Timer = System.Timers.Timer; @@ -17,60 +20,83 @@ namespace AKSWebBrowser.Common public string jsonstr = string.Empty; public string jsontemp = string.Empty; public int maxCHunkSize = 1024; + public string callback = string.Empty; + public string ml = "COM4"; public COMUtils() { - try - { + OpenCOM(); + } - if (!serialPort.IsOpen) - { - OpenCOM("/dev/ttyCH341USB0"); - } - } - catch (Exception ex) + //打开COM口 + public void OpenCOM() + { + + try { - try + //要执行的Linux命令 + string[] cmd = LinuxCmdArea("ls /dev"); + if (cmd.Length > 0) { - Log.Info("服务启动异常ex: " + ex.Message + ""); - if (!serialPort.IsOpen) + string parm = string.Empty; + foreach (string line in cmd) { - OpenCOM("/dev/ttyCH341USB1"); + if (line.Contains("ttyCH341USB")) + { + parm = line; + break; + } + } + if (!string.IsNullOrEmpty(parm)) + { + ml = "/dev/" + parm; + Log.Info("输出结果:" + ml); + //给管理权限 + LinuxCmd(ml); + //打开串口 + // 设置COM口,波特率,奇偶校验,数据位,停止位 + serialPort.PortName = ml; // 请替换为你的串口名称 + serialPort.BaudRate = 115200; // 设置波特率 + serialPort.Parity = Parity.None; + serialPort.DataBits = 8; + serialPort.StopBits = StopBits.One; + serialPort.Handshake = Handshake.None; + serialPort.DtrEnable = true; //启用控制终端就续信号 + //serialPort.ReadTimeout = 18000; + //serialPort.RtsEnable = true; //启用请求发送信号 + serialPort.NewLine = "\n"; + serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); + if (!serialPort.IsOpen) + { + serialPort.Open(); + } + Timer timer = new Timer(3000);//1秒钟的时间间隔 + timer.Elapsed += OnTimedEvent; + timer.AutoReset = true;//重复执行 + timer.Enabled = true;//启动定时器 + Log.Info("浏览器COM服务启动成功"); + } + else + { + Log.Info("串口类型不匹配"); } } - catch (Exception ex1) + else { - Log.Info("服务启动异常ex1: " + ex1.Message + ""); + Log.Info("当前设备没有串口设备"); } } - } - - //打开COM口 - public void OpenCOM(string comName) - { - // 设置COM口,波特率,奇偶校验,数据位,停止位 - serialPort.PortName = comName; // 请替换为你的串口名称 - serialPort.BaudRate = 115200; // 设置波特率 - serialPort.Parity = Parity.None; - serialPort.DataBits = 8; - serialPort.StopBits = StopBits.One; - serialPort.Handshake = Handshake.None; - serialPort.DtrEnable = true; //启用控制终端就续信号 - serialPort.ReadTimeout = 50000; - //serialPort.RtsEnable = true; //启用请求发送信号 - serialPort.NewLine = "\n"; - serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); - if (!serialPort.IsOpen) + catch (Exception ex) { - serialPort.Open(); + Log.Info("服务启动异常ex: " + ex.Message + ""); } - Timer timer = new Timer(3000);//1秒钟的时间间隔 - timer.Elapsed += OnTimedEvent; - timer.AutoReset = true;//重复执行 - timer.Enabled = true;//启动定时器 - Log.Info("浏览器COM服务启动成功"); + } //接受数据 + public static string bsid = string.Empty; + public static string bsext = string.Empty; + public static string bspath = string.Empty; + public static bool sfjswc = false; private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { try @@ -82,7 +108,10 @@ namespace AKSWebBrowser.Common if (_jsonstr.Contains("\n")) { jsonstr = jsontemp + _jsonstr; - jsontemp = string.Empty; + //向js发送数据 + //CShaseBJavaScript(jsonstr); + //jsontemp = string.Empty; + //jsonstr = string.Empty; } else { @@ -92,19 +121,9 @@ namespace AKSWebBrowser.Common } catch (Exception ex) { - Log.Error("接受数据数据异常: " + ex.Message + ""); - jsonstr= MainModel.str2Base64("{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" +"接受数据异常:"+ ex.Message + "\"}"); - } - } - - // 处理接收到的数据 - private void ProcessReceivedData(byte[] data) - { - - // 例如,打印出每个字节的值 - foreach (byte b in data) - { - Log.Info("串口接收byte数据:" + b.ToString()); + Log.Info("接受数据数据异常: " + ex.Message + ""); + jsonstr = MainModel.str2Base64("{\"callback\":\"" + this.callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "接受数据数据超时:" + ex.Message + "\"}"); + // CShaseBJavaScript(jsonstr); } } @@ -120,38 +139,63 @@ namespace AKSWebBrowser.Common } catch (Exception ex) { - Log.Error("打开串口异常: " + ex.Message + ""); + Log.Info("定时任务打开串口异常: " + ex.Message + ""); } } //发送数据 - public string SendData(string data) + public string SendData(string data, string callback) { try { + this.callback = callback; if (serialPort.IsOpen) { - jsonstr = string.Empty; jsontemp = string.Empty; + jsonstr = string.Empty; //写入数据并以换行符结束 serialPort.WriteLine(data); + Log.Info("发送数据成功: " + data + ""); while (string.IsNullOrEmpty(jsonstr)) { - Task.Delay(10).Wait(); + Task.Delay(10).Wait(); } - return jsonstr; } else { - return ""; + //重新打开串口 + OpenCOM(); + if (serialPort.IsOpen) + { + jsontemp = string.Empty; + jsonstr = string.Empty; + //写入数据并以换行符结束 + serialPort.WriteLine(data); + Log.Info("发送数据成功: " + data + ""); + while (string.IsNullOrEmpty(jsonstr)) + { + Task.Delay(10).Wait(); + } + } + else + { + jsontemp = string.Empty; + jsonstr = string.Empty; + Log.Info("发送数据失败"); + jsonstr = MainModel.str2Base64("{\"callback\":\"" + this.callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "串口未打开" + "\"}"); + //CShaseBJavaScript(jsonstr); + } } } catch (Exception ex) { - Log.Error("发送数据异常3: " + ex.Message + ""); - return ""; + jsontemp = string.Empty; + jsonstr = string.Empty; + Log.Info("发送数据异常3: " + ex.Message + ""); + jsonstr = MainModel.str2Base64("{\"callback\":\"" + this.callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "发送数据异常:" + ex.Message + "\"}"); + //CShaseBJavaScript(jsonstr); } - + return jsonstr; } //关闭 @@ -169,5 +213,109 @@ namespace AKSWebBrowser.Common Log.Error("关闭异常: " + ex.Message + ""); } } + + /// + /// COM接收文件 + /// + public void NewMethod1(SerialPort sp, string path) + { + byte[] buffer = new byte[sp.ReadBufferSize]; + int bytesRead = sp.Read(buffer, 0, buffer.Length); + using (FileStream fileStream = new FileStream(path, FileMode.Append)) + { + fileStream.Write(buffer, 0, bytesRead); + fileStream.Close(); + fileStream.Dispose(); + } + } + + + /// + /// COM口公共发送文件 + /// + /// + public void NewMethod(string url, string id) + { + string ext = Path.GetExtension(url); + serialPort.WriteLine("Start_" + id + "_" + ext); + // 发送端 + byte[] documentBytes = File.ReadAllBytes(url); + serialPort.Write(documentBytes, 0, documentBytes.Length); + serialPort.WriteLine("End"); + } + + + //向js传输数据 + public void CShaseBJavaScript(string param) + { + Task.Run(async () => + { + param = MainModel.Base64str2(param); + Log.Info("返回数据:" + param); + JObject jo = (JObject)JsonConvert.DeserializeObject(param); + bool fieldExists = jo.ContainsKey("callback"); + if (fieldExists) + { + string callback = jo["callback"].ToString(); + Log.Info("回调js方法:" + callback); + string _parm = callback + "('" + param + "')"; + await Parame.webBrowser.ExecuteJavaScript(_parm); + } + else + { + Log.Info("回调js方法为空"); + } + }); + } + + //执行命令 + public void LinuxCmd(string command) + { + command = $"echo 'aks@123456' sudo -S chmod 777 {command}"; + Log.Info("执行命令:" + command); + // 启动进程 + var process = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{command}\"", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + } + }; + process.Start(); + string output = process.StandardOutput.ReadToEnd(); + string error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Log.Info("执行命令结果返回:" + output); + Log.Info("执行命令错误结果返回:" + error); + } + + //执行命令返回数组 + public string[] LinuxCmdArea(string command) + { + // 使用ProcessStartInfo设置启动参数 + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "/bin/bash", // 指定bash shell + Arguments = $"-c \"{command}\"", // 要执行的命令 + RedirectStandardOutput = true, // 重定向标准输出 + UseShellExecute = false, // 不使用系统外壳程序启动 + CreateNoWindow = true // 不创建新窗口 + }; + + // 启动进程 + using (Process process = Process.Start(startInfo)) + { + using (System.IO.StreamReader reader = process.StandardOutput) + { + string result = reader.ReadToEnd(); // 读取全部输出 + return result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); // 转换为字符串数组 + } + } + } } } diff --git a/CPF_Cef/Common/Utils.cs b/CPF_Cef/Common/Utils.cs new file mode 100644 index 0000000..5616b15 --- /dev/null +++ b/CPF_Cef/Common/Utils.cs @@ -0,0 +1,21 @@ +using CPF.Controls; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AksWebBrowser.Common +{ + public class Utils + { + /// + /// 消息弹框 + /// + /// + public static void MessagesBox(string mes) { + MessageBox.ShowSync(mes); + + } + } +} diff --git a/CPF_Cef/CusWebBrowser.cs b/CPF_Cef/CusWebBrowser.cs index da9e69e..d51b8b7 100644 --- a/CPF_Cef/CusWebBrowser.cs +++ b/CPF_Cef/CusWebBrowser.cs @@ -1,9 +1,12 @@ using CPF; using CPF.Cef; +using CPF.Cef.JSExtenstions; +using CPF.Mac.CoreText; using CPF.Reflection; using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.ConstrainedExecution; using System.Text; using System.Threading.Tasks; @@ -14,15 +17,17 @@ namespace AKS.EnterpriseLibrary.WebBrowser { public CusCefRequestHandler CusRequest = new CusCefRequestHandler(); public CusWebBrowser() { } - + protected override CpfCefClient OnCreateWebBrowser(CefBrowserSettings settings) { CpfCefClient cefClient = base.OnCreateWebBrowser(settings); cefClient.RequestHandler = CusRequest; + cefClient.ContextMenuHandler = new MenuHandler(); + cefClient.DragHandler = new DragHandler(); return cefClient; } } - + public class CusCefRequestHandler : CpfCefRequestHandler { public delegate void CusResquestDelegate(CefPostData postData, CefRequest request); @@ -36,4 +41,37 @@ namespace AKS.EnterpriseLibrary.WebBrowser return null; } } + + public class DragHandler : CpfCefDragHandler + { + protected override bool OnDragEnter(CefBrowser browser, CefDragData dragData, CefDragOperationsMask mask) + { + return true; + } + protected override void OnDraggableRegionsChanged(CefBrowser browser, CefFrame frame, CefDraggableRegion[] regions) + { + + } + } + + public class MenuHandler : CpfCefContextMenuHandler + { + protected override void OnBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams state, CefMenuModel model) + { + model.Clear(); + } + protected override bool OnContextMenuCommand(CefBrowser browser, CefFrame frame, CefContextMenuParams state, int commandId, CefEventFlags eventFlags) + { + return false; + } + protected override void OnContextMenuDismissed(CefBrowser browser, CefFrame frame) + { + + } + protected override bool RunContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams parameters, CefMenuModel model, CefRunContextMenuCallback callback) + { + return false; + } + } + } diff --git a/CPF_Cef/FrmMain.cs b/CPF_Cef/FrmMain.cs index d38ec6d..cae73a7 100644 --- a/CPF_Cef/FrmMain.cs +++ b/CPF_Cef/FrmMain.cs @@ -1,27 +1,25 @@ using AksWebBrowser; -using AKSWebBrowser.Commen; using CPF; -using CPF.Animation; using CPF.Cef; -using CPF.Charts; using CPF.Controls; -using CPF.Drawing; using CPF.Platform; -using CPF.Shapes; -using CPF.Styling; -using CPF.Svg; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.Diagnostics; using System.IO; -using System.Linq; +using System.Net.Http; using System.Text; using System.Threading.Tasks; +using AKSWebBrowser.Commen; +using System.Collections.Generic; +using System.Reflection.Metadata; +using AksWebBrowser.Common; namespace AKS.EnterpriseLibrary.WebBrowser { public class FrmMain : Window { + protected override void InitializeComponent() { LoadStyleFile("res://AksWebBrowser/StyleSheet.css"); @@ -43,7 +41,7 @@ namespace AKS.EnterpriseLibrary.WebBrowser new CusWebBrowser { PresenterFor = this, - Name = nameof(webBrowser), + Name = nameof(Parame.webBrowser), Bindings = { { @@ -64,7 +62,6 @@ namespace AKS.EnterpriseLibrary.WebBrowser ); } private TextBox textBox; - private CusWebBrowser webBrowser; protected override async void OnInitialized() { //窗体大小 @@ -72,35 +69,37 @@ namespace AKS.EnterpriseLibrary.WebBrowser this.Height = 1920; //SetTaskStatus.Hidetask(); base.OnInitialized(); - webBrowser = FindPresenterByName(nameof(webBrowser)); + Parame.webBrowser = FindPresenterByName(nameof(Parame.webBrowser)); textBox = FindPresenterByName(nameof(textBox)); - webBrowser.CusRequest.CusResquestEvent += CusRequest_CusResquestEvent; + Parame.webBrowser.CusRequest.CusResquestEvent += CusRequest_CusResquestEvent; //浏览器大小 - webBrowser.Width = 1080; - webBrowser.Height = 1920; - webBrowser.Url = "http://192.168.0.57:5173/"; - //webBrowser.Url = Application.StartupPath + @"\html\index.html"; + Parame.webBrowser.Width = 1080; + Parame.webBrowser.Height = 1920; + Parame.webBrowser.Url = "http://192.168.0.34:8078/#/main-out"; + //Parame.webBrowser.Url = Application.StartupPath + @"\html\index.html"; //开发者工具暂时只能支持Windows //webBrowser.ShowDev(); //SetTaskStatus.Showtask(); - webBrowser.LoadEnd += WebBrowser_LoadEnd; + Parame.webBrowser.LoadEnd += WebBrowser_LoadEnd; this.Closing += MainWindow_Closing; } //关闭事件 private void MainWindow_Closing(object sender, ClosingEventArgs e) { - MainModel.KillProcessByName("AksWebBrowser"); new MainModel().CLoseCOM(); + MainModel.KillProcessByName("AksWebBrowser"); } - bool showDev = true; + bool showDev = false; private void WebBrowser_LoadEnd(object sender, LoadEndEventArgs e) { if (!showDev) { showDev = true; - webBrowser.ShowDev(); + Parame.webBrowser.ShowDev(); } + //获取授权 + GetSQObject(); } public void Writelog(string str, string dirName = @"logs") @@ -148,7 +147,56 @@ namespace AKS.EnterpriseLibrary.WebBrowser //调用JS内的JS方法 async void InvokeJS(CpfObject obj, RoutedEventArgs eventArgs) { - var r = await webBrowser.ExecuteJavaScript("callback('调用绑定到JS里的C#方法')"); + var r = await Parame.webBrowser.ExecuteJavaScript("callback('调用绑定到JS里的C#方法')"); + } + + /// + /// 或者可以用授权接口 + /// + public void GetSQObject() + { + Task.Run(async () => + { + var client = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Get, $"{Parame.apiUrl}/api/Interface/Getlist?Ytjbm={Parame.key}"); + var response = await client.SendAsync(request); + List list = new List(); + if (response.StatusCode.ToString() == "200") + { + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + JObject jo = (JObject)JsonConvert.DeserializeObject(body); + if (jo["IsSucceed"].ToString() == "True") + { + string result = jo["result"].ToString(); + if (!string.IsNullOrEmpty("result")) + { + JArray array = (JArray)JsonConvert.DeserializeObject(result); + foreach (JObject item in array) + { + Func func = new Func() + { + Id = item["Id"].ToString(), + Platform = item["Platform"].ToString(), + Interfaceaddress = item["Interfaceaddress"].ToString(), + }; + list.Add(func); + } + } + else + { + Log.Info("未获取授权"); + Utils.MessagesBox("未获取授权"); + } + } + else + { + Log.Info("未获取授权"); + Utils.MessagesBox("未获取授权"); + } + } + Parame.FuncObject = list; + }); } } } diff --git a/CPF_Cef/MainModel.cs b/CPF_Cef/MainModel.cs index 634a27a..0dcd33e 100644 --- a/CPF_Cef/MainModel.cs +++ b/CPF_Cef/MainModel.cs @@ -1,22 +1,35 @@ -using AksWebBrowser.Common; +using AksWebBrowser; +using AksWebBrowser.Common; using AKSWebBrowser.Commen; using AKSWebBrowser.Common; using CPF.Cef; +using CPF.Mac.AppKit; +using NAudio.Wave; +using NAudio.Wave.SampleProviders; +using SkiaSharp; using System; using System.Diagnostics; using System.Globalization; using System.IO; +using System.Linq; +using System.Net; using System.Net.Http; +using System.Net.Http.Headers; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; -using static System.Net.Mime.MediaTypeNames; +using System.Web; +using System.Xml.Linq; namespace AKS.EnterpriseLibrary.WebBrowser { public class MainModel : CPF.CpfObject { public COMUtils com = new COMUtils(); + public string callback = string.Empty; + public string PrinterName = "Lexmark-MS430-Series"; + public static Process recordingProcess; + public static Process Typrocess; /// /// 读取身份证卡号 @@ -28,23 +41,28 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - paramsString = "{\"type\":\"1\",\"param\":{\"data\":\"" + "" + "\"}}"; - Log.Info("读取身份证卡号: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("IDCardRead")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "获取数据失败" + "\"}"; + Utils.MessagesBox("读取身份证设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "读取身份证设备未授权使用" + "\"}"; } else { - return Base64str2(str); + paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"1\",\"param\":{\"data\":\"" + "" + "\"}}"; + Log.Info("读取身份证卡号: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string result = Base64str2(str); + SubmitLogs(result, "IDCardRead"); + return result; } } catch (Exception ex) { Log.Error("读取身份证卡号异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "IDCardRead"); + return result; } } @@ -61,90 +79,133 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"2\",\"param\":{\"ph\":\"" + ph + "\",\"ddrs\":\"" + ddrs + "\",\"qrcode\":\"" + qrcode + "\",\"ywmc\":\"" + ywmc + "\"}}"; - Log.Info("打印排队票据: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("SendByPrint")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印排队票据失败" + "\"}"; + Utils.MessagesBox("打印排队票据设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印排队票据设备未授权使用" + "\"}"; } else { - return Base64str2(str); + string paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"2\",\"param\":{\"ph\":\"" + ph + "\",\"ddrs\":\"" + ddrs + "\",\"qrcode\":\"" + qrcode + "\",\"ywmc\":\"" + ywmc + "\"}}"; + Log.Info("打印排队票据: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string result = Base64str2(str); + SubmitLogs(result, "SendByPrint"); + return result; } } catch (Exception ex) { Log.Error("打印排队票据异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "SendByPrint"); + return result; } } /// /// 文字语音播报 + /// apt install sox + /// apt install libsox-fmt-all /// /// /// /// + public WaveOutEvent playerTxt = null; + public static string tempWav = string.Empty; [JSFunction] public string payleText(string text, bool ispaye) { try { - if (text.Length > 65535) + if (!isFuncisFuncObject("payleText")) { - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":" + "文字太长" + "}"; + Utils.MessagesBox("文字语音播报设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "文字语音播报设备未授权使用" + "\"}"; } - string paramsString = "{\"type\":\"3\",\"param\":{\"text\":\"" + text + "\",\"ispaye\":\"" + ispaye + "\"}}"; - Log.Info("文字语音播报: " + paramsString + ""); - string base64 = str2Base64(paramsString); - if (base64.Length > 1024) + else { - string url = "http://192.168.0.34:92/api/UploadFP/UploadFP"; - Task.Run(async () => + string paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"3\",\"param\":{\"text\":\"" + text + "\",\"ispaye\":\"" + ispaye + "\"}}"; + Log.Info("文字语音播报: " + paramsString + ""); + //string base64 = str2Base64(paramsString); + //if (base64.Length > 1024) + //{ + // //形成临时文件 + // DateTime dateTime = DateTime.Now; + // string time = DateTime.Now.ToString( + // "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + // var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "TempFile"); + // if (!Directory.Exists(dirpath)) + // { + // Directory.CreateDirectory(dirpath); + // } + // var filepath = System.IO.Path.Combine(dirpath, time); + // string path = dirpath + @"/" + time + ".txt"; + // base64 = str2Base64(text); + // byte[] bytes = Convert.FromBase64String(base64); + // System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew); + // System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); + // writer.Write(bytes, 0, bytes.Length); + // writer.Close(); + // Log.Info("文字语音播报临时文件: " + path + ""); + // string id = Guid.NewGuid().ToString(); + // //通过文件发送数据 + // com.NewMethod(path, ".txt"); + + // //正式执行命令 + // string url = "http://192.168.0.34:92/api/UploadFP/UploadFP"; + // Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)"); + // MatchCollection mc = re.Matches(url);//获取的是一个数组 + // string pdfurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath; + // paramsString = "{\"callback\":\"" + callback + "\",\"bsid\":\"" + id + "\",\"type\":\"3\",\"param\":{\"text\":\"" + pdfurl + "\",\"ispaye\":\"" + ispaye + "\"}}"; + // Log.Info("文字语音播报: " + paramsString + ""); + // base64 = str2Base64(paramsString); + //} + //string str = com.SendData(base64, callback); + //return Base64str2(str); + if (ispaye) { - DateTime dateTime = DateTime.Now; - string time = DateTime.Now.ToString( - "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); - var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "TempFile"); - if (!Directory.Exists(dirpath)) + Task.Run(() => { - Directory.CreateDirectory(dirpath); - } - var filepath = Path.Combine(dirpath, time); - string path = dirpath + @"/" + time + ".txt"; - base64 = str2Base64(text); - byte[] bytes = Convert.FromBase64String(base64); - System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew); - System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); - writer.Write(bytes, 0, bytes.Length); - writer.Close(); - Log.Info("文字语音播报临时文件: " + path + ""); - UploadInfo(url, path); - }); - @event2.WaitOne(); - Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)"); - MatchCollection mc = re.Matches(url);//获取的是一个数组 - string pdfurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath; - paramsString = "{\"type\":\"3\",\"param\":{\"text\":\"" + pdfurl + "\",\"ispaye\":\"" + ispaye + "\"}}"; - Log.Info("文字语音播报: " + paramsString + ""); - base64 = str2Base64(paramsString); - } - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) - { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "文字语音播报失败" + "\"}"; - } - else - { - return Base64str2(str); + if (Typrocess != null) + { + // 如果进程还在运行 + if (!Typrocess.HasExited) + { + // 发送SIGTERM信号来停止进程 + Typrocess.Kill(); + // 等待进程真正停止 + Typrocess.WaitForExit(); + } + } + }); + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + "停止播放成功" + "}"; + SubmitLogs(result, "payleText"); + return result; + } + else + { + Task.Run(() => + { + //形成语音 + tempWav = GenerateWavFromText(text); + //开始播放 + string command = $"sox {tempWav} -d"; + ShllCommad(command); + }); + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + "开始播放" + "}"; + SubmitLogs(result, "payleText"); + return result; + } } } catch (Exception ex) { - Log.Error("文字语音播报异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + Log.Error("文字语音播报异常2: " + ex.Message + ""); + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "payleText"); + return result; } } @@ -159,23 +220,28 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"4\",\"param\":{\"content\":\"" + content + "\",\"phone\":\"" + phone + "\"}}"; - Log.Info("发送短信: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("SendSSM")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "发送短信失败" + "\"}"; + Utils.MessagesBox("发送短信设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "发送短信设备未授权使用" + "\"}"; } else { - return Base64str2(str); + string paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"4\",\"param\":{\"content\":\"" + content + "\",\"phone\":\"" + phone + "\"}}"; + Log.Info("发送短信: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string result = Base64str2(str); + SubmitLogs(result, "SendSSM"); + return result; } } catch (Exception ex) { Log.Error("发送短信异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "SendSSM"); + return result; } } @@ -189,23 +255,38 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"5\",\"param\":{\"url\":\"" + url + "\"}}"; - Log.Info("打开高拍仪并且进行快速扫描文件: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("openCamera")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打开高拍仪并且进行快速扫描文件失败" + "\"}"; + Utils.MessagesBox("高拍仪设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "高拍仪设备未授权使用" + "\"}"; } else { - return Base64str2(str); + string paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"5\",\"param\":{\"url\":\"" + url + "\"}}"; + Log.Info("打开高拍仪并且进行快速扫描文件: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string data = Base64str2(str); + if (data == "400") + { + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "获取签字失败" + "\"}"; + SubmitLogs(result, "openCamera"); + return result; + } + else + { + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"jpg\",\"data\":\"" + str + "\"}"; + SubmitLogs(result, "openCamera"); + return result; + } } } catch (Exception ex) { Log.Error("打开高拍仪并且进行快速扫描文件异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "openCamera"); + return result; } } @@ -219,23 +300,28 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - paramsString = "{\"type\":\"6\",\"param\":{\"data\":\"" + "" + "\"}}"; - Log.Info("打开签字版: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("OpenSign")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打开签字版失败" + "\"}"; + Utils.MessagesBox("签字版设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}"; } else { - return Base64str2(str); + paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"6\",\"param\":{\"data\":\"" + "" + "\"}}"; + Log.Info("打开签字版: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string result = Base64str2(str); + SubmitLogs(result, "OpenSign"); + return result; } } catch (Exception ex) { Log.Error("打开签字版异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "OpenSign"); + return result; } } @@ -249,23 +335,28 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - paramsString = "{\"type\":\"7\",\"param\":{\"data\":\"" + "" + "\"}}"; - Log.Info("关闭签字版: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("OpenSign")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "关闭签字版失败" + "\"}"; + Utils.MessagesBox("签字版设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}"; } else { - return Base64str2(str); + paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"7\",\"param\":{\"data\":\"" + "" + "\"}}"; + Log.Info("关闭签字版: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string result = Base64str2(str); + SubmitLogs(result, "OpenSign"); + return result; } } catch (Exception ex) { Log.Error("关闭签字版异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "OpenSign"); + return result; } } @@ -279,28 +370,45 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"8\",\"param\":{\"url\":\"" + url + "\"}}"; - Log.Info("获取签字版数据: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("OpenSign")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "获取签字版数据失败" + "\"}"; + Utils.MessagesBox("签字版设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}"; } else { - return Base64str2(str); + string paramsString = "{\"callback\":\"" + callback + "\",\"type\":\"8\",\"param\":{\"url\":\"" + url + "\"}}"; + Log.Info("获取签字版数据: " + paramsString + ""); + string base64 = str2Base64(paramsString); + string str = com.SendData(base64, callback); + string data = Base64str2(str); + if (data == "400") + { + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "获取签字失败" + "\"}"; + SubmitLogs(result, "OpenSign"); + return result; + } + else + { + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"png\",\"data\":\"" + str + "\"}"; + SubmitLogs(result, "OpenSign"); + return result; + } } } catch (Exception ex) { Log.Error("获取签字版数据异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "OpenSign"); + return result; } } /// /// 开始录音、取消录音、结束录音 + /// sudo apt-get update + /// sudo apt-get install alsa-utils /// /// /// @@ -310,23 +418,78 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"11\",\"param\":{\"isopen\":\"" + isopen + "\",\"url\":\"" + url + "\"}}"; - Log.Info("开始录音、取消录音、结束录音: " + paramsString + ""); - string base64 = str2Base64(paramsString); - string str = com.SendData(base64); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("SoundRecording")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "开始录音、取消录音、结束录音失败" + "\"}"; + Utils.MessagesBox("录音设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "录音设备未授权使用" + "\"}"; } else { - return Base64str2(str); + //结束录音上传文件 + if (!string.IsNullOrEmpty(url) && !isopen) + { + if (StopRecording()) + { + Task.Run(async () => + { + UploadInfo(url, srpath); + }); + @event2.WaitOne(); + Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)"); + MatchCollection mc = re.Matches(url);//获取的是一个数组 + string reurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath; + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + reurl + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + else + { + string result = "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"suffix\":\"wav\",\"data\":\"" + "结束录音失败" + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + } + else if (isopen)//开始录音 + { + if (StartRecording()) + { + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + "开始录音" + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + else + { + string result = "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"suffix\":\"wav\",\"data\":\"" + "录音失败" + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + } + else //取消录音 + { + if (StopRecording()) + { + srpath = string.Empty; + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"suffix\":\"wav\",\"data\":\"" + "取消录音" + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + else + { + srpath = string.Empty; + string result = "{\"callback\":\"" + callback + "\",\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"suffix\":\"wav\",\"data\":\"" + "取消录音失败" + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; + } + + } } } catch (Exception ex) { Log.Error("开始录音、取消录音、结束录音异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "SoundRecording"); + return result; } } @@ -340,23 +503,59 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - string paramsString = "{\"type\":\"9\",\"param\":{\"url\":\"" + url + "\",\"ext\":\"" + ext + "\"}}"; - Log.Info("根据文件地址在线打印: " + paramsString + ""); - string base64_1 = str2Base64(paramsString); - string str = com.SendData(base64_1); - if (string.IsNullOrEmpty(str)) + if (!isFuncisFuncObject("PrintFile")) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "根据文件地址在线打印失败" + "\"}"; + Utils.MessagesBox("打印机设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印机设备未授权使用" + "\"}"; } else { - return Base64str2(str); + Task.Run(async () => + { + DateTime dateTime = DateTime.Now; + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + var filepath = System.IO.Path.Combine(dirpath, time); + string path = dirpath + "\\" + time + "." + ext; + WebRequest request = WebRequest.Create(url); + WebResponse response = request.GetResponse(); + using (Stream stream = response.GetResponseStream()) + { + using (FileStream fileStream = new FileStream(path, FileMode.Create)) + { + stream.CopyTo(fileStream); + } + } + response.Close(); + Log.Info("根据文件base64打印: " + path + ""); + string command = $"lp -d {PrinterName} {path}"; + ShllCommad(command); + }); + + //string id = Guid.NewGuid().ToString(); + ////通过文件发送数据 + //com.NewMethod(path, id); + //string paramsString = "{\"callback\":\"" + callback + "\",\"bsid\":\"" + id + "\",\"type\":\"9\",\"param\":{\"url\":\"" + url + "\",\"ext\":\"" + ext + "\"}}"; + //Log.Info("根据文件地址在线打印: " + paramsString + ""); + //string base64_1 = str2Base64(paramsString); + //string str = com.SendData(base64_1, callback); + //return Base64str2(str); + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "打印成功" + "\"}"; + SubmitLogs(result, "PrintFile"); + return result; } } catch (Exception ex) { Log.Error("根据文件地址在线打印异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "PrintFile"); + return result; } } @@ -372,60 +571,280 @@ namespace AKS.EnterpriseLibrary.WebBrowser { try { - Task.Run(async () => + if (!isFuncisFuncObject("PrintBase64")) { - DateTime dateTime = DateTime.Now; - string time = DateTime.Now.ToString( - "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); - var dirpath = Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile"); - if (!Directory.Exists(dirpath)) + Utils.MessagesBox("打印机设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印机设备未授权使用" + "\"}"; + } + else + { + Task.Run(async () => { - Directory.CreateDirectory(dirpath); - } - var filepath = Path.Combine(dirpath, time); - string path = dirpath + @"/" + time + "." + ext; - byte[] bytes = Convert.FromBase64String(base64); - System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew); - System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); - writer.Write(bytes, 0, bytes.Length); - writer.Close(); - Log.Info("根据文件base64打印: " + path + ""); - UploadInfo(url, path); - }); - @event2.WaitOne(); - Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)"); - MatchCollection mc = re.Matches(url);//获取的是一个数组 - string pdfurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath; - Log.Info("根据文件base64打印: " + pdfurl + ""); - try + DateTime dateTime = DateTime.Now; + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "PrintFile"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + var filepath = System.IO.Path.Combine(dirpath, time); + string path = dirpath + @"/" + time + "." + ext; + byte[] bytes = Convert.FromBase64String(base64); + System.IO.FileStream stream = new System.IO.FileStream(path, System.IO.FileMode.CreateNew); + System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); + writer.Write(bytes, 0, bytes.Length); + writer.Close(); + Log.Info("根据文件base64打印: " + path + ""); + string command = $"lp -d {PrinterName} {path}"; + ShllCommad(command); + }); + //string id = Guid.NewGuid().ToString(); + ////通过文件发送数据 + //com.NewMethod(path, ext); + //Regex re = new Regex(@"(((?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:ww‌​w.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?‌​(?:[\w]*))?)"); + //MatchCollection mc = re.Matches(url);//获取的是一个数组 + //string pdfurl = mc[0].ToString() + "://" + mc[1].ToString() + urlpath; + //Log.Info("根据文件base64打印: " + pdfurl + ""); + //try + //{ + // string paramsString = "{\"callback\":\"" + callback + "\",\"bsid\":\"" + id + "\",\"type\":\"9\",\"param\":{\"url\":\"" + pdfurl + "\",\"ext\":\"" + ext + "\"}}"; + // Log.Info("根据文件base64打印: " + paramsString + ""); + // string base64_1 = str2Base64(paramsString); + // string str = com.SendData(base64_1, callback); + // return Base64str2(str); + //} + //catch (Exception ex) + //{ + // Log.Error("根据文件base64打印异常: " + ex.Message + ""); + // return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + //} + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":\"" + "打印成功" + "\"}"; + SubmitLogs(result, "PrintBase64"); + return result; + } + } + catch (Exception ex) + { + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "PrintBase64"); + return result; + } + } + + /// + /// 播放音频文件 + /// + /// + /// + public static WaveOutEvent player = null; + public static AudioFileReader audioFileReader = null; + public static string WaveOutPath = string.Empty; + [JSFunction] + public string PalyFile(string url, bool ispaly) + { + try + { + if (!isFuncisFuncObject("PalyFile")) + { + Utils.MessagesBox("音频设备未授权使用"); + return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "音频设备未授权使用" + "\"}"; + } + else { - string paramsString = "{\"type\":\"9\",\"param\":{\"url\":\"" + pdfurl + "\",\"ext\":\"" + ext + "\"}}"; - Log.Info("根据文件base64打印: " + paramsString + ""); - string base64_1 = str2Base64(paramsString); - string str = com.SendData(base64_1); - if (string.IsNullOrEmpty(str)) + if (ispaly) { - return "{\"message\":\"success\",\"code\":\"400\",\"status\":false,\"data\":\"" + "根据文件base64打印失败" + "\"}"; + Task.Run(() => + { + Uri uri = new Uri(url); + //返回 123.xlsx + var filename = HttpUtility.UrlDecode(uri.Segments.Last()); + //获取文件后缀 + string ext = System.IO.Path.GetExtension(filename); + DateTime dateTime = DateTime.Now; + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "WaveOutFile"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + string path = dirpath + @"/" + time + "." + ext; + WebRequest request = WebRequest.Create(url); + WebResponse response = request.GetResponse(); + using (Stream stream = response.GetResponseStream()) + { + using (FileStream fileStream = new FileStream(WaveOutPath, FileMode.Create)) + { + stream.CopyTo(fileStream); + } + } + response.Close(); + + //开始播放 + string command = $"sox {path} -d"; + ShllCommad(command); + }); + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + "开始播放" + "}"; + SubmitLogs(result, "PalyFile"); + return result; } else { - return Base64str2(str); + Task.Run(() => + { + if (Typrocess != null) + { + // 如果进程还在运行 + if (!Typrocess.HasExited) + { + // 发送SIGTERM信号来停止进程 + Typrocess.Kill(); + // 等待进程真正停止 + Typrocess.WaitForExit(); + } + } + }); + string result = "{\"callback\":\"" + callback + "\",\"message\":\"success\",\"code\":\"200\",\"status\":true,\"data\":" + "停止播放成功" + "}"; + SubmitLogs(result, "PalyFile"); + return result; } } - catch (Exception ex) + } + catch (Exception ex) + { + string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + SubmitLogs(result, "PalyFile"); + return result; + } + } + + /// + /// 播放音频公共方法 + /// + /// + private void NewMethod(string url) + { + Uri uri = new Uri(url); + //返回 123.xlsx + var filename = HttpUtility.UrlDecode(uri.Segments.Last()); + //获取文件后缀 + string ext = System.IO.Path.GetExtension(filename); + DateTime dateTime = DateTime.Now; + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "WaveOutFile"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + string path = dirpath + @"/" + time + "." + ext; + WebRequest request = WebRequest.Create(url); + WebResponse response = request.GetResponse(); + using (Stream stream = response.GetResponseStream()) + { + using (FileStream fileStream = new FileStream(WaveOutPath, FileMode.Create)) + { + stream.CopyTo(fileStream); + } + } + response.Close(); + + + using (player = new WaveOutEvent()) + { + player.PlaybackStopped += waveOut_PlaybackStopped; + using (audioFileReader = new AudioFileReader(WaveOutPath)) { - Log.Error("根据文件base64打印异常: " + ex.Message + ""); - return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; + // 创建一个增益效果器对象 + var volumeProvider = new VolumeSampleProvider(audioFileReader.ToSampleProvider()); + // 将音频文件添加到WaveOutEvent对象中 + player.Init(volumeProvider); + // 设置音量增益为2倍 + volumeProvider.Volume = 2.0f; + // 开始播放音频 + player.Play(); + while (player.PlaybackState == PlaybackState.Playing) + { + Thread.Sleep(1000); + } } + } + Log.Info("开始播放"); + } + /// + /// 播放完成 + /// + /// + /// + private void waveOut_PlaybackStopped(object sender, StoppedEventArgs e) + { + try + { + player.Stop(); + // 释放资源 + player.Dispose(); + audioFileReader.Dispose(); + player = null; + File.Delete(WaveOutPath); + Log.Info("播放完成"); + } + catch (Exception ex) + { + Log.Info("播放完成,清除本地文件异常" + ex.Message); + } + } + /// + /// 唤醒键盘 + /// + /// + /// + [JSFunction] + public string openKey(string paramsString) + { + try + { + Task.Run(() => + { + Bash("/usr/bin/python3 /usr/bin/onboard"); + }); + return "{\"message\":\"seccse\",\"code\":\"200\",\"status\":true,\"data\":\"" + "唤醒键盘成功" + "\"}"; } catch (Exception ex) { + Log.Error("唤醒键盘异常: " + ex.Message + ""); return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}"; } } + /// + /// 执行文件 + /// + /// + /// + public static string Bash(string command) + { + var escapedArgs = command.Replace("\"", "\\\""); + var process = new Process() + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{escapedArgs}\"", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true, + } + }; + process.Start(); + string result = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + process.Dispose(); + return result; + } + /// /// 初始文件上传 /// @@ -439,6 +858,19 @@ namespace AKS.EnterpriseLibrary.WebBrowser @event2.Set(); } + + //上传本地文件中转 + private string urlP = string.Empty; + private AutoResetEvent @event5 = new AutoResetEvent(false); + private async void UploadInfoByFile(string url, string strpath) + { + var httpClient = new HttpClient(); + var uploader = new ChunkedUpload(httpClient); + urlP = await uploader.UploadFileAsync(url, strpath); + File.Delete(strpath); + @event5.Set(); + } + /// /// string 转换为 base64 /// @@ -462,13 +894,11 @@ namespace AKS.EnterpriseLibrary.WebBrowser return result; } - /// - /// 根据程序名称杀死进程 - /// - /// + //根据程序名称杀死进程 public static void KillProcessByName(string processName) { Process[] processes = Process.GetProcessesByName(processName); + foreach (Process process in processes) { try @@ -480,12 +910,297 @@ namespace AKS.EnterpriseLibrary.WebBrowser } } - /// - /// 关闭串口 - /// + //关闭串口 public void CLoseCOM() { com.ClosePort(); } + + /// + /// 开始录音 + /// + /// + public bool StartRecording() + { + try + { + if (recordingProcess != null) + { + // 如果进程还在运行 + if (!recordingProcess.HasExited) + { + // 发送SIGTERM信号来停止arecord进程 + recordingProcess.Kill(); + recordingProcess.WaitForExit(); // 等待进程真正停止 + } + } + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "Record"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + srpath = dirpath + "/" + time + ".wav"; + string outputFile = srpath; // 输出文件名 + string device = "default"; // 音频设备,可以通过arecord -l来列出所有设备 + // 构建arecord命令 + string command = $"arecord --device={device} --file-type=wav --duration=10 --quiet {outputFile}"; + // 启动进程 + recordingProcess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{command}\"", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; + recordingProcess.Start(); + return true; + } + catch (Exception ex) + { + Log.Error("开始录音异常:" + ex.Message); + return false; + } + } + + /// + /// 结束录音 + /// + public bool StopRecording() + { + try + { + // 如果进程还在运行 + if (!recordingProcess.HasExited) + { + // 发送SIGTERM信号来停止arecord进程 + recordingProcess.Kill(); + recordingProcess.WaitForExit(); // 等待进程真正停止 + } + return true; + } + catch (Exception ex) + { + Log.Error("结束录音异常:" + ex.Message); + return false; + } + } + + + public static WaveFileWriter writer; + public static StreamWriter mStreamWriter; + public static WaveInEvent waveIn = null; + private string srpath = string.Empty; + //开启录音 + private bool StateSoundRecor() + { + if (waveIn != null) + { + waveIn.StopRecording(); + waveIn.Dispose(); + writer.Close(); + mStreamWriter.Close(); + waveIn = null; + } + // 录音对象 + waveIn = new WaveInEvent(); + int sampleRate = 48000; //采样率 + int channels = 2; //录音通道数 + int bitsPerSample = 16; //位深 + WaveFormat waveFormat = new WaveFormat(sampleRate, bitsPerSample, channels); + waveIn.WaveFormat = waveFormat; //设置录音格式 + DateTime dateTime = DateTime.Now; + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "Record"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + srpath = dirpath + "/" + time + ".wav"; + string pathfile = dirpath + "/" + time + ".txt"; + // 创建WaveFileWriter对象来保存录音数据 路径在bin文件下 + writer = new WaveFileWriter(srpath, waveFormat); + //编写器 + mStreamWriter = new StreamWriter(pathfile, false, new System.Text.UTF8Encoding(false)); + // 设置录音回调函数 + int bitIndex = bitsPerSample / 8; + waveIn.DataAvailable += (sender, e) => + { + // 将录音数据写入文件 + writer.Write(e.Buffer, 0, e.BytesRecorded); + for (int i = 0; i < e.BytesRecorded / bitIndex; i++) + { + //24bit,导出的数据 + //int sample = (int)((e.Buffer[i * bitIndex + 2] << 16) | (e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]); + //16bit 将两个byte数据组合成一个short数据 + short sample = (short)((e.Buffer[i * bitIndex + 1] << 8) | e.Buffer[i * bitIndex]); + mStreamWriter.Write("{0},", sample); + } + }; + try + { + //尝试打开录音设备,如果设备支持设置的WaveFormat,则能够成功打开 + waveIn.StartRecording(); + return true; + } + catch (Exception ex) + { + Log.Info("录音开启失败:" + ex.Message); + srpath = ""; + return false; + } + } + + /// + /// 停止录音、取消录音 + /// + /// + private bool StopSoundRecor() + { + + try + { + //停止录音 + waveIn.StopRecording(); + waveIn.Dispose(); + writer.Close(); + mStreamWriter.Close(); + waveIn = null; + return true; + } + catch (Exception ex) + { + Log.Info("停止录音、取消录音失败:" + ex.Message); + srpath = ""; + return false; + } + } + + /// + /// 执行命令 + /// + public static void ShllCommad(string command) + { + Log.Info("执行命令:" + command); + // 启动进程 + Typrocess = new Process + { + StartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", + Arguments = $"-c \"{command}\"", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + } + }; + Typrocess.Start(); + Typrocess.WaitForExit(); + } + + /// + /// 开源文字转语音 + /// sudo apt-get install espeak + /// + /// + /// + static string GenerateWavFromText(string text) + { + string time = DateTime.Now.ToString( + "yyyyMMddHHmmss", DateTimeFormatInfo.InvariantInfo); + var dirpath = System.IO.Path.Combine(Environment.CurrentDirectory, "wwwroot", "WavFile"); + if (!Directory.Exists(dirpath)) + { + Directory.CreateDirectory(dirpath); + } + var tempFile = dirpath + "/" + time + ".wav"; + text = text.Replace("(", "").Replace(")", "、"); + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "espeak", + Arguments = $" -vzh -s 150 \"{text}\" -w {tempFile}", // 设置语速为150,输出为WAV文件 + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }; + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); // 等待进程结束 + process.Close(); + process.Dispose(); + } + return tempFile; + } + + /// + /// 是否已获取收取 + /// + /// + /// + public bool isFuncisFuncObject(string funcName) + { + bool isFunc = false; + if (Parame.FuncObject.Count > 0) + { + foreach (Func func in Parame.FuncObject) + { + if (func.Interfaceaddress.Contains(funcName)) + { + isFunc = true; + break; + } + } + } + return isFunc; + } + + //提交设备操作日志 + public static void SubmitLogs(string Describer, string funcName) + { + Task.Run(async () => + { + string ApiId = string.Empty; + string Name = string.Empty; + string Interfaceaddress = string.Empty; + bool isFunc = false; + if (Parame.FuncObject.Count > 0) + { + foreach (Func func in Parame.FuncObject) + { + if (func.Interfaceaddress.Contains(funcName)) + { + isFunc = true; + ApiId = func.Id; + Name = func.Platform; + Interfaceaddress = func.Interfaceaddress; + break; + } + } + } + if (isFunc) + { + var client = new HttpClient(); + var request = new HttpRequestMessage(HttpMethod.Post, $"{Parame.apiUrl}/api/Interface/JournalAdd"); + var content = new StringContent("{\"Name\": \"" + Name + "\",\"Describer\": \"" + str2Base64(Describer) + "\", \"Interfaceaddress\": \"" + Interfaceaddress + "\", \"ApiId\": \"" + ApiId + "\"}", null, "application/json"); + request.Content = content; + var response = await client.SendAsync(request); + if (response.StatusCode.ToString() == "200") + { + response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync(); + Log.Info(body); + } + } + }); + } + + } } diff --git a/CPF_Cef/Parame.cs b/CPF_Cef/Parame.cs new file mode 100644 index 0000000..834aeb6 --- /dev/null +++ b/CPF_Cef/Parame.cs @@ -0,0 +1,25 @@ +using AKS.EnterpriseLibrary.WebBrowser; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AksWebBrowser +{ + public class Parame + { + public static CusWebBrowser webBrowser { get; set; } + public static List FuncObject { get; set; } + //接口地址 + public static string apiUrl = "http://192.168.0.34:92"; + //授权key + public static string key = "1"; + } + public struct Func + { + public string Id { get; set; } + public string Platform { get; set; } + public string Interfaceaddress { get; set; } + }; +} diff --git a/CPF_Cef/Program.cs b/CPF_Cef/Program.cs index 7e53444..9f15228 100644 --- a/CPF_Cef/Program.cs +++ b/CPF_Cef/Program.cs @@ -27,8 +27,8 @@ namespace AKS.EnterpriseLibrary.WebBrowser { return; } - CefRuntime.Initialize(mainArgs, new CefSettings { }, app, IntPtr.Zero); - + CefRuntime.Initialize(mainArgs, new CefSettings{ }, app, IntPtr.Zero); + var model = new MainModel(); Application.Run(new FrmMain { DataContext = model, CommandContext = model });