public override void Parse(IPacketParser parser) { //eat packet bytes -- they will be save to bytearray and stored in response parser.ReadRemainingBytes(); // TODO gotta save it because it isn't know to the enum apiId won't GenericApiId = (byte)parser.ApiId; }
public static IPacketParser selectPacketParser(byte[] dataBuffer, int iRx) { IPacketParser packetParser = null; try { // Is the packet of a min sensible length, exact number to be defined. if (iRx >= 10) { var start = 0; var payloadStr = getString(dataBuffer, ref start, dataBuffer.Length); if (string.IsNullOrEmpty(payloadStr)) { return(null); //it's not a string } var split = payloadStr.Split(','); if (split.Length < 4) { return(null); //too short packet or malformed } // If we understand how to parse this packet then create a parser for it. switch (split[2].ToUpper()) { case "V100": return(new PacketParserV100()); case "V101": return(new PacketParserV101()); case "V109": return(new PacketParserV109()); case "V114": return(new PacketParserV114()); case "V141": return(new PacketParserV141()); case "V210": return(new PacketParserV210()); case "V204": return(new PacketParserV204()); case "V201": return(new PacketParserV201()); default: return(null); } } } catch (Exception e) { Logger.GetInstance().Exception("selectPacketParser ", e, EventLogPostfix); } return(packetParser); }
private IoSample ParseIoSample(IPacketParser parser) { ushort digital = 0; var analog = new double[Pin.AnalogCount]; if (ContainsDigital) { Logger.LowDebug("Sample contains digital inputs"); digital = UshortUtils.ToUshort(parser.Read(), parser.Read()); } if (ContainsAnalog) { var analogCount = 0; for (var i = 0; i < analog.Length; i++) { if (!IsEnabled((Pin.Analog) i)) continue; var reading = UshortUtils.Parse10BitAnalog(parser.Read(), parser.Read()); analog[i] = AdcHelper.ToMilliVolts(reading); analogCount++; } Logger.LowDebug("Sample contains " + analogCount +" analog inputs"); } return new IoSample(analog, digital); }
public override void Parse(IPacketParser parser) { Sender = new NodeInfo { SerialNumber = parser.ParseAddress64(), NetworkAddress = parser.ParseAddress16() }; Option = (PacketOption)parser.Read("Option"); Remote = new NodeInfo { NetworkAddress = parser.ParseAddress16(), SerialNumber = parser.ParseAddress64() }; byte ch; // NI is terminated with 0 while ((ch = parser.Read("Node Identifier")) != 0) { if (ch > 32 && ch < 126) { Remote.NodeIdentifier += (char)ch; } } ParentAddress = parser.ParseAddress16(); NodeType = (NodeType)parser.Read("Device Type"); SourceAction = (SourceActions)parser.Read("Source Action"); ProfileId = UshortUtils.ToUshort(parser.Read("Profile MSB"), parser.Read("Profile LSB")); MfgId = UshortUtils.ToUshort(parser.Read("MFG MSB"), parser.Read("MFG LSB")); }
public NetworkPacketParser(IPacketParser <T> parser) { _packetLength = 0; _recvBuffOffset = 0; _packetParser = parser; _recvBuffers = new byte[1024 * 10]; //为啥是 10*1024 }
public override void Parse(IPacketParser parser) { base.Parse(parser); DestinationAddress = parser.ParseAddress16(); RetryCount = parser.Read("ZNet Tx Status Tx Count"); DeliveryStatus = (DeliveryResult)parser.Read("ZNet Tx Status Delivery Status"); DiscoveryStatus = (DiscoveryResult)parser.Read("ZNet Tx Status Discovery Status"); }
public Client(IClientManager manager, IClientChecker checker, IPacketParser parser, IStreamParser streamParser) { _manager = manager; _checker = checker; _parser = parser; _streamParser = streamParser; }
public override void Parse(IPacketParser parser) { var value = parser.Read("Modem Status"); Status = value < (byte)ModemStatus.StackError ? (ModemStatus)value : ModemStatus.StackError; }
protected override void ParseFrameHeader(IPacketParser parser) { base.ParseFrameHeader(parser); SourceEndpoint = parser.Read("Reading Source Endpoint"); DestinationEndpoint = parser.Read("Reading Destination Endpoint"); ClusterId = UshortUtils.ToUshort(parser.Read("Reading Cluster Id MSB"), parser.Read("Reading Cluster Id LSB")); ProfileId = UshortUtils.ToUshort(parser.Read("Reading Profile Id MSB"), parser.Read("Reading Profile Id LSB")); }
public override void Parse(IPacketParser parser) { Source = parser.ApiId == ApiId.Rx16Response ? (XBeeAddress)parser.ParseAddress16() : parser.ParseAddress64(); base.Parse(parser); Payload = parser.ReadRemainingBytes(); }
public override void Parse(IPacketParser parser) { Source = parser.ApiId == ApiId.Rx16Response ? (XBeeAddress) parser.ParseAddress16() : parser.ParseAddress64(); base.Parse(parser); Payload = parser.ReadRemainingBytes(); }
// step ready to be parsed collection public void parseAllReadyData(DBWriter myDBWriter) { if (!closing) { DateTime start = DateTime.Now; var parseDurations = new List <double>(); lock (currentlyParsingLock) { lock (failedParsing) { currentlyParsingIndex = 0; // Parse all data currentlyParsing.ForEach(delegate(RawData obj) { try { Logger.GetInstance().WritePayloadToLogFile(obj.rawData, obj.rawDataLength, LogType.RawData); Logger.GetInstance().WritePayloadBinaryToLogFile(obj.rawData, obj.rawDataLength, LogType.RawBinary); } catch (Exception ex) { Logger.GetInstance().Exception("Failed to write the log file", ex, EventLogPostfix); } bool moreDataExpected = false; // currently ignored bool packetParsedOK = false; IPacketParser packetParser = PacketParserCommon.selectPacketParser(obj.rawData, obj.rawDataLength); currentlyParsingIndex++; var parseStart = DateTime.Now; if (packetParser != null) { packetParser.TrackerID = obj.trackerID; packetParsedOK = packetParser.Parse(myDBWriter, obj.rawData, obj.rawDataLength, ref moreDataExpected); obj.parsedOK = packetParsedOK; if (!packetParsedOK) { obj.parseRetryCount++; } } parseDurations.Add((DateTime.Now - parseStart).TotalMilliseconds); }); currentlyParsing.Clear(); } } previousParseDurationAverage = Average(parseDurations); previousParseDuration = DateTime.Now - start; } }
public override void Parse(IPacketParser parser) { base.Parse(parser); Command = UshortUtils.ToUshort( parser.Read("AT Response Char 1"), parser.Read("AT Response Char 2")); Status = (AtResponseStatus)parser.Read("AT Response Status"); Value = parser.ReadRemainingBytes(); }
public override void Parse(IPacketParser parser) { base.Parse(parser); Command = UshortUtils.ToUshort( parser.Read("AT Response Char 1"), parser.Read("AT Response Char 2")); Status = (AtResponseStatus) parser.Read("AT Response Status"); Value = parser.ReadRemainingBytes(); }
public override void Parse(IPacketParser parser) { FrameId = parser.Read("Frame Id"); RemoteSerial = parser.ParseAddress64(); RemoteAddress = parser.ParseAddress16(); Command = UshortUtils.ToUshort( parser.Read("AT Response Char 1"), parser.Read("AT Response Char 2")); Status = (AtResponseStatus) parser.Read("AT Response Status"); Value = parser.ReadRemainingBytes(); }
public override void Parse(IPacketParser parser) { FrameId = parser.Read("Frame Id"); RemoteSerial = parser.ParseAddress64(); RemoteAddress = parser.ParseAddress16(); Command = UshortUtils.ToUshort( parser.Read("AT Response Char 1"), parser.Read("AT Response Char 2")); Status = (AtResponseStatus)parser.Read("AT Response Status"); Value = parser.ReadRemainingBytes(); }
public iRemote() { this.addTv = new UPnPCallbackFunc(TvAddedCallback); this.delTv = new UPnPCallbackFunc(TvDeletedCallback); this.packetCb = new IPacketParser(PacketParser); this.connectOk = new IRemoteCallback(connectSuccess); this.connectFail = new IRemoteCallback(connectionFail); this.authentic = new IRemoteCallback(authentication); this.disc = new IRemoteCallback(disconnect); this.authenticFail = new IRemoteCallback(authenticationFail); this.authenticFull = new IRemoteCallback(authenticationFull); this.authenticDeny = new IRemoteCallback(authenticationDeny); iRemote.InstallUPnPCallback(this.addTv, this.delTv); int num = iRemote.StartUPnP(new StringBuilder("Mobile Simulator")); }
protected override void ParseFramePayload(IPacketParser parser) { // eat sample size.. always 1 var size = parser.Read("ZNet RX IO Sample Size"); if (size != 1) { throw new XBeeParseException("Sample size is not supported if > 1 for ZNet I/O"); } DigitalChannelMask = UshortUtils.ToUshort(parser.Read("ZNet RX IO Sample Digital Mask 1"), parser.Read("ZNet RX IO Sample Digital Mask 2")); // TODO apparent bug: channel mask on ZigBee Pro firmware has DIO10/P0 as enabled even though it's set to 01 (RSSI). Digital value reports low. DigitalChannelMask &= 0x1CFF; //11100 zero out all but bits 3-5 AnalogChannelMask = parser.Read("ZNet RX IO Sample Analog Channel Mask"); AnalogChannelMask &= 0x8f; //10001111 zero out n/a bits if (ContainsDigital) { Digital = UshortUtils.ToUshort(parser.Read("ZNet RX IO DIO MSB"), parser.Read("ZNet RX IO DIO LSB")); } // parse 10-bit analog values Analog = new int[5]; for (var pin = Pin.A0; pin <= Pin.A3; pin++) { if (!IsAnalogEnabled(pin)) { continue; } Analog[(byte)pin] = UshortUtils.Parse10BitAnalog(parser.Read(), parser.Read()); } if (IsAnalogEnabled(Pin.SupplyVoltage)) { Analog[SupplyVoltageIndex] = UshortUtils.Parse10BitAnalog(parser.Read(), parser.Read()); } }
public WorkerTCPSocket(ServiceConfigurationSection config, Socket tcpSocket, DBWriter dbWriter, RawDataManager rawDataManager) { m_WorkerTCPSocketID = new Random().Next(); myDBWriter = dbWriter; myTCPSocket = tcpSocket; myRawDataManager = rawDataManager; myConfig = config; firstChunk = true; moreChunksExpected = false; dataBufferIndex = 0; emptyRxCount = 0; allChunksReceived = false; // Mark the age of this worker object connectionTime = DateTime.Now; packetParser = null; }
public override void Parse(IPacketParser parser) { Source = parser.ApiId == ApiId.Rx16IoResponse ? (XBeeAddress)parser.ParseAddress16() : parser.ParseAddress64(); base.Parse(parser); SampleCount = parser.Read(); ChannelIndicator = UshortUtils.ToUshort(parser.Read(), parser.Read()); ContainsDigital = (ChannelIndicator & DigitalMask) > 0; ContainsAnalog = (ChannelIndicator & AnalogMask) > 0; Samples = new IoSample[SampleCount]; for (var i = 0; i < SampleCount; i++) { Logger.LowDebug("Parsing I/O sample nr " + (i + 1)); Samples[i] = ParseIoSample(parser); } }
/// <summary> /// Close the socket and dispose of the worker object /// </summary> public void CloseAndDestroy() { if (myTCPSocket != null) { try { myTCPSocket.Close(); } catch (Exception) { // socket may already have been closed } myTCPSocket = null; } packetParser = null; // request removal from the worker object array list so that we get gc'd CameraListenerService.RemoveWorkerTCPSocket(this); }
private void ParseData(DBWriter myDBWriter, RawData obj, List <double> parseDurations) { bool moreDataExpected = false; // currently ignored bool packetParsedOK = false; IPacketParser packetParser = PacketParserCommon.selectPacketParser(obj.rawData, obj.rawDataLength); currentlyParsingIndex++; var parseStart = DateTime.Now; if (packetParser != null) { packetParser.TrackerID = obj.trackerID; packetParsedOK = packetParser.Parse(myDBWriter, obj.rawData, obj.rawDataLength, ref moreDataExpected); obj.parsedOK = packetParsedOK; if (!packetParsedOK) { obj.parseRetryCount++; } } parseDurations.Add((DateTime.Now - parseStart).TotalMilliseconds); }
public override ICommandReader CreateCommandReader(IPacketParser parser) { return(new TextCommandReader(parser)); }
/// <summary> /// Call back for received data. /// </summary> public void OnDataReceived(IAsyncResult asyn) { bool packetParsedOK = false; //Logger.GetInstance().Message(string.Format("ID: {0};", m_WorkerTCPSocketID)); lock (parserlock) { bool moreDataExpected = false; // Mark the age of this worker object connectionTime = DateTime.Now; try { // finish the rx process and get the count of bytes in buffer int iRx = myTCPSocket.EndReceive(asyn); try { Logger.GetInstance().WritePayloadToLogFile(dataBuffer, iRx, LogType.RawData); } catch (Exception ex) { Logger.GetInstance().Exception("Failed to write the log file", ex, EventLogPostfix); } if ((packetParser == null)) { packetParser = PacketParserCommon.selectPacketParser(dataBuffer, iRx); } if (packetParser != null) { if (packetParser.IsContinuous) { if (packetParser.Validate(dataBuffer, iRx, ref moreDataExpected)) { myRawDataManager.addNewRawData(dataBuffer, iRx, packetParser.TrackerID); } sendACK_NACK(packetParser.getPacketACK_NACK()); moreDataExpected = true; } else { if (firstChunk && packetParser.IsMultiChunk) // this should be a method of the selected packet parser that tells us if we need more data { moreChunksExpected = true; // for now the only end condition for this is to allow the socket to timeout and save the data on socket close // JL also doesn't have an ACK scheme here! } if (!moreChunksExpected) { // original behaviour before freeze frame data packetParsedOK = packetParser.Validate(dataBuffer, iRx, ref moreDataExpected); if (packetParsedOK) { myRawDataManager.addNewRawData(dataBuffer, iRx); } sendACK_NACK(packetParser.getPacketACK_NACK()); } else { //Logger.GetInstance().Warning(string.Format("ID: {0}; TCP, More Chunks; {1}", m_WorkerTCPSocketID, dataBufferIndex)); // more chunks expected if (firstChunk) { dataBufferAllChunks = new byte[32 * 1024]; //Needs to be bigger for F blobs } Array.Copy(dataBuffer, 0, dataBufferAllChunks, dataBufferIndex, iRx); dataBufferIndex += iRx; if (iRx == 0) { emptyRxCount++; if (emptyRxCount > 10) { allChunksReceived = true; } } } } } else { Logger.GetInstance().Message("OnReceiveData, no packet parser selected.", EventLogPostfix); } } catch (ObjectDisposedException) { // Socket was closed unexpectadly just ignore? // Should we remove / dispose of worker object? } catch (SocketException se) { if (se.ErrorCode == 10054) // error code for connection reset by peer { // no error just remove worker object? } else { Logger.GetInstance().Exception("OnReceiveData, socket error", se, EventLogPostfix); // Should we remove / dispose of worker object? } } catch (Exception e) { Logger.GetInstance().Exception("OnDataReceive, general", e, EventLogPostfix); // Should we remove / dispose of worker object? // timer task ill tidy us up } finally { firstChunk = false; // no longer first Chunk if (moreChunksExpected) { // New method for large single packets from (freeze frame data) if (allChunksReceived) { // all done packetParsedOK = packetParser.Validate(dataBufferAllChunks, dataBufferIndex, ref moreDataExpected); if (packetParsedOK) { myRawDataManager.addNewRawData(dataBufferAllChunks, dataBufferIndex); } sendACK_NACK(packetParser.getPacketACK_NACK()); // don't bother with command sending on FF data blobs packetParser = null; CloseAndDestroy(); } else { WaitForData(); } } else if (moreDataExpected) { // old method for multi line packets from C-Series WaitForData(); } else { packetParser = null; CloseAndDestroy(); } } } }
public override void Parse(IPacketParser parser) { // do nothing }
public override void Parse(IPacketParser parser) { FrameId = parser.Read("Frame Id"); }
/// <summary> /// All subclasses must implement to parse the packet from the input stream. /// The subclass must parse all bytes in the packet starting after the API_ID, and /// up to but not including the checksum. Reading either more or less bytes that expected will /// result in an error. /// </summary> /// <param name="parser"></param> public abstract void Parse(IPacketParser parser);
protected override void ParseFramePayload(IPacketParser parser) { Payload = parser.ReadRemainingBytes(); }
public IEntityHandle Create( [NotNull] SerializablePlayerModel model, [NotNull] ISocketContext socket, [NotNull] IPacketParser packetParser, [NotNull] IPacketHandlerCatalogue packets) { if (model == null) { throw new ArgumentNullException(nameof(model)); } if (socket == null) { throw new ArgumentNullException(nameof(socket)); } if (packetParser == null) { throw new ArgumentNullException(nameof(packetParser)); } if (packets == null) { throw new ArgumentNullException(nameof(packets)); } var id = GetId(); if (id == InvalidPlayerId) { return(null); } Debug.Assert(InstanceLookup[id] == null); var entHandle = EntitySystem.Create($"Entity for player {model.Username}"); var ent = entHandle.Get(); ent.Components.Add(new MessageLogComponent(ent)); ent.Components.Add(new MessageNetworkSyncComponent(ent)); //#if DEBUG ent.Components.Add(new DebugStatNetworkSyncComponent(ent)); //#endif ent.Components.Add(new NetworkingComponent(ent, socket, packetParser)); ent.Components.Add(new PacketDispatcherComponent(ent, packets)); ent.Components.Add(new FlagAccumulatorComponent(ent)); ent.Components.Add(new MarkedForDeathBroadcasterComponent(ent)); var client = new ClientPositionComponent(ent); ent.Components.Add(client); ent.Components.Add <IClientPositionComponent>(client); ent.Components.Add(new RegionNetworkSyncComponent(ent)); var health = new HealthComponent(ent); ent.Components.Add(health); ent.Components.Add <IHealthComponent>(health); var cmb = new CombatStatComponent(ent); ent.Components.Add(cmb); ent.Components.Add <ICombatStatComponent>(cmb); ent.Components.Add(new CombatStatNetworkSyncComponent(ent)); var interf = new InterfaceComponent(ent); ent.Components.Add(interf); ent.Components.Add <IInterfaceComponent>(interf); ent.Components.Add(new InterfaceNetworkSyncComponent(ent)); var skills = new SkillComponent(ent); ent.Components.Add(skills); ent.Components.Add <ISkillComponent>(skills); ent.Components.Add(new SkillNetworkSyncComponent(ent)); var vision = new CappedVisionComponent(ent); ent.Components.Add(vision); ent.Components.Add <IVisionComponent>(vision); ent.Components.Add(new NearbyEntityWatcherComponent(ent)); ent.Components.Add(new NpcNetworkSyncComponent(ent)); ent.Components.Add(new PlayerNetworkSyncComponent(ent)); ent.Components.Add(new GroundItemNetworkSyncComponent(ent)); ent.Components.Add(new TileMovementComponent(ent)); ent.Components.Add(new MovementActionComponent(ent)); ent.Components.Add(new ItemActionDispatchComponent(ent)); var inv = new PlayerInventoryComponent(ent, new ListItemContainer(ent, model.Backpack), new PlayerEquipmentContainer(ent, model.Equipment), new ListItemContainer(ent, model.Bank)); ent.Components.Add(inv); ent.Components.Add <IInventoryComponent>(inv); var player = new PlayerComponent(ent, model.Username, model.Apperance, true, model.TitleId, id, DestroyCallback); ent.Components.Add(player); ent.Components.Add <IPlayerComponent>(player); var check = ent.AreComponentRequirementsSatisfied(out var msg); if (!check) { throw new InvalidOperationException(msg); } // setup skills foreach (var skill in model.Skils) { skills.All.Add(skill.Key, new NormalSkillModel(skill.Key, skill.Value.Boost, skill.Value.Experience)); } // setup health health.SetNewMaxHealth(skills.All[SkillDb.Hitpoints].Level); health.SetNewHealth(model.Health); InstanceLookup[id] = entHandle; _usernameLookup.Add(model.Username, entHandle); NumAlivePlayers++; // teleport player to pos ent.GetTransform().Teleport(model.PosX, model.PosY, model.PosZ); // init components ent.SendMessage(NotificationMessage.Initialize); return(entHandle); }
protected abstract void ParseFramePayload(IPacketParser parser);
protected virtual void ParseFrameOptions(IPacketParser parser) { Option = (Options)parser.Read("ZNet RX Option"); }
public static extern void SetPacketParser(IPacketParser cb);
public override void Parse(IPacketParser parser) { base.Parse(parser); DestinationAddress = parser.ParseAddress16(); RetryCount = parser.Read("ZNet Tx Status Tx Count"); DeliveryStatus = (DeliveryResult) parser.Read("ZNet Tx Status Delivery Status"); DiscoveryStatus = (DiscoveryResult) parser.Read("ZNet Tx Status Discovery Status"); }
public override void Parse(IPacketParser parser) { Sender = new NodeInfo { SerialNumber = parser.ParseAddress64(), NetworkAddress = parser.ParseAddress16() }; Option = (PacketOption) parser.Read("Option"); Remote = new NodeInfo { NetworkAddress = parser.ParseAddress16(), SerialNumber = parser.ParseAddress64() }; byte ch; // NI is terminated with 0 while ((ch = parser.Read("Node Identifier")) != 0) { if (ch > 32 && ch < 126) Remote.NodeIdentifier += (char) ch; } ParentAddress = parser.ParseAddress16(); NodeType = (NodeType) parser.Read("Device Type"); SourceAction = (SourceActions) parser.Read("Source Action"); ProfileId = UshortUtils.ToUshort(parser.Read("Profile MSB"), parser.Read("Profile LSB")); MfgId = UshortUtils.ToUshort(parser.Read("MFG MSB"), parser.Read("MFG LSB")); }
public override void Parse(IPacketParser parser) { Rssi = -1 * parser.Read("RSSI"); Option = (Options)parser.Read("Options"); }
public BinaryCommandReader(IPacketParser parser) { m_parser = parser; }
protected override void ParseFramePayload(IPacketParser parser) { // eat sample size.. always 1 var size = parser.Read("ZNet RX IO Sample Size"); if (size != 1) throw new XBeeParseException("Sample size is not supported if > 1 for ZNet I/O"); DigitalChannelMask = UshortUtils.ToUshort(parser.Read("ZNet RX IO Sample Digital Mask 1"), parser.Read("ZNet RX IO Sample Digital Mask 2")); // TODO apparent bug: channel mask on ZigBee Pro firmware has DIO10/P0 as enabled even though it's set to 01 (RSSI). Digital value reports low. DigitalChannelMask &= 0x1CFF; //11100 zero out all but bits 3-5 AnalogChannelMask = parser.Read("ZNet RX IO Sample Analog Channel Mask"); AnalogChannelMask &= 0x8f; //10001111 zero out n/a bits if (ContainsDigital) Digital = UshortUtils.ToUshort(parser.Read("ZNet RX IO DIO MSB"), parser.Read("ZNet RX IO DIO LSB")); // parse 10-bit analog values Analog = new int[5]; for (var pin = Pin.A0; pin <= Pin.A3; pin++) { if (!IsAnalogEnabled(pin)) continue; Analog[(byte)pin] = UshortUtils.Parse10BitAnalog(parser.Read(), parser.Read()); } if (IsAnalogEnabled(Pin.SupplyVoltage)) Analog[SupplyVoltageIndex] = UshortUtils.Parse10BitAnalog(parser.Read(), parser.Read()); }
protected virtual void ParseFrameHeader(IPacketParser parser) { SourceSerial = parser.ParseAddress64(); SourceAddress = parser.ParseAddress16(); }
public CommandServer(IMotorController motorController, IPacketParser packetParser) { _motorController = motorController; _packetParser = packetParser; }
public override void Parse(IPacketParser parser) { ParseFrameHeader(parser); ParseFrameOptions(parser); ParseFramePayload(parser); }