修改3种文件上传数据库功能

master
mzhifa 12 months ago
parent e293e6024a
commit 25827e5273

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Txgy.FilesWatcher.DBModels
{
public class UploadRealtime
{
public string filename { get; set; }
public string uploadtime { get; set; }
}
}

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Txgy.FilesWatcher.DBModels
{
public class realtimewavedatas
{
public string EventTime { get; set; }
public int WorkAreaID { get; set; }
public byte[] WaveData { get; set; }
public byte[] JsonFile { get; set; }
}
}

@ -6,7 +6,9 @@
<UseWindowsForms>True</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.21" />
<PackageReference Include="HandyControl" Version="3.4.0" />
<PackageReference Include="MySql.Data" Version="8.2.0" />
<PackageReference Include="Prism.DryIoc" Version="8.1.97" />
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
</ItemGroup>

@ -22,6 +22,7 @@ using System.Text.Unicode;
using System.Net.Sockets;
using System.Security.Policy;
using Prism.Events;
using System.Windows.Shapes;
namespace Txgy.FilesWatcher.ViewModels
{
@ -29,82 +30,21 @@ namespace Txgy.FilesWatcher.ViewModels
{
public MainViewModel(WebsocketClient websocketClient, IEventAggregator ea)
{
string filter = "*.txt";
string filter = "*.index";
string str = File.ReadAllText("systemconfig.json");
systemConfig = JsonSerializer.Deserialize<SystemConfig>(str);
WatcherPath = systemConfig.FilePath;
WatcherMseedPath= systemConfig.WatcherMseedPath;
MseedFilePath = systemConfig.MseedFilePath;
watcherArray[0] = new FileSystemWatcher();
watcherArray[1] = new FileSystemWatcher();
InitializeParams(filter);
StartTime = DateTime.Now;
this._websocketClient = websocketClient;
this._ea = ea;
_websocketClient.WebsocketError = WebSocket_Error;
_websocketClient.WebSocketMessageReceived = WebSocket4Net_MessageReceived;
_websocketClient.WebSocketInit(systemConfig.Url);
}
private void WebSocket4Net_MessageReceived(string message)
{
Debug.WriteLine($"服务端回复数据:{message}");
using (JsonDocument document = JsonDocument.Parse(message))
{
JsonElement root = document.RootElement;
if (root.TryGetProperty("type", out JsonElement dataElement))
{
string type = dataElement.ToString();
switch (type)
{
case CSMessage.sigin:
var user= JsonSerializer.Deserialize<SCUserSigin>(message, new JsonSerializerOptions
{
// 整齐打印
WriteIndented = true,
//重新编码,解决中文乱码问题
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
});
if(user.code==200)
{
isLogin = true;
LoginContent = "登 出";
}
App.Current.Dispatcher.Invoke(() =>
{
HandyControl.Controls.MessageBox.Show(user.message, "warning");
});
this.HideLoading();
break;
case CSMessage.subscribe:
var sub= JsonSerializer.Deserialize<SCUserSubscribeMessage>(message, new JsonSerializerOptions
{
// 整齐打印
WriteIndented = true,
//重新编码,解决中文乱码问题
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
});
break;
case CSMessage.publish:
var publish = JsonSerializer.Deserialize<SCDevicePublish>(message, new JsonSerializerOptions
{
// 整齐打印
WriteIndented = true,
//重新编码,解决中文乱码问题
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
});
if (publish.serialNumber >= 0)
{
dataList[publish.serialNumber - 1].IsSend = true;
}
break;
default:
break;
}
}
}
}
void WebSocket_Error(SuperSocket.ClientEngine.ErrorEventArgs e)
{
//出错后隐藏加载窗口
this.HideLoading();
Debug.WriteLine("websocket_Error:" + e.Exception.ToString());
// this._websocketClient = websocketClient;
// _websocketClient.WebsocketError = WebSocket_Error;
// _websocketClient.WebSocketMessageReceived = WebSocket4Net_MessageReceived;
// _websocketClient.WebSocketInit(systemConfig.Url);
}
private string watcherPath;
@ -113,7 +53,21 @@ namespace Txgy.FilesWatcher.ViewModels
get { return watcherPath; }
set { SetProperty(ref watcherPath, value); }
}
private string watcherMseedPath;
public string WatcherMseedPath
{
get { return watcherMseedPath; }
set { SetProperty(ref watcherMseedPath, value); }
}
private string mseedFilePath;
public string MseedFilePath
{
get { return mseedFilePath; }
set { SetProperty(ref mseedFilePath, value); }
}
private ObservableCollection<WatcherFileModel> dataList = new ObservableCollection<WatcherFileModel>();
public ObservableCollection<WatcherFileModel> DataList
@ -187,13 +141,13 @@ namespace Txgy.FilesWatcher.ViewModels
if (!isLogin)
{
this.ShowLoading();
_websocketClient.SiginServer(Account, Password);
// _websocketClient.SiginServer(Account, Password);
}
else
{
isLogin = false;
LoginContent = "登 录";
_websocketClient.Closed();
// _websocketClient.Closed();
}
});
@ -209,7 +163,6 @@ namespace Txgy.FilesWatcher.ViewModels
timer1.Start();
timer1.Tick += timer1_Tick;
IsIndeterminate = true;
_websocketClient.SendMes(JsonSerializer.Serialize(new CSUserSubscribeMessage { type = CSMessage.subscribe }));
}
private void Stop()
@ -217,23 +170,33 @@ namespace Txgy.FilesWatcher.ViewModels
WatchStartOrSopt(false);
timer1.Stop();
IsIndeterminate = false;
_websocketClient.SendMes(JsonSerializer.Serialize(new CSUserSubscribeMessage { type = CSMessage.unsubscribe }));
}
public DelegateCommand FilePathSaveCommand => new(() =>
public DelegateCommand<object> FilePathSaveCommand => new((obj) =>
{
System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
fbd.SelectedPath = WatcherPath;
string para = obj.ToString();
fbd.SelectedPath = (para == "WatcherPath") ? WatcherPath : watcherMseedPath;
fbd.Description = "请选择文件路径";
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (fbd.SelectedPath != WatcherPath)
{
WatcherPath = fbd.SelectedPath;
if (para == "WatcherPath")
{
WatcherPath = fbd.SelectedPath;
watcherArray[0].Path = watcherPath;
}
else
{
watcherMseedPath = fbd.SelectedPath;
watcherArray[1].Path = watcherMseedPath;
}
systemConfig.FilePath = WatcherPath;
var options = new JsonSerializerOptions {
systemConfig.WatcherMseedPath = watcherMseedPath;
var options = new JsonSerializerOptions
{
// 整齐打印
WriteIndented = true,
//重新编码,解决中文乱码问题
@ -251,7 +214,14 @@ namespace Txgy.FilesWatcher.ViewModels
private string settingDataPath = "systemconfig.json";
private void timer1_Tick(object? sender, EventArgs e)
{
RunTime = DateDiff(DateTime.Now, StartTime);
DateTime currentT= DateTime.Now;
RunTime = DateDiff(currentT, StartTime);
string path = $"{MseedFilePath}/NET{currentT.Year.ToString("D4")}/{currentT.Month.ToString("D2")}/{currentT.Day.ToString("D2")}/{currentT.Hour.ToString("D2")}/{currentT.AddMinutes(-2).Minute.ToString("D2")}";
// path = "I:\\DATA/NET2023/06/22/22/56";
if (Directory.Exists(path))
{
UploadMseedFile.UploadMSeedOnce(path);
}
}
private void InitializeParams(string fileFilter)
@ -265,38 +235,47 @@ namespace Txgy.FilesWatcher.ViewModels
IntervalTimesSource.Add(60);
SelectedIndex = 1;
//如果设置的目录不存在设置到根目录
if (!File.Exists(WatcherPath))
if (!Directory.Exists(WatcherPath))
{
WatcherPath = AppDomain.CurrentDomain.BaseDirectory;
}
watcher = new FileSystemWatcher();
//初始化监听
watcher.BeginInit();
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//设置监听的路径
watcher.Path = WatcherPath;
watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
// watcher.Created += Watcher_Created;
watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
watcher.Error += OnError;
//设置监听文件类型
watcher.Filter = fileFilter;
//设置是否监听子目录
watcher.IncludeSubdirectories = false;
//设置是否启用监听
watcher.EnableRaisingEvents = false;
watcher.EndInit();
if (!Directory.Exists(watcherMseedPath))
{
watcherMseedPath = AppDomain.CurrentDomain.BaseDirectory;
}
watcherArray[0].Path = watcherPath;
watcherArray[1].Path = watcherMseedPath;
//watcherArray = new FileSystemWatcher();
foreach (var watcher in watcherArray)
{
//初始化监听
watcher.BeginInit();
//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
//设置监听的路径
// watcher.Path = WatcherPath;
watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
// watcherArray.Created += Watcher_Created;
watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
watcher.Error += OnError;
//设置监听文件类型
watcher.Filter = fileFilter;
//设置是否监听子目录
watcher.IncludeSubdirectories = false;
//设置是否启用监听
watcher.EnableRaisingEvents = false;
watcher.EndInit();
}
}
@ -329,12 +308,21 @@ namespace Txgy.FilesWatcher.ViewModels
}
private void Watcher_Changed(object sender, System.IO.FileSystemEventArgs e)
{
// DateTime dt = DateTime.Now;
// string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
// string tmp = dt.Hour.ToString() + "时" + dt.Minute.ToString() + "分" + dt.Second.ToString() + "秒" + dt.Millisecond.ToString() + "毫秒,目录发生变化\r\n";
DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
watcher.EnableRaisingEvents = false;
Debug.WriteLine($"最后修改时间:{lastWriteTime}");
string lastLine = File.ReadAllLines(e.FullPath).Last().Trim();
var watch= sender as FileSystemWatcher;
string lastLine = File.ReadAllLines(e.FullPath).Last().Trim();
Debug.WriteLine($"最后修改时间:{lastWriteTime},文件路径:{watch.Path}");
if (watch != null && watch.Path == watcherArray[0].Path)
{
watcherArray[0].EnableRaisingEvents = false;
UploadRealtimeFile.UploadRealtimeFileOnce(e.FullPath, lastLine);
}
else if (watch != null && watch.Path == watcherArray[1].Path)
{
watcherArray[1].EnableRaisingEvents = false;
UploadPostproFile.UploadPostproFileOnce(watcherArray[1].Path, lastLine);
}
var str= dataList.Where(f => f.Data == lastLine).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(lastLine)
&& str==null)
@ -350,18 +338,16 @@ namespace Txgy.FilesWatcher.ViewModels
Data = lastLine,
IsSend = false
});
CSDevicePublish cSDevicePublish = new CSDevicePublish()
{
type = CSMessage.publish,
message = lastLine,
serialNumber = DataList.Count,
};
string jsonStr = JsonSerializer.Serialize(cSDevicePublish);
_websocketClient.SendMes(jsonStr);
}));
}
watcher.EnableRaisingEvents = true;
if (watch != null && watch.Path == watcherArray[0].Path)
{
watcherArray[0].EnableRaisingEvents = true;
}
else if (watch != null && watch.Path == watcherArray[1].Path)
{
watcherArray[1].EnableRaisingEvents = true;
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
@ -422,13 +408,14 @@ namespace Txgy.FilesWatcher.ViewModels
/// <param name="IsEnableRaising">True:启用监听,False:关闭监听</param>
private void WatchStartOrSopt(bool IsEnableRaising)
{
watcher.EnableRaisingEvents = IsEnableRaising;
watcherArray[0].EnableRaisingEvents = IsEnableRaising;
watcherArray[1].EnableRaisingEvents = IsEnableRaising;
}
private FileSystemWatcher watcher = new FileSystemWatcher();
private FileSystemWatcher[] watcherArray = new FileSystemWatcher[2];
private DispatcherTimer timer1 = new DispatcherTimer();
private SystemConfig systemConfig = new SystemConfig();
private readonly WebsocketClient _websocketClient;
// private readonly WebsocketClient _websocketClient;
private readonly IEventAggregator _ea;
protected void ShowLoading(string tip = "正在加载....")

@ -1,4 +1,5 @@
using Prism.Events;
using MySql.Data.MySqlClient;
using Prism.Events;
using Prism.Mvvm;
using Txgy.FilesWatcher.model;

@ -26,14 +26,14 @@
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="30"/>
<RowDefinition Height="50"/>
<RowDefinition Height="130"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30*"/>
<RowDefinition Height="30"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.ColumnSpan="2">
<Grid Grid.Row="0" Grid.ColumnSpan="2" Visibility="Hidden">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
@ -47,7 +47,7 @@
<TextBlock Text="密 码:" VerticalAlignment="Center"/>
<hc:PasswordBox UnsafePassword="{Binding Password,UpdateSourceTrigger=PropertyChanged}" IsSafeEnabled="False" ShowClearButton="True" ShowEyeButton="True" DockPanel.Dock="Right"/>
</DockPanel>
<Button Grid.Row="2" Content="{Binding LoginContent}" Command="{Binding LoginCommand}"/>
<Button Grid.Row="2" Content="{Binding LoginContent}" Command="{Binding LoginCommand}" Visibility="Hidden"/>
</Grid>
<RadioButton GroupName="start" Content="启动" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center">
<i:Interaction.Triggers>
@ -67,12 +67,26 @@
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1.5*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1.5*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1.5*"/>
</Grid.RowDefinitions>
<TextBlock Text="监控文件路径:" Grid.Row="0" Grid.Column="0" />
<TextBlock Text="监控路径1" Grid.Row="0" Grid.Column="0" />
<DockPanel Grid.Row="1">
<Button Content="..." Command="{Binding FilePathSaveCommand}" DockPanel.Dock="Right" HorizontalAlignment="Right" Height="28" Width="30"/>
<Button Content="..." Command="{Binding FilePathSaveCommand}" CommandParameter="WatcherPath" DockPanel.Dock="Right" HorizontalAlignment="Right" Height="28" Width="30"/>
<TextBox Text="{Binding WatcherPath}" IsReadOnly="True" DockPanel.Dock="Right" FontSize="10"/>
</DockPanel>
<TextBlock Text="监控路径2" Grid.Row="2" Grid.Column="0" />
<DockPanel Grid.Row="3">
<Button Content="..." Command="{Binding FilePathSaveCommand}" CommandParameter="WatcherMseedPath" DockPanel.Dock="Right" HorizontalAlignment="Right" Height="28" Width="30"/>
<TextBox Text="{Binding WatcherMseedPath}" IsReadOnly="True" DockPanel.Dock="Right" FontSize="10"/>
</DockPanel>
<TextBlock Text="目录:" Grid.Row="4" Grid.Column="0" />
<DockPanel Grid.Row="5">
<Button Content="..." Command="{Binding FilePathSaveCommand}" CommandParameter="WatcherMseedPath" DockPanel.Dock="Right" HorizontalAlignment="Right" Height="28" Width="30"/>
<TextBox Text="{Binding MseedFilePath}" IsReadOnly="True" DockPanel.Dock="Right" FontSize="10"/>
</DockPanel>
</Grid>
<TextBlock Grid.Row="3" VerticalAlignment="Center" Grid.ColumnSpan="3">

@ -0,0 +1,72 @@
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Txgy.FilesWatcher.model
{
public class DBConfig
{
private static readonly string _connStr;
private static IDbConnection Cnn => new MySqlConnection(_connStr);
static DBConfig()
{
_connStr = "Server=bj-cdb-q64mbxr6.sql.tencentcdb.com;Port=60027;Database=yuwu2021;Uid=yuwudba;Pwd=Yw123456;charset='utf8'";
}
public static MySqlConnection OpenConnection()
{
MySqlConnection connection = new MySqlConnection(_connStr);
// SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
connection.Open();
return connection;
}
public string getConfig(string configkey)
{
return "";
}
/////////////////////////////////
//createtables 配置
//起始台站号
public int stationNoStart = 02;
//结束台站号
public int stationNoend => 27;
//起始年月
public string YearMonthStart => "2022-03";
//结束年月
public string YearMonthend => "2027-03";
//uploadminiseed 配置(以分钟为单位)
//Miniseed文件路径BASE
public string MiniseedPathBase => "Y:/YuwuN3102mseed/NET2023";
//从当前年、月、日、时、分往以前X分钟
//'BeforeNMin' => 60*24*1,
public int BeforeNMin => 60 * 1 * 1;
//从当前年、月、日、时、分往以后X分钟
//'AfterNMin' => 60*24*1,
public int AfterNMin => 10 * 1 * 1;
/////////////////////////////////
/////////////////////////////////
//uploadrealtime 配置(以天为单位)
//realtimeEvent文件路径BASE
public string EventPathBase => "Y:/YuwuN3102mseed/";
//从当前年、月、日往以前X天
public int EventBeforeNDay => 3;
//从当前年、月、日往以后X天
public int EventAfterNDay => 1;
/////////////////////////////////
/////////////////////////////////
//uploadpostpro 配置(以天为单位)
//PostProEvent文件路径BASE
public string PostProEventPathBase => "Y:/YuwuN3102mseed/post/";
//从当前年、月、日往以前X天
public int PostProEventBeforeNDa => 3;
//从当前年、月、日往以后X天
public int PostProEventAfterNDay => 1;
}
}

@ -9,7 +9,9 @@ namespace Txgy.FilesWatcher.model
public class SystemConfig
{
public string FilePath { get; set; }
public string WatcherMseedPath { get; set; }
public string MseedFilePath { get; set; }
public string Url { get; set; }
}
}

@ -0,0 +1,68 @@
using Dapper;
using HandyControl.Controls;
using HandyControl.Themes;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Txgy.FilesWatcher.DBModels;
using static System.Net.WebRequestMethods;
namespace Txgy.FilesWatcher.model
{
public class UploadMseedFile
{
public string FileName { get; set; }
public static void UploadMSeedOnce(string path, int workAreaId=1)
{
try
{
var currentTime = DateTime.Now;
var Dfiles = new DirectoryInfo(path).GetFiles("*.mseed");
foreach (var DFile in Dfiles)
{
string file = DFile.Name;
string tbname = file.Substring(3,10);
tbname=tbname.Replace("-","");
string uploadedtbname = $"uploaded{tbname}";
string sqlNumber = $"SELECT COUNT(*) FROM {uploadedtbname} WHERE filename = '{file}'";
//检查文件是否已经上传
using (var conn = DBConfig.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(sqlNumber, conn);
var a = conn.QueryFirst<int>(sqlNumber);
if (a == 0)
{
//WorkAreaId = 1,更新
FileStream fs = new FileStream(DFile.FullName, FileMode.Open, FileAccess.Read);
BinaryReader mbr = new BinaryReader(fs);
Byte[] mseedDatas = mbr.ReadBytes((int)fs.Length);
fs.Close();
string WaveTime = tbname.Substring(3);
sqlNumber = $"INSERT INTO {tbname} (WaveTime, WorkAreaID, WaveData) VALUES('{WaveTime}', '{workAreaId}', @mseedD)";
var res = conn.Execute(sqlNumber, new { mseedD=mseedDatas});
//更新上传文件记录
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}

@ -0,0 +1,74 @@
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Txgy.FilesWatcher.DBModels;
namespace Txgy.FilesWatcher.model
{
public class UploadPostproFile
{
public static void UploadPostproFileOnce(string path, string eventMessage, int workAreaId = 1)
{
try
{
var currentTime = DateTime.Now;
var mseedFile = new DirectoryInfo(path).GetFiles("*.mseed");
var Dfiles = mseedFile.Where(f => eventMessage.Contains($"{f.Name.Substring(3, 4)}-{f.Name.Substring(7, 2)}-{f.Name.Substring(9, 2)}T{f.Name.Substring(12, 2)}:{f.Name.Substring(14, 2)}:{f.Name.Substring(16, 2)}"));
var files = Directory.GetFiles(path);
foreach (var dFile in Dfiles)
{
string file = dFile.Name;
string tbrealtimeresult = "postproeventresult";
string tbname = "postproeventwavedatas";
string uploadedtbname = "uploadedpostpro";
string sqlNumber = $"SELECT COUNT(*) FROM {uploadedtbname} WHERE filename = '{file}'";
//检查文件是否已经上传
using (var conn = DBConfig.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(sqlNumber, conn);
var a = conn.QueryFirst<int>(sqlNumber);
if (a == 0)
{
// string WaveTime = $"{file.Substring(3, 4)}-{file.Substring(7, 2)}-{file.Substring(9, 2)}T{file.Substring(12, 2)}:{file.Substring(14, 2)}:{file.Substring(16, 2)}";
string[] index_file_line = eventMessage.Split(" ");
string EventTime = index_file_line[0].Substring(0, 23);
string OriginTime = EventTime;
//WorkAreaId = 1,更新realtimeeventresult
sqlNumber = $"INSERT INTO {tbrealtimeresult}(WorkAreaId, EventTime, OriginTime, X, Y, Z, ML, LocSta, MLSta, RMS) VALUES('{workAreaId}', '{EventTime}', '{OriginTime}', '{index_file_line[1]}', '{index_file_line[2]}', '{index_file_line[3]}', '{index_file_line[5]}', '{index_file_line[7]}', '{index_file_line[8]}', '{index_file_line[6]}')";
var res = conn.Execute(sqlNumber);
// .mseed文件
FileStream fs = new FileStream(dFile.FullName, FileMode.Open, FileAccess.Read);
BinaryReader mbr = new BinaryReader(fs);
Byte[] mseedDatas = mbr.ReadBytes((int)fs.Length);
fs.Close();
//.json文件
string JsonPath = dFile.FullName.Replace(".mseed", "A.json");
fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read);
BinaryReader jbr = new BinaryReader(fs);
Byte[] jsonDatas = jbr.ReadBytes((int)fs.Length);
fs.Close();
sqlNumber = $"INSERT INTO {tbname} (EventTime, WorkAreaID, WaveData, JsonFile) VALUES('{EventTime}', '{workAreaId}', @mDatas, @jDatas);";
MySqlCommand mycomm = new MySqlCommand(sqlNumber, conn);
res = conn.Execute(sqlNumber, new { mDatas = mseedDatas, jDatas = jsonDatas });
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
}
}
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
}
}

@ -0,0 +1,80 @@
using Dapper;
using DryIoc;
using Google.Protobuf.WellKnownTypes;
using HandyControl.Controls;
using Microsoft.Xaml.Behaviors.Media;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Pqc.Crypto.Lms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using System.Xml.Linq;
using Txgy.FilesWatcher.DBModels;
using static System.Net.WebRequestMethods;
namespace Txgy.FilesWatcher.model
{
public class UploadRealtimeFile
{
public static void UploadRealtimeFileOnce(string path, string eventMessage, int workAreaId= 1)
{
try
{
var currentTime = DateTime.Now;
var mseedFile = new DirectoryInfo(path).GetFiles("*.mseed");
var Dfiles= mseedFile.Where(f => eventMessage.Contains($"{f.Name.Substring(3, 4)}-{f.Name.Substring(7, 2)}-{f.Name.Substring(9, 2)}T{f.Name.Substring(12, 2)}:{f.Name.Substring(14, 2)}:{f.Name.Substring(16, 2)}"));
var files = Directory.GetFiles(path);
foreach (var dFile in Dfiles)
{
string file = dFile.Name;
string tbrealtimeresult = "realtimeeventresult";
string tbname = "realtimewavedatas";
string uploadedtbname = "uploadedrealtime";
string sqlNumber = $"SELECT COUNT(*) FROM {uploadedtbname} WHERE filename = '{file}'";
//检查文件是否已经上传
using (var conn = DBConfig.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(sqlNumber, conn);
var a = conn.QueryFirst<int>(sqlNumber);
if (a==0)
{
// string WaveTime = $"{file.Substring(3, 4)}-{file.Substring(7, 2)}-{file.Substring(9, 2)}T{file.Substring(12, 2)}:{file.Substring(14, 2)}:{file.Substring(16, 2)}";
string[] index_file_line = eventMessage.Split(" ");
string EventTime = index_file_line[0].Substring(0, 23);
string OriginTime = EventTime;
//WorkAreaId = 1,更新realtimeeventresult
sqlNumber = $"INSERT INTO {tbrealtimeresult}(WorkAreaId, EventTime, OriginTime, X, Y, Z, ML, LocSta, MLSta, RMS) VALUES('{workAreaId}', '{EventTime}', '{OriginTime}', '{index_file_line[1]}', '{index_file_line[2]}', '{index_file_line[3]}', '{index_file_line[5]}', '{index_file_line[7]}', '{index_file_line[8]}', '{index_file_line[6]}')";
var res = conn.Execute(sqlNumber);
// .mseed文件
FileStream fs = new FileStream(dFile.FullName, FileMode.Open, FileAccess.Read);
BinaryReader mbr = new BinaryReader(fs);
Byte[] mseedDatas = mbr.ReadBytes((int)fs.Length);
fs.Close();
//.json文件
string JsonPath = dFile.FullName.Replace(".mseed", "A.json");
fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read);
BinaryReader jbr = new BinaryReader(fs);
Byte[] jsonDatas = jbr.ReadBytes((int)fs.Length);
fs.Close();
sqlNumber = $"INSERT INTO {tbname} (EventTime, WorkAreaID, WaveData, JsonFile) VALUES('{EventTime}', '{workAreaId}', @mDatas, @jDatas);";
MySqlCommand mycomm = new MySqlCommand(sqlNumber,conn);
res = conn.Execute(sqlNumber, new { mDatas = mseedDatas, jDatas = jsonDatas });
sqlNumber = $"INSERT INTO {uploadedtbname}(filename, uploadtime) VALUES('{file}', '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
res = conn.Execute(sqlNumber);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

@ -1,4 +1,6 @@
{
"Url": "ws://43.138.12.228:80/ws",
"FilePath": "F:\\SourceTest\\Txgy.FilesWatcher"
"FilePath": "F:\\SourceTest\\Txgy.FilesWatcher",
"WatcherMseedPath": "H:\\mzhifa\\txgy\\20231119",
"MseedFilePath": "I:\\DATA"
}

@ -1,5 +1,5 @@
C2S
{"type":"sigin","utype":"device","uid":123}
{"type":"sigin","utype":"device", "account":"clientA", "password":""}
{"type":"sigin","code":"OK","uid":123}
C2S
{"type":"sigin","utype":"user","uid":123}
@ -23,3 +23,9 @@ C2S
{"type":"heartbeat","utype":"device","uid":123}
C2S
{"type":"close","utype":"device","uid":123}
C2S
{"type":"transmitMes","message":"DAFSDFSADfsaSFASdf", "receiveUid":5}

Loading…
Cancel
Save