DataUploadJob.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. 
  2. using log4net;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. using Quartz;
  6. using RDIFramework.Utilities;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Configuration;
  10. using System.Data;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. namespace TimedUpload.QuartzJobs
  17. {
  18. public class DataUploadJob : IJob
  19. {
  20. private readonly ILog log = LogManager.GetLogger(typeof(DataUploadJob));
  21. static IDbProvider NBHelper
  22. {
  23. get
  24. {
  25. var DbDefine = DbFactoryProvider.GetProvider(CurrentDbType.SqlServer, Config.GetValue("NBConn"));
  26. return DbDefine;
  27. }
  28. }
  29. static IDbProvider DbHelper
  30. {
  31. get
  32. {
  33. var DbDefine = DbFactoryProvider.GetProvider(CurrentDbType.SqlServer, Config.GetValue("DbConn"));
  34. return DbDefine;
  35. }
  36. }
  37. public void Execute(IJobExecutionContext context)
  38. {
  39. try
  40. {
  41. UploadData();
  42. }
  43. catch (Exception ex)
  44. {
  45. log.Error("上传数据错误:" + ex.Message);
  46. }
  47. }
  48. #region 增加设备
  49. /// <summary>
  50. /// 设备同步
  51. /// </summary>
  52. #region DataTable转换成json
  53. public void UploadData()
  54. {
  55. String result;
  56. Dictionary<String, String> dic;
  57. String sql;
  58. //try
  59. //{
  60. // log.Info("~~~~~~~~~~~~~~~~开始上传数据~~~~~~~~~~~~~~~~~~");
  61. // 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") + "'";
  62. // DataTable dt = NBHelper.Fill(sql);
  63. // if (dt != null && dt.Rows.Count > 0)
  64. // {
  65. // StringBuilder stb = new StringBuilder();
  66. // foreach (DataRow row in dt.Rows)
  67. // {
  68. // stb.Clear();
  69. // stb.Append("{");
  70. // stb.Append("\"encrypt\":\"" + encryptThreeDESECB(getTimeStamp() + "_" + Config.GetValue("appId"), Config.GetValue("Userkey")) + "\",");
  71. // stb.Append("\"appId\":\"" + Config.GetValue("appId") + "\",");
  72. // stb.Append("\"uptime\":" + getTimeStamp() + ",");
  73. // stb.Append("\"appType\":\"JC\",");
  74. // stb.Append("\"order_type\":null,");
  75. // stb.Append("\"seq\":\"0\",");
  76. // stb.Append("\"param\":null,");
  77. // stb.Append("\"order_result\":null,");
  78. // stb.Append("\"datas\":[{");
  79. // stb.Append("\"code\":\"" + row["ElecAddress"] + "01\",");
  80. // stb.Append("\"value\":" + row["NowReading"] + ",");
  81. // stb.Append("\"time\":" + getTimeStamp(Convert.ToDateTime(row["NowRadingDT"])) + "");
  82. // stb.Append("}]");
  83. // stb.Append("}");
  84. // result = postSend(Config.GetValue("UploadDataUrl"), stb.ToString());
  85. // log.Debug("~~~~~~~~~返回result:" + result);
  86. // stb.Clear();
  87. // if (result == "ok")
  88. // {
  89. // sql = "update RMRS_MeterInfo set DataUploadTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where ElecAddress='" + row["ElecAddress"] + "'";
  90. // NBHelper.ExecuteNonQuery(sql);
  91. // log.Info("上传成功" + row["ElecAddress"]);
  92. // }
  93. // //dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(result);
  94. // //if (dic !=null )
  95. // //{
  96. // // if (dic["code"] =="1")
  97. // // {
  98. // // }
  99. // //}
  100. // }
  101. // }
  102. //}
  103. //catch (Exception ex)
  104. //{
  105. // log.Error(ex.ToString());
  106. //}
  107. try
  108. {
  109. log.Info("定时任务开始了!" );
  110. sql = " select 表地址,表读数,ReviseDT from Bsc_MeterInfo where ReviseDT>DataUploadTime or DataUploadTime is null ";
  111. DataTable meterDt = DbHelper.Fill(sql);
  112. log.Info("有"+ meterDt.Rows.Count+"条未上报数据!");
  113. if (meterDt != null && meterDt.Rows.Count > 0)
  114. {
  115. StringBuilder stb = new StringBuilder();
  116. foreach (DataRow row in meterDt.Rows)
  117. {
  118. try
  119. {
  120. stb.Clear();
  121. stb.Append("{");
  122. stb.Append("\"encrypt\":\"" + encryptThreeDESECB(getTimeStamp() + "_" + Config.GetValue("appId"), Config.GetValue("Userkey")) + "\",");
  123. stb.Append("\"appId\":\"" + Config.GetValue("appId") + "\",");
  124. stb.Append("\"uptime\":" + getTimeStamp() + ",");
  125. stb.Append("\"appType\":\"JC\",");
  126. stb.Append("\"order_type\":null,");
  127. stb.Append("\"seq\":\"0\",");
  128. stb.Append("\"param\":null,");
  129. stb.Append("\"order_result\":null,");
  130. stb.Append("\"datas\":[{");
  131. stb.Append("\"code\":\"" + row["表地址"] + "01\",");
  132. stb.Append("\"value\":" + row["表读数"] + ",");
  133. stb.Append("\"time\":" + getTimeStamp(Convert.ToDateTime(row["ReviseDT"])) + "");
  134. stb.Append("}]");
  135. stb.Append("}");
  136. result = postSend(Config.GetValue("UploadDataUrl"), stb.ToString());
  137. log.Debug("~~~~~~~~~返回result:" + result);
  138. stb.Clear();
  139. if (result.Contains("ok"))
  140. {
  141. sql = "update Bsc_MeterInfo set DataUploadTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where 表地址='" + row["表地址"] + "'";
  142. DbHelper.ExecuteNonQuery(sql);
  143. log.Info("上传成功" + row["表地址"]);
  144. }
  145. }
  146. catch (Exception)
  147. {
  148. log.Info("error");
  149. }
  150. //dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(result);
  151. //if (dic != null)
  152. //{
  153. // if (dic["code"] == "1")
  154. // {
  155. // }
  156. //}
  157. }
  158. }
  159. log.Info("定时任务结束了!");
  160. }
  161. catch (Exception ex)
  162. {
  163. log.Info("出现异常了!"+ex.InnerException);
  164. throw;
  165. }
  166. }
  167. /// <summary>
  168. /// 自动维护AccessToken
  169. /// </summary>
  170. public string GetAccessToken() {
  171. String GetAccessTokenUrl = Config.GetValue("GetAccessTokenUrl");
  172. String param = "";
  173. String result = "";
  174. try
  175. {
  176. param = "{\"CompanyCode\":\"" + Config.GetValue("CompanyCode") + "\",\"Userkey\":\"" + Config.GetValue("Userkey") + "\"}";
  177. result = postSend(GetAccessTokenUrl, param);
  178. Dictionary<String, String> dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(result);
  179. if (dic != null && !string.IsNullOrEmpty(dic["Token"]))
  180. {
  181. Config.SetValue("Token", dic["Token"]);
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. //重新获取AccessToken
  187. param = "{\"CompanyCode\":\"" + Config.GetValue("CompanyCode") + "\",\"Userkey\":\"" + Config.GetValue("Userkey") + "\"";
  188. result = postSend(GetAccessTokenUrl, param);
  189. Dictionary<String, String> dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(result);
  190. if (dic != null && !string.IsNullOrEmpty(dic["Token"]))
  191. {
  192. Config.SetValue("Token", dic["Token"]);
  193. }
  194. }
  195. return Config.GetValue("Token");
  196. }
  197. #endregion
  198. #region 请求接口
  199. public string postSend(string url, string param)
  200. {
  201. string strResult = "";
  202. Encoding myEncode = Encoding.GetEncoding("UTF-8");
  203. byte[] postBytes = Encoding.UTF8.GetBytes(param);
  204. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
  205. req.Method = "POST";
  206. req.ContentType = "application/json;";
  207. req.ContentLength = postBytes.Length;
  208. try
  209. {
  210. using (Stream reqStream = req.GetRequestStream())
  211. {
  212. reqStream.Write(postBytes, 0, postBytes.Length);
  213. }
  214. using (WebResponse res = req.GetResponse())
  215. {
  216. using (StreamReader sr = new StreamReader(res.GetResponseStream(), myEncode))
  217. {
  218. strResult = sr.ReadToEnd();
  219. return strResult;
  220. }
  221. }
  222. }
  223. catch (WebException ex)
  224. {
  225. log.Error("Post数据出错:" + ex.Message);
  226. return "";
  227. }
  228. }
  229. #endregion
  230. #region 3DES加密
  231. public String encryptThreeDESECB(String text, String key)
  232. {
  233. var tripleDESCipher = new TripleDESCryptoServiceProvider();
  234. tripleDESCipher.Mode = CipherMode.ECB;
  235. tripleDESCipher.Padding = PaddingMode.PKCS7;
  236. byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(key);
  237. byte[] keyBytes = new byte[24];
  238. int len = pwdBytes.Length;
  239. if (len > keyBytes.Length)
  240. len = keyBytes.Length;
  241. System.Array.Copy(pwdBytes, keyBytes, len);
  242. tripleDESCipher.Key = keyBytes;
  243. // tripleDESCipher.IV = Encoding.ASCII.GetBytes(iv);
  244. ICryptoTransform transform = tripleDESCipher.CreateEncryptor();
  245. byte[] plainText = Encoding.UTF8.GetBytes(text);
  246. byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
  247. return Convert.ToBase64String(cipherBytes);
  248. }
  249. #endregion
  250. public String getTimeStamp()
  251. {
  252. TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  253. return Convert.ToInt64(ts.TotalMilliseconds).ToString();
  254. }
  255. public String getTimeStamp(DateTime dateTime)
  256. {
  257. TimeSpan ts = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  258. return Convert.ToInt64(ts.TotalMilliseconds).ToString();
  259. }
  260. }
  261. }
  262. #endregion