简体   繁体   中英

.CORE 5 Web Api and Client MQTT

is it possible to create a.core webapi project and a mqtt client? For example, create a separate thread in the startup.cs where you can instantiate a mqtt client

I try to add a Singleton service to instantiate the mqtt client in startup.cs and it works fine, the program recive the posted message on topic. The first question, is it correct to create this service in this location?

The problem is when I try to add the migration or update of the database with the package console tool. The command does not complete the sequencing and the console is locked.

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
            services.AddSingleton<MyMqtt>(new MyMqtt());
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "CoWorkOfficeWebApi", Version = "v1" });
            });
        }

Class

    public class MyMqtt
    {
        MqttClient client;

        public MyMqtt()
        {
            // create client instance 
            client = new MqttClient("127.0.0.1");
            // register to message received 
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
            string clientId = Guid.NewGuid().ToString();
            client.Connect(clientId);
            // subscribe to the topic "/home/temperature" with QoS 2 
            client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
        }


        static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Message);
            Console.WriteLine($"Topic: {e.Topic}, Message: {msg}");
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM