-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformMain.pas
More file actions
435 lines (376 loc) · 14.2 KB
/
Copy pathformMain.pas
File metadata and controls
435 lines (376 loc) · 14.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
//=============================================================================
// HyperCos v1 Arduino to Scratch bridge
// Copyright (C) 2009 David Knaack (davidknaack@gmail.com)
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
//=============================================================================
unit formMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, jpeg, ExtCtrls, StdCtrls, Buttons, uHyperCos, uFirmata;
type
TfrmMain = class(TForm, IHyperCosDisplay)
Image1: TImage;
Label4: TLabel;
Label5: TLabel;
lblLastCommand: TLabel;
lblFirmataInfo: TLabel;
lblErrorText: TLabel;
lblScratchInfo: TLabel;
lblManual: TLabel;
procedure FormCreate(Sender: TObject);
procedure lblErrorTextClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
slCmdHistory : TStringList;
cmdHistFile : string;
HistoryPos : Integer;
fHyperCos : IHyperCosControl;
ButtonBits : array of TSpeedButton;
IOLabels : array of TLabel;
procedure ButtonBitClick(Sender: TObject);
procedure AppOnExcept(Sender: TObject; E: Exception);
// IHyperCosDisplay implementations
procedure ShowFirmataConnectionStatus( const Port: string; const Speed: Integer; const Version: string; const Connected: Boolean );
procedure ShowScratchConnectionStatus( const Host: string; Port: Integer; const Connected: Boolean );
procedure ShowErrorText( const Text: string );
procedure ShowLastCmdText( const Text: string );
procedure ShowPinState( const Pin: Integer; const State: Boolean );
procedure ShowPinMode( const Pin: Integer; const Mode: TPinMode );
function GetHyperCos: IHyperCosControl;
public
property HyperCos: IHyperCosControl read GetHyperCos write fHyperCos;
end;
var
frmMain: TfrmMain;
implementation
uses Math;
{$R *.dfm}
{ TfrmMain }
//=====================================================================
// Procedure: FormCreate
// Author: DavidK
// Date: 17-Aug-2009
// Comments: Form creation, set up connections, controls, etc.
procedure TfrmMain.FormCreate(Sender: TObject);
const
cControlsTop = 30;
cControlsLeft = 70;
var
i : Integer;
begin
Application.OnException := AppOnExcept;
// Instead of setting up the visual controls in the form designer, this
// code is used to create them at start-up. This is a little more typing,
// but it's much easier to manage an array of similar controls this way.
SetLength( ButtonBits, 14 );
SetLength( IOLabels, 14 );
for i := 0 to 13 do begin
// Labels displaying the pin mode
IOLabels[i] := TLabel.Create(Self);
with IOLabels[i] do
begin
AutoSize := False;
Parent := Self;
Width := 15;
Height := 13;
Left := cControlsLeft + (i*(Width+4));
Top := cControlsTop;
Caption := 'o';
ParentFont := False;
Font.Color := clWhite;
Font.Style := [fsBold];
Transparent := True;
Alignment := taCenter;
end;
// Create a 14 buttons representing the Arduino pins
ButtonBits[i] := TSpeedButton.Create(Self);
with ButtonBits[i] do
begin
Parent := Self;
Tag := i;
Width := 17;
Height := 17;
Left := cControlsLeft + (i*(Width + 2));
Top := cControlsTop + 16;
GroupIndex := Tag;
AllowAllUp := True;
Caption := 'D';
OnClick := ButtonBitClick;
end;
// Labels identifying the buttons, 2..13
with TLabel.Create(Self) do
begin
AutoSize := False;
Parent := Self;
Width := 15;
Height := 13;
Left := cControlsLeft + (i*(Width+4));
Top := cControlsTop + 33;
Caption := IntToStr( i );
ParentFont := False;
Font.Color := clWhite;
Font.Style := [fsBold];
Transparent := True;
Alignment := taCenter;
end;
end;
// This form represents a Duemilanove compatible device,
// so disable the first two pins. They are used for serial
// IO and are not available.
ButtonBits[0].Enabled := False;
ButtonBits[1].Enabled := False;
IOLabels[0].Caption := 'x';
IOLabels[1].Caption := 'x';
// A stringlist for use as a simple command buffer.
slCmdHistory := TStringList.Create;
cmdHistFile := ExtractFilePath( Application.ExeName ) + 'CmdHistory.txt';
if FileExists( cmdHistFile ) then
slCmdHistory.LoadFromFile( cmdHistFile );
end;
//=====================================================================
// Procedure: FormDestroy
// Author: DavidK
// Date: 21-Oct-2009
// Comments:
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
// Most of the objects created in the FormCreate are owned by
// the form and so will automatically be released. The command
// buffer will have to be released here.
slCmdHistory.Free;
end;
//=====================================================================
// Procedure: GetHyperCos
// Author: DavidK
// Date: 08-Oct-2009
// Comments: Property read accessor for HyperCosControl interface.
// The form will use this internally rather than accessing
// the field directly in order to protect itself from an
// unset control interface.
function TfrmMain.GetHyperCos: IHyperCosControl;
begin
Result := fHyperCos;
if Result = nil then
raise Exception.Create( 'HyperCos control interface has not been set.' );
end;
//=====================================================================
// Procedure: ShowFirmataConnectionStatus
// Author: DavidK
// Date: 08-Oct-2009
// Comments:
procedure TfrmMain.ShowFirmataConnectionStatus( const Port: string; const Speed: Integer; const Version: string; const Connected: Boolean );
var conn: string;
begin
if Connected then begin
conn := 'connected';
// Clear any errors
ShowErrorText('');
end else
conn := 'disconnected';
lblFirmataInfo.Caption := Format( 'Firmata: %s:%d %s %s', [Port, Speed, Version, conn])
end;
//=====================================================================
// Procedure: ShowScratchConnectionStatus
// Author: DavidK
// Date: 08-Oct-2009
// Comments:
procedure TfrmMain.ShowScratchConnectionStatus( const Host: string; Port: Integer; const Connected: Boolean );
var conn: string;
begin
if Connected then begin
conn := 'connected';
// Clear any errors
ShowErrorText('');
end else
conn := 'disconnected';
lblScratchInfo.Caption := Format( 'Scratch: %s:%d %s', [Host, Port, conn]);
end;
//=====================================================================
// Procedure: ShowErrorText
// Author: DavidK
// Date: 07-Oct-2009
// Comments: Display the error message on the form and manage
// showing and hiding the error label. If the label
// is not hidden when it is blank it's hint will show
// up when the mouse hovers over it.
procedure TfrmMain.ShowErrorText( const Text: string );
begin
lblErrorText.Caption := Text;
lblErrorText.Visible := lblErrorText.Caption <> '';
end;
//=====================================================================
// Procedure: ShowLastCmdText
// Author: DavidK
// Date: 08-Oct-2009
// Comments:
procedure TfrmMain.ShowLastCmdText( const Text: string );
begin
lblLastCommand.Caption := Text;
end;
//=====================================================================
// Procedure: ShowPinState
// Author: DavidK
// Date: 08-Oct-2009
// Comments: Handle notification from HyperCos of pin state changes.
procedure TfrmMain.ShowPinState(const Pin: Integer; const State: Boolean);
begin
ButtonBits[Pin].Down := State;
end;
//=====================================================================
// Procedure: ShowPinMode
// Author: DavidK
// Date: 08-Oct-2009
// Comments: Handle notification from HyperCos of pin mode changes.
procedure TfrmMain.ShowPinMode(const Pin: Integer; const Mode: TPinMode);
var
cap : string;
begin
// Display an indicator for each mode.
case Mode of
pmDigitalInput : cap := 'i';
pmDigitalOutput : cap := 'o';
pmAnalogInput : cap := 'a';
pmDigitalPWM : cap := 'p';
pmServo : cap := 's';
pmUnavailable : cap := '-';
else cap := '?';
end;
IOLabels[Pin].Caption := cap;
end;
//=====================================================================
// Procedure: AppOnExcept
// Author: DavidK
// Date: 07-Oct-2009
// Comments: Unhandled exceptions may come through here, depending
// on whether a third-party exception handler is installed.
// Packages like madExcept or the JCL Debug system can catch
// exceptions before they arrive here.
// Most of the code in this form that is be expected to raise
// various exceptions is trapped and redirected already.
procedure Tfrmmain.AppOnExcept(Sender: TObject; E: Exception);
begin
ShowErrorText( E.Message );
end;
//=====================================================================
// Procedure: lblErrorTextClick
// Author: DavidK
// Date: 03-Oct-2009
// Comments: Clear error message when clicked
procedure TfrmMain.lblErrorTextClick(Sender: TObject);
begin
ShowErrorText( '' );
end;
//=====================================================================
// Procedure: ButtonBitClick
// Author: DavidK
// Date: 17-Aug-2009
// Comments: The user has clicked one of the buttons representing
// a port pin. Set the state of the appropriate pin.
procedure TfrmMain.ButtonBitClick(Sender: TObject);
const
cPinState : array[boolean] of string = ('low', 'high');
begin
try
with Sender as TSpeedButton do
// For simplicity HyperCos currently just allows for the injection
// of text as if it had been sent from Scratch (minus the caret prefix).
HyperCos.InjectCommand( Format( 'digitalwrite %d %s', [Tag, cPinState[Down]]));
except
on e:Exception do
ShowErrorText( E.Message );
end;
end;
//=====================================================================
// Procedure: FormKeyUp
// Author: DavidK
// Date: 21-Oct-2009
// Comments: This is a simple debug feature. The user may type
// HyperCos commands directly into the interface much
// as if Scratch had sent them. Note that the caption
// property is used as a storage variable for the user's
// input. In general this is a very bad habit to get into.
// It combines data management with the user interface
// elements and makes it difficult to reuse or refactor.
// I'm doing it here only because this is intended as a
// simple debug feature. However, you can see that feature
// creep has already started with the addition of a command
// buffer to allow easy reuse of commands. It might be a
// good exercise to create a new form that replaces this
// badly designed bit of code with a nicer interface that
// give the user some hints about what commands can be used,
// maybe some buttons for quick access, etc.
procedure TfrmMain.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
oldColor : TColor;
begin
case key of
// Append keystrokes to command buffer
// The calls to Ord() here are just to make it easy to use
// the VK_ codes below which are integer type. You could also
// leave out the Ord()s here and cast the VK_ constants to char.
Ord('A')..Ord('Z'),
Ord('0')..Ord('9'),
Ord(' ') :
lblManual.Caption := lblManual.Caption + Char(Key);
// Up arrow. 'VK' stands for 'virtual key'.
VK_Up : begin
// Decrement and limit history pointer
Dec( HistoryPos );
HistoryPos := Max( HistoryPos, 0 );
// Display the command
lblManual.Caption := slCmdHistory[HistoryPos];
end;
// Down arrow
VK_Down : begin
// Increment and limit history pointer
Inc( HistoryPos );
HistoryPos := Min( HistoryPos, slCmdHistory.Count-1 );
// Display the command
lblManual.Caption := slCmdHistory[HistoryPos];
end;
// Typos happen.
VK_BACK :
lblManual.Caption := copy( lblManual.Caption, 1, length( lblManual.Caption )-1);
// Escape key clears input
VK_ESCAPE :
lblManual.Caption := '';
// Enter submits input
VK_RETURN : begin
// Manage the command history
if slCmdHistory.IndexOf( lblManual.Caption ) = -1 then begin
slCmdHistory.Add( lblManual.Caption );
// Save it now, during development it isn't unusual to kill
// the program without going through normal shutdown, so if
// the file is only saved then it won't ever build the history.
slCmdHistory.SaveToFile( cmdHistFile );
end;
// Some commands take a little while to process, so provide some
// feedback by changing the label color.
oldColor := lblManual.font.Color;
lblManual.font.Color := clLime;
lblManual.Refresh;
// inject the command
HyperCos.InjectCommand( lblManual.Caption );
// Reset the label color.
lblManual.Caption := '';
lblManual.font.Color := oldColor;
end;
end; // case
end;
end.