feat/update_PVT: completed
This commit is contained in:
		
							parent
							
								
									13f8a31251
								
							
						
					
					
						commit
						791d807642
					
				| 
						 | 
				
			
			@ -5,5 +5,7 @@ namespace RuleEngine.Constants
 | 
			
		|||
        public const double SPOOFING_THRESH_DISTANCE = 10;
 | 
			
		||||
        public const double STOP_SPEED_LIMIT = 15;
 | 
			
		||||
        public const double SECONDS_SET_CAR_STOP = 900; // 15 phút
 | 
			
		||||
        public const int MAX_DISTANCE = 50;
 | 
			
		||||
        public const double MAX_DISTANCE_STOP = 0.01;
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			@ -3,6 +3,6 @@ namespace RuleEngine.Constants
 | 
			
		|||
    public class MqttTopic
 | 
			
		||||
    {
 | 
			
		||||
        public const string UpdatePVTFormat = "devices/update_pvt/{0}";
 | 
			
		||||
        public const string UpdatePVTResponseFormat = "devices/update_pvt_response/{0}";
 | 
			
		||||
        public const string UpdatePVTResponseFormat = "iot/devices/update_PVT_response/{0}";
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										15
									
								
								RuleEngine/DTOs/DeviceDTO.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								RuleEngine/DTOs/DeviceDTO.cs
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
				
			
			@ -0,0 +1,15 @@
 | 
			
		|||
namespace RuleEngine.DTOs
 | 
			
		||||
{
 | 
			
		||||
    public class DeviceInstantInfo
 | 
			
		||||
    {
 | 
			
		||||
        public TimeSpan? Timestamp { get; set; }
 | 
			
		||||
        public double? Latitude { get; set; }
 | 
			
		||||
        public double? Longtitude { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
    
 | 
			
		||||
    public class ShortDeviceInfor
 | 
			
		||||
    {
 | 
			
		||||
        public int CarID { get; set; }
 | 
			
		||||
        public int UnitID { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										0
									
								
								RuleEngine/Logs/Debug.txt
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								RuleEngine/Logs/Debug.txt
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										0
									
								
								RuleEngine/Logs/PVTException.txt
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								RuleEngine/Logs/PVTException.txt
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										512
									
								
								RuleEngine/Logs/ruleengine_log_20250515.log
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										512
									
								
								RuleEngine/Logs/ruleengine_log_20250515.log
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
				
			
			@ -0,0 +1,512 @@
 | 
			
		|||
2025-05-15 15:44:51.262 +07:00 [INF] RuleEngineWorker initialized with broker: localhost:1883
 | 
			
		||||
2025-05-15 15:44:51.318 +07:00 [INF] RuleEngineWorker starting at: "2025-05-15T15:44:51.3178293+07:00"
 | 
			
		||||
2025-05-15 15:44:51.325 +07:00 [INF] Connecting to MQTT broker at localhost:1883...
 | 
			
		||||
2025-05-15 15:44:51.399 +07:00 [INF] Connected to MQTT broker successfully
 | 
			
		||||
2025-05-15 15:44:51.400 +07:00 [INF] Subscribing to MQTT topics...
 | 
			
		||||
2025-05-15 15:44:51.419 +07:00 [INF] Subscribed to topic 'iot/devices/#' with ResultCode: "GrantedQoS1"
 | 
			
		||||
2025-05-15 15:44:51.420 +07:00 [INF] MQTT reconnect timer initialized and started
 | 
			
		||||
2025-05-15 15:45:05.444 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:45:08.414 +07:00 [ERR] An error occurred using the connection to database 'LPB.CarTracking' on server '203.171.20.94,1434'.
 | 
			
		||||
2025-05-15 15:45:08.428 +07:00 [ERR] An exception occurred while iterating over the results of a query for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:abcc35e1-196b-456d-bddc-c15bff7f03e9
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:abcc35e1-196b-456d-bddc-c15bff7f03e9
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
2025-05-15 15:45:08.450 +07:00 [ERR] An error occurred using the connection to database 'LPB.CarTracking' on server '203.171.20.94,1434'.
 | 
			
		||||
2025-05-15 15:45:08.450 +07:00 [ERR] An exception occurred while iterating over the results of a query for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:abcc35e1-196b-456d-bddc-c15bff7f03e9
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:abcc35e1-196b-456d-bddc-c15bff7f03e9
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
2025-05-15 15:45:08.455 +07:00 [WRN] Update PVT for device 22222test2222 failed
 | 
			
		||||
2025-05-15 15:45:08.530 +07:00 [INF] Published message to topic iot/devices/update_pvt_response/22222test2222
 | 
			
		||||
2025-05-15 15:45:08.551 +07:00 [INF] Received MQTT message: iot/devices/update_pvt_response/22222test2222 -> 97 bytes
 | 
			
		||||
2025-05-15 15:45:15.488 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:45:15.529 +07:00 [ERR] An error occurred using the connection to database 'LPB.CarTracking' on server '203.171.20.94,1434'.
 | 
			
		||||
2025-05-15 15:45:15.530 +07:00 [ERR] An exception occurred while iterating over the results of a query for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:8688c9ad-d38d-4414-9396-4a30cdc183ab
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock, Boolean asyncClose)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
 | 
			
		||||
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword, SqlConnectionEncryptOption encrypt)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:8688c9ad-d38d-4414-9396-4a30cdc183ab
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
2025-05-15 15:45:15.531 +07:00 [ERR] An error occurred using the connection to database 'LPB.CarTracking' on server '203.171.20.94,1434'.
 | 
			
		||||
2025-05-15 15:45:15.532 +07:00 [ERR] An exception occurred while iterating over the results of a query for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:8688c9ad-d38d-4414-9396-4a30cdc183ab
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
 | 
			
		||||
 ---> System.ComponentModel.Win32Exception (0x80090325): The certificate chain was issued by an authority that is not trusted.
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlConnection.Open()
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__21_0(DbContext _, Enumerator enumerator)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
 | 
			
		||||
ClientConnectionId:8688c9ad-d38d-4414-9396-4a30cdc183ab
 | 
			
		||||
Error Number:-2146893019,State:0,Class:20
 | 
			
		||||
2025-05-15 15:45:15.533 +07:00 [WRN] Update PVT for device 22222test2222 failed
 | 
			
		||||
2025-05-15 15:45:15.535 +07:00 [INF] Published message to topic iot/devices/update_pvt_response/22222test2222
 | 
			
		||||
2025-05-15 15:45:15.535 +07:00 [INF] Received MQTT message: iot/devices/update_pvt_response/22222test2222 -> 97 bytes
 | 
			
		||||
2025-05-15 15:46:43.887 +07:00 [INF] Stopping RuleEngineWorker
 | 
			
		||||
2025-05-15 15:46:43.897 +07:00 [INF] Disconnected from MQTT broker
 | 
			
		||||
2025-05-15 15:46:43.898 +07:00 [WRN] Disconnected from MQTT broker: "NormalDisconnection"
 | 
			
		||||
2025-05-15 15:46:43.898 +07:00 [INF] RuleEngineWorker stopping due to cancellation
 | 
			
		||||
2025-05-15 15:46:43.898 +07:00 [INF] RuleEngineWorker stopped at: "2025-05-15T15:46:43.8984105+07:00"
 | 
			
		||||
2025-05-15 15:46:49.827 +07:00 [INF] RuleEngineWorker initialized with broker: localhost:1883
 | 
			
		||||
2025-05-15 15:46:49.881 +07:00 [INF] RuleEngineWorker starting at: "2025-05-15T15:46:49.8809353+07:00"
 | 
			
		||||
2025-05-15 15:46:49.888 +07:00 [INF] Connecting to MQTT broker at localhost:1883...
 | 
			
		||||
2025-05-15 15:46:49.961 +07:00 [INF] Connected to MQTT broker successfully
 | 
			
		||||
2025-05-15 15:46:49.962 +07:00 [INF] Subscribing to MQTT topics...
 | 
			
		||||
2025-05-15 15:46:49.980 +07:00 [INF] Subscribed to topic 'iot/devices/#' with ResultCode: "GrantedQoS1"
 | 
			
		||||
2025-05-15 15:46:49.982 +07:00 [INF] MQTT reconnect timer initialized and started
 | 
			
		||||
2025-05-15 15:46:53.757 +07:00 [INF] Stopping RuleEngineWorker
 | 
			
		||||
2025-05-15 15:46:53.767 +07:00 [INF] Disconnected from MQTT broker
 | 
			
		||||
2025-05-15 15:46:53.768 +07:00 [INF] RuleEngineWorker stopping due to cancellation
 | 
			
		||||
2025-05-15 15:46:53.768 +07:00 [INF] RuleEngineWorker stopped at: "2025-05-15T15:46:53.7688841+07:00"
 | 
			
		||||
2025-05-15 15:46:53.770 +07:00 [WRN] Disconnected from MQTT broker: "NormalDisconnection"
 | 
			
		||||
2025-05-15 15:47:20.954 +07:00 [INF] RuleEngineWorker initialized with broker: localhost:1883
 | 
			
		||||
2025-05-15 15:47:21.007 +07:00 [INF] RuleEngineWorker starting at: "2025-05-15T15:47:21.0069469+07:00"
 | 
			
		||||
2025-05-15 15:47:21.014 +07:00 [INF] Connecting to MQTT broker at localhost:1883...
 | 
			
		||||
2025-05-15 15:47:21.086 +07:00 [INF] Connected to MQTT broker successfully
 | 
			
		||||
2025-05-15 15:47:21.088 +07:00 [INF] Subscribing to MQTT topics...
 | 
			
		||||
2025-05-15 15:47:21.105 +07:00 [INF] Subscribed to topic 'iot/devices/#' with ResultCode: "GrantedQoS1"
 | 
			
		||||
2025-05-15 15:47:21.107 +07:00 [INF] MQTT reconnect timer initialized and started
 | 
			
		||||
2025-05-15 15:48:28.501 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:48:31.147 +07:00 [ERR] Failed executing DbCommand (8ms) [Parameters=[@p0='?' (DbType = Boolean), @p1='?' (DbType = Boolean), @p2='?' (DbType = Boolean), @p3='?' (DbType = Int32), @p4='?' (DbType = Int32), @p5='?' (DbType = Int32), @p6='?' (DbType = DateTime2), @p7='?' (DbType = Boolean), @p8='?' (Size = 4000), @p9='?' (DbType = Double), @p10='?' (DbType = Double), @p11='?' (DbType = Int32), @p12='?' (DbType = Boolean), @p13='?' (DbType = Boolean), @p14='?' (DbType = Boolean), @p15='?' (DbType = Boolean), @p16='?' (DbType = Double), @p17='?' (DbType = Double), @p18='?' (DbType = DateTime2), @p19='?' (Size = 4000), @p20='?' (DbType = Boolean), @p21='?' (DbType = Int32)], CommandType='"Text"', CommandTimeout='30']
 | 
			
		||||
SET IMPLICIT_TRANSACTIONS OFF;
 | 
			
		||||
SET NOCOUNT ON;
 | 
			
		||||
INSERT INTO [Histories] ([Cam1OK], [Cam2OK], [CamDetach], [CarId], [CarStatus], [DeviceDate], [DeviceTime], [EngineOn], [GpsInfor], [GpsLat], [GpsLon], [GpsVelocity], [IsGPSLost], [IsJamming], [IsSos], [IsSpoofing], [NetworkLat], [NetworkLon], [ReceivedTime], [Rfidstring], [StrongBoxOpen], [UnitId])
 | 
			
		||||
OUTPUT INSERTED.[Id]
 | 
			
		||||
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21);
 | 
			
		||||
2025-05-15 15:48:31.164 +07:00 [ERR] An exception occurred in the database while saving changes for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
2025-05-15 15:48:31.168 +07:00 [INF] Update PVT for device 22222test2222 succeeded
 | 
			
		||||
2025-05-15 15:48:31.245 +07:00 [INF] Published message to topic iot/devices/update_PVT_response/22222test2222
 | 
			
		||||
2025-05-15 15:48:31.254 +07:00 [INF] Received MQTT message: iot/devices/update_PVT_response/22222test2222 -> 100 bytes
 | 
			
		||||
2025-05-15 15:48:38.501 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:48:38.577 +07:00 [ERR] Failed executing DbCommand (5ms) [Parameters=[@p0='?' (DbType = Boolean), @p1='?' (DbType = Boolean), @p2='?' (DbType = Boolean), @p3='?' (DbType = Int32), @p4='?' (DbType = Int32), @p5='?' (DbType = Int32), @p6='?' (DbType = DateTime2), @p7='?' (DbType = Boolean), @p8='?' (Size = 4000), @p9='?' (DbType = Double), @p10='?' (DbType = Double), @p11='?' (DbType = Int32), @p12='?' (DbType = Boolean), @p13='?' (DbType = Boolean), @p14='?' (DbType = Boolean), @p15='?' (DbType = Boolean), @p16='?' (DbType = Double), @p17='?' (DbType = Double), @p18='?' (DbType = DateTime2), @p19='?' (Size = 4000), @p20='?' (DbType = Boolean), @p21='?' (DbType = Int32)], CommandType='"Text"', CommandTimeout='30']
 | 
			
		||||
SET IMPLICIT_TRANSACTIONS OFF;
 | 
			
		||||
SET NOCOUNT ON;
 | 
			
		||||
INSERT INTO [Histories] ([Cam1OK], [Cam2OK], [CamDetach], [CarId], [CarStatus], [DeviceDate], [DeviceTime], [EngineOn], [GpsInfor], [GpsLat], [GpsLon], [GpsVelocity], [IsGPSLost], [IsJamming], [IsSos], [IsSpoofing], [NetworkLat], [NetworkLon], [ReceivedTime], [Rfidstring], [StrongBoxOpen], [UnitId])
 | 
			
		||||
OUTPUT INSERTED.[Id]
 | 
			
		||||
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21);
 | 
			
		||||
2025-05-15 15:48:38.579 +07:00 [ERR] An exception occurred in the database while saving changes for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
2025-05-15 15:48:38.582 +07:00 [INF] Update PVT for device 22222test2222 succeeded
 | 
			
		||||
2025-05-15 15:48:38.584 +07:00 [INF] Published message to topic iot/devices/update_PVT_response/22222test2222
 | 
			
		||||
2025-05-15 15:48:38.585 +07:00 [INF] Received MQTT message: iot/devices/update_PVT_response/22222test2222 -> 100 bytes
 | 
			
		||||
2025-05-15 15:48:48.515 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:48:48.740 +07:00 [ERR] Failed executing DbCommand (21ms) [Parameters=[@p0='?' (DbType = Boolean), @p1='?' (DbType = Boolean), @p2='?' (DbType = Boolean), @p3='?' (DbType = Int32), @p4='?' (DbType = Int32), @p5='?' (DbType = Int32), @p6='?' (DbType = DateTime2), @p7='?' (DbType = Boolean), @p8='?' (Size = 4000), @p9='?' (DbType = Double), @p10='?' (DbType = Double), @p11='?' (DbType = Int32), @p12='?' (DbType = Boolean), @p13='?' (DbType = Boolean), @p14='?' (DbType = Boolean), @p15='?' (DbType = Boolean), @p16='?' (DbType = Double), @p17='?' (DbType = Double), @p18='?' (DbType = DateTime2), @p19='?' (Size = 4000), @p20='?' (DbType = Boolean), @p21='?' (DbType = Int32)], CommandType='"Text"', CommandTimeout='30']
 | 
			
		||||
SET IMPLICIT_TRANSACTIONS OFF;
 | 
			
		||||
SET NOCOUNT ON;
 | 
			
		||||
INSERT INTO [Histories] ([Cam1OK], [Cam2OK], [CamDetach], [CarId], [CarStatus], [DeviceDate], [DeviceTime], [EngineOn], [GpsInfor], [GpsLat], [GpsLon], [GpsVelocity], [IsGPSLost], [IsJamming], [IsSos], [IsSpoofing], [NetworkLat], [NetworkLon], [ReceivedTime], [Rfidstring], [StrongBoxOpen], [UnitId])
 | 
			
		||||
OUTPUT INSERTED.[Id]
 | 
			
		||||
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21);
 | 
			
		||||
2025-05-15 15:48:48.742 +07:00 [ERR] An exception occurred in the database while saving changes for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
2025-05-15 15:48:48.743 +07:00 [INF] Update PVT for device 22222test2222 succeeded
 | 
			
		||||
2025-05-15 15:48:48.746 +07:00 [INF] Published message to topic iot/devices/update_PVT_response/22222test2222
 | 
			
		||||
2025-05-15 15:48:48.747 +07:00 [INF] Received MQTT message: iot/devices/update_PVT_response/22222test2222 -> 100 bytes
 | 
			
		||||
2025-05-15 15:48:58.527 +07:00 [INF] Received MQTT message: iot/devices/update_PVT -> 1068 bytes
 | 
			
		||||
2025-05-15 15:48:58.577 +07:00 [ERR] Failed executing DbCommand (5ms) [Parameters=[@p0='?' (DbType = Boolean), @p1='?' (DbType = Boolean), @p2='?' (DbType = Boolean), @p3='?' (DbType = Int32), @p4='?' (DbType = Int32), @p5='?' (DbType = Int32), @p6='?' (DbType = DateTime2), @p7='?' (DbType = Boolean), @p8='?' (Size = 4000), @p9='?' (DbType = Double), @p10='?' (DbType = Double), @p11='?' (DbType = Int32), @p12='?' (DbType = Boolean), @p13='?' (DbType = Boolean), @p14='?' (DbType = Boolean), @p15='?' (DbType = Boolean), @p16='?' (DbType = Double), @p17='?' (DbType = Double), @p18='?' (DbType = DateTime2), @p19='?' (Size = 4000), @p20='?' (DbType = Boolean), @p21='?' (DbType = Int32)], CommandType='"Text"', CommandTimeout='30']
 | 
			
		||||
SET IMPLICIT_TRANSACTIONS OFF;
 | 
			
		||||
SET NOCOUNT ON;
 | 
			
		||||
INSERT INTO [Histories] ([Cam1OK], [Cam2OK], [CamDetach], [CarId], [CarStatus], [DeviceDate], [DeviceTime], [EngineOn], [GpsInfor], [GpsLat], [GpsLon], [GpsVelocity], [IsGPSLost], [IsJamming], [IsSos], [IsSpoofing], [NetworkLat], [NetworkLon], [ReceivedTime], [Rfidstring], [StrongBoxOpen], [UnitId])
 | 
			
		||||
OUTPUT INSERTED.[Id]
 | 
			
		||||
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15, @p16, @p17, @p18, @p19, @p20, @p21);
 | 
			
		||||
2025-05-15 15:48:58.578 +07:00 [ERR] An exception occurred in the database while saving changes for context type 'RuleEngine.Database.DatabaseContext'.
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.
 | 
			
		||||
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Operand type clash: int is incompatible with date
 | 
			
		||||
   at Microsoft.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__209_0(Task`1 result)
 | 
			
		||||
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
 | 
			
		||||
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
 | 
			
		||||
--- End of stack trace from previous location ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
ClientConnectionId:1cf21008-c7cb-485f-bc1f-d0b83bf46408
 | 
			
		||||
Error Number:206,State:2,Class:16
 | 
			
		||||
   --- End of inner exception stack trace ---
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Update.Internal.SqlServerModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
 | 
			
		||||
   at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
 | 
			
		||||
2025-05-15 15:48:58.581 +07:00 [INF] Update PVT for device 22222test2222 succeeded
 | 
			
		||||
2025-05-15 15:48:58.583 +07:00 [INF] Published message to topic iot/devices/update_PVT_response/22222test2222
 | 
			
		||||
2025-05-15 15:48:58.584 +07:00 [INF] Received MQTT message: iot/devices/update_PVT_response/22222test2222 -> 100 bytes
 | 
			
		||||
2025-05-15 15:49:45.724 +07:00 [INF] Stopping RuleEngineWorker
 | 
			
		||||
2025-05-15 15:49:45.734 +07:00 [INF] Disconnected from MQTT broker
 | 
			
		||||
2025-05-15 15:49:45.735 +07:00 [WRN] Disconnected from MQTT broker: "NormalDisconnection"
 | 
			
		||||
2025-05-15 15:49:45.735 +07:00 [INF] RuleEngineWorker stopping due to cancellation
 | 
			
		||||
2025-05-15 15:49:45.735 +07:00 [INF] RuleEngineWorker stopped at: "2025-05-15T15:49:45.7357220+07:00"
 | 
			
		||||
| 
						 | 
				
			
			@ -102,8 +102,8 @@ namespace RuleEngine
 | 
			
		|||
        private MqttClientOptions CreateMqttClientOptions()
 | 
			
		||||
        {
 | 
			
		||||
            return new MqttClientOptionsBuilder()
 | 
			
		||||
                .WithTcpServer("localhost", 1883)
 | 
			
		||||
                .WithClientId($"RuleEngineWorker-{Guid.NewGuid()}")
 | 
			
		||||
                .WithTcpServer(_mqttBroker, 1883)
 | 
			
		||||
                .WithClientId($"RuleEngineWorker")
 | 
			
		||||
                .WithCredentials(_mqttUsername, _mqttPassword)
 | 
			
		||||
                .WithCleanSession(false)
 | 
			
		||||
                .WithSessionExpiryInterval(604800) // 7 days in seconds
 | 
			
		||||
| 
						 | 
				
			
			@ -310,7 +310,7 @@ namespace RuleEngine
 | 
			
		|||
                
 | 
			
		||||
                object responsePayload;
 | 
			
		||||
                
 | 
			
		||||
                if (result)
 | 
			
		||||
                if (result == true)
 | 
			
		||||
                {
 | 
			
		||||
                    _logger.LogInformation("Update PVT for device {Imei} succeeded", imei);
 | 
			
		||||
                    responsePayload = new
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -17,7 +17,7 @@ namespace RuleEngine.Services
 | 
			
		|||
        private readonly static string logFolderPath = LogConstants.LOG_FILE_PATH;
 | 
			
		||||
        private readonly static string exceptionFolder = LogConstants.LOG_EXCEPTION_FILE_PATH;
 | 
			
		||||
        private static readonly Dictionary<string, LimitedSizeQueue<DateTime>> dictCarHistory = [];
 | 
			
		||||
 | 
			
		||||
        readonly Dictionary<string, DeviceInstantInfo> carHistory = [];
 | 
			
		||||
        public DeviceService(DatabaseContext dbContext, IConfiguration config)
 | 
			
		||||
        {
 | 
			
		||||
            _dbContext = dbContext;
 | 
			
		||||
| 
						 | 
				
			
			@ -147,6 +147,7 @@ namespace RuleEngine.Services
 | 
			
		|||
            string strOBD = deviceMessage?.StrOBD ?? string.Empty;
 | 
			
		||||
            string strLac = deviceMessage?.LacID ?? string.Empty;
 | 
			
		||||
            string version = deviceMessage?.Version ?? string.Empty;
 | 
			
		||||
            string provider = deviceMessage?.Provider ?? string.Empty;
 | 
			
		||||
            var gpsInfor = deviceMessage?.GpsInfor;
 | 
			
		||||
            bool isJamming = deviceMessage?.IsJamming ?? false;
 | 
			
		||||
            bool isSpoofing = deviceMessage?.IsSpoofing ?? false;
 | 
			
		||||
| 
						 | 
				
			
			@ -222,10 +223,150 @@ namespace RuleEngine.Services
 | 
			
		|||
                if (Directory.Exists(logFolderPath))
 | 
			
		||||
                    StaticResources.Log2File(logFolderPath + "CELLException.txt", ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            DateTime currentDate = DateTime.UtcNow;
 | 
			
		||||
            DateTime checkedTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 0, 0, 0);
 | 
			
		||||
 | 
			
		||||
            // begin validate data
 | 
			
		||||
            if (string.IsNullOrEmpty(Imei))
 | 
			
		||||
            {
 | 
			
		||||
                return new DeviceLogRequest { Imei = Imei, Code = "ERROR", Message = "NO Imei" };
 | 
			
		||||
                //return new DeviceLogRequest { }
 | 
			
		||||
            }
 | 
			
		||||
            if (Imei.Length < 10 || Imei.Length > 25)
 | 
			
		||||
            {
 | 
			
		||||
                return new DeviceLogRequest { Imei = Imei, Code = "ERROR", Message = "WRONG Imei" };
 | 
			
		||||
            }
 | 
			
		||||
            // end validate data
 | 
			
		||||
            var deviceInfor = FindIdXeFromDeviceImei(_dbContext, Imei);
 | 
			
		||||
 | 
			
		||||
            if (!carHistory.ContainsKey(Imei))
 | 
			
		||||
            {
 | 
			
		||||
                carHistory.Add(Imei, new DeviceInstantInfo { Latitude = latitude, Longtitude = longtitude });
 | 
			
		||||
            }
 | 
			
		||||
            else
 | 
			
		||||
            {
 | 
			
		||||
                carHistory[Imei] = new DeviceInstantInfo { Latitude = latitude, Longtitude = longtitude };
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
            //chuyen sang gio Vietnam
 | 
			
		||||
            TimeSpan ts = new TimeSpan(7, 0, 0);
 | 
			
		||||
            receivedTime = receivedTime + ts;
 | 
			
		||||
 | 
			
		||||
            double oriLati = 0;
 | 
			
		||||
            double oriLongi = 0;
 | 
			
		||||
 | 
			
		||||
            int Cellid = 1;
 | 
			
		||||
            if (provider != null)
 | 
			
		||||
            {
 | 
			
		||||
                Cellid = provider.Contains("network") == true ? 1 : 0;
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            int carStatus = 0; //is runing
 | 
			
		||||
 | 
			
		||||
            //kiem tra neu trang thai xe dang la chay nhung khoang cach vi tri den diem truoc do qua xa --> nhieu do ublox tinh sai vi tri
 | 
			
		||||
            if (isStopping == false)
 | 
			
		||||
            {
 | 
			
		||||
                if (carHistory.ContainsKey(Imei))
 | 
			
		||||
                {
 | 
			
		||||
                    double last_Longi = carHistory[Imei].Longtitude != null ? carHistory[Imei].Longtitude.Value : 0;
 | 
			
		||||
                    double last_Lati = carHistory[Imei].Latitude != null ? carHistory[Imei].Latitude.Value : 0;
 | 
			
		||||
 | 
			
		||||
                    if (StaticResources.DistanceGpsCalculate(latitude, longtitude, last_Lati, last_Longi, 'K') > DeviceConfig.MAX_DISTANCE)
 | 
			
		||||
                    {
 | 
			
		||||
                        oriLati = latitude;
 | 
			
		||||
                        oriLongi = latitude;
 | 
			
		||||
 | 
			
		||||
                        latitude = last_Lati;
 | 
			
		||||
                        longtitude = last_Longi;
 | 
			
		||||
 | 
			
		||||
                        carStatus = 2; //xe dang do nhung bi nhay vi tri
 | 
			
		||||
                    }
 | 
			
		||||
 | 
			
		||||
                    //hiephv
 | 
			
		||||
                    if (gpsSpeed < 3)
 | 
			
		||||
                    {
 | 
			
		||||
                        // loc truong hop xe dung yen, nhung toa do xe dich
 | 
			
		||||
                        if (StaticResources.DistanceGpsCalculate(latitude, longtitude, last_Lati, last_Longi, 'K') > DeviceConfig.MAX_DISTANCE_STOP)
 | 
			
		||||
                        {
 | 
			
		||||
                            oriLati = latitude;
 | 
			
		||||
                            oriLongi = latitude;
 | 
			
		||||
 | 
			
		||||
                            latitude = last_Lati;
 | 
			
		||||
                            longtitude = last_Longi;
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            if (isStopping == true)
 | 
			
		||||
            {
 | 
			
		||||
                carStatus = 1;               //dung
 | 
			
		||||
            }
 | 
			
		||||
            else
 | 
			
		||||
            {
 | 
			
		||||
                if ((isEngineOn == false)
 | 
			
		||||
                   && (gpsSpeed <= DeviceConfig.STOP_SPEED_LIMIT))
 | 
			
		||||
                {
 | 
			
		||||
                    carStatus = 1;
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
            if (receivedTime.Hour > 21)
 | 
			
		||||
            {
 | 
			
		||||
                carStatus = 2;              // do
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            string RFID = "";
 | 
			
		||||
            if (!string.IsNullOrEmpty(strRFID))
 | 
			
		||||
            {
 | 
			
		||||
                RFID = strRFID.Trim().Length > 255 ? strRFID.Trim().Substring(0, 255) : strRFID.Trim();
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
            int LacID = 0;
 | 
			
		||||
            if (!string.IsNullOrEmpty(strLac))
 | 
			
		||||
            {
 | 
			
		||||
                LacID = int.Parse(strLac, System.Globalization.NumberStyles.HexNumber);
 | 
			
		||||
            }
 | 
			
		||||
            if (deviceInfor.CarID > 0)
 | 
			
		||||
            {
 | 
			
		||||
                requestLog = new DeviceLogRequest()
 | 
			
		||||
                {
 | 
			
		||||
                    Imei = Imei,
 | 
			
		||||
                    CarID = deviceInfor.CarID,
 | 
			
		||||
                    UnitID = deviceInfor.UnitID,
 | 
			
		||||
                    ReceivedTime = receivedTime,
 | 
			
		||||
                    GpsLat = latitude,
 | 
			
		||||
                    GpsLon = longtitude,
 | 
			
		||||
                    NetworkLat = cell_lat,
 | 
			
		||||
                    NetworkLon = cell_lon,
 | 
			
		||||
                    OriLati = oriLati,
 | 
			
		||||
                    OriLongi = oriLongi,
 | 
			
		||||
                    GpsSpeed = gpsSpeed,
 | 
			
		||||
                    CellID = Cellid,
 | 
			
		||||
                    LacID = 0,
 | 
			
		||||
                    IsSos = isSos,
 | 
			
		||||
                    IsStrongBoxOpen = isStrongBoxOpen,
 | 
			
		||||
                    IsEngineOn = isEngineOn,
 | 
			
		||||
                    CarStatus = carStatus,
 | 
			
		||||
                    IsGPSLost = isGPSLost,
 | 
			
		||||
                    StrRFID = RFID,
 | 
			
		||||
                    Version = version,
 | 
			
		||||
                    GPSInfor = gpsInfor != null ? gpsInfor.ToString() : string.Empty,
 | 
			
		||||
                    IsJamming = isJamming,
 | 
			
		||||
                    IsSpoofing = isSpoofing,
 | 
			
		||||
                    Cam1OK = cam1OK,
 | 
			
		||||
                    Cam2OK = cam2OK,
 | 
			
		||||
                    CamDetach = camDetach,
 | 
			
		||||
                    Code = "OK",
 | 
			
		||||
                };
 | 
			
		||||
            }
 | 
			
		||||
            return requestLog;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        private async Task UpdateOnlineProcedure(DeviceLogRequest request, string imei)
 | 
			
		||||
        private async Task UpdateOnlineProcedure(DeviceLogRequest request, string Imei)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
| 
						 | 
				
			
			@ -246,7 +387,7 @@ namespace RuleEngine.Services
 | 
			
		|||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                StaticResources.LogException2File(exceptionFolder, imei + "_ex_pvt", DateTime.UtcNow.ToString() + " InsertLst_TrucTuyen " + ex.ToString());
 | 
			
		||||
                StaticResources.LogException2File(exceptionFolder, Imei + "_ex_pvt", DateTime.UtcNow.ToString() + " InsertLst_TrucTuyen " + ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
| 
						 | 
				
			
			@ -340,7 +481,7 @@ namespace RuleEngine.Services
 | 
			
		|||
            await _dbContext.SaveChangesAsync();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        private async Task InsertHistoryProcedure(DeviceLogRequest request, string imei)
 | 
			
		||||
        private async Task InsertHistoryProcedure(DeviceLogRequest request, string Imei)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
| 
						 | 
				
			
			@ -376,7 +517,7 @@ namespace RuleEngine.Services
 | 
			
		|||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                StaticResources.LogException2File(exceptionFolder, imei + "_ex_pvt", DateTime.UtcNow.ToString() + " InsertHistoryProcedure " + ex.ToString());
 | 
			
		||||
                StaticResources.LogException2File(exceptionFolder, Imei + "_ex_pvt", DateTime.UtcNow.ToString() + " InsertHistoryProcedure " + ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
| 
						 | 
				
			
			@ -400,5 +541,170 @@ namespace RuleEngine.Services
 | 
			
		|||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public ShortDeviceInfor FindIdXeFromDeviceImei(DatabaseContext context, string Imei)
 | 
			
		||||
        {
 | 
			
		||||
            var shortDeviceInfor = new ShortDeviceInfor
 | 
			
		||||
            {
 | 
			
		||||
                CarID = 0,
 | 
			
		||||
                UnitID = 0
 | 
			
		||||
            };
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                try
 | 
			
		||||
                {
 | 
			
		||||
                    var device = context.Devices.AsNoTracking()
 | 
			
		||||
                        .Where(p => p.Imei == Imei)
 | 
			
		||||
                        .Select(p => new { p.Id, p.UnitId })
 | 
			
		||||
                        .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                    if (device != null)
 | 
			
		||||
                    {
 | 
			
		||||
                        // da ton tai thiet bi tren he thong
 | 
			
		||||
                        // truong hop nhap thang truc tiep Imei qua website
 | 
			
		||||
                        // truong hop xoa bien so xe, nhung Imei thiet bi van con
 | 
			
		||||
                        var car = context.Cars.AsNoTracking()
 | 
			
		||||
                            .Where(p => p.DeviceId == device.Id)
 | 
			
		||||
                            .Select(p => new { p.Id, p.UnitId })
 | 
			
		||||
                            .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                        if (car != null)
 | 
			
		||||
                        {
 | 
			
		||||
                            shortDeviceInfor.CarID = car.Id;
 | 
			
		||||
                            shortDeviceInfor.UnitID = car.UnitId ?? 0;
 | 
			
		||||
                            return shortDeviceInfor;
 | 
			
		||||
                        }
 | 
			
		||||
                        else
 | 
			
		||||
                        {
 | 
			
		||||
                            var autoAddConfig = context.AppCfgs.AsNoTracking()
 | 
			
		||||
                            .Where(p => p.CfgKey == "AUTO_ADD_DEVICE")
 | 
			
		||||
                            .Select(p => new { p.CfgValue })
 | 
			
		||||
                            .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                            if (autoAddConfig != null && Convert.ToInt32(autoAddConfig.CfgValue ?? 0) == 1)
 | 
			
		||||
                            {
 | 
			
		||||
                                shortDeviceInfor = AutoAddDevice(context, Imei, device.Id);
 | 
			
		||||
                                return shortDeviceInfor;
 | 
			
		||||
                            }
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                    else
 | 
			
		||||
                    {
 | 
			
		||||
                        // chua ton tai thiet bi
 | 
			
		||||
                        // tao moi thiet bi
 | 
			
		||||
                        var autoAddConfig = context.AppCfgs.AsNoTracking()
 | 
			
		||||
                            .Where(p => p.CfgKey == "AUTO_ADD_DEVICE")
 | 
			
		||||
                            .Select(p => new { p.CfgValue })
 | 
			
		||||
                            .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                        if (autoAddConfig != null && (int)autoAddConfig.CfgValue == 1)
 | 
			
		||||
                        {
 | 
			
		||||
                            shortDeviceInfor = AutoAddDevice(context, Imei, 0);
 | 
			
		||||
                            return shortDeviceInfor;
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
                catch (Exception ex)
 | 
			
		||||
                {
 | 
			
		||||
                    StaticResources.Log2File(logFolderPath + "Debug.txt", ex.ToString());
 | 
			
		||||
                }
 | 
			
		||||
                shortDeviceInfor.CarID = 0;
 | 
			
		||||
                shortDeviceInfor.UnitID = 0;
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                StaticResources.Log2File(logFolderPath + "Debug.txt", ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
            return shortDeviceInfor;
 | 
			
		||||
        }
 | 
			
		||||
        
 | 
			
		||||
        private ShortDeviceInfor AutoAddDevice(DatabaseContext context,string Imei, int existDeviceId)
 | 
			
		||||
        {
 | 
			
		||||
            ShortDeviceInfor shortDeviceInfor = new ShortDeviceInfor
 | 
			
		||||
            {
 | 
			
		||||
                CarID = 0,
 | 
			
		||||
                UnitID = 0
 | 
			
		||||
            };
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                // check nhom xe
 | 
			
		||||
                var orgDevice = context.Units.AsNoTracking().Where(p => p.Province == "INSTALLING_CAR").FirstOrDefault();
 | 
			
		||||
                var demoUser = context.Users.AsNoTracking()
 | 
			
		||||
                                    .Where(p => p.UserName == "demo")
 | 
			
		||||
                                    .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                if (demoUser == null)
 | 
			
		||||
                {
 | 
			
		||||
                    demoUser = new User();
 | 
			
		||||
                    demoUser.UserName = "demo";
 | 
			
		||||
                    context.Users.Add(demoUser);
 | 
			
		||||
                    context.SaveChanges();
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
                if (orgDevice == null)
 | 
			
		||||
                {
 | 
			
		||||
                    orgDevice = new Unit();
 | 
			
		||||
                    orgDevice.Name = "Xe đang lắp đặt";
 | 
			
		||||
                    orgDevice.Description = "Xe đang lắp đặt";
 | 
			
		||||
                    orgDevice.CreatedAt = DateTime.UtcNow.AddHours(7);
 | 
			
		||||
                    orgDevice.UpdatedAt = DateTime.UtcNow.AddHours(7);
 | 
			
		||||
                    orgDevice.Province = "INSTALLING_CAR";
 | 
			
		||||
 | 
			
		||||
                    context.Units.Add(orgDevice);
 | 
			
		||||
                    context.SaveChanges();
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
                var orgUser = _dbContext.UserUnits.AsNoTracking()
 | 
			
		||||
                    .Where(p => p.UserId == demoUser.Id && p.UnitId == orgDevice.Id)
 | 
			
		||||
                    .FirstOrDefault();
 | 
			
		||||
 | 
			
		||||
                if (orgUser == null)
 | 
			
		||||
                {
 | 
			
		||||
                    orgUser = new UserUnit();
 | 
			
		||||
                    orgUser.UserId = demoUser.Id;
 | 
			
		||||
                    orgUser.UnitId = orgDevice.Id;
 | 
			
		||||
                    context.UserUnits.Add(orgUser);
 | 
			
		||||
                    context.SaveChanges();
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
                int tempDeviceId = 0;
 | 
			
		||||
                if (existDeviceId > 0)
 | 
			
		||||
                {
 | 
			
		||||
                    // da ton tai thiet bi
 | 
			
		||||
                    tempDeviceId = existDeviceId;
 | 
			
		||||
                }
 | 
			
		||||
                else
 | 
			
		||||
                {
 | 
			
		||||
                    // thiet bi chua ton tai tren he thong
 | 
			
		||||
                    // Add device
 | 
			
		||||
                    var newDevice = new Device();
 | 
			
		||||
                    newDevice.DeviceNumber = Imei;
 | 
			
		||||
                    newDevice.Imei = Imei;
 | 
			
		||||
                    newDevice.UnitId = orgDevice.Id;
 | 
			
		||||
                    newDevice.IsActive = true;
 | 
			
		||||
                    newDevice.AllowUpdate = false;
 | 
			
		||||
 | 
			
		||||
                    _dbContext.Devices.Add(newDevice);
 | 
			
		||||
                    _dbContext.SaveChanges();
 | 
			
		||||
 | 
			
		||||
                    tempDeviceId = newDevice.Id;
 | 
			
		||||
                }
 | 
			
		||||
                
 | 
			
		||||
                // Add Car
 | 
			
		||||
                var newCar = new Car();
 | 
			
		||||
                newCar.LicensePlate = Imei;
 | 
			
		||||
                newCar.DeviceId = tempDeviceId;
 | 
			
		||||
                newCar.UnitId = orgDevice.Id;
 | 
			
		||||
                _dbContext.Cars.Add(newCar);
 | 
			
		||||
                _dbContext.SaveChanges();
 | 
			
		||||
                shortDeviceInfor.CarID = newCar.Id;
 | 
			
		||||
                shortDeviceInfor.UnitID = newCar.UnitId??0;
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                StaticResources.Log2File(logFolderPath + "LogAddDevice.txt", Imei + "_" + DateTime.Now.ToString() + ": " + ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
            
 | 
			
		||||
            return shortDeviceInfor;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			@ -33,16 +33,14 @@
 | 
			
		|||
    "Broker": "localhost",
 | 
			
		||||
    "Port": 1883,
 | 
			
		||||
    "JwtSecret": "emqx@sivan123456789@emqx@sivan123456789@emqx@sivan123456789@emqx@sivan123456789",
 | 
			
		||||
    "Username": "emqxruleengine",
 | 
			
		||||
    "Username": "ruleengine",
 | 
			
		||||
    "Password": "navis@123",
 | 
			
		||||
    "Topic": {
 | 
			
		||||
      "DeviceStatus": "devices/status",
 | 
			
		||||
      "DeviceHealth": "devices/health",
 | 
			
		||||
      "PushCommand": "devices/command"
 | 
			
		||||
      "UpdatePVT": "iot/devices/update_PVT"
 | 
			
		||||
    }
 | 
			
		||||
  },
 | 
			
		||||
  "ConnectionStrings": {
 | 
			
		||||
    "RuleEngineConnectStr": "Data Source=203.171.20.94,1434;Database=LPB.CarTracking;User ID=mbbcartracking05;Password=navis@123"
 | 
			
		||||
    "RuleEngineConnectStr": "Data Source=203.171.20.94,1434;Database=LPB.CarTracking;User ID=mbbcartracking05;Password=navis@123;TrustServerCertificate=True;"
 | 
			
		||||
  },
 | 
			
		||||
  "EnableLogFile": true,
 | 
			
		||||
  "LogFolderPath": "..\/Logs",
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
							
								
								
									
										31
									
								
								RuleEngine/docker-compose.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								RuleEngine/docker-compose.yml
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
				
			
			@ -0,0 +1,31 @@
 | 
			
		|||
services:
 | 
			
		||||
  ruleengine:
 | 
			
		||||
    container_name: car_tracking_rule_engine
 | 
			
		||||
    build: 
 | 
			
		||||
      context: .
 | 
			
		||||
      dockerfile: Dockerfile
 | 
			
		||||
    environment:
 | 
			
		||||
      - APP_UID=1000
 | 
			
		||||
    depends_on:
 | 
			
		||||
      - emqx
 | 
			
		||||
    restart: unless-stopped
 | 
			
		||||
    networks:
 | 
			
		||||
      - ruleengine_network
 | 
			
		||||
 | 
			
		||||
  emqx:
 | 
			
		||||
    image: emqx:5.8.5
 | 
			
		||||
    container_name: emqx
 | 
			
		||||
    ports:
 | 
			
		||||
      - "1883:1883"
 | 
			
		||||
      - "8083:8083"
 | 
			
		||||
      - "8084:8084"
 | 
			
		||||
      - "18083:18083"
 | 
			
		||||
    environment:
 | 
			
		||||
      - EMQX_DASHBOARD__DEFAULT_USERNAME=admin
 | 
			
		||||
      - EMQX_DASHBOARD__DEFAULT_PASSWORD=public
 | 
			
		||||
    networks:
 | 
			
		||||
      - ruleengine_network
 | 
			
		||||
  
 | 
			
		||||
networks:
 | 
			
		||||
  ruleengine_network:
 | 
			
		||||
    driver: bridge
 | 
			
		||||
| 
						 | 
				
			
			@ -1,167 +1,89 @@
 | 
			
		|||
using System.Security.Cryptography;
 | 
			
		||||
using System.Text.Json;
 | 
			
		||||
using System.Text;
 | 
			
		||||
using MQTTnet;
 | 
			
		||||
using MQTTnet;
 | 
			
		||||
using MQTTnet.Protocol;
 | 
			
		||||
using Newtonsoft.Json;
 | 
			
		||||
using System.Collections.Concurrent;
 | 
			
		||||
using System.Text;
 | 
			
		||||
using SimulatedTrackingDevice.DTOs; // Giữ nguyên nếu class DeviceMessage ở đây
 | 
			
		||||
 | 
			
		||||
namespace SimulatedTrackingDevice
 | 
			
		||||
{
 | 
			
		||||
    internal class Program
 | 
			
		||||
    {
 | 
			
		||||
        private static readonly string BrokerIp = "127.0.0.1";
 | 
			
		||||
        //private static readonly string BrokerIp = "localhost";
 | 
			
		||||
        private static readonly string BrokerIp = "localhost";
 | 
			
		||||
        private static readonly int BrokerPort = 1883;
 | 
			
		||||
        private static readonly string Username = "emqxdevice";
 | 
			
		||||
        private static readonly string Password = "sivan@123";
 | 
			
		||||
        private static readonly string DevicePasswordSalt = "navis@salt";
 | 
			
		||||
        private static readonly int secondsToReconnect = 2000;
 | 
			
		||||
        private static readonly int secondsToHealthcheck = 10000;
 | 
			
		||||
        private static readonly string Imei = "22222test2222";
 | 
			
		||||
 | 
			
		||||
        //private static readonly int DeviceCount = 1000;
 | 
			
		||||
 | 
			
		||||
        private static readonly string UpdatePVTTopic = "iot/device/update_pvt";
 | 
			
		||||
        private static readonly ConcurrentDictionary<string, string> deviceTokens = new();
 | 
			
		||||
        private static readonly ConcurrentDictionary<string, SemaphoreSlim> deviceSemaphores = new();
 | 
			
		||||
        private static readonly string UpdatePvtTopic = "iot/devices/update_PVT";
 | 
			
		||||
        private static readonly string ResponseTopic = $"iot/devices/update_PVT_response/{Imei}";
 | 
			
		||||
 | 
			
		||||
        static async Task Main(string[] args)
 | 
			
		||||
        {
 | 
			
		||||
            List<Task> deviceTasks = new();
 | 
			
		||||
            for (int i = 1; i <= 1; i++)
 | 
			
		||||
            {
 | 
			
		||||
                string localMacAddress = $"DeviceTest{i:0000}";
 | 
			
		||||
                deviceSemaphores[localMacAddress] = new SemaphoreSlim(1, 1); // Tạo semaphore riêng cho từng thiết bị
 | 
			
		||||
                //deviceTasks.Add(AllDevicePublish(macAddress, i));
 | 
			
		||||
                deviceTasks.Add(SimulateDevice(localMacAddress));
 | 
			
		||||
            var factory = new MqttClientFactory();
 | 
			
		||||
            var mqttClient = factory.CreateMqttClient();
 | 
			
		||||
 | 
			
		||||
                await Task.Delay(50); // Tránh quá tải khi tạo quá nhiều thiết bị cùng lúc
 | 
			
		||||
            mqttClient.ApplicationMessageReceivedAsync += async e =>
 | 
			
		||||
            {
 | 
			
		||||
                string topic = e.ApplicationMessage.Topic;
 | 
			
		||||
                string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
 | 
			
		||||
 | 
			
		||||
                if (topic == ResponseTopic)
 | 
			
		||||
                {
 | 
			
		||||
                    Console.WriteLine($"📩 Received response on topic '{topic}':");
 | 
			
		||||
                    Console.WriteLine(payload);
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
                await Task.CompletedTask;
 | 
			
		||||
            };
 | 
			
		||||
 | 
			
		||||
            var options = new MqttClientOptionsBuilder()
 | 
			
		||||
                .WithClientId($"SimDevice-{Guid.NewGuid()}")
 | 
			
		||||
                .WithCredentials("simdevice", "navis@123")
 | 
			
		||||
                .WithTcpServer(BrokerIp, BrokerPort)
 | 
			
		||||
                .WithCleanSession()
 | 
			
		||||
                .Build();
 | 
			
		||||
 | 
			
		||||
            await mqttClient.ConnectAsync(options);
 | 
			
		||||
 | 
			
		||||
            await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder()
 | 
			
		||||
                .WithTopic(ResponseTopic)
 | 
			
		||||
                .WithAtLeastOnceQoS()
 | 
			
		||||
                .Build());
 | 
			
		||||
 | 
			
		||||
            Console.WriteLine($"✅ Subscribed to response topic: {ResponseTopic}");
 | 
			
		||||
 | 
			
		||||
            // Load mock data from file
 | 
			
		||||
            string jsonFilePath = "mock_data.json";
 | 
			
		||||
            if (!File.Exists(jsonFilePath))
 | 
			
		||||
            {
 | 
			
		||||
                Console.WriteLine("❌ File 'mock_data.json' not found.");
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
            await Task.WhenAll(deviceTasks);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        private static async Task SimulateDevice(string localMacAddress)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            string jsonContent = await File.ReadAllTextAsync(jsonFilePath);
 | 
			
		||||
            var message = JsonConvert.DeserializeObject<DeviceMessage>(jsonContent);
 | 
			
		||||
            if (message == null)
 | 
			
		||||
            {
 | 
			
		||||
                var factory = new MqttClientFactory();
 | 
			
		||||
                var mqttClient = factory.CreateMqttClient();
 | 
			
		||||
                string token = "";
 | 
			
		||||
                Console.WriteLine("❌ Failed to parse JSON data.");
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
                var options = new MqttClientOptionsBuilder()
 | 
			
		||||
                    .WithClientId(localMacAddress)
 | 
			
		||||
                    .WithTcpServer(BrokerIp, BrokerPort)
 | 
			
		||||
                    .WithCredentials(Username, Password)
 | 
			
		||||
                    .WithCleanSession()
 | 
			
		||||
            // Gửi bản tin update_pvt mỗi 10 giây
 | 
			
		||||
            while (true)
 | 
			
		||||
            {
 | 
			
		||||
                message.ReceivedTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
 | 
			
		||||
 | 
			
		||||
                string jsonPayload = JsonConvert.SerializeObject(message);
 | 
			
		||||
                var mqttMessage = new MqttApplicationMessageBuilder()
 | 
			
		||||
                    .WithTopic(UpdatePvtTopic)
 | 
			
		||||
                    .WithPayload(jsonPayload)
 | 
			
		||||
                    .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
 | 
			
		||||
                    .WithRetainFlag(false)
 | 
			
		||||
                    .Build();
 | 
			
		||||
 | 
			
		||||
                mqttClient.ApplicationMessageReceivedAsync += async e =>
 | 
			
		||||
                {
 | 
			
		||||
                    var macAddressProperty = e.ApplicationMessage.UserProperties
 | 
			
		||||
                                                .FirstOrDefault(p => p.Name == "MacAddress")?.Value;
 | 
			
		||||
                    if (macAddressProperty == localMacAddress)
 | 
			
		||||
                    {
 | 
			
		||||
                        var commandTopic = "iot/server/" + localMacAddress + "/command";
 | 
			
		||||
                        string topic = e.ApplicationMessage.Topic;
 | 
			
		||||
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
 | 
			
		||||
                await mqttClient.PublishAsync(mqttMessage);
 | 
			
		||||
                Console.WriteLine($"📤 Sent PVT message to '{UpdatePvtTopic}'");
 | 
			
		||||
 | 
			
		||||
                        if (topic == ResponseTopic)
 | 
			
		||||
                        {
 | 
			
		||||
                            if (!string.IsNullOrEmpty(payload))
 | 
			
		||||
                            {
 | 
			
		||||
                                var response = System.Text.Json.JsonSerializer.Deserialize<DeviceRegisterResponse>(payload);
 | 
			
		||||
                                token = response.AccessToken;
 | 
			
		||||
 | 
			
		||||
                                // Unsubscribe khỏi topic response sau khi nhận token
 | 
			
		||||
                                await mqttClient.UnsubscribeAsync(ResponseTopic);
 | 
			
		||||
                                Console.WriteLine(localMacAddress + ": Unsubscribed from response topic");
 | 
			
		||||
 | 
			
		||||
                                // log file
 | 
			
		||||
                                Log2File("./LogFiles/" + localMacAddress + ".txt", DateTime.UtcNow.AddHours(7).ToString("yyyy/MM/dd HH:mm:ss") + " - Received: " + payload);
 | 
			
		||||
                            }
 | 
			
		||||
                        }
 | 
			
		||||
                        else if (topic == commandTopic)
 | 
			
		||||
                        {
 | 
			
		||||
                            // xu ly lenh gui tu server
 | 
			
		||||
                            Console.WriteLine(localMacAddress + ": " + payload);
 | 
			
		||||
                            // log file
 | 
			
		||||
                            Log2File("./LogFiles/" + localMacAddress + ".txt", DateTime.UtcNow.AddHours(7).ToString("yyyy/MM/dd HH:mm:ss") + " - Received: " + payload);
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                };
 | 
			
		||||
 | 
			
		||||
                await mqttClient.ConnectAsync(options, CancellationToken.None);
 | 
			
		||||
                await mqttClient.SubscribeAsync(ResponseTopic, MqttQualityOfServiceLevel.AtLeastOnce);
 | 
			
		||||
                await SendRegistrationRequest(mqttClient, localMacAddress);
 | 
			
		||||
 | 
			
		||||
                while (string.IsNullOrEmpty(token))
 | 
			
		||||
                {
 | 
			
		||||
                    await Task.Delay(1000);
 | 
			
		||||
                }
 | 
			
		||||
 | 
			
		||||
                var _factory = new MqttClientFactory();
 | 
			
		||||
                var _mqttClient = _factory.CreateMqttClient();
 | 
			
		||||
                var _options = new MqttClientOptionsBuilder()
 | 
			
		||||
                    .WithClientId(localMacAddress)
 | 
			
		||||
                    .WithTcpServer(BrokerIp, BrokerPort)
 | 
			
		||||
                    .WithCredentials(localMacAddress, token)
 | 
			
		||||
                    .WithCleanSession()
 | 
			
		||||
                    .Build();
 | 
			
		||||
 | 
			
		||||
                _mqttClient.DisconnectedAsync += async (e) =>
 | 
			
		||||
                {
 | 
			
		||||
                    Console.WriteLine($"MQTT Disconnected. Reason: {e.ToString()}");
 | 
			
		||||
 | 
			
		||||
                    // Nếu lỗi có thể do token hết hạn, gửi lại request đăng ký
 | 
			
		||||
                    if (e.Reason == MqttClientDisconnectReason.NotAuthorized)
 | 
			
		||||
                    {
 | 
			
		||||
                        Console.WriteLine("Token might be expired. Sending Register...");
 | 
			
		||||
                    }
 | 
			
		||||
                };
 | 
			
		||||
 | 
			
		||||
                await _mqttClient.ConnectAsync(_options, CancellationToken.None);
 | 
			
		||||
 | 
			
		||||
                while (true)
 | 
			
		||||
                {
 | 
			
		||||
                    await SendHealthData(_mqttClient, localMacAddress, token);
 | 
			
		||||
                    await Task.Delay(10000);
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                // log file
 | 
			
		||||
                Log2File("./LogFiles/Exceptions.txt", DateTime.UtcNow.AddHours(7).ToString("yyyy/MM/dd HH:mm:ss") + "- User: " + Username + " - " + localMacAddress + ": " + ex.ToString());
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public static void Log2File(string filePath, string data)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                FileInfo info = new FileInfo(filePath);
 | 
			
		||||
                try
 | 
			
		||||
                {
 | 
			
		||||
                    if (info.Exists && info.Length > 10000000) // delete the file first if 10 MB
 | 
			
		||||
                    {
 | 
			
		||||
                        File.Delete(filePath);
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
                catch (Exception ex)
 | 
			
		||||
                {
 | 
			
		||||
 | 
			
		||||
                }
 | 
			
		||||
                using (var fs = File.Open(filePath, FileMode.Append))
 | 
			
		||||
                {
 | 
			
		||||
                    using (var sw = new StreamWriter(fs))
 | 
			
		||||
                    {
 | 
			
		||||
                        sw.WriteLine(data);
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                await Task.Delay(10000);
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
   
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
							
								
								
									
										
											BIN
										
									
								
								SimulatedTrackingDevice/bin/Debug/net8.0/MQTTnet.dll
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								SimulatedTrackingDevice/bin/Debug/net8.0/MQTTnet.dll
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							
							
								
								
									
										
											BIN
										
									
								
								SimulatedTrackingDevice/bin/Debug/net8.0/Newtonsoft.Json.dll
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								SimulatedTrackingDevice/bin/Debug/net8.0/Newtonsoft.Json.dll
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							| 
						 | 
				
			
			@ -0,0 +1,57 @@
 | 
			
		|||
{
 | 
			
		||||
  "runtimeTarget": {
 | 
			
		||||
    "name": ".NETCoreApp,Version=v8.0",
 | 
			
		||||
    "signature": ""
 | 
			
		||||
  },
 | 
			
		||||
  "compilationOptions": {},
 | 
			
		||||
  "targets": {
 | 
			
		||||
    ".NETCoreApp,Version=v8.0": {
 | 
			
		||||
      "SimulatedTrackingDevice/1.0.0": {
 | 
			
		||||
        "dependencies": {
 | 
			
		||||
          "MQTTnet": "5.0.1.1416",
 | 
			
		||||
          "Newtonsoft.Json": "13.0.3"
 | 
			
		||||
        },
 | 
			
		||||
        "runtime": {
 | 
			
		||||
          "SimulatedTrackingDevice.dll": {}
 | 
			
		||||
        }
 | 
			
		||||
      },
 | 
			
		||||
      "MQTTnet/5.0.1.1416": {
 | 
			
		||||
        "runtime": {
 | 
			
		||||
          "lib/net8.0/MQTTnet.dll": {
 | 
			
		||||
            "assemblyVersion": "5.0.1.1416",
 | 
			
		||||
            "fileVersion": "5.0.1.1416"
 | 
			
		||||
          }
 | 
			
		||||
        }
 | 
			
		||||
      },
 | 
			
		||||
      "Newtonsoft.Json/13.0.3": {
 | 
			
		||||
        "runtime": {
 | 
			
		||||
          "lib/net6.0/Newtonsoft.Json.dll": {
 | 
			
		||||
            "assemblyVersion": "13.0.0.0",
 | 
			
		||||
            "fileVersion": "13.0.3.27908"
 | 
			
		||||
          }
 | 
			
		||||
        }
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
  },
 | 
			
		||||
  "libraries": {
 | 
			
		||||
    "SimulatedTrackingDevice/1.0.0": {
 | 
			
		||||
      "type": "project",
 | 
			
		||||
      "serviceable": false,
 | 
			
		||||
      "sha512": ""
 | 
			
		||||
    },
 | 
			
		||||
    "MQTTnet/5.0.1.1416": {
 | 
			
		||||
      "type": "package",
 | 
			
		||||
      "serviceable": true,
 | 
			
		||||
      "sha512": "sha512-ONYieEMaHiIei5dAtHXywnfJGhmrd5Av5sNJSQERp6AtZdPk3xxjCR6Cv0C5RUr/XbLeHO4/HQ0Rc2bQ5NF5Mw==",
 | 
			
		||||
      "path": "mqttnet/5.0.1.1416",
 | 
			
		||||
      "hashPath": "mqttnet.5.0.1.1416.nupkg.sha512"
 | 
			
		||||
    },
 | 
			
		||||
    "Newtonsoft.Json/13.0.3": {
 | 
			
		||||
      "type": "package",
 | 
			
		||||
      "serviceable": true,
 | 
			
		||||
      "sha512": "sha512-HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==",
 | 
			
		||||
      "path": "newtonsoft.json/13.0.3",
 | 
			
		||||
      "hashPath": "newtonsoft.json.13.0.3.nupkg.sha512"
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							
										
											Binary file not shown.
										
									
								
							| 
						 | 
				
			
			@ -0,0 +1,12 @@
 | 
			
		|||
{
 | 
			
		||||
  "runtimeOptions": {
 | 
			
		||||
    "tfm": "net8.0",
 | 
			
		||||
    "framework": {
 | 
			
		||||
      "name": "Microsoft.NETCore.App",
 | 
			
		||||
      "version": "8.0.0"
 | 
			
		||||
    },
 | 
			
		||||
    "configProperties": {
 | 
			
		||||
      "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										44
									
								
								SimulatedTrackingDevice/mock_data.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								SimulatedTrackingDevice/mock_data.json
									
									
									
									
									
										Normal file
									
								
							| 
						 | 
				
			
			@ -0,0 +1,44 @@
 | 
			
		|||
{
 | 
			
		||||
  "imei": "22222test2222",
 | 
			
		||||
  "receivedTime": "2023/06/09 10:04:59",
 | 
			
		||||
  "longitude": 106.69218166,
 | 
			
		||||
  "latitude": 10.76435698,
 | 
			
		||||
  "gpsSpeed": 0,
 | 
			
		||||
  "celID": "151221762",
 | 
			
		||||
  "lacID": "25136",
 | 
			
		||||
  "isSOS": false,
 | 
			
		||||
  "isStrongBoxOpen": false,
 | 
			
		||||
  "isEngineOn": true,
 | 
			
		||||
  "isStopping": true,
 | 
			
		||||
  "isGPSLost": false,
 | 
			
		||||
  "totalImgCam1": 52,
 | 
			
		||||
  "totalImgCam2": 469,
 | 
			
		||||
  "strRFID": "FF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007EFFFFFFFFFF017F000000007E",
 | 
			
		||||
  "strOBD": "0;0;0;0",
 | 
			
		||||
  "provider": "gps",
 | 
			
		||||
  "version": "2023050901_mb_hub3.0_onoff_cam",
 | 
			
		||||
  "cpuTime": 321,
 | 
			
		||||
  "geoMinDistance": 1000000,
 | 
			
		||||
  "nearestLat": 0,
 | 
			
		||||
  "nearestLon": 0,
 | 
			
		||||
  "nearestID": 0,
 | 
			
		||||
  "nearestName": "",
 | 
			
		||||
  "maxsnr": 43,
 | 
			
		||||
  "cpuTemp": "43674",
 | 
			
		||||
  "gpsInfor": {
 | 
			
		||||
    "agcLevelDb": -13.45,
 | 
			
		||||
    "maxsnr": 43.6,
 | 
			
		||||
    "satelliteUseInFixed": 0,
 | 
			
		||||
    "cellid": "151221762",
 | 
			
		||||
    "lacid": "25136",
 | 
			
		||||
    "mcc": "452",
 | 
			
		||||
    "mnc": "04",
 | 
			
		||||
    "networkType": "class android.telephony.CellSignalStrengthLte",
 | 
			
		||||
    "signalStrength": "-69"
 | 
			
		||||
  },
 | 
			
		||||
  "cam1OK": true,
 | 
			
		||||
  "cam2OK": true,
 | 
			
		||||
  "camDetach": false,
 | 
			
		||||
  "isJamming": false,
 | 
			
		||||
  "isSpoofing": false
 | 
			
		||||
}
 | 
			
		||||
		Loading…
	
		Reference in New Issue
	
	Block a user