2025年3月6日木曜日

TODO案件

micro:bit :: spi for 外部SRAM

https://jhalfmoon.com/dbc/2021/08/04/%E3%83%96%E3%83%AD%E3%83%83%E3%82%AF%E3%82%92%E3%81%A4%E3%81%BF%E3%81%AA%E3%81%8C%E3%82%8930-bbc-microbit%E3%80%81512k-sram%E3%82%92spi%E6%8E%A5%E7%B6%9A/


----------------------------------------------------------------------


raspicow :: ble central and peripheral

raspicow :: mqtt

https://randomnerdtutorials.com/raspberry-pi-pico-w-mqtt-micropython/  

umqttt directoryをつくり以下にrobust.py,simple.pyを置く!ルートにはconfig.pyを!

raspicow :: nrf2401!

2025年3月4日火曜日

Raspberry pi pico w :: mqtt sub pub

https://mqttx.app/web-client で無料サーバに入る

https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.simple/umqtt/simple.py をumqtt.pyでインストした

ーーーーーーーサブスクライブ例ーーーーーーーーーーーーーーーーーーー

subscribe codeでLEDオンオフ成功! https://mqttx.app/web_clientを開くuser名は

適当でいいのでログインしてCONNECT 最初に{"message":"on"}などが入っていたら

"on"と書き直してpublishでled on,"off"でled offに成功した

from machine import Pin

import time

from umqtt import MQTTClient

import ubinascii

import machine

import micropython

import network

import gc


#led alive check

led_pin = Pin(15, Pin.OUT)

led_pin.value(1)

time.sleep(5)

led_pin.value(0)


gc.collect()


ssid = 'HUAWEI@nova@lite@3+'

password = '99991111'

mqtt_server = 'broker.emqx.io'  #Replace with your MQTT Broker IP


client_id = ubinascii.hexlify(machine.unique_id()) #ユニークな名でログインのため

topic_sub = b'rpi_pico_w/test_sub' # なかったら作る(publish欄で)


station = network.WLAN(network.STA_IF)

station.active(True)

station.connect(ssid, password)

while station.isconnected() == False:

  pass

print('Connection successful')

print(station.ifconfig())


def sub_cb(topic, msg): #このcb(callback)でやりたい仕事を仕分ける

  print ('Received Message %s from topic %s' %(msg, topic))

  if msg==b'"on"':

    led_pin.value(1)

  elif msg==b'"off"':

    led_pin.value(0)


def connect_and_subscribe():

  global client_id, mqtt_server, topic_sub

  client = MQTTClient(client_id, mqtt_server)

  client.set_callback(sub_cb)

  client.connect()

  client.subscribe(topic_sub)

  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))

  return client


def restart_and_reconnect():

  print('Failed to connect to MQTT broker. Reconnecting...')

  time.sleep(10)

  machine.reset()


try:

  client = connect_and_subscribe()

except OSError as e:    # もしこれ起こったら

  restart_and_reconnect() # 上記でmachine.resetがかかるのでOK

  

while True:

  try:

       new_msg = client.check_msg()

       time.sleep(10)

  except OSError as e:

    restart_and_reconnect

ーーーーー以下はパブリッシュ例ーーーーーーーーーーーーーーーーーーーーーーーーーー

https://mqttx.app/web-client#/recent_connections/32a3a13e-7aef-4224-8ddc-6226007aa6caでtest/topic1をつくる

https://mqttx.app/web-clienthttps://tech-and-investment.com/raspberrypi-picow-6-mqtt/ にある以下のコードに成功


import time
import network
from umqtt import MQTTClient
import machine
from picozero import pico_temp_sensor,

import sys

#
# Wi-Fi ルーターのSSIDとパスワードです。
# お使いの設定に書き換えてください。
#
ssid = 'NAME OF YOUR WIFI NETWORK'
password = 'YOUR SECRET PASSWORD'

#
#  Wi-Fiに接続する関数です
#
def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
        
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        time.sleep(1)
    ip = wlan.ifconfig()[0]
    print(f'Connected on {ip}')
    return ip

#
# 受信(Subscribe)したメッセージを表示する関数です
#
def printMessage(topic, message):
    
    # 受信データはbytes型なのでUTF-8の文字列に変換してから表示します
    print("topic:" + topic.decode("utf-8") )
    print("message:" + message.decode("utf-8") )

#
# メインの処理部です
#

# ブローカーのIPやトピック名を定義します。
mqttBroker = '192.168.10.9'
myId = 'esu'
topic= b'test/topic1'

# MQTTのオブジェクト(変数)を定義します
client = MQTTClient(myId, mqttBroker, keepalive=3600)

# 受信(Subscribe)した時に呼ぶ関数を設定します
client.set_callback(printMessage)

# Wi-Fiに接続します
connect()

try:
    # ブローカーに接続します
    client.connect()
    # Subscribeするトピックを登録します。(注:接続前はエラー)
    client.subscribe(topic)
    
except:
    # ブローカーへの接続に失敗した場合は、プログラムを終了します
    print("Could not connect to mqtt server.")
    sys.exit()
    
print("mqqtt connect done ")

#
# 温度センサの情報を3秒ごとにPublishします
#
while True:
    # Pico W 本体の温度情報を取得します
    temp =  pico_temp_sensor.temp

    # 送信(Publish)用のメッセージに温度を代入します
    msg = " \"temp\":" + str(temp)

    # 送信(Publish)します。
    client.publish(topic, msg)

    # ブローカーからのPublishをチェックします。
    client.check_msg()
    # test/topic1に"on"を書くとmessage:onとでる!
    time.sleep(3)

2025年3月2日日曜日

Raspberry pi Python :: subprocess / gmail of image or text

 

import subprocess
 
cmd = "ls -l"
subprocess.call(cmd.split())

上記のCMDを任意のシェル命令に変更可能(libcameraetc)

----------------------------------------------------------------------------

https://mychma.com/python-gmail/334/#google_vignette が画像をおくる版

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

https://note.com/noa813/n/nde0116fcb03f のとうりにapp pwd作成して成功

my_gmail_account.py is below ::

#ご自身のgmailアドレス account = "********@gmail.com" #アプリパスワード(16桁) password = "****************"

gmail_send.py is below ::

import smtplib, ssl

from email.mime.text import MIMEText

#上で作成したpyファイルから、account情報を読み込みます

import my_gmail_account as gmail


# 送信先のアドレスを登録します

send_address = "*****@gmail.com"


# メインの関数になります

def send_test_email():

  msg = make_mime_text(

    mail_to = send_address,

    subject = "テスト送信",

    body = "Pythonでのメール送信です"

  )

  send_gmail(msg)


# 件名、送信先アドレス、本文を渡す関数です

def make_mime_text(mail_to, subject, body):

  msg = MIMEText(body, "html")

  msg["Subject"] = subject

  msg["To"] = mail_to

  msg["From"] = gmail.account

  return msg


# smtp経由でメール送信する関数です

def send_gmail(msg):

  server = smtplib.SMTP_SSL(

    "smtp.gmail.com", 465,

    context = ssl.create_default_context())

  server.set_debuglevel(0)

  server.login(gmail.account, gmail.password)

  server.send_message(msg)


# うまくいったら”OK”と表示させます

if __name__ == "__main__":

  send_test_email()

  print("ok")



2025年2月26日水曜日

ESP8266 pedia

 WEMOS/ESP01を所有するが前者がピンが多く便利でほぼ一択状態

DHt11,LCD1602はRANDOMNERD TUTORIALでいけた

SSD1306はARDUINO-IDEサンプルのGRAPHICはいけたが文字があかん

https://github.com/datasith/Ai_Ardulib_SSD1306/tree/mainをインストして成功

#include <Wire.h>

#include "ACROBOTIC_SSD1306.h" // これが重要!

void setup()

{

  Wire.begin();

  oled.init();                      // Initialze SSD1306 OLED display

  oled.clearDisplay();              // Clear screen

  oled.setTextXY(0,0);              // Set cursor position, start of line 0

  oled.putString("ACROBOTIC");

  oled.setTextXY(1,0);              // Set cursor position, start of line 1

  oled.putString("industries");

  oled.setTextXY(2,0);              // Set cursor position, start of line 2

  oled.putString("Pasadena,");

  oled.setTextXY(2,10);             // Set cursor position, line 2 10th character

  oled.putString("CA");

}

void loop()

{

}

2025年2月23日日曜日

mqtt pedia :: Raspi,ESP32,ESP8266,

https://mqttx.app/web-client#/recent_connections/32a3a13e-7aef-4224-8ddc-6226007aa6ca でGUI版がうごく

-------------------mqttx / mosquito client-------------------https://qiita.com/emqx_japan/items/634a5b91f0b760664711 にある

mqttx client for desktop::arm64version get and click deb file for install success!

cf 

https://qiita.com/ekzemplaro/items/168a4a98fe65aa24abb9 でbroker.emqx.ioに

sample/imageTopicをsubしておいて(mqttxにて)mosquitto.shでpubして成功

----------------------------------------------------------------

https://www.emqx.com/ja/blog/use-mqtt-with-raspberry-pi より

# subscriber.py

from gpiozero import LED # もらったメッセージでLED操作する

from time import sleep,time #そのため、この2行必要

import paho.mqtt.client as mqtt

led = LED(17)


def on_connect(client, userdata, flags, rc):

    print(f"Connected with result code {rc}")

    # Subscribe, which need to put into on_connect

    # If reconnect after losing the connection with the broker, 

 # it will continue to subscribe to the raspberry/topic topic

    client.subscribe("raspberry/topic")


# The callback function, it will be triggered when receiving messages

def on_message(client, userdata, msg):

    print(f"{msg.topic} {msg.payload}")

    if msg.payload == b'4':

        led.on()

        sleep(10)

        led.off()

client = mqtt.Client()

client.on_connect = on_connect

client.on_message = on_message

# Set the will message, when the Raspberry Pi is powered off, or the network is interrupted abnormally, it will send the will message to other clients

client.will_set('rasp', b'{"status": "Off"}')

# Create connection, the three parameters are broker address, broker port number, and keep-alive time respectively

client.connect("broker.emqx.io", 1883, 60)

# Set the network loop blocking, it will not actively end the program before calling disconnect() or the program crash

client.loop_forever()

上記を起動しておいて、下記を実行するとサブにでてくる

# publish.py

import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")

    # Send a message to the raspberry/topic every 1 second, 5 times in a row
    for i in range(5):
        # The four parameters are topic, sending content, QoS and whether retaining the message respectively
        client.publish('raspberry/topic', payload=i, qos=0, retain=False)
        print(f"send {i} to raspberry/topic")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)

client.loop_forever()

-------mqtt and esp32------------------------------------

https://diysmartmatter.com/archives/355 にてモスキートクライアントをインスト

https://qiita.com/koichi_baseball/items/8fa9e0bdbe6d0aebe57d also refferd!

broker.emqx.ioにかえて成功 -t # でなく -t test/# -vだった 上記パブサブ成功

https://qiita.com/emqx_japan/items/6ddf82d90c506312d875 をインストして

mosquitto_sub -h broker.emqx.io -t emqx/esp32 -v でサブモードで

こんにちは、ESP32です ^^ うけとれた

mosquitto_pub -h broker.emqx.io -t emqx/esp32  -m goodbye でパブモードで

goodbyeおくれた

-------------mqtt and esp8266------------------------------------------------

  https://qiita.com/emqx_japan/items/f74e9d108c7ecaa4f2ddを改変して成功

公開emqxブローカーへのコネクションはどんな名前でもログインOK

esp8266/ledなどのトピックをつくる!mqttx画面でplain textモードになっていること!

#include <ESP8266WiFi.h>

#include <PubSubClient.h>


// GPIO 5 D1

#define LED 5


// WiFi

const char *ssid = "HUAWEI@nova@lite@3+"; // WiFi名を入力

const char *password = "99991111";  // WiFiパスワードを入力


// MQTTブローカー

const char *mqtt_broker = "broker.emqx.io";

const char *topic = "esp8266/led";

const char *mqtt_username = "emqx";

const char *mqtt_password = "public";

const int mqtt_port = 1883;


bool ledState = false;


WiFiClient espClient;

PubSubClient client(espClient);


void setup() {

    

    // ソフトウェアシリアルのボーレートを115200に設定;

    Serial.begin(115200);

    delay(1000); // 安定性のために遅延


    // WiFiネットワークに接続

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {

        delay(500);

        Serial.println("WiFiに接続中...");

    }

    Serial.println("WiFiネットワークに接続しました");


    // LEDピンを出力として設定

    pinMode(LED, OUTPUT);

    digitalWrite(LED,HIGH);

    delay(1000);

    digitalWrite(LED, LOW);  // 最初はLEDを消灯


    // MQTTブローカーに接続

    client.setServer(mqtt_broker, mqtt_port);

    client.setCallback(callback);

    while (!client.connected()) {

        String client_id = "esp8266-client-";

        client_id += String(WiFi.macAddress());

        Serial.printf("クライアント %s が公開MQTTブローカーに接続しています\n", client_id.c_str());

        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {

            Serial.println("公開EMQX MQTTブローカーに接続しました");

        } else {

            Serial.print("失敗しました ステート ");

            Serial.print(client.state());

            delay(2000);

        }

    }


    // メッセージの公開と購読

    client.publish(topic, "hello emqx");

    client.subscribe(topic);

}


void callback(char *topic, byte *payload, unsigned int length) {

    Serial.print("トピックにメッセージが到着: ");

    Serial.println(topic);

    Serial.print("メッセージ: ");

    String message;

    for (int i = 0; i < length; i++) {

        message += (char) payload[i];  // byteをStringに変換

    }

    Serial.println(message);

    if (message.indexOf("on")==1 && !ledState) { // replaced by me

        Serial.println("ledon");

        digitalWrite(LED, HIGH);  // LEDを点灯

        ledState = true;

    }

    if (message.indexOf("off")==1 && ledState) {   // replaced by me

          Serial.println("ledoff");

        digitalWrite(LED, LOW); // LEDを消灯

        ledState = false;

    }

    Serial.println();

    Serial.println("-----------------------");

}


void loop() {

    client.loop();

    delay(100); // ループの各反復で短い遅延

}

2025年2月16日日曜日

Raspberry pi :: video / libcamera / gpiozero

 

zero は2になっても2GしかWifi未対応 3a+は5Gも対応している

install時のusキーボード配列は、起動後にraspi-configでjpキーボードに変更できた

https://mail.google.com/mail/u/0/?tab=rm&ogbl#inbox 

gpiozero で 直感的にデバイスを制御する



https://ponkichi.blog/mjpg-streamer/ これも参考にして以下を

https://raspi-katsuyou.com/index.php/2020/06/30/11/10/44/644/
 これはブルーバックスと同じだが、ブルーバックスは
 全コマンドを/opt以下にmvしたので、10-02-stream.shを使用!

単純にヴィデオクリップするのならguvcviewがいい パイカメラの場合はv4l2が必要?
USBウェブカメラ(マイク付き)なら録音もできるからベターかも

https://gihyo.jp/admin/serial/01/ubuntu-recipe/0303

https://mekou.com/linux-magazine/web%e3%82%ab%e3%83%a1%e3%83%a9%e6%92%ae%e5%bd%b1guvcview/
以上2個は同上 ----------------------------------------------
Raspberry Pi(ラズパイ)のOSが32ビットか64ビットかを確認するには、コマンド「lsb_release -a」を使用します
【確認方法】
  1. コマンド「lsb_release -a」を実行します。
また、OSが対応するbitを確認するには「getconf LONG_BIT」を使用

legacyOS::bullseye 32bitにはraspistillが入っていたが以下をトライして成功

RasTech Raspberry Pi カメラモジュール Raspberry Pi カメラ 500万画素 Raspberry Pi 5/4B/3B+/3B/2B+/ZERO1.3/ZERO 2W/ZERO W for Raspberry Pi クリアスタンド*1、リボンケーブル*3 をもちいるため

https://qiita.com/yamatonori/items/019d05a19b206cbcf571 
によればOV5647センサーでLIBCAMERAを使う準備をして成功 VNCでも動いた

https://hellobreak.net/raspberry-pi-bullseye-libcamera/ に説明が詳しい

-----------------about gpiozero---------------------------------------------------------------------------------------------

https://gpiozero.readthedocs.io/en/latest/recipes.html#led 英語
https://www.denshi.club/ 日本語