Commit f9e08c84 by liulongfei

引入HTTP辅助类

添加包装程序集
parent e117582f
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Newtonsoft.Json;
namespace VIZ.Framework.Core
{
/// <summary>
/// HTTP辅助类
/// </summary>
public static class HttpHelper
{
/// <summary>
/// 日志
/// </summary>
private static readonly ILog log = LogManager.GetLogger(typeof(HttpHelper));
/// <summary>
/// 缓存字节大小
/// </summary>
private static readonly int BUFFER_SIZE = 10 * 1024;
/// <summary>
/// 超时时间
/// </summary>
private static readonly int TIME_OUT = 10 * 1000;
/// <summary>
/// Get请求
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="url">请求url</param>
/// <returns>返回数据</returns>
public static string Get(string url, CookieContainer cookie)
{
try
{
using (HttpClientHandler handler = new HttpClientHandler())
{
using (HttpClient client = new HttpClient(handler))
{
if (cookie != null)
{
handler.UseCookies = true;
handler.CookieContainer = cookie;
}
client.Timeout = TimeSpan.FromMilliseconds(TIME_OUT);
using (HttpResponseMessage response = client.GetAsync(url).Result)
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
string json = sr.ReadToEnd();
return json;
}
}
}
}
catch (Exception ex)
{
log.Error(ex);
return null;
}
}
/// <summary>
/// Get请求
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="url">请求url</param>
/// <returns>返回json对象</returns>
public static T Get<T>(string url, CookieContainer cookie) where T : class
{
try
{
string json = Get(url, cookie);
if (string.IsNullOrWhiteSpace(json))
return null;
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
log.Error(ex);
return null;
}
}
/// <summary>
/// Post请求
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="url">请求url</param>
/// <param name="content">请求内容</param>
/// <param name="args">参数集合</param>
/// <returns>返回json对象</returns>
public static string Post(string url, object data, CookieContainer cookie)
{
try
{
string postJson = data == null ? string.Empty : JsonConvert.SerializeObject(data);
using (HttpClientHandler handler = new HttpClientHandler())
{
if (cookie != null)
{
handler.UseCookies = true;
handler.CookieContainer = cookie;
}
using (HttpClient client = new HttpClient(handler))
{
client.Timeout = TimeSpan.FromMilliseconds(TIME_OUT);
StringContent content = new StringContent(postJson, Encoding.UTF8);
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
string json = sr.ReadToEnd();
return json;
}
}
}
}
catch (Exception ex)
{
log.Error(ex);
return null;
}
}
/// <summary>
/// Post请求
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="url">请求url</param>
/// <param name="content">请求内容</param>
/// <param name="args">参数集合</param>
/// <returns>返回json对象</returns>
public static T Post<T>(string url, object data, CookieContainer cookie) where T : class
{
try
{
string json = Post(url, data, cookie);
return JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
log.Error(ex);
return null;
}
}
}
}
\ No newline at end of file
......@@ -53,6 +53,9 @@
<HintPath>..\packages\log4net.2.0.14\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualBasic" />
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\VIZ.TimeSlice\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NvAPIWrapper, Version=0.8.1.100, Culture=neutral, PublicKeyToken=310fd07b25df79b3, processorArchitecture=MSIL">
<HintPath>..\..\VIZ.H2V\packages\NvAPIWrapper.Net.0.8.1.101\lib\net45\NvAPIWrapper.dll</HintPath>
</Reference>
......@@ -96,6 +99,7 @@
<Compile Include="Core\Enum\EnumModel.cs" />
<Compile Include="Core\Helper\ByteHelper.cs" />
<Compile Include="Core\Helper\CmdHelper.cs" />
<Compile Include="Core\Helper\HttpHelper.cs" />
<Compile Include="Core\Helper\KeepSymbolHelper.cs" />
<Compile Include="Core\Helper\ProcessHelper.cs" />
<Compile Include="Core\Helper\FPSHelper.cs" />
......
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="2.0.14" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net48" />
<package id="NvAPIWrapper.Net" version="0.8.1.101" targetFramework="net48" />
<package id="SharpDX" version="4.2.0" targetFramework="net48" />
<package id="SharpDX.Mathematics" version="4.2.0" targetFramework="net48" />
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using VIZ.Framework.Core;
namespace VIZ.Framework.TVP.Golf
{
/// <summary>
/// 高尔夫 包装 设备模型
/// </summary>
public class GolfDeviceModel : ModelBase
{
// ===============================================================================
// Property
// ===============================================================================
#region ConnectionFailures -- 连接失败次数
private int connectionFailures;
/// <summary>
/// 连接失败次数
/// </summary>
public int ConnectionFailures
{
get { return connectionFailures; }
set { connectionFailures = value; this.RaisePropertyChanged(nameof(ConnectionFailures)); }
}
#endregion
#region SerialNumber -- 设备序列号
private string serialNumber;
/// <summary>
/// 设备序列号
/// </summary>
public string SerialNumber
{
get { return serialNumber; }
set { serialNumber = value; this.RaisePropertyChanged(nameof(SerialNumber)); }
}
#endregion
#region DisplayWidth -- 显示宽度
private int displayWidth;
/// <summary>
/// 显示宽度
/// </summary>
public int DisplayWidth
{
get { return displayWidth; }
set { displayWidth = value; this.RaisePropertyChanged(nameof(DisplayWidth)); }
}
#endregion
#region DisplayHeight -- 显示高度
private int displayHeight;
/// <summary>
/// 显示高度
/// </summary>
public int DisplayHeight
{
get { return displayHeight; }
set { displayHeight = value; this.RaisePropertyChanged(nameof(DisplayHeight)); }
}
#endregion
#region IsConnected -- 是否已经连接
private bool isConnected;
/// <summary>
/// 是否已经连接
/// </summary>
public bool IsConnected
{
get { return isConnected; }
set { isConnected = value; this.RaisePropertyChanged(nameof(IsConnected)); }
}
#endregion
#region LeftTeeAreaPoints -- 左手球座区域
private PointCollection leftTeeAreaPoints;
/// <summary>
/// 左手球座区域
/// </summary>
public PointCollection LeftTeeAreaPoints
{
get { return leftTeeAreaPoints; }
set { leftTeeAreaPoints = value; this.RaisePropertyChanged(nameof(LeftTeeAreaPoints)); }
}
#endregion
#region RightTeeAreaPoints -- 右手球座区域
private PointCollection rightTeeAreaPoints;
/// <summary>
/// 右手球座区域
/// </summary>
public PointCollection RightTeeAreaPoints
{
get { return rightTeeAreaPoints; }
set { rightTeeAreaPoints = value; this.RaisePropertyChanged(nameof(RightTeeAreaPoints)); }
}
#endregion
// ===============================================================================
// Public Function
// ===============================================================================
/// <summary>
/// 连接设备
/// </summary>
public void Connect()
{
if (!LaunchMonitor.Connect())
{
// 清除连接失败次数
this.ConnectionFailures = 0;
// 设备序列号
this.SerialNumber = LaunchMonitor.GetSerialNumber();
// 设置已经连接
this.IsConnected = true;
}
}
private PointCollection MapPointCollectionToForm(PointCollection points)
{
PointCollection result = new PointCollection();
foreach (Point p in points)
result.Add(MapPointToForm(p));
return result;
}
private Point MapPointToForm(Point p)
{
return new Point(mCenterX + p.X * mScaleFactor, mCenterY + p.Y * mScaleFactor);
}
}
}
// -----------------------------------------------------------------------
// Class BallFindDLLProxy
//
// Copyright (c) 2021 iTrack LLC
// All rights reserved
//
// This class wraps the itrackAccessDLL data structures and methods,
// alleviating the rest of the App from having to deal with Interop, etc.
//
// -----------------------------------------------------------------------
namespace VIZ.Framework.TVP.Golf
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
public class BallFindDLLProxy
{
// ==================================================
// ===== itrackAccessDLL Import Declarations =====
// ==================================================
// ----- Interop Data Structures -----
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct LaunchMonitorStatus
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]
public String FirmwareVers;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
public String SerialNum;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
public String HardwareVers;
public uint StatusFlags;
public int LMIndex;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Point2D
{
public int x;
public int y;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct Trapezoid
{
public Point2D topLeft;
public Point2D topRight;
public Point2D bottomLeft;
public Point2D bottomRight;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct BallPlacementParameters
{
public int lcd_width;
public int lcd_height;
public Trapezoid left;
public Trapezoid right;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct BallData
{
public Point2D location;
public int diameter;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct BallPlacementState
{
public int flags;
public int num_balls;
public BallData ball_data0;
public BallData ball_data1;
public BallData ball_data2;
public BallData ball_data3;
public BallData ball_data4;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct HittingMode
{
public int mode; // We could directly pass an int but we'll define this struct for consistency with the DLL declaration
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct FlashStatistics
{
public UInt32 total_Sequences;
public UInt32 total_Flashes;
public UInt32 total_EnergyUsed;
public UInt32 total_MisFires; // AKA Invalid Shots
public UInt32 last_shot_Average; // The Average Flash "Feedback" for the most recent valid shot
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct SleepFlags
{
public UInt32 flags; // We could directly pass an int but we'll define this struct for consistency with the DLL declaration
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct InstallationFlags
{
public UInt32 flags; // We could directly pass an int but we'll define this struct for consistency with the DLL declaration
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct ShotCountData
{
public UInt32 count;
};
// ----- Interop Callback Prototypes -----
public delegate int FsEventCallback(IntPtr pEventInfo, IntPtr pContext);
// ----- Interop Calls -----
private const String DLL_IDENTIFIER = "itrackAccessDLL.dll";
[DllImport(DLL_IDENTIFIER, SetLastError = false, CharSet = CharSet.Unicode)]
public static extern int ITRACK_Initialize(StringBuilder configDirPath, uint flags);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_Shutdown(uint reserved);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetLaunchMonitorStatus(int launchMonitorIndex, ref LaunchMonitorStatus launchMonitorStatus);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_SetEventCallback(FsEventCallback eventCallback, IntPtr pContext);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetBallPlacementData(ref BallPlacementParameters parameters);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetBallPlacementState(ref BallPlacementState state);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetHittingMode(ref HittingMode mode);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_SetHittingMode(ref HittingMode mode);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetFlashStatistics(ref FlashStatistics stats);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_ResetFlashStatistics();
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetSleepFlags(ref SleepFlags flags);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_SetSleepFlags(ref SleepFlags flags);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetInstallationFlags(ref InstallationFlags flags);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_SetInstallationFlags(ref InstallationFlags flags);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_GetTotalShots(ref ShotCountData data);
[DllImport(DLL_IDENTIFIER, SetLastError = false)]
public static extern int ITRACK_ResetLaunchMonitor();
// ===========================
// ===== Private Members =====
// ===========================
// The following members must have values that match the equivalent values declared in itrackAccess.h
public const int ITRACK_SUCCESS = 0;
public const int ITRACK_LM_SHOTDATA = 1;
public const int ITRACK_BALL_PLACEMENT_STATE_CHANGE = 6;
public const UInt32 ITRACK_DEV_TRACKER_LOCKED = 0x2;
public const UInt32 ITRACK_DEV_RIGHT_BALL_LOCKED = 0x4;
public const UInt32 ITRACK_DEV_HMT_CONNECTED = 0x8;
public const UInt32 ITRACK_SLEEP_FLAG_TRACKER = 0x1;
public const UInt32 ITRACK_SLEEP_FLAG_BLUETOOTH = 0x2;
public const UInt32 ITRACK_INSTALLATION_FLAG_INDOOR_ONLY = 0x1;
} // End of BallFindDLLProxy
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VIZ.Framework.TVP.Golf
{
/// <summary>
/// 监视错误码
/// </summary>
public enum LaunchMonitorErrorCode
{
}
}
......@@ -85,6 +85,10 @@
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="SDK\BallFindDLLProxy.cs" />
<Compile Include="SDK\LaunchMonitor.cs" />
<Compile Include="Model\GolfDeviceModel.cs" />
<Compile Include="SDK\LaunchMonitorErrorCode.cs" />
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
......@@ -115,5 +119,11 @@
<None Include="Lib\itrackSDK_usb\ReadMe_usb.txt" />
<None Include="Lib\itrackSDK_usb\SDKSampleApp.exe" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VIZ.Framework.Core\VIZ.Framework.Core.csproj">
<Project>{75b39591-4bc3-4b09-bd7d-ec9f67efa96e}</Project>
<Name>VIZ.Framework.Core</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment