-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunified_epd_adapter.py
More file actions
665 lines (538 loc) · 20 KB
/
unified_epd_adapter.py
File metadata and controls
665 lines (538 loc) · 20 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
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
Unified E-Paper Display Adapter
This module provides a unified interface for different e-paper display types,
allowing the same code to work with various Waveshare displays.
Supported displays:
- epd2in15g (2.15" grayscale)
- epd13in3E (13.3" color)
- epd7in3e (7.3" color)
Usage:
# For 2.15" display
epd = UnifiedEPD.create_display("epd2in15g")
# For 13.3" display
epd = UnifiedEPD.create_display("epd13in3E")
# For 7.3" display
epd = UnifiedEPD.create_display("epd7in3e")
# Common interface
epd.init()
epd.display(image)
epd.clear()
epd.sleep()
"""
import sys
import os
import logging
from abc import ABC, abstractmethod
from typing import Union, Optional
from PIL import Image
logger = logging.getLogger(__name__)
class EPDAdapter(ABC):
"""Abstract base class for EPD adapters"""
@abstractmethod
def init(self) -> int:
"""Initialize the display"""
pass
@abstractmethod
def display(self, image) -> None:
"""Display an image"""
pass
@abstractmethod
def clear(self, color: Optional[int] = None) -> None:
"""Clear the display"""
pass
@abstractmethod
def sleep(self) -> None:
"""Put display to sleep"""
pass
@abstractmethod
def getbuffer(self, image: Image.Image):
"""Convert image to display buffer"""
pass
@property
@abstractmethod
def display_type(self) -> str:
"""Display type"""
pass
@property
@abstractmethod
def width(self) -> int:
"""Display width"""
pass
@property
@abstractmethod
def height(self) -> int:
"""Display height"""
pass
@property
@abstractmethod
def WHITE(self) -> int:
"""White color value"""
pass
@property
@abstractmethod
def BLACK(self) -> int:
"""Black color value"""
pass
@property
@abstractmethod
def RED(self) -> int:
"""Red color value"""
pass
@property
@abstractmethod
def YELLOW(self) -> int:
"""Yellow color value"""
pass
# Orientation-aware properties
@property
def native_orientation(self) -> str:
"""Get native orientation of the display"""
# This will be overridden in concrete adapters
return "landscape"
@property
def landscape_width(self) -> int:
"""Width when display is in landscape orientation"""
if self.native_orientation == "landscape":
return self.width
else:
return self.height
@property
def landscape_height(self) -> int:
"""Height when display is in landscape orientation"""
if self.native_orientation == "landscape":
return self.height
else:
return self.width
@property
def portrait_width(self) -> int:
"""Width when display is in portrait orientation"""
if self.native_orientation == "portrait":
return self.width
else:
return self.height
@property
def portrait_height(self) -> int:
"""Height when display is in portrait orientation"""
if self.native_orientation == "portrait":
return self.height
else:
return self.width
class EPD2in15gAdapter(EPDAdapter):
"""Adapter for epd2in15g display"""
def __init__(self):
# Import the actual display module
try:
from waveshare_epd import epd2in15g
self._epd = epd2in15g.EPD()
except ImportError:
logger.error("epd2in15g module not found. Make sure waveshare_epd is in your path.")
raise
@property
def display_type(self) -> str:
return "epd2in15g"
def init(self) -> int:
"""Initialize the display"""
return self._epd.init()
def display(self, image) -> None:
"""Display an image"""
self._epd.display(image)
def clear(self, color: Optional[int] = None) -> None:
"""Clear the display"""
if color is None:
color = 0x55 # Default for 2in15g
# Try both Clear and clear methods for compatibility
if hasattr(self._epd, 'Clear'):
self._epd.Clear(color)
elif hasattr(self._epd, 'clear'):
self._epd.clear(color)
else:
raise AttributeError(f"EPD object has neither 'Clear' nor 'clear' method")
def Clear(self, color: Optional[int] = None) -> None:
"""Clear the display (uppercase for backward compatibility)"""
self.clear(color)
def sleep(self) -> None:
"""Put display to sleep"""
self._epd.sleep()
def getbuffer(self, image: Image.Image):
"""Convert image to display buffer"""
return self._epd.getbuffer(image)
@property
def width(self) -> int:
return self._epd.width
@property
def height(self) -> int:
return self._epd.height
@property
def WHITE(self) -> int:
return self._epd.WHITE
@property
def BLACK(self) -> int:
return self._epd.BLACK
@property
def RED(self) -> int:
return self._epd.RED
@property
def YELLOW(self) -> int:
return self._epd.YELLOW
@property
def native_orientation(self) -> str:
return "portrait"
class EPD13in3EAdapter(EPDAdapter):
"""Adapter for epd13in3E display"""
def __init__(self):
# Import the actual display module - 13.3" has different structure
try:
# First try the separate program structure (13.3" specific)
import sys
import os
# Add the 13.3" library path to sys.path
script_dir = os.path.dirname(os.path.abspath(__file__))
epd13_path = os.path.join(script_dir, 'e-Paper', 'E-paper_Separate_Program',
'13.3inch_e-Paper_E', 'RaspberryPi', 'python', 'lib')
logger.info(f"13.3\" library path in principle: {epd13_path}")
if os.path.exists(epd13_path):
sys.path.insert(0, epd13_path)
import epd13in3E
self._epd = epd13in3E.EPD()
logger.info(f"Loaded 13.3\" display from separate program path: {epd13_path}")
else:
# Fallback to waveshare_epd structure
from waveshare_epd import epd13in3E
self._epd = epd13in3E.EPD()
logger.info("Loaded 13.3\" display from waveshare_epd")
except ImportError as e:
logger.error(f"epd13in3E module not found. Error: {e}")
logger.error("For 13.3\" display, ensure the library is installed from:")
logger.error("e-Paper/E-paper_Separate_Program/13.3inch_e-Paper_E/RaspberryPi/python/lib/")
raise
@property
def display_type(self) -> str:
return "epd13in3E"
def init(self) -> int:
"""Initialize the display"""
return self._epd.Init() # Note: capital I
def display(self, image) -> None:
"""Display an image"""
self._epd.display(image)
def clear(self, color: Optional[int] = None) -> None:
"""Clear the display"""
if color is None:
color = 0x11 # Default for 13in3E
# Try both Clear and clear methods for compatibility
if hasattr(self._epd, 'Clear'):
self._epd.Clear(color)
elif hasattr(self._epd, 'clear'):
self._epd.clear(color)
else:
raise AttributeError(f"EPD object has neither 'Clear' nor 'clear' method")
def Clear(self, color: Optional[int] = None) -> None:
"""Clear the display (uppercase for backward compatibility)"""
self.clear(color)
def sleep(self) -> None:
"""Put display to sleep"""
self._epd.sleep()
def getbuffer(self, image: Image.Image):
"""Convert image to display buffer"""
return self._epd.getbuffer(image)
@property
def width(self) -> int:
return self._epd.width
@property
def height(self) -> int:
return self._epd.height
@property
def WHITE(self) -> int:
return self._epd.WHITE
@property
def BLACK(self) -> int:
return self._epd.BLACK
@property
def RED(self) -> int:
return self._epd.RED
@property
def YELLOW(self) -> int:
return self._epd.YELLOW
@property
def native_orientation(self) -> str:
return "portrait"
class EPD7in3eAdapter(EPDAdapter):
"""Adapter for epd7in3e display"""
def __init__(self):
# Import the actual display module
try:
from waveshare_epd import epd7in3e
self._epd = epd7in3e.EPD()
except ImportError as e:
try:
import sys
logger.error(
"epd7in3e module not found. sys.executable=%s, sys.path sample=%s, error=%s",
sys.executable,
sys.path[:5],
repr(e)
)
except Exception:
logger.error("epd7in3e module not found. Make sure waveshare_epd is in your path.")
raise
@property
def display_type(self) -> str:
return "epd7in3e"
def init(self) -> int:
"""Initialize the display"""
return self._epd.init()
def display(self, image) -> None:
"""Display an image"""
self._epd.display(image)
def clear(self, color: Optional[int] = None) -> None:
"""Clear the display"""
if color is None:
color = 0x11 # Default for 7in3e
# Try both Clear and clear methods for compatibility
if hasattr(self._epd, 'Clear'):
self._epd.Clear(color)
elif hasattr(self._epd, 'clear'):
self._epd.clear(color)
else:
raise AttributeError(f"EPD object has neither 'Clear' nor 'clear' method")
def Clear(self, color: Optional[int] = None) -> None:
"""Clear the display (uppercase for backward compatibility)"""
self.clear(color)
def sleep(self) -> None:
"""Put display to sleep"""
self._epd.sleep()
def getbuffer(self, image: Image.Image):
"""Convert image to display buffer"""
return self._epd.getbuffer(image)
@property
def width(self) -> int:
return self._epd.width
@property
def height(self) -> int:
return self._epd.height
@property
def WHITE(self) -> int:
return self._epd.WHITE
@property
def BLACK(self) -> int:
return self._epd.BLACK
@property
def RED(self) -> int:
return self._epd.RED
@property
def YELLOW(self) -> int:
return self._epd.YELLOW
@property
def native_orientation(self) -> str:
# we say this even though it's portrait, because in the library the width and height are swapped
return "landscape"
class UnifiedEPD:
"""Factory class for creating unified EPD instances"""
# Display configuration database
DISPLAY_CONFIGS = {
"epd2in15g": {
"class": EPD2in15gAdapter,
"name": "2.15\" Grayscale Display",
"resolution": (296, 120),
"colors": "4-color grayscale",
"native_orientation": "portrait"
},
"epd13in3E": {
"class": EPD13in3EAdapter,
"name": "13.3\" Color Display",
"resolution": (1600, 1200),
"colors": "7-color",
"native_orientation": "portrait"
},
"epd7in3e": {
"class": EPD7in3eAdapter,
"name": "7.3\" Color Display",
"resolution": (800, 480),
"colors": "7-color",
"native_orientation": "landscape"
}
}
@classmethod
def create_display(cls, display_type: str) -> EPDAdapter:
"""
Create a unified EPD instance based on display type
Args:
display_type: Type of display ("epd2in15g" or "epd13in3E")
Returns:
EPDAdapter instance
Raises:
ValueError: If display type is not supported
"""
if display_type not in cls.DISPLAY_CONFIGS:
supported = ", ".join(cls.DISPLAY_CONFIGS.keys())
raise ValueError(f"Unsupported display type: {display_type}. Supported types: {supported}")
config = cls.DISPLAY_CONFIGS[display_type]
adapter_class = config["class"]
width, height = config['resolution']
logger.info(f"Creating {config['name']} ({width}x{height}, {config['colors']})")
return adapter_class()
@classmethod
def list_supported_displays(cls) -> dict:
"""List all supported display types and their configurations"""
return cls.DISPLAY_CONFIGS.copy()
@classmethod
def get_display_info(cls, display_type: str) -> Optional[dict]:
"""Get information about a specific display type"""
return cls.DISPLAY_CONFIGS.get(display_type)
@classmethod
def get_display_resolution(cls, display_type: str) -> Optional[tuple]:
"""Get resolution as (width, height) tuple for a display type"""
config = cls.DISPLAY_CONFIGS.get(display_type)
return config['resolution'] if config else None
@classmethod
def get_display_dimensions(cls, display_type: str) -> Optional[tuple]:
"""Get display dimensions as (width, height) tuple (alias for get_display_resolution)"""
return cls.get_display_resolution(display_type)
@classmethod
def get_display_pixel_count(cls, display_type: str) -> Optional[int]:
"""Get total pixel count (width * height) for a display type"""
config = cls.DISPLAY_CONFIGS.get(display_type)
if config:
width, height = config['resolution']
return width * height
return None
@classmethod
def get_landscape_dimensions(cls, display_type: str) -> Optional[tuple]:
"""Get landscape dimensions (width, height) for a display type"""
config = cls.DISPLAY_CONFIGS.get(display_type)
if config:
width, height = config['resolution']
native_orientation = config.get('native_orientation', 'landscape')
if native_orientation == 'landscape':
return (width, height) # Already landscape
else:
return (height, width) # Swap for portrait-native displays
return None
@classmethod
def get_portrait_dimensions(cls, display_type: str) -> Optional[tuple]:
"""Get portrait dimensions (width, height) for a display type"""
config = cls.DISPLAY_CONFIGS.get(display_type)
if config:
width, height = config['resolution']
native_orientation = config.get('native_orientation', 'landscape')
if native_orientation == 'portrait':
return (width, height) # Already portrait
else:
return (height, width) # Swap for landscape-native displays
return None
@classmethod
def get_native_orientation(cls, display_type: str) -> Optional[str]:
"""Get native orientation for a display type"""
config = cls.DISPLAY_CONFIGS.get(display_type)
return config.get('native_orientation') if config else None
# Configuration helper
class EPDConfig:
"""Configuration management for EPD displays"""
@staticmethod
def load_display_config() -> str:
"""
Load display type from configuration file
Returns:
Display type string
"""
# Try multiple possible locations for config file
script_dir = os.path.dirname(os.path.abspath(__file__))
home_dir = os.path.expanduser('~')
repo_root = script_dir # current file resides in repo root
config_locations = [
os.path.join(repo_root, '.epd_config.json'), # Repo root (~/RpiEinky/.epd_config.json)
os.path.join(home_dir, 'RpiEinky', '.epd_config.json'), # Explicit home repo path
]
config_file = None
logger.info(f"EPDConfig: searching display config in: {config_locations}")
for location in config_locations:
if os.path.exists(location):
config_file = location
logger.info(f"EPDConfig: found config file: {config_file}")
# Log a small preview of the file for diagnostics
try:
with open(config_file, 'r') as f:
preview = f.read(200)
logger.info(f"EPDConfig: config preview: {preview}")
except Exception as e:
logger.warning(f"EPDConfig: failed reading config preview: {e}")
break
try:
if config_file:
import json
with open(config_file, 'r') as f:
config = json.load(f)
display_type = config.get('display_type', 'epd2in15g')
logger.info(f"Loaded display config: {display_type} from {config_file}")
return display_type
except Exception as e:
logger.warning(f"Could not load display config: {e}")
# Default to 2.15" display
logger.info("EPDConfig: using default display type: epd2in15g")
return 'epd2in15g'
@staticmethod
def save_display_config(display_type: str) -> None:
"""
Save display type to configuration file
Args:
display_type: Type of display to save
"""
# Save to same directory as script by default
script_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(script_dir, '.epd_config.json')
try:
import json
config = {'display_type': display_type}
# Ensure directory exists
os.makedirs(os.path.dirname(config_file), exist_ok=True)
with open(config_file, 'w') as f:
json.dump(config, f, indent=2)
logger.info(f"Saved display config: {display_type}")
except Exception as e:
logger.error(f"Could not save display config: {e}")
# Convenience function for easy usage
def create_epd(display_type: Optional[str] = None) -> EPDAdapter:
"""
Create an EPD instance with automatic configuration loading
Args:
display_type: Optional display type. If None, loads from config file
Returns:
EPDAdapter instance
"""
if display_type is None:
display_type = EPDConfig.load_display_config()
return UnifiedEPD.create_display(display_type)
# Example usage and testing
if __name__ == "__main__":
# Test the unified interface
logging.basicConfig(level=logging.INFO)
print("Available displays:")
for display_type, config in UnifiedEPD.list_supported_displays().items():
width, height = config['resolution']
pixel_count = width * height
print(f" {display_type}: {config['name']} ({width}x{height}, {pixel_count:,} pixels)")
print("\nTesting display creation...")
try:
# Test 2.15" display
print("Testing epd2in15g...")
epd1 = UnifiedEPD.create_display("epd2in15g")
print(f" Created: {epd1.width}x{epd1.height}")
# Test 13.3" display
print("Testing epd13in3E...")
epd2 = UnifiedEPD.create_display("epd13in3E")
print(f" Created: {epd2.width}x{epd2.height}")
# Test 7.3" display
print("Testing epd7in3e...")
epd3 = UnifiedEPD.create_display("epd7in3e")
print(f" Created: {epd3.width}x{epd3.height}")
print("All tests passed!")
# Test utility methods
print("\nTesting utility methods...")
for display_type in ["epd2in15g", "epd13in3E", "epd7in3e"]:
resolution = UnifiedEPD.get_display_resolution(display_type)
pixel_count = UnifiedEPD.get_display_pixel_count(display_type)
print(f" {display_type}: {resolution} = {pixel_count:,} pixels")
except Exception as e:
print(f"Test failed: {e}")
print("This is expected if the display modules are not available in the current environment.")