Inovance_EIP.cs 121 KB

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