using log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Quartz; using RDIFramework.Utilities; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; namespace TimedUpload.QuartzJobs { public class DataUploadJob : IJob { private readonly ILog log = LogManager.GetLogger(typeof(DataUploadJob)); static IDbProvider NBHelper { get { var DbDefine = DbFactoryProvider.GetProvider(CurrentDbType.SqlServer, Config.GetValue("NBConn")); return DbDefine; } } static IDbProvider DbHelper { get { var DbDefine = DbFactoryProvider.GetProvider(CurrentDbType.SqlServer, Config.GetValue("DbConn")); return DbDefine; } } public void Execute(IJobExecutionContext context) { try { UploadData(); } catch (Exception ex) { log.Error("上传数据错误:" + ex.Message); } } #region 增加设备 /// /// 设备同步 /// #region DataTable转换成json public void UploadData() { String result; Dictionary dic; String sql; //try //{ // log.Info("~~~~~~~~~~~~~~~~开始上传数据~~~~~~~~~~~~~~~~~~"); // sql = " select ElecAddress,NowReading,NowRadingDT, '0' ValueControlState from RMRS_MeterInfo where NowRadingDT>DataUploadTime and DeleteMark=0 and RoomID is not null and CompanyID ='" + Config.GetValue("CompanyId") + "'"; // DataTable dt = NBHelper.Fill(sql); // if (dt != null && dt.Rows.Count > 0) // { // StringBuilder stb = new StringBuilder(); // foreach (DataRow row in dt.Rows) // { // stb.Clear(); // stb.Append("{"); // stb.Append("\"encrypt\":\"" + encryptThreeDESECB(getTimeStamp() + "_" + Config.GetValue("appId"), Config.GetValue("Userkey")) + "\","); // stb.Append("\"appId\":\"" + Config.GetValue("appId") + "\","); // stb.Append("\"uptime\":" + getTimeStamp() + ","); // stb.Append("\"appType\":\"JC\","); // stb.Append("\"order_type\":null,"); // stb.Append("\"seq\":\"0\","); // stb.Append("\"param\":null,"); // stb.Append("\"order_result\":null,"); // stb.Append("\"datas\":[{"); // stb.Append("\"code\":\"" + row["ElecAddress"] + "01\","); // stb.Append("\"value\":" + row["NowReading"] + ","); // stb.Append("\"time\":" + getTimeStamp(Convert.ToDateTime(row["NowRadingDT"])) + ""); // stb.Append("}]"); // stb.Append("}"); // result = postSend(Config.GetValue("UploadDataUrl"), stb.ToString()); // log.Debug("~~~~~~~~~返回result:" + result); // stb.Clear(); // if (result == "ok") // { // sql = "update RMRS_MeterInfo set DataUploadTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where ElecAddress='" + row["ElecAddress"] + "'"; // NBHelper.ExecuteNonQuery(sql); // log.Info("上传成功" + row["ElecAddress"]); // } // //dic = JsonConvert.DeserializeObject>(result); // //if (dic !=null ) // //{ // // if (dic["code"] =="1") // // { // // } // //} // } // } //} //catch (Exception ex) //{ // log.Error(ex.ToString()); //} try { log.Info("定时任务开始了!" ); sql = " select 表地址,表读数,ReviseDT from Bsc_MeterInfo where ReviseDT>DataUploadTime or DataUploadTime is null "; DataTable meterDt = DbHelper.Fill(sql); log.Info("有"+ meterDt.Rows.Count+"条未上报数据!"); if (meterDt != null && meterDt.Rows.Count > 0) { StringBuilder stb = new StringBuilder(); foreach (DataRow row in meterDt.Rows) { try { stb.Clear(); stb.Append("{"); stb.Append("\"encrypt\":\"" + encryptThreeDESECB(getTimeStamp() + "_" + Config.GetValue("appId"), Config.GetValue("Userkey")) + "\","); stb.Append("\"appId\":\"" + Config.GetValue("appId") + "\","); stb.Append("\"uptime\":" + getTimeStamp() + ","); stb.Append("\"appType\":\"JC\","); stb.Append("\"order_type\":null,"); stb.Append("\"seq\":\"0\","); stb.Append("\"param\":null,"); stb.Append("\"order_result\":null,"); stb.Append("\"datas\":[{"); stb.Append("\"code\":\"" + row["表地址"] + "01\","); stb.Append("\"value\":" + row["表读数"] + ","); stb.Append("\"time\":" + getTimeStamp(Convert.ToDateTime(row["ReviseDT"])) + ""); stb.Append("}]"); stb.Append("}"); result = postSend(Config.GetValue("UploadDataUrl"), stb.ToString()); log.Debug("~~~~~~~~~返回result:" + result); stb.Clear(); if (result.Contains("ok")) { sql = "update Bsc_MeterInfo set DataUploadTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where 表地址='" + row["表地址"] + "'"; DbHelper.ExecuteNonQuery(sql); log.Info("上传成功" + row["表地址"]); } } catch (Exception) { log.Info("error"); } //dic = JsonConvert.DeserializeObject>(result); //if (dic != null) //{ // if (dic["code"] == "1") // { // } //} } } log.Info("定时任务结束了!"); } catch (Exception ex) { log.Info("出现异常了!"+ex.InnerException); throw; } } /// /// 自动维护AccessToken /// public string GetAccessToken() { String GetAccessTokenUrl = Config.GetValue("GetAccessTokenUrl"); String param = ""; String result = ""; try { param = "{\"CompanyCode\":\"" + Config.GetValue("CompanyCode") + "\",\"Userkey\":\"" + Config.GetValue("Userkey") + "\"}"; result = postSend(GetAccessTokenUrl, param); Dictionary dic = JsonConvert.DeserializeObject>(result); if (dic != null && !string.IsNullOrEmpty(dic["Token"])) { Config.SetValue("Token", dic["Token"]); } } catch (Exception ex) { //重新获取AccessToken param = "{\"CompanyCode\":\"" + Config.GetValue("CompanyCode") + "\",\"Userkey\":\"" + Config.GetValue("Userkey") + "\""; result = postSend(GetAccessTokenUrl, param); Dictionary dic = JsonConvert.DeserializeObject>(result); if (dic != null && !string.IsNullOrEmpty(dic["Token"])) { Config.SetValue("Token", dic["Token"]); } } return Config.GetValue("Token"); } #endregion #region 请求接口 public string postSend(string url, string param) { string strResult = ""; Encoding myEncode = Encoding.GetEncoding("UTF-8"); byte[] postBytes = Encoding.UTF8.GetBytes(param); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/json;"; req.ContentLength = postBytes.Length; try { using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(postBytes, 0, postBytes.Length); } using (WebResponse res = req.GetResponse()) { using (StreamReader sr = new StreamReader(res.GetResponseStream(), myEncode)) { strResult = sr.ReadToEnd(); return strResult; } } } catch (WebException ex) { log.Error("Post数据出错:" + ex.Message); return ""; } } #endregion #region 3DES加密 public String encryptThreeDESECB(String text, String key) { var tripleDESCipher = new TripleDESCryptoServiceProvider(); tripleDESCipher.Mode = CipherMode.ECB; tripleDESCipher.Padding = PaddingMode.PKCS7; byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key); byte[] keyBytes = new byte[24]; int len = pwdBytes.Length; if (len > keyBytes.Length) len = keyBytes.Length; System.Array.Copy(pwdBytes, keyBytes, len); tripleDESCipher.Key = keyBytes; // tripleDESCipher.IV = Encoding.ASCII.GetBytes(iv); ICryptoTransform transform = tripleDESCipher.CreateEncryptor(); byte[] plainText = Encoding.UTF8.GetBytes(text); byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); return Convert.ToBase64String(cipherBytes); } #endregion public String getTimeStamp() { TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } public String getTimeStamp(DateTime dateTime) { TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds).ToString(); } } } #endregion