Beispiel #1
0
        public void TestBufferReuse()
        {
            var ringBuffer = new RingBuffer(12); // 16 cap
            var data       = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            ringBuffer.Write(data);
            ringBuffer.Read();
            ringBuffer.Write(data);
            var read = ringBuffer.Read();

            Assert.AreEqual(10, read.Length);
            Assert.AreEqual(1, read[0]);
            Assert.AreEqual(10, read[9]);
        }
 void ProcessTasks()
 {
     try
     {
         while (true)
         {
             if (tasks.Empty)
             {
                 ev.WaitOne();
                 continue;
             }
             try
             {
                 var fn = tasks.Read();
                 fn();
             }
             catch (IndexOutOfRangeException)
             {
                 continue;
             }
         }
     }
     catch (ThreadAbortException)
     {
     }
     catch (System.Exception ex)
     {
         Debug.LogWarning(ex);
     }
 }
Beispiel #3
0
        protected void ProcessRingBuffer(byte[] data)
        {
            try
            {
                if (_device == null)
                {
                    return;
                }
                bool   found = false;
                byte[] buff;
                bool   dataAdded;

Process:
                dataAdded = false;

                if (!_ringBuffer.IsFull)
                {
                    _ringBuffer.Write(data, 0, data.Length);
                    dataAdded = true;
                }

                if (DoParse != null)
                {
                    found = false;
                    buff  = DoParse(_device.GetType(), _ringBuffer);

                    while (buff != null)
                    {
                        found = true;
                        _device.UpdateData(buff);

                        buff = DoParse(_device.GetType(), _ringBuffer);
                    }
                }

                // incase no data package found
                // Remove unidentified bytes from buffer to release spaces
                if (!found && _ringBuffer.IsFull)
                {
                    var byteToRelease = _ringBuffer.Capacity - 200;
                    if (byteToRelease < 0)
                    {
                        byteToRelease = _ringBuffer.Capacity - 100;
                    }

                    var unusedBytes = new byte[byteToRelease];

                    _ringBuffer.Read(unusedBytes, 0, byteToRelease);
                }

                if (!dataAdded)
                {
                    goto Process;
                }
            }
            catch (Exception ex)
            {
                LogService.Logger.Error("ProcessRingBuffer", ex);
            }
        }
Beispiel #4
0
        public void TestReadEmptyBuffer()
        {
            var ringBuffer = new RingBuffer(4); // 4 cap
            var read       = ringBuffer.Read();

            Assert.AreEqual(0, read.Length);

            var peek = ringBuffer.Peek();

            Assert.AreEqual(0, peek.Length);

            var buffer = new byte[5];
            var r      = ringBuffer.Read(buffer, 2);

            Assert.AreEqual(0, r);
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            int iValue = rfBuffer.Read(buffer, offset, count);

            lock (oPushSync)
            {
                bIsPush = false;

                while (iNextPush != -1 && IsPushInRange(iReadCount, (iReadCount + count) % rfBuffer.Length, iNextPush))
                {
                    bIsPush = true;
                    qPushIndex.Dequeue();
                    if (qPushIndex.Count > 0)
                    {
                        iNextPush = qPushIndex.Peek();
                    }
                    else
                    {
                        iNextPush = -1;
                    }
                }

                iReadCount += count;
                iReadCount %= rfBuffer.Length;
            }
            return(iValue);
        }
Beispiel #6
0
        public int sceMpegAvcDecode(int mpeg, int au, int framewidth, int buffer, int num)
        {
            Debug.Assert(num != 0);

            byte *   pmpeg   = _memorySystem.Translate(( uint )mpeg);
            SceMpeg *sceMpeg = ( SceMpeg * )pmpeg;
            byte *   ptr     = RingBuffer.Read(
                _memorySystem.Translate(( uint )sceMpeg->Ringbuffer->pData),
                sceMpeg->Ringbuffer->iPackets, sceMpeg->Ringbuffer->iPacketSize,
                ref sceMpeg->Ringbuffer->iReadPackets);

            uint  pbuffer  = *(( uint * )_memorySystem.Translate(( uint )buffer));
            uint *ppbuffer = ( uint * )_memorySystem.Translate(pbuffer);

            for (int n = 0; n < framewidth; n++)
            {
                *(ppbuffer++) = ( uint )(0xCCDDEEFF + n);
            }

            // 1 = decoded something, else 0
            if (num != 0)
            {
                uint *pnum = ( uint * )_memorySystem.Translate(( uint )num);
                *     pnum = 1;
            }

            return(0);
        }
        void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            WebClient wc = new WebClient();

            while (_go)
            {
                if (e.Cancel)
                {
                    break;
                }


                while (!_untrackedqueue.isEmpty && TrackEnabled && hastrackurl)
                {
                    if (e.Cancel)
                    {
                        break;
                    }
                    // get item
                    Track t = _untrackedqueue.Read();
                    try
                    {
                        // dimon: this is where actual upload of all tracked detail is happaning (wc stands for webClient).
                        // Just comment next line to disable tracking:
                        //wc.UploadValues(TrackUrl, "POST", t.ToQuery());   // <-- this is where actuall tracking (upload) use to happen
                    }
                    catch (Exception ex)
                    {
                        debug("error uploading: " + t.ToQuery() + " " + ex.Message + ex.StackTrace);
                    }
                    System.Threading.Thread.Sleep((int)((double)_SLEEP / 10));
                }
                System.Threading.Thread.Sleep(_SLEEP);
            }
        }
Beispiel #8
0
        void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            WebClient wc = new WebClient();

            while (_go)
            {
                if (e.Cancel)
                {
                    break;
                }


                while (!_untrackedqueue.isEmpty && TrackEnabled && hastrackurl)
                {
                    if (e.Cancel)
                    {
                        break;
                    }
                    // get item
                    Track t = _untrackedqueue.Read();
                    try
                    {
                        wc.UploadValues(TrackUrl, "POST", t.ToQuery());
                    }
                    catch (Exception ex)
                    {
                        debug("error uploading: " + t.ToQuery() + " " + ex.Message + ex.StackTrace);
                    }
                    System.Threading.Thread.Sleep((int)((double)_SLEEP / 10));
                }
                System.Threading.Thread.Sleep(_SLEEP);
            }
        }
Beispiel #9
0
    public void LoadAll()
    {
        if (!File.Exists(SaveFile))
        {
            return;
        }

        using (var r = new BinaryReader(new FileStream(SaveFile, FileMode.Open)))
        {
            try
            {
                var count = r.ReadInt32();
                var data  = r.ReadBytes((int)r.BaseStream.Length);
                var buff  = new RingBuffer();
                buff.Write(data);

                FC.For(count, (i) =>
                {
                    var replay = buff.Read <BattleReplay>();
                    replays.Add(replay);
                });
            }
            catch (Exception)
            {
                replays.Clear();
            }
            finally
            {
                r.Close();
            }
        }
    }
Beispiel #10
0
        public void TestReadWrite()
        {
            var ringBuffer = new RingBuffer();
            var buffer     = new byte[] { 1, 2, 4, 5 };

            ringBuffer.Write(buffer, 1, 2);
            var read = ringBuffer.Read();

            Assert.AreEqual(2, read.Length);
            Assert.AreEqual(2, read[0]);
            Assert.AreEqual(4, read[1]);

            ringBuffer = new RingBuffer();
            buffer     = new byte[] { 1, 2, 3, 4, 5 };
            ringBuffer.Write(buffer, 2);
            buffer = new byte[5];
            var readCount = ringBuffer.Read(buffer, 2);

            Assert.AreEqual(3, readCount);
            Assert.AreEqual(0, buffer[0]);
            Assert.AreEqual(0, buffer[1]);
            Assert.AreEqual(3, buffer[2]);
            Assert.AreEqual(4, buffer[3]);
            Assert.AreEqual(5, buffer[4]);
        }
Beispiel #11
0
        public int Read(TimeLocatedBuffer1D <T> target, int elements)
        {
            var timeBegin = TimeAtReadPosition;
            var read      = _buffer.Read(target.Data, 0, elements);

            target.SetWritten(read, timeBegin.Increment(read, Samplerate));
            return(read);
        }
Beispiel #12
0
 public virtual byte ReadByte()
 {
     if (terminalBuffer.Count > 0)
     {
         return(terminalBuffer.Read());
     }
     return(0);
 }
Beispiel #13
0
 private void downloaddata()
 {
     while (newchartsyms.hasItems)
     {
         string sym   = newchartsyms.Read();
         var    chart = BarListImpl.GetChart(sym, usecachenow, 200, debug);
         newChart(chart);
     }
 }
Beispiel #14
0
    void OnAudioFilterRead(float[] data, int channels)
    {
        const float AMPLIFIER = 4;

        ringBuffer.Read(data);
        for (int i = 0; i < data.Length; ++i)
        {
            data[i] = data[i] * AMPLIFIER;
        }
    }
Beispiel #15
0
        private void Client_BinaryInput(byte[] data)
        {
            RingBuffer.Write(data);

            byte[] pdata;

            while (RingBuffer.Read(out pdata))
            {
                DataOn(pdata);
            }
        }
Beispiel #16
0
        public int Read(TimeLocatedBufferFFT target, int frames)
        {
            var timeBegin = TimeAtReadPosition;
            var read      = _buffer.Read(target.Data, 0, frames * FrameSize);

            if (read % FrameSize != 0)
            {
                throw new InvalidOperationException("shouldn't dequeue amount which is not a multiple of the frame size");
            }
            target.SetWritten(read / FrameSize, timeBegin.Increment(read * FrameSize, Samplerate));
            return(read / FrameSize);
        }
Beispiel #17
0
        public void RingBufferReadTest()
        {
            RingBuffer <string> ring = new RingBuffer <string>(3);

            ring.Write("q");
            Assert.IsTrue(ring.Count == 1);
            string s = ring.Read();

            Assert.AreEqual(s, "q");
            Assert.IsTrue(ring.IsEmpty);

            ring.Write("aaa");
            ring.Write("bbb");
            ring.Write("ccc");
            ring.Write("ddd");
            string s2 = ring.Read();

            Assert.AreEqual(s2, "bbb");
            string s3 = ring.Read();

            Assert.AreEqual(s3, "ccc");
            Assert.IsTrue(ring.Count == 1);
        }
Beispiel #18
0
        public void ConcurrentReadWrite()
        {
            //Arrange
            const int capacity = 128;
            RingBuffer<object> ringBuffer = new RingBuffer<object>(capacity, i => new RingBufferItem<object>(i));

            AutoResetEvent resetEvent = new AutoResetEvent(false);
            Action writerAction = () =>
            {
                for (int i = 0; i < capacity; i++)
                {
                    int writeIndex = ringBuffer.Write(new object());
                    Assert.AreEqual(i, writeIndex);
                    resetEvent.Set();
                }

            };

            Action readerAction = () =>
                {

                    for (int i = 0; i < capacity; i++)
                    {
                        int readIndex;
                        object read = ringBuffer.Read(out readIndex);
                        if (readIndex < 0)
                        {
                            resetEvent.WaitOne(100);
                            read = ringBuffer.Read(out readIndex);
                        }
                        Assert.AreEqual(i, readIndex, "readIndex does not equal loop index.");
                        Assert.IsNotNull(read, "read object in null");
                    }
                };

            Parallel.Invoke(writerAction, readerAction);
        }
Beispiel #19
0
        public void TestOutOffset()
        {
            var ringBuffer = new RingBuffer(4); // 4 cap
            var buffer     = new byte[5];

            ExceptionAssert.Throws <ArgumentOutOfRangeException>(() =>
            {
                ringBuffer.Read(buffer, 2, 10);
            });

            ExceptionAssert.Throws <ArgumentOutOfRangeException>(() =>
            {
                ringBuffer.Write(buffer, 2, 10);
            });
        }
Beispiel #20
0
        public void TestPeek()
        {
            var ringBuffer = new RingBuffer(12); // 16 cap
            var buffer     = new byte[] { 1, 2, 3, 4, 5 };

            ringBuffer.Write(buffer);

            Assert.AreEqual(11, ringBuffer.WriteableCapacity);
            Assert.AreEqual(5, ringBuffer.ReadableCapacity);

            var data = ringBuffer.Peek();

            Assert.AreEqual(5, data.Length);
            Assert.AreEqual(1, data[0]);
            Assert.AreEqual(2, data[1]);
            Assert.AreEqual(3, data[2]);
            Assert.AreEqual(4, data[3]);
            Assert.AreEqual(5, data[4]);

            var data2 = new byte[5];
            var read  = ringBuffer.Peek(data2, 3);

            Assert.AreEqual(2, read);
            Assert.AreEqual(5, data2.Length);
            Assert.AreEqual(0, data2[0]);
            Assert.AreEqual(0, data2[1]);
            Assert.AreEqual(0, data2[2]);
            Assert.AreEqual(1, data2[3]);
            Assert.AreEqual(2, data2[4]);

            // double peek test
            data2 = new byte[5];
            read  = ringBuffer.Peek(data2);
            Assert.AreEqual(5, read);
            Assert.AreEqual(5, data2.Length);
            Assert.AreEqual(1, data2[0]);
            Assert.AreEqual(2, data2[1]);
            Assert.AreEqual(3, data2[2]);
            Assert.AreEqual(4, data2[3]);
            Assert.AreEqual(5, data2[4]);

            Assert.AreEqual(11, ringBuffer.WriteableCapacity);
            Assert.AreEqual(5, ringBuffer.ReadableCapacity);
            ringBuffer.Read();
            Assert.AreEqual(16, ringBuffer.WriteableCapacity);
            Assert.AreEqual(0, ringBuffer.ReadableCapacity);
        }
Beispiel #21
0
        void saveraw_DoWork(object sender, DoWorkEventArgs e)
        {
            string rawfn  = Util.ProgramData(IQFeedFrm.PROGRAM) + "\\Iqfeedraw." + Util.ToTLDate() + ".txt";
            bool   fileok = false;

            try
            {
                rawfile           = new System.IO.StreamWriter(rawfn, true);
                rawfile.AutoFlush = true;
                debug("started rawfeed archive at: " + rawfn);
                fileok = true;
            }
            catch (Exception ex)
            {
                debug("Raw saving failed from error writing to raw file: " + rawfn + " err: " + ex.Message + ex.StackTrace);
            }
            if (fileok)
            {
                while (_go)
                {
                    while (rawdatabuf.hasItems)
                    {
                        if (e.Cancel || !_go)
                        {
                            break;
                        }
                        string data = rawdatabuf.Read();
                        if (data != string.Empty)
                        {
                            rawfile.Write(data);
                        }
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            debug("Ended raw file write: " + rawfn);
            try
            {
                if (rawfile != null)
                {
                    rawfile.Close();
                }
            }
            catch { }
        }
Beispiel #22
0
        protected virtual void AppendData()
        {
            Display.Print(spinner[spinnerIndex]);
            spinnerIndex = (spinnerIndex + 1) % spinner.Length;
            Display.MoveLeft();

            byte b = dataBuffer.Peek();

            if (dataBuffer.Count >= BLOCK_LENGTH)
            {
                // SOH begins an XMODEM block
                // read until we get a valid SOH and then
                // enter the block.
                if (b == SOH)
                {
                    Stage = TransferStages.Data;
                    ProcessBuffer();
                }
                else
                {
                    dataBuffer.Read();
                }
            }
            if (b == ETX) // cancel
            {
                dataBuffer.Read();
                Display.PrintSeparater();
                Display.PrintAtStart("Canceled by remote host.");
                Cancel();
            }
            else if (b == EOT)
            {
                dataBuffer.Read();
                SendACK();
                CompleteReceive();
            }
        }
Beispiel #23
0
        private void SegmentAndSend()
        {
            lock (oTCBLock)
            {
                if (tcpState != TCPSocketState.Established)
                {
                    bFlushWhenEstablished = true;
                    return;
                }

                byte[] bSegment = new byte[Math.Min(rbSendBuffer.Count, (tcb.SND_UNA + tcb.SND_WND - tcb.SND_NXT))];
                rbSendBuffer.Read(bSegment, 0, bSegment.Length);

                for (int iC1 = 0; iC1 < bSegment.Length; iC1 += MaximumSegmentSize)
                {
                    byte[] bSegmentedSegment = new byte[Math.Min(bSegment.Length - iC1, MaximumSegmentSize)];

                    for (int iC2 = 0; iC2 < bSegmentedSegment.Length; iC2++)
                    {
                        bSegmentedSegment[iC2] = bSegment[iC2 + (iC1)];
                    }

                    TCPFrame tcpFrame = new TCPFrame();

                    tcpFrame.SequenceNumber        = tcb.SND_NXT;
                    tcpFrame.AcknowledgementNumber = tcb.RCV_NXT;
                    tcpFrame.Window = tcb.RCV_WND;
                    tcpFrame.AcknowledgementFlagSet = true;
                    tcpFrame.SourcePort             = this.LocalBinding;
                    tcpFrame.DestinationPort        = this.RemoteBinding;
                    tcpFrame.EncapsulatedFrame      = new RawDataFrame(bSegmentedSegment);
                    tcpFrame.PushFlagSet            = true;
                    tcb.SND_NXT      += (uint)bSegmentedSegment.Length;
                    tcpFrame.Checksum = tcpFrame.CalculateChecksum(pseudoHeaderSource.GetPseudoHeader(tcpFrame));

                    TransmitAssured(tcpFrame);
                }
            }
        }
Beispiel #24
0
 void _bw_DoWork(object sender, DoWorkEventArgs e)
 {
     while (_go)
     {
         if (e.Cancel)
         {
             break;
         }
         System.Threading.Thread.Sleep(_SLEEP);
         while (!_untrackedqueue.isEmpty && TrackEnabled)
         {
             if (e.Cancel)
             {
                 break;
             }
             // get item
             AssemblaTicket t     = _untrackedqueue.Read();
             string         space = t.Space == string.Empty ? Space : t.Space;
             string         un    = t.Username == string.Empty ? _un : t.Username;
             string         pw    = t._pw == string.Empty ? _pw : t._pw;
             if ((space == string.Empty) || (un == string.Empty))
             {
                 debug(t.ToString() + " space or login information not provided, ignoring ticket.");
                 continue;
             }
             try
             {
                 int tid = AssemblaTicket.Create(space, un, pw, t.Summary, t.Description, t.Status, t.Priority);
                 debug("created ticket: " + tid);
             }
             catch (Exception ex)
             {
                 debug("error uploading: " + t.ToString() + " " + ex.Message + ex.StackTrace);
             }
             System.Threading.Thread.Sleep((int)((double)_SLEEP / 10));
         }
     }
 }
Beispiel #25
0
        void doqueues(object obj)
        {
            while (_bwgo)
            {
                bool newsym = false;
                while (!_newsyms.isEmpty)
                {
                    _newsyms.Read();
                    newsym = true;
                }
                if (newsym)
                {
                    // get symbols
                    Basket b   = BasketImpl.FromString(_newsymlist);
                    object err = null;
                    foreach (Security s in b)
                    {
                        try
                        {
                            string se = string.Empty;
                            if (vret == null)
                            {
                                vret = _cc.VBRediCache.Submit("L1", "true", ref err);
                                checkerror(ref err, "submit");
                            }
                            _cc.VBRediCache.AddWatch(0, s.Symbol, string.Empty, ref err);
                            checkerror(ref err, "watch");
                        }
                        catch (Exception ex)
                        {
                            debug(s.Symbol + " error subscribing: " + ex.Message + ex.StackTrace);
                        }
                    }
                    debug("registered: " + _newsymlist);
                }
                while (!_neworders.isEmpty)
                {
                    Order o = _neworders.Read();
                    v("received order: " + o.ToString());
                    if (o.Account == string.Empty)
                    {
                        o.Account = Account;
                    }

                    if (isPaperTradeEnabled)
                    {
                        ptt.sendorder(o);
                    }
                    else
                    {
                        RediLib.ORDER rediOrder = new RediLib.ORDERClass();


                        // get any current position in symbol
                        Position p = pt[o.symbol];
                        // determine if a sell order should be a long exit or a short entry
                        string side = !o.side && !p.isLong ? "Sell Short" : (o.side ? "Buy" : "Sell");

                        rediOrder.Account  = o.Account;
                        rediOrder.UserID   = _userid;
                        rediOrder.Password = _pwd;

                        rediOrder.TIF    = gettiftype(o);
                        rediOrder.Side   = side;
                        rediOrder.Symbol = o.symbol;
                        if (o.ex == string.Empty)
                        {
                            o.ex = o.symbol.Length > 3 ? "ARCA" : "NYSE";
                        }
                        rediOrder.Exchange  = o.ex;
                        rediOrder.Quantity  = o.UnsignedSize;
                        rediOrder.Price     = o.price.ToString();
                        rediOrder.PriceType = getpricetype(o);

                        rediOrder.StopPrice = o.stopp;
                        rediOrder.Memo      = o.comment;
                        rediOrder.Warning   = false;
                        object err          = null;
                        object transId      = null;
                        bool   IsSuccessful = rediOrder.Submit2(ref transId, ref err);
                        if (IsSuccessful)
                        {
                            v("successfully sent order: " + o.ToString());
                            object err1 = null;
                            _messageCache.VBRediCache.AddWatch(1, o.symbol, "", ref err1);

                            if (!(err1 == null))
                            {
                                debug("FAILED open of Table! Table : Message  Error:" + err1.ToString());
                            }
                            else
                            {
                                v("successfully watching symbol: " + o.symbol);
                            }
                        }
                        else
                        {
                            v("error sending order: " + o.ToString());
                            if (!(err == null))
                            {
                                debug("order submission was not successful: " + err.ToString());
                            }
                        }
                    }
                }
                while (!_newcancel.isEmpty)
                {
                    long id = _newcancel.Read();
                    v("received cancel request: " + id);
                    if (isPaperTradeEnabled)
                    {
                        ptt.sendcancel(id);
                    }
                    else
                    {
                        object err = null;
                        _messageCache.VBRediCache.Cancel(id, ref err);
                        if (err != null)
                        {
                            v("error canceling id: " + id);
                        }
                        else
                        {
                            v("cancel request sent for: " + id);
                        }
                    }
                }
                if (_newcancel.isEmpty && _neworders.isEmpty && _newsyms.isEmpty)
                {
                    Thread.Sleep(_SLEEP);
                }
            }
        }
 public void ReadEmpty()
 {
     RingBuffer.Read();
 }
Beispiel #27
0
        void background(object param)
        {
            while (_runbg)
            {
                try
                {
                    // orders
                    while (!_orderq.isEmpty)
                    {
                        //STIOrder order = new STIOrder();
                        Order o = _orderq.Read();
                        if (VerboseDebugging)
                        {
                            debug("client order received: " + o.ToString());
                        }
                        if (o.id == 0)
                        {
                            o.id = _idt.AssignId;
                        }

                        o.price = Math.Round(o.price, FixOrderDecimalPlace);
                        o.stopp = Math.Round(o.stopp, FixOrderDecimalPlace);


                        //order.LmtPrice = (double)o.price;
                        //order.StpPrice = (double)o.stopp;
                        if (o.ex == string.Empty)
                        {
                            o.ex = o.symbol.Length > 3 ? "NSDQ" : "NYSE";
                        }

                        int err = (int)SendOrder(o);


                        if (VerboseDebugging)
                        {
                            debug("client order sent: ");
                        }
                        string tmp = "";
                        if ((err == 0))
                        {
                            // save account/id relationship for canceling
                            //idacct.Add(o.id, order.Account);
                            // wait briefly between orders
                            Thread.Sleep(_ORDERSLEEP);
                        }
                        if (err < 0)
                        {
                            debug("Error sending order: " + Util.PrettyError(tl.newProviderName, err) + o.ToString());
                        }
                        if (err == -1)
                        {
                            debug("Make sure you have set the account in sending program.");
                        }
                    }

                    // new quotes
                    if (!_symsq.isEmpty)
                    {
                        _symsq.Read();
                        foreach (string sym in symquotes.Split(','))
                        {
                            //stiQuote.RegisterQuote(sym, "*");
                            GetQuote(sym);
                        }
                    }
                    // old quotes
                    while (removesym.hasItems)
                    {
                        string rem = removesym.Read();
                        // stiQuote.DeRegisterQuote(rem, "*");
                    }

                    // cancels
                    if (!_cancelq.isEmpty)
                    {
                        long orderid = _cancelq.Read();
                        int  BBoxId  = -1;
                        dictOrderIdBBoxId.TryGetValue(orderid, out BBoxId);
                        if (BBoxId != -1)
                        {
                            CancelOrder(BBoxId);
                        }
                        //string acct = "";
                        //if (idacct.TryGetValue(number, out acct))
                        //{
                        //    // get unique cancel id
                        //    long cancelid = _canceltracker.AssignId;
                        //    // save cancel to order id relationship
                        //    _cancel2order.Add(cancelid, number);
                        //    // send cancel
                        //    stiOrder.CancelOrder(acct, 0, number.ToString(), cancelid.ToString());
                        //    if (VerboseDebugging)
                        //        debug("client cancel requested: " + number.ToString() + " " + cancelid.ToString());
                        //}
                        //else
                        //    debug("No record of id: " + number.ToString());
                        // see if empty yet
                        if (_cancelq.hasItems)
                        {
                            Thread.Sleep(_CANCELWAIT);
                        }
                    }

                    //// messages
                    //if (_msgq.hasItems)
                    //{
                    //    GenericMessage gm = _msgq.Read();
                    //    switch (gm.Type)
                    //    {
                    //        case MessageTypes.SENDORDERPEGMIDPOINT:
                    //            {
                    //                // create order
                    //                STIOrder order = new STIOrder();
                    //                // pegged 2 midmarket
                    //                order.ExecInst = "M";
                    //                // get order
                    //                Peg2Midpoint o = Peg2Midpoint.Deserialize(gm.Request);
                    //                if (!o.isValid) break;
                    //                if (VerboseDebugging)
                    //                    debug("client P2M order: " + o.ToString());
                    //                order.Symbol = o.symbol;
                    //                order.PegDiff = (double)o.pegdiff;
                    //                order.PriceType = STIPriceTypes.ptSTIPegged;
                    //                bool side = o.size > 0;
                    //                order.Side = getside(o.symbol, side);
                    //                order.Quantity = Math.Abs(o.size);
                    //                order.Destination = o.ex;
                    //                order.ClOrderID = o.id.ToString();
                    //                order.Tif = "D";
                    //                string acct = Account != string.Empty ? Account : string.Empty;
                    //                order.Account = o.Account != string.Empty ? o.Account : acct;
                    //                int err = order.SubmitOrder();
                    //                string tmp = "";
                    //                if ((err == 0) && (!idacct.TryGetValue(o.id, out tmp)))
                    //                    idacct.Add(o.id, order.Account);
                    //                if (err < 0)
                    //                    debug("Error sending order: " + Util.PrettyError(tl.newProviderName, err) + o.ToString());
                    //                if (err == -1)
                    //                    debug("Make sure you have set the account in sending program.");

                    //            }
                    //            break;
                    //    }
                    //}

                    //if (_lastimbalance != _imbalance)
                    //{
                    //    _lastimbalance = _imbalance;
                    //    // register for imbalance data
                    //    stiQuote.RegisterForAllMdx(true);
                    //}
                }
                catch (Exception ex)
                {
                    debug(ex.Message + ex.StackTrace);
                }
                if (_symsq.isEmpty && _orderq.isEmpty && _cancelq.isEmpty)
                {
                    Thread.Sleep(_SLEEP);
                }
            }
        }
Beispiel #28
0
        void _bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            while (_bwgo)
            {
                bool newsym = false;
                while (!_newsyms.isEmpty)
                {
                    _newsyms.Read();
                    newsym = true;
                }
                if (newsym)
                {
                    // get symbols
                    _numDisplayed = 0;
                    _numIgnored   = 0;
                    debug("Subscribe request: " + _newsymlist);
                    if (!isConnected)
                    {
                        debug("not connected.");
                        return;
                    }

                    Basket b = BasketImpl.FromString(_newsymlist);
                    foreach (Security s in b)
                    {
                        try
                        {
                            TBL.WantData(TBL.TqlForBidAskTrade(s.Symbol, null), true, true);
                            TBL.Start();
                            //TT.WantData(TBL.TqlForBidAskTrade(s.Symbol, null), true, true);
                            //TT.Start();
                            _done.WaitOne(30000);
                        }
                        catch (Exception ex)
                        {
                            debug(s.Symbol + " error subscribing: " + ex.Message + ex.StackTrace);
                        }
                    }
                    debug(string.Format("DISPLAYED {0} TRADES AND IGNORED {1} QUOTES", _numDisplayed, _numIgnored));
                    debug("DONE.");
                    debug("registered: " + _newsymlist);
                }
                while (!_neworders.isEmpty)
                {
                    Order o  = _neworders.Read();
                    var   ob = new OrderBuilder(_oc);
                    ob.SetAccount(null, o.Account, null, null);
                    ob.SetBuySell(o.side ? OrderBuilder.BuySell.BUY : OrderBuilder.BuySell.SELL);
                    ob.SetExpiration(OrderBuilder.Expiration.DAY);
                    ob.SetRoute("NYS");
                    ob.SetSymbol(o.symbol, o.Exchange, OrderBuilder.SecurityType.STOCK);
                    if (o.size != 0)
                    {
                        ob.SetVolume(Math.Abs(o.size));
                    }
                    if (o.isMarket)
                    {
                        ob.SetPriceMarket();
                    }
                    if (o.isLimit)
                    {
                        ob.SetPriceLimit(new Price(o.price.ToString()));
                    }
                    if (o.isStop)
                    {
                        ob.SetPriceLimit(new Price(o.price.ToString()));
                    }
                    // ob.SetGoodFrom(DateTime.Now.AddMinutes(60));
                    currentOrderId = o.id;
                    state          = OrderState.OrderPending;
                    _oc.SubmitOrder(ob);
                }
                while (!_newcancel.isEmpty)
                {
                    long id = _newcancel.Read();
                    if (_orSet.ContainsKey(id))
                    {
                        var cxl = new CancelBuilder(_orSet[id]);
                        try
                        {
                            _oc.SubmitCancel(cxl);
                        }
                        catch (Exception ee)
                        {
                            debug("ORDER CANCEL FAILED:" + ee.Message);
                        }

                        state = OrderState.CancelPending;
                        debug("ORDER CANCEL FINISHED");
                    }
                    else
                    {
                        debug("ORDER CANCEL FAILED, NOT EXIST THE Order.Id:" + id);
                    }
                }
                if (_newcancel.isEmpty && _neworders.isEmpty && _newsyms.isEmpty)
                {
                    Thread.Sleep(_SLEEP);
                }
            }
        }
Beispiel #29
0
        public void FillBufferThenReadHalfThenWriteHalf()
        {
            //Arrange
            const int capacity = 256;
            RingBuffer<object> ringBuffer = new RingBuffer<object>(capacity, i => new RingBufferItem<object>(i));
            Assert.AreEqual(256, ringBuffer.Capacity);

            //act
            for (int i = 0; i < capacity; i++)
            {
                var indexUsed = ringBuffer.Write(new object());
                Assert.AreEqual(i, indexUsed, "The write index should match the loop index");
            }

            //The buffer should be full, so no more writes are allowed
            var index = ringBuffer.Write(new object());
            Assert.AreEqual(-1, index);

            for (int i = 0; i < capacity / 2; i++)
            {
                int readIndex;
                var item = ringBuffer.Read(out readIndex);
                Assert.IsNotNull(item, "Item should not be null");
                Assert.AreEqual(i, readIndex, "The Read index should be same as the loop index");
            }

            //Write again from the beginning
            for (int i = 0; i < capacity / 2; i++)
            {
                var indexUsed = ringBuffer.Write(new object());
                Assert.AreEqual(i, indexUsed, "The write index should match the loop index");
            }

            //Assert
            index = ringBuffer.Write(new object());
            Assert.AreEqual(-1, index);
        }
Beispiel #30
0
        public void ReadEmptyBuffer()
        {
            //Arrange
            const int capacity = 64;
            RingBuffer<object> ringBuffer = new RingBuffer<object>(capacity, i => new RingBufferItem<object>(i));
            Assert.AreEqual(64, ringBuffer.Capacity);

            //Act
            int readIndex;
            object read = ringBuffer.Read(out readIndex);

            //Assert
            Assert.IsNull(read, "The read object should be null");
            Assert.AreEqual(-1, readIndex, "readIndex should not be positive");
        }
Beispiel #31
0
        public void FillHalfTheBufferThenReadAll()
        {
            //Arrange
            const int capacity = 256;
            RingBuffer<object> ringBuffer = new RingBuffer<object>(capacity, index => new RingBufferItem<object>(index));
            Assert.AreEqual(256, ringBuffer.Capacity);

            //act
            for (int j = 0; j < capacity / 2; j++)
            {
                var indexUsed = ringBuffer.Write(new object());
                Assert.AreEqual(j, indexUsed, "The write index should match the loop index");
            }

            int i;
            int readIndex = 0;
            for (i = 0; i < capacity; i++)
            {
                var item = ringBuffer.Read(out readIndex);
                if (readIndex == -1)
                    break;
                Assert.IsNotNull(item);
                Assert.AreEqual(i, readIndex, "The Read index should be same as the loop index");
            }

            //Assert
            Assert.AreEqual(-1, readIndex);
            Assert.AreEqual(capacity / 2, i);
        }
Beispiel #32
0
        public int Read(byte[] buffer, int offset, int count)
        {
            //Fill ring buffer when needed
            streamBPCM.DecodingVolume = vol;

            while (rb.Count < buffer.Length || rb.Count == 0)
            {
                object tmp = streamBPCM.GetFrame();
                if (tmp.Equals(false))
                {
                    break;
                }
                if (streamBPCM.EOF)
                {
                    break;
                }
                Frame frame = (Frame)tmp;
                tmp      = null;
                tsOffset = 0;
                if (!Equals(frame.Data, null))
                {
                    rb.Write(frame.Data);
                }
                else
                {
                    byte[] silence = new byte[frame.SampleCount * frame.Channels * 2];
                    for (int i = 0; i < silence.Length; i++)
                    {
                        silence[i] = 0;
                    }

                    //Set volume info to silence
                    frame.VolumeInfo         = new ADPCM4BIT.VolumeInfo();
                    frame.VolumeInfo.dbPeakL = double.NegativeInfinity;
                    frame.VolumeInfo.dbPeakR = double.NegativeInfinity;
                    frame.VolumeInfo.dbAvgL  = double.NegativeInfinity;
                    frame.VolumeInfo.dbAvgR  = double.NegativeInfinity;

                    rb.Write(silence);
                }
                currentFrame = frame;
            }

            if (rb.Count != 0)
            {
                int newLen = buffer.Length;
                if (newLen > rb.Count)
                {
                    newLen = rb.Count;
                }
                rb.Read(newLen).CopyTo(buffer, 0);
                ADPCM4BIT.VolumeInfo vi = currentFrame.VolumeInfo;
                int cf = currentFrame.FrameNumber;
                if (cf < 0)
                {
                    cf = 0;
                }
                if (cf >= streamBPCM.Analysis.FrameSet.Count)
                {
                    cf = streamBPCM.Analysis.FrameSet.Count - 1;
                }
                currentFrame            = streamBPCM.Analysis.FrameSet[cf];
                currentFrame.TimeStamp += tsOffset;
                tsOffset += (buffer.Length / (double)(currentFrame.Channels * 2 * currentFrame.SamplingRate));
                currentFrame.VolumeInfo = vi;
                readDone?.Invoke(currentFrame);

                return(newLen);
            }
            else
            {
                return(0);
            }
        }
Beispiel #33
0
        // Read line from UART Fifo
        private String _uartReadLine(int Timeout)
        {
            // This whole function may be executed only one at a time
            lock (_bufferedlinedata)
            {
                bool   CR = false;
                char   r;
                String s = _bufferedlinedata;

                // Make timeout datetime object
                DateTime timeoutAt = DateTime.Now.AddMilliseconds(Timeout);

                // Keep working until we
                while ((DateTime.Now < timeoutAt) | (Timeout == -1))
                {
                    Thread.Sleep(1);

                    // Lock input FIFO
                    lock (_inputFIFO)
                    {
                        // If empty wait
                        if (_inputFIFO.isEmpty())
                        {
                            continue;
                        }

                        // Read Char from fifo
                        r = (char)_inputFIFO.Read();
                    }

                    // Add character to string
                    s += r;

                    // After recieving more then two chars check for <cr><lf>
                    // This prevents the first <cr><lf> to trigger end of line
                    if (s.Length > 2)
                    {
                        // Check for <cr>
                        if (r == '\r')
                        {
                            CR = true;
                        }

                        // Check for <lf>
                        if (r == '\n')
                        {
                            // Check if we have already recieved a <cr>
                            if (CR)
                            {
                                // Check for last line enter
                                if (s == "\r\n\r\n")
                                {
                                    s = "\r\n";
                                    continue;
                                }

                                // Valid line end
                                _bufferedlinedata = "";
                                return(s);
                            }
                            else
                            {
                                // False <cr> recieved
                                CR = false;
                            }
                        }

                        // We seem to have recieved an SEND_SMS_MESSAGE response
                        if (s == "\r\n>")
                        {
                            return(s);
                        }
                    }
                }

                // Invalid line, buffer data
                _bufferedlinedata = (s != "\r\n") ? s : "";
                return("");
            }
        }
Beispiel #34
0
 public virtual byte ReadByte()
 {
     return(SendBuffer.Read());
 }