using Infrastructure; using Infrastructure.Attribute; using Microsoft.Extensions.DependencyInjection; using Quartz; using Quartz.Impl.Triggers; using Quartz.Impl; using SqlSugar.IOC; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DOAN.Model.System; using Tea; using AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models; using JinianNet.JNTemplate.Nodes; using Newtonsoft.Json.Linq; using AlibabaCloud.SDK.Dingtalkyida_1_0.Models; using Newtonsoft.Json; using Microsoft.AspNetCore.Http; using DOAN.Model.System; using static System.Runtime.InteropServices.JavaScript.JSType; using DOAN.Tasks; using DOAN.Model.huate_group.CloudMonitor; using DOAN.Model.huate_group.recipe; using ZR.Model.Cloud.Dto; using DOAN.Common; using Infrastructure.Model; using Microsoft.Extensions.Options; using DOAN.Model; using System.Net; using System.Reflection; using SqlSugar; namespace DOAN.Tasks.TaskScheduler { [AppService(ServiceType = typeof(YIDA_dataUpload_Task), ServiceLifetime = LifeTime.Scoped)] public class YIDA_dataUpload_Task : JobBase, IJob { private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); private readonly MqttPublisher publisher = null; private readonly MqttPublicConfig mqttPublicConfig; public YIDA_dataUpload_Task(IOptions options) { OptionsSetting OptionsSetting = options.Value; mqttPublicConfig = OptionsSetting.mqttPublicConfig; //init MQTT publisher = new MqttPublisher(mqttPublicConfig.BrokerIp, mqttPublicConfig.ClientId, mqttPublicConfig.Port); } public async Task Execute(IJobExecutionContext context) { try { await publisher.ConnectAsync(); Console.WriteLine("---------------------------------上传开始"); AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger; var infoTask = await DbScoped.SugarScope.CopyNew() .AsTenant().QueryableWithAttr() .FirstAsync(f => f.ID == trigger.JobName) ?? throw new CustomException($"任务{trigger?.JobName}宜搭数据上传任务执行失败,任务不存在"); if (infoTask != null) { // 执行异步上传任务 Task t1 = dataUpLoad(); //Task t2 = dataUpLoad(); //Task t3 = dataUpLoad(); //Task t4 = dataUpLoad(); //Task t5 = dataUpLoad(); //Task t6 = dataUpLoad(); //Task t7 = dataUpLoad(); //Task t8 = dataUpLoad(); //Task t9 = dataUpLoad(); //Task t10 = dataUpLoad(); //Task t11 = dataUpLoad(); await Task.WhenAll(t1); if (t1.Result > 0) { //获取上传设备id string tablecode = typeof(ZiyuanDevice01).GetCustomAttribute().TableName; if (!string.IsNullOrEmpty(tablecode)) { ReflexAccount reflexAccount = DbScoped.SugarScope.CopyNew().AsTenant() .QueryableWithAttr().Where(it => it.TableCode == tablecode).First(); if (reflexAccount != null) { string jsonString = "{\"num\": " + t1.Result + ", \"datetime\": \"" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\"}"; await publisher.PublishAsync(mqttPublicConfig.Topic + $"/{reflexAccount.FkDeviceId}", jsonString) ; } } } Console.WriteLine("---------------------------------上传结束" + t1.Result); } } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } finally { await publisher.DisconnectAsync(); } } /// /// 异步任务 数据上传 /// /// public Task dataUpLoad() where T : ZiyuanDevice01, new() { return Task.Run(() => { int flag = 0; //1.读取设备数据 List device01s = DbScoped.SugarScope.AsTenant().QueryableWithAttr().Where(it => it.IsUpload == 0).Take(60).ToList(); List yidas = new List(); //2.上传到宜搭 //2.1 获取token GetAccessTokenResponse tokenResponse = GetDINGIDNG_token(); //2.2 上传数据 if (device01s != null && device01s.Count > 0) { var query = DbScoped.SugarScope.AsTenant().QueryableWithAttr().ToList(); List itemsToRemove = new List(); foreach (T item in device01s) { //1.1 判断设备配置情况 Recipee options = query .Where(it => it.Id == item.FkRecipeId).FirstOrDefault(); if (options != null) { //不可上传 if (!(bool)options.IsUpload) { Console.WriteLine("设备名为" + typeof(T).Name + "不可上传,禁止上传"); // device01s.Remove(item); itemsToRemove.Add(item); continue; } //开启过滤 if ((bool)options.Isfilter) { if (item.Value > item.UpValue || item.Value < item.LowValue) { Console.WriteLine("设备名为" + typeof(T).Name + "不合格数据,禁止上传"); //device01s.Remove(item); itemsToRemove.Add(item); continue; } } item.IsUpload = 1; } } foreach (T item in itemsToRemove) { device01s.Remove(item); } if (device01s.Count > 0) { foreach (T item in device01s) { ZiyuanDevice_YIDA ziyuan = new ZiyuanDevice_YIDA(); ziyuan.textField_l3plle21 = item.SupplierCode; ziyuan.textField_l3plle22 = item.SupplierName; ziyuan.textField_l3plle23 = item.Vehiclemodel; ziyuan.textField_l3plle24 = item.Partnumber; ziyuan.textField_l3plle25 = item.Partname; ziyuan.textField_l3plle26 = item.Configuration; ziyuan.textField_l3plle27 = item.Workstation; ziyuan.textField_l3plle29 = item.Paramter; ziyuan.numberField_l3plle2x = item.Value; ziyuan.textField_l3plle2o = item.Value; ziyuan.numberField_l3plle2y = item.LowValue; ziyuan.textField_l3plle2q = item.LowValue; ziyuan.textField_l3plle2s = item.UpValue; ziyuan.numberField_l3plle2z = item.UpValue; // ziyuan.dateField_l3plle30 = ((DateTime)item.MeasureTime).ToString("yyyyMMddHHmmss"); ziyuan.dateField_l3plle30 = (long)(((DateTime)item.MeasureTime).ToUniversalTime().Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds; ziyuan.textField_l3plle2u = ((DateTime)item.MeasureTime).ToString("yyyy-MM-dd HH:mm:ss"); ziyuan.textField_l3plle2m = "张帆"; yidas.Add(JsonConvert.SerializeObject(ziyuan)); } } } BatchSaveFormDataResponse response = UploadYIDABatch(tokenResponse.Body.AccessToken.ToString(), yidas); if (response != null && response.StatusCode == 200) { flag = DbScoped.SugarScope.AsTenant().UpdateableWithAttr(device01s).ExecuteCommand(); } return flag; }); } /// /// 获取钉钉的token /// /// public GetAccessTokenResponse GetDINGIDNG_token() { GetAccessTokenResponse token = null; AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateClient(); AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest getAccessTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest { AppKey = "dingnlq6pfrucmeyvdoz", AppSecret = "148xa-m_kz9nhyf6q8drRTQBW50iwgr5GjcqYwFZwZq7ATPyAdS3mGyP6uHuB6Kn", }; try { token = client.GetAccessToken(getAccessTokenRequest); } catch (TeaException err) { if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } catch (Exception _err) { TeaException err = new TeaException(new Dictionary { { "message", _err.Message } }); if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } return token; } /// /// insert宜搭表单(单条) /// /// token /// json形式的数据 public SaveFormDataResponse UpdateTable(string token, string data_json) { SaveFormDataResponse response = null; AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient_2(); AlibabaCloud.SDK.Dingtalkyida_1_0.Models.SaveFormDataHeaders saveFormDataHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.SaveFormDataHeaders(); saveFormDataHeaders.XAcsDingtalkAccessToken = token; AlibabaCloud.SDK.Dingtalkyida_1_0.Models.SaveFormDataRequest saveFormDataRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.SaveFormDataRequest { AppType = "APP_KFYJRG27IHBAO961DH2V", SystemToken = "DH9669D1U17FUH2OC0W9KA7GR7TN2YKSTGCOLSP2", UserId = "28674126181143515", Language = "zh_CN", FormUuid = "FORM-20B66BD166EFFI8DFORBX4254N5B23NSTGCOLA6", FormDataJson = data_json, }; try { response = client.SaveFormDataWithOptions(saveFormDataRequest, saveFormDataHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions()); } catch (TeaException err) { Console.WriteLine(err.ToString()); if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } catch (Exception _err) { TeaException err = new TeaException(new Dictionary { { "message", _err.Message } }); if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } return response; } /// /// 批量上传宜搭 /// /// /// /// public BatchSaveFormDataResponse UploadYIDABatch(string token, List data_json) { BatchSaveFormDataResponse response = null; AlibabaCloud.SDK.Dingtalkyida_1_0.Client client = CreateClient3(); AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchSaveFormDataHeaders batchSaveFormDataHeaders = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchSaveFormDataHeaders(); batchSaveFormDataHeaders.XAcsDingtalkAccessToken = token; AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchSaveFormDataRequest batchSaveFormDataRequest = new AlibabaCloud.SDK.Dingtalkyida_1_0.Models.BatchSaveFormDataRequest { NoExecuteExpression = true, FormUuid = "FORM-20B66BD166EFFI8DFORBX4254N5B23NSTGCOLA6", AppType = "APP_KFYJRG27IHBAO961DH2V", AsynchronousExecution = true, SystemToken = "DH9669D1U17FUH2OC0W9KA7GR7TN2YKSTGCOLSP2", KeepRunningAfterException = true, UserId = "28674126181143515", FormDataJsonList = data_json }; try { response = client.BatchSaveFormDataWithOptions(batchSaveFormDataRequest, batchSaveFormDataHeaders, new AlibabaCloud.TeaUtil.Models.RuntimeOptions()); } catch (TeaException err) { if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } catch (Exception _err) { TeaException err = new TeaException(new Dictionary { { "message", _err.Message } }); if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 // err 中含有 code 和 message 属性,可帮助开发定位问题 logger.Error($"token获取异常" + err.Code + "---" + err.Message); } } return response; } public static AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client CreateClient() { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config(); config.Protocol = "https"; config.RegionId = "central"; return new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client(config); } public static AlibabaCloud.SDK.Dingtalkyida_1_0.Client CreateClient_2() { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config(); config.Protocol = "https"; config.RegionId = "central"; return new AlibabaCloud.SDK.Dingtalkyida_1_0.Client(config); } public static AlibabaCloud.SDK.Dingtalkyida_1_0.Client CreateClient3() { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config(); config.Protocol = "https"; config.RegionId = "central"; return new AlibabaCloud.SDK.Dingtalkyida_1_0.Client(config); } } }