Android端末をshellで操作できるTermux:APIで遊んでみた

※この記事は「鹿児島Linux勉強会 2018.06」で発表したものに社会性フィルタをかけて加筆修正したものです.鹿児島らぐでは月一回位をペースにオフ会を行っています.

TermuxはAndroid上でLinux環境を構築するアプリケーションです.他に標準のLinuxディストリビューションがchroot環境で動作するソフトウェアが色々ある(Debian no root等)ので独自パッケージ管理なTermuxにはあまり惹かれていなかったのですが,API経由でAndroidデバイスの操作が出来るということを知り試してみました.

入手先

API利用時にはAPIアプリも導入が必要

※互換性の問題があるのでF-DroidとGoogle Playのアプリは混在させてはいけないらしいので注意.

要件

Android 5.0 or newer.

Permissions

Permissions
android.permission.INTERNET
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.WAKE_LOCK
android.permission.VIBRATE
android.permission.READ_EXTERNAL_STORAGE

api pkg導入

Termux上で実行

$ pkg install termux-api

APIを試す

はじめTermux:APIで紹介されているものを確認しました.

パッケージを確認すると他にもコマンドがあったのでそちらも確認し直しました.

dpkg -L termux-api|grep /bin/|cut -d\/ -f8|sort
termux-audio-info
termux-battery-status
termux-brightness
termux-call-log
termux-camera-info
termux-camera-photo
termux-clipboard-get
termux-clipboard-set
termux-contact-list
termux-dialog
termux-download
termux-fingerprint
termux-infrared-frequencies
termux-infrared-transmit
termux-location
termux-media-player
termux-media-scan
termux-microphone-record
termux-notification
termux-notification-remove
termux-sensor
termux-share
termux-sms-inbox
termux-sms-send
termux-speech-to-text
termux-storage-get
termux-telephony-call
termux-telephony-cellinfo
termux-telephony-deviceinfo
termux-toast
termux-torch
termux-tts-engines
termux-tts-speak
termux-vibrate
termux-volume
termux-wallpaper
termux-wifi-connectioninfo
termux-wifi-enable
termux-wifi-scaninfo

基本的にjson形式で結果は帰って来ます.使い方がわからない場合は-hオプションで簡易helpが表示されます.パーミッションを求められる場合はダイアログが表示されるので許可してあげる必要があります.(その回は失敗する)

SIMや赤外線通信の使えるAndroid 5以上の端末が手元にないのでその辺りの物は試せてません.

  • termux-audio-info

    オーディオ情報の取得

      $ termux-audio-info -h
      Usage: termux-audio-info
      Get information about audio capabilities.
      $ termux-audio-info  
      {
        "PROPERTY_OUTPUT_SAMPLE_RATE": "48000",
        "PROPERTY_OUTPUT_FRAMES_PER_BUFFER": "960",
        "STREAM_MUSIC_VOLUME": 1,
        "STREAM_MUSIC_MAXVOLUME": 15,
        "BLUETOOTH_A2DP_IS_ON": false,
        "WIREDHEADSET_IS_CONNECTED": false,
        "AUDIOTRACK_NATIVE_OUTPUT_SAMPLE_RATE": 48000
      }
    
  • termux-battery-status

    バッテリー情報の取得

    $ termux-battery-status -h
    Usage: termux-battery-status
    Get the status of the device battery.
    $ termux-battery-status
    {
      "health": "GOOD",
      "percentage": 70,
      "plugged": "PLUGGED_USB",
      "status": "CHARGING",
      "temperature": 36.900001525878906
    }
    
  • termux-brightness

    輝度の調整?0や255を指定しても動作が解らなかった

    $ termux-brightness
    Usage: termux-brightness brightness
    Set the screen brightness between 0 and 255
    $ termux-brightness 0
    $ termux-brightness 255
    
  • termux-call-log

    通話履歴の取得

    $ termux-call-log -h
    Usage: termux-call-log [-d] [-l limit] [-o offset]
    List call log history
      -l limit   offset in call log list (default: 10)
      -o offset  offset in call log list (default: 0)
    $ termux-call-log
    
  • termux-camera-info

    カメラ情報が取得できる.カメラIDや解像度など.

    $ termux-camera-info -h
    Usage: termux-camera-info
    Get information about device camera(s).
    $ termux-camera-info
    [
      {
        "id": "0",
        "facing": "back",
        "jpeg_output_sizes": [
          {
            "width": 5248,
            "height": 3936
          },
          {
            "width": 5248,
            "height": 2952
          },
          {
            "width": 3840,
            "height": 2160
          },
          {
            "width": 3264,
            "height": 2448
          },
          {
            "width": 2048,
            "height": 1536
          },
          {
            "width": 1920,
            "height": 1080
          },
          {
            "width": 1280,
            "height": 720
          },
          {
            "width": 640,
            "height": 480
          },
          {
            "width": 480,
            "height": 320
          },
          {
            "width": 320,
            "height": 240
          }
        ],
        "focal_lengths": [
          4.900000095367432
        ],
        "auto_exposure_modes": [
          "CONTROL_AE_MODE_ON",
          "CONTROL_AE_MODE_ON_AUTO_FLASH",
          "CONTROL_AE_MODE_ON_ALWAYS_FLASH",
          "CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE"
        ],
        "physical_size": {
          "width": 6.219269752502441,
          "height": 4.663866996765137
        },
        "capabilities": [
          "backward_compatible"
        ]
      },
      {
        "id": "1",
        "facing": "front",
        "jpeg_output_sizes": [
          {
            "width": 1920,
            "height": 1080
          },
          {
            "width": 1600,
            "height": 1200
          },
          {
            "width": 1280,
            "height": 720
          },
          {
            "width": 640,
            "height": 480
          },
          {
            "width": 480,
            "height": 320
          },
          {
            "width": 320,
            "height": 240
          }
        ],
        "focal_lengths": [
          1.809999942779541
        ],
        "auto_exposure_modes": [
          "CONTROL_AE_MODE_ON"
        ],
        "physical_size": {
          "width": 2.1837236881256104,
          "height": 1.2063192129135132
        },
        "capabilities": [
          "backward_compatible"
        ]
      }
    ]
    
  • termux-camera-photo

    カメラを使って写真撮影が出来る.引数にカメラID(option)や写真ファイル名(必須)が指定できる.写真はJPEG形式

    $ termux-camera-photo -h
    
    Usage: termux-camera-photo [-c camera-id] output-file
    Take a photo and save it to a file in JPEG format.
      -c camera-id  ID of the camera to use (see termux-camera-info), default: 0
    $ termux-camera-photo termix_photo.jpg
    
  • termux-clipboard-get

    クリップボードの文字列を取得

    $ termux-clipboard-get -h
    Usage: termux-clipboard-get
    Get the system clipboard text.
    
  • termux-clipboard-set

    クリップボードに文字列を格納

    $ termux-clipboard-set -h
    Usage: termux-clipboard-set [text]
    Set the system clipboard text. The text to set is either supplied as arguments or read from stdin if no arguments are given.
    $ termux-clipboard-set hello
    $ termux-clipboard-get
    hello
    
  • termux-contact-list

    全てのコンタクトリストが表示される

    $ termux-contact-list -h
    Usage: termux-contact-list
    List all contacts.
    $ termux-contact-list
    [
      {
        "name": "MATOHARA Kenichiro",
        "number": "0X0-XXXX-XXXX"
      },
         :
    
  • termux-dialog

    ダイヤログを表示してその結果を取得できる.パスワード文字列などの指定も可能.

    $ termux-dialog -h
    Usage: termux-dialog [-i hint] [-m] [-p] [-t title]
    Show a text entry dialog.
      -i hint   the input hint to show when the input is empty
      -m        use a textarea with multiple lines instead of a single
      -p        enter the input as a password
      -t title  the title to show for the input prompt
    
    $ echo `termux-dialog`
    hoge
    

    28037547727_edb2027c2c_o

    $ echo `termux-dialog -i hint -m -t termux\ dialog`|od -xc
    0000000   h   o   g   e       f   u   g   a  \n
            6f68 6567 6620 6775 0a61
    0000012
    

    28037548487_5ff4a35999_o

    $ echo `termux-dialog -p`
    passwordddd
    

    42188267074_de542c5ee6_o

  • termux-download

    指定したURLからダウンロードが出来る.Androidのダウンロードアプリに渡される.(単にファイル取得ならwgetが入っている)

    $ termux-download -h
    Usage: termux-download [-d description] [-t title] url-to-download
    Download a resource using the system download manager.
      -d description  description for the download request notification
      -t title        title for the download request notification
    
  • termux-fingerprint

    指紋認証を行う?(未確認)

    $ termux-fingerprint -h
    Usage: termux-fingerprint
    Use fingerprint sensor on device to check for authentication
    NOTE: Only available on Marshmallow and later
    $ termux-fingerprint
    {
      "errors": [
        "ERROR_UNSUPPORTED_OS_VERSION"
      ],
      "failed_attempts": 0,
      "auth_result": "AUTH_RESULT_UNKNOWN"
    
  • termux-infrared-frequencies

    赤外線通信情報を取得?(未確認)

    $ termux-infrared-frequencies -h
    Usage: termux-infrared-frequencies
    Query the infrared transmitter's supported carrier frequencies.
    $ termux-infrared-frequencies
    []
    
  • termux-infrared-transmit

    赤外通信で送信する?(未確認)

    $ termux-infrared-transmit -h
    Usage: termux-infrared-transmit -f frequency pattern
    Transmit an infrared pattern. The pattern is specified in comma-separated on/off intervals, such as '20,50,20,30'. Only patterns shorter than 2 seconds will be transmitted.
      -f frequency  IR carrier frequency in Hertz
    
  • termux-location

    位置情報を取得.GPSを利用すると時間が掛かる.位置情報が取得できない場合はタイムアウト後何も帰ってこない.タイムアウトは65秒前後.

    $ termux-location -h
    usage: termux-location [-p provider] [-r request]
    Get the device location.
      -p provider  location provider [gps/network/passive] (default: gps)
      -r request   kind of request to make [once/last/updates] (default: once)
    $ termux-location -p gps
    $ termux-location -p network  
    {
      "latitude": 31.2529767,
      "longitude": 130.8509959,
      "altitude": 0.0,
      "accuracy": 19.31999969482422,
      "bearing": 0.0,
      "speed": 0.0,
      "elapsedMs": 39,
      "provider": "network"
    }
    $ termux-location -p passive
    {
      "latitude": 34.77000045776367,
      "longitude": 138.4600067138672,
      "altitude": 0.0,
      "accuracy": 976974.0625,
      "bearing": 81.0,
      "speed": 0.0,
      "elapsedMs": 5,
      "provider": "fused"
    }
    
  • termux-media-player
    メディアの再生,操作

    $ termux-media-player -h
    termux-media-player: Invalid cmd: '-h'
    Usage: termux-media-player cmd [args]
    
    help        Shows this help
    info        Displays current playback information
    play        Resumes playback if paused
    play <file> Plays specified media file
    pause       Pauses playback
    stop        Quits playback
    $ termux-media-player play 
    No previous track to resume!
    Please supply a new media file
    $ termux-media-player play /storage/sdcard1/Android/data/com.bambuna.podcastaddict/files/podcast/エッジのたたないポッドキャスト/MzoRbgzFVe_3248.mp3
    Now Playing: MzoRbgzFVe_3248.mp3
    $ termux-media-player pause
    Paused playback
    $ termux-media-player play
    Resumed playback
    Track: MzoRbgzFVe_3248.mp3
    Current Position: 00:27 / 13:39
    $ termux-media-player info  
    Status: Playing
    Track: MzoRbgzFVe_3248.mp3
    Current Position: 01:10 / 13:39
    $ termux-media-player info
    No track currently!
    $ termux-media-player play photo.jpg
    
    Prepare failed.: status=0x1
    
  • termux-media-scan

    メディアをスキャンする?

    $ termux-media-scan -h
    Usage: termux-media-scan [-v] [-r] file [file...]
    Scan the specified file(s) and add it to the media content provider.
      -r  scan directories recursively
      -v  verbose mode
    $ termux-media-scan -r /storage/sdcard1/Android/data/com.bambuna.podcastaddict/files/podcast/エッジのたたないポッドキャスト
    Finished scanning 2 file(s)
    $ termux-media-scan -r -v /storage/sdcard1/Android/data/com.bambuna.podcastaddict/files/podcast/エッジのたたないポッドキャスト
    /storage/sdcard1/Android/data/com.bambuna.podcastaddict/files/podcast/エッジのたたないポッドキャスト
    /storage/sdcard1/Android/data/com.bambuna.podcastaddict/files/podcast/エッジのたたないポッドキャスト/MzoRbgzFVe_3248.mp3
    Finished scanning 2 file(s)
    $ termux-media-player info
    No track currently!
    
  • termux-microphone-record

    録音をする.出力ファイル形式は3GPPのよう

    $ termux-microphone-record -h
    Usage: termux-microphone-record [args]
    Record using microphone on your device
    
    -h           Shows this help
    -d           Start recording w/ defaults
    -f <file>    Start recording to specific file
    -l <limit>   Start recording w/ specified limit (in seconds)
    -i           Get info about current recording
    -q           Quits recording
    $ termux-microphone-record -d -f termux-record.mp3 -l 10
    Recording started: /data/data/com.termux/files/home/termux-record 
    Max Duration: 00:10
    $ termux-microphone-record -i
    {
      "isRecording": true,
      "outputFile": "\/data\/data\/com.termux\/files\/home\/termux-record"
    }
    $ termux-microphone-record -i
    {
      "isRecording": false
    }
    file ./termux-record
    ./termux-record: ISO Media, MPEG v4 system, 3GPP
    $ mv ./termux-record ./termux-record.3gpp
    $ termux-media-player play ./termux-record.3gpp
    Now Playing: termux-record.3gpp
    
  • termux-notification

    通知を出力する.タイトル,メッセージ以外にもバイブレーションやサウンド,LEDなども操作できる.

    $ termux-notification -h
    Usage: termux-notification [options]
    Display a system notification. Context text is read from stdin or specified using --content.
      --action action          action to execute when pressing the notification
      --button1 text           text to show on the first notification button
      --button1-action action  action to execute on the first notification button
      --button2 text           text to show on the second notification button
      --button2-action action  action to execute on the second notification button
      --button3 text           text to show on the third notification button
      --button3-action action  action to execute on the third notification button
      --content content        content to show in the notification. Read from stdin not specified here.
      --id id                  notification id (will overwrite any previous notification with the same id)
      --led-color rrggbb       color of the blinking led as RRGGBB (default: none)
      --led-on milliseconds    number of milliseconds for the LED to be on while it's flashing (default: 800)
      --led-off milliseconds   number of milliseconds for the LED to be off while it's flashing (default: 800)
      --on-delete action       action to execute when the the notification is cleared
      --priority prio          notification priority (high/low/max/min/default)
      --sound                  play a sound with the notification
      --title title            notification title to show
      --vibrate pattern        vibrate pattern, comma separated as in 500,1000,200
    $ termux-notification --title hoge --content fuga
    

    Screenshot_2018-06-21-00-54-59

  • termux-notification-remove

    termux-notification -idで指定したidのメッセージを削除する.

    $ termux-notification-remove -h
    Usage: termux-notification-remove notification-id
    Remove a notification previously shown with termux-notification --id.
    $ termux-notification --content hoge --id tm01
    $ termux-notification-remove tm01
    
  • termux-sensor

    センサーの値を取得する.センサーの値は定期的に表示される(既定値は多分1秒間隔)

    $ termux-sensor -h
    Usage: termux-sensor
    Get information about types of sensors as well as live data
      -h, help           Show this help
      -a, all            Listen to all sensors (WARNING! may have battery impact)
      -c, cleanup        Perform cleanup (release sensor resources)
      -l, list           Show list of available sensors
      -s, sensors [,,,]  Sensors to listen to (can contain just partial name)
      -d, delay [ms]     Delay time in milliseconds before receiving new sensor update
    $ termux-sensor -l
    {
      "sensors": [
        "BMA2X2 Accelerometer\/Temperature\/Double-tap",
        "AK8963 Magnetometer",
        "AK8963 Magnetometer Uncalibrated",
        "BMG160 Gyroscope",
        "BMG160 Gyroscope Uncalibrated",
        "APDS-9930\/QPDS-T930 Proximity & Light",
        "APDS-9930\/QPDS-T930 Proximity & Light",
        "Gravity",
        "Linear Acceleration",
        "Rotation Vector",
        "Step Detector",
        "Step Counter",
        "Significant Motion Detector",
        "Game Rotation Vector",
        "GeoMagnetic Rotation Vector",
        "Orientation"
      ]
    }
    $ termux-sensor -s "BMA2X2 Accelerometer\/Temperature\/Double-tap"
    No valid sensors were registered!
    $ termux-sensor -s "AK8963 Magnetometer"
    {
      "AK8963 Magnetometer": {
        "values": [
          -11.248207092285156,
          -37.157630920410156,
          23.89850616455078
        ]
      }
    }
    {
      "AK8963 Magnetometer": {
        "values": [
          16.16058349609375,
          -33.7738037109375,
          -13.971900939941406
        ]
      }
    }
    {
      "AK8963 Magnetometer": {
        "values": [
          3.6207199096679688,
          -38.532447814941406,
          -17.789649963378906
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "AK8963 Magnetometer Uncalibrated"
    {
      "AK8963 Magnetometer Uncalibrated": {
        "values": [
          -18.68438720703125,
          -71.844482421875,
          195.37200927734375,
          -26.05126953125,
          -30.462646484375,
          221.81549072265625
        ]
      }
    }
    {
      "AK8963 Magnetometer Uncalibrated": {
        "values": [
          -18.6492919921875,
          -70.87860107421875,
          196.197509765625,
          -26.05126953125,
          -30.462646484375,
          221.81549072265625
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "BMG160 Gyroscope"
    {
      "BMG160 Gyroscope": {
        "values": [
          8.544921875E-4,
          8.087158203125E-4,
          8.544921875E-4
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "BMG160 Gyroscope Uncalibrated"
    {
      "BMG160 Gyroscope Uncalibrated": {
        "values": [
          -0.006317138671875,
          0.002044677734375,
          0,
          -0.006103517021983862,
          0.0012359619140625,
          -8.544921875E-4
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "APDS-9930\/QPDS-T930 Proximity & Light"
    No valid sensors were registered!
    $ termux-sensor -s "Gravity"
    {
      "Gravity": {
        "values": [
          1.4136531352996826,
          -1.045373558998108,
          9.647754669189453
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Linear Acceleration"
    {
      "Linear Acceleration": {
        "values": [
          -0.0018668174743652344,
          0.005246162414550781,
          0.001544952392578125
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Rotation Vector"
    {
      "Rotation Vector": {
        "values": [
          0.07332251220941544,
          -0.0574394166469574,
          0.9877411723136902,
          0.12526708841323853,
          0.1745329201221466
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Step Detector"
    {}
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Step Counter"
    {
      "Step Counter": {
        "values": [
          0
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Significant Motion Detector"
    {}
    {}
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Game Rotation Vector"
    {
      "Game Rotation Vector": {
        "values": [
          -0.04727154225111008,
          -0.08051935583353043,
          0.005690218415111303,
          0.9956152439117432
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "GeoMagnetic Rotation Vector"
    {
      "GeoMagnetic Rotation Vector": {
        "values": [
          0.07260913401842117,
          -0.05879773199558258,
          0.9851652383804321,
          0.14394499361515045,
          0.1745329201221466
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    $ termux-sensor -s "Orientation"
    {
      "Orientation": {
        "values": [
          194.80770874023438,
          5.517017364501953,
          9.214399337768555
        ]
      }
    }
    ^CCaught interrupt.. Finishing...
    Performing sensor cleanup
    Sensor cleanup successful!
    
  • termux-share

    引数に指定されたファイルを共有する.

    $ termux-share -h
    Usage: termux-share [-a action] [-c content-type] [-d] [-t title] [file]
    Share a file specified as argument or the text received on stdin if no file argument is given.
      -a action        which action to performed on the shared content:
                         edit/send/view (default:view)
      -c content-type  content-type to use (default: guessed from file extension,
                         text/plain for stdin)
      -d               share to the default receiver if one is selected
                         instead of showing a chooser
      -t title         title to use for shared content (default: shared file name)
    $ termux-share photo.jpg 
    
  • termux-sms-inbox

    受信済のSMSメッセージを読み込む.(未確認.SIMなし端末で試したら0件表示された)

    $ termux-sms-inbox -h
    Usage: termux-sms-inbox [-d] [-l limit] [-n] [-o offset]
    List received SMS messages.
      -d         show dates when messages were created
      -l limit   offset in sms list (default: 10)
      -n         show phone numbers
      -o offset  offset in sms list (default: 0)
    $ termux-sms-inbox
    
  • termux-sms-send

    smsメッセージを送信する.(未確認)

    $ termux-sms-send -h
    Usage: termux-sms-send -n number[,number2,number3,...] [text]
    Send a SMS message to the specified recipient number(s). The text to send is either supplied as arguments or read from stdin if no arguments are given.
      -n number(s)  recipient number(s) - separate multiple numbers by commas
    $ termux-sms-send -n 電話番号 message
    
  • termux-speech-to-text

    音声認識した結果を表示する.端末上では空行しか見えないがodに流すと文字列が帰っているのが解る.多分英語のみ?

    $ termux-speech-to-text -h
    Usage: termux-speech-to-text
    Converts speech to text, sending partial matches to stdout.
    $ termux-speech-to-text
    
    
    
    
    
    $ termux-speech-to-text|od -xc
    0000000  \n  \n  \n   H   u   d   l  \n
            0a0a 480a 6475 0a6c
    0000010
    
  • termux-storage-get

    システムに指定したファイルを渡して開く?反応がない.

    $ termux-storage-get -h
    Usage: termux-storage-get output-file
    Request a file from the system and output it to the specified file.
    $ termux-storage-get photo.jpg 
    
  • termux-telephony-call

    指定した番号に電話を掛ける(mobile回線は未確認だが,電話のみでもアプリ選択画面にはなるのでWi-FiのみでもSIPなどで電話することは多分可能)

    $ termux-telephony-call -h
    Usage: termux-telephony-call <number>
    Call a telephony number.
    $ termux-telephony-call 電話番号
    
  • termux-telephony-cellinfo

    電話基地局情報を取得?

    $ termux-telephony-cellinfo -h
    Usage: termux-telephony-cellinfo
    Get information about all observed cell information from all radios on the device including the primary and neighboring cells.
    $ termux-telephony-cellinfo
    [
      {
        "type": "wcdma",
        "registered": true,
        "asu": 6,
        "dbm": -101,
        "level": 2,
        "cid": 249053510,
        "lac": 25994,
        "mcc": 440,
        "mnc": 10,
        "psc": 33
      }
    ]
    

     

  • termux-telephony-deviceinfo

    テレフォニーデバイス情報を取得?

    $ termux-telephony-deviceinfo -h
    Usage: termux-telephony-deviceinfo
    Get information about the telephony device.
    $ termux-telephony-deviceinfo
    {
      "data_activity": "none",
      "data_state": "disconnected",
      "device_id": "357931051XXXXXXX",
      "device_software_version": "81",
      "phone_type": "gsm",
      "network_operator": "",
      "network_operator_name": "",
      "network_country_iso": "",
      "network_type": "unknown",
      "network_roaming": false,
      "sim_country_iso": "",
      "sim_operator": "",
      "sim_operator_name": "",
      "sim_serial_number": null,
      "sim_subscriber_id": null,
      "sim_state": "absent"
    }
    
  • termux-toast

    Toast(一時的なポップアップ)メッセージを表示する

    $ termux-toast -h
    Usage: termux-toast [-s] [text]
    Show text in a Toast (a transient popup). The text to show is either supplied as arguments or read from stdin if no arguments are given.
     -s  only show the toast for a short while
    $ termux-toast hello
    

    Screenshot_2018-06-21-01-57-40

  • termux-torch

    トーチをon/offする?手元の環境では反応がなかった.

    $ termux-torch -h
    Illegal parameter: -h
    Usage: termux-torch [on | off]
    Toggle LED Torch on device
    $ termux-torch on
    ^C
    
  • termux-tts-engines

    テキスト読み上げエンジン(tts)の一覧を表示する

    $ termux-tts-engines -h
    Usage: termux-tts-engines
    Get information about the available text-to-speech (TTS) engines. The name of an engine may be given to the termux-tts-speak command using the -e option.
    $ termux-tts-engines
    [
      {
        "name": "com.google.android.tts",
        "label": "Googleテキスト読み上げエンジン",
        "default": false
      },
      {
        "name": "jp.kddilabs.n2tts",
        "label": "KDDILABS N2 TTS",
        "default": true
      }
    ]
    
  • termux-tts-speak

    テキスト読み上げを行う.日本語に対応したttsであれば日本語も問題ない.標準入力からも受け付けるので記事や小説の読み上げも簡単.

    $ termux-tts-speak こんにちは
    $ echo '吾輩は猫である' | termux-tts-speak
    $ w3m -dump https://www.aozora.gr.jp/cards/000148/files/789_14547.html | termux-tts-speak
    
  • termux-vibrate

    バイブレートを実行.長さの指定やサイレントモードでも強行するモードもある.

    $ termux-vibrate -h
    Usage: termux-vibrate [-d duration] [-f]
    Vibrate the device.
      -d duration  the duration to vibrate in ms (default:1000)
      -f           force vibration even in silent mode
    $ termux-vibrate
    
  • termux-volume
    ボリュームの変更.手元の環境では0〜15で数字が大きいほど音量が大きくなった.16以上を指定しても15と同じ動きになった.

    $ termux-volume -h
    Invalid argument count
    Usage: termux-volume stream volume
    Change volume of audio stream
    Valid audio streams are: alarm, music, notification, ring, system, call
    Call w/o arguments to show information about each audio stream
    $ termux-volume music 5
    
  • termux-wallpaper

    壁紙を設定.位置合わせや切り抜き指定は出来ない.-uが便利.

    $ termux-wallpaper -h
    Change wallpaper on your device
    
    Usage: termux-wallpaper cmd [args]
    -h         show this help
    -f <file>  set wallpaper from file
    -u <url>   set wallpaper from url resource
    -l         set wallpaper for lockscreen (Nougat and later)
    $ termux-wallpaper -u https://www.nasa.gov/sites/default/files/styles/full_width_feature/public/thumbnails/image/pia22422.jpg
    Wallpaper set successfully!
    
  • termux-wifi-connectioninfo

    Wi-Fi接続情報を表示.

    $ termux-wifi-connectioninfo -h
    Usage: termux-wifi-connectioninfo
    Get information about the current wifi connection.
    $ termux-wifi-connectioninfo
    {
      "bssid": "10:6f:3f:XX:XX:XX",
      "frequency_mhz": 2462,
      "ip": "192.168.2.211",
      "link_speed_mbps": 54,
      "mac_address": "68:76:4f:XX:XX:XX",
      "network_id": 0,
      "rssi": -51,
      "ssid": "home-ap",
      "ssid_hidden": false,
      "supplicant_state": "COMPLETED"
    }
    
  • termux-wifi-enable

    Wi-Fiの有効無効設定.

    $ termux-wifi-enable -h
    Usage: termux-wifi-enable [true | false]
    Toggle Wi-Fi On/Off
    $ termux-wifi-enable false
    
    $ termux-wifi-enable true
    
    
  • termux-wifi-scaninfo

    Wi-Fiスキャン結果を表示.

    $ termux-wifi-scaninfo -h
    Usage: termux-wifi-scaninfo
    Get information about the last wifi scan.
    $ termux-wifi-scaninfo
    [
      {
        "bssid": "12:6f:3f:XX:XX:XX",
        "frequency_mhz": 2462,
        "rssi": -55,
        "ssid": "home-guest",
        "timestamp": 2978153233
      },
      {
        "bssid": "10:6f:3f:XX:XX:XX",
        "frequency_mhz": 2462,
        "rssi": -54,
        "ssid": "home-ap",
        "timestamp": 2978153243
      },
      {
        "bssid": "10:6f:3f:XX:XX:XX",
        "frequency_mhz": 2447,
        "rssi": -78,
        "ssid": "matohara",
        "timestamp": 2978153249
      }
    ]
    

Androidアプリケーションを作成しなくてもちょっとしたことならこのAPIの組み合わせで遊ぶことができそうです.(bash+Zenityみたいな?ちょっとちがうか)
Termux:Task/Boot等と組み合わせると更に活用の幅は広がりそうです.(未確認)

Android端末にTermux + Dropbearでssh login

TermuxはAndroid上でLinux環境が構築できる独自パッケージシステムなアプリケーションです.端末ソフトも同梱されています.Termux-apiを使うとshellでAndroidの操作が出来てちょっと面白いのですが,Androidのタッチパネルで文字を打つのが面倒.リモート操作したいのでsshdが動かないか試してみました.

パッケージを検索してみます.定番のOpenSSHとDropbearが使えそうです.

$ pkg search ssh
Hit:1 https://termux.net stable InRelease
Reading package lists... Done
Building dependency tree       
Reading state information... Done
All packages are up to date.
Sorting... Done
Full Text Search... Done
autossh/stable 1.4f arm
  Automatically restart SSH sessions and tunnels

corkscrew/stable 2.0-1 arm
  A tool for tunneling SSH through HTTP proxies

dropbear/stable,now 2018.76-1 arm [installed]
  Small SSH server and client

libssh/stable 0.7.5-1 arm
  Tiny C SSH library

libssh-dev/stable 0.7.5-1 arm
  Development files for libssh

openssh/stable 7.7p1-2 arm
  Secure shell for logging into a remote machine

sshpass/stable 1.06 arm
  Noninteractive ssh password provider

今回は操作ができればいいので消費リソースの少ないDropbearを選択しました.

$ pkg install dropbear
$ dropbear -h
Dropbear server v2018.76 https://matt.ucc.asn.au/dropbear/dropbear.html
Usage: dropbear [options]
-b bannerfile   Display the contents of bannerfile before user login
                (default: none)
-r keyfile  Specify hostkeys (repeatable)
                defaults: 
                dss /data/data/com.termux/files/usr/etc/dropbear/dropbear_dss_host_key
                rsa /data/data/com.termux/files/usr/etc/dropbear/dropbear_rsa_host_key
                ecdsa /data/data/com.termux/files/usr/etc/dropbear/dropbear_ecdsa_host_key
-R              Create hostkeys as required
-F              Don't fork into background
(Syslog support not compiled in, using stderr)
-w              Disallow root logins
-G              Restrict logins to members of specified group
-T              Maximum authentication tries (default 10)
-j              Disable local port forwarding
-k              Disable remote port forwarding
-a              Allow connections to forwarded ports from any host
-c command      Force executed command
-p [address:]port
                Listen on specified tcp port (and optionally address),
                up to 10 can be specified
                (default port is 8022 if none specified)
-P PidFile      Create pid file PidFile
                (default /data/data/com.termux/files/usr/var/run/dropbear.pid)
-i              Start for inetd
-W <receive_window_buffer> (default 24576, larger may be faster, max 1MB)
-K <keepalive>  (0 is never, default 0, in seconds)
-I <idle_timeout>  (0 is never, default 0, in seconds)
-V    Version

鍵を用意します.普通に~/.ssh/authorized_keysに公開鍵を登録すれば良いようです.PCで作成した鍵ペアの公開鍵を登録しました.

$ cd && pwd
/data/data/com.termux/files/home
$ ls -lA ~/.ssh
total 4
-rw-------    1 u0_a235  u0_a235        170 Jun 20 03:58 authorized_keys

sshデーモンを起動します.オプションは適当でポート番号を2222番にしています.

$ dropbear -w -T 2 -j -k -p 2222 -I 600

Androidのipアドレスを確認して,

$ ip r
default via 192.168.2.1 dev wlan0  metric 322 
100.93.0.128/26 dev rmnet0  proto kernel  scope link  src 100.93.0.160 
192.168.2.0/24 dev wlan0  proto kernel  scope link  src 192.168.2.211  metric 322

PCからこんな感じで接続してみると繋がりました!

$ ssh u0_a235@192.168.2.211 -p 2222 -i ~/.ssh/id_ed25519_termux

これで操作が楽に&端末の結果を保存しやすくなりました.

追記)
Dropbearを止める

$ pgrep dropbear
10925
10958
$ pkill dropbear

Google Photos の PWA版を試す

鹿児島らぐの「鹿児島Linux勉強会 2018.06」の帰りにだべっていたときにGoogle Photos の PWA版がリリースされているという話を聞きました.これまでLinux版のアプリはなかったと思うので便利かも?と試してみました.

Google Chromeの設定

Google Chrome で chrome://flags/#enable-desktop-pwas にアクセスしてPWAをEnabled(有効)にします.Google Chromeを再起動すると反映されます.

20180610_19:06:14-7169

 

Google Photosページから導入

Google ChromeでGoogle Photosのページ( https://photos.google.com/ )にアクセスし,ログインします.

右上の「︙」マークの設定に「「Google Photos」をインストールしています︙」という項目が現れるのでこれをクリックすると「アプリをインストールしますか?」と聞かれるので「インストール」ボタンをクリックしてインストールします.(「インストールしています」というメッセージなので待っていたのですがいつまで経ってもインストールが始まりません……)

shutter_18-06-10_19:49:15_001

shutter_18-06-11_02:34:35_001

「インストール」ボタンを押すとポコッとGoogle ChromeからGoogle Photoアプリが分離します.

20180611_02:06:13-10426

これがPWA版のGoogle Photoのようです.

デスクトップアイコンの有効化

デスクトップ上に謎の「~/Desktop/chrome-ncmjhecbjeaamljdfahankockkkdmedg-Default.desktop」というファイルが現れました.中見はGoogle Chromeのアプリを呼ぶもののようでそれっぽいです.

$ cat ~/Desktop/chrome-ncmjhecbjeaamljdfahankockkkdmedg-Default.desktop
#!/usr/bin/env xdg-open
[Desktop Entry]
Version=1.0
Terminal=false
Type=Application
Name=Google Photos
Exec=/opt/google/chrome/google-chrome --profile-directory=Default --app-id=ncmjhecbjeaamljdfahankockkkdmedg
Icon=chrome-ncmjhecbjeaamljdfahankockkkdmedg-Default
StartupWMClass=crx_ncmjhecbjeaamljdfahankockkkdmedg

#この後Chromiumでも試してみたところファイルは上書きされ,Execのgoogle-chromeがchromiumに変わりました.

このファイルを開くと警告が表示され,「信頼して起動(L)」ボタンを押すことでGoogle PhotosのPWA版が起動しました.

20180611_02:06:49-10049

「信頼して起動(L) 」ボタンを押したタイミングで,デスクトップの「chrome-ncmjhecbjeaamljdfahankockkkdmedg-Default.desktop」は「Google Photos」という名称とアイコンに代りました.実体は変わっていないようでshellでlsなどをすると以前の名前のままです.

20180611_02:06:21-10504

 

まだリリースされたばかりのせいか機能はWeb版と同じように見えます.メニューには「アプリのダウンロード」がありますし,まだこれからという感じです.

でも切り替わる頃にはフル機能になるでしょうしそうなるとLinuxでも現在のデスクトップ版と同様の機能が使えるようになるのではないかと期待しています.

ちなみに現在の画像ファイルのGoogle Photosへの自動アップロードは ~/Pictures 以下をcrontabでGoogleCLのgoogleコマンドを叩いてアップロードするようにしています.

$ crontab -l|grep google
*/10 * * * *  D=`date +\%m\%d\%H\%M.\%S` ; find ~/Pictures -newer ${HOME}/Pictures/.picasa_time -type f -print0 | xargs -0 -r -n1 google -v picasa post 'Instant Upload' && touch -t ${D} ${HOME}/Pictures/.picasa_time

しかしGoogleCLはオリジナルは認証関連でだいぶん前に動かなくなってフォーク版を使っていたり,PicasaのAPIだったりといつ動かなくなるか不安だったりします.動かなくなる前にPWA版の機能が充実してくれるといいですね.

環境

$ dpkg-query -W google-chrome-stable
google-chrome-stable    67.0.3396.79-1
$ dpkg-query -W chromium
chromium        67.0.3396.62-1
$ uname -m
x86_64
$ lsb_release -d
Description:    Debian GNU/Linux unstable (sid)

StarDictからGoldenDictに移行した

The original StarDict project has recently been removed from SourceForge due to copyright infringement reports. Most of the files were lost with the demise of the project.

てことで後継のGoldenDictを試してみました.

StarDictでは辞書は英辞郎(テキストデータ版)とstardict-dic-jaを利用していました.

英辞郎の辞書は以下のページのscriptを利用してStarDict形式に変換しました.

eiji2sd_20160307.zipの中のPerl版(eiji2sd-text.pl)を利用して変換後StarDictの辞書ディレクトリにコピーしていました.以下は古めのマシンで実行しているので30分近く変換に掛かっていますが,通常はもっと短い時間で終わると思います.

$ unzip eiji2sd_20160307.zip
$ time perl eiji2sd-text.pl ../EIJIRO-1444.TXT
Now reading: yohimbine activation
Sorting...
Writing dictionary:  99% Zina
Done.

real    26m41.099s
user    3m3.413s
sys     0m7.541s
$ sudo install -b -D -g root -o root -m 0444 ./* /usr/share/stardict/dic/eijiro/

という状態でStarDictを利用していました.

GoldenDictの導入

20180511_17:05:38-1489

GoldenDictをディストリビューションパッケージで導入します.

$ sudo apt install goldendict

GoldenDictの辞書設定

導入したら早速起動して辞書の設定を行います.

メニューバーの「編集」->「辞書」で辞書ウィンドウを起動.
「ソース」タブの「ファイル」タブで「追加」ボタンを押し,辞書を追加します.GoldenDictもStarDictの辞書形式を利用できるのでStarDictの辞書ディレクトリを指定します.「/usr/share/stardict/dic」を指定しました.辞書データをGoldenDictの辞書ディレクトリに持っていってもokです.その場合は「`
追加したあと「再帰」チェックボックスにチェックをし,「今すぐ再スキャン」ボタンを押します.上部の「辞書」タブで辞書が反映されているか確認します.

20180511_20:05:16-26744

一旦ウィンドゥを閉じて,利用したいスキャンポップアップ機能を試します.タスクトレイのGoldenDictアイコンを右クリックして,「スキャン ポップアップ」にチェックが入っているのを確認して,適当な文字列を選択してポップアップウィンドウで辞書引きが出来るのを確認します.

20180511_17:05:24-20380

このままではちょっとポップアップが出る頻度が多くてうっとおしいですし,日本語入力が基本的に不可能になってしまいます.タスクトレイアイコンでOn/Offが出来ますが面倒です.

「編集」->「環境設定」の「スキャンポップアップ」タブの「すべての選択されたキーが押されているときのみポップアップを表示する」をチェックして有効にします.

20180608_14:06:17-1723

もう一つCtrl+c+cでもポップアップが表示されます.これは「ホットキー」タブの「クリップボードからの単語を翻訳するのに次のホットキーを使用します」が有効になっているためです.私はクリップボードへのコピー時につい2回cを押してこれを出してしまうので無効にしました.

20180530_05:05:23-12855

オンライン辞書の利用

「編集」->「辞書」の「ソース」タブの「Wikipedia」タブでWikipediaを引けるようになります.しかし,プリセットを有効にしても使えません.

20180511_18:05:19-17217

「アドレス」のURLをhttp://からhttps://に修正することで使えるようになりました.これが案外便利です.

20180511_18:05:40-14823shutter_18-05-11_19:35:24_001

Wikipediaが便利なので「Webサイト」タブで「ニコニコ大百科」と「はてなキーワード」も追加してみましたが表示されるまでの時間がかかりすぎるし,ヘッダーなどでコンテンツが見えづらいのでちょっとこのままでは使えなさそうです.

20180511_22:05:11-774120180511_23:05:11-26007

環境

Ubuntu 16.04 LTS arm64
Debian sid amd64

スワップファイルを作ってお手軽にスワップを増やす

RAMを大量に必要とするプログラムがあって遅くてもいいから一時的にスワップを増やしてやり過ごすことがあります.また,RAMの少ないマシンでディスクの構成をいじるのが面倒なときにもスワップファイルが使えます.ということで今回RAMが2GBでそこそこあるけど偶に使い切ってしまう(主にchromium!)のでスワップファイルを用意してみました.

スワップファイルを作成します.今回は/var/tmp/swap.imgというファイルで2GB用意しました.

$ sudo install -o root -g root -m 0600 /dev/null /var/tmp/swap.img
$ sudo dd if=/dev/zero of=/var/tmp/swap.img bs=1M count=2048
$ sudo mkswap /var/tmp/swap.img

とりあえずスワップファイルをアドホックに有効にします.

$ sudo swapon /var/tmp/swap.img 

.スワップが増えています.

$ swapon -s
Filename                                Type            Size    Used    Priority
/dev/zram0                              partition       254688  80024   5
/dev/zram1                              partition       254688  80016   5
/dev/zram2                              partition       254688  79940   5
/dev/zram3                              partition       254688  79928   5
/var/tmp/swap.img                       file            2097148 0       -1

一時的に必要な場合はこれで良いのですが,恒久的に利用したい場合はこのままでは再起動後には有効になりません./etc/fstabに設定を書いて起動時に有効になるようにします.

$ sudo vi /etc/fstab
$ grep -i swap.img /etc/fstab 
/var/tmp/swap.img     none    swap    sw      0       0

一旦swapoffでスワップを無効にしてswapon -aでfatabの設定が有効か試します.swapon -afstabのスワップの設定を全て有効にします.

$ sudo swapoff /var/tmp/swap.img
$ sudo swapon -a
$ swapon -s
Filename                                Type            Size    Used    Priority
/dev/zram0                              partition       254688  80020   5
/dev/zram1                              partition       254688  80016   5
/dev/zram2                              partition       254688  79940   5
/dev/zram3                              partition       254688  79928   5
/var/tmp/swap.img                       file            2097148 0       -1

念のため再起動してスワップファイルが有効かも試せばOKです :)

スワップファイルの利用はお手軽ですが,スワップパーティーションに比べると性能は少し落ちるので可能ならスワップパーティーションを利用したほうが良いです.RAMが増設できるならそれが一番です.

環境

$ dpkg-query -W mount
mount   2.27.1-6ubuntu3.6
$ lsb_release -d
Description:    Ubuntu 16.04.4 LTS
$ uname -m
aarch64

MACアドレスをランダムに変更してくれるGNU MAC Changerを試してみる

簡単にMACアドレスをランダムに偽装できる GNU MAC Changer を試してみました.

導入

$ sudo apt install macchanger

導入時にネットワークインターフェイスが有効になるときにmacchangerを有効にするかどうかを聞いてきます.

 ┌────────────────────────┤ Configuring macchanger ├─────────────────────────┐
 │                                                                           │ 
 │ Please specify whether macchanger should be set up to run automatically   │ 
 │ every time a network device is brought up or down. This gives a new MAC   │ 
 │ address whenever you attach an ethernet cable or reenable wifi.           │ 
 │                                                                           │ 
 │ Change MAC automatically?                                                 │ 
 │                                                                           │ 
 │                    <Yes>                       <No>                       │ 
 │                                                                           │ 
 └───────────────────────────────────────────────────────────────────────────┘ 
                                                                               

20180529_21:05:46-14602

あとで変更したい場合は sudo dpkg-reconfigure macchanger で再度設定できます.

help

$ macchanger --help
GNU MAC Changer
Usage: macchanger [options] device

  -h,  --help                   Print this help
  -V,  --version                Print version and exit
  -s,  --show                   Print the MAC address and exit
  -e,  --ending                 Don't change the vendor bytes
  -a,  --another                Set random vendor MAC of the same kind
  -A                            Set random vendor MAC of any kind
  -p,  --permanent              Reset to original, permanent hardware MAC
  -r,  --random                 Set fully random MAC
  -l,  --list[=keyword]         Print known vendors
  -b,  --bia                    Pretend to be a burned-in-address
  -m,  --mac=XX:XX:XX:XX:XX:XX
       --mac XX:XX:XX:XX:XX:XX  Set the MAC XX:XX:XX:XX:XX:XX

Report bugs to https://github.com/alobbs/macchanger/issues

現在のMACアドレス確認

wls1のMACアドレスは00:22:fa:33:45:6aになっています.

$ ip link show wls1 
2: wls1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DORMANT group default qlen 1000
    link/ether 00:22:fa:33:45:6a brd ff:ff:ff:ff:ff:ff

ネットワークインターフェイスをダウン

upのままだとエラーとなります.([ERROR] Could not change MAC: interface up or insufficient permissions: Operation not permitted)

$ sudo ip link set dev wls1 down

MACアドレスをランダムに変更

$ sudo macchanger -r wls1
Current MAC:   de:ed:be:ef:01:23 (unknown)
Permanent MAC: 00:22:fa:33:45:6a (Intel Corporate)
New MAC:       7a:a9:98:47:10:1a (unknown)

macアドレスを元に戻す

$ sudo macchanger -p wls1
Current MAC:   78:a9:98:e1:2e:f8 (unknown)
Permanent MAC: 00:22:fa:33:45:6a (Intel Corporate)
New MAC:       00:22:fa:33:45:6a (Intel Corporate)

ベンダーIDは保持してランダムに変更

このオプションは使い勝手が良さそうですね.

$ sudo macchanger -e wls1
Current MAC:   00:22:fa:33:45:6a (Intel Corporate)
Permanent MAC: 00:22:fa:33:45:6a (Intel Corporate)
New MAC:       00:22:fa:db:b9:ed (Intel Corporate)

手動設定

これはip link set dev wls1 de:ed:be:ef:01:23ifconfig wls1 hw ether de:ed:be:ef:01:23と同じなのであまりmacchangerを使う意味ないですね.

$ sudo macchanger --mac=de:ed:be:ef:01:23 wls1
Current MAC:   00:22:fa:33:45:6a (Intel Corporate)
Permanent MAC: 00:22:fa:33:45:6a (Intel Corporate)
New MAC:       de:ed:be:ef:01:23 (unknown)

ネットワークインターフェイスをアップ

upして何時ものように利用します.

$ sudo ip link set dev wls1 up

自動起動時の動作

/etc/network/if-pre-up.d/macchanger, /etc/network/if-post-down.d/macchangerで設定しているようです.この中を見ると,以下のように-e optionで実行されるのでベンダーIDは維持した状態でランダムに設定されるようです.

/usr/bin/{package} -e IFACE >> $LOGFILE 2>&1

ログファイルは/var/log/macchanger.logに保存されます.

環境

$ neofetch 
       _,met$$$$$gg.          mk@x200 
    ,g$$$$$$$$$$$$$$$P.       ------- 
  ,g$$P"     """Y$$.".        OS: Debian GNU/Linux unstable (sid) x86_64 
 ,$$P'              `$$$.     Model: 74574PJ ThinkPad X200 
',$$P       ,ggs.     `$$b:   Kernel: 4.16.0-1-amd64 
`d$$'     ,$P"'   .    $$$    Uptime: 2 days, 13 hours, 17 minutes 
 $$P      d$'     ,    $$P    Packages: 5718 
 $$:      $$.   -    ,d$$'    Shell: bash 4.4.19 
 $$;      Y$b._   _,d$P'      Resolution: 1280x800 
 Y$$.    `.`"Y$$$$P"'         WM: awesome 
 `$$b      "-.__              Terminal: sakura 
  `Y$$                        Terminal Font: Fira Code 11 
   `Y$$.                      CPU: Intel Core 2 Duo P8400 (2) @ 2.267GHz 
     `$$b.                    GPU: Intel® GM45 Express Chipset 
       `Y$$b.                 Memory: 6579MiB / 7871MiB 
          `"Y$b._ 
              `"""                                    

$ dpkg-query -W macchanger
macchanger      1.7.0-5.3+b1

microSDスロットの固定機構の壊れたRaspberry Pi 2 Bのバネを取り外して普通に使えるようにする

SANY0011

Raspberry Pi 2 Bを使っているのですが,以前からmicroSDソケットの固定機構が壊れてしまっています.セロハンテープで留めて更にケースに入れて動きにくくしているのですがたまにずれるようで起動中にストレージを見失ってしまうことがあります.(そして数回に一回は要fsckに)

ちょっと面倒なので対処したいなと思いながら放置していたのですが,また今日も起こったので調べてみることに.多分microSDを押し返すピンかバネを無くしてしまえたら解決しそうな気がします.でも内部が見えないのでどこにピンやバネがあるのかよくわからないです.

SANY0015

きっと先駆者が居るだろうと検索するといくつかそれらしいページを見つけました.

ソケットを交換するアプローチ

ソケットの中のスプリングを取り出してしまうアプローチ

後者のスプリングを取り出すのが簡単そうだし,最悪失敗しても前者のソケットを交換すればいいかなと試してみました.スプリングの場所が分かったのですが現物を見てもよくわからないです.光を当てながら少し斜めから見るとバネが見えました.バネの横の部分を一旦開けて中を確認する人も居るようです.

SANY0019

ここで安全ピンのピン先でこじるようにと思いましたがちょっと安全ピンが大きいせいかソケットが膨らむのでジャンパワイヤのオスを使いました.

ソケットのスプリングの上側からこじるとプラスチックのラッチが外れました.一旦ラッチを取り出して更にその奥をこじるとスプリングの反応がありました.スプリングを内側に倒してから引っ張り上げるようにして取り外せました.

SANY0020

この状態でmicroSDを差し込むとmicroSDは押し返されなくなりました!これで最近のRaspberry Pi Zero(多分3B/3B+も)と同じような使い勝手になったと思います.

SANY0022

今回はRaspberry Pi 2 Bでしたが,Raspberry Pi B+/Raspbery Pi A+もロック機構が壊れたら同様の機構なので同じように解決できると思います.

今だと最新のRaspberry Pi 3 B+を買う人が多いでしょうが.

Androidの容量が少なくなって困る

Android端末の容量が少なくてGoogle Playがアプリを更新できないとエラーを出ています.確認すると「その他のファイル」が妙に容量を食っている.見ると「mhenv」というフォルダが殆どを占めています.
開発者も土が有効な状態でadb shellで中に入って見てみると実体は/storage/emulated/legacy/mhenv/ここで12GB以上です.

$ adb shell
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
shell@g2:/ $ cd /storage/emulated/legacy
$ du -ms mhenv
12467 mhenv

中を見ると「YMO!」(小説家になろうなどのオンライン小説リーダ)のデータが12GB以上食っている!
テキストデータだけじゃないの?と中を見るとこんな感じで更新時に毎回バックアップを取っているような感じです.

$ ls -l 猫正宗 
-rw-rw---- root sdcard_r 988721 2018-05-24 13:14 隣の部屋の女騎士は、異世界人で飲み友達_n2059ek.txt
-rw-rw---- root sdcard_r 288071 2017-12-16 14:12 隣の部屋の女騎士は、異世界人で飲み友達_n2059ek_rev20171217001107.txt
-rw-rw---- root sdcard_r 325287 2017-12-23 23:52 隣の部屋の女騎士は、異世界人で飲み友達_n2059ek_rev20171226002611.txt
-rw-rw---- root sdcard_r 341974 2017-12-26 00:26 隣の部屋の女騎士は、異世界人で飲み友達_n2059ek_rev20171228101117.txt
:

恐らく「${作者名}/{タイトル}${小説コード}.txt」が最新で,「${作者名}/{タイトル}${小説コード}_rev${年月日??????}.txt」が古いもの.

念の為バックアップを取って,findで……無かったorz

$ find . -name "*_rev??????????.txt" -ls

ディレクトリ階層も決まっているので,こんな感じでlsで確認してから消してみました.12.5GB近かったのが0.5GB以下になりました.

$ ls */*_rev??????????????.txt 
$ rm */*_rev??????????????.txt
$ du -ms . 
493 .

アプリケーション側の動作も問題無さそうです.

ちなみにこの後Androidアプリケーション側の設定を確認すると,「データ保存先変更」で端末によってはSD Cardに移動できそうです.手元の端末では変更不可でした.
それと,「改定時ファイル保存設定」と「古い稿を残す基準を設定」といものがあり,この設定だけで良かった気がします…….

環境

Devuan jessieをasciiにdist-upgradeしてみた

screenshot

Devuan asciiもRelease Candidateが出てそろそろ正式版になりそうです.てことで手元のDevuan jessie i386環境をascii環境にdist-upgradeしてみました.

DevuanはDebianからフォークした脱Systemdなディストリビューションです.コードネームはjessieはDebianと同じですがその次のバージョンから独自になっていて,Devuan asciiはDebian stretch相当になります.

アップグレードのドキュメントは以下にありました.

うーんシンプル.念の為Debianの文章も参考にします.

これらの文章と違うところはsources.list編集時にapt edit-sourcesコマンドを使ったくらいです.今回はこんな感じに.

diff --git a/apt/sources.list b/apt/sources.list
index 142945f..afaa14d 100644
--- a/apt/sources.list
+++ b/apt/sources.list
@@ -1,16 +1,16 @@
-# deb http://jp.mirror.devuan.org/merged/ jessie main
+# deb http://jp.mirror.devuan.org/merged/ ascii main
 
-deb http://jp.mirror.devuan.org/merged/ jessie main non-free contrib
-deb-src http://jp.mirror.devuan.org/merged/ jessie main non-free contrib
+deb http://jp.mirror.devuan.org/merged/ ascii main non-free contrib
+deb-src http://jp.mirror.devuan.org/merged/ ascii main non-free contrib
 
-# jessie-security, previously known as 'volatile'
-deb http://jp.mirror.devuan.org/merged/ jessie-security main contrib non-free
-deb-src http://jp.mirror.devuan.org/merged/ jessie-security main contrib non-free
+# ascii-security, previously known as 'volatile'
+deb http://jp.mirror.devuan.org/merged/ ascii-security main contrib non-free
+deb-src http://jp.mirror.devuan.org/merged/ ascii-security main contrib non-free
 
-# jessie-updates, previously known as 'volatile'
-deb http://jp.mirror.devuan.org/merged/ jessie-updates main contrib non-free
-deb-src http://jp.mirror.devuan.org/merged/ jessie-updates main contrib non-free
+# ascii-updates, previously known as 'volatile'
+deb http://jp.mirror.devuan.org/merged/ ascii-updates main contrib non-free
+deb-src http://jp.mirror.devuan.org/merged/ ascii-updates main contrib non-free
 
-# jessie-backports, previously on backports.debian.org
-deb http://jp.mirror.devuan.org/merged/ jessie-backports main contrib non-free
-deb-src http://jp.mirror.devuan.org/merged/ jessie-backports main contrib non-free
+# ascii-backports, previously on backports.debian.org
+deb http://jp.mirror.devuan.org/merged/ ascii-backports main contrib non-free
+deb-src http://jp.mirror.devuan.org/merged/ ascii-backports main contrib non-free

特に問題なく処理は進んでいましたが,apt dist-upgradeでエラーが発生しました.bluemanで以下のようなエラーとなりました.

Setting up blueman (2.0.4-1) ...
Reloading system message bus config...Error org.freedesktop.DBus.Error.FileNotFound: Failed to open "/etc/dbus-1/system.conf": No such file or directory
invoke-rc.d: initscript dbus, action "reload" failed.
dpkg: error processing package blueman (--configure):
 subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
 blueman
E: Sub-process /usr/bin/dpkg returned an error code (1)

一旦削除して再起動後導入し直したら導入に成功しました.

$ sudo apt remove blueman
$ sudo reboot
$ sudo apt install blueman

ということでシンプルなシステムだったせいかさっくりとdist-upgradeに成功しました :)

<追記>
うまく行かなかった人も居るよう.

</追記>

terminalで動作するMastodon clientのnanotodonを試してみた

mikutodonをDebian jessie armhfに入れてみた.Makefileを修正したら動いたけど文字化けする.ちなみにDebian sid amd64では問題なく動作した.

$ cat /etc/debian_version 
8.10
$ uname -m
armv7l

ライブラリ等導入

$ sudo apt install build-essential libcurl4-openssl-dev libjson-c-dev libncurses-dev libncursesw5
$ dpkg-query -W build-essential libcurl4-openssl-dev libjson-c-dev libncurses-dev libncursesw5
build-essential 11.7
libcurl4-openssl-dev:armhf      7.38.0-4+deb8u11
libjson-c-dev:armhf     0.11-4
libncurses-dev  
libncursesw5:armhf      5.9+20140913-1+deb8u2

<追記>
入ってない場合gitも必要ですね $ sudo apt install git
</追記>

source入手

$ git clone https://github.com/taka-tuos/nanotodon

make

コケた

$ cd nanotodon
$ make
make -r nanotodon
make[1]: Entering directory '/home/chip/src/nanotodon'
gcc -c -g -o nanotodon.o nanotodon.c
nanotodon.c: In function 'stream_event_notify':
nanotodon.c:110:12: warning: initialization discards 'const' qualifier from pointer target type
  char *t = json_object_get_string(notify_type);
            ^
nanotodon.c: At top level:
nanotodon.c:138:6: warning: conflicting types for 'stream_event_update'
 void stream_event_update(struct json_object *jobj_from_string)
      ^
nanotodon.c:128:3: note: previous implicit declaration of 'stream_event_update' was here
   stream_event_update(status);
   ^
nanotodon.c: In function 'stream_event_update':
nanotodon.c:180:14: warning: initialization discards 'const' qualifier from pointer target type
  char *src = json_object_get_string(content);
              ^
nanotodon.c:226:3: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
   for (int i = 0; i < json_object_array_length(media_attachments); ++i) {
   ^
nanotodon.c:226:3: note: use option -std=c99, -std=gnu99, -std=c11 or -std=gnu11 to compile your code
nanotodon.c:245:3: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
   for(int i = 0; i < term_w - (l + 4); i++) waddstr(scr, " ");
   ^
nanotodon.c: At top level:
nanotodon.c:589:6: warning: conflicting types for 'do_htl'
 void do_htl()
      ^
nanotodon.c:303:2: note: previous implicit declaration of 'do_htl' was here
  do_htl();
  ^
nanotodon.c: In function 'do_htl':
nanotodon.c:618:3: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
   for (int i = json_object_array_length(jobj_from_string) - 1; i >= 0; i--) {
   ^
nanotodon.c: In function 'main':
nanotodon.c:751:2: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
  for(int i = 0; i < term_w; i++) mvaddch(5, i, '-');
  ^
nanotodon.c:777:4: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
    for(int i = 0; i < term_w; i++) mvaddch(5, i, '-');
    ^
nanotodon.c:802:3: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
   for(int i = 0; i < txt.stringlen; i++) {
   ^
Makefile.in:21: recipe for target 'nanotodon.o' failed
make[1]: *** [nanotodon.o] Error 1
make[1]: Leaving directory '/home/chip/src/nanotodon'
Makefile.in:11: recipe for target 'default' failed
make: *** [default] Error 2

Makefileを修正したら通った

diff --git a/Makefile b/Makefile
index ac1828f..a35ee6a 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,7 @@
 TARGET         = nanotodon
 OBJS_TARGET    = nanotodon.o
 
-CFLAGS = -g
+CFLAGS = -g -std=gnu99
 LDFLAGS = 
 LIBS = -lc -lm -lcurl -ljson-c -lncursesw -lpthread
 

文字化け><

20180521_20:05:50-30304

Debian sid amd64ではMakefileの書き換えも必要なく文字化けもしない.

20180521_20:05:01-31796

$ cat /etc/debian_version 
buster/sid
$ uname -m
x86_64
$ dpkg-query -W build-essential libcurl4-openssl-dev libjson-c-dev libncurses-dev libncursesw5
build-essential 12.5
libcurl4-openssl-dev:amd64      7.60.0-1
libjson-c-dev:amd64     0.12.1-1.3
libncurses-dev:amd64    6.1+20180210-3
libncursesw5:amd64      6.1+20180210-3