-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfinal_clean_arduino_examples_no_undefined.py
More file actions
490 lines (399 loc) · 15.8 KB
/
final_clean_arduino_examples_no_undefined.py
File metadata and controls
490 lines (399 loc) · 15.8 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
"""
Complete Arduino-to-PC Message Examples for X-Plane Dataref Bridge
This file provides complete working examples for both Arduino and PC sides
of the communication protocol.
"""
# ARDUINO SIDE EXAMPLE (.ino file content)
ARDUINO_EXAMPLE = '''
// Arduino Message Functions Example
// Place this code in your Arduino .ino file
// Function to send INPUT <KEY> <VALUE> message
void sendInputNotification(String key, String value) {
String message = "INPUT " + key + " " + value;
Serial.println(message);
Serial.flush();
}
// Function to send CMD <COMMAND> message
void sendCommand(String command) {
String message = "CMD " + command;
Serial.println(message);
Serial.flush();
}
// Function to send DREF <DATAREF> <VALUE> message (for writing to datarefs)
void sendDatarefWrite(String dataref, String value) {
String message = "DREF " + dataref + " " + value;
Serial.println(message);
Serial.flush();
}
// Function to send ACK <KEY> <VALUE> message
void sendAck(String key, String value) {
String message = "ACK " + key + " " + value;
Serial.println(message);
Serial.flush();
}
// Function to send VALUE <DATAREF> <VALUE> message (for reporting dataref values)
void sendValueResponse(String dataref, String value) {
String message = "VALUE " + dataref + " " + value;
Serial.println(message);
Serial.flush();
}
// Function to send ARRAYVALUE <ARRAY_NAME> <TYPE> <CSV_VALUES> message
void sendArrayValue(String arrayName, String dataType, String csvValues) {
String message = "ARRAYVALUE " + arrayName + " " + dataType + " " + csvValues;
Serial.println(message);
Serial.flush();
}
// Function to send ELEMVALUE <ARRAY_NAME[INDEX]> <TYPE> <VALUE> message
void sendElementValue(String arrayName, int index, String dataType, String value) {
String message = "ELEMVALUE " + arrayName + "[" + index + "] " + dataType + " " + value;
Serial.println(message);
Serial.flush();
}
// Example usage in Arduino loop
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Arduino ready - sending messages to PC");
}
void loop() {
// Example: Send button press notification
sendInputNotification("BUTTON_1", "PRESSED");
delay(100);
// Example: Send command execution
sendCommand("SET_MODE_AUTO");
delay(100);
// Example: Send dataref write request
sendDatarefWrite("sim/cockpit/electrical/avionics_on", "1");
delay(100);
// Example: Send acknowledgment
sendAck("INIT", "COMPLETE");
delay(100);
// Example: Send value response
sendValueResponse("sim/flightmodel/position/altitude", "1500.5");
delay(100);
// Example: Send array value
sendArrayValue("sensor_array", "float", "1.0,2.5,3.7,4.2,5.1");
delay(100);
// Example: Send element value
sendElementValue("servo_positions", 2, "int", "1500");
delay(100);
delay(2000); // Wait 2 seconds before sending next batch
}
'''
# PC SIDE PYTHON EXAMPLE
import re
from typing import Dict, Any, List, Optional, Union
class ArduinoMessageParser:
"""
Parser for handling messages from Arduino in the X-Plane Dataref Bridge protocol
"""
def __init__(self):
# Regex patterns for different message types
self.patterns = {
'INPUT': r'^INPUT\s+(\w+)\s+(.+)$',
'CMD': r'^CMD\s+(.+)$',
'DREF': r'^DREF\s+([^\s]+)\s+(.+)$',
'ACK': r'^ACK\s+(\w+)\s+(.+)$',
'VALUE': r'^VALUE\s+([^\s]+)\s+(.+)$',
'ARRAYVALUE': r'^ARRAYVALUE\s+(\w+)\s+(\w+)\s+(.+)$',
'ELEMVALUE': r'^ELEMVALUE\s+(\w+)\[(\d+)\]\s+(\w+)\s+(.+)$'
}
def parse_message(self, message: str) -> Optional[Dict[str, Any]]:
"""
Parse an incoming message and return its type and components
"""
message = message.strip()
for msg_type, pattern in self.patterns.items():
match = re.match(pattern, message)
if match:
groups = match.groups()
if msg_type == 'INPUT':
return {
'type': 'INPUT',
'key': groups[0],
'value': groups[1]
}
elif msg_type == 'CMD':
return {
'type': 'CMD',
'command': groups[0]
}
elif msg_type == 'DREF':
return {
'type': 'DREF',
'dataref': groups[0],
'value': groups[1]
}
elif msg_type == 'ACK':
return {
'type': 'ACK',
'key': groups[0],
'value': groups[1]
}
elif msg_type == 'VALUE':
return {
'type': 'VALUE',
'dataref': groups[0],
'value': groups[1]
}
elif msg_type == 'ARRAYVALUE':
return {
'type': 'ARRAYVALUE',
'array_name': groups[0],
'data_type': groups[1],
'values': [val.strip() for val in groups[2].split(',')]
}
elif msg_type == 'ELEMVALUE':
return {
'type': 'ELEMVALUE',
'array_name': groups[0],
'index': int(groups[1]),
'data_type': groups[2],
'value': groups[3]
}
# If no pattern matches, return None
return None
class ArduinoMessageHandler:
"""
Handler for processing different types of messages from Arduino
"""
def __init__(self):
self.parser = ArduinoMessageParser()
self.variables = {}
self.datarefs = {}
self.arrays = {}
def handle_message(self, message: str) -> bool:
"""
Process an incoming message from Arduino
"""
parsed_msg = self.parser.parse_message(message)
if not parsed_msg:
print(f"Unknown message format: {message}")
return False
msg_type = parsed_msg['type']
if msg_type == 'INPUT':
return self.handle_input(parsed_msg)
elif msg_type == 'CMD':
return self.handle_cmd(parsed_msg)
elif msg_type == 'DREF':
return self.handle_dref(parsed_msg)
elif msg_type == 'ACK':
return self.handle_ack(parsed_msg)
elif msg_type == 'VALUE':
return self.handle_value(parsed_msg)
elif msg_type == 'ARRAYVALUE':
return self.handle_arrayvalue(parsed_msg)
elif msg_type == 'ELEMVALUE':
return self.handle_elemvalue(parsed_msg)
return False
def handle_input(self, msg: Dict[str, Any]) -> bool:
"""
Handle INPUT <KEY> <VALUE> messages
Used for input notifications from Arduino (buttons, switches, etc.)
"""
key = msg['key']
value = msg['value']
print(f"Input notification received: {key} = {value}")
# Store the input value in variables
self.variables[key] = value
# Trigger specific actions based on the input
if key.startswith('BUTTON'):
self.process_button(key, value)
elif key.startswith('SWITCH'):
self.process_switch(key, value)
elif key.startswith('POT'):
self.process_potentiometer(key, value)
return True
def handle_cmd(self, msg: Dict[str, Any]) -> bool:
"""
Handle CMD <COMMAND> messages
Used for command execution requests from Arduino
"""
command = msg['command']
print(f"Command execution request: {command}")
# Execute the command
if command == "RESET":
self.execute_reset()
elif command == "REBOOT":
self.execute_reboot()
elif command.startswith("SET_MODE "):
mode = command.split(' ', 1)[1]
self.set_mode(mode)
else:
print(f"Unknown command: {command}")
return False
return True
def handle_dref(self, msg: Dict[str, Any]) -> bool:
"""
Handle DREF <DATAREF> <VALUE> messages
Used for writing values to datarefs from Arduino
"""
dataref = msg['dataref']
value = msg['value']
print(f"Dataref write request: {dataref} = {value}")
# In a real implementation, this would send the value to X-Plane
# For now, we'll just store it locally
self.datarefs[dataref] = value
# Send acknowledgment back to Arduino
self.send_ack(f"DREF_WRITE_{dataref}", "SUCCESS")
return True
def handle_ack(self, msg: Dict[str, Any]) -> bool:
"""
Handle ACK <KEY> <VALUE> messages
Used for acknowledgments from Arduino
"""
key = msg['key']
value = msg['value']
print(f"Acknowledgment received: {key} = {value}")
# Process acknowledgment based on the key
if key == 'INIT':
print("Arduino initialization acknowledged")
elif key == 'CONFIG':
print(f"Configuration acknowledged: {value}")
elif key.startswith('WRITE'):
print(f"Write operation acknowledged: {value}")
return True
def handle_value(self, msg: Dict[str, Any]) -> bool:
"""
Handle VALUE <DATAREF> <VALUE> messages
Used for reporting dataref values from Arduino sensors
"""
dataref = msg['dataref']
value = msg['value']
print(f"Dataref value reported: {dataref} = {value}")
# Store the reported value
self.datarefs[dataref] = value
# Could trigger updates in the UI or other systems
self.update_dataref_display(dataref, value)
return True
def handle_arrayvalue(self, msg: Dict[str, Any]) -> bool:
"""
Handle ARRAYVALUE <ARRAY_NAME> <TYPE> <CSV_VALUES> messages
Used for reporting array values from Arduino
"""
array_name = msg['array_name']
data_type = msg['data_type']
values_str = msg['values']
print(f"Array value reported: {array_name} ({data_type}) = {values_str}")
# Convert CSV string to list
values_list = [val.strip() for val in values_str.split(',')]
# Convert values based on type
converted_values = self.convert_values(values_list, data_type)
# Store the array
self.arrays[array_name] = {
'type': data_type,
'values': converted_values
}
# Could trigger updates for array data
self.update_array_display(array_name, converted_values)
return True
def handle_elemvalue(self, msg: Dict[str, Any]) -> bool:
"""
Handle ELEMVALUE <ARRAY_NAME[INDEX]> <TYPE> <VALUE> messages
Used for reporting individual array element values from Arduino
"""
array_name = msg['array_name']
index = msg['index']
data_type = msg['data_type']
value = msg['value']
print(f"Array element value: {array_name}[{index}] ({data_type}) = {value}")
# Convert value based on type
converted_value = self.convert_single_value(value, data_type)
# Initialize array if it doesn't exist
if array_name not in self.arrays:
self.arrays[array_name] = {'type': data_type, 'values': []}
# Ensure the array is large enough
while len(self.arrays[array_name]['values']) <= index:
self.arrays[array_name]['values'].append(None)
# Set the value at the specified index
self.arrays[array_name]['values'][index] = converted_value
# Could trigger updates for specific array elements
self.update_array_element_display(array_name, index, converted_value)
return True
def convert_values(self, values: List[str], data_type: str) -> List[Any]:
"""
Convert string values to appropriate types based on data_type
"""
if data_type.lower() == 'float':
return [float(v) for v in values]
elif data_type.lower() == 'int':
return [int(v) for v in values]
elif data_type.lower() == 'bool':
return [v.lower() == 'true' for v in values]
else: # Default to string
return values
def convert_single_value(self, value: str, data_type: str) -> Any:
"""
Convert a single string value to appropriate type
"""
if data_type.lower() == 'float':
return float(value)
elif data_type.lower() == 'int':
return int(value)
elif data_type.lower() == 'bool':
return value.lower() == 'true'
else: # Default to string
return value
# Placeholder methods for actual implementations
def process_button(self, key: str, value: str):
"""Process button input"""
print(f"Processing button {key} with value {value}")
def process_switch(self, key: str, value: str):
"""Process switch input"""
print(f"Processing switch {key} with value {value}")
def process_potentiometer(self, key: str, value: str):
"""Process potentiometer input"""
print(f"Processing potentiometer {key} with value {value}")
def execute_reset(self):
"""Execute reset command"""
print("Executing reset command")
def execute_reboot(self):
"""Execute reboot command"""
print("Executing reboot command")
def set_mode(self, mode: str):
"""Set system mode"""
print(f"Setting mode to {mode}")
def update_dataref_display(self, dataref: str, value: str):
"""Update dataref display in UI"""
print(f"Updating display for {dataref} = {value}")
def update_array_display(self, array_name: str, values: List[Any]):
"""Update array display in UI"""
print(f"Updating array display for {array_name}: {values}")
def update_array_element_display(self, array_name: str, index: int, value: Any):
"""Update specific array element display in UI"""
print(f"Updating array element display for {array_name}[{index}] = {value}")
def send_ack(self, key: str, value: str):
"""Send acknowledgment back to Arduino"""
print(f"Sending ACK {key} {value}")
# Example usage
if __name__ == "__main__":
parser = ArduinoMessageParser()
handler = ArduinoMessageHandler()
# Test messages
test_messages = [
"INPUT BUTTON_1 PRESSED",
"CMD SET_MODE_AUTO",
"DREF sim/cockpit/electrical/avionics_on 1",
"ACK INIT COMPLETE",
"VALUE sim/flightmodel/position/altitude 1500.5",
"ARRAYVALUE sensor_array float 1.0,2.5,3.7,4.2,5.1",
"ELEMVALUE servo_positions[2] int 1500"
]
print("Testing Arduino message parsing and handling:")
print("=" * 50)
for msg in test_messages:
print(f"\nProcessing: {msg}")
parsed = parser.parse_message(msg)
if parsed:
print(f"Parsed: {parsed}")
success = handler.handle_message(msg)
print(f"Result: {'Success' if success else 'Failed'}")
else:
print("Failed to parse message")
print("\nFinal state:")
print(f"Variables: {handler.variables}")
print(f"Datarefs: {handler.datarefs}")
print(f"Arrays: {handler.arrays}")
print("\nArduino code example:")
print("=" * 50)
print(ARDUINO_EXAMPLE)