Skip to content

Commit

Permalink
Unite old and new chbases
Browse files Browse the repository at this point in the history
  • Loading branch information
KirillGutyrchik committed Oct 25, 2024
1 parent 446d2c4 commit 64b50c0
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public void CheckChbaseSameID_NoAssert()
public void DisableAllChannels()
{
Assert.AreEqual("<channels:enabled>0</channels:enabled><channels:enabled>0</channels:enabled><channels:enabled>0</channels:enabled>",
ChannelBaseTransformer.DisableAllChannels("<channels:enabled>-1</channels:enabled><channels:enabled>-1</channels:enabled><channels:enabled>0</channels:enabled>"));
ChannelBaseTransformer.DisableAllSubtypesChannels("<channels:enabled>-1</channels:enabled><channels:enabled>-1</channels:enabled><channels:enabled>0</channels:enabled>"));
}

[Test]
Expand All @@ -157,7 +157,19 @@ public void GetDeriverID()
Assert.AreEqual(1, ChannelBaseTransformer.GetDriverID(""));
Assert.AreEqual(22, ChannelBaseTransformer.GetDriverID("<driver:id>22</driver:id>"));
});

}

[Test]
public void GetFreeSubtypeID()
{
Assert.AreEqual(5, ChannelBaseTransformer.GetFreeSubtypeID("<subtypes:sid>1</subtypes:sid><subtypes:sid>3</subtypes:sid><subtypes:sid>4</subtypes:sid>"));
}

[Test]
public void ShiftSubtypeID()
{
Assert.AreEqual($"<subtypes:sid>5</subtypes:sid><channels:id>{0x01050001}</channels:id>",
ChannelBaseTransformer.ShiftSubtypeID($"<subtypes:sid>2</subtypes:sid><channels:id>{0x01020001}</channels:id>", 3));
}
}

Expand Down
75 changes: 73 additions & 2 deletions src/ProjectImportICP/ChannelBaseTransformer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public class Tag

public string Property { get; set; }

public string Descr { get; set; }

public string OldID { get; set; }

public string NewID { get; set; }
Expand Down Expand Up @@ -69,6 +71,30 @@ public static string ToWagoDevice(IODevice device)
return "";
}


/// <summary>
///
/// </summary>
/// <param name="newChannelDB"></param>
/// <param name="oldChannelDB"></param>
/// <param name="devices"></param>
/// <returns></returns>
public static string ModifyDescription(string oldChannelDB, string newChannelDB, IEnumerable<(string devName, string wagoName)> devices)
{
var tags = GetNewTagsValueAndState(ParseChannelsBase(newChannelDB));

var namesToReplaced = devices
.Where(d => d.wagoName != string.Empty && d.devName != string.Empty && tags.Any(t => t.Name == d.devName))
.ToDictionary(j => j.wagoName, j => tags.FirstOrDefault(t => t.Name == j.devName).Descr);

var replaceRegex = new Regex($@"(?<=<channels:descr>)(?<wago_name>{string.Join("|", namesToReplaced.Keys)}) :[\w\W]*?(?=<\/channels:descr>)",
RegexOptions.None, TimeSpan.FromMilliseconds(10000));


return replaceRegex.Replace(oldChannelDB, m => namesToReplaced[m.Groups["wago_name"].Value]);
}


/// <summary>
/// Изменить ID новой базы каналов на старые ID тегов
/// </summary>
Expand Down Expand Up @@ -121,6 +147,7 @@ private static IEnumerable<Tag> GetNewTagsValueAndState(IEnumerable<(string desc
{
Name = xml.description.Split('.')[0],
Property = xml.description.Split('.')[1],
Descr = xml.description,
NewID = xml.id
} into tag
where tag.Property == "V" || tag.Property == "ST"
Expand Down Expand Up @@ -186,9 +213,9 @@ from nullableOldTag in allOldTags.DefaultIfEmpty()
/// <summary>
/// Выключить все теги
/// </summary>
public static string DisableAllChannels(string chbase)
public static string DisableAllSubtypesChannels(string chbase)
{
var regex = new Regex(@"(?<=<channels:enabled>)(?:-?\d*?)(?=<\/channels:enabled>)",
var regex = new Regex(@"(?<=<(channels|subtypes):enabled>)(?:-?\d*?)(?=<\/(channels|subtypes):enabled>)",
RegexOptions.None,
TimeSpan.FromMilliseconds(100));

Expand All @@ -209,6 +236,27 @@ public static string ShiftID(string chbase, int bit_offset = 0b1000_0000_0000_00
m => $"{int.Parse(m.Value) | bit_offset}");
}


/// <summary>
/// Сместить типы в базе каналов
/// </summary>
/// <param name="chbase">База каналов</param>
/// <param name="offset">Смещение</param>
public static string ShiftSubtypeID(string chbase, int offset)
{
var replaceTypeSidRegex = new Regex(@"(?<=<subtypes:sid>)\d*?(?=<\/subtypes:sid>)",
RegexOptions.None, TimeSpan.FromMilliseconds(1000));

var replaceIDRegex = new Regex(@"(?<=<channels:id>)\d*?(?=<\/channels:id>)",
RegexOptions.None, TimeSpan.FromMilliseconds(1000));

var idOffset = offset << 16;

chbase = replaceTypeSidRegex.Replace(chbase, m => $"{int.Parse(m.Value) + offset}");
return replaceIDRegex.Replace(chbase, m => $"{int.Parse(m.Value) + idOffset}");
}


/// <summary>
/// Изменить индекс драйвера (также изменяются и ID драйвера всех каналов)
/// </summary>
Expand Down Expand Up @@ -270,5 +318,28 @@ public static int GetDriverID(string chbase)

return 1;
}


/// <summary>
/// Получение первого свободного ID базы каналов
/// </summary>
/// <param name="chbase">Базаф каналов</param>
public static int GetFreeSubtypeID(string chbase)
{
var getSubtypeIDRegex = new Regex(@"(?<=<subtypes:sid>)\d*(?=</subtypes:sid>)",
RegexOptions.None, TimeSpan.FromMilliseconds(100));

var matches = getSubtypeIDRegex.Matches(chbase);

int res = -1;
foreach (Match match in matches)
{
res = Math.Max(res, int.Parse(match.Value));
}

return res + 1;
}


}
}
1 change: 0 additions & 1 deletion src/ProjectImportICP/ModifyChannelsDBDialog.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 39 additions & 26 deletions src/ProjectImportICP/ModifyChannelsDBDialog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace EasyEPlanner.ProjectImportICP
{
Expand Down Expand Up @@ -103,42 +104,62 @@ private void ModifyBttn_Click(object sender, EventArgs e)
var srcPath = SrcChbasePathTextBox.Text;
var dstPath = DstChbasePathTextBox.Text;

var needExport = !File.Exists(dstPath);

if (!File.Exists(srcPath))
return;

// Экспорт новой базы каналов, если ее не существует
if (needExport)
ExportChbase(dstPath);

ExportChbase(dstPath);

// Чтение баз каналов
var srcChbase = ReadFile(srcPath);
var dstChbase = ReadFile(dstPath);

Logs.Clear();
Logs.Show();

// Получение индекса драйвера старой базы каналов
var srcDriverID = ChannelBaseTransformer.GetDriverID(srcChbase);

// Смещение индексов новой базы каналов, для записи старых индексов для избежания повторов
dstChbase = ChannelBaseTransformer.ShiftID(dstChbase);
// Модификация названий устройств старой базы каналов
var modifiedSrcChbase = ChannelBaseTransformer.ModifyDescription(srcChbase, dstChbase, GetDevicesNames());

// Выключение всех тегов базы каналов, нужные будут включены
dstChbase = ChannelBaseTransformer.DisableAllChannels(dstChbase);
// Получение индекса драйвера старой базы каналов
var srcDriverID = ChannelBaseTransformer.GetDriverID(srcChbase);

// Модификация базы каналов
var modifiedDstChbase = ChannelBaseTransformer.ModifyID(dstChbase, srcChbase, GetDevicesNames());
// Смещение типов новой базы каналов для вставки старой
var modifiedDstChbase = ChannelBaseTransformer.ShiftSubtypeID(dstChbase, ChannelBaseTransformer.GetFreeSubtypeID(srcChbase));

// Изменение ID драйвера и всех каналов
modifiedDstChbase = ChannelBaseTransformer.ModifyDriverID(modifiedDstChbase, srcDriverID);

// Проверка совпадения индексов
ChannelBaseTransformer.CheckChbaseID(modifiedDstChbase);
// Выключение всех тегов базы каналов
modifiedDstChbase = ChannelBaseTransformer.DisableAllSubtypesChannels(modifiedDstChbase);

var srcXmlDoc = new XmlDocument();
srcXmlDoc.LoadXml(modifiedSrcChbase);

var dstXmlDoc = new XmlDocument();
dstXmlDoc.LoadXml(modifiedDstChbase);


// Disable all channels except devices
foreach (XmlNode node in srcXmlDoc.GetElementsByTagName("driver:subtypes")[0].ChildNodes)
{
if (int.Parse(node.ChildNodes.OfType<XmlNode>().FirstOrDefault(n => n.Name == "subtypes:sid").InnerText) != 0)
{
node.ChildNodes.OfType<XmlNode>().FirstOrDefault(n => n.Name == "subtypes:enabled").InnerText = "0";

foreach (XmlNode channelsNode in node.ChildNodes.OfType<XmlNode>().FirstOrDefault(n => n.Name == "subtypes:channels").ChildNodes)
{
channelsNode.ChildNodes.OfType<XmlNode>().FirstOrDefault(n => n.Name == "channels:enabled").InnerText = "0";
}
}
}

var subtypesNode = dstXmlDoc.GetElementsByTagName("driver:subtypes")[0];
foreach (XmlNode node in srcXmlDoc.GetElementsByTagName("driver:subtypes")[0].ChildNodes)
{
subtypesNode.InsertBefore(dstXmlDoc.ImportNode(node, true), subtypesNode.FirstChild);
}

using (var writer = new StreamWriter(dstPath, false, Encoding.UTF8))
writer.Write(modifiedDstChbase);
dstXmlDoc.Save(writer);

Logs.SetProgress(100);
Logs.EnableButtons();
Expand Down Expand Up @@ -190,14 +211,6 @@ private static string ReadFile(string path)
return deviceNames;
}

private void DstChbasePathTextBox_TextChanged(object sender, EventArgs e)
{
var fileExists = File.Exists(DstChbasePathTextBox.Text);

CombineTagCmbBx.Enabled = !fileExists;
FormatTagCmbBx.Enabled = !fileExists;
}

private void CancelBttn_Click(object sender, EventArgs e) => Close();
}
}

0 comments on commit 64b50c0

Please sign in to comment.