This repository was archived by the owner on Nov 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBot.cs
More file actions
172 lines (140 loc) · 7.08 KB
/
Bot.cs
File metadata and controls
172 lines (140 loc) · 7.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
using Newtonsoft.Json;
using System.Drawing;
using System.Net.WebSockets;
using System.Text;
namespace PxlsAutomaton
{
public class Bot
{
public Config BotConfig = null;
public Ditherer Ditherer = new Ditherer();
public Loader Loader = new Loader();
public ClientWebSocket SocketClient = new ClientWebSocket();
public Bitmap TargetImage = null;
public void LoadConfig()
{
if (!File.Exists("config.json"))
{
Logger.Log("Configuration file is missing. Writing default one.", LogSeverity.Error);
BotConfig = new Config();
JsonSerializerSettings SerializerSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented
};
string DefaultJson = JsonConvert.SerializeObject(BotConfig, SerializerSettings);
File.WriteAllText("config.json", DefaultJson);
BotConfig = null;
return;
}
BotConfig = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
if (BotConfig == null) Logger.Log("Error loading configuration file.", LogSeverity.Error);
}
public async Task InitializeBot()
{
if (BotConfig == null) return;
if (BotConfig.PixelDelay < 50)
Logger.Log($"A pixel delay of [bold lightgoldenrod2_2]{BotConfig.PixelDelay}ms[/] may cause timing issues. " +
$"Please set it to [bold lightgoldenrod2_2]50ms[/] or more.", LogSeverity.Warning);
if (BotConfig.ImageWidth <= 0 || BotConfig.ImageHeight <= 0) Logger.Log($"Downloading and resizing image from [bold dodgerblue1]{BotConfig.ImageUrl}[/]...", LogSeverity.Message);
else Logger.Log($"Downloading image from [bold dodgerblue1]{BotConfig.ImageUrl}[/]...", LogSeverity.Message);
Bitmap DownloadedBitmap = Loader.DownloadImageAndResize(BotConfig.ImageUrl, BotConfig.ImageWidth, BotConfig.ImageHeight);
if (DownloadedBitmap == null) return;
Logger.Log("Downloaded image successfully!", LogSeverity.Success);
Logger.Log("Dithering image...", LogSeverity.Message);
TargetImage = Ditherer.ExecuteFloydSteinberg(ref DownloadedBitmap);
Logger.Log("Image dithered successfully!", LogSeverity.Success);
Logger.Log($"Attempting to open websocket connection to \"[bold dodgerblue1]{BotConfig.PxlsUrl}[/]\"...", LogSeverity.Message);
try
{
CancellationTokenSource TimeoutToken = new CancellationTokenSource();
TimeoutToken.CancelAfter(5000);
TimeoutToken.Token.ThrowIfCancellationRequested();
await SocketClient.ConnectAsync(new Uri(BotConfig.PxlsUrl), TimeoutToken.Token);
Console.Title = $"PxlsAutomaton - Connected to {BotConfig.PxlsUrl}";
Logger.Log("Connection established successfully!", LogSeverity.Success);
Task.WaitAll(SendThread(), ReceiveThread());
}
catch (Exception ex)
{
Logger.Log("[bold]ERROR:[/] " + ex.Message, LogSeverity.Error);
}
finally
{
if (SocketClient != null) SocketClient.Dispose();
if (DownloadedBitmap != null) DownloadedBitmap.Dispose();
if (TargetImage != null) TargetImage.Dispose();
if (File.Exists(Loader.LoadedImage)) File.Delete(Loader.LoadedImage);
}
}
private async Task SendThread()
{
TimeSpan TotalMilliseconds = TimeSpan.FromMilliseconds(TargetImage.Width * TargetImage.Height * BotConfig.PixelDelay);
int TotalPixels = TargetImage.Width * TargetImage.Height;
Logger.Log($"Drawing {TargetImage.Width}x{TargetImage.Height} dithered image " +
$"at ({BotConfig.PositionX}, {BotConfig.PositionY}) with {BotConfig.PixelDelay}ms delay...", LogSeverity.Message);
Logger.Log($"Drawing this image will take approximately [bold dodgerblue1]{TotalMilliseconds:hh} hour(s)[/], " +
$"[bold dodgerblue1]{TotalMilliseconds:mm} minute(s)[/] and [bold dodgerblue1]{TotalMilliseconds:ss} second(s)[/].", LogSeverity.Message);
for (int y = 0; y < TargetImage.Height; y++)
{
for (int x = 0; x < TargetImage.Width; x++)
{
if (SocketClient.State != WebSocketState.Open) throw new Exception("Lost connection to websocket.");
CancellationTokenSource SendTimeoutToken = new CancellationTokenSource();
SendTimeoutToken.CancelAfter(5000);
SendTimeoutToken.Token.ThrowIfCancellationRequested();
Color PixelColor = TargetImage.GetPixel(x, y);
int ColorIndex = Ditherer.ColorPalette[PixelColor];
Pixel PixelRequest = new Pixel()
{
Type = "pixel",
X = x + BotConfig.PositionX,
Y = y + BotConfig.PositionY,
Color = ColorIndex
};
string JsonPixel = JsonConvert.SerializeObject(PixelRequest);
await SocketClient.SendAsync(Encoding.UTF8.GetBytes(JsonPixel), WebSocketMessageType.Text, true, SendTimeoutToken.Token);
await Task.Delay(BotConfig.PixelDelay);
}
}
Logger.Log("Image has been drawn successfully!", LogSeverity.Success);
await SocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
private async Task ReceiveThread()
{
byte[] buffer = new byte[64];
while (SocketClient.State == WebSocketState.Open)
{
try
{
WebSocketReceiveResult result = await SocketClient.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close) await SocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
catch (Exception)
{
//Do nothing. Receiving is not as important as sending.
}
}
}
}
public class Config
{
public string ImageUrl { get; set; }
public int ImageWidth { get; set; }
public int ImageHeight { get; set; }
public int PositionX { get; set; }
public int PositionY { get; set; }
public int PixelDelay { get; set; }
public string PxlsUrl { get; set; }
}
public class Pixel
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("x")]
public int X { get; set; }
[JsonProperty("y")]
public int Y { get; set; }
[JsonProperty("color")]
public int Color { get; set; }
}
}