Merge branch 'dev_cyp1' into dev_ar_cyp

# Conflicts:
#	Assets/Plugins/Android/unityandroidbluetoothlelib.jar
#	Assets/Resources/UI/language.json
#	Assets/Scenes/MainScene.unity
#	Assets/Scripts/Devices/Ble/mobile/BleMobileInterface.cs
#	Assets/Scripts/Devices/Ble/mobile/BleMobileThread.cs
#	Assets/Scripts/Scenes/MainController.cs
#	Assets/Scripts/UI/Prefab/Panel/RowerHomeScript.cs
#	Assets/Scripts/UI/Prefab/Rower/RowerDeviceView.cs
#	Assets/Scripts/UI/Prefab/Rower/RowerGraphChartFeed.cs
#	Assets/Scripts/UIManager.cs
This commit is contained in:
lishuo committed 2022-06-27 10:36:20 +08:00
commit 1d015706db
41 files changed
+14379 -166815

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ public class BluetoothDeviceScript : MonoBehaviour
public Action<string> ConnectedDisconnectPeripheralAction { get; set; }
public Action<string,string> ConnectErrorAction { get; set; }
public Action<string> DisconnectedPeripheralAction;
public Action<string> DeviceBleStatusDisconnectedAction;
public Action<string> DeviceBleStatusDisconnectedAction { get; set; }
public Action<string, string> DiscoveredServiceAction;
public Action<string, string, string> DiscoveredCharacteristicAction;
public Action<string> DidWriteCharacteristicAction;
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

@@ -0,0 +1,128 @@
fileFormatVersion: 2
guid: 23324df2738e17840a880b3a6a667a98
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 11
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
applyGammaDecoding: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 1024
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 1024
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: iPhone
maxTextureSize: 1024
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 3
buildTarget: Android
maxTextureSize: 1024
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -823,6 +823,174 @@ MonoBehaviour:
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!1 &7779863355442684396
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 7034836054261949127}
- component: {fileID: 6143368985754638542}
- component: {fileID: 5753665062704233989}
- component: {fileID: 1495845730394678308}
m_Layer: 5
m_Name: Text
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &7034836054261949127
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7779863355442684396}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 4661211349328450780}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0}
m_AnchorMax: {x: 0.5, y: 0}
m_AnchoredPosition: {x: 0, y: -16}
m_SizeDelta: {x: 192, y: 26}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &6143368985754638542
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7779863355442684396}
m_CullTransparentMesh: 0
--- !u!114 &5753665062704233989
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7779863355442684396}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_FontData:
m_Font: {fileID: 12800000, guid: 1db9e217733971041be26b076fda6083, type: 3}
m_FontSize: 22
m_FontStyle: 0
m_BestFit: 0
m_MinSize: 2
m_MaxSize: 40
m_Alignment: 4
m_AlignByGeometry: 0
m_RichText: 1
m_HorizontalOverflow: 1
m_VerticalOverflow: 1
m_LineSpacing: 1
m_Text: NO DEVICE
--- !u!114 &1495845730394678308
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7779863355442684396}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: e47f6ee11b78f3247a0b474b6c36e2cd, type: 3}
m_Name:
m_EditorClassIdentifier:
key:
--- !u!1 &7796194410704820496
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 4661211349328450780}
- component: {fileID: 5386702751970923277}
- component: {fileID: 6255635068988837825}
m_Layer: 5
m_Name: Error
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 0
--- !u!224 &4661211349328450780
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7796194410704820496}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 7034836054261949127}
- {fileID: 1853356364457434975}
m_Father: {fileID: 5111540946519637648}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0.5}
m_AnchorMax: {x: 0.5, y: 0.5}
m_AnchoredPosition: {x: -4.600006, y: 25.800003}
m_SizeDelta: {x: 50, y: 50}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &5386702751970923277
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7796194410704820496}
m_CullTransparentMesh: 0
--- !u!114 &6255635068988837825
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 7796194410704820496}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 1, g: 1, b: 1, a: 1}
m_RaycastTarget: 1
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_Sprite: {fileID: 21300000, guid: 23324df2738e17840a880b3a6a667a98, type: 3}
m_Type: 0
m_PreserveAspect: 0
m_FillCenter: 1
m_FillMethod: 4
m_FillAmount: 1
m_FillClockwise: 1
m_FillOrigin: 0
m_UseSpriteMesh: 0
m_PixelsPerUnitMultiplier: 1
--- !u!1 &7824156360689418142
GameObject:
m_ObjectHideFlags: 0
@@ -1023,6 +1191,98 @@ MonoBehaviour:
m_OnValueChanged:
m_PersistentCalls:
m_Calls: []
--- !u!1 &8037773402551538084
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 1853356364457434975}
- component: {fileID: 8162886766775582271}
- component: {fileID: 2416531608984966904}
- component: {fileID: 6648807303715948149}
m_Layer: 5
m_Name: Text (1)
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!224 &1853356364457434975
RectTransform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8037773402551538084}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 4661211349328450780}
m_RootOrder: 1
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
m_AnchorMin: {x: 0.5, y: 0}
m_AnchorMax: {x: 0.5, y: 0}
m_AnchoredPosition: {x: -0.42, y: -42}
m_SizeDelta: {x: 487.94348, y: 24}
m_Pivot: {x: 0.5, y: 0.5}
--- !u!222 &8162886766775582271
CanvasRenderer:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8037773402551538084}
m_CullTransparentMesh: 0
--- !u!114 &2416531608984966904
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8037773402551538084}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3}
m_Name:
m_EditorClassIdentifier:
m_Material: {fileID: 0}
m_Color: {r: 0.36078432, g: 0.36078432, b: 0.43137255, a: 1}
m_RaycastTarget: 1
m_Maskable: 1
m_OnCullStateChanged:
m_PersistentCalls:
m_Calls: []
m_FontData:
m_Font: {fileID: 12800000, guid: 1db9e217733971041be26b076fda6083, type: 3}
m_FontSize: 16
m_FontStyle: 0
m_BestFit: 0
m_MinSize: 1
m_MaxSize: 40
m_Alignment: 4
m_AlignByGeometry: 0
m_RichText: 1
m_HorizontalOverflow: 1
m_VerticalOverflow: 1
m_LineSpacing: 1
m_Text: Please make sure the device is powered on and awakened
--- !u!114 &6648807303715948149
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8037773402551538084}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: e47f6ee11b78f3247a0b474b6c36e2cd, type: 3}
m_Name:
m_EditorClassIdentifier:
key:
--- !u!1 &8099950033695761744
GameObject:
m_ObjectHideFlags: 0
@@ -1358,6 +1618,7 @@ RectTransform:
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 2253444633616264453}
- {fileID: 4661211349328450780}
m_Father: {fileID: 8260988677505792498}
m_RootOrder: 3
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -2923,7 +2923,7 @@ MonoBehaviour:
m_Content: {fileID: 6436148473733942689}
m_Horizontal: 0
m_Vertical: 1
m_MovementType: 1
m_MovementType: 2
m_Elasticity: 0.1
m_Inertia: 1
m_DecelerationRate: 0.135
@@ -4847,12 +4847,12 @@ PrefabInstance:
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
propertyPath: m_AnchorMax.y
value: 0
value: 1
objectReference: {fileID: 0}
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
propertyPath: m_AnchorMin.y
value: 0
value: 1
objectReference: {fileID: 0}
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
@@ -5022,12 +5022,12 @@ PrefabInstance:
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
propertyPath: m_AnchorMax.y
value: 0
value: 1
objectReference: {fileID: 0}
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
propertyPath: m_AnchorMin.y
value: 0
value: 1
objectReference: {fileID: 0}
- target: {fileID: 5329299856310536127, guid: 6b94e789d6585a04dbdc04c8a7cf97b2,
type: 3}
+10 -20
View File
@@ -207,6 +207,7 @@
"Heart Rate Monitor": "心率带",
"NO DEVICE": "无可用设备",
"CHOOSE DEVICE": "查看可用设备",
"NOCONN DEVICE": "未连接设备",
"Edit": "编辑",
"Record": "记录",
"More": "更多",
@@ -366,16 +367,10 @@
"Please check the network status!": "请检查网络连接是否正常!",
"FINISH": "终点",
"Continue the game?": "有中断的划船记录,是否继续?",
"Week": "周",
"You're watching": "你正在观看",
"Bicycle": "自行车",
"Helmet": "头盔",
"Uniform": "服装",
"Skin": "肤色",
"Suit": "套装",
"View": "预览",
"Capture": "截图",
"BATTLE": "对战"
"Save the game?": "有中断的划船记录,是否保存?",
"Please make sure the device is powered on and awakened": "请确保设备有电且已唤醒",
"Powerfun need location service permission,please open the location permission.": "Powerfun需要定位服务权限,请打开定位服务权限!",
"Disconnect the device?": "是否断开该设备?"
},
"en": {
"HOT ROUTES": "HOT ROUTES",
@@ -463,6 +458,7 @@
"Smart Trainer": "Smart Trainer",
"NO DEVICE": "NO DEVICE",
"CHOOSE DEVICE": "CHOOSE DEVICE",
"NOCONN DEVICE": "NO CONNECTED DEVICE",
"CONNECT": "CONNECT",
"CLOSE": "CLOSE",
"PAIR": "PAIR",
@@ -736,15 +732,9 @@
"Please check the network status!": "Please check if the network connection is normal!",
"FINISH": "FINISH",
"Continue the game?": "Continue the game?",
"Week": "Week",
"You're watching": "You're watching",
"Bicycle": "Bicycle",
"Helmet": "Helmet",
"Uniform": "Uniform",
"Skin": "Skin",
"Suit": "Suit",
"View": "View",
"Capture": "Capture",
"BATTLE": "BATTLE"
"Save the game?": "Save the game?",
"Please make sure the device is powered on and awakened": "Please make sure the device is powered on and awakened",
"Powerfun need location service permission,please open the location permission.": "Powerfun need location service permission,please open the location permission.",
"Disconnect the device?": "Disconnect the device?"
}
}
File diff suppressed because it is too large. Load diff
+151 -156052
View File
File diff suppressed because it is too large. Load diff
@@ -98,6 +98,7 @@ namespace Assets.Scripts.Apis.Models
public int Nid { get; set; }
public double Ticks { get; set; }
public int rankNum { get; set; }
public string GradeStr { get; set; }
}
public class Info
+1
View File
@@ -224,6 +224,7 @@ public static class App
{"http://192.168.0.101:5083/","http://pfweb.juze.pro/" }
};
public static List<string> cacheList = new List<string>();
static App()
{
InitLanguage();
@@ -1,4 +1,5 @@
using Assets.Scripts.Devices.Ble.Characteristic;
using Assets.Scripts.Ble.Commands;
using Assets.Scripts.Devices.Ble.Characteristic;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -14,5 +15,6 @@ namespace Assets.Scripts.Devices.Ant.Interfaces
void Reset();
void SetResistanceLevel(ushort v);
void C2GetStatus(byte[] bs);
void SendCommand(RowerCommand command,int data = 0);
}
}
@@ -48,5 +48,13 @@ namespace Assets.Scripts
{
return (uint)((int)bytes[startIndex] | (int)bytes[startIndex + 1] << 8 | (int)bytes[startIndex + 2] << 16);
}
public static byte[] HexToByteArray(string hex)
{
hex=hex.Replace(" ", "");
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}
+1 -1
View File
@@ -128,7 +128,7 @@ namespace Assets.Scripts.Devices.Ble
Debug.Log("断开设备" + this.Name);
//App.MainDeviceAdapter.PrintStatus();
this.State = DeviceState.Disconnected;
//this.State = DeviceState.Disconnected;
this.hwInterface.DisconnectPeripheral(this.peripheralInfo, () => {
//App.MainDeviceAdapter.PrintStatus();
@@ -19,7 +19,7 @@ namespace Assets.Scripts.Devices.Ble
private IDictionary<string, BleDevice> discoveredDevices = new Dictionary<string, BleDevice>();
private IBleWinHwInterface hwInterface { get; set; }
public IBleWinHwInterface hwInterface { get; private set; }
public BleDeviceAdapter(IBleWinHwInterface bleWinHwInterface)
{
@@ -11,6 +11,11 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
{
public class C2RowerData : ICharacteristic, IRowerCommonData
{
public static string JUSTROW_HEX = "F1 76 07 01 01 01 13 02 01 01 61 F2";
public static string TERMINATEWORKOUT_HEX = "F1 76 04 13 02 01 02 62 F2";
public static string FIXEDDISTANCE_HEX = "F1 76 18 01 01 03 03 05 80 00 00 07 D0 05 05 80 00 00 01 90 14 01 01 13 02 01 01 28 F2";
public static string FIXEDTIME_HEX = "F1 76 07 01 01 01 13 02 01 01 61 F2";
public Guid Uuid => ServiceUuids.Characteristics.C2RowerData35;
public Guid ServiceUuid => ServiceUuids.Characteristics.C2Service;
@@ -27,7 +32,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
_isEnabled = value;
if (EnableChanged != null)
{
EnableChanged(_isEnabled, new EventArgs());
EnableChanged(_isEnabled, null);
}
}
}
@@ -46,16 +51,18 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
_pullValue = value;
if (this.PullChanged != null)
{
this.PullChanged(this, new EventArgs());
this.PullChanged(this, null);
}
}
}
public static bool IsUserDefined { get; set; }
public static bool isReadyStatus { get; private set; }
public static RowerTaskPanel.RowerType rowerType { get; private set; }
public void HandleAttributeReceived(byte[] data)
{
Debug.Log("数据" + string.Join(",", data));
if (data[0] == 0x35)
{
PeakDriveForce = LbsToNewton(Convert.ToDouble(BitConvertHelper.ToUInt16(data, 13)) / 10, true);
@@ -63,20 +70,19 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
ElapsedTime = (int)(Convert.ToDouble(BitConvertHelper.ToUInt24(data, 1)) / 100);
TotalDistance = (uint)(Convert.ToDouble(BitConvertHelper.ToUInt24(data, 4)) / 10);
StrokeCount = BitConvertHelper.ToUInt16(data, 19);
Debug.Log($"峰力值:{PeakDriveForce} 均力值{AverageDriveForce}");
}
else if (data[0] == 0x3d)
{
//老款表头不支持
List<ushort> r = new List<ushort>();
//List<ushort> r = new List<ushort>();
for (int i = 3; i < data.Length; i += 2)
{
ushort pull = data[i] < 5 ? (ushort)0 : Convert.ToUInt16(Math.Round(LbsToNewton(data[i], true)));
r.Add(pull);
ushort pull = data[i] < 10 ? (ushort)0 : Convert.ToUInt16(Math.Round(LbsToNewton(data[i], true)));
//r.Add(pull);
PullValue = pull;
}
Debug.Log("拉力曲线:" + string.Join(",", r));
// Debug.Log("拉力曲线:" + string.Join(",", r));
}
else if (data[0] == 0x31)
{
@@ -87,26 +93,31 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
rowerType = new RowerTaskPanel.RowerType();
rowerType.type = 1;
rowerType.value = value;
IsUserDefined = true;
}
else if (status == 0)
{
rowerType = new RowerTaskPanel.RowerType();
rowerType.type = 2;
rowerType.value = value / 100;
IsUserDefined = false;
}
else
{
rowerType = null;
IsUserDefined = false;
}
Debug.Log($"里程:{TotalDistance}峰力值:{PeakDriveForce} 均力值{AverageDriveForce} ReadyStatus:{isReadyStatus} TIME{DateTime.Now}");
//isReadyStatus = data[9] == 0;
var time = ((data[3] << 16) + (data[2] << 8) + data[1]) / 100;
Debug.Log("划船时间" + time);
isReadyStatus = data[9] == 0;
if (RowerResChanged != null)
{
RowerResChanged.Invoke(data[19], new EventArgs());
}
var hasChanged = data[19] != ResistanceLevel;
ResistanceLevel = data[19];
if (RowerResChanged != null && hasChanged)
{
RowerResChanged.Invoke(this, null);
}
//isReadyStatus = data[2] == 1 || data[2] == 129;
}
else if (data[0] == 0x32)
@@ -126,17 +137,20 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
InstantaneousPower = BitConvertHelper.ToUInt16(data, 4);
//TotalEnergy = BitConvertHelper.ToUInt16(data, 6);
}
//else if (data[0] == 0x39)
//{
// AverageStrokeRate = (int)data[11];
// ResistanceLevel = (int)data[16];
//}
else if (data[0] == 0x39)
{
ElapsedTime = (int)(Convert.ToDouble(BitConvertHelper.ToUInt24(data, 5)) / 100);
TotalDistance = (uint)(Convert.ToDouble(BitConvertHelper.ToUInt24(data, 8)) / 10);
CompleteEvent?.Invoke(this, null);
}
Debug.Log("数据" + string.Join(",", data) + $" | {ElapsedTime}-{TotalDistance}");
//else if (data[0] == 34)
//{
// isReadyStatus = data[2] == 1 || data[2] == 129;
//}
}
public event EventHandler StartEvent;
public event EventHandler CompleteEvent;
private double LbsToNewton(double lbs,bool isKg = false) => 4.4482216 * lbs * (isKg ? (1f / 9.8f) : 1f);
public void SetUnavailable()
{
@@ -155,7 +169,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
/// 平均划桨频率
/// </summary>
public int AverageStrokeRate { get; set; } = 0;
private UInt32 _totalDistance = 0;
private UInt32 _totalDistance = 1;
public UInt32 TotalDistance
{
get => _totalDistance;
@@ -163,7 +177,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
{
if (_totalDistance == 0 && value != 0 && StartEvent != null)
{
StartEvent.Invoke(null, new EventArgs());
StartEvent.Invoke(this, null);
}
_totalDistance = value;
}
@@ -25,7 +25,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
/// </summary>
public int AverageStrokeRate { get; set; } = 0;
private UInt32 _totalDistance = 0;
private UInt32 _totalDistance = 1;
public UInt32 TotalDistance
{
get => _totalDistance;
@@ -33,16 +33,17 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
{
if (_totalDistance == 0 && value != 0 && StartEvent != null)
{
StartEvent.Invoke(null, new EventArgs());
StartEvent.Invoke(this, null);
}
_totalDistance = value;
}
}
//private UInt16 _instantaneousPace = 0;
//private UInt16 _instantaneousPace = 1;
/// <summary>
/// 即时配速
/// </summary>
public UInt16 InstantaneousPace { get; set; } = 0;
/// <summary>
/// 平均配速
/// </summary>
@@ -61,7 +62,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
{
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected) && d.Sensor == SensorType.Rower);
if (device == null) return 0;
if (device.Name.Contains("Think"))
if (device.Name.Contains("Think") || device.Name.Contains("PF"))
{
return thinkRes;
}
@@ -93,6 +94,10 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
public event EventHandler PullChanged;
//开始事件
public event EventHandler StartEvent;
//结束事件
public event EventHandler CompleteEvent;
//日志事件
public event EventHandler LogEvent;
private ushort _pullValue;
public ushort PullValue
{
@@ -102,7 +107,7 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
_pullValue = value;
if (this.PullChanged != null)
{
this.PullChanged(this, new EventArgs());
this.PullChanged(this, null);
}
}
}
@@ -113,6 +118,8 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
return this.Flags.HasFlag(RowerDataFlag.MoreData);
}
}
private string[] deviceNamePool = new string[] {"Think","PF" };
private List<ushort> tempPullList = new List<ushort>();
public void HandleAttributeReceived(byte[] data)
{
@@ -126,9 +133,8 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
// return;
//}
var output = "";
output += "收到消息:" + string.Join("\t", data);
output += "收到消息:" + string.Join(",", data);
this.Flags = (RowerDataFlag)BitConverter.ToUInt16(data, 0);
int b = 2;
if (!this.MoreDataFlag)
@@ -156,6 +162,11 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
{
var vvv = BitConvertHelper.ToUInt24(data, (int)b);
output += $" 总距离{ vvv }米";
if (vvv < 10)
{
LogEvent?.Invoke(DateTime.Now.ToString() + ":" + output,null);
//App.cacheList.Add(DateTime.Now.ToString() + ":" + output);
}
b += this.SizeOfDataForFlag(RowerDataFlag.TotalDistance);
this.TotalDistance = vvv;
@@ -186,11 +197,13 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
}
if (this.Flags.HasFlag(RowerDataFlag.ResistanceLevel))
{
this.commonRes = BitConvertHelper.ToInt16(data, b);
var newRes = BitConvertHelper.ToInt16(data, b);
var resChanged = newRes != this.commonRes;
this.commonRes = newRes;
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected) && d.Sensor == SensorType.Rower);
if (device != null && !device.Name.Contains("Think") && RowerResChanged != null)
if (resChanged && device != null && deviceNamePool.FirstOrDefault(x => device.Name.ToLower().Contains(x.ToLower())) == null && RowerResChanged != null)
{
RowerResChanged.Invoke(this.commonRes, null);
RowerResChanged.Invoke(this, null);
}
b += this.SizeOfDataForFlag(RowerDataFlag.ResistanceLevel);
}
@@ -225,27 +238,29 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
}
if (this.Flags.HasFlag(RowerDataFlag.ThinkDragFactor))
{
var originRes = BitConvertHelper.ToInt16(data, b + 1);
var thinkResChanged = originRes != this.thinkRes;
this.thinkRes = BitConvertHelper.ToInt16(data, b + 1);
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected) && d.Sensor == SensorType.Rower);
if (device != null && device.Name.Contains("Think") && RowerResChanged != null)
if (thinkResChanged && device != null && deviceNamePool.FirstOrDefault(x=>device.Name.ToLower().Contains(x.ToLower()))!=null && RowerResChanged != null)
{
RowerResChanged.Invoke(this.thinkRes, null);
RowerResChanged.Invoke(this, null);
}
b += this.SizeOfDataForFlag(RowerDataFlag.ThinkDragFactor);
}
if (this.Flags.HasFlag(RowerDataFlag.Pull))
{
List<ushort> list = new List<ushort>();
for (int pullB = 4; pullB < data.Length; pullB += 2)
{
var val = BitConverter.ToUInt16(data, pullB);
val = Convert.ToUInt16(((double)val) /9.8f);
list.Add(val);
tempPullList.Add(val);
PullValue = val;
}
Debug.Log("拉力列表:" + string.Join(",", tempPullList));
if (pullList == null) pullList = new List<ushort>();
foreach (var pull in list)
foreach (var pull in tempPullList)
{
if (pull == 0)
{
@@ -258,16 +273,17 @@ namespace Assets.Scripts.Devices.Ble.Characteristic
}
pullList.Add(pull);
}
Debug.Log("拉力:" + string.Join(",",list));
tempPullList.Clear();
}
}
List<ushort> pullList;
List<ushort> pullList { get; set; }
public void Reset()
{
this.StrokeRate = 0;
this.StrokeCount = 0;
this.AverageStrokeRate = 0;
this.TotalDistance = 0;
//this.TotalDistance = 0;
this.InstantaneousPace = 0;
this.AveragePace = 0;
this.InstantaneousPower = 0;
@@ -6,7 +6,14 @@ using System.Threading.Tasks;
namespace Assets.Scripts.Ble.Commands
{
public enum CommandResponseCode
public enum RowerCommand
{
JustRow = 1,
FixedDistance=2,
FixedTime = 3,
}
public enum CommandResponseCode
{
// Token: 0x04000FEB RID: 4075
Success = 1,
+118 -8
View File
@@ -1,4 +1,5 @@
using Assets.Scripts.Ble;
using Assets.Scripts.Ble.Commands;
using Assets.Scripts.Devices.Ant.Interfaces;
using Assets.Scripts.Devices.Ble.Characteristic;
using Assets.Scripts.Devices.Ble.Interfaces;
@@ -21,7 +22,7 @@ namespace Assets.Scripts.Devices.Ble.Devices
public C2RowerData c2RowerData { get => _c2RowerData; }
private List<BleServiceInfo> Services;
private BleCharacteristicInfo controlPointCharacteristic;
private BleCharacteristicInfo c2Control;
private BleCharacteristicInfo c2Control { get; set; }
public FtmsRower(BlePeripheralInfo peripheralInfo, IBleWinHwInterface bleWinHwInterface) : base(peripheralInfo, bleWinHwInterface, Ant.SensorType.Rower)
{
@@ -53,6 +54,8 @@ namespace Assets.Scripts.Devices.Ble.Devices
Debug.Log("中控台获取");
this.controlPointCharacteristic = character;
C2RowerData.IsEnabled = false;
//Thread.Sleep(100);
//Reset();
}
else if (character.MatchGuid(ServiceUuids.Characteristics.RowerData))
{
@@ -101,7 +104,7 @@ namespace Assets.Scripts.Devices.Ble.Devices
}
else if (character.MatchGuid(ServiceUuids.Characteristics.C2RowerControl))
{
Debug.Log("c2划船机控制台");
Debug.Log($"c2划船机控制台{character.Id}");
this.c2Control = character;
}
}
@@ -171,6 +174,26 @@ namespace Assets.Scripts.Devices.Ble.Devices
}
}
public void SendCommand(RowerCommand command,int data = 0)
{
if (!C2RowerData.IsEnabled)
return;
switch (command)
{
case RowerCommand.JustRow:
SetJustRow();
break;
case RowerCommand.FixedDistance:
SetFixedDistance(data);
break;
case RowerCommand.FixedTime:
SetFixedTime(data);
break;
default:
break;
}
}
public void Reset()
{
if (C2RowerData.IsEnabled == true)
@@ -188,23 +211,110 @@ namespace Assets.Scripts.Devices.Ble.Devices
if (this.controlPointCharacteristic != null)
{
Debug.Log("发送重置命令" + this.controlPointCharacteristic.ToString());
//App.cacheList.Add(DateTime.Now.ToString() + ":发送重置命令" + this.controlPointCharacteristic.ToString());
hwInterface.WriteCharacteristic(this.controlPointCharacteristic, new byte[] { 0x01 });
}
}
}
/// <summary>
///
/// </summary>
/// <param name="workoutType">训练类型:0,1,2(里程不分段),3(里程分段),4(时间不分段),5,6,7,8~13</param>
public void SetWorkoutType(int workoutType)
{
var typeHex = workoutType.ToString("X2");
var checkSum = "00";
var data = BitConvertHelper.HexToByteArray($"F1 76 03 01 01 {typeHex} {checkSum} F2");//"F1 76 03 01 01 03 76 F2"//03?
checkSum = GetChecksumHexString(data);
data = BitConvertHelper.HexToByteArray($"F1 76 03 01 01 {typeHex} {checkSum} F2");
hwInterface.WriteCharacteristic(this.c2Control, data);
Thread.Sleep(5);
}
public void SetConfigureWorkout()
{
var data = BitConvertHelper.HexToByteArray("F1 76 03 14 01 01 61 F2"); //03?
hwInterface.WriteCharacteristic(this.c2Control, data);
Thread.Sleep(5);
}
public void SetScreenState()
{
var data = BitConvertHelper.HexToByteArray("F1 76 04 13 02 01 01 63 F2"); //04?
hwInterface.WriteCharacteristic(this.c2Control, data);
}
public void SetPoll()
{
var data = BitConvertHelper.HexToByteArray($"F1 76 07 8D 93 A3 A0 A8 B3 B6 C1 F2");
hwInterface.WriteCharacteristic(this.c2Control, data);
}
public void SetJustRow()
{
var data = BitConvertHelper.HexToByteArray("F1 76 07 01 01 01 13 02 01 01 61 F2");
Debug.Log($"SetJustRow:{string.Join(",", data)}");
hwInterface.WriteCharacteristic(this.c2Control, data);
Thread.Sleep(5);
SetScreenState();
}
public void SetFixedDistance(int distance)
{
if (distance < 100)
return;
SetWorkoutType(3);
var hexditance = distance.ToString("X4");
var checkSum = "00";
var data = BitConvertHelper.HexToByteArray($"F1 76 07 03 05 80 00 00 {hexditance} {checkSum} F2");//F1 76 07 03 05 80 00 00 {hexditance} {checkSum} F2
checkSum = GetChecksumHexString(data);
data = BitConvertHelper.HexToByteArray($"F1 76 07 03 05 80 00 00 {hexditance} {checkSum} F2");//07?
hwInterface.WriteCharacteristic(this.c2Control, data);
Thread.Sleep(5);
SetConfigureWorkout();
SetScreenState();
}
private string GetChecksumHexString(byte[] data)
{
var res = data[1];
for (int i = 2; i < data.Length-2; i++)
{
res ^= data[i];
}
return res.ToString("X2");
}
public void SetFixedTime(int mins)
{
SetWorkoutType(5);
Thread.Sleep(5);
var timeHex = (mins * 100).ToString("X6");
var checkNum = "00";
var data = BitConvertHelper.HexToByteArray($"F1 76 07 03 05 00 00 {timeHex} {checkNum} F2");
checkNum = GetChecksumHexString(data);
data = BitConvertHelper.HexToByteArray($"F1 76 07 03 05 00 00 {timeHex} {checkNum} F2");
hwInterface.WriteCharacteristic(this.c2Control, data);
Thread.Sleep(5);
SetConfigureWorkout();
Thread.Sleep(5);
SetScreenState();
}
public void SetResistanceLevel(ushort v)
{
if (C2RowerData.IsEnabled == true)
{
//等对csafe协议研究透彻后写
////等对csafe协议研究透彻后写
//if (this.c2Control != null)
//{
// var data = new byte[] { 0x29 }.Concat(BitConverter.GetBytes(v)).ToArray();
// byte checksum = (byte)((byte)(data[0] ^ data[1]) ^ data[2]);
// var r = new byte[] { 0xF1 }.Concat(data).Concat(new byte[] { checksum, 0xf2 }) .ToArray();
// Debug.Log($"设置阻力{v}, {string.Join(",", r)}");
// hwInterface.WriteCharacteristic(this.c2Control, r);
//02312131 = > 03010103
//var data = new byte[] { 0x76 }.Concat(BitConverter.GetBytes(v)).ToArray();
//byte checksum = (byte)((byte)(data[0] ^ data[1]) ^ data[2]);
//var r = new byte[] { 0xF1 }.Concat(data).Concat(new byte[] { checksum, 0xf2 }).ToArray();
//Debug.Log($"设置阻力{v}, {string.Join(",", r)}");
//
// var data = BitConvertHelper.HexToByteArray("F1 76 07 01 01 01 13 02 01 01 61 F2");
// hwInterface.WriteCharacteristic(this.c2Control, data);
//}
}
else
@@ -45,6 +45,7 @@ namespace Assets.Scripts.Devices.Ble.Interfaces
int ResistanceLevel { get; set; }
void Reset();
event EventHandler StartEvent;
event EventHandler CompleteEvent;//结束事件
event EventHandler RowerResChanged;
}
}
@@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using UnityEngine;
@@ -116,6 +117,10 @@ namespace Assets.Scripts.Ble
private void ManagerStatusChanged(BleMobileThread sender, WclBleManagerStatus status)
{
this.BleState = BleMobileInterface.StateFromNativeState(status);
if (this.BleState == BleState.Off)
{
ClearAllCallbacks();
}
}
private void WatcherScanInfoReceived(BleMobileThread sender, string address, string name, int rssi,string[] uuids)
@@ -236,6 +241,7 @@ namespace Assets.Scripts.Ble
IsSuccess = true,
Error = null
};
PeripheralDisconnected(address, info);//连接前断开
callback?.Invoke(self, info, s);
this.callbacks.Remove(info);
Debug.Log("连接成功!" + info.Name);
@@ -337,8 +343,6 @@ namespace Assets.Scripts.Ble
{
characteristicsDiscoveredCallbacks.Remove(characteristicsDiscoveredCallback.First().Key);
}
peripheralDisconnectedEvent(this, info, null, false);
}
#endregion
@@ -348,6 +352,7 @@ namespace Assets.Scripts.Ble
BluetoothLEHardwareInterface.DisconnectPeripheral(peripheral.Address, (address) =>
{
Debug.Log("断开回调"+ address);
PeripheralDisconnected(address,peripheral);
peripheralDisconnectedEvent(this, peripheral, null, true);
callback?.Invoke();
});
@@ -374,6 +379,17 @@ namespace Assets.Scripts.Ble
{
bleMobileThread?.Stop();
}
public void ClearAllCallbacks()
{
callbacks?.Clear();
servicesCallbacks?.Clear();
characteristicNotificationCallbacks?.Clear();
characteristicReadCallbacks?.Clear();
characteristicsDiscoveredCallbacks?.Clear();
_discoveredCallback = null;
_pCache?.Clear();
}
//发现服务列表
public void DiscoverServices(BlePeripheralInfo peripheral, Action<IBleWinHwInterface, BlePeripheralInfo, BleResponse<List<BleServiceInfo>>> callback)
@@ -398,10 +414,11 @@ namespace Assets.Scripts.Ble
{
this.characteristicNotificationCallbacks.Add(characteristic.Peripheral, callback);
}
Debug.Log("SubscribeCharacteristic" + characteristic.Peripheral.Name + characteristic.Service.ToString() + characteristic.Service.ToString());
Thread.Sleep(50);
Debug.Log("SubscribeCharacteristic" + characteristic.Peripheral.Name + characteristic.Service.ToString() + characteristic.Id.ToString());
BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(characteristic.Peripheral.Address, characteristic.Service.ToString(), characteristic.Id.ToString(), (a,b)=>
{
Debug.Log("返回特征值," + a + "," + b);
Debug.Log("返回特征值," + a + "," + b+DateTime.Now.ToString());
}, (deviceAddress, characteristric, bytes) =>
{
if (characteristicReadEvent != null)
@@ -1,5 +1,6 @@
using Assets.Scripts.Ble;
using System.Timers;
using UnityEngine;
namespace Assets.Scripts.Devices.Ble
{
@@ -35,76 +36,17 @@ namespace Assets.Scripts.Devices.Ble
this.managerStatusChanged -= value;
}
}
WclBleManagerStatus statusEnum = WclBleManagerStatus.RadioOff;
WclBleManagerStatus statusEnum = WclBleManagerStatus.RadioOn;
internal BleMobileThread() {
var self = this;
//初始蓝牙
BluetoothLEHardwareInterface.Initialize(true, false, () => {
statusEnum = WclBleManagerStatus.RadioOn;
managerInitialized?.Invoke(self);
},
(error) => {
statusEnum = WclBleManagerStatus.RadioOff;
BluetoothLEHardwareInterface.Log("Error: " + error);
if (error.Contains("Bluetooth LE Not Enabled"))
BluetoothLEHardwareInterface.BluetoothEnable(true);
}, (status) => {
statusEnum = WclBleManagerStatus.RadioOn;
switch (status)
{
case 13:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 11:
statusEnum = WclBleManagerStatus.RadioOn;
break;
}
if (managerStatusChanged != null)
{
managerStatusChanged.Invoke(self, statusEnum);
}
});
Initialize();//初始蓝牙
}
public void StartWatcher() {
var self = this;
if (statusEnum == WclBleManagerStatus.RadioOff)
{
//Initialize();
BluetoothLEHardwareInterface.BluetoothEnable(true);
BluetoothLEHardwareInterface.Initialize(true, false, () =>
{
statusEnum = WclBleManagerStatus.RadioOn;
managerInitialized?.Invoke(self);
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{
ScanInfoReceived?.Invoke(self, address, name, rssi, bytes);
}, true);
},
(error) =>
{
statusEnum = WclBleManagerStatus.RadioOff;
BluetoothLEHardwareInterface.Log("Error: " + error);
if (error.Contains("Bluetooth LE Not Enabled"))
BluetoothLEHardwareInterface.BluetoothEnable(true);
}, (status) =>
{
statusEnum = WclBleManagerStatus.RadioOn;
switch (status)
{
case 13:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 11:
statusEnum = WclBleManagerStatus.RadioOn;
break;
}
if (managerStatusChanged != null)
{
managerStatusChanged.Invoke(self, statusEnum);
}
});
}
else
{
@@ -114,6 +56,53 @@ namespace Assets.Scripts.Devices.Ble
}, true);
}
}
public void Initialize()
{
Debug.Log("Initialize");
var self = this;
BluetoothLEHardwareInterface.BluetoothEnable(true);
BluetoothLEHardwareInterface.Initialize(true, false, () =>
{
statusEnum = WclBleManagerStatus.RadioOn;
managerInitialized?.Invoke(self);
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{
ScanInfoReceived?.Invoke(self, address, name, rssi, bytes);
}, true);
},
(error) =>
{
statusEnum = WclBleManagerStatus.RadioOff;
BluetoothLEHardwareInterface.Log("Error: " + error);
if (error.Contains("Bluetooth LE Not Enabled"))
BluetoothLEHardwareInterface.BluetoothEnable(true);
}, (status) =>
{
statusEnum = WclBleManagerStatus.RadioOn;
switch (status)
{
case 10:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 13:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 11:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 12:
statusEnum = WclBleManagerStatus.RadioOn;
break;
default:
statusEnum = WclBleManagerStatus.RadioOff;
break;
}
if (managerStatusChanged != null)
{
managerStatusChanged.Invoke(self, statusEnum);
}
});
}
public void Stop()
{
@@ -119,5 +119,17 @@ namespace Assets.Scripts.Devices
str += "---------------------------\r\n";
Debug.Log(str);
}
public BleDeviceAdapter GetBleDeviceAdapter()
{
foreach (var item in adapters)
{
var bleadapter = (BleDeviceAdapter)item;
if (bleadapter != null) {
return bleadapter;
}
}
return null;
}
}
}
+32 -6
View File
@@ -37,20 +37,46 @@ public class PFUISlider : MonoBehaviour
public bool runCallback = false;
public void SetValueChanged(System.Action<float> a)
{
this.ValueChangedHandler = a;
slider = transform.GetComponent<Slider>();
slider.onValueChanged.RemoveAllListeners();
UIManager.AddEvent(slider.gameObject, EventTriggerType.EndDrag, (e) =>
{
OnValueChanged();
});
slider.onValueChanged.AddListener((f) =>
{
var step = 1f / (colorGradientList.Count-1);
var index = (int)Math.Round(f / step, 0);
slider.targetGraphic.color = colorGradientList[index];
text.text = $"{valueHandler(f).ToString("#0")}";
a.Invoke(f);
current = f;
});
}
public void SetValue(float a)
float current;
System.Action<float> ValueChangedHandler;
private void OnValueChanged()
{
float f = current;
var step = 1f / (colorGradientList.Count - 1);
var index = (int)Math.Round(f / step, 0);
slider.targetGraphic.color = colorGradientList[index];
text.text = $"{valueHandler(f):#0}";
this.ValueChangedHandler?.Invoke(f);
}
public void SetValue(float a,bool silent = false)
{
a = a > 1 ? 1 : a;
a = a < 0 ? 0 : a;
slider.value = a;
text.text = $"{valueHandler(a):#0}";
if(!silent)
OnValueChanged();
}
public float GetValue()
{
return slider.value;
}
public List<Color> SetColorGradient(List<Color> list, int divideCount)
@@ -98,14 +98,15 @@ public class ActivityController : PFUIPanel
webView.SetUserAgent($"UniWebView {Application.platform} {Application.version}");
webView.BackgroundColor = Utils.HexToColorHtml("#23232d");
//webView.CleanCache();
if (action == null)
{
webView.Load(url);
}
else
{
action.Invoke();
}
webView.Load(url);
//if (action == null)
//{
// webView.Load(url);
//}
//else
//{
// action.Invoke();
//}
// Show it.
webView.Show();
webView.OnMessageReceived -= FromJs;
@@ -44,6 +44,7 @@ public class ConnectDeviceModal : PFUIPanel
private Dictionary<string, DeviceItem> deviceList;
private Text noDevice,Title;
private RectTransform searchIconRect;
private GameObject deviceNotFound;
protected override void Awake()
{
@@ -52,6 +53,7 @@ public class ConnectDeviceModal : PFUIPanel
deviceList = new Dictionary<string, DeviceItem>();
var container = this.transform.Find("GameObject");
deviceNotFound = container.Find("Panel/Error").gameObject;
var closeBtn = container.Find("CloseBtn");
Logo = container.Find("Logo").GetComponent<Image>();
Title = container.Find("Title").GetComponent<Text>();
@@ -259,6 +261,7 @@ public class ConnectDeviceModal : PFUIPanel
//如果没有可连接的设备按钮只读
connectBtn.mButton.enabled = deviceList.Count > 0;
connectBtn.mButton.interactable = deviceList.Count > 0;
deviceNotFound.SetActive(deviceList.Count <= 0);
}
}
//选中需要连接的设备
@@ -285,7 +288,7 @@ public class ConnectDeviceModal : PFUIPanel
}
}
noDevice.text = deviceItemObj.DeviceInfo.Name + "-"+ deviceItemObj.DeviceInfo.DeviceNumber;
noDevice.text = deviceItemObj.DeviceInfo.Name;
if (deviceItemObj.DeviceInfo.State == DeviceState.Connected)
{
noDevice.color = Color.white;
@@ -71,11 +71,11 @@ public class DeviceItem : Selectable, IEventSystemHandler, IPointerClickHandler
//signal.enabled = true;
var signalValue = DeviceInfo.SignalStrength * -1;
if (signalValue >= 0 && signalValue <= 20)
if (signalValue >= 0 && signalValue <= 30)
{
signal.sprite = Signal_1;
}
else if (signalValue > 20 && signalValue <= 60)
else if (signalValue > 30 && signalValue <= 60)
{
signal.sprite = Signal_2;
}
+1
View File
@@ -183,6 +183,7 @@ public class NewMainNav : MonoBehaviour
{
if (App.IsRowerMode == true)
{
if (UIManager.Instance.RowerHomeScript.checkRowing()) return;
UIManager.ShowEditUserPanel();
}
else
+377 -166
View File
@@ -17,12 +17,14 @@ using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.UI;
using static RowerTaskPanel;
using Assets.Scripts.Ble.Commands;
public class RowerHomeScript : PFUIPanel
{
private class TempRowerCalc
private class TempRowerCalc
{
public int power { get; set; }
public ushort pace { get; set; }
@@ -52,19 +54,20 @@ public class RowerHomeScript : PFUIPanel
protected override void OnDestroy()
{
Debug.Log("銷毀");
if (RowerData != null)
if (RowerData != null)
{
RowerData.PullChanged -= PaintPullCurve;
RowerData.StartEvent -= StartFunc;
RowerData.CompleteEvent -= CompelteFunc;
RowerData.RowerResChanged -= ResChanged;
}
C2RowerData.EnableChanged -= ModeChanged;
}
private IRowerDevice Rower
private IRowerDevice Rower
{
get
{
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower);
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => d.State == DeviceState.Connected && d.Sensor == SensorType.Rower);
if (device != null)
{
return (IRowerDevice)device;
@@ -75,9 +78,9 @@ public class RowerHomeScript : PFUIPanel
/// <summary>
/// 心率数据
/// </summary>
private int? HeartRate
private int? HeartRate
{
get
get
{
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.HeartRate);
if (device != null)
@@ -88,12 +91,12 @@ public class RowerHomeScript : PFUIPanel
}
}
GameObject btnStart;
Transform left, bottom, mid,rmydata;
Transform left, bottom, mid, rmydata;
Image leftImage;
Image rightImage;
float timer = 1.0f;
float timer = 0f;
List<DoubleVector2> pullList, historyPullList;
public Dictionary<object, Sprite> spriteDict,spriteDict2;
public Dictionary<object, Sprite> spriteDict, spriteDict2;
List<string> records;
List<TempRowerCalc> values;
DateTime startTime;
@@ -127,7 +130,7 @@ public class RowerHomeScript : PFUIPanel
{
Id = Guid.NewGuid().ToString();
rowerType = new RowerType() { type = 1, value = 500 };
spriteDict = new Dictionary<object, Sprite>()
{
{"Start",Resources.Load<Sprite>("Images/RowerNew/ICON_continue_44") },
@@ -201,30 +204,26 @@ public class RowerHomeScript : PFUIPanel
UIManager.AddEvent(transform.Find("ResBar/BtnAdd").gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, b =>
{
if (RowerData != null)
if (RowerData != null)
{
slider.GetComponent<PFUISlider>().SetValue((RowerData.ResistanceLevel + 1 - 50) / 300f);
}
});
UIManager.AddEvent(transform.Find("ResBar/BtnSub").gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, b =>
{
if (RowerData != null)
if (RowerData != null)
{
slider.GetComponent<PFUISlider>().SetValue((RowerData.ResistanceLevel - 1 - 50) / 300f);
}
});
slider.GetComponent<PFUISlider>().valueHandler = (a) => 50 + a * 300;
slider.GetComponent<PFUISlider>().SetValueChanged(r =>
{
var v = (ushort)Math.Round((r * 300));
print("设置阻力" + v);
if (Rower != null)
{
Rower.SetResistanceLevel(v);
//RowerData.
}
StartCoroutine(SetResistanceLevel(v));
});
//transform.Find("Ready/DeviceStatus").gameObject.SetActive(!flag);
//transform.Find("Ready/DeviceStatusConnect").gameObject.SetActive(flag);
@@ -238,26 +237,39 @@ public class RowerHomeScript : PFUIPanel
if (checkRowing()) return;
UIManager.ShowRowerDevicePanel();
});
UIManager.AddEvent(transform.Find("Stopped/DeviceStatus").gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, b =>
{
//if (checkRowing()) return;
UIManager.ShowRowerDevicePanel();
});
UIManager.AddEvent(transform.Find("Stopped/DeviceStatusConnect").gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, b =>
{
//if (checkRowing()) return;
UIManager.ShowRowerDevicePanel();
});
//手机版tab
#if UNITY_ANDROID || UNITY_IOS
var nav = transform.Find("MainNav-mobile").GetComponent<NewMainNav>();
var c1 = new NewMainNav.CustomButton(Resources.Load<Sprite>("Images/RowerNew/ICON_create_44"), () =>
{
//UIManager.ShowRowerWelldone("33171855-66FC-4121-935C-0F4DA98E5BB2", Init);
//UIManager.ShowRowerWelldone("31C5A37D-6ADD-4EE1-B6DA-5AA2F9949C4B", Init);
//return;
//UIManager.ShowRowerWelldone("C0F81E83-120B-4A2C-AD0E-8BC1B8EB3E74", Init);
//return;
if (checkRowing()) return;
if (C2RowerData.IsEnabled == true && C2RowerData.rowerType != null) return;
UIManager.ShowRowerTaskPanel(type=>
//if (C2RowerData.IsEnabled == true && C2RowerData.rowerType != null) return;
UIManager.ShowRowerTaskPanel(type =>
{
rowerType = type;
if(C2RowerData.IsEnabled)
HandleC2RowerTaskPanel(type);//处理app自定义课程同步到c2划船机
HandleSelectType();
},rowerType);
}, rowerType);
}, false);
var c2 = new NewMainNav.CustomButton(Resources.Load<Sprite>("Images/RowerNew/记录"), () =>
var c2 = new NewMainNav.CustomButton(Resources.Load<Sprite>("Images/RowerNew/记录"), () =>
{
if (checkRowing()) return;
UIManager.ShowResultListPanel();
}, false);
btnStart = transform.Find("MainNav-mobile/Custom2").gameObject;
@@ -278,25 +290,56 @@ public class RowerHomeScript : PFUIPanel
{
Discard();
});
if (RowerData != null)
if (RowerData != null)
{
RowerData.PullChanged -= PaintPullCurve;
RowerData.PullChanged += PaintPullCurve;
RowerData.StartEvent -= StartFunc;
RowerData.StartEvent += StartFunc;
RowerData.CompleteEvent -= CompelteFunc;
RowerData.CompleteEvent += CompelteFunc;
}
rowerType = new RowerType { type = 1, value = 500 };
HandleSelectType();
Init();
isFirstReset = false;
}
void HandleC2RowerTaskPanel(RowerType rowerType)
{
if (!C2RowerData.IsEnabled)
return;
RowerCommand currentCommand = RowerCommand.JustRow;
if (rowerType.type == 0 && rowerType.value == 0)
{
currentCommand = RowerCommand.JustRow;
}
if (rowerType.type == 1 && rowerType.value >= 100)
{
currentCommand = RowerCommand.FixedDistance;
}
if (rowerType.type == 2 && rowerType.value > 0)
{
currentCommand = RowerCommand.FixedTime;
}
Rower?.SendCommand(currentCommand, (int)rowerType.value);
}
IEnumerator SetResistanceLevel(ushort res)
{
yield return new WaitForSeconds(0.1f);
if (Rower != null)
{
Rower.SetResistanceLevel(res);
}
}
RowerResultModel reRowData = null;
public void ReRow(RowerResultModel r)
{
this.reRowData = r;
if (r!= null && r.Type.HasValue)
if (r != null && r.Type.HasValue)
{
rowerType = new RowerType { type = r.Type.Value,value = (float)r.TypeValue.Value };
rowerType = new RowerType { type = r.Type.Value, value = (float)r.TypeValue.Value };
if (Rower != null)
{
Rower.Reset();
@@ -308,17 +351,34 @@ public class RowerHomeScript : PFUIPanel
if (rowerType.type == 0)
{
dw = $"\nM/ 30Min";
}
else if (rowerType.type == 2)
}
else if (rowerType.type == 2)
{
dw = $"\nM";
}
bottom.Find("Expected/Title").GetComponent<Text>().text = $"{App.GetLocalString("EST")}{dw}";
}
}
private void Discard()
private void DeleteCacheDir()
{
//删除实时记录
try
{
var dir = $"{PFConstants.RowerRecordCacheFolder}/{App.CurrentUser.Id}/";
if (Directory.Exists(dir))
{
Helper.DelectDir(dir);
//Directory.Delete(dir, true);
}
}
catch (Exception e)
{
Debug.LogError(e.ToString());
}
}
private void Discard()
{
openTimer = false;
if (Application.internetReachability == NetworkReachability.NotReachable)
{
transform.Find("Stopped").gameObject.SetActive(true);
@@ -326,8 +386,9 @@ public class RowerHomeScript : PFUIPanel
return;
}
transform.Find("Stopped").gameObject.SetActive(false);
openTimer = false;
isPause = true;
DeleteCacheDir();
historyTime = 0;
if (C2RowerData.IsEnabled == true)
{
Utils.showToast(null, "Press \"Menu\" to save.", int.MaxValue, stopFunc: () => C2RowerData.isReadyStatus, endCallback: Init);
@@ -362,12 +423,17 @@ public class RowerHomeScript : PFUIPanel
//Utils.showToast(null, "请滑动划船机并开始", isLowest: true, type: 1);
}
protected override void OnDisable()
{
base.OnDisable();
//App.MainDeviceAdapter.StopScan();
}
public override void Show()
{
base.Show();
//var mainNav = this.transform.Find("MainNav").GetComponent<MainNav>();
//mainNav.ShowRowerTab();
//App.MainDeviceAdapter.StartScan();
transform.MyDOFade();
//Debug.Log("140,开始扫描");
//App.MainDeviceAdapter.StartScan();
@@ -375,18 +441,18 @@ public class RowerHomeScript : PFUIPanel
CheckLocalData();
//transform.Find("Left/Rower").GetComponent<RowerAnimation>().StartAnimation();
}
void Disconnect()
void Disconnect()
{
foreach(var d in App.MainDeviceAdapter.GetDevices())
foreach (var d in App.MainDeviceAdapter.GetDevices())
{
if ((d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && (d.Sensor == SensorType.Rower || d.Sensor == SensorType.HeartRate))
if ((d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && (d.Sensor == SensorType.Rower || d.Sensor == SensorType.HeartRate))
{
d.Disconnect();
}
}
App.MainDeviceAdapter.StopScan();
}
void HandleDiscardDirect()
void HandleDiscardDirect()
{
openTimer = false;
isPause = true;
@@ -395,7 +461,7 @@ public class RowerHomeScript : PFUIPanel
btnStart.tag = "Start";
Init();
}
void HandleSaveDirect()
void HandleSaveDirect()
{
openTimer = false;
isPause = true;
@@ -410,7 +476,7 @@ public class RowerHomeScript : PFUIPanel
{
if (Save()) Init();
}
else
else
{
if (SaveFunc(tempRecordData.model, tempRecordData.files)) Init();
}
@@ -420,7 +486,7 @@ public class RowerHomeScript : PFUIPanel
{
Utils.showToast(null, "Press \"Menu\" to save.", int.MaxValue, stopFunc: () => C2RowerData.isReadyStatus, endCallback: f);
}
else
else
{
f.Invoke();
}
@@ -429,9 +495,29 @@ public class RowerHomeScript : PFUIPanel
int truelyTime = 0;
private void StartFunc(object sender, EventArgs e)
{
var bleDevice = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower) as BleDevice;
if (bleDevice != null)
{
deviceName = bleDevice.Name;
deviceNetwork = bleDevice.Network.ToString();
deviceAddress = bleDevice.Address;
deviceSensor = bleDevice.Sensor.ToString();
}
var rowdata = (IRowerCommonData)sender;
if (rowdata != RowerData)
return;
Debug.Log($"开始了:{openTimer}-{DateTime.Now}");
if (UIManager.Instance.confirm != null && UIManager.Instance.confirm.IsActive())
{
print("当前有弹窗");
return;
}
if (openTimer) return;
Id = Guid.NewGuid().ToString();
if (transform.parent.parent.Find("ModalPanel/RowerWelldone(Clone)") && transform.parent.parent.Find("ModalPanel/RowerWelldone(Clone)").gameObject.activeInHierarchy)
if (transform.parent.parent.Find("ModalPanel/RowerWelldone(Clone)") && transform.parent.parent.Find("ModalPanel/RowerWelldone(Clone)").gameObject.activeInHierarchy)
{
return;
}
@@ -443,7 +529,7 @@ public class RowerHomeScript : PFUIPanel
}
if (!isPause)
{
}
if (!openTimer)
{
@@ -452,7 +538,7 @@ public class RowerHomeScript : PFUIPanel
truelyTime = historyTime;
//TimerTicks();
openTimer = true;
timer = 1.0f;
timer = 0f;
}
transform.Find("Ready").gameObject.SetActive(false);
//if (UIManager.Instance.RowerWelldone)
@@ -462,15 +548,49 @@ public class RowerHomeScript : PFUIPanel
btnStart.GetComponent<Image>().sprite = spriteDict["Untagged"];
btnStart.tag = "Untagged";
}
private bool SaveFunc(RowerRecordModel model, List<string> files)
private void CompelteFunc(object sender, EventArgs e)
{
if (Application.internetReachability == NetworkReachability.NotReachable)
var rowdata = (IRowerCommonData)sender;
if (rowdata != RowerData)
return;
var heartRate = HeartRate ?? 0;
var energy = RowerData.TotalEnergy;
var strokeCount = RowerData.StrokeCount;
var power = RowerData.InstantaneousPower;
var rate = RowerData.StrokeRate;
if (rowerType.type == 1)
{
TimeText.text = $"{RowerData.ElapsedTime}";
KMText.text = "0";
}
else
{
TimeText.text = TimeSpan.FromSeconds(0).ToPFString();
KMText.text = $"{RowerData.TotalDistance}";
}
records.Add($"{strokeCount},{RowerData.ElapsedTime},{RowerData.TotalDistance},{RowerData.InstantaneousPower},{RowerData.InstantaneousPace},{RowerData.StrokeRate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{RowerData.ElapsedTime}");
var tmpdata = new TempRowerCalc() { strokeCount = strokeCount, pace = RowerData.InstantaneousPace, power = power, rate = rate, heartRate = heartRate, distance = (int)RowerData.TotalDistance, energy = energy };
values.Add(tmpdata);
SendDataToRace(tmpdata);
HandleSaveDirect();
}
private bool SaveFunc(RowerRecordModel model, List<string> files)
{
if (Application.internetReachability == NetworkReachability.NotReachable)
{
transform.Find("Stopped").gameObject.SetActive(true);
Utils.showToast(null, App.GetLocalString("Please check the network status!"));
tempRecordData = new TempRecordData(model, files);
return false;
}
model.ManufacturerName = deviceName + " " + deviceNetwork + " " + deviceSensor;
model.DeviceNumber = $"{ deviceAddress },{ deviceSensor }";
var res = ConfigHelper.rowerApi.Add(model, files);
if (res.result)
{
@@ -481,6 +601,7 @@ public class RowerHomeScript : PFUIPanel
{
File.Delete(files[0]);
}
DeleteCacheDir();
}
catch (Exception ex)
{
@@ -494,31 +615,47 @@ public class RowerHomeScript : PFUIPanel
tempRecordData = null;
return true;
}
public class TempRecordData
public class TempRecordData
{
public RowerRecordModel model;
public List<string> files;
public TempRecordData(RowerRecordModel model, List<string> files)
public TempRecordData(RowerRecordModel model, List<string> files)
{
this.model = model;
this.files = files;
}
}
TempRecordData tempRecordData;
private bool Save()
private string deviceName { get; set; }
private string deviceNetwork { get; set; }
private string deviceSensor { get; set; }
private string deviceAddress { get; set; }
private bool Save(string shadowids = null)
{
var bleDevice = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower) as BleDevice;
RowerRecordModel model = new RowerRecordModel();
model.Ticks = records.Count;
if (bleDevice != null)
var bleDevice = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower) as BleDevice;
if (bleDevice != null)
{
model.ManufacturerName = bleDevice.Name + " " + bleDevice.Network + " " + bleDevice.Sensor;
model.DeviceNumber = $"{ bleDevice.Address },{ bleDevice.Sensor }";
}
else
{
model.ManufacturerName = deviceName + " " + deviceNetwork + " " + deviceSensor;
model.DeviceNumber = $"{ deviceAddress },{ deviceSensor }";
}
model.Id = Id;//Guid.NewGuid().ToString();
model.Weight = App.CurrentUser.Weight;
model.Kj = RowerData.TotalEnergy;
model.StartTime = startTime;
if (string.IsNullOrEmpty(shadowids))
{
model.StartTime = startTime;
}
else
{
model.StartTime = createTime.Value.AddSeconds(-values.Count);
}
model.CreateTime = createTime.Value;
Debug.Log(values.Count);
if (values.Count > 0)
@@ -536,11 +673,13 @@ public class RowerHomeScript : PFUIPanel
model.AvgHeartRate = (int)values.Average(x => x.heartRate);
model.StrokeCount = (ushort)values.Max(x=>x.strokeCount);
model.TotalDistance = (ushort)values.Max(x => x.distance);
model.Kj = values.Max(x => x.energy);
}
model.TotalTime = RowerData.ElapsedTime;
model.TotalTime = records.Count;
model.Type = rowerType.type == 0 ? (int?)null : rowerType.type;
model.TypeValue = rowerType.value == 0 ? (float?)null : rowerType.value;
model.ShadowIds = string.Join(",",GetComponent<RowerMultiModeScript>().shadowList.Select(x=>x.Nid));
model.ShadowIds = string.IsNullOrEmpty(shadowids)?string.Join(",",GetComponent<RowerMultiModeScript>().shadowList.Select(x=>x.Nid)):shadowids;
var path = PFConstants.RowerRecordFolder + "/" + model.Id;
Helper.CreateDirectoryIfNotExsit(path);
var files = new List<string>();
@@ -573,15 +712,21 @@ public class RowerHomeScript : PFUIPanel
private void Init()
{
ResetChart();
deviceName = "";
deviceNetwork = "";
deviceAddress = "";
deviceSensor = "";
pointCount = 0;
print("初始化");
if (RowerData != null)
{
RowerData.Reset();
}
if (Rower != null)
if (Rower != null)
{
Rower.Reset();
}
//if (RowerData != null)
//{
// RowerData.Reset();
//}
GetComponent<RowerMultiModeScript>().GetShadowList(rowerType, reRowData);
btnStart.tag = "Start";
btnStart.GetComponent<Image>().sprite = spriteDict["Start"];
@@ -674,6 +819,8 @@ public class RowerHomeScript : PFUIPanel
RowerData.PullChanged += PaintPullCurve;
RowerData.StartEvent -= StartFunc;
RowerData.StartEvent += StartFunc;
RowerData.CompleteEvent -= CompelteFunc;
RowerData.CompleteEvent += CompelteFunc;
RowerData.RowerResChanged -= ResChanged;
RowerData.RowerResChanged += ResChanged;
}
@@ -684,13 +831,15 @@ public class RowerHomeScript : PFUIPanel
private void ResChanged(object sender, EventArgs e)
{
if ((Convert.ToSingle(sender) >= 50) && slider)
var originData = (IRowerCommonData)sender;
if (slider && RowerData!= null && originData == RowerData)
{
slider.GetComponent<PFUISlider>().SetValue((Convert.ToSingle(sender) - 50) / 300f);
var origin = RowerData.ResistanceLevel;
var wrapped = origin< 50 ? 50 : origin;
slider.GetComponent<PFUISlider>().SetValue((wrapped - 50) / 300f,false);
}
}
public bool checkRowing()
{
if (seconds > 0)
@@ -735,36 +884,55 @@ public class RowerHomeScript : PFUIPanel
private Text rmyAvgForceText { get; set; }
private Text PeakForceText { get; set; }
private Text rmyPeakForceText { get; set; }
private bool interruptFlag{ get; set; }
void TimerTicks()
void TimerTicks()
{
var heartRate = HeartRate ?? 0;
#if UNITY_EDITOR
var a = tempList[(tempx++) % tempList.Count];
//Debug.Log(a);
PaintPullCurve((ushort)(a / 10));
if (RowerData == null) return;
#endif
#if !UNITY_EDITOR
//#if !UNITY_EDITOR
if (Rower == null)
{
HandleDiscardDirect();
interruptFlag = true;
//HandleDiscardDirect();
isPause = true;
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Save the game?"), () =>
{
HandleSaveDirect();
UIManager.CloseConfirm();
interruptFlag = false;
}, 2, ()=> {
Init();
interruptFlag = false;
});
return;
}
if (interruptFlag) {
transform.Find("Stopped").gameObject.SetActive(false);
return;
}
if (RowerData == null) return;
#endif
var heartRate = HeartRate ?? 0;
BPMText.text = heartRate.ToString();
//断线重连继续
//#endif
//断线重连继续()
var distance = (int)RowerData.TotalDistance + historyDistance;
var energy = RowerData.TotalEnergy + historyEnergy;
var strokeCount = RowerData.StrokeCount + historyStrokeCount;
var power = RowerData.InstantaneousPower;
var rate = RowerData.StrokeRate;
truelyTime++;
Debug.Log($"ElapsedTime :{RowerData.ElapsedTime} : {truelyTime}-{RowerData.TotalDistance}");
TempRowerCalc tmpdata = null;
//解决C2里程训练无法结束的问题
var c2notStop = C2RowerData.IsEnabled && rowerType!=null && rowerType.type !=0 && (rowerType.value-totalDistance) <= 5;
//里程停止逻辑
if (totalDistance == RowerData.TotalDistance + historyDistance)
if (totalDistance == RowerData.TotalDistance && !c2notStop)
{
//判定一次停止
stopSeconds++;
@@ -776,6 +944,12 @@ public class RowerHomeScript : PFUIPanel
}
if (stopSeconds >= 2)
{
Debug.Log($"stopSeconds:{RowerData.TotalDistance}");
if (UIManager.Instance.confirm != null && UIManager.Instance.confirm.IsActive()) {
Debug.Log("stopSeconds >= 2");
transform.Find("Stopped").gameObject.SetActive(false);
return;
}
transform.Find("Stopped").gameObject.SetActive(true);
//if (stopSeconds == 6)
//{
@@ -897,18 +1071,19 @@ public class RowerHomeScript : PFUIPanel
KMText.text = totalDistance.ToString();
}
records.Add($"{strokeCount},{RowerData.ElapsedTime},{distance},{RowerData.InstantaneousPower},{RowerData.InstantaneousPace},{RowerData.StrokeRate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{truelyTime}");
tmpdata = new TempRowerCalc() { strokeCount = strokeCount, pace = pace, power = power, rate = rate, heartRate = heartRate, distance = distance, energy = energy };
values.Add(tmpdata);
SendDataToRace(tmpdata);
if (C2RowerData.IsEnabled == true && C2RowerData.isReadyStatus && values.Count()>10)
if (truelyTime > 0)
{
HandleSaveDirect();
records.Add($"{strokeCount},{RowerData.ElapsedTime},{distance},{RowerData.InstantaneousPower},{RowerData.InstantaneousPace},{RowerData.StrokeRate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{truelyTime}");
tmpdata = new TempRowerCalc() { strokeCount = strokeCount, pace = pace, power = power, rate = rate, heartRate = heartRate, distance = distance, energy = energy };
values.Add(tmpdata);
SendDataToRace(tmpdata);
}
if (ticks % 5 == 0)
{
SaveRealTimes();//实时保存数据
}
truelyTime++;
}
//检查本地数据
int historyDistance = 0,historyStrokeCount = 0,historyEnergy = 0;
@@ -924,44 +1099,58 @@ public class RowerHomeScript : PFUIPanel
var files = Directory.GetFiles(dir);
if (files.Length == 0)
return;
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Continue the game?"), () =>
var historyRowerTime = PlayerPrefs.GetString("historyRowerTime");
deviceName = PlayerPrefs.GetString("deviceName");
deviceNetwork = PlayerPrefs.GetString("deviceNetwork");
deviceAddress = PlayerPrefs.GetString("deviceAddress");
deviceSensor = PlayerPrefs.GetString("deviceSensor");
if (!string.IsNullOrEmpty(historyRowerTime))
{
var str = File.ReadAllText(files[0]);
var list = str.Replace("\r\n", " ").Split(' ');
records.Clear();
foreach (var item in list)
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Save the game?"), () =>
{
if (!string.IsNullOrEmpty(item))
var str = File.ReadAllText(files[0]);
var list = str.Replace("\r\n", " ").Split(' ');
records.Clear();
foreach (var item in list)
{
records.Add(item);
}
//records.Add($"{strokeCount},{RowerData.ElapsedTime},{distance},{power},{pace},{rate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{truelyTime}");
var _re = records.LastOrDefault();
if (!string.IsNullOrEmpty(_re))
{
var datas = _re.Split(',');
historyStrokeCount = int.Parse(datas[0]);
historyDistance = int.Parse(datas[2]);
historyTime = int.Parse(datas[10]);
seconds = historyTime;
historyEnergy = int.Parse(datas[8]);
var historyRowerType = PlayerPrefs.GetString("historyRowerType");
if (!string.IsNullOrEmpty(historyRowerType))
if (!string.IsNullOrEmpty(item))
{
var typeObject = historyRowerType.Split(',');
rowerType = new RowerType() { type = int.Parse(typeObject[0]), value = float.Parse(typeObject[1]) };
HandleSelectType();
var datas = item.Split(',');
records.Add(item);
values.Add(new TempRowerCalc()
{
strokeCount = int.Parse(datas[0]),
pace = ushort.Parse(datas[4]),
power = int.Parse(datas[3]),
rate = uint.Parse(datas[5]),
heartRate = int.Parse(datas[7]),
distance = int.Parse(datas[2]),
energy = int.Parse(datas[8])
});
}
//records.Add($"{strokeCount}0,{RowerData.ElapsedTime},{distance}2,{power}3,{pace}4,{rate}5,{RowerData.ResistanceLevel},{heartRate}7,{energy}8,{RowerData.AveragePower},{truelyTime}");
}
}
Helper.DelectDir(dir);
UIManager.CloseConfirm();
}, 2,
() =>
{
Helper.DelectDir(dir);
UIManager.CloseConfirm();
});
var historyRowerType = PlayerPrefs.GetString("historyRowerType");
if (!string.IsNullOrEmpty(historyRowerType))
{
var typeObject = historyRowerType.Split(',');
rowerType = new RowerType() { type = int.Parse(typeObject[0]), value = float.Parse(typeObject[1]) };
}
createTime = UIManager.Now.GetDateTime();
Save(PlayerPrefs.GetString("historyRowerShadowIds"));
Helper.DelectDir(dir);
UIManager.CloseConfirm();
}, 2,
() =>
{
Helper.DelectDir(dir);
UIManager.CloseConfirm();
if (Rower != null)
{
Rower.Reset();
}
});
}
}
}
catch (Exception e)
@@ -981,7 +1170,16 @@ public class RowerHomeScript : PFUIPanel
Directory.CreateDirectory(dir);
}
File.WriteAllText(path, string.Join("\r\n", records));
//File.WriteAllText($"{PFConstants.RowerRecordCacheFolder}/cache.txt", string.Join("\r\n", App.cacheList));
PlayerPrefs.SetString("deviceName", deviceName);
PlayerPrefs.SetString("deviceNetwork", deviceNetwork);
PlayerPrefs.SetString("deviceAddress", deviceAddress);
PlayerPrefs.SetString("deviceSensor", deviceSensor);
PlayerPrefs.SetString("historyRowerType", $"{rowerType.type},{rowerType.value}");
PlayerPrefs.SetString("historyRowerTime", UIManager.Now.GetDateTime().ToString());
PlayerPrefs.SetString("historyRowerShadowIds", string.Join(",", GetComponent<RowerMultiModeScript>().shadowList.Select(x => x.Nid)));
//Debug.Log(Convert.ToDateTime());
}
catch (Exception e)
{
@@ -1005,7 +1203,10 @@ public class RowerHomeScript : PFUIPanel
void PaintPullCurve(object sender, EventArgs e)
{
//防止设备断开重连rowData对象发生变化,事件重复触发
var ftms = (IRowerCommonData)sender;
if (RowerData != ftms)
return;
//Debug.Log(ftms.PullValue);
PaintPullCurve(ftms.PullValue);
}
@@ -1013,8 +1214,7 @@ public class RowerHomeScript : PFUIPanel
int pointCount = 0;
void PaintPullCurve(ushort y)
{
Debug.Log("收到拉力" + y + ","+ DateTime.Now.Ticks);
//Debug.Log($"收到拉力 x={x} , y={y}");
//#if !UNITY_EDITOR
// if (!openTimer)
// {
@@ -1035,7 +1235,6 @@ public class RowerHomeScript : PFUIPanel
if (rate > 1) rate = 1f;
leftImage.fillAmount = rate;
rightImage.fillAmount = rate;
//动画
//left.Find("Rower").GetComponent<Image>().sprite = spriteDict[y / 67];
//曲线
@@ -1044,11 +1243,11 @@ public class RowerHomeScript : PFUIPanel
//if (pullList.Count == 0)
if(pointCount == 0)
{
ClearChart();
isPlay = true;
x = 0.1;
x = 0;
pointCount++;
pullList.Add(new DoubleVector2(x, y));
//SetChartData(pullList, historyPullList);
SetChartData(x, y);
}
//else if (pullList.Count > 1)
@@ -1058,19 +1257,19 @@ public class RowerHomeScript : PFUIPanel
pointCount++;
pullList.Add(new DoubleVector2(x, y));
SetChartData(x, y);
//SetChartData(pullList, historyPullList);
//historyPullList = pullList.Select(x => x).ToList();
historyPullList = pullList.Select(x => x).ToList();
pullList.Clear();
pointCount = 0;
ClearChart();
x = 0.1;
isPlay = true;
pullList.Add(new DoubleVector2(x, y));
//x = 0.1;
//SetChartData(x, y);
pointCount = 1;
//isPlay = true;
//pullList.Add(new DoubleVector2(x, y));
}
else
{
//只有0并且两秒没拉,曲线消失
if (stopSeconds == 1)
if (stopSeconds == 1)
{
ClearChart();
//SetChartData(new List<DoubleVector2>(), new List<DoubleVector2>());
@@ -1079,6 +1278,12 @@ public class RowerHomeScript : PFUIPanel
}
else
{
if (pullList.Count(x => x.y == 0) == pullList.Count)
{
ClearChart();
pointCount = 0;
//SetChartData(0.1, 0);
}
x += 0.1;
pointCount++;
pullList.Add(new DoubleVector2(x, y));
@@ -1107,18 +1312,23 @@ public class RowerHomeScript : PFUIPanel
}
void ClearChart()
{
rowerGraphChartFeed.ClearChart();
graphChartFeed.ClearChart();
if (x > 0)
{
rowerGraphChartFeed.ClearChart();
graphChartFeed.ClearChart();
x = 0;
}
}
void ResetChart() {
rowerGraphChartFeed?.ResetChart();
graphChartFeed?.ResetChart();
}
double preX, preY;
void SetChartData(double x, double y)
{
if (M1.localPosition.x == 0)
{
rowerGraphChartFeed.SetCurrentPoint(x, y);
var index = pullList.Count - 1 < 0 ? 0 : pullList.Count - 1;
var pre = pullList[index];
rowerGraphChartFeed.SetPrePoint(pre.x, pre.y);
rowerGraphChartFeed.SetHistoryData(x, historyPullList);
}
else
{
@@ -1131,7 +1341,7 @@ public class RowerHomeScript : PFUIPanel
//graph.DataSource.AddPointToCategoryRealtime("Player 2", item.x, item.y);
if (M1.localPosition.x == 0)
{
rowerGraphChartFeed.SetData(v1, v2);
rowerGraphChartFeed.SetData(v1, v2);
}
else
{
@@ -1143,60 +1353,49 @@ public class RowerHomeScript : PFUIPanel
int ticks { get; set; } = 0;
void Update()
{
#if UNITY_EDITOR
if (openTimer || true)
#else
if (openTimer)
#endif
shortTimer -= Time.deltaTime;
if (shortTimer <= 0)
{
timer -= Time.deltaTime;
shortTimer -= Time.deltaTime;
if (shortTimer <= 0)
{
ShortUpdateData();
shortTimer += 0.25f;
}
if (openTimer && timer <= 0)
ShortUpdateData();
shortTimer += 0.25f;
}
timer -= Time.deltaTime;
if (timer <= 0)
{
#if UNITY_EDITOR
if (openTimer || true)
#else
if (openTimer)
#endif
{
TimerTicks();
ticks++;
timer = 1f + timer;
}
}
staticTimer -= Time.deltaTime;
if (staticTimer <= 0)
{
var heartRate = HeartRate ?? 0;
BPMText.text = heartRate == 0 ? "---" : heartRate.ToString();
HandleStatic();
staticTimer += 1f;
}
//shortTimer -= Time.deltaTime;
//if (shortTimer <= 0)
//{
// if (openTimer)
// {
// ShortUpdateData();
// }
// shortTimer += 0.5f;
//}
timer += 1f ;
}
}
void ShortUpdateData()
{
if (!openTimer) return;
if (RowerData == null) return;
var power = RowerData.InstantaneousPower;
var rate = RowerData.StrokeRate;
var pace = RowerData.InstantaneousPace;
var strokeCount = RowerData.StrokeCount;
var distance = (int)RowerData.TotalDistance;
var energy = RowerData.TotalEnergy;
var strokeCount = RowerData.StrokeCount + historyStrokeCount;
var energy = RowerData.TotalEnergy + historyEnergy;
var heartRate = HeartRate ?? 0;
if (rowerType.type == 1 && totalDistance >=rowerType.value && !createTime.HasValue)
if (rowerType.type == 1 && totalDistance >= rowerType.value && !createTime.HasValue)
{
openTimer = false;
KMText.text = "0";
records.Add($"{strokeCount},{RowerData.ElapsedTime},{distance},{power},{pace},{rate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{truelyTime}");
var tmpdata = new TempRowerCalc() { strokeCount = strokeCount, pace = pace, power = power, rate = rate, heartRate = heartRate, distance = distance, energy = energy };
records.Add($"{strokeCount},{RowerData.ElapsedTime},{rowerType.value},{power},{pace},{rate},{RowerData.ResistanceLevel},{heartRate},{energy},{RowerData.AveragePower},{truelyTime}");
var tmpdata = new TempRowerCalc() { strokeCount = strokeCount, pace = pace, power = power, rate = rate, heartRate = heartRate, distance = (int)rowerType.value, energy = energy };
values.Add(tmpdata);
SendDataToRace(tmpdata);
HandleSaveDirect();
@@ -1212,19 +1411,31 @@ public class RowerHomeScript : PFUIPanel
MSText.text = rate.ToString();
}
bool isFirstReset = false;
void HandleStatic()
{
var flag = Rower != null && RowerData != null && !(UIManager.Instance.confirm != null && UIManager.Instance.confirm.IsActive());
if (transform.Find("Ready").gameObject.activeInHierarchy)
{
var flag = Rower != null && RowerData != null;
transform.Find("Ready/DeviceStatus").gameObject.SetActive(!flag);
transform.Find("Ready/Img").gameObject.SetActive(flag);
transform.Find("Ready/Text").gameObject.SetActive(flag);
transform.Find("Ready/DeviceStatusConnect").gameObject.SetActive(flag);
if (flag && RowerData.TotalDistance != 0)
{
Rower.Reset();
if(C2RowerData.IsEnabled)
RowerData.Reset();
}
}
if (transform.Find("Stopped").gameObject.activeInHierarchy)
{
transform.Find("Stopped/DeviceStatus").gameObject.SetActive(!flag);
transform.Find("Stopped/DeviceStatusConnect").gameObject.SetActive(flag);
}
if (Rower != null)
{
if (C2RowerData.IsEnabled == true && !openTimer && !isPause && C2RowerData.rowerType!=null)
if (C2RowerData.IsEnabled == true && !openTimer && !isPause && C2RowerData.rowerType!=null && rowerType!= null && !rowerType.EqualTo(C2RowerData.rowerType))
{
rowerType = C2RowerData.rowerType;
HandleSelectType();
@@ -2,6 +2,7 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.UI;
public class RowerDevicePanel : PFUIPanel
@@ -10,6 +11,7 @@ public class RowerDevicePanel : PFUIPanel
{
UIManager.AddEvent(transform.Find("Container/Tools/Back").gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, b =>
{
App.MainDeviceAdapter.StopScan();
Close();
});
}
@@ -25,6 +27,18 @@ public class RowerDevicePanel : PFUIPanel
#if UNITY_ANDROID || UNITY_IOS
#if UNITY_ANDROID
Utils.CallAndroidMethod("OpenLocationService");
if (!Permission.HasUserAuthorizedPermission(Permission.CoarseLocation))
{
Permission.RequestUserPermission(Permission.CoarseLocation);
Permission.RequestUserPermission(Permission.FineLocation);
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Powerfun need location service permission,please open the location permission.")
, () => {
UIManager.CloseConfirm();
}, 2
, () => {
UIManager.CloseConfirm();
});
}
#endif
App.MainDeviceAdapter.StartScan();
#endif
@@ -35,7 +35,7 @@ public class RowerDeviceView : MonoBehaviour
private GameObject mDisconnectButton;
private GameObject unconnectionPanel;
private GameObject connectionPanel;
private Text searchState;
private Text searchState,connSearchState;
private ConnectDeviceModal deviceModal;
private Text title;
private Text noDevice;
@@ -58,7 +58,7 @@ public class RowerDeviceView : MonoBehaviour
/// </summary>
private Sprite sprite3;
private float timer = 1.0f;
private float timer = 0f;
private void Awake()
{
title = this.transform.Find("Title").GetComponent<Text>();
@@ -69,7 +69,7 @@ public class RowerDeviceView : MonoBehaviour
searchState = unconnectionPanel.transform.Find("SearchState").GetComponent<Text>();
//mPairButton.SetActive(false);
connectionPanel = this.transform.Find("ConnectionPanel").gameObject;
connSearchState = connectionPanel.transform.Find("SearchState").GetComponent<Text>();
var material = Instantiate(Resources.Load<Material>("UI/Material/RoundedCornersTextureMaterial"));
var rect = ((RectTransform)transform).rect;
material.SetVector(Shader.PropertyToID("_WidthHeightRadius"), new Vector4(rect.width, rect.height, rect.height * 0.2f, 0));
@@ -132,9 +132,10 @@ public class RowerDeviceView : MonoBehaviour
var device = GetDevice();
if (device != null && device.State == DeviceState.Connected)
{
UIManager.ShowConfirm("警告", "是否断开该设备?", () =>
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Disconnect the device?"), () =>
{
device.Disconnect(false);
DeviceCache.Remove(device);
UIManager.CloseConfirm();
}, 2, () => {
UIManager.CloseConfirm();
@@ -146,11 +147,12 @@ public class RowerDeviceView : MonoBehaviour
}
});
UIManager.AddEvent(mDisconnectButton, EventTriggerType.PointerClick, new UnityEngine.Events.UnityAction<BaseEventData>(e => {
UIManager.ShowConfirm("警告", "是否断开该设备?", () =>
UIManager.ShowConfirm(App.GetLocalString("Warning"), App.GetLocalString("Disconnect the device?"), () =>
{
var device = GetDevice();
if (device != null && device.State == DeviceState.Connected)
{
DeviceCache.Remove(device);
device.Disconnect(false);
}
UIManager.CloseConfirm();
@@ -271,9 +273,8 @@ public class RowerDeviceView : MonoBehaviour
connectionPanel.SetActive(false);
logo.sprite = sprite0;
noDevice.text = App.GetLocalString("NO DEVICE");
searchState.text = App.GetLocalString("Searching...");
var hasDevice = false;
if (SensorType == SensorType.SpeedCadence)
{
@@ -283,6 +284,8 @@ public class RowerDeviceView : MonoBehaviour
{
hasDevice = App.MainDeviceAdapter.GetDevices().Any(d => d.Sensor == SensorType);
}
searchState.text = hasDevice ? App.GetLocalString("CHOOSE DEVICE") : App.GetLocalString("NO DEVICE");
noDevice.text = "";// App.GetLocalString("NOCONN DEVICE"); //hasDevice ? App.GetLocalString("CHOOSE DEVICE") : ;
if (hasDevice)
{
mSearchButton.SetActive(false);
@@ -346,7 +349,6 @@ public class RowerDeviceView : MonoBehaviour
}
logo.sprite = sprite3;
//title.text = connectedDevice.Name;
if (connectedDevice.Network == NetworkType.BLE)
{
@@ -2,6 +2,7 @@
using UnityEngine;
using ChartAndGraph;
using System.Collections;
using System.Linq;
using System.Collections.Generic;
public class RowerGraphChartFeed : MonoBehaviour
@@ -42,14 +43,45 @@ public class RowerGraphChartFeed : MonoBehaviour
}
public void SetCurrentPoint(double x,double y)
{
if(dataSource != null)
x += dataSource.HorizontalViewOrigin;
Debug.Log($"SetCurrentPoint:{x}-{y}");
dataSource?.AddPointToCategoryRealtime("Player 2", x, y);
}
public void ClearChart()
{
dataSource?.ClearCategory("Player 1");
dataSource?.ClearCategory("Player 2");
if (dataSource != null)
{
dataSource.HorizontalViewOrigin += 10;
SetCurrentPoint(0, 0);
}
}
public void SetHistoryData(double x,List<DoubleVector2> list2 = null)
{
if (list2 != null && list2.Count > 0)
{
var offset = dataSource.HorizontalViewOrigin;
graph.DataSource.AddPointToCategoryRealtime("Player 1", offset, 0);
for (int i = 0; i < list2.Count; i++)
{
var item = list2[i];
graph.DataSource.AddPointToCategoryRealtime("Player 1", item.x + offset, item.y);
}
}
}
public void ResetChart()
{
if (dataSource != null)
{
dataSource.HorizontalViewOrigin = -0.03;
dataSource.ClearCategory("Player 1");
dataSource.ClearCategory("Player 2");
}
}
public void SetData(List<DoubleVector2> list,List<DoubleVector2> list2 = null)
{
if (graph != null)
@@ -10,6 +10,8 @@ using UnityEngine.UI;
using Assets.Scripts.UI.Prefab.Login;
using Newtonsoft.Json;
using Assets.Scripts.UI.UIEffect;
using UnityEngine.Networking;
using Assets.Scripts.Apis;
public class RowerMultiModeScript : MonoBehaviour
{
@@ -197,49 +199,86 @@ public class RowerMultiModeScript : MonoBehaviour
public int diff { get; set; }
public int sumdiff { get; set; }
}
public Dictionary<int, RankDiff> rankDiffDict;
private IEnumerator Get(string url,Action<JsonResult<List<RowerRank>>> callback)
{
var request = new UnityWebRequest(url, "GET");
request.SetRequestHeader("Accept", "application/json");
request.SetRequestHeader("User-Agent", "PowerFun UnityApp/2.1.3 Android");
request.SetRequestHeader("Pf-User-Agent", "PowerFun UnityApp/2.1.3 Android");
request.SetRequestHeader("Cookie", $"PowerFun.AUTH={App.CurrentUser.cookie}");
request.SetRequestHeader("Language", App.GetLocalLanguage());
request.SetRequestHeader("deviceUniqueIdentifier", App.DeviceUniqueIdentifier);
request.SetRequestHeader("host", "pf.juze.pro");
//request.SetRequestHeader("Accept-Encoding", "gzip, deflate");
//defaultRequestHeaders.Add("deviceUniqueIdentifier", App.DeviceUniqueIdentifier);
//defaultRequestHeaders.Remove("Language");
//defaultRequestHeaders.Add("Language", App.GetLocalLanguage());
request.downloadHandler = new DownloadHandlerBuffer();
yield return request.SendWebRequest();
if (request.isHttpError || request.isNetworkError)
{
Debug.LogError(request.error);
}
else
{
var res = JsonConvert.DeserializeObject<JsonResult<List<RowerRank>>>(request.downloadHandler.text, new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
});
callback.Invoke(res);
//Debug.Log(request.downloadHandler.text);
}
}
public async void GetShadowList(RowerTaskPanel.RowerType rowerType, RowerResultModel reRowData)
{
this.rowerType = rowerType;
currentSecond = GetComponent<RowerHomeScript>().historyTime - 1;
//if(Application.internetReachability == NetworkReachability.NotReachable)
var res = reRowData ==null? await ConfigHelper.rowerApi.GetShadowList(rowerType): await ConfigHelper.rowerApi.GetReRowShadowList(reRowData.Id);
shadowList = res.data;
//foreach (var t in traceList)
//{
// t.userId = 0;
// t.trace.gameObject.SetActive(false);
//}
var _tmpList = shadowList.Select(x => new TraceData
var url = $"{App.Host}Rower/GetShadowList?type={rowerType.type}&typeValue={rowerType.value}";
if (reRowData != null)
{
list = x.list,
NickName = x.NickName,
Avatar = x.WxHeadImg,
UserId = x.UserId,
isMine = false,
currentDistance = 0,
Country = x.Country
}).ToList();
myData = new TraceData();
myData.list = new List<RowerChartModel>();
myData.UserId = App.CurrentUser.Id;
myData.NickName = App.CurrentUser.Nickname;
myData.Avatar = App.CurrentUser.WxHeadImg;
myData.isMine = true;
myData.Country = App.CurrentUser.Country;
_tmpList.Insert(_tmpList.Count / 2, myData);
//_tmpList.Add(myData);
userList = _tmpList.OrderByDescending(x => x.currentDistance).ToList();
rankDiffDict = new Dictionary<int, RankDiff>();
for (int i = 0; i < userList.Count; i++)
{
userList[i].currentRank = i + 1;
rankDiffDict.Add(userList[i].UserId, new RankDiff { rank = userList[i].currentRank, diff = 0 });
url = $"{App.Host}Rower/GetReRowShadowList?Id={reRowData.Id}";
}
DisplayUserRanks(true);
DisplayTraces(true);
StartCoroutine(Get(url, (res) =>
{
shadowList = res.data;
var _tmpList = shadowList.Select(x => new TraceData
{
list = x.list,
NickName = x.NickName,
Avatar = x.WxHeadImg,
UserId = x.UserId,
isMine = false,
currentDistance = 0,
Country = x.Country
}).ToList();
myData = new TraceData();
myData.list = new List<RowerChartModel>();
myData.UserId = App.CurrentUser.Id;
myData.NickName = App.CurrentUser.Nickname;
myData.Avatar = App.CurrentUser.WxHeadImg;
myData.isMine = true;
myData.Country = App.CurrentUser.Country;
_tmpList.Insert(_tmpList.Count / 2, myData);
//_tmpList.Add(myData);
userList = _tmpList.OrderByDescending(x => x.currentDistance).ToList();
rankDiffDict = new Dictionary<int, RankDiff>();
for (int i = 0; i < userList.Count; i++)
{
userList[i].currentRank = i + 1;
rankDiffDict.Add(userList[i].UserId, new RankDiff { rank = userList[i].currentRank, diff = 0 });
}
DisplayUserRanks(true);
DisplayTraces(true);
}));
//App.Host + $"/Rower/GetShadowList?type={rowerType.type}&typeValue={rowerType.value}"
//var res = reRowData == null ? await ConfigHelper.rowerApi.GetShadowList(rowerType) : await ConfigHelper.rowerApi.GetReRowShadowList(reRowData.Id);
//return;
}
float GetStrokeSpeed(uint rate)
{
@@ -425,11 +464,11 @@ public class RowerMultiModeScript : MonoBehaviour
}
}
//if(!data.isMine) diffWidth = 101;
t.Find("Left/Rank").GetComponent<Text>().text = (userList.FindIndex(x => x.UserId == data.UserId) + 1).ToString("00");
if (is0to100(diffWidth))
{
var tWidth = (diffWidth / 100f) * width;
t.Find("Main/Boat").gameObject.SetActive(true);
t.Find("Left/Rank").GetComponent<Text>().text = (userList.FindIndex(x => x.UserId == data.UserId) + 1).ToString("00");
if (isAni)
{
t.Find("Main/Boat").DOLocalMoveX(21.5f + tWidth, 0.9f);
@@ -951,6 +990,7 @@ public class RowerMultiModeScript : MonoBehaviour
}
private void DisplayUserRanks(bool isRefresh = false)
{
if (!scrollRank) return;
if (isRefresh)
{
scrollRank.content.DestroyChildren();
@@ -22,6 +22,9 @@ public class RowerTaskPanel : PFUIPanel
/// 里程:m 时间:s
/// </summary>
public float value { get; set; }
public bool EqualTo(RowerType rowerType) {
return this.type == rowerType.type && this.value == rowerType.value;
}
}
Transform selector, distance, time;
public RowerType rowerType;
@@ -124,7 +124,14 @@ public class RowerWelldone : PFUIPanel
game.transform.Find("Content/Rank").GetComponent<Text>().text = item.rankNum.ToString("00");
game.transform.Find("Content/NickName").GetComponent<Text>().text = item.NickName;
Utils.DisplayImageTempDict(game.transform.Find("Content/Avatar").GetComponent<RawImage>(), item.WxHeadImg, caches);
game.transform.Find("Content/Time").GetComponent<Text>().text = data.info.Type == 1 ? TimeSpan.FromSeconds(item.Ticks).ToString(@"hh\:mm\:ss") : item.TotalDistance.ToString("#0M");
if (item.GradeStr.Contains("DNF"))
{
game.transform.Find("Content/Time").GetComponent<Text>().text = "DNF";
}
else
{
game.transform.Find("Content/Time").GetComponent<Text>().text = data.info.Type == 1 ? TimeSpan.FromSeconds(item.Ticks).ToString(@"hh\:mm\:ss") : item.TotalDistance.ToString("#0M");
}
game.transform.SetParent(rankContent);
game.transform.localScale = Vector3.one;
game.SetActive(true);
+2 -1
View File
@@ -1326,7 +1326,7 @@ public class UIManager : MonoBehaviour
}
}
Confirm confirm = null;
public Confirm confirm;
public static void ShowConfirm(string title, string content, UnityAction action,int type = 2,UnityAction cancel = null)
{
@@ -1349,6 +1349,7 @@ public class UIManager : MonoBehaviour
UIManager.Instance.confirm.Show();
UIManager.Instance.confirm.Set(title, content, action, cancel);
}
UIManager.Instance.confirm.transform.SetAsLastSibling();
UIManager.Instance.confirm.SetType(type);
}
public static void CloseConfirm()
+2
View File
@@ -294,6 +294,8 @@ public class UniWebView: MonoBehaviour {
/// </summary>
public void UpdateFrame() {
Rect rect = NextFrameRect();
if (listener == null)
return;
UniWebViewInterface.SetFrame(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
}
+2 -2
View File
@@ -256,7 +256,7 @@ PlayerSettings:
clonedFromGUID: c0afd0d1d80e3634a9dac47e8a0426ea
templatePackageId: com.unity.template.3d@4.2.8
templateDefaultScene: Assets/Scenes/SampleScene.unity
AndroidTargetArchitectures: 1
AndroidTargetArchitectures: 3
AndroidSplashScreenScale: 0
androidSplashScreen: {fileID: 0}
AndroidKeystoreName: '{inproject}: Assets/Plugins/Android/powerfun.keystore'
@@ -868,7 +868,7 @@ PlayerSettings:
platformArchitecture:
iPhone: 1
scriptingBackend:
Android: 0
Android: 1
Standalone: 0
il2cppCompilerConfiguration:
Standalone: 0