Inovance_EIP.cs 121 KB

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