// Use this for initialization void Start () { int score = ScoreKeeper.instance.score; int size = QuizListManager.instance.quizList.Count; string result = size + "問中" + score + "問正解!!"; HistoryData historyData = new HistoryData (); historyData.Average = ((double)score / (double)size) * 100; historyData.result = result; historyData.date = DateTime.Now.ToString ("yyyy/MM/dd (ddd) HH:mm:ss"); historyData.title = SelectedQuiz.instance.Name; historyData.mode = QuizListManager.instance.modeName; HistoryDataDao.instance.InsertHistoryData (historyData); mAverage = ((double)score / (double)size) * 100; resultLabelArray [0].GetComponent<UILabel> ().text = SelectedQuiz.instance.Name; resultLabelArray [1].GetComponent<UILabel> ().text = QuizListManager.instance.modeName; resultLabelArray [2].GetComponent<UILabel> ().text = result; resultLabelArray [3].GetComponent<UILabel> ().text = "\u6b63\u89e3\u7387 : " + Math.Round (mAverage) + "%"; foreach (GameObject item in resultLabelArray) { iTweenEvent.GetEvent (item, "EntranceEvent").Play (); } if(Application.internetReachability != NetworkReachability.NotReachable){ Invoke ("OpenWallAd",3.0f); } }
public void InsertHistoryData (HistoryData historyData) { SQLiteDB sqliteDB = OpenDB (); string sql = CreateInsertSQL (historyData); SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, sql); sqliteQuery.Step (); sqliteDB.Close (); }
private string CreateInsertSQL (HistoryData historyData) { StringBuilder sb = new StringBuilder (); sb.Append ("insert into " + TABLE_NAME + " values("); sb.Append ("null ,"); sb.Append (historyData.Average + " ,"); sb.Append ("'" + historyData.title + "',"); sb.Append ("'" + historyData.mode + "',"); sb.Append ("'" + historyData.result + "',"); sb.Append ("'" + historyData.date + "'"); sb.Append (");"); return sb.ToString (); }
public IList<HistoryData> QueryHistoryDataList () { IList<HistoryData> historyDataList = new List<HistoryData> (); SQLiteDB sqliteDB = OpenDB (); string sql = "select * from " + TABLE_NAME + ";"; SQLiteQuery sqliteQuery = new SQLiteQuery (sqliteDB, sql); while (sqliteQuery.Step ()) { HistoryData historyData = new HistoryData (); historyData.id = sqliteQuery.GetInteger (ID_FIELD); historyData.Average = sqliteQuery.GetDouble (AVERAGE_FIELD); historyData.title = sqliteQuery.GetString (TITLE_FIELD); historyData.mode = sqliteQuery.GetString (MODE_FIELD); historyData.result = sqliteQuery.GetString (RESULT_FIELD); historyData.date = sqliteQuery.GetString (DATE_FIELD); historyDataList.Add (historyData); } return historyDataList; }
public List<HistoryData> GetHistoryDataList () { List<HistoryData> historyDataList = new List<HistoryData> (); for (int i = 1; i<=4; i++) { HistoryData historyData = new HistoryData (); System.DateTime dateTimeNow = System.DateTime.Now; System.Text.StringBuilder sb = new System.Text.StringBuilder (); sb.Append (dateTimeNow.Month + "/"); sb.Append (dateTimeNow.Day + " "); sb.Append(dateTimeNow.Hour+":"); sb.Append(dateTimeNow.Minute); historyData.Id = i; historyData.EnemyId = i; historyData.Result = "result"; historyData.Date = sb.ToString (); historyDataList.Add (historyData); } return historyDataList; }
public void Init (HistoryData historyData) { mHistoryData = historyData; StringBuilder sb = new StringBuilder (); sb.Append (historyData.date + "\n"); sb.Append (historyData.title + " | " + historyData.mode + "\n"); sb.Append (historyData.result); historyLabel.text = sb.ToString (); double average = mHistoryData.Average; Debug.Log("average = "+ average); if(average >=100){ medalSprite.spriteName = "01.gold"; }else if(average >= 90){ medalSprite.spriteName = "02.silver"; }else if(average >= 80){ medalSprite.spriteName = "03.bronze"; }else if(average <=15){ medalSprite.spriteName = "04.0"; }else { medalSprite.enabled = false; } if(historyData.flagTweet == 1){ tweetButton.SetActive (false); } }
public bool RecieveData(string data) //when sendmessge arrived WM_COPYDATA { int index = data.IndexOf('#'); //格式:GroupID#TagID:Value|TagID:Value|TagID:Value if (index > 0 && data.Substring(0, index) == _id.ToString()) { string[] strs = data.Right(index).Split('|'); HistoryData[] hdata = new HistoryData[strs.Length]; DateTime date = DateTime.Now; int i = 0; foreach (string d in strs) { int ind = d.IndexOf(':'); if (ind > 0) { short tid; if (short.TryParse(data.Substring(0, ind), out tid)) { ITag tag = _server[tid]; if (tag != null) { Storage value = Storage.Empty; DataType type = tag.Address.VarType; switch (type) { case DataType.BOOL: value.Boolean = Convert.ToBoolean(d.Right(ind)); break; case DataType.BYTE: value.Byte = Convert.ToByte(d.Right(ind)); break; case DataType.WORD: value.Word = Convert.ToUInt16(d.Right(ind)); break; case DataType.SHORT: value.Int16 = Convert.ToInt16(d.Right(ind)); break; case DataType.DWORD: value.DWord = Convert.ToUInt32(d.Right(ind)); break; case DataType.INT: value.Int32 = Convert.ToInt32(d.Right(ind)); break; case DataType.FLOAT: value.Single = Convert.ToSingle(d.Right(ind)); break; case DataType.STR: break; } tag.Update(value, date, QUALITIES.QUALITY_GOOD);//也可以不传值,tag自身refresh hdata[i].ID = tag.ID; hdata[i].Value = value; hdata[i].TimeStamp = date; hdata[i].Quality = QUALITIES.QUALITY_GOOD; } } } i++; } if (DataChange != null) { foreach (DataChangeEventHandler deleg in DataChange.GetInvocationList()) { deleg.BeginInvoke(this, new DataChangeEventArgs(1, hdata), null, null); } } return(true); } return(false); }
//------------------------------------------------------------------------------- // protected override void OnLoad(EventArgs e) { base.OnLoad(e); //tabTwitDisp.SelectedIndex = 0; _settingsDataPath = Utilization.GetDefaultSettingsDataFilePath(); SettingsData = SettingsData.Restore(_settingsDataPath); if (SettingsData == null) { SettingsData = new SettingsData(); } _historyDataPath = "history.xml"; HistoryData = HistoryData.Restore(_historyDataPath); if (HistoryData == null) { HistoryData = new HistoryData(); } _shortcutDataPath = "shortcut.xml"; ShortcutKeyData = ShortcutKeyData.Restore(_shortcutDataPath); if (ShortcutKeyData == null) { ShortcutKeyData = ShortcutKeyData.DefaultData(); } // ↓設定を復元↓ ConfigTabAndUserDispControl(tabpgHome, uctlDispHome); ConfigTabAndUserDispControl(tabpgReply, uctlDispReply); ConfigTabAndUserDispControl(tabpgHistory, uctlDispHistory); ConfigTabAndUserDispControl(tabpgDirect, uctlDispDirect); /*ConfigTabAndUserDispControl(tabpgPublic, uctlDispPublic);*/ foreach (TabPage tabpage in DEFAULT_TABPAGES) { tabpage.ToolTipText = DefaultTabToString(tabpage); } foreach (TabData tabdata in SettingsData.TabDataDic.Values) { MakeTab(tabdata, false); } if (SettingsData.UserInfoList.Count > 0) { Twitter.SetUser(SettingsData.UserInfoList[0].AccessToken, SettingsData.UserInfoList[0].AccessTokenSecret, SettingsData.UserInfoList[0].ScreenName, SettingsData.UserInfoList[0].ID); TransitToAuthenticatedMode(); } else { _isAuthenticated = false; } InitializeControls(); // スレッド作成 _bgThread = new Thread(AutoGetTweet); _bgThread.IsBackground = true; _bgThread.Name = "AutoGetThread"; //_bgThread.SetApartmentState(ApartmentState.STA); _bgThread.Start(); }
public DataViewGraph() { dataHistoryArray = new HistoryData(10); DoubleBuffer = true; }
private void LocalHandler(int gameId, PackedResult result) { var worldId = pool.GetContext(gameId).World; if (result.Type == PackedResultType.MarketRequest) { var itemid = ((MarketRequestResult)result.Result).ItemId; Task.Run(() => { RETRY: int ret = 0; var listing = new List <ListingData>(); var history = new List <HistoryData>(); PackedResultBundle res = null; try { var local = new ExchangeProcedure(); try { ret = local.Step2(itemid, out res); } catch (HttpRequestException exception) { ret = 02_0000 + (int)exception.Data["StatusCode"]; } if (!CheckVendor.NotValidResponseCode(ret)) { listing.AddRange(res.Listings.Select(x => ListingData.FromResultItem(x.RawItem, x.ReportTime, 0, x.WorldId))); history.AddRange(res.Histories.Select(x => HistoryData.FromResultItem(x.RawItem, x.ReportTime, 0, x.WorldId))); } if (ret % 10000 == 0511 && ApiVendor.ValidateAndRenewToken()) { goto RETRY; } var lst = (List <ListingData>)DataHolder.GetCache(worldId, itemid, 0); var hst = (List <HistoryData>)DataHolder.GetCache(worldId, itemid, 1); if (lst != null) { listing.RemoveAll(x => x.World == worldId); br.OverlayListingData = listing.Concat(lst) .OrderBy(x => x.UnitPrice).ToList(); } else { lst = br.OverlayListingData.Where(x => x.World == worldId && x.ItemId == itemid).ToList(); if (lst.Any()) { listing.RemoveAll(x => x.World == worldId); br.OverlayListingData = listing.Concat(lst) .OrderBy(x => x.UnitPrice).ToList(); } br.OverlayListingData = listing.OrderBy(x => x.UnitPrice).ToList(); } if (hst != null) { history.RemoveAll(x => x.World == worldId); br.OverlayHistoryData = history.Concat(hst) .OrderByDescending(x => x.PurchaseTime).ToList(); } else { hst = br.OverlayHistoryData.Where(x => x.World == worldId && x.ItemId == itemid).ToList(); if (hst.Any()) { history.RemoveAll(x => x.World == worldId); br.OverlayHistoryData = history.Concat(hst) .OrderByDescending(x => x.PurchaseTime).ToList(); } br.OverlayHistoryData = history.OrderByDescending(x => x.PurchaseTime).ToList(); } } catch (HttpRequestException ex) { ret = 02_0000 + (int)(ex.Data["StatusCode"]); if (ret == 02_0511 && ApiVendor.ValidateAndRenewToken()) { goto RETRY; } } catch (Exception) { ret = 02_0000; } if (CheckVendor.NotValidResponseCode(ret)) { LoggingManagementService.WriteLine( $"Api Error: {MessageVendor.FormatError(ret)} on requesting {DictionaryManagementService.Item[itemid]}", "ApiSys"); } }); } if (result.Type == PackedResultType.MarketHistory) { var r = (MarketHistoryResult)result.Result; br.OverlayItemId = r.ItemId; var t = new List <HistoryData>(); foreach (var i in r.HistoryItems) { t.Add(new HistoryData { BuyerName = i.BuyerName, IsHq = i.IsHq == 1, ItemId = i.ItemId, OnMannequin = i.OnMannequin == 1, PurchaseTime = Helper.UnixTimeStampToDateTime(i.PurchaseTime), Quantity = i.Quantity, UnitPrice = i.UnitPrice, UpdateTime = DateTime.Now, World = worldId, Zone = 0 }); } DataHolder.AddCache(worldId, r.ItemId, 1, t, 120); } if (result.Type == PackedResultType.MarketListing) { var r = (MarketListingResult)result.Result; var t = new List <ListingData>(); foreach (var i in r.ListingItems) { t.Add(new ListingData { ItemId = i.ItemId, IsHq = i.IsHq == 1, Materia = new int[] { i.Materia1, i.Materia2, i.Materia3, i.Materia4, i.Materia5 }, UnitPrice = i.UnitPrice, Quantity = i.Quantity, Tax = i.TotalTax, Retainer = i.RetainerName, Artisan = i.ArtisanId.ToString("X"), OnMannequin = i.OnMannequin == 1, PlayerName = i.PlayerName, RetainerLocation = i.RetainerLocation, DyeId = i.DyeId, ListingTime = Helper.UnixTimeStampToDateTime(i.UpdateTime), UpdateTime = DateTime.Now, World = worldId, Zone = 0, }); } var sample = t.FirstOrDefault(); if (sample != null) { DataHolder.AddCache(worldId, sample.ItemId, 0, t, 120); } } LoggingManagementService.WriteLine($"Data Received: {result.Type.ToString()} @ {DictionaryManagementService.World[worldId]}", $"Game {gameId}"); }
private void ProcessHistoryData() { int totalentries = datalist.Count; cumulus.LogMessage("Processing history data, number of entries = " + totalentries); int rollHour = Math.Abs(cumulus.GetHourInc()); int luhour = cumulus.LastUpdateTime.Hour; bool rolloverdone = luhour == rollHour; bool midnightraindone = luhour == 0; while (datalist.Count > 0) { HistoryData historydata = datalist[datalist.Count - 1]; DateTime timestamp = historydata.timestamp; cumulus.LogMessage("Processing data for " + timestamp); int h = timestamp.Hour; // if outside rollover hour, rollover yet to be done if (h != rollHour) { rolloverdone = false; } // In rollover hour and rollover not yet done if ((h == rollHour) && !rolloverdone) { // do rollover cumulus.LogMessage("Day rollover " + timestamp.ToShortTimeString()); DayReset(timestamp); rolloverdone = true; } // Not in midnight hour, midnight rain yet to be done if (h != 0) { midnightraindone = false; } // In midnight hour and midnight rain (and sun) not yet done if ((h == 0) && !midnightraindone) { ResetMidnightRain(timestamp); ResetSunshineHours(); midnightraindone = true; } // Indoor Humidity ====================================================== if ((historydata.inHum > 100) && (historydata.inHum != 255)) { cumulus.LogMessage("Ignoring bad data: inhum = " + historydata.inHum); } else if ((historydata.inHum > 0) && (historydata.inHum != 255)) { // 255 is the overflow value, when RH gets below 10% - ignore DoIndoorHumidity(historydata.inHum); } // Indoor Temperature =================================================== if ((historydata.inTemp > -50) && (historydata.inTemp < 50)) { DoIndoorTemp(ConvertTempCToUser(historydata.inTemp)); } // Pressure ============================================================= if ((historydata.pressure < cumulus.EwOptions.MinPressMB) || (historydata.pressure > cumulus.EwOptions.MaxPressMB)) { cumulus.LogMessage("Ignoring bad data: pressure = " + historydata.pressure); cumulus.LogMessage(" offset = " + pressureOffset); } else { DoPressure(ConvertPressMBToUser(historydata.pressure), timestamp); } if (historydata.SensorContactLost) { cumulus.LogMessage("Sensor contact lost; ignoring outdoor data"); } else { // Outdoor Humidity ===================================================== if ((historydata.outHum > 100) && (historydata.outHum != 255)) { cumulus.LogMessage("Ignoring bad data: outhum = " + historydata.outHum); } else if ((historydata.outHum > 0) && (historydata.outHum != 255)) { // 255 is the overflow value, when RH gets below 10% - ignore DoOutdoorHumidity(historydata.outHum, timestamp); } // Wind ================================================================= if ((historydata.windGust > 60) || (historydata.windGust < 0)) { cumulus.LogMessage("Ignoring bad data: gust = " + historydata.windGust); } else if ((historydata.windSpeed > 60) || (historydata.windSpeed < 0)) { cumulus.LogMessage("Ignoring bad data: speed = " + historydata.windSpeed); } { DoWind(ConvertWindMSToUser(historydata.windGust), historydata.windBearing, ConvertWindMSToUser(historydata.windSpeed), timestamp); } // Outdoor Temperature ================================================== if ((historydata.outTemp < -50) || (historydata.outTemp > 70)) { cumulus.LogMessage("Ignoring bad data: outtemp = " + historydata.outTemp); } else { DoOutdoorTemp(ConvertTempCToUser(historydata.outTemp), timestamp); // add in 'archivePeriod' minutes worth of temperature to the temp samples tempsamplestoday += historydata.interval; TempTotalToday += (OutdoorTemperature * historydata.interval); } // update chill hours if (OutdoorTemperature < cumulus.ChillHourThreshold) { // add 1 minute to chill hours ChillHours += (historydata.interval / 60.0); } var raindiff = prevraintotal == -1 ? 0 : historydata.rainCounter - prevraintotal; // record time of last rain tip, to use in // normal running rain rate calc NB rain rate calc not currently used /* * if (raindiff > 0) * { * lastraintip = timestamp; * * raininlasttip = raindiff; * } * else * { * lastraintip = DateTime.MinValue; * * raininlasttip = 0; * } */ double rainrate; if (raindiff > 100) { cumulus.LogMessage("Warning: large increase in rain gauge tip count: " + raindiff); rainrate = 0; } else { if (historydata.interval > 0) { rainrate = ConvertRainMMToUser((raindiff * 0.3) * (60.0 / historydata.interval)); } else { rainrate = 0; } } DoRain(ConvertRainMMToUser(historydata.rainCounter * 0.3), rainrate, timestamp); prevraintotal = historydata.rainCounter; OutdoorDewpoint = ConvertTempCToUser(MeteoLib.DewPoint(ConvertUserTempToC(OutdoorTemperature), OutdoorHumidity)); CheckForDewpointHighLow(timestamp); // calculate wind chill if (ConvertUserWindToMS(WindAverage) < 1.5) { DoWindChill(OutdoorTemperature, timestamp); } else { // calculate wind chill from calibrated C temp and calibrated win in KPH DoWindChill(ConvertTempCToUser(MeteoLib.WindChill(ConvertUserTempToC(OutdoorTemperature), ConvertUserWindToKPH(WindAverage))), timestamp); } DoApparentTemp(timestamp); DoFeelsLike(timestamp); DoHumidex(timestamp); if (hasSolar) { if (historydata.uvVal == 255) { // ignore } else if (historydata.uvVal < 0) { DoUV(0, timestamp); } else if (historydata.uvVal > 16) { DoUV(16, timestamp); } else { DoUV(historydata.uvVal, timestamp); } if ((historydata.solarVal >= 0) && (historydata.solarVal <= 300000)) { DoSolarRad((int)Math.Floor(historydata.solarVal * cumulus.LuxToWM2), timestamp); // add in archive period worth of sunshine, if sunny if ((SolarRad > CurrentSolarMax * cumulus.SunThreshold / 100) && (SolarRad >= cumulus.SolarMinimum)) { SunshineHours += (historydata.interval / 60.0); } LightValue = historydata.solarVal; } } } // add in 'following interval' minutes worth of wind speed to windrun cumulus.LogMessage("Windrun: " + WindAverage.ToString(cumulus.WindFormat) + cumulus.Units.WindText + " for " + historydata.followinginterval + " minutes = " + (WindAverage * WindRunHourMult[cumulus.Units.Wind] * historydata.followinginterval / 60.0).ToString(cumulus.WindRunFormat) + cumulus.Units.WindRunText); WindRunToday += (WindAverage * WindRunHourMult[cumulus.Units.Wind] * historydata.followinginterval / 60.0); // update heating/cooling degree days UpdateDegreeDays(historydata.interval); // update dominant wind bearing CalculateDominantWindBearing(Bearing, WindAverage, historydata.interval); CheckForWindrunHighLow(timestamp); bw.ReportProgress((totalentries - datalist.Count) * 100 / totalentries, "processing"); //UpdateDatabase(timestamp.ToUniversalTime(), historydata.interval, false); cumulus.DoLogFile(timestamp, false); if (cumulus.StationOptions.LogExtraSensors) { cumulus.DoExtraLogFile(timestamp); } AddLastHourDataEntry(timestamp, Raincounter, OutdoorTemperature); AddGraphDataEntry(timestamp, Raincounter, RainToday, RainRate, OutdoorTemperature, OutdoorDewpoint, ApparentTemperature, WindChill, HeatIndex, IndoorTemperature, Pressure, WindAverage, RecentMaxGust, AvgBearing, Bearing, OutdoorHumidity, IndoorHumidity, SolarRad, CurrentSolarMax, UV, FeelsLike, Humidex); AddLast3HourDataEntry(timestamp, Pressure, OutdoorTemperature); AddRecentDataEntry(timestamp, WindAverage, RecentMaxGust, WindLatest, Bearing, AvgBearing, OutdoorTemperature, WindChill, OutdoorDewpoint, HeatIndex, OutdoorHumidity, Pressure, RainToday, SolarRad, UV, Raincounter, FeelsLike, Humidex); RemoveOldLHData(timestamp); RemoveOldL3HData(timestamp); RemoveOldGraphData(timestamp); DoTrendValues(timestamp); UpdatePressureTrendString(); UpdateStatusPanel(timestamp); cumulus.AddToWebServiceLists(timestamp); datalist.RemoveAt(datalist.Count - 1); } cumulus.LogMessage("End processing history data"); }
/// <summary> /// 设置历史记录cookie /// </summary> /// <param name="cookName"></param> /// <param name="id"></param> /// <param name="max"></param> /// <returns></returns> public static string SetHistory(string cookName, int id, int max) { HistoryData hd = new HistoryData(cookName, max); return(hd.Add(id)); }
void RunTest(AggregateType aggregate) { try { AggregateTestResultSet myResults = AggregateTestResultSet.LoadFromXMLFile( String.Format(@"{0}TestResult.xml", Enum.GetName(typeof(AggregateType), aggregate))); for (int i = 0; i < myResults.Count; i++) { AggregateTestResult testResult = myResults[i] as AggregateTestResult; Debug.WriteLine(String.Format("Test Data: {0}", testResult.TestDataName)); Debug.WriteLine(String.Format("Start time: {0}\tEnd time: {1}\tInterval: {2}", testResult.Details.StartTime.TimeOfDay, testResult.Details.EndTime.TimeOfDay, testResult.Details.ProcessingInterval)); // get expected values List <DataValue> expected = new List <DataValue>(testResult.DataValues.Count); for (int ii = 0; ii < testResult.DataValues.Count; ii++) { expected.Add(testResult.DataValues[ii].GetDataValue()); } // configure the aggregate calculator NewAggregateFilter filter = new NewAggregateFilter() { StartTime = testResult.Details.StartTime, EndTime = testResult.Details.EndTime, AggregateType = AggregateLookup[aggregate], AggregateConfiguration = TestData[myResults[i].TestDataName].Configuration.AggregateConfiguration, ProcessingInterval = testResult.Details.ProcessingInterval }; TestData testData = TestData[testResult.TestDataName]; AggregateCalculatorImpl calculator = Aggregators.CreateAggregator(filter, testData.Configuration.Stepped); /* * calculator.Configuration = new AggregateConfiguration() * { * PercentDataBad = 0, * PercentDataGood = 100, * SteppedSlopedExtrapolation = false, * TreatUncertainAsBad = true * }; */ HistoryData rawHistoryData = new HistoryData(); for (int ii = 0; ii < testData.DataValues.Count; ii++) { DataValue dv = testData.DataValues[ii].GetDataValue(); rawHistoryData.DataValues.Add(dv); } HistoryData historyData = new HistoryData(); var sr = new ServiceResult(StatusCodes.Good); foreach (DataValue raw in rawHistoryData.DataValues) { IList <DataValue> released = calculator.ProcessValue(raw, sr); if (StatusCode.IsGood(sr.StatusCode) && released.Count > 0) { historyData.DataValues.AddRange(released); } } var lsr = new ServiceResult(StatusCodes.Good); historyData.DataValues.AddRange(calculator.ProcessTermination(lsr)); // obtain the actual values List <DataValue> actual = new List <DataValue>(historyData.DataValues); // compare the two value sets bool assertion = true; HelperMethods.CompareResults(expected, actual, testResult.TestDataName, assertion); Console.WriteLine("Test {0} passed", i); } } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); throw; } }
public virtual int BatchWrite(SortedDictionary <ITag, object> items, bool isSync = true) { int len = items.Count; int rev = 0; IMultiReadWrite multi = _fileReader as IMultiReadWrite; if (DataChange == null) { if (multi != null) { DeviceAddress[] addrs = new DeviceAddress[len]; object[] objs = new object[len]; int i = 0; foreach (var item in items) { addrs[i] = item.Key.Address; objs[i] = item.Value; i++; } return(multi.WriteMultiple(addrs, objs)); } else { foreach (var tag in items) { tag.Key.Write(tag.Value); } return(0); } } else { HistoryData[] data = new HistoryData[len]; int i = 0; if (multi != null) { DeviceAddress[] addrs = new DeviceAddress[len]; object[] objs = new object[len]; foreach (var item in items) { ITag tag = item.Key; addrs[i] = tag.Address; objs[i] = item.Value; data[i].ID = tag.ID; data[i].TimeStamp = tag.TimeStamp; data[i].Quality = tag.Quality; data[i].Value = item.Key.ToStorage(item.Value); i++; } rev = multi.WriteMultiple(addrs, objs); } else { foreach (var item in items) { ITag tag = item.Key; if (tag.Write(tag.Value) >= 0) { data[i].ID = tag.ID; data[i].TimeStamp = tag.TimeStamp; data[i].Quality = tag.Quality; data[i].Value = item.Key.ToStorage(item.Value); i++; } } } foreach (DataChangeEventHandler deleg in DataChange.GetInvocationList()) { deleg.BeginInvoke(this, new DataChangeEventArgs(1, data), null, null); } } return(rev); }
/// <summary> /// Reads the history of an HDA item. /// </summary> private ServiceResult HistoryReadProcessedItem( ServerSystemContext context, ComHdaClient client, ReadProcessedDetails details, TimestampsToReturn timestampsToReturn, uint aggregateId, HistoryReadValueId nodeToRead, HdaParsedNodeId parsedNodeId, HistoryReadResult result) { // create the request or load it from a continuation point. HdaHistoryReadProcessedRequest request = null; if (nodeToRead.ContinuationPoint == null) { request = new HdaHistoryReadProcessedRequest(parsedNodeId.RootId, aggregateId, details, nodeToRead); } else { request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint) as HdaHistoryReadProcessedRequest; if (request == null) { return StatusCodes.BadContinuationPointInvalid; } } // fetch the data. result.StatusCode = client.ReadHistory(request); // fill in the results. if (request.Results != null) { HistoryData data = new HistoryData(); data.DataValues = request.Results; result.HistoryData = new ExtensionObject(data); } // create a new continuation point. if (!request.Completed) { result.ContinuationPoint = SaveContinuationPoint(context, request); } return result.StatusCode; }
private void FireDataChange(int dwTransid, int hGroup, int hrMasterquality, int hrMastererror, int dwCount, IntPtr phClientItems, IntPtr pvValues, IntPtr pwQualities, IntPtr pftTimeStamps, IntPtr ppErrors) { HistoryData[] clents = new HistoryData[dwCount]; for (int i = 0; i < dwCount; i++) { ITag item = GetItemByID(Marshal.ReadInt16(phClientItems)); if (item == null) { continue; } if (HRESULTS.Succeeded(Marshal.ReadInt32(ppErrors))) { Storage value = Storage.Empty; VarEnum vt = (VarEnum)Marshal.ReadInt32(pvValues); switch (item.Address.VarType) { case DataType.BOOL: value.Boolean = Marshal.ReadByte(pvValues + 8) > 0; break; case DataType.BYTE: value.Byte = Marshal.ReadByte(pvValues + 8); break; case DataType.WORD: case DataType.SHORT: value.Int16 = Marshal.ReadInt16(pvValues + 8); break; case DataType.INT: value.Int32 = Marshal.ReadInt32(pvValues + 8); break; case DataType.FLOAT: if (vt == VarEnum.VT_UI2) { ushort us = (ushort)Marshal.ReadInt16(pvValues + 8); value.Single = Convert.ToSingle(us); } else { float[] x = new float[1]; Marshal.Copy(pvValues + 8, x, 0, 1); value.Single = x[0]; } break; case DataType.SYS: case DataType.STR: string str = Marshal.PtrToStringUni(Marshal.ReadIntPtr(pvValues + 8)); StringTag tag = item as StringTag; if (tag != null) { tag.String = str; } break; default: value.Boolean = Marshal.ReadByte(pvValues + 8) > 0; break; } DateTime time = DateTime.FromFileTime(Marshal.ReadInt64(pftTimeStamps)); QUALITIES quality = (QUALITIES)Marshal.ReadInt16(pwQualities); clents[i].ID = item.ID; clents[i].Quality = quality; clents[i].Value = value; clents[i].TimeStamp = time; item.Update(value, time, quality); } ppErrors += 4; phClientItems += 4; pvValues += 16; pwQualities += 2; pftTimeStamps += 8; } DataChange(this, new DataChangeEventArgs(1, clents)); }
public HistoryData[] BatchRead(DataSource source, bool isSync, params ITag[] itemArray) { IntPtr pErrors; int len = itemArray.Length; int result = 0; int[] arrHSrv = Array.ConvertAll(itemArray, c => c.Address.Start); HistoryData[] values = new HistoryData[len]; if (isSync) { IntPtr pItemValues; result = _sync.Read((OPCDATASOURCE)source, len, arrHSrv, out pItemValues, out pErrors); if (HRESULTS.Succeeded(result)) { for (int i = 0; i < len; i++) { var item = itemArray[i]; if (Marshal.ReadInt32(pErrors) == 0) { switch (item.Address.VarType) { case DataType.BOOL: values[i].Value.Boolean = Marshal.ReadByte(pItemValues + 16) > 0; break; case DataType.BYTE: values[i].Value.Byte = Marshal.ReadByte(pItemValues + 16); break; case DataType.WORD: case DataType.SHORT: values[i].Value.Int16 = Marshal.ReadInt16(pItemValues + 16); break; case DataType.INT: values[i].Value.Int32 = Marshal.ReadInt32(pItemValues + 16); break; case DataType.FLOAT: float[] x = new float[1]; Marshal.Copy(pItemValues + 16, x, 0, 1); values[i].Value.Single = x[0]; break; case DataType.STR: string str = Marshal.PtrToStringUni(Marshal.ReadIntPtr(pItemValues + 16)); StringTag tag = item as StringTag; if (tag != null) { tag.String = str; } break; } values[i].ID = item.ID; values[i].Quality = (QUALITIES)Marshal.ReadInt16(pItemValues + 12); values[i].TimeStamp = Marshal.ReadInt64(pItemValues + 4).ToDateTime(); item.Update(values[i].Value, values[i].TimeStamp, values[i].Quality); } pItemValues += 32; pErrors += 4; } Marshal.FreeCoTaskMem(pItemValues); } else { Marshal.FreeCoTaskMem(pItemValues); return(null); } } else { int cancelID = 0; result = _async.Read(len, arrHSrv, 1, out cancelID, out pErrors); } Marshal.FreeCoTaskMem(pErrors); return(values); }
void BindingData() { if (!dtstart.Value.HasValue || !dtend.Value.HasValue) { return; } DateTime start = dtstart.Value.Value; DateTime end = dtend.Value.Value; if ((end - start).Days > 7) { end = start.AddDays(7); dtend.Value = end; } else if (start >= end) { end = start.AddDays(1); dtend.Value = end; } HashSet <short> hash = new HashSet <short>(); foreach (var item in sortlist) { item.Value.Collection.Clear(); hash.Add(item.Key); } foreach (KeyValuePair <short, string> item in chklist.SelectedItems) { ObservableDataSource <HistoryData> source; if (!sortlist.TryGetValue(item.Key, out source)) { source = new ObservableDataSource <HistoryData>(); source.SetXMapping(X => hTimeSpanAxis.ConvertToDouble(X.TimeStamp)); source.SetSourceMapping(App.Server[item.Key]); if (comodel.SelectedIndex == 0 || (comodel.SelectedIndex == 1 && sortlist.Count == 0)) //|| (comodel.SelectedIndex == 2 && (sortlist.Count == 0 || chklist.SelectedItems.Count == 1))) { plotterlist[item.Key] = chartPlotter1.AddLineGraph(source, 2, item.Value); } else { var innerPlotter = new InjectedPlotter() { SetViewportBinding = false }; var axis = new HorizontalDateTimeAxis(); innerPlotter.Children.Add(axis); innerPlotter.MainHorizontalAxis = axis; innerPlotter.Children.Add(new VerticalAxis() { Placement = AxisPlacement.Right }); innerPlotter.Children.Add(new VerticalAxisTitle() { Content = item.Value, Placement = AxisPlacement.Right }); chartPlotter1.Children.Add(innerPlotter); innerPlotter.AddLineGraph(source, 2, item.Value); plotterlist.Add(item.Key, innerPlotter); } sortlist.Add(item.Key, source); } hash.Remove(item.Key); var data = App.Server.ReadRaw(start, end, item.Key); if (data != null) { bool first = true; var temp = new HistoryData(item.Key, QUALITIES.QUALITY_GOOD, Storage.Empty, start); source.SuspendUpdate(); foreach (var p in data) { if (first) { temp.Value = p.Value; source.Collection.Add(temp); first = false; } source.Collection.Add(p); } if (source.Collection.Count == 0) { source.Collection.Add(temp); } temp = source.Collection[source.Collection.Count - 1]; temp.TimeStamp = end; source.Collection.Add(temp); source.ResumeUpdate(); } chartPlotter1.FitToView(); } foreach (short id in hash) { sortlist.Remove(id); IPlotterElement plotter; if (plotterlist.TryGetValue(id, out plotter)) { var chart = plotter as Plotter; if (chart != null) { for (int i = chart.Children.Count - 1; i >= 0; i--) { chart.Children[i].RemoveFromPlotter(); } } plotter.RemoveFromPlotter(); plotterlist.Remove(id); } } }
public History(HistoryData hd) { Load(hd); }
private void BtnSave_Click(Object sender, EventArgs e) { if (this.gamePanel.ButtonList == null || this.matrixAlgorithm == null) { MessageBox.Show("Game could not be saved !"); return; } //DataBaseWriter dataBaseWriter = new DataBaseWriter(); this.savedGameState = new SavedGameState { BoardSize = this.matrixAlgorithm.BoardSize, CurrentTurn = this.matrixAlgorithm.CurrentTurn, CurrentTurnCount = this.matrixAlgorithm.CurrentTurnCount, BoardData = this.mapper.WriteCurrentBoardToString(this.matrixAlgorithm), }; Data data = new Data { CurrentGame = savedGameState, Round = this.settings.RoundCount, HistoryList = this.settings.HistoryList, Difficulty = this.ChooseDifficulty() }; HistoryData historyData = new HistoryData { HistoryList = this.settings.HistoryList, }; if (this.settings.HistoryList.Count >= 1) { this.dataBaseWriter.WriteDatabaseFile(historyData); } using (SaveFileDialog saveFileDialog = new SaveFileDialog()) { saveFileDialog.InitialDirectory = Application.StartupPath + "/settings/"; saveFileDialog.Filter = "JSON File(*.json)| *.json; | XML Document(*.xml) | *.xml; | Configuration settings(*.ini) | *.ini"; if (saveFileDialog.ShowDialog() != DialogResult.OK) { return; } if (saveFileDialog.FileName.Contains(".json")) { this.serialize.SerializeJson(saveFileDialog.FileName, data); MessageBox.Show($"Your progress was successfully saved to {saveFileDialog.FileName}"); } else if (saveFileDialog.FileName.Contains(".xml")) { this.serialize.SerializeXml(saveFileDialog.FileName, data); MessageBox.Show($"Your progress was successfully saved to {saveFileDialog.FileName}"); } else if (saveFileDialog.FileName.Contains(".ini")) { this.iniParseData.WriteToIni(saveFileDialog.FileName, data); } else { MessageBox.Show("Unable to save your progress!"); } } }
void RunTest(AggregateType aggregate) { try { AggregateTestResultSet myResults = AggregateTestResultSet.LoadFromXMLFile( String.Format(@"{0}TestResult.xml", Enum.GetName(typeof(AggregateType), aggregate))); for (int i = 0; i < myResults.Count; i++) { AggregateTestResult testResult = myResults[i] as AggregateTestResult; Debug.WriteLine(String.Format("Test Data: {0}", testResult.TestDataName)); Debug.WriteLine(String.Format("Start time: {0}\tEnd time: {1}\tInterval: {2}", testResult.Details.StartTime.TimeOfDay, testResult.Details.EndTime.TimeOfDay, testResult.Details.ProcessingInterval)); // get expected values List<DataValue> expected = new List<DataValue>(testResult.DataValues.Count); for (int ii = 0; ii < testResult.DataValues.Count; ii++) expected.Add(testResult.DataValues[ii].GetDataValue()); // configure the aggregate calculator NewAggregateFilter filter = new NewAggregateFilter() { StartTime = testResult.Details.StartTime, EndTime = testResult.Details.EndTime, AggregateType = AggregateLookup[aggregate], AggregateConfiguration = TestData[myResults[i].TestDataName].Configuration.AggregateConfiguration, ProcessingInterval = testResult.Details.ProcessingInterval }; TestData testData = TestData[testResult.TestDataName]; AggregateCalculatorImpl calculator = Aggregators.CreateAggregator(filter, testData.Configuration.Stepped); /* calculator.Configuration = new AggregateConfiguration() { PercentDataBad = 0, PercentDataGood = 100, SteppedSlopedExtrapolation = false, TreatUncertainAsBad = true }; */ HistoryData rawHistoryData = new HistoryData(); for (int ii = 0; ii < testData.DataValues.Count; ii++) { DataValue dv = testData.DataValues[ii].GetDataValue(); rawHistoryData.DataValues.Add(dv); } HistoryData historyData = new HistoryData(); var sr = new ServiceResult(StatusCodes.Good); foreach (DataValue raw in rawHistoryData.DataValues) { IList<DataValue> released = calculator.ProcessValue(raw, sr); if (StatusCode.IsGood(sr.StatusCode) && released.Count > 0) { historyData.DataValues.AddRange(released); } } var lsr = new ServiceResult(StatusCodes.Good); historyData.DataValues.AddRange(calculator.ProcessTermination(lsr)); // obtain the actual values List<DataValue> actual = new List<DataValue>(historyData.DataValues); // compare the two value sets bool assertion = true; HelperMethods.CompareResults(expected, actual, testResult.TestDataName, assertion); Console.WriteLine("Test {0} passed", i); } } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); throw; } }
public IEnumerable <HistoryData> SendHdaRequest(DateTime start, DateTime end, short id) { if (_tcpSend == null || !_tcpSend.Connected) { yield break; } ITag tag = _server[id]; if (tag == null) { yield break; } byte[] hdaReq = new byte[20]; hdaReq[0] = FCTCOMMAND.fctHead; hdaReq[1] = FCTCOMMAND.fctHdaIdRequest; byte[] startbuffer = BitConverter.GetBytes(start.ToFileTime()); startbuffer.CopyTo(hdaReq, 2); byte[] endbuffer = BitConverter.GetBytes(end.ToFileTime()); endbuffer.CopyTo(hdaReq, 10); byte[] idbuffer = BitConverter.GetBytes(id); idbuffer.CopyTo(hdaReq, 18); SocketError error; int index = 0; HistoryData data = HistoryData.Empty; data.ID = id; int result = 0; lock (sendasync) { _tcpSend.Send(hdaReq); switch (tag.Address.VarType) { case DataType.FLOAT: do { result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error); if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown) { _tcpSend.Dispose(); yield break; } while (index + 12 <= result) { data.Value.Single = BitConverter.ToSingle(tcpBuffer, index); //未来可考虑量程转换和其他数据类型 index += 4; long fileTime = BitConverter.ToInt64(tcpBuffer, index); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); index += 8; yield return(data); } if (index == result) { index = 0; } else { index += 12 - result; //丢弃一个值 } } while (result > 0); break; case DataType.INT: do { result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error); if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown) { _tcpSend.Dispose(); yield break; } while (index + 12 <= result) { data.Value.Int32 = BitConverter.ToInt32(tcpBuffer, index); //未来可考虑量程转换和其他数据类型 index += 4; long fileTime = BitConverter.ToInt64(tcpBuffer, index); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); index += 8; yield return(data); } if (index == result) { index = 0; } else { index += 12 - result; //丢弃一个值 } } while (result > 0); break; case DataType.BOOL: //布尔量一个都不能少 { byte[] temp = new byte[9]; do { result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error); if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown) { _tcpSend.Dispose(); yield break; } if (index != 0) { Array.Copy(tcpBuffer, 0, temp, 9 - index, index); data.Value.Boolean = BitConverter.ToBoolean(temp, 0); long fileTime = BitConverter.ToInt64(temp, 1); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); yield return(data); } while (index + 9 <= result) { data.Value.Boolean = BitConverter.ToBoolean(tcpBuffer, index); index += 1; long fileTime = BitConverter.ToInt64(tcpBuffer, index); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); index += 8; yield return(data); } if (index == result) { index = 0; } else { Array.Copy(tcpBuffer, index, temp, 0, result - index); index += 9 - result; } } while (result > 0); } break; } } }
private DateTime ReadFirstDate() { ReadRawModifiedDetails details = new ReadRawModifiedDetails(); details.StartTime = new DateTime(1970, 1, 1); details.EndTime = DateTime.UtcNow.AddDays(1); details.IsReadModified = false; details.NumValuesPerNode = 1; details.ReturnBounds = false; HistoryReadValueId nodeToRead = new HistoryReadValueId(); nodeToRead.NodeId = m_nodeId; HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection(); nodesToRead.Add(nodeToRead); HistoryReadResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Source, false, nodesToRead, out results, out diagnosticInfos); Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); if (StatusCode.IsBad(results[0].StatusCode)) { return(DateTime.MinValue); } HistoryData data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData; if (results == null) { return(DateTime.MinValue); } DateTime startTime = data.DataValues[0].SourceTimestamp; if (results[0].ContinuationPoint != null) { nodeToRead.ContinuationPoint = results[0].ContinuationPoint; m_session.HistoryRead( null, new ExtensionObject(details), TimestampsToReturn.Source, true, nodesToRead, out results, out diagnosticInfos); Session.ValidateResponse(results, nodesToRead); Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); } return(startTime); }
public HistoryData[] BatchRead(DataSource source, bool isSync, params ITag[] itemArray) { if (itemArray.Length == 0 || _tcpSend == null || !_tcpSend.Connected) { return(null); } short len = (short)itemArray.Length; byte[] bt = new byte[2]; byte[] data = new byte[5 + len * 2]; int j = 0; data[j++] = FCTCOMMAND.fctHead; data[j++] = FCTCOMMAND.fctReadMultiple; data[j++] = source == DataSource.Cache ? (byte)0 : (byte)1; bt = BitConverter.GetBytes(len); data[j++] = bt[0]; data[j++] = bt[1]; for (int i = 0; i < len; i++) { bt = BitConverter.GetBytes(itemArray[i].ID); data[j++] = bt[0]; data[j++] = bt[1]; } SocketError error; lock (sendasync) { _tcpSend.Send(data, 0, data.Length, SocketFlags.None, out error); int result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error); } //!!!!此处的协议应注意,如批量读入的数据量超过缓存,必须分批合并;在协议头应加入总字节数,以和result比较是否需要循环读入。 j = 5; if (error == SocketError.Success) { DateTime time = DateTime.Now; HistoryData[] values = new HistoryData[len]; for (int i = 0; i < len; i++) { short id = BitConverter.ToInt16(tcpBuffer, j); j += 2; ITag tag = _server[id]; byte length = tcpBuffer[j++]; if (tag != null && length > 0) { switch (tag.Address.VarType) { case DataType.BOOL: values[i].Value.Boolean = BitConverter.ToBoolean(tcpBuffer, j); break; case DataType.BYTE: values[i].Value.Byte = tcpBuffer[j]; break; case DataType.WORD: case DataType.SHORT: values[i].Value.Int16 = BitConverter.ToInt16(tcpBuffer, j); break; case DataType.INT: values[i].Value.Int32 = BitConverter.ToInt32(tcpBuffer, j); break; case DataType.FLOAT: values[i].Value.Single = BitConverter.ToSingle(tcpBuffer, j); break; case DataType.STR: StringTag strTag = tag as StringTag; if (strTag != null) { strTag.String = Encoding.ASCII.GetString(tcpBuffer, j, length).Trim(); } break; } if (values[i].Value != tag.Value) { tag.Update(values[i].Value, time, QUALITIES.QUALITY_GOOD); } } j += length; } return(values); } else { return(null); } }
/// <summary> /// Reads the raw data for a variable /// </summary> protected ServiceResult HistoryReadRaw( ISystemContext context, BaseVariableState source, ReadRawModifiedDetails details, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueId nodeToRead, HistoryReadResult result) { ServerSystemContext serverContext = context as ServerSystemContext; HistoryDataReader reader = null; HistoryData data = new HistoryData(); if (nodeToRead.ContinuationPoint != null && nodeToRead.ContinuationPoint.Length > 0) { // restore the continuation point. reader = RestoreDataReader(serverContext, nodeToRead.ContinuationPoint); if (reader == null) { return StatusCodes.BadContinuationPointInvalid; } // node id must match previous node id. if (reader.VariableId != nodeToRead.NodeId) { Utils.SilentDispose(reader); return StatusCodes.BadContinuationPointInvalid; } // check if releasing continuation points. if (releaseContinuationPoints) { Utils.SilentDispose(reader); return ServiceResult.Good; } } else { // get the source for the variable. IHistoryDataSource datasource = null; ServiceResult error = GetHistoryDataSource(serverContext, source, out datasource); if (ServiceResult.IsBad(error)) { return error; } // create a reader. reader = new HistoryDataReader(nodeToRead.NodeId, datasource); // start reading. reader.BeginReadRaw( serverContext, details, timestampsToReturn, nodeToRead.ParsedIndexRange, nodeToRead.DataEncoding, data.DataValues); } // continue reading data until done or max values reached. bool complete = reader.NextReadRaw( serverContext, timestampsToReturn, nodeToRead.ParsedIndexRange, nodeToRead.DataEncoding, data.DataValues); // save continuation point. if (!complete) { SaveDataReader(serverContext, reader); result.StatusCode = StatusCodes.GoodMoreData; } // return the dat. result.HistoryData = new ExtensionObject(data); return result.StatusCode; }
public IEnumerable <HistoryData> SendHdaRequest(DateTime start, DateTime end) { if (_tcpSend == null || !_tcpSend.Connected) { yield break; } byte[] hdaReq = new byte[18]; hdaReq[0] = FCTCOMMAND.fctHead; hdaReq[1] = FCTCOMMAND.fctHdaRequest; byte[] startbuffer = BitConverter.GetBytes(start.ToFileTime()); startbuffer.CopyTo(hdaReq, 2); byte[] endbuffer = BitConverter.GetBytes(end.ToFileTime()); endbuffer.CopyTo(hdaReq, 10); SocketError error; HistoryData data = HistoryData.Empty; short tempid = short.MinValue; byte[] temp = new byte[14]; ITag tag = null; int index = 0; int size = 0; int result = 0; short id = 0; lock (sendasync) { _tcpSend.Send(hdaReq); do { result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error); if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown) { _tcpSend.Dispose(); yield break; } if (index != 0) { Array.Copy(tcpBuffer, 0, temp, 14 - index, index); id = BitConverter.ToInt16(temp, 0); tempid = id; tag = _server[id]; if (tag == null) { yield break; } data.ID = id; size = tag.Address.DataSize; index -= (4 - size); switch (tag.Address.VarType) { case DataType.BOOL: data.Value.Boolean = BitConverter.ToBoolean(temp, 2); break; case DataType.BYTE: data.Value.Byte = tcpBuffer[index]; break; case DataType.WORD: case DataType.SHORT: data.Value.Int16 = BitConverter.ToInt16(temp, 2); break; case DataType.TIME: case DataType.INT: data.Value.Int32 = BitConverter.ToInt32(temp, 2); break; case DataType.FLOAT: data.Value.Single = BitConverter.ToSingle(temp, 2); break; } long fileTime = BitConverter.ToInt64(temp, 2 + size); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); yield return(data); } while (result >= index + 2) { id = BitConverter.ToInt16(tcpBuffer, index); if (tempid != id) { tempid = id; tag = _server[id]; if (tag == null) { yield break; } size = tag.Address.DataSize; } if (index + 10 + size > result) { break; } data.ID = id; index += 2; switch (tag.Address.VarType) { case DataType.BOOL: data.Value.Boolean = BitConverter.ToBoolean(tcpBuffer, index); break; case DataType.BYTE: data.Value.Byte = tcpBuffer[index]; break; case DataType.WORD: case DataType.SHORT: data.Value.Int16 = BitConverter.ToInt16(tcpBuffer, index); break; case DataType.TIME: case DataType.INT: data.Value.Int32 = BitConverter.ToInt32(tcpBuffer, index); break; case DataType.FLOAT: data.Value.Single = BitConverter.ToSingle(tcpBuffer, index); break; } index += size; long fileTime = BitConverter.ToInt64(tcpBuffer, index); if (fileTime == -1) { yield break; } data.TimeStamp = DateTime.FromFileTime(fileTime); index += 8; yield return(data); } if (index == result) { index = 0; } else { Array.Copy(tcpBuffer, index, temp, 0, result - index); index += 14 - result; } } while (result > 0); } yield break; }
public override void getAndProcessHistoryData() { var data = new byte[32]; cumulus.LogMessage("Current culture: " + CultureInfo.CurrentCulture.DisplayName); //DateTime now = DateTime.Now; cumulus.LogMessage(DateTime.Now.ToString("G")); cumulus.LogMessage("Start reading history data"); cumulus.LogConsoleMessage("Downloading Archive Data"); DateTime timestamp = DateTime.Now; //LastUpdateTime = DateTime.Now; // lastArchiveTimeUTC.ToLocalTime(); cumulus.LogMessage("Last Update = " + cumulus.LastUpdateTime); ReadAddress(0, data); // get address of current location int addr = ((data[31]) * 256) + data[30]; //int previousaddress = addr; cumulus.LogMessage("Reading current address " + addr.ToString("X4")); ReadAddress(addr, data); bool moredata = true; datalist = new List <HistoryData>(); while (moredata) { followinginterval = interval; interval = data[0]; // calculate timestamp of previous history data timestamp = timestamp.AddMinutes(-interval); if ((interval != 255) && (timestamp > cumulus.LastUpdateTime) && (datalist.Count < maxHistoryEntries - 2)) { // Read previous data addr -= foEntrysize; if (addr == 0xF0) { addr = foMaxAddr; // wrap around } ReadAddress(addr, data); // add history data to collection var histData = new HistoryData(); string msg = "Read logger entry for " + timestamp + " address " + addr.ToString("X4"); int numBytes = hasSolar ? 20 : 16; cumulus.LogMessage(msg); msg = "Data block: "; for (int i = 0; i < numBytes; i++) { msg += data[i].ToString("X2"); msg += " "; } cumulus.LogDataMessage(msg); histData.timestamp = timestamp; histData.interval = interval; histData.followinginterval = followinginterval; histData.inHum = data[1] == 255 ? 10 : data[1]; histData.outHum = data[4] == 255 ? 10 : data[4]; double outtemp = ((data[5]) + (data[6] & 0x7F) * 256) / 10.0f; var sign = (byte)(data[6] & 0x80); if (sign == 0x80) { outtemp = -outtemp; } if (outtemp > -200) { histData.outTemp = outtemp; } histData.windGust = (data[10] + ((data[11] & 0xF0) * 16)) / 10.0f; histData.windSpeed = (data[9] + ((data[11] & 0x0F) * 256)) / 10.0f; histData.windBearing = (int)(data[12] * 22.5f); histData.rainCounter = data[13] + (data[14] * 256); double intemp = ((data[2]) + (data[3] & 0x7F) * 256) / 10.0f; sign = (byte)(data[3] & 0x80); if (sign == 0x80) { intemp = -intemp; } histData.inTemp = intemp; // Get pressure and convert to sea level histData.pressure = (data[7] + (data[8] * 256)) / 10.0f + pressureOffset; histData.SensorContactLost = (data[15] & 0x40) == 0x40; if (hasSolar) { histData.uvVal = data[19]; histData.solarVal = (data[16] + (data[17] * 256) + (data[18] * 65536)) / 10.0; } datalist.Add(histData); bw.ReportProgress(datalist.Count, "collecting"); } else { moredata = false; } } cumulus.LogMessage("Number of history entries = " + datalist.Count); if (datalist.Count > 0) { ProcessHistoryData(); } //using (cumulusEntities dataContext = new cumulusEntities()) //{ // UpdateHighsAndLows(dataContext); //} }
protected void MenuItemClicked(object sender, ActiveEventArgs e) { if (string.IsNullOrEmpty(Users.LoggedInUserName)) { return; } string menuEventToRaise = e.Params["MenuEventName"].Get<string>(); string menuText = e.Params["MenuText"].Get<string>(); string pars = e.Params["Params"].Get<string>(); // Checking to see if we need to delete older items... // This is done since we only store the x last items, where x == a setting which // defaults to 5... int numberOfExistingItems = ActiveType<HistoryData>.CountWhere( Criteria.Eq("Username", Users.LoggedInUserName)); int maxItems = Settings.Instance.Get("NumberOfHistoryItemsPerUser", 50); if (numberOfExistingItems >= maxItems) { int itemsToDelete = (numberOfExistingItems - maxItems) + 1; List<HistoryData> items = new List<HistoryData>( ActiveType<HistoryData>.Select( Criteria.Eq("Username", Users.LoggedInUserName))); items.Sort( delegate(HistoryData left, HistoryData right) { return left.WhenRaised.CompareTo(right.WhenRaised); }); for (int idx = 0; idx < itemsToDelete; idx++) { items[idx].Delete(); } } // Now we can create a new History Item and insert... HistoryData h = new HistoryData { Username = Users.LoggedInUserName, MenuEventName = menuEventToRaise, MenuText = menuText, Params = pars }; h.Save(); // Sending the "HistoryUpdated" event... Node node = new Node(); List<HistoryData> list = new List<HistoryData>( ActiveType<HistoryData>.Select( Criteria.Eq("Username", Users.LoggedInUserName))); list.Sort( delegate(HistoryData left, HistoryData right) { return right.WhenRaised.CompareTo(left.WhenRaised); }); node["Grid"]["Columns"]["MenuItem"]["Caption"].Value = Language.Instance["HistoryMenuItemCaption", null, "Menu Item"]; node["Grid"]["Columns"]["MenuItem"]["ControlType"].Value = "LinkButton"; node["Grid"]["Columns"]["When"]["Caption"].Value = Language.Instance["HistoryWhenCaption", null, "When"]; node["Grid"]["Columns"]["When"]["ControlType"].Value = "Label"; int idxNo = 0; foreach (HistoryData idx in list) { if (idx.MenuEventName == "Menu-ViewHistory") continue; node["Grid"]["Rows"]["Row" + idxNo]["ID"].Value = idx.ID; node["Grid"]["Rows"]["Row" + idxNo]["MenuItem"].Value = idx.MenuText; node["Grid"]["Rows"]["Row" + idxNo]["When"].Value = idx.WhenRaised; node["Grid"]["Rows"]["Row" + idxNo]["When"]["Format"].Value = "d MMM yy"; idxNo += 1; } ActiveEvents.Instance.RaiseActiveEvent( this, "HistoryWasUpdated", node); }
/// <summary> /// Displays the results of a history operation. /// </summary> private void DisplayResults(HistoryData values) { HistoryModifiedData modifiedData = values as HistoryModifiedData; if (modifiedData != null) { ResultsDV.Columns[5].Visible = true; ResultsDV.Columns[6].Visible = true; ResultsDV.Columns[7].Visible = true; ResultsDV.Columns[8].Visible = false; for (int ii = 0; ii < modifiedData.DataValues.Count; ii++) { AddValue(modifiedData.DataValues[ii], modifiedData.ModificationInfos[ii]); } } else { ResultsDV.Columns[5].Visible = false; ResultsDV.Columns[6].Visible = false; ResultsDV.Columns[7].Visible = false; ResultsDV.Columns[8].Visible = false; if (values != null) { foreach (DataValue value in values.DataValues) { AddValue(value, null); } } } m_dataset.AcceptChanges(); }
public void selItemsHistoryDataToChart(Chart chart, List <SelectItem> selItems, List <DateRange> dateRangeList, RunMode runMode, out ChartXUnit xUnit) { List <HistoryData> dataList = new List <HistoryData>(); List <DateSelectItem> items = RegressResult.ToDaySelectItemList(selItems, dateRangeList); xUnit = SUtils.DetermineXUnit(items.Count); if (items.Count == 0) { return; } if (xUnit == ChartXUnit.CXU_Year) { items.Reverse(); int startDate = items[0].date_; int endDate = items[items.Count - 1].date_; int startYear = Utils.Year(startDate); int endYear = Utils.Year(endDate); int iSearchStartHint = 0; for (int iYear = startYear; iYear <= endYear; iYear++) { int iStartIndex = -1; int nDaySpan = 0; for (int i = iSearchStartHint; i < items.Count; i++) { if (iStartIndex == -1 && Utils.Year(items[i].date_) == iYear) { iStartIndex = i; } if (iStartIndex != -1) { if (Utils.Year(items[i].date_) == iYear) { nDaySpan++; } else { break; } } } iSearchStartHint = iStartIndex + nDaySpan; HistoryData data = StrategyAsset.GetHistoryData(items, iStartIndex, nDaySpan, runMode); dataList.Add(data); } } else { int nDaySpan = SUtils.ToDayCount(xUnit); int iStartIndex = 0; do { if (iStartIndex + nDaySpan - 1 > items.Count) { break; } HistoryData data = StrategyAsset.GetHistoryData(items, iStartIndex, nDaySpan, runMode); dataList.Add(data); iStartIndex += nDaySpan; } while (iStartIndex < items.Count); dataList.Reverse(); } List <String> xDescList = new List <string>(); foreach (var item in dataList) { xDescList.Add(SUtils.ToXDesc(xUnit, item.startDate_, item.endDate_)); } SUtils.FillHistoryDataToChart(chart, dataList, xDescList); re_.reHistory_ = StrategyAsset.GetHistoryData(items, 0, items.Count, re_.runMode_); }
/// <summary> /// コメント受信時に発生するイベントメソッド /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _Host_ReceivedComment(object sender, ReceivedCommentEventArgs e) { try { // 多重処理防止 if (_LastLiveId == _Host.GetPlayerStatus().LiveNum) { return; } _LastLiveId = _Host.GetPlayerStatus().LiveNum; // インデックスチェック int commentLastIndex = e.CommentDataList.Count - 1; if (commentLastIndex < 0) { return; } // 放送主時以外の受信は無視 if (!_Host.GetPlayerStatus().Stream.IsOwner.Equals("1")) { return; } // [設定] 運営コメントは無視 var ownerFlag = NicoLibrary.NicoLiveData.PremiumFlags.Premium | NicoLibrary.NicoLiveData.PremiumFlags.ServerComment; if (excludeOwnerComment.Checked && ((e.CommentDataList[commentLastIndex].PremiumBits & (ownerFlag)) == ownerFlag)) { return; } // [設定] No1のコメントが運営コメントの場合、No2を1Get処理する if (No2AsNo1Comment.Checked && commentLastIndex == 1) { if ((e.CommentDataList[0].PremiumBits & (ownerFlag)) != ownerFlag) { // No1が運営コメントではない return; } } // No1のコメント以外は無視 else if (!e.CommentDataList[commentLastIndex].No.Equals("1")) { return; } string userId = e.CommentDataList[commentLastIndex].UserId; string nickname = _Host.GetUserSettingInPlugin().UserDataList.Find(x => x.UserId == e.CommentDataList[e.CommentDataList.Count - 1].UserId)?.NickName; int acquisitionCount = 1; HistoryData historyData = _HistoryDataList.FirstOrDefault(x => x.UserId.Equals(userId)); if (historyData == null) { // 新規登録 historyData = new HistoryData { UserId = userId, NickName = nickname, AcquisitionCount = 1, RegisterDate = DateTime.Now }; _HistoryDataList.Add(historyData); } else { // 更新 historyData.NickName = nickname; historyData.AcquisitionCount += 1; acquisitionCount = historyData.AcquisitionCount; } // 運営コメント送信有無 if (!ReplyCommentToggle.Checked) { return; } // 運営コメント編集 string ownerComment = ReplyCommentTextBox.Text; ownerComment = ownerComment.Replace("{Nickname}", !string.IsNullOrEmpty(nickname) ? nickname : "名無し") .Replace("{Count}", acquisitionCount.ToString()); // 運営コメント送信 _Host.SendOwnerComment(ownerComment); } catch { // TODO: 例外処理 // 報告しやすい(してもらいやすい)形式で出力する } }
public void Draw(MatterHackers.Agg.Transform.ITransform Position, Graphics2D renderer) { double TextHeight = m_Position.y - 20; double Range = (m_DataViewMaxY - m_DataViewMinY); VertexSourceApplyTransform TransformedLinesToDraw; Stroke StrockedTransformedLinesToDraw; RoundedRect BackGround = new RoundedRect(m_Position.x, m_Position.y - 1, m_Position.x + m_Width, m_Position.y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround = new VertexSourceApplyTransform(BackGround, Position); renderer.Render(TransformedBackGround, new RGBA_Bytes(0, 0, 0, .5)); // if the 0 line is within the window than draw it. if (m_DataViewMinY < 0 && m_DataViewMaxY > 0) { m_LinesToDraw.remove_all(); m_LinesToDraw.MoveTo(m_Position.x, m_Position.y + ((0 - m_DataViewMinY) * m_Height / Range)); m_LinesToDraw.LineTo(m_Position.x + m_Width, m_Position.y + ((0 - m_DataViewMinY) * m_Height / Range)); TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, new RGBA_Bytes(0, 0, 0, 1)); } double MaxMax = -999999999; double MinMin = 999999999; double MaxAverage = 0; foreach (KeyValuePair <String, HistoryData> historyKeyValue in m_DataHistoryArray) { HistoryData history = historyKeyValue.Value; m_LinesToDraw.remove_all(); MaxMax = System.Math.Max(MaxMax, history.GetMaxValue()); MinMin = System.Math.Min(MinMin, history.GetMinValue()); MaxAverage = System.Math.Max(MaxAverage, history.GetAverageValue()); for (int i = 0; i < m_Width - 1; i++) { if (i == 0) { m_LinesToDraw.MoveTo(m_Position.x + i, m_Position.y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } else { m_LinesToDraw.LineTo(m_Position.x + i, m_Position.y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } } TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, history.m_Color); String Text = historyKeyValue.Key + ": Min:" + MinMin.ToString("0.0") + " Max:" + MaxMax.ToString("0.0"); renderer.DrawString(Text, m_Position.x, TextHeight - m_Height); TextHeight -= 20; } RoundedRect BackGround2 = new RoundedRect(m_Position.x, m_Position.y - 1, m_Position.x + m_Width, m_Position.y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround2 = new VertexSourceApplyTransform(BackGround2, Position); Stroke StrockedTransformedBackGround = new Stroke(TransformedBackGround2); renderer.Render(StrockedTransformedBackGround, new RGBA_Bytes(0.0, 0, 0, 1)); //renderer.Color = BoxColor; //renderer.DrawRect(m_Position.x, m_Position.y - 1, m_Width, m_Height + 2); }
/// <summary> /// Reads the data at the specified time for an item. /// </summary> protected override void HistoryReadAtTime( ServerSystemContext context, ReadAtTimeDetails details, TimestampsToReturn timestampsToReturn, IList<HistoryReadValueId> nodesToRead, IList<HistoryReadResult> results, IList<ServiceResult> errors, List<NodeHandle> nodesToProcess, IDictionary<NodeId, NodeState> cache) { for (int ii = 0; ii < nodesToRead.Count; ii++) { NodeHandle handle = nodesToProcess[ii]; HistoryReadValueId nodeToRead = nodesToRead[handle.Index]; HistoryReadResult result = results[handle.Index]; HistoryReadRequest request = null; try { // validate node. NodeState source = ValidateNode(context, handle, cache); if (source == null) { continue; } // load an exising request. if (nodeToRead.ContinuationPoint != null) { request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint); if (request == null) { errors[handle.Index] = StatusCodes.BadContinuationPointInvalid; continue; } } // create a new request. else { request = CreateHistoryReadRequest( context, details, handle, nodeToRead); } // process values until the max is reached. HistoryData data = new HistoryData(); while (request.NumValuesPerNode == 0 || data.DataValues.Count < request.NumValuesPerNode) { if (request.Values.Count == 0) { break; } DataValue value = request.Values.First.Value; request.Values.RemoveFirst(); data.DataValues.Add(value); } errors[handle.Index] = ServiceResult.Good; // check if a continuation point is requred. if (request.Values.Count > 0) { result.ContinuationPoint = SaveContinuationPoint(context, request); } // check if no data returned. else { errors[handle.Index] = StatusCodes.GoodNoData; } // return the data. result.HistoryData = new ExtensionObject(data); } catch (Exception e) { errors[handle.Index] = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error processing request."); } } }
public static IEnumerable <HistoryData> LoadFromFile(DateTime start, DateTime end, bool sdt = false) { //Stopwatch sw = Stopwatch.StartNew(); //文件的组织格式:头文件:31,ln为间隔日期,position为指向日期段的指针,sizes为日期段的长度。 //每日的抬头:按ID次序,包含每个TAG的数量,arr为每个日期所有的标签、每标签数量、数据类型、位置指针。 //按时间排序,每个标签的值、时间戳。 string path = string.Concat(m_Path, "\\", start.Year.ToString(), "-", start.Month.ToString(), sdt ? ".sdt" : ".bin"); if (!File.Exists(path)) { yield break; } int day1 = start.Day; int startTicks = new SqlDateTime(start).TimeTicks; int endTicks = new SqlDateTime(end).TimeTicks; int ln = end.Day - day1 + 1; using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader reader = new BinaryReader(stream); long[] positions = new long[ln + 1]; long[] sizes = new long[ln]; stream.Seek((day1 - 1) * 8, SeekOrigin.Begin); positions[0] = reader.ReadInt64(); for (int i = 0; i < ln; i++) { positions[i + 1] = reader.ReadInt64(); sizes[i] = positions[i + 1] - positions[i];//每一天数据的长度 } //reader.Close(); HistoryData data = HistoryData.Empty; using (MemoryMappedFile mapp = MemoryMappedFile.CreateFromFile(stream, Guid.NewGuid().ToString(), 0, MemoryMappedFileAccess.Read, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, false)) { for (int k = 0; k < ln; k++) { if (positions[k] < 0x100 || sizes[k] <= 0 || positions[k] + sizes[k] > stream.Length) { continue; } using (MemoryMappedViewAccessor acc = mapp.CreateViewAccessor(positions[k], sizes[k], MemoryMappedFileAccess.Read)) { long pos = 0; int day = acc.ReadInt32(pos); pos += 8; int count = acc.ReadInt32(pos); pos += 4; HDataFormat[] arr = new HDataFormat[count]; for (int i = 0; i < count; i++) { arr[i].ID = acc.ReadInt16(pos); pos += 2; arr[i].Type = (DataType)acc.ReadByte(pos); pos++; arr[i].Count = acc.ReadInt32(pos);//4个字节是预留 pos += 8; } long tempos = pos; for (int i = 0; i < count; i++) { int con = arr[i].Count; int j = 0; pos = tempos + acc.ReadInt32(i * 11 + 19); long pf = pos; DataType type = arr[i].Type; int len = dataLen[(int)type]; if (k == 0) //判断是否为起始日期或结束日期 { int ind = BinarySearchTime(acc, pf, con, len, startTicks); if (ind < 0) { ind = ~ind; } j += ind; pos += ind * len; } if (k == ln - 1) { int index = BinarySearchTime(acc, pf, con, len, endTicks); con = index >= 0 ? index : ~index; } while (j++ < con) { data.ID = arr[i].ID; data.TimeStamp = new SqlDateTime(day, acc.ReadInt32(pos)).Value; pos += 4; switch (type) { case DataType.BOOL: data.Value.Boolean = acc.ReadBoolean(pos); pos++; break; case DataType.BYTE: data.Value.Byte = acc.ReadByte(pos); pos++; break; case DataType.WORD: case DataType.SHORT: data.Value.Int16 = acc.ReadInt16(pos); pos += 2; break; case DataType.INT: data.Value.Int32 = acc.ReadInt32(pos); pos += 4; break; case DataType.FLOAT: data.Value.Single = acc.ReadSingle(pos); pos += 4; break; } yield return(data); } } } } } } yield break; }
/// <summary> /// Displays the results of a history operation. /// </summary> private void DisplayResults(HistoryData values) { foreach (DataValue value in values.DataValues) { AddValue(value, null); } m_dataset.AcceptChanges(); }
public static IEnumerable <HistoryData> LoadFromFile(DateTime start, DateTime end, short ID, bool sdt = false) { string path = string.Concat(m_Path, "\\", start.Year.ToString(), "-", start.Month.ToString(), sdt ? ".sdt" : ".bin");//bin-sdt if (!File.Exists(path)) { yield break; } int day1 = start.Day; int startTicks = new SqlDateTime(start).TimeTicks; //开始日期部分的4位数据 int endTicks = new SqlDateTime(end).TimeTicks; int ln = end.Day - day1 + 1; //日期天数 using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { long filelen = stream.Length; //文件长度 BinaryReader reader = new BinaryReader(stream); long[] positions = new long[ln]; //每日数据指针(指向第一条数据,包括当日数据索引区) stream.Seek((day1 - 1) * 8, SeekOrigin.Begin); ///找到对应的开始日期索引位置 for (int i = 0; i < ln; i++) { positions[i] = reader.ReadInt64();//读入时间段内每日数据长度值 } long[] sizes = new long[ln]; for (int i = 0; i < ln; i++) { if (positions[i] >= filelen) { break; //如果读入长度超过文件大小则退出 } stream.Seek(positions[i] + 8, SeekOrigin.Begin); //定位文件指针到当日数据开头 sizes[i] = reader.ReadInt32(); //sizes为当日该标签数 } //reader.Close(); HistoryData data = HistoryData.Empty; //stream.Read(new byte[] using (MemoryMappedFile mapp = MemoryMappedFile.CreateFromFile(stream, Guid.NewGuid().ToString(), filelen, MemoryMappedFileAccess.Read, new MemoryMappedFileSecurity(), HandleInheritability.Inheritable, false)) { for (int k = 0; k < ln; k++)//先读入当日索引区 { if (positions[k] < 0x100 || sizes[k] <= 0 || positions[k] + sizes[k] > filelen) { continue; } //if (sizes[k] == 0) continue; long pos = 0; int count = 0; int day = 0; int len = 0; DataType type = DataType.NONE; using (MemoryMappedViewAccessor acc1 = mapp.CreateViewAccessor(positions[k], 12 + sizes[k] * 11, MemoryMappedFileAccess.Read)) //12是头的长度,11是一个格式字段的长度 { day = acc1.ReadInt32(0); //当日日期部分 int index = BinarySearch(acc1, (int)sizes[k], ID); //找到当天 指定标签的记录索引 if (index >= 0) { index = index * 11 + 12;//如找到,则定位到当日数据的元数据(相对位移) } //sw.Stop(); else { continue; } byte tp = acc1.ReadByte(index + 2); //读入数据类型 type = (DataType)tp; len = dataLen[tp]; //4,6,8分别为存储的标签长度,其中4字节是时间戳 count = acc1.ReadInt32(index + 3); //读入数量 pos = positions[k] + 12 + sizes[k] * 11 + acc1.ReadInt32(index + 7); //指针指向当日当前标签第一条记录 } using (MemoryMappedViewAccessor acc2 = mapp.CreateViewAccessor(pos, count * len, MemoryMappedFileAccess.Read)) //重新从头定位文件指针到数据区 { pos = 0; int j = 0; if (k == 0) //判断是否为起始日期或结束日期 { int ind = BinarySearchTime(acc2, 0, count, len, startTicks); //根据时间排序方式二分法查找当日当前时间节点的数据,如为第一日 if (ind < 0) { ind = ~ind; } j += ind; pos += ind * len; } if (k == ln - 1) { int ind = BinarySearchTime(acc2, 0, count, len, endTicks);//如果为最后一日的数据,则按结束时间定位 count = ind >= 0 ? ind : ~ind; } while (j++ < count) { data.ID = ID; data.TimeStamp = new SqlDateTime(day, acc2.ReadInt32(pos)).Value; //日期在前(4位) pos += 4; //数据区也是4位 switch (type) { case DataType.BOOL: data.Value.Boolean = acc2.ReadBoolean(pos); pos++; break; case DataType.BYTE: data.Value.Byte = acc2.ReadByte(pos); pos++; break; case DataType.WORD: case DataType.SHORT: data.Value.Int16 = acc2.ReadInt16(pos); pos += 2; break; case DataType.INT: data.Value.Int32 = acc2.ReadInt32(pos); pos += 4; break; case DataType.FLOAT: data.Value.Single = acc2.ReadSingle(pos); pos += 4; break; } yield return(data); } } } } reader.Close(); } yield break; }
/// <summary> /// Reads the raw data for a variable /// </summary> protected ServiceResult HistoryReadRaw( ISystemContext context, BaseVariableState source, ReadRawModifiedDetails details, TimestampsToReturn timestampsToReturn, bool releaseContinuationPoints, HistoryReadValueId nodeToRead, HistoryReadResult result) { ServerSystemContext serverContext = context as ServerSystemContext; HistoryDataReader reader = null; HistoryData data = new HistoryData(); if (nodeToRead.ContinuationPoint != null && nodeToRead.ContinuationPoint.Length > 0) { // restore the continuation point. reader = RestoreDataReader(serverContext, nodeToRead.ContinuationPoint); if (reader == null) { return StatusCodes.BadContinuationPointInvalid; } // node id must match previous node id. if (reader.VariableId != nodeToRead.NodeId) { Utils.SilentDispose(reader); return StatusCodes.BadContinuationPointInvalid; } // check if releasing continuation points. if (releaseContinuationPoints) { Utils.SilentDispose(reader); return ServiceResult.Good; } } else { // get the source for the variable. IHistoryDataSource datasource = null; ServiceResult error = GetHistoryDataSource(serverContext, source, out datasource); if (ServiceResult.IsBad(error)) { return error; } // create a reader. reader = new HistoryDataReader(nodeToRead.NodeId, datasource); // start reading. reader.BeginReadRaw( serverContext, details, timestampsToReturn, nodeToRead.ParsedIndexRange, nodeToRead.DataEncoding, data.DataValues); } // continue reading data until done or max values reached. bool complete = reader.NextReadRaw( serverContext, timestampsToReturn, nodeToRead.ParsedIndexRange, nodeToRead.DataEncoding, data.DataValues); // save continuation point. if (!complete) { SaveDataReader(serverContext, reader); result.StatusCode = StatusCodes.GoodMoreData; } // return the dat. result.HistoryData = new ExtensionObject(data); return result.StatusCode; }
public static IEnumerable <HistoryData> LoadFromDatabaseAtTime(short?ID, params DateTime[] timeStamps) { StringBuilder sql = new StringBuilder("SELECT "); if (ID == null) { sql.Append("ID,"); } sql.Append(" [TIMESTAMP],[VALUE],M.DATATYPE FROM LOG_HDATA L INNER JOIN META_TAG M ON L.ID=M.TAGID WHERE"); if (ID != null) { sql.Append(" ID=").Append(ID.Value).Append(" AND "); } sql.Append(" [TIMESTAMP] IN("); for (int i = 0; i < timeStamps.Length; i++) { sql.Append("'").Append(timeStamps[i]).Append("',"); } using (SqlDataReader dataReader = DataHelper.ExecuteReader(sql.Append("1)").ToString())) { if (dataReader == null) { yield break; } HistoryData data = HistoryData.Empty; int itime = ID == null ? 0 : 1; int ivalue = ID == null ? 1 : 2; int itype = ID == null ? 2 : 3; while (dataReader.Read()) { data.ID = ID == null?dataReader.GetInt16(0) : ID.Value; data.TimeStamp = dataReader.GetDateTime(itime); switch ((DataType)dataReader.GetByte(itype)) { case DataType.BOOL: data.Value.Boolean = dataReader.GetFloat(ivalue) > 0 ? true : false; break; case DataType.BYTE: data.Value.Byte = Convert.ToByte(dataReader.GetFloat(ivalue)); break; case DataType.WORD: case DataType.SHORT: data.Value.Int16 = Convert.ToInt16(dataReader.GetFloat(ivalue)); break; case DataType.INT: data.Value.Int32 = Convert.ToInt32(dataReader.GetFloat(ivalue)); break; case DataType.FLOAT: data.Value.Single = dataReader.GetFloat(ivalue); break; } yield return(data); } } yield break; }
/// <summary> /// Reads the history of an HDA item annotations. /// </summary> private ServiceResult HistoryReadAnnotations( ServerSystemContext context, ComHdaClient client, ReadRawModifiedDetails details, TimestampsToReturn timestampsToReturn, HistoryReadValueId nodeToRead, HdaParsedNodeId parsedNodeId, HistoryReadResult result) { // create the request or load it from a continuation point. HdaHistoryReadAnnotationRequest request = null; if (nodeToRead.ContinuationPoint == null) { // create a new request. request = new HdaHistoryReadAnnotationRequest(parsedNodeId.RootId, details, nodeToRead); // fetch all of the data at once. result.StatusCode = client.ReadAnnotationHistory(request); } else { request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint) as HdaHistoryReadAnnotationRequest; if (request == null) { return StatusCodes.BadContinuationPointInvalid; } } // select a subset of the results. if (StatusCode.IsGood(result.StatusCode)) { request.Results = new DataValueCollection(); request.GetHistoryResults(context, nodeToRead, request.Results); } // fill in the results. if (request.Results != null) { HistoryData data = new HistoryData(); data.DataValues = request.Results; result.HistoryData = new ExtensionObject(data); } // create a new continuation point. if (!request.Completed) { result.ContinuationPoint = SaveContinuationPoint(context, request); } return result.StatusCode; }
public static List <HistoryResponse <OldNewValueResponse> > ProcessOldNewValues <T>(this HistoryData data, List <string> excludedProperties, string userFullName) where T : DeletableEntity { var result = new List <HistoryResponse <OldNewValueResponse> >(); var oldVal = data.OldVal.DeserializeToEntity <T>(); var newVal = data.NewVal.DeserializeToEntity <T>(); var oldPropValues = oldVal.GetEnityPropertyValues(true, excludedProperties); var newPropValues = newVal.GetEnityPropertyValues(true, excludedProperties); foreach (var newProp in newPropValues) { var oldProp = oldPropValues.FirstOrDefault(x => x.Key == newProp.Key); //if the oldVal of property is the same with newVal, do not show if (oldProp.Value?.ToString() == newProp.Value?.ToString()) { continue; } result.Add(new HistoryResponse <OldNewValueResponse> { Id = data.Id, Date = data.Date, Item = new OldNewValueResponse { Date = data.Date, User = userFullName ?? string.Empty, Field = newProp.Key.ToTitleCase(), OldValue = oldProp.Value?.ToString() ?? string.Empty, NewValue = newProp.Value?.ToString(), Action = data.Operation.GetDescription() } }); } return(result); }
void Init (HistoryData historydata) { historyLabel.text = historydata.Date +"\n" + historydata.Result; }
/// <summary> /// 从指定路径的文件读取历史数据 /// </summary> /// <param name="path"></param> /// <returns></returns> private List <HistoryData> LoadHistoryInfo(string path, out string title) { List <HistoryData> list = new List <HistoryData>(); int i = 0; title = ""; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8); while (!sr.EndOfStream) { if (i == 0) { title = sr.ReadLine();//首行为标题 } else { string rowInfo = sr.ReadLine();//数据行 string[] hisData = rowInfo.Split(';'); if (hisData.Length > 0) { string[] HistoryData = hisData[0].Split(','); /*历史数据: * (1)温湿度 2019-10-12 09:00:00.111,23.45,12.1; * (2)电流值 2019-10-12 09:00:00.111,23.2; */ if (HistoryData.Length > 0) { for (int j = 1; j <= HistoryData.Length - 1; j++) { HistoryData his = new HistoryData(); his.id = j; his.time = Convert.ToDateTime(HistoryData[0]); his.value = Convert.ToDouble(HistoryData[j]); list.Add(his); } } //if (HistoryData.Length == 3) //{ // //温度、湿度 // for(int j = 1; j < HistoryData.Length-1; j++) // { // HistoryData his = new HistoryData(); // his.id = i; // his.time = Convert.ToDateTime(HistoryData[0]); // his.value = Convert.ToDouble(HistoryData[i]); // list.Add(his); // } //} //else if(HistoryData.Length == 2) //{ // //电流 // HistoryData his = new HistoryData(); // his.id = 1; // his.time = Convert.ToDateTime(HistoryData[0]); // his.value = Convert.ToDouble(HistoryData[1]); // list.Add(his); //} } } i++; } return(list); }
public void perform(HistoryData data, double input, IPresenter presenter) { data.Reset(); presenter.showStatus(1, "Done."); }
/// <summary> /// 获取开奖结果 /// </summary> /// <param name="PageURL"></param> /// <param name="name"></param> private LotteryResult GetResult(string subUrl) { LotteryResult lr = new LotteryResult(); lr.isRight = false; if (task.website.StartsWith("https://www.1393c.com")) { string subHtml = Browser.getHtml(subUrl); HtmlAgilityPack.HtmlDocument subdoc = new HtmlAgilityPack.HtmlDocument(); subdoc.LoadHtml(subHtml); HtmlNodeCollection nodes = subdoc.DocumentNode.SelectNodes("//table[@class='lot-table']//tr[2]"); if (nodes != null) { List <LotteryResult> rst = new List <LotteryResult>(); foreach (HtmlNode node in nodes) { HtmlNodeCollection tds = node.SelectNodes("td"); int tdNum = tds.Count; //lr = new LotteryResult(); int no = 0; lr.lotteryID = task.lotteryID; lr.lotteryType = task.lotteryType; HtmlNodeCollection ps = tds[no++].SelectNodes("p"); lr.No = StringHelper.trimEnd(ps[0].InnerText).Replace("-", ""); lr.time = StringHelper.trimEnd(ps[1].InnerText); //开奖号码 Match m = Regex.Match(tds[no++].InnerHtml, @"\d+"); while (m.Success) { lr.Number += (StringHelper.trimEnd(m.Value) + ","); m = m.NextMatch(); } //冠亚和 lr.guanYaHe += StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText); //龙虎 lr.longHu = StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText); rst.Add(lr); } //DapperHelper.setLotteryResult(rst); } } else if (task.website.StartsWith("https://1680380.com")) { string subHtml = Browser.getHtml(subUrl); HtmlAgilityPack.HtmlDocument subdoc = new HtmlAgilityPack.HtmlDocument(); subdoc.LoadHtml(subHtml); HtmlNodeCollection nodes = subdoc.DocumentNode.SelectNodes("//div[@id='jrsmhmtj']//tr[2]");//position()>1 if (nodes != null) { List <LotteryResult> rst = new List <LotteryResult>(); foreach (HtmlNode node in nodes) { HtmlNodeCollection tds = node.SelectNodes("td"); //lr = new LotteryResult(); int no = 0; lr.lotteryID = task.lotteryID; lr.lotteryType = task.lotteryType; //时间 lr.time = StringHelper.trimEnd(tds[no++].InnerText); //期数 lr.No = StringHelper.trimEnd(tds[no++].InnerText).Replace("-", ""); //开奖号码 HtmlNodeCollection lis = tds[no++].SelectNodes("ul/li/i"); foreach (HtmlNode li in lis) { lr.Number += StringHelper.trimEnd(li.InnerText) + ","; } //冠亚和 lr.guanYaHe += StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText); //龙虎 lr.longHu = StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText) + "," + StringHelper.trimEnd(tds[no++].InnerText); rst.Add(lr); } //DapperHelper.setLotteryResult(rst); } } else { string apiUrl = string.Format("http://cx971.com/pc/index/getLottoDetail?lottoName={0}&page=1&showpage=10", subUrl); string subHtml = Browser.getResponse(apiUrl); HistoryData hd = JsonConvert.DeserializeObject <HistoryData>(subHtml); if (hd != null) { List <LotteryResult> rst = new List <LotteryResult>(); foreach (History his in hd.data.history) { //lr = new LotteryResult(); lr.lotteryID = task.lotteryID; lr.lotteryType = task.lotteryType; //时间 lr.time = his.timeDraw; //期数 lr.No = (his.qishu + "").Replace("-", ""); //开奖号码 foreach (int n in his.nums) { lr.Number += StringHelper.trimEnd(n.ToString()) + ","; } //冠亚和 lr.guanYaHe = ((his.nums[0] + his.nums[1]) + "," + (his.SumBigSmall == "1"?"大,":"小,") + (his.SumOddEven == "1" ? "单" : "双")); //龙虎 lr.longHu = (his.DragonTiger1 == "1"?"龙,":"虎,") + (his.DragonTiger2 == "1" ? "龙," : "虎,") + (his.DragonTiger3 == "1" ? "龙," : "虎,") + (his.DragonTiger4 == "1" ? "龙," : "虎,") + (his.DragonTiger5 == "1" ? "龙" : "虎"); rst.Add(lr); break; } //DapperHelper.setLotteryResult(rst); } } return(lr); }