ひゃまだのblog

ひゃまだ(id:hymd3a)の趣味のブログ

はてなブログの記事ごとのスターの数と持っているスターの種類と数

(2021-12-07 初稿 - )

はじめに

はてなブログで記事をアップすると、極々たまにはてなスターをいただくことがある。

書いた本人としては、どの記事が人気があるのか、あるいは気に入ってもらえたのか気になる。

ところが、毎回、その見方を忘れてしまうので、備忘録としてアップする。

記事ごとのはてなスターの数の確認

以下のUserIDの部分を自分のIDに変えれば、何日にどの記事に何個はてなスターをいただいたかが確認できる。

https://s.hatena.ne.jp/UserID/report

筆者の場合は、以下のとおり。

f:id:hymd3a:20211207200140p:plain

頂いたはてなスターの一覧

現在自分が持っているはてなスターの種類と数の確認

下記のリンクをクリックすると、自分の持っているはてなスターの種類と数がわかる。

f:id:hymd3a:20211207200921p:plain

自分の持っているはてなスターの種類と数

以上、参考になれば…

関連ページ

リンクを別のタブで開く(html)

(2021-12-06 初稿 - )

このはてなブログも、編集モードでリンクを作成すると現在利用しているタブで開いてしまう。

ここでは、別のタブで開くためのHTML編集のコマンドを記載する。

 

1. 編集(見たまま)モードでリンクを作成後、HTML編集に変更

2. 別ページで開きたいリンクのところに、targetとrelコマンドを挿入

<a href="ここにリンク先のURLを入れる" target="_blank" rel="noopener noreferrer">リンク先のタイトル</a>

 

ちなみに、rel コマンドは悪意のあるサイトからの変更を防止するために入れるとのこと。

このブログでも、外部へのリンクは別タブで開くように少しずつ改変するつもり。

関連ページ

Githubに登録の際の認証エラー対策

(2021-12-04 初稿 - )

はじめに

git cloneは利用したことがあるが、自分の稚拙なスクリプト等をgitで管理しようとは思っていなかった。しかし、自分のページを見てくれて方が、ブログ内のスクリプト等をダウンロードするのに便利かと思い登録することにした。

すぐに使えるかと思ったが、2点ほどトラブルに見舞われたので、このページではその解決策を記載する。

基本的な使い方

このページでは、githubへの登録やgitの使い方にはついては、解説しない(手抜き(^^ゞ)。

以下のサイト等を参照し、チャレンジして欲しい。

上記の記述のとおり、手順は、まずgithubのアカウントを作成して、手元のPC(以下、ローカルPC)で以下の操作を行う。

ここでは、sampleというRipositoryを作成し、hello.pyというスクリプトを登録すると仮定する。

1. mkdir sample
2. cd sample
3. git init
4. git status
On branch master
Untracked files:
 (use "git add <file>..." to include in what will be committed)
 hello.py
5. git add hello.py
6. git status
On branch master
Changes to be committed:
 (use "git restore --staged <file>..." to unstage)
 new file: hello.html
7. git commit -m "add new file"
8. git status
On branch master
nothing to commit, working tree clean
9. git remote add origin https://github.com//awesome.git
10. git push origin master

エラーは、10でpushしたときに、以下のメッセージを出して起こる。

エラーメッセージ

Username for 'https://github.com': userid
Password for 'https://userid@github.com': 
remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: Authentication failed for 'https://github.com/userid/sample.git/'

解決方法

解決方法は、以下のサイトにあった。多謝。

また、解決に必要なSSHの登録は、複数台のPCでgitを利用するためにも必要である。

実際の変更は、gitに含まれるconfigファイルを以下のとおり変更する。

cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
[remote "origin"]
  url = https://github.com:userid/sample.git  # 変更前
  url = git@github.com:userid/sample.git    # 変更後
  fetch = +refs/heads/*:refs/remotes/origin/*

ファイルの追加

該当ディレクトリにファイルを追加するときにもトラブルがあった。これは、筆者が知らないだけなのかも。

手順は、以下のとおり実施するが、4.のoriginを再度リモートに登録する必要はない。

1. git add hello2.py
2. git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
  new file:   hello2.py
3. git commit -m "add new file"
[master ea42f6e] add new file
 1 file changed, 16 insertions(+)
 create mode 100755 hello2.py
4. git remote add origin gttps://github/userid/rp-temphum.git   # 不要
error: remote origin already exists.    
5. git push origin master
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
>Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 478 bytes | 478.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
To github.com:userid/sample.git
   c7221c7..ea42f6e  master -> master

おわりに

はてなブログにコードを貼るには、Gistを利用する。Gistについては、別にアップする予定。

関連ページ

Python3でもっと簡単に値を受付ける

(2021-12-02 初稿 - )

はじめに

以前、python-tkで値の入力を受付けるスクリプトを紹介した。

今回は、zenifyを利用した値の入力を受付けるスクリプトを紹介。

なお、この記事はzenifyが使えるLinuxRaspberry Piでの利用を想定している。

類似のファイル選択については、以下のページの参照を。

スクリプト

さっそく、python3で値の入力ダイアログを表示して、ファイルを選択するスクリプトを紹介する。

pyhton3から外部のプログラムを利用するため、subprocess.runを用いる。なお、Zenityは選択した値をバイナリ形式で標準出力に出力する。

#!/usr/bin/env python3
import subprocess

# Zenityの起動、stdoutをpipeに
result = subprocess.run(['zenity','--entry'], stdout=subprocess.PIPE)
print(result.stdout.decode("utf-8"))    # 出力をUTF-8

実行すると以下のようなダイアログが出る。

f:id:hymd3a:20211202132353p:plain

実行結果

オプション

Zenityにオプション付けると、下図のようになる。

--text=何かの文字を入力して

--entry-text=初期値

f:id:hymd3a:20211202132833p:plain

オプションを付けて実行

この他、--hide-text で入力文字を隠すことができる。

詳細は、man zenity または zenity --help-entry で。 

関連ページ

Raspberry PiでCircuitPythonを利用して温湿度を測る(DHT22、AM2302)

(2021-12-01 初稿 - 2022-08-28 修正)

以前にRaspberry Piで、DHT22が付いたAM2302というセンサーで温湿度を測り、飽差を計算する記事を書いた。

記事をアップした当初は正常に動作したが、新たにインストールしたRaspberry Piでは動作しなくなってしまった。

確かに、当時使っていたライブラリのサイトを見ると、DEPRECATED LIBRARYとなっており、現在は推奨されていない。 

ここでは、Adafruit社のCircuitPythonのライブラリをインストールして、温湿度を測る方法を改めて記述する。

なお、以下の方法は、Raspberry Pi のOS Bullseye相当で確認を行った。

温度と湿度のセンサー

今回の目的のために購入した温湿度センサーは以下のとおり。
1個500〜600円なので、財布には優しい。

このセンサーはDHT22が温度・湿度センサーで、既にハンダ付けされて付属のケーブルでつなぐだけのAM2302を購入した。以下、このセンサーをAM2302と呼ぶ。

f:id:hymd3a:20210514153725j:plain

購入したAM2302

AM2302のつなぎ方

AM2302とラズパイの接続を間違えるとセンサーが壊れてしまうので、注意すること。
以下に写真を載せるので、付属ケーブルの接続方法を確認すること。

+    ⇒ pin1
out ⇒ pin7
-     ⇒ pin9

f:id:hymd3a:20210513100734j:plain

AM2302の端子

温度と湿度を測る

ライブラリのインストール

接続完了後、以下のとおりライブラリをインストールする。

まず、python3の pip を事前にインストール。既にインストールされていれば、不要。

$ sudo apt-get update 
$ sudo apt-get install python3-pip

以下のサイトに記述があるように、ライブラリをインストールする。

pip3 install adafruit-circuitpython-dht
sudo apt-get install libgpiod2

温度の計測

動作のテストは、上記サイトにあるスクリプトをコピーして実行するか、以下のスクリプトを試す。

以下のスクリプトは、筆者がCronで起動するために作成したもので、temp_hum-cp.py等と名前をつけて保存する。

$cat temp_hum-cp.py    

#!/usr/bin/env python3
# coding: utf-8
import time
import datetime
import board
import adafruit_dht

MAXTRY = 4

# add 2021-08-20
humidity = temperature = None

# Initial the dht device, with data pin connected to:
# 測定の開始(4は、接続したGPIOポート)
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False) # mod2022-08-29

cnt = 0
while cnt < MAXTRY:
    try:
        temperature = dhtDevice.temperature
        humidity = dhtDevice.humidity
        if humidity is not None and temperature is not None:
            #print(temperature, humidity)
            break

    except RuntimeError as error:
        print(error.args[0])
        time.sleep(1)
        cnt += 1
        continue

    except Exception as error:
        dhtDevice.exit()
        print("Exception error")
        raise error

# 時間の取得
now = datetime.datetime.today()

# 結果の表示
print("{} {} Temperature= {:.1f} *C, Humidity= {:.1f} %".format(now.strftime("%Y-%m-%d"),now.strftime("%H:%M:%S"), temperature , humidity))

サンプルプログラムの実行

$ chmod +x temp_hum-cp.py
$ python3 ./temp_hum-cp.py
2021-12-01 14:25:01 Temperature= 25.3 *C, Humidity= 40.7 %

上記のとおり、温度と湿度が表示されれば、正常に作している。

Crontab登録のためのBashスクリプトの作成

温湿度が計測できるようになったので、せっかくなのでデータを保存できるようにBashでラッパーを作成する。

ここでは、単純に ~/data ディレクトリに日付(2021-12-01.txt 等)ごとのファイルを作成し保存することとした。

このスクリプトは、t_temp_hum 等の名前にして、~/binディレクトリに保存する。

#!/bin/env bash
# 測定program for AM2302

rtext=$(/home/pi/py-s/temp_hum-cp.py)
set $rtext  # setで要素に分解 超便利
#echo ${1}
fpath="/home/pi/data/"

fname=error.txt
if [[ ${1} =~ [0-9]{4}-[0-9]{2}-[0-9]{2} ]]; then # 日付だったら
  fname=${1}.txt
fi

echo $rtext
echo $rtext  >> $fpath$fname  # >> 追記

作成したBashスクリプトは以下のとおり、実行権を与えてテストする。

$ chmod +x ~/bin/t_temp_hum
$ t_temp_hum
2021-12-01 14:25:01 Temperature= 25.3 *C, Humidity= 40.7 %

Crontabへの登録

出来上がったBashスクリプトは、Crontabへ登録する。

$ crontab -e

*/5 * * * * /home/pi/t-png 1>/dev/null

以上で、5分おきに温湿度を記録するようになる。

おわりに

以前の方法は非推奨とのことだったので、改めてCircuitPythonライブラリを用いた温湿度計測方法にスクリプトを書き直した。また、変更があれば、修正・追記を行う。

関連ページ

 

Raspberry PiのOSを10⇒11(Bullseye)に変更

(2021-11-30 初稿 - )

はじめに

本家のDebianは、2021年8月14日に11(Bullseye)をリリースしたのに続いて、Raspberry Pi OSも、2021年11月8日にBullseye相当の新しいOSをリリースした。

GTK+3を利用し見た目がきれいになったが、やや重くなり2GB以上のRAMがほしいとのこと。

初回の起動時に、日本語の設定(fcitx+mozc)を行ってくれるので、起動直後から日本語が使える親切設計である。

f:id:hymd3a:20211130141900p:plain

11(Bullseye)インストール直後のデスクトップ

残念ながら、公式のホームページでは、アップグレードではなく新規のインストールを推奨している。Raspberry Piをサーバ用途で使っている筆者にとってはつらい。(T_T)

このページでは、Raspberry Pi OSを新規にインストールする方法を記載する。

imagerのインストール

まず、最初はimagerのインストールから始める。なお、筆者はDebianを使っているので、他のOSでも大きな違いは無いと思うが、Debianでインストールする方法を記載する。

上記サイトから、赤丸の部分をクリックして、imager_1.6.2_amd64.debをダウンロード。

f:id:hymd3a:20211130135550p:plain

imagerのダウンロード

ダンロードしたdebパッケージをaptでインストールする。

$ sudo apt install imager_1.6.2_amd64.deb

Debian 11(Bullseye)では問題なくインストールできた。メニューのアクセサリにある「Imager」を起動し、Raspberry Pi OS(32bit)と書き込むmicro SDカードを選択後、Writeで書き込めば準備は完了である。

初回の起動時にハーティションを変更してデータ領域等を拡張するので、imagerを利用する方法が簡単である。

f:id:hymd3a:20211130140823p:plain

ImagerによるOSの書き込み

起動後の設定

起動後の設定は、様々なものがあるが、ここでは、IPアドレスの固定とSSHVNCの設定のみを紹介する。

IPアドレスの固定

サーバとして利用する場合は、IPアドレスを固定(静的)した方が都合がよい。

デスクトップ右上にあるネットワークのアイコンを右クリックすることで、IPアドレスを設定できる。

ちなみに、設定は /etc/dhcpcd.conf に書き込まれ、例えば、アクセスポイントSSID abcd  Wi-Fi にアクセスする際には以下のようになる。なお、XXXの部分は接続するネットワークに合わせて変更する。

SSID abcd Wi-Fi inform 192.168.XXX.XXX static routers=192.168.XXX.1 static domain_name_servers=192.168.XXX.1 static domain_search=8.8.8.8 noipv6

SSHの起動

下の画面にあるsshにチェックを入れれば(赤丸)、sshが使えるようになる。

他のPCから接続する場合は、上記で設定したIPアドレスを用いて以下のように接続する。

$ ssh pi@192.168.XXX.XXX

f:id:hymd3a:20211130191341p:plain

sshVNCの起動

VNCの起動

同様に、上の画面のVNCにチェックを入れれば(赤丸)、サーバとして機能する。tigervnc等のVNCビューアで接続できるが、パスワードの設定をUNIXパスワードからVNCパスワードに変更しないと接続できないので注意すること。

f:id:hymd3a:20211130191555p:plain

VNCのオプション変更

おわりに

以上、IPアドレスの固定化とSSHVNCのサーバの設定を行った。SSHVNCが使えれば、リモートでも設定可能になると思われる。

関連ページ

こちらの方が良かった軽量版WinPythonの始め方

(2021-11-29 初稿 - )

はじめに

WinPythonを使うようになって、以下のページをアップしたが、軽量版のWinPythonがあることがわかった。

軽量版のWinPythonを利用することにより、ダウンロードや展開の時間の短縮、スクリプト実行の高速化ができる。

ただし、いくつかのライブラリは手動でインストールする必要がある。しかし、小さいファイルサイズは人にコピーして渡すときに便利だし、実行時間の短縮は開発時間の短縮に効果があり、ライブラリーのインストトールの手間があってもこちらの方が良かったと思う。

ダウンロードと展開

ダウンロードは以下のページから行う。

f:id:hymd3a:20211129193709p:plain

WinPythonのホームページ 赤丸の最新安定版の軽量版をダウンロードする

実際のダウンロードは、SouceForgeのサイトから行った。

同じVersion 3.9.8.0でも、通常版のWinpython64-3.9.8.0.exeファイルは826MB、軽量版のWinpython64-3.9.8.0dot.exeはわずか26.5MBしかない。

実際に展開すると、通常版は4.3GB程度、軽量版は、80MBに満たない程度である。

f:id:hymd3a:20211129193846p:plain

SorceForgeからダウンロード

ダウンロードしたファイルを実行し、展開先を指定すればすぐに使えるようになる。

ライブラリのインストール

軽量版だけに、インストールされているライブラリは少ない。

もし、インストールが必要になった場合は、以下のコマンドでインストールできる。

ここでは、例として numpy をインストールする。

展開したフォルダにあるWinPython Command Promptを開いて、以下のコマンドを入力する。

python -m pip install numpy

ライブラリのインストールはやや面倒だが、以下のようにヘルプをみれば概ね操作できると思う。

python -m pip -h
Usage:   
  C:\WPy64\python-3.9.8.amd64\python.exe -m pip  [options]

Commands:
  install                     Install packages.
  download                    Download packages.
  uninstall                   Uninstall packages.
  freeze                      Output installed packages in requirements format.
  list                        List installed packages.
  show                        Show information about installed packages.
  check                       Verify installed packages have compatible dependencies.
  config                      Manage local and global configuration.
  search                      Search PyPI for packages.
  cache                       Inspect and manage pip's wheel cache.
  index                       Inspect information available from package indexes.
  wheel                       Build wheels from your requirements.
  hash                        Compute hashes of package archives.
  completion                  A helper command used for command completion.
  debug                       Show information useful for debugging.
  help                        Show help for commands.

General Options:
  -h, --help                  Show help.
  --debug                     Let unhandled exceptions propagate outside the
                              main subroutine, instead of logging them to
                              stderr.
  --isolated                  Run pip in an isolated mode, ignoring
                              environment variables and user configuration.
  -v, --verbose               Give more output. Option is additive, and can be
                              used up to 3 times.
  -V, --version               Show version and exit.
  -q, --quiet                 Give less output. Option is additive, and can be
                              used up to 3 times (corresponding to WARNING,
                              ERROR, and CRITICAL logging levels).
  --log                 Path to a verbose appending log.
  --no-input                  Disable prompting for input.
  --proxy              Specify a proxy in the form
                              [user:passwd@]proxy.server:port.
  --retries          Maximum number of retries each connection should
                              attempt (default 5 times).
  --timeout              Set the socket timeout (default 15 seconds).
  --exists-action     Default action when a path already exists:
                              (s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.
  --trusted-host    Mark this host or host:port pair as trusted,
                              even though it does not have valid or any HTTPS.
  --cert                Path to PEM-encoded CA certificate bundle. If
                              provided, overrides the default. See 'SSL
                              Certificate Verification' in pip documentation
                              for more information.
  --client-cert         Path to SSL client certificate, a single file
                              containing the private key and the certificate
                              in PEM format.
  --cache-dir           Store the cache data in.
  --no-cache-dir              Disable the cache.
  --disable-pip-version-check
                              Don't periodically check PyPI to determine
                              whether a new version of pip is available for
                              download. Implied with --no-index.
  --no-color                  Suppress colored output.
  --no-python-version-warning
                              Silence deprecation warnings for upcoming
                              unsupported Pythons.
  --use-feature      Enable new functionality, that may be backward
                              incompatible.
  --use-deprecated   Enable deprecated functionality, that will be
                              removed in the future.

関連ページ