This commit is contained in:
HuyND 2025-03-25 10:01:22 +07:00
commit 4cfa741654
29 changed files with 1530 additions and 0 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
.gitignore vendored Normal file
View File

@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,2 @@
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

25
UbloxSC20.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UbloxSC20", "UbloxSC20\UbloxSC20.csproj", "{565520AB-106B-49D8-B222-DF38B9246FB5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{565520AB-106B-49D8-B222-DF38B9246FB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{565520AB-106B-49D8-B222-DF38B9246FB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{565520AB-106B-49D8-B222-DF38B9246FB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{565520AB-106B-49D8-B222-DF38B9246FB5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BB7C38E3-53C5-4322-A148-E3DF3401F7B5}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,236 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NuGet.Packaging.Signing;
using UbloxSC20.Data;
using UbloxSC20.Model;
using UbloxSC20.UBXDecoder;
using Serilog;
using System.CodeDom;
using System.Security.Cryptography;
using System.Text;
using System.Security.Cryptography.Xml;
namespace UbloxSC20.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class NavigationModelsController : ControllerBase
{
private readonly UbloxSC20Context _context;
string privateKey = "MIIEowIBAAKCAQEAuqvwyKfMPcEkSElMM59pBNFLJLIAqJYWdHe6w7oaHf9sPNTQ3g+/E9dUuZH8TWqimPr5Wq/2pD" +
"mD8D4wnXeNe09ldsPFxGMrLxdHEscin56+SAVoX1O0bumSUIKiODHLTNkxAIibZkUbPSJZDySRLAoQ+21e9JL6/ocRMN21W37CF/HVPBB5JPLIO" +
"go2zqg3VX9DUIKQG72Wh8b6TGMwDE4FIQQXcsTA1UuCVEC41B0FQnygA6IdK11TTart5WMFRhWufcI/yZL7MF+/4myob5m5ESa4oQWHT7twHOjpf" +
"o7uJRF9PaB7lRMWQH5sEnQqBdjNUicFpTPR0D7XxKmLDQIDAQABAoIBAFAKi8suD+hm2azZKQB1mO1E5MiOPrQK7wPvlrh4Ity7+eg3hHvDGrZiPW" +
"T4kMuNLr0T2Dmne8U9GDK6J9RNP/Agwivjk/g6YXjmrUYC9vikc4ikMPW3CYYJRwCYkwAvcbG460cETEXU2fIjuTZCArF0e4WjhvSt1UuwFJH0buA" +
"UxKdrvenpLh054UaPhR4NzpElggqtq0Xpi5Yp80+M7iMcLh1JzuOdouLFd0B92HhvC0aAAIPi7ikvfLDpJPn6hhaXFtkmsaBqwUiSSiuoShNKelAP2" +
"+a9ATXFqUqVAYRsKFePyTvVHs7yGzxi+BfiuhIEgiT6IGmXplOYgN7PSw0CgYEAxVsLJ62qKLmYO3c9+Y32dso1ih39hoSWEDIxnetjaB/dEPq/j4k" +
"XKqefMb2WGZXXtfcDd7FWXsLvnDEQy+sjr5rYp4BCIIjAnEn6Qi3a8rD1bszmuJIL9BEpIwtBJYyFTMB1n88axJd5YpWKrl3Yw/fqzHO6d0G7MQu4qQ" +
"wn7B8CgYEA8iQoxuvwtDA2L/G7/8OdYrh9uLjQEV12Yqvb/IAwiAjqivO8Obxu3BgK8wB/FfGmpxeNiVNikFsYQWqDI98MrGB2QJcuYU8MUCE0kpz/V" +
"5HCyO1UeIFjYQ86Xuwek7tAyNUuDhB6AwD7Ia9JXuGAsplTWcJ/21M1lEQ6yK+YY1MCgYBg/vgijjX9QgpR3680AdPKWmOp+EdsX6mpWCIOrWvz9wUd" +
"nT+c+hHKwwt41Ob6uCyGoFqx7xS2CjTdnTfWIUEuw3oMCPt3Jf8UUT+QWx0q/lICHO6gdBcv42dGc/eWztOM/2JQIufTC2d7TmgUfsdUuXpK9e4FQuc" +
"PmeUuIG1WnQKBgA2gS0sma903+VSpXdL+xxSPHUQP4mWXxNm4oiCLdi+xkMFRBf6ZxANOtw8FsCEkACTXBnf74UgOWEcWH1sdajEpHH52A34mXKMFu1" +
"ekzhm3ciasdFxzq4wCt14wG2hk2Th0Bqtz8enJXFiA7LgSKJPkXPRoJZnKDPHTBRvWBdVRAoGBAJd7evuesoSfjHQP84lqZvIz6vx2BSaxVp5fzrd8gB" +
"bTfMTaVND8XPEiijePx2qvdByIhEAUwzSCWJVuTf1L5c1WZVN35la+lS8VbJdFXs5vh7e3YSXxzAnD9WbLXZYzffScysw4s/3FA4qgHTHKfZKp87fbXQXxyt65iyrun4gF";
string publicKey = "MIIBCgKCAQEAuqvwyKfMPcEkSElMM59pBNFLJLIAqJYWdHe6w7oaHf9sPNTQ3g+/E9dUuZH8TWqimPr5Wq/2pDmD8D4wnXeNe0" +
"9ldsPFxGMrLxdHEscin56+SAVoX1O0bumSUIKiODHLTNkxAIibZkUbPSJZDySRLAoQ+21e9JL6/ocRMN21W37CF/HVPBB5JPLIOgo2zqg3VX9DUIKQG72Wh8b" +
"6TGMwDE4FIQQXcsTA1UuCVEC41B0FQnygA6IdK11TTart5WMFRhWufcI/yZL7MF+/4myob5m5ESa4oQWHT7twHOjpfo7uJRF9PaB7lRMWQH5sEnQqBdjNUicF" +
"pTPR0D7XxKmLDQIDAQAB";
public NavigationModelsController(UbloxSC20Context context)
{
_context = context;
}
private string SignData(string data, string privateKey)
{
byte[] privateKeyBytes = Convert.FromBase64String(privateKey);
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportRSAPrivateKey(privateKeyBytes, out _);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] signedBytes = rsa.SignData(dataBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(signedBytes);
}
}
[HttpGet]
public async Task<ActionResult<IEnumerable<NavigationModel>>> GetNavigationModel()
{
return await _context.NavigationModel.ToListAsync();
}
// GET: api/NavigationModels/5
[HttpGet("{svId}/{week}/{tow}")]
public async Task<ActionResult<NavigationModel>> GetNavigationMessage(int svId, int week, int tow)
{
var navigationModel = await _context.NavigationModel
.FirstOrDefaultAsync(n => n.SvId == svId );
if (navigationModel == null)
{
return NotFound();
}
return navigationModel;
}
// PUT: api/NavigationModels/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{id}")]
public async Task<IActionResult> PutNavigationModel(int id, NavigationModel navigationModel)
{
if (id != navigationModel.Id)
{
return BadRequest();
}
_context.Entry(navigationModel).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!NavigationModelExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/NavigationModels
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<NavigationModel>> PostNavigationModel(NavigationModel navigationModel)
{
_context.NavigationModel.Add(navigationModel);
await _context.SaveChangesAsync();
return CreatedAtAction("GetNavigationModel", new { id = navigationModel.Id }, navigationModel);
}
[HttpPost("check")]
public async Task<ActionResult<NavigationModel>> PostCheckNavigationModel([FromBody] String navigaionHexString)
{
byte[] ubxSfrbxPacket = UbxDecoder.HexStringToByteArray(navigaionHexString);
//Parsed data
UbxDecoder decoder = new UbxDecoder();
UbxDecoder.UbxSfrbxResult result = decoder.DecodeUbxSfrbx(ubxSfrbxPacket);
if(result == null)
{
string notification = "Not Found HexString";
string signatureDecoder = SignData(notification, privateKey);
return Ok(new
{
Message = notification,
Signature = signatureDecoder
});
}
//Create Timestamp
DateTimeOffset serverDateTime = DateTimeOffset.UtcNow;
double timestamp = serverDateTime.ToUnixTimeSeconds();
byte[] payloadBytes = new byte[result.LastPayload.Length * sizeof(uint)];
Buffer.BlockCopy(result.LastPayload, 0, payloadBytes, 0, payloadBytes.Length);
//NavigationMessage
string navMessage;
navMessage = BitConverter.ToString(payloadBytes).Replace("-", "");
string responseMessage = "";
try
{
var navigationModelCheck = await _context.NavigationModel
.FirstOrDefaultAsync(n => n.SvId == result.SvId && n.SigId == result.SigId && n.GnssId == result.GnssId && n.FreqId == result.FreqId);
if (navigationModelCheck == null)
{
responseMessage = $"{navMessage}-{result.GnssId}-NotFoundGNSSSystem";
}
else
{
var navigationModelCheckNavMess = await _context.NavigationModel.FirstOrDefaultAsync(n => n.NavigationMessage.Equals(navMessage));
if (navigationModelCheckNavMess == null)
{
responseMessage = $"{navMessage}-{result.GnssId}-NotFound";
}
else
{
double timeStampCheck = 0;
try
{
timeStampCheck = Convert.ToDouble(navigationModelCheck.Timestamp);
}
catch (Exception ex)
{
Log.Information(ex.ToString());
}
if (Math.Abs(timestamp - timeStampCheck) <= 20)
{
Console.WriteLine(timeStampCheck);
responseMessage = $"{navMessage}-{result.GnssId}-Ok";
}
else
{
responseMessage = $"{navMessage}-{result.GnssId}-Ok-LimitedTime-{Math.Abs(timestamp - timeStampCheck)}s";
}
}
}
}
catch (Exception ex)
{
Log.Information(ex.ToString());
}
string signature = SignData(responseMessage, privateKey);
return Ok(new
{
Message = responseMessage,
Signature = signature
});
}
// DELETE: api/NavigationModels/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteNavigationModel(int id)
{
var navigationModel = await _context.NavigationModel.FindAsync(id);
if (navigationModel == null)
{
return NotFound();
}
_context.NavigationModel.Remove(navigationModel);
await _context.SaveChangesAsync();
return NoContent();
}
private bool NavigationModelExists(int id)
{
return _context.NavigationModel.Any(e => e.Id == id);
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UbloxSC20.Model;
namespace UbloxSC20.Data
{
public class UbloxSC20Context : DbContext
{
public UbloxSC20Context (DbContextOptions<UbloxSC20Context> options)
: base(options)
{
}
public DbSet<UbloxSC20.Model.NavigationModel> NavigationModel { get; set; } = default!;
}
}

View File

@ -0,0 +1,59 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
[Migration("20241015042217_NavigationMessage")]
partial class NavigationMessage
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Tow")
.HasColumnType("int");
b.Property<int>("Week")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UbloxSC20.Migrations
{
/// <inheritdoc />
public partial class NavigationMessage : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "NavigationModel",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
SvId = table.Column<int>(type: "int", nullable: false),
Week = table.Column<int>(type: "int", nullable: false),
Tow = table.Column<int>(type: "int", nullable: false),
NavigationMessage = table.Column<string>(type: "nvarchar(max)", nullable: false),
Timestamp = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NavigationModel", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "NavigationModel");
}
}
}

View File

@ -0,0 +1,59 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
[Migration("20241029030641_id_update")]
partial class id_update
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Tow")
.HasColumnType("int");
b.Property<int>("Week")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UbloxSC20.Migrations
{
/// <inheritdoc />
public partial class id_update : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -0,0 +1,59 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
[Migration("20241029034049_update")]
partial class update
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Tow")
.HasColumnType("int");
b.Property<int>("Week")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UbloxSC20.Migrations
{
/// <inheritdoc />
public partial class update : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -0,0 +1,62 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
[Migration("20241119080431_payload")]
partial class payload
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("GnssId")
.HasColumnType("int");
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SigId")
.HasColumnType("int");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("freqId")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UbloxSC20.Migrations
{
/// <inheritdoc />
public partial class payload : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Week",
table: "NavigationModel",
newName: "freqId");
migrationBuilder.RenameColumn(
name: "Tow",
table: "NavigationModel",
newName: "SigId");
migrationBuilder.AddColumn<int>(
name: "GnssId",
table: "NavigationModel",
type: "int",
nullable: false,
defaultValue: 0);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "GnssId",
table: "NavigationModel");
migrationBuilder.RenameColumn(
name: "freqId",
table: "NavigationModel",
newName: "Week");
migrationBuilder.RenameColumn(
name: "SigId",
table: "NavigationModel",
newName: "Tow");
}
}
}

View File

@ -0,0 +1,62 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
[Migration("20241119082430_updateFreqId")]
partial class updateFreqId
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("FreqId")
.HasColumnType("int");
b.Property<int>("GnssId")
.HasColumnType("int");
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SigId")
.HasColumnType("int");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace UbloxSC20.Migrations
{
/// <inheritdoc />
public partial class updateFreqId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "freqId",
table: "NavigationModel",
newName: "FreqId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "FreqId",
table: "NavigationModel",
newName: "freqId");
}
}
}

View File

@ -0,0 +1,59 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using UbloxSC20.Data;
#nullable disable
namespace UbloxSC20.Migrations
{
[DbContext(typeof(UbloxSC20Context))]
partial class UbloxSC20ContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("UbloxSC20.Model.NavigationModel", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("FreqId")
.HasColumnType("int");
b.Property<int>("GnssId")
.HasColumnType("int");
b.Property<string>("NavigationMessage")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("SigId")
.HasColumnType("int");
b.Property<int>("SvId")
.HasColumnType("int");
b.Property<string>("Timestamp")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("NavigationModel");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace UbloxSC20.Model
{
public class NavigationModel
{
public int Id { get; set; }
public int GnssId { get; set; }
public int SigId { get; set; }
public int FreqId { get; set; }
public int SvId { get; set; }
public string NavigationMessage { get; set; }
public string Timestamp { get; set; }
}
}

34
UbloxSC20/Program.cs Normal file
View File

@ -0,0 +1,34 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using UbloxSC20.Data;
var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Services.AddDbContext<UbloxSC20Context>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("UbloxSC20Context") ?? throw new InvalidOperationException("Connection string 'UbloxSC20Context' not found.")));
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:62925",
"sslPort": 44348
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5009",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7253;http://localhost:5009",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,8 @@
{
"dependencies": {
"mssql1": {
"type": "mssql",
"connectionId": "ConnectionStrings:UbloxSC20Context"
}
}
}

View File

@ -0,0 +1,8 @@
{
"dependencies": {
"mssql1": {
"type": "mssql.local",
"connectionId": "ConnectionStrings:UbloxSC20Context"
}
}
}

View File

@ -0,0 +1,131 @@
namespace UbloxSC20.UBXDecoder;
public class UbxDecoder
{
const byte SYNC_CHAR_1 = 0xB5;
const byte SYNC_CHAR_2 = 0x62;
const byte CLASS_NAV = 0x02;
const byte MSG_SFRBX = 0x13; // ID for UBX-RXM-SFRBX
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
struct UbxHeader
{
public byte Sync1;
public byte Sync2;
public byte ClassId;
public byte MsgId;
public ushort Length;
}
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]
struct UbxSfrbxMessage
{
public UbxHeader Header;
public byte GnssId;
public byte SvId;
public byte SigId;
public byte FreqId;
public uint[] LastPayload;
public byte CkA;
public byte CkB;
}
public class UbxSfrbxResult
{
public byte GnssId { get; set; }
public byte SvId { get; set; }
public byte SigId { get; set; }
public byte FreqId { get; set; }
public uint[] LastPayload { get; set; }
}
private bool VerifyChecksum(byte[] data, ushort length, byte ckA, byte ckB)
{
byte a = 0, b = 0;
for (ushort i = 0; i < length; i++)
{
a += data[i];
b += a;
}
return (a == ckA) && (b == ckB);
}
public UbxSfrbxResult DecodeUbxSfrbx(byte[] buffer)
{
if (buffer.Length < System.Runtime.InteropServices.Marshal.SizeOf(typeof(UbxHeader)) + 4)
{
Console.WriteLine("Buffer too small!");
return null;
}
UbxHeader header;
IntPtr headerPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(typeof(UbxHeader)));
try
{
System.Runtime.InteropServices.Marshal.Copy(buffer, 0, headerPtr, System.Runtime.InteropServices.Marshal.SizeOf(typeof(UbxHeader)));
header = (UbxHeader)System.Runtime.InteropServices.Marshal.PtrToStructure(headerPtr, typeof(UbxHeader));
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(headerPtr);
}
// Kiểm tra độ dài thực tế của buffer
if (buffer.Length < header.Length + System.Runtime.InteropServices.Marshal.SizeOf(typeof(UbxHeader)) + 2)
{
Console.WriteLine("Buffer length mismatch!");
return null;
}
// Kiểm tra checksum
if (!VerifyChecksum(buffer[2..], (ushort)(header.Length + 4), buffer[^2], buffer[^1]))
{
Console.WriteLine("Checksum verification failed!");
return null;
}
// Giải mã các trường chính
UbxSfrbxMessage msg = new UbxSfrbxMessage
{
Header = header,
GnssId = buffer[6],
SvId = buffer[7],
SigId = buffer[8],
FreqId = buffer[9],
CkA = buffer[^2],
CkB = buffer[^1]
};
// Lấy payload (các byte còn lại sau các trường chính)
int payloadStartIndex = 14;
int payloadLength = header.Length - (payloadStartIndex - 6); // Trừ đi các byte đã ánh xạ
uint[] lastPayload = new uint[payloadLength / 4];
for (int i = 0; i < lastPayload.Length; i++)
{
lastPayload[i] = BitConverter.ToUInt32(buffer, payloadStartIndex + i * 4);
}
// Trả về kết quả
return new UbxSfrbxResult
{
GnssId = msg.GnssId,
SvId = msg.SvId,
SigId = msg.SigId,
FreqId = msg.FreqId,
LastPayload = lastPayload
};
}
public static byte[] HexStringToByteArray(string hex)
{
int numberChars = hex.Length;
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
return bytes;
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.6" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>

6
UbloxSC20/UbloxSC20.http Normal file
View File

@ -0,0 +1,6 @@
@UbloxSC20_HostAddress = http://localhost:5009
GET {{UbloxSC20_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"UbloxSC20Context": "Server=203.171.20.94,1434;Initial Catalog=EphProvider;TrustServerCertificate=True;Trusted_Connection=True;Trusted_Connection=False;User ID=ngocmx;Password=Navis123"
}
}

5
UbloxSC20/libman.json Normal file
View File

@ -0,0 +1,5 @@
{
"version": "3.0",
"defaultProvider": "cdnjs",
"libraries": []
}