Repository navigation
Expand file tree
/
Copy pathgenerate_csharp_examples.py
More file actions
executable file
·719 lines (556 loc) · 30.2 KB
/
Copy pathgenerate_csharp_examples.py
File metadata and controls
executable file
·719 lines (556 loc) · 30.2 KB
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
C# Examples Generator
Copyright (C) 2015-2019 Matthias Bolte <matthias@tinkerforge.com>
generate_csharp_examples.py: Generator for C# examples
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
"""
import sys
if sys.hexversion < 0x3040000:
print('Python >= 3.4 required')
sys.exit(1)
import os
import importlib.util
import importlib.machinery
def create_generators_module():
generators_dir = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
if sys.hexversion < 0x3050000:
generators_module = importlib.machinery.SourceFileLoader('generators', os.path.join(generators_dir, '__init__.py')).load_module()
else:
generators_spec = importlib.util.spec_from_file_location('generators', os.path.join(generators_dir, '__init__.py'))
generators_module = importlib.util.module_from_spec(generators_spec)
generators_spec.loader.exec_module(generators_module)
sys.modules['generators'] = generators_module
if 'generators' not in sys.modules:
create_generators_module()
from generators import common
from generators.csharp import csharp_common
global_line_prefix = ''
class CSharpConstant(common.Constant):
def get_csharp_source(self):
template = '{device_category}{device_name}.{constant_group_name}_{constant_name}'
return template.format(device_category=self.get_device().get_category().camel,
device_name=self.get_device().get_name().camel,
constant_group_name=self.get_constant_group().get_name().upper,
constant_name=self.get_name().upper)
class CSharpExample(common.Example):
def get_csharp_source(self):
template = r"""using System;
{imports}using Tinkerforge;{incomplete}{description}
class Example
{{
private static string HOST = "localhost";
private static int PORT = 4223;
private static string UID = "{dummy_uid}"; // Change {dummy_uid} to the UID of your {device_name_long_display}
{functions}
static void Main()
{{
IPConnection ipcon = new IPConnection(); // Create IP connection
{device_category}{device_name_camel} {device_name_initial} ={constructor_break}new {device_category}{device_name_camel}(UID, ipcon); // Create device object
ipcon.Connect(HOST, PORT); // Connect to brickd
// Don't use device before ipcon is connected
{sources}
Console.WriteLine("Press enter to exit");
Console.ReadLine();{cleanups}
ipcon.Disconnect();
}}
}}
"""
if self.is_incomplete():
incomplete = '\n\n// FIXME: This example is incomplete'
else:
incomplete = ''
if self.get_description() != None:
description = '\n\n// {0}'.format(self.get_description().replace('\n', '\n// '))
else:
description = ''
imports = []
functions = []
sources = []
cleanups = []
for function in self.get_functions():
imports += function.get_csharp_imports()
functions.append(function.get_csharp_function())
sources.append(function.get_csharp_source())
for cleanup in self.get_cleanups():
imports += cleanup.get_csharp_imports()
functions.append(cleanup.get_csharp_function())
cleanups.append(cleanup.get_csharp_source())
unique_imports = []
for import_ in imports:
if import_ not in unique_imports:
unique_imports.append(import_)
while None in functions:
functions.remove(None)
while None in sources:
sources.remove(None)
if len(sources) == 0:
sources = ['\t\t// TODO: Add example code here\n']
while None in cleanups:
cleanups.remove(None)
if len(self.get_device().get_name().camel) > 14:
constructor_break = '\n\t\t '
else:
constructor_break = ' '
return template.format(incomplete=incomplete,
description=description,
device_category=self.get_device().get_category().camel,
device_name_camel=self.get_device().get_name().camel,
device_name_initial=self.get_device().get_initial_name(),
device_name_long_display=self.get_device().get_long_display_name(),
dummy_uid=self.get_dummy_uid(),
imports=''.join(unique_imports),
functions=common.wrap_non_empty('\n', '\n'.join(functions), ''),
sources='\n' + '\n'.join(sources).replace('\n\r', '').lstrip('\r'),
cleanups=common.wrap_non_empty('\n\n', '\n'.join(cleanups).replace('\n\r', '').lstrip('\r').rstrip('\n'), '\n'),
constructor_break=constructor_break)
class CSharpExampleArgument(common.ExampleArgument):
def get_csharp_source(self):
type_ = self.get_type()
def helper(value):
if type_ == 'float':
return common.format_float(value) + 'f'
elif type_ == 'bool':
return str(bool(value)).lower()
elif type_ == 'char':
return "'{0}'".format(value.replace("'", "\\'"))
elif type_ == 'string':
return '"{0}"'.format(value.replace('"', '\\"'))
elif ':bitmask:' in type_:
return common.make_c_like_bitmask(value)
elif type_.endswith(':constant'):
return self.get_value_constant(value).get_csharp_source()
else:
return str(value)
value = self.get_value()
if isinstance(value, list):
return 'new {0}[]{{{1}}}'.format(csharp_common.get_csharp_type(self.get_type().split(':')[0], 1), ', '.join([helper(item) for item in value]))
return helper(value)
class CSharpExampleArgumentsMixin(object):
def get_csharp_arguments(self):
return [argument.get_csharp_source() for argument in self.get_arguments()]
class CSharpExampleParameter(common.ExampleParameter):
def get_csharp_source(self):
templateA = '{type_} {name}'
templateB = '{type_}[] {name}'
if self.get_cardinality() == 1:
template = templateA
else:
template = templateB
return template.format(type_=csharp_common.get_csharp_type(self.get_type().split(':')[0], 1),
name=self.get_name().headless)
def get_csharp_write_lines(self):
if self.get_type().split(':')[-1] == 'constant':
if self.get_label_name() == None:
return []
# FIXME: need to handle multiple labels
assert self.get_label_count() == 1
template = '{global_line_prefix}\t\t{else_}if({name} == {constant_name})\n{global_line_prefix}\t\t{{\n{global_line_prefix}\t\t\tConsole.WriteLine("{label}: {constant_title}");{comment}\n{global_line_prefix}\t\t}}'
constant_group = self.get_constant_group()
result = []
for constant in constant_group.get_constants():
result.append(template.format(global_line_prefix=global_line_prefix,
else_='else ' if len(result) > 0 else '',
name=self.get_name().headless,
label=self.get_label_name(),
constant_name=constant.get_csharp_source(),
constant_title=constant.get_name().space,
comment=self.get_formatted_comment(' // {0}')))
result = ['\r' + '\n'.join(result) + '\r']
else:
template = '{global_line_prefix}\t\tConsole.WriteLine("{label}: " + {to_binary_prefix}{name}{index}{divisor}{to_binary_suffix}{unit});{comment}'
if self.get_label_name() == None:
return []
if self.get_cardinality() < 0:
return [] # FIXME: streaming
# FIXME: Convert.ToString() doesn't support leading zeros. therefore,
# the result is not padded to the requested number of digits
if ':bitmask:' in self.get_type():
to_binary_prefix = 'Convert.ToString('
to_binary_suffix = ', 2)'
else:
to_binary_prefix = ''
to_binary_suffix = ''
result = []
for index in range(self.get_label_count()):
result.append(template.format(global_line_prefix=global_line_prefix,
name=self.get_name().headless,
label=self.get_label_name(index=index),
index='[{0}]'.format(index) if self.get_label_count() > 1 else '',
divisor=self.get_formatted_divisor('/{0}'),
unit=self.get_formatted_unit_name(' + " {0}"'),
to_binary_prefix=to_binary_prefix,
to_binary_suffix=to_binary_suffix,
comment=self.get_formatted_comment(' // {0}')))
return result
class CSharpExampleResult(common.ExampleResult):
def get_csharp_variable_declaration(self):
name = self.get_name().headless
if name == self.get_device().get_initial_name():
name += '_'
type_ = csharp_common.get_csharp_type(self.get_type().split(':')[0], 1)
if self.get_cardinality() > 1 and type_ != 'string':
type_ += '[]'
return type_, name
def get_csharp_variable_reference(self):
template = 'out {name}'
name = self.get_name().headless
if name == self.get_device().get_initial_name():
name += '_'
return template.format(name=name)
def get_csharp_write_lines(self):
if self.get_type().split(':')[-1] == 'constant':
# FIXME: need to handle multiple labels
assert self.get_label_count() == 1
template = '{global_line_prefix}\t\t{else_}if({name} == {constant_name})\n{global_line_prefix}\t\t{{\n\t\t\tConsole.WriteLine("{label}: {constant_title}");{comment}\n{global_line_prefix}\t\t}}'
constant_group = self.get_constant_group()
result = []
for constant in constant_group.get_constants():
result.append(template.format(global_line_prefix=global_line_prefix,
else_='else ' if len(result) > 0 else '',
name=self.get_name().headless,
label=self.get_label_name(),
constant_name=constant.get_csharp_source(),
constant_title=constant.get_name().space,
comment=self.get_formatted_comment(' // {0}')))
result = ['\r' + '\n'.join(result) + '\r']
else:
template = '{global_line_prefix}\t\tConsole.WriteLine("{label}: " + {to_binary_prefix}{name}{index}{divisor}{to_binary_suffix}{unit});{comment}'
if self.get_label_name() == None:
return []
if self.get_cardinality() < 0:
return [] # FIXME: streaming
name = self.get_name().headless
if name == self.get_device().get_initial_name():
name += '_'
# FIXME: Convert.ToString() doesn't support leading zeros. therefore,
# the result is not padded to the requested number of digits
if ':bitmask:' in self.get_type():
to_binary_prefix = 'Convert.ToString('
to_binary_suffix = ', 2)'
else:
to_binary_prefix = ''
to_binary_suffix = ''
result = []
for index in range(self.get_label_count()):
result.append(template.format(global_line_prefix=global_line_prefix,
name=name,
label=self.get_label_name(index=index),
index='[{0}]'.format(index) if self.get_label_count() > 1 else '',
divisor=self.get_formatted_divisor('/{0}'),
unit=self.get_formatted_unit_name(' + " {0}"'),
to_binary_prefix=to_binary_prefix,
to_binary_suffix=to_binary_suffix,
comment=self.get_formatted_comment(' // {0}')))
return result
class CSharpExampleGetterFunction(common.ExampleGetterFunction, CSharpExampleArgumentsMixin):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
templateA = r"""{global_line_prefix} // Get current {function_name_comment}
{global_line_prefix}{variable_declarations} = {device_name}.{function_name_camel}({arguments});
{write_lines}
"""
templateB = r"""{global_line_prefix} // Get current {function_name_comment}
{global_line_prefix}{variable_declarations};
{global_line_prefix} {device_name}.{function_name_camel}({arguments});
{write_lines}
"""
variable_declarations = []
variable_references = []
write_lines = []
for result in self.get_results():
variable_declarations.append(result.get_csharp_variable_declaration())
variable_references.append(result.get_csharp_variable_reference())
write_lines += result.get_csharp_write_lines()
if len(variable_declarations) == 1:
template = templateA
else:
template = templateB
merged_variable_declarations = []
for variable_declaration in variable_declarations:
merged = False
for merged_variable_declaration in merged_variable_declarations:
if merged_variable_declaration[0] == variable_declaration[0]:
merged_variable_declaration[1].append(variable_declaration[1])
merged = True
break
if not merged:
merged_variable_declarations.append([variable_declaration[0], [variable_declaration[1]]])
variable_declarations = []
for merged_variable_declaration in merged_variable_declarations:
variable_declarations.append('{0} {1}'.format(merged_variable_declaration[0],
',<BP>'.join(merged_variable_declaration[1])))
variable_declarations = common.break_string('\t\t' + ';<BP>'.join(variable_declarations),
merged_variable_declarations[0][0] + ' ')
while None in write_lines:
write_lines.remove(None)
if len(write_lines) > 1:
write_lines.insert(0, '\b')
arguments = self.get_csharp_arguments()
if len(variable_references) > 1:
arguments += variable_references
result = template.format(device_name=self.get_device().get_initial_name(),
function_name_camel=self.get_name().camel,
function_name_comment=self.get_comment_name(),
variable_declarations=variable_declarations,
write_lines='\n'.join(write_lines).replace('\b\n\r', '\n').replace('\b', '').replace('\r\n\r', '\n\n').rstrip('\r').replace('\r', '\n'),
arguments=',<BP>'.join(arguments),
global_line_prefix=global_line_prefix)
return common.break_string(result, '{}('.format(self.get_name().camel))
class CSharpExampleSetterFunction(common.ExampleSetterFunction, CSharpExampleArgumentsMixin):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
template = '{comment1}{global_line_prefix}\t\t{device_name}.{function_name}({arguments});{comment2}\n'
result = template.format(global_line_prefix=global_line_prefix,
device_name=self.get_device().get_initial_name(),
function_name=self.get_name().camel,
arguments=',<BP>'.join(self.get_csharp_arguments()),
comment1=self.get_formatted_comment1(global_line_prefix + '\t\t// {0}\n', '\r', '\n' + global_line_prefix + '\t\t// '),
comment2=self.get_formatted_comment2(' // {0}', ''))
return common.break_string(result, '{}('.format(self.get_name().camel))
class CSharpExampleCallbackFunction(common.ExampleCallbackFunction):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
template1A = r""" // Callback function for {function_name_comment} callback
"""
template1B = r"""{override_comment}
"""
template2 = r""" static void {function_name_camel}CB({device_category}{device_name} sender{parameters})
{{
{write_lines}{extra_message}
}}
"""
override_comment = self.get_formatted_override_comment('\t// {0}', None, '\n\t// ')
if override_comment == None:
template1 = template1A
else:
template1 = template1B
parameters = []
write_lines = []
for parameter in self.get_parameters():
parameters.append(parameter.get_csharp_source())
write_lines += parameter.get_csharp_write_lines()
while None in write_lines:
write_lines.remove(None)
if len(write_lines) > 1:
write_lines.append('\t\tConsole.WriteLine("");')
extra_message = self.get_formatted_extra_message('\t\tConsole.WriteLine("{0}");')
if len(extra_message) > 0 and len(write_lines) > 0:
extra_message = '\n' + extra_message
result = template1.format(function_name_comment=self.get_comment_name(),
override_comment=override_comment) + \
template2.format(device_category=self.get_device().get_category().camel,
device_name=self.get_device().get_name().camel,
function_name_camel=self.get_name().camel,
parameters=common.wrap_non_empty(',<BP>', ',<BP>'.join(parameters), ''),
write_lines='\n'.join(write_lines).replace('\r\n\r', '\n\n').strip('\r').replace('\r', '\n'),
extra_message=extra_message)
return common.break_string(result, '{}CB('.format(self.get_name().camel))
def get_csharp_source(self):
template = r""" // Register {function_name_comment}<BP>callback<BP>to<BP>function<BP>{function_name_camel}CB
{device_name}.{function_name_camel}Callback += {function_name_camel}CB;
"""
result = template.format(device_name=self.get_device().get_initial_name(),
function_name_camel=self.get_name().camel,
function_name_comment=self.get_comment_name())
return common.break_string(result, '// ', indent_tail='// ')
class CSharpExampleCallbackPeriodFunction(common.ExampleCallbackPeriodFunction, CSharpExampleArgumentsMixin):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
templateA = r""" // Set period for {function_name_comment} callback to {period_sec_short} ({period_msec}ms)
{device_name}.Set{function_name_camel}Period({arguments}{period_msec});
"""
templateB = r""" // Set period for {function_name_comment} callback to {period_sec_short} ({period_msec}ms)
// Note: The {function_name_comment} callback is only called every {period_sec_long}
// if the {function_name_comment} has changed since the last call!
{device_name}.Set{function_name_camel}CallbackPeriod({arguments}{period_msec});
"""
if self.get_device().get_name().space.startswith('IMU'):
template = templateA # FIXME: special hack for IMU Brick (2.0) callback behavior and name mismatch
else:
template = templateB
period_msec, period_sec_short, period_sec_long = self.get_formatted_period()
return template.format(device_name=self.get_device().get_initial_name(),
function_name_camel=self.get_name().camel,
function_name_comment=self.get_comment_name(),
arguments=common.wrap_non_empty('', ', '.join(self.get_csharp_arguments()), ', '),
period_msec=period_msec,
period_sec_short=period_sec_short,
period_sec_long=period_sec_long)
class CSharpExampleCallbackThresholdMinimumMaximum(common.ExampleCallbackThresholdMinimumMaximum):
def get_csharp_imports(self):
return []
def get_csharp_source(self):
template = '{minimum}, {maximum}'
return template.format(minimum=self.get_formatted_minimum(),
maximum=self.get_formatted_maximum())
class CSharpExampleCallbackThresholdFunction(common.ExampleCallbackThresholdFunction, CSharpExampleArgumentsMixin):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
template = r""" // Configure threshold for {function_name_comment} "{option_comment}"
{device_name}.Set{function_name_camel}CallbackThreshold({arguments}'{option_char}', {minimum_maximums});
"""
minimum_maximums = []
for minimum_maximum in self.get_minimum_maximums():
minimum_maximums.append(minimum_maximum.get_csharp_source())
return template.format(device_name=self.get_device().get_initial_name(),
function_name_camel=self.get_name().camel,
function_name_comment=self.get_comment_name(),
arguments=common.wrap_non_empty('', ', '.join(self.get_csharp_arguments()), ', '),
option_char=self.get_option_char(),
option_comment=self.get_option_comment(),
minimum_maximums=', '.join(minimum_maximums))
class CSharpExampleCallbackConfigurationFunction(common.ExampleCallbackConfigurationFunction, CSharpExampleArgumentsMixin):
def get_csharp_imports(self):
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
templateA = r""" // Set period for {function_name_comment} callback to {period_sec_short} ({period_msec}ms)
{device_name}.Set{function_name_camel}CallbackConfiguration({arguments}{period_msec}{value_has_to_change});
"""
templateB = r""" // Set period for {function_name_comment} callback to {period_sec_short} ({period_msec}ms) without a threshold
{device_name}.Set{function_name_camel}CallbackConfiguration({arguments}{period_msec}{value_has_to_change}, '{option_char}', {minimum_maximums});
"""
templateC = r""" // Configure threshold for {function_name_comment} "{option_comment}"
// with a debounce period of {period_sec_short} ({period_msec}ms)
{device_name}.Set{function_name_camel}CallbackConfiguration({arguments}{period_msec}{value_has_to_change}, '{option_char}', {minimum_maximums});
"""
if self.get_option_char() == None:
template = templateA
elif self.get_option_char() == 'x':
template = templateB
else:
template = templateC
period_msec, period_sec_short, period_sec_long = self.get_formatted_period()
minimum_maximums = []
for minimum_maximum in self.get_minimum_maximums():
minimum_maximums.append(minimum_maximum.get_csharp_source())
return template.format(device_name=self.get_device().get_initial_name(),
function_name_camel=self.get_name().camel,
function_name_comment=self.get_comment_name(),
arguments=common.wrap_non_empty('', ', '.join(self.get_csharp_arguments()), ', '),
period_msec=period_msec,
period_sec_short=period_sec_short,
value_has_to_change=common.wrap_non_empty(', ', self.get_value_has_to_change('true', 'false', ''), ''),
option_char=self.get_option_char(),
option_comment=self.get_option_comment(),
minimum_maximums=', '.join(minimum_maximums))
class CSharpExampleSpecialFunction(common.ExampleSpecialFunction):
def get_csharp_imports(self):
if self.get_type() == 'sleep':
return ['using System.Threading;\n']
else:
return []
def get_csharp_function(self):
return None
def get_csharp_source(self):
global global_line_prefix
type_ = self.get_type()
if type_ == 'empty':
return ''
elif type_ == 'debounce_period':
template = r""" // Get threshold callbacks with a debounce time of {period_sec} ({period_msec}ms)
{device_initial_name}.SetDebouncePeriod({period_msec});
"""
period_msec, period_sec = self.get_formatted_debounce_period()
return template.format(device_initial_name=self.get_device().get_initial_name(),
period_msec=period_msec,
period_sec=period_sec)
elif type_ == 'sleep':
template = '{comment1}{global_line_prefix}\t\tThread.Sleep({duration});{comment2}\n'
return template.format(global_line_prefix=global_line_prefix,
duration=self.get_sleep_duration(),
comment1=self.get_formatted_sleep_comment1(global_line_prefix + '\t\t// {0}\n', '\r', '\n' + global_line_prefix + '\t\t// '),
comment2=self.get_formatted_sleep_comment2(' // {0}', ''))
elif type_ == 'wait':
return None
elif type_ == 'loop_header':
template = '{comment}\t\tfor(int i = 0; i < {limit}; i++)\n\t\t{{\n'
global_line_prefix = '\t'
return template.format(limit=self.get_loop_header_limit(),
comment=self.get_formatted_loop_header_comment('\t\t// {0}\n', '', '\n\t\t// '))
elif type_ == 'loop_footer':
global_line_prefix = ''
return '\r\t\t}\n'
class CSharpExamplesGenerator(csharp_common.CSharpGeneratorTrait, common.ExamplesGenerator):
def get_constant_class(self):
return CSharpConstant
def get_example_class(self):
return CSharpExample
def get_example_argument_class(self):
return CSharpExampleArgument
def get_example_parameter_class(self):
return CSharpExampleParameter
def get_example_result_class(self):
return CSharpExampleResult
def get_example_getter_function_class(self):
return CSharpExampleGetterFunction
def get_example_setter_function_class(self):
return CSharpExampleSetterFunction
def get_example_callback_function_class(self):
return CSharpExampleCallbackFunction
def get_example_callback_period_function_class(self):
return CSharpExampleCallbackPeriodFunction
def get_example_callback_threshold_minimum_maximum_class(self):
return CSharpExampleCallbackThresholdMinimumMaximum
def get_example_callback_threshold_function_class(self):
return CSharpExampleCallbackThresholdFunction
def get_example_callback_configuration_function_class(self):
return CSharpExampleCallbackConfigurationFunction
def get_example_special_function_class(self):
return CSharpExampleSpecialFunction
def generate(self, device):
if os.getenv('TINKERFORGE_GENERATE_EXAMPLES_FOR_DEVICE', device.get_name().camel) != device.get_name().camel:
common.print_verbose(' \033[01;31m- skipped\033[0m')
return
examples_dir = self.get_examples_dir(device)
examples = device.get_examples()
if len(examples) == 0:
common.print_verbose(' \033[01;31m- no examples\033[0m')
return
if not os.path.exists(examples_dir):
os.makedirs(examples_dir)
for example in examples:
filename = 'Example{0}.cs'.format(example.get_name().camel)
filepath = os.path.join(examples_dir, filename)
if example.is_incomplete():
if os.path.exists(filepath) and self.skip_existing_incomplete_example:
common.print_verbose(' - ' + filename + ' \033[01;35m(incomplete, skipped)\033[0m')
continue
else:
common.print_verbose(' - ' + filename + ' \033[01;31m(incomplete)\033[0m')
else:
common.print_verbose(' - ' + filename)
with open(filepath, 'w') as f:
f.write(example.get_csharp_source())
def generate(root_dir, language, internal):
common.generate(root_dir, language, internal, CSharpExamplesGenerator)
if __name__ == '__main__':
args = common.dockerize('csharp', __file__, add_internal_argument=True)
generate(os.getcwd(), 'en', args.internal)