//------------------------------------------------------------------------------------------------------------------------ #endregion #region Constructor //------------------------------------------------------------------------------------------------------------------------ public LANDiscoverer(IDiscoveryMessageBase DiscoveryMessage, int DiscoveryMessageMaxSize = 1024, int BroadcastPort = DefaultBroadcastPort, int?ID = null) { DebugEx.Assert(DiscoveryMessage != null, "DiscoveryMessage cannot be null"); if (DiscoveryMessage == null) { throw new NullReferenceException("DiscoveryMessage cannot be null"); } //keep info this.BroadcastPort = BroadcastPort; this.DiscoveryMessageMaxSize = DiscoveryMessageMaxSize; //set id if (ID.HasValue) { myID = ID.Value; } //generate id while (myID == 0) #if NETFX { myID = MathTools.GetRandomNumber(0, 10000); } #elif UNIVERSAL { myID = MathTools.GetRandomNumber(20000, 100000); } #endif //update discovery message UpdateDiscoveryMessage(DiscoveryMessage); //hook event for shutdown Channel.OnSystemShutDownRequest.Add(Yodiwo.WeakAction <object> .Create(Deinitialize)); }
//------------------------------------------------------------------------------------------------------------------------ bool _reader(byte[] buffer, int offset, int count) { int r = 0; int penalty = 0; while (r < count && r >= 0) { var _r = streamIn.Read(buffer, offset + r, count - r); if (_r == 0) { //penalty for zero read penalty++; Thread.Sleep(100); //check that we are still connected if (!IsConnected || penalty > 10) { return(false); } } else if (_r < 0) { DebugEx.Assert("Channel (" + Name + ") packet read error (negative readcount)"); return(false); } r += _r; } //check readcount if (r <= 0) { DebugEx.Assert("Channel (" + Name + ") packet read error (invalid readcount)"); return(false); } //finished ok return(true); }
private static (Tile, Train) _move(this World world, Tile tile, Train train, double movementLeft) { DebugEx.Assert(train.T >= 0 && train.T <= 1); var path = world.GetPath(tile); var(t, newMovementLeft) = MoveOnPath(path, train.T, movementLeft); if (Math.Abs(newMovementLeft) > 0.000001) { var nextPath = world.GetNextPath(tile, t == 1); if (nextPath != null) { var nextTile = nextPath?.Tile; var endOfNextPath = nextPath?.AtEndOfPath ?? false; var flip = train.FacingEnd == endOfNextPath; DebugEx.Assert(world.ModifyTileData(nextTile.BaseData, _ => nextTile.Data), "Tile could not be found."); return(world._move( nextTile, new Train(endOfNextPath ? 1 : 0, train.Speed, flip ? !train.FacingEnd : train.FacingEnd, train.Id), flip ? -newMovementLeft : newMovementLeft)); } } return(tile, new Train(t, train.Speed, train.FacingEnd, train.Id)); }
//------------------------------------------------------------------------------------------------------------------------ public void Deinitialize() { lock (this) { try { //close socket #if NETFX try { _sock?.Disconnect(false); } catch { } try { _sock?.Close(); } catch { } #endif try { _sock?.Dispose(); } catch { } _sock = null; //stop tasks IsRunning = false; #if NETFX DiscoveryTask?.Join(200); BroadcastTask?.Join(200); #elif UNIVERSAL DiscoveryTask?.Wait(200); BroadcastTask?.Wait(200); #endif DiscoveryTask = null; BroadcastTask = null; } catch (Exception ex) { DebugEx.Assert(ex); } } }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Functions //------------------------------------------------------------------------------------------------------------------------ public override bool Initialize(mNodeConfig mNodeConfig, string PluginConfig, string UserConfig) { //init base if (base.Initialize(mNodeConfig, PluginConfig, UserConfig) == false) { return(false); } //read config if (!string.IsNullOrWhiteSpace(PluginConfig)) { try { Config = (PluginConfig ?? "").FromJSON <PluginConfig>(); } catch { Config = new PluginConfig(); } } //init try { SetupSerialPortThing(); DebugEx.TraceLog("Successful start of DevelopmentTools plugin."); } catch (Exception ex) { DebugEx.Assert(ex, "Could not init"); } //done return(true); }
//------------------------------------------------------------------------------------------------------------------------ public void Initialize(Node ParentNode) { try { lock (locker) { //check if (IsInitialized) { return; } //keep this._Node = ParentNode; //hook on nodediscovery module if (Node.NodeDiscovery != null) { Node.NodeDiscovery.OnVBMReceived += NodeDiscovery_OnVBMReceived; } //start GraphManager.Start(); //register for thing solve YEventRouter.EventRouter.AddEventHandler <Logic.Blocks.Things.EvThingSolved>(OnThingSolvedCb, 100); //set flag IsInitialized = true; } } catch (Exception ex) { DebugEx.Assert(ex); } }
//------------------------------------------------------------------------------------------------------------------------ public void DeInitialize() { try { lock (locker) { //check if (!IsInitialized) { return; } //set flag IsInitialized = false; //unhook on nodediscovery module if (Node.NodeDiscovery != null) { Node.NodeDiscovery.OnVBMReceived -= NodeDiscovery_OnVBMReceived; } //start GraphManager.Stop(); //register for thing solve YEventRouter.EventRouter.RemoveEventHandler <Logic.Blocks.Things.EvThingSolved>(OnThingSolvedCb); } } catch (Exception ex) { DebugEx.Assert(ex); } }
public bool IsSameType(ThingDescriptor thing) { if (!String.IsNullOrWhiteSpace(Type) && Type != thing.Type) { return(false); } if (Ports.Count != thing.Ports.Count) { return(false); } foreach (var pkv in thing.Ports) { // build the right PortKey PortKey thingPortKey = PortKey.BuildFromArbitraryString(thing.ThingKey, ((PortKey)pkv.PortKey).PortUID); PortDescriptor Port = thing.GetPort(thingPortKey); if (Port == null) { DebugEx.Assert("could not find Port for pkey: " + thingPortKey); } if (Port.PortType != pkv.PortType) { return(false); } } return(true); }
public Rail(string[] sprites, ElmFunc <double, Double2> path) { DebugEx.Assert(sprites.Length == 1 || sprites.Length == 2 || sprites.Length == 4); DebugEx.Assert(sprites.All(Sprite.IsValidElmFunctionName)); Sprites = sprites.ToImmutableList(); Path = path; }
//-------------------------------------------------------------------------------------------------------------------- public static object jsonPost(string url, object data, Type responseType) { var response = default(Tools.Http.RequestResult); try { response = Yodiwo.Tools.Http.RequestPost(url, data.ToJSON(), HttpRequestDataFormat.Json, null); if (response.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(response.ResponseBodyText)) { return(response.ResponseBodyText.FromJSON(responseType)); } else { DebugEx.TraceWarning("post response: " + response.StatusCode.ToString()); return(null); } } catch (Exception ex) { if (response.ResponseBodyText == null) { DebugEx.Assert(ex, "Pairing jsonPost failed (no body)"); } else { DebugEx.Assert(ex, "Pairing jsonPost failed" + Environment.NewLine + "Json Body : " + response.ResponseBodyText); } return(null); } }
public Tile(TileBaseData baseData, ITileData data) { DebugEx.Assert(baseData != null); DebugEx.Assert(data != null); BaseData = baseData; Data = data; }
//------------------------------------------------------------------------------------------------------------------------- #endregion #region Functions //------------------------------------------------------------------------------------------------------------------------- public void StartConnectionTask() { //already running? if (ConnectionTaskRunning) { return; } //start new task Task.Run(async() => { ConnectionTaskRunning = true; try { while (!_IsDisposed && ClientChannel?.State != YPChannel.ChannelStates.Open) { if (Connect()) { break; } else { await Task.Delay(reconnectionAttemptSleep); } } } catch (Exception ex) { DebugEx.Assert(ex, "Unhandled exception in connection Task"); } finally { ConnectionTaskRunning = false; } }); }
/// <summary> /// /// </summary> /// <returns></returns> public static BinaryResourceDescriptor CreateDescriptor(byte[] resource, eBinaryResourceLocationType locationType, object locationDescriptor) { BinaryResourceDescriptor descriptor = new BinaryResourceDescriptor(); try { // Construct descriptor if (locationType.Equals(eBinaryResourceLocationType.Http)) { var locDesc = locationDescriptor as HttpLocationDescriptor; descriptor.LocationDescriptorJson = (new HttpLocationDescriptor { Uri = locDesc.Uri }).ToJSON(); // Use Dropbox's REST API to upload resource } else if (locationType.Equals(eBinaryResourceLocationType.RedisDB)) { var locDesc = locationDescriptor as RedisDBLocationDescriptor; descriptor.LocationDescriptorJson = (new RedisDBLocationDescriptor()).ToJSON(); } } catch (Exception ex) { descriptor = null; DebugEx.Assert(ex, "Error constructing descriptor for specified resource"); } return(descriptor); }
public static bool TestFlavors(PackagesAPI.PackageFlavors flavor, string value1, string value2) { if (flavor == PackagesAPI.PackageFlavors.Version) { //examine versions return(RangedIntegerMatch(value1, value2)); } else if (flavor == PackagesAPI.PackageFlavors.Platform) { //examine platforms return(value1 == value2); } else if (flavor == PackagesAPI.PackageFlavors.Architecture) { //examine architectures return(value1 == value2); } else if (flavor == PackagesAPI.PackageFlavors.Unkown) { DebugEx.Assert("Unkown flavor detected"); return(true); } else { DebugEx.Assert("Unkown flavor " + flavor); return(value1 == value2); //simple string match in unkown cases } }
//------------------------------------------------------------------------------------------------------------------------ public void OnRxRsp(MqttMsg wrapper_msg, object api_msg) { //sanity check DebugEx.Assert(wrapper_msg.SyncId != 0, "Responses must have syncId set to a non-zero number"); if (wrapper_msg.SyncId == 0) { return; } //get id int syncId = wrapper_msg.SyncId; //find blocked transaction, if any RpcBlocker w = null; lock (RpcPending) if (RpcPending.TryGetValue(syncId, out w)) { RpcPending.Remove(syncId); } //remove if found //set result and wake if (w != null) { lock (w) { w.Response = api_msg; Monitor.Pulse(w); } } else { DebugEx.TraceError("Could not find mqtt waiter from response message with ResponseToSeqNo=" + syncId); } }
public static byte[] HttpFetchHandler(BinaryResourceDescriptor descriptor) { byte[] resource = null; // Fetch resource from HTTP location try { var uri = (descriptor.LocationDescriptor as HttpLocationDescriptor).Uri; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream stream = response.GetResponseStream()) using (var ms = new MemoryStream()) { int count = 0; do { byte[] buf = new byte[1024]; count = stream.Read(buf, 0, 1024); ms.Write(buf, 0, count); } while (stream.CanRead && count > 0); resource = ms.ToArray(); } } catch (Exception ex) { DebugEx.Assert(ex, "Error fetching resource from specified HTTP location"); } return(resource); }
public void Stop() { DebugEx.Assert(coroutine != null); AirSystem.OnUpdate -= OnUpdateCallback; //EditorApplication.update -= EditorAppUpdateCallback; PlayState = PlayState.Paused; coroutine = null; }
public TileBaseData(int tileTypeId, Int2 gridPosition, int rotation) { DebugEx.Assert(tileTypeId >= 0, "Tile ids must be non-negative."); DebugEx.Assert(rotation >= 0 && rotation < 4); TileTypeId = tileTypeId; GridPosition = gridPosition; Rotation = rotation; }
public GotRegionMessage(Int2 superGridPosition, ImmutableList <Tile> tiles) { DebugEx.Assert( tiles.All( item => World.GridToSuperGrid(item.BaseData.GridPosition).Equals(superGridPosition))); SuperGridPosition = superGridPosition; Tiles = tiles; }
//------------------------------------------------------------------------------------------------------------------------ private void NodeDiscovery_OnVBMReceived(NodeKey BrotherNode, VirtualBlockEventMsg msg) { try { HandleIncomingVirtualBlockEventMsg(msg); } catch (Exception ex) { DebugEx.Assert(ex); } }
public static void BlendGameObjectAnimation(GameObject go, string animName) { DebugEx.Assert(go != null); Animation animation = go.GetComponent <Animation>(); animation.Blend(animName); }
//------------------------------------------------------------------------------------------------------------------------ public static string AppendPackageFlavorValue(string Component, PackagesAPI.PackageFlavors flavor, string value) { if (Validators.ValidatePackageFlavor(value)) { DebugEx.Assert("Invalid flavor value"); } return(Component + PackagesAPI.PackageFlavorSeparator + PackagesAPI.PackageFlavorKey[flavor] + value); }
//------------------------------------------------------------------------------------------------------------------------- private bool YPChannel_Negotiation(YPChannel.Channel Channel) { DebugEx.TraceLog($"RemoteNode : Negotiation started with node. (ip:{IPAddress} port:{RemotePort} nodekey:{RemoteNodeKey})"); //check if (Channel.ChannelRole != YPChannel.ChannelRole.Server) { DebugEx.Assert("Should not be here"); return(false); } //--------------------- // Association Request //--------------------- { //send request var req = new AssociationRequest() { UnsafeNodeKey = Node.NodeKey, PublicKey = null, }; var rsp = Channel.SendRequest <AssociationResponse>(req); if (rsp == null) { return(false); } //keep discovery message DiscoveryMessage = rsp.DiscoveryMessage; RemoteEndpointID.ID = rsp.DiscoveryMessage.Id; //examine discovery message //.. //keep node key RemoteNodeKey = rsp.UnsafeNodeKey; if (RemoteNodeKey.IsInvalid) { return(false); } //keep public key /* * if (rsp.PublicKey == null || rsp.PublicKey.Length == 0 || rsp.PublicKey.Length > 1024 * 20) * return false; * else*/ PublicKey = rsp.PublicKey; } //--------------------- // Authentication Request //--------------------- //.. //all ok return(true); }
public GotTrainsMessage(Int2 superGridPosition, ImmutableList <Tile> tiles) { DebugEx.Assert(tiles.All(item => item.Data is IRailTileData)); DebugEx.Assert( tiles.All( item => World.GridToSuperGrid(item.BaseData.GridPosition).Equals(superGridPosition))); SuperGridPosition = superGridPosition; TrainTiles = tiles; }
public static bool PointInRectangle(Int2 topLeft, Int2 size, Int2 point) { DebugEx.Assert(size.X >= 0 && size.Y >= 0); var bottomRight = topLeft + size; return (topLeft.X <= point.X && point.X < bottomRight.X && topLeft.Y <= point.Y && point.Y < bottomRight.Y); }
public bool Start(int Port) #endif { lock (this) { //keep this.Port = Port; //get certificate #if NETFX this._certificate = certificate; if (Certificate != null && !Certificate.HasPrivateKey) { DebugEx.Assert("Not private key found in servers certificate"); return(false); } #endif //create socket and bind try { #if NETFX sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Bind(new IPEndPoint(IPAddress.Any, Port)); #elif UNIVERSAL sock = new StreamSocketListener(); sock.ConnectionReceived += Sock_ConnectionReceived; sock.BindServiceNameAsync(Port.ToStringInvariant()).AsTask().Wait(); #endif } catch (Exception ex) { DebugEx.Assert(ex, "YPServer failed to bind port " + Port); return(false); } //mark running _IsRunning = true; //log #if NETFX DebugEx.TraceLog("YPServer (socks) started on port " + Port + " (Secure=" + (certificate != null).ToStringInvariant() + ")"); #elif UNIVERSAL DebugEx.TraceLog("YPServer (socks) started on port " + Port + " (Secure= False)"); #endif //start port listener #if NETFX PortListener = new Thread(PortListenerEntryPoint); PortListener.Name = "YPC Server PortListener thread"; PortListener.IsBackground = true; PortListener.Start(); #endif //done return(true); } }
public static Type ePortType2Type(ePortType PortType) { if (PortType == ePortType.Undefined) { return(null); //treat string as default } else if (PortType == ePortType.Integer) { return(typeof(Int64)); } else if (PortType == ePortType.Decimal || PortType == ePortType.DecimalHigh) { return(typeof(double)); } else if (PortType == ePortType.Boolean) { return(typeof(bool)); } else if (PortType == ePortType.Color) { return(typeof(YColor)); } else if (PortType == ePortType.String) { return(typeof(string)); //already string } else if (PortType == ePortType.VideoDescriptor) { return(typeof(VideoMediaDescriptor)); } else if (PortType == ePortType.AudioDescriptor) { return(typeof(AudioMediaDescriptor)); } else if (PortType == ePortType.BinaryResourceDescriptor) { return(typeof(BinaryResourceDescriptor)); } else if (PortType == ePortType.I2CDescriptor) { return(typeof(I2CCommand));//sos discuss with mits and gepa } else if (PortType == ePortType.JsonString) { return(typeof(string)); } else if (PortType == ePortType.Timestamp) { return(typeof(DateTime)); } else { DebugEx.Assert($"channel type {PortType} not accounted for"); return(null); } }
public Port(PortKey portKey, ePortType type, ioPortDirection ioDirection, string portmodelid = null) { this.PortKey = portKey; this.Type = type; this.State = null; this.PortModelId = portmodelid; DebugEx.Assert(ioDirection != ioPortDirection.Undefined, $"Undefined IO direction for port {portKey}"); this.ioDirection = ioDirection; }
//------------------------------------------------------------------------------------------------------------------------ public void Stop(bool CloseAllChannels = false) { try { lock (this) { //close all channels if (CloseAllChannels) { _Channels.ForEach(c => { try { c.Close("Server stopped"); } catch (Exception ex) { DebugEx.Assert(ex, "Error while closing channel"); } }); _Channels.Clear(); } //update flag if (!_IsRunning) { return; } else { _IsRunning = false; } //close my socket try { if (sock != null) { #if NETFX try { sock.Close(); } catch { } #endif try { sock.Dispose(); } catch { } } } catch (Exception ex) { DebugEx.TraceErrorException(ex); } sock = null; //wait for task finish #if NETFX PortListener?.Join(1000); #elif UNIVERSAL PortListener?.Wait(1000); #endif PortListener = null; } } catch (Exception ex) { DebugEx.Assert(ex, "YPChannel Server Stop() failed"); } }
public static Dictionary <string, object> GetSemantics(string semantics) { //checks if (string.IsNullOrWhiteSpace(semantics)) { return(null); } //deserialize var des = semantics.FromJSON <Dictionary <string, object> >(); var ret = new Dictionary <string, object>(); //restore values foreach (var __entry in des) { try { var key = __entry.Key; var value = __entry.Value; //fix values (deserialized json from object) if (key == nameof(Boolean_Format)) { value = Enum.Parse(typeof(Boolean_Format), value.ToStringInvariant()); } else if (key == nameof(String_Case)) { value = Enum.Parse(typeof(String_Case), value.ToStringInvariant()); } else if (key == nameof(Decimal_Range)) { value = (value as string).FromJSON <Decimal_Range>(); } else if (key == nameof(Integer_Range)) { value = (value as string).FromJSON <Integer_Range>(); } //else if ... else { DebugEx.Assert("Could not deserialize semantic entry"); } //add to final dictionary if (value != null) { ret.ForceAdd(key, value); } } catch { } } //return result return(ret); }