-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUCCNCplugin.cs
572 lines (442 loc) · 19.6 KB
/
UCCNCplugin.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/*
BSD 2-Clause License
Copyright (c) 2018, Stephan Thiele
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Reflection;
namespace Plugins {
public class UCCNCplugin { // Class name must be UCCNCplugin to work!
public class CppDll {
static class Kernel32 {
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
public CppDll(String dllPath) {
path = dllPath;
}
~CppDll() {
Unload();
}
public bool Load() {
if (pDll != IntPtr.Zero)
return false;
pDll = Kernel32.LoadLibrary(path);
if (pDll == IntPtr.Zero) {
MessageBox.Show(String.Format("Failed to load {0}!", path), "Error on loading cpp dll");
return false;
}
onFirstCycle = (OnFirstCycle_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "onFirstCycle"), typeof(OnFirstCycle_t));
onTick = (OnTick_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "onTick"), typeof(OnTick_t));
onShutdown = (OnShutdown_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "onShutdown"), typeof(OnShutdown_t));
buttonpress_event = (Buttonpress_event_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "buttonpress_event"), typeof(Buttonpress_event_t));
textfieldclick_event = (Textfieldclick_event_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "textfieldclick_event"), typeof(Textfieldclick_event_t));
textfieldtexttyped_event = (Textfieldtexttyped_event_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "textfieldtexttyped_event"), typeof(Textfieldtexttyped_event_t));
getproperties_event = (Getproperties_event_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "getproperties_event"), typeof(Getproperties_event_t));
setCallBacks = (SetCallBacks_t)Marshal.GetDelegateForFunctionPointer(
Kernel32.GetProcAddress(pDll, "setCallBacks"), typeof(SetCallBacks_t));
return true;
}
public bool Unload() {
bool success = Kernel32.FreeLibrary(pDll);
pDll = IntPtr.Zero;
return success;
}
public bool IsLoaded() {
return pDll != IntPtr.Zero;
}
private string path;
private IntPtr pDll = IntPtr.Zero;
public OnFirstCycle_t onFirstCycle;
public OnTick_t onTick;
public OnShutdown_t onShutdown;
public Buttonpress_event_t buttonpress_event;
public Textfieldclick_event_t textfieldclick_event;
public Textfieldtexttyped_event_t textfieldtexttyped_event;
public Getproperties_event_t getproperties_event;
public SetCallBacks_t setCallBacks;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool OnFirstCycle_t();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool OnTick_t();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool OnShutdown_t();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Buttonpress_event_t(int buttonnumber, bool onscreen);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Textfieldclick_event_t(int labelnumber, bool Ismainscreen);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Textfieldtexttyped_event_t(int labelnumber, bool Ismainscreen, StringBuilder text);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void Getproperties_event_t(StringBuilder author, StringBuilder pluginName,
StringBuilder pluginVersion);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void SetCallBacks_t(PluginInterfaceEntry pInterface);
}
public string currentAssemblyFileName() {
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyName = assemblyPath.Substring(assemblyPath.LastIndexOf('/') + 1);
return assemblyName;
}
public String cppDllName() {
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyName = assemblyPath.Substring(assemblyPath.LastIndexOf('/') + 1);
string cppDllName = assemblyName.Substring(0, assemblyName.LastIndexOf('_')) + ".dll";
return cppDllName;
}
public String cppDllPath() {
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyName = assemblyPath.Substring(assemblyPath.LastIndexOf('/') + 1);
string cppDllName = assemblyName.Substring(0, assemblyName.LastIndexOf('_')) + ".dll";
string absoluteDllPath = assemblyPath.Substring(0, assemblyPath.LastIndexOf('/')) +
@"/cpp/" + cppDllName;
return absoluteDllPath;
}
// Do loading and unloading of dll in a safe state to avoid unloading while code in dll is executed.
// Else this meight result in a crash:
enum DllDelayedOperation {
None,
Load,
Unload
};
DllDelayedOperation delayedDllOperation;
public void loadDllAsync() {
delayedDllOperation = DllDelayedOperation.Load;
}
public void unloadDllAsync() {
delayedDllOperation = DllDelayedOperation.Unload;
}
public unsafe void unsafeStrCpy(byte* pDst, int dstBufLen, String src) {
// TOOD: how to do the string copy right!?
int len = src.Length < dstBufLen - 1 ? src.Length : dstBufLen - 1;
for (int i = 0; i < len; i++)
pDst[i] = (byte)src[i];
pDst[len] = (byte)'\0';
}
public unsafe int unsafeStrLen(byte* pUnsafeCStr) {
int i = 0;
while (pUnsafeCStr[i] != '\0')
i++;
return i;
}
public unsafe String unsafeByteToStr(byte* pUnsafeCStr) {
// TOOD: how to do the string copy right!?
String s = "";
int len = unsafeStrLen(pUnsafeCStr);
for(int i = 0; i < len; i++)
s += (char)pUnsafeCStr[i];
return s;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public unsafe delegate void GetFieldCallBack(byte* pResult, int resultBufLen, bool isAS3, int fieldnumber);
private unsafe void GetFieldHandler(byte* pField, int fieldBufLen, bool isAS3, int fieldnumber) {
string result = UC.Getfield(isAS3, fieldnumber);
unsafeStrCpy(pField, fieldBufLen, result);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int GetFieldIntCallBack(bool isAS3, int fieldnumber);
private int GetFieldIntHandler(bool isAS3, int fieldnumber) {
return UC.Getfieldint(isAS3, fieldnumber);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetFieldDoubleCallBack(bool isAS3, int fieldnumber);
private double GetFieldDoubleHandler(bool isAS3, int fieldnumber) {
return UC.Getfielddouble(isAS3, fieldnumber);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool GetLedCallBack(int ledNumber);
private bool GetLedHandler(int ledNumber) {
return UC.GetLED(ledNumber);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate bool IsMovingCallBack();
private unsafe bool IsMovingHandler() {
return UC.IsMoving();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetXposCallBack();
private double GetXposHandler() {
return UC.GetXpos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetYposCallBack();
private double GetYposHandler() {
return UC.GetYpos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetZposCallBack();
private double GetZposHandler() {
return UC.GetZpos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetAposCallBack();
private double GetAposHandler() {
return UC.GetApos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetBposCallBack();
private double GetBposHandler() {
return UC.GetBpos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate double GetCposCallBack();
private double GetCposHandler() {
return UC.GetCpos();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void GetGetgcodefilenameCallBack(byte* pFileName, int fileNameBufLen);
private unsafe void GetgcodefilenameHandler(byte* pFileName, int fileNameBufLen) {
string fileName = UC.Getgcodefilename();
unsafeStrCpy(pFileName, fileNameBufLen, fileName);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void CodeCallBack(byte* pCode);
private unsafe void codeHandler(byte* pCode) {
String code = unsafeByteToStr(pCode);
UC.Code(code);
}
[StructLayout(LayoutKind.Sequential)]
public struct PluginInterfaceEntry {
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetFieldCallBack pGetField;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetFieldIntCallBack pGetFieldInt;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetFieldDoubleCallBack pGetFieldDouble;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetLedCallBack pGetLed;
[MarshalAs(UnmanagedType.FunctionPtr)]
public IsMovingCallBack pIsMoving;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetXposCallBack pGetXpos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetYposCallBack pGetYpos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetZposCallBack pGetZpos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetAposCallBack pGetApos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetBposCallBack pGetBpos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetCposCallBack pGetCpos;
[MarshalAs(UnmanagedType.FunctionPtr)]
public GetGetgcodefilenameCallBack pGetGcodeFileName;
[MarshalAs(UnmanagedType.FunctionPtr)]
public CodeCallBack pCode;
}
void exceptionHandler(Exception e, String where) {
MessageBox.Show(String.Format("Exception in c++ plugin '{0}'!\n {1}", cppDllName(), e.StackTrace),
where);
}
// Use instance variable if PluginInterfaceEntry to ensure the delegates don't get garbage collected:
private PluginInterfaceEntry uc_callbacks;
public Plugininterface.Entry UC;
PluginForm pluginForm;
public bool isFirstCycle = true;
public bool loopstop = false;
public CppDll cppDll;
public unsafe UCCNCplugin() {
cppDll = new CppDll(cppDllPath());
delayedDllOperation = DllDelayedOperation.None;
try {
uc_callbacks = new PluginInterfaceEntry();
uc_callbacks.pGetField = new GetFieldCallBack(GetFieldHandler);
uc_callbacks.pGetFieldInt = new GetFieldIntCallBack(GetFieldIntHandler);
uc_callbacks.pGetFieldDouble = new GetFieldDoubleCallBack(GetFieldDoubleHandler);
uc_callbacks.pGetLed = new GetLedCallBack(GetLedHandler);
uc_callbacks.pIsMoving = new IsMovingCallBack(IsMovingHandler);
uc_callbacks.pGetXpos = new GetXposCallBack(GetXposHandler);
uc_callbacks.pGetYpos = new GetYposCallBack(GetYposHandler);
uc_callbacks.pGetZpos = new GetZposCallBack(GetZposHandler);
uc_callbacks.pGetApos = new GetAposCallBack(GetAposHandler);
uc_callbacks.pGetBpos = new GetBposCallBack(GetBposHandler);
uc_callbacks.pGetCpos = new GetCposCallBack(GetCposHandler);
uc_callbacks.pGetGcodeFileName = new GetGetgcodefilenameCallBack(GetgcodefilenameHandler);
uc_callbacks.pCode = new CodeCallBack(codeHandler);
}
catch(Exception e) {
exceptionHandler(e, "setting uc_callbacks");
}
// Do not load dll asynchronously at this point or Getproperties_event() call will never reach cpp dll:
cppDll.Load();
cppDll.setCallBacks(uc_callbacks);
}
// Called when the plugin is initialised.
// The parameter is the Plugin interface object which contains all functions prototypes for calls and callbacks.
public void Init_event(Plugininterface.Entry UC) {
this.UC = UC;
pluginForm = new PluginForm(this);
String assemblyFileName = currentAssemblyFileName();
String value = UC.Readkey("Plugins_enabled", assemblyFileName, "undefined").ToLower();
if (value == "true") {
cppDll.Load();
cppDll.setCallBacks(uc_callbacks);
}
}
// Called when the plugin is loaded, the author of the plugin should set the details of the plugin here.
public Plugininterface.Entry.Pluginproperties Getproperties_event(Plugininterface.Entry.Pluginproperties Properties) {
StringBuilder author = new StringBuilder(256);
StringBuilder pluginName = new StringBuilder(256);
StringBuilder pluginVersion = new StringBuilder(256);
author.Append("---");
pluginName.Append("---");
pluginVersion.Append("---");
if (cppDll.IsLoaded()) {
cppDll.getproperties_event(author, pluginName, pluginVersion);
cppDll.Unload();
}
Properties.author = author.ToString();
Properties.pluginname = pluginName.ToString(); ;
Properties.pluginversion = pluginVersion.ToString();
return Properties;
}
// Called from UCCNC when the user presses the Configuration button in the Plugin configuration menu.
// Typically the plugin configuration window is shown to the user.
public void Configure_event() {
ConfigForm cform = new ConfigForm();
cform.ShowDialog();
}
// Called from UCCNC when the plugin is loaded and started.
public void Startup_event() {
if (pluginForm.IsDisposed)
pluginForm = new PluginForm(this);
pluginForm.Show();
}
// Called when the Pluginshowup(string Pluginfilename); function is executed in the UCCNC.
public void Showup_event() {
if (pluginForm.IsDisposed)
pluginForm = new PluginForm(this);
pluginForm.Show();
pluginForm.BringToFront();
}
// Called when the UCCNC software is closing.
public void Shutdown_event() {
try {
loopstop = true;
if (cppDll.IsLoaded())
cppDll.onShutdown();
pluginForm.Close();
}
catch (Exception e) {
exceptionHandler(e, "Shutdown_event");
}
}
public void processDelayedDllOperation() {
switch(delayedDllOperation) {
case DllDelayedOperation.Load:
if (!cppDll.Load())
MessageBox.Show("Loading cpp dll failed!");
cppDll.setCallBacks(uc_callbacks);
isFirstCycle = true;
break;
case DllDelayedOperation.Unload:
if(!cppDll.Unload())
MessageBox.Show("Unloading cpp dll failed!");
break;
}
delayedDllOperation = DllDelayedOperation.None;
}
// Called in a loop with a 25Hz interval.
public void Loop_event() {
if (loopstop)
return;
processDelayedDllOperation();
if (!cppDll.IsLoaded())
return;
if (pluginForm == null || pluginForm.IsDisposed)
return;
if (isFirstCycle) {
isFirstCycle = false;
cppDll.onFirstCycle();
}
try {
cppDll.onTick();
}
catch (Exception e) {
exceptionHandler(e, "LoopEvent");
}
}
// This is a direct function call addressed to this plugin dll
// The function can be called by macros or by another plugin
// The passed parameter is an object and the return value is also an object
public object Informplugin_event(object Message) {
if (!(pluginForm == null || pluginForm.IsDisposed)) {
if (Message is string) {
string receivedstr = Message as string;
MessageBox.Show(this.pluginForm, "Informplugin message received by UCCNC cpp plugin! Message was: "
+ receivedstr);
}
}
string returnstr = "Return string by UCCNC cpp plugin";
return (object)returnstr;
}
// This is a function call made to all plugin dll files
// The function can be called by macros or by another plugin
// The passed parameter is an object and there is no return value
public void Informplugins_event(object Message) {
if (!(pluginForm == null || pluginForm.IsDisposed)) {
string receivedstr = Message as string;
MessageBox.Show(this.pluginForm, "Informplugins message received by UCCNC cpp plugin! Message was: "
+ receivedstr);
}
}
// Called when the user presses a button on the UCCNC GUI or if a Callbutton function is executed.
// The int buttonnumber parameter is the ID of the caller button.
// The bool onscreen parameter is true if the button was pressed on the GUI and is false if the Callbutton
// function was called.
public void Buttonpress_event(int buttonnumber, bool onscreen) {
if(cppDll.IsLoaded())
cppDll.buttonpress_event(buttonnumber, onscreen);
}
// Called when the user clicks and enters a Textfield on the screen
// The labelnumber parameter is the ID of the accessed Textfield
// The bool Ismainscreen parameter is true is the Textfield is on the main screen and false if it is on the
// jog screen
public void Textfieldclick_event(int labelnumber, bool Ismainscreen) {
if (cppDll.IsLoaded())
cppDll.textfieldclick_event(labelnumber, Ismainscreen);
}
// Called when the user enters text into the Textfield and it gets validated
// The labelnumber parameter is the ID of the accessed Textfield
// The bool Ismainscreen parameter is true is the Textfield is on the main screen and false if it is on the jog screen.
// The text parameter is the text entered and validated by the user
public void Textfieldtexttyped_event(int labelnumber, bool Ismainscreen, string text) {
StringBuilder sbText = new StringBuilder(text);
if (cppDll.IsLoaded())
cppDll.textfieldtexttyped_event(labelnumber, Ismainscreen, sbText);
}
}
}