Ejemplo n.º 1
0
 public int SignalStream(string aStreamName, Stream aStream) {
     var payload = new TByteBuffer();
     if (!IsPublished && connection.AutoPublish)
         Publish();
     if (IsPublished) {
         // ekStreamHeader, includes stream name, no stream data
         var streamNameUtf8 = Encoding.UTF8.GetBytes(aStreamName);
         var streamID = connection.getConnectionHashCode(streamNameUtf8);
         payload.Prepare(ID);
         payload.Prepare((Int32) 0); // tick
         payload.Prepare((Int32) TEventKind.ekStreamHeader); // event kind
         payload.Prepare(streamID);
         payload.Prepare(aStreamName);
         payload.PrepareApply();
         payload.QWrite(ID);
         payload.QWrite((Int32) 0); // tick
         var eventKindIndex = payload.WriteCursor;
         payload.QWrite((Int32) TEventKind.ekStreamHeader); // event kind
         payload.QWrite(streamID);
         var bodyIndex = payload.WriteCursor;
         payload.QWrite(aStreamName);
         var res = connection.WriteCommand(TConnectionPlatform.TCommands.icEvent, payload.Buffer);
         if (res > 0) {
             // ekStreamBody, only buffer size chunks of data
             // prepare Payload to same value but aStreamName stripped
             // fixup event kind
             payload.WriteStart(eventKindIndex);
             payload.QWrite((Int32) TEventKind.ekStreamBody);
             payload.WriteStart(bodyIndex);
             // prepare room for body data
             payload.PrepareStart();
             payload.PrepareSize(TConnection.MaxStreamBodyBuffer);
             payload.PrepareApply();
             // write pointer in ByteBuffer is still at beginning of stream read buffer!
             // but buffer is already created on correct length
             Int32 readSize;
             do {
                 readSize = ReadBytesFromStream(payload, aStream);
                 //ReadSize = aStream.Read(Payload.Buffer, BodyIndex, Connection.MaxStreamBodyBuffer);
                 if (readSize == TConnection.MaxStreamBodyBuffer)
                     res = connection.WriteCommand(TConnectionPlatform.TCommands.icEvent, payload.Buffer);
                 // reset write position
                 payload.WriteStart(bodyIndex);
             } while ((readSize == TConnection.MaxStreamBodyBuffer) && (res > 0));
             if (res > 0) {
                 // clip ByteBuffer to bytes read from stream
                 // write pointer in ByteBuffer is still at beginning of stream read buffer!
                 payload.PrepareStart();
                 payload.PrepareSize(readSize);
                 payload.PrepareApplyAndTrim();
                 // fixup event kind
                 payload.WriteStart(eventKindIndex);
                 payload.QWrite((Int32) TEventKind.ekStreamTail);
                 res = connection.WriteCommand(TConnectionPlatform.TCommands.icEvent, payload.Buffer);
             }
         }
         return res;
     }
     else
         return TConnection.iceNotEventPublished;
 }
Ejemplo n.º 2
0
 // write all readable data WITH size
 public void Write(TByteBuffer aValue)
 {
     if (sizeof(Int32) + aValue.ReadAvailable > WriteAvailable)
         Length = FWriteCursor + sizeof(Int32) + aValue.ReadAvailable;
     QWrite(aValue.ReadAvailable);
     Array.Copy(aValue.FBuffer, aValue.ReadCursor, FBuffer, FWriteCursor, aValue.ReadAvailable);
     FWriteCursor += aValue.ReadAvailable;
 }
Ejemplo n.º 3
0
        private void Effects_OnNormalEvent(TEventEntry aevent, TByteBuffer apayload)
        {
            Execute.OnUIThread(() =>
            {
                int command = -1;
                string strJson = "";

                apayload.Read(out command);
                apayload.Read(out strJson);

                //                Debug.WriteLine("NormalEvent received from IMB: [id:{0}, command:{1}]:\n{2}", aevent.ID, command, strJson);
                Debug.WriteLine("NormalEvent received from IMB: [id:{0}, command:{1}]:\n{2} bytes", this.GetHashCode(), command, strJson.Length);
                if (!string.IsNullOrWhiteSpace(strJson))
                {
                    //todo: fixed in new effects binary, this replace WILL produce problems and MUST be removed:
                    strJson = strJson.Replace("NAN", "NaN");
                    var body = JObject.Parse(strJson);
                    Guid id;

                    switch (command)
                    {
                        case 1102:
                            Debug.WriteLine("ImbEvent hash: {0}", this.GetHashCode());
                            SetModelData(body["Models"] as JArray);
                            break;
                        case 1104:
                            var reply = body["ParametersReply"];
                            id = (Guid)reply["ID"];
                            SetModelPropertyData(id, reply["Parameters"] as JArray);
                            break;
                        case 1106:
                            var result = body["Result"];
                            id = (Guid)result["ID"];
                            SetCalculatedData(id, result["Parameters"] as JArray);
                            break;
                        case 1108:
                            //SetUnitsData
                            break;
                        case 1110:
                            SetChemicalsData(body["ChemicalNames"] as JArray);
                            break;
                    }
                }
            });
        }
Ejemplo n.º 4
0
 // read size and data and store WITH size and data
 public bool Read(TByteBuffer aValue)
 {
     Int32 Len;
     if (Read(out Len))
     {
         if (Len <= ReadAvailable)
         {
             aValue.PrepareSize(Len + sizeof(Int32));
             aValue.PrepareApply();
             aValue.QWrite(Len);
             Array.Copy(FBuffer, FReadCursor, aValue.FBuffer, aValue.FWriteCursor, Len);
             FReadCursor += Len;
             return true;
         }
         else
             return false;
     }
     else
         return false;
 }
Ejemplo n.º 5
0
 // read rest
 public void ReadRest(ref TByteBuffer aValue)
 {
     if (ReadAvailable > 0)
     {
         if (ReadAvailable > aValue.WriteAvailable)
             aValue.Length = aValue.FWriteCursor + ReadAvailable;
         Array.Copy(FBuffer, FReadCursor, aValue.FBuffer, FWriteCursor, ReadAvailable);
     }
 }
Ejemplo n.º 6
0
        private void Media_OnBuffer(TEventEntry aEvent, int aTick, int aBufferID, TByteBuffer aBuffer) {
            Execute.OnUIThread(() => {
                using (var stream = new MemoryStream(aBuffer.Buffer)) {
                    var image = new BitmapImage();
                    image.BeginInit();
                    image.StreamSource = stream;
                    image.EndInit();

                    var m = new Media {Image = image};
                    TriggerMediaReceived(m);
                }
            });
        }
Ejemplo n.º 7
0
 private void Media_OnNormalEvent(TEventEntry aEvent, TByteBuffer aPayload)
 {
     var pl = aPayload.ReadString();
     var m = Media.FromString(pl);
     if (m == null) return;
     if (MediaReceived == null) return;
     var s = FindClient(Convert.ToInt32(m.Sender));
     if (MediaReceived!=null) MediaReceived(this, new MediaReceivedEventArgs
     {
         Media = m,
         Sender = s
     });
 }
Ejemplo n.º 8
0
 public int SignalString(string p) {
     var SmallTestEventPayload = new TByteBuffer();
     // build payload for small event
     SmallTestEventPayload.Prepare(p);
     SmallTestEventPayload.PrepareApply();
     SmallTestEventPayload.QWrite(p);
     return SignalEvent(TEventKind.ekNormalEvent, SmallTestEventPayload.Buffer);
 }
Ejemplo n.º 9
0
 protected bool ReadCommand(ref TCommands aCommand, byte[] aFixedCommandPart, TByteBuffer aPayload, byte[] aPayloadCheck)
 {
     int NumBytesRead = FNetStream.Read(aFixedCommandPart, 0, aFixedCommandPart.Length);
     if (NumBytesRead > 0)
     {
         while (BitConverter.ToInt64(aFixedCommandPart, 0) != MagicBytesInt64)
         {
             Array.Copy(aFixedCommandPart, 1, aFixedCommandPart, 0, aFixedCommandPart.Length - 1);
             int rbr = FNetStream.ReadByte();
             if (rbr != -1)
                 aFixedCommandPart[aFixedCommandPart.Length - 1] = (byte)rbr; // skipped bytes because of invalid magic in read command
             else
                 return false; // error, no valid connection
         }
         // we found the magic in the stream
         aCommand = (TCommands)BitConverter.ToInt32(aFixedCommandPart, MagicBytes.Length);
         Int32 PayloadSize = BitConverter.ToInt32(aFixedCommandPart, MagicBytes.Length + sizeof(Int32));
         if (PayloadSize <= MaxPayloadSize)
         {
             aPayload.Clear(PayloadSize);
             if (PayloadSize > 0)
             {
                 int Len = ReadBytesFromNetStream(aPayload);
                 if (Len == aPayload.Length)
                 {
                     NumBytesRead = FNetStream.Read(aPayloadCheck, 0, aPayloadCheck.Length);
                     return NumBytesRead == aPayloadCheck.Length && BitConverter.ToInt32(aPayloadCheck, 0) == CheckStringMagic;
                 }
                 else
                     return false; // error, payload size mismatch
             }
             else
                 return true; // ok, no payload
         }
         else
             return false;  // error, payload is over max size
     }
     else
         return false; //  error, no valid connection
 }
Ejemplo n.º 10
0
 public int TimerAcknowledge(string aTimerName, string aClientName, int aProposedTimeStep) {
     var Payload = new TByteBuffer();
     Payload.Prepare(aClientName);
     Payload.Prepare(aTimerName);
     Payload.Prepare(aProposedTimeStep);
     Payload.PrepareApply();
     Payload.QWrite(aClientName);
     Payload.QWrite(aTimerName);
     Payload.QWrite(aProposedTimeStep);
     return SignalEvent(TEventKind.ekTimerAcknowledge, Payload.Buffer);
 }
Ejemplo n.º 11
0
 // log
 public int LogWriteLn(string aLine, TLogLevel aLevel) {
     var Payload = new TByteBuffer();
     if (!IsPublished && connection.AutoPublish)
         Publish();
     if (IsPublished) {
         Payload.Prepare((Int32) 0); // client id filled in by hub
         Payload.Prepare(aLine);
         Payload.Prepare((Int32) aLevel);
         Payload.PrepareApply();
         Payload.QWrite((Int32) 0); // client id filled in by hub
         Payload.QWrite(aLine);
         Payload.QWrite((Int32) aLevel);
         return SignalEvent(TEventKind.ekLogWriteLn, Payload.Buffer);
     }
     else
         return TConnection.iceNotEventPublished;
 }
Ejemplo n.º 12
0
 public int TimerSetSpeed(string aTimerName, double aSpeedFactor) {
     var Payload = new TByteBuffer();
     Payload.Prepare(aTimerName);
     Payload.Prepare(aSpeedFactor);
     Payload.PrepareApply();
     Payload.QWrite(aTimerName);
     Payload.QWrite(aSpeedFactor);
     return SignalEvent(TEventKind.ekTimerSetSpeed, Payload.Buffer);
 }
Ejemplo n.º 13
0
 // timers
 public int TimerCreate(string aTimerName, Int64 aStartTimeUTCorRelFT, int aResolutionms, double aSpeedFactor,
     int aRepeatCount = trcInfinite) {
     var Payload = new TByteBuffer();
     if (!IsPublished && connection.AutoPublish)
         Publish();
     if (IsPublished) {
         Payload.Prepare(ID);
         Payload.Prepare(aTimerName);
         Payload.Prepare(aStartTimeUTCorRelFT);
         Payload.Prepare(aResolutionms);
         Payload.Prepare(aSpeedFactor);
         Payload.Prepare(aRepeatCount);
         Payload.PrepareApply();
         Payload.QWrite(ID);
         Payload.QWrite(aTimerName);
         Payload.QWrite(aStartTimeUTCorRelFT);
         Payload.QWrite(aResolutionms);
         Payload.QWrite(aSpeedFactor);
         Payload.QWrite(aRepeatCount);
         return connection.WriteCommand(TConnectionPlatform.TCommands.icCreateTimer, Payload.Buffer);
     }
     else
         return TConnection.iceNotEventPublished;
 }
Ejemplo n.º 14
0
 public int SignalChangeObject(int aAction, int aObjectID, string aAttribute = "") {
     var Payload = new TByteBuffer();
     if (!IsPublished && connection.AutoPublish)
         Publish();
     if (IsPublished) {
         Payload.Prepare(ID);
         Payload.Prepare((Int32) 0); // tick
         Payload.Prepare((Int32) TEventKind.ekChangeObjectEvent);
         Payload.Prepare(aAction);
         Payload.Prepare(aObjectID);
         Payload.Prepare(aAttribute);
         Payload.PrepareApply();
         Payload.QWrite(ID);
         Payload.QWrite((Int32) (0)); // tick
         Payload.QWrite((Int32) TEventKind.ekChangeObjectEvent);
         Payload.QWrite(aAction);
         Payload.QWrite(aObjectID);
         Payload.QWrite(aAttribute);
         return connection.WriteCommand(TConnectionPlatform.TCommands.icEvent, Payload.Buffer);
     }
     else
         return TConnection.iceNotEventPublished;
 }
Ejemplo n.º 15
0
        void _strokeStream_OnNormalEvent(TEventEntry aEvent, TByteBuffer aPayload)
        {
            rsv.Dispatcher.Invoke(
                delegate
                {   
                    string strokesStr = aPayload.ReadString();
                    if (String.IsNullOrEmpty(strokesStr))
                        return;
                    if (strokesStr == "clear")
                    {
                        _strokes = new Dictionary<string, Stroke>();
                        rsv.inkStrokes.Strokes.Clear();
                        rsv.inkStrokes.InvalidateVisual();
                        rsv.gMain.InvalidateVisual();
                        return;
                    }
                    string[] strokesArr = strokesStr.Split(';');
                    _strokes = new Dictionary<string, Stroke>();
                    rsv.inkStrokes.Strokes.Clear();
                    foreach (string strokeStr in strokesArr)
                    {
                        string[] strokeDef = strokeStr.Split('/');
                        if (strokeDef.Length != 2)
                            break;
                        string guid = strokeDef[0];
                        if (_strokes.ContainsKey(guid))
                            continue;
                            
                        string[] pointsArr = strokeDef[1].Split('|');
                        StylusPointCollection points = new StylusPointCollection();
                        try
                        {
                            foreach (string pointStr in pointsArr)
                            {

                                string[] pointParts = pointStr.Split(',');

                                if (pointParts.Length == 2 && wb != null)
                                {
                                    StylusPoint point = new StylusPoint(wb.Width / 640d * double.Parse(pointParts[1]), wb.Height - (wb.Height / 480d * double.Parse(pointParts[0])));
                                    //StylusPoint point = new StylusPoint(double.Parse(pointParts[1]), wb.Height - double.Parse(pointParts[0]));
                                    points.Add(point);
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            string errMsg = err.Message;
                        }
                        try
                        {
                            Stroke stroke = new Stroke(points);
                            stroke.DrawingAttributes.Color = Colors.Red;
                            stroke.DrawingAttributes.Height = 3;
                            stroke.DrawingAttributes.Width = 3;
                            //rsv.inkStrokes.Width = rsv.bs.ActualWidth;
                            rsv.inkStrokes.Strokes.Add(stroke);
                                
                            _strokes.Add(guid, stroke);
                               
                        }
                        catch { }
                    }
                    rsv.inkStrokes.InvalidateVisual();
                    rsv.gMain.InvalidateVisual();
                });
        }
Ejemplo n.º 16
0
 protected virtual void HandleCommand(TCommands aCommand, TByteBuffer aPayload)
 {
 }
Ejemplo n.º 17
0
        //        public void AddLocalDataServiceTemplate(string folder, string file) {
        //            var idName = Path.GetFileNameWithoutExtension(file); 
        //            var guid = Guid.NewGuid();
        //            if (string.IsNullOrEmpty(idName)) return;
        //            var ps = new PoiService {
        //                IsLocal = true,
        //                Folder = folder,
        //                Id = guid,
        //                Name = idName,
        //                IsTemplate = true,
        //                StaticService = false,
        //                RelativeFolder = folder.Replace(baseFolder, string.Empty)
        //            };
        //            ps.InitPoiService();
        //            Templates.Add(ps);
        //            //CheckSettings(ps);
        //        }
        //
        //        public PoiService AddLocalDataServiceFromCsv(string folder, Mode _mode, string file, string originFolder = "",
        //            bool autoStart = false)
        //        {
        //            PoiServiceImporterFromFileList poiServiceImporterFromFileList = PoiServiceImporterFromFileList.Instance;
        //            IImporter<FileLocation, PoiService> suitableImporter = poiServiceImporterFromFileList.FirstOrDefault(importer => importer.DataFormatExtension.Equals("csv"));
        //
        //            if (suitableImporter == null)
        //            {
        //                throw new NotImplementedException("Cannot find an importer for CSV files in the assembly.");
        //            }
        //
        //            IOResult<PoiService> ioResult = suitableImporter.ImportData(new FileLocation(Path.Combine(folder, file)));
        //            if (ioResult.Successful)
        //            {
        //                return ioResult.Result;
        //            }
        //            else
        //            {
        //                throw ioResult.Exception;
        //            }
        //        }

        //private static void CheckSettings(Service ps) {
        //    if (ps.SettingsList != null) return;
        //    ps.SettingsList = ps.CreateContentList("settings", typeof(ServiceSettings));
        //    ps.SettingsList.Add(new ServiceSettings());
        //    ps.AllContent.Remove(ps.AllContent.FirstOrDefault(c => string.Equals(ps.SettingsList.Id, c.Id, StringComparison.InvariantCultureIgnoreCase)));
        //    ps.AllContent.Add(ps.SettingsList);
        //}

        /// <summary>
        ///     received message on private channel
        /// </summary>
        private void ReceivedPrivateMessage(TEventEntry aEvent, int aTick, int aBufferId, TByteBuffer aBuffer){ // REVIEW TODO fix: removed async
            var pm = PrivateMessage.ConvertByteArrayToMessage(aBuffer.Buffer);
            if (pm == null)
            {
                LogCs.LogWarning(String.Format("Received IMB message: Corrupt message! ", pm.Id, pm.Action));
                return;
            }
            var s = Services.FirstOrDefault(k => k.Id == pm.Id);
            if (s == null)
            {
                LogCs.LogWarning(String.Format("Received IMB message: Service with GUID '{0}' is not found in servicelist (msg action is {1}). Ignore message. ",
                        pm.Id, pm.Action));
                return;
            }
            var reqClient = AppState.Imb.FindClient(pm.Sender);
            switch (pm.Action) {
                case PrivateMessageActions.RequestData:
                    SendData(pm.Sender, s, pm.ContentId, pm.OwnerId, pm.Channel);
                    break;
                case PrivateMessageActions.ResponseData:
                    if ((s.store.SaveBytes(s.Folder, pm.ContentId, pm.Content, false))) // REVIEW TODO fix: removed await
                        s.DataReceived(pm.ContentId, pm.Content);
                    break;
                case PrivateMessageActions.SubscribeRequest:
                    // TODO EV Why do you set server initialization to false? When adding a task, it is not synchronized anymore (RegisterContent is cancelled).
                    //s.IsInitialized = false;
                    if (!s.Subscribers.Contains(pm.Sender)) s.Subscribers.Add(pm.Sender);
                    LogImbService.LogMessage(String.Format("Received IMB message: IMB client with handle {0} ({1}) requested to subscribe (join) service '{2}' ({3}) (add to service).",
                          pm.Sender, (reqClient != null) ? reqClient.Name : "-", s.Name, pm.Id));
                    SendToImbBusSubscriptedToService(s.Id, pm.Sender);
                    LogImbService.LogMessage(String.Format("IMB handles subscribed (joined) to service {0}: {1}", s.Name, s.SubscribedImbClientHandles));

                    if (reqClient != null && (AppState.Imb.ActiveGroup == null || !AppState.Imb.ActiveGroup.Clients.Contains(reqClient.Id)))
                        Execute.OnUIThread(
                            () => AppState.TriggerNotification(reqClient.Name + " has joined " + s.Name, image: reqClient.Image));
                    break;
                case PrivateMessageActions.UnsubscribeRequest:
                    //s.IsInitialized = false;
                    if (s.Subscribers.Contains(pm.Sender)) s.Subscribers.Remove(pm.Sender);
                    SendPrivateMessage(pm.Sender, PrivateMessageActions.Unsubscribe, s.Id);
                    var unsubClient = AppState.Imb.FindClient(pm.Sender);
                    if (unsubClient != null) Execute.OnUIThread(() => AppState.TriggerNotification(unsubClient.Name + " has left " + s.Name, image: unsubClient.Image));
                    LogImbService.LogMessage(String.Format("Received IMB message: IMB client {0} requested to unsubscribe (unjoin) to service '{1}'({2}) (joined service).",
                       AppState.Imb.ImbClientHandleToName(pm.Sender), s.Name, pm.Id));
                    LogImbService.LogMessage(String.Format("IMB handles subscribed (joined) to service '{0}'({1}): {2}", s.Name, s.Id, s.SubscribedImbClientHandles));
                    break;
                case PrivateMessageActions.ServiceReset: // requested for service reset
                    int priority = 2;
                    int.TryParse(pm.Channel, out priority);
                    SendServiceReset(pm.Sender, s.Id, priority);
                    //var resx = s.ToXml().ToString();
                    //SendPrivateMessage(pm.Sender,PrivateMessageActions.ResponseXml,s.Id,resx,Guid.Empty);
                    break;
                case PrivateMessageActions.RequestXml:
                    var res = s.ToXml().ToString();
                    SendPrivateMessage(pm.Sender, PrivateMessageActions.ResponseXml, s.Id, res, Guid.Empty);
                    break;
                case PrivateMessageActions.ResponseXml:
                    LogImbService.LogMessage(String.Format("Received IMB message: Recieved service XML definition for service {0} ({1}), Load XML into service.",
                         s.Name, s.Id));
                    LogImbService.ToFile(String.Format("./logging/ReceivedServiceDefinition_{0}_{1}_{2}", s.Name, s.Id, DateTime.Now.Ticks), pm.ContentId);
                    s.FromXml(pm.ContentId, s.Folder);
                    s.TriggerInitialized();
                    break;
                case PrivateMessageActions.Subscribe:
                    LogImbService.LogMessage(String.Format("Received IMB message: Subscribe request to subscribe to (join) service '{0}'({1}) acknowledged (mode={2})", s.Name, s.Id, mode));
                    s.Subscribe(mode);
                    s.SubscribeServiceChannel();
                    //Subscribe(s);
                    if (Subscribed != null) Subscribed(this, new ServiceSubscribeEventArgs { Service = s });
                    var npm = new PrivateMessage {
                        Action = PrivateMessageActions.ServiceReset,
                        Id = s.Id,
                        Sender = client.Id,
                        Channel = SyncPriority.ToString()
                    };
                    SendPrivateMessage(pm.Sender, npm);
                    break;
                case PrivateMessageActions.Unsubscribe:
                    s.Unsubscribe();
                    s.UnSubscribeServiceChannel();
                    if (UnSubscribed != null) UnSubscribed(this, new ServiceSubscribeEventArgs { Service = s });
                    break;
                case PrivateMessageActions.ListReset: // receiving lists from server
                    ListReset(s.Id, pm.Content, pm.Channel);
                    if (pm.ContentId == "First")
                    {
                        count = 0;
                    }
                    count += pm.Content.Length;
                    if (pm.ContentId == "Last")
                    {
                        var l = count;
                        LogImbService.LogMessage(String.Format("Received last content for Service {0}", s.Id));
                        s.TriggerInitialized();
                    }
                    LogImbService.LogMessage(String.Format("Received the content #{4} of service '{0}'({1}) from IMB client {2} (channel='{3}') (ListReset action).",
                        s.Name, s.Id, AppState.Imb.ImbClientHandleToName(pm.Sender), pm.Channel, count));
                    break;
                case PrivateMessageActions.SendData:
                    
                    var f = s.Folder + @"\_Media\" + pm.ContentId;
                    LogImbService.LogMessage(String.Format("IMB Message SendData received; store {0} bytes to location '{1}'", pm.Content.Length, f));
                    s.store.SaveBytes(f, pm.Content);
                    break;
            }
        }
Ejemplo n.º 18
0
 protected void ReadCommands()
 {
     // todo: more like Delphi code
     TCommands Command = TCommands.icEndSession;
     // define once
     byte[] FixedCommandPart = new byte[MagicBytes.Length + sizeof(Int32) + sizeof(Int32)]; // magic + command + payloadsize
     TByteBuffer Payload = new TByteBuffer();
     byte[] PayloadCheck = new byte[sizeof(Int32)];
     do
     {
         try
         {
             try
             {
                 if (ReadCommand(ref Command, FixedCommandPart, Payload, PayloadCheck))
                     HandleCommand(Command, Payload);
             }
             catch (ThreadAbortException)
             {
                 Thread.ResetAbort();
                 Command = TCommands.icEndSession;
             }
         }
         catch (Exception e) {
             var level = 0;
             while (e != null) {
                 Logger.Log("IMB3", "General Exception, level " + level++, e.Message, Logger.Level.Error);
                 e = e.InnerException;
             }
             
             //if (Connected)
             //    Debug.Print("## Exception in ReadCommands loop: " + e.Message);
         }
     } while (Command != TCommands.icEndSession && Connected);
 }
Ejemplo n.º 19
0
 private void Positions_OnNormalEvent(TEventEntry aEvent, TByteBuffer aPayload)
 {
     var d = aPayload.ReadString();
     var s = aEvent.EventName.Split('.');
     if (s.Length != 3) return;
     var cl = Clients.FirstOrDefault(k => k.Key == Int32.Parse(s[1]));
     cl.Value.UpdatePosition(d);
 }
Ejemplo n.º 20
0
 // manually reading commands when not using a reader thread
 public void ReadCommandsNonBlocking()
 {
     TCommands Command = TCommands.icEndSession;
     byte[] FixedCommandPart = new byte[MagicBytes.Length + sizeof(Int32) + sizeof(Int32)]; // magic + command + payloadsize
     TByteBuffer Payload = new TByteBuffer();
     byte[] PayloadCheck = new byte[sizeof(Int32)];
     if (FNetStream.DataAvailable)
     {
         do
         {
             if (ReadCommand(ref Command, FixedCommandPart, Payload, PayloadCheck))
                 HandleCommand(Command, Payload);
         } while (Command != TCommands.icEndSession && Connected);
     }
 }
Ejemplo n.º 21
0
 private void Commands_OnNormalEvent(TEventEntry aEvent, TByteBuffer aPayload)
 {
     var c = Command.FromString(aPayload.ReadString());
     if (CommandReceived != null) CommandReceived(this, c);
 }
Ejemplo n.º 22
0
 // manually reading commands when not using a reader thread
 public void ReadCommandsNonThreaded(int aTimeOut)
 {
     TCommands Command = TCommands.icEndSession;
     byte[] FixedCommandPart = new byte[MagicBytes.Length + sizeof(Int32) + sizeof(Int32)]; // magic + command + payloadsize
     TByteBuffer Payload = new TByteBuffer();
     byte[] PayloadCheck = new byte[sizeof(Int32)];
     FNetStream.ReadTimeout = aTimeOut;
     do
     {
         if (ReadCommand(ref Command, FixedCommandPart, Payload, PayloadCheck))
             HandleCommand(Command, Payload);
     } while ((Command != TCommands.icEndSession) && Connected);
 }
Ejemplo n.º 23
0
 // read size and data and store as a whole WITHOUT size (size=length buffer)
 public TByteBuffer ReadByteBuffer()
 {
     Int32 Len;
     if (Read(out Len))
     {
         if (Len <= ReadAvailable)
         {
             TByteBuffer Buffer = new TByteBuffer(Len);
             Array.Copy(FBuffer, FReadCursor, Buffer.FBuffer, Buffer.FWriteCursor, Len);
             Buffer.Written(Len);
             FReadCursor += Len;
             return Buffer;
         }
         else
             return null;
     }
     else
         return null;
 }
Ejemplo n.º 24
0
 protected int ReadBytesFromNetStream(TByteBuffer aBuffer)
 {
     try
     {
         int Count = 0;
         int NumBytesRead = -1;
         while (aBuffer.WriteAvailable > 0 && NumBytesRead != 0)
         {
             NumBytesRead = FNetStream.Read(aBuffer.Buffer, aBuffer.WriteCursor, aBuffer.WriteAvailable);
             aBuffer.Written(NumBytesRead);
             Count += NumBytesRead;
         }
         return Count;
     }
     catch (IOException)
     {
         return 0; // signal connection error
     }
 }
Ejemplo n.º 25
0
 // prepare all readable data WITH size
 public void Prepare(TByteBuffer aValue) { FPrepareCursor += sizeof(Int32) + aValue.ReadAvailable; }
Ejemplo n.º 26
0
 private void _cameraStream_OnBuffer(TEventEntry aEvent, int aTick, int aBufferId, TByteBuffer aBuffer)
 {
     rsv.Dispatcher.Invoke(delegate
     {
         //string fotoStr = aPayload.ReadString();
         byte[] fotoBa = aBuffer.Buffer;
         BitmapImage bmp = GetBitmapImage(fotoBa);
         wb = new WriteableBitmap(bmp);
         rsv.bs.Source = wb;
         rsv.bs.InvalidateVisual();
         rsv.inkStrokes.Width = wb.Width;
         rsv.inkStrokes.Height = wb.Height;
     });
 }
Ejemplo n.º 27
0
 // write, with no checking, all readable data WITH size
 public void QWrite(TByteBuffer aValue)
 {
     QWrite(aValue.ReadAvailable);
     Array.Copy(aValue.FBuffer, aValue.ReadCursor, FBuffer, FWriteCursor, aValue.ReadAvailable);
     FWriteCursor += aValue.ReadAvailable;
 }
Ejemplo n.º 28
0
 private void _screenshot_OnBuffer(TEventEntry aEvent, int aTick, int aBufferId, TByteBuffer aBuffer)
 {
     rsv.Dispatcher.Invoke(
         delegate
         {
             //rsv.bs.Source = GetBitmapImage(aBuffer.Buffer);
             //Console.WriteLine(rsv.bs.Source.ToString());
             var bsSrc =  GetImageFromJpegByteArray(aBuffer.Buffer);
             if(bsSrc != null)
                 rsv.bs.Source = bsSrc;
             //rsv.bs.Source = GetImageFromByteArray(aBuffer.Buffer, Client.ResolutionY / Client.Quality,Client.ResolutionX / Client.Quality);
         });
 }
Ejemplo n.º 29
0
        private void SignalEvent(int commandId, string body = null)
        {
            if (_effectsEvent == null)
            {
                ImbSubscribe();

                if (_effectsEvent == null) return;
            }

            Debug.WriteLine(string.Format("Send IMB command {0}:\n{1}", commandId, body));

            TByteBuffer Payload = new TByteBuffer();
            Payload.Prepare((int)commandId);
            if (body != null)
            {
                Payload.Prepare(body);
            }
            Payload.PrepareApply();
            Payload.QWrite((int)commandId);
            if (body != null)
            {
                Payload.QWrite(body);
            }

            _effectsEvent.SignalEvent(TEventEntry.TEventKind.ekNormalEvent, Payload.Buffer);
        }
Ejemplo n.º 30
0
 private static int ReadBytesFromStream(TByteBuffer aBuffer, Stream aStream) {
     try {
         var count = 0;
         var numBytesRead = -1;
         while (aBuffer.WriteAvailable > 0 && numBytesRead != 0) {
             numBytesRead = aStream.Read(aBuffer.Buffer, aBuffer.WriteCursor, aBuffer.WriteAvailable);
             aBuffer.Written(numBytesRead);
             count += numBytesRead;
         }
         return count;
     }
     catch (IOException) {
         return 0; // signal stream read error
     }
 }