国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

.net6中, 用數(shù)據(jù)屬性事件觸發(fā) 用httpclient向服務(wù)器提交Mes工單

這篇具有很好參考價值的文章主要介紹了.net6中, 用數(shù)據(jù)屬性事件觸發(fā) 用httpclient向服務(wù)器提交Mes工單。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

MES開發(fā)中, 客戶往往會要求 工單開始時記錄工藝數(shù)據(jù), 工單結(jié)束時將這些工藝數(shù)據(jù)回傳到更上一級的WES系統(tǒng)中. 因為MES系統(tǒng)和PLC 是多線程讀取, 所以加鎖, 事件觸發(fā)是常用手段.文章來源地址http://www.zghlxwxcb.cn/news/detail-690020.html

using MyWebApiTest.PLC;
using MyWebApiTest.Service;
using MyWebApiTest.Service.Entry;
using MyWebApiTest.Service.Entry.Imp;
using MyWebApiTest.Service.Factory;
using MyWebApiTest.Service.Factory.Impl;
using MyWebApiTest.Utils;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


//日志
builder.Host.UseSerilog((context, logger) =>
{
    logger.ReadFrom.Configuration(context.Configuration);
    logger.Enrich.FromLogContext();
});

// Add services to the container.
builder.Configuration.AddJsonFile("appsettings.json", false, true);
var cfg = builder.Configuration;
builder.Services.AddSingleton<IConfiguration>(cfg);


//ORM
builder.Services.AddSingleton<ISqlSugarService ,SqlSugarServiceImpl>();
builder.Services.AddSingleton<SqlSugarHelper>();

builder.Services.AddSingleton<IAbsFactoryService, AbsFactoryServiceImpl>();

builder.Services.AddSingleton<IConnFactoryService, ConnFactoryServiceImpl2>();
builder.Services.AddSingleton<IConnFactoryService, ConnFactoryServiceImpl1>();

//PLC數(shù)據(jù)
builder.Services.AddSingleton<MyS7Entry>();
builder.Services.AddSingleton<IS7ConnService, S7ConnServiceImpl>();

//運行初始化任務(wù)  測試client
//builder.Services.AddSingleton<IHostedService, StartupInitializationService>();

//client
builder.Services.AddHttpClient();

//AutoMapper
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

builder.Services.AddControllers();
builder.Services.AddCors(c => c.AddPolicy("any", p => p.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin()));
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//日志
builder.Host.UseSerilog((context, logger) =>
{
    logger.ReadFrom.Configuration(context.Configuration);
    logger.Enrich.FromLogContext();
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("any");

app.UseAuthorization();

app.MapControllers();

app.Run();

using S7.Net;

namespace MyWebApiTest.Service.Entry
{
    public interface IS7ConnService
    {
        void ConnPlc();


        bool MyIsConnected
        {
            get;
        }

        Plc MyS7Master { get; }
    }
}

using MyWebApiTest.PLC;
using MyWebApiTest.Service.Entry;
using S7.Net;

namespace MyWebApiTest.Service.Entry.Imp
{
    public class S7ConnServiceImpl : IS7ConnService
    {
        public S7ConnServiceImpl(IConfiguration configuration,
            HttpClient httpClient,
            ILogger<S7ConnServiceImpl> logger,
            MyS7Entry myS7Entry)
        {
            this.configuration = configuration;
            this.httpClient = httpClient;
            this.logger = logger;
            this.myS7Entry = myS7Entry;
            myIp = configuration.GetSection("PlcIp").Value;
        }

        private readonly IConfiguration configuration;
        private readonly HttpClient httpClient;
        private readonly ILogger<S7ConnServiceImpl> logger;
        private MyS7Entry myS7Entry;
        private string myIp;
        private Plc myS7Master = null;
        private MyS7EntityRecive? myS7test = new MyS7EntityRecive();
        private MyS7Entry myS7Data = new MyS7Entry();
        private bool myIsConnected = false;
        private CancellationTokenSource cts = new();
        private int errorTimes = 0;
        private static readonly object lockObj = new object(); // 創(chuàng)建一個對象作為鎖

        public Plc MyS7Master
        {
            get => myS7Master;
        }

        public MyS7Entry MyS7Data
        {
            get => myS7Data;
            set => myS7Data = value;
        }

        public bool MyIsConnected
        {
            get => myIsConnected;
            set
            {
                if (myIsConnected == false && value == true)
                {
                    logger.LogInformation("PLC連接成功!");
                }
                myIsConnected = value;
            }
        }

        public void ConnPlc()
        {
            Task.Run(async () =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (myS7Master == null || !MyIsConnected)
                    {
                        try
                        {
                            myS7Master = new Plc(CpuType.S71500, myIp, 0, 0);
                            myS7Master.Open();
                            MyIsConnected = myS7Master.IsConnected;
                        }
                        catch (Exception ex)
                        {
                            myS7Master?.Close();
                            myS7Master = null;
                            MyIsConnected = false;
                            logger.LogError(ex.Message);
                            await Task.Delay(2000);
                        }
                    }
                    else if (MyIsConnected)
                    {
                        //注入Client

                        //var url = "http://localhost:5190/api/private/v1/My/MyGet"; // 目標(biāo) Web API 的地址

                        //var response = await httpClient.GetAsync(url);

                        //if (response.IsSuccessStatusCode)
                        //{
                        //    var content = await response.Content.ReadAsStringAsync();
                        //    logger.LogError(content);

                        //}

                        try
                        {
                            MyIsConnected = myS7Master.IsConnected;
                            await Task.Delay(1000);
                            myS7test = await myS7Master.ReadClassAsync<MyS7EntityRecive>(31, 416);
                            lock (lockObj)
                            {
                                myS7Entry.MyShort1 = myS7test.MyShort1;
                                myS7Entry.MyShort2 = myS7test.MyShort2;
                            }
                            logger.LogInformation(myS7Entry.MyShort1.ToString() + "====");
                        }
                        catch (Exception ex)
                        {
                            errorTimes++;
                            await Task.Delay(1000);

                            logger.LogError($"讀取時發(fā)生錯誤:{ex.Message}");
                            logger.LogError($"讀取時發(fā)生錯誤次數(shù):{errorTimes}");
                            myS7Master.Close();
                            MyIsConnected = false;
                            myS7Master = null;
                        }
                    }
                }
            }, cts.Token);
        }
    }
}

/*
 使用了 lock 來保護 myS7Entry.MyShort1 和 myS7Entry.MyShort2 的同時修改,
以確保在同一時間只有一個線程可以修改這兩個屬性。這是一種常見的使用鎖的方式,
目的是避免競態(tài)條件和數(shù)據(jù)不一致性。

死鎖通常發(fā)生在兩個或多個線程之間存在循環(huán)依賴鎖的情況下,
導(dǎo)致它們互相等待對方釋放鎖。在你的代碼中,只有一個 lock,并且在修改屬性時使用,
不會導(dǎo)致循環(huán)依賴鎖,因此不會發(fā)生死鎖。

但要注意,死鎖可能在其他情況下發(fā)生,比如在涉及多個鎖的復(fù)雜情況下,
或者在鎖嵌套的情況下。確保你的代碼中不會出現(xiàn)多個鎖之間的循環(huán)依賴,
以及在鎖內(nèi)部避免阻塞線程,以保證代碼的正常執(zhí)行。
 
 */
using System.ComponentModel;

namespace MyWebApiTest.PLC
{
    public class MyS7Entry : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        private short myShort1;

        public short MyShort1
        {
            get => myShort1;
            set
            {
                if (myShort1 != value)
                {
                    if (myShort1 == 1 && value == 0)
                    {
                        OnPropertyChanged(nameof(MyShort1));
                    }
                    myShort1 = value;
                }
            }
        }

        private short myShort2;

        public short MyShort2
        {
            get => myShort2;
            set
            {
                if (myShort2 != value)
                {
                    if (myShort2 == 1 && value == 0)
                    {
                        OnPropertyChanged(nameof(MyShort2));
                    }
                    myShort2 = value;
                }

            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

namespace MyWebApiTest.PLC
{
    public class MyS7EntityRecive
    {
        public short MyShort1 { get; set; }
        public short MyShort2 { get; set; }
    }
}

using MyWebApiTest.entities;
using MyWebApiTest.PLC;
using MyWebApiTest.Service.Entry;
using System.Text.Json;

namespace MyWebApiTest.Utils
{
    public class StartupInitializationService : IHostedService
    {
        private readonly MyS7Entry myS7Entry;
        private readonly IS7ConnService s7ConnService;
        private readonly ILogger<StartupInitializationService> logger;
        private readonly HttpClient httpClient;

        public StartupInitializationService(MyS7Entry myS7Entry
            , IS7ConnService s7ConnService
            , ILogger<StartupInitializationService> logger
            , HttpClient httpClient
            )
        {
            this.myS7Entry = myS7Entry;
            this.s7ConnService = s7ConnService;
            this.logger = logger;
            this.httpClient = httpClient;
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                s7ConnService.ConnPlc();
            }
            catch (Exception ex)
            {
                logger.LogError($"網(wǎng)絡(luò)錯誤:{ex.Message}");
                return Task.CompletedTask;
            }

            logger.LogWarning("初始化函數(shù)成功");

            myS7Entry.PropertyChanged += async (s, e) =>
            {
                if (e.PropertyName == "MyShort1")
                {
                    string? url = "http://127.0.0.1:8081/endpoint/mes/kx/reportA";
                    Student stu = new()
                    {
                        Id = 1,
                        Name = "MyBool1",
                        Age = 999
                    };
                    var json = JsonSerializer.Serialize(stu);
                    var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(url, content);
                    if (response.IsSuccessStatusCode)
                    {
                        logger.LogInformation("Data sent successfullyS1.");
                    }
                    else
                    {
                        logger.LogInformation("Failed to send dataS1.");
                    }
                }

                else if (e.PropertyName == "MyShort2")
                {
                    string? url = "http://127.0.0.1:8081/endpoint/mes/kx/reportB";
                    Student stu = new()
                    {
                        Id = 2,
                        Name = "MyBool2",
                        Age = 888
                    };

                    var json = JsonSerializer.Serialize(stu);
                    var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                    var response = await httpClient.PostAsync(url, content);
                    if (response.IsSuccessStatusCode)
                    {
                        logger.LogInformation("Data sent successfullyS1.");
                    }
                    else
                    {
                        logger.LogInformation("Failed to send dataS1.");
                    }
                }
            };

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            // 在應(yīng)用程序停止時執(zhí)行清理邏輯(如果有必要)
            return Task.CompletedTask;
        }
    }
}

到了這里,關(guān)于.net6中, 用數(shù)據(jù)屬性事件觸發(fā) 用httpclient向服務(wù)器提交Mes工單的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 銀河麒麟服務(wù)器v10 sp1 部署.Net6.0項目后無法訪問靜態(tài)文件

    銀河麒麟服務(wù)器v10 sp1 部署.Net6.0項目后無法訪問靜態(tài)文件

    上一篇:銀河麒麟服務(wù)器v10 sp1 部署.Net6.0 http https_csdn_aspnet的博客-CSDN博客 由于本人項目直接從.NetCore3.1升級到.Net6.0的,請參考文章:NetCore3.1項目升級到Net6.0_vs2022 沒有startup_csdn_aspnet的博客-CSDN博客 雖然部署項目后,swagger與接口可以正常訪問,但是靜態(tài)文件,如html、css、j

    2024年02月12日
    瀏覽(27)
  • 銀河麒麟服務(wù)器v10 sp1 .Net6.0 上傳文件錯誤 access to the path is denied

    銀河麒麟服務(wù)器v10 sp1 .Net6.0 上傳文件錯誤 access to the path is denied

    上一篇:銀河麒麟服務(wù)器v10 sp1 部署.Net6.0 http https_csdn_aspnet的博客-CSDN博客 .NET 6之前,在Linux服務(wù)器上安裝 libgdiplus 即可解決,libgdiplus是System.Drawing.Common原生端跨平臺實現(xiàn)的主要提供者,是開源mono項目。地址:GitHub - mono/libgdiplus: C-based implementation of the GDI+ API 因此,解決方法

    2024年02月12日
    瀏覽(24)
  • .NET6 項目使用RabbitMQ實現(xiàn)基于事件總線EventBus通信

    .NET6 項目使用RabbitMQ實現(xiàn)基于事件總線EventBus通信

    一、概念及介紹 ????????通常通過使用事件總線實現(xiàn)來執(zhí)行此發(fā)布/訂閱系統(tǒng)。 事件總線可以設(shè)計為包含 API 的接口,該 API 是訂閱和取消訂閱事件和發(fā)布事件所需的。 它還可以包含一個或多個基于跨進程或消息通信的實現(xiàn),例如支持異步通信和發(fā)布/訂閱模型的消息隊列或

    2024年04月28日
    瀏覽(26)
  • 在input加了disabled屬性后,如何觸發(fā)點擊事件?

    input標(biāo)簽 disabled屬性說明 被禁用的input標(biāo)簽 既不可用,也不可進行點擊 解決方案 使用readonly屬性 來替換disabled屬性 外套一層父標(biāo)簽,給父標(biāo)簽添加點擊事件,并設(shè)置input的樣式為\\\"pointer-events:none\\\" 去掉鼠標(biāo)事件,然后通過冒泡觸發(fā)到父標(biāo)簽上的點擊事件。 冒泡事件 點擊子標(biāo)簽

    2024年02月10日
    瀏覽(20)
  • WPF .Net6框架下, 使用 Microsoft.Xaml.Behaviors.Wpf 的Interaction.Triggers特性,實現(xiàn)ComboBox 在展開時,觸發(fā)刷新列表內(nèi)容的動作

    ComboBox 在WPF中是常見的控件。 一般情況下,在綁定好數(shù)據(jù)源后,其內(nèi)容是固定的。 當(dāng)然,你也可以實時刷新,但這將帶來較高的資源消耗。 因此有個折中的辦法: 只在它在展開時,自動更新列表內(nèi)容。 當(dāng)前文章基于 .Net6框架,其他框架不適用。 這個是用于平替winform某個組

    2024年02月09日
    瀏覽(23)
  • 【2023-09-01】vue中自定義按鈕設(shè)置disabled屬性后,異常觸發(fā)click事件

    項目中自定義按鈕,使用a標(biāo)簽實現(xiàn)。設(shè)置disabled屬性后,點擊可以觸發(fā)click事件。 由于各種原因,項目中并未使用成熟的第三方組件庫,例如element-ui,ant-design。大多數(shù)組件是自己封裝的,部分借鑒了原項目中jQuery、bootstrap實現(xiàn)。 列表中需要根據(jù)數(shù)據(jù)中某個變量的值,控制該

    2024年02月10日
    瀏覽(17)
  • .NET6創(chuàng)建Windows服務(wù)

    .NET6創(chuàng)建Windows服務(wù)

    之前的文章已經(jīng)寫過了創(chuàng)建Windows服務(wù)。 C#創(chuàng)建Windows服務(wù)_c# 創(chuàng)建windows服務(wù)_故里2130的博客-CSDN博客 ?不過之前使用的是.NET Framework創(chuàng)建的Windows服務(wù)?,F(xiàn)在已經(jīng)2023年了,其中vs2022有新的方法去創(chuàng)建Windows服務(wù),本次使用.NET6創(chuàng)建Windows服務(wù)。 1.選擇如圖所示,其中vs2022這樣的,vs

    2024年02月10日
    瀏覽(22)
  • ASP.NET WebForm中在TextBox輸入框回車時會觸發(fā)其他事件,如何處理?

    ASP.NET WebForm中在TextBox輸入框回車時會觸發(fā)其他事件,如何處理?

    在ASP.NET WebForm中,在頁面中按鍵盤上的回車鍵,會自動觸發(fā)某些事件,但是這并不是我們想要的效果,我們可以設(shè)置將其取消,那如何處理呢? 前臺代碼: ? 后臺在Page_Load中設(shè)置代碼: ?代碼示例: ? ? 在ASP.NET WebForm中,在頁面中按鍵盤上的回車鍵,需要自定義設(shè)置觸發(fā)某

    2024年02月15日
    瀏覽(21)
  • HttpClient:HTTP GET請求的服務(wù)器響應(yīng)輸出

    HttpClient:HTTP GET請求的服務(wù)器響應(yīng)輸出

    前言 在現(xiàn)代軟件開發(fā)中,與網(wǎng)絡(luò)通信相關(guān)的技術(shù)變得愈發(fā)重要。Java作為一種強大而靈活的編程語言,提供了豐富的工具和庫,用于處理各種網(wǎng)絡(luò)通信場景。本文將聚焦在Java中使用HttpClient庫發(fā)送HTTP GET請求,并將服務(wù)器的響應(yīng)數(shù)據(jù)進行輸出,同時加入代理服務(wù)器的配置,以應(yīng)

    2024年02月20日
    瀏覽(27)
  • 使用Autofac進行服務(wù)注冊,適用版本.Net6(程序集、泛型)

    具體的也可以去參考官網(wǎng):https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html 首先在Program.cs所屬的層中引用nuget包: nuget網(wǎng)址:https://www.nuget.org/packages? 可以使用NuGet包管理器進行搜索安裝 在Program.cs中加入如下代碼: 代碼中SmartHealthcare.Application可以替換為具體自己項目中Ap

    2024年02月16日
    瀏覽(24)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包