Program.cs 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.IO;
  8. using System.Xml;
  9. using System.IO.BACnet;
  10. using System.Threading.Tasks;
  11. using NPOI.HSSF.UserModel;
  12. using NPOI.SS.UserModel;
  13. using System.Text.RegularExpressions;
  14. using Quartz;
  15. using Quartz.Impl;
  16. namespace NetCore31BACNetTransfor
  17. {
  18. public class Program
  19. {
  20. static BacnetClient Bacnet_client;
  21. static AsyncUdpClient Udp_Client;
  22. static List<BacDevice> DevicesList;
  23. static List<BacDevice> DevicesListScan;
  24. //BACnet序号
  25. static int udpId = 0;
  26. static String LocalBacIP="127.0.0.1";
  27. static int LocalBacPort;
  28. //util.xml
  29. //common
  30. static String RunMode = "formal";// 运行模式,支持formal/debug,缺省为formal
  31. static String BreakPoint = "false";// 断点模式,是否启用断点存储模式
  32. static String StorageClass = "CSV";// 断点存储格式,与BreakPoint组合使用
  33. static String StoragePath = "D:";// 断点存储路径,预留
  34. static String PointsFrom = "EXCEL";// pointList来源
  35. static String IntervalType = "interval";// 整点:integral/ 间隔:interval
  36. static String CollectInterval = "20Second";// 采集周期,以Second/min为单位
  37. static int SendCount = 10;// 最大上传报文条数
  38. static String SendInterval = "1min";// 上传周期,以Second/min为单位
  39. static int HandleDataThread = 1;// 报文解析线程数
  40. static String BuildingQaurry = "manual";// 下发楼号来源
  41. static String BuildingControl = null;// 下发指定楼号,与BuildingQaurry组合使用
  42. static String WaitingTimeControl = "3Second";// 下发等待时间,以Second为单位
  43. static String NodeMac = "1";// 节点网关
  44. static String ReportVersion = "addtion";// 报文版本,配置为standard时发report版报文;配置为addtion时发reportaddtion版报文
  45. //upload
  46. static String LocalUdpIP;
  47. static int LocalUdpPort;
  48. static String RemoteUdpIP;
  49. static int RemoteUdpPort;
  50. static String protocol = "bacnetipv2";
  51. static Dictionary<String, Dictionary<String, List<PointSet>>> CollectorPointSetList = new Dictionary<String, Dictionary<String, List<PointSet>>>();// 存放下发的原始设定记录
  52. static Dictionary<String, Dictionary<String, Dictionary<String, String>>> CollectorPropertyValues = new Dictionary<String, Dictionary<String, Dictionary<String, String>>>();// 存储collector各属性信息
  53. static Dictionary<String, List<Collector>> ProtocolCollectorList = new Dictionary<String, List<Collector>>();// 存储各协议对应的采集列表
  54. static Dictionary<String, Dictionary<String, Point>> Collector_Device_Point = new Dictionary<String, Dictionary<String, Point>>();// 存储各采集设备对应的点位信息
  55. static Dictionary<String, String> Meter_Protocol = new Dictionary<String, String>();// 存储Meter与采集协议的对应
  56. static Dictionary<String, String> Meter_CollectorMAC = new Dictionary<String, String>();// 存储Meter与采集设备网关的对应
  57. static Dictionary<String, String> Meter_SubPath = new Dictionary<String, String>();// 定制,不维护
  58. static Dictionary<String, String> Meter_CollectorAddress = new Dictionary<String, String>();// 存储Meter与采集设备地址的对应
  59. static Dictionary<String, String> Meter_Site = new Dictionary<String, String>();// 存储Meter与地址(对接系统)的对应
  60. static Dictionary<String, String> Meter_Building = new Dictionary<String, String>();// 存储Meter与楼号的对应
  61. static Dictionary<String, String> Meter_FunctionGroup = new Dictionary<String, String>();// 存储Meter与功能号组的对应
  62. static Dictionary<String, Point> Meter_Point = new Dictionary<String, Point>();// 存储Meter与点位的对应
  63. static Dictionary<String, Point> Item_Point = new Dictionary<String, Point>();// 存储Item与点位的对应
  64. static Dictionary<String, Int32> RecordAddress = new Dictionary<String, Int32>();// 存储数据地址
  65. // static List<Record> RecordList = new ArrayList<Record>();// 存储数据列表
  66. // static Dictionary<String, List<Report>> ReportList = new HashMap<String, List<Report>>();// 存储报文列表
  67. // static Dictionary<String, List<Date>> Round_Static = new HashMap<String, List<Date>>();// 预留
  68. static Dictionary<String, Collector> Meter_Collector = new Dictionary<String, Collector>();// 存储Meter与采集设备的对应
  69. //static List<String> CollectorProtocolGroup = new ArrayList<String>();// 存储协议组列表
  70. static Dictionary<String, String> CollectorMAC_Meter = new Dictionary<String, String>();// 存储Meter与采集设备网关的对应
  71. static Dictionary<String, String> SimulationDevicesMap = new Dictionary<String, String>();// 存储模拟设备列表
  72. static Dictionary<String, String> PointTopic = new Dictionary<String, String>();// 存储点位与topic对应,mqtt协议用到
  73. static Dictionary<String, String> PointQueue = new Dictionary<String, String>();// 存储点位与queue对应,amqp协议队列模式用到
  74. static Dictionary<String, Dictionary<String, String[]>> PointExchange = new Dictionary<String, Dictionary<String, String[]>>();// 存储点位与exchange对应,amqp协议路由模式用到
  75. static Dictionary<String, String> exchangeType = new Dictionary<String, String>();// 存储路由类型,amqp协议路由模式用到
  76. static Dictionary<String, String> pointConvType = new Dictionary<String, String>();// 存储点位解析类型,modbus-tcp协议用到
  77. static Dictionary<String, String> pointSlave = new Dictionary<String, String>();// 存储点位SlaveID,modbus-tcp协议用到
  78. static Dictionary<String, String> pointAddress = new Dictionary<String, String>();// 存储点位Address,modbus-tcp协议用到
  79. static Dictionary<String, Dictionary<String, Dictionary<String, String>>> FunctionPropertyValues = new Dictionary<String, Dictionary<String, Dictionary<String, String>>>();// 存储功能号各属性信息
  80. static Dictionary<String, Dictionary<String, Dictionary<String, String>>> PointPropertyValues = new Dictionary<String, Dictionary<String, Dictionary<String, String>>>();// 存储Point各属性信息
  81. static Dictionary<String, Dictionary<String, String>> Function_Old_New = new Dictionary<String, Dictionary<String, String>>();// 存储新旧功能号对应
  82. static Dictionary<String, Dictionary<String, String>> Function_New_Old = new Dictionary<String, Dictionary<String, String>>();// 存储新旧功能号对应
  83. static Dictionary<String, Dictionary<String, String>> Function_New_Site = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与地址(对接系统)对应
  84. static Dictionary<String, Dictionary<String, String>> Function_New_SubSite = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与二级地址(对接系统)对应
  85. static Dictionary<String, Dictionary<String, String>> Function_Old_Type = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与类型(对接系统)对应
  86. static Dictionary<String, Dictionary<String, String>> Function_New_Type = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与类型(对接系统)对应
  87. static Dictionary<String, Dictionary<String, String>> Function_New_Reverse = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与寄存器反转标记(对接系统)对应
  88. static Dictionary<String, Dictionary<String, String>> Function_Old_CONVType = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与数据解析类型(对接系统)对应
  89. static Dictionary<String, Dictionary<String, String>> Function_Old_Size = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与寄存器数量(对接系统)对应
  90. static Dictionary<String, Dictionary<String, String>> Function_Old_Radio = new Dictionary<String, Dictionary<String, String>>();// 存储功能号与数据换算系数对应
  91. static Dictionary<String, Dictionary<String, String>> DataConvert = new Dictionary<String, Dictionary<String, String>>();// 存储数据转换对应关系
  92. static Dictionary<String, Dictionary<String, String>> Function_New_DataConvert = new Dictionary<String, Dictionary<String, String>>();// 存储功能号及数据转换的对应关系
  93. static List<String>Function_Threshold = new List<string>();//存储阈值和function_id之间关系
  94. static List<Record> RecordList = new List<Record>();// 存储数据列表
  95. static int GetCurrentUdpId()
  96. {
  97. udpId++;
  98. if (udpId >= 65536) udpId = 1;
  99. return udpId;
  100. }
  101. //BACnet序号
  102. static byte invokeId = 0;
  103. static byte GetCurrentInvokeId()
  104. {
  105. invokeId++;
  106. if (invokeId >= byte.MaxValue) invokeId = 1;
  107. return invokeId;
  108. }
  109. //心跳
  110. static int HeartBeatIndex = 0;
  111. static int GetHeartBeatIndex()
  112. {
  113. HeartBeatIndex++;
  114. if (HeartBeatIndex == int.MaxValue)
  115. HeartBeatIndex = 0;
  116. return HeartBeatIndex;
  117. }
  118. public static void Main(string[] args)
  119. {
  120. Logger.Log("Begin Translate BACnet Datas");
  121. Init(args);
  122. }
  123. class SendMessageJob : IJob
  124. {
  125. /// <summary>
  126. /// 创建要执行的作业
  127. /// </summary>
  128. /// <param name="context"></param>
  129. /// <returns></returns>
  130. public async Task Execute(IJobExecutionContext context)
  131. {
  132. await Task.Run(() => {
  133. Console.WriteLine("你好啊!");
  134. });
  135. }
  136. }
  137. public static void Show()
  138. {
  139. //创建调度单元
  140. Task<IScheduler> tsk = StdSchedulerFactory.GetDefaultScheduler();
  141. IScheduler scheduler = tsk.Result;
  142. //2.创建一个具体的作业即job (具体的job需要单独在一个文件中执行)
  143. IJobDetail job = JobBuilder.Create<SendMessageJob>().WithIdentity("完成").Build();
  144. //3.创建并配置一个触发器即trigger 1s执行一次
  145. ITrigger _CronTrigger = TriggerBuilder.Create()
  146. .WithIdentity("定时确认")
  147. .WithCronSchedule("0/2 * * * * ?") //秒 分 时 某一天 月 周 年(可选参数)
  148. .Build()
  149. as ITrigger;
  150. //4.将job和trigger加入到作业调度池中
  151. scheduler.ScheduleJob(job, _CronTrigger);
  152. //5.开启调度
  153. scheduler.Start();
  154. Console.ReadLine();
  155. }
  156. static void Init(string[] args)
  157. {
  158. try
  159. {
  160. Settings.InitSettings(args);
  161. LoadSettingFromXML(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "util.xml"));
  162. LoadSettingFromExcel(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "setting.xls"));
  163. LoadPointsFromExcel(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "pointlist.xls"), protocol);
  164. // InitBacnet_client();
  165. Thread.Sleep(50 * 1000);
  166. if (Settings.RollCall)
  167. {
  168. //List<string> iplist = new List<string>();
  169. //foreach (var list in Collector_Device_Point)
  170. //{
  171. // foreach (var list1 in list.Value)
  172. // {
  173. // Console.WriteLine(list1);
  174. // String listStr = list1.ToString().Split(",")[0];
  175. // listStr = listStr.Split("[")[1];
  176. // String[] listinfo = listStr.Split("-");
  177. // for (int i = 0; i < listinfo.Count(); i++) {
  178. // Console.WriteLine(listinfo[1]);
  179. // if (IsNumStr(listinfo[1])) {
  180. // iplist.Add(listinfo[1]);
  181. // }
  182. // }
  183. // //var targetObjId = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)10);
  184. // //var targetBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, "192.168.1.1");
  185. // //var rez = Bacnet_client.ReadPropertyAsync(targetBacnetAddress, targetObjId, BacnetPropertyIds.PROP_OBJECT_LIST);
  186. // //rez.ContinueWith((sender) =>
  187. // //{
  188. // // var result = sender.Result;
  189. // // foreach (var item in result)
  190. // // {
  191. // // //do stuff
  192. // // Console.WriteLine(item.Value);
  193. // // }
  194. // //});
  195. // //String ip = list1.ToString().Split(":")[0];
  196. // //ip = ip.Split("[")[1];
  197. // //iplist.Add(ip);
  198. // }
  199. //}
  200. //var ipdist = (from li in iplist select li).Distinct();
  201. //iplist = ipdist.OrderBy(s => int.Parse(Regex.Match(s, @"^\d+$").Value)).ToList();
  202. //foreach (var i in iplist) {
  203. // Console.WriteLine(i);
  204. //}
  205. var thread = new Thread(() => ForEachBacnet_client());
  206. thread.Start();
  207. }
  208. else {
  209. var thread = new Thread(() => InitBacnet_client());
  210. thread.Start();
  211. // InitBacnet_client();
  212. }
  213. InitUdp_Client();
  214. //等待扫描,尽量多等一会
  215. Thread.Sleep(5*60*1000);
  216. Task.Factory.StartNew(BeginScanBac);
  217. Task.Factory.StartNew(BeginHeartBeat);
  218. }
  219. catch (Exception exp)
  220. {
  221. Logger.Error("Init: ", exp);
  222. }
  223. }
  224. private static void ForEachBacnet_client() {
  225. while (true) {
  226. InitBacnet_clientRollCall();
  227. Thread.Sleep(30*60*1000);
  228. }
  229. }
  230. static void InitBacnet_clientRollCall()
  231. {
  232. try
  233. {
  234. // Bacnet_client = new BacnetClient(new BacnetIpUdpProtocolTransport(Settings.LocalBacPort, false));
  235. Bacnet_client = new BacnetClient(new BacnetIpUdpProtocolTransport(LocalBacPort, false, false, 1472, LocalBacIP));
  236. Bacnet_client.OnIam -= new BacnetClient.IamHandler(handler_OnIam1);
  237. Bacnet_client.OnIam += new BacnetClient.IamHandler(handler_OnIam1);
  238. // Bacnet_client.Iam(999999);
  239. Bacnet_client.Start();
  240. Bacnet_client.WhoIs();
  241. }
  242. catch (Exception exp)
  243. {
  244. Logger.Error("InitBacnet_clientRollCall: ", exp);
  245. }
  246. }
  247. static void handler_OnIam1(BacnetClient sender, BacnetAddress adr, uint deviceId, uint maxAPDU,
  248. BacnetSegmentations segmentation, ushort vendorId)
  249. {
  250. try
  251. {
  252. if (IsDetecteDeviceFinished) return;
  253. if (DevicesListScan == null) DevicesListScan = new List<BacDevice>();
  254. lock (DevicesListScan)
  255. {
  256. if (DevicesListScan.Any(x => x.DeviceId == deviceId)) return;
  257. var device = new BacDevice(adr, deviceId);
  258. string ip = Regex.Split(System.Convert.ToString(device.Address), ":", RegexOptions.IgnoreCase)[0];
  259. Console.WriteLine("Chack_ip: " + ip + ", " + Collector_Device_Point.ContainsKey(Convert.ToString(ip)));
  260. if (!Collector_Device_Point.ContainsKey(Convert.ToString(ip)))
  261. {
  262. return;
  263. }
  264. if (Settings.Localdebug)
  265. {
  266. Logger.Log(@"Detect Device: " + ip + " " + deviceId);
  267. }
  268. else {
  269. Console.WriteLine(@"Detect Device: " + ip + " " + deviceId);
  270. }
  271. device.LoadProperties(device.DeviceId, Collector_Device_Point[Convert.ToString(ip)]);
  272. //device.LoadPropertiesFromExcel(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Constants.AimExcelDir, "" + deviceId + ".xls"));
  273. DevicesListScan.Add(device);
  274. }
  275. }
  276. catch (Exception exp)
  277. {
  278. Logger.Error("handler_OnIam", exp);
  279. //InitBacnet_client();
  280. //InitUdp_Client();
  281. }
  282. }
  283. private static void LoadPointsFromExcel(string file, string protocol)
  284. {
  285. Dictionary<Int32, Dictionary<Int32, String>> sheetData = readExcel(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "pointlist.xls"), protocol);
  286. excuteDataConvert(sheetData);
  287. excuteFunctions(sheetData);
  288. excutePoints(sheetData);
  289. }
  290. public static BacnetAddress ConvertIP(System.Net.IPEndPoint ep)
  291. {
  292. BacnetAddress addr;
  293. byte[] tmp1 = ep.Address.GetAddressBytes();
  294. byte[] tmp2 = BitConverter.GetBytes((ushort)ep.Port);
  295. Array.Reverse(tmp2);
  296. Array.Resize<byte>(ref tmp1, tmp1.Length + tmp2.Length);
  297. Array.Copy(tmp2, 0, tmp1, tmp1.Length - tmp2.Length, tmp2.Length);
  298. addr = new BacnetAddress(BacnetAddressTypes.IP, 0, tmp1);
  299. return addr;
  300. }
  301. private static void excutePoints(Dictionary<int, Dictionary<int, string>> sheetData)
  302. {
  303. int begin = 65535;
  304. int sbegin = 65535;
  305. int end = 65535;
  306. CollectorPropertyValues.Add(protocol, new Dictionary<String, Dictionary<String, String>>());
  307. CollectorPointSetList.Add(protocol, new Dictionary<String, List<PointSet>>());
  308. Dictionary<String, List<PointSet>> ps = new Dictionary<String, List<PointSet>>();
  309. List<Collector> CollectorList = new List<Collector>();
  310. Dictionary<String, Int32> collectorPty = new Dictionary<String, Int32>();
  311. Dictionary<Int32, String> collectorPtyValue = new Dictionary<Int32, String>();
  312. Dictionary<String, Int32> pointPty = new Dictionary<String, Int32>();
  313. Dictionary<Int32, String> pointPtyValue = new Dictionary<Int32, String>();
  314. Collector group = new Collector();
  315. String collectorName = "";
  316. for (int i = 0; i <= sheetData.Count; i++)
  317. {
  318. if (!sheetData.ContainsKey(i))
  319. {
  320. continue;
  321. }
  322. Dictionary<Int32, String> rowData = sheetData[i];
  323. if (rowData.ContainsKey(0) && "Collector".Equals(rowData[0]))
  324. {
  325. // Constant.info("Collector begin: " + i);
  326. begin = i;
  327. sbegin = 65535;
  328. for (int j = 1; j < rowData.Count; j++)
  329. {
  330. if (collectorPty.ContainsKey(rowData[j]))
  331. {
  332. collectorPty[rowData[j]] = j;
  333. }
  334. else
  335. {
  336. collectorPty.Add(rowData[j], j);
  337. }
  338. if (collectorPtyValue.ContainsKey(j))
  339. {
  340. collectorPtyValue[j] = rowData[j];
  341. }
  342. else
  343. {
  344. collectorPtyValue.Add(j, rowData[j]);
  345. }
  346. }
  347. }
  348. else if (rowData.ContainsKey(0) && "Point".Equals(rowData[0]))
  349. {
  350. // Constant.info("Point begin: " + i);
  351. sbegin = i;
  352. for (int j = 1; j < rowData.Count; j++)
  353. {
  354. if (pointPty.ContainsKey(rowData[j]))
  355. {
  356. pointPty[rowData[j]] = j;
  357. }
  358. else
  359. {
  360. pointPty.Add(rowData[j], j);
  361. }
  362. if (pointPtyValue.ContainsKey(j))
  363. {
  364. pointPtyValue[j] = rowData[j];
  365. }
  366. else
  367. {
  368. pointPtyValue.Add(j, rowData[j]);
  369. }
  370. }
  371. }
  372. else if (rowData.ContainsKey(0) && (rowData[0].Length > 0) && !("Point".Equals(rowData[0])))
  373. {
  374. // Constant.info("Collector end: " + i);
  375. end = i;
  376. begin = 65535;
  377. sbegin = 65535;
  378. end = 65535;
  379. collectorPty = new Dictionary<String, Int32>();
  380. collectorPtyValue = new Dictionary<Int32, String>();
  381. pointPty = new Dictionary<String, Int32>();
  382. pointPtyValue = new Dictionary<Int32, String>();
  383. group = new Collector();
  384. }
  385. else if (i > sbegin && i < end)
  386. {
  387. if (rowData.ContainsKey(1) && rowData[1].Length > 0)
  388. {
  389. // Constant.info("Point add: " + i);
  390. Dictionary<String, Point> deviceList = new Dictionary<String, Point>();
  391. Point point = new Point();
  392. Meter_Protocol.Add(rowData[pointPty["MeterSign"]], protocol);
  393. Meter_CollectorMAC.Add(rowData[pointPty["MeterSign"]], group.MAC);
  394. Meter_Collector.Add(rowData[pointPty["MeterSign"]], group);
  395. //CollectorMAC_Meter[group.MAC] = rowData[pointPty["MeterSign"]];
  396. //CollectorMAC_Meter.Add(group.MAC, rowData[pointPty["MeterSign"]]);
  397. Meter_Site.Add(rowData[pointPty["MeterSign"]],
  398. !pointPty.ContainsKey("Site") ? "0" : rowData[pointPty["Site"]]);
  399. Meter_SubPath.Add(rowData[pointPty["MeterSign"]],
  400. !pointPty.ContainsKey("SubPath") ? "null" : rowData[pointPty["SubPath"]]);
  401. Meter_Building.Add(rowData[pointPty["MeterSign"]],
  402. rowData[pointPty["BuildingSign"]]);
  403. Meter_FunctionGroup.Add(rowData[pointPty["MeterSign"]],
  404. rowData[pointPty["Functions_Group"]]);
  405. String deviceSite = "";
  406. if (pointPty.ContainsKey("MAC") && rowData[pointPty["MAC"]] != null
  407. && rowData[pointPty["MAC"]] != null
  408. && rowData[pointPty["MAC"]].ToString().Length > 0)
  409. {
  410. deviceSite = rowData[pointPty["MAC"]].ToString();
  411. Meter_CollectorMAC.Add(rowData[pointPty["MeterSign"]],
  412. rowData[pointPty["MAC"]].ToString());
  413. //CollectorMAC_Meter.Add(rowData[pointPty["MAC"]].ToString(),rowData[pointPty["MeterSign"]]);
  414. }
  415. else
  416. {
  417. deviceSite = (!pointPty.ContainsKey("BusNo") ? "0" : rowData[pointPty["BusNo"]])
  418. + "-" + (!pointPty.ContainsKey("Site") ? "0" : rowData[pointPty["Site"]]);
  419. deviceSite = (!pointPty.ContainsKey("BusNo") || !pointPty.ContainsKey("Site"))
  420. ? rowData[pointPty["MeterSign"]] : deviceSite;
  421. }
  422. point.Item = !pointPty.ContainsKey("Item") ? "null" : rowData[pointPty["Item"]];
  423. point.buildingSign = rowData[pointPty["BuildingSign"]];
  424. point.meterSign = rowData[pointPty["MeterSign"]];
  425. point.deviceId = !pointPty.ContainsKey("DeviceId") ? "null"
  426. : rowData[pointPty["DeviceId"]];
  427. point.type = !pointPty.ContainsKey("Type") ? "null" : rowData[pointPty["Type"]];
  428. point.instanceNumber = !pointPty.ContainsKey("InstanceNumber") ? "null"
  429. : rowData[pointPty["InstanceNumber"]];
  430. Function f = new Function();
  431. point.funcGroupID = !pointPty.ContainsKey("Functions_Group") ? "null" : rowData[pointPty["Functions_Group"]];
  432. f.functionID = int.Parse(point.funcGroupID);
  433. point.functionList.Add(f);
  434. // point.functionList.Add(int.Parse(!pointPty.ContainsKey("Functions_Group") ? "null" : rowData[pointPty["Functions_Group"]]));
  435. //foreach (String function in Function_New_Old[rowData[pointPty["Functions_Group"]]].Keys)
  436. //{
  437. // Function f = new Function();
  438. // f.functionID = int.Parse(function);
  439. // point.functionList.Add(f);
  440. //}
  441. Meter_Point.Add(point.meterSign, point);
  442. //Item_Point.Add(point.Item, point);
  443. deviceSite = group.IP + ":" + group.Port + "-" + point.deviceId + "-" + point.type + "-" + point.instanceNumber;
  444. if (Settings.Localdebug)
  445. {
  446. Logger.Log("deviceSite: " + deviceSite);
  447. }
  448. deviceList.Add(deviceSite, point);
  449. //if (!Settings.RollCall) {
  450. // IPAddress address = IPAddress.Parse(group.IP);
  451. // IPEndPoint endpoint = new IPEndPoint(address, group.Port);
  452. // BacDevice item = new BacDevice(ConvertIP(endpoint), uint.Parse(point.deviceId));
  453. // DevicesList.Add(item);
  454. //}
  455. if (Collector_Device_Point.ContainsKey(group.IP))
  456. {
  457. foreach (KeyValuePair<string, Point> kv in deviceList)
  458. {
  459. Collector_Device_Point[group.IP].Add(kv.Key, kv.Value);
  460. if (Settings.Localdebug)
  461. {
  462. Logger.Log("1_group.IP" + group.IP + " kv.Key: " + kv.Key + " kv.Value: " + kv.Value.ToString());
  463. }
  464. }
  465. }
  466. else
  467. {
  468. Collector_Device_Point.Add(group.IP, deviceList);
  469. if (Settings.Localdebug)
  470. {
  471. Logger.Log("2_group.IP" + group.IP + " deviceList: " + deviceList.ToString());
  472. }
  473. }
  474. PointPropertyValues[collectorName].Add(point.buildingSign + "-" + point.meterSign,
  475. new Dictionary<String, String>());
  476. for (int j = 1; j < rowData.Count; j++)
  477. {
  478. PointPropertyValues[collectorName]
  479. [point.buildingSign + "-" + point.meterSign]
  480. .Add(pointPtyValue[j], rowData[j]);
  481. }
  482. }
  483. }
  484. else if (i > begin && i < end)
  485. {
  486. if (rowData.ContainsKey(1) && rowData[1].Length > 0)
  487. {
  488. // Constant.info("Collector add: " + i);
  489. Collector collector = new Collector();
  490. collector.IP = !collectorPty.ContainsKey("IP") ? "null" : rowData[(collectorPty[("IP")])];
  491. collector.Port = int.Parse(
  492. !collectorPty.ContainsKey("Port") ? "0" : rowData[(collectorPty[("Port")])]);
  493. collector.User = !collectorPty.ContainsKey("User") ? "null"
  494. : rowData[(collectorPty[("User")])];
  495. collector.Password = !collectorPty.ContainsKey("Password") ? "null"
  496. : rowData[(collectorPty[("Password")])];
  497. collector.ProgId = !collectorPty.ContainsKey("ProgId") ? "null"
  498. : rowData[(collectorPty[("ProgId")])];
  499. collector.BroadcastAddress = !collectorPty.ContainsKey("BroadcastAddress") ? "null"
  500. : rowData[(collectorPty[("BroadcastAddress")])];
  501. collector.MAC = !collectorPty.ContainsKey("MAC") ? "null"
  502. : rowData[(collectorPty[("MAC")])];
  503. collector.PROTOCOL = !collectorPty.ContainsKey("PROTOCOL") ? "UDP"
  504. : rowData[(collectorPty[("PROTOCOL")])];
  505. collector.Mode = !collectorPty.ContainsKey("Mode") ? "mina"
  506. : rowData[(collectorPty[("Mode")])];
  507. collector.Max_size = int.Parse(!collectorPty.ContainsKey("Max_size") ? "1000"
  508. : rowData[(collectorPty[("Max_size")])]);
  509. collector.SqlContent = !collectorPty.ContainsKey("SqlContent") ? "null"
  510. : rowData[(collectorPty[("SqlContent")])];
  511. group = collector;
  512. if (collectorPty.ContainsKey("IP"))
  513. {
  514. collectorName = rowData[(collectorPty[("IP")])];
  515. }
  516. else if (collectorPty.ContainsKey("url"))
  517. {
  518. collectorName = rowData[(collectorPty[("url")])];
  519. }
  520. else if (collectorPty.ContainsKey("MAC"))
  521. {
  522. collectorName = rowData[(collectorPty[("MAC")])];
  523. }
  524. // collectorName = collectorPty.containsKey("IP") ?
  525. // rowData.get(collectorPty.get("IP"))
  526. // : rowData.get(collectorPty.get("url"));
  527. collector.Name = collectorName;
  528. CollectorList.Add(collector);
  529. if (CollectorPropertyValues[(protocol)].ContainsKey(collectorName))
  530. {
  531. CollectorPropertyValues[(protocol)][collectorName] = new Dictionary<String, String>();
  532. }
  533. else
  534. {
  535. CollectorPropertyValues[(protocol)].Add(collectorName, new Dictionary<String, String>());
  536. }
  537. if (PointPropertyValues.ContainsKey(collectorName))
  538. {
  539. PointPropertyValues[collectorName] = new Dictionary<String, Dictionary<String, String>>();
  540. }
  541. else
  542. {
  543. PointPropertyValues.Add(collectorName, new Dictionary<String, Dictionary<String, String>>());
  544. }
  545. if (ps.ContainsKey(collector.IP))
  546. {
  547. ps[collector.IP] = new List<PointSet>();
  548. }
  549. else
  550. {
  551. ps.Add(collector.IP, new List<PointSet>());
  552. }
  553. for (int j = 1; j < rowData.Count; j++)
  554. {
  555. CollectorPropertyValues[(protocol)][(collectorName)]
  556. .Add(collectorPtyValue[j], rowData[j]);
  557. }
  558. }
  559. }
  560. }
  561. CollectorPointSetList[protocol] = ps;
  562. ProtocolCollectorList[protocol] = CollectorList;
  563. //CollectorPointSetList.Add(protocol, ps);
  564. //ProtocolCollectorList.Add(protocol, CollectorList);
  565. }
  566. private static void excuteFunctions(Dictionary<int, Dictionary<int, string>> sheetData)
  567. {
  568. int begin = 65535;
  569. int sbegin = 65535;
  570. int end = 65535;
  571. Dictionary<String, Int32> functionPty = new Dictionary<String, Int32>();
  572. Dictionary<Int32, String> functionPtyValue = new Dictionary<Int32, String>();
  573. String group = "";
  574. for (int i = 0; i <= sheetData.Count; i++)
  575. {
  576. if (!sheetData.ContainsKey(i))
  577. {
  578. continue;
  579. }
  580. Dictionary<Int32, String> rowData = sheetData[i];
  581. if (rowData.ContainsKey(0) && "Threshold".Equals(rowData[0]))
  582. {
  583. begin = i;
  584. sbegin = 65535;
  585. // Logger.Log("Functions begin: " + i);
  586. }
  587. else if (rowData.ContainsKey(0) && "Function".Equals(rowData[0]))
  588. {
  589. sbegin = i;
  590. // Logger.Log("Function begin: " + i);
  591. //for (int j = 1; j < rowData.Count; j++)
  592. //{
  593. // functionPty.Add(rowData[j], j);
  594. // functionPtyValue.Add(j, rowData[j]);
  595. //}
  596. }
  597. else if (rowData.ContainsKey(0) && (rowData[0].Length > 0) && !("Function".Equals(rowData[0])))
  598. {
  599. end = i;
  600. begin = 65535;
  601. sbegin = 65535;
  602. end = 65535;
  603. functionPty = new Dictionary<String, Int32>();
  604. functionPtyValue = new Dictionary<Int32, String>();
  605. group = "";
  606. // Logger.Log("Functions end: " + i);
  607. }
  608. else if (i > sbegin && i < end)
  609. {
  610. //if (rowdata.containskey(1) && rowdata[1].length > 0)
  611. //{
  612. // // logger.log("function add: " + i);
  613. // string function_new = rowdata[functionpty["new"]];
  614. // string function_old = rowdata[functionpty["old"]];
  615. // // function
  616. // string function = function_new;
  617. // // dataconvert_group
  618. // string dataconvert_group = !functionpty.containskey("dataconvert_group") ? "null"
  619. // : rowdata[functionpty["dataconvert_group"]];
  620. // function_old_new[group].add(function_old, function_new);
  621. // function_new_old[group].add(function_new, function_old);
  622. // if (!dataconvert.containskey(dataconvert_group))
  623. // {
  624. // function_new_dataconvert.add(function_new, null);
  625. // }
  626. // else
  627. // {
  628. // function_new_dataconvert.add(function_new, dataconvert[dataconvert_group]);
  629. // }
  630. // function_new_site[group].add(function_new, !functionpty.containskey("site") ? "0"
  631. // : rowdata[functionpty["site"]]);
  632. // function_new_subsite[group].add(function_new, !functionpty.containskey("subsite")
  633. // ? "0" : rowdata[functionpty["subsite"]]);
  634. // function_old_type[group].add(function_old,
  635. // !functionpty.containskey("type") ? "double" : rowdata[functionpty["type"]]);
  636. // function_new_type[group].add(function_new,
  637. // !functionpty.containskey("type") ? "double" : rowdata[functionpty["type"]]);
  638. // function_new_reverse[group].add(function_new,
  639. // !functionpty.containskey("reverse") ? "false" : rowdata[functionpty["reverse"]]);
  640. // function_old_convtype[group].add(function_old,
  641. // !functionpty.containskey("convtype") ? "0" : rowdata[functionpty["convtype"]]);
  642. // function_old_size[group].add(function_old,
  643. // !functionpty.containskey("size") ? "1" : rowdata[functionpty["size"]]);
  644. // function_old_radio[group].add(function_old,
  645. // !functionpty.containskey("radio") ? "1" : rowdata[functionpty["radio"]]);
  646. // functionpropertyvalues[group].add(function, new dictionary<string, string>());
  647. // for (int j = 1; j < rowdata.count; j++)
  648. // {
  649. // functionpropertyvalues[group][function].add(functionptyvalue[j],
  650. // rowdata[j]);
  651. // }
  652. //}
  653. }
  654. else if (i > begin && i < end)
  655. {
  656. if (rowData.ContainsKey(1) && rowData[1].Length > 0) {
  657. Function_Threshold.Add(rowData[1].Trim() + ","+rowData[2].Trim() + "," + rowData[3].Trim());
  658. }
  659. //if (rowData.ContainsKey(1) && rowData[1].Length > 0)
  660. //{
  661. // // Logger.Log("Functions add: " + i);
  662. // group = rowData[1];
  663. // Function_Old_New.Add(group, new Dictionary<String, String>());
  664. // Function_New_Old.Add(group, new Dictionary<String, String>());
  665. // Function_New_Site.Add(group, new Dictionary<String, String>());
  666. // Function_New_SubSite.Add(group, new Dictionary<String, String>());
  667. // Function_Old_Type.Add(group, new Dictionary<String, String>());
  668. // Function_New_Type.Add(group, new Dictionary<String, String>());
  669. // Function_New_Reverse.Add(group, new Dictionary<String, String>());
  670. // Function_Old_CONVType.Add(group, new Dictionary<String, String>());
  671. // Function_Old_Size.Add(group, new Dictionary<String, String>());
  672. // Function_Old_Radio.Add(group, new Dictionary<String, String>());
  673. // FunctionPropertyValues.Add(group, new Dictionary<String, Dictionary<String, String>>());
  674. //}
  675. }
  676. }
  677. //foreach (var a in Function_Threshold) {
  678. // Console.WriteLine(a);
  679. //}
  680. }
  681. private static void excuteDataConvert(Dictionary<Int32, Dictionary<Int32, String>> sheetData)
  682. {
  683. int begin = 65535;
  684. int sbegin = 65535;
  685. int end = 65535;
  686. String group = "";
  687. for (int i = 0; i <= sheetData.Count; i++)
  688. {
  689. if (!sheetData.ContainsKey(i))
  690. {
  691. continue;
  692. }
  693. Dictionary<Int32, String> rowData = sheetData[i];
  694. if (!rowData.ContainsKey(0))
  695. {
  696. continue;
  697. }
  698. if ("DataConvert".Equals(rowData[0]))
  699. {
  700. begin = i;
  701. sbegin = 65535;
  702. // Logger.Log("DataConvert begin: " + i);
  703. }
  704. else if ("Convert".Equals(rowData[0]))
  705. {
  706. sbegin = i;
  707. // Logger.Log("Convert begin: " + i);
  708. }
  709. else if ((rowData[0].Length > 0) && !("Convert".Equals(rowData[0])))
  710. {
  711. begin = 65535;
  712. sbegin = 65535;
  713. end = 65535;
  714. group = "";
  715. // Logger.Log("DataConvert end: " + i);
  716. }
  717. else if (i > sbegin && i < end)
  718. {
  719. if (!rowData.ContainsKey(1))
  720. {
  721. continue;
  722. }
  723. if (rowData[1].Length > 0)
  724. {
  725. DataConvert[group].Add(rowData[1], rowData[2]);
  726. // Logger.Log("Convert add: " + i);
  727. }
  728. }
  729. else if (i > begin && i < end)
  730. {
  731. if (!rowData.ContainsKey(1))
  732. {
  733. continue;
  734. }
  735. if (rowData[1].Length > 0)
  736. {
  737. DataConvert.Add(rowData[1], new Dictionary<String, String>());
  738. group = rowData[1];
  739. // Logger.Log("DataConvert add: " + i);
  740. }
  741. }
  742. }
  743. }
  744. public static bool IsIP(string ip)
  745. {
  746. if (ip != null||!"".Equals(ip)) {
  747. //判断是否为IP
  748. return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
  749. }
  750. return false;
  751. }
  752. public static bool IsNumStr(String theStr) {
  753. if (theStr != null||!"".Equals(theStr))//注意加非空判断,否则报错
  754. {
  755. System.Text.RegularExpressions.Regex rex =new System.Text.RegularExpressions.Regex(@"^\d+$");//^开始,\d匹配一个数字字符,+出现至少一次,$结尾
  756. if (rex.IsMatch(theStr))
  757. {
  758. return true;
  759. }
  760. }
  761. return false;
  762. }
  763. private static bool CheckCellFormat(String SheetName, int rowNum , int colNum ,String cellContent) {
  764. if ("bacnetipv2".Equals(SheetName)) {
  765. if (colNum == 1 || colNum == 2 || colNum == 4 || colNum == 5)
  766. {
  767. if ("".Equals(cellContent) || IsIP(cellContent) || IsNumStr(cellContent)
  768. || "IP".Equals(cellContent) || "BuildingSign".Equals(cellContent) || "Port".Equals(cellContent) || "MeterSign".Equals(cellContent)
  769. || "DeviceId".Equals(cellContent) || "InstanceNumber".Equals(cellContent)|| "Functions_Group_ID".Equals(cellContent)
  770. ||"MIN".Equals(cellContent)||"MAX".Equals(cellContent))
  771. {
  772. return true;
  773. }
  774. }
  775. else {
  776. return true;
  777. }
  778. }
  779. return false;
  780. }
  781. private static Dictionary<Int32, Dictionary<Int32, String>> readExcel(string file, string sheetName)
  782. {
  783. Dictionary<Int32, Dictionary<Int32, String>> result = new Dictionary<Int32, Dictionary<Int32, String>>();
  784. using (FileStream fp = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  785. {
  786. var book = new HSSFWorkbook(fp);
  787. for (int sheetNum = 0; sheetNum < book.NumberOfSheets; sheetNum++)
  788. {
  789. var sheet = book.GetSheetAt(sheetNum);
  790. if (sheetName.Equals(sheet.SheetName))
  791. {
  792. if (Settings.Localdebug)
  793. {
  794. Logger.Log("Received:" + sheet.SheetName);
  795. }
  796. else {
  797. Console.WriteLine("Received:" + sheet.SheetName);
  798. }
  799. if (sheet.FirstRowNum < 0 || sheet.FirstRowNum >= sheet.LastRowNum) continue;
  800. for (var rowNum = sheet.FirstRowNum; rowNum <= sheet.LastRowNum; rowNum++)
  801. {
  802. try
  803. {
  804. var rowContent = sheet.GetRow(rowNum);
  805. result.Add(rowNum, new Dictionary<Int32, String>());
  806. if (rowContent != null) {
  807. if (rowContent.FirstCellNum < 0 || rowContent.FirstCellNum >= rowContent.LastCellNum || rowContent == null) continue;
  808. for (var colNum = rowContent.FirstCellNum; colNum <= rowContent.LastCellNum; colNum++)
  809. {
  810. try
  811. {
  812. DataFormatter formatter = new DataFormatter();
  813. String cellContent = formatter.FormatCellValue(sheet.GetRow(rowNum).GetCell(colNum));
  814. //var cellContent = rowContent.GetCell(colNum);
  815. if (CheckCellFormat(sheetName, (int)rowNum, (int)colNum, cellContent))
  816. {
  817. result[rowNum].Add(colNum, cellContent);
  818. if (Settings.Localdebug) {
  819. Logger.Log("(" + (rowNum + 1) + "," + (colNum + 1) + ")=" + cellContent);
  820. }
  821. }
  822. else
  823. {
  824. Logger.Error("DataFormatterError_rowNum_In_Pointlist :" + (rowNum + 1) + ", colNum: " + (colNum + 1) + ", EMsg: " + cellContent.ToString());
  825. }
  826. }
  827. catch (Exception exp)
  828. {
  829. if (Settings.Localdebug)
  830. {
  831. Logger.Error("DataFormatterError_rowNum:" + (rowNum + 1) + ", colNum: " + (colNum + 1) + ", EMsg: " + exp.ToString());
  832. }
  833. }
  834. }
  835. }
  836. }
  837. catch (Exception exp)
  838. {
  839. }
  840. }
  841. }
  842. }
  843. }
  844. return result;
  845. }
  846. private static void LoadSettingFromXML(string file)
  847. {
  848. XmlDocument xml = new XmlDocument();
  849. xml.Load(file);
  850. XmlNodeList nodeList;
  851. //RunMode
  852. nodeList = xml.SelectNodes("/root/RunMode");
  853. foreach (XmlNode item in nodeList)
  854. {
  855. RunMode = item.InnerXml;
  856. }
  857. //BreakPoint
  858. nodeList = xml.SelectNodes("/root/BreakPoint");
  859. foreach (XmlNode item in nodeList)
  860. {
  861. BreakPoint = item.InnerXml;
  862. }
  863. //StorageClass
  864. nodeList = xml.SelectNodes("/root/StorageClass");
  865. foreach (XmlNode item in nodeList)
  866. {
  867. StorageClass = item.InnerXml;
  868. }
  869. //StoragePath
  870. nodeList = xml.SelectNodes("/root/StoragePath");
  871. foreach (XmlNode item in nodeList)
  872. {
  873. StoragePath = item.InnerXml;
  874. }
  875. //PointsFrom
  876. nodeList = xml.SelectNodes("/root/PointsFrom");
  877. foreach (XmlNode item in nodeList)
  878. {
  879. PointsFrom = item.InnerXml;
  880. }
  881. //IntervalType
  882. nodeList = xml.SelectNodes("/root/IntervalType");
  883. foreach (XmlNode item in nodeList)
  884. {
  885. IntervalType = item.InnerXml;
  886. }
  887. //CollectInterval
  888. nodeList = xml.SelectNodes("/root/CollectInterval");
  889. foreach (XmlNode item in nodeList)
  890. {
  891. CollectInterval = item.InnerXml;
  892. }
  893. //SendCount
  894. nodeList = xml.SelectNodes("/root/SendCount");
  895. foreach (XmlNode item in nodeList)
  896. {
  897. SendCount = int.Parse(item.InnerXml);
  898. }
  899. //SendInterval
  900. nodeList = xml.SelectNodes("/root/SendInterval");
  901. foreach (XmlNode item in nodeList)
  902. {
  903. SendInterval = item.InnerXml;
  904. }
  905. //HandleDataThread
  906. nodeList = xml.SelectNodes("/root/HandleDataThread");
  907. foreach (XmlNode item in nodeList)
  908. {
  909. HandleDataThread = int.Parse(item.InnerXml);
  910. }
  911. //BuildingQaurry
  912. nodeList = xml.SelectNodes("/root/BuildingQaurry");
  913. foreach (XmlNode item in nodeList)
  914. {
  915. BuildingQaurry = item.InnerXml;
  916. }
  917. //BuildingControl
  918. nodeList = xml.SelectNodes("/root/BuildingControl");
  919. foreach (XmlNode item in nodeList)
  920. {
  921. BuildingControl = item.InnerXml;
  922. }
  923. //WaitingTimeControl
  924. nodeList = xml.SelectNodes("/root/WaitingTimeControl");
  925. foreach (XmlNode item in nodeList)
  926. {
  927. WaitingTimeControl = item.InnerXml;
  928. }
  929. //NodeMac
  930. nodeList = xml.SelectNodes("/root/NodeMac");
  931. foreach (XmlNode item in nodeList)
  932. {
  933. NodeMac = item.InnerXml;
  934. }
  935. //ReportVersion
  936. nodeList = xml.SelectNodes("/root/ReportVersion");
  937. foreach (XmlNode item in nodeList)
  938. {
  939. ReportVersion = item.InnerXml;
  940. }
  941. //UploadList
  942. nodeList = xml.SelectNodes("/root/UploadList/Upload");
  943. foreach (XmlNode item in nodeList)
  944. {
  945. XmlNodeList nodes;
  946. nodes = item.SelectNodes("IP");
  947. foreach (XmlNode n in nodes)
  948. {
  949. LocalUdpIP = n.InnerXml;
  950. }
  951. nodes = item.SelectNodes("Port");
  952. foreach (XmlNode n in nodes)
  953. {
  954. LocalUdpPort = int.Parse(n.InnerXml);
  955. }
  956. nodes = item.SelectNodes("ServerIP");
  957. foreach (XmlNode n in nodes)
  958. {
  959. RemoteUdpIP = n.InnerXml;
  960. }
  961. nodes = item.SelectNodes("ServerPort");
  962. foreach (XmlNode n in nodes)
  963. {
  964. RemoteUdpPort = int.Parse(n.InnerXml);
  965. }
  966. }
  967. }
  968. static void BeginHeartBeat()
  969. {
  970. var heartBeatInterval = Settings.HeartBeatInterval;
  971. while (true)
  972. {
  973. StringBuilder sb = new StringBuilder();
  974. Thread.Sleep(heartBeatInterval);
  975. foreach (string building in Meter_Building.Values)
  976. {
  977. sb.AppendLine(SendUdpConn(building, GetCurrentUdpId()));
  978. break;
  979. }
  980. Thread.Sleep(1000);
  981. sb = new StringBuilder();
  982. foreach (string building in Meter_Building.Values)
  983. {
  984. sb.AppendLine(SendUdpHeart(building, GetCurrentUdpId()));
  985. break;
  986. }
  987. Logger.Log(" ^ Heart Beat ^ " + GetHeartBeatIndex());
  988. }
  989. }
  990. static void InitBacnet_client()
  991. {
  992. try
  993. {
  994. // Bacnet_client = new BacnetClient(new BacnetIpUdpProtocolTransport(Settings.LocalBacPort, false));
  995. Bacnet_client = new BacnetClient(new BacnetIpUdpProtocolTransport(LocalBacPort, false, false, 1472, LocalBacIP));
  996. Bacnet_client.OnIam -= new BacnetClient.IamHandler(handler_OnIam);
  997. Bacnet_client.OnIam += new BacnetClient.IamHandler(handler_OnIam);
  998. // Bacnet_client.Iam(999999);
  999. Bacnet_client.Start();
  1000. Bacnet_client.WhoIs();
  1001. //List<string> iplist = new List<string>();
  1002. //if (Settings.RollCall)
  1003. //{
  1004. // foreach (var list in Collector_Device_Point)
  1005. // {
  1006. // foreach (var list1 in list.Value)
  1007. // {
  1008. // Console.WriteLine(list1);
  1009. // //String ip = list1.ToString().Split(":")[0];
  1010. // //ip = ip.Split("[")[1];
  1011. // //iplist.Add(ip);
  1012. // }
  1013. // }
  1014. // //var ipdist = (from li in iplist select li).Distinct();
  1015. // //foreach (var ip in ipdist)
  1016. // //{
  1017. // // Console.WriteLine(ip);
  1018. // // Bacnet_client.RemoteWhoIs(ip);
  1019. // //}
  1020. //}
  1021. //else {
  1022. // foreach (var list in Collector_Device_Point)
  1023. // {
  1024. // foreach (var list1 in list.Value)
  1025. // {
  1026. // Console.WriteLine(list1);
  1027. // String listStr = list1.ToString().Split(",")[0];
  1028. // listStr = listStr.Split("[")[1];
  1029. // String[] listinfo = listStr.Split("-");
  1030. // for (int i = 0; i < listinfo.Count(); i++)
  1031. // {
  1032. // //Console.WriteLine(listinfo[1]);
  1033. // if (IsNumStr(listinfo[1]))
  1034. // {
  1035. // iplist.Add(listinfo[1]);
  1036. // }
  1037. // }
  1038. // //var targetObjId = new BacnetObjectId(BacnetObjectTypes.OBJECT_DEVICE, (uint)10);
  1039. // //var targetBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, "192.168.1.1");
  1040. // //var rez = Bacnet_client.ReadPropertyAsync(targetBacnetAddress, targetObjId, BacnetPropertyIds.PROP_OBJECT_LIST);
  1041. // //rez.ContinueWith((sender) =>
  1042. // //{
  1043. // // var result = sender.Result;
  1044. // // foreach (var item in result)
  1045. // // {
  1046. // // //do stuff
  1047. // // Console.WriteLine(item.Value);
  1048. // // }
  1049. // //});
  1050. // //String ip = list1.ToString().Split(":")[0];
  1051. // //ip = ip.Split("[")[1];
  1052. // //iplist.Add(ip);
  1053. // }
  1054. // }
  1055. // var ipdist = (from li in iplist select li).Distinct();
  1056. // iplist = ipdist.OrderBy(s => int.Parse(Regex.Match(s, @"^\d+$").Value)).ToList();
  1057. // foreach (var i in iplist)
  1058. // {
  1059. // // Console.WriteLine(i);
  1060. // Bacnet_client.WhoIs(int.Parse(i),int.Parse(i));
  1061. // Thread.Sleep(100);
  1062. // }
  1063. //}
  1064. }
  1065. catch (Exception exp)
  1066. {
  1067. Logger.Error("InitBacnet_client: ", exp);
  1068. }
  1069. }
  1070. static void InitUdp_Client()
  1071. {
  1072. try
  1073. {
  1074. //本机节点
  1075. // var LocalUdpPort = Settings.LocalUdpPort;
  1076. IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(LocalUdpIP), LocalUdpPort);
  1077. // 远程节点
  1078. //var RemoteUdpIP = IPAddress.Parse(Settings.RemoteUdpIP);
  1079. //var RemoteUdpPort = Settings.RemoteUdpPort;
  1080. IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(RemoteUdpIP), RemoteUdpPort);
  1081. Udp_Client = new AsyncUdpClient(localEP, remoteEP, false, new NullLogger());
  1082. //Receive
  1083. new Thread(new ThreadStart(() =>
  1084. {
  1085. while (true)
  1086. {
  1087. var str = Udp_Client.PopReceive();
  1088. if (!string.IsNullOrEmpty(str))
  1089. {
  1090. StringBuilder sb = new StringBuilder();
  1091. Logger.Log("Receive UdpCallback:" + str);
  1092. string[] rList = Regex.Split(System.Convert.ToString(str), ";", RegexOptions.IgnoreCase);
  1093. if ("pointcount".Equals(rList[2]))
  1094. {
  1095. sb = pointcount(rList);
  1096. }
  1097. else if ("pointlist".Equals(rList[2]))
  1098. {
  1099. sb = pointlist(rList);
  1100. }
  1101. else if ("senddownread".Equals(rList[2]))
  1102. {
  1103. sb = senddownread(rList);
  1104. }
  1105. else if ("senddownset".Equals(rList[2]))
  1106. {
  1107. sb = senddownset(rList);
  1108. //BacnetObjectId oid = new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_INPUT, 0);
  1109. //BacnetAddress adr;
  1110. //BacnetPropertyIds propertyId = BacnetPropertyIds.PROP_PRESENT_VALUE;
  1111. //BacnetValue[] NoScalarValue = {new BacnetValue(Convert.ToSingle(1))};
  1112. //byte invokeId = 0;
  1113. //foreach (BacDevice device in DevicesList)
  1114. //{
  1115. // bool result = Bacnet_client.WritePropertyRequest(device.Address, oid, propertyId, NoScalarValue, invokeId);
  1116. //}
  1117. }
  1118. else if ("reportack".Equals(rList[2]) || "reportaddtionack".Equals(rList[2]))
  1119. {
  1120. }
  1121. else if ("connectack".Equals(rList[2]) || "heartack".Equals(rList[2]))
  1122. {
  1123. }
  1124. else
  1125. {
  1126. }
  1127. Console.WriteLine("Slength: " + sb.Length + ",MSg: " + sb.ToString());
  1128. if (sb.Length > 0)
  1129. {
  1130. Udp_Client.PushSend(sb.ToString());
  1131. }
  1132. }
  1133. Thread.Sleep(100);
  1134. }
  1135. })).Start();
  1136. Udp_Client.Start();
  1137. }
  1138. catch (Exception exp)
  1139. {
  1140. Logger.Error("InitUdp_Client: ", exp);
  1141. }
  1142. }
  1143. private static StringBuilder senddownset(string[] rList)
  1144. {
  1145. //1101070037;1;senddownset;;123;1001;11;3.1
  1146. StringBuilder sb = new StringBuilder();
  1147. string buildingSign = rList[0];
  1148. string meterSign = rList[5];
  1149. string funcID = rList[6];
  1150. string dataSet = rList[7];
  1151. Point point = Meter_Point[meterSign];
  1152. bool unanimously = false;
  1153. if (!RecordAddress.ContainsKey(buildingSign + "-" + meterSign + "-" + funcID))
  1154. {
  1155. return null;
  1156. }
  1157. int address = RecordAddress[buildingSign + "-" + meterSign + "-" + funcID];
  1158. if (double.Parse(RecordList[address].data).Equals(double.Parse(dataSet)))
  1159. {
  1160. unanimously = true;
  1161. }
  1162. {
  1163. if (unanimously)
  1164. {
  1165. if (Settings.Localdebug)
  1166. {
  1167. Logger.Log("Unanimously!" + " Buildingsign:"
  1168. + buildingSign + ", Meter:"
  1169. + meterSign + ", FunctionID:"
  1170. + funcID + ", Data:"
  1171. + RecordList[address].receivetime + " "
  1172. + RecordList[address].data + ", DataSet:" + dataSet);
  1173. sb.AppendWithSplit(rList[0]);
  1174. sb.AppendWithSplit(rList[1]);
  1175. sb.AppendWithSplit("senddownsetack");
  1176. sb.AppendWithSplit((DateTime.Now.ToString(@"yyyyMMddHHmmss")));
  1177. sb.AppendWithSplit(rList[4]);
  1178. sb.AppendWithSplit(rList[5]);
  1179. sb.AppendWithSplit(rList[6]);
  1180. sb.AppendWithSplit("success");
  1181. //1101070037;1;senddownsetack;20010203040506;123;1001;11;success
  1182. }
  1183. else {
  1184. Console.WriteLine("Unanimously!" + " Buildingsign:"
  1185. + buildingSign + ", Meter:"
  1186. + meterSign + ", FunctionID:"
  1187. + funcID + ", Data:"
  1188. + RecordList[address].receivetime + " "
  1189. + RecordList[address].data + ", DataSet:" + dataSet);
  1190. sb.AppendWithSplit(rList[0]);
  1191. sb.AppendWithSplit(rList[1]);
  1192. sb.AppendWithSplit("senddownsetack");
  1193. sb.AppendWithSplit((DateTime.Now.ToString(@"yyyyMMddHHmmss")));
  1194. sb.AppendWithSplit(rList[4]);
  1195. sb.AppendWithSplit(rList[5]);
  1196. sb.AppendWithSplit(rList[6]);
  1197. sb.AppendWithSplit("success");
  1198. }
  1199. }
  1200. else
  1201. {
  1202. Collector c = Meter_Collector[meterSign];
  1203. if (c != null)
  1204. {
  1205. bool result = false;
  1206. BacnetObjectId oid = new BacnetObjectId(getObjectType(point.type), uint.Parse(point.instanceNumber));
  1207. //BacnetAddress adr;
  1208. BacnetPropertyIds propertyId = BacnetPropertyIds.PROP_PRESENT_VALUE;
  1209. BacnetValue[] NoScalarValue = { new BacnetValue(Convert.ToSingle(double.Parse(dataSet))) };
  1210. byte invokeId = 0;
  1211. foreach (BacDevice device in DevicesList)
  1212. {
  1213. if (Convert.ToString(device.Address).Equals(c.IP + ":" + c.Port))
  1214. {
  1215. if (uint.Parse(Convert.ToString(device.DeviceId)).Equals(uint.Parse(point.deviceId)))
  1216. {
  1217. result = Bacnet_client.WritePropertyRequest(device.Address, oid, propertyId, NoScalarValue, invokeId);
  1218. break;
  1219. }
  1220. }
  1221. }
  1222. if (result)
  1223. {
  1224. sb.AppendWithSplit(rList[0]);
  1225. sb.AppendWithSplit(rList[1]);
  1226. sb.AppendWithSplit("senddownsetack");
  1227. sb.AppendWithSplit((DateTime.Now.ToString(@"yyyyMMddHHmmss")));
  1228. sb.AppendWithSplit(rList[4]);
  1229. sb.AppendWithSplit(rList[5]);
  1230. sb.AppendWithSplit(rList[6]);
  1231. sb.AppendWithSplit("success");
  1232. }
  1233. else
  1234. {
  1235. sb.AppendWithSplit(rList[0]);
  1236. sb.AppendWithSplit(rList[1]);
  1237. sb.AppendWithSplit("senddownsetack");
  1238. sb.AppendWithSplit((DateTime.Now.ToString(@"yyyyMMddHHmmss")));
  1239. sb.AppendWithSplit(rList[4]);
  1240. sb.AppendWithSplit(rList[5]);
  1241. sb.AppendWithSplit(rList[6]);
  1242. sb.AppendWithSplit("fail:error");
  1243. }
  1244. }
  1245. }
  1246. }
  1247. return sb;
  1248. }
  1249. private static BacnetObjectTypes getObjectType(String type)
  1250. {
  1251. // TODO Auto-generated method stub
  1252. if ("analogInput".Equals(type))
  1253. {
  1254. return BacnetObjectTypes.OBJECT_ANALOG_INPUT;
  1255. }
  1256. else if ("analogOutput".Equals(type))
  1257. {
  1258. return BacnetObjectTypes.OBJECT_ANALOG_OUTPUT;
  1259. }
  1260. else if ("analogValue".Equals(type))
  1261. {
  1262. return BacnetObjectTypes.OBJECT_ANALOG_VALUE;
  1263. }
  1264. else if ("binaryInput".Equals(type))
  1265. {
  1266. return BacnetObjectTypes.OBJECT_BINARY_INPUT;
  1267. }
  1268. else if ("binaryOutput".Equals(type))
  1269. {
  1270. return BacnetObjectTypes.OBJECT_BINARY_OUTPUT;
  1271. }
  1272. else if ("binaryValue".Equals(type))
  1273. {
  1274. return BacnetObjectTypes.OBJECT_BINARY_VALUE;
  1275. }
  1276. else if ("multiStateInput".Equals(type))
  1277. {
  1278. return BacnetObjectTypes.OBJECT_MULTI_STATE_INPUT;
  1279. }
  1280. else if ("multiStateOutput".Equals(type))
  1281. {
  1282. return BacnetObjectTypes.OBJECT_MULTI_STATE_OUTPUT;
  1283. }
  1284. else if ("multiStateValue".Equals(type))
  1285. {
  1286. return BacnetObjectTypes.OBJECT_MULTI_STATE_VALUE;
  1287. }
  1288. return BacnetObjectTypes.OBJECT_ANALOG_INPUT;
  1289. }
  1290. private static StringBuilder senddownread(string[] list)
  1291. {
  1292. // TODO Auto-generated method stub
  1293. StringBuilder sb = new StringBuilder();
  1294. Record record = new Record();
  1295. record = getCacheData(list);
  1296. sb.Append(list[0]).Append(";").Append(list[1]).Append(";").Append("senddownreadack").Append(";")
  1297. .Append(record.receivetime).Append(";").Append(list[4]).Append(";")
  1298. .Append(record.meterSign).Append(";").Append(record.funcID).Append(";").Append(record.data).Append(";");
  1299. return sb;
  1300. }
  1301. private static Record getCacheData(String[] list)
  1302. {
  1303. // TODO Auto-generated method stub
  1304. Record record = new Record();
  1305. if (RecordAddress.ContainsKey(list[0] + "-" + list[5] + "-" + list[6]))
  1306. {
  1307. int address = RecordAddress[(list[0] + "-" + list[5] + "-" + list[6])];
  1308. record = RecordList[(address)];
  1309. // Constant.info("get pointread by address !");
  1310. }
  1311. else
  1312. {
  1313. foreach (Record r in RecordList)
  1314. {
  1315. if (list[0].Equals(r.buildingSign) && list[5].Equals(r.meterSign)
  1316. && int.Parse(list[6]).Equals(r.funcID))
  1317. {
  1318. record = r;
  1319. // Constant.info("get pointread by for circle !");
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. return record;
  1325. }
  1326. private static StringBuilder pointlist(String[] list)
  1327. {
  1328. // TODO Auto-generated method stub
  1329. int no = 0;
  1330. int count = 0;
  1331. int from = int.Parse(list[5]) * (int.Parse(list[7]) - 1);
  1332. int to = int.Parse(list[5]) * (int.Parse(list[7]));
  1333. StringBuilder sb = new StringBuilder();
  1334. sb.Append(list[0]).Append(";").Append(list[1]).Append(";").Append("pointlistack").Append(";;").Append(list[4])
  1335. .Append(";").Append(list[5]).Append(";").Append(list[6]).Append(";").Append(list[7]).Append(";");
  1336. if (to > getCount(list[0]))
  1337. {
  1338. count = getCount(list[0]) - from;
  1339. }
  1340. else
  1341. {
  1342. count = to - from;
  1343. }
  1344. sb.Append(count).Append(";");
  1345. foreach (var deviceList in Collector_Device_Point)
  1346. {
  1347. foreach (var device in deviceList.Value)
  1348. {
  1349. if (list[0].Equals(device.Value.buildingSign))
  1350. {
  1351. foreach (Function function in device.Value.functionList)
  1352. {
  1353. no++;
  1354. if (no < from)
  1355. {
  1356. continue;
  1357. }
  1358. if (no > to)
  1359. {
  1360. continue;
  1361. }
  1362. sb.Append(device.Value.meterSign).Append(";").Append(function.functionID).Append(";");
  1363. }
  1364. }
  1365. }
  1366. }
  1367. return sb;
  1368. }
  1369. private static StringBuilder pointcount(String[] list)
  1370. {
  1371. // TODO Auto-generated method stub
  1372. StringBuilder sb = new StringBuilder();
  1373. sb.Append(list[0]).Append(";").Append(list[1]).Append(";").Append("pointcountack").Append(";;").Append(list[4])
  1374. .Append(";").Append(getCount(list[0])).Append(";");
  1375. return sb;
  1376. }
  1377. private static int getCount(String buildingSign)
  1378. {
  1379. // TODO Auto-generated method stub
  1380. int count = 0;
  1381. foreach (var deviceList in Collector_Device_Point)
  1382. {
  1383. foreach (var device in deviceList.Value)
  1384. {
  1385. if (buildingSign.Equals(device.Value.buildingSign))
  1386. {
  1387. foreach (Function function in device.Value.functionList)
  1388. {
  1389. count++;
  1390. }
  1391. }
  1392. }
  1393. }
  1394. return count;
  1395. }
  1396. //发现设备
  1397. static bool IsDetecteDeviceFinished = false;
  1398. static void handler_OnIam(BacnetClient sender, BacnetAddress adr, uint deviceId, uint maxAPDU,
  1399. BacnetSegmentations segmentation, ushort vendorId)
  1400. {
  1401. try
  1402. {
  1403. if (IsDetecteDeviceFinished) return;
  1404. if (DevicesList == null) DevicesList = new List<BacDevice>();
  1405. lock (DevicesList)
  1406. {
  1407. if (DevicesList.Any(x => x.DeviceId == deviceId)) return;
  1408. var device = new BacDevice(adr, deviceId);
  1409. string ip = Regex.Split(System.Convert.ToString(device.Address), ":", RegexOptions.IgnoreCase)[0];
  1410. Console.WriteLine("Chack_ip: " + ip + ", " + Collector_Device_Point.ContainsKey(Convert.ToString(ip)));
  1411. if (!Collector_Device_Point.ContainsKey(Convert.ToString(ip)))
  1412. {
  1413. return;
  1414. }
  1415. if (Settings.Localdebug)
  1416. {
  1417. Logger.Log(@"Detect Device: " + ip + " " + deviceId);
  1418. }
  1419. else {
  1420. Console.WriteLine(@"Detect Device: " + ip + " " + deviceId);
  1421. }
  1422. device.LoadProperties(device.DeviceId, Collector_Device_Point[Convert.ToString(ip)]);
  1423. //device.LoadPropertiesFromExcel(Path.Combine(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + Constants.AimExcelDir, "" + deviceId + ".xls"));
  1424. DevicesList.Add(device);
  1425. }
  1426. }
  1427. catch (Exception exp)
  1428. {
  1429. Logger.Error("handler_OnIam", exp);
  1430. //InitBacnet_client();
  1431. //InitUdp_Client();
  1432. }
  1433. }
  1434. static void LoadSettingFromExcel(string file)
  1435. {
  1436. try
  1437. {
  1438. if (!File.Exists(file)) return;
  1439. using (FileStream fp = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  1440. {
  1441. var book = new HSSFWorkbook(fp);
  1442. var sheet = book.GetSheetAt(0);
  1443. var rowContent = sheet.GetRow(1);
  1444. LocalBacIP = rowContent.GetCell(0).ToString();
  1445. LocalBacPort = Convert.ToInt32(rowContent.GetCell(1).ToString());
  1446. LocalUdpIP = rowContent.GetCell(2).ToString();
  1447. LocalUdpPort = Convert.ToInt32(rowContent.GetCell(3).ToString());
  1448. RemoteUdpIP = rowContent.GetCell(4).ToString();
  1449. RemoteUdpPort = Convert.ToInt32(rowContent.GetCell(5).ToString());
  1450. }
  1451. }
  1452. catch (Exception exp)
  1453. {
  1454. Logger.Error("BacDevice.LoadPropertiesFromExcel: ", exp);
  1455. }
  1456. }
  1457. static void ThreadProc(Object device)
  1458. {
  1459. ScanBac((BacDevice)device);
  1460. }
  1461. //扫点
  1462. static void BeginScanBac()
  1463. {
  1464. try
  1465. {
  1466. Logger.Log("BeginScanBac");
  1467. IsDetecteDeviceFinished = true;
  1468. if (Settings.RollCall) {
  1469. InitBacnet_clientRollCall();
  1470. Thread.Sleep(Settings.WaitTime);
  1471. if (DevicesListScan == null) return;
  1472. } else {
  1473. InitBacnet_client();
  1474. Thread.Sleep(Settings.WaitTime);
  1475. if (DevicesList == null) return;
  1476. }
  1477. while (true)
  1478. {
  1479. DevicesListScan = DevicesListScan.Where(x => x != null).OrderBy(x => x.DeviceId).ToList();
  1480. foreach (var deviceScan in DevicesListScan) {
  1481. if (DevicesList == null) {
  1482. DevicesList = DevicesListScan;
  1483. }
  1484. if (!DevicesList.Contains(deviceScan))
  1485. {
  1486. DevicesList.Add(deviceScan);
  1487. }
  1488. }
  1489. DevicesList = DevicesList.Where(x => x != null).OrderBy(x => x.DeviceId).ToList();
  1490. foreach (var device in DevicesList)
  1491. {
  1492. ThreadPool.QueueUserWorkItem(o=> ThreadProc(device));
  1493. }
  1494. try
  1495. {
  1496. Thread.Sleep(1000 * Settings.AcquisitionFrequency);
  1497. }
  1498. catch (Exception exp)
  1499. {
  1500. }
  1501. }
  1502. }
  1503. catch (Exception exp)
  1504. {
  1505. Logger.Error("BeginScanBac_Error", exp);
  1506. //BeginScanBac();
  1507. }
  1508. }
  1509. //扫点轮次
  1510. static int ScanIndex = 0;
  1511. static void ScanBac(BacDevice device)
  1512. {
  1513. if (device == null || device.Address == null) return;
  1514. StringBuilder sb = new StringBuilder();
  1515. try
  1516. {
  1517. if (Settings.Localdebug)
  1518. {
  1519. Logger.Log(" @DeviceScan " + device.Address + "-" + device.DeviceId + " Scan "
  1520. //+ device.ScanIndex
  1521. );
  1522. }
  1523. else {
  1524. Console.WriteLine(" @DeviceScan " + device.Address + "-" + device.DeviceId + " Scan "
  1525. //+ device.ScanIndex
  1526. );
  1527. }
  1528. var adr = device.Address;
  1529. var deviceid = device.DeviceId;
  1530. List<BacnetPropertyReference> rList = new List<BacnetPropertyReference>();
  1531. rList.Add(new BacnetPropertyReference((uint)BacnetPropertyIds.PROP_PRESENT_VALUE, uint.MaxValue));
  1532. var group = device.Properties.Partition(Settings.BacSplitSize);
  1533. foreach (var subGroup in group)
  1534. {
  1535. try
  1536. {
  1537. if (deviceid == 1) continue;
  1538. List<BacnetReadAccessSpecification> properties =
  1539. subGroup.Select(pro => new BacnetReadAccessSpecification(pro.ObjectId, rList)).ToList();
  1540. IList<BacnetReadAccessResult> lstAccessRst;
  1541. //foreach (var item in properties) {
  1542. // Logger.Error("Input_Address: " + adr + ",properties:" + item.propertyReferences.ToString());
  1543. //}
  1544. var bRst = Bacnet_client.ReadPropertyMultipleRequest(adr, properties, out lstAccessRst, GetCurrentInvokeId());
  1545. Thread.Sleep(15 * Settings.AcquisitionFrequency);
  1546. if (!bRst) continue;
  1547. if (lstAccessRst == null || lstAccessRst.Count == 0) continue;
  1548. //sb.AppendLine("=== properties.Count:" + properties.Count + " ,lstAccessRst.Count: " + lstAccessRst.Count);
  1549. foreach (var aRst in lstAccessRst)
  1550. {
  1551. var bPValue = aRst.values.First();
  1552. if (bPValue.value == null || bPValue.value.Count == 0) continue;
  1553. var bValue = bPValue.value.First();
  1554. var strBValue = "" + bValue.Value;
  1555. if (Settings.Localdebug) {
  1556. Logger.Log(" @ReceiveMsg: " + device.Address + "-" + device.DeviceId + "-" + getType(aRst.objectIdentifier.type) + "-" + aRst.objectIdentifier.instance + " " + strBValue);
  1557. }
  1558. //string addr = System.Convert.ToString(device.Address);
  1559. //string[] sArray = Regex.Split(addr, ":", RegexOptions.IgnoreCase);
  1560. string ip = Regex.Split(System.Convert.ToString(device.Address), ":", RegexOptions.IgnoreCase)[0];
  1561. //Logger.Log("ip: " + ip);
  1562. Console.WriteLine("ip: " + ip);
  1563. Console.WriteLine("RD1: " + !Collector_Device_Point.ContainsKey(ip));
  1564. Console.WriteLine("RD2: " + !Collector_Device_Point[ip].ContainsKey(device.Address + "-" + device.DeviceId + "-" + getType(aRst.objectIdentifier.type) + "-" + aRst.objectIdentifier.instance));
  1565. if (!Collector_Device_Point.ContainsKey(ip) || !Collector_Device_Point[ip].ContainsKey(device.Address + "-" + device.DeviceId + "-" + getType(aRst.objectIdentifier.type) + "-" + aRst.objectIdentifier.instance))
  1566. {
  1567. continue;
  1568. }
  1569. Console.WriteLine("================");
  1570. Point point = Collector_Device_Point[ip][device.Address + "-" + device.DeviceId + "-" + getType(aRst.objectIdentifier.type) + "-" + aRst.objectIdentifier.instance];
  1571. Console.WriteLine("RD3:" + point.ToString());
  1572. // var pro = device.Properties.FirstOrDefault(x => x.ObjectId == aRst.objectIdentifier);
  1573. // try { } catch (Exception e) { }
  1574. BacProperty pro = device.Properties.FirstOrDefault(x => x.ObjectId == aRst.objectIdentifier);
  1575. // Console.WriteLine("RD4:" + pro.ToString());
  1576. if (pro == null) continue;
  1577. //值没变,忽略
  1578. //if (string.Equals(strBValue, pro.PROP_PRESENT_VALUE))
  1579. //{
  1580. // // sb.AppendLine($"值没变,忽略 {pro.PROP_DESCRIPTION} : { strBValue}");
  1581. // continue;
  1582. //}
  1583. // var preValue = pro.PROP_PRESENT_VALUE;
  1584. var preValue = strBValue;
  1585. //Logger.Log("RD5_0_strBValue:" + strBValue);
  1586. // pro.PROP_PRESENT_VALUE = strBValue;
  1587. //因为霍尼韦尔的误报,消防报警后面跟的故障报警暂时不报(临时)
  1588. //if (string.Equals(strBValue, "3", StringComparison.CurrentCultureIgnoreCase) &&
  1589. // string.Equals(preValue, "2", StringComparison.CurrentCultureIgnoreCase))
  1590. //{
  1591. // //sb.AppendLine("因为霍尼韦尔的误报,消防报警后面跟的故障报警暂时不报(临时)");
  1592. // continue;
  1593. //}
  1594. //if (!Settings.IgnoreFirstValue || device.ScanIndex != 0)//初始值也转发
  1595. // {
  1596. //sb.AppendLine(SendUdpMessage(pro, GetCurrentUdpId()));
  1597. Console.WriteLine("RD5:" + preValue.Length +","+ preValue.ToString());
  1598. if (preValue != null && preValue.Length > 0)
  1599. {
  1600. Console.WriteLine(" @ConSole_ReceiveMsg: " + device.Address + "-" + device.DeviceId + "-" + getType(aRst.objectIdentifier.type) + "-" + aRst.objectIdentifier.instance + " " + strBValue);
  1601. Thread.Sleep(Settings.AcquisitionFrequency*10);
  1602. StringBuilder pFuncid = new StringBuilder();
  1603. foreach (var funcidlsit in point.functionList) {
  1604. pFuncid.AppendWithSplit(funcidlsit.functionID);
  1605. }
  1606. var PFuncidStrArr = pFuncid.ToString().Trim().Split(";");
  1607. var PFuncidStr = PFuncidStrArr[0];
  1608. foreach (var funcT in Function_Threshold) {
  1609. Console.WriteLine("PFuncidStr: "+ PFuncidStr + " ,funcT :"+ funcT +" ,bool: "+ funcT.Trim().IndexOf(PFuncidStr.Trim()));
  1610. if (funcT.Trim().IndexOf(PFuncidStr.Trim())>-1) {
  1611. String[] funcTArr = funcT.Trim().Split(",");
  1612. Double min = Convert.ToDouble(int.Parse(funcTArr[1].Trim()));
  1613. min = min * 1.000000;
  1614. Double max = Convert.ToDouble(int.Parse(funcTArr[2].Trim()));
  1615. max = max * 1.000000;
  1616. Double pvalue = Double.Parse(preValue);
  1617. Console.WriteLine("min: " + min + " ,max: " + max + " ,pvalue: " + pvalue + " ,first: " + isequal(min, max, pvalue));
  1618. if (isequal(min, max, pvalue)) {
  1619. sb.AppendLine(SendUdpMessage(point, preValue, GetCurrentUdpId()));
  1620. }
  1621. else {
  1622. continue;
  1623. }
  1624. }
  1625. }
  1626. }
  1627. //}
  1628. //sb.AppendLine("" + pro.PROP_OBJECT_NAME + " , " + strBValue + " ; ");
  1629. }
  1630. }
  1631. catch (Exception exp)
  1632. {
  1633. if (Settings.Localdebug) {
  1634. Logger.Error("ScanBac_1 Error: " + device.Address + "-" + device.DeviceId + "-" + exp.ToString());
  1635. }
  1636. }
  1637. }
  1638. }
  1639. catch (Exception exp)
  1640. {
  1641. if (Settings.Localdebug)
  1642. {
  1643. Logger.Error("ScanBac_2 Error: " + device.Address + " " + device.DeviceId + " " + exp);
  1644. }
  1645. }
  1646. finally
  1647. {
  1648. if (Settings.Localdebug)
  1649. {
  1650. Logger.Log("finally: " + sb.ToString());
  1651. }
  1652. else {
  1653. Console.WriteLine("finally: " + sb.ToString());
  1654. }
  1655. //扫描完一轮
  1656. ScanIndex++;
  1657. if (ScanIndex == int.MaxValue) ScanIndex = 0;
  1658. //device.ScanIndex = ScanIndex;
  1659. // ScanBac(device);
  1660. }
  1661. }
  1662. private static bool isequal(object a, object b, object c)
  1663. {
  1664. if (a == null || b == null)
  1665. return (a == b);
  1666. if (a == b) {
  1667. return true;
  1668. }
  1669. double da, db, dc;
  1670. if (Double.TryParse(a.ToString(), out da) && Double.TryParse(b.ToString(), out db)&& Double.TryParse(c.ToString(), out dc))
  1671. return DoubleEquals(da, db, dc);
  1672. return false;
  1673. }
  1674. public static bool DoubleEquals(double value1, double value2,double value3)
  1675. {
  1676. //双精度误差
  1677. var DOUBLE_DELTA = 1E-6;
  1678. //bool f = Math.Abs(value2 - value1) > DOUBLE_DELTA;
  1679. bool f= (value3.CompareTo(value1)> DOUBLE_DELTA ? true : false) && (value3.CompareTo(value2)< DOUBLE_DELTA ? true: false) ;
  1680. return f;
  1681. }
  1682. public static bool DoubleEqualsBak(double value1, double value2)
  1683. {
  1684. //双精度误差
  1685. var DOUBLE_DELTA = 1E-6;
  1686. return value1 == value2 || Math.Abs(value1 - value2) < DOUBLE_DELTA;
  1687. }
  1688. static String getType(BacnetObjectTypes objectType)
  1689. {
  1690. if (objectType.Equals(BacnetObjectTypes.OBJECT_ANALOG_INPUT))
  1691. {
  1692. return "analogInput";
  1693. }
  1694. else if (objectType.Equals(BacnetObjectTypes.OBJECT_ANALOG_OUTPUT))
  1695. {
  1696. return "analogOutput";
  1697. }
  1698. else if (objectType.Equals(BacnetObjectTypes.OBJECT_ANALOG_VALUE))
  1699. {
  1700. return "analogValue";
  1701. }
  1702. else if (objectType.Equals(BacnetObjectTypes.OBJECT_BINARY_INPUT))
  1703. {
  1704. return "binaryInput";
  1705. }
  1706. else if (objectType.Equals(BacnetObjectTypes.OBJECT_BINARY_OUTPUT))
  1707. {
  1708. return "binaryOutput";
  1709. }
  1710. else if (objectType.Equals(BacnetObjectTypes.OBJECT_BINARY_VALUE))
  1711. {
  1712. return "binaryValue";
  1713. }
  1714. else if (objectType.Equals(BacnetObjectTypes.OBJECT_MULTI_STATE_INPUT))
  1715. {
  1716. return "multiStateInput";
  1717. }
  1718. else if (objectType.Equals(BacnetObjectTypes.OBJECT_MULTI_STATE_OUTPUT))
  1719. {
  1720. return "multiStateOutput";
  1721. }
  1722. else if (objectType.Equals(BacnetObjectTypes.OBJECT_MULTI_STATE_VALUE))
  1723. {
  1724. return "multiStateValue";
  1725. }
  1726. return null;
  1727. }
  1728. //上传UDP
  1729. static string SendUdpMessage( BacProperty pro, int udpid = 0)
  1730. {
  1731. try
  1732. {
  1733. if (Udp_Client == null || string.IsNullOrEmpty(Settings.BuildingSign) || pro == null) return string.Empty;
  1734. StringBuilder sb = new StringBuilder();
  1735. sb.AppendWithSplit(pro.building);
  1736. sb.AppendWithSplit(Settings.Gateway);
  1737. sb.AppendWithSplit(Settings.SendType);
  1738. sb.AppendWithSplit(DateTime.Now.ToString(@"yyyyMMddHHmmss"));
  1739. sb.AppendWithSplit(udpid == 0 ? GetCurrentUdpId() : udpid);
  1740. sb.AppendWithSplit(pro.meter);
  1741. sb.AppendWithSplit(1);
  1742. sb.AppendWithSplit(pro.funcid);
  1743. sb.Append(pro.PROP_PRESENT_VALUE);
  1744. var str = sb.ToString();
  1745. // for (int i = 0; i < 5; i++)
  1746. // {
  1747. Udp_Client.PushSend(str);
  1748. Thread.Sleep(100);
  1749. // }
  1750. return "SendUdpMessage: " + str;
  1751. }
  1752. catch (Exception exp)
  1753. {
  1754. Logger.Error("SendUdpMessage", exp);
  1755. return string.Empty;
  1756. }
  1757. }
  1758. private static void handleData(string buildingSign, string meterSign, long funcID, string receivetime, string data)
  1759. {
  1760. // 已有数据更新
  1761. if (RecordAddress.ContainsKey(buildingSign + "-" + meterSign + "-" + funcID) && RecordAddress[(buildingSign + "-" + meterSign + "-" + funcID)] > 0)
  1762. {
  1763. int address = RecordAddress[(buildingSign + "-" + meterSign + "-" + funcID)];
  1764. try
  1765. {
  1766. RecordList[(address)].receivetime = (receivetime);
  1767. RecordList[(address)].data = data;
  1768. if (Settings.Localdebug)
  1769. {
  1770. Logger.Log((address + 1) + "/" + RecordList.Count + " UPDATE "
  1771. + RecordList[(address)].buildingSign + "."
  1772. + RecordList[(address)].meterSign + "." + RecordList[(address)].funcID
  1773. + ":" + receivetime + " "
  1774. + RecordList[(address)].data);
  1775. }
  1776. else {
  1777. Console.WriteLine((address + 1) + "/" + RecordList.Count + " UPDATE "
  1778. + RecordList[(address)].buildingSign + "."
  1779. + RecordList[(address)].meterSign + "." + RecordList[(address)].funcID
  1780. + ":" + receivetime + " "
  1781. + RecordList[(address)].data);
  1782. }
  1783. }
  1784. catch (Exception e)
  1785. {
  1786. if (Settings.Localdebug)
  1787. {
  1788. Logger.Error("handleData_Error_1: " + e);
  1789. }
  1790. }
  1791. }
  1792. else
  1793. {
  1794. // 新增数据并记录地址
  1795. try
  1796. {
  1797. Record record = new Record();
  1798. record.buildingSign = buildingSign;
  1799. record.meterSign = meterSign;
  1800. record.funcID = System.Convert.ToString(funcID);
  1801. record.receivetime = (receivetime);
  1802. record.data = data;
  1803. RecordAddress.Add(buildingSign + "-" + meterSign + "-" + funcID, RecordList.Count());
  1804. RecordList.Add(record);
  1805. if (Settings.Localdebug)
  1806. {
  1807. Logger.Log(" " + RecordList.Count + "/" + RecordList.Count + " ADD "
  1808. + record.buildingSign + "." + record.meterSign + "." + record.funcID + ":"
  1809. + (record.receivetime) + " " + record.data);
  1810. }
  1811. else {
  1812. Console.WriteLine(" " + RecordList.Count + "/" + RecordList.Count + " ADD "
  1813. + record.buildingSign + "." + record.meterSign + "." + record.funcID + ":"
  1814. + (record.receivetime) + " " + record.data);
  1815. }
  1816. }
  1817. catch (Exception e)
  1818. {
  1819. // TODO Auto-generated catch block
  1820. if (Settings.Localdebug)
  1821. {
  1822. Logger.Error("handleData_Error_2: " + e);
  1823. }
  1824. }
  1825. }
  1826. }
  1827. static string SendUdpMessage(Point point, string value, int udpid = 0)
  1828. {
  1829. try
  1830. {
  1831. if (Udp_Client == null || string.IsNullOrEmpty(Settings.BuildingSign) || point == null) return string.Empty;
  1832. StringBuilder sb = new StringBuilder();
  1833. string buildingSign = point.buildingSign;
  1834. string meterSign = point.meterSign;
  1835. string receivetime = DateTime.Now.ToString(@"yyyyMMddHHmmss");
  1836. sb.AppendWithSplit(buildingSign);
  1837. sb.AppendWithSplit(Settings.Gateway);
  1838. sb.AppendWithSplit(Settings.SendType);
  1839. sb.AppendWithSplit(receivetime);
  1840. sb.AppendWithSplit(udpid == 0 ? GetCurrentUdpId() : udpid);
  1841. sb.AppendWithSplit(meterSign);
  1842. sb.AppendWithSplit(point.functionList.Count);
  1843. foreach (var funcid in point.functionList)
  1844. {
  1845. sb.AppendWithSplit(funcid.functionID);
  1846. sb.Append(value);
  1847. handleData(buildingSign, meterSign, funcid.functionID, receivetime, value);
  1848. }
  1849. var str = sb.ToString();
  1850. // for (int i = 0; i < 5; i++)
  1851. // {
  1852. Udp_Client.PushSend(str);
  1853. Thread.Sleep(100);
  1854. // }
  1855. return "SendUdpMessage: " + str;
  1856. }
  1857. catch (Exception exp)
  1858. {
  1859. Logger.Error("SendUdpMessage", exp);
  1860. return string.Empty;
  1861. }
  1862. }
  1863. static string SendUdpHeart(string buildingSign, int udpid = 0)
  1864. {
  1865. try
  1866. {
  1867. if (Udp_Client == null) return string.Empty;
  1868. StringBuilder sb = new StringBuilder();
  1869. //1101070037;1;heart
  1870. sb.AppendWithSplit(buildingSign);
  1871. sb.AppendWithSplit(Settings.Gateway);
  1872. sb.AppendWithSplit("heart");
  1873. var str = sb.ToString();
  1874. Udp_Client.PushSend(str);
  1875. Thread.Sleep(100);
  1876. return "SendUdpHeart: " + str;
  1877. }
  1878. catch (Exception exp)
  1879. {
  1880. Logger.Error("SendUdpHeart", exp);
  1881. return string.Empty;
  1882. }
  1883. }
  1884. static string SendUdpConn(string buildingSign, int udpid = 0)
  1885. {
  1886. try
  1887. {
  1888. if (Udp_Client == null) return string.Empty;
  1889. StringBuilder sb = new StringBuilder();
  1890. //1101070037;1;connect
  1891. sb.AppendWithSplit(buildingSign);
  1892. sb.AppendWithSplit(Settings.Gateway);
  1893. sb.AppendWithSplit("connect");
  1894. var str = sb.ToString();
  1895. Udp_Client.PushSend(str);
  1896. Thread.Sleep(100);
  1897. return "SendUdpConn: " + str;
  1898. }
  1899. catch (Exception exp)
  1900. {
  1901. Logger.Error("SendUdpConn", exp);
  1902. return string.Empty;
  1903. }
  1904. }
  1905. }
  1906. public class NullLogger : ILogger
  1907. {
  1908. public void Debug(string message)
  1909. {
  1910. }
  1911. public void Error(string message)
  1912. {
  1913. }
  1914. public void Fatal(string message)
  1915. {
  1916. }
  1917. public void Info(string message)
  1918. {
  1919. }
  1920. public void Warn(string message)
  1921. {
  1922. }
  1923. }
  1924. static class LinqExtensions
  1925. {
  1926. public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> items,
  1927. int numOfParts)
  1928. {
  1929. int i = 0;
  1930. return items.GroupBy(x => i++ % numOfParts);
  1931. }
  1932. public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> items,
  1933. int partitionSize)
  1934. {
  1935. int i = 0;
  1936. return items.GroupBy(x => i++ / partitionSize).ToArray();
  1937. }
  1938. }
  1939. public class Collector
  1940. {
  1941. public String Name;
  1942. public String IP;
  1943. public int Port;
  1944. public String User;
  1945. public String Password;
  1946. public String ProgId;
  1947. public String BroadcastAddress;
  1948. public String MAC;
  1949. public String PROTOCOL;
  1950. public String Mode;
  1951. public int Max_size;
  1952. public String SqlContent;
  1953. }
  1954. public class Point
  1955. {
  1956. public String MAC;
  1957. public String Item;
  1958. public String buildingSign;
  1959. public String meterSign;
  1960. public String deviceId;
  1961. public String type;
  1962. public String instanceNumber;
  1963. public HashSet<Function> functionList = new HashSet<Function>();
  1964. //增加编辑定义函数分组
  1965. public String funcGroupID;
  1966. }
  1967. public class Function
  1968. {
  1969. public long functionID;
  1970. public Dictionary<String, String> DataConvert;
  1971. }
  1972. public class PointSet
  1973. {
  1974. public String uploadName;
  1975. public String[] content;
  1976. public String mac;
  1977. public int ID;
  1978. public double sendTime = 0;
  1979. public double recTime = 0;
  1980. public String status;
  1981. public String buildingSign;
  1982. public String buildingSignNew;
  1983. public String meterSign;
  1984. public int funcID;
  1985. public String collectorMAC;
  1986. public String cmd;
  1987. public double dataSet;
  1988. }
  1989. public class Record
  1990. {
  1991. public String buildingSign;
  1992. public String meterSign;
  1993. public String funcID;
  1994. public String receivetime;
  1995. public String data;
  1996. public String addtion;
  1997. }
  1998. }