Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex authored and Alex committed Nov 26, 2019
1 parent d0c718c commit 08ca5e5
Show file tree
Hide file tree
Showing 68 changed files with 1,539 additions and 4,884 deletions.
415 changes: 415 additions & 0 deletions CodeMapModel.dgml

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions UDP_Test/DB/NBIoTCommand.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;

namespace UDP_Test.DB
{
public class NBIoTCommand
{
public int Id { get; set; }
public int UserId { get; set; }
public byte IdDev { get; set; }
[Index]
public int IdDev { get; set; }
public byte[] Data { get; set; }
public string DataShema { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
}
11 changes: 9 additions & 2 deletions UDP_Test/DB/NBIoTData.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations.Schema;

namespace UDP_Test.DB
{
public class NBIoTData
{
public int Id { get; set; }
[Index]
public int UserId { get; set; }
[Index]
public short IdMSG { get; set; }
public byte IdDev { get; set; }
[Index]
public int IdDev { get; set; }
[Index]
public long IMEI { get; set; }
[Index]
public long IMSI { get; set; }
[Index]
public DateTime DateTime { get; set; }
public long address { get; set; }
public int port { get; set; }
public byte[] Data { get; set; }
public DateTime DateTime { get; set; }
}
}
13 changes: 12 additions & 1 deletion UDP_Test/DB/User.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,26 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;

namespace UDP_Test.DB
{

public class User
{
public int Id { get; set; }
public string Name { get; set; }
[Index]
public Guid KeyAPI { get; set; }
public string DataShema { get; set; }
[Index]
public Guid ReadKeyAPI { get; set; }

public ICollection<NBIoTCommand> NBIoTCommands { get; set; }
public User()
{
NBIoTCommands = new List<NBIoTCommand>();
}

}

}
46 changes: 15 additions & 31 deletions UDP_Test/DataPackets/IoT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,57 +8,41 @@
namespace UDP_Test.DataPackets
{

public unsafe abstract class IoT
public abstract class IoT
{
public bool DataOk = false;
public Guid KeyAPI;
public Guid KeyAPI; //16b
public ushort IdMSG; //2b
public byte IdDev; //1b
public uint IdDev; //4b

public IoT(byte[] packet)
{


byte[] KeyAPIByte = new byte[16]; //GUID=16 Bytes
for (int i = 0; i < 16; i++)
{
KeyAPIByte[i] = packet[i];
}
KeyAPI = new Guid(KeyAPIByte);

byte* pp = stackalloc byte[3];
for (int i = 16; i < 19; i++)
{
pp[i - 16] = packet[i];
}
IdMSG = *(ushort*)(pp); //
IdDev = *(pp + 2); //

var StrGUID = BitConverter.ToString(packet, 0, 16);
KeyAPI = new Guid(StrGUID.Replace("-", ""));
IdMSG = BitConverter.ToUInt16(packet, 16);
IdDev = BitConverter.ToUInt32(packet, 18);
}

public override string ToString()
{
return String.Format("KeyAPI:{0}; IdMSG:{1}; IdDev:{2}", KeyAPI.ToString(), IdMSG, IdDev);
}
}
public unsafe class NBIoT : IoT
public class NBIoT : IoT
{
public ulong IMEI;
public ulong IMSI;
public UInt16 TimeOut;
public byte[] Data;
public NBIoT(byte[] packet) : base(packet)
{
if (packet.Length > 30)
{
byte* pp = stackalloc byte[16];
for (int i = 19; i < 35; i++)
{
pp[i - 19] = packet[i];
}
IMEI = *(ulong*)(pp);
IMSI = *(ulong*)(pp + 8);
Data = new byte[packet.Length - 35];
Array.Copy(packet, 35, Data, 0, packet.Length - 35);
{
IMEI = BitConverter.ToUInt64(packet, 22);
IMSI = BitConverter.ToUInt64(packet, 30);
TimeOut = BitConverter.ToUInt16(packet, 38);
Data = new byte[packet.Length - 40]; //Данные пользователя
Array.Copy(packet, 40, Data, 0, Data.Length);
DataOk = true;
}
}
Expand Down
108 changes: 52 additions & 56 deletions UDP_Test/UDP/UDPSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class UDPSystem
private UdpClient ServerIn, ServerCommand;

private Dictionary<Guid, User> UsersCashe = new Dictionary<Guid, User>();
private Dictionary<Tuple<int, byte>, bool> CommandBufer;
private Dictionary<Tuple<int, int>, bool> CommandBufer;

private ConcurrentQueue<NBIoTData> QueueNBIoTData = new ConcurrentQueue<NBIoTData>();
public int ServerPort;
Expand All @@ -33,12 +33,12 @@ public UDPSystem(int PORT, int CommandPORT)
Console.WriteLine("ServerPort: {0} CommandServerPort: {1}", PORT, CommandPORT);
ServerPort = PORT;
CommandServerPort = CommandPORT;
CommandBufer = new Dictionary<Tuple<int, byte>, bool>();
CommandBufer = new Dictionary<Tuple<int, int>, bool>();
}

private void ToUserAsync(IPEndPoint IpEP, byte[] data)
{
ConnectionCount++;
ConnectionCount++; //Еще один девайс
var ParsePacket = new DataPackets.NBIoT(data);
if (ParsePacket.DataOk)
{
Expand Down Expand Up @@ -74,7 +74,7 @@ private void ToUserAsync(IPEndPoint IpEP, byte[] data)
UserId = user.Id,
address = IpEP.Address.Address,
port = IpEP.Port,
IdDev = ParsePacket.IdDev,
IdDev = unchecked((int)ParsePacket.IdDev),
IdMSG = unchecked((short)ParsePacket.IdMSG),
IMEI = unchecked((long)ParsePacket.IMEI),
IMSI = unchecked((long)ParsePacket.IMSI),
Expand All @@ -85,37 +85,33 @@ private void ToUserAsync(IPEndPoint IpEP, byte[] data)
var IdMSGBytes = BitConverter.GetBytes(ParsePacket.IdMSG);

Console.SetCursorPosition(0, 4);
Console.Write("User IP {0}:{1} IMSI:{2} MSG:{3} ", IpEP.Address, IpEP.Port, ParsePacket.IMSI, ParsePacket.IdMSG);
Console.Write("User IP {0}:{1} IMSI:{2} MSG:{3} TimeOut:{4} ", IpEP.Address, IpEP.Port, ParsePacket.IMSI, ParsePacket.IdMSG, ParsePacket.TimeOut);

byte[] dgram = new byte[] { 0x4D, 0x53, 0x47, IdMSGBytes[0], IdMSGBytes[1] }; //Ответ MSG+IdMSG

var timeStart = DateTime.Now;
bool newCommand = false;
bool startCommand = true;
while ((DateTime.Now - timeStart).Minutes < 1)
while ((DateTime.Now - timeStart).TotalSeconds < ParsePacket.TimeOut) //Устройство задает время ожидания команды
{
var command = GetNewCommand(ParsePacket.IdDev, user.Id, startCommand);
var command = GetNewCommand(unchecked((int)ParsePacket.IdDev), user.Id, startCommand);
startCommand = false;
if (command != null)
{
if ((ParsePacket.Data[ParsePacket.Data.Length - 1] != command[command.Length - 1]) ||
(ParsePacket.Data[ParsePacket.Data.Length - 2] != command[command.Length - 2]))
//Сравним старые и новые команды
if (TestBytes(command, ParsePacket.Data)) // Команды в конце пакета. Если была новая команда - работаем
{
var dgram_command = dgram.Concat(command).ToArray();
var dgram_command = dgram.Concat(command).ToArray(); //Объеденим ответ (MSG+IdMSG) и команды
ServerIn.Send(dgram_command, dgram_command.Length, IpEP); //отправим ответ и команду
Console.SetCursorPosition(0, 6);
Console.Write("Send Commands ");
newCommand = true;
break;
}
else
{

}
}
Thread.Sleep(1000);
Thread.Sleep(1000); // Спим 1 сек.
Console.SetCursorPosition(0, 6);
Console.Write("Сommand waiting {0} sec ", (DateTime.Now - timeStart).Seconds);
Console.Write("Сommand waiting {0} sec ", (DateTime.Now - timeStart).TotalSeconds);
}
if (!newCommand)
{
Expand All @@ -127,64 +123,65 @@ private void ToUserAsync(IPEndPoint IpEP, byte[] data)
Console.Write("Connections: {0} ", ConnectionCount);
}
}
ConnectionCount--;
ConnectionCount--; // Одним девайсом меньше
}

private byte[] GetNewCommand(byte IdDev, int userId, bool startCommand)
/// <summary>
/// Команды соответствуют структуре данных от устройства. Сверка идет с конца
/// </summary>
/// <param name="newData">Данные для сверки. Длина newData не более oldData</param>
/// <param name="oldData">То с чем сверяем</param>
/// <returns>Если есть отличия - true</returns>
private static bool TestBytes(byte[] newData, byte[] oldData)
{
for (int i = 1; i <= newData.Length; i++)
{
if (oldData[oldData.Length - i] != newData[newData.Length - i])
{
return true;
}
}
return false;
}

private byte[] GetNewCommand(int IdDev, int userId, bool startCommand)
{
byte[] NewCommand = null;
var UserDevId = new Tuple<int, byte>(userId, IdDev);
var UserDevId = new Tuple<int, int>(userId, IdDev);
if (!CommandBufer.ContainsKey(UserDevId))
{
using (var db = new UserContext())
{
var sel = db.NBIoTCommands
.AsNoTracking()
.Where(p => (p.UserId == userId && p.IdDev == IdDev))
.ToArray();
if (sel.Count()>0) NewCommand = sel[0].Data;

lock(lockerCom)
var sel = db.NBIoTCommands.AsNoTracking()
.FirstOrDefault(p => (p.UserId == userId && p.IdDev == IdDev));
if(sel != null)
{
CommandBufer.Add(UserDevId, false);
NewCommand = sel.Data;
lock(lockerCom)
{
CommandBufer.Add(UserDevId, false);
}
}
}
}
else if (CommandBufer[UserDevId] || startCommand) // Есть новая команда или первый запрос
{
using (var db = new UserContext())
{
var sel = db.NBIoTCommands
.AsNoTracking()
.Where(p => (p.UserId == userId && p.IdDev == IdDev))
.ToArray();
if (sel.Count() > 0) NewCommand = sel[0].Data;

lock (lockerCom)
var sel = db.NBIoTCommands.AsNoTracking()
.FirstOrDefault(p => (p.UserId == userId && p.IdDev == IdDev));
if(sel != null)
{
CommandBufer[UserDevId] = false;
NewCommand = sel.Data;
lock(lockerCom)
{
CommandBufer[UserDevId] = false;
}
}
}
}
return NewCommand;
}

private static void SaveIoTData(UserContext db, NBIoTData iotData)
{
var par = new Npgsql.NpgsqlParameter[] {

new Npgsql.NpgsqlParameter("@p1", iotData.UserId) ,
new Npgsql.NpgsqlParameter("@p2", iotData.IdMSG),
new Npgsql.NpgsqlParameter("@p3", iotData.IdDev),
new Npgsql.NpgsqlParameter("@p4", iotData.IMEI),
new Npgsql.NpgsqlParameter("@p5", iotData.IMSI),
new Npgsql.NpgsqlParameter("@p6", iotData.address),
new Npgsql.NpgsqlParameter("@p7", iotData.port),
new Npgsql.NpgsqlParameter("@p8", iotData.Data)
};
db.Database.ExecuteSqlCommand("INSERT INTO dbo.\"NBIoTDatas\"( \"UserId\", \"IdMSG\", \"IdDev\", \"IMEI\", \"IMSI\", address, port, \"Data\") VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)", par);
}

}
public void Run()
{
//QueueNBIoTData. Очередь сообщений
Expand All @@ -194,7 +191,6 @@ public void Run()
//Сервер команд
Task taskCommanData = new Task(() => CommanDataServer());
taskCommanData.Start();

while (true)
{
try
Expand All @@ -220,8 +216,8 @@ private void CommanDataServer()
IPEndPoint IpEP = null;
byte[] data = ServerCommand.Receive(ref IpEP); // получаем данные команд
var userId = BitConverter.ToInt32(data, 0);
var IdDev = data[4];
var UserDevId = new Tuple<int, byte>(userId, IdDev);
var IdDev = BitConverter.ToInt32(data, 4);
var UserDevId = new Tuple<int, int>(userId, IdDev);
Console.SetCursorPosition(0, 8);
Console.Write("Command to {0}:{1} ", userId, IdDev);
if (!CommandBufer.ContainsKey(UserDevId))
Expand Down
Loading

0 comments on commit 08ca5e5

Please sign in to comment.