Files
SendNotify/Program.cs
2025-04-15 10:07:07 +04:00

173 lines
6.9 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 SendNotify;
using System.Data.SqlClient;
using System.Net;
using System.Text;
internal class Program
{
private static DateTime lastDate = DateTime.MinValue;
private static void Main(string[] args)
{
while (true)
{
string? gotifyUrl = null;
string? appToken_izhstal = null;
string? proxyUrl = null;
string? proxyUsername = null;
string? proxyPassword = null;
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);
}
if (gotifyUrl == null || appToken_izhstal == null || proxyUrl == null || proxyUsername == null || proxyPassword == null)
{
Console.WriteLine("Ошибка: не все параметры указаны в config.txt");
Log.Logger("Ошибка: не все параметры указаны в config.txt");
}
else
NotifyPollingAsync(gotifyUrl, appToken_izhstal, proxyUrl, proxyUsername, proxyPassword);
Thread.Sleep(60000);
}
}
private static async void NotifyPollingAsync(string url, string token, string proxyUrl, string proxyUsername, string proxyPassword)
{
#region check furnace 250
DateTime now = DateTime.Now;
var result = CheckFurnace250Async().Result;
if (!result.status)
{
var notification = new
{
title = "Статус ПШП ст.250",
message = result.msg,
priority = 5
};
await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword);
}
#endregion
#region test msg to check
if (now.Hour == 8 && now.Date != lastDate.Date)
{
var notification = new
{
title = "Test notify",
message = "IS OK",
priority = 3
};
await SendNotify(url, token, notification, proxyUrl, proxyUsername, proxyPassword);
lastDate = now;
}
#endregion
}
private static async Task<(bool status, string msg)> CheckFurnace250Async()
{
int cntEmptyPOID = 0;
DateTime lastDT = DateTime.Now;
try
{
string sqlConn = @"Password=WonderUser;User ID=WonderUser;Initial Catalog=Furnace_l2;Data Source=10.14.18.38\IZHSTALSQLSRVER;TrustServerCertificate=true;Encrypt=true;";
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())
{
cntEmptyPOID = Convert.ToInt32(dbReader.GetValue(0));
lastDT = Convert.ToDateTime(dbReader.GetValue(1));
}
}
}
}
catch
{
return (false, "Ошибка подключения к БД!");
}
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
{
HttpResponseMessage response = await client.PostAsync(url, 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}");
}
}
}
}
}