123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297 |
-
- 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 增加设备
- /// <summary>
- /// 设备同步
- /// </summary>
-
-
- #region DataTable转换成json
- public void UploadData()
- {
- String result;
- Dictionary<String, String> 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<Dictionary<String, String>>(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<Dictionary<String, String>>(result);
- //if (dic != null)
- //{
- // if (dic["code"] == "1")
- // {
-
- // }
- //}
- }
- }
- log.Info("定时任务结束了!");
- }
- catch (Exception ex)
- {
- log.Info("出现异常了!"+ex.InnerException);
- throw;
- }
- }
- /// <summary>
- /// 自动维护AccessToken
- /// </summary>
- 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<String, String> dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(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<String, String> dic = JsonConvert.DeserializeObject<Dictionary<String, String>>(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
|