Browse Source

Squashed 'libs/Adafruit-PiTFT-Helper/' content from commit 7d07f55

git-subtree-dir: libs/Adafruit-PiTFT-Helper
git-subtree-split: 7d07f55ed1
Brennen Bearnes 3 years ago
commit
78958bacb8
5 changed files with 875 additions and 0 deletions
  1. 22
    0
      LICENSE
  2. 76
    0
      README.md
  3. 74
    0
      adafruit-pitft-chroot-install
  4. 356
    0
      adafruit-pitft-helper
  5. 347
    0
      adafruit-pitft-touch-cal

+ 22
- 0
LICENSE View File

@@ -0,0 +1,22 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2015 Adafruit Industries
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.
22
+

+ 76
- 0
README.md View File

@@ -0,0 +1,76 @@
1
+# Adafruit-PiTFT-Helper
2
+
3
+A script for configuring Adafruit's PiTFT displays on a Raspberry Pi.
4
+
5
+**This is in a beta state and may contain bugs.**
6
+
7
+## PiTFT Documentation
8
+
9
+- [PiTFT - Assembled 320x240 2.8" TFT+Touchscreen for Raspberry Pi](https://www.adafruit.com/product/1601)
10
+- [PiTFT - Assembled 480x320 3.5" TFT+Touchscreen for Raspberry Pi](https://www.adafruit.com/product/2097)
11
+
12
+## Getting Started: Kernel & Helper Script Installation
13
+
14
+First, add [Adafruit's Occidentalis package repository][o] to your system.
15
+Occidentalis is a growing collection of useful packages and configuration
16
+defaults for installation on Raspbian systems.
17
+
18
+If you want to bootstrap the full version of Occidentalis on a fresh, unused Pi
19
+from another computer, we offer an easy graphical tool called the [Pi Finder][p].
20
+Once bootstrapped, you can open a terminal on your Pi and run:
21
+
22
+```sh
23
+sudo apt-get install adafruit-pitft-helper
24
+```
25
+
26
+...which will install both the helper script and a custom kernel with PiTFT
27
+support.  If you _just_ want to install the kernel and helper without pulling
28
+down any other extra packages, you can run the following from the command line
29
+of a working Pi:
30
+
31
+```sh
32
+curl -SLs https://apt.adafruit.com/add | sudo bash
33
+sudo apt-get install adafruit-pitft-helper
34
+```
35
+
36
+This can take a surprisingly long time to finish, especially if you're using a
37
+slower SD card, so be patient.
38
+
39
+**Please be careful!** Installing a new kernel always has the potential to
40
+leave your Raspberry Pi unbootable.  You should make a backup copy of your SD
41
+card before trying this, or (even better!) start with a fresh card.
42
+
43
+## Using adafruit-pitft-helper
44
+
45
+`adafruit-pitft-helper` must be run with root privileges, and takes a parameter
46
+specifying the type of PiTFT to configure.  Invoke it like so:
47
+
48
+```sh
49
+sudo adafruit-pitft-helper -t 28r
50
+```
51
+
52
+For a full list of available options, check the help:
53
+
54
+```sh
55
+adafruit-pitft-helper -h
56
+```
57
+
58
+## Installing PiTFT support in a Raspbian image file (experimental!)
59
+
60
+This repository includes a [small wrapper script][c] for installing the custom
61
+kernel and PiTFT configuration in a Rasbpian image file.  In order to use it,
62
+you can download and unzip a recent Raspbian image on a Raspberry Pi, then do
63
+something like the following in a terminal:
64
+
65
+```sh
66
+curl -SLs https://apt.adafruit.com/add | sudo bash
67
+sudo apt-get install adafruit-pitft-helper
68
+sudo adafruit-pitft-chroot-install -t 28r -i ~/2015-02-16-raspbian-wheezy.img
69
+```
70
+
71
+...where `-t` specifies the type of PiTFT just like the same option to
72
+`adafruit-pitft-helper`, and `-i` specifies the path to an image file.
73
+
74
+[o]: https://github.com/adafruit/Adafruit-Occidentalis
75
+[p]: https://github.com/adafruit/Adafruit-Pi-Finder
76
+[c]: https://github.com/adafruit/Adafruit-PiTFT-Helper/blob/master/adafruit-pitft-chroot-install

+ 74
- 0
adafruit-pitft-chroot-install View File

@@ -0,0 +1,74 @@
1
+#!/usr/bin/env bash
2
+
3
+set -e
4
+
5
+function print_help() {
6
+    echo "Usage: $0 -t [pitfttype]"
7
+    echo "    -h            Print this help"
8
+    echo "    -t [type]     Specify the type of PiTFT: '28r' (PID 1601) or '28c' (PID 1983) or '35r' or '22'"
9
+    echo
10
+    echo "You must specify a type of display."
11
+    exit 1
12
+}
13
+
14
+args=$(getopt -uo 'ht:i:' -- $*)
15
+[ $? != 0 ] && print_help
16
+set -- $args
17
+
18
+for i
19
+do
20
+      case "$i"
21
+      in
22
+            -h)
23
+                    print_help
24
+                    ;;
25
+            -t)
26
+                    pitfttype="$2"
27
+                    echo "Type = ${2}"
28
+                    shift
29
+                    shift
30
+                    ;;
31
+            -i)
32
+                    target_image="$2"
33
+                    echo "Image = ${2}"
34
+                    shift
35
+                    shift
36
+                    ;;
37
+      esac
38
+done
39
+
40
+if [[ $EUID -ne 0 ]]; then
41
+    echo "$0 must be run as root. try: sudo $0"
42
+    exit 1
43
+fi
44
+
45
+if  [ "${pitfttype}" != "28r" ] && [ "${pitfttype}" != "28c" ] && [ "${pitfttype}" != "35r" ] && [ "${pitfttype}" != "22" ]
46
+then
47
+        echo "Type must be '28r' (2.8\" resistive, PID 1601) or '28c' (2.8\" capacitive, PID 1983)  or '35r' (3.5\" Resistive) or '22' (2.2\" no touch)"
48
+        print_help
49
+fi
50
+
51
+target_mnt="/media/raspbian-target"
52
+
53
+echo "Mounting $target_image on $target_mnt"
54
+kpartx -av $target_image
55
+mkdir -p $target_mnt
56
+mount /dev/mapper/loop0p2 $target_mnt
57
+mount /dev/mapper/loop0p1 $target_mnt/boot
58
+
59
+echo "Adding apt.adafruit.com to sources.list"
60
+curl -SLs https://apt.adafruit.com/add | chroot $target_mnt /bin/bash
61
+
62
+echo "Installing adafruit-pitft-helper and dependencies"
63
+chroot $target_mnt sudo apt-get install adafruit-pitft-helper
64
+
65
+echo "Running adafruit-pitft-helper"
66
+chroot $target_mnt sudo adafruit-pitft-helper -t $pitfttype
67
+
68
+echo "Dropping you into Bash"
69
+chroot $target_mnt sudo /bin/bash
70
+
71
+echo "Unmounting $target_image"
72
+umount $target_mnt/boot
73
+umount $target_mnt
74
+kpartx -d $target_image

+ 356
- 0
adafruit-pitft-helper View File

@@ -0,0 +1,356 @@
1
+#!/usr/bin/env bash
2
+
3
+set -e
4
+
5
+function print_version() {
6
+    echo "Adafruit PiTFT Helper v0.5.0"
7
+    exit 1
8
+}
9
+
10
+function print_help() {
11
+    echo "Usage: $0 -t [pitfttype]"
12
+    echo "    -h            Print this help"
13
+    echo "    -v            Print version information"
14
+    echo "    -u [homedir]  Specify path of primary user's home directory (defaults to /home/pi)"
15
+    echo "    -t [type]     Specify the type of PiTFT: '28r' (PID 1601) or '28c' (PID 1983) or '35r' or '22'"
16
+    echo
17
+    echo "You must specify a type of display."
18
+    exit 1
19
+}
20
+
21
+group=ADAFRUIT
22
+function info() {
23
+    system="$1"
24
+    group="${system}"
25
+    shift
26
+    FG="1;32m"
27
+    BG="40m"
28
+    echo -e "[\033[${FG}\033[${BG}${system}\033[0m] $*"
29
+}
30
+
31
+function bail() {
32
+    FG="1;31m"
33
+    BG="40m"
34
+    echo -en "[\033[${FG}\033[${BG}${group}\033[0m] "
35
+    if [ -z "$1" ]; then
36
+        echo "Exiting due to error"
37
+    else
38
+        echo "Exiting due to error: $*"
39
+    fi
40
+    exit 1
41
+}
42
+
43
+function ask() {
44
+    # http://djm.me/ask
45
+    while true; do
46
+
47
+        if [ "${2:-}" = "Y" ]; then
48
+            prompt="Y/n"
49
+            default=Y
50
+        elif [ "${2:-}" = "N" ]; then
51
+            prompt="y/N"
52
+            default=N
53
+        else
54
+            prompt="y/n"
55
+            default=
56
+        fi
57
+
58
+        # Ask the question
59
+        read -p "$1 [$prompt] " REPLY
60
+
61
+        # Default?
62
+        if [ -z "$REPLY" ]; then
63
+            REPLY=$default
64
+        fi
65
+
66
+        # Check if the reply is valid
67
+        case "$REPLY" in
68
+            Y*|y*) return 0 ;;
69
+            N*|n*) return 1 ;;
70
+        esac
71
+    done
72
+}
73
+
74
+# update /boot/config.txt with appropriate values
75
+function update_configtxt() {
76
+
77
+    if grep -q "adafruit-pitft-helper" "/boot/config.txt"; then
78
+        echo "Already have an adafruit-pitft-helper section in /boot/config.txt."
79
+        echo "Adding new section, but please run:"
80
+        echo "sudo nano /boot/config.txt"
81
+        echo "...and remove any duplicate sections."
82
+    fi
83
+
84
+    if [ "${pitfttype}" == "22" ]; then
85
+        # formerly: options fbtft_device name=adafruit22a gpios=dc:25 rotate=270 frequency=32000000
86
+        overlay="dtoverlay=pitft22,rotate=270,speed=32000000,fps=20"
87
+    fi
88
+
89
+    if [ "${pitfttype}" == "28r" ]; then
90
+        overlay="dtoverlay=pitft28r,rotate=90,speed=32000000,fps=20"
91
+    fi
92
+
93
+    if [ "${pitfttype}" == "28c" ]; then
94
+        overlay="dtoverlay=pitft28c,rotate=90,speed=32000000,fps=20"
95
+    fi
96
+
97
+    if [ "${pitfttype}" == "35r" ]; then
98
+        overlay="dtoverlay=pitft35r,rotate=90,speed=42000000,fps=20"
99
+    fi
100
+
101
+    date=`date`
102
+
103
+    cat >> /boot/config.txt <<EOF
104
+
105
+# --- added by adafruit-pitft-helper $date ---
106
+[pi1]
107
+device_tree=bcm2708-rpi-b-plus.dtb
108
+[pi2]
109
+device_tree=bcm2709-rpi-2-b.dtb
110
+[all]
111
+dtparam=spi=on
112
+dtparam=i2c1=on
113
+dtparam=i2c_arm=on
114
+$overlay
115
+# --- end adafruit-pitft-helper $date ---
116
+EOF
117
+
118
+}
119
+
120
+# currently for '90' rotation only
121
+function update_xorg() {
122
+    mkdir -p /etc/X11/xorg.conf.d
123
+
124
+    if [ "${pitfttype}" == "28r" ]; then
125
+        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
126
+Section "InputClass"
127
+        Identifier      "calibration"
128
+        MatchProduct    "stmpe-ts"
129
+        Option  "Calibration"   "3800 200 200 3800"
130
+        Option  "SwapAxes"      "1"
131
+EndSection
132
+EOF
133
+    fi
134
+
135
+    if [ "${pitfttype}" == "35r" ]; then
136
+        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
137
+Section "InputClass"
138
+        Identifier      "calibration"
139
+        MatchProduct    "stmpe-ts"
140
+        Option  "Calibration"   "3800 120 200 3900"
141
+        Option  "SwapAxes"      "1"
142
+EndSection
143
+EOF
144
+    fi
145
+
146
+    if [ "${pitfttype}" == "28c" ]; then
147
+        cat > /etc/X11/xorg.conf.d/99-calibration.conf <<EOF
148
+Section "InputClass"
149
+         Identifier "captouch"
150
+         MatchProduct "ft6x06_ts"
151
+         Option "SwapAxes" "1"
152
+         Option "InvertY" "1"
153
+         Option "Calibration" "0 320 0 240"
154
+EndSection
155
+EOF
156
+    fi
157
+}
158
+
159
+function update_x11profile() {
160
+    fbturbo_path="/usr/share/X11/xorg.conf.d/99-fbturbo.conf"
161
+    if [ -e $fbturbo_path ]; then
162
+        echo "Moving ${fbturbo_path} to ${target_homedir}"
163
+        mv "$fbturbo_path" "$target_homedir"
164
+    fi
165
+
166
+    if grep -xq "export FRAMEBUFFER=/dev/fb1" "${target_homedir}/.profile"; then
167
+        echo "Already had 'export FRAMEBUFFER=/dev/fb1'"
168
+    else
169
+        echo "Adding 'export FRAMEBUFFER=/dev/fb1'"
170
+        cat >> "${target_homedir}.profile" <<EOF
171
+export FRAMEBUFFER=/dev/fb1
172
+EOF
173
+    fi
174
+}
175
+
176
+# currently for '90' rotation only
177
+function update_pointercal() {
178
+    if [ "${pitfttype}" == "28r" ]; then
179
+        cat > /etc/pointercal <<EOF
180
+-30 -5902 22077792 4360 -105 -1038814 65536
181
+EOF
182
+    fi
183
+
184
+    if [ "${pitfttype}" == "35r" ]; then
185
+        cat > /etc/pointercal <<EOF
186
+8 -8432 32432138 5699 -112 -965922 65536
187
+EOF
188
+    fi
189
+
190
+    if [ "${pitfttype}" == "28c" ]; then
191
+        cat > /etc/pointercal <<EOF
192
+320 65536 0 -65536 0 15728640 65536
193
+EOF
194
+    fi
195
+}
196
+
197
+function update_udev() {
198
+    if [ "${pitfttype}" == "28r" ] || [ "${pitfttype}" == "35r" ]; then
199
+        cat > /etc/udev/rules.d/95-stmpe.rules <<EOF
200
+        SUBSYSTEM=="input", ATTRS{name}=="stmpe-ts", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen"
201
+EOF
202
+    fi
203
+
204
+    if [ "${pitfttype}" == "28c" ]; then
205
+        cat > /etc/udev/rules.d/95-ft6206.rules <<EOF
206
+        SUBSYSTEM=="input", ATTRS{name}=="ft6x06_ts", ENV{DEVNAME}=="*event*", SYMLINK+="input/touchscreen" 
207
+EOF
208
+    fi
209
+}
210
+
211
+function install_console() {
212
+    if ! grep -q 'fbcon=map:10 fbcon=font:VGA8x8' /boot/cmdline.txt; then
213
+        echo "Updating /boot/cmdline.txt"
214
+        sed -i 's/rootwait/rootwait fbcon=map:10 fbcon=font:VGA8x8/g' "/boot/cmdline.txt"
215
+    else
216
+        echo "/boot/cmdline.txt already updated"
217
+    fi
218
+    sed -i 's/BLANK_TIME=.*/BLANK_TIME=0/g' "/etc/kbd/config"
219
+}
220
+
221
+function uninstall_console() {
222
+    sed -i 's/rootwait fbcon=map:10 fbcon=font:VGA8x8/rootwait/g' "/boot/cmdline.txt"
223
+    sed -i 's/BLANK_TIME=0/BLANK_TIME=10/g' "/etc/kbd/config"
224
+    echo "Screen blanking time reset to 10 minutes"
225
+}
226
+
227
+function update_etcmodules() {
228
+    if [ "${pitfttype}" == "28c" ]; then
229
+        ts_module="ft6x06_ts"
230
+    elif [ "${pitfttype}" == "28r" ] || [ "${pitfttype}" == "35r" ]; then
231
+        ts_module="stmpe_ts"
232
+    else
233
+        return 0
234
+    fi
235
+
236
+    if grep -xq "$ts_module" "/etc/modules"; then
237
+        echo "Already had $ts_module"
238
+    else
239
+        echo "Adding $ts_module"
240
+        echo "$ts_module" >> /etc/modules
241
+    fi
242
+}
243
+
244
+function install_onoffbutton() {
245
+    echo "Adding rpi_power_switch to /etc/modules"
246
+    if grep -xq "rpi_power_switch" "${chr}/etc/modules"; then
247
+        echo "Already had rpi_power_switch"
248
+    else
249
+        echo "Adding rpi_power_switch"
250
+        cat >> /etc/modules <<EOF
251
+rpi_power_switch
252
+EOF
253
+    fi
254
+
255
+    echo "Adding rpi_power_switch config to /etc/modprobe.d/adafruit.conf"
256
+    if grep -xq "options rpi_power_switch gpio_pin=23 mode=0" "${chr}/etc/modprobe.d/adafruit.conf"; then
257
+        echo "Already had rpi_power_switch config"
258
+    else
259
+        echo "Adding rpi_power_switch"
260
+        cat >> /etc/modprobe.d/adafruit.conf <<EOF
261
+options rpi_power_switch gpio_pin=23 mode=0
262
+EOF
263
+    fi
264
+}
265
+
266
+# MAIN
267
+
268
+target_homedir="/home/pi"
269
+
270
+args=$(getopt -uo 'hvri:t:o:b:u:' -- $*)
271
+[ $? != 0 ] && print_help
272
+set -- $args
273
+
274
+for i
275
+do
276
+    case "$i"
277
+    in
278
+        -h)
279
+            print_help
280
+            ;;
281
+        -v)
282
+            print_version
283
+            ;;
284
+        -u)
285
+            target_homedir="$2"
286
+            echo "Homedir = ${2}"
287
+            shift
288
+            shift
289
+            ;;
290
+        -t)
291
+            pitfttype="$2"
292
+            echo "Type = ${2}"
293
+            shift
294
+            shift
295
+            ;;
296
+    esac
297
+done
298
+
299
+if [[ $EUID -ne 0 ]]; then
300
+    bail "adafruit-pitft-helper must be run as root. try: sudo adadfruit-pitft-helper"
301
+fi
302
+
303
+if grep -q boot /proc/mounts; then
304
+    echo "/boot is mounted"
305
+else
306
+    bail "/boot must be mounted. try: sudo mount /dev/mmcblk0p1 /boot"
307
+fi
308
+
309
+if [[ ! -e "$target_homedir" || ! -d "$target_homedir" ]]; then
310
+    bail "$target_homedir must be an existing directory (use -u /home/foo to specify)"
311
+fi
312
+
313
+if [ "${pitfttype}" != "28r" ] && [ "${pitfttype}" != "28c" ] && [ "${pitfttype}" != "35r" ] && [ "${pitfttype}" != "22" ]; then
314
+    echo "Type must be one of:"
315
+    echo "  '28r' (2.8\" resistive, PID 1601)"
316
+    echo "  '28c' (2.8\" capacitive, PID 1983)"
317
+    echo "  '35r' (3.5\" Resistive)"
318
+    echo "  '22'  (2.2\" no touch)"
319
+    echo
320
+    print_help
321
+fi
322
+
323
+info PITFT "Updating X11 default calibration..."
324
+update_xorg || bail "Unable to update /etc/X11/xorg.conf.d/99-calibration.conf"
325
+
326
+info PITFT "Updating X11 setup tweaks..."
327
+update_x11profile || bail "Unable to update X11 setup"
328
+
329
+info PITFT "Updating TSLib default calibration..."
330
+update_pointercal || bail "Unable to update /etc/pointercal"
331
+
332
+info PITFT "Updating SysFS rules for Touchscreen..."
333
+update_udev || bail "Unable to update /etc/udev/rules.d"
334
+
335
+# ask for console access
336
+if ask "Would you like the console to appear on the PiTFT display?"; then
337
+    info PITFT "Updating console to PiTFT..."
338
+    install_console || bail "Unable to configure console"
339
+else
340
+    info PITFT "Making sure console doesn't use PiTFT"
341
+    uninstall_console || bail "Unable to configure console"
342
+fi
343
+
344
+info PITFT "Updating /etc/modules..."
345
+update_etcmodules || bail "Unable to update /etc/modules"
346
+
347
+if [ "${pitfttype}" != "35r" ]; then
348
+    # ask for 'on/off' button
349
+    if ask "Would you like GPIO #23 to act as a on/off button?"; then
350
+        info PITFT "Adding GPIO #23 on/off to PiTFT..."
351
+        install_onoffbutton || bail "Unable to add on/off button"
352
+    fi
353
+fi
354
+
355
+info PITFT "Updating /boot/config.txt..."
356
+update_configtxt || bail "Unable to update /boot/config.txt"

+ 347
- 0
adafruit-pitft-touch-cal View File

@@ -0,0 +1,347 @@
1
+#!/usr/bin/python
2
+
3
+# Script to automatically update Raspberry Pi PiTFT touchscreen calibration
4
+# based on the current rotation of the screen.
5
+
6
+# Copyright (c) 2014 Adafruit Industries
7
+# Author: Tony DiCola
8
+
9
+# Permission is hereby granted, free of charge, to any person obtaining a copy
10
+# of this software and associated documentation files (the "Software"), to deal
11
+# in the Software without restriction, including without limitation the rights
12
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+# copies of the Software, and to permit persons to whom the Software is
14
+# furnished to do so, subject to the following conditions:
15
+
16
+# The above copyright notice and this permission notice shall be included in all
17
+# copies or substantial portions of the Software.
18
+
19
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+# SOFTWARE.
26
+import argparse
27
+import os
28
+import subprocess
29
+import sys
30
+
31
+
32
+# Calibration configuration default values.
33
+CAL_CONFIG = {}
34
+
35
+# 2.8" resisitive touch calibration values.
36
+CAL_CONFIG['28r'] = {}
37
+CAL_CONFIG['28r']['pointercal'] = {}
38
+CAL_CONFIG['28r']['pointercal']['0']   = '4315 -49 -889068 18 5873 -1043172 6553636'
39
+CAL_CONFIG['28r']['pointercal']['90']  = '-30 -5902 22077792 4360 -105 -1038814 65536'
40
+CAL_CONFIG['28r']['pointercal']['180'] = '-4228 73 16353030 -60 -5888 22004262 65536'
41
+CAL_CONFIG['28r']['pointercal']['270'] = '-69 5859 -829540 -4306 3 16564590 6553636'
42
+CAL_CONFIG['28r']['xorg'] = {}
43
+CAL_CONFIG['28r']['xorg']['0'] = """
44
+Section "InputClass"
45
+    Identifier      "calibration"
46
+    MatchProduct    "stmpe-ts"
47
+    Option  "Calibration"   "252 3861 180 3745"
48
+    Option  "SwapAxes"      "0"
49
+EndSection
50
+"""
51
+CAL_CONFIG['28r']['xorg']['90'] = """
52
+Section "InputClass"
53
+    Identifier      "calibration"
54
+    MatchProduct    "stmpe-ts"
55
+    Option  "Calibration"   "3807 174 244 3872"
56
+    Option  "SwapAxes"      "1"
57
+EndSection
58
+"""
59
+CAL_CONFIG['28r']['xorg']['180'] = """
60
+Section "InputClass"
61
+    Identifier      "calibration"
62
+    MatchProduct    "stmpe-ts"
63
+    Option  "Calibration"   "3868 264 3789 237"
64
+    Option "SwapAxes"      "0"
65
+EndSection
66
+"""
67
+CAL_CONFIG['28r']['xorg']['270'] = """
68
+Section "InputClass"
69
+    Identifier      "calibration"
70
+    MatchProduct    "stmpe-ts"
71
+    Option  "Calibration"   "287 3739 3817 207"
72
+    Option  "SwapAxes"      "1"
73
+EndSection
74
+"""
75
+
76
+# 2.8" capacitive touch calibration values.
77
+CAL_CONFIG['28c'] = {}
78
+CAL_CONFIG['28c']['pointercal'] = {}
79
+CAL_CONFIG['28c']['pointercal']['0']   = '-65536 0 15728640 -320 -65536 20971520 65536'
80
+CAL_CONFIG['28c']['pointercal']['90']  = '320 65536 0 -65536 0 15728640 65536'
81
+CAL_CONFIG['28c']['pointercal']['180'] = '65536 0 -655360 0 65536 -655360 65536'
82
+CAL_CONFIG['28c']['pointercal']['270'] = '0 -65536 20971520 65536 0 -65536 65536'
83
+CAL_CONFIG['28c']['xorg'] = {}
84
+CAL_CONFIG['28c']['xorg']['0'] = """
85
+Section "InputClass"
86
+    Identifier "captouch"
87
+    MatchProduct "ft6x06_ts"
88
+    Option "SwapAxes" "0"
89
+    Option "InvertY" "1"
90
+    Option "InvertX" "1"
91
+    Option "Calibration" "0 240 0 320"
92
+EndSection
93
+"""
94
+CAL_CONFIG['28c']['xorg']['90'] = """
95
+Section "InputClass"
96
+    Identifier "captouch"
97
+    MatchProduct "ft6x06_ts"
98
+    Option "SwapAxes" "1"
99
+    Option "InvertY" "1"
100
+    Option "Calibration" "0 320 0 240"
101
+EndSection
102
+"""
103
+CAL_CONFIG['28c']['xorg']['180'] = """
104
+Section "InputClass"
105
+    Identifier "captouch"
106
+    MatchProduct "ft6x06_ts"
107
+    Option "SwapAxes" "0"
108
+    Option "InvertY" "0"
109
+    Option "Calibration" "0 240 0 320"
110
+EndSection
111
+"""
112
+CAL_CONFIG['28c']['xorg']['270'] = """
113
+Section "InputClass"
114
+    Identifier "captouch"
115
+    MatchProduct "ft6x06_ts"
116
+    Option "SwapAxes" "1"
117
+    Option "InvertY" "0"
118
+    Option "InvertX" "1"
119
+    Option "Calibration" "0 320 0 240"
120
+EndSection
121
+"""
122
+
123
+# 3.5" resisitive touch calibration values.
124
+CAL_CONFIG['35r'] = {}
125
+CAL_CONFIG['35r']['pointercal'] = {}
126
+CAL_CONFIG['35r']['pointercal']['0']   = '5835 56 -1810410 22 8426 -1062652 65536'
127
+CAL_CONFIG['35r']['pointercal']['90']  = '-16 -8501 33169914 5735 45 -1425640 65536'
128
+CAL_CONFIG['35r']['pointercal']['180'] = '-5853 8 22390770 -59 -8353 32810368 65536'
129
+CAL_CONFIG['35r']['pointercal']['270'] = '-95 8395 -908648 -5849 164 22156762 65536'
130
+CAL_CONFIG['35r']['xorg'] = {}
131
+CAL_CONFIG['35r']['xorg']['0'] = """
132
+Section "InputClass"
133
+    Identifier "calibration"
134
+    MatchProduct "stmpe-ts"
135
+    Option "Calibration" "291 3847 141 3889"
136
+    Option "SwapAxes" "0"
137
+EndSection
138
+"""
139
+CAL_CONFIG['35r']['xorg']['90'] = """
140
+Section "InputClass"
141
+    Identifier "calibration"
142
+    MatchProduct "stmpe-ts"
143
+    Option "Calibration" "150 3912 3843 255"
144
+    Option "SwapAxes" "1"
145
+    Option "InvertX" "1"
146
+    Option "InvertY" "1"  
147
+EndSection
148
+"""
149
+CAL_CONFIG['35r']['xorg']['180'] = """
150
+Section "InputClass"
151
+    Identifier "calibration"
152
+    MatchProduct "stmpe-ts"
153
+    Option "Calibration" "291 3847 141 3889"
154
+    Option "SwapAxes" "0"
155
+    Option "InvertX" "1"
156
+    Option "InvertY" "1"
157
+EndSection
158
+"""
159
+CAL_CONFIG['35r']['xorg']['270'] = """
160
+Section "InputClass"
161
+    Identifier "calibration"
162
+    MatchProduct "stmpe-ts"
163
+    Option "Calibration" "150 3912 3843 255"
164
+    Option "SwapAxes" "1"
165
+    Option "InvertX" "0"
166
+    Option "InvertY" "0"  
167
+EndSection
168
+"""
169
+
170
+# Other configuration.
171
+POINTERCAL_FILE = '/etc/pointercal'
172
+XORGCAL_FILE = '/etc/X11/xorg.conf.d/99-calibration.conf'
173
+ALLOWED_TYPES = CAL_CONFIG.keys()
174
+ALLOWED_ROTATIONS = ['0', '90', '180', '270']
175
+
176
+
177
+def read_file(filename):
178
+    """Read specified file contents and return them, or None if file isn't
179
+    readable.
180
+    """
181
+    try:
182
+        with open(filename, 'r') as infile:
183
+            return infile.read()
184
+    except IOError:
185
+        return None
186
+
187
+def write_file(filename, data):
188
+    """Write specified data to file.  Returns True if data was written."""
189
+    try:
190
+        # Check if path to file exists.  Create path if necessary.
191
+        directory = os.path.dirname(filename)
192
+        if not os.path.exists(directory):
193
+            os.makedirs(directory)
194
+        # Open file and write data.
195
+        with open(filename, 'w') as outfile:
196
+            outfile.write(data)
197
+            return True
198
+    except IOError, OSError:
199
+        return False
200
+
201
+def determine_rotation():
202
+    """Determine the rotation of the PiTFT screen by examining 
203
+    /sys/class/graphics/fb1/rotate config.
204
+    """
205
+    return read_file('/sys/class/graphics/fb1/rotate')
206
+
207
+def determine_type():
208
+    """Determine the type of display by examining loaded kernel modules.
209
+    """
210
+    # Call lsmod to list kernel modules.
211
+    output = subprocess.check_output('lsmod')
212
+    # Parse out module names from lsmod response (grab first word of each line
213
+    # after the first line).
214
+    modules = map(lambda x: x.split()[0], output.splitlines()[1:])
215
+    # Check for display type based on loaded modules.
216
+    if 'stmpe_ts' in modules and 'fb_ili9340' in modules:
217
+        return '28r'
218
+    elif 'ft6x06_ts' in modules and 'fb_ili9340' in modules:
219
+        return '28c'
220
+    elif 'stmpe_ts' in modules and 'fb_hx8357d' in modules:
221
+        return '35r'
222
+    else:
223
+        return None
224
+
225
+
226
+# Parse command line arguments.
227
+parser = argparse.ArgumentParser(description='Automatically set the PiTFT touchscreen calibration for both /etc/pointercal and X.Org based on the current screen rotation.')
228
+parser.add_argument('-t', '--type',
229
+    choices=ALLOWED_TYPES, 
230
+    required=False,
231
+    dest='type',
232
+    help='set display type')
233
+parser.add_argument('-r', '--rotation', 
234
+    choices=ALLOWED_ROTATIONS, 
235
+    required=False,
236
+    dest='rotation',
237
+    help='set calibration for specified screen rotation')
238
+parser.add_argument('-f', '--force',
239
+    required=False,
240
+    action='store_const',
241
+    const=True,
242
+    default=False,
243
+    dest='force',
244
+    help='update calibration without prompting for confirmation')
245
+args = parser.parse_args()
246
+
247
+# Check that you're running as root.
248
+if os.geteuid() != 0:
249
+    print 'Must be run as root so calibration files can be updated!'
250
+    print 'Try running with sudo, for example: sudo ./pitft_touch_cal.py'
251
+    sys.exit(1)
252
+
253
+# Determine display type if not specified in parameters.
254
+display_type = args.type
255
+if display_type is None:
256
+    display_type = determine_type()
257
+    if display_type is None:
258
+        print 'Could not detect display type!'
259
+        print ''
260
+        print 'Make sure PiTFT software is configured and run again.'
261
+        print 'Alternatively, run with the --type parameter to'
262
+        print 'specify an explicit display type value.'
263
+        print ''
264
+        parser.print_help()
265
+        sys.exit(1)
266
+
267
+# Check display type is allowed value.
268
+if display_type not in ALLOWED_TYPES:
269
+    print 'Unsupported display type: {0}'.format(display_type)
270
+    parser.print_help()
271
+    sys.exit(1)
272
+
273
+# Determine rotation if not specified in parameters.
274
+rotation = args.rotation
275
+if rotation is None:
276
+    rotation = determine_rotation()
277
+    if rotation is None:
278
+        # Error if rotation couldn't be determined.
279
+        print 'Could not detect screen rotation!'
280
+        print ''
281
+        print 'Make sure PiTFT software is configured and run again.'
282
+        print 'Alternatively, run with the --rotation parameter to'
283
+        print 'specify an explicit rotation value.'
284
+        print ''
285
+        parser.print_help()
286
+        sys.exit(1)
287
+
288
+# Check rotation is allowed value.
289
+rotation = rotation.strip()
290
+if rotation not in ALLOWED_ROTATIONS:
291
+    print 'Unsupported rotation value: {0}'.format(rotation)
292
+    parser.print_help()
293
+    sys.exit(1)
294
+
295
+print '---------------------------------'
296
+print 'USING DISPLAY: {0}'.format(display_type)
297
+print ''
298
+print '---------------------------------'
299
+print 'USING ROTATION: {0}'.format(rotation)
300
+print ''
301
+
302
+# Print current calibration values.
303
+print '---------------------------------'
304
+print 'CURRENT CONFIGURATION'
305
+print ''
306
+for cal_file in [POINTERCAL_FILE, XORGCAL_FILE]:
307
+    cal = read_file(cal_file)
308
+    if cal is None:
309
+        print 'Could not determine {0} configuration.'.format(cal_file)
310
+    else:
311
+        print 'Current {0} configuration:'.format(cal_file)
312
+        print cal.strip()
313
+        print ''
314
+
315
+# Determine new calibration values.
316
+new_pointercal = CAL_CONFIG[display_type]['pointercal'][rotation]
317
+new_xorgcal    = CAL_CONFIG[display_type]['xorg'][rotation]
318
+
319
+# Print new calibration values.
320
+print '---------------------------------'
321
+print 'NEW CONFIGURATION'
322
+print ''
323
+for cal, filename in [(new_pointercal, POINTERCAL_FILE), 
324
+                      (new_xorgcal, XORGCAL_FILE)]:
325
+    print 'New {0} configuration:'.format(filename)
326
+    print cal.strip()
327
+    print ''
328
+
329
+# Confirm calibration change with user.
330
+if not args.force:
331
+    confirm = raw_input('Update current configuration to new configuration? [y/N]: ')
332
+    print '---------------------------------'
333
+    print ''
334
+    if confirm.lower() not in ['y', 'yes']:
335
+        print 'Exiting without updating configuration.'
336
+        sys.exit(0)
337
+
338
+# Change calibration.
339
+status = 0
340
+for cal, filename in [(new_pointercal, POINTERCAL_FILE), 
341
+                      (new_xorgcal, XORGCAL_FILE)]:
342
+    if not write_file(filename, cal):
343
+        print 'Failed to update {0}'.format(filename)
344
+        status = 1
345
+    else:
346
+        print 'Updated {0}'.format(filename)
347
+sys.exit(status)

Loading…
Cancel
Save