Inovance_EIP.cs 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Drawing;
  6. using System.Dynamic;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Runtime.Serialization;
  11. using System.Security.Policy;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Windows.Forms;
  15. using System.Xml.Linq;
  16. using static System.Net.Mime.MediaTypeNames;
  17. using static System.Windows.Forms.VisualStyles.VisualStyleElement;
  18. namespace EIP_Protocol
  19. {
  20. #region MES与PLC通讯结构
  21. public enum eMachineState:short
  22. {
  23. Uninitialized=0, //未初始化状态
  24. Initializing, //初始化中...
  25. Initialized, //初始化完成
  26. Running, //运行中
  27. Paused, //暂停状态
  28. Fault, //故障状态
  29. Alarm //报警状态
  30. }
  31. public enum eMesCmd:byte
  32. {
  33. none=0,
  34. InStation = 1, //1:工站进站申请
  35. OutStation =2 //2:工站出站申请
  36. }
  37. public enum eAgvCmd
  38. {
  39. RequestPassingIn = 1, // = 1, AGV请求进料
  40. ConfirmPassInFinish = 2, //= 2, AGV请求进料完成确认
  41. RequestPassingOut = 3, //=3, AGV请求出料
  42. ConfrimPassingOutFinish = 4 //= 4, AGV请求出料完成确认
  43. }
  44. //图⽚命名需要遵循⼩⽶标准
  45. //[项⽬]_[⼯站]_[SN]_[物料-功能]_[测试时间]_[定位/检测/测量结果]_[是否原图-当前第⼏张-共⼏张]
  46. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  47. public struct CommandToPLC
  48. {
  49. [MarshalAs(UnmanagedType.U1)]
  50. public byte cmd; //1:AGV请求进料 2:AGV请求进料完成确认 3:AGV请求出料 4:AGV请求出料完成确认 PLC:成功回被PC清零
  51. [MarshalAs(UnmanagedType.I2)]
  52. public short cmdParam; //1:左边接口 2:右边接口
  53. [MarshalAs(UnmanagedType.I2)]
  54. public short cmdResult; //指令执行结果 1:OK 110:失败
  55. }
  56. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  57. public struct CommandFromPLC
  58. {
  59. [MarshalAs(UnmanagedType.U1)]
  60. public byte cmd; //1:工站进站申请 2:工站出站申请
  61. [MarshalAs(UnmanagedType.I2)]
  62. public short cmdParam; //指令参数
  63. [MarshalAs(UnmanagedType.I2)]
  64. public short cmdResult; //指令执行结果 1:OK 110:失败
  65. }
  66. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  67. public struct OP10_From_PLC
  68. {
  69. [MarshalAs(UnmanagedType.I4)]
  70. public int nThrowCount; //抛料次数
  71. [MarshalAs(UnmanagedType.R4)]
  72. public float fCleanAirPress; //清洁气压
  73. [MarshalAs(UnmanagedType.R4)]
  74. public float fCleanSpeed; //清洁速度mm/s
  75. [MarshalAs(UnmanagedType.R4)]
  76. public float fWindBladeHeight; //风刀高度mm
  77. [MarshalAs(UnmanagedType.R4)]
  78. public float fCleanTime; //清洁时间S
  79. [MarshalAs(UnmanagedType.I4)]
  80. public int nCleanCount; //清洁次数
  81. }
  82. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  83. public struct OP10_DataSet_t
  84. {
  85. [MarshalAs(UnmanagedType.I4)]
  86. public int nThrowCount; //抛料次数
  87. [MarshalAs(UnmanagedType.R4)]
  88. public float fCleanAirPress; //清洁气压
  89. [MarshalAs(UnmanagedType.R4)]
  90. public float fCleanSpeed; //清洁速度mm/s
  91. [MarshalAs(UnmanagedType.R4)]
  92. public float fWindBladeHeight; //风刀高度mm
  93. [MarshalAs(UnmanagedType.R4)]
  94. public float fCleanTime; //清洁时间S
  95. [MarshalAs(UnmanagedType.I4)]
  96. public int nCleanCount; //清洁次数
  97. [MarshalAs(UnmanagedType.I4)]
  98. public int nRemainCount; //外壳体余料数
  99. }
  100. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  101. public struct IoT_DataSet_t
  102. {
  103. [MarshalAs(UnmanagedType.I2)]
  104. public short machineState; //设备状态
  105. [MarshalAs(UnmanagedType.I2)]
  106. public short work_type; //作业类型:=1 PRESSURE_TEST(压测),=2 POINT_CHECK(点检),=3 OUT_STATION(正常跑料数据)
  107. [MarshalAs(UnmanagedType.I2)]
  108. public short testStatus; //测试状态:=1 PASS 0=FAIL
  109. [MarshalAs(UnmanagedType.I2)]
  110. public short BeatAction; //节拍动作 1:上料开始 2:上料结束 3:作业开始 4:作业结束 5:下料开始 6:下料结束
  111. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] //一个单独的位代表一个报警32*10=320
  112. public uint[] fault_codes;
  113. }
  114. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  115. public struct OP20_DataSet_t
  116. {
  117. [MarshalAs(UnmanagedType.I4)]
  118. public int nThrowCount; //抛料次数
  119. [MarshalAs(UnmanagedType.I4)]
  120. public int nRemainCount; //上盖余料数
  121. }
  122. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  123. public struct OP30_DataSet_t //站数据集
  124. {
  125. [MarshalAs(UnmanagedType.R4)]
  126. public float fGlueSupplySpeed; //供胶速度
  127. [MarshalAs(UnmanagedType.R4)]
  128. public float fAB_AirPress; //AB管气压
  129. [MarshalAs(UnmanagedType.R4)]
  130. public float fAB_AirPressDiff; //AB管气压差
  131. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
  132. public float[] fMesHeightInfos; //产品测高信息--点胶前的测高(mm)
  133. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
  134. public float[] fIntervalWeights; //可能没有:定期称重数据 A胶,B胶
  135. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
  136. public float[] fRemainGlues; //剩余胶量A:0 B:1
  137. }
  138. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  139. public struct OP30_stnDataSet_t
  140. {
  141. public BarcodeSet_t BarcodeSet; //条码集合
  142. public CommandFromPLC mesCommFrmPLC; //MES通讯
  143. public OP30_DataSet_t mesData;
  144. public IoT_DataSet_t iotData;
  145. }
  146. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  147. public struct OP40_DataSet_t
  148. {
  149. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
  150. public float[] fGluePosX; //胶线位置X偏差
  151. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
  152. public float[] fGluePosY; //胶线位置Y偏差
  153. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
  154. public float[] fGlue_Areas; //胶线面积
  155. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
  156. public float[] fGlue_Heights; //胶线高度
  157. [MarshalAs(UnmanagedType.I4)]
  158. public int nResult; //胶线检测结果 1:OK 非1:NG
  159. //public Image TestPic; //测试照片
  160. }
  161. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  162. public struct OP50_DataSet_t
  163. {
  164. [MarshalAs(UnmanagedType.I4)]
  165. public int nIsAddPCBAsmOK; //是否组装到位
  166. [MarshalAs(UnmanagedType.I4)]
  167. public int nHaveAddPCB; //是否有ADD板
  168. [MarshalAs(UnmanagedType.R4)]
  169. public float fForceAddPCB; //装ADD板的压力
  170. [MarshalAs(UnmanagedType.I4)]
  171. public int nRemainCount; //ADD板余料数
  172. }
  173. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  174. public struct OP60_DataSet_t
  175. {
  176. [MarshalAs(UnmanagedType.I4)]
  177. public int nIsTopCoverAsmOK; //是否组装到位
  178. [MarshalAs(UnmanagedType.I4)]
  179. public int nHaveTopCover; //是否有上盖板
  180. [MarshalAs(UnmanagedType.R4)]
  181. public float fForceTopCover; //装上盖板的压力
  182. }
  183. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  184. public struct OP70_DataSet_t
  185. {
  186. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  187. public float[] fScrewTimes; //锁附时间 PLC 14颗螺丝 预留6
  188. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  189. public short[] nScrewOrders; //锁附顺序 PLC 锁螺丝的标号
  190. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  191. public short[] nScrewResults; //锁附结果 PLC
  192. [MarshalAs(UnmanagedType.I4)]
  193. public int nRemainCount; //螺丝余料数
  194. }
  195. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  196. public struct OP70_ScrewDataSet_t
  197. {
  198. [MarshalAs(UnmanagedType.R4)]
  199. public float fTorque; //上位机传到PLC的锁螺丝扭力 每次读到阿特拉斯的数据都传一次
  200. [MarshalAs(UnmanagedType.R4)]
  201. public float fCircles; //上位机传到PLC的锁螺丝圈数 每次读到阿特拉斯的数据都传一次
  202. }
  203. public class OP70_PC_CollectDataSet_t
  204. {
  205. //需要自己收集
  206. public float[] fScrewTorques; //锁附扭力
  207. public float[] fScrewCircles; //锁附圈数
  208. public float[][] fTorqueCurve; //扭力曲线
  209. }
  210. public struct OP70_stnDataSet_t
  211. {
  212. public BarcodeSet_t BarcodeSet; //条码集合
  213. public CommandFromPLC mesCommFrmPLC; //MES通讯
  214. public OP70_DataSet_t mesData;
  215. public IoT_DataSet_t iotData;
  216. public OP70_ScrewDataSet_t screwDataToPLC; //传到PLC的锁螺丝数据,用于HMI显示用
  217. }
  218. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  219. public struct BarcodeSet_t
  220. {
  221. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 51)] //载具条码
  222. public string strCarrierBarcode;
  223. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 101)] //产品条码
  224. public string strProductBarcode;
  225. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 101)] //工位零部件条码
  226. public string strPartBarcode;
  227. }
  228. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  229. public struct OP10_MesData_t
  230. {
  231. public BarcodeSet_t BarcodeSet; //条码集合
  232. public CommandToPLC agvCommToPLC; //AGV通讯
  233. public CommandFromPLC mesCommFrmPLC; //MES通讯
  234. public OP10_DataSet_t mesData;
  235. public IoT_DataSet_t iotData;
  236. }
  237. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  238. public struct OP20_MesData_t
  239. {
  240. public BarcodeSet_t BarcodeSet; //条码集合
  241. public CommandToPLC agvCommToPLC; //AGV通讯
  242. public CommandFromPLC mesCommFrmPLC; //MES通讯
  243. public OP20_DataSet_t mesData;
  244. public IoT_DataSet_t iotData;
  245. }
  246. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  247. public struct OP30_MesData_t
  248. {
  249. public OP30_stnDataSet_t Left;
  250. public OP30_stnDataSet_t Right;
  251. }
  252. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  253. public struct OP40_MesData_t
  254. {
  255. public BarcodeSet_t BarcodeSet; //条码集合
  256. public CommandFromPLC mesCommFrmPLC; //MES通讯
  257. public OP40_DataSet_t mesData;
  258. public IoT_DataSet_t iotData;
  259. }
  260. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  261. public struct OP50_MesData_t
  262. {
  263. public BarcodeSet_t BarcodeSet; //条码集合
  264. public CommandToPLC agvCommToPLC; //AGV通讯
  265. public CommandFromPLC mesCommFrmPLC; //MES通讯
  266. public OP50_DataSet_t mesData;
  267. public IoT_DataSet_t iotData;
  268. }
  269. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  270. public struct OP60_MesData_t
  271. {
  272. public BarcodeSet_t BarcodeSet; //条码集合
  273. public CommandFromPLC mesCommFrmPLC; //MES通讯
  274. public OP60_DataSet_t mesData;
  275. public IoT_DataSet_t iotData;
  276. }
  277. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  278. public struct OP70_iotDataSet_t
  279. {
  280. public IoT_DataSet_t Left;
  281. public IoT_DataSet_t Right;
  282. }
  283. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  284. public struct OP70_MesData_t
  285. {
  286. public OP70_stnDataSet_t Left;
  287. public OP70_stnDataSet_t Right;
  288. }
  289. public struct OP80_DataSet_t
  290. {
  291. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  292. public float[] fScrewHeights; //螺丝高度 PLC 14颗螺丝 预留6
  293. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
  294. public short[] nScrewResults; //螺丝检测结果 PLC 1:OK 0:NG
  295. }
  296. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  297. public struct OP80_MesData_t
  298. {
  299. public BarcodeSet_t BarcodeSet; //条码集合
  300. public CommandFromPLC mesCommFrmPLC; //MES通讯
  301. public OP80_DataSet_t mesData;
  302. public IoT_DataSet_t iotData;
  303. }
  304. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  305. public struct OP90_DataSet_t
  306. {
  307. [MarshalAs(UnmanagedType.I4)]
  308. public int nThrowCount; //抛料次数
  309. [MarshalAs(UnmanagedType.I4)]
  310. public int nRemainCount; //料箱余料数
  311. }
  312. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 8)]
  313. public struct OP90_MesData_t
  314. {
  315. public BarcodeSet_t BarcodeSet; //条码集合
  316. public CommandToPLC agvCommToPLC; //AGV通讯
  317. public CommandFromPLC mesCommFrmPLC; //MES通讯
  318. public OP90_DataSet_t mesData;
  319. public IoT_DataSet_t iotData;
  320. }
  321. #endregion MES与PLC通讯结构
  322. public class Inovance_EIP
  323. {
  324. private string strTagPrefix = "Application.GVL."; //标签前缀
  325. private object m_objLock = new object();
  326. bool isStart = false;
  327. string strClaimedComputerIP = ""; //PC的IP地址 - private实际IP
  328. private int m_nInstanceId = 0; //实例ID
  329. public bool m_bConnected = false;
  330. public string _pcIPStr = string.Empty; //PC的IP地址
  331. public string _plcIPStr = string.Empty; //PLC的IP地址
  332. public bool IsConnected
  333. {
  334. get { return m_bConnected; }
  335. }
  336. public void Config_TagPrefix(string TagPrefix)
  337. {
  338. strTagPrefix = TagPrefix;
  339. }
  340. #region 自定义的结构
  341. public enum ERROR_NO : int
  342. {
  343. ERR_EIP_STOPED = -2,//协议栈未开启
  344. OTHER_ERROR = -1,
  345. SUCCESS = 0,
  346. ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED = 1,//连接的实例ID与已有的ID重复或超过最大值
  347. ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH,//连接的网络路径格式错误,无法检测出来目标IP离线等错误
  348. ERRI_CONNECTION_COUNT_LIMIT_REACHED,//达到最大连接数量
  349. ERRI_OUT_OF_MEMORY,//内存溢出,缓冲区已满
  350. ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH, //连接的网络地址无效
  351. ERRR_CONN_CONFIG_FAILED_NO_RESPONSE, //连接无响应
  352. ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE,//连接响应错误
  353. ERRR_INVALID_DESTINATION, //目标标签不存在
  354. ERRR_TAGNAME_TOO_LONG, //标签名超过255字节
  355. ERRR_REQUEST_DATA_TOO_LARGE, //请求数据超限
  356. ERRR_CONN_CONNECTION_TIMED_OUT, //活动连接响应超时,请检查目标IP是否离线
  357. ERRR_TAGNAME_CONVERT_FAILED, //标签名解析错误
  358. ERRR_WRITE_DATASIZE_UNCONSISTENT, //数据长度与标签实际长度不一致
  359. ERRR_SCAN_ERROR, //扫描标签信息失败
  360. };
  361. public enum TAG_TYPE : int
  362. {
  363. TAG_TYPE_UNDEFINE = -1,
  364. TAG_TYPE_BOOL = 0xC1, //新增
  365. TAG_TYPE_SINT = 0xC2,
  366. TAG_TYPE_INT = 0xC3,
  367. TAG_TYPE_DINT = 0xC4,
  368. TAG_TYPE_LINT = 0xC5,
  369. TAG_TYPE_USINT = 0xC6,
  370. TAG_TYPE_UINT = 0xC7,
  371. TAG_TYPE_UDINT = 0xC8,
  372. TAG_TYPE_ULINT = 0xC9,
  373. TAG_TYPE_REAL = 0xCA,
  374. TAG_TYPE_LREAL = 0xCB,
  375. TAG_TYPE_STRING = 0xD0, //新增
  376. TAG_TYPE_BYTE = 0xD1,
  377. TAG_TYPE_WORD = 0xD2,
  378. TAG_TYPE_DWORD = 0xD3,
  379. TAG_TYPE_LWORD = 0xD4,
  380. TAG_TYPE_STRUCT = 0xA2, //新增
  381. TAG_TYPE_ARRAY = 0xA3
  382. };
  383. enum EtIPConnectionState : int
  384. {
  385. ConnectionNonExistent = 0x0, //该实例未有连接
  386. ConnectionConfiguring = 0x1, //连接正在打开过程中
  387. ConnectionEstablished = 0x3, //连接已成功建立并在活动中
  388. ConnectionTimedOut = 0x4, //连接超时
  389. ConnectionClosing = 0x6 //连接正在关闭中
  390. };
  391. public const uint INVALID_MEMBER = 0xffffffff; //Member is not valid flag should be used when no member should be specified in the UCMM
  392. public struct tagTagReadData
  393. {
  394. public string pName;
  395. public int nElementCount;
  396. public int nArrayPos;
  397. };
  398. public struct tagTagReadDataBase
  399. {
  400. public string pName;
  401. public int nElementCount;
  402. };
  403. public struct tagTagRetValue
  404. {
  405. public IntPtr pData;
  406. public TAG_TYPE pType;
  407. public int nDataLength;
  408. //tagTagRetValue()
  409. //{
  410. // pData = NULL;
  411. // pType = TAG_TYPE_UNDEFINE;
  412. // nDataLength = 0;
  413. //}
  414. //~tagTagRetValue()
  415. //{
  416. // if (pData)
  417. // {
  418. // delete pData;
  419. // pData = NULL;
  420. // }
  421. //}
  422. };
  423. [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
  424. public struct tagTagWriteData
  425. {
  426. public string pName;
  427. public IntPtr pData;
  428. public TAG_TYPE pType;
  429. public int nArrayPos;
  430. public int nDataLength;
  431. public int nElementCount;
  432. };
  433. public struct tagTagWriteDataBase
  434. {
  435. public string pName;
  436. public IntPtr pData;
  437. public TAG_TYPE pType;
  438. public int nDataLength;
  439. public int nElementCount;
  440. };
  441. public class MySerializationBinder : SerializationBinder
  442. {
  443. public override Type BindToType(string assemblyName, string typeName)
  444. {
  445. // 如果类型名称是"MyNamespace.MyUnsupportedType",则将其转换为"MyNamespace.MySupportType"
  446. if (typeName == "MyNamespace.MyUnsupportedType")
  447. {
  448. return Type.GetType("MyNamespace.MySupportType");
  449. }
  450. // 否则返回null,表示无法进行转换
  451. return null;
  452. }
  453. }
  454. #endregion 自定义的结构
  455. #region 动态类型
  456. public class DynamicMethodProvider
  457. {
  458. public dynamic GetDynamicValue(string propertyName)
  459. {
  460. dynamic result;
  461. switch (propertyName)
  462. {
  463. case "Name":
  464. result = "John Doe";
  465. break;
  466. case "Age":
  467. result = 30;
  468. break;
  469. default:
  470. result = new ExpandoObject();
  471. ((IDictionary<string, object>)result).Add("UnknownProperty", "UnknownValue");
  472. break;
  473. }
  474. return result;
  475. }
  476. }
  477. public static T CreateElement<T>()
  478. {
  479. Type t = typeof(T);
  480. return (T)t.Assembly.CreateInstance(t.FullName);
  481. }
  482. public static dynamic CreateElement(string typename)
  483. {
  484. Type t = GetTypeByName(typename);
  485. return t.Assembly.CreateInstance(t.FullName);
  486. }
  487. public static Type GetTypeByName(string typename)
  488. {
  489. Type t = null;
  490. string source = typename;
  491. try
  492. {
  493. t = Type.GetType(source);
  494. if (t != null)
  495. {
  496. return t;
  497. }
  498. Assembly[] assembly = AppDomain.CurrentDomain.GetAssemblies();
  499. foreach (Assembly ass in assembly)
  500. {
  501. t = ass.GetType(source);
  502. if (t != null)
  503. {
  504. return t;
  505. }
  506. Type[] ts = ass.GetTypes();
  507. foreach (Type st in ts)
  508. {
  509. if (Regex.IsMatch(st.FullName, @"\." + source + @"(`?\d+)?$"))
  510. {
  511. return st;
  512. }
  513. }
  514. }
  515. }
  516. catch (Exception ex)
  517. {
  518. }
  519. return t;
  520. }
  521. public static Type GetTypeByName2(string typename)
  522. {
  523. Type t = null;
  524. string source = typename;
  525. if (source.IndexOf('<') > 0)
  526. {
  527. List<string> lv = new List<string>();
  528. while (Regex.IsMatch(source, @"<[^<>]+>"))
  529. {
  530. lv.Add(Regex.Match(source, @"(?<=<)[^<>]+(?=>)").Value);
  531. source = Regex.Replace(source, @"<[^<>]+>", "/" + (lv.Count - 1));
  532. }
  533. List<Type[]> args = new List<Type[]>();
  534. for (int i = 0; i < lv.Count; i++)
  535. {
  536. List<Type> arg = new List<Type>();
  537. string[] sp = lv[i].Split(',');
  538. for (int j = 0; j < sp.Length; j++)
  539. {
  540. string s = sp[j].Trim();
  541. if (!string.IsNullOrEmpty(s))
  542. {
  543. if (Regex.IsMatch(s, @"/\d+$"))
  544. {
  545. Match m = Regex.Match(s, @"^([^/\s]+)\s*/(\d+)$");
  546. if (!m.Success)
  547. {
  548. throw new Exception("");
  549. }
  550. Type p = GetTypeByName(m.Groups[1].Value);
  551. Type c = p.MakeGenericType(args[Convert.ToInt32(m.Groups[2].Value)]);
  552. arg.Add(c);
  553. }
  554. else
  555. {
  556. arg.Add(GetTypeByName(s));
  557. }
  558. }
  559. }
  560. args.Add(arg.ToArray());
  561. }
  562. Match f = Regex.Match(source, @"^([^/\s]+)\s*/(\d+)$");
  563. if (!f.Success)
  564. {
  565. throw new Exception("");
  566. }
  567. Type fp = GetTypeByName(f.Groups[1].Value);
  568. Type fc = fp.MakeGenericType(args[Convert.ToInt32(f.Groups[2].Value)]);
  569. return fc;
  570. }
  571. else
  572. {
  573. try
  574. {
  575. t = Type.GetType(source);
  576. if (t != null)
  577. {
  578. return t;
  579. }
  580. Assembly[] assembly = AppDomain.CurrentDomain.GetAssemblies();
  581. foreach (Assembly ass in assembly)
  582. {
  583. t = ass.GetType(source);
  584. if (t != null)
  585. {
  586. return t;
  587. }
  588. Type[] ts = ass.GetTypes();
  589. foreach (Type st in ts)
  590. {
  591. //if (Regex.IsMatch(st.FullName, @"\." + Regex.FormatRegEx(source) + @"(`?\d+)?$"))
  592. if (Regex.IsMatch(st.FullName, @"\." + source + @"(`?\d+)?$"))
  593. {
  594. return st;
  595. }
  596. }
  597. }
  598. }
  599. catch (Exception ex)
  600. {
  601. }
  602. }
  603. return t;
  604. }
  605. #endregion 动态类型
  606. #region DLL
  607. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  608. public static extern void EipStart();
  609. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  610. public static extern void EipStop();
  611. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  612. public static extern int EipOpenConnection(string ipAddress, IntPtr instanceID);
  613. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  614. public static extern int EipCloseConnection(int nID);
  615. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  616. public static extern int EipReadTag(int instanceID, string tagName, IntPtr type, byte[] dest, int dataLength, ushort elementCount = 1, uint nPos = INVALID_MEMBER);
  617. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  618. public static extern int EipWriteTag(int instanceID, string tagName, int type, byte[] source, int dataLength, ushort elementCount = 1, uint nPos = INVALID_MEMBER/*, uint strLen = 0*/);
  619. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  620. public static extern int EipGetConnectionState(int nID);
  621. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  622. public static extern bool EipStartExt(string ipAddress, uint nPort = 0);
  623. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  624. public static extern int EipReadTagList(int instanceID, int nNumOfTags, tagTagReadData[] pTagList, ref tagTagRetValue pdest);
  625. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  626. public static extern ERROR_NO EipWriteTagList(int instanceID, int nNumOfTags, tagTagWriteData[] pTagWritenData);
  627. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  628. public static extern bool DeleteTagListStru(ref tagTagRetValue pRetValue, int nNumOfTags);
  629. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  630. public static extern int EipReadTagExt(int instanceID, string tagName, IntPtr type, byte[] dest, int dataLength, ushort elementCount = 1);
  631. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  632. public static extern int EipWriteTagExt(int instanceID, string tagName, int type, byte[] source, int dataLength, ushort elementCount = 1);
  633. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  634. public static extern int EipReadTagListExt(int instanceID, int nNumOfTags, tagTagReadDataBase[] pTagList, ref tagTagRetValue pdest, bool bScan = false);
  635. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  636. public static extern ERROR_NO EipWriteTagListExt(int instanceID, int nNumOfTags, tagTagWriteDataBase[] pTagWritenData, bool bScan = false);
  637. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  638. public static extern ERROR_NO EipReadTagExt2(int iInstanceID, tagTagReadDataBase[] pTagList, ref tagTagRetValue pDest);
  639. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  640. public static extern ERROR_NO EipWriteTagExt2(int iInstanceID, tagTagWriteDataBase[] pTagWritenData);
  641. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  642. public static extern void ResetTagInfo();
  643. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  644. public static extern ERROR_NO EipReadTagRaw(int iInstanceID, tagTagReadDataBase[] pTagList, ref tagTagRetValue pDest);
  645. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  646. public static extern ERROR_NO EipWriteTagRaw(int iInstanceID, tagTagWriteDataBase[] pTagWritenData);
  647. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  648. public static extern int EipReadTagListRaw(int instanceID, int nNumOfTags, tagTagReadDataBase[] pTagList, ref tagTagRetValue pdest);
  649. [DllImport("EipTagSimple.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
  650. public static extern ERROR_NO EipWriteTagListRaw(int instanceID, int nNumOfTags, tagTagWriteDataBase[] pTagWritenData);
  651. #endregion DLL
  652. #region private方法
  653. private string getTypeString(TAG_TYPE eType)
  654. {
  655. string strType = "";
  656. switch (eType)
  657. {
  658. case TAG_TYPE.TAG_TYPE_SINT:
  659. strType = "SINT";
  660. break;
  661. case TAG_TYPE.TAG_TYPE_INT:
  662. strType = "INT";
  663. break;
  664. case TAG_TYPE.TAG_TYPE_DINT:
  665. strType = "DINT";
  666. break;
  667. case TAG_TYPE.TAG_TYPE_LINT:
  668. strType = "LINT";
  669. break;
  670. case TAG_TYPE.TAG_TYPE_USINT:
  671. strType = "USINT";
  672. break;
  673. case TAG_TYPE.TAG_TYPE_UINT:
  674. strType = "UINT";
  675. break;
  676. case TAG_TYPE.TAG_TYPE_UDINT:
  677. strType = "UDINT";
  678. break;
  679. case TAG_TYPE.TAG_TYPE_ULINT:
  680. strType = "ULINT";
  681. break;
  682. case TAG_TYPE.TAG_TYPE_REAL:
  683. strType = "REAL";
  684. break;
  685. case TAG_TYPE.TAG_TYPE_LREAL:
  686. strType = "LREAL";
  687. break;
  688. case TAG_TYPE.TAG_TYPE_BYTE:
  689. strType = "BYTE";
  690. break;
  691. case TAG_TYPE.TAG_TYPE_WORD:
  692. strType = "WORD";
  693. break;
  694. case TAG_TYPE.TAG_TYPE_DWORD:
  695. strType = "DWORD";
  696. break;
  697. case TAG_TYPE.TAG_TYPE_LWORD:
  698. strType = "LWORD";
  699. break;
  700. case TAG_TYPE.TAG_TYPE_BOOL:
  701. strType = "BOOL";
  702. break;
  703. case TAG_TYPE.TAG_TYPE_STRING:
  704. strType = "STRING";
  705. break;
  706. case TAG_TYPE.TAG_TYPE_STRUCT:
  707. strType = "STRUCT";
  708. break;
  709. default:
  710. break;
  711. }
  712. return strType;
  713. }
  714. private byte[] StringToBytes(string s)
  715. {
  716. string[] str = s.Split(' ');
  717. int n = str.Length;
  718. byte[] cmdBytes = null;
  719. int p = 0;
  720. for (int k = 0; k < n; k++)
  721. {
  722. int sLen = str[k].Length;
  723. int bytesLen = sLen / 2;
  724. int position = 0;
  725. byte[] bytes = new byte[bytesLen];
  726. for (int i = 0; i < bytesLen; i++)
  727. {
  728. string abyte = str[k].Substring(position, 2);
  729. bytes[i] = Convert.ToByte(abyte, 16);
  730. position += 2;
  731. }
  732. if (position >= 2)
  733. {
  734. byte[] cmdBytes2 = new byte[p + bytesLen];
  735. if (cmdBytes != null)
  736. {
  737. Array.Copy(cmdBytes, 0, cmdBytes2, 0, p);
  738. }
  739. Array.Copy(bytes, 0, cmdBytes2, p, bytesLen);
  740. cmdBytes = cmdBytes2;
  741. p += bytesLen;
  742. }
  743. }
  744. return cmdBytes;
  745. }
  746. private (int,string) OpenEip(string strLocalComputerIp)
  747. {
  748. //limit input of controller
  749. bool blnTest = false;
  750. bool bValidIP = true;
  751. Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
  752. blnTest = regex.IsMatch(strLocalComputerIp);
  753. if (blnTest == true)
  754. {
  755. string[] strTemp = strLocalComputerIp.Split(new char[] { '.' });
  756. if (strTemp.Length < 4)
  757. {
  758. bValidIP = false;
  759. return (-1, "不符合IP格式");
  760. }
  761. for (int i = 0; (i < strTemp.Length) && bValidIP; i++)
  762. {
  763. if (Convert.ToInt32(strTemp[i]) > 255)
  764. {
  765. //大于255则提示,不符合IP格式
  766. bValidIP = false;
  767. return (-2, "IP大于255,不符合IP格式");
  768. }
  769. }
  770. }
  771. else
  772. {
  773. //输入非数字则提示,不符合IP格式
  774. bValidIP = false;
  775. return (-3, "输入非数字,不符合IP格式");
  776. }
  777. if (bValidIP)
  778. {
  779. if (!isStart)
  780. {
  781. if (EipStartExt(strLocalComputerIp, 0))
  782. {
  783. isStart = true;
  784. strClaimedComputerIP = strLocalComputerIp;
  785. return (0, "EIP协议栈开启成功");
  786. }
  787. else
  788. {
  789. isStart = false;
  790. return (1, "EIP协议栈开启失败");
  791. }
  792. }
  793. else
  794. {
  795. if (string.Compare(strClaimedComputerIP, strLocalComputerIp) != 0)
  796. {
  797. return (2,"更改上位机IP时需先关闭协议栈,再开启");
  798. }
  799. else
  800. {
  801. return (3, "EIP协议栈已经开启");
  802. }
  803. }
  804. }
  805. return (-4, "无效IP");
  806. }
  807. private (bool,string) CloseEip()
  808. {
  809. if (isStart)
  810. {
  811. EipStop();
  812. isStart = false;
  813. return (true, "EIP协议栈关闭");
  814. }
  815. else
  816. {
  817. return (false, "EIP协议栈未开启,请先开启");
  818. }
  819. }
  820. #endregion private方法
  821. #region 连接/断开
  822. #region 连接方式 一
  823. public Inovance_EIP() { }
  824. /// <summary>
  825. /// 连接PLC
  826. /// </summary>
  827. /// <param name="strComputerIp">PC的IP地址</param>
  828. /// <param name="strPlcIp">PLC的IP地址</param>
  829. /// <returns>成功:True 失败:False </returns>
  830. public (int,string) Connect(string strComputerIp,string strPlcIp)
  831. {
  832. _pcIPStr = strComputerIp;
  833. _plcIPStr = strPlcIp;
  834. lock (m_objLock)
  835. {
  836. string strRet = "";
  837. int nRet = 0;
  838. if (!isStart) (nRet, strRet) = OpenEip(strComputerIp);
  839. if (nRet != 0) return (nRet, strRet);
  840. bool blnTest = false;
  841. bool bValidIP = true;
  842. Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
  843. blnTest = regex.IsMatch(strPlcIp);
  844. if (blnTest == true)
  845. {
  846. string[] strTemp = strPlcIp.Split(new char[] { '.' });
  847. for (int i = 0; i < strTemp.Length; i++)
  848. {
  849. if (Convert.ToInt32(strTemp[i]) > 255)
  850. {
  851. bValidIP = false;
  852. return (-10, "PLC IP 大于255,不符合IP格式");
  853. }
  854. }
  855. }
  856. else
  857. {
  858. bValidIP = false;
  859. return (-11, "PLC IP输入非数字,不符合IP格式");
  860. }
  861. if (bValidIP)
  862. {
  863. if (strPlcIp.CompareTo(strClaimedComputerIP) == 0)
  864. {
  865. string strLog = "";
  866. strLog += "上位机IP与PLC IP相同,请重新输入";
  867. return (-20, strLog);
  868. }
  869. if (strPlcIp.CompareTo(strComputerIp) == 0)
  870. {
  871. string strLog = "";
  872. strLog += "上位机IP与PLC IP相同,请重新输入";
  873. return (-21, strLog);
  874. }
  875. int instanceId = 0;
  876. ERROR_NO errorNo;
  877. unsafe
  878. {
  879. errorNo = (ERROR_NO)EipOpenConnection(strPlcIp, (IntPtr)(&instanceId));
  880. }
  881. m_nInstanceId = instanceId;
  882. string str = "";
  883. str += "\n请求创建PLC连接 ip:";
  884. str += strPlcIp;
  885. str += " ";
  886. if (errorNo != ERROR_NO.SUCCESS)
  887. {
  888. m_bConnected = false;
  889. str += ("失败 ");
  890. switch (errorNo)
  891. {
  892. case ERROR_NO.ERR_EIP_STOPED:
  893. str += ("协议栈未开启");
  894. break;
  895. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  896. str += ("连接的实例ID与已有的ID重复或超过最大值");
  897. break;
  898. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  899. str += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  900. break;
  901. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  902. str += ("达到最大连接数量");
  903. break;
  904. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  905. str += ("内存溢出,缓冲区已满");
  906. break;
  907. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  908. str += ("连接的网络地址无效");
  909. break;
  910. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  911. str += ("连接无响应");
  912. break;
  913. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  914. str += ("连接响应错误");
  915. break;
  916. default:
  917. str += ("其他错误");
  918. break;
  919. }
  920. }
  921. else
  922. {
  923. str += "成功";
  924. str += " 分配的实例ID 为 ";
  925. str += instanceId.ToString();
  926. m_bConnected = true;
  927. return (0, str);
  928. }
  929. str += "\n";
  930. return (100 + (int)errorNo, str);
  931. }
  932. }
  933. return (1000, "Error");
  934. }
  935. #endregion 连接方式 一
  936. #region 连接方式 二
  937. /// <summary>
  938. ///
  939. /// </summary>
  940. /// <param name="strComputerIp">PC的IP地址</param>
  941. /// <param name="strPlcIp">PLC的IP地址</param>
  942. public Inovance_EIP(string strComputerIp, string strPlcIp)
  943. {
  944. _pcIPStr = strComputerIp;
  945. _plcIPStr = strPlcIp;
  946. }
  947. /// <summary>
  948. /// 连接PLC
  949. /// </summary>
  950. /// <returns>成功:True 失败:False </returns>
  951. public (int, string) Connect()
  952. {
  953. lock (m_objLock)
  954. {
  955. string strRet = "";
  956. int nRet = 0;
  957. if (!isStart) (nRet, strRet) = OpenEip(_pcIPStr);
  958. if (nRet != 0) return (nRet, strRet);
  959. bool blnTest = false;
  960. bool bValidIP = true;
  961. Regex regex = new Regex("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$");
  962. blnTest = regex.IsMatch(_plcIPStr);
  963. if (blnTest == true)
  964. {
  965. string[] strTemp = _plcIPStr.Split(new char[] { '.' });
  966. for (int i = 0; i < strTemp.Length; i++)
  967. {
  968. if (Convert.ToInt32(strTemp[i]) > 255)
  969. {
  970. bValidIP = false;
  971. return (-10, "PLC IP 大于255,不符合IP格式");
  972. }
  973. }
  974. }
  975. else
  976. {
  977. bValidIP = false;
  978. return (-11, "PLC IP输入非数字,不符合IP格式");
  979. }
  980. if (bValidIP)
  981. {
  982. if (_plcIPStr.CompareTo(strClaimedComputerIP) == 0)
  983. {
  984. string strLog = "";
  985. strLog += "上位机IP与PLC IP相同,请重新输入";
  986. return (-20, strLog);
  987. }
  988. if (_plcIPStr.CompareTo(_pcIPStr) == 0)
  989. {
  990. string strLog = "";
  991. strLog += "上位机IP与PLC IP相同,请重新输入";
  992. return (-21, strLog);
  993. }
  994. int instanceId = 0;
  995. ERROR_NO errorNo;
  996. unsafe
  997. {
  998. errorNo = (ERROR_NO)EipOpenConnection(_plcIPStr, (IntPtr)(&instanceId));
  999. }
  1000. m_nInstanceId = instanceId;
  1001. string str = "";
  1002. str += "\n请求创建PLC连接 ip:";
  1003. str += _plcIPStr;
  1004. str += " ";
  1005. if (errorNo != ERROR_NO.SUCCESS)
  1006. {
  1007. m_bConnected = false;
  1008. str += ("失败 ");
  1009. switch (errorNo)
  1010. {
  1011. case ERROR_NO.ERR_EIP_STOPED:
  1012. str += ("协议栈未开启");
  1013. break;
  1014. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  1015. str += ("连接的实例ID与已有的ID重复或超过最大值");
  1016. break;
  1017. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1018. str += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  1019. break;
  1020. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  1021. str += ("达到最大连接数量");
  1022. break;
  1023. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  1024. str += ("内存溢出,缓冲区已满");
  1025. break;
  1026. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1027. str += ("连接的网络地址无效");
  1028. break;
  1029. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  1030. str += ("连接无响应");
  1031. break;
  1032. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  1033. str += ("连接响应错误");
  1034. break;
  1035. default:
  1036. str += ("其他错误");
  1037. break;
  1038. }
  1039. }
  1040. else
  1041. {
  1042. str += "成功";
  1043. str += " 分配的实例ID 为 ";
  1044. str += instanceId.ToString();
  1045. m_bConnected = true;
  1046. return (0, str);
  1047. }
  1048. str += "\n";
  1049. return (100 + (int)errorNo, str);
  1050. }
  1051. }
  1052. return (1000, "Error");
  1053. }
  1054. #endregion 连接方式 二
  1055. /// <summary>
  1056. /// 断开连接
  1057. /// </summary>
  1058. /// <returns>成功:True 失败:False</returns>
  1059. public bool Disconnect()
  1060. {
  1061. lock (m_objLock)
  1062. {
  1063. if (m_nInstanceId == 0 || !m_bConnected)
  1064. {
  1065. m_nInstanceId = 0;
  1066. m_bConnected = false;
  1067. return true;
  1068. }
  1069. ERROR_NO errorNo = (ERROR_NO)EipCloseConnection(m_nInstanceId);
  1070. //string str = "";
  1071. if (errorNo != ERROR_NO.SUCCESS)
  1072. {
  1073. //str += "失败";
  1074. m_bConnected = false;
  1075. m_nInstanceId = 0;
  1076. return false;
  1077. }
  1078. else
  1079. {
  1080. //str += "成功";
  1081. m_bConnected = false;
  1082. m_nInstanceId = 0;
  1083. CloseEip();
  1084. return true;
  1085. }
  1086. }
  1087. }
  1088. #endregion 连接/断开
  1089. public (int,string) Read_Tag(string strTagName, int nCount, out byte[] pBuf)
  1090. {
  1091. pBuf = null;
  1092. string strType = "";
  1093. lock (m_objLock)
  1094. {
  1095. if (!m_bConnected) return (-1,"未连接");
  1096. string tagName = strTagName;
  1097. byte[] tagNameUTF8 = Encoding.UTF8.GetBytes(tagName);
  1098. if (m_nInstanceId <= 0)
  1099. {
  1100. return (-2, "实例ID需大于0");
  1101. }
  1102. if (tagNameUTF8.Length > 255)
  1103. {
  1104. return (-3, "标签名长度超过255字节");
  1105. }
  1106. ushort elementCount = (ushort)nCount;
  1107. if (elementCount > 0)
  1108. {
  1109. int destLength = 1400;
  1110. byte[] dest = new byte[destLength];
  1111. char[] cChar = Encoding.ASCII.GetChars(dest);
  1112. //TAG_TYPE type = TAG_TYPE.TAG_TYPE_UNDEFINE;
  1113. //int returnLength = 0;
  1114. tagTagReadDataBase[] pTaglist = new tagTagReadDataBase[1];
  1115. pTaglist[0].pName = tagName;
  1116. pTaglist[0].nElementCount = elementCount;
  1117. tagTagRetValue[] tagValue = new tagTagRetValue[1];
  1118. ERROR_NO errorNo = ERROR_NO.OTHER_ERROR;
  1119. unsafe
  1120. {
  1121. errorNo = EipReadTagExt2(m_nInstanceId, pTaglist, ref tagValue[0]);
  1122. }
  1123. string strLog = "";
  1124. strLog += "读取请求";
  1125. if (/*returnLength < 0*/errorNo != ERROR_NO.SUCCESS)
  1126. {
  1127. strLog += " 失败 标签名:" + tagName + " 实例ID:" + m_nInstanceId.ToString() + " ";
  1128. switch (/*returnLength*/errorNo)
  1129. {
  1130. //case -1:
  1131. // strLog += ("其他错误");
  1132. // break;
  1133. //case -2:
  1134. // strLog += ("协议栈未开启");
  1135. // break;
  1136. //case -3:
  1137. // strLog += ("实例id小于或等于0");
  1138. // break;
  1139. //case -4:
  1140. // strLog += ("标签名长度大于255字节");
  1141. // break;
  1142. //case -5:
  1143. // strLog += ("目标标签不存在");
  1144. // break;
  1145. //case -6:
  1146. // strLog += ("响应超时,请检查设备是否离线");
  1147. // break;
  1148. //case -7:
  1149. // strLog += ("标签名解析错误");
  1150. // break;
  1151. //case -8:
  1152. // strLog += ("扫描标签信息失败");
  1153. // break;
  1154. //default:
  1155. // strLog += ("其他错误");
  1156. // break;
  1157. case ERROR_NO.ERR_EIP_STOPED:
  1158. strLog += ("协议栈未开启");
  1159. break;
  1160. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  1161. strLog += ("连接的实例ID与已有的ID重复或超过最大值");
  1162. break;
  1163. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1164. strLog += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  1165. break;
  1166. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  1167. strLog += ("达到最大连接数量");
  1168. break;
  1169. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  1170. strLog += ("内存溢出,缓冲区已满");
  1171. break;
  1172. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1173. strLog += ("连接的网络地址无效");
  1174. break;
  1175. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  1176. strLog += ("连接无响应");
  1177. break;
  1178. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  1179. strLog += ("连接响应错误");
  1180. break;
  1181. case ERROR_NO.ERRR_INVALID_DESTINATION:
  1182. strLog += ("目标标签不存在");
  1183. break;
  1184. case ERROR_NO.ERRR_TAGNAME_TOO_LONG:
  1185. strLog += ("标签名超过255字节");
  1186. break;
  1187. case ERROR_NO.ERRR_REQUEST_DATA_TOO_LARGE:
  1188. strLog += ("请求数据超限");
  1189. break;
  1190. case ERROR_NO.ERRR_CONN_CONNECTION_TIMED_OUT:
  1191. strLog += ("响应超时,请检查设备是否离线");
  1192. break;
  1193. case ERROR_NO.ERRR_TAGNAME_CONVERT_FAILED:
  1194. strLog += ("标签名解析错误");
  1195. break;
  1196. case ERROR_NO.ERRR_SCAN_ERROR:
  1197. strLog += ("扫描标签信息失败");
  1198. break;
  1199. default:
  1200. strLog += ("其他错误");
  1201. break;
  1202. }
  1203. strLog += "\n";
  1204. return (10,strLog);
  1205. }
  1206. else
  1207. {
  1208. switch (/*type*/tagValue[0].pType)
  1209. {
  1210. case TAG_TYPE.TAG_TYPE_BOOL:
  1211. strType += "Boolean";
  1212. break;
  1213. case TAG_TYPE.TAG_TYPE_SINT:
  1214. strType += "SByte";
  1215. break;
  1216. case TAG_TYPE.TAG_TYPE_INT:
  1217. strType += "Int16";
  1218. break;
  1219. case TAG_TYPE.TAG_TYPE_DINT:
  1220. strType += "Int32";
  1221. break;
  1222. case TAG_TYPE.TAG_TYPE_LINT:
  1223. strType += "Int64";
  1224. break;
  1225. case TAG_TYPE.TAG_TYPE_USINT:
  1226. strType += "Byte";
  1227. break;
  1228. case TAG_TYPE.TAG_TYPE_UINT:
  1229. strType += "UInt16";
  1230. break;
  1231. case TAG_TYPE.TAG_TYPE_UDINT:
  1232. strType += "UInt32";
  1233. break;
  1234. case TAG_TYPE.TAG_TYPE_ULINT:
  1235. strType += "UInt64";
  1236. break;
  1237. case TAG_TYPE.TAG_TYPE_REAL:
  1238. strType += "Single";
  1239. break;
  1240. case TAG_TYPE.TAG_TYPE_LREAL:
  1241. strType += "Double";
  1242. break;
  1243. case TAG_TYPE.TAG_TYPE_STRING:
  1244. strType += "String";
  1245. break;
  1246. case TAG_TYPE.TAG_TYPE_BYTE:
  1247. strType += "Byte";
  1248. break;
  1249. case TAG_TYPE.TAG_TYPE_WORD:
  1250. strType += "UInt16";
  1251. break;
  1252. case TAG_TYPE.TAG_TYPE_DWORD:
  1253. strType += "UInt32";
  1254. break;
  1255. case TAG_TYPE.TAG_TYPE_LWORD:
  1256. strType += "UInt64";
  1257. break;
  1258. case TAG_TYPE.TAG_TYPE_STRUCT:
  1259. strType += "STRUCT";
  1260. break;
  1261. case TAG_TYPE.TAG_TYPE_ARRAY:
  1262. strType += "ARRAY";
  1263. break;
  1264. default:
  1265. break;
  1266. }
  1267. pBuf = new byte[tagValue[0].nDataLength];
  1268. unsafe
  1269. {
  1270. byte* memBytePtr = (byte*)tagValue[0].pData.ToPointer();
  1271. for (int j = 0; j < tagValue[0].nDataLength; j++)
  1272. {
  1273. pBuf[j] = memBytePtr[j];
  1274. //string str = "";
  1275. //str += j.ToString() + ": ";
  1276. //str += "0x" + String.Format("{0:X2}", memBytePtr[j]) + "\n";
  1277. }
  1278. }
  1279. DeleteTagListStru(ref tagValue[0], 1); //调用接口释放内存
  1280. }
  1281. }
  1282. else
  1283. {
  1284. return (-10, "元素个数参数错误,必须>0");
  1285. }
  1286. return (0, strType);
  1287. }
  1288. }
  1289. public (int, string) Write_Tag(string strTagName, int nCount, byte[] pBuf)
  1290. {
  1291. lock (m_objLock)
  1292. {
  1293. if (!m_bConnected) return (-1, "未连接");
  1294. string tagName = strTagName;
  1295. byte[] tagNameUTF8 = Encoding.UTF8.GetBytes(tagName);
  1296. if (m_nInstanceId <= 0)
  1297. {
  1298. return (-2, "实例ID需大于0");
  1299. }
  1300. if (tagNameUTF8.Length > 255)
  1301. {
  1302. return (-3, "标签名长度超过255字节");
  1303. }
  1304. ushort elementCount = (ushort)nCount;
  1305. if ((pBuf.Length < 1) || (elementCount < 1))
  1306. {
  1307. return (-4, "请求个数必须大于0,请重新输入");
  1308. }
  1309. if (pBuf.Length > 1400)
  1310. {
  1311. return (-5, "标签数据长度超过1400字节,请重新输入");
  1312. }
  1313. int dataLength = pBuf.Length;
  1314. tagTagWriteDataBase[] pTaglist = new tagTagWriteDataBase[1];
  1315. //标签1属性
  1316. pTaglist[0].pName = tagName;
  1317. pTaglist[0].nElementCount = elementCount;
  1318. pTaglist[0].pType = TAG_TYPE.TAG_TYPE_UNDEFINE;
  1319. pTaglist[0].pData = Marshal.AllocHGlobal(1400);
  1320. pTaglist[0].nDataLength = dataLength;
  1321. byte temp = 0;
  1322. for (int i = 0; i < dataLength; ++i)
  1323. {
  1324. temp = pBuf[i];
  1325. Marshal.WriteByte(pTaglist[0].pData + i * sizeof(byte), temp);
  1326. }
  1327. //ERROR_NO errorNo = (ERROR_NO)EipWriteTag(m_nInstanceId, tagName, (int)type, source, dataLength, elementCount, arrayPos/*, strLen*/);
  1328. //ERROR_NO errorNo = (ERROR_NO)EipWriteTagExt(m_nInstanceId, tagName, (int)type, source, dataLength, elementCount);
  1329. ERROR_NO errorNo = EipWriteTagExt2(m_nInstanceId, pTaglist);
  1330. //ERROR_NO errorNo = EipWriteTagRaw(instanceId, pTaglist);
  1331. string strLog = "";
  1332. strLog += "\n写入请求 ";
  1333. if (errorNo != ERROR_NO.SUCCESS)
  1334. {
  1335. strLog += " 失败 标签名:" + tagName + " 实例ID:" + m_nInstanceId.ToString() + " ";
  1336. switch (errorNo)
  1337. {
  1338. case ERROR_NO.ERR_EIP_STOPED:
  1339. strLog += ("协议栈未开启");
  1340. break;
  1341. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  1342. strLog += ("连接的实例ID与已有的ID重复或超过最大值");
  1343. break;
  1344. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1345. strLog += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  1346. break;
  1347. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  1348. strLog += ("达到最大连接数量");
  1349. break;
  1350. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  1351. strLog += ("内存溢出,缓冲区已满");
  1352. break;
  1353. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1354. strLog += ("连接的网络地址无效");
  1355. break;
  1356. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  1357. strLog += ("连接无响应");
  1358. break;
  1359. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  1360. strLog += ("连接响应错误");
  1361. break;
  1362. case ERROR_NO.ERRR_INVALID_DESTINATION:
  1363. strLog += ("目标标签不存在");
  1364. break;
  1365. case ERROR_NO.ERRR_TAGNAME_TOO_LONG:
  1366. strLog += ("标签名超过255字节");
  1367. break;
  1368. case ERROR_NO.ERRR_REQUEST_DATA_TOO_LARGE:
  1369. strLog += ("请求数据超限");
  1370. break;
  1371. case ERROR_NO.ERRR_CONN_CONNECTION_TIMED_OUT:
  1372. strLog += ("响应超时,请检查设备是否离线");
  1373. break;
  1374. case ERROR_NO.ERRR_TAGNAME_CONVERT_FAILED:
  1375. strLog += ("标签名解析错误");
  1376. break;
  1377. case ERROR_NO.ERRR_WRITE_DATASIZE_UNCONSISTENT:
  1378. strLog += ("写入数据长度与标签实际长度不一致");
  1379. break;
  1380. case ERROR_NO.ERRR_SCAN_ERROR:
  1381. strLog += ("扫描标签信息失败");
  1382. break;
  1383. default:
  1384. strLog += ("其他错误");
  1385. break;
  1386. }
  1387. strLog += "\n";
  1388. return (10, strLog);
  1389. }
  1390. else
  1391. {
  1392. return (0, "OK");
  1393. }
  1394. }
  1395. }
  1396. /// <summary>
  1397. /// 标签结构
  1398. /// </summary>
  1399. public struct StructTag
  1400. {
  1401. public string strTagName;
  1402. public Type tTagType;
  1403. public int nCount;
  1404. }
  1405. /// <summary>
  1406. /// 一次读取多个标签
  1407. /// </summary>
  1408. /// <param name="stTagList">多个标签的列表</param>
  1409. /// <param name="pBuf">多个标签的返回值</param>
  1410. /// <returns>函数执行结构值,非零异常,零成功</returns>
  1411. public (int, string) Read_Tags(List<StructTag> stTagList, out byte[][] pBuf)
  1412. {
  1413. pBuf = null;
  1414. string strType = "";
  1415. lock (m_objLock)
  1416. {
  1417. if (!m_bConnected) return (-1, "未连接");
  1418. if (m_nInstanceId <= 0)
  1419. {
  1420. return (-2, "实例ID需大于0");
  1421. }
  1422. if (stTagList == null) return (-3, "标签列表空");
  1423. int nNumOfTags = stTagList.Count;
  1424. if (nNumOfTags < 1) return (-4, "标签列表长度空");
  1425. for (int i = 0; i < nNumOfTags; i++)
  1426. {
  1427. byte[] tagNameUTF8 = Encoding.UTF8.GetBytes(stTagList[i].strTagName);
  1428. if (tagNameUTF8.Length > 255)
  1429. {
  1430. return (-5, "标签名长度超过255字节");
  1431. }
  1432. if (stTagList[i].nCount < 1) return (-6, "标签读取长度小于1");
  1433. }
  1434. tagTagReadDataBase[] pTaglist = new tagTagReadDataBase[nNumOfTags];
  1435. for (int i = 0; i < nNumOfTags; i++)
  1436. {
  1437. pTaglist[i].pName = stTagList[i].strTagName;
  1438. pTaglist[i].nElementCount = stTagList[i].nCount;
  1439. }
  1440. tagTagRetValue[] pTagsValue = new tagTagRetValue[nNumOfTags];
  1441. pBuf = new byte[nNumOfTags][];
  1442. if (pBuf == null) return (-7, "分配内存失败,可能内存不足");
  1443. //ERROR_NO errorNo = (ERROR_NO)EipReadTagList(m_nInstanceId, nNumOfTags, pTaglist, ref pTagsValue[0]);
  1444. ERROR_NO errorNo = (ERROR_NO)EipReadTagListExt(m_nInstanceId, nNumOfTags, pTaglist, ref pTagsValue[0], true);
  1445. //ERROR_NO errorNo = (ERROR_NO)EipReadTagListRaw(m_nInstanceId, nNumOfTags, pTaglist, ref pTagsValue[0]);
  1446. string strLog = "";
  1447. strLog += "\n读取请求";
  1448. if (errorNo != ERROR_NO.SUCCESS)
  1449. {
  1450. strLog += " 失败 标签个数:" + nNumOfTags.ToString() + " 实例ID:" + m_nInstanceId.ToString() + " ";
  1451. switch (errorNo)
  1452. {
  1453. case ERROR_NO.ERR_EIP_STOPED:
  1454. strLog += ("协议栈未开启");
  1455. break;
  1456. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  1457. strLog += ("连接的实例ID与已有的ID重复或超过最大值");
  1458. break;
  1459. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1460. strLog += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  1461. break;
  1462. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  1463. strLog += ("达到最大连接数量");
  1464. break;
  1465. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  1466. strLog += ("内存溢出,缓冲区已满");
  1467. break;
  1468. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1469. strLog += ("连接的网络地址无效");
  1470. break;
  1471. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  1472. strLog += ("连接无响应");
  1473. break;
  1474. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  1475. strLog += ("连接响应错误");
  1476. break;
  1477. case ERROR_NO.ERRR_INVALID_DESTINATION:
  1478. strLog += ("目标标签不存在");
  1479. break;
  1480. case ERROR_NO.ERRR_TAGNAME_TOO_LONG:
  1481. strLog += ("标签名超过255字节");
  1482. break;
  1483. case ERROR_NO.ERRR_REQUEST_DATA_TOO_LARGE:
  1484. strLog += ("请求数据超限");
  1485. break;
  1486. case ERROR_NO.ERRR_CONN_CONNECTION_TIMED_OUT:
  1487. strLog += ("响应超时,请检查设备是否离线");
  1488. break;
  1489. case ERROR_NO.ERRR_TAGNAME_CONVERT_FAILED:
  1490. strLog += ("标签名解析错误");
  1491. break;
  1492. case ERROR_NO.ERRR_SCAN_ERROR:
  1493. strLog += ("扫描标签信息失败");
  1494. break;
  1495. default:
  1496. strLog += ("其他错误");
  1497. break;
  1498. }
  1499. strLog += "\n";
  1500. return (-10, strLog);
  1501. }
  1502. else
  1503. {
  1504. for (int i = 0; i < nNumOfTags; i++)
  1505. {
  1506. strType += "\n标签名:" + pTaglist[i].pName + " 类型:";
  1507. switch (pTagsValue[i].pType)
  1508. {
  1509. case TAG_TYPE.TAG_TYPE_BOOL:
  1510. strType += "BOOL";
  1511. break;
  1512. case TAG_TYPE.TAG_TYPE_SINT:
  1513. strType += "SINT";
  1514. break;
  1515. case TAG_TYPE.TAG_TYPE_INT:
  1516. strType += "INT";
  1517. break;
  1518. case TAG_TYPE.TAG_TYPE_DINT:
  1519. strType += "DINT";
  1520. break;
  1521. case TAG_TYPE.TAG_TYPE_LINT:
  1522. strType += "LINT";
  1523. break;
  1524. case TAG_TYPE.TAG_TYPE_USINT:
  1525. strType += "USINT";
  1526. break;
  1527. case TAG_TYPE.TAG_TYPE_UINT:
  1528. strType += "UINT";
  1529. break;
  1530. case TAG_TYPE.TAG_TYPE_UDINT:
  1531. strType += "UDINT";
  1532. break;
  1533. case TAG_TYPE.TAG_TYPE_ULINT:
  1534. strType += "ULINT";
  1535. break;
  1536. case TAG_TYPE.TAG_TYPE_REAL:
  1537. strType += "REAL";
  1538. break;
  1539. case TAG_TYPE.TAG_TYPE_LREAL:
  1540. strType += "LREAL";
  1541. break;
  1542. case TAG_TYPE.TAG_TYPE_STRING:
  1543. strType += "STRING";
  1544. break;
  1545. case TAG_TYPE.TAG_TYPE_BYTE:
  1546. strType += "BYTE";
  1547. break;
  1548. case TAG_TYPE.TAG_TYPE_WORD:
  1549. strType += "WORD";
  1550. break;
  1551. case TAG_TYPE.TAG_TYPE_DWORD:
  1552. strType += "DWORD";
  1553. break;
  1554. case TAG_TYPE.TAG_TYPE_LWORD:
  1555. strType += "LWORD";
  1556. break;
  1557. case TAG_TYPE.TAG_TYPE_STRUCT:
  1558. strType += "STRUCT";
  1559. break;
  1560. case TAG_TYPE.TAG_TYPE_ARRAY:
  1561. strType += "ARRAY";
  1562. break;
  1563. default:
  1564. strType += pTagsValue[i].pType.ToString();
  1565. break;
  1566. }
  1567. strType += " 元素个数:" + pTaglist[i].nElementCount.ToString();
  1568. strType += " 数据长度:" + pTagsValue[i].nDataLength.ToString() + "\n";
  1569. unsafe
  1570. {
  1571. byte* memBytePtr = (byte*)pTagsValue[i].pData.ToPointer();
  1572. pBuf[i] = new byte[pTagsValue[i].nDataLength];
  1573. for (int j = 0; j < pTagsValue[i].nDataLength; j++)
  1574. {
  1575. pBuf[i][j] = memBytePtr[j];
  1576. //string str = "";
  1577. ///str += j.ToString() + ": ";
  1578. //str += "0x" + String.Format("{0:X2}", memBytePtr[j]) + "\n";
  1579. }
  1580. }
  1581. }
  1582. }
  1583. DeleteTagListStru(ref pTagsValue[0], nNumOfTags); //调用接口释放内存
  1584. return (0, strType);
  1585. }
  1586. }
  1587. /// <summary>
  1588. /// 一次写多个标签
  1589. /// </summary>
  1590. /// <param name="TagList">将写入的标签列表</param>
  1591. /// <param name="ObjList">与标签列表对应的值对象</param>
  1592. /// <returns></returns>
  1593. public (int, string) Write_Tags(List<StructTag> TagList, List<Object> ObjList)
  1594. {
  1595. int size = 0;
  1596. byte[] pBuf = null;
  1597. int nRet = 0;
  1598. string strRet = "";
  1599. if (!m_bConnected) return (-1, "未连接");
  1600. if (m_nInstanceId <= 0) return (-2, "实例ID需大于0");
  1601. if (ObjList.Count != TagList.Count) return (-3, "标签列表和数据列表不一致");
  1602. int nLen = TagList.Count;
  1603. int nNumOfTags = TagList.Count;
  1604. tagTagWriteDataBase[] pTaglist = new tagTagWriteDataBase[nNumOfTags];
  1605. try
  1606. {
  1607. for (int i = 0; i < nLen; i++)
  1608. {
  1609. if (TagList[i].strTagName.Length > 255) return (-4, "标签名称长度超过255字节");
  1610. if (TagList[i].tTagType == null) return (-5, "标签类型不能空");
  1611. //标签属性
  1612. pTaglist[i].pName = TagList[i].strTagName;
  1613. pTaglist[i].nElementCount = TagList[i].nCount;
  1614. pTaglist[i].pType = TAG_TYPE.TAG_TYPE_UNDEFINE;
  1615. pTaglist[i].pData = Marshal.AllocHGlobal(1400);
  1616. //标签写入的数据
  1617. size = 0;
  1618. string str = TagList[i].tTagType.Name;
  1619. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  1620. bool containsAny = substrings.Any(substring => str.Contains(substring));
  1621. if (containsAny)
  1622. {
  1623. Type type = ObjList[i].GetType();
  1624. if (str != type.Name) return (120, "变量类型不一致");
  1625. }
  1626. if (str == "String")
  1627. {
  1628. string data = ObjList[i] as string;
  1629. pBuf = System.Text.Encoding.Default.GetBytes(data);
  1630. size = pBuf.Length;
  1631. if (size > 1400)
  1632. {
  1633. return (110, "数据长度超过1400字节,请重新输入");
  1634. }
  1635. }
  1636. else
  1637. {
  1638. if (TagList[i].tTagType.Name == "Boolean")
  1639. {
  1640. pBuf = new byte[1];
  1641. Type targetType = TagList[i].tTagType;
  1642. if ((bool)Convert.ChangeType(ObjList[i], targetType))
  1643. {
  1644. pBuf[0] = 1;
  1645. }
  1646. else
  1647. {
  1648. pBuf[0] = 0;
  1649. }
  1650. size = 1;
  1651. }
  1652. else
  1653. {
  1654. size = Marshal.SizeOf(TagList[i].tTagType);
  1655. pBuf = StructToBytes(ObjList[i], size);
  1656. }
  1657. }
  1658. //填充数据
  1659. for (int j = 0; j < size; j++)
  1660. {
  1661. Marshal.WriteByte(pTaglist[i].pData + j * sizeof(byte), pBuf[j]);
  1662. }
  1663. pTaglist[i].nDataLength = size;
  1664. }
  1665. ERROR_NO errorNo = ERROR_NO.SUCCESS;
  1666. lock (m_objLock)
  1667. {
  1668. //errorNo = EipWriteTagList(m_nInstanceId, nNumOfTags, pTaglist);
  1669. errorNo = EipWriteTagListExt(m_nInstanceId, nNumOfTags, pTaglist, true);
  1670. //errorNo = EipWriteTagListRaw(m_nInstanceId, nNumOfTags, pTaglist);
  1671. }
  1672. string strLog = "";
  1673. strLog += "\n写入请求";
  1674. if (errorNo != ERROR_NO.SUCCESS)
  1675. {
  1676. strLog += " 失败 标签个数:" + nNumOfTags.ToString() + " 实例ID:" + m_nInstanceId.ToString() + " ";
  1677. switch (errorNo)
  1678. {
  1679. case ERROR_NO.ERR_EIP_STOPED:
  1680. strLog += ("协议栈未开启");
  1681. break;
  1682. case ERROR_NO.ERRI_INVALID_CONNECTION_INSTANCE_SPECIFIED:
  1683. strLog += ("连接的实例ID与已有的ID重复或超过最大值");
  1684. break;
  1685. case ERROR_NO.ERRI_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1686. strLog += ("连接的网络路径格式错误,无法检测出来目标IP离线等错误");
  1687. break;
  1688. case ERROR_NO.ERRI_CONNECTION_COUNT_LIMIT_REACHED:
  1689. strLog += ("达到最大连接数量");
  1690. break;
  1691. case ERROR_NO.ERRI_OUT_OF_MEMORY:
  1692. strLog += ("内存溢出,缓冲区已满");
  1693. break;
  1694. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_INVALID_NETWORK_PATH:
  1695. strLog += ("连接的网络地址无效");
  1696. break;
  1697. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_NO_RESPONSE:
  1698. strLog += ("连接无响应");
  1699. break;
  1700. case ERROR_NO.ERRR_CONN_CONFIG_FAILED_ERROR_RESPONSE:
  1701. strLog += ("连接响应错误");
  1702. break;
  1703. case ERROR_NO.ERRR_INVALID_DESTINATION:
  1704. strLog += ("目标标签不存在");
  1705. break;
  1706. case ERROR_NO.ERRR_TAGNAME_TOO_LONG:
  1707. strLog += ("标签名超过255字节");
  1708. break;
  1709. case ERROR_NO.ERRR_REQUEST_DATA_TOO_LARGE:
  1710. strLog += ("请求数据超限");
  1711. break;
  1712. case ERROR_NO.ERRR_CONN_CONNECTION_TIMED_OUT:
  1713. strLog += ("响应超时,请检查设备是否离线");
  1714. break;
  1715. case ERROR_NO.ERRR_TAGNAME_CONVERT_FAILED:
  1716. strLog += ("标签名解析错误");
  1717. break;
  1718. case ERROR_NO.ERRR_WRITE_DATASIZE_UNCONSISTENT:
  1719. strLog += ("写入数据长度与标签实际长度不一致");
  1720. break;
  1721. case ERROR_NO.ERRR_SCAN_ERROR:
  1722. strLog += ("扫描标签信息失败");
  1723. break;
  1724. default:
  1725. strLog += ("其他错误");
  1726. break;
  1727. }
  1728. strLog += "\n";
  1729. strRet = strLog;
  1730. nRet = -10;
  1731. }
  1732. else
  1733. {
  1734. //成功
  1735. strRet = "OK";
  1736. nRet = 0;
  1737. }
  1738. }
  1739. catch (Exception ex)
  1740. {
  1741. nRet = 120;
  1742. strRet = ex.ToString();
  1743. }
  1744. finally
  1745. {
  1746. for (int i = 0; i < nLen; i++)
  1747. {
  1748. if (pTaglist[i].pData != ((IntPtr)0))
  1749. {
  1750. Marshal.FreeHGlobal(pTaglist[i].pData);
  1751. pTaglist[i].pData = (IntPtr)0;
  1752. }
  1753. }
  1754. }
  1755. return (nRet, strRet);
  1756. }
  1757. /// <summary>
  1758. /// 一次读取Bool标签或Bool数组标签
  1759. /// </summary>
  1760. /// <param name="strTagName">标签的名称</param>
  1761. /// <param name="nCount">读取的标签个数</param>
  1762. /// <param name="boolBuf">相应标签的返回值</param>
  1763. /// <returns>函数返回结果</returns>
  1764. public (int, string) Read_Bool_Tag(string strTagName, int nCount, out bool[] boolBuf)
  1765. {
  1766. byte[] pBuf = null;
  1767. boolBuf = null;
  1768. int nRet = 0;
  1769. string strRet = "";
  1770. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  1771. if (nRet != 0) return (nRet, strRet);
  1772. return Parse_Bool_Tag(pBuf, out boolBuf);
  1773. }
  1774. /// <summary>
  1775. /// 一次写入Bool标签或Bool数组标签
  1776. /// </summary>
  1777. /// <param name="strTagName">标签的名称</param>
  1778. /// <param name="nCount">标签个数</param>
  1779. /// <param name="boolBuf">相应标签的写入值</param>
  1780. /// <returns>函数返回结果</returns>
  1781. public (int, string) Write_Bool_Tag(string strTagName, int nCount, bool[] boolBuf)
  1782. {
  1783. byte[] pBuf = null;
  1784. int nRet = 0;
  1785. string strRet = "";
  1786. pBuf = BoolToBytes(boolBuf);
  1787. if (pBuf == null) return (1, "缓存区空");
  1788. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  1789. return (nRet, strRet);
  1790. }
  1791. //将转换为Byte数组
  1792. public static byte[] BoolToBytes(bool[] boolBuf)
  1793. {
  1794. if (boolBuf==null) return null;
  1795. int nNum = 0;
  1796. nNum = boolBuf.Length;
  1797. if (nNum < 1) return null;
  1798. byte[] bytes = new byte[nNum];
  1799. for (int i = 0; i < nNum; i++)
  1800. {
  1801. if (boolBuf[i])
  1802. bytes[i] = 1;
  1803. else
  1804. bytes[i] = 0;
  1805. }
  1806. return bytes;
  1807. }
  1808. public (int, string) Parse_Bool_Tag(byte[] pBuf, out bool[] boolBuf)
  1809. {
  1810. boolBuf = null;
  1811. int nNum = 0;
  1812. nNum = pBuf.Length;
  1813. if (nNum < 1) return (1, "Parse Failed");
  1814. boolBuf = new bool[nNum];
  1815. for (int i = 0; i < nNum; i++)
  1816. {
  1817. byte[] databuf = new byte[1] {0};
  1818. databuf[0] = pBuf[i];
  1819. bool iTemp = BitConverter.ToBoolean(databuf, 0);
  1820. boolBuf[i] = iTemp;
  1821. }
  1822. return (0, "OK");
  1823. }
  1824. public (int, string) Read_Byte_Tag(string strTagName, int nCount, out byte[] pBuf)
  1825. {
  1826. return Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  1827. }
  1828. public (int, string) Write_Byte_Tag(string strTagName, int nCount, byte[] pBuf)
  1829. {
  1830. return Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  1831. }
  1832. public (int, string) Read_SInt_Tag(string strTagName, int nCount, out sbyte[] sintBuf)
  1833. {
  1834. byte[] pBuf = null;
  1835. sintBuf = null;
  1836. int nRet = 0;
  1837. string strRet = "";
  1838. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  1839. if (nRet != 0) return (nRet, strRet);
  1840. return Parse_SInt_Tag(pBuf, out sintBuf);
  1841. }
  1842. public (int, string) Write_SInt_Tag(string strTagName, int nCount, sbyte[] DataBuf)
  1843. {
  1844. byte[] pBuf = null;
  1845. int nRet = 0;
  1846. string strRet = "";
  1847. pBuf = SByteToBytes(DataBuf);
  1848. if (pBuf == null) return (1, "pBuf is Null");
  1849. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  1850. return (nRet, strRet);
  1851. }
  1852. //将转换为Byte数组
  1853. public static byte[] SByteToBytes(sbyte[] DataBuf)
  1854. {
  1855. if (DataBuf == null || DataBuf.Length <= 0) return null;
  1856. int nNum = 0;
  1857. nNum = DataBuf.Length;
  1858. if (nNum < 1) return null;
  1859. byte[] bytes = new byte[nNum];
  1860. for (int i = 0; i < nNum; i++)
  1861. {
  1862. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  1863. bytes[i] = databuf[0];
  1864. }
  1865. return bytes;
  1866. }
  1867. public (int, string) Parse_SInt_Tag(byte[] pBuf, out sbyte[] sintBuf)
  1868. {
  1869. sintBuf = null;
  1870. int nNum = 0;
  1871. nNum = pBuf.Length;
  1872. if (nNum < 1) return (1, "Parse Failed");
  1873. sintBuf = new sbyte[nNum];
  1874. for (int i = 0; i < nNum; i++)
  1875. {
  1876. sintBuf[i] = (sbyte)pBuf[i];
  1877. }
  1878. return (0, "OK");
  1879. }
  1880. public (int, string) Read_String_Tag(string strTagName, int nCount, out string strBuf)
  1881. {
  1882. int nRet=0;
  1883. string strRet = "";
  1884. byte[] pBuf = null;
  1885. strBuf = "";
  1886. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  1887. if (nRet == 0)
  1888. strBuf = System.Text.Encoding.UTF8.GetString(pBuf);
  1889. return (nRet, strRet);
  1890. }
  1891. public (int, string) Write_String_Tag(string strTagName, int nCount, string strBuf)
  1892. {
  1893. int nRet = 0;
  1894. string strRet = "";
  1895. byte[] pBuf = null;
  1896. if (string.IsNullOrEmpty(strBuf)) return (1, "string is null");
  1897. pBuf = System.Text.Encoding.UTF8.GetBytes(strBuf);
  1898. if (pBuf == null || pBuf.Length == 0 ) return (2, "pBuf is null");
  1899. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  1900. return (nRet, strRet);
  1901. }
  1902. public (int, string) Parse_String_Tag(byte[] pBuf, out string strBuf)
  1903. {
  1904. int nRet = 0;
  1905. string strRet = "";
  1906. strBuf = "";
  1907. strBuf = System.Text.Encoding.UTF8.GetString(pBuf);
  1908. return (nRet, strRet);
  1909. }
  1910. public (int, string) Read_Word_Tag(string strTagName, int nCount, out ushort[] wordBuf)
  1911. {
  1912. return Read_UInt_Tag(strTagName, nCount, out wordBuf);
  1913. }
  1914. public (int, string) Write_Word_Tag(string strTagName, int nCount, ushort[] wordBuf)
  1915. {
  1916. return Write_UInt_Tag(strTagName, nCount, wordBuf);
  1917. }
  1918. public (int, string) Read_DWord_Tag(string strTagName, int nCount, out uint[] dwordBuf)
  1919. {
  1920. return Read_UDInt_Tag(strTagName, nCount, out dwordBuf);
  1921. }
  1922. public (int, string) Write_DWord_Tag(string strTagName, int nCount, uint[] dwordBuf)
  1923. {
  1924. return Write_UDInt_Tag(strTagName, nCount, dwordBuf);
  1925. }
  1926. public (int, string) Read_LWord_Tag(string strTagName, int nCount, out ulong[] lwordBuf)
  1927. {
  1928. return Read_ULInt_Tag(strTagName, nCount, out lwordBuf);
  1929. }
  1930. public (int, string) Write_LWord_Tag(string strTagName, int nCount, ulong[] lwordBuf)
  1931. {
  1932. return Write_ULInt_Tag(strTagName, nCount, lwordBuf);
  1933. }
  1934. /// <summary>
  1935. /// read 16bit int
  1936. /// </summary>
  1937. /// <param name="strTagName"></param>
  1938. /// <param name="nCount"></param>
  1939. /// <param name="intBuf"></param>
  1940. /// <returns></returns>
  1941. public (int, string) Read_Int_Tag(string strTagName, int nCount, out short[] intBuf)
  1942. {
  1943. byte[] pBuf = null;
  1944. intBuf = null;
  1945. int nRet=0;
  1946. string strRet = "";
  1947. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  1948. if (nRet != 0) return (nRet, strRet);
  1949. return Parse_Int_Tag(pBuf, out intBuf);
  1950. }
  1951. public (int, string) Parse_Int_Tag(byte[] pBuf, out short[] intBuf)
  1952. {
  1953. intBuf = null;
  1954. int nNum = 0;
  1955. nNum = pBuf.Length / 2;
  1956. if (nNum < 1) return (1, "Parse Failed");
  1957. intBuf = new short[nNum];
  1958. for (int i = 0; i < nNum; i++)
  1959. {
  1960. byte[] databuf = new byte[2] { 0, 0 };
  1961. databuf[0] = pBuf[i * 2];
  1962. databuf[1] = pBuf[i * 2 + 1];
  1963. short iTemp = BitConverter.ToInt16(databuf, 0);
  1964. intBuf[i] = iTemp;
  1965. }
  1966. return (0, "OK");
  1967. }
  1968. public (int, string) Write_Int_Tag(string strTagName, int nCount, short[] DataBuf)
  1969. {
  1970. byte[] pBuf = null;
  1971. int nRet = 0;
  1972. string strRet = "";
  1973. pBuf = ShortToBytes(DataBuf);
  1974. if (pBuf == null ) return (1, "pBuf is Null");
  1975. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  1976. return (nRet, strRet);
  1977. }
  1978. //将转换为Byte数组
  1979. public static byte[] ShortToBytes(short[] DataBuf)
  1980. {
  1981. if (DataBuf == null || DataBuf.Length<=0) return null;
  1982. int nNum = 0;
  1983. //int size = Marshal.SizeOf(typeof(short));
  1984. //int size = sizeof(short);
  1985. nNum = DataBuf.Length;
  1986. if (nNum < 1) return null;
  1987. byte[] bytes = new byte[nNum*2];
  1988. for (int i = 0; i < nNum; i++)
  1989. {
  1990. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  1991. bytes[i * 2] = databuf[0];
  1992. bytes[i * 2 + 1] = databuf[1];
  1993. }
  1994. return bytes;
  1995. }
  1996. /// <summary>
  1997. /// 16bit uint
  1998. /// </summary>
  1999. /// <param name="strTagName"></param>
  2000. /// <param name="nCount"></param>
  2001. /// <param name="uintBuf"></param>
  2002. /// <returns></returns>
  2003. public (int, string) Read_UInt_Tag(string strTagName, int nCount, out UInt16[] uintBuf)
  2004. {
  2005. byte[] pBuf = null;
  2006. uintBuf = null;
  2007. int nRet = 0;
  2008. string strRet = "";
  2009. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2010. if (nRet != 0) return (nRet, strRet);
  2011. return Parse_UInt_Tag(pBuf, out uintBuf);
  2012. }
  2013. public (int, string) Write_UInt_Tag(string strTagName, int nCount, ushort[] DataBuf)
  2014. {
  2015. byte[] pBuf = null;
  2016. int nRet = 0;
  2017. string strRet = "";
  2018. pBuf = UShortToBytes(DataBuf);
  2019. if (pBuf == null) return (1, "pBuf is Null");
  2020. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2021. return (nRet, strRet);
  2022. }
  2023. //将转换为Byte数组
  2024. public static byte[] UShortToBytes(ushort[] DataBuf)
  2025. {
  2026. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2027. int nNum = 0;
  2028. //int size = Marshal.SizeOf(typeof(short));
  2029. //int size = sizeof(short);
  2030. nNum = DataBuf.Length;
  2031. if (nNum < 1) return null;
  2032. byte[] bytes = new byte[nNum*2];
  2033. for (int i = 0; i < nNum; i++)
  2034. {
  2035. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2036. bytes[i * 2] = databuf[0];
  2037. bytes[i * 2 + 1] = databuf[1];
  2038. }
  2039. return bytes;
  2040. }
  2041. public (int, string) Parse_UInt_Tag(byte[] pBuf, out UInt16[] uintBuf)
  2042. {
  2043. uintBuf = null;
  2044. int nNum = 0;
  2045. nNum = pBuf.Length / 2;
  2046. if (nNum < 1) return (1, "Parse Failed");
  2047. uintBuf = new UInt16[nNum];
  2048. for (int i = 0; i < nNum; i++)
  2049. {
  2050. byte[] databuf = new byte[2] { 0, 0 };
  2051. databuf[0] = pBuf[i * 2];
  2052. databuf[1] = pBuf[i * 2 + 1];
  2053. UInt16 iTemp = BitConverter.ToUInt16(databuf, 0);
  2054. uintBuf[i] = iTemp;
  2055. }
  2056. return (0, "OK");
  2057. }
  2058. /// <summary>
  2059. /// 32bits int
  2060. /// </summary>
  2061. /// <param name="strTagName"></param>
  2062. /// <param name="nCount"></param>
  2063. /// <param name="intBuf"></param>
  2064. /// <returns></returns>
  2065. public (int, string) Read_DInt_Tag(string strTagName, int nCount, out int[] intBuf)
  2066. {
  2067. byte[] pBuf = null;
  2068. intBuf = null;
  2069. int nRet = 0;
  2070. string strRet = "";
  2071. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2072. if (nRet != 0) return (nRet, strRet);
  2073. return Parse_DInt_Tag(pBuf, out intBuf);
  2074. }
  2075. public (int, string) Write_DInt_Tag(string strTagName, int nCount, int[] DataBuf)
  2076. {
  2077. byte[] pBuf = null;
  2078. int nRet = 0;
  2079. string strRet = "";
  2080. pBuf = DIntToBytes(DataBuf);
  2081. if (pBuf == null) return (1, "pBuf is Null");
  2082. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2083. return (nRet, strRet);
  2084. }
  2085. //将转换为Byte数组
  2086. public static byte[] DIntToBytes(int[] DataBuf)
  2087. {
  2088. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2089. int nNum = 0;
  2090. nNum = DataBuf.Length;
  2091. if (nNum < 1) return null;
  2092. byte[] bytes = new byte[nNum*4];
  2093. for (int i = 0; i < nNum; i++)
  2094. {
  2095. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2096. bytes[i * 4] = databuf[0];
  2097. bytes[i * 4 + 1] = databuf[1];
  2098. bytes[i * 4 + 2] = databuf[2];
  2099. bytes[i * 4 + 3] = databuf[3];
  2100. }
  2101. return bytes;
  2102. }
  2103. public (int, string) Parse_DInt_Tag(byte[] pBuf, out int[] intBuf)
  2104. {
  2105. intBuf = null;
  2106. int nNum = 0;
  2107. nNum = pBuf.Length / 4;
  2108. if (nNum < 1) return (1, "Parse Failed");
  2109. intBuf = new int[nNum];
  2110. for (int i = 0; i < nNum; i++)
  2111. {
  2112. byte[] databuf = new byte[4] { 0, 0, 0, 0 };
  2113. databuf[0] = pBuf[i * 4];
  2114. databuf[1] = pBuf[i * 4 + 1];
  2115. databuf[2] = pBuf[i * 4 + 2];
  2116. databuf[3] = pBuf[i * 4 + 3];
  2117. int iTemp = BitConverter.ToInt32(databuf, 0);
  2118. intBuf[i] = iTemp;
  2119. }
  2120. return (0, "OK");
  2121. }
  2122. /// <summary>
  2123. /// 无符号32位整数
  2124. /// </summary>
  2125. /// <param name="strTagName"></param>
  2126. /// <param name="nCount"></param>
  2127. /// <param name="intBuf"></param>
  2128. /// <returns></returns>
  2129. public (int, string) Read_UDInt_Tag(string strTagName, int nCount, out uint[] uintBuf)
  2130. {
  2131. byte[] pBuf = null;
  2132. uintBuf = null;
  2133. int nRet = 0;
  2134. string strRet = "";
  2135. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2136. if (nRet != 0) return (nRet, strRet);
  2137. return Parse_UDInt_Tag(pBuf, out uintBuf);
  2138. }
  2139. public (int, string) Write_UDInt_Tag(string strTagName, int nCount, uint[] DataBuf)
  2140. {
  2141. byte[] pBuf = null;
  2142. int nRet = 0;
  2143. string strRet = "";
  2144. pBuf = UDIntToBytes(DataBuf);
  2145. if (pBuf == null) return (1, "pBuf is Null");
  2146. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2147. return (nRet, strRet);
  2148. }
  2149. //将转换为Byte数组
  2150. public static byte[] UDIntToBytes(uint[] DataBuf)
  2151. {
  2152. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2153. int nNum = 0;
  2154. nNum = DataBuf.Length;
  2155. if (nNum < 1) return null;
  2156. byte[] bytes = new byte[nNum * 4];
  2157. for (int i = 0; i < nNum; i++)
  2158. {
  2159. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2160. bytes[i * 4] = databuf[0];
  2161. bytes[i * 4 + 1] = databuf[1];
  2162. bytes[i * 4 + 2] = databuf[2];
  2163. bytes[i * 4 + 3] = databuf[3];
  2164. }
  2165. return bytes;
  2166. }
  2167. public (int, string) Parse_UDInt_Tag(byte[] pBuf, out uint[] uintBuf)
  2168. {
  2169. uintBuf = null;
  2170. int nNum = 0;
  2171. nNum = pBuf.Length / 4;
  2172. if (nNum < 1) return (1, "Parse Failed");
  2173. uintBuf = new uint[nNum];
  2174. for (int i = 0; i < nNum; i++)
  2175. {
  2176. byte[] databuf = new byte[4] { 0, 0, 0, 0 };
  2177. databuf[0] = pBuf[i * 4];
  2178. databuf[1] = pBuf[i * 4 + 1];
  2179. databuf[2] = pBuf[i * 4 + 2];
  2180. databuf[3] = pBuf[i * 4 + 3];
  2181. uint iTemp = BitConverter.ToUInt32(databuf, 0);
  2182. uintBuf[i] = iTemp;
  2183. }
  2184. return (0, "OK");
  2185. }
  2186. public (int, string) Read_LInt_Tag(string strTagName, int nCount, out long[] longBuf)
  2187. {
  2188. byte[] pBuf = null;
  2189. longBuf = null;
  2190. int nRet = 0;
  2191. string strRet = "";
  2192. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2193. if (nRet != 0) return (nRet, strRet);
  2194. return Parse_LInt_Tag(pBuf, out longBuf);
  2195. }
  2196. public (int, string) Write_LInt_Tag(string strTagName, int nCount, long[] DataBuf)
  2197. {
  2198. byte[] pBuf = null;
  2199. int nRet = 0;
  2200. string strRet = "";
  2201. pBuf = LIntToBytes(DataBuf);
  2202. if (pBuf == null) return (1, "pBuf is Null");
  2203. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2204. return (nRet, strRet);
  2205. }
  2206. //将转换为Byte数组
  2207. public static byte[] LIntToBytes(long[] DataBuf)
  2208. {
  2209. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2210. int nNum = 0;
  2211. nNum = DataBuf.Length;
  2212. if (nNum < 1) return null;
  2213. byte[] bytes = new byte[nNum * 8];
  2214. for (int i = 0; i < nNum; i++)
  2215. {
  2216. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2217. bytes[i * 4] = databuf[0];
  2218. bytes[i * 4 + 1] = databuf[1];
  2219. bytes[i * 4 + 2] = databuf[2];
  2220. bytes[i * 4 + 3] = databuf[3];
  2221. bytes[i * 4 + 4] = databuf[4];
  2222. bytes[i * 4 + 5] = databuf[5];
  2223. bytes[i * 4 + 6] = databuf[6];
  2224. bytes[i * 4 + 7] = databuf[7];
  2225. }
  2226. return bytes;
  2227. }
  2228. public (int, string) Parse_LInt_Tag(byte[] pBuf, out long[] longBuf)
  2229. {
  2230. longBuf = null;
  2231. int nNum = 0;
  2232. nNum = pBuf.Length / 8;
  2233. if (nNum < 1) return (1, "Parse Failed");
  2234. longBuf = new long[nNum];
  2235. for (int i = 0; i < nNum; i++)
  2236. {
  2237. byte[] databuf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
  2238. databuf[0] = pBuf[i * 4];
  2239. databuf[1] = pBuf[i * 4 + 1];
  2240. databuf[2] = pBuf[i * 4 + 2];
  2241. databuf[3] = pBuf[i * 4 + 3];
  2242. databuf[4] = pBuf[i * 4 + 4];
  2243. databuf[5] = pBuf[i * 4 + 5];
  2244. databuf[6] = pBuf[i * 4 + 6];
  2245. databuf[7] = pBuf[i * 4 + 7];
  2246. long iTemp = BitConverter.ToInt64(databuf, 0);
  2247. longBuf[i] = iTemp;
  2248. }
  2249. return (0, "OK");
  2250. }
  2251. /// <summary>
  2252. /// 无符号64整数
  2253. /// </summary>
  2254. /// <param name="strTagName"></param>
  2255. /// <param name="nCount"></param>
  2256. /// <param name="ulongBuf"></param>
  2257. /// <returns></returns>
  2258. public (int, string) Read_ULInt_Tag(string strTagName, int nCount, out ulong[] ulongBuf)
  2259. {
  2260. byte[] pBuf = null;
  2261. ulongBuf = null;
  2262. int nRet = 0;
  2263. string strRet = "";
  2264. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2265. if (nRet != 0) return (nRet, strRet);
  2266. return Parse_ULInt_Tag(pBuf, out ulongBuf);
  2267. }
  2268. public (int, string) Write_ULInt_Tag(string strTagName, int nCount, ulong[] DataBuf)
  2269. {
  2270. byte[] pBuf = null;
  2271. int nRet = 0;
  2272. string strRet = "";
  2273. pBuf = ULIntToBytes(DataBuf);
  2274. if (pBuf == null) return (1, "pBuf is Null");
  2275. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2276. return (nRet, strRet);
  2277. }
  2278. //将转换为Byte数组
  2279. public static byte[] ULIntToBytes(ulong[] DataBuf)
  2280. {
  2281. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2282. int nNum = 0;
  2283. nNum = DataBuf.Length;
  2284. if (nNum < 1) return null;
  2285. byte[] bytes = new byte[nNum * 8];
  2286. for (int i = 0; i < nNum; i++)
  2287. {
  2288. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2289. bytes[i * 4] = databuf[0];
  2290. bytes[i * 4 + 1] = databuf[1];
  2291. bytes[i * 4 + 2] = databuf[2];
  2292. bytes[i * 4 + 3] = databuf[3];
  2293. bytes[i * 4 + 4] = databuf[4];
  2294. bytes[i * 4 + 5] = databuf[5];
  2295. bytes[i * 4 + 6] = databuf[6];
  2296. bytes[i * 4 + 7] = databuf[7];
  2297. }
  2298. return bytes;
  2299. }
  2300. public (int, string) Parse_ULInt_Tag(byte[] pBuf, out ulong[] ulongBuf)
  2301. {
  2302. ulongBuf = null;
  2303. int nNum = 0;
  2304. nNum = pBuf.Length / 8;
  2305. if (nNum < 1) return (1, "Parse Failed");
  2306. ulongBuf = new ulong[nNum];
  2307. for (int i = 0; i < nNum; i++)
  2308. {
  2309. byte[] databuf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
  2310. databuf[0] = pBuf[i * 4];
  2311. databuf[1] = pBuf[i * 4 + 1];
  2312. databuf[2] = pBuf[i * 4 + 2];
  2313. databuf[3] = pBuf[i * 4 + 3];
  2314. databuf[4] = pBuf[i * 4 + 4];
  2315. databuf[5] = pBuf[i * 4 + 5];
  2316. databuf[6] = pBuf[i * 4 + 6];
  2317. databuf[7] = pBuf[i * 4 + 7];
  2318. ulong iTemp = BitConverter.ToUInt64(databuf, 0);
  2319. ulongBuf[i] = iTemp;
  2320. }
  2321. return (0, "OK");
  2322. }
  2323. public (int, string) Read_Real_Tag(string strTagName, int nCount, out float[] floatBuf)
  2324. {
  2325. floatBuf = null;
  2326. byte[] pBuf = null;
  2327. int nRet = 0;
  2328. string strRet = "";
  2329. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2330. if (nRet != 0) return (nRet, strRet);
  2331. return Parse_Real_Tag(pBuf, out floatBuf);
  2332. }
  2333. public (int, string) Write_Real_Tag(string strTagName, int nCount, float[] DataBuf)
  2334. {
  2335. byte[] pBuf = null;
  2336. int nRet = 0;
  2337. string strRet = "";
  2338. pBuf = RealToBytes(DataBuf);
  2339. if (pBuf == null) return (1, "pBuf is Null");
  2340. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2341. return (nRet, strRet);
  2342. }
  2343. //将转换为Byte数组
  2344. public static byte[] RealToBytes(float[] DataBuf)
  2345. {
  2346. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2347. int nNum = 0;
  2348. nNum = DataBuf.Length;
  2349. if (nNum < 1) return null;
  2350. byte[] bytes = new byte[nNum * 4];
  2351. for (int i = 0; i < nNum; i++)
  2352. {
  2353. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2354. bytes[i * 4] = databuf[0];
  2355. bytes[i * 4 + 1] = databuf[1];
  2356. bytes[i * 4 + 2] = databuf[2];
  2357. bytes[i * 4 + 3] = databuf[3];
  2358. }
  2359. return bytes;
  2360. }
  2361. public (int, string) Parse_Real_Tag(byte[] pBuf, out float[] floatBuf)
  2362. {
  2363. floatBuf = null;
  2364. int nNum = 0;
  2365. nNum = pBuf.Length / 4;
  2366. floatBuf = new float[nNum];
  2367. if (nNum < 1) return (1, "Parse Failed");
  2368. for (int i = 0; i < nNum; i++)
  2369. {
  2370. byte[] databuf = new byte[4] { 0, 0, 0, 0 };
  2371. databuf[0] = pBuf[i * 4];
  2372. databuf[1] = pBuf[i * 4 + 1];
  2373. databuf[2] = pBuf[i * 4 + 2];
  2374. databuf[3] = pBuf[i * 4 + 3];
  2375. float fTemp = BitConverter.ToSingle(databuf, 0);
  2376. floatBuf[i] = fTemp;
  2377. }
  2378. return (0, "OK");
  2379. }
  2380. public (int, string) Read_LReal_Tag(string strTagName, int nCount, out double[] doubleBuf)
  2381. {
  2382. doubleBuf = null;
  2383. byte[] pBuf = null;
  2384. int nRet = 0;
  2385. string strRet = "";
  2386. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2387. if (nRet != 0) return (nRet, strRet);
  2388. return Parse_LReal_Tag(pBuf, out doubleBuf);
  2389. }
  2390. public (int, string) Write_LReal_Tag(string strTagName, int nCount, double[] DataBuf)
  2391. {
  2392. byte[] pBuf = null;
  2393. int nRet = 0;
  2394. string strRet = "";
  2395. pBuf = LRealToBytes(DataBuf);
  2396. if (pBuf == null) return (1, "pBuf is Null");
  2397. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2398. return (nRet, strRet);
  2399. }
  2400. //将转换为Byte数组
  2401. public static byte[] LRealToBytes(double[] DataBuf)
  2402. {
  2403. if (DataBuf == null || DataBuf.Length <= 0) return null;
  2404. int nNum = 0;
  2405. nNum = DataBuf.Length;
  2406. if (nNum < 1) return null;
  2407. byte[] bytes = new byte[nNum * 8];
  2408. for (int i = 0; i < nNum; i++)
  2409. {
  2410. byte[] databuf = BitConverter.GetBytes(DataBuf[i]);
  2411. bytes[i * 4] = databuf[0];
  2412. bytes[i * 4 + 1] = databuf[1];
  2413. bytes[i * 4 + 2] = databuf[2];
  2414. bytes[i * 4 + 3] = databuf[3];
  2415. bytes[i * 4 + 4] = databuf[4];
  2416. bytes[i * 4 + 5] = databuf[5];
  2417. bytes[i * 4 + 6] = databuf[6];
  2418. bytes[i * 4 + 7] = databuf[7];
  2419. }
  2420. return bytes;
  2421. }
  2422. public (int, string) Parse_LReal_Tag(byte[] pBuf, out double[] doubleBuf)
  2423. {
  2424. doubleBuf = null;
  2425. int nNum = 0;
  2426. nNum = pBuf.Length / 8;
  2427. if (nNum < 1) return (1, "Parse Failed");
  2428. doubleBuf = new double[nNum];
  2429. for (int i = 0; i < nNum; i++)
  2430. {
  2431. byte[] databuf = new byte[8] { 0, 0, 0, 0, 0, 0, 0, 0 };
  2432. databuf[0] = pBuf[i * 8];
  2433. databuf[1] = pBuf[i * 8 + 1];
  2434. databuf[2] = pBuf[i * 8 + 2];
  2435. databuf[3] = pBuf[i * 8 + 3];
  2436. databuf[4] = pBuf[i * 8 + 4];
  2437. databuf[5] = pBuf[i * 8 + 5];
  2438. databuf[6] = pBuf[i * 8 + 6];
  2439. databuf[7] = pBuf[i * 8 + 7];
  2440. double dTemp = BitConverter.ToDouble(databuf, 0);
  2441. doubleBuf[i] = dTemp;
  2442. }
  2443. return (0, "OK");
  2444. }
  2445. #region 对象与字节数组转化
  2446. //将结构体类型转换为Byte数组
  2447. public static byte[] StructToBytes(object structObj, int size)
  2448. {
  2449. byte[] bytes = new byte[size];
  2450. IntPtr structPtr = Marshal.AllocHGlobal(size);
  2451. try
  2452. {
  2453. //将结构体拷到分配好的内存空间
  2454. Marshal.StructureToPtr(structObj, structPtr, false);
  2455. //从内存空间拷贝到byte 数组
  2456. Marshal.Copy(structPtr, bytes, 0, size);
  2457. }
  2458. finally
  2459. {
  2460. //释放内存空间
  2461. Marshal.FreeHGlobal(structPtr);
  2462. }
  2463. return bytes;
  2464. }
  2465. //将Byte转换为结构体类型
  2466. public static object ByteToStruct(byte[] bytes, Type type)
  2467. {
  2468. int size = Marshal.SizeOf(type);
  2469. if (type.Name == "Boolean") size = 1;
  2470. if (size > bytes.Length)
  2471. {
  2472. return null;
  2473. }
  2474. //分配结构体内存空间
  2475. IntPtr structPtr = Marshal.AllocHGlobal(size);
  2476. object obj = null;
  2477. try
  2478. {
  2479. //将byte数组拷贝到分配好的内存空间
  2480. Marshal.Copy(bytes, 0, structPtr, size);
  2481. //将内存空间转换为目标结构体
  2482. obj = Marshal.PtrToStructure(structPtr, type);
  2483. }
  2484. finally
  2485. {
  2486. //释放内存空间
  2487. Marshal.FreeHGlobal(structPtr);
  2488. }
  2489. return obj;
  2490. }
  2491. //将Byte转换为结构体类型
  2492. public static Object ByteToStruct2(byte[] bytes, Type type)
  2493. {
  2494. int size = Marshal.SizeOf(type);
  2495. if (type.Name == "Boolean") size = 1;
  2496. if (size > bytes.Length)
  2497. {
  2498. return null;
  2499. }
  2500. //分配结构体内存空间
  2501. IntPtr structPtr = Marshal.AllocHGlobal(size);
  2502. object obj = null;
  2503. try
  2504. {
  2505. //将byte数组拷贝到分配好的内存空间
  2506. Marshal.Copy(bytes, 0, structPtr, size);
  2507. //将内存空间转换为目标结构体
  2508. obj = Marshal.PtrToStructure(structPtr, type);
  2509. }
  2510. finally
  2511. {
  2512. //释放内存空间
  2513. Marshal.FreeHGlobal(structPtr);
  2514. }
  2515. return obj;
  2516. }
  2517. public static T ConvertBytesToStruct<T>(byte[] bytes)
  2518. {
  2519. // 将字节数组转换为结构体
  2520. GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
  2521. T myStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
  2522. handle.Free();
  2523. return myStruct;
  2524. }
  2525. #endregion 对象与字节数组转化
  2526. /// <summary>
  2527. /// 一次读取单个标签
  2528. /// </summary>
  2529. /// <typeparam name="T">需要读取的标签结构</typeparam>
  2530. /// <param name="strTagName">需要读取的标签名</param>
  2531. /// <param name="nCount">读取标签的个数</param>
  2532. /// <param name="outObj">返回相应标签值对象</param>
  2533. /// <returns></returns>
  2534. public (int, string) Read_SingleTag<T>(string strTagName, int nCount, out T outObj)
  2535. {
  2536. outObj = default(T);
  2537. byte[] pBuf = null;
  2538. int nRet = 0;
  2539. string strRet = "";
  2540. try
  2541. {
  2542. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2543. if (nRet != 0) return (nRet, strRet);
  2544. string str = typeof(T).Name;
  2545. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  2546. bool containsAny = substrings.Any(substring => str.Contains(substring));
  2547. if (containsAny)
  2548. {
  2549. if (str != strRet) return (120, "变量类型不一致");
  2550. }
  2551. if (str == "String")
  2552. {
  2553. outObj = (T)(object)System.Text.Encoding.UTF8.GetString(pBuf);
  2554. return (0, "OK");
  2555. }
  2556. outObj = (T)ByteToStruct(pBuf, typeof(T));
  2557. }
  2558. catch(Exception ex)
  2559. {
  2560. return (110, ex.ToString());
  2561. }
  2562. return (0, "OK");
  2563. }
  2564. public (int, string) Write_SingleTag<T>(string strTagName, int nCount, T inObj)
  2565. {
  2566. byte[] pBuf = null;
  2567. int nRet = 0;
  2568. string strRet = "";
  2569. int size = 0;
  2570. try
  2571. {
  2572. string str = typeof(T).Name;
  2573. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  2574. bool containsAny = substrings.Any(substring => str.Contains(substring));
  2575. if (containsAny)
  2576. {
  2577. Type type = inObj.GetType();
  2578. if (str != type.Name) return (120, "变量类型不一致");
  2579. }
  2580. if (str == "String")
  2581. {
  2582. //size = inObj.ToString().Length + 1;
  2583. string wtStr= inObj as string;
  2584. pBuf = System.Text.Encoding.Default.GetBytes(wtStr);
  2585. size = pBuf.Length;
  2586. }
  2587. else
  2588. {
  2589. if (typeof(T).Name == "Boolean")
  2590. {
  2591. //pBuf = new byte[1];
  2592. //Type targetType = typeof(T);
  2593. //if ((bool)Convert.ChangeType(inObj, targetType))
  2594. //{
  2595. // pBuf[0] = 1;
  2596. //}
  2597. //else
  2598. //{
  2599. // pBuf[0] = 0;
  2600. //}
  2601. size = 1;
  2602. }
  2603. else
  2604. {
  2605. size = Marshal.SizeOf(typeof(T));
  2606. }
  2607. pBuf = StructToBytes(inObj, size);
  2608. }
  2609. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2610. return (nRet, strRet);
  2611. }
  2612. catch (Exception ex)
  2613. {
  2614. return (110, ex.ToString());
  2615. }
  2616. }
  2617. /// <summary>
  2618. /// 一次读取多个标签
  2619. /// </summary>
  2620. /// <param name="stTagList">需要读取的标签列表信息</param>
  2621. /// <param name="outObj">返回的相应标签对象</param>
  2622. /// <returns>执行是否成功,非0不成功,以及显示相应的失败信息</returns>
  2623. public (int, string) Read_MultiTags(List<StructTag> stTagList, out List<Object> outObj)
  2624. {
  2625. outObj = new List<Object>();
  2626. byte[][] pBuf = null;
  2627. int nRet = 0;
  2628. string strRet = "";
  2629. int nLen = stTagList.Count;
  2630. List<StructTag> TagList=new List<StructTag>();
  2631. try
  2632. {
  2633. foreach(StructTag tag in stTagList)
  2634. {
  2635. TagList.Add(new StructTag {strTagName= strTagPrefix + tag.strTagName,tTagType=tag.tTagType,nCount=tag.nCount});
  2636. }
  2637. (nRet, strRet) = Read_Tags(TagList, out pBuf);
  2638. if (nRet != 0) return (nRet, strRet);
  2639. for (int i = 0; i < nLen; i++)
  2640. {
  2641. //需要调用的方法
  2642. //MethodInfo mi = typeof(Inovance_EIP).GetMethod("ByteToStruct");
  2643. //该方法的泛型类型Type->typeof(int)
  2644. //MethodInfo miConstructed = mi.MakeGenericMethod(strTagList[i].TagType);
  2645. //var arg = { pBuf[i]};
  2646. //执行调用
  2647. //miConstructed.Invoke(null, args);
  2648. //outObj.Add(Convert.ChangeType(ByteToStruct2(pBuf[i], targetType), targetType));
  2649. Type targetType = TagList[i].tTagType;
  2650. if (targetType != null)
  2651. {
  2652. object obj = ByteToStruct(pBuf[i], targetType);
  2653. //if (obj != null)
  2654. outObj.Add(obj);
  2655. }
  2656. }
  2657. }
  2658. catch (Exception ex)
  2659. {
  2660. return (110, ex.ToString());
  2661. }
  2662. return (0, "OK");
  2663. }
  2664. /// <summary>
  2665. /// 一次写多个标签
  2666. /// </summary>
  2667. /// <param name="stTagList">需要写入的标签列表信息</param>
  2668. /// <param name="ObjList">写入的相应标签对象</param>
  2669. /// <returns>执行是否成功,非0不成功,以及显示相应的失败信息</returns>
  2670. public (int, string) Write_MultiTags(List<StructTag> stTagList, List<Object> ObjList)
  2671. {
  2672. int nRet = 0;
  2673. string strRet = "";
  2674. int nLen = stTagList.Count;
  2675. if (ObjList.Count != nLen) return (10, "标签列表和对象列表长度不一致");
  2676. List<StructTag> TagList = new List<StructTag>();
  2677. try
  2678. {
  2679. foreach (StructTag tag in stTagList)
  2680. {
  2681. TagList.Add(new StructTag { strTagName = strTagPrefix + tag.strTagName, tTagType = tag.tTagType, nCount = tag.nCount });
  2682. }
  2683. (nRet, strRet) = Write_Tags(TagList, ObjList);
  2684. return (nRet, strRet);
  2685. }
  2686. catch (Exception ex)
  2687. {
  2688. return (110, ex.ToString());
  2689. }
  2690. }
  2691. #region 清除标签缓存
  2692. /// <summary>
  2693. /// 清除标签缓存
  2694. /// </summary>
  2695. public void Clear_TagCache()
  2696. {
  2697. ResetTagInfo();
  2698. }
  2699. #endregion 清除标签缓存
  2700. }
  2701. }