20230201_145_upperpc/InSituLaboratory.Entities/tools.cs
2024-06-28 17:51:00 +08:00

751 lines
26 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.NetworkInformation;
using System.Configuration;
using System.Net.Sockets;
using System.Net;
using System.ComponentModel.DataAnnotations.Schema;
namespace InSituLaboratory.Entities
{
[NotMapped]
public static class tools
{
static Dictionary<string, bool> Txt_Used = new Dictionary<string, bool>();
#region
/// <summary>
/// 获取当前设备的所有端口号
/// </summary>
/// <returns></returns>
public static string[] GetSerialPort()
{
string[] ports = null;
return ports;
}
#endregion
#region PING IP是否ping通
/// <summary>
/// IP地址是否ping通
/// </summary>
/// <param name="strIP">IP地址例如“10.8.2.1”</param>
/// <returns></returns>
public static bool PingIp(string strIP)
{
bool bRet = false;
try
{
Ping pingSend = new Ping();
PingReply reply = pingSend.Send(strIP, 1000);
if (reply.Status == IPStatus.Success)
bRet = true;
}
catch (Exception)
{
bRet = false;
}
return bRet;
}
#endregion
#region
//获取当前程序运行路径
private static string Save_Path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"数据记录\";
public static void Logging(string message)
{
AddLgoToTXT("Log.txt", Save_Path + DateTime.Now.ToString("yyyy_MM_dd") + @"\", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ---- " + message + "\r\n");
}
public static void AddLog(string logstring)
{
AddLgoToTXT("解析数据.txt", AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"数据记录\" + DateTime.Now.ToString("yyyy_MM_dd") + @"\", logstring);
}
#endregion
#region
/// <summary>
/// 文件自动保存
/// </summary>
/// <param name="_file_name">文件名称</param>
/// <param name="path">保存路径</param>
/// <param name="logstring">文件内容</param>
public static void AddLgoToTXT(string _file_name, string path, string logstring)
{
//检查是否存在该路径
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + _file_name;
//检查该路径下是否存在该文件
if (!File.Exists(path))
{
FileStream stream = null;
try
{
stream = File.Create(path);
stream.Close();
stream.Dispose();
}
catch (Exception ex)
{
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
if (!Txt_Used.ContainsKey(path))
{
Txt_Used.Add(path, true);
}
else
{
if (Txt_Used[path])
{
return;
}
else
{
Txt_Used[path] = true;
}
}
FileStream fs = null;
try
{
//[1]创建文件流 文件路径 和枚举类型的文件操作类型
fs = new FileStream(path, FileMode.Append);
//[2]创建写入器
StreamWriter sw = new StreamWriter(fs);
//[3]以流的方式写入数据
sw.Write(logstring);
//[4]关闭写入器
sw.Close();
//[5]关闭文件流
fs.Close();
Txt_Used[path] = false;
}
catch (Exception ex)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}
#endregion
#region TXT文件
public static string ReadFromTXT(string _file_name, string path)
{
//检查是否存在该路径
if (!Directory.Exists(path))
return "所选时间段没有系统日志";
path = path + _file_name;
//检查该路径下是否存在该文件
if (!File.Exists(path))
return "所选时间段没有系统日志";
//如果文件占用就
if (FileIsInUse(new FileInfo(path)))
return "";
//[1]创建文件流
FileStream fs = new FileStream(path, FileMode.Open);
//【2】创建读取器
//Encoding.Default 读取未知文件是使用default格式
//StreamReader sr = new StreamReader(fs,Encoding.Default);
StreamReader sr = new StreamReader(fs);
//【3】以流的方式读取数据
string txt = sr.ReadToEnd();
//[4]关闭读取器
sr.Close();
//【5】关闭文件流
fs.Close();
return txt;
}
#endregion
#region
static bool FileIsInUse(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//如果文件被占用,即
//1.文件正在被另一个线程处理
//2.或者正在被另一个线程处理
//3.或者文件不存在
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
#endregion
#region CRC校验
private static readonly byte[] aucCRCHi = {
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40
};
private static readonly byte[] aucCRCLo = {
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
0x41, 0x81, 0x80, 0x40
};
public static byte[] Crc16(byte[] pucFrame, int usLen)
{
int i = 0;
byte crcHi = 0xFF;
byte crcLo = 0xFF;
ushort iIndex = 0x0000;
while (usLen-- > 0)
{
iIndex = (ushort)(crcLo ^ pucFrame[i++]);
crcLo = (byte)(crcHi ^ aucCRCHi[iIndex]);
crcHi = aucCRCLo[iIndex];
}
return new byte[] { crcLo, crcHi };
}
#endregion
#region 16ASCII
/// <summary>
/// 16进制转字符串ASCII
/// </summary>
/// <param name="hs"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string HexStringToString(string hs, Encoding encode)
{
StringBuilder strTemp = new StringBuilder();
byte[] b = new byte[hs.Length / 2];
for (int i = 0; i < hs.Length / 2; i++)
{
strTemp.Clear();
strTemp.Append(hs.Substring(i * 2, 2));
b[i] = Convert.ToByte(strTemp.ToString(), 16);
}
return encode.GetString(b);
}
#endregion
#region 162
/// <summary>
/// //16转2方法
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static string HexString2BinString(string hexString)
{
try
{
string result = string.Empty;
foreach (char c in hexString)
{
int v = Convert.ToInt32(c.ToString(), 16);
int v2 = int.Parse(Convert.ToString(v, 2));
// 去掉格式串中的空格即可去掉每个4位二进制数之间的空格
result += string.Format("{0:d4} ", v2);
}
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
#endregion
#region 16
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
#endregion
#region 16
/// <summary>
/// 16进制原码字符串转字节数组
/// </summary>
/// <param name="hexString">"AABBCC"或"AA BB CC"格式的字符串</param>
/// <returns></returns>
public static byte[] ConvertHexStringToBytes(string hexString)
{
hexString = hexString.Replace(" ", "");
if (hexString.Length % 2 != 0)
{
throw new ArgumentException("参数长度不正确");
}
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
{
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return returnBytes;
}
#endregion
#region 1/0 True/False
public static List<bool> O_C(string o_c)
{
o_c = o_c.Trim();
List<bool> result = new List<bool>();
for (int i = 0; i < o_c.Length; i++)
{
if (o_c.Substring(i, 1).Equals("1"))
{
result.Add(true);
}
else if (o_c.Substring(i, 1).Equals("0"))
{
result.Add(false);
}
}
return result;
}
#endregion
#region 16ASI码字符串
/// <summary>
/// 将一条十六进制字符串转换为ASCII
/// </summary>
/// <param name="hexstring">一条十六进制字符串</param>
/// <returns>返回一条ASCII码</returns>
public static string HexStringToASCII(string hexstring)
{
byte[] bt = HexStringToBinary(hexstring);
string lin = "";
for (int i = 0; i < bt.Length; i++)
{
lin = lin + bt[i] + " ";
}
string[] ss = lin.Trim().Split(new char[] { ' ' });
char[] c = new char[ss.Length];
int a;
for (int i = 0; i < c.Length; i++)
{
a = Convert.ToInt32(ss[i]);
c[i] = Convert.ToChar(a);
}
string b = new string(c);
return b;
}
/**/
/// <summary>
/// 16进制字符串转换为二进制数组
/// </summary>
/// <param name="hexstring">用空格切割字符串</param>
/// <returns>返回一个二进制字符串</returns>
public static byte[] HexStringToBinary(string hexstring)
{
string[] tmpary = hexstring.Trim().Split(' ');
byte[] buff = new byte[tmpary.Length];
for (int i = 0; i < buff.Length; i++)
{
buff[i] = Convert.ToByte(tmpary[i], 16);
}
return buff;
}
#endregion
#region
private static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
/// <summary>
/// 获取配置文件
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static string GetAppSetting(string key)
{
if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
{
string value = config.AppSettings.Settings[key].Value;
return value;
}
else
{
return null;
}
}
/// <summary>
/// 更新配置文件信息
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public static void UpdateAppSettings(string key, string value)
{
if (GetAppSetting(key) == value) //如果写入的配置文件和之前一致 就不写入了
return;
if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
{
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");//刷新数据
}
else
{
Console.WriteLine("当前节点不存在!");
}
}
#endregion
#region Telnet
public static bool TelnetPort(string ip, int port)
{
if (checkPingEnable(ip))
{
if (checkPortEnable(ip, port))
{
return true;
}
}
return false;
}
//检查是否ping通
public static bool checkPingEnable(string _ip)
{
bool _isEnable = false;
try
{
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(_ip, 120);//第一个参数为ip地址第二个参数为ping的时间
if (reply.Status == IPStatus.Success)
{
_isEnable = true;
}
else
{
_isEnable = false;
}
}
catch (Exception)
{
_isEnable = false;
}
return _isEnable;
}
/// <summary>
/// telnet port
/// </summary>
/// <param name="_ip"></param>
/// <param name="_port"></param>
/// <returns></returns>
public static bool checkPortEnable(string _ip, int _port)
{
//将IP和端口替换成为你要检测的
string ipAddress = _ip;
int portNum = _port;
IPAddress ip = IPAddress.Parse(ipAddress);
IPEndPoint point = new IPEndPoint(ip, portNum);
bool _portEnable = false;
try
{
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(point);
//Console.WriteLine("连接{0}成功!", point);
sock.Close();
_portEnable = true;
}
}
catch (SocketException e)
{
//Console.WriteLine("连接{0}失败", point);
_portEnable = false;
}
return _portEnable;
}
#endregion
#region
/// <summary>
///设置线程工作的空间
/// </summary>
/// <param name="process">线程</param>
/// <param name="minSize">最小空间</param>
/// <param name="maxSize">最大空间</param>
/// <returns></returns>
[System.Runtime.InteropServices.DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)]
private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int maximumWorkingSetSize);
public static void ClearMemory(object o)
{
GC.Collect();
GC.SuppressFinalize(o);
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
#endregion
#region Other
public static byte[] intoBytes(int value)
{
byte[] src = new byte[4]
{
(byte)(value & 0xFF),
(byte)(value >> 8 & 0xFF),
(byte)(value >> 16 & 0xFF),
(byte)(value >> 24 & 0xFF)
};
return src;
}
public static byte[] shortoBytes(int value)
{
byte[] src = new byte[2]
{
(byte)(value & 0xFF),
(byte)(value >> 8 & 0xFF)
};
return src;
}
#endregion
#region TcpClient检测 / Socket检测
/// <summary>
/// TcpClient检测
/// </summary>
/// <param name="ip">ip地址</param>
/// <param name="port">端口号</param>
public static bool TcpClientCheck(string ip, int port)
{
IPAddress ipa = IPAddress.Parse(ip);
IPEndPoint point = new IPEndPoint(ipa, port);
TcpClient tcp = null;
try
{
tcp = new TcpClient();
tcp.Connect(point);
//Console.WriteLine("端口打开");
return true;
}
catch (Exception ex)
{
//Console.WriteLine("计算机端口检测失败,错误消息为:" + ex.Message);
return false;
}
finally
{
if (tcp != null)
{
tcp.Close();
}
}
}
/// <summary>
/// Socket检测
/// </summary>
/// <param name="ip">ip地址</param>
/// <param name="port">端口号</param>
public static bool SocketCheck(string ip, int port)
{
Socket sock = null;
try
{
IPAddress ipa = IPAddress.Parse(ip);
IPEndPoint point = new IPEndPoint(ipa, port);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(point);
//Console.WriteLine("端口打开");
return true;
}
catch (SocketException ex)
{
//Console.WriteLine("计算机端口检测失败,错误消息为:" + ex.Message);
return false;
}
finally
{
if (sock != null)
{
sock.Close();
sock.Dispose();
}
}
}
#endregion
#region byte数组按长度在前面补0
/// <summary>
/// byte数组按长度在前面补0
/// </summary>
/// <param name="array"></param>
/// <param name="targetLength"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static byte[] PadArrayWithZeros(byte[] array, int targetLength)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (targetLength <= 0)
throw new ArgumentOutOfRangeException(nameof(targetLength), "Target length must be a positive integer.");
if (targetLength <= array.Length)
return array; // No need to pad
byte[] paddedArray = new byte[targetLength];
Array.Copy(array, 0, paddedArray, targetLength - array.Length, array.Length);
return paddedArray;
}
#endregion
#region CRC-8 x8+x5+x4+1 0x31(0x131)
/// <summary>
/// CRC8位校验表
/// </summary>
private static byte[] CRC8Table = new byte[]
{
0,94,188,226,97,63,221,131,194,156,126,32,163,253,31,65,
157,195,33,127,252,162,64,30, 95,1,227,189,62,96,130,220,
35,125,159,193,66,28,254,160,225,191,93,3,128,222,60,98,
190,224,2,92,223,129,99,61,124,34,192,158,29,67,161,255,
70,24,250,164,39,121,155,197,132,218,56,102,229,187,89,7,
219,133,103,57,186,228,6,88,25,71,165,251,120,38,196,154,
101,59,217,135,4,90,184,230,167,249,27,69,198,152,122,36,
248,166,68,26,153,199,37,123,58,100,134,216,91,5,231,185,
140,210,48,110,237,179,81,15,78,16,242,172,47,113,147,205,
17,79,173,243,112,46,204,146,211,141,111,49,178,236,14,80,
175,241,19,77,206,144,114,44,109,51,209,143,12,82,176,238,
50,108,142,208,83,13,239,177,240,174,76,18,145,207,45,115,
202,148,118,40,171,245,23,73,8,86,180,234,105,55,213,139,
87,9,235,181,54,104,138,212,149,203, 41,119,244,170,72,22,
233,183,85,11,136,214,52,106,43,117,151,201,74,20,246,168,
116,42,200,150,21,75,169,247,182,232,10,84,215,137,107,53
};
public static byte CRC(byte[] buffer)
{
return CRC(buffer, 0, buffer.Length);
}
public static byte CRC(byte[] buffer, int off, int len)
{
byte crc = 0;
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (off < 0 || len < 0 || off + len > buffer.Length)
{
throw new ArgumentOutOfRangeException();
}
for (int i = off; i < len; i++)
{
crc = CRC8Table[crc ^ buffer[i]];
}
return crc;
}
#endregion
}
}