예제 #1
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            try
            {
                discoveryBroadcaster.Start();
            }
            catch (Exception ex)
            {
                Log.Error("Failed to start discovery broadcaster: " + ex);
                return(false);
            }
            try
            {
                localWorkerService = new LocalWorkerServiceImpl(this, Log);
                grpcServer         = new Server
                {
                    Services = { LocalWorkerService.BindService(localWorkerService) },
                    Ports    = { new ServerPort("0.0.0.0", Entity.APIPort, ServerCredentials.Insecure) }
                };
                grpcServer.Start();
            }
            catch (Exception ex)
            {
                Log.Error("Failed to start GRPC server: " + ex);
                return(false);
            }

            try
            {
                client = new MqttClient(Entity.HostName);
                client.MqttMsgPublishReceived += onMqttMsgPublishReceived;
                client.MqttMsgPublished       += onMqttMsgPublished;
                client.ConnectionClosed       += onMqttConnectionClosed;

                // Power on
                client.Connect(clientID);

                // Subscribe to topics
                var topics = getSubscribeTopics();
                var qos    = topics.Select(x => MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE).ToArray();
                client.Subscribe(topics, qos);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to connect to MQTT server: " + ex);
                return(false);
            }
            return(true);
        }
예제 #2
0
 public override void Dispose()
 {
     if (client != null)
     {
         client.MqttMsgPublishReceived -= onMqttMsgPublishReceived;
         client.MqttMsgPublished       -= onMqttMsgPublished;
         client.ConnectionClosed       -= onMqttConnectionClosed;
         client.Disconnect();
         client = null;
     }
     discoveryBroadcaster.Stop();
     if (localWorkerService != null)
     {
         localWorkerService.Stop = true;
         localWorkerService      = null;
     }
     if (grpcServer != null)
     {
         grpcServer.ShutdownAsync().Wait();
         grpcServer = null;
     }
     base.Dispose();
 }