chip-game/Assets/Scripts/ExternalFilesGetter.cs
2026-01-12 09:36:17 +03:00

275 lines
9.3 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.IO;
using System.Linq;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public static class ExternalFilesGetter
{
const string GAMEDATA_FOLDER = "C4";
const string IMAGES_DIR = "Images";
const string SERIAL_PATH = "serialdata.dat";
const string OVERRIDES_FILE = "overrides/Light.conf";
const string ELEKTRO_VERSION_FILE = "elektro_version.rr";
const string SENSOR_VERSION_FILE = "HopperSensor.rr";
/// <summary>
///
/// </summary>
/// <param name="spriteName">передавать без расширения</param>
/// <returns></returns>
public static Sprite GetChipSprite(string spriteName)
{
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path = Path.Combine(docPath, GAMEDATA_FOLDER,IMAGES_DIR, spriteName+".png");
//проверить есть ли файл
if (File.Exists(path))
{
var bytes = File.ReadAllBytes(path);
var tex = new Texture2D(2,2,TextureFormat.ARGB32, false);
tex.LoadImage(bytes);
tex.filterMode = FilterMode.Point;
var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0.5f, 0.5f),pixelsPerUnit: 625);
return sprite;
}
else
{
Debug.LogWarning($"Не найден файл {spriteName}");
return null;
}
}
/// <summary>
/// Читает серийные данные из файла serialdata.dat
/// </summary>
/// <returns>Текст из файла или "<не указано>", если файл не существует</returns>
public static string GetSerial()
{
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(docPath, GAMEDATA_FOLDER, SERIAL_PATH);
try
{
// Проверяем существование файла
if (!File.Exists(filePath))
{
Debug.LogWarning($"Файл serialdata.dat не найден по пути: {filePath}");
return "<не указано>";
}
// Читаем весь текст из файла
string serialData = File.ReadAllText(filePath);
// Убираем лишние пробелы и проверяем на пустоту
if (string.IsNullOrWhiteSpace(serialData))
{
Debug.LogWarning("Файл serialdata.dat пуст");
return "<не указано>";
}
return serialData.Trim();
}
catch (Exception ex)
{
Debug.LogError($"Ошибка при чтении файла serialdata.dat: {ex.Message}");
return "<не указано>";
}
}
public static string GetLightVersion()
{
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(docPath, GAMEDATA_FOLDER, OVERRIDES_FILE);
try
{
// Проверяем существование файла
if (!File.Exists(filePath))
{
Debug.LogWarning($"Файл не найден по пути: {filePath}");
return "";
}
// Читаем весь текст из файла
string serialData = File.ReadAllText(filePath);
// Убираем лишние пробелы и проверяем на пустоту
if (string.IsNullOrWhiteSpace(serialData))
{
Debug.LogWarning("Файл пуст");
return "";
}
return serialData.Trim();
}
catch (Exception ex)
{
Debug.LogError($"Ошибка при чтении файла: {ex.Message}");
return "";
}
}
public static string ReadBotsAmountHash()
{
try
{
// Получаем путь к файлу Documents\C4\BotsAmount.rr
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(documentsPath, "C4", "BotsAmount.rr");
// Проверяем существование файла
if (!File.Exists(filePath))
{
Console.WriteLine($"Файл не найден: {filePath}");
return null;
}
// Считываем содержимое файла
string hash = File.ReadAllText(filePath).Trim();
// Выводим отладочную информацию
Console.WriteLine($"Файл прочитан: {filePath}");
Console.WriteLine($"Хэш: {hash}");
Console.WriteLine($"Длина хэша: {hash.Length}");
return hash;
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при чтении файла: {ex.Message}");
return null;
}
}
public static string GetMacAddressPythonStyle()
{
try
{
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var nic in nics)
{
var addr = nic.GetPhysicalAddress();
if (addr != null && addr.GetAddressBytes().Length == 6)
{
// Форматирование в XX:XX:XX:XX:XX:XX
byte[] bytes = addr.GetAddressBytes();
return string.Join(":", bytes.Select(b => b.ToString("X2")));
}
}
}
catch
{
// ignore
}
return "00:00:00:00:00:00";
}
public static string GetElektroVersion()
{
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(docPath, GAMEDATA_FOLDER, ELEKTRO_VERSION_FILE);
try
{
// Проверяем существование файла
if (!File.Exists(filePath))
{
Debug.LogWarning($"Файл {ELEKTRO_VERSION_FILE} не найден по пути: {filePath}");
return string.Empty;
}
// Читаем содержимое файла
string versionData = File.ReadAllText(filePath).Trim();
// Убираем лишние пробелы и проверяем на пустоту
if (string.IsNullOrWhiteSpace(versionData))
{
Debug.LogWarning($"Файл {ELEKTRO_VERSION_FILE} пуст");
return string.Empty;
}
// Проверяем содержимое файла
Debug.Log($"Считана версия подключения кнопок: {versionData}");
return versionData;
}
catch (Exception ex)
{
Debug.LogError($"Ошибка при чтении файла {ELEKTRO_VERSION_FILE}: {ex.Message}");
return string.Empty;
}
}
public static char GetSensorPositiveValue()
{
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filePath = Path.Combine(docPath, GAMEDATA_FOLDER, SENSOR_VERSION_FILE);
char china_hopper_positive = '0'; //позитивное значение для китайских хопперов (Нормально разомкнутый (по умолчанию)
char ru_hopper_positive = '1'; //позитивное значение для русского хоппера (Нормально замкнутый)
try
{
// Проверяем существование файла
if (!File.Exists(filePath))
{
Debug.LogWarning($"Файл {SENSOR_VERSION_FILE} не найден по пути: {filePath}");
return china_hopper_positive;
}
// Читаем содержимое файла
string versionData = File.ReadAllText(filePath).Trim();
// Убираем лишние пробелы и проверяем на пустоту
if (string.IsNullOrWhiteSpace(versionData))
{
Debug.LogWarning($"Файл {SENSOR_VERSION_FILE} пуст");
return china_hopper_positive;
}
char result = china_hopper_positive;
switch (versionData)
{
case "1":
result = china_hopper_positive;
break;
case "2":
result = ru_hopper_positive;
break;
default:
result = china_hopper_positive;
break;
}
return result;
}
catch (Exception ex)
{
Debug.LogError($"Ошибка при чтении файла {SENSOR_VERSION_FILE}: {ex.Message}");
return china_hopper_positive;
}
}
}