public void GetBytesTest() { UInt32Attribute target = new Bandwidth() { Value = 0x87654321, }; byte[] expected = new byte[] { 0xee, 0xee, 0xee, 0xee, 0x00, 0x10, 0x00, 0x04, 0x87, 0x65, 0x43, 0x21, }; byte[] actual = new byte[] { 0xee, 0xee, 0xee, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; int startIndex = 4; target.GetBytes(actual, ref startIndex); Assert.AreEqual(12, startIndex); Helpers.AreArrayEqual(expected, actual); }
/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { // used to set values for bars less than the period int tmpPeriod = Math.Min(CurrentBar, Period); double average = Close[0]; switch (averageType) { case BollingerBandwidth_MATypes.EMA: average = EMA(tmpPeriod)[0]; break; case BollingerBandwidth_MATypes.SMA: average = SMA(tmpPeriod)[0]; break; } double stdDevValue = StdDev(tmpPeriod)[0]; double upperValue = average + numStdDev * stdDevValue; double lowerValue = average - numStdDev * stdDevValue; Bandwidth.Set((upperValue - lowerValue) / average * 100); Bulge.Set(MAX(Bandwidth, bulgeLength)[0]); Squeeze.Set(MIN(Bandwidth, squeezeLength)[0]); }
public async Task <IActionResult> Edit(int id, [Bind("ID,Name,Value")] Bandwidth bandwidth) { if (id != bandwidth.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(bandwidth); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BandwidthExists(bandwidth.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(bandwidth)); }
public void TestCalculateAverageSpeed() { // arrange int delayTime = 50; int receivedBytesPerDelay = 250; int testElapsedTime = 4000; // 4s int repeatCount = testElapsedTime / delayTime; Bandwidth calculator = new Bandwidth(); var speedHistory = new List <double>(); // act for (int i = 0; i < repeatCount; i++) { Thread.Sleep(delayTime); calculator.CalculateSpeed(receivedBytesPerDelay); speedHistory.Add(calculator.Speed); } // assert var expectedAverageSpeed = Math.Ceiling(speedHistory.Average()); var actualAverageSpeed = Math.Ceiling(calculator.AverageSpeed); var theoryAverageSpeed = 1000 / delayTime * receivedBytesPerDelay; Assert.IsTrue(expectedAverageSpeed < actualAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Expected Average Speed is: {expectedAverageSpeed}"); Assert.IsTrue(actualAverageSpeed < theoryAverageSpeed, $"Actual Average Speed is: {actualAverageSpeed} , Theory Average Speed is: {theoryAverageSpeed}"); }
/// <summary> /// Puts the sensor into initial state. /// </summary> /// <param name="bandwidth">Digital low-pass filter configuration.</param> /// <param name="sampleRateDivider">Sample rate divider: Fsample = Finternal / (divider + 1).</param> public void Init(Bandwidth bandwidth = Bandwidth.Hz42, byte sampleRateDivider = 0) { bus.Write(0x3E, 0x00); bus.Write(0x15, sampleRateDivider); bus.Write(0x16, (byte)(0x18 | (byte)bandwidth)); bus.Write(0x17, 0x00); }
public void OnBandwidthUpdated(long upload, long download) { if (InvokeRequired) { BeginInvoke(new Action <long, long>(OnBandwidthUpdated), upload, download); return; } try { if (upload < 1 || download < 1) { return; } UsedBandwidthLabel.Text = $"{i18N.Translate("Used", ": ")}{Bandwidth.Compute(upload + download)}"; UploadSpeedLabel.Text = $"↑: {Bandwidth.Compute(upload - LastUploadBandwidth)}/s"; DownloadSpeedLabel.Text = $"↓: {Bandwidth.Compute(download - LastDownloadBandwidth)}/s"; LastUploadBandwidth = upload; LastDownloadBandwidth = download; Refresh(); } catch { // ignored } }
private bool HandleTunnelData(IEnumerable <TunnelDataMessage> msgs) { EncryptTunnelMessages(msgs); #if LOG_ALL_TUNNEL_TRANSFER LogDataSent.Log(() => "PassthroughTunnel " + Destination.Id32Short + " TunnelData sent."); #endif var dropped = 0; foreach (var one in msgs) { if (Limiter.DropMessage()) { ++dropped; continue; } one.TunnelId = SendTunnelId; Bandwidth.DataSent(one.Payload.Length); TransportProvider.Send(Destination, one); } #if LOG_ALL_TUNNEL_TRANSFER if (dropped > 0) { DebugUtils.LogDebug(() => string.Format("{0} bandwidth limit. {1} dropped messages. {2}", this, dropped, Bandwidth)); } #endif return(true); }
public void GetBytesTest() { UInt32Attribute target = new Bandwidth() { Value = 0x87654321, }; byte[] expected = new byte[] { 0xee, 0xee, 0xee, 0xee, 0x00, 0x10, 0x00, 0x04, 0x87, 0x65, 0x43, 0x21, }; byte[] actual = new byte[] { 0xee, 0xee, 0xee, 0xee, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; int startIndex = 4; target.GetBytes(actual, ref startIndex); Assert.AreEqual(12, startIndex); Helpers.AreArrayEqual(expected, actual); }
/// <summary> /// Puts the sensor into initial state. /// </summary> /// <param name="scale">Full scale acceleration range.</param> /// <param name="bandwidth">Bandwidth defining type and quality of filters.</param> public void Init(ScaleRange scale = ScaleRange.G2, Bandwidth bandwidth = Bandwidth.Hz150) { EnableSettingsEditing(); SetScaleRange((byte)scale); SetBandwidth((byte)bandwidth); BlockMsbWhileLsbIsRead(); }
public static Bandwidth GetBandwidthInfo() { Bandwidth bandwidth = default(Bandwidth); PrxNetInfoGetBandwidth(out bandwidth); return(bandwidth); }
private void EditButton_Click(object sender, EventArgs e) { double Bandwidth; if (BandBox.Text == "" || !double.TryParse(BandBox.Text, out Bandwidth))//prawdopodobnie można wywalić sprawdanie pustego { host.messageQueue.Enqueue(Logger.Log("Wrong band width.", LogType.ERROR)); return; } AllLockedState(); try { if (host.ReSetSession(Bandwidth)) { host.messageQueue.Enqueue(Logger.Log("Band changed to " + Bandwidth.ToString() + " Mbps.", LogType.INFO)); SessionState(); } else { host.messageQueue.Enqueue(Logger.Log("Failed to change bandwidth", LogType.ERROR)); SessionState(); } } catch (Exception ex) { host.messageQueue.Enqueue(Logger.Log(ex.Message, LogType.ERROR)); InitState(); } }
public StandardConfig(bool enable, Radio radio, int @if, Bandwidth bandwidth, SpreadingFactor spreadingFactor) { Enable = enable; Radio = radio; If = @if; Bandwidth = bandwidth; SpreadingFactor = spreadingFactor; }
public void From(SpreadingFactor sf, Bandwidth bw) { var subject = LoRaDataRate.From(sf, bw); Assert.Equal(sf, subject.SpreadingFactor); Assert.Equal(bw, subject.Bandwidth); Assert.Equal(ModulationKind.LoRa, subject.ModulationKind); }
private bool HandleReceiveQueue() { II2NPHeader16[] messages = null; lock ( ReceiveQueue ) { if (ReceiveQueue.Count == 0) { return(true); } var msgs = new List <II2NPHeader16>(); int dropped = 0; foreach (var msg in ReceiveQueue) { if (Limiter.DropMessage()) { ++dropped; continue; } msgs.Add((II2NPHeader16)msg); } messages = msgs.ToArray(); #if LOG_ALL_TUNNEL_TRANSFER if (dropped > 0) { if (FilterMessageTypes.Update(new HashedItemGroup(Destination, 0x63e9))) { Logging.LogDebug(() => string.Format("{0} bandwidth limit. {1} dropped messages. {2}", this, dropped, Bandwidth)); } } #endif } if (messages == null || messages.Length == 0) { return(true); } var tdata = TunnelDataMessage.MakeFragments(messages.Select(msg => (TunnelMessage)(new TunnelMessageLocal(msg))), SendTunnelId); EncryptTunnelMessages(tdata); #if LOG_ALL_TUNNEL_TRANSFER if (FilterMessageTypes.Update(new HashedItemGroup(Destination, 0x17f3))) { Logging.Log("GatewayTunnel " + Destination.Id32Short + ": TunnelData sent."); } #endif foreach (var tdmsg in tdata) { Bandwidth.DataSent(tdmsg.Payload.Length); TransportProvider.Send(Destination, tdmsg); } return(true); }
private async Task ControlFun() { Configuration.Save(); if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 if (!(ServerComboBox.SelectedItem is Server server)) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (!(ModeComboBox.SelectedItem is Models.Mode mode)) { MessageBoxX.Show(i18N.Translate("Please select a mode first")); return; } // 清除模式搜索框文本选择 ModeComboBox.Select(0, 0); State = State.Starting; if (await MainController.Start(server, mode)) { State = State.Started; _ = Task.Run(() => { Bandwidth.NetTraffic(); }); // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; if (_isFirstCloseWindow) { // 显示提示语 NotifyTip(i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore.")); _isFirstCloseWindow = false; } Hide(); } } else { State = State.Stopped; StatusText(i18N.Translate("Start failed")); } } else { // 停止 State = State.Stopping; await MainController.Stop(); State = State.Stopped; } }
public bool BandWidthCheckCheckSupport(Bandwidth ban) { if (this.BandWithSupport.Contains(ban)) { return(true); } return(false); }
public void AddBandwidth(SessionBandwidth sessionBandwidth) { if (Bandwidth == null) { Bandwidth = new List <SessionBandwidth>(); } Bandwidth.Add(sessionBandwidth); }
public override int GetHashCode() { unchecked { var hashCode = Bandwidth.GetHashCode(); hashCode = (hashCode * 397) ^ MinBufferTime.GetHashCode(); hashCode = (hashCode * 397) ^ Stream.GetHashCode(); return(hashCode); } }
public async Task <IActionResult> Create([Bind("ID,Name,Value")] Bandwidth bandwidth) { if (ModelState.IsValid) { _context.Add(bandwidth); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(bandwidth)); }
//===================================================================== /// <summary> /// Return Best Intersection Bandwith for use in TDLS /// </summary> /// <param name="otherBandWith">Array list of supported Bandwith for other device</param> /// <returns>Return Best Intersection Bandwith</returns> public Bandwidth GetBestIntersectionBandwith(ArrayList otherBandWith) { Bandwidth ret = Bandwidth._20MHz; if (this.BandWithSupport.Contains(Bandwidth._40Mhz) && otherBandWith.Contains(Bandwidth._40Mhz)) { ret = Bandwidth._40Mhz; } return(ret); }
private static void WriteBandwidthToDb(Bandwidth Bandwidth) { try { var client = new MongoClient("mongodb://" + dbServer); var database = client.GetDatabase(dbName); database.GetCollection <Bandwidth>(Bandwidth.Site).InsertOne(Bandwidth); } catch (Exception e) { Console.WriteLine(e); } }
public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine("\nMetaData Configuration:"); sb.AppendLine("\tStream = " + Stream); sb.AppendLine("\tBandwidth = " + (Bandwidth.HasValue ? Bandwidth.ToString() : "N/A")); sb.AppendLine("\tMinBufferTime = " + (MinBufferTime.HasValue ? MinBufferTime.ToString() : "N/A")); sb.AppendLine("\tBufferDuration = " + BufferDuration); return(sb.ToString()); }
/// <summary> /// Displays the equation for the bandwidth. /// </summary> private void bandwidthButton_Click(object sender, EventArgs e) { if (Bandwidth.Instance == false) { Bandwidth form = new Bandwidth(this); form.Show(this); Bandwidth.Instance = true; } else if (Bandwidth.Instance) { // Do nothing. } }
public void CanDeSerialize() { var field = $"b=X-YZ:128".ToByteArray(); var result = BandwithSerializer.Instance.ReadValue(field); var expected = new Bandwidth() { Type = "X-YZ", Value = "128", }; Assert.True(CheckIfAreSame(expected, result)); }
/// <summary> /// Converts the bandwidth to specific unit. /// </summary> /// <param name="bandwidth"> /// The bandwidth. /// </param> /// <param name="transferUnit"> /// The transfer unit. /// </param> /// <returns> /// Conversion result. /// </returns> public static double To(this Bandwidth bandwidth, TransferUnit transferUnit) { if (TransferUnit.Kilobytes == transferUnit) { return(bandwidth.Kilobytes); } if (TransferUnit.Megabytes == transferUnit) { return(bandwidth.Megabytes); } return(bandwidth.Gigabytes); }
public void ParseTest() { byte[] bytes = new byte[] { 0xff, 0xff, 0xff, 0x00, 0x10, 0x00, 0x04, 0x12, 0x34, 0x56, 0x78, }; int startIndex = 3; UInt32Attribute target = new Bandwidth(); target.Parse(bytes, ref startIndex); Assert.AreEqual(11, startIndex); Assert.AreEqual(0x12345678, target.Value); }
public void OnBandwidthUpdated(long download) { try { UsedBandwidthLabel.Text = $"{i18N.Translate("Used", ": ")}{Bandwidth.Compute(download)}"; //UploadSpeedLabel.Text = $"↑: {Utils.Bandwidth.Compute(upload - LastUploadBandwidth)}/s"; DownloadSpeedLabel.Text = $"↑↓: {Bandwidth.Compute(download - LastDownloadBandwidth)}/s"; //LastUploadBandwidth = upload; LastDownloadBandwidth = download; Refresh(); } catch (Exception) { } }
public void ParseTest() { byte[] bytes = new byte[] { 0xff, 0xff, 0xff, 0x00, 0x10, 0x00, 0x04, 0x12, 0x34, 0x56, 0x78, }; int startIndex = 3; UInt32Attribute target = new Bandwidth(); target.Parse(bytes, ref startIndex); Assert.AreEqual(11, startIndex); Assert.AreEqual(0x12345678, target.Value); }
public void WriteValue(IBufferWriter <byte> writer, Bandwidth value) { if (value == null) { return; } SerializationHelpers.EnsureFieldIsPresent("Bandwith field Type", value.Type); SerializationHelpers.CheckForReserverdChars("Connection Data nettype", value.Type, ReservedChars); SerializationHelpers.EnsureFieldIsPresent("Bandwith field value", value.Value); SerializationHelpers.CheckForReserverdChars("Bandwith field value", value.Value, ReservedChars); var field = $"b={value.Type}:{value.Value}{SDPSerializer.CRLF}"; writer.WriteString(field); }
public async Task CanSerialize() { var expected = $"b=X-YZ:128{SDPLib.SDPSerializer.CRLF}".ToByteArray(); var pipe = new Pipe(); var value = new Bandwidth() { Type = "X-YZ", Value = "128", }; BandwithSerializer.Instance.WriteValue(pipe.Writer, value); pipe.Writer.Complete(); var serialized = (await pipe.Reader.ReadAsync()).Buffer.ToArray(); Assert.Equal(expected, serialized); }
private bool CreateTunnelMessageFragments(IEnumerable <TunnelMessage> messages) { var data = TunnelDataMessage.MakeFragments(messages, SendTunnelId); var encr = OutboundGatewayDecrypt(data); foreach (var msg in encr) { #if LOG_ALL_TUNNEL_TRANSFER if (FilterMessageTypes.Update(new HashedItemGroup((int)msg.MessageType, 0x4272))) { Logging.LogDebug($"OutboundTunnel: Send {NextHop.Id32Short} : {msg}"); } #endif Bandwidth.DataSent(msg.Payload.Length); TransportProvider.Send(NextHop, msg); } return(true); }
public void OnBandwidthUpdated(long upload, long download) { try { if (upload < 1 || download < 1) { return; } UsedBandwidthLabel.Text = $"{i18N.Translate("Used",": ")}{Bandwidth.Compute(upload + download)}"; UploadSpeedLabel.Text = $"↑: {Bandwidth.Compute(upload - LastUploadBandwidth)}/s"; DownloadSpeedLabel.Text = $"↓: {Bandwidth.Compute(download - LastDownloadBandwidth)}/s"; LastUploadBandwidth = upload; LastDownloadBandwidth = download; Refresh(); } catch (Exception) { } }
public Bandwidth ReadValue(ReadOnlySpan <byte> data) { var remainingSlice = data; // header SerializationHelpers.ParseRequiredHeader("Bandwith field", remainingSlice, HeaderBytes); remainingSlice = remainingSlice.Slice(HeaderBytes.Length); var bandwith = new Bandwidth(); // type bandwith.Type = SerializationHelpers.ParseRequiredString("Bandwith field: Type", SerializationHelpers.NextRequiredDelimitedField("Bandwith field: Type", SDPSerializer.ByteColon, remainingSlice, out var consumed)); remainingSlice = remainingSlice.Slice(consumed + 1); // value bandwith.Value = SerializationHelpers.ParseRequiredString("Bandwith field: value", remainingSlice); return(bandwith); }
public void OnBandwidthUpdated(ulong download) { if (InvokeRequired) { BeginInvoke(new Action <ulong>(OnBandwidthUpdated), download); return; } if (State == State.Started) { try { labelUsed.Text = $"{Bandwidth.Compute(download)}"; labelSpeed.Text = $"{Bandwidth.Compute(download - LastDownloadBandwidth)}/s"; //LastUploadBandwidth = upload; LastDownloadBandwidth = download; Refresh(); } catch { // ignored } } }
public bool BandWidthCheckCheckSupport(Bandwidth ban) { if(this.BandWithSupport.Contains(ban)) { return true; } return false; }
public void BandwidthConstructorTest() { Bandwidth target = new Bandwidth(); Assert.AreEqual(AttributeType.Bandwidth, target.AttributeType); }
private void ParseAttributes(byte[] bytes, int startIndex, int length, TurnMessageRfc rfc) { int currentIndex = startIndex + HeaderLength; int endIndex = startIndex + length; while (currentIndex < endIndex) { UInt16 attributeType1 = bytes.BigendianToUInt16(currentIndex); if (Enum.IsDefined(typeof(AttributeType), (Int32)attributeType1) == false) throw new TurnMessageException(ErrorCode.UnknownAttribute); AttributeType attributeType = (AttributeType)attributeType1; if (rfc == TurnMessageRfc.Rfc3489) if (IsRfc3489(attributeType)) throw new TurnMessageException(ErrorCode.UnknownAttribute); if (attributeType == AttributeType.Fingerprint) { if (Fingerprint == null) { if (storedBytes == null) { storedBytes = new byte[length]; Array.Copy(bytes, startIndex, storedBytes, 0, length); } fingerprintStartOffset = currentIndex - startIndex; Fingerprint = new Fingerprint(); Fingerprint.Parse(bytes, ref currentIndex); } else { Attribute.Skip(bytes, ref currentIndex); } } else if (MessageIntegrity != null) { Attribute.Skip(bytes, ref currentIndex); } else { switch (attributeType) { case AttributeType.AlternateServer: AlternateServer = new AlternateServer(); AlternateServer.Parse(bytes, ref currentIndex); break; case AttributeType.Bandwidth: Bandwidth = new Bandwidth(); Bandwidth.Parse(bytes, ref currentIndex); break; case AttributeType.Data: Data = new Data(); Data.Parse(bytes, ref currentIndex); break; case AttributeType.DestinationAddress: DestinationAddress = new DestinationAddress(); DestinationAddress.Parse(bytes, ref currentIndex); break; case AttributeType.ErrorCode: ErrorCodeAttribute = new ErrorCodeAttribute(); ErrorCodeAttribute.Parse(bytes, ref currentIndex); break; case AttributeType.Fingerprint: break; case AttributeType.Lifetime: Lifetime = new Lifetime(); Lifetime.Parse(bytes, ref currentIndex); break; case AttributeType.MagicCookie: MagicCookie = new MagicCookie(); MagicCookie.Parse(bytes, ref currentIndex); break; case AttributeType.MappedAddress: MappedAddress = new MappedAddress(); MappedAddress.Parse(bytes, ref currentIndex); break; case AttributeType.MessageIntegrity: messageIntegrityStartOffset = currentIndex - startIndex; if (storedBytes == null) { if (rfc == TurnMessageRfc.MsTurn) { storedBytes = new byte[GetPadded64(messageIntegrityStartOffset)]; Array.Copy(bytes, startIndex, storedBytes, 0, messageIntegrityStartOffset); } else { storedBytes = new byte[length]; Array.Copy(bytes, startIndex, storedBytes, 0, length); } } MessageIntegrity = new MessageIntegrity(); MessageIntegrity.Parse(bytes, ref currentIndex); break; case AttributeType.MsVersion: MsVersion = new MsVersion(); MsVersion.Parse(bytes, ref currentIndex); break; case AttributeType.MsSequenceNumber: MsSequenceNumber = new MsSequenceNumber(); MsSequenceNumber.Parse(bytes, ref currentIndex); break; case AttributeType.RemoteAddress: RemoteAddress = new RemoteAddress(); RemoteAddress.Parse(bytes, ref currentIndex); break; case AttributeType.Software: Software = new Software(); Software.Parse(bytes, ref currentIndex); break; case AttributeType.UnknownAttributes: UnknownAttributes = new UnknownAttributes(); // Not Implemented UnknownAttributes.Parse(bytes, ref currentIndex); break; case AttributeType.Username: if (MsVersion != null) { MsUsername = new MsUsername(); MsUsername.Parse(bytes, ref currentIndex); } else { Username = new Username(); Username.Parse(bytes, ref currentIndex); } break; // ietf-mmusic-ice case AttributeType.Priority: case AttributeType.UseCandidate: case AttributeType.IceControlled: case AttributeType.IceControlling: Attribute.Skip(bytes, ref currentIndex); break; // rfc3489 case AttributeType.ChangedAddress: ChangedAddress = new ChangedAddress(); ChangedAddress.Parse(bytes, ref currentIndex); break; case AttributeType.ChangeRequest: ChangeRequest = new ChangeRequest(); ChangeRequest.Parse(bytes, ref currentIndex); break; case AttributeType.ResponseAddress: ResponseAddress = new ResponseAddress(); ResponseAddress.Parse(bytes, ref currentIndex); break; case AttributeType.SourceAddress: SourceAddress = new SourceAddress(); SourceAddress.Parse(bytes, ref currentIndex); break; case AttributeType.ReflectedFrom: ReflectedFrom = new ReflectedFrom(); ReflectedFrom.Parse(bytes, ref currentIndex); break; case AttributeType.Password: Password = new Password(); Password.Parse(bytes, ref currentIndex); break; default: if (rfc == TurnMessageRfc.MsTurn) { switch (attributeType) { case AttributeType.Nonce: Nonce = new Nonce(rfc); Nonce.Parse(bytes, ref currentIndex); break; case AttributeType.Realm: Realm = new Realm(rfc); Realm.Parse(bytes, ref currentIndex); break; case AttributeType.XorMappedAddress: XorMappedAddress = new XorMappedAddress(rfc); XorMappedAddress.Parse(bytes, ref currentIndex, TransactionId); break; default: throw new NotImplementedException(); } } else { switch (attributeType) { case AttributeType.NonceStun: Nonce = new Nonce(rfc); Nonce.Parse(bytes, ref currentIndex); break; case AttributeType.RealmStun: Realm = new Realm(rfc); Realm.Parse(bytes, ref currentIndex); break; case AttributeType.XorMappedAddressStun: XorMappedAddress = new XorMappedAddress(rfc); XorMappedAddress.Parse(bytes, ref currentIndex, TransactionId); break; default: throw new NotImplementedException(); } } break; } } if (rfc != TurnMessageRfc.MsTurn) { if (currentIndex % 4 > 0) currentIndex += 4 - currentIndex % 4; } } }