using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Windows.Forms; namespace LadfDataApp { public partial class FrmMain : Form { private string sid = string.Empty;//认证码 private System.Timers.Timer timer = new System.Timers.Timer();//指定间隔循环 private int timeInterval = 0; private DateTime startTime; public FrmMain() { InitializeComponent(); this.Load += OnFrmMainLoad; this.linkBtn.Click += OnLinkBtnClick; this.startBtn.Click += OnStartBtnClick; this.radioFix.CheckedChanged += OnCheckedChanged; this.radioNext.CheckedChanged += OnCheckedChanged; } private void OnFrmMainLoad(object sender, EventArgs e) { startBtn.Enabled = false; DateTime nowDateTime = DateTime.Now; fixStartDate.Value = new DateTime(nowDateTime.Year, nowDateTime.Month, nowDateTime.Day, 0, 0, 0, 0); fixEndDate.Value = new DateTime(nowDateTime.Year, nowDateTime.Month, nowDateTime.Day, 23, 59, 59, 999); nextStartDate.Value = new DateTime(nowDateTime.Year, nowDateTime.Month, nowDateTime.Day, 0, 0, 0, 0); this.loginNameBox.Text = ConfigurationManager.AppSettings["loginName"]; this.serverBox.Text = ConfigurationManager.AppSettings["server"]; this.dataBaseBox.Text = ConfigurationManager.AppSettings["database"]; this.timeIntervalBox.Text = ConfigurationManager.AppSettings["intervalTime"]; if (this.loginNameBox.Text.Equals("lserptest")) { this.loginPasswordBox.Text = "lserpAdmin"; } } private void OnCheckedChanged(object sender, EventArgs e) { if (sender == radioFix && radioFix.Checked) { radioNext.Checked = false; panelNext.Enabled = false; panelFix.Enabled = true; } if (sender == radioNext && radioNext.Checked) { radioFix.Checked = false; panelFix.Enabled = false; panelNext.Enabled = true; } } /// /// 加载项目下拉框数据源 /// private void InitComboBox() { try { this.projectComboBox.Items.Clear(); string url = "https://api.123321yun.com/api/user/queryProjectList"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("isAll", "true"); pmsDic.Add("pageNum", "1"); pmsDic.Add("pageSize", "10"); Dictionary headerDic = new Dictionary(); headerDic.Add("__sid", sid); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, headerDic, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { JArray projectArray = (JArray)resultJObject["data"]; foreach (JObject projectJObject in projectArray) { try { string projectName = projectJObject["name"] + ""; this.projectComboBox.Items.Add(projectName); } catch (Exception) { } } } } } catch (Exception) { } } private void OnLinkBtnClick(object sender, EventArgs e) { ClearMsg(); bool isConnection = CreateConnection(); if (!isConnection) { startBtn.Enabled = false; MessageBox.Show("网络连接失败", "提示"); return; } if (!Login()) { startBtn.Enabled = false; MessageBox.Show("物联网平台登录失败", "提示"); return; } string alterSql = $@"if not exists (select 1 from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'p_systemtab' and COLUMN_NAME = 'ProjectEndTime') BEGIN ALTER TABLE p_systemtab ADD ProjectEndTime datetime END"; SqlHelper.ExecuteNonQuery(alterSql); string selectSql = $"select ProjectEndTime from p_systemtab"; string endDateTime = SqlHelper.ExecuteScalar(selectSql) + ""; if (!string.IsNullOrEmpty(endDateTime)) { this.nextStartDate.Value = Convert.ToDateTime(endDateTime); } else { SqlHelper.ExecuteNonQuery($"update p_systemtab set ProjectEndTime = '{this.nextStartDate.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'"); } InitComboBox(); UpdateMsg("连接成功\r\n"); startBtn.Enabled = true; } private void OnStartBtnClick(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.loginNameBox.Text) || string.IsNullOrEmpty(this.loginPasswordBox.Text)) { MessageBox.Show("用户名或密码不能为空", "提示"); return; } if (string.IsNullOrEmpty(this.serverBox.Text) || string.IsNullOrEmpty(this.dataBaseBox.Text)) { MessageBox.Show("服务器或数据库不能为空", "提示"); return; } if (string.IsNullOrEmpty(this.projectComboBox.SelectedItem + "")) { MessageBox.Show("未选择项目", "提示"); return; } bool isConnection = CreateConnection(); if (isConnection) { if (radioFix.Checked) { GetDataOnlyOne(); } else if (radioNext.Checked) { if (!int.TryParse(this.timeIntervalBox.Text, out timeInterval) && timeInterval <= 0) { MessageBox.Show("间隔时间必须大于0", "提示"); return; } timer.Elapsed += OnTimerElapsed; timer.Interval = 100; timer.Start(); } } else { MessageBox.Show("网络连接失败", "提示"); } } /// /// 获取数据事件 /// /// /// private void GetDataOnlyOne() { try { this.Invoke(new Action(() => { this.groupBox3.Enabled = false; this.panelFix.Enabled = false; this.linkBtn.Enabled = false; this.startBtn.Enabled = false; this.loginNameBox.Enabled = false; this.loginPasswordBox.Enabled = false; this.serverBox.Enabled = false; this.dataBaseBox.Enabled = false; this.timeIntervalBox.Enabled = false; this.projectComboBox.Enabled = false; })); ClearMsg(); QueryProjectList(); UpdateMsg("同步完成,所有数据已成功写入\r\n"); } catch (Exception) { } finally { this.Invoke(new Action(() => { this.groupBox3.Enabled = true; this.panelFix.Enabled = true; this.loginNameBox.Enabled = true; this.loginPasswordBox.Enabled = true; this.linkBtn.Enabled = true; this.startBtn.Enabled = true; this.serverBox.Enabled = true; this.dataBaseBox.Enabled = true; this.timeIntervalBox.Enabled = true; this.projectComboBox.Enabled = true; })); } } /// /// 获取数据事件 /// /// /// private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e) { timer.Enabled = false; try { this.Invoke(new Action(() => { this.groupBox2.Enabled = false; this.panelNext.Enabled = false; this.linkBtn.Enabled = false; this.startBtn.Enabled = false; this.loginNameBox.Enabled = false; this.loginPasswordBox.Enabled = false; this.serverBox.Enabled = false; this.dataBaseBox.Enabled = false; this.timeIntervalBox.Enabled = false; this.projectComboBox.Enabled = false; })); if (timer.Interval == 100) { startTime = this.nextStartDate.Value; SqlHelper.ExecuteNonQuery($"update p_systemtab set ProjectEndTime = '{this.nextStartDate.Value.ToString("yyyy-MM-dd HH:mm:ss.fff")}'"); } else { string selectSql = $"select ProjectEndTime from p_systemtab"; string endDateTime = SqlHelper.ExecuteScalar(selectSql) + ""; startTime = this.nextStartDate.Value; if (!string.IsNullOrEmpty(endDateTime)) { startTime = Convert.ToDateTime(endDateTime); } } if (timer.Interval == 100) { timer.Interval = timeInterval * 60 * 1000; } ClearMsg(); string nextTime = startTime.AddMinutes(timeInterval).ToString("yyyy-MM-dd HH:mm:ss.fff"); if (startTime.AddMinutes(timeInterval) <= DateTime.Now) { QueryProjectList(); UpdateMsg("同步完成,所有数据已成功写入\r\n"); SqlHelper.ExecuteNonQuery($"update p_systemtab set ProjectEndTime = '{startTime.AddMinutes(timeInterval).ToString("yyyy-MM-dd HH:mm:ss.fff")}'"); UpdateMsg($"下次同步时间:{DateTime.Now.AddMinutes(timeInterval).ToString("yyyy-MM-dd HH:mm:ss.fff")}\r\n"); } else { UpdateMsg($"结束时间{nextTime}大于当前时间{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}\r\n"); UpdateMsg($"下次同步时间:{DateTime.Now.AddMinutes(timeInterval).ToString("yyyy-MM-dd HH:mm:ss.fff")}\r\n"); } } catch (Exception) { } finally { } timer.Enabled = true; } /// /// 登录 /// /// private bool Login() { bool isLogin = false; try { string url = "https://api.123321yun.com/api/user/login"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("username", this.loginNameBox.Text); pmsDic.Add("password", this.loginPasswordBox.Text); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, null, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { sid = resultJObject["data"] + ""; isLogin = true; } } } catch (Exception) { } return isLogin; } /// /// 查询项目列表 /// private void QueryProjectList() { try { string url = "https://api.123321yun.com/api/user/queryProjectList"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("isAll", "true"); pmsDic.Add("pageNum", "1"); pmsDic.Add("pageSize", "10"); Dictionary headerDic = new Dictionary(); headerDic.Add("__sid", sid); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, headerDic, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { string selectProjectName = ""; this.Invoke(new Action(() => { selectProjectName = projectComboBox.SelectedItem + ""; })); JArray projectArray = (JArray)resultJObject["data"]; foreach (JObject projectJObject in projectArray) { try { if (projectJObject.ContainsKey("name") && (projectJObject["name"] + "").Equals(selectProjectName)) { try { UpdateMsg($"正在读取项目:{projectJObject["name"]}\r\n"); ProjectModel projectModel = new ProjectModel(); projectModel.projectId = projectJObject["id"] + ""; projectModel.name = projectJObject["name"] + ""; projectModel.delFlag = projectJObject["delFlag"] + ""; projectModel.province = projectJObject["province"] + ""; projectModel.city = projectJObject["city"] + ""; projectModel.county = projectJObject["county"] + ""; projectModel.address = projectJObject["address"] + ""; projectModel.propertyOwner = projectJObject["propertyOwner"] + ""; projectModel.constructionTime = projectJObject["constructionTime"] + ""; projectModel.acreage = projectJObject["acreage"] + ""; projectModel.typeId = projectJObject["typeId"] + ""; projectModel.state = projectJObject["state"] + ""; projectModel.enableTime = projectJObject["enableTime"] + ""; projectModel.energyConsumption = projectJObject["energyConsumption"] + ""; projectModel.imgUrl = projectJObject["imgUrl"] + ""; projectModel.remarks = projectJObject["remarks"] + ""; projectModel.contractor = projectJObject["contractor"] + ""; projectModel.propertyMgmt = projectJObject["propertyMgmt"] + ""; projectModel.projectTypeId = projectJObject["projectType"]["id"] + ""; projectModel.projectTypeName = projectJObject["projectType"]["name"] + ""; StringBuilder projectSqlStrBuilder = new StringBuilder(); StringBuilder projectInsertKeys = new StringBuilder(); StringBuilder projectInsertValues = new StringBuilder(); PropertyInfo[] devicePmsPropertyInfos = projectModel.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo projectPropertyInfo in devicePmsPropertyInfos) { projectInsertKeys.Append($"{projectPropertyInfo.Name},"); projectInsertValues.Append($"'{(projectPropertyInfo.GetValue(projectModel, null) + "").Replace("'", "''")}',"); } projectSqlStrBuilder.Append($"delete from LadfProjectTab where projectid = '{projectModel.projectId}';\r\n" + $"insert into LadfProjectTab ({projectInsertKeys.ToString().TrimEnd(',')}) values ({projectInsertValues.ToString().TrimEnd(',')});\r\n"); if (!string.IsNullOrEmpty(projectSqlStrBuilder.ToString())) { SqlHelper.ExecuteNonQuery(projectSqlStrBuilder.ToString()); } QueryDeviceByProject(projectModel); UpdateMsg($"项目:{projectJObject["name"]}数据写入完成\r\n"); } catch (Exception ex) { UpdateMsg($"项目:{projectJObject["name"]}数据写入失败,原因:{ex.Message}\r\n"); } } } catch (Exception) { } } } else if (code.Equals("4012")) { UpdateMsg($"登录失败\r\n"); Login(); QueryProjectList(); } } } catch (Exception) { } } /// /// 查询项目的设备列表 /// private void QueryDeviceByProject(ProjectModel projectModel) { UpdateMsg($"正在读取项目:{projectModel.name}的设备\r\n"); try { string url = "https://api.123321yun.com/api/device/queryDeviceByProject"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("projId", projectModel.projectId); Dictionary headerDic = new Dictionary(); headerDic.Add("__sid", sid); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, headerDic, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { JArray deviceArray = (JArray)resultJObject["data"]; foreach (JObject deviceJObject in deviceArray) { try { StringBuilder projectSqlStrBuilder = new StringBuilder(); UpdateMsg($"正在读取设备:{deviceJObject["name"]}\r\n"); DeviceModel deviceModel = new DeviceModel(); deviceModel.deviceId = deviceJObject["id"] + ""; deviceModel.brand = deviceJObject["brand"] + ""; deviceModel.model = deviceJObject["model"] + ""; deviceModel.typeId = deviceJObject["typeId"] + ""; deviceModel.projectId = deviceJObject["projectId"] + ""; deviceModel.power = deviceJObject["power"] + ""; deviceModel.regionId = deviceJObject["regionId"] + ""; deviceModel.produceTime = deviceJObject["produceTime"] + ""; deviceModel.deviceTypeId = deviceJObject["deviceType"]["id"] + ""; deviceModel.deviceTypeName = deviceJObject["deviceType"]["name"] + ""; deviceModel.name = deviceJObject["name"] + ""; StringBuilder deviceInsertKeys = new StringBuilder(); StringBuilder deviceInsertValues = new StringBuilder(); PropertyInfo[] devicePropertyInfos = deviceModel.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo devicePropertyInfo in devicePropertyInfos) { deviceInsertKeys.Append($"{devicePropertyInfo.Name},"); deviceInsertValues.Append($"'{(devicePropertyInfo.GetValue(deviceModel, null) + "").Replace("'", "''")}',"); } projectSqlStrBuilder.Append($"delete from LadfDeviceTab where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}';\r\n"); projectSqlStrBuilder.Append($"insert into LadfDeviceTab ({deviceInsertKeys.ToString().TrimEnd(',')}) values ({deviceInsertValues.ToString().TrimEnd(',')});\r\n"); if (!string.IsNullOrEmpty(projectSqlStrBuilder.ToString())) { SqlHelper.ExecuteNonQuery(projectSqlStrBuilder.ToString()); } QueryDeviceParamStatus(deviceModel); if (checkHistory.Checked) { QueryDeviceParamStatusHistory(deviceModel); } } catch (Exception ex) { UpdateMsg($"读取设备{deviceJObject["name"]}失败,原因:{ex.Message}\r\n"); } } } else if (code.Equals("4012")) { UpdateMsg($"登录失败\r\n"); Login(); QueryDeviceByProject(projectModel); } } } catch (Exception ex) { if (ex.Message.Contains("未将对象引用设置到")) { UpdateMsg($"读取项目:{projectModel.name}的设备失败,原因:未查询到数据\r\n"); } else { UpdateMsg($"读取项目:{projectModel.name}的设备失败,原因:{ex.Message}\r\n"); } } } /// /// 查询单个设备的属性 /// private void QueryDeviceParamStatus(DeviceModel deviceModel) { StringBuilder projectSqlStrBuilder = new StringBuilder(); UpdateMsg($"正在读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性数据\r\n"); try { string url = "https://api.123321yun.com/api/device/queryDeviceParamStatus"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("id", deviceModel.deviceId); Dictionary headerDic = new Dictionary(); headerDic.Add("__sid", sid); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, headerDic, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { if (resultJObject.ContainsKey("data")) { JObject deviceParamJObject = (JObject)resultJObject["data"]; DeviceParamModel deviceParamModel = new DeviceParamModel(); deviceParamModel.deviceTypeId = deviceParamJObject["deviceType"]["id"] + ""; deviceParamModel.deviceTypeName = deviceParamJObject["deviceType"]["name"] + ""; deviceParamModel.deviceId = deviceParamJObject["deviceId"] + ""; deviceParamModel.deviceName = deviceParamJObject["deviceName"] + ""; deviceParamModel.workload = deviceParamJObject["workload"] + ""; deviceParamModel.elec = deviceParamJObject["elec"] + ""; deviceParamModel.errorParamNum = deviceParamJObject["errorParamNum"] + ""; deviceParamModel.warnParamNum = deviceParamJObject["warnParamNum"] + ""; deviceParamModel.errorTimeSum = deviceParamJObject["errorTimeSum"] + ""; deviceParamModel.runTimeSum = deviceParamJObject["runTimeSum"] + ""; deviceParamModel.warnEventSum = deviceParamJObject["warnEventSum"] + ""; deviceParamModel.errorEventSum = deviceParamJObject["errorEventSum"] + ""; deviceParamModel.projectId = deviceParamJObject["projectId"] + ""; deviceParamModel.status = deviceParamJObject["status"] + ""; deviceParamModel.timestamp = deviceParamJObject["timestamp"] + ""; StringBuilder deviceParamInsertKeys = new StringBuilder(); StringBuilder deviceParamInsertValues = new StringBuilder(); PropertyInfo[] deviceParamPropertyInfos = deviceParamModel.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo deviceParamPropertyInfo in deviceParamPropertyInfos) { deviceParamInsertKeys.Append($"{deviceParamPropertyInfo.Name},"); deviceParamInsertValues.Append($"'{(deviceParamPropertyInfo.GetValue(deviceParamModel, null) + "").Replace("'", "''")}',"); } projectSqlStrBuilder.Append($"delete from LadfDeviceParamTab where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}';\r\n"); projectSqlStrBuilder.Append($"insert into LadfDeviceParamTab ({deviceParamInsertKeys.ToString().TrimEnd(',')}) values ({deviceParamInsertValues.ToString().TrimEnd(',')});\r\n"); projectSqlStrBuilder.Append($"delete from LadfDeviceParamStatusTab where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}';\r\n"); JArray devicePmsArray = (JArray)deviceParamJObject["jsonParams"]; foreach (JObject devicePmsJObject in devicePmsArray) { try { DeviceParamStatusModel devicePmsModel = new DeviceParamStatusModel(); devicePmsModel.projectId = deviceModel.projectId; devicePmsModel.deviceId = deviceModel.deviceId; devicePmsModel.qs = devicePmsJObject["qs"] + ""; devicePmsModel.realValue = devicePmsJObject["realValue"] + ""; devicePmsModel.flag = devicePmsJObject["flag"] + ""; devicePmsModel.id = devicePmsJObject["id"] + ""; devicePmsModel.paramName = devicePmsJObject["paramName"] + ""; devicePmsModel.value = devicePmsJObject["value"] + ""; devicePmsModel.unitName = devicePmsJObject["unitName"] + ""; devicePmsModel.dataType = devicePmsJObject["dataType"] + ""; StringBuilder devicePmsInsertKeys = new StringBuilder(); StringBuilder devicePmsInsertValues = new StringBuilder(); PropertyInfo[] devicePmsPropertyInfos = devicePmsModel.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo devicePmsPropertyInfo in devicePmsPropertyInfos) { devicePmsInsertKeys.Append($"{devicePmsPropertyInfo.Name},"); devicePmsInsertValues.Append($"'{(devicePmsPropertyInfo.GetValue(devicePmsModel, null) + "").Replace("'", "''")}',"); } projectSqlStrBuilder.Append($"insert into LadfDeviceParamStatusTab ({devicePmsInsertKeys.ToString().TrimEnd(',')}) values ({devicePmsInsertValues.ToString().TrimEnd(',')});\r\n"); } catch (Exception) { } } if (!string.IsNullOrEmpty(projectSqlStrBuilder.ToString())) { SqlHelper.ExecuteNonQuery(projectSqlStrBuilder.ToString()); } UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性成功\r\n"); } else { projectSqlStrBuilder.Append($"update LadfDeviceParamTab set status = '3' where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}';\r\n"); if (!string.IsNullOrEmpty(projectSqlStrBuilder.ToString())) { SqlHelper.ExecuteNonQuery(projectSqlStrBuilder.ToString()); } UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性成功,但设备已离线\r\n"); } } else if (code.Equals("4012")) { UpdateMsg($"登录失败\r\n"); Login(); QueryDeviceParamStatus(deviceModel); } } } catch (Exception ex) { if (ex.Message.Contains("未将对象引用设置到")) { UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性成功,但未查询到数据\r\n"); } else { UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性数据失败,原因:{ex.Message}\r\n"); } } } /// /// 查询历史数据 /// private void QueryDeviceParamStatusHistory(DeviceModel deviceModel) { StringBuilder projectSqlStrBuilder = new StringBuilder(); UpdateMsg($"正在读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性历史数据\r\n"); try { string url = "https://api.123321yun.com/api/device/queryDeviceParamHistoryData"; HttpUtil.setting("application/x-www-form-urlencoded", null, null); Dictionary pmsDic = new Dictionary(); pmsDic.Add("deviceId", deviceModel.deviceId); if (radioFix.Checked) { pmsDic.Add("start", GetStamp(fixStartDate.Value)); pmsDic.Add("end", GetStamp(fixEndDate.Value)); } else { pmsDic.Add("start", GetStamp(startTime)); pmsDic.Add("end", GetStamp(startTime.AddMinutes(timeInterval))); } pmsDic.Add("type", "1"); Dictionary headerDic = new Dictionary(); headerDic.Add("__sid", sid); HttpWebResponse webResponse = HttpUtil.Post(url, "", pmsDic, headerDic, HttpUtil.Method.POST); string result = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8).ReadToEnd(); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject resultJObject = (JObject)JsonConvert.DeserializeObject(result); string code = resultJObject["code"] + ""; if (code.Equals("200")) { if (radioFix.Checked) { projectSqlStrBuilder.Append($"delete from LadfDeviceParamStatusHistoryTab where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}' and datetime >= {GetStamp(fixStartDate.Value)} and datetime <= {GetStamp(fixEndDate.Value)};\r\n"); } else if (radioNext.Checked) { projectSqlStrBuilder.Append($"delete from LadfDeviceParamStatusHistoryTab where projectid = '{deviceModel.projectId}' and deviceId = '{deviceModel.deviceId}' and datetime >= {GetStamp(startTime)} and datetime <= {GetStamp(startTime.AddMinutes(timeInterval))};\r\n"); } JArray deviceParamHistoryJArray = (JArray)resultJObject["data"]; foreach (JObject deviceParamHistoryJObject in deviceParamHistoryJArray) { int datetime; if (!int.TryParse(deviceParamHistoryJObject["datetime"] + "", out datetime)) { Console.WriteLine("时间转换失败"); } IEnumerable properties = deviceParamHistoryJObject.Properties(); foreach (JProperty item in properties) { string flag = item.Name.ToString().Replace("'", "''"); string value = item.Value.ToString().Replace("'", "''"); projectSqlStrBuilder.Append($"insert into LadfDeviceParamStatusHistoryTab (projectId,deviceId,flag,value,datetime) values ('{deviceModel.projectId}','{deviceModel.deviceId}','{flag}','{value}',{datetime});\r\n"); } } if (!string.IsNullOrEmpty(projectSqlStrBuilder.ToString())) { SqlHelper.ExecuteNonQuery(projectSqlStrBuilder.ToString()); } } else if (code.Equals("4012")) { UpdateMsg($"登录失败\r\n"); Login(); QueryDeviceParamStatusHistory(deviceModel); } UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性历史数据成功\r\n"); } } catch (Exception ex) { if (ex.Message.Contains("未将对象引用设置到")) { UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性历史数据失败,原因:未查询到数据\r\n"); } else { UpdateMsg($"读取设备:{deviceModel.name}{deviceModel.deviceTypeName}的属性历史数据失败,原因:{ex.Message}\r\n"); } } } /// /// 连接数据库 /// /// private bool CreateConnection() { string connStr = GetConnection(); if (SqlHelper._connection != null) { try { SqlHelper._connection.Close(); SqlHelper._connection.Dispose(); } catch (Exception) { } SqlHelper._connection = null; } try { SqlHelper._connection = new SqlConnection(connStr); SqlHelper._connection.Open(); return true; } catch (Exception) { // LogHelper.Instance.WriteLog(ex.Message); } return false; } private void CloseConnection() { if (SqlHelper._connection != null) { try { SqlHelper._connection.Close(); SqlHelper._connection.Dispose(); } catch (Exception) { } SqlHelper._connection = null; } } /// /// 获取连接服务器的字符串 /// /// public string GetConnection() { return string.Format("Server={0};Database={1};Persist Security Info=True;User ID={2};Password={3};Connection Timeout=5;MultipleActiveResultSets=true", this.serverBox.Text, this.dataBaseBox.Text, "lserpAdmin", "lserp110"); } /// /// 获取当天零点的时间戳 /// /// public string GetNowTime0Stamp() { int year = DateTime.Now.Year; int month = DateTime.Now.Month; int day = DateTime.Now.Day; DateTime dateTime = new DateTime(year, month, day, 0, 0, 0, 0); TimeSpan tspan = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(tspan.TotalSeconds).ToString(); } /// /// 获取当天24点的时间戳 /// /// public string GetNowTime24Stamp() { int year = DateTime.Now.Year; int month = DateTime.Now.Month; int day = DateTime.Now.Day; DateTime dateTime = new DateTime(year, month, day, 23, 59, 59, 999); TimeSpan tspan = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(tspan.TotalSeconds).ToString(); } /// /// 获取指定时间的时间戳 /// /// public string GetStamp(DateTime dateTime) { TimeSpan tspan = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Con