Files
SendNotify/Program.cs
2025-05-27 11:54:32 +04:00

349 lines
14 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 Microsoft.Data.SqlClient;
using Oracle.ManagedDataAccess.Client;
using SendNotify;
using System.Net;
using System.Net.Http.Json;
using System.Text;
internal class Program
{
private static DateTime lastDate = DateTime.MinValue;
private static DateTime startProgramDT = DateTime.MinValue;
public static bool statusRemovingBillets = false;
private static CancellationTokenSource? removalCts;
private static object removalLock = new object();
private static void Main(string[] args)
{
startProgramDT = DateTime.Now;
var RemovingBillets = new RemovingBillets();
while (true)
{
string? gotifyUrl = null;
string? appToken_izhstal = null;
string? clientToken_izhstal = null;
string? proxyUrl = null;
string? proxyUsername = null;
string? proxyPassword = null;
string? checkNow = null;
int targetPriority = -1;
var config = File.ReadAllLines("config.txt");
foreach (var line in config)
{
if (line.StartsWith("gotify_url="))
gotifyUrl = line.Substring("gotify_url=".Length);
else if (line.StartsWith("app_token_izhstal="))
appToken_izhstal = line.Substring("app_token_izhstal=".Length);
else if (line.StartsWith("proxy_url="))
proxyUrl = line.Substring("proxy_url=".Length);
else if (line.StartsWith("proxy_username="))
proxyUsername = line.Substring("proxy_username=".Length);
else if (line.StartsWith("proxy_password="))
proxyPassword = line.Substring("proxy_password=".Length);
else if (line.StartsWith("check_now="))
checkNow = line.Substring("check_now=".Length);
else if (line.StartsWith("client_token_izhstal="))
clientToken_izhstal = line.Substring("client_token_izhstal=".Length);
else if (line.StartsWith("target_priority="))
int.TryParse(line.Substring("target_priority=".Length), out targetPriority);
}
if (gotifyUrl == null || appToken_izhstal == null || proxyUrl == null || proxyUsername == null ||
proxyPassword == null || checkNow == null || clientToken_izhstal == null || targetPriority == -1)
{
Console.WriteLine("Ошибка: не все параметры указаны в config.txt");
Log.Logger("Ошибка: не все параметры указаны в config.txt");
}
else
{
NotifyPollingAsync(gotifyUrl, appToken_izhstal, proxyUrl, proxyUsername, proxyPassword, checkNow);
var result = ReceiveMessagesAsync(gotifyUrl, clientToken_izhstal, proxyUrl, proxyUsername, proxyPassword, targetPriority).Result;
if (result.status && result.msg.Date > startProgramDT)
{
if (result.msg.Title?.ToLower() == "L2_REM".ToLower())
{
lock (removalLock)
{
if (result.msg.Message?.ToLower() == "ON".ToLower() && !statusRemovingBillets)
{
removalCts = new CancellationTokenSource();
Task.Run(() => RemovingBillets.StartRemovalProcess(removalCts.Token));
statusRemovingBillets = true;
Log.Logger("Удаление заготовок: ЗАПУЩЕНО");
}
else if (result.msg.Message?.ToLower() == "OFF".ToLower() && statusRemovingBillets)
{
removalCts?.Cancel();
statusRemovingBillets = false;
Log.Logger("Удаление заготовок: ОСТАНОВЛЕНО");
}
}
}
}
}
Thread.Sleep(60000);
}
}
private static async void NotifyPollingAsync(string url, string token, string proxyUrl, string proxyUsername, string proxyPassword, string checkNow)
{
#region test msg to check
DateTime now = DateTime.Now;
if ((now.Hour == 8 && now.Date != lastDate.Date) || checkNow.ToLower() == "yes")
{
var notification = new
{
title = "Test notify",
message = "IS OK",
priority = 3
};
await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword);
if (checkNow.ToLower() != "yes")
lastDate = now;
}
#endregion
#region check furnace 250
var result = CheckFurnace250().Result;
if (!result.status)
{
var notification = new
{
title = "Статус ПШП ст.250",
message = result.msg,
priority = 5
};
await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword);
}
#endregion
#region check billets 250
result = CheckRoughToFinishedBilletCount().Result;
if (!result.status)
{
var notification = new
{
title = "Статус мониторинга ст.250",
message = result.msg,
priority = 5
};
await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword);
}
#endregion
}
private static async Task<(bool status, string msg)> CheckRoughToFinishedBilletCount()
{
int cntBillets = 0;
const string sqlConn = "User Id=main;Password=main;Data Source=10.14.18.50:1521/izl2;";
try
{
using (var conn = new OracleConnection(sqlConn))
{
await conn.OpenAsync();
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM V_TRACKING_MILL";
cntBillets = Convert.ToInt32(await command.ExecuteScalarAsync());
}
}
}
catch (Exception ex)
{
return (false, ex.Message);
}
if (cntBillets > 15)
{
return (false, $"Заготовок в стане - {cntBillets}");
}
return (true, "OK");
}
private static async Task<(bool status, string msg)> CheckFurnace250()
{
int cntEmptyPOID = 0;
DateTime lastDT = DateTime.Now;
const string sqlConn = @"Password=WonderUser;User ID=WonderUser;Initial Catalog=Furnace_l2;Data Source=10.14.18.38\IZHSTALSQLSRVER;TrustServerCertificate=true;Encrypt=true;";
try
{
using (var conn = new SqlConnection(sqlConn))
{
await conn.OpenAsync();
string sqlQuery = @"SELECT
COUNT(PO_ID) cnt_empty_poid,
(
SELECT
top(1) CHARGING_TIME
FROM
[Furnace_l2].[dbo].[HIST_PIECES]
WHERE
[IS_DISCHARGED] = 'N'
AND datediff(DAY, CHARGING_TIME, Getdate()) < 1
AND RTRIM(LTRIM(PO_ID)) != ''
ORDER BY
CHARGING_TIME DESC
) last_dt
FROM
[Furnace_l2].[dbo].[HIST_PIECES]
WHERE
[IS_DISCHARGED] = 'N'
AND datediff(DAY, CHARGING_TIME, Getdate()) < 1
AND RTRIM(LTRIM(PO_ID)) = '';";
using (var command = new SqlCommand(sqlQuery, conn))
using (var dbReader = await command.ExecuteReaderAsync())
{
while (await dbReader.ReadAsync())
{
if (dbReader.GetValue(0) != DBNull.Value && dbReader.GetValue(1) != DBNull.Value)
{
cntEmptyPOID = Convert.ToInt32(dbReader.GetValue(0));
lastDT = Convert.ToDateTime(dbReader.GetValue(1));
}
}
}
}
}
catch (Exception ex)
{
return (false, ex.Message);
}
if (cntEmptyPOID > 15 && DateTime.Now - lastDT > new TimeSpan(0, 5, 0))
{
return (false, $"Проблема с привязкой ID заготовок в ПШП. Не привязанных - {cntEmptyPOID}, время последней привязанной - {lastDT}");
}
return (true, "OK");
}
private static async Task SendNotify(string url, string token, object notification, string proxyUrl, string proxyUsername, string proxyPassword)
{
var proxy = new WebProxy(new Uri(proxyUrl))
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword, "MECHEL")
};
var handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true,
UseDefaultCredentials = false
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Add("X-Gotify-Key", token);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(notification);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var requestUrl = $"{url}/message";
HttpResponseMessage response = await client.PostAsync(requestUrl, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"{DateTime.Now} - Отправлено сообщение.");
Log.Logger($"Отправлено сообщение.");
}
else
{
Console.WriteLine($"Ошибка: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
Log.Logger($"Ошибка: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
}
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Ошибка подключения: {ex.Message}");
Log.Logger($"Ошибка подключения: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Детали: {ex.InnerException.Message}");
Log.Logger($"Детали: {ex.InnerException.Message}");
}
}
}
}
private static async Task<(bool status, GotifyMessage msg)> ReceiveMessagesAsync(
string url,
string token,
string proxyUrl,
string proxyUsername,
string proxyPassword,
int targetPriority)
{
var proxy = new WebProxy(new Uri(proxyUrl))
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword, "MECHEL")
};
var handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true,
UseDefaultCredentials = false
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Add("X-Gotify-Key", token);
var requestUrl = $"{url}/message?limit=100";
try
{
var response = await client.GetAsync(requestUrl);
if (response.IsSuccessStatusCode)
{
var messages = await response.Content.ReadFromJsonAsync<GotifyMessagesResponse>();
var filtered = messages.Messages?
.Where(m => m.Priority == targetPriority)
.OrderByDescending(m => m.Date)
.ToList();
if (filtered?.Count > 0)
{
var lastMsg = filtered.First();
return (true, lastMsg);
}
return (false, null);
}
Console.WriteLine($"Ошибка HTTP: {response.StatusCode}");
return (false, null);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка: {ex.Message}");
Log.Logger($"Ошибка получения сообщений: {ex.Message}");
return (false, null);
}
}
}
public class GotifyMessagesResponse
{
public required List<GotifyMessage> Messages { get; set; }
}
public class GotifyMessage
{
public string? Title { get; set; }
public string? Message { get; set; }
public int Priority { get; set; }
public DateTime Date { get; set; }
}
}