Inovance_EIP.cs 118 KB

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