Inovance_EIP.cs 122 KB

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