采用串口方式连接
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1206 lines
51 KiB

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 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;
/// <summary>
/// 读取身份证卡号
/// </summary>
/// <param name="paramsString"></param>
/// <returns></returns>
[JSFunction]
public string IDCardRead(string paramsString)
{
try
{
if (!isFuncisFuncObject("IDCardRead"))
{
Utils.MessagesBox("读取身份证设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "读取身份证设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "IDCardRead");
return result;
}
}
/// <summary>
/// 打印排队票据
/// </summary>
/// <param name="ph">排号</param>
/// <param name="ddrs">等待人数</param>
/// <param name="qrcode">二维码</param>
/// <param name="ywmc">办理业务名称</param>
/// <returns></returns>
[JSFunction]
public string SendByPrint(string ph, string ddrs, string qrcode, string ywmc)
{
try
{
if (!isFuncisFuncObject("SendByPrint"))
{
Utils.MessagesBox("打印排队票据设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印排队票据设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "SendByPrint");
return result;
}
}
/// <summary>
/// 文字语音播报
/// apt install sox
/// apt install libsox-fmt-all
/// </summary>
/// <param name="text"></param>
/// <param name="ispaye"></param>
/// <returns></returns>
public WaveOutEvent playerTxt = null;
public static string tempWav = string.Empty;
[JSFunction]
public string payleText(string text, bool ispaye)
{
try
{
if (!isFuncisFuncObject("payleText"))
{
Utils.MessagesBox("文字语音播报设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "文字语音播报设备未授权使用" + "\"}";
}
else
{
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]+)?|(?:www.|[-;:&=\+\$,\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)
{
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, "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("文字语音播报异常2: " + ex.Message + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "payleText");
return result;
}
}
/// <summary>
/// 发送短信
/// </summary>
/// <param name="content"></param>
/// <param name="phone"></param>
/// <returns></returns>
[JSFunction]
public string SendSSM(string content, string phone)
{
try
{
if (!isFuncisFuncObject("SendSSM"))
{
Utils.MessagesBox("发送短信设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "发送短信设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "SendSSM");
return result;
}
}
/// <summary>
/// 打开高拍仪并且进行快速扫描文件
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
[JSFunction]
public string openCamera(string url)
{
try
{
if (!isFuncisFuncObject("openCamera"))
{
Utils.MessagesBox("高拍仪设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "高拍仪设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "openCamera");
return result;
}
}
/// <summary>
/// 打开签字版
/// </summary>
/// <param name="paramsString"></param>
/// <returns></returns>
[JSFunction]
public string OpenSign(string paramsString)
{
try
{
if (!isFuncisFuncObject("OpenSign"))
{
Utils.MessagesBox("签字版设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "OpenSign");
return result;
}
}
/// <summary>
/// 关闭签字版
/// </summary>
/// <param name="paramsString"></param>
/// <returns></returns>
[JSFunction]
public string CloseSign(string paramsString)
{
try
{
if (!isFuncisFuncObject("OpenSign"))
{
Utils.MessagesBox("签字版设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "OpenSign");
return result;
}
}
/// <summary>
/// 获取签字版数据
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
[JSFunction]
public string GetSignData(string url)
{
try
{
if (!isFuncisFuncObject("OpenSign"))
{
Utils.MessagesBox("签字版设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "签字版设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "OpenSign");
return result;
}
}
/// <summary>
/// 开始录音、取消录音、结束录音
/// sudo apt-get update
/// sudo apt-get install alsa-utils
/// </summary>
/// <param name="isopen"></param>
/// <param name="url"></param>
/// <returns></returns>
[JSFunction]
public string SoundRecording(bool isopen, string url)
{
try
{
if (!isFuncisFuncObject("SoundRecording"))
{
Utils.MessagesBox("录音设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "录音设备未授权使用" + "\"}";
}
else
{
//结束录音上传文件
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]+)?|(?:www.|[-;:&=\+\$,\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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "SoundRecording");
return result;
}
}
/// <summary>
/// 根据文件地址在线打印
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
[JSFunction]
public string PrintFile(string url, string ext)
{
try
{
if (!isFuncisFuncObject("PrintFile"))
{
Utils.MessagesBox("打印机设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印机设备未授权使用" + "\"}";
}
else
{
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 + "");
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "PrintFile");
return result;
}
}
/// <summary>
/// 根据文件base64打印
/// </summary>
/// <param name="base64"></param>
/// <param name="ext"></param>
/// <returns></returns>
[JSFunction]
public string PrintBase64(string url, string base64, string ext)
{
try
{
if (!isFuncisFuncObject("PrintBase64"))
{
Utils.MessagesBox("打印机设备未授权使用");
return "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + "打印机设备未授权使用" + "\"}";
}
else
{
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;
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]+)?|(?:www.|[-;:&=\+\$,\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;
}
}
/// <summary>
/// 播放音频文件
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
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
{
if (ispaly)
{
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
{
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)
{
string result = "{\"message\":\"fali\",\"code\":\"400\",\"status\":false,\"data\":\"" + ex.Message + "\"}";
SubmitLogs(result, "PalyFile");
return result;
}
}
/// <summary>
/// 播放音频公共方法
/// </summary>
/// <param name="url"></param>
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))
{
// 创建一个增益效果器对象
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("开始播放");
}
/// <summary>
/// 播放完成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
/// <summary>
/// 唤醒键盘
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
[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 + "\"}";
}
}
/// <summary>
/// 执行文件
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 初始文件上传
/// </summary>
private string urlpath = string.Empty;
private AutoResetEvent @event2 = new AutoResetEvent(false);
private async void UploadInfo(string url, string srpath)
{
var httpClient = new HttpClient();
var uploader = new ChunkedUpload(httpClient);
urlpath = await uploader.UploadFileAsync(url, srpath);
@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();
}
/// <summary>
/// string 转换为 base64
/// </summary>
/// <returns></returns>
public static string str2Base64(string str)
{
byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
string result = Convert.ToBase64String(b);
return result;
}
/// <summary>
/// base64 转换为 string
/// </summary>
/// <param name="data"></param>
public static string Base64str2(string data)
{
byte[] c = Convert.FromBase64String(data);
string result = System.Text.Encoding.UTF8.GetString(c);
Log.Info("接收返回数据:" + result);
return result;
}
//根据程序名称杀死进程
public static void KillProcessByName(string processName)
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process process in processes)
{
try
{
process.Kill();
process.WaitForExit(); // 等待进程退出
}
catch (Exception ex) { }
}
}
//关闭串口
public void CLoseCOM()
{
com.ClosePort();
}
/// <summary>
/// 开始录音
/// </summary>
/// <returns></returns>
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;
}
}
/// <summary>
/// 结束录音
/// </summary>
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;
}
}
/// <summary>
/// 停止录音、取消录音
/// </summary>
/// <param name="isopen"></param>
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;
}
}
/// <summary>
/// 执行命令
/// </summary>
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();
}
/// <summary>
/// 开源文字转语音
/// sudo apt-get install espeak
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 是否已获取收取
/// </summary>
/// <param name="funcName"></param>
/// <returns></returns>
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);
}
}
});
}
}
}