-
Notifications
You must be signed in to change notification settings - Fork 585
/
LcdConsole.cs
585 lines (525 loc) · 21.6 KB
/
LcdConsole.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
573
574
575
576
577
578
579
580
581
582
583
584
585
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Globalization;
using System.Drawing;
using Iot.Device.Graphics;
namespace Iot.Device.CharacterLcd
{
/// <summary>
/// This is a high-level interface to an LCD display.
/// It supports automatic wrapping of text, automatic scrolling and code page mappings.
/// This class is thread safe, however using Write from different threads may lead to unexpected results, since the order is not guaranteed.
/// </summary>
public sealed class LcdConsole : IDisposable
{
private readonly object _lock;
private readonly bool _shouldDispose;
private ICharacterLcd _lcd;
/// <summary>
/// The text currently on the display (required for arbitrary scrolling)
/// </summary>
private StringBuilder[] _currentData;
private LineWrapMode _lineFeedMode;
private TimeSpan _scrollUpDelay;
private string _romType;
private Encoding? _characterEncoding;
/// <summary>
/// Creates a new instance of the <see cref="LcdConsole"/> class using the specified LCD low-level interface.
/// This class automatically configures the low-level interface. Do not use the low-level interface at the same time.
/// </summary>
/// <param name="lcd">The low-level LCD interface.</param>
/// <param name="romType">Name of character ROM of display. Currently supported types: A00 and A02.</param>
/// <param name="shouldDispose">If the class should dispose the LCD driver when it is disposed. Defaults to true</param>
public LcdConsole(ICharacterLcd lcd, string romType, bool shouldDispose = true)
{
_lcd = lcd;
_shouldDispose = shouldDispose;
_romType = romType;
_characterEncoding = null;
Size = lcd.Size;
_currentData = new StringBuilder[Size.Height];
CursorLeft = 0;
CursorTop = 0;
ScrollUpDelay = TimeSpan.Zero;
_lock = new object();
_lcd.UnderlineCursorVisible = false;
_lcd.BlinkingCursorVisible = false;
_lcd.DisplayOn = true;
_lcd.BacklightOn = true;
ClearStringBuffer();
_lcd.Clear();
}
/// <summary>
/// Position of the cursor, from left.
/// Note: May be outside the bounds of the display.
/// </summary>
public int CursorLeft { get; private set; }
/// <summary>
/// Position of the cursor, from top
/// Note: May be outside the bounds of the display.
/// </summary>
public int CursorTop { get; private set; }
/// <summary>
/// If this is larger than zero, an a wait is introduced each time the display wraps to the next line or scrolls up. Can be used to print long texts to the display,
/// but keeping it readable.
/// </summary>
public TimeSpan ScrollUpDelay
{
get => _scrollUpDelay;
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(value), "Timespan must be positive");
}
_scrollUpDelay = value;
}
}
/// <summary>
/// Enables or disables the backlight
/// </summary>
public bool BacklightOn
{
get
{
lock (_lock)
{
return _lcd.BacklightOn;
}
}
set
{
lock (_lock)
{
_lcd.BacklightOn = value;
}
}
}
/// <summary>
/// Enables or disables the display
/// </summary>
public bool DisplayOn
{
get
{
lock (_lock)
{
return _lcd.DisplayOn;
}
}
set
{
lock (_lock)
{
_lcd.DisplayOn = value;
}
}
}
/// <summary>
/// Sets the Line Feed Mode.
/// This defines what happens when writting past the end of the line/screen.
/// </summary>
public LineWrapMode LineFeedMode
{
get => _lineFeedMode;
set
{
_lineFeedMode = value;
}
}
/// <summary>
/// Size of the display
/// </summary>
public Size Size { get; }
private void ClearStringBuffer()
{
for (int i = 0; i < Size.Height; i++)
{
// The display has now only spaces on it.
_currentData[i] = new StringBuilder(new String(' ', Size.Width));
}
}
/// <summary>
/// Clears the screen and sets the cursor back to the start.
/// </summary>
public void Clear()
{
lock (_lock)
{
_lcd.Clear();
ClearStringBuffer();
SetCursorPosition(0, 0);
}
}
/// <summary>
/// Moves the cursor to an explicit column and row position.
/// The position may be outside the bounds of the display. Any subsequent writes will then have no effect, unless <see cref="LineFeedMode"/> allows it or a newline character is written.
/// </summary>
/// <param name="left">The column position from left to right starting with 0.</param>
/// <param name="top">The row position from the top starting with 0.</param>
/// <exception cref="ArgumentOutOfRangeException">The new position negative.</exception>
public void SetCursorPosition(int left, int top)
{
lock (_lock)
{
if (left < 0)
{
throw new ArgumentOutOfRangeException(nameof(left));
}
if (top < 0)
{
throw new ArgumentOutOfRangeException(nameof(top));
}
if (left < Size.Width && top < Size.Height)
{
_lcd.SetCursorPosition(left, top);
}
CursorLeft = left;
CursorTop = top;
}
}
/// <summary>
/// Write text to display.
/// </summary>
/// <param name="text">Text to be displayed.</param>
/// <exception cref="ArgumentNullException"><paramref name="text"/> was null.</exception>
/// <remarks>
/// There are only 256 characters available. There are chip variants
/// with different character sets. Characters from space ' ' (32) to
/// '}' are usually the same with the exception of '\', which is a
/// yen symbol on some chips '¥'. See constructor for character map definitions.
/// </remarks>
public void Write(string text)
{
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
text = text.Replace("\r\n", "\n"); // Change to linux format only, so we have to consider only this case further
List<string> lines = text.Split('\n').ToList();
FindLineWraps(CursorLeft, lines);
for (int i = 0; i < lines.Count; i++)
{
string line = lines[i];
string currentLine = line;
int remainingChars = Math.Min(currentLine.Length, Size.Width - CursorLeft);
int actuallyUsedRemainingChars = (CursorLeft + remainingChars) < Size.Width ? CursorLeft + remainingChars : Size.Width;
if (CursorLeft + remainingChars < Size.Width && LineFeedMode != LineWrapMode.Truncate)
{
// If we're in line feed mode, make sure we delete anything past the end of the new line (relevant in case of overwriting)
currentLine += new string(' ', Size.Width - remainingChars - CursorLeft);
remainingChars = currentLine.Length;
}
if (remainingChars > 0)
{
lock (_lock)
{
WriteCurrentLine(currentLine.Substring(0, remainingChars));
}
// Reset back, so that if we write a line with multiple calls to Write, the line is continued.
if (actuallyUsedRemainingChars < Size.Width)
{
CursorLeft = actuallyUsedRemainingChars;
}
}
if (i != lines.Count - 1)
{
// Insert newline except after the last text segment.
NewLine();
}
}
}
/// <summary>
/// Replaces the text of the given line.
/// This will overwrite the text in the given line, filling up with spaces, if needed.
/// This will never wrap to the next line, and line feeds in the input string are not allowed.
/// </summary>
/// <param name="lineNumber">0-based index of the line to start</param>
/// <param name="text">Text to insert. No newlines supported.</param>
/// <exception cref="ArgumentException">The string contains newlines.</exception>
public void ReplaceLine(int lineNumber, string text)
{
if (text.Contains("\n"))
{
// This is to simplify usage. You would normally use this method to replace one line with new text (i.e. replace only the active element, not affecting the menu title)
throw new ArgumentException("The string may not contain line feeds");
}
lock (_lock)
{
SetCursorPosition(0, lineNumber);
if (text.Length > Size.Width)
{
text = text.Substring(0, Size.Width);
}
else if (text.Length < Size.Width)
{
text = text + new string(' ', Size.Width - text.Length);
}
WriteCurrentLine(text);
}
}
/// <summary>
/// Find where we need to insert additional newlines
/// </summary>
private void FindLineWraps(int cursorPos, List<string> lines)
{
if (LineFeedMode == LineWrapMode.Wrap || LineFeedMode == LineWrapMode.WordWrap)
{
int roomOnLine = Size.Width - cursorPos;
roomOnLine = Math.Max(roomOnLine, 0);
for (int i = 0; i < lines.Count; i++)
{
string remaining = lines[i];
if (remaining.Length > roomOnLine)
{
if (LineFeedMode == LineWrapMode.WordWrap)
{
// In intelligent mode, try finding spaces backwards
// Note: this indexes the element 1 char after the last to be printed in the first iteration, since there might be a space just there
int tempRoomOnLine = roomOnLine;
while (remaining[tempRoomOnLine] != ' ' && tempRoomOnLine > 0)
{
tempRoomOnLine--;
}
// If we didn't find a space, break after the maximum number of chars
if (tempRoomOnLine > 0)
{
roomOnLine = tempRoomOnLine;
}
}
// This line does not fit on the remaining room of this row
string firstPart = remaining.Substring(0, roomOnLine);
lines[i] = firstPart;
// Insert the remaining part as new entry to the list, continue iteration there
string remainingPart = remaining.Substring(roomOnLine).TrimStart(' ');
lines.Insert(i + 1, remainingPart);
}
roomOnLine = Size.Width; // From now on, we have the full width available
}
}
}
/// <summary>
/// Writes the given text to the current position, then wraps to the next line.
/// </summary>
/// <param name="text">Text to draw.</param>
/// <exception cref="ArgumentNullException"><paramref name="text"/> was null.</exception>
public void WriteLine(string text = "")
{
Write(text);
NewLine();
}
/// <summary>
/// Blinks the display text (and the backlight, if available).
/// Can be used to get user attention.
/// Operation is synchronous.
/// </summary>
/// <param name="times">Number of times to blink. The blink rate is 1 Hz</param>
public void BlinkDisplay(int times)
{
var blinkTask = BlinkDisplayAsync(times);
blinkTask.Wait();
}
/// <summary>
/// Blinks the display in the background
/// </summary>
/// <param name="times">Number of times to blink</param>
/// <returns>A task handle</returns>
public Task BlinkDisplayAsync(int times)
{
return Task.Factory.StartNew(() =>
{
for (int i = 0; i < times; i++)
{
lock (_lock)
{
_lcd.DisplayOn = false;
_lcd.BacklightOn = false;
}
Thread.Sleep(500);
lock (_lock)
{
_lcd.DisplayOn = true;
_lcd.BacklightOn = true;
}
Thread.Sleep(500);
}
});
}
private void NewLine()
{
// Wait before scrolling, so that the last line may also contain text
if (_scrollUpDelay > TimeSpan.Zero)
{
Thread.Sleep(_scrollUpDelay);
}
lock (_lock)
{
if (CursorTop < Size.Height - 1)
{
SetCursorPosition(0, CursorTop + 1);
}
else if (LineFeedMode == LineWrapMode.WordWrap || LineFeedMode == LineWrapMode.Wrap)
{
ScrollUp();
SetCursorPosition(0, Size.Height - 1); // Go to beginning of last line
}
else
{
CursorLeft = Size.Width; // We are outside the screen, any further writes will be ignored
}
}
}
/// <summary>
/// Refreshes the display from the cache (i.e. after a scroll operation)
/// Does not change the cursor position
/// </summary>
private void RefreshFromBuffer()
{
int x = CursorLeft;
int y = CursorTop;
for (int i = 0; i < Size.Height; i++)
{
_lcd.SetCursorPosition(0, i);
char[] buffer = MapChars(_currentData[i].ToString());
_lcd.Write(buffer);
}
SetCursorPosition(x, y);
}
/// <summary>
/// Scrolls the text up by one row, clearing the last row. Does not change the cursor position.
/// Implementation note: Caller must own the lock.
/// </summary>
private void ScrollUp()
{
for (int i = 1; i < Size.Height; i++)
{
_currentData[i - 1] = _currentData[i];
}
_currentData[Size.Height - 1] = new StringBuilder(new String(' ', Size.Width));
RefreshFromBuffer();
}
/// <summary>
/// This is expected to be called only with a string length of less or equal the remaining number of characters on the current line.
/// Implementation note: Caller must own the lock.
/// </summary>
private void WriteCurrentLine(string line)
{
// Replace the existing chars at the given position with the new text
_currentData[CursorTop].Remove(CursorLeft, line.Length);
_currentData[CursorTop].Insert(CursorLeft, line);
char[] buffer = MapChars(line);
_lcd.Write(buffer);
CursorLeft += line.Length;
}
/// <summary>
/// Creates an encoding that can be used for an LCD display.
/// Typically, the returned value will be loaded using <see cref="LoadEncoding(LcdCharacterEncoding)"/>.
/// </summary>
/// <param name="culture">Required display culture (forwarded to the factory)</param>
/// <param name="romType">The name of the ROM for which the encoding is to be applied. The default factory supports roms A00 and A02.</param>
/// <param name="unknownCharacter">The character to print for unknown letters, default: ?</param>
/// <param name="maxNumberOfCustomCharacters">The maximum number of custom characters supported by the hardware.</param>
/// <param name="factory">Character encoding factory that delivers the mapping of the Char type to the hardware ROM character codes. May add special characters into
/// the character ROM. Default: Null (Use internal factory)</param>
public static LcdCharacterEncoding CreateEncoding(CultureInfo culture, string romType, char unknownCharacter = '?', int maxNumberOfCustomCharacters = 8, LcdCharacterEncodingFactory? factory = null) =>
(factory ?? new LcdCharacterEncodingFactory()).Create(culture, romType, unknownCharacter, maxNumberOfCustomCharacters);
/// <summary>
/// Loads the specified encoding.
/// This behaves as <see cref="LoadEncoding(LcdCharacterEncoding)"/> when the argument is of the dynamic type <see cref="LcdCharacterEncoding"/>, otherwise like an encding
/// with no special characters.
/// </summary>
/// <param name="encoding">The encoding to load.</param>
/// <returns>See true if the encoding was correctly loaded.</returns>
public bool LoadEncoding(Encoding encoding)
{
if (encoding is LcdCharacterEncoding lcdCharacterEncoding)
{
return LoadEncoding(encoding);
}
lock (_lock)
{
_characterEncoding = encoding;
}
return true;
}
/// <summary>
/// Loads the specified character encoding. This loads any custom characters from the encoding to the display.
/// </summary>
/// <param name="encoding">The encoding to load.</param>
/// <returns>True if the character encoding was successfully loaded, false if there are not enough custom slots for all the required custom characters.
/// This may also return false if the encoding factory returned incomplete results, such as a missing custom character for a special diacritic.</returns>
public bool LoadEncoding(LcdCharacterEncoding encoding)
{
bool allCharactersLoaded = encoding.AllCharactersSupported;
lock (_lock)
{
int numberOfCharactersToLoad = Math.Min(encoding.ExtraCharacters.Count, _lcd.NumberOfCustomCharactersSupported);
if (numberOfCharactersToLoad < encoding.ExtraCharacters.Count)
{
// We can't completely load that encoding, because there are not enough custom slots.
allCharactersLoaded = false;
}
for (byte i = 0; i < numberOfCharactersToLoad; i++)
{
byte[] pixelMap = encoding.ExtraCharacters[i];
_lcd.CreateCustomCharacter(i, pixelMap);
}
_characterEncoding = encoding;
}
return allCharactersLoaded;
}
/// <summary>
/// Resets the character encoding to hardware defaults (using simply the lower byte of a char).
/// </summary>
public void ResetEncoding()
{
lock (_lock)
{
_characterEncoding = null;
}
}
private char[] MapChars(string line)
{
char[] buffer = new char[line.Length];
if (_characterEncoding is null)
{
for (int i = 0; i < line.Length; i++)
{
buffer[i] = line[i];
}
return buffer;
}
else
{
byte[] buff = _characterEncoding.GetBytes(line);
if (buff is not object)
{
return new char[0];
}
char[] encoded = new char[buff.Length];
for (int i = 0; i < buff.Length; i++)
{
encoded[i] = (char)buff[i];
}
return encoded;
}
}
/// <summary>
/// Disposes this instance.
/// </summary>
public void Dispose()
{
if (_shouldDispose)
{
_lcd?.Dispose();
}
GC.SuppressFinalize(this);
}
}
}