--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+internal static partial class Interop
+{
+ internal static class Libraries
+ {
+ public const string Stc = "libcapi-network-stc.so.0";
+ public const string Glib = "libglib-2.0.so.0";
+ public const string Libc = "libc.so.6";
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using Tizen;
+using Tizen.Network.Stc;
+using System.Runtime.InteropServices;
+
+/// <summary>
+/// The Interop class for Stc.
+/// </summary>
+internal static partial class Interop
+{
+ /// <summary>
+ /// The Stc native APIs.
+ /// </summary>
+ internal static class Stc
+ {
+ // Callback for Statistics Information
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate CallbackRet StatsInfoCallback(int result, IntPtr info, IntPtr userData);
+
+ // Callback for getting All Statistics Information in one handle
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
+ internal delegate void GetAllStatsFinishedCallback(int result, IntPtr infoList, IntPtr userData);
+
+ [DllImport(Libraries.Stc,EntryPoint = "stc_initialize")]
+ internal static extern int Initialize(out SafeStcHandle stc);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_deinitialize")]
+ internal static extern int Deinitialize(IntPtr stc);
+
+ [DllImport(Libraries.Stc,EntryPoint = "stc_get_all_stats")]
+ internal static extern int GetAllStats(SafeStcHandle stc, SafeFilterHandle filter, GetAllStatsFinishedCallback infoCb, IntPtr userData);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_foreach_all_stats")]
+ internal static extern int ForeachAllStats(IntPtr infoList, StatsInfoCallback infoCb, IntPtr userData);
+
+ internal static class Filter {
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_create")]
+ internal static extern int Create(SafeStcHandle stc, out SafeFilterHandle filter);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_destroy")]
+ internal static extern int Destroy(IntPtr filter);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_set_app_id")]
+ internal static extern int SetAppId(SafeFilterHandle filter, string appId);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_set_time_interval")]
+ internal static extern int SetTimeInterval(SafeFilterHandle filter, Int32 from, Int32 to);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_set_iface_type")]
+ internal static extern int SetInterfaceType(SafeFilterHandle filter, NetworkInterface ifaceType);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_rule_set_time_period")]
+ internal static extern int SetTimePeriod(SafeFilterHandle filter, NativeTimePeriodType timePeriod);
+ }
+
+ internal static class Info {
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_clone")]
+ internal static extern int StatsClone(IntPtr info, out SafeStatsHandle cloned);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_destroy")]
+ internal static extern int StatsDestroy(IntPtr info);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_app_id")]
+ internal static extern int GetAppId(SafeStatsHandle info, out string appId);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_iface_name")]
+ internal static extern int GetInterfaceName(SafeStatsHandle info, out string IfaceName);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_time_interval")]
+ internal static extern int GetTimeInterval(SafeStatsHandle info, out Int32 from, out Int32 to);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_iface_type")]
+ internal static extern int GetInterfaceType(SafeStatsHandle info, out NetworkInterface ifaceType);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_counter")]
+ internal static extern int GetCounter(SafeStatsHandle info, out long incoming, out long outgoing);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_roaming_type")]
+ internal static extern int GetRoaming(SafeStatsHandle info, out RoamingType roaming);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_protocol_type")]
+ internal static extern int GetProtocol(SafeStatsHandle info, out NetworkProtocol protocol);
+ [DllImport(Libraries.Stc,EntryPoint = "stc_stats_info_get_process_state")]
+ internal static extern int GetProcessState(SafeStatsHandle info, out ApplicationStateType state);
+ }
+
+ internal sealed class SafeFilterHandle : SafeHandle
+ {
+ public SafeFilterHandle() : base(IntPtr.Zero, true)
+ {
+ }
+
+ public SafeFilterHandle(IntPtr handle) : base(handle, true)
+ {
+ }
+
+ public override bool IsInvalid
+ {
+ get
+ {
+ return this.handle == IntPtr.Zero;
+ }
+ }
+
+ protected override bool ReleaseHandle()
+ {
+ int ret = Interop.Stc.Filter.Destroy(this.handle);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to release Filter handle, Error - " + (StcError)ret);
+ return false;
+ }
+ return true;
+ }
+ }
+
+ internal sealed class SafeStatsHandle : SafeHandle
+ {
+ public SafeStatsHandle() : base(IntPtr.Zero, true)
+ {
+ }
+
+ public SafeStatsHandle(IntPtr handle) : base(handle, true)
+ {
+ }
+
+ public override bool IsInvalid
+ {
+ get
+ {
+ return this.handle == IntPtr.Zero;
+ }
+ }
+
+ protected override bool ReleaseHandle()
+ {
+ int ret = Interop.Stc.Info.StatsDestroy(this.handle);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to release network statistics handle, Error - " + (StcError)ret);
+ return false;
+ }
+ return true;
+ }
+ }
+ }
+
+ internal static Int32 ConvertDateTimeToTimestamp(DateTime dateTime)
+ {
+ DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
+ return (Int32)((dateTime.ToUniversalTime() - epoch).TotalSeconds);
+ }
+
+ internal static DateTime ConvertTimestampToDateTime(Int32 timestamp)
+ {
+ DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
+ return epoch.AddSeconds(timestamp).ToLocalTime();
+ }
+}
--- /dev/null
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>netstandard2.0</TargetFramework>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\Tizen\Tizen.csproj" />
+ <ProjectReference Include="..\Tizen.Log\Tizen.Log.csproj" />
+ </ItemGroup>
+
+</Project>
--- /dev/null
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26228.64
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tizen.Network.Stc", "Tizen.Network.Stc.csproj", "{7DB9ED96-A996-4527-AE60-6B97E1E27A57}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {7DB9ED96-A996-4527-AE60-6B97E1E27A57}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7DB9ED96-A996-4527-AE60-6B97E1E27A57}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7DB9ED96-A996-4527-AE60-6B97E1E27A57}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7DB9ED96-A996-4527-AE60-6B97E1E27A57}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using Tizen.Internals.Errors;
+
+namespace Tizen.Network.Stc
+{
+ /// <summary>
+ /// Internal Enumeration for Stc time period.
+ /// </summary>
+ internal enum NativeTimePeriodType
+ {
+ /// <summary>
+ /// Unknown
+ /// </summary>
+ Unknown = 0,
+ /// <summary>
+ /// Hour
+ /// </summary>
+ Hour = 3600,
+ /// <summary>
+ /// Day
+ /// </summary>
+ Day = 86400,
+ /// <summary>
+ /// Week
+ /// </summary>
+ Week = 604800,
+ /// <summary>
+ /// Month
+ /// </summary>
+ Month = 2419200
+ }
+
+ /// <summary>
+ /// Enumeration for Stc time period.
+ /// </summary>
+ public enum TimePeriodType
+ {
+ /// <summary>
+ /// Hour
+ /// </summary>
+ Hour = 3600,
+ /// <summary>
+ /// Day
+ /// </summary>
+ Day = 86400,
+ /// <summary>
+ /// Week
+ /// </summary>
+ Week = 604800,
+ /// <summary>
+ /// Month
+ /// </summary>
+ Month = 2419200
+ }
+
+ /// <summary>
+ /// Enumeration for network interface type.
+ /// </summary>
+ public enum NetworkInterface
+ {
+ /// <summary>
+ /// Network interface type is uncategorized.
+ /// </summary>
+ Others = 0,
+ /// <summary>
+ /// Network interface type is datacall.
+ /// </summary>
+ Datacall,
+ /// <summary>
+ /// Network interface type is wifi.
+ /// </summary>
+ Wifi,
+ /// <summary>
+ /// Network interface type is wired.
+ /// </summary>
+ Wired,
+ /// <summary>
+ /// Network interface type is bluetooth.
+ /// </summary>
+ Bluetooth,
+ /// <summary>
+ /// Type for any network interface.
+ /// </summary>
+ All
+ }
+
+ /// <summary>
+ /// Internal Enumeration for network roaming type
+ /// </summary>
+ internal enum RoamingType
+ {
+ /// <summary>
+ /// Not in roaming.
+ /// </summary>
+ Disabled,
+ /// <summary>
+ /// In roaming.
+ /// </summary>
+ Enabled
+ }
+
+ /// <summary>
+ /// Enumeration for hardware network protocol type.
+ /// </summary>
+ public enum NetworkProtocol
+ {
+ /// <summary>
+ /// Network protocol uncategorized.
+ /// </summary>
+ Others,
+ /// <summary>
+ /// Network no service.
+ /// </summary>
+ NoService,
+ /// <summary>
+ /// Network emergency.
+ /// </summary>
+ Emergency,
+ /// <summary>
+ /// Network search 1900.
+ /// </summary>
+ Search,
+ /// <summary>
+ /// Network 2G.
+ /// </summary>
+ Datacall_2G,
+ /// <summary>
+ /// Network 2.5G.
+ /// </summary>
+ Datacall_2_5G,
+ /// <summary>
+ /// Network EDGE.
+ /// </summary>
+ Datacall_2_5G_Edge,
+ /// <summary>
+ /// Network UMTS.
+ /// </summary>
+ Datacall_3G,
+ /// <summary>
+ /// Network HSDPA.
+ /// </summary>
+ Hsdpa,
+ /// <summary>
+ /// Network LTE.
+ /// </summary>
+ Lte
+ }
+
+ /// <summary>
+ /// Enumeration for monitored application state.
+ /// </summary>
+ public enum ApplicationStateType
+ {
+ /// <summary>
+ /// Uncategorized state.
+ /// </summary>
+ Others,
+ /// <summary>
+ /// Foreground state.
+ /// </summary>
+ Foreground,
+ /// <summary>
+ /// Background state.
+ /// </summary>
+ Background
+ }
+
+ /// <summary>
+ /// Enumeration for return type of the callback.
+ /// </summary>
+ internal enum CallbackRet
+ {
+ /// <summary>
+ /// Cancel
+ /// </summary>
+ Cancel,
+ /// <summary>
+ /// Continue
+ /// </summary>
+ Continue
+ }
+
+ /// <summary>
+ /// Internal Enumeration for the Stc error code.
+ /// </summary>
+ internal enum StcError
+ {
+ /// <summary>
+ /// Successful.
+ /// </summary>
+ None = ErrorCode.None,
+ /// <summary>
+ /// Operation not permitted.
+ /// </summary>
+ NotPermitted = ErrorCode.NotPermitted,
+ /// <summary>
+ /// Out of memory.
+ /// </summary>
+ OutOfMemory = ErrorCode.OutOfMemory,
+ /// <summary>
+ /// Permission denied.
+ /// </summary>
+ PermissionDenied = ErrorCode.PermissionDenied,
+ /// <summary>
+ /// Device or the resource is busy.
+ /// </summary>
+ ResourceBusy = ErrorCode.ResourceBusy,
+ /// <summary>
+ /// Invalid operation.
+ /// </summary>
+ InvalidOperation = ErrorCode.InvalidOperation,
+ /// <summary>
+ /// Invalid function parameter.
+ /// </summary>
+ InvalidParameter = ErrorCode.InvalidParameter,
+ /// <summary>
+ /// Not supported.
+ /// </summary>
+ NotSupported = ErrorCode.NotSupported,
+ /// <summary>
+ /// Operation failed.
+ /// </summary>
+ OperationFailed = -0x02F80000 | 0x01,
+ /// <summary>
+ /// Not initialized.
+ /// </summary>
+ NotInitialized = -0x02F80000 | 0x02,
+ /// <summary>
+ /// Already initialized the client.
+ /// </summary>
+ AlreadyInitialized = -0x02F80000 | 0x03,
+ /// <summary>
+ /// In progress.
+ /// </summary>
+ InProgress = -0x02F80000 | 0x04
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+
+namespace Tizen.Network.Stc
+{
+ internal static class StcErrorFactory
+ {
+ internal static void ThrowStcException(int exception)
+ {
+ StcError _error = (StcError)exception;
+ switch (_error)
+ {
+ case StcError.NotPermitted:
+ throw new InvalidOperationException("Operation not permitted");
+ case StcError.OutOfMemory:
+ throw new InvalidOperationException("Out of memory");
+ case StcError.PermissionDenied:
+ throw new UnauthorizedAccessException("Permission denied (http://tizen.org/privilege/network.get)");
+ case StcError.ResourceBusy:
+ throw new InvalidOperationException("Resource is busy");
+ case StcError.InvalidOperation:
+ throw new InvalidOperationException("Invalid operation");
+ case StcError.InvalidParameter:
+ throw new InvalidOperationException("Invalid parameter");
+ case StcError.NotSupported:
+ throw new NotSupportedException("Unsupported STC feature http://tizen.org/feature/network.traffic_control");
+ case StcError.OperationFailed:
+ throw new InvalidOperationException("Operation failed");
+ case StcError.NotInitialized:
+ throw new InvalidOperationException("Not initialized");
+ case StcError.AlreadyInitialized:
+ throw new InvalidOperationException("Already initialized");
+ case StcError.InProgress:
+ throw new InvalidOperationException("In progress");
+ default:
+ throw new InvalidOperationException("Unexpected value error = " + exception);
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Threading.Tasks;
+using System.ComponentModel;
+
+namespace Tizen.Network.Stc
+{
+ /// <summary>
+ /// A class for managing the Stc handle.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public sealed class SafeStcHandle : SafeHandle
+ {
+ internal SafeStcHandle() : base(IntPtr.Zero, true)
+ {
+ }
+
+ /// <summary>
+ /// Checks the validity of the handle.
+ /// </summary>
+ /// <value>Represents the validity of the handle.</value>
+ public override bool IsInvalid
+ {
+ get
+ {
+ return this.handle == IntPtr.Zero;
+ }
+ }
+
+ /// <summary>
+ /// Release the Stc handle
+ /// </summary>
+ /// <returns>True if the handle is released successfully, otherwise false.</returns>
+ protected override bool ReleaseHandle()
+ {
+ Interop.Stc.Deinitialize(this.handle);
+ this.SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+
+ /// <summary>
+ /// A class which is used to manage Smart Traffic control (Stc).<br/>
+ /// </summary>
+ public static class StcManager
+ {
+ /// <summary>
+ /// Gets the Stc safe handle.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <returns>The instance of the SafeStcHandle.</returns>
+ /// <feature>http://tizen.org/feature/network.traffic_control</feature>
+ /// <privilege>http://tizen.org/privilege/network.get</privilege>
+ /// <exception cref="NotSupportedException">Thrown when the Stc is not supported.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when the permission is denied.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the method failed due to an invalid operation.</exception>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ internal static SafeStcHandle GetStcHandle()
+ {
+ return StcManagerImpl.Instance.GetSafeHandle();
+ }
+
+ /// <summary>
+ /// Gets statistics information of applications that used network in between specified timestamps and matches the given StatisticsFilter, asynchronously.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <param name="filter"> The StatisticsFilter object.</param>
+ /// <returns>A list of the NetworkStatistics objects.</returns>
+ /// <feature>http://tizen.org/feature/network.traffic_control</feature>
+ /// <privilege>http://tizen.org/privilege/network.get</privilege>
+ /// <exception cref="NotSupportedException">Thrown when the Stc is not supported.</exception>
+ /// <exception cref="UnauthorizedAccessException">Thrown when the permission is denied.</exception>
+ /// <exception cref="InvalidOperationException">Thrown when the method failed due to an invalid operation.</exception>
+ /// <exception cref="ArgumentException">Thrown when the method is provided with invalid argument.</exception>
+ public static Task<IEnumerable<NetworkStatistics>> GetStatisticsAsync(StatisticsFilter filter)
+ {
+ return StcManagerImpl.Instance.GetStatisticsAsync(filter);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Tizen.Network.Stc
+{
+ internal static class Globals
+ {
+ internal const string LogTag = "Tizen.Network.Stc";
+ }
+
+ internal class StcHandleHolder
+ {
+ readonly SafeStcHandle _handle;
+
+ internal StcHandleHolder()
+ {
+ _handle = StcManagerImpl.Instance.Initialize();
+ Log.Debug(Globals.LogTag, "Handle: " + _handle);
+ }
+
+ internal SafeStcHandle GetSafeHandle()
+ {
+ Log.Debug(Globals.LogTag, "StcHandleholder safehandle = " + _handle);
+ return _handle;
+ }
+ }
+
+ /// <summary>
+ /// The implementation of Stc APIs.
+ /// </summary>
+ internal class StcManagerImpl
+ {
+ private static StcManagerImpl _instance;
+ private Dictionary<IntPtr, Interop.Stc.GetAllStatsFinishedCallback> _getAllStatsCb_map = new Dictionary<IntPtr, Interop.Stc.GetAllStatsFinishedCallback>();
+ private int _requestAllId = 0;
+
+ private StcManagerImpl()
+ {
+ }
+
+ internal static StcManagerImpl Instance
+ {
+ get
+ {
+ if (_instance == null)
+ {
+ Log.Debug(Globals.LogTag, "Instance is null");
+ _instance = new StcManagerImpl();
+ }
+
+ return _instance;
+ }
+ }
+
+ private static ThreadLocal<StcHandleHolder> s_threadName = new ThreadLocal<StcHandleHolder>(() =>
+ {
+ Log.Info(Globals.LogTag, "In threadlocal delegate");
+ return new StcHandleHolder();
+ });
+
+ internal SafeStcHandle GetSafeHandle()
+ {
+ return s_threadName.Value.GetSafeHandle();
+ }
+
+ internal SafeStcHandle Initialize()
+ {
+ SafeStcHandle handle;
+ int ret = Interop.Stc.Initialize(out handle);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to initialize Stc, Error - " + (StcError)ret);
+ StcErrorFactory.ThrowStcException(ret);
+ }
+ return handle;
+ }
+
+ internal Task<IEnumerable<NetworkStatistics>> GetStatisticsAsync(StatisticsFilter filter)
+ {
+ TaskCompletionSource<IEnumerable<NetworkStatistics>> task = new TaskCompletionSource<IEnumerable<NetworkStatistics>>();
+ IntPtr id;
+
+ lock (_getAllStatsCb_map)
+ {
+ id = (IntPtr)_requestAllId++;
+ _getAllStatsCb_map[id] = (int result, IntPtr infoList, IntPtr key) =>
+ {
+ if (result != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "GetAllStats failed, Error - " + (StcError)result);
+ task.SetException(new InvalidOperationException("Error occurs during GetAllStats(), " + (StcError)result));
+ }
+
+ List<NetworkStatistics> statsList = new List<NetworkStatistics>();
+
+ Interop.Stc.StatsInfoCallback foreachAllStatsCb = (int resultTemp, IntPtr info, IntPtr userDataTemp) =>
+ {
+ if (resultTemp != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "ForeachAllStats failed, Error - " + (StcError)resultTemp);
+ task.SetException(new InvalidOperationException("Error occurs during ForeachAllStats(), " + (StcError)resultTemp));
+ }
+
+ Interop.Stc.SafeStatsHandle cloned;
+ int retValue = Interop.Stc.Info.StatsClone(info, out cloned);
+ if (retValue != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "StatsClone() failed , Error - " + (StcError)retValue);
+ task.SetException(new InvalidOperationException("Error occurs during StatsClone(), " + (StcError)retValue));
+ }
+
+ statsList.Add(new NetworkStatistics(cloned));
+ return CallbackRet.Continue;
+ };
+
+ int retTemp = Interop.Stc.ForeachAllStats(infoList, foreachAllStatsCb, IntPtr.Zero);
+ if(retTemp != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "foreachAllStatus() failed , Error - " + (StcError)retTemp);
+ task.SetException(new InvalidOperationException("Error occurs during foreachAllStatus(), " + (StcError)retTemp));
+ }
+ else
+ {
+ task.SetResult(statsList);
+ }
+
+ lock (_getAllStatsCb_map)
+ {
+ _getAllStatsCb_map.Remove(key);
+ }
+ };
+ }
+
+ using (var filterHandle = filter.ConvertToNativeFilter())
+ {
+ int ret = Interop.Stc.GetAllStats(GetSafeHandle(), filterHandle, _getAllStatsCb_map[id], id);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "GetAllStatus() failed , Error - " + (StcError)ret);
+ StcErrorFactory.ThrowStcException(ret);
+ }
+ }
+ return task.Task;
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace Tizen.Network.Stc
+{
+ /// <summary>
+ /// A class for managing the Stc statistics information.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+
+ public class NetworkStatistics : IDisposable
+ {
+ private Interop.Stc.SafeStatsHandle _infoHandle;
+ private bool _disposed;
+
+ internal NetworkStatistics(Interop.Stc.SafeStatsHandle handle)
+ {
+ Log.Debug(Globals.LogTag, "New Statistics Handle: " + handle);
+ _infoHandle = handle;
+ }
+
+ /// <summary>
+ /// Destroy the NetworkStatistics object
+ /// </summary>
+ ~NetworkStatistics()
+ {
+ Dispose(false);
+ }
+
+ /// <summary>
+ /// A method to destroy the managed NetworkStatistics objects.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Releases the resources used by the NetworkStatistics.
+ /// </summary>
+ /// <param name="disposing">True to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
+ protected void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if(disposing)
+ {
+ _infoHandle.Dispose();
+ _infoHandle = null;
+ }
+
+ _disposed = true;
+ }
+
+ /// <summary>
+ /// A property to get the application ID from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Application ID.</value>
+ public string AppId
+ {
+ get
+ {
+ string appId;
+ int ret = Interop.Stc.Info.GetAppId(_infoHandle, out appId);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get AppId from NetworkStatistics, Error - " + (StcError)ret);
+ return string.Empty;
+ }
+ return appId;
+ }
+ }
+
+ /// <summary>
+ /// A property to get interface name from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Interface name.</value>
+ public string InterfaceName
+ {
+ get
+ {
+ string ifaceName;
+ int ret = Interop.Stc.Info.GetInterfaceName(_infoHandle, out ifaceName);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get interface name from NetworkStatistics, Error - " + (StcError)ret);
+ return string.Empty;
+ }
+ return ifaceName;
+ }
+ }
+
+ /// <summary>
+ /// A property to get "from" value(start) of time interval from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>from(start) of time interval.</value>
+ public DateTime From
+ {
+ get
+ {
+ Int32 from;
+ Int32 to;
+ int ret = Interop.Stc.Info.GetTimeInterval(_infoHandle, out from, out to);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get time interval(from value) from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return Interop.ConvertTimestampToDateTime(from);
+ }
+ }
+
+ /// <summary>
+ /// A property to get "to" value(end) of time interval from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>to(end) of time interval.</value>
+ public DateTime To
+ {
+ get
+ {
+ Int32 from;
+ Int32 to;
+ int ret = Interop.Stc.Info.GetTimeInterval(_infoHandle, out from, out to);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get time interval(to value) from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return Interop.ConvertTimestampToDateTime(to);
+ }
+ }
+
+ /// <summary>
+ /// A property to get the interface type from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Interface type.</value>
+ public NetworkInterface InterfaceType
+ {
+ get
+ {
+ NetworkInterface ifaceType;
+ int ret = Interop.Stc.Info.GetInterfaceType(_infoHandle, out ifaceType);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get Interface type from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return ifaceType;
+ }
+ }
+
+ /// <summary>
+ /// A property to get incoming counter from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>incoming counter.</value>
+ public long IncomingCounter
+ {
+ get
+ {
+ long incoming;
+ long outgoing;
+ int ret = Interop.Stc.Info.GetCounter(_infoHandle, out incoming, out outgoing);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get incoming counter from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return incoming;
+ }
+ }
+
+ /// <summary>
+ /// A property to get outgoing counter from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>outgoing counter.</value>
+ public long OutgoingCounter
+ {
+ get
+ {
+ long incoming;
+ long outgoing;
+ int ret = Interop.Stc.Info.GetCounter(_infoHandle, out incoming, out outgoing);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get outgoing counter from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return outgoing;
+ }
+ }
+
+ /// <summary>
+ /// A property to get the roaming type from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>IsRoaming.</value>
+ public bool IsRoaming
+ {
+ get
+ {
+ RoamingType roaming;
+ int ret = Interop.Stc.Info.GetRoaming(_infoHandle, out roaming);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get Roaming type from NetworkStatistics, Error - " + (StcError)ret);
+ }
+
+ return roaming == RoamingType.Enabled;
+ }
+ }
+
+ /// <summary>
+ /// A property to get the network protocol type from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Network Protocol type.</value>
+ public NetworkProtocol Protocol
+ {
+ get
+ {
+ NetworkProtocol protocol;
+ int ret = Interop.Stc.Info.GetProtocol(_infoHandle, out protocol);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get Protocol type from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return protocol;
+ }
+ }
+
+ /// <summary>
+ /// A property to get the application state from NetworkStatistics.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Monitored application state.</value>
+ public ApplicationStateType ApplicationState
+ {
+ get
+ {
+ ApplicationStateType state;
+ int ret = Interop.Stc.Info.GetProcessState(_infoHandle, out state);
+ if (ret != (int)StcError.None)
+ {
+ Log.Error(Globals.LogTag, "Failed to get ApplicationState from NetworkStatistics, Error - " + (StcError)ret);
+ }
+ return state;
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+using System;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+namespace Tizen.Network.Stc
+{
+ /// <summary>
+ /// A class for managing the Statistics Filters to match applications.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ public class StatisticsFilter
+ {
+ /// <summary>
+ /// A property for App Id for statistics filter. AppId can be provided to get statistics for a specific application.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Application id.</value>
+ public string AppId { get; set; }
+
+ /// <summary>
+ /// A property for "from" value of time interval for statistics filter.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>from(start) of time interval.</value>
+ public DateTime? From { get; set; }
+
+ /// <summary>
+ /// A property for "to" value of time interval for statistics filter.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>to(end) of time interval.</value>
+ public DateTime? To { get; set; }
+
+ /// <summary>
+ /// A property for Interface type for statistics filter.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Interface type.</value>
+ public NetworkInterface? InterfaceType { get; set; }
+
+ /// <summary>
+ /// A property for Time period for statistics filter. This is used to granulate the statistics data.
+ /// </summary>
+ /// <since_tizen> 6 </since_tizen>
+ /// <value>Time period.</value>
+ public TimePeriodType? TimePeriod { get; set; }
+
+ internal Interop.Stc.SafeFilterHandle ConvertToNativeFilter()
+ {
+ Interop.Stc.SafeFilterHandle handle;
+ Interop.Stc.Filter.Create(StcManagerImpl.Instance.GetSafeHandle(), out handle);
+
+ Interop.Stc.Filter.SetAppId(handle, AppId);
+ if (From.HasValue && To.HasValue)
+ {
+ Interop.Stc.Filter.SetTimeInterval(handle,
+ Interop.ConvertDateTimeToTimestamp(From.Value),
+ Interop.ConvertDateTimeToTimestamp(To.Value));
+ }
+ if (InterfaceType.HasValue)
+ {
+ Interop.Stc.Filter.SetInterfaceType(handle, InterfaceType.Value);
+ }
+ if (TimePeriod.HasValue)
+ {
+ Interop.Stc.Filter.SetTimePeriod(handle, (NativeTimePeriodType)TimePeriod.Value);
+ }
+ return handle;
+ }
+ }
+}