public VisualHostForPlot(TickParamsAll unpackedParameters, ParameterName parameterName, Rect rect) { //Основные параметры для рисования графика: this.unpackedParameters = unpackedParameters; //массив, содержащий исходные данные this.parameterName = parameterName; //выбранный параметр для построения графика this.rectBounds = rect; //прямоугольник,ограничивающий место на экране для графика //внутри уже нарисованных осей координат _children = new VisualCollection(this) { CreateDrawingVisualPlot() }; }
static void Main(string[] s) { if (s.Length > 1 && File.Exists(s[1])) { Globals.fileName = s[1]; } readAllTheBytes(Globals.fileName); //В переменной readValues находится адрес массива в памяти с данными из файла if (!(s.Length > 0 && Enum.IsDefined(typeof(ParameterName), s[0]))) //по названию параметра не выходит { try { Int32 theEnteredNumber; //parameterNumber = (ParameterName)Int32.Parse(s[0]); bool itIsANumber = Int32.TryParse(s[0], out theEnteredNumber); //проверим с помощью TryParse, //возможно,введён номер параметра вместо его символьного наименования if (itIsANumber & Enum.IsDefined(typeof(ParameterName), theEnteredNumber)) { parameterName = (ParameterName)theEnteredNumber; } else { parameterName = ParameterName.Напряжение_дуги; throw new Exception(); } } catch (Exception e) { //Если введено неверное название параметра Console.WriteLine("Задайте имя(или № байта) параметра и исходный файл в командной строке!"); Environment.Exit(0); } } else { parameterName = (ParameterName)Enum.Parse(typeof(ParameterName), s[0]); } Console.Write("Имя введённого параметра: {0} ", parameterName); Console.WriteLine("Тип параметра {0}", Constants.ParameterData[(int)(parameterName)].parameterType); if (s.Length > 1 && !File.Exists(s[1])) { Console.WriteLine("Отсутствует указанный файл параметров"); return; } if (s.Length > 2) { Console.WriteLine("Будем вводить стартовое время для выдачи параметра"); try { Globals.startOfParameterOutput = TimeSpan.Parse(s[2]); Console.WriteLine("{0} --> {1}", s[2], Globals.startOfParameterOutput.ToString("c")); } catch (FormatException) { Console.WriteLine("{0}: Неправильный формат для начала времени выводв", s[2]); } catch (OverflowException) { Console.WriteLine("{0}: Overflow", s[2]); } } Globals.startTimeOfFileRecording = new DateTime(Int32.Parse(Globals.fileName.Substring(0, 4)), Int32.Parse(Globals.fileName.Substring(4, 2)), Int32.Parse(Globals.fileName.Substring(6, 2))); Globals.startTimeOfFileRecording += Globals.deltaForStartingOfRecord; Console.WriteLine("Start time of writing to the file: {0:D}", Globals.startTimeOfFileRecording); // Would be better new TickParam:IEnumerator(string Globals.fileName) try { int FileMarkerIndex = 0; for (int i = 0; i < Constants.ParamsBlockLengthInBytes; i++) { FileMarkerIndex = 2 * i; if (i != readValues[FileMarkerIndex]) { throw new Exception(); } //FileMarkerIndex++; } if (readValues[FileMarkerIndex + 2] != 0xFF || readValues[FileMarkerIndex + 3] != 0xFB) { throw new Exception(); } } catch { MessageBox.Show("Неверная полная запись в начале файла!"); } //File O.K, let's read it ReadParamFromDisk packedParameters = new ReadParamFromDisk(Globals.fileName); TickParamsAll unpackedParameters = new TickParamsAll(packedParameters); #if OUTPUT_TO_THE_SCREEN Console.WriteLine("Output to the screen from the fully inflated file of parameters"); //выдадим всё в файл! Console.WriteLine("Длина массива = {0}", unpackedParameters.inflatedParameters.Length); //FileStream fs = File.Open(Globals.fileName+".txt",FileMode.Create); File.WriteAllBytes(Globals.fileName + ".bin", unpackedParameters.inflatedParameters); string unitOfMeasure = (string)Constants.ParameterData[(int)(parameterName)].parameterUnit.ToString(); DateTime realDateTime = Globals.startTimeOfFileRecording + TimeSpan.FromSeconds(Globals.startOfParameterOutput.TotalSeconds); short intAssembled; bool stepMode = true; Console.WriteLine("Нажмите любую клавишу для пошагового чтения или ENTER для непрерывной выдачи"); for ( int iParam = (int)parameterName / (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый ? 1:10) + (int)Globals.startOfParameterOutput.TotalSeconds * Constants.ParamsBlockLengthInBytes; iParam < unpackedParameters.inflatedParameters.Length; iParam = iParam + Constants.ParamsBlockLengthInBytes) { //Console.WriteLine("Номер ячейки = {0}",iParam); //обеспечиваем построчную выдачу на экран if (stepMode) { if (Console.ReadKey(true).Key == ConsoleKey.Enter) { stepMode = !stepMode; } } else if (Console.KeyAvailable && ((Console.ReadKey(true).Key == ConsoleKey.Enter) || (Console.ReadKey(true).Key == ConsoleKey.Spacebar))) { stepMode = !stepMode; } /* * for(int i=127;i<unpackedParameters.inflatedParameters.Length;i=i+Constants.ParamsBlockLengthInBytes) * Console.WriteLine( unpackedParameters.inflatedParameters[i]); */ //Выдача на экран построчно заданного в командной строке параметра из заданного файла с заданного момента if (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый) { intAssembled = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam); //Globals.swapBytes(ref intAssembled); switch (Constants.ParameterData[(int)(parameterName)].parameterUnit) { case ParameterUnit._: unitOfMeasure = ""; break; case ParameterUnit.м3_ч: unitOfMeasure = "м3/ч"; break; case ParameterUnit.мм_рт_ст: if (intAssembled < 0) { unitOfMeasure = "мм рт.ст"; intAssembled &= 0x777; } else { unitOfMeasure = "мк"; } break; } Console.WriteLine("Время с начала суток: {0} Значение {1} : {2:N1}{3}", realDateTime, parameterName, (float)intAssembled / 10, unitOfMeasure); } else { bool onOff = ((byte)Constants.ParameterData[(int)(parameterName)].bitMask & unpackedParameters.inflatedParameters[iParam]) > 0; unitOfMeasure = ""; Console.WriteLine("Время с начала суток: {0} Значение {1} : {2:N1}{3}", realDateTime, parameterName, onOff, unitOfMeasure); } realDateTime = realDateTime.AddSeconds(1.0); } #endif }
public void Startup_Procedure(object x, System.EventArgs e) { Console.WriteLine("Запуск главной формы"); Application app = Current; //Считываем с диска файл с параметрами,имя файла запомнено с помощью //механизма ApplicationSettingBase mySettings = new MyUserSettings(); scull_Furnaces_Main_Window = new Scull_Furnaces_Main_Window(); scull_Furnaces_Main_Window.InitializeComponent(); //Устанавливаем имя считываемого файла из сохранённого значания, оно будет обновлятся //после диалога с пользователем TabControlData[0].canvasForDiplayedPlot = scull_Furnaces_Main_Window.voltageGraph; TabControlData[1].canvasForDiplayedPlot = scull_Furnaces_Main_Window.currentGraph; TabControlData[2].canvasForDiplayedPlot = scull_Furnaces_Main_Window.vacuumGraph; TabControlData[3].canvasForDiplayedPlot = scull_Furnaces_Main_Window.waterGraph; scull_Furnaces_Main_Window._remembranceOfFileName.fileName = mySettings.FileName; //записываем его в глобальное поле как для доступа из консольной программы Globals.fileName = scull_Furnaces_Main_Window._remembranceOfFileName.fileName; WriteLine("Считанное имя файла : {0}", Globals.fileName); scull_Furnaces_Main_Window._remembranceOfFileName.PropertyChanged += rememberTheChosenFileName; Globals.readAllTheBytes(Globals.fileName); //проверка файла через чтение его в память и проверку первого блока ReadParamFromDisk packedParameters = new ReadParamFromDisk(Globals.fileName); //повторное чтение файла параметров //в память с инструментарием для работы с ним. unpackedParameters = new TickParamsAll(packedParameters); //получение распакованного массива //File.WriteAllBytes(Globals.fileName+".bin", unpackedParameters.inflatedParameters); //запись на диск //распакованного массива //scull_Furnaces_Main_Window.maxValueForCurrentOnYAxis.Text = mySettings.UpperLimitForCurrent; scull_Furnaces_Main_Window.maxValueForCurrentOnYAxis.DataContext = mySettings; scull_Furnaces_Main_Window.maxValueForVoltageOnYAxis.DataContext = mySettings; scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.Alarm_On = false; //не обнавлять график при начальной установке диапазона времени для отображения scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.Alarm_On = false; //не обнавлять график при начальной установке диапазона времени для отображения scull_Furnaces_Main_Window.begTimeForVoltageOnXAxis.clockWatch.Alarm_On = false; scull_Furnaces_Main_Window.endTimeForVoltageOnXAxis.clockWatch.Alarm_On = false; scull_Furnaces_Main_Window.begTimeOnXAxis.Ticks.Text = mySettings.TimeLowerBoundaryForTheCurrent.ToString(); scull_Furnaces_Main_Window.endTimeOnXAxis.Ticks.Text = mySettings.TimeUpperBoundaryForTheCurrent.ToString(); scull_Furnaces_Main_Window.begTimeForVoltageOnXAxis.Ticks.Text = mySettings.TimeLowerBoundaryForTheVoltage.ToString(); scull_Furnaces_Main_Window.endTimeForVoltageOnXAxis.Ticks.Text = mySettings.TimeUpperBoundaryForTheVoltage.ToString(); scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMinTimeValue; scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMaxTimeValue; scull_Furnaces_Main_Window.begTimeForVoltageOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMinTimeForVoltageValue; scull_Furnaces_Main_Window.endTimeForVoltageOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMaxTimeForVoltageValue; scull_Furnaces_Main_Window.momentOfTime.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setParameterValueOnTheTab; scull_Furnaces_Main_Window.momentOfTime.clockWatch.AlarmProcedure += testAlarm; scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.Alarm_On = true; //обновлять график при изменении нижней границы диапазона времени scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.Alarm_On = true; //обновлять график при изменении верхней границы диапазона времени scull_Furnaces_Main_Window.begTimeForVoltageOnXAxis.clockWatch.Alarm_On = true; scull_Furnaces_Main_Window.endTimeForVoltageOnXAxis.clockWatch.Alarm_On = true; scull_Furnaces_Main_Window.unpackedParameters = this.unpackedParameters; scull_Furnaces_Main_Window.WindowStyle = WindowStyle.ToolWindow; scull_Furnaces_Main_Window.Show(); //Создаём табло с набором дискретных параметров и привязкой каждого из них к свойству parameterState //в обьекте класса ColorSource ParameterAllValues parameterDescription = null; foreach (var pair in ParameterData) { parameterDescription = pair.Value; if (parameterDescription.parameterType == ParameterType.дискретный) { DiscretePlaque btnControl = new DiscretePlaque() { Content = parameterDescription.parameterName }; btnControl.discreteNumber = pair.Key; // the key in the Dictionary remembered ColorSource colorSourceForAParameter = new ColorSource(); //в свойстве parameterState этого объекта храниться состояние дискрета вкл/выкл //опеределяющее цвет привязанного к нему Plaque, информационной таблички-кнопки. parameterDescription.colorBinding.Source = colorSourceForAParameter; parameterDescription.colorBinding.Converter = colorSourceForAParameter; btnControl.SetBinding(Button.BackgroundProperty, parameterDescription.colorBinding); btnControl.Template = (ControlTemplate)scull_Furnaces_Main_Window.FindResource("MyBetterButtonTemplate"); scull_Furnaces_Main_Window.uniGrid.Children.Add(btnControl); } } //Устанаваливаем номер вкладки на окне из сохранённого значения, он будет обновлятся далее //автоматически через привязку BINDING к номеру вкладки в XAML окна scull_Furnaces_Main_Window._typeOfParameters.PropertyChanged += SelectThePageWithParameters; scull_Furnaces_Main_Window._typeOfParameters.PropertyChanged += testSelectPage; scull_Furnaces_Main_Window._typeOfParameters.theNumberOfTab = mySettings.SelectedIndex; TimeMover.numberOfSecond = 0; }
private void currentPlotting(ParameterName parameterName, Canvas canGraph, params AlarmEventArgs[] aea) { const double dashTickLength = 10; const double marginX = 25; const double marginY = 25; const double dashHourTickLength = 12; const double dashHalfHourTickLength = 8; const double dashTenMinuteTickLength = 5; const double dashFiveMinuteTickLength = 3; const double dashMinuteTickLength = 2; const double axisLineThickness = 1; double LowerLimitForTimeOnXAxis; double UpperLimitForTimeOnXAxis; double LowerLimitForCurrentOnYAxis; double UpperLimitForCurrentOnYAxis; GeometryGroup axisX = new GeometryGroup(); GeometryGroup axisY = new GeometryGroup(); TickParamsAll unpackedParameters = app.unpackedParameters; //данные для построения графика Rect rectGraphWithAxesBounds = new Rect(0, 0, 0, 0); //структура для хранения координат внутри части окна, где будет рисоваться график с осями координат, //обозначаними осей, числоввыми значаниями и полями для масштабирования осей Rect rectGraphBounds = new Rect(0, 0, 0, 0); //структура для хранения координат внутри части окна, где будет рисоваться только линия графика this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state) { if (canGraph.ActualWidth == 0) { return(null); } canGraph.Children.Clear(); rectGraphWithAxesBounds.Width = canGraph.ActualWidth; rectGraphWithAxesBounds.Height = canGraph.ActualHeight; double xmin = marginX; double xmax = rectGraphWithAxesBounds.Width - marginX; double ymin = marginY; double ymax = rectGraphWithAxesBounds.Height - marginY; //вызов может быть 1) с часов, 2) при начальном запуске программы, 3) при смене файла для отображения параметров switch (aea.Length) { case 1: LowerLimitForTimeOnXAxis = aea[0].TicksToAlarm; //изиенение нижней границы интервала времени UpperLimitForTimeOnXAxis = Int32.Parse(this.endTimeOnXAxis.Ticks.Text); break; case 2: LowerLimitForTimeOnXAxis = Int32.Parse(this.begTimeOnXAxis.Ticks.Text); UpperLimitForTimeOnXAxis = aea[1].TicksToAlarm; //изиенение верхней границы интервала времени break; default: LowerLimitForTimeOnXAxis = Int32.Parse(this.begTimeOnXAxis.Ticks.Text); //интервал времени берётся непосредственно с часов, UpperLimitForTimeOnXAxis = Int32.Parse(this.endTimeOnXAxis.Ticks.Text); // вызов пришёл при выполнении условий 2) или 3) break; } LowerLimitForCurrentOnYAxis = 0; UpperLimitForCurrentOnYAxis = Int32.Parse(maxValueForCurrentOnYAxis.Text); axisX = new GeometryGroup(); axisY = new GeometryGroup(); PrepareTransformations( LowerLimitForTimeOnXAxis, UpperLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis, UpperLimitForCurrentOnYAxis, xmin, xmax, ymin, ymax ); rectGraphBounds.X = xmin; rectGraphBounds.Y = ymin; rectGraphBounds.Width = xmax; rectGraphBounds.Height = ymax; double step = Math.Round((xmax - xmin) / (24 * 6)); axisX = new GeometryGroup(); axisX.Children.Add(new LineGeometry(WtoD(new Point(LowerLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis)), WtoD(new Point(UpperLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis)))); //Расставляем часовые деления на оси X //Расставляем получасовые деления на оси X //Расставляем 10-минутные деления на оси X //Для крупного масштаба расставляем 5 - минутные //и минутные деления. Action <string, Point, HorizontalAlignment, VerticalAlignment> PutLabel = DrawText; PutTimeTicks(3600, dashHourTickLength, PutLabel); PutLabel = null; PutTimeTicks(1800, dashHalfHourTickLength, PutLabel); PutTimeTicks(600, dashTenMinuteTickLength, PutLabel); if ((UpperLimitForTimeOnXAxis - LowerLimitForTimeOnXAxis) / 3600 <= 2) { PutTimeTicks(300, dashFiveMinuteTickLength, PutLabel); PutTimeTicks(60, dashMinuteTickLength, PutLabel); } Path axisX_path = new Path(); axisX_path.StrokeThickness = axisLineThickness; axisX_path.Stroke = Brushes.Black; axisX_path.Data = axisX; axisY = new GeometryGroup(); PutYTicks(10, 10.0, null); axisY.Children.Add(new LineGeometry(new Point(xmin, ymin), new Point(xmin, ymax))); for (double y = ymax; y >= ymin; y -= step) { if (Math.Round((ymax - y) / step) % 10 == 0) { axisY.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + 2 * dashTickLength, y)) ); } else if (Math.Round((ymax - y) / step) % 5 == 0) { axisY.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength, y)) ); } else { axisY.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength / 2, y)) ); } } Path axisY_path = new Path(); axisY_path.StrokeThickness = 1; axisY_path.Stroke = Brushes.Black; axisY_path.Data = axisY; canGraph.Children.Add(axisX_path); canGraph.Children.Add(axisY_path); WriteLine("Adding VisualHostForPlot_1 to the Children collection of the Canvas"); canGraph.Children.Add(new VisualHostForPlot_1(unpackedParameters, parameterName, rectGraphBounds)); return(null); }), null); void PutTimeTicks(int IntervalInSeconds, double TickLength, Action <string, Point, HorizontalAlignment, VerticalAlignment> PutLabel) { Point onX_axis; Point overX_axis; for (double Dash = TickMeasure(LowerLimitForTimeOnXAxis); Dash < UpperLimitForTimeOnXAxis; Dash += IntervalInSeconds) { onX_axis = WtoD(new Point(Dash, LowerLimitForCurrentOnYAxis)); overX_axis = onX_axis; overX_axis.Y -= TickLength; axisX.Children.Add(new LineGeometry ( onX_axis, overX_axis ) ); Point underX_axis = onX_axis; underX_axis.Y = overX_axis.Y; if (PutLabel != null) { PutLabel(((int)Dash / IntervalInSeconds).ToString(), underX_axis, HorizontalAlignment.Center, VerticalAlignment.Top); } } double TickMeasure(double timeInSeconds) { return((((int)timeInSeconds / IntervalInSeconds) + ((timeInSeconds % IntervalInSeconds == 0) ? 0:1)) * IntervalInSeconds); } } void PutYTicks(int IntervalInAmperes, double TickLength, Action <string, Point, HorizontalAlignment, VerticalAlignment> PutLabel) { Point onY_axis; Point right_toY_axis; for (double Dash = TickMeasure(LowerLimitForCurrentOnYAxis); Dash < UpperLimitForCurrentOnYAxis; Dash += IntervalInAmperes) { onY_axis = WtoD(new Point(LowerLimitForTimeOnXAxis, Dash)); right_toY_axis = onY_axis; right_toY_axis.Y += TickLength; axisX.Children.Add(new LineGeometry ( onY_axis, right_toY_axis ) ); Point left_toY_axis = onY_axis; left_toY_axis.Y = right_toY_axis.Y; if (PutLabel != null) { PutLabel(((int)Dash / IntervalInAmperes).ToString(), left_toY_axis, HorizontalAlignment.Center, VerticalAlignment.Top); } } double TickMeasure(double CurrentInAmperes) { return((((int)CurrentInAmperes / IntervalInAmperes) + ((CurrentInAmperes % IntervalInAmperes == 0) ? 0 : 1)) * IntervalInAmperes); } } void DrawText(string text, Point location, HorizontalAlignment halign, VerticalAlignment valign) { // Make the label. Label label = new Label(); label.Content = text; canGraph.Children.Add(label); // Position the label. label.Measure(new Size(double.MaxValue, double.MaxValue)); double x = location.X; if (halign == HorizontalAlignment.Center) { x -= label.DesiredSize.Width / 2; } else if (halign == HorizontalAlignment.Right) { x -= label.DesiredSize.Width; } Canvas.SetLeft(label, x); double y = location.Y; if (valign == VerticalAlignment.Center) { y += label.DesiredSize.Height / 2; } else if (valign == VerticalAlignment.Bottom) { y += label.DesiredSize.Height; } else { y += label.DesiredSize.Height / 6; } Canvas.SetTop(label, y); } }
private void vacuumPlotting(ParameterName parameterName, Canvas canGraph) { TickParamsAll unpackedParameters = app.unpackedParameters; //данные для построения графика Rect rectBounds = new Rect(0, 0, 0, 0); //структура для хранения координат внутри части окна, где будет рисоваться график this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state) { if (canGraph.ActualWidth == 0) { return(null); } canGraph.Children.Clear(); rectBounds.Width = canGraph.ActualWidth; rectBounds.Height = canGraph.ActualHeight; const double dashTickLength = 10; const double marginX = 10; const double marginY = 10; double xmin = marginX; double xmax = rectBounds.Width - marginX; double ymin = marginY; double ymax = rectBounds.Height - marginY; double step = Math.Round((xmax - xmin) / (24 * 6)); double dotsPerSecond = (xmax - xmin) / SecondsInADay; int intSecondsPerDot = (int)(SecondsInADay / (xmax - xmin)); double dotsPerVolt = 100 * step / 100; // Make the X axis. GeometryGroup axis_X_geom = new GeometryGroup(); axis_X_geom.Children.Add(new LineGeometry(new Point(xmin, ymax), new Point(xmax, ymax))); for (double x = xmin + step; x <= xmax; x += step) { if ((x - xmin) / step % 6 == 0) { axis_X_geom.Children.Add(new LineGeometry ( new Point(x, ymax - dashTickLength), new Point(x, ymax)) ); } else { axis_X_geom.Children.Add(new LineGeometry ( new Point(x, ymax - dashTickLength / 2), new Point(x, ymax)) ); } } Path axis_X_path = new Path(); axis_X_path.StrokeThickness = 1; axis_X_path.Stroke = Brushes.Black; axis_X_path.Data = axis_X_geom; canGraph.Children.Add(axis_X_path); // Make the Y ayis. GeometryGroup axis_Y_geom = new GeometryGroup(); axis_Y_geom.Children.Add(new LineGeometry(new Point(xmin, ymin), new Point(xmin, ymax))); for (double y = ymax; y >= ymin; y -= step) { if (Math.Round((ymax - y) / step) % 10 == 0) { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + 2 * dashTickLength, y)) ); } else if (Math.Round((ymax - y) / step) % 5 == 0) { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength, y)) ); } else { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength / 2, y)) ); } } Path axis_Y_path = new Path(); axis_Y_path.StrokeThickness = 1; axis_Y_path.Stroke = Brushes.Black; axis_Y_path.Data = axis_Y_geom; canGraph.Children.Add(axis_Y_path); canGraph.Children.Add(new VisualHostForPlot(unpackedParameters, parameterName, rectBounds)); return(null); }), null); }
private void waterPlotting(ParameterName parameterName, Canvas canGraph) { TickParamsAll unpackedParameters = app.unpackedParameters; //данные для построения графика Rect rectBounds = new Rect(0, 0, 0, 0); //структура для хранения координат внутри части окна, где будет рисоваться график this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state) { if (canGraph.ActualWidth == 0) { return(null); } canGraph.Children.Clear(); rectBounds.Width = canGraph.ActualWidth; rectBounds.Height = canGraph.ActualHeight; const double dashTickLength = 10; const double marginX = 10; const double marginY = 10; double xmin = marginX; double xmax = rectBounds.Width - marginX; double ymin = marginY; double ymax = rectBounds.Height - marginY; double step = Math.Round((xmax - xmin) / (24 * 6)); string unitOfMeasure; double dotsPerSecond = (xmax - xmin) / SecondsInADay; int intSecondsPerDot = (int)(SecondsInADay / (xmax - xmin)); double dotsPerVolt = 100 * step / 100; // Make the X axis. GeometryGroup axis_X_geom = new GeometryGroup(); axis_X_geom.Children.Add(new LineGeometry(new Point(xmin, ymax), new Point(xmax, ymax))); for (double x = xmin + step; x <= xmax; x += step) { if ((x - xmin) / step % 6 == 0) { axis_X_geom.Children.Add(new LineGeometry ( new Point(x, ymax - dashTickLength), new Point(x, ymax)) ); } else { axis_X_geom.Children.Add(new LineGeometry ( new Point(x, ymax - dashTickLength / 2), new Point(x, ymax)) ); } } Path axis_X_path = new Path(); axis_X_path.StrokeThickness = 1; axis_X_path.Stroke = Brushes.Black; axis_X_path.Data = axis_X_geom; canGraph.Children.Add(axis_X_path); // Make the Y ayis. GeometryGroup axis_Y_geom = new GeometryGroup(); axis_Y_geom.Children.Add(new LineGeometry(new Point(xmin, ymin), new Point(xmin, ymax))); for (double y = ymax; y >= ymin; y -= step) { if (Math.Round((ymax - y) / step) % 10 == 0) { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + 2 * dashTickLength, y)) ); } else if (Math.Round((ymax - y) / step) % 5 == 0) { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength, y)) ); } else { axis_Y_geom.Children.Add(new LineGeometry ( new Point(xmin, y), new Point(xmin + dashTickLength / 2, y)) ); } } Path axis_Y_path = new Path(); axis_Y_path.StrokeThickness = 1; axis_Y_path.Stroke = Brushes.Black; axis_Y_path.Data = axis_Y_geom; canGraph.Children.Add(axis_Y_path); #if POLYLINE //Значения для графика тока подтягиваются сюда. //Для рисования через Polyline points = new PointCollection(); int numSec = 0; short intAssembled; double realValueOfFunction; double peakAtInterval = 0; //максимальное значение функции на интервале double bottomAtInterval = Int32.MaxValue; //минимальное значение функции на интервале Point begPoint = new Point(xmin, ymax); Point endPoint = new Point(xmin, ymax); bool theFirstDotInPair = true; for ( int iParam = (int)parameterName / (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый ? 1:10) + (int)Globals.startOfParameterOutput.TotalSeconds * Constants.ParamsBlockLengthInBytes; iParam < unpackedParameters.inflatedParameters.Length; iParam = iParam + Constants.ParamsBlockLengthInBytes) { if (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый) { intAssembled = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam); realValueOfFunction = (double)intAssembled / 10; switch (Constants.ParameterData[(int)(parameterName)].parameterUnit) { case ParameterUnit._: unitOfMeasure = ""; break; case ParameterUnit.м3_ч: unitOfMeasure = "м3/ч"; break; case ParameterUnit.мм_рт_ст: if (intAssembled < 0) { unitOfMeasure = "мм рт.ст"; intAssembled &= 0x777; } else { unitOfMeasure = "мк"; } break; } } else { throw new Exception(); } //* if (peakAtInterval < realValueOfFunction) { peakAtInterval = realValueOfFunction; } if (bottomAtInterval > realValueOfFunction) { bottomAtInterval = realValueOfFunction; } if (numSec % intSecondsPerDot == 0) { //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале //но надо отмечать и МИНИМАЛЬНОЕ ! if (!theFirstDotInPair) { points.Add(new Point(xmin + (numSec - 1) * dotsPerSecond, ymax - dotsPerVolt * bottomAtInterval)); points.Add(new Point(xmin + (numSec) * dotsPerSecond, ymax - dotsPerVolt * peakAtInterval)); //points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval)); peakAtInterval = 0; bottomAtInterval = Int32.MaxValue; theFirstDotInPair = true; } else { theFirstDotInPair = false; } } /* else * if(numSec%intSecondsPerDot==(int)(intSecondsPerDot/2)) * { * //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале * //но надо отмечать и МИНИМАЛЬНОЕ ! * points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval)); * bottomAtInterval = Int32.MaxValue; * } */ //* /*endPoint = new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval); * plotGeometry.Children.Add(new LineGeometry(begPoint,endPoint)); * WriteLine("Dot number {0}",numSec ); * endPoint = begPoint; * points.Add( new Point(xmin +(numSec++)*dotsPerSecond,ymax - dotsPerVolt*(double)intAssembled/10));*/ numSec++; } Polyline polyline1 = new Polyline(); polyline1.StrokeThickness = 1; polyline1.Stroke = Brushes.Red; polyline1.Points = points; canGraph.Children.Add(polyline1); #else canGraph.Children.Add(new VisualHostForPlot(unpackedParameters, parameterName, rectBounds)); #endif return(null); }), null); }
public void setParameterValueOnTheTab(AlarmEventArgs aea) { TickParamsAll unpackedParameters = app.unpackedParameters; short intAssembled; TabData tab = TabControlData[_typeOfParameters.theNumberOfTab]; if ((tab.parameterType) == (ParameterType.дискретный)) { TimeMover.numberOfSecond = aea.TicksToAlarm; instantParameterValue.Visibility = Visibility.Collapsed; instantParameterName.Visibility = Visibility.Collapsed; } else //устанавливается значение аналогового параметра //при выборе вкладки или изменении значения таймера { int iParam = (int)tab.parameterName + aea.TicksToAlarm * Constants.ParamsBlockLengthInBytes; System.Console.WriteLine("iParam = {0}", iParam); intAssembled = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam); //Globals.swapBytes(ref intAssembled); string unitOfMeasure; switch (Constants.ParameterData[(int)(tab.parameterName)].parameterUnit) { case ParameterUnit._: unitOfMeasure = ""; break; case ParameterUnit.м3_ч: unitOfMeasure = "м3/ч"; break; case ParameterUnit.мм_рт_ст: if (intAssembled < 0) { unitOfMeasure = "мм рт.ст"; intAssembled &= 0x777; } else { unitOfMeasure = "мк"; } break; default: unitOfMeasure = ""; break; } if (tab.canvasForDiplayedPlot != null) { Console.WriteLine(tab.canvasForDiplayedPlot.Name); } if (tab.canvasForDiplayedPlot != null) { doTheLineDrawing(tab.canvasForDiplayedPlot, WtoD(new Point(aea.TicksToAlarm, 0)), tab); } instantParameterValue.Visibility = Visibility.Visible; instantParameterName.Visibility = Visibility.Visible; instantParameterValue.Content = String.Format("{0} " + unitOfMeasure, (float)intAssembled / 10); instantParameterName.Content = tab.parameterNameToDisplay; } }
public void Startup_Procedure(object x, System.EventArgs e) { Console.WriteLine("Запуск главной формы"); Application app = Current; //Считываем с диска файл с параметрами,имя файла запомнено с помощью //механизма ApplicationSettingBase mySettings = new MyUserSettings(); scull_Furnaces_Main_Window = new Scull_Furnaces_Main_Window(); scull_Furnaces_Main_Window.InitializeComponent(); //Устанавливаем имя считываемого файла из сохранённого значания, оно будет обновлятся //после диалога с пользователем scull_Furnaces_Main_Window._remembranceOfFileName.fileName = mySettings.FileName; //записываем его в глобальное поле как для доступа из консольной программы Globals.fileName = scull_Furnaces_Main_Window._remembranceOfFileName.fileName; WriteLine("Считанное имя файла : {0}", Globals.fileName); scull_Furnaces_Main_Window._remembranceOfFileName.PropertyChanged += rememberTheChosenFileName; Globals.readAllTheBytes(Globals.fileName); //проверка файла через чтение его в память и проверку первого блока ReadParamFromDisk packedParameters = new ReadParamFromDisk(Globals.fileName); //повторное чтение файла параметров //в память с инструментарием для работы с ним. unpackedParameters = new TickParamsAll(packedParameters); //получение распакованного массива //File.WriteAllBytes(Globals.fileName+".bin", unpackedParameters.inflatedParameters); //запись на диск //распакованного массива //scull_Furnaces_Main_Window.maxValueForCurrentOnYAxis.Text = mySettings.UpperLimitForCurrent; scull_Furnaces_Main_Window.maxValueForCurrentOnYAxis.DataContext = mySettings; scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.Alarm_On = false; //не обнавлять график при начальной установке диапазона времени для отображения scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.Alarm_On = false; //не обнавлять график при начальной установке диапазона времени для отображения scull_Furnaces_Main_Window.begTimeOnXAxis.Ticks.Text = mySettings.TimeLowerBoundaryForTheCurrent.ToString(); scull_Furnaces_Main_Window.endTimeOnXAxis.Ticks.Text = mySettings.TimeUpperBoundaryForTheCurrent.ToString(); scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMinTimeValue; scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.AlarmProcedure += scull_Furnaces_Main_Window.setMaxTimeValue; scull_Furnaces_Main_Window.begTimeOnXAxis.clockWatch.Alarm_On = true; //обновлять график при изменении нижней границы диапазона времени scull_Furnaces_Main_Window.endTimeOnXAxis.clockWatch.Alarm_On = true; //обновлять график при изменении верхней границы диапазона времени scull_Furnaces_Main_Window.WindowStyle = WindowStyle.ToolWindow; scull_Furnaces_Main_Window.Show(); ParameterAllValues parameterDescription = null; foreach (var pair in ParameterData) { parameterDescription = pair.Value; if (parameterDescription.parameterType == ParameterType.дискретный) { DiscretePlaque btnControl = new DiscretePlaque() { Content = parameterDescription.parameterName }; btnControl.discreteNumber = pair.Key; // the key in the Dictionary remembered //Binding colorBindingForAParameter = new Binding("parameterState"); //to the parameterDesription !!! Binding colorBindingForAParameter = parameterDescription.colorBinding; ColorSource colorSourceForAParameter = new ColorSource(); colorBindingForAParameter.Source = colorSourceForAParameter; //put the Binding into initial state, setting the parameterState in colorSourceForAParameter in accordance with the parameter value being read from disk colorBindingForAParameter.Converter = colorSourceForAParameter; btnControl.SetBinding(Button.BackgroundProperty, colorBindingForAParameter); btnControl.Template = (ControlTemplate)scull_Furnaces_Main_Window.FindResource("MyBetterButtonTemplate"); //btnControl.discreteNumber - ?? how to define ? the number in [] scull_Furnaces_Main_Window.uniGrid.Children.Add(btnControl); } } //Устанаваливаем номер вкладки на окне из сохранённого значения, он будет обновлятся далее //автоматически через привязку BINDING к номеру вкладки в XAML окна scull_Furnaces_Main_Window._typeOfParameters.PropertyChanged += rememberThePageWithParameters; scull_Furnaces_Main_Window._typeOfParameters.theNumberOfTab = mySettings.SelectedIndex; TimeMover.numberOfSecond = 1; //Начинаем просмотр дискретов с 1 секунды! }