This commit is contained in:
hehaoyang 2024-01-23 18:44:16 +08:00
parent 1661bf7ddf
commit 98d0761a19
9 changed files with 142 additions and 179 deletions

View File

@ -4,7 +4,7 @@
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Nullable>disable</Nullable>
<PublishAot>true</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
@ -16,6 +16,7 @@
<Compile Remove="Peripheral\._MonitorServer.cs" />
<Compile Remove="Utils\._FileUtils.cs" />
<Compile Remove="Utils\._JsonUtils.cs" />
<Compile Remove="Utils\._LiteDBUtils.cs" />
<Compile Remove="Utils\._LogUtils.cs" />
<Compile Remove="Utils\._SQLiteUtils.cs" />
<Compile Remove="Utils\._TaskUtils.cs" />
@ -23,8 +24,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="LiteDB.Async" Version="0.1.7" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Data.SQLite" Version="1.0.118" />
</ItemGroup>
</Project>

View File

@ -6,7 +6,6 @@ using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Data.SQLite;
using HxServer.Utils;
using System.Data.SqlTypes;
using Newtonsoft.Json;
@ -16,201 +15,163 @@ using System.Reflection;
using System.IO;
using System.Threading.Channels;
using System.Xml.Linq;
using LiteDB;
using LiteDB.Async;
namespace HxServer.Peripheral
{
public class HxSetting
{
public int ID { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public class HxLog
{
public int ID { get; set; }
public DateTime Timestamp { get; set; }
public int Type { get; set; }
public int Index { get; set; }
public string Message { get; set; }
public string Data { get; set; }
}
public class HxVideoRecord
{
[JsonIgnore]
public int ID { get; set; }
[JsonProperty(PropertyName = "channel")]
public int Channel { get; set; }
[JsonProperty(PropertyName = "start_time")]
public string? StartTime { get; set; }
public DateTime StartTime { get; set; }
[JsonProperty(PropertyName = "end_time")]
public string? EndTime { get; set; }
public DateTime EndTime { get; set; }
[JsonProperty(PropertyName = "duration")]
public int Duration { get; set; }
[JsonProperty(PropertyName = "name")]
public string? Name { get; set; }
public string Name { get; set; }
[JsonProperty(PropertyName = "path")]
public string? Path { get; set; }
}
public string Path { get; set; }
}
public class DataBase
{
private const string filename ="HxNvr.DataBase.db";
private const string filename = "HxNvr.DataBase.db";
private static SQLiteConnection? Connection { get; set; }
// 打开数据库 (如果不存在则创建)
private static LiteDatabaseAsync database { get; set; } = new(@"HxNvr.DataBase.db");
private static SQLiteCommand InsertLogCommand = new("INSERT INTO [Log] ([timestamp], [type], [index], [message], [data]) VALUES (@timestamp, @type, @index, @message, @data); SELECT LAST_INSERT_ROWID();");
//private static SQLiteCommand InsertLogCommand = new("INSERT INTO [Log] ([timestamp], [type], [index], [message], [data]) VALUES (@timestamp, @type, @index, @message, @data); SELECT LAST_INSERT_ROWID();");
public static void Initialization()
{
if (!File.Exists(filename)) try { SQLiteConnection.CreateFile(filename); } catch { return; }
Connection = new SQLiteConnection("Data Source=" + filename);
try { Connection.Open(); }
catch
var collection = database.GetCollection<HxSetting>("Settings");
var array = collection.FindAllAsync().Result;
if (array.Count() == 0)
{
try
{
var corrupted = filename + string.Format("_[{0:yyyyMMddHHmmss}].BAK", DateTime.Now);
File.Move(filename, corrupted);
SQLiteConnection.CreateFile(filename);
Connection.Open();
}
catch { }
collection.InsertAsync(new HxSetting() { Name = "code", Value = "TVIS" });
collection.InsertAsync(new HxSetting() { Name = "recording_split_time", Value = "10" });
collection.InsertAsync(new HxSetting() { Name = "recording_reserver_time", Value = "15" });
collection.InsertAsync(new HxSetting() { Name = "drive_threshold", Value = "10" });
collection.InsertAsync(new HxSetting() { Name = "is_cleanup_enabled", Value = "1" });
collection.InsertAsync(new HxSetting() { Name = "is_cleanup_forced_for_reserve_time", Value = "0" });
collection.InsertAsync(new HxSetting() { Name = "disks", Value = "/home/hehaoyang/harddisk1;D://" });
collection.InsertAsync(new HxSetting() { Name = "channel_00", Value = "0;通道 01;Bsm;teweishi.oicp.net;554;1;15;1;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_01", Value = "1;通道 02;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_02", Value = "2;通道 03;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_03", Value = "3;通道 04;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_04", Value = "4;通道 05;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_05", Value = "5;通道 06;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_06", Value = "6;通道 07;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_07", Value = "7;通道 08;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_08", Value = "8;通道 09;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_09", Value = "9;通道 10;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_10", Value = "10;通道 11;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_11", Value = "11;通道 12;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_12", Value = "12;通道 13;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_13", Value = "13;通道 14;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_14", Value = "14;通道 15;Bsm;192.168.10.101;554;1;15;0;1;0" });
collection.InsertAsync(new HxSetting() { Name = "channel_15", Value = "15;通道 16;Bsm;192.168.10.101;554;1;15;0;1;0" });
}
/* 创建程序配置表 */
Connection.ExecuteNonQuery(
"CREATE TABLE IF NOT EXISTS [Settings] (" +
" [name] TEXT NOT NULL PRIMARY KEY," +
" [value] TEXT" +
");");
/* 创建日志信息表 */
Connection.ExecuteNonQuery(
"CREATE TABLE IF NOT EXISTS [Log] (" +
" [id] INTEGER NOT NULL PRIMARY KEY," +
" [timestamp] DATETIME NOT NULL," +
" [type] INTEGER NOT NULL," +
" [index] INTEGER," +
" [message] NTEXT NOT NULL," +
" [data] NTEXT" +
");");
/* 创建录像信息表 */
Connection.ExecuteNonQuery(
"CREATE TABLE IF NOT EXISTS [Records] (" +
" [channel] INTEGER NOT NULL," +
" [date] DATE NOT NULL," +
" [start_time] TIME NOT NULL," +
" [end_time] TIME," +
" [duration] INTEGER," +
" [name] NTEXT NOT NULL," +
" [path] NTEXT NOT NULL," +
"PRIMARY KEY (name));");
InsertLogCommand.Connection = Connection;
InsertLogCommand.Parameters.Add("@timestamp", DbType.DateTime);
InsertLogCommand.Parameters.Add("@type", DbType.Int64);
InsertLogCommand.Parameters.Add("@index", DbType.Int64);
InsertLogCommand.Parameters.Add("@message", DbType.String);
InsertLogCommand.Parameters.Add("@data", DbType.String);
InsertLogCommand.Prepare();
}
public static Dictionary<string, string> ReadSettings()
{
Dictionary<string, string> keyValuePairs = [];
using SQLiteCommand command = new("SELECT * FROM [Settings]", Connection);
using SQLiteDataReader reader = command.ExecuteReader();
while(reader.Read())
{
keyValuePairs.Add(reader.GetString(0), reader.IsDBNull(1) ? "" : reader.GetString(1));
}
/* 打开表 */
var collection = database.GetCollection<HxSetting>("Settings");
var array = collection.FindAllAsync().Result;
/* 查询所有数据 */
foreach (var c in array)
keyValuePairs.Add(c.Name, c.Value);
return keyValuePairs;
}
public static void WriteLogger(DateTime timestamp, int type, int? index, string? message, string? data)
public static async void WriteLogger(DateTime timestamp, int type, int index, string message, string data)
{
InsertLogCommand.Parameters["@timestamp"].Value = timestamp;
InsertLogCommand.Parameters["@type"].Value = (long)type;
if (index.HasValue && index != -1) InsertLogCommand.Parameters["@index"].Value = index.Value;
InsertLogCommand.Parameters["@message"].Value = message;
InsertLogCommand.Parameters["@data"].Value = data;
try { object res = InsertLogCommand.ExecuteScalar(); } catch { }
/* 打开表 */
var collection = database.GetCollection<HxLog>("Log");
/* 插入数据 */
await collection.InsertAsync(new HxLog() { Timestamp = timestamp, Type = type, Index = index, Message = message, Data = data });
}
public static List<object> QueryFirstRecord()
public static List<HxVideoRecord> QueryFirstRecord()
{
List<object> records = [];
List<HxVideoRecord> records = [];
using SQLiteCommand command = new($"SELECT * FROM [Records]", Connection);
using SQLiteDataReader reader = command.ExecuteReader();
if (reader.Read())
{
int channel = reader.GetInt32(0);
string _date = reader.GetString(1);
string start_time = _date + " " + reader.GetString(2);
string end_time = reader.GetString(3) == "" ? "" : (_date + " " + reader.GetString(3));
int duration = reader.GetInt32(4);
string name = reader.GetString(5);
string path = reader.GetString(6);
/* 打开表 */
var collection = database.GetCollection<HxVideoRecord>("Records");
records.Add(new HxVideoRecord()
{
Channel = channel,
StartTime = start_time,
EndTime = end_time,
Duration = duration,
Name = name,
Path = path,
});
}
var record = collection.FindOneAsync(x=> !string.IsNullOrEmpty(x.Name)).Result;
if (record != null)
records.Add(record);
return records;
}
public static List<object> QueryRecord(string? date)
public static List<HxVideoRecord> QueryRecord(DateTime date)
{
List<object> records = [];
List<HxVideoRecord> records = [];
using SQLiteCommand command = new($"SELECT * FROM [Records] WHERE [date] = '{date}'", Connection);
using SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int channel = reader.GetInt32(0);
string _date = reader.GetString(1);
string start_time = _date + " " + reader.GetString(2);
string end_time = reader.GetString(3) == "" ? "" : (_date + " " + reader.GetString(3));
int duration = reader.GetInt32(4);
string name = reader.GetString(5);
string path = reader.GetString(6);
///* 打开表 */
//var collection = LiteDBUtils.GetCollection<HxVideoRecord>(filename, "Records");
records.Add(new HxVideoRecord()
{
Channel = channel,
StartTime = start_time,
EndTime = end_time,
Duration = duration,
Name = name,
Path = path,
});
}
//records = collection.Find(x => x.StartTime.Date.CompareTo(date.Date) == 0).ToList();
return records;
}
public static void ReplaceRecord(int channel, DateTime start_time, DateTime? end_time, int duration, string? name, string? path)
public static void ReplaceRecord(int channel, DateTime start_time, DateTime end_time, int duration, string name, string path)
{
string commandText = string.Format("REPLACE INTO [Records] ([channel], [date], [start_time], [end_time], [duration], [name], [path]) VALUES ({0}, '{1:yyyy-MM-dd}', '{1:HH:mm:ss}', '{2:HH:mm:ss}', {3}, '{4}', '{5}');",
channel,
start_time,
end_time,
duration,
name,
path);
///* 打开表 */
//var collection = LiteDBUtils.GetCollection<HxVideoRecord>(filename, "Records");
using SQLiteCommand command = new(commandText, Connection);
try { command.ExecuteScalar(); } catch { }
//collection.Update(new HxVideoRecord() { Channel = channel, StartTime = start_time, EndTime = end_time, Duration = duration, Name = name, Path = path });
}
public static void DeleteRecord(string? key, string? value)
public static void DeleteRecordByPath(string path)
{
string commandText = string.Format("DELETE FROM Records WHERE [{0}] = '{1}'", key, value);
///* 打开表 */
//var collection = LiteDBUtils.GetCollection<HxVideoRecord>(filename, "Records");
using SQLiteCommand command = new(commandText, Connection);
try { command.ExecuteScalar(); } catch { }
//var record = collection.DeleteMany(x => x.Path == path);
}
}
}

View File

@ -20,7 +20,7 @@ public class Model
public int ActionType { get; set; }
[JsonProperty(PropertyName = "msgInfo")]
public object? MsgInfo { get; set; }
public object MsgInfo { get; set; }
public Model() { }
@ -44,7 +44,7 @@ public class AppInfo
public class MonitorServer
{
private static UdpClient? UdpClient;
private static UdpClient UdpClient;
private static readonly ConcurrentDictionary<string, AppInfo> AppInfos = new();
@ -73,16 +73,16 @@ public class MonitorServer
{
var point = new IPEndPoint(IPAddress.Any, 0);
var buffer = UdpClient?.EndReceive(ar, ref point);
var buffer = UdpClient.EndReceive(ar, ref point);
TaskUtils.Run(Process, buffer, point);
UdpClient?.BeginReceive(RequestCallback, null);
UdpClient.BeginReceive(RequestCallback, null);
}
private static void Process(byte[]? buffer, IPEndPoint? point)
private static void Process(byte[] buffer, IPEndPoint point)
{
if (buffer?.Length > 0)
if (buffer.Length > 0)
{
var model = JsonConvert.DeserializeObject<Model>(Encoding.UTF8.GetString(buffer));
@ -101,15 +101,15 @@ public class MonitorServer
break;
case 1:
UdpClient?.Send(point, new Model(1, DataBase.ReadSettings()));
UdpClient.Send(point, new Model(1, DataBase.ReadSettings()));
break;
case 2:
UdpClient?.Send(point, new Model(1, DataBase.ReadSettings()));
UdpClient.Send(point, new Model(1, DataBase.ReadSettings()));
break;
case 3:
UdpClient?.Send(point, new Model(1, DataBase.ReadSettings()));
UdpClient.Send(point, new Model(1, DataBase.ReadSettings()));
break;
case 4:
@ -126,14 +126,14 @@ public class MonitorServer
case 5:
if (dictionary == null || dictionary.Count == 0)
{
UdpClient?.Send(point, new Model(5, DataBase.QueryFirstRecord()));
UdpClient.Send(point, new Model(5, DataBase.QueryFirstRecord()));
}
else
{
if (dictionary.ContainsKey("date"))
UdpClient?.Send(point, new Model(5, DataBase.QueryRecord(dictionary["date"].ToString())));
UdpClient.Send(point, new Model(5, DataBase.QueryRecord(Convert.ToDateTime(dictionary["date"].ToString()))));
else
UdpClient?.Send(point, new Model(5, DataBase.QueryRecord(dictionary["start_date"].ToString())));
UdpClient.Send(point, new Model(5, DataBase.QueryRecord(Convert.ToDateTime(dictionary["start_date"].ToString()))));
}
break;
@ -143,7 +143,7 @@ public class MonitorServer
DataBase.ReplaceRecord(Convert.ToInt32(dictionary["channel"]),
Convert.ToDateTime(dictionary["start_time"]),
dictionary["end_time"].ToString() == "" ? null :Convert.ToDateTime(dictionary["end_time"]),
Convert.ToDateTime(dictionary["end_time"]),
Convert.ToInt32(dictionary["duration"]),
dictionary["name"].ToString(),
dictionary["path"].ToString());
@ -155,16 +155,16 @@ public class MonitorServer
return;
if (dictionary.ContainsKey("path"))
DataBase.DeleteRecord("path", dictionary["path"].ToString());
else if (dictionary.ContainsKey("date"))
DataBase.DeleteRecord("date", dictionary["date"].ToString());
DataBase.DeleteRecordByPath(dictionary["path"].ToString());
//else if (dictionary.ContainsKey("date"))
// DataBase.DeleteRecord("date", dictionary["date"].ToString());
break;
}
}
}
private static void UpdateAppInfos(string? name, string? version, IPEndPoint? point)
private static void UpdateAppInfos(string name, string version, IPEndPoint point)
{
if (name == null) return;
@ -179,7 +179,7 @@ public class MonitorServer
Console.WriteLine($"{name}[{version}] {app.DateTime:yyyy-MM-dd HH:mm:ss}");
}
UdpClient?.Send(Encoding.UTF8.GetBytes("OK " + name), 5, point);
UdpClient.Send(Encoding.UTF8.GetBytes("OK " + name), 5, point);
}
private static void AppMonitorProcess()

View File

@ -9,7 +9,7 @@ namespace HxServer;
/// <summary>
/// 版本信息
/// </summary>
/// </summary>c vv
public class ReadMe
{
public static string AppName { get => "HxServer"; }

View File

@ -0,0 +1,19 @@
using LiteDB;
using LiteDB.Async;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HxServer.Utils
{
public static class LiteDBUtils
{
public static ILiteCollection<T> GetCollection<T>(LiteDatabase database, string name, BsonAutoId autoId = BsonAutoId.ObjectId)
{
/* 获取集合(相当于表) */
return database.GetCollection<T>(name);
}
}
}

View File

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HxServer.Utils
{
public static class SQLiteCommandUtils
{
public static int ExecuteNonQuery(this SQLiteConnection connection, string commandText)
{
var command = new SQLiteCommand(commandText, connection);
return command.ExecuteNonQuery();
}
}
}

View File

@ -47,8 +47,8 @@ else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
INCLUDEPATH += $$PWD/external/HxUtils/include
LIBS += -L$$PWD/external/HxUtils -lHxUtils
PRE_TARGETDEPS += $$PWD/external/HxUtils/libHxUtils.a
LIBS += -L$$PWD/external/HxUtils/lib -lHxUtils
PRE_TARGETDEPS += $$PWD/external/HxUtils/lib/libHxUtils.a
unix {
INCLUDEPATH += /usr/local/ffmpeg/include

View File

@ -57,6 +57,9 @@ void broadcast_receive_event(QByteArray data)
{
case 1:
HxTask::invoke([=](QJsonObject _msginfo) {
if(_msginfo.size() == 0)
return;
HxRecordCleanup::set(_msginfo);
if (is_startup)