Inovance_EIP.cs 122 KB

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