초기 커밋.

This commit is contained in:
2026-02-11 10:10:43 +09:00
parent a1407fe1c0
commit 0956e4d38a
142 changed files with 72021 additions and 0 deletions

View File

@@ -0,0 +1,899 @@
using System;
using LFP_Manager.DataStructure;
using LFP_Manager.Utils;
namespace LFP_Manager.Function
{
// 1. Define the data type
public struct PACKET_HEADER
{
public byte Index; // 3
public byte R; // 1
public byte DP; // 1
public byte PF; // 8
public byte PS; // 8
public byte SA; // 8
}
class csCanCommFunction
{
public static void CanRxProcess(ref CommConfig aConfig, int sId, UInt32 ExID, byte[] data, ref DeviceSystemData rSystemData, DateTime rTime)
{
PACKET_HEADER PacketHeader = CovertPtoH(ExID);
if (PacketHeader.SA == (200 + sId))
{
if (data.Length > 0)
{
int REF = 0;
rSystemData.CommFail = false;
rSystemData.ShelfCommFail = false;
rSystemData.LastRxTime = rTime;
switch (PacketHeader.PF)
{
case 201: // Device heartbeat
rSystemData.heatbeat = (UInt32)((data[0] << 24)
| (data[1] << 16)
| (data[2] << 8)
| (data[3] << 0));
rSystemData.OneBuffTime = (data[4] << 8) | data[5];
rSystemData.AllBuffTime = (data[6] << 8) | data[7];
break;
case 1: // Send data 0x01
break;
case 11: // Module Voltage, Current
rSystemData.ValueData.voltageOfPack = (short)((data[0] * 256) + data[1]);
//rSystemData.ValueData.rSOC = (short)(data[2]);
rSystemData.CalibriationData.ForcedBalancing.AutoB = (data[3] == 0x01) ? true : false;
rSystemData.StatusData.warning = (short)((data[4] << 8) | data[5]);
rSystemData.StatusData.protect = (short)((data[6] << 8) | data[7]);
break;
case 12: // Status code 2, Software version
rSystemData.StatusData.batteryStatusA = (short)((data[0] << 8) | data[1]);
rSystemData.StatusData.status = (short)(data[2]); // Op Status
rSystemData.ValueData.fw_ver[0] = (byte)((((data[6] * 256) + data[7]) >> 12) & 0xf);
rSystemData.ValueData.fw_ver[1] = (byte)((((data[6] * 256) + data[7]) >> 8) & 0xf);
rSystemData.ValueData.fw_ver[2] = (byte)((((data[6] * 256) + data[7]) >> 4) & 0xf);
rSystemData.ValueData.fw_ver[3] = (byte)((((data[6] * 256) + data[7]) >> 0) & 0xf);
break;
case 13: // Status code 3
rSystemData.StatusData.batteryStatusB = (short)((data[0] << 8) | data[1]); // Battery Status 1
rSystemData.StatusData.protect1 = (short)((data[2] << 8) | data[3]); // Protection 1
break;
case 15: // Balancing Status - Active Balancing
rSystemData.StatusData.BalanceEnable = (uint)((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3] << 0));
rSystemData.StatusData.BalanceMode = (uint)((data[4] << 24) | (data[5] << 16) | (data[6] << 8) | (data[7] << 0));
break;
case 31: // Cell Temperature #1 ~ #4
case 32: // Cell Temperature #5 ~ #8
case 33: // Cell Temperature #9 ~ #12
case 34: // Cell Temperature #13 ~ #16
REF = PacketHeader.PF - 31;
for (int i = 0; i < 4; i++)
{
if (((REF * 4) + i) < rSystemData.tempQty)
rSystemData.ValueData.CellTemperature[(REF * 4) + i] = (short)(((data[(i * 2)] * 256) + data[(i * 2) + 1]) - 800);
}
MakeMaxAvgMinTemperature(ref rSystemData);
break;
case 41:
rSystemData.ValueData.rSOC = (short)((data[0] << 8) | data[1]);
break;
case 191: // Cell Voltage 1 ~ 4
case 192: // Cell Voltage 5 ~ 8
case 193: // Cell Voltage 9 ~ 12
case 194: // Cell Voltage 13 ~ 16
case 195: // Cell Voltage 17 ~ 20
case 196: // Cell Voltage 21 ~ 24
case 197: // Cell Voltage 25 ~ 28
case 198: // Cell Voltage 29 ~ 32
case 199: // Cell Voltage 33 ~ 36
REF = PacketHeader.PF - 191;
for (int i = 0; i < 4; i++)
{
if (((REF * 4) + i) < rSystemData.cellQty)
rSystemData.ValueData.CellVoltage[(REF * 4) + i] = (ushort)((data[(i * 2)] * 256) + data[(i * 2) + 1]);
}
rSystemData = MakeMaxAvgMinCellVoltage(rSystemData);
break;
case 111: // Cell Balancing Status
switch (aConfig.TargetModelIndex)
{
case 0: // PR-57150
rSystemData.StatusData.cellBalanceValue = (ushort)((data[0] << 8) + data[1]);
rSystemData.StatusData.cellBalanceEndGap = (short)(data[2]);
rSystemData.StatusData.cellBalanceFlag = (short)(data[3]);
rSystemData.StatusData.cellBallanceStatusLv = (uint)((data[4] << 0) | (data[5] << 8) | (data[6] << 16));
rSystemData.StatusData.cellBalanceInterval = (short)(data[7]);
break;
case 3: // PR-102150
rSystemData.StatusData.cellBalanceValue = (ushort)((data[0] << 8) + data[1]);
rSystemData.StatusData.cellBalanceEndGap = (short)(data[2] & 0x7F);
rSystemData.StatusData.cellBalanceFlag = (short)((data[2] >> 7) & 0x01);
rSystemData.StatusData.cellBalanceInterval = (short)(data[3]);
rSystemData.StatusData.cellBallanceStatusLv = (uint)((data[4] << 0) | (data[5] << 8)
| (data[6] << 16) | (data[7] << 24));
break;
case 4: // PR-115300
rSystemData.StatusData.cellBalanceValue = (ushort)((data[0] << 8) + data[1]);
rSystemData.StatusData.cellBalanceEndGap = (short)(data[2] & 0x7F);
rSystemData.StatusData.cellBalanceFlag = (short)((data[2] >> 7) & 0x01);
rSystemData.StatusData.cellBalanceInterval = (short)(data[3]);
rSystemData.StatusData.cellBallanceStatusLv = (uint)((data[4] << 0) | (data[5] << 8)
| (data[6] << 16) | (data[7] << 24));
break;
case 5: // PR-67150
rSystemData.StatusData.cellBalanceValue = (ushort)((data[0] << 8) + data[1]);
rSystemData.StatusData.cellBalanceEndGap = (short)(data[2] * 10);
rSystemData.StatusData.cellBalanceFlag = (short)((data[3] >> 7) & 0x01);
rSystemData.StatusData.cellBallanceStatusLv = (uint)((data[4] << 0) | (data[5] << 8) | (data[6] << 16));
rSystemData.StatusData.cellBalanceInterval = (short)(data[7]);
break;
default:
rSystemData.StatusData.cellBalanceValue = (ushort)((data[0] << 8) + data[1]);
rSystemData.StatusData.cellBalanceFlag = (short)((data[2] >> 7) & 0x01);
rSystemData.StatusData.cellBalanceEndGap = (short)((data[2] & 0x7F) * 10);
rSystemData.StatusData.cellBalanceInterval = (short)(data[3]);
rSystemData.StatusData.cellBallanceStatusLv = (uint)((data[4] << 0) | (data[5] << 8) | (data[6] << 16) | (data[7] << 24));
break;
}
break;
case 112: // Cell Balancing Status
rSystemData.StatusData.cellBallanceStatusHv = (uint)((data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24));
break;
case 51: // Cell Voltage Parameter
rSystemData.ParamData.CellUnderVoltageWarning = (short)((data[0] * 256) + data[1]);
rSystemData.ParamData.CellUnderVoltageTrip = (short)((data[2] * 256) + data[3]);
rSystemData.ParamData.CellOverVoltageWarning = (short)((data[4] * 256) + data[5]);
rSystemData.ParamData.CellOverVoltageTrip = (short)((data[6] * 256) + data[7]);
break;
case 71: // System Voltage Parameter
rSystemData.ParamData.SysUnderVoltageWarning = (short)((data[0] * 256) + data[1]);
rSystemData.ParamData.SysUnderVoltageTrip = (short)((data[2] * 256) + data[3]);
rSystemData.ParamData.SysOverVoltageWarning = (short)((data[4] * 256) + data[5]);
rSystemData.ParamData.SysOverVoltageTrip = (short)((data[6] * 256) + data[7]);
break;
case 61: // Temperature Parameter
rSystemData.ParamData.ChaLowTempWarning = (short)(data[0] - 80);
rSystemData.ParamData.ChaLowTempTrip = (short)(data[1] - 80);
rSystemData.ParamData.ChaHighTempWarning = (short)(data[2] - 80);
rSystemData.ParamData.ChaHighTempTrip = (short)(data[3] - 80);
rSystemData.ParamData.DchLowTempWarning = (short)(data[4] - 80);
rSystemData.ParamData.DchLowTempTrip = (short)(data[5] - 80);
rSystemData.ParamData.DchHighTempWarning = (short)(data[6] - 80);
rSystemData.ParamData.DchHighTempTrip = (short)(data[7] - 80);
break;
case 141: // Soc Parameter, System Voltage Calibration K, B
rSystemData.ParamData.LowSocWarning = (short)(data[0]);
rSystemData.ParamData.LowSocRelease = (short)(data[1]);
rSystemData.CalibriationData.SystemVoltage.Calibration_K = (short)((data[4] * 256) + data[5]);
rSystemData.CalibriationData.SystemVoltage.Calibration_B = (short)((data[6] * 256) + data[7]);
break;
case 151: // Battery Option Parameter - Cell Voltage Offset
rSystemData.CalibriationData.CellVoltge.CvOffsetLow = (short)((data[0] << 8) | data[1]);
rSystemData.CalibriationData.CellVoltge.CvOffsetHigh = (short)((data[2] << 8) | data[3]);
break;
case 221: // Over Current Parameter
rSystemData.ParamData.ChaOverCurrentWarning = (short)((data[0] * 256) + data[1] - 30000);
rSystemData.ParamData.ChaOverCurrentTrip = (short)((data[2] * 256) + data[3] - 30000);
rSystemData.ParamData.DchOverCurrentWarning = (short)((data[4] * 256) + data[5] - 30000);
rSystemData.ParamData.DchOverCurrentTrip = (short)((data[6] * 256) + data[7] - 30000);
break;
case 231: // Voltage release Parameter
rSystemData.ParamData.CellUnderVoltageRelease = (short)((data[0] * 256) + data[1]);
rSystemData.ParamData.CellOverVoltageRelease = (short)((data[2] * 256) + data[3]);
rSystemData.ParamData.SysUnderVoltageRelease = (short)((data[4] * 256) + data[5]);
rSystemData.ParamData.SysOverVoltageRelease = (short)((data[6] * 256) + data[7]);
break;
case 241: // Temperature, Current release Parameter
rSystemData.ParamData.ChaLowTempRelease = (short)(data[0] - 80);
rSystemData.ParamData.ChaHighTempRelease = (short)(data[1] - 80);
rSystemData.ParamData.DchLowTempRelease = (short)(data[2] - 80);
rSystemData.ParamData.DchHighTempRelease = (short)(data[3] - 80);
rSystemData.ParamData.ChaOverCurrentRelease = (short)((data[4] * 256) + data[5] - 30000);
rSystemData.ParamData.DchOverCurrentRelease = (short)((data[6] * 256) + data[7] - 30000);
break;
case 81: // Battery Parameter
rSystemData.CalibriationData.Battery.CellQty = (short)(data[0]);
rSystemData.CalibriationData.Battery.TempQty = (short)(data[1]);
rSystemData.CalibriationData.Battery.Capacity = (UInt32)((data[2] * 256) + data[3]);
break;
case 91: // Device Address Setting
rSystemData.CalibriationData.SystemInfo.devAddr = (ushort)((data[0] * 256) + data[1]);
break;
case 171: // Cell Balancing Paramwter
rSystemData.CalibriationData.CbParam.Threadhold = (short)((data[0] * 256) + data[1]);
rSystemData.CalibriationData.CbParam.Window = (short)((data[2] * 256) + data[3]);
rSystemData.CalibriationData.CbParam.Min = (short)(data[4]);
rSystemData.CalibriationData.CbParam.Interval = (short)(data[5]);
break;
case 211:
DateTime dev = new DateTime(data[0] + 1970
, data[1]
, data[2]
, data[3]
, data[4]
, data[5]
);
rSystemData.CalibriationData.SystemInfo.devTime = dev;
break;
case 21: // Cell Voltage Difference Parameter
rSystemData.ParamData.CellVoltageDifferenceTrip = (short)((data[0] * 256) + data[1]);
rSystemData.ParamData.CellVoltageDifferenceWarning = (short)((data[2] * 256) + data[3]);
rSystemData.ParamData.CellVoltageDifferenceRelease = (short)((data[4] * 256) + data[5]);
rSystemData.ParamData.CellVoltageDifferenceTime = (short)((data[6] * 256) + data[7]);
break;
}
}
if (rSystemData.StatusData.protect != 0)
rSystemData.StatusData.alarm = 2;
else if (rSystemData.StatusData.warning != 0)
rSystemData.StatusData.alarm = 1;
else
rSystemData.StatusData.alarm = 0;
}
}
public static void CanInvRxProcess(int sId, UInt32 exID, byte[] rData, ref DeviceSystemData aSystemData, DateTime rTime)
{
PACKET_HEADER PacketHeader = CovertPtoH(exID);
if (PacketHeader.SA == (200 + sId))
{
if (rData.Length > 0)
{
aSystemData.CommFail = false;
aSystemData.ShelfCommFail = false;
aSystemData.LastRxTime = rTime;
switch (PacketHeader.PF)
{
case 11: // Device ManufactureDate
aSystemData.Information.ManufactureDate = (UInt32)((rData[0] << 24)
| (rData[1] << 16)
| (rData[2] << 8)
| (rData[3] << 0));
break;
case 21: // Device Serial Number MSB
for (int i = 0; i < 8; i++)
{
aSystemData.Information.pcb_sn[i] = rData[i];
}
break;
case 31: // Device Serial Number LSB
for (int i = 0; i < 8; i++)
{
aSystemData.Information.pcb_sn[i + 8] = rData[i];
}
break;
}
}
}
}
public static PACKET_HEADER CovertPtoH(UInt32 id)
{
PACKET_HEADER hdr = new PACKET_HEADER();
hdr.Index = (byte)((id >> 26) & 0x07);
hdr.R = (byte)((id >> 25) & 0x01);
hdr.DP = (byte)((id >> 24) & 0x01);
hdr.PF = (byte)((id >> 16) & 0xFF);
hdr.PS = (byte)((id >> 8) & 0xFF);
hdr.SA = (byte)((id >> 0) & 0xFF);
return hdr;
}
public static UInt32 CovertHtoP(PACKET_HEADER hdr)
{
UInt32 Packet = 0;
Packet = (((UInt32)hdr.Index << 26)
| ((UInt32)hdr.R << 25)
| ((UInt32)hdr.DP << 24)
| ((UInt32)hdr.PF << 16)
| ((UInt32)hdr.PS << 8)
| ((UInt32)hdr.SA << 0)
);
return Packet;
}
public static byte[] MakeSocRecoveryCanData(byte nSoc)
{
byte[] result = new byte[8];
for (int i = 0; i < 8; i++)
result[i] = 0xFF;
result[0] = 0;
result[1] = nSoc;
return result;
}
public static byte[] MakeCanData(int mode, int flag, int dcp, ref DeviceParamData aParam, ref DeviceCalibration aCalib)
{
byte[] result = new byte[8];
short temp = 0;
for (int i = 0; i < 8; i++)
{ result[i] = 0xFF; }
switch (mode)
{
case 1: // Status Req
result[6] = (byte)dcp;
break;
//case 10: // Cell Balancing set
// aCalib.CellBalancingVoltage = 3600;
// aCalib.CellBalancingVoltageEndGap = 100;
// aCalib.CellBalancingVoltageInterval = 5;
// result[0] = (byte)(aCalib.CellBalancingVoltage >> 8);
// result[1] = (byte)(aCalib.CellBalancingVoltage >> 0);
// result[2] = (byte)(aCalib.CellBalancingVoltageEndGap / 10);
// result[3] = (byte)(aCalib.CellBalancingVoltageInterval << 1);
// int ss = Convert.ToInt32(String.Format("{0:ss}", DateTime.Now));
// if (ss == 0)
// {
// result[3] |= 1;
// UInt32 nTime = (UInt32)csUtils.UnixTimeNow();
// result[4] = (byte)(nTime >> 24);
// result[5] = (byte)(nTime >> 16);
// result[6] = (byte)(nTime >> 8);
// result[7] = (byte)(nTime >> 0);
// }
// break;
//case 17:
// if (aCalib.Current.SelectSubItem != 2)
// result[7] = (byte)aCalib.Current.ChaAndDchSelect;
// break;
}
// Parameter Set
if (flag == 1)
{
switch (mode)
{
case 25:
result[0] = (byte)1;
break;
case 10: // Cell Balancing set
result[0] = (byte)(aCalib.CellBalancingVoltage >> 8);
result[1] = (byte)(aCalib.CellBalancingVoltage >> 0);
result[2] = (byte)(aCalib.CellBalancingVoltageEndGap / 10);
result[3] = (byte)(aCalib.CellBalancingVoltageInterval << 1);
int ss = Convert.ToInt32(String.Format("{0:ss}", DateTime.Now));
if (ss == 0)
{
result[3] = 1;
UInt32 nTime = (UInt32)csUtils.UnixTimeNow();
result[4] = (byte)(nTime >> 24);
result[5] = (byte)(nTime >> 16);
result[6] = (byte)(nTime >> 8);
result[7] = (byte)(nTime >> 0);
}
break;
case 5: // Cell Voltage Warning and Fault Parameter
result[0] = (byte)(aParam.CellUnderVoltageWarning >> 8);
result[1] = (byte)(aParam.CellUnderVoltageWarning >> 0);
result[2] = (byte)(aParam.CellUnderVoltageTrip >> 8);
result[3] = (byte)(aParam.CellUnderVoltageTrip >> 0);
result[4] = (byte)(aParam.CellOverVoltageWarning >> 8);
result[5] = (byte)(aParam.CellOverVoltageWarning >> 0);
result[6] = (byte)(aParam.CellOverVoltageTrip >> 8);
result[7] = (byte)(aParam.CellOverVoltageTrip >> 0);
break;
case 6: // Temperature Warning and Fault Parameter
result[0] = (byte)(aParam.ChaLowTempWarning + 80);
result[1] = (byte)(aParam.ChaLowTempTrip + 80);
result[2] = (byte)(aParam.ChaHighTempWarning + 80);
result[3] = (byte)(aParam.ChaHighTempTrip + 80);
result[4] = (byte)(aParam.DchLowTempWarning + 80);
result[5] = (byte)(aParam.DchLowTempTrip + 80);
result[6] = (byte)(aParam.DchHighTempWarning + 80);
result[7] = (byte)(aParam.DchHighTempTrip + 80);
break;
case 7: // System Voltage Warning and Fault Parameter
result[0] = (byte)(aParam.SysUnderVoltageWarning >> 8);
result[1] = (byte)(aParam.SysUnderVoltageWarning >> 0);
result[2] = (byte)(aParam.SysUnderVoltageTrip >> 8);
result[3] = (byte)(aParam.SysUnderVoltageTrip >> 0);
result[4] = (byte)(aParam.SysOverVoltageWarning >> 8);
result[5] = (byte)(aParam.SysOverVoltageWarning >> 0);
result[6] = (byte)(aParam.SysOverVoltageTrip >> 8);
result[7] = (byte)(aParam.SysOverVoltageTrip >> 0);
break;
case 14: // SOC Warning and System Voltage Calibration K, B Parameter
result[0] = (byte)(aParam.LowSocWarning);
result[1] = (byte)(aParam.LowSocRelease);
result[2] = 0;
result[3] = 0;
result[4] = (byte)(aCalib.SystemVoltage.Calibration_K >> 8);
result[5] = (byte)(aCalib.SystemVoltage.Calibration_K >> 0);
result[6] = (byte)(aCalib.SystemVoltage.Calibration_B >> 8);
result[7] = (byte)(aCalib.SystemVoltage.Calibration_K >> 0);
break;
case 22: // Current Warning and Fault Parameter
temp = (short)(aParam.ChaOverCurrentWarning + 30000);
result[0] = (byte)(temp >> 8);
result[1] = (byte)(temp >> 0);
temp = (short)(aParam.ChaOverCurrentTrip + 30000);
result[2] = (byte)(temp >> 8);
result[3] = (byte)(temp >> 0);
temp = (short)(aParam.DchOverCurrentWarning + 30000);
result[4] = (byte)(temp >> 8);
result[5] = (byte)(temp >> 0);
temp = (short)(aParam.DchOverCurrentTrip + 30000);
result[6] = (byte)(temp >> 8);
result[7] = (byte)(temp >> 0);
break;
case 23: // Cell and System Voltage Release Parameter
result[0] = (byte)(aParam.CellUnderVoltageRelease >> 8);
result[1] = (byte)(aParam.CellUnderVoltageRelease >> 0);
result[2] = (byte)(aParam.CellOverVoltageRelease >> 8);
result[3] = (byte)(aParam.CellOverVoltageRelease >> 0);
result[4] = (byte)(aParam.SysUnderVoltageRelease >> 8);
result[5] = (byte)(aParam.SysUnderVoltageRelease >> 0);
result[6] = (byte)(aParam.SysOverVoltageRelease >> 8);
result[7] = (byte)(aParam.SysOverVoltageRelease >> 0);
break;
case 24: // Cell and System Voltage Release Parameter
result[0] = (byte)(aParam.ChaLowTempRelease + 80);
result[1] = (byte)(aParam.ChaHighTempRelease + 80);
result[2] = (byte)(aParam.DchLowTempRelease + 80);
result[3] = (byte)(aParam.DchHighTempRelease + 80);
temp = (short)(aParam.ChaOverCurrentRelease + 30000);
result[4] = (byte)(temp >> 8);
result[5] = (byte)(temp >> 0);
temp = (short)(aParam.DchOverCurrentRelease + 30000);
result[6] = (byte)(temp >> 8);
result[7] = (byte)(temp >> 0);
break;
case 9:
result[0] = (byte)(aCalib.SystemInfo.devAddr >> 8);
result[1] = (byte)(aCalib.SystemInfo.devAddr >> 0);
break;
case 1: // Auto Cell Balancing Set Data (0: Off. 1: On)
//result[6] = (byte)((aCalib.ForcedBalancing.DCP) ? 0x01 : 0x00);
result[7] = (byte)((aCalib.ForcedBalancing.AutoB) ? 0x01 : 0x00);
break;
case 12: // Forced Cell Balancing
result[0] = (byte)(aCalib.ForcedBalancing2.Control);
result[1] = (byte)(aCalib.ForcedBalancing2.CellNo);
result[2] = (byte)(aCalib.ForcedBalancing2.Mode);
result[3] = (byte)(aCalib.ForcedBalancing2.Enable);
break;
case 8: // Battery Paramter
result[0] = (byte)(aCalib.Battery.CellQty);
result[1] = (byte)(aCalib.Battery.TempQty);
result[2] = (byte)(aCalib.Battery.Capacity >> 8);
result[3] = (byte)(aCalib.Battery.Capacity >> 0);
break;
case 17: // Cell Balancing Parameter
result[0] = (byte)(aCalib.CbParam.Threadhold >> 8);
result[1] = (byte)(aCalib.CbParam.Threadhold >> 0);
result[2] = (byte)(aCalib.CbParam.Window >> 8);
result[3] = (byte)(aCalib.CbParam.Window >> 0);
result[4] = (byte)(aCalib.CbParam.Min >> 0);
result[5] = (byte)(aCalib.CbParam.Interval >> 0);
break;
case 21: // System Information (Device Address)
result[0] = (byte)(aCalib.SystemInfo.devAddr >> 8);
result[1] = (byte)(aCalib.SystemInfo.devAddr >> 0);
break;
case 13: // Soc Calibration
result[0] = (byte)(aCalib.SocCalib.CellNo);
result[1] = (byte)(aCalib.SocCalib.SocValue);
break;
case 15: // Parameter Option
result[0] = (byte)(aCalib.CellVoltge.CvOffsetLow >> 8);
result[1] = (byte)(aCalib.CellVoltge.CvOffsetLow >> 0);
result[2] = (byte)(aCalib.CellVoltge.CvOffsetHigh >> 8);
result[3] = (byte)(aCalib.CellVoltge.CvOffsetHigh >> 0);
result[7] = (byte)(0x01);
break;
case 16: // Default Parameter
result[0] = (byte)(aParam.DefalutParamOption);
break;
case 2: // Default Parameter
result[0] = (byte)(aParam.CellVoltageDifferenceTrip >> 8);
result[1] = (byte)(aParam.CellVoltageDifferenceTrip >> 0);
result[2] = (byte)(aParam.CellVoltageDifferenceWarning >> 8);
result[3] = (byte)(aParam.CellVoltageDifferenceWarning >> 0);
result[4] = (byte)(aParam.CellVoltageDifferenceRelease >> 8);
result[5] = (byte)(aParam.CellVoltageDifferenceRelease >> 0);
result[6] = (byte)(aParam.CellVoltageDifferenceTime >> 8);
result[7] = (byte)(aParam.CellVoltageDifferenceTime >> 0);
break;
case 900:
result[0] = (byte)(aCalib.InvData.ManufactureDate >> 24);
result[1] = (byte)(aCalib.InvData.ManufactureDate >> 16);
result[2] = (byte)(aCalib.InvData.ManufactureDate >> 8);
result[3] = (byte)(aCalib.InvData.ManufactureDate >> 0);
result[7] = (byte)(1);
break;
case 901:
for (int i = 0; i < 8; i++)
{
result[i] = (byte)(aCalib.InvData.pcb_sn[i]);
}
break;
case 902:
for (int i = 0; i < 8; i++)
{
result[i] = (byte)(aCalib.InvData.pcb_sn[i + 8]);
}
break;
}
}
return result;
}
private static DeviceSystemData MakeMaxAvgMinCellVoltage(DeviceSystemData rSystemData)
{
DeviceSystemData result = rSystemData;
int Max, Avg, Min, Sum;
int MaxNo, MinNo;
Max = Avg = Min = Sum = 0;
MaxNo = MinNo = 0;
for (int i = 0; i < rSystemData.cellQty; i++)
{
if (i == 0)
{
Max = Min = rSystemData.ValueData.CellVoltage[i];
}
Sum += rSystemData.ValueData.CellVoltage[i];
if (Max < rSystemData.ValueData.CellVoltage[i])
{
Max = rSystemData.ValueData.CellVoltage[i];
MaxNo = i;
}
if (Min > rSystemData.ValueData.CellVoltage[i])
{
Min = rSystemData.ValueData.CellVoltage[i];
MinNo = i;
}
}
if (rSystemData.cellQty > 0)
Avg = Sum / rSystemData.cellQty;
result.AvgData.avgCellVoltage = (ushort)Avg;
result.AvgData.maxCellVoltage = (ushort)Max;
result.AvgData.maxCellNum = (short)(MaxNo + 1);
result.AvgData.minCellVoltage = (ushort)Min;
result.AvgData.minCellNum = (short)(MinNo + 1);
result.AvgData.diffCellVoltage = (ushort)(Max - Min);
return result;
}
private static void MakeMaxAvgMinTemperature(ref DeviceSystemData rSystemData)
{
int Max, Avg, Min, Sum;
int MaxNo, MinNo;
Max = Avg = Min = Sum = 0;
MaxNo = MinNo = 0;
for (int i = 0; i < rSystemData.tempQty; i++)
{
if (i == 0)
{
Max = Min = rSystemData.ValueData.CellTemperature[i];
}
Sum += rSystemData.ValueData.CellTemperature[i];
if (Max < rSystemData.ValueData.CellTemperature[i])
{
Max = rSystemData.ValueData.CellTemperature[i];
MaxNo = i;
}
if (Min > rSystemData.ValueData.CellTemperature[i])
{
Min = rSystemData.ValueData.CellTemperature[i];
MinNo = i;
}
}
if (rSystemData.tempQty > 0)
Avg = Sum / rSystemData.tempQty;
rSystemData.AvgData.avgTemp = (short)Avg;
rSystemData.AvgData.maxTemp = (short)Max;
rSystemData.AvgData.maxTempNum = (short)(MaxNo + 1);
rSystemData.AvgData.minTemp = (short)Min;
rSystemData.AvgData.minTempNum = (short)(MinNo + 1);
rSystemData.AvgData.diffTemp = (short)(Max - Min);
}
private static DeviceSystemData MakeAlarmTripData(int id, short ndata, DeviceSystemData rSystemData)
{
bool[] aData = csUtils.Int16ToBitArray(ndata);
short bFault = rSystemData.StatusData.protect;
short bWarning = rSystemData.StatusData.warning;
int i = 0;
switch (id)
{
case 0: // Status Code 1
if (aData[i++]) bWarning |= (1 << 4); // 00 Cell Over Voltage Warning
else bWarning &= ~(1 << 4);
if (aData[i++]) bWarning |= (1 << 5); // 01 Cell Under Voltage Warning
else bWarning &= ~(1 << 5);
if (aData[i++]) bWarning |= (1 << 0); // 02 High Temperature Warning
else bWarning &= ~(1 << 0);
if (aData[i++]) bWarning |= (1 << 1); // 03 Low Temperature Warning
else bWarning &= ~(1 << 1);
if (aData[i++]) bWarning |= (1 << 2); // 04 Module Over Voltage Warning
else bWarning &= ~(1 << 2);
if (aData[i++]) bWarning |= (1 << 3); // 05 Module Under Voltage Warning
else bWarning &= ~(1 << 3);
if (aData[i++]) bWarning |= (1 << 9); // 06 Cell Voltage Difference Warning
else bWarning &= ~(1 << 9);
i++; // 07 Reserved
if (aData[i++]) bFault |= (1 << 4); // 08 Cell Over Voltage Fault
else bFault &= ~(1 << 4);
if (aData[i++]) bFault |= (1 << 5); // 09 Cell Under Voltage Fault
else bFault &= ~(1 << 5);
if (aData[i++]) bFault |= (1 << 0); // 10 High Temperature Warning
else bFault &= ~(1 << 0);
if (aData[i++]) bFault |= (1 << 1); // 11 Low Temperature Warning
else bFault &= ~(1 << 1);
if (aData[i++]) bFault |= (1 << 2); // 12 Module Over Voltage Warning
else bFault &= ~(1 << 2);
if (aData[i++]) bFault |= (1 << 3); // 13 Module Under Voltage Warning
else bFault &= ~(1 << 3);
if (aData[i++]) bFault |= (1 << 9); // 14 Cell Voltage Difference Fault
else bFault &= ~(1 << 9);
break;
case 1: // Status Code 2
i++; // 00 High SOC Warning
i++; // 01 High SOC Fault
if (aData[i++]) bWarning |= (1 << 11); // 02 Low SOC Warning
else bWarning &= ~(1 << 11);
i++; // 03 Low SOC Fault
i++; // 04 Reserved
i++; // 05 Reserved
i++; // 06 Reserved
i++; // 07 Reserved
if (aData[i++]) bWarning |= (1 << 6); // 08 Charge Over Current Warning
else bWarning &= ~(1 << 6);
if (aData[i++]) bFault |= (1 << 6); // 09 Charge Over Current Fault
else bFault &= ~(1 << 6);
if (aData[i++]) bWarning |= (1 << 7); // 10 Discharge Over Current Warning
else bWarning &= ~(1 << 7);
if (aData[i++]) bFault |= (1 << 7); // 11 Discharge Over Current Fault
else bFault &= ~(1 << 7);
break;
}
rSystemData.StatusData.protect = bFault;
rSystemData.StatusData.warning = bWarning;
return rSystemData;
}
private static DeviceSystemData MakeWarningAlarmData(int id, short ndata, DeviceSystemData rSystemData)
{
bool[] aData = csUtils.Int16ToBitArray(ndata);
short bFault = rSystemData.StatusData.protect;
short bWarning = rSystemData.StatusData.warning;
int i = 0;
switch (id)
{
case 0: // Status Code 1
if (aData[i++]) bWarning |= (1 << 4); // 00 Cell Over Voltage Warning
else bWarning &= ~(1 << 4);
if (aData[i++]) bWarning |= (1 << 5); // 01 Cell Under Voltage Warning
else bWarning &= ~(1 << 5);
if (aData[i++]) bWarning |= (1 << 0); // 02 High Temperature Warning
else bWarning &= ~(1 << 0);
if (aData[i++]) bWarning |= (1 << 1); // 03 Low Temperature Warning
else bWarning &= ~(1 << 1);
if (aData[i++]) bWarning |= (1 << 2); // 04 Module Over Voltage Warning
else bWarning &= ~(1 << 2);
if (aData[i++]) bWarning |= (1 << 3); // 05 Module Under Voltage Warning
else bWarning &= ~(1 << 3);
if (aData[i++]) bWarning |= (1 << 9); // 06 Cell Voltage Difference Warning
else bWarning &= ~(1 << 9);
i++; // 07 Reserved
if (aData[i++]) bFault |= (1 << 4); // 08 Cell Over Voltage Fault
else bFault &= ~(1 << 4);
if (aData[i++]) bFault |= (1 << 5); // 09 Cell Under Voltage Fault
else bFault &= ~(1 << 5);
if (aData[i++]) bFault |= (1 << 0); // 10 High Temperature Warning
else bFault &= ~(1 << 0);
if (aData[i++]) bFault |= (1 << 1); // 11 Low Temperature Warning
else bFault &= ~(1 << 1);
if (aData[i++]) bFault |= (1 << 2); // 12 Module Over Voltage Warning
else bFault &= ~(1 << 2);
if (aData[i++]) bFault |= (1 << 3); // 13 Module Under Voltage Warning
else bFault &= ~(1 << 3);
if (aData[i++]) bFault |= (1 << 9); // 14 Cell Voltage Difference Fault
else bFault &= ~(1 << 9);
break;
case 1: // Status Code 2
i++; // 00 High SOC Warning
i++; // 01 High SOC Fault
if (aData[i++]) bWarning |= (1 << 11); // 02 Low SOC Warning
else bWarning &= ~(1 << 11);
i++; // 03 Low SOC Fault
i++; // 04 Reserved
i++; // 05 Reserved
i++; // 06 Reserved
i++; // 07 Reserved
if (aData[i++]) bWarning |= (1 << 6); // 08 Charge Over Current Warning
else bWarning &= ~(1 << 6);
if (aData[i++]) bFault |= (1 << 6); // 09 Charge Over Current Fault
else bFault &= ~(1 << 6);
if (aData[i++]) bWarning |= (1 << 7); // 10 Discharge Over Current Warning
else bWarning &= ~(1 << 7);
if (aData[i++]) bFault |= (1 << 7); // 11 Discharge Over Current Fault
else bFault &= ~(1 << 7);
break;
}
rSystemData.StatusData.protect = bFault;
rSystemData.StatusData.warning = bWarning;
return rSystemData;
}
public static string PacketToMsg(UInt32 exID, byte[] rData, int flag)
{
string result = "";
PACKET_HEADER PacketHeader = CovertPtoH(exID);
if (flag == 0) result = "RD: ";
else result = "TD: ";
result += String.Format(" ID:0x{0:X4}", exID);
result += String.Format("[PF({3:000}) PS({4:000}) SA({5:000})]"
, PacketHeader.Index
, PacketHeader.R
, PacketHeader.DP
, PacketHeader.PF
, PacketHeader.PS
, PacketHeader.SA
);
result += String.Format("Data({0}): ", rData.Length);
for (int i = 0; i < rData.Length; i++)
{
result += String.Format("{0:X2} ", rData[i]);
}
return result;
}
unsafe public static string PacketToMsg(VCI_CAN_OBJ obj, int flag)
{
PACKET_HEADER PacketHeader = CovertPtoH(obj.ID);
string str;
if (flag == 0) str = "RD: ";
else str = "TD: ";
str += String.Format(" ID:0x{0}", obj.ID.ToString("X4"));
//str += String.Format("[I({0}) R({1}) DP({2}) PF({3}) PS({4}) SA({5})]"
// , PacketHeader.Index
// , PacketHeader.R
// , PacketHeader.DP
// , PacketHeader.PF
// , PacketHeader.PS
// , PacketHeader.SA
// );
str += String.Format("[PF({3:000}) PS({4:000}) SA({5:000})]"
, PacketHeader.Index
, PacketHeader.R
, PacketHeader.DP
, PacketHeader.PF
, PacketHeader.PS
, PacketHeader.SA
);
str += " Frame:";
if (obj.RemoteFlag == 0)
str += "D-Frame ";
else
str += "R-Frame ";
//if (obj.ExternFlag == 0)
// str += "Std-Frame ";
//else
// str += "Ext-Frame ";
//////////////////////////////////////////
if (obj.RemoteFlag == 0)
{
byte len = (byte)(obj.DataLen % 9);
str += String.Format("Data({0}): ", len);
for (int i = 0; i < len; i++)
{
str += String.Format("{0} ", obj.Data[i].ToString("X2"));
}
}
return str;
}
unsafe public static string PacketToMsg1(VCI_CAN_OBJ obj)
{
string str;
str = "Received data: ";
str += " Frame ID:0x" + System.Convert.ToString((Int32)obj.ID, 16);
str += " Frame format:";
if (obj.RemoteFlag == 0)
str += "Data Frame ";
else
str += "Remote frame ";
if (obj.ExternFlag == 0)
str += "Standard frame ";
else
str += "Extended frame ";
//////////////////////////////////////////
if (obj.RemoteFlag == 0)
{
str += "Data: ";
byte len = (byte)(obj.DataLen % 9);
byte j = 0;
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[0], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[1], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[2], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[3], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[4], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[5], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[6], 16);
if (j++ < len)
str += " " + System.Convert.ToString(obj.Data[7], 16);
}
return str;
}
}
}

View File

@@ -0,0 +1,275 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LFP_Manager.Function
{
// 1. Define the data type
public struct PACKET_HEADER_DN
{
public byte Rsvd; // 3
public byte PR; // 3 Priority
public byte FC; // 4 Function Code
public byte NO; // 8 Number
public byte SID; // 7 Source ID
public byte DID; // 7 Destination ID
}
public struct PACKET_DN
{
public UInt32 hdr; // Header
public byte[] data; // Data
}
class csCanFwUpdateFunction
{
// Function Code Define
public const int DL_START_CODE = 0; // Start Fw Update
public const int DL_SECTOR_ERASE_CODE = 1; // Sector Erase Code
public const int DL_SET_ADDRESS_CODE = 2; // Flash Address Set Code
public const int DL_READ_DATA_CODE = 3; // Flash Data Read Code
public const int DL_WRITE_DATA_CODE = 4; // Flash Data Write Code
public const int DL_WRITE_DATA_CSUM_CODE = 5; // Flash Data Write Checksum Code
public const int DL_IMAGE_CSUM_CODE = 6; // Fw Image Checksum Code
public const int DL_RESTART_CODE = 7; // Restart
public static PACKET_HEADER_DN CovertPtoH(UInt32 id)
{
PACKET_HEADER_DN hdr = new PACKET_HEADER_DN();
hdr.PR = (byte)((id >> 26) & 0x07);
hdr.FC = (byte)((id >> 22) & 0x07);
hdr.NO = (byte)((id >> 14) & 0xFF);
hdr.SID = (byte)((id >> 7) & 0x7F);
hdr.DID = (byte)((id >> 0) & 0x7F);
return hdr;
}
public static UInt32 CovertHtoP(PACKET_HEADER_DN hdr)
{
UInt32 Packet = 0;
Packet = (((UInt32)hdr.PR << 26)
| ((UInt32)hdr.FC << 22)
| ((UInt32)hdr.NO << 14)
| ((UInt32)hdr.SID << 7)
| ((UInt32)hdr.DID << 0)
);
return Packet;
}
unsafe public static PACKET_DN FwUpdateStartPacket(UInt32 dev_id, byte[] fwver, UInt32 fwlen)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_START_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = fwver[0];
result.data[1] = fwver[1];
result.data[2] = fwver[2];
result.data[3] = fwver[3];
result.data[4] = (byte)(fwlen >> 24);
result.data[5] = (byte)(fwlen >> 16);
result.data[6] = (byte)(fwlen >> 8);
result.data[7] = (byte)(fwlen >> 0);
return result;
}
unsafe public static PACKET_DN SectorErasePacket(UInt32 dev_id, UInt32 fAddr)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_SECTOR_ERASE_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = (byte)(fAddr >> 24);
result.data[1] = (byte)(fAddr >> 16);
result.data[2] = (byte)(fAddr >> 8);
result.data[3] = (byte)(fAddr >> 0);
result.data[4] = 0;
result.data[5] = 0;
result.data[6] = 0;
result.data[7] = 0;
return result;
}
unsafe public static PACKET_DN SetAddrPacket(UInt32 dev_id, UInt32 sAddr, UInt32 sLen)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_SET_ADDRESS_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = (byte)(sAddr >> 24);
result.data[1] = (byte)(sAddr >> 16);
result.data[2] = (byte)(sAddr >> 8);
result.data[3] = (byte)(sAddr >> 0);
result.data[4] = (byte)(sLen >> 24);
result.data[5] = (byte)(sLen >> 16);
result.data[6] = (byte)(sLen >> 8);
result.data[7] = (byte)(sLen >> 0);
return result;
}
unsafe public static PACKET_DN WritePacket(UInt32 dev_id, byte dno, byte[] data)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_WRITE_DATA_CODE;
hdr.NO = dno;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
for (int i = 0; i < 8; i++)
{
result.data[i] = data[i];
}
return result;
}
unsafe public static PACKET_DN WriteChkSumPacket(UInt32 dev_id, UInt32 waddr, UInt32 csum)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_WRITE_DATA_CSUM_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = (byte)(waddr >> 24);
result.data[1] = (byte)(waddr >> 16);
result.data[2] = (byte)(waddr >> 8);
result.data[3] = (byte)(waddr >> 0);
result.data[4] = (byte)(csum >> 24);
result.data[5] = (byte)(csum >> 16);
result.data[6] = (byte)(csum >> 8);
result.data[7] = (byte)(csum >> 0);
return result;
}
unsafe public static PACKET_DN FwImageChkSumPacket(UInt32 dev_id, UInt32 fwlen, UInt32 csum)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_IMAGE_CSUM_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = (byte)(fwlen >> 24);
result.data[1] = (byte)(fwlen >> 16);
result.data[2] = (byte)(fwlen >> 8);
result.data[3] = (byte)(fwlen >> 0);
result.data[4] = (byte)(csum >> 24);
result.data[5] = (byte)(csum >> 16);
result.data[6] = (byte)(csum >> 8);
result.data[7] = (byte)(csum >> 0);
return result;
}
unsafe public static PACKET_DN UpdateRestartPacket(UInt32 dev_id, byte option)
{
PACKET_DN result;
PACKET_HEADER_DN hdr;
result = new PACKET_DN();
result.data = new byte[8];
hdr = new PACKET_HEADER_DN();
hdr.PR = 4;
hdr.FC = DL_RESTART_CODE;
hdr.NO = 0;
hdr.SID = 0;
hdr.DID = (byte)dev_id;
result.hdr = CovertHtoP(hdr);
result.data[0] = option;
result.data[1] = 0x00;
result.data[2] = 0x00;
result.data[3] = 0x00;
result.data[4] = 0x00;
result.data[5] = 0x00;
result.data[6] = 0x00;
result.data[7] = 0x00;
return result;
}
}
}

View File

@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.IO;
using System.Data.OleDb;
namespace LFP_Manager.Function
{
public static class csExcelExport
{
public static void ExportToExcel(this DataTable dataTable, String filePath, bool overwiteFile = true)
{
if (Directory.Exists(Path.GetDirectoryName(filePath)) == false)
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
if (File.Exists(filePath) && overwiteFile)
File.Delete(filePath);
//var conn = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=0';", filePath);
var conn = "";
if (filePath.IndexOf(".xlsx") > -1) // 확장자에 따라서 provider 주의
conn = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=3';", filePath);
else
conn = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=3';", filePath);
using (OleDbConnection connection = new OleDbConnection(conn))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
List<String> columnNames = new List<string>();
List<String> columnTypes = new List<string>();
foreach (DataColumn dataColumn in dataTable.Columns)
{
columnNames.Add(dataColumn.ColumnName);
string tName = "VARCHAR";
switch (dataColumn.DataType.Name)
{
case "Int16": tName = "INTEGER"; break;
case "Int32": tName = "INTEGER"; break;
case "Int64": tName = "INTEGER"; break;
case "Double": tName = "DOUBLE"; break;
case "String": tName = "VARCHAR"; break;
default: tName = dataColumn.DataType.Name; break;
}
columnTypes.Add(tName);
}
String tableName = !String.IsNullOrWhiteSpace(dataTable.TableName) ? dataTable.TableName : Guid.NewGuid().ToString();
//command.CommandText = @"CREATE TABLE [{tableName}] ({String.Join(",", columnNames.Select(c => $"[{c}] VARCHAR").ToArray())});";
//string join = String.Join(",", columnNames.Select(c => String.Format("[{0}] VARCHAR", c)).ToArray());
string join = "";
for (int i = 0; i < columnNames.Count; i++)
{
join += String.Format("[{0}] {1}", columnNames[i], columnTypes[i]);
if (i < (columnNames.Count - 1)) join += ",";
}
command.CommandText = String.Format("CREATE TABLE [{0}] ({1});",
tableName,
join
);
command.ExecuteNonQuery();
foreach (DataRow row in dataTable.Rows)
{
List<String> rowValues = new List<string>();
foreach (DataColumn column in dataTable.Columns)
{
rowValues.Add((row[column] != null && row[column] != DBNull.Value) ? row[column].ToString() : String.Empty);
}
//command.CommandText = $"INSERT INTO [{tableName}]({String.Join(",", columnNames.Select(c => $"[{c}]"))}) VALUES ({String.Join(",", rowValues.Select(r => $"'{r}'").ToArray())});";
string a = String.Join(",", columnNames.Select(c => String.Format("[{0}]", c)));
string b = String.Join(",", rowValues.Select(r => String.Format("'{0}'", (r == "") ? "0": r)).ToArray());
command.CommandText = String.Format("INSERT INTO [{0}]({1}) VALUES ({2});", tableName, a, b);
command.ExecuteNonQuery();
}
}
connection.Close();
}
}
}
}

View File

@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace LFP_Manager.Function
{
public class csExcelFunction
{
public static DataTable[] ExcelImport(string Ps_FileName, string[] sheetName)
{
DataTable[] result = null;
try
{
string ExcelConn = string.Empty;
if (Ps_FileName.IndexOf(".xlsx") > -1) // 확장자에 따라서 provider 주의
{
ExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Ps_FileName
+ ";Extended Properties='Excel 12.0;HDR=YES'";
}
else
{
ExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Ps_FileName
+ ";Extended Properties='Excel 8.0;HDR=YES'";
}
// 첫 번째 시트의 이름을 가져옮
using (OleDbConnection con = new OleDbConnection(ExcelConn))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dtExcelSchema.Rows.Count > 0)
{
sheetName = new string[dtExcelSchema.Rows.Count];
for (int i = 0; i < dtExcelSchema.Rows.Count; i++)
sheetName[i] = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
}
con.Close();
}
}
string msg = string.Empty;
for (int i = 0; i < sheetName.Length; i++)
msg += sheetName[i] + "\r\n";
//MessageBox.Show("sheetName = " + msg);
// 첫 번째 쉬트의 데이타를 읽어서 datagridview 에 보이게 함.
using (OleDbConnection con = new OleDbConnection(ExcelConn))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
result = new DataTable[sheetName.Length];
for (int i = 0; i < sheetName.Length; i++)
{
result[i] = new DataTable();
result[i].TableName = sheetName[i];
cmd.CommandText = "SELECT * From [" + sheetName[i] + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
try
{
oda.Fill(result[i]);
}
catch (Exception)
{
//MessageBox.Show(e1.Message);
}
con.Close();
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return result;
}
public static void ExcelExport(string Ps_FileName, string[] sheetName)
{
string ExcelConn = string.Empty;
if (Ps_FileName.IndexOf(".xlsx") > -1) // 확장자에 따라서 provider 주의
{
ExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Ps_FileName
+ ";Extended Properties='Excel 12.0;HDR=YES;IMEX=3;READONLY=FALSE'";
}
else
{
ExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Ps_FileName
+ ";Extended Properties='Excel 8.0;HDR=YES;IMEX=3;READONLY=FALSE'";
}
// 첫 번째 시트의 이름을 가져옮
using (OleDbConnection con = new OleDbConnection(ExcelConn))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dtExcelSchema.Rows.Count > 0)
{
sheetName = new string[dtExcelSchema.Rows.Count];
for (int i = 0; i < dtExcelSchema.Rows.Count; i++)
sheetName[i] = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
}
con.Close();
}
}
using (OleDbConnection connection =
new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + @"C:\Users\[...]\Classeur.xls"
+ ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1;READONLY=FALSE\""))
{
connection.Open();
OleDbCommand commande = new OleDbCommand(
"INSERT INTO [Feuil1$](F1,F2,F3) VALUES ('A3','B3','C3');", connection);
commande.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
}
}
}

View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace LFP_Manager.Function
{
// 1. The type of the ZLGCAN series interface card information.
public struct VCI_BOARD_INFO
{
public UInt16 hw_Version;
public UInt16 fw_Version;
public UInt16 dr_Version;
public UInt16 in_Version;
public UInt16 irq_Num;
public byte can_Num;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] str_Serial_Num;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 40)]
public byte[] str_hw_Type;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] Reserved;
}
// 2. Define the data type of the CAN message frame.
unsafe public struct VCI_CAN_OBJ //Use unsafe code
{
public uint ID;
public uint TimeStamp;
public byte TimeFlag;
public byte SendType;
public byte RemoteFlag; //Whether it is a remore frame
public byte ExternFlag; //Whether it is a extended frame
public byte DataLen;
public fixed byte Data[8];
public fixed byte Reserved[3];
}
//2. Define the data type of the CAN message frame.
//public struct VCI_CAN_OBJ
//{
// public UInt32 ID;
// public UInt32 TimeStamp;
// public byte TimeFlag;
// public byte SendType;
// public byte RemoteFlag;//Whether it is a remore frame
// public byte ExternFlag;//Whether it is a extended frame
// public byte DataLen;
// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
// public byte[] Data;
// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
// public byte[] Reserved;
// public void Init()
// {
// Data = new byte[8];
// Reserved = new byte[3];
// }
//}
// 3. Define the data type of the CAN controller status.
public struct VCI_CAN_STATUS
{
public byte ErrInterrupt;
public byte regMode;
public byte regStatus;
public byte regALCapture;
public byte regECCapture;
public byte regEWLimit;
public byte regRECounter;
public byte regTECounter;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public byte[] Reserved;
}
// 4. Define the data type of the error message.
public struct VCI_ERR_INFO
{
public UInt32 ErrCode;
public byte Passive_ErrData1;
public byte Passive_ErrData2;
public byte Passive_ErrData3;
public byte ArLost_ErrData;
}
// 5. Define the data type for initializing CAN
public struct VCI_INIT_CONFIG
{
public UInt32 AccCode;
public UInt32 AccMask;
public UInt32 Reserved;
public byte Filter;
public byte Timing0;
public byte Timing1;
public byte Mode;
}
public struct CHGDESIPANDPORT
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public byte[] szpwd;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
public byte[] szdesip;
public Int32 desport;
public void Init()
{
szpwd = new byte[10];
szdesip = new byte[20];
}
}
///////// new add struct for filter /////////
//typedef struct _VCI_FILTER_RECORD{
// DWORD ExtFrame; //Whether it is an extended frame
// DWORD Start;
// DWORD End;
//}VCI_FILTER_RECORD,*PVCI_FILTER_RECORD;
public struct VCI_FILTER_RECORD
{
public UInt32 ExtFrame;
public UInt32 Start;
public UInt32 End;
}
class csExtCANControlFunction
{
[DllImport("controlcan.dll")]
static extern UInt32 VCI_OpenDevice(UInt32 DeviceType, UInt32 DeviceInd, UInt32 Reserved);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_CloseDevice(UInt32 DeviceType, UInt32 DeviceInd);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_InitCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_INIT_CONFIG pInitConfig);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_ReadBoardInfo(UInt32 DeviceType, UInt32 DeviceInd, ref VCI_BOARD_INFO pInfo);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_ReadErrInfo(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_ERR_INFO pErrInfo);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_ReadCANStatus(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_STATUS pCANStatus);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_GetReference(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, UInt32 RefType, ref byte pData);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_SetReference(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, UInt32 RefType, ref byte pData);
//unsafe static extern UInt32 VCI_SetReference(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, UInt32 RefType, byte* pData);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_GetReceiveNum(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_ClearBuffer(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_StartCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_ResetCAN(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd);
[DllImport("controlcan.dll")]
static extern UInt32 VCI_Transmit(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pSend, UInt32 Len);
//[DllImport("controlcan.dll")]
//static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, ref VCI_CAN_OBJ pReceive, UInt32 Len, Int32 WaitTime);
[DllImport("controlcan.dll", CharSet = CharSet.Ansi)]
static extern UInt32 VCI_Receive(UInt32 DeviceType, UInt32 DeviceInd, UInt32 CANInd, IntPtr pReceive, UInt32 Len, Int32 WaitTime);
}
}

View File

@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SQLite;
using LFP_Manager.DataStructure;
using LFP_Manager.Utils;
namespace LFP_Manager.Function
{
class csHistoryFunction
{
#region DB CREATE
public static void DbCreate(string mPath)
{
string dbFilename = mPath + csDbConstData.DataBase.FileName;
if (Directory.Exists(System.IO.Path.GetDirectoryName(dbFilename)) == false)
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dbFilename));
if (File.Exists(dbFilename) == false)
// Create database
SQLiteConnection.CreateFile(dbFilename);
// Open database
string strConn = @"Data Source=" + dbFilename;
using (var connection = new SQLiteConnection(strConn))
{
connection.Open();
try
{
// Create table
using (SQLiteCommand command = connection.CreateCommand())
{
command.CommandText = csDbConstData.DataBase.CreateTable;
command.ExecuteNonQuery();
}
}
catch (Exception)
{
}
finally
{
connection.Close();
}
}
}
#endregion
#region DB INSERT DATA
private void IDInsert(DataTable aData, string mPath, string Quary)
{
string dbFilename = mPath + csDbConstData.DataBase.FileName;
// Open database
string strConn = @"Data Source=" + dbFilename;
using (var connection = new SQLiteConnection(strConn))
{
connection.Open();
try
{
// Insert data
using (SQLiteCommand command = connection.CreateCommand())
{
command.CommandText = "BEGIN;"; //명시적 트렌젝션 시작
command.ExecuteNonQuery();
//sSQL = "insert into TrendTable ( TrendStamp, TagName, TagValue) Values ( " + IntToStr(stamp) + "," + name + "," + value + ");";
//command.CommandText = "INSERT INTO " + csDbConstData.DataBase.TableName + "(id) " + " Values (@id);";
command.CommandText = Quary;
SQLiteParameter p = new SQLiteParameter("@id", DbType.String);
command.Parameters.Add(p);
for (int i = 0; i < aData.Rows.Count; i++)
{
p.Value = String.Format("{0}", aData.Rows[i][0].ToString()); // id
try
{
command.ExecuteNonQuery();
}
catch (Exception)
{
//MessageBox.Show(e1.ToString() + ":" + i.ToString());
}
finally
{
}
}
command.CommandText = "COMMIT;"; //명시적 트렌젝션 시작
command.ExecuteNonQuery();
}
}
catch (Exception)
{
//MessageBox.Show(e.ToString());
}
finally
{
connection.Close();
}
}
}
#endregion
}
}

View File

@@ -0,0 +1,204 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using LFP_Manager.DataStructure;
namespace LFP_Manager.Function
{
class csIniControlFunction
{
#region [Function] INI File Read Function(Section Setting)
public static string[] GetIniValue(string Section, string path)
{
byte[] ba = new byte[5000];
uint Flag = GetPrivateProfileSection(Section, ba, 5000, path);
return Encoding.Default.GetString(ba).Split(new char[1] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
#endregion
#region [Function] INI File Read Function(Section and Key Setting)
public static string GetIniValue(string Section, string key, string path)
{
StringBuilder sb = new StringBuilder(500);
int Flag = GetPrivateProfileString(Section, key, "", sb, 500, path);
return sb.ToString();
}
#endregion
#region [Function] INI File Read Function(Section, Key, Value, Address Setting)
public bool SetIniValue(string Section, string Key, string Value, string path)
{
return (WritePrivateProfileString(Section, Key, Value, path));
}
#endregion
#region [DLL Function] INI DLL Load
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32")]
public static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
[DllImport("kernel32")]
public static extern uint GetPrivateProfileInt(string lpAppName, string lpKeName, int nDefault, string lpFileName);
[DllImport("kernel32")]
public static extern uint GetPrivateProfileSection(string lpAppName, byte[] lpPairValues, uint nSize, string lpFileName);
[DllImport("kernel32")]
public static extern uint GetPrivateProfileSectionNames(byte[] lpSections, uint nSize, string lpFileName);
#endregion
public static DateTime Delay(int MS)
{
DateTime thisMoment = DateTime.Now;
TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
DateTime afterMoment = thisMoment.Add(duration);
while (afterMoment >= thisMoment)
{
System.Windows.Forms.Application.DoEvents();
thisMoment = DateTime.Now;
}
return DateTime.Now;
}
public static CommConfig IniLoad(string AppPath, CommConfig aConfig)
{
string path;
path = Path.GetDirectoryName(AppPath);
if (aConfig == null)
{
aConfig = new CommConfig();
}
if (File.Exists(String.Format("{0}\\CommSet.ini", path)))
{
StringBuilder ret = new StringBuilder();
string InIPath = String.Format("{0}\\CommSet.ini", path);
// CommType = 0: USBCAN, 1: UARTCAN
aConfig.CommType = (int)csIniControlFunction.GetPrivateProfileInt("COMM TYPE", "TYPE", 0, InIPath);
// SNMP Config
// IP
ret.Clear();
csIniControlFunction.GetPrivateProfileString("SNMP", "IP", "(NONE)", ret, 32, InIPath);
aConfig.SnmpIP = ret.ToString();
// Model
aConfig.SnmpModelIndex = (int)csIniControlFunction.GetPrivateProfileInt("SNMP", "MODEL", 2, InIPath);
// Module Quantity
aConfig.SnmpMdQty = (int)csIniControlFunction.GetPrivateProfileInt("SNMP", "MD_QTY", 2, InIPath);
// CAN Config
// DEVICE
ret.Clear();
aConfig.CanDevice = (int)csIniControlFunction.GetPrivateProfileInt("CAN", "DEVICE", 0, InIPath);
// INDEX
aConfig.CanIndex = (int)csIniControlFunction.GetPrivateProfileInt("CAN", "INDEX", 0, InIPath);
// CAN NO
aConfig.CanNo = (int)csIniControlFunction.GetPrivateProfileInt("CAN", "CAN_NO", 0, InIPath);
// SPEED
aConfig.CanBaudrate = (int)csIniControlFunction.GetPrivateProfileInt("CAN", "BAUDRATE", 0, InIPath);
// MODEL
aConfig.TargetModelIndex = (int)csIniControlFunction.GetPrivateProfileInt("CAN", "MODEL", 0, InIPath);
// UART Config
// PORT
ret.Clear();
csIniControlFunction.GetPrivateProfileString("UART", "PORT", "(NONE)", ret, 32, InIPath);
aConfig.UartPort = ret.ToString();
// SPEED
aConfig.UartBaudrate = (int)csIniControlFunction.GetPrivateProfileInt("UART", "BAUDRATE", 0, InIPath);
// Database Config
ret.Clear();
// Log Period
aConfig.DbLogPeriod = (int)csIniControlFunction.GetPrivateProfileInt("DATABASE", "LOG_PERIOD", 5, InIPath);
// CB Test Config
aConfig.CbTestGap = (int)csIniControlFunction.GetPrivateProfileInt("CB_TEST", "MAX_GAP", 1500, InIPath);
// CB Test Config
aConfig.CbTestTime = (int)csIniControlFunction.GetPrivateProfileInt("CB_TEST", "TIME", 3000, InIPath);
}
else
{
aConfig.CommType = csConstData.CommType.COMM_USBCAN;
// MODEL
aConfig.TargetModelIndex = 0;
// CAN DEVICE
aConfig.CanDevice = 0;
// CAN INDEX
aConfig.CanIndex = 0;
// CAN NO
aConfig.CanNo = 0;
// SPEED
aConfig.CanBaudrate = 0;
// UART PORT
aConfig.UartPort = "";
// SPEED
aConfig.UartBaudrate = 0;
aConfig.DbLogPeriod = 5;
aConfig.CbTestGap = 1500;
aConfig.CbTestTime = 3000;
}
return aConfig;
}
public static void IniSave(string AppPath, CommConfig aConfig)
{
string path = System.IO.Path.GetDirectoryName(AppPath);
string InIPath = String.Format("{0}\\CommSet.ini", path);
// write ini
// CommType = 0: SNMP, 1: UARTCAN, 2: USBCAN
csIniControlFunction.WritePrivateProfileString("COMM TYPE", "TYPE", aConfig.CommType.ToString(), InIPath);
// SNMP Config
// IP
csIniControlFunction.WritePrivateProfileString("SNMP", "IP", aConfig.SnmpIP, InIPath);
// Model
csIniControlFunction.WritePrivateProfileString("SNMP", "MODEL", aConfig.SnmpModelIndex.ToString(), InIPath);
// Module Quantity
csIniControlFunction.WritePrivateProfileString("SNMP", "MD_QTY", aConfig.SnmpMdQty.ToString(), InIPath);
// CAN Config
// DEVICE
csIniControlFunction.WritePrivateProfileString("CAN", "DEVICE", aConfig.CanDevice.ToString(), InIPath);
// INDEX
csIniControlFunction.WritePrivateProfileString("CAN", "INDEX", aConfig.CanIndex.ToString(), InIPath);
// CAN NO
csIniControlFunction.WritePrivateProfileString("CAN", "CAN_NO", aConfig.CanNo.ToString(), InIPath);
// SPEED
csIniControlFunction.WritePrivateProfileString("CAN", "BAUDRATE", aConfig.CanBaudrate.ToString(), InIPath);
// MODEL
csIniControlFunction.WritePrivateProfileString("CAN", "MODEL", aConfig.TargetModelIndex.ToString(), InIPath);
// UART Config
// PORT
csIniControlFunction.WritePrivateProfileString("UART", "PORT", aConfig.UartPort.ToString(), InIPath);
// SPEED
csIniControlFunction.WritePrivateProfileString("UART", "BAUDRATE", aConfig.UartBaudrate.ToString(), InIPath);
// Database Config
// Log Period
csIniControlFunction.WritePrivateProfileString("DATABASE", "LOG_PERIOD", aConfig.DbLogPeriod.ToString(), InIPath);
// CB Test Config
// MAX GAP
csIniControlFunction.WritePrivateProfileString("CB_TEST", "MAX_GAP", aConfig.CbTestGap.ToString(), InIPath);
// TIME
csIniControlFunction.WritePrivateProfileString("CB_TEST", "TIME", aConfig.CbTestTime.ToString(), InIPath);
}
}
}

View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LFP_Manager.DataStructure;
using LFP_Manager.Utils;
namespace LFP_Manager.Function
{
class csMakeDataFunction
{
private static DeviceSystemData MakeAlarmTripData(int id, short ndata, DeviceSystemData rSystemData)
{
bool[] aData = csUtils.Int16ToBitArray(ndata);
short bFault = rSystemData.StatusData.protect;
short bWarning = rSystemData.StatusData.warning;
int i = 0;
switch (id)
{
case 0: // Warning
if (aData[i++]) bWarning |= (1 << 2); // Bit 0 : Over voltage warning
else bWarning &= ~(1 << 2);
if (aData[i++]) bWarning |= (1 << 4); // Bit 1 : Cell Over voltage warning
else bWarning &= ~(1 << 4);
if (aData[i++]) bWarning |= (1 << 3); // Bit 2 : Low voltage warning
else bWarning &= ~(1 << 3);
if (aData[i++]) bWarning |= (1 << 5); // Bit 3 : Low cell voltage warning
else bWarning &= ~(1 << 5);
if (aData[i++]) bWarning |= (1 << 6); // Bit 4 : Charge over current warning
else bWarning &= ~(1 << 6);
if (aData[i++]) bWarning |= (1 << 7); // Bit 5 : Discharge over current warning
else bWarning &= ~(1 << 7);
i++; // 06 Abnormal balancing current
i++; // 07 Reserved
if ((aData[8]) || (aData[9])) bWarning |= (1 << 0); // Bit 8 : Charge over temperature warning, Bit 9 : Discharge over temperature warning
else bWarning &= ~(1 << 0);
i++; // 08
i++; // 09
if ((aData[10]) || (aData[11])) bWarning |= (1 << 1); // Bit 10 : Charge low temperature warning, Bit 11 : Discharge low temperature warning
else bWarning &= ~(1 << 1);
i++; // 10
i++; // 11
if (aData[i++]) bWarning |= (1 << 11); // 12 : Low capacity warning
else bWarning &= ~(1 << 11);
i++; // 13
if (aData[i++]) bWarning |= (1 << 9); // 14 Cell Voltage Difference Warning
else bWarning &= ~(1 << 9);
break;
case 1: // Status Code 2
if (aData[i++]) bFault |= (1 << 2); // Bit 0 : Over voltage warning
else bFault &= ~(1 << 2);
if (aData[i++]) bFault |= (1 << 4); // Bit 1 : Cell Over voltage warning
else bFault &= ~(1 << 4);
if (aData[i++]) bFault |= (1 << 3); // Bit 2 : Low voltage warning
else bFault &= ~(1 << 3);
if (aData[i++]) bFault |= (1 << 5); // Bit 3 : Low cell voltage warning
else bFault &= ~(1 << 5);
if (aData[i++]) bFault |= (1 << 6); // Bit 4 : Charge over current warning
else bFault &= ~(1 << 6);
if (aData[i++]) bFault |= (1 << 7); // Bit 5 : Discharge over current warning
else bFault &= ~(1 << 7);
i++; // 06 Abnormal balancing current
i++; // 07 Reserved
if ((aData[8]) || (aData[9])) bFault |= (1 << 0); // Bit 8 : Charge over temperature warning, Bit 9 : Discharge over temperature warning
else bFault &= ~(1 << 0);
i++; // 08
i++; // 09
if ((aData[10]) || (aData[11])) bFault |= (1 << 1); // Bit 10 : Charge low temperature warning, Bit 11 : Discharge low temperature warning
else bFault &= ~(1 << 1);
i++; // 10
i++; // 11
i++; // 12
i++; // 13
if (aData[i++]) bFault |= (1 << 9); // 14 Cell Voltage Difference Warning
else bFault &= ~(1 << 9);
break;
}
rSystemData.StatusData.protect = bFault;
rSystemData.StatusData.warning = bWarning;
return rSystemData;
}
}
}

View File

@@ -0,0 +1,627 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LFP_Manager.DataStructure;
namespace LFP_Manager.Function
{
public static class csSbCanAPI
{
#region CONST DATA
/*************************************
define
**************************************/
public static bool ISDAR(byte x)
{
return (x & 0x01) != 0x00;
}
public static bool ISABOR(byte x)
{
return (x & 0x02) != 0x00;
}
public static void SETDAR(ref byte x)
{
x |= 0x01;
}
public static void SETABOR(ref byte x)
{
x |= 0x02;
}
// VCP Status Const data
public const byte CS_CANv2_ActiveMode = 0x11;
public const byte CS_CANv2_SetupMode = 0x10;
public const byte uCAN_VCOM = 0x21;
public const byte eCAN_VCOM = 0x31;
public const byte NotConnect = 0x00;
public const byte NotFind = 0xFF;
// CAN
public const byte CR = 0x0D;
// Error Code
public const byte Invalid_Arg = 0x01;
public const byte No_Error = 0x00;
#endregion
public static bool IsSTD(byte format)
{
if ((format & 0x06) == 0x04)
return true;
else
return false;
}
public static bool IsEXT(byte format)
{
if ((format & 0x06) == 0x06)
return true;
else
return false;
}
public static bool IsDATA(byte format)
{
if ((format & 0x05) == 0x04)
return true;
else
return false;
}
public static bool IsREMOTE(byte format)
{
if ((format & 0x05) == 0x05)
return true;
else
return false;
}
public static byte SendCANTxFrame(CAN_Struct Tx, ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
byte ind = 0;
byte tmp_index = 0;
byte[] buf = new byte[40];
switch (Tx.Format)
{
case (byte)CAN_StructFormat.TX_STD_DATA: buf[ind++] = (byte)CAN_SerialCommandHeader.STD_DATA; break;
case (byte)CAN_StructFormat.TX_STD_REMOTE: buf[ind++] = (byte)CAN_SerialCommandHeader.STD_REMOTE; break;
case (byte)CAN_StructFormat.TX_EXT_DATA: buf[ind++] = (byte)CAN_SerialCommandHeader.EXT_DATA; break;
case (byte)CAN_StructFormat.TX_EXT_REMOTE: buf[ind++] = (byte)CAN_SerialCommandHeader.EXT_REMOTE; break;
default: return Invalid_Arg;
}
if (IsSTD(Tx.Format))
tmp_index = 3;
else if (IsEXT(Tx.Format))
tmp_index = 8;
for (int i = 1; i <= tmp_index; i++)
{
buf[ind++] = toASCII_HEX(Div_4(Tx.ID, (byte)(tmp_index - i)));
}
buf[ind++] = toASCII_HEX(Tx.DLC);
if (IsDATA(Tx.Format))
{
for (int i = 0; i < Tx.DLC; i++)
{
buf[ind++] = toASCII_HEX(Div_4(Tx.DATA[i], 1));
buf[ind++] = toASCII_HEX(Div_4(Tx.DATA[i], 0));
}
}
buf[ind++] = CR;
if (ind > BufferSize)
return Invalid_Arg;
ConvertSize = ind;
for (int i = 0; i < ind; i++)
{
SerialBuffer[i] = buf[i];
}
return No_Error;
}
public static byte SetSerialConfig(SerialConfigInfo info, ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
byte len;
byte[] buf = new byte[21];
buf[0] = (byte)'W';
buf[1] = (byte)'S';
switch (info.flow)
{
case (byte)FlowControl.NoFlowControl: buf[2] = (byte)'N'; break;
case (byte)FlowControl.HardwareControl: buf[2] = (byte)'H'; break;
default: return Invalid_Arg;
}
switch (info.data)
{
case (byte)DataBits.Data8: buf[3] = (byte)'8'; break;
default: return Invalid_Arg;
}
switch (info.parity)
{
case (byte)Parity.NoParity: buf[4] = (byte)'N'; break;
case (byte)Parity.EvenParity: buf[4] = (byte)'E'; break;
case (byte)Parity.OddParity: buf[4] = (byte)'O'; break;
case (byte)Parity.SpaceParity: buf[4] = (byte)'S'; break;
case (byte)Parity.MarkParity: buf[4] = (byte)'M'; break;
default: return Invalid_Arg;
}
switch (info.stop)
{
case (byte)StopBits.OneStop: buf[5] = (byte)'1'; break;
case (byte)StopBits.TwoStop: buf[5] = (byte)'2'; break;
default: return Invalid_Arg;
}
byte[] value = new byte[20 - 6];
len = int2ascii(info.Baudrate, ref value, 20 - 6);
if (len == 0)
{
return Invalid_Arg;
}
for (int i = 0; i < len; i++)
buf[6 + i] = value[i];
buf[6 + len] = CR;
if ((len + 7) > BufferSize)
return Invalid_Arg;
ConvertSize = (byte)(len + 7);
for (int i = 0; i < (len + 7); i++)
{
SerialBuffer[i] = buf[i];
}
return No_Error;
}
static byte SetCANConfig(CANConfigInfo info, ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
byte len;
byte ind;
byte[] buf = new byte[31];
byte[] value = new byte[30];
byte function;
function = 0;
buf[0] = (byte)'W';
buf[1] = (byte)'C';
switch (info.Spec)
{
case (byte)CANSpec.CAN_A: buf[2] = (byte)'A'; break;
case (byte)CANSpec.CAN_B: buf[2] = (byte)'B'; break;
default: return Invalid_Arg;
}
buf[3] = (byte)',';
len = int2ascii(info.Baudrate, ref value, 4);
if (len == 0)
{
return Invalid_Arg;
}
for (int i = 0; i < len; i++)
buf[4 + i] = value[i];
buf[len + 4] = (byte)',';
ind = (byte)(len + 5);
len = hex2ID(info.ID, info.Spec, ref value, 8);
if (len == 0)
{
return Invalid_Arg;
}
for (int i = 0; i < len; i++)
buf[ind + i] = value[i];
buf[len + ind] = (byte)',';
ind = (byte)(len + ind + 1);
len = hex2ID(info.Mask, info.Spec, ref value, 8);
if (len == 0)
{
return Invalid_Arg;
}
for (int i = 0; i < len; i++)
buf[ind + i] = value[i];
buf[len + ind] = (byte)',';
ind = (byte)(len + ind + 1);
if (info.DAR)
SETDAR(ref function);
if (info.ABOR)
SETABOR(ref function);
buf[ind++] = toASCII_HEX(function);
buf[ind++] = CR;
if (ind > BufferSize)
return Invalid_Arg;
ConvertSize = ind;
for (int i = 0; i < ind; i++)
SerialBuffer[i] = buf[i];
return No_Error;
}
static byte GetSerialConfig(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (3 > BufferSize)
return Invalid_Arg;
ConvertSize = 3;
SerialBuffer[0] = (byte)'R';
SerialBuffer[1] = (byte)'S';
SerialBuffer[2] = CR;
return No_Error;
}
static byte GetCANConfig(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (3 > BufferSize)
return Invalid_Arg;
ConvertSize = 3;
SerialBuffer[0] = (byte)'R';
SerialBuffer[1] = (byte)'C';
SerialBuffer[2] = CR;
return No_Error;
}
static byte SaveConfig(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (3 > BufferSize)
return Invalid_Arg;
ConvertSize = 3;
SerialBuffer[0] = (byte)'S';
SerialBuffer[1] = (byte)'V';
SerialBuffer[2] = CR;
return No_Error;
}
static byte FirmwareUpgrade(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (3 > BufferSize)
return Invalid_Arg;
ConvertSize = 3;
SerialBuffer[0] = (byte)'F';
SerialBuffer[1] = (byte)'U';
SerialBuffer[2] = CR;
return No_Error;
}
static byte FirmwareVersion(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (3 > BufferSize)
return Invalid_Arg;
ConvertSize = 3;
SerialBuffer[0] = (byte)'F';
SerialBuffer[1] = (byte)'V';
SerialBuffer[2] = CR;
return No_Error;
}
static byte GetErrorInfo(ref byte[] SerialBuffer, byte BufferSize, ref byte ConvertSize)
{
if (1 > BufferSize)
return Invalid_Arg;
ConvertSize = 1;
SerialBuffer[0] = (byte)'!';
return No_Error;
}
static byte ParsingSerialInfo(ref SerialConfigInfo info, ref byte[] SerialBuffer, byte BufferSize)
{
SerialConfigInfo tmp;
UInt32 baudrate;
byte flow, stop, data, parity;
flow = SerialBuffer[0];
data = SerialBuffer[1];
parity = SerialBuffer[2];
stop = SerialBuffer[3];
byte[] bBuf = new byte[BufferSize - 5];
for (int i = 0; i < BufferSize - 5; i++)
bBuf[i] = SerialBuffer[4 + i];
baudrate = ascii2int(ref bBuf, (byte)(BufferSize - 5));
switch (flow)
{
case (byte)'N': tmp.flow = (byte)FlowControl.NoFlowControl; break;
case (byte)'H': tmp.flow = (byte)FlowControl.HardwareControl; break;
default: return Invalid_Arg;
}
switch (data)
{
case (byte)'8': tmp.data = (byte)DataBits.Data8; break;
default: return Invalid_Arg;
}
switch (parity)
{
case (byte)'N': tmp.parity = (byte)Parity.NoParity; break;
case (byte)'E': tmp.parity = (byte)Parity.EvenParity; break;
case (byte)'O': tmp.parity = (byte)Parity.OddParity; break;
case (byte)'S': tmp.parity = (byte)Parity.SpaceParity; break;
case (byte)'M': tmp.parity = (byte)Parity.MarkParity; break;
default: return Invalid_Arg;
}
switch (stop)
{
case (byte)'1': tmp.stop = (byte)StopBits.OneStop; break;
case (byte)'2': tmp.stop = (byte)StopBits.TwoStop; break;
default: return Invalid_Arg;
}
if ((baudrate % 100) > 0)
return Invalid_Arg;
else
{
tmp.Baudrate = baudrate;
}
//*info = tmp;
info = tmp;
return No_Error;
}
static byte ParsingCANInfo(ref CANConfigInfo info, ref byte[] SerialBuffer, byte BufferSize)
{
CANConfigInfo tmp;
byte[] org = new byte[50];
byte[][] tt = new byte[5][];
byte function;
switch (SerialBuffer[0])
{
case (byte)'A':
tmp.Spec = (byte)CANSpec.CAN_A;
if (14 >= BufferSize || BufferSize >= 18)
return Invalid_Arg;
break;
case (byte)'B':
if (24 >= BufferSize || BufferSize >= 28)
return Invalid_Arg;
tmp.Spec = (byte)CANSpec.CAN_B;
break;
default: return Invalid_Arg;
}
org = SerialBuffer;
//for (int i = 0; i < tt.GetLength(0); i++)
// for (int j = 0; j < tt.GetLength(1); j++)
// tt[i, j] = 0x00;
string equation = Encoding.Default.GetString(org);
string[] equationTokens = equation.Split(new char[1] { ',' });
for (int i = 0; i < equationTokens.Length; i++)
{
tt[i] = Encoding.UTF8.GetBytes(equationTokens[i]);
}
tmp.Baudrate = ascii2int(ref tt[0], (byte)tt[0].Length);
tmp.ID = (uint)ascii2ID_Rev(ref tt[1], tmp.Spec);
tmp.Mask = (uint)ascii2ID_Rev(ref tt[2], tmp.Spec);
function = (byte)ascii2int(ref tt[3], 1);
if (function > 255)
return No_Error;
if (ISDAR(function))
tmp.DAR = true;
else
tmp.DAR = false;
if (ISABOR(function))
tmp.ABOR = true;
else
tmp.ABOR = false;
//*info = tmp;
info = tmp;
return No_Error;
}
static byte ParsingErrorInfo(ref CANErorrInfo info, ref byte[] SerialBuffer, byte BufferSize)
{
CANErorrInfo tmp = new CANErorrInfo();
info = tmp;
return No_Error;
}
/**********************************************************************
private functions
**********************************************************************/
static byte Div_8(UInt32 data, byte index)
{
byte ret;
data = data >> (index * 8);
ret = (byte)(data & 0xFF);
return ret;
}
public static int ascii2hex(byte ch)
{
if (0x30 <= ch && ch <= 0x39)
{//0~9
ch &= 0x0f;
return ch;
}
else if (0x61 <= ch && ch <= 0x66)
{ //a~f
ch &= 0x0f;
ch += 9;
return ch;
}
else if (0x41 <= ch && ch <= 0x46)
{ //A~F
ch &= 0x0f;
ch += 9;
return ch;
}
else
return -1;
}
static int ascii2ID_Rev(ref byte[] SourceBuffer, byte idCount)
{
int idTmp = 0;
int tmp = 0, i = 0;
for (i = 0; i < idCount; i++)
{
tmp = ascii2hex(SourceBuffer[i]);
if (tmp != -1)
{
idTmp = idTmp << 4;
idTmp |= tmp;
}
}
return idTmp;
}
static byte Div_4(UInt32 data, byte index)
{
byte ret;
data = data >> (index * 4);
ret = (byte)(data & 0x0F);
return ret;
}
static byte int2ascii(UInt32 val, ref byte[] SourceBuffer, byte size)
{
UInt32 check = 10;
byte su = 1;
if (val < 10)
return 0;
while ((val / check) > 0)
{
su++;
check *= 10;
}
if (su > size)
return 0;
string tmpStr = String.Format("{0}", val);
SourceBuffer = Encoding.UTF8.GetBytes(tmpStr);
return su;
}
static UInt32 ascii2int(ref byte[] SourceBuffer, byte size)
{
UInt32 val = 0;
byte ind = 0;
int ret = 0;
UInt32 mul = 1;
while (ret != -1)
{
ret = ascii2hex(SourceBuffer[ind++]);
}
ind--;
while (ind > 0)
{
ind--;
ret = ascii2hex(SourceBuffer[ind]);
val = (UInt32)(val + (ret * mul));
mul *= 10;
}
return val;
}
static byte hex2ID(UInt32 val, byte idCount, ref byte[] SourceBuffer, byte size)
{
UInt32 comp;
switch (idCount)
{
case (byte)CANSpec.CAN_A: comp = 0x07ff; break;
case (byte)CANSpec.CAN_B: comp = 0x1fffffff; break;
default: return 0;
}
if (val > comp)
return 0;
if (idCount > size)
return 0;
switch (idCount)
{
case (byte)CANSpec.CAN_A: SourceBuffer = Encoding.UTF8.GetBytes(String.Format("{0:X3}", val)); break;
case (byte)CANSpec.CAN_B: SourceBuffer = Encoding.UTF8.GetBytes(String.Format("{0:X8}", val)); break;
default: return 0;
}
return idCount;
}
static byte toASCII_HEX(byte int_hex)
{
byte ret = 0;
if (0 <= int_hex && int_hex <= 9)
{
ret = (byte)('0' + int_hex);
}
else if (0x0A <= int_hex && int_hex <= 0x0F)
{
ret = (byte)('A' + (int_hex % 10));
}
return ret;
}
}
}

File diff suppressed because it is too large Load Diff