Inovance_EIP.cs 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237
  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. /// <summary>
  2608. /// 一次读取单个标签
  2609. /// </summary>
  2610. /// <typeparam name="T">需要读取的标签结构</typeparam>
  2611. /// <param name="strTagName">需要读取的标签名</param>
  2612. /// <param name="nCount">读取标签的个数</param>
  2613. /// <param name="outObj">返回相应标签值对象</param>
  2614. /// <returns></returns>
  2615. public (int, string) Read_SingleTag<T>(string strTagName, int nCount, out T outObj)
  2616. {
  2617. outObj = default(T);
  2618. byte[] pBuf = null;
  2619. int nRet = 0;
  2620. string strRet = "";
  2621. try
  2622. {
  2623. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2624. if (nRet != 0) return (nRet, strRet);
  2625. string str = typeof(T).Name;
  2626. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  2627. bool containsAny = substrings.Any(substring => str.Contains(substring));
  2628. if (containsAny)
  2629. {
  2630. if (str != strRet) return (120, "变量类型不一致");
  2631. }
  2632. if (str == "String")
  2633. {
  2634. outObj = (T)(object)System.Text.Encoding.UTF8.GetString(pBuf);
  2635. return (0, "OK");
  2636. }
  2637. outObj = (T)ByteToStruct(pBuf, typeof(T));
  2638. }
  2639. catch (Exception ex)
  2640. {
  2641. return (110, ex.ToString());
  2642. }
  2643. return (0, "OK");
  2644. }
  2645. private Form _processingForm;
  2646. private void ShowProcessingDialog(Control uiControl)
  2647. {
  2648. if (uiControl == null)
  2649. {
  2650. throw new ArgumentNullException(nameof(uiControl), "UI 控件不能为空。");
  2651. }
  2652. // 确保在主线程上更新 UI
  2653. if (uiControl.InvokeRequired)
  2654. {
  2655. uiControl.Invoke(new Action(() => ShowProcessingDialog(uiControl)));
  2656. return;
  2657. }
  2658. // 创建并显示提示框
  2659. Form processingForm = new Form
  2660. {
  2661. Text = "请稍候",
  2662. Size = new Size(300, 100),
  2663. StartPosition = FormStartPosition.CenterScreen,
  2664. FormBorderStyle = FormBorderStyle.FixedDialog,
  2665. ControlBox = false,
  2666. TopMost = true
  2667. };
  2668. Label label = new Label
  2669. {
  2670. Text = "正在读取中,请稍后...",
  2671. Dock = DockStyle.Fill,
  2672. TextAlign = ContentAlignment.MiddleCenter
  2673. };
  2674. processingForm.Controls.Add(label);
  2675. processingForm.Show();
  2676. // 保存提示框引用以便后续关闭
  2677. _processingForm = processingForm;
  2678. }
  2679. private void CloseProcessingDialog(Control uiControl)
  2680. {
  2681. if (uiControl == null)
  2682. {
  2683. return;
  2684. }
  2685. // 确保在主线程上更新 UI
  2686. if (uiControl.InvokeRequired)
  2687. {
  2688. uiControl.Invoke(new Action(() => CloseProcessingDialog(uiControl)));
  2689. return;
  2690. }
  2691. // 关闭提示框
  2692. _processingForm?.Close();
  2693. _processingForm = null;
  2694. }
  2695. /*
  2696. public (int, string) Read_SingleTag<T>(string strTagName, int nCount, out T outObj)
  2697. {
  2698. outObj = default(T);
  2699. byte[] pBuf = null;
  2700. int nRet = 0;
  2701. string strRet = "";
  2702. try
  2703. {
  2704. (nRet, strRet) = Read_Tag(strTagPrefix + strTagName, nCount, out pBuf);
  2705. if (nRet != 0) return (nRet, strRet);
  2706. string str = typeof(T).Name;
  2707. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  2708. bool containsAny = substrings.Any(substring => str.Contains(substring));
  2709. if (containsAny)
  2710. {
  2711. if (str != strRet) return (120, "变量类型不一致");
  2712. }
  2713. if (str == "String")
  2714. {
  2715. outObj = (T)(object)System.Text.Encoding.UTF8.GetString(pBuf);
  2716. return (0, "OK");
  2717. }
  2718. outObj = (T)ByteToStruct(pBuf, typeof(T));
  2719. }
  2720. catch (Exception ex)
  2721. {
  2722. return (110, ex.ToString());
  2723. }
  2724. return (0, "OK");
  2725. }*/
  2726. public (int, string) Write_SingleTag<T>(string strTagName, int nCount, T inObj)
  2727. {
  2728. byte[] pBuf = null;
  2729. int nRet = 0;
  2730. string strRet = "";
  2731. int size = 0;
  2732. try
  2733. {
  2734. string str = typeof(T).Name;
  2735. string[] substrings = { "Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32", "Int64", "UInt64", "Single", "Double", "String" };
  2736. bool containsAny = substrings.Any(substring => str.Contains(substring));
  2737. if (containsAny)
  2738. {
  2739. Type type = inObj.GetType();
  2740. if (str != type.Name) return (120, "变量类型不一致");
  2741. }
  2742. if (str == "String")
  2743. {
  2744. //size = inObj.ToString().Length + 1;
  2745. string wtStr= inObj as string;
  2746. pBuf = System.Text.Encoding.Default.GetBytes(wtStr);
  2747. size = pBuf.Length;
  2748. }
  2749. else
  2750. {
  2751. if (typeof(T).Name == "Boolean")
  2752. {
  2753. //pBuf = new byte[1];
  2754. //Type targetType = typeof(T);
  2755. //if ((bool)Convert.ChangeType(inObj, targetType))
  2756. //{
  2757. // pBuf[0] = 1;
  2758. //}
  2759. //else
  2760. //{
  2761. // pBuf[0] = 0;
  2762. //}
  2763. size = 1;
  2764. }
  2765. else
  2766. {
  2767. size = Marshal.SizeOf(typeof(T));
  2768. }
  2769. pBuf = StructToBytes(inObj, size);
  2770. }
  2771. (nRet, strRet) = Write_Tag(strTagPrefix + strTagName, nCount, pBuf);
  2772. return (nRet, strRet);
  2773. }
  2774. catch (Exception ex)
  2775. {
  2776. return (110, ex.ToString());
  2777. }
  2778. }
  2779. /// <summary>
  2780. /// 一次读取多个标签
  2781. /// </summary>
  2782. /// <param name="stTagList">需要读取的标签列表信息</param>
  2783. /// <param name="outObj">返回的相应标签对象</param>
  2784. /// <returns>执行是否成功,非0不成功,以及显示相应的失败信息</returns>
  2785. public (int, string) Read_MultiTags(List<StructTag> stTagList, out List<Object> outObj)
  2786. {
  2787. outObj = new List<Object>();
  2788. byte[][] pBuf = null;
  2789. int nRet = 0;
  2790. string strRet = "";
  2791. int nLen = stTagList.Count;
  2792. List<StructTag> TagList=new List<StructTag>();
  2793. try
  2794. {
  2795. foreach(StructTag tag in stTagList)
  2796. {
  2797. TagList.Add(new StructTag {strTagName= strTagPrefix + tag.strTagName,tTagType=tag.tTagType,nCount=tag.nCount});
  2798. }
  2799. (nRet, strRet) = Read_Tags(TagList, out pBuf);
  2800. if (nRet != 0) return (nRet, strRet);
  2801. for (int i = 0; i < nLen; i++)
  2802. {
  2803. //需要调用的方法
  2804. //MethodInfo mi = typeof(Inovance_EIP).GetMethod("ByteToStruct");
  2805. //该方法的泛型类型Type->typeof(int)
  2806. //MethodInfo miConstructed = mi.MakeGenericMethod(strTagList[i].TagType);
  2807. //var arg = { pBuf[i]};
  2808. //执行调用
  2809. //miConstructed.Invoke(null, args);
  2810. //outObj.Add(Convert.ChangeType(ByteToStruct2(pBuf[i], targetType), targetType));
  2811. Type targetType = TagList[i].tTagType;
  2812. if (targetType != null)
  2813. {
  2814. object obj = ByteToStruct(pBuf[i], targetType);
  2815. //if (obj != null)
  2816. outObj.Add(obj);
  2817. }
  2818. }
  2819. }
  2820. catch (Exception ex)
  2821. {
  2822. return (110, ex.ToString());
  2823. }
  2824. return (0, "OK");
  2825. }
  2826. /// <summary>
  2827. /// 一次写多个标签
  2828. /// </summary>
  2829. /// <param name="stTagList">需要写入的标签列表信息</param>
  2830. /// <param name="ObjList">写入的相应标签对象</param>
  2831. /// <returns>执行是否成功,非0不成功,以及显示相应的失败信息</returns>
  2832. public (int, string) Write_MultiTags(List<StructTag> stTagList, List<Object> ObjList)
  2833. {
  2834. int nRet = 0;
  2835. string strRet = "";
  2836. int nLen = stTagList.Count;
  2837. if (ObjList.Count != nLen) return (10, "标签列表和对象列表长度不一致");
  2838. List<StructTag> TagList = new List<StructTag>();
  2839. try
  2840. {
  2841. foreach (StructTag tag in stTagList)
  2842. {
  2843. TagList.Add(new StructTag { strTagName = strTagPrefix + tag.strTagName, tTagType = tag.tTagType, nCount = tag.nCount });
  2844. }
  2845. (nRet, strRet) = Write_Tags(TagList, ObjList);
  2846. return (nRet, strRet);
  2847. }
  2848. catch (Exception ex)
  2849. {
  2850. return (110, ex.ToString());
  2851. }
  2852. }
  2853. #region 清除标签缓存
  2854. /// <summary>
  2855. /// 清除标签缓存
  2856. /// </summary>
  2857. public void Clear_TagCache()
  2858. {
  2859. ResetTagInfo();
  2860. }
  2861. #endregion 清除标签缓存
  2862. }
  2863. }