add openhack files

This commit is contained in:
Ryan Peters
2022-11-03 16:41:13 -04:00
commit b2c9f7e29f
920 changed files with 118861 additions and 0 deletions

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
</appSettings>
</configuration>

View File

@ -0,0 +1,258 @@
using DeviceSim.Helpers;
using Simulator.DataObjects;
using Simulator.DataStore.Stores;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DeviceSim.Controllers
{
public class ApiTripController : BaseTripController
{
private Trip CurrentTrip;
private List<TripPoint> CurrentTripPoints;
private TripStore tripStore;
private TripPointStore tripPointStore;
private PoiStore poiStore;
private UserStore userStore;
private string userApiEndPoint;
private string poiApiEndPoint;
private string tripsApiEndPoint;
private DateTime dateTime;
public ApiTripController(DBConnectionInfo dBConnectionInfo, string UserApiEndPoint,string PoiApiEndPoint, string TripsApiEndPoint ) : base(dBConnectionInfo)
{
userApiEndPoint = UserApiEndPoint;
poiApiEndPoint = PoiApiEndPoint;
tripsApiEndPoint = TripsApiEndPoint;
tripStore = new TripStore(tripsApiEndPoint);
tripPointStore = new TripPointStore(tripsApiEndPoint);
poiStore = new PoiStore(poiApiEndPoint);
userStore = new UserStore(userApiEndPoint);
}
public async Task CreateTrip()
{
dateTime = DateTime.UtcNow;
CurrentTrip = new Trip
{
Id = Guid.NewGuid().ToString(),
UserId = "Hacker 1",
Name = $"API-Trip {DateTime.Now}",
RecordedTimeStamp = dateTime.AddTicks(-1 * dateTime.Ticks % 10000),
EndTimeStamp = dateTime.AddTicks(-1 * dateTime.Ticks % 10000),
UpdatedAt = dateTime.AddTicks(-1 * dateTime.Ticks % 10000),
Distance = 5.95,
Rating = 90,
Created = dateTime.AddTicks(-1 * dateTime.Ticks % 10000)
};
try
{
CurrentTrip = await tripStore.CreateItemAsync(CurrentTrip);
await CreateTripPoints();
await CreatePois();
await UpdateUserProfile();
await UpdateTrip();
return;
}
catch (Exception)
{
throw new Exception($"Trip was not Recorded Successfully: \n Trip Name : {CurrentTrip.Name} \n Trip Guid: {CurrentTrip.Id}");
}
}
public async Task CreateTripPoints()
{
try
{
CurrentTripPoints = new List<TripPoint>();
DateTime dateTime = DateTime.UtcNow;
Vin v = new Vin() { String = string.Empty, Valid = false };
foreach (var tps in TripPointSourceInfo)
{
TripPoint _tripPoint = new TripPoint()
{
Id = Guid.NewGuid().ToString(),
TripId = new Guid(CurrentTrip.Id),
Latitude = Convert.ToDouble(tps.Lat),
Longitude = Convert.ToDouble(tps.Lon),
Speed = Convert.ToDouble(tps.Speed),
RecordedTimeStamp = Convert.ToDateTime(tps.Recordedtimestamp),
Sequence = Convert.ToInt32(tps.Sequence),
Rpm = Convert.ToDouble(tps.Enginerpm),
ShortTermFuelBank = Convert.ToDouble(tps.Shorttermfuelbank),
LongTermFuelBank = Convert.ToDouble(tps.Longtermfuelbank),
ThrottlePosition = Convert.ToDouble(tps.Throttleposition),
RelativeThrottlePosition = Convert.ToDouble(tps.Relativethrottleposition),
Runtime = Convert.ToDouble(tps.Runtime),
DistanceWithMalfunctionLight = Convert.ToDouble(tps.Distancewithmil),
EngineLoad = Convert.ToDouble(tps.Engineload),
//MassFlowRate = Convert.ToDouble(tps.Mafflowrate),
EngineFuelRate = Convert.ToDouble(tps.Enginefuelrate),
Vin = v,
CreatedAt = dateTime.AddTicks(-1 * dateTime.Ticks % 10000),
UpdatedAt = dateTime.AddTicks(-1 * dateTime.Ticks % 10000)
};
CurrentTripPoints.Add(_tripPoint);
}
//Update Time Stamps to current date and times before sending to IOT Hub
UpdateTripPointTimeStamps(CurrentTrip);
foreach (TripPoint tripPoint in CurrentTripPoints)
{
try
{
await tripPointStore.CreateItemAsync(tripPoint);
}
catch (Exception)
{
throw new Exception($"Could not update Trip Time Stamps from Samples at {DateTime.Now.ToString()}.");
}
//Console.WriteLine($"Processing Sequence No: {tripPoint.Sequence} on Thread : {Thread.CurrentThread.ManagedThreadId}");
}
//Parallel.ForEach(CurrentTripPoints, tripPoint =>
//{
// tripPointStore.CreateItemAsync(tripPoint);
// Console.WriteLine($"Processing Sequence No: {tripPoint.Sequence} on Thread : {Thread.CurrentThread.ManagedThreadId}");
//});
//Console.WriteLine("TripPoint Processing Completed");
}
catch (Exception ex)
{
Console.WriteLine($"Could not create/update Trip Points. For more detail see: {ex.Message}.");
}
}
private void UpdateTripPointTimeStamps(Trip trip)
{
try
{
//Sort Trip Points By Sequence Number
CurrentTripPoints = CurrentTripPoints.OrderBy(p => p.Sequence).ToList();
List<timeInfo> timeToAdd = new List<timeInfo>();
System.TimeSpan tDiff;
//Create a Variable to Track the Time Range as it Changes
System.DateTime runningTime = CurrentTrip.RecordedTimeStamp;
//Calculate the Difference in time between Each Sequence Item
for (int currentTripPoint = (CurrentTripPoints.Count - 1); currentTripPoint > -1; currentTripPoint--)
{
if (currentTripPoint > 0)
{
tDiff = CurrentTripPoints.ElementAt(currentTripPoint).RecordedTimeStamp
- CurrentTripPoints.ElementAt(currentTripPoint - 1).RecordedTimeStamp;
timeToAdd.Add(new timeInfo() { evtSeq = CurrentTripPoints.ElementAt(currentTripPoint).Sequence, tSpan = tDiff });
}
}
//Sort List in order to Add time to Trip Points
timeToAdd = timeToAdd.OrderBy(s => s.evtSeq).ToList();
//Update Trip Points
for (int currentTripPoint = 1, timeToAddCollIdx = 0; currentTripPoint < CurrentTripPoints.Count; currentTripPoint++, timeToAddCollIdx++)
{
runningTime = runningTime.Add(timeToAdd[timeToAddCollIdx].tSpan);
CurrentTripPoints.ElementAt(currentTripPoint).RecordedTimeStamp = runningTime;
}
// Update Initial Trip Point
CurrentTripPoints.ElementAt(0).RecordedTimeStamp = CurrentTrip.RecordedTimeStamp;
}
catch (Exception ex)
{
Console.WriteLine($"Could not update Trip Time Stamps from Samples. for more info see:{ex.Message}.");
}
}
public async Task CreatePois()
{
//CurrentPois = new List<Poi>();
foreach (var poi in TripPOIsource)
{
try
{
dateTime = DateTime.Now;
await poiStore.CreateItemAsync(new Poi
{
TripId = new Guid(CurrentTrip.Id),
Latitude = poi.Latitude,
Longitude = poi.Longitude,
PoiType = poi.Poitype,
Deleted = false,
Id = Guid.NewGuid(),
Timestamp = dateTime.AddTicks(-1 * dateTime.Ticks % 10000)
});
}
catch (Exception)
{
Console.WriteLine($"POI Creation Failure : {DateTime.Now.ToString()}");
}
}
CurrentTrip.HardStops = TripPOIsource.Where(p => p.Poitype == 2).Count();
CurrentTrip.HardAccelerations = TripPOIsource.Where(p => p.Poitype == 1).Count();
}
private async Task UpdateTrip()
{
//Get Current Trip and Update it After TripPoints Creation
CurrentTrip.Distance = 5.95;
CurrentTrip.IsComplete = true;
CurrentTrip.EndTimeStamp =
CurrentTripPoints.Last<TripPoint>().RecordedTimeStamp.AddTicks(-1 * CurrentTripPoints.Last<TripPoint>().RecordedTimeStamp.Ticks % 10000);
CurrentTrip.Rating = 90;
try
{
await tripStore.UpdateItemAsync(CurrentTrip);
}
catch (Exception)
{
Console.WriteLine($"Trip Statistics Update Failure : {DateTime.Now.ToString()}");
}
}
private async Task UpdateUserProfile()
{
//Get User
List<User> users = userStore.GetItemsAsync().Result;
User CurrentUser = users.Where(u => u.UserId == "Hacker 1").SingleOrDefault();
//Update USer
CurrentUser.TotalTrips++;
CurrentUser.TotalDistance = CurrentUser.TotalDistance + CurrentTrip.Distance;
CurrentUser.HardStops = CurrentUser.HardStops + CurrentTrip.HardStops;
CurrentUser.HardAccelerations = CurrentUser.HardAccelerations + CurrentTrip.HardAccelerations;
try
{
string json = CurrentUser.ToJson();
await userStore.UpdateItemAsync(CurrentUser);
}
catch (Exception)
{
Console.WriteLine($"User Profile Update Failure : {DateTime.Now.ToString()}");
}
}
}
}

View File

@ -0,0 +1,49 @@
using DeviceSim.DataObjects.Models;
using DeviceSim.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace DeviceSim.Controllers
{
public class BaseTripController
{
protected internal mydrivingDBContext Ctx { get; set; }
protected internal List<TripPointSource> TripPointSourceInfo { get; set; }
protected internal List<Poisource> TripPOIsource { get; set; }
public BaseTripController(DBConnectionInfo dBConnectionInfo)
{
Ctx = new mydrivingDBContext(dBConnectionInfo);
//Select Random Trip
GetSampleTrip();
//Default Constructor
}
private void GetSampleTrip()
{
Random r = new Random();
//Get Sample Trip Names
List<string> tripNames = Ctx.TripPointSource.Select(p => p.Name).Distinct().ToList();
//Choose Random Trip
var tName = tripNames.ElementAt(r.Next(0, tripNames.Count));
//Get Source TripPoints for Random Trip
TripPointSourceInfo = Ctx.TripPointSource.Where(p => p.Name == tName).ToList();
//Get Source POIs for Random Trip
TripPOIsource = Ctx.Poisource.Where(p => p.TripId == (TripPointSourceInfo.FirstOrDefault().Name)).ToList();
//Console.WriteLine($"Sample Trip Selected: {tName}");
}
}
}

View File

@ -0,0 +1,252 @@
using DeviceSim.DataObjects.Models;
using DeviceSim.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
namespace DeviceSim.Controllers
{
public class EFTripController : BaseTripController
{
#region Variables
private Trips CurrentTrip;
//private mydrivingDBContext ctx;
//private List<TripPointSource> tripInfo;
//private List<Poisource> tripPOIsource;
#endregion
#region Constructor
//Create Trips from Data in the Database
public EFTripController(DBConnectionInfo dBConnectionInfo):base(dBConnectionInfo)
{
}
#endregion
#region Public Methods
public async Task CreateTrip()
{
//1 - Initialize Trip
CurrentTrip = new Trips()
{
RecordedTimeStamp = DateTime.UtcNow,
Name = $"Trip {DateTime.Now}",
Id = Guid.NewGuid().ToString(),
UserId = "Hacker 1"
};
CreateTripPoints();
//TODO : Do proper Distance Calculation and Add a method to determine Rating
CurrentTrip.EndTimeStamp = CurrentTrip.TripPoints.Last<TripPoints>().RecordedTimeStamp;
CurrentTrip.Rating = 90;
//TODO : DO BingMaps Call to determine distance
CurrentTrip.Distance = 5.95;
//Get Trip POIs and Update Trip Summary Information
CreateTripPois();
//Update Driver Profile with Trip Data
UpdateUserProfile();
//Add trips to DB Instance
await Ctx.Trips.AddAsync(CurrentTrip);
}
public async Task<bool> SaveChangesAsync()
{
try
{
await Ctx.SaveChangesAsync();
Ctx.Dispose();
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region Private Methods
//private void GetSampleTrip()
//{
// Random r = new Random();
// //Get Sample Trip Names
// List<string> tripNames = ctx.TripPointSource.Select(p => p.Name).Distinct().ToList();
// //Choose Random Trip
// var tName = tripNames.ElementAt(r.Next(0, tripNames.Count));
// //Get Source TripPoints for Random Trip
// tripInfo = ctx.TripPointSource.Where(p => p.Name == tName).ToList();
// //Get Source POIs for Random Trip
// tripPOIsource = ctx.Poisource.Where(p => p.TripId == (tripInfo.FirstOrDefault().Name)).ToList();
// //Console.WriteLine($"Sample Trip Selected: {tName}");
//}
private void CreateTripPois()
{
List<Pois> poiList = Ctx.Pois.Where(p => p.TripId == CurrentTrip.Id).ToList<Pois>();
//Generate POIs from Source
foreach (var sPOI in TripPOIsource)
{
poiList.Add(new Pois
{
Id = Convert.ToString(Guid.NewGuid()), //New Guid
TripId = CurrentTrip.Id, //Current Trips Id
Latitude = sPOI.Latitude,
Longitude = sPOI.Longitude,
Poitype = sPOI.Poitype,
RecordedTimeStamp = DateTime.Now.ToLongTimeString()
});
}
//Add POI's to Database Context
Ctx.Pois.AddRangeAsync(poiList);
CurrentTrip.HardStops = poiList.Where(p => p.Poitype == 2).Count();
CurrentTrip.HardAccelerations = poiList.Where(p => p.Poitype == 1).Count();
}
private void UpdateUserProfile()
{
try
{
UserProfiles up = Ctx.UserProfiles
.Where(user => user.UserId == CurrentTrip.UserId)
.SingleOrDefault();
up.TotalTrips++;
up.TotalDistance += CurrentTrip.Distance;
up.HardStops += CurrentTrip.HardStops;
up.HardAccelerations += CurrentTrip.HardAccelerations;
}
catch (Exception ex)
{
Console.WriteLine($"Unable to Update User Profile. Ensure that the Trip UserProfile Matches with records in the database for Hacker 1, for more information see: {ex.Message}.");
}
}
private void CreateTripPoints()
{
try
{
foreach (var tps in TripPointSourceInfo)
{
TripPoints _tripPoint = new TripPoints()
{
TripId = CurrentTrip.Id,
Id = Guid.NewGuid().ToString(),
Latitude = Convert.ToDouble(tps.Lat),
Longitude = Convert.ToDouble(tps.Lon),
Speed = Convert.ToDouble(tps.Speed),
RecordedTimeStamp = Convert.ToDateTime(tps.Recordedtimestamp),
Sequence = Convert.ToInt32(tps.Sequence),
Rpm = Convert.ToDouble(tps.Enginerpm),
ShortTermFuelBank = Convert.ToDouble(tps.Shorttermfuelbank),
LongTermFuelBank = Convert.ToDouble(tps.Longtermfuelbank),
ThrottlePosition = Convert.ToDouble(tps.Throttleposition),
RelativeThrottlePosition = Convert.ToDouble(tps.Relativethrottleposition),
Runtime = Convert.ToDouble(tps.Runtime),
DistanceWithMalfunctionLight = Convert.ToDouble(tps.Distancewithmil),
EngineLoad = Convert.ToDouble(tps.Engineload),
MassFlowRate = Convert.ToDouble(tps.Mafflowrate),
EngineFuelRate = Convert.ToDouble(tps.Enginefuelrate)
};
CurrentTrip.TripPoints.Add(_tripPoint);
}
//Update Time Stamps to current date and times before sending to IOT Hub
UpdateTripPointTimeStamps(CurrentTrip);
}
catch (Exception ex)
{
Console.WriteLine($"Could not create/update Trip Points. For more detail see: {ex.Message}.");
}
}
private void UpdateTripPointTimeStamps(Trips trip)
{
try
{
//Sort Trip Points By Sequence Number
CurrentTrip.TripPoints = CurrentTrip.TripPoints.OrderBy(p => p.Sequence).ToList();
List<timeInfo> timeToAdd = new List<timeInfo>();
System.TimeSpan tDiff;
//Create a Variable to Track the Time Range as it Changes
System.DateTime runningTime = CurrentTrip.RecordedTimeStamp;
//Calculate the Difference in time between Each Sequence Item
for (int currentTripPoint = (CurrentTrip.TripPoints.Count - 1); currentTripPoint > -1; currentTripPoint--)
{
if (currentTripPoint > 0)
{
tDiff = CurrentTrip.TripPoints.ElementAt(currentTripPoint).RecordedTimeStamp
- CurrentTrip.TripPoints.ElementAt(currentTripPoint - 1).RecordedTimeStamp;
timeToAdd.Add(new timeInfo() { evtSeq = CurrentTrip.TripPoints.ElementAt(currentTripPoint).Sequence, tSpan = tDiff });
}
}
//Sort List in order to Add time to Trip Points
timeToAdd = timeToAdd.OrderBy(s => s.evtSeq).ToList();
//Update Trip Points
for (int currentTripPoint = 1, timeToAddCollIdx = 0; currentTripPoint < CurrentTrip.TripPoints.Count; currentTripPoint++, timeToAddCollIdx++)
{
runningTime = runningTime.Add(timeToAdd[timeToAddCollIdx].tSpan);
CurrentTrip.TripPoints.ElementAt(currentTripPoint).RecordedTimeStamp = runningTime;
}
// Update Initial Trip Point
CurrentTrip.TripPoints.ElementAt(0).RecordedTimeStamp = CurrentTrip.RecordedTimeStamp;
}
catch (Exception ex)
{
Console.WriteLine($"Could not update Trip Time Stamps from Samples. for more info see:{ex.Message}.");
}
}
#endregion
}
public struct timeInfo
{
public int evtSeq;
public TimeSpan tSpan;
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeviceSim.EDataObjects.Models
{
public partial class Trips
{
//public IList<TripPoints> Points { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using DeviceSim.Helpers;
namespace DeviceSim.DataObjects.Models
{
public partial class mydrivingDBContext : DbContext
{
private string _connectionString;
public string connString
{
get { return _connectionString; }
set { _connectionString = value; }
}
public mydrivingDBContext(DBConnectionInfo dBConnectionInfo) : base()
{
ConnectionStringHelper csHelper = new ConnectionStringHelper(dBConnectionInfo);
connString = csHelper.ConnectionString;
}
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class Devices
{
public string Id { get; set; }
public string Name { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
public string UserProfileId { get; set; }
public UserProfiles UserProfile { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class IothubDatas
{
public string Id { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class Pois
{
public string Id { get; set; }
public string TripId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Poitype { get; set; }
public string RecordedTimeStamp { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
public DateTime Timestamp { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class Poisource
{
public string Id { get; set; }
public string TripId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public int Poitype { get; set; }
public string RecordedTimeStamp { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class TripPointSource
{
public string Tripid { get; set; }
public string Userid { get; set; }
public string Name { get; set; }
public string Trippointid { get; set; }
public decimal Lat { get; set; }
public decimal Lon { get; set; }
public int Speed { get; set; }
public string Recordedtimestamp { get; set; }
public int Sequence { get; set; }
public int Enginerpm { get; set; }
public int Shorttermfuelbank { get; set; }
public int Longtermfuelbank { get; set; }
public int Throttleposition { get; set; }
public int Relativethrottleposition { get; set; }
public int Runtime { get; set; }
public int Distancewithmil { get; set; }
public int Engineload { get; set; }
public int Mafflowrate { get; set; }
public string Outsidetemperature { get; set; }
public int Enginefuelrate { get; set; }
public int? Field21 { get; set; }
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class TripPoints
{
public string Id { get; set; }
public string TripId { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Speed { get; set; }
public DateTime RecordedTimeStamp { get; set; }
public int Sequence { get; set; }
public double Rpm { get; set; }
public double ShortTermFuelBank { get; set; }
public double LongTermFuelBank { get; set; }
public double ThrottlePosition { get; set; }
public double RelativeThrottlePosition { get; set; }
public double Runtime { get; set; }
public double DistanceWithMalfunctionLight { get; set; }
public double EngineLoad { get; set; }
public double MassFlowRate { get; set; }
public double EngineFuelRate { get; set; }
public string Vin { get; set; }
public bool HasObddata { get; set; }
public bool HasSimulatedObddata { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
public Trips Trip { get; set; }
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class Trips
{
public Trips()
{
TripPoints = new HashSet<TripPoints>();
//Points = new List<TripPoints>();
}
public string Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
public DateTime RecordedTimeStamp { get; set; }
public DateTime EndTimeStamp { get; set; }
public int Rating { get; set; }
public bool IsComplete { get; set; }
public bool HasSimulatedObddata { get; set; }
public double AverageSpeed { get; set; }
public double FuelUsed { get; set; }
public long HardStops { get; set; }
public long HardAccelerations { get; set; }
public string MainPhotoUrl { get; set; }
public double Distance { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
public ICollection<TripPoints> TripPoints { get; set; }
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
namespace DeviceSim.DataObjects.Models
{
public partial class UserProfiles
{
public UserProfiles()
{
Devices = new HashSet<Devices>();
}
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public string ProfilePictureUri { get; set; }
public int Rating { get; set; }
public int Ranking { get; set; }
public double TotalDistance { get; set; }
public long TotalTrips { get; set; }
public long TotalTime { get; set; }
public long HardStops { get; set; }
public long HardAccelerations { get; set; }
public double FuelConsumption { get; set; }
public double MaxSpeed { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
public ICollection<Devices> Devices { get; set; }
}
}

View File

@ -0,0 +1,263 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace DeviceSim.DataObjects.Models
{
public partial class mydrivingDBContext : DbContext
{
public virtual DbSet<Devices> Devices { get; set; }
public virtual DbSet<IothubDatas> IothubDatas { get; set; }
public virtual DbSet<Pois> Pois { get; set; }
public virtual DbSet<TripPoints> TripPoints { get; set; }
public virtual DbSet<Trips> Trips { get; set; }
public virtual DbSet<UserProfiles> UserProfiles { get; set; }
public virtual DbSet<Poisource> Poisource { get; set; }
public virtual DbSet<TripPointSource> TripPointSource { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(connString);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Devices>(entity =>
{
entity.HasIndex(e => e.CreatedAt)
.HasName("IX_CreatedAt")
.ForSqlServerIsClustered();
entity.HasIndex(e => e.UserProfileId)
.HasName("IX_UserProfile_Id");
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.UserProfileId)
.HasColumnName("UserProfile_Id")
.HasMaxLength(128);
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
entity.HasOne(d => d.UserProfile)
.WithMany(p => p.Devices)
.HasForeignKey(d => d.UserProfileId)
.HasConstraintName("FK_dbo.Devices_dbo.UserProfiles_UserProfile_Id");
});
modelBuilder.Entity<IothubDatas>(entity =>
{
entity.ToTable("IOTHubDatas");
entity.HasIndex(e => e.CreatedAt)
.HasName("IX_CreatedAt")
.ForSqlServerIsClustered();
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
});
modelBuilder.Entity<Pois>(entity =>
{
entity.ToTable("POIs");
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.Poitype).HasColumnName("POIType");
entity.Property(e => e.RecordedTimeStamp).HasMaxLength(50);
entity.Property(e => e.Timestamp)
.HasColumnType("datetime")
.HasDefaultValueSql("('1900-01-01T00:00:00.000')");
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
});
modelBuilder.Entity<Poisource>(entity =>
{
entity.ToTable("POISource");
entity.Property(e => e.Id)
.HasMaxLength(128)
.ValueGeneratedNever();
entity.Property(e => e.Poitype).HasColumnName("POIType");
entity.Property(e => e.RecordedTimeStamp).HasMaxLength(50);
});
modelBuilder.Entity<TripPoints>(entity =>
{
entity.HasIndex(e => e.CreatedAt)
.HasName("IX_CreatedAt")
.ForSqlServerIsClustered();
entity.HasIndex(e => e.TripId)
.HasName("IX_TripId");
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.HasObddata).HasColumnName("HasOBDData");
entity.Property(e => e.HasSimulatedObddata).HasColumnName("HasSimulatedOBDData");
entity.Property(e => e.RecordedTimeStamp).HasColumnType("datetime");
entity.Property(e => e.Rpm).HasColumnName("RPM");
entity.Property(e => e.TripId).HasMaxLength(128);
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
entity.Property(e => e.Vin).HasColumnName("VIN");
entity.HasOne(d => d.Trip)
.WithMany(p => p.TripPoints)
.HasForeignKey(d => d.TripId)
.HasConstraintName("FK_dbo.TripPoints_dbo.Trips_TripId");
});
modelBuilder.Entity<TripPointSource>(entity =>
{
entity.HasKey(e => e.Trippointid);
entity.Property(e => e.Trippointid)
.HasColumnName("trippointid")
.HasMaxLength(36)
.IsUnicode(false)
.ValueGeneratedNever();
entity.Property(e => e.Distancewithmil).HasColumnName("distancewithmil");
entity.Property(e => e.Enginefuelrate).HasColumnName("enginefuelrate");
entity.Property(e => e.Engineload).HasColumnName("engineload");
entity.Property(e => e.Enginerpm).HasColumnName("enginerpm");
entity.Property(e => e.Field21).HasColumnName("FIELD21");
entity.Property(e => e.Lat)
.HasColumnName("lat")
.HasColumnType("numeric(18, 15)");
entity.Property(e => e.Lon)
.HasColumnName("lon")
.HasColumnType("numeric(19, 14)");
entity.Property(e => e.Longtermfuelbank).HasColumnName("longtermfuelbank");
entity.Property(e => e.Mafflowrate).HasColumnName("mafflowrate");
entity.Property(e => e.Name)
.HasColumnName("name")
.HasMaxLength(30)
.IsUnicode(false);
entity.Property(e => e.Outsidetemperature)
.HasColumnName("outsidetemperature")
.HasMaxLength(30)
.IsUnicode(false);
entity.Property(e => e.Recordedtimestamp)
.IsRequired()
.HasColumnName("recordedtimestamp")
.HasMaxLength(28)
.IsUnicode(false);
entity.Property(e => e.Relativethrottleposition).HasColumnName("relativethrottleposition");
entity.Property(e => e.Runtime).HasColumnName("runtime");
entity.Property(e => e.Sequence).HasColumnName("sequence");
entity.Property(e => e.Shorttermfuelbank).HasColumnName("shorttermfuelbank");
entity.Property(e => e.Speed).HasColumnName("speed");
entity.Property(e => e.Throttleposition).HasColumnName("throttleposition");
entity.Property(e => e.Tripid)
.IsRequired()
.HasColumnName("tripid")
.HasMaxLength(36)
.IsUnicode(false);
entity.Property(e => e.Userid)
.IsRequired()
.HasColumnName("userid")
.HasMaxLength(33)
.IsUnicode(false);
});
modelBuilder.Entity<Trips>(entity =>
{
entity.HasIndex(e => e.CreatedAt)
.HasName("IX_CreatedAt")
.ForSqlServerIsClustered();
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.EndTimeStamp).HasColumnType("datetime");
entity.Property(e => e.HasSimulatedObddata).HasColumnName("HasSimulatedOBDData");
entity.Property(e => e.RecordedTimeStamp).HasColumnType("datetime");
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
});
modelBuilder.Entity<UserProfiles>(entity =>
{
entity.HasIndex(e => e.CreatedAt)
.HasName("IX_CreatedAt")
.ForSqlServerIsClustered();
entity.Property(e => e.Id)
.HasMaxLength(128)
.HasDefaultValueSql("(newid())");
entity.Property(e => e.CreatedAt).HasDefaultValueSql("(sysutcdatetime())");
entity.Property(e => e.Version)
.IsRequired()
.IsRowVersion();
});
}
}
}

View File

@ -0,0 +1,43 @@
namespace DeviceSim.EF.SQL.DataObjects.Models
{
using System;
//using System.Data.Entity;
//using System.Data.Entity.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
public partial class mydrivingDBEntities : DbContext
{
private string connectionString = "Server=tcp:mydrivingdbserver-or76fh5yqpqg2.database.windows.net,1433;Initial Catalog=mydrivingDB;Persist Security Info=False;User ID=YourUserName;Password=OpenHack-85439610;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
//public mydrivingDBEntities()
// : base("name=mydrivingDBEntities")
//{
//}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(connectionString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//throw new NotImplementedException("Change this Model");
}
//protected override void OnModelCreating(DbModelBuilder modelBuilder)
//{
// throw new UnintentionalCodeFirstException();
//}
public virtual DbSet<Device> Devices { get; set; }
public virtual DbSet<factMLOutputData> factMLOutputDatas { get; set; }
public virtual DbSet<IOTHubData> IOTHubDatas { get; set; }
public virtual DbSet<POIs> POIs { get; set; }
public virtual DbSet<TripPoint> TripPoints { get; set; }
public virtual DbSet<Trips> Trips { get; set; }
public virtual DbSet<UserProfile> UserProfiles { get; set; }
}
}

View File

@ -0,0 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Remove="DataObjects\Model\**" />
<Compile Remove="Scripts\Database\**" />
<EmbeddedResource Remove="DataObjects\Model\**" />
<EmbeddedResource Remove="Scripts\Database\**" />
<None Remove="DataObjects\Model\**" />
<None Remove="Scripts\Database\**" />
</ItemGroup>
<ItemGroup>
<Compile Remove="DataObjects\MyDriving.Context.cs" />
<Compile Remove="Controllers\FileService.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Interfaces\" />
<Folder Include="helm\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Devices" Version="1.6.0" />
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.7.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Simulator.DataStore.API\Simulator.DataStore.API.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace DeviceSim.Helpers
{
public class ConnectionStringHelper
{
private string connectionString;
public string ConnectionString
{
get => connectionString;
private set => connectionString = value;
}
private void ConnectionStringBuilder(DBConnectionInfo dBConnectionInfo)
{
ConnectionString = $"Server=tcp:{dBConnectionInfo.DBServer},1433;Initial Catalog={dBConnectionInfo.DBCatalog};Persist Security Info=False;User ID={dBConnectionInfo.DBUserName};Password={dBConnectionInfo.DBPassword};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=60";
}
public ConnectionStringHelper(DBConnectionInfo dBConnectionInfo)
{
ConnectionStringBuilder(dBConnectionInfo);
}
}
public struct DBConnectionInfo
{
public string DBServer;
public string DBCatalog;
public string DBUserName;
public string DBPassword;
}
}

View File

@ -0,0 +1,51 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System.Reflection;
namespace DeviceSim.Model
{
public class CustomContractResolver : DefaultContractResolver
{
public CustomContractResolver()
{
PropertyMappings = new Dictionary<string, string>
{
["Longitude"] = "Lon",
["Latitude"] = "Lat",
["ShortTermFuelBank"] = "ShortTermFuelBank1",
["LongTermFuelBank"] = "LongTermFuelBank1",
["MassFlowRate"] = "MAFFlowRate",
["RPM"] = "EngineRPM",
["Id"] = "TripPointId",
["DistanceWithMalfunctionLight"] = "DistancewithMIL",
["HasSimulatedOBDData"] = "IsSimulated",
};
IgnoreProperties = new List<string> { "HasOBDData" };
}
private Dictionary<string, string> PropertyMappings { get; }
private List<string> IgnoreProperties { get; }
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName;
var resolved = PropertyMappings.TryGetValue(propertyName, out resolvedName);
return resolved ? resolvedName : base.ResolvePropertyName(propertyName);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (IgnoreProperties.Contains(property.PropertyName))
{
property.ShouldSerialize = p => false;
}
return property;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
using DeviceSim.Interfaces;
namespace DeviceSim.Helpers
{
public class Logger : ILogger
{
public void Report(Exception exception, LogCategory category)
{
throw new NotImplementedException();
}
public void WriteMessage( LogLevel level, string message)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace DeviceSim.Interfaces
{
public interface ILogger
{
void WriteMessage(LogLevel level, string message);
void Report(Exception exception, LogCategory category);
}
public enum LogLevel
{
CRITICAL = 0,
ERROR = 1,
WARNING = 2,
INFO = 3,
VERBOSE = 4
}
public enum LogCategory
{
CONFIGERROR = 0,
SQLERROR = 1 ,
APIERROR =2
}
}

View File

@ -0,0 +1,106 @@
using DeviceSim.Controllers;
using DeviceSim.Helpers;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceSim
{
internal class Program
{
#region Variables
private static DBConnectionInfo dBConnectionInfo;
public static int WaitTime { get; private set; }
public static string TeamName { get; private set; }
public static bool UseApi { get; private set; }
public static string UserApiEndPoint { get; private set; }
public static string PoiApiEndPoint { get; private set; }
public static string TripsApiEndPoint { get; private set; }
#endregion Variables
private static void Main(string[] args)
{
InitializeApp();
UseApi = true;
Console.WriteLine($"***** {TeamName}-Driving Simulator *****");
Console.WriteLine($"Currently Using API Routes : {UseApi.ToString()}");
Console.WriteLine($"*Starting Simulator - A new trip will be created every {WaitTime / 1000} seconds *");
while (true)
{
try
{
CreateTripAsync().Wait();
Thread.Sleep(WaitTime);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private static async Task CreateTripAsync()
{
try
{
Console.WriteLine($"Starting Trip Creation : {DateTime.Now}. ");
await CreateTrip();
Console.WriteLine($"Trip Completed at : {DateTime.Now}. ");
}
catch (Exception)
{
throw;
}
}
private static void InitializeApp()
{
IConfiguration funcConfiguration;
var builder = new ConfigurationBuilder().AddEnvironmentVariables();
funcConfiguration = builder.Build();
//Environmental Variables - Pass to Container
//Database Connection Information
dBConnectionInfo.DBServer = funcConfiguration.GetSection("SQL_SERVER").Value;
dBConnectionInfo.DBUserName = funcConfiguration.GetSection("SQL_USER").Value;
dBConnectionInfo.DBPassword = funcConfiguration.GetSection("SQL_PASSWORD").Value;
dBConnectionInfo.DBCatalog = "mydrivingDB";
//Api Connection Information
UseApi = Convert.ToBoolean(funcConfiguration.GetSection("USE_API").Value);
UserApiEndPoint = funcConfiguration.GetSection("USER_ROOT_URL").Value;
PoiApiEndPoint = funcConfiguration.GetSection("POI_ROOT_URL").Value;
TripsApiEndPoint = funcConfiguration.GetSection("TRIPS_ROOT_URL").Value;
//Execution Information
WaitTime = Convert.ToInt32(funcConfiguration.GetSection("TRIP_FREQUENCY").Value ?? ("180000"));
TeamName = funcConfiguration.GetSection("TEAM_NAME").Value ?? ("TEAM 01");
}
private static async Task CreateTrip()
{
try
{
if (UseApi)
{
ApiTripController CurrentTrip = new ApiTripController(dBConnectionInfo, UserApiEndPoint, PoiApiEndPoint, TripsApiEndPoint);
await CurrentTrip.CreateTrip();
}
else
{
EFTripController CurrentTrip = new EFTripController(dBConnectionInfo);
await CurrentTrip.CreateTrip();
await CurrentTrip.SaveChangesAsync();
}
}
catch (Exception)
{
throw;//do Nothing just continue throwing
}
}
}
}

File diff suppressed because it is too large Load Diff