Skip to content

Commit

Permalink
Use await-sync instead of CoRoutine, remove csharp-wescoket
Browse files Browse the repository at this point in the history
  • Loading branch information
hypergori committed Nov 2, 2018
1 parent 150b494 commit 534e8c8
Show file tree
Hide file tree
Showing 4 changed files with 178 additions and 102 deletions.
9 changes: 7 additions & 2 deletions BtcPayClient.sln
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
# Visual Studio 15
VisualStudioVersion = 15.0.28010.2016
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BtcPayClient", "BtcPayService\BtcPayClient.csproj", "{D88A49C3-0280-4320-B120-AE519B2DB219}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BtcPayServiceTest", "BtcPayServiceTest\BtcPayServiceTest.csproj", "{71166BF5-DA31-4BFD-90E6-16172E894EAA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BtcPayClientSample", "BtcPayClient\BtcPayClientSample.csproj", "{7069D12D-4D07-4CE4-A0BF-406D599CD2F0}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5318CC2B-36CF-42E4-A3A3-6E09187F9887}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -31,4 +33,7 @@ Global
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B35FA3C1-F2C5-4E03-96F5-82C0DA9E0B42}
EndGlobalSection
EndGlobal
22 changes: 15 additions & 7 deletions BtcPayClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ class Program
{
static void Main(string[] args)
{
String pairingCode = "vT5iJ1b";
BTCPayClient bitpay = new BTCPayClient(pairingCode);
String pairingCode = "uGhQ6vx";
String host = "btcpaytest.indiesquare.net";
BTCPayClient bitpay = new BTCPayClient(pairingCode,host);

//New Invoice Prep
Invoice invoice = new Invoice(1.0, "USD");
Expand All @@ -35,14 +36,21 @@ static void Main(string[] args)
Invoice inv = bitpay.getInvoice(invoice.Id, BTCPayClient.FACADE_MERCHANT);

//Subscribe Invoice to change
Task<Invoice> t = bitpay.GetInvoiceAsync(invoice.Id);
Console.WriteLine(t.Status);
Task t = bitpay.subscribeInvoiceAsync(invoice.Id, printInvoice);
t.Wait();
Invoice invo = t.Result;
Console.WriteLine(t.Status);

Console.WriteLine(t.Status);

Console.WriteLine(invo.Url);
Console.WriteLine(invo.ToString());
}

public static async Task printInvoice(Invoice invoice)
{
Console.WriteLine("payment is not completed:" + invoice.Status);
Console.WriteLine(invoice.Url);
Console.WriteLine(invoice.ToString());
await Task.Delay(1000);
return;
}
}
}
245 changes: 156 additions & 89 deletions BtcPayService/BtcPayClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using BitCoinSharp;
using System.Collections;
using System.Net.WebSockets;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand All @@ -11,11 +11,9 @@
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using WebSocketSharp;
using UnityEngine;
using ZXing;
using ZXing.QrCode;
using BtcPayApi;

/**
* @author Andy Phillipson
Expand All @@ -32,8 +30,7 @@ public class BTCPayClient
private const String BITPAY_API_VERSION = "2.0.0";
private const String BITPAY_PLUGIN_INFO = "BTCPay CSharp Client " + BITPAY_API_VERSION;
// private const String BITPAY_URL = "https://bitpay.com/";
// public const String HOST = "btcpaytest.indiesquare.net";
public const String HOST = "btcpayreg.indiesquare.net";
public const String HOST = "";
private const String BITPAY_URL = "https://"+HOST+"/";

public const String FACADE_PAYROLL = "payroll";
Expand All @@ -49,8 +46,10 @@ public class BTCPayClient
private String _clientName = "";
private Dictionary<string, string> _tokenCache; // {facade, token}

private List<WebSocket> _wsList = new List<WebSocket>();
private String pairingCode = "";
// private WebSocketManager webSocketManager = new WebSocketManager();
// private Dictionary<string, ClientWebSocket> _wsMap = new Dictionary<string, ClientWebSocket>();


/// <summary>
/// Constructor for use if the keys and SIN are managed by this library.
Expand Down Expand Up @@ -225,48 +224,47 @@ public Invoice getInvoice(String invoiceId, String facade = FACADE_POS)
return JsonConvert.DeserializeObject<Invoice>(this.responseToJsonString(response));
}

public async Task<Invoice> GetInvoiceAsync(String invoiceId)
{
return await Task.Run( () => getInvoiceByWS(invoiceId));
}

private Invoice getInvoiceByWS(String invoiceId)
{
Invoice inv = null;
//WebSocket loop
using (var ws = new WebSocket("wss://" + _serverHost + "/i/" + invoiceId + "/status/ws"))
{
ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
ws.OnMessage += (sender, e) =>
{
Console.WriteLine("WS Message: " + e.Data);
//Get Invoice
inv = getInvoice(invoiceId, BTCPayClient.FACADE_MERCHANT);
ws.Close();
};
ws.OnClose += (sender, e) =>
{
//Console.WriteLine("WS Closed: " + e.Code);
};
ws.OnError += (sender, e) =>
{
//Console.WriteLine("WS Err: " + e.Exception);
};
ws.OnOpen += (sender, e) =>
Console.WriteLine("WS Opened.");

ws.Connect();

while (ws.IsAlive)
{
Thread.Sleep(500);
Console.WriteLine("Sleep 500ms.");
}
}//Close websocket
return inv;

}

//public async Task<Invoice> GetInvoiceAsync(String invoiceId)
//{
// return await Task.Run( () => getInvoiceByWS(invoiceId));
//}

//private Invoice getInvoiceByWS(String invoiceId)
//{
// Invoice inv = null;
// //WebSocket loop
// using (var ws = new WebSocketSharp.WebSocket("wss://" + _serverHost + "/i/" + invoiceId + "/status/ws"))
// {
// ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
// ws.OnMessage += (sender, e) =>
// {
// Console.WriteLine("WS Message: " + e.Data);
// //Get Invoice
// inv = getInvoice(invoiceId, BTCPayClient.FACADE_MERCHANT);
// ws.Close();
// };
// ws.OnClose += (sender, e) =>
// {
// //Console.WriteLine("WS Closed: " + e.Code);
// };
// ws.OnError += (sender, e) =>
// {
// //Console.WriteLine("WS Err: " + e.Exception);
// };
// ws.OnOpen += (sender, e) =>
// Console.WriteLine("WS Opened.");

// ws.Connect();

// while (ws.IsAlive)
// {
// Thread.Sleep(500);
// Console.WriteLine("Sleep 500ms.");
// }
// }//Close websocket
// return inv;
//
// }

/// <summary>
/// Retrieve a list of invoices by date range using the merchant facade.
Expand Down Expand Up @@ -464,58 +462,127 @@ public Settlement getSettlementReconciliationReport(Settlement settlement)
return JsonConvert.DeserializeObject<Settlement>(responseToJsonString(response));
}

public IEnumerator subscribeInvoice(string invoiceId, Action<Invoice> actionOnInvoice, MonoBehaviour mb)
{
CoroutineWithData cd = new CoroutineWithData(mb, SubscribeInvoiceCoroutine(invoiceId));
yield return cd.coroutine;

Debug.Log("BtcPayUnity: Invoice Result is " + cd.result);
//public IEnumerator subscribeInvoice(string invoiceId, Action<Invoice> actionOnInvoice, MonoBehaviour mb)
//{
// CoroutineWithData cd = new CoroutineWithData(mb, SubscribeInvoiceCoroutine(invoiceId));
// yield return cd.coroutine;

// Debug.Log("BtcPayUnity: Invoice Result is " + cd.result);

// Invoice resultInv = (Invoice)cd.result;
// actionOnInvoice(resultInv);
//}
//private IEnumerator SubscribeInvoiceCoroutine(string invoiceId)
//{
// Invoice inv = null;
// //WebSocket loop

// using (var ws = new WebSocket("wss://" + _serverHost + "/i/" + invoiceId + "/status/ws"))
// {
// ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
// ws.OnMessage += (sender, e) =>
// {
// Debug.Log("BtcPayUnity:WS Message: " + e.Data);
// //Get Invoice
// // inv = getInvoice(invoiceId, BTCPay.FACADE_MERCHANT);
// inv = getInvoice(invoiceId, BTCPayClient.FACADE_MERCHANT);
// Debug.Log("BtcPayUnity:Got invoice : " + inv.Status);
// ws.Close();
// };
// ws.OnClose += (sender, e) =>
// {
// //Console.WriteLine("WS Closed: " + e.Code);
// };
// ws.OnError += (sender, e) =>
// {
// //Console.WriteLine("WS Err: " + e.Exception);
// };
// ws.OnOpen += (sender, e) =>
// Debug.Log("BtcPayUnity:WS Opened.");

// ws.Connect();

// ////Wait connection is closed when invoice is gotten or exception
// //while (ws.IsAlive)
// //{
// // //Thread.Sleep(500);
// // yield return new WaitForSeconds(0.5f);
// // Debug.Log("BtcPayUnity:Websocket Sleep 500ms.");
// //}
// }//Close websocket
// yield return inv;
//}


public async Task subscribeInvoiceAsync(string invoiceId, Func<Invoice, Task> actionOnInvoice)
{

await SubscribeInvoiceAsync(invoiceId, actionOnInvoice);
}

// private async Task SubscribeInvoiceAsync(string invoiceId, Action<Invoice> actionOnInvoice)
private async Task SubscribeInvoiceAsync(string invoiceId, Func<Invoice,Task> actionOnInvoice)
{
Uri serverUri = new Uri("wss://" + _serverHost + "/i/" + invoiceId + "/status/ws");
// ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(serverUri, CancellationToken.None);
Invoice invoice = await ReceiveAsync(webSocket, invoiceId);
await actionOnInvoice(invoice);
}
catch(Exception ex)
{
Debug.Log("Exception:"+ ex.ToString());
}
finally
{
if (webSocket != null) webSocket.Dispose();
Debug.Log("Web Socket Closed");
}

Invoice resultInv = (Invoice)cd.result;
actionOnInvoice(resultInv);
}

private IEnumerator SubscribeInvoiceCoroutine(string invoiceId)
private async Task<Invoice> ReceiveAsync(ClientWebSocket webSocket,string invoiceId)
{
Invoice inv = null;
// string _serverHost = "btcpayreg.indiesquare.net";
//WebSocket loop
using (var ws = new WebSocket("wss://" + _serverHost + "/i/" + invoiceId + "/status/ws"))
byte[] buffer = new byte[1024];
while(webSocket.State == System.Net.WebSockets.WebSocketState.Open)
{
ws.SslConfiguration.EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12;
ws.OnMessage += (sender, e) =>
{
Debug.Log("BtcPayUnity:WS Message: " + e.Data);
//Get Invoice
// inv = getInvoice(invoiceId, BTCPay.FACADE_MERCHANT);
inv = getInvoice(invoiceId, BTCPayClient.FACADE_MERCHANT);
Debug.Log("BtcPayUnity:Got invoice : " + inv.Status);
ws.Close();
};
ws.OnClose += (sender, e) =>
{
//Console.WriteLine("WS Closed: " + e.Code);
};
ws.OnError += (sender, e) =>
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if(result.MessageType == WebSocketMessageType.Close)
{
//Console.WriteLine("WS Err: " + e.Exception);
};
ws.OnOpen += (sender, e) =>
Debug.Log("BtcPayUnity:WS Opened.");

ws.Connect();

//Wait connection is closed when invoice is gotten or exception
while (ws.IsAlive)
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
//Thread.Sleep(500);
yield return new WaitForSeconds(0.5f);
Debug.Log("BtcPayUnity:Websocket Sleep 500ms.");
Debug.Log("webSocket MessageType : " + result.MessageType);
string msg = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
Debug.Log("Receive : " + msg);
inv = getInvoice(invoiceId, BTCPayClient.FACADE_MERCHANT);
Debug.Log("BtcPayUnity:Got invoice with status: " + inv.Status);
break;
}
}//Close websocket
yield return inv;
}
return inv;
}



//public void printws()
//{
// Debug.Log("Number of ws:" + _wsMap.Count);
// if(_wsMap.Count> 0)
// {
// foreach(var entry in _wsMap)
// {
// Debug.Log("ws status:" + entry.Value.IsAlive);
// }
// }
//}

private static Color32[] Encode(string textForEncoding,
int width, int height)
{
Expand Down
4 changes: 0 additions & 4 deletions BtcPayService/BtcPayClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,6 @@
<Reference Include="UnityEngine">
<HintPath>..\..\..\..\..\Program Files\Unity2018\Editor\Data\Managed\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="websocket-sharp, Version=1.0.2.4712, Culture=neutral, PublicKeyToken=5660b08a1845a91e, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\websocket-sharp.dll</HintPath>
</Reference>
<Reference Include="zxing.unity">
<HintPath>..\packages\zxing.unity.dll</HintPath>
</Reference>
Expand Down

0 comments on commit 534e8c8

Please sign in to comment.