/
Program.cs
339 lines (258 loc) · 12.5 KB
/
Program.cs
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Runtime.Loader;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
/*
https://arnowelzel.de/wp/en/control-av-receivers-by-pioneer-over-the-network
*/
namespace PioPi
{
public class SynchronousSocketClient {
// State object for receiving data from remote device.
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient {
// The port number for the remote device.
private const int port = 8102;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static AutoResetEvent sendDone = new AutoResetEvent(false);
private static Socket _client = null;
public static void StopClient()
{
// Release the socket.
_client.Shutdown(SocketShutdown.Both);
_client.Close();
_isRunning = false;
}
private static bool _isRunning = false;
public static bool IsRunning
{
get { return _isRunning; }
}
private static void StartClient() {
// Connect to a remote device.
try {
_isRunning = true;
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry("vsx1123.bem.lan");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
_client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
_client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), _client);
connectDone.WaitOne();
// Create the state object.
StateObject state = new StateObject();
state.workSocket = _client;
// Begin receiving the data from the remote device.
_client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
// Send test data to the remote device. POWERSTATUS
Send("?P\r\n");
sendDone.WaitOne();
// Send test data to the remote device. AUDIOINFO
Send("?AST\r\n");
sendDone.WaitOne();
// Send test data to the remote device. INPUTSOURCE
Send("?F\r\n");
sendDone.WaitOne();
// Send test data to the remote device. VOLUMESTATUS
Send("?V\r\n");
sendDone.WaitOne();
// Send test data to the remote device. LISTENINGMODE
Send("?L\r\n");
sendDone.WaitOne();
// Send test data to the remote device. AUDIODELAY
Send("?ATF\r\n");
sendDone.WaitOne();
} catch (Exception e) {
Console.WriteLine(e.ToString());
_isRunning = false;
}
}
private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
}
if (state.sb.Length > 0)
{
int index = state.sb.ToString().IndexOf("\r\n");
while (index >= 0)
{
// The response from the remote device.
string response = state.sb.ToString().Substring(0,index);
if (state.sb.Length == index+2)
{
state.sb.Clear();
}
else
{
state.sb.Remove(0,index+2);
}
if (response.Length > 0)
{
// Signal that all bytes have been received.
DataReceived(response);
}
index = state.sb.ToString().IndexOf("\r\n");
}
}
// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private static void Send(String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
_client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), _client);
}
private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
//Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public static IReceiver _pioVSX;
public static int Main(String[] args) {
AssemblyLoadContext.Default.Unloading += SigTermEventHandler; //register sigterm event handler. Don't forget to import System.Runtime.Loader!
Console.CancelKeyPress += CancelHandler; //register sigint event handler
List<InputSourceProperties> inputSources = new List<InputSourceProperties>();
IConfiguration config;
string logFile = "";
try
{
config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", optional:false, reloadOnChange:true)
.Build();
logFile = $"/home/piopi/piopi.log";
}
catch
{
config = new ConfigurationBuilder()
.AddJsonFile($"/home/bas/Projects/PioPi/appsettings.json", optional:false, reloadOnChange:true)
.Build();
logFile = $"/home/bas/Projects/PioPi/piopi.log";
}
foreach ( string item in Enum.GetNames(typeof(PioPi.PioVSX.InputSource)))
{
string name = config[$"InputSource:{item}:Name"];
if (name != null)
{
int volume = -1;
bool isWebradio = false;
int.TryParse(config[$"InputSource:{item}:Volume"], out volume);
isWebradio = ((config[$"InputSource:{item}:IsWebRadio"])?.ToLower() == "true");
InputSourceProperties inputSource = new InputSourceProperties();
inputSource.Source = (PioPi.PioVSX.InputSource)Enum.Parse(typeof(PioPi.PioVSX.InputSource), item);
inputSource.Name = name;
inputSource.Volume = volume;
inputSource.IsWebradio = isWebradio;
inputSources.Add(inputSource);
}
}
_pioVSX = new PioVSX(inputSources,logFile);
_pioVSX.SendInformationEvent += InformationEventHandler;
_pioVSX.SendResponseEvent += ResponseEventHandler;
_pioVSX.Start();
StartClient();
while (IsRunning)
{
Thread.Sleep(2000);
}
_pioVSX.Stop();
_pioVSX.SendInformationEvent -= InformationEventHandler;
_pioVSX.SendResponseEvent -= ResponseEventHandler;
_pioVSX = null;
return 0;
}
private static void SigTermEventHandler(AssemblyLoadContext obj)
{
System.Console.WriteLine("Unloading...");
StopClient();
}
private static void CancelHandler(object sender, ConsoleCancelEventArgs e)
{
System.Console.WriteLine("Exiting...");
StopClient();
}
public static int _responseNumber = 0;
public static void DataReceived(string data)
{
_pioVSX.ProcessData(data);
}
public static void InformationEventHandler(Object sender, InfoEventArgs e)
{
_responseNumber +=1;
if (!String.IsNullOrWhiteSpace(e.Data))
{
Console.WriteLine($"{_responseNumber.ToString("00000")} {DateTime.Now.ToString("yyyyMMdd.HHmmss")}: {e.Data}");
}
}
public static void ResponseEventHandler(Object sender, SendResponseEventArgs e)
{
if (!String.IsNullOrWhiteSpace(e.Data))
{
if (e.TimeToWaitBeforeSend > 0)
{
Thread.Sleep(e.TimeToWaitBeforeSend);
}
Console.WriteLine($" >>>> SENDDATA: {e.Data}");
// Send test data to the remote device.
Send($"{e.Data}\r\n");
sendDone.WaitOne();
}
}
}
}
}