วันอังคารที่ 12 มกราคม พ.ศ. 2564

python check process running

ถ้าเราต้องการตรวจสอบว่า โปรแกรมที่เราเขียนยังทำงานอยู่ไหม ทำดังนี้

 ลง psutil

 pip install psutil

 

 

สร้างไฟล์ checkMyProgram.py ที่ /home/pi เพื่อเช็คการทำงานของโปรแกรมที่ชื่อว่า MyProgram

import psutil
import datetime

def checkIfProcessRunning(processName):
    '''
    Check if there is any running process that contains the given name processName.
    '''
    #Iterate over the all the running process
    for proc in psutil.process_iter():
        try:
            # Check if process name contains the given name string.
            if processName.lower() in proc.name().lower():
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;



time = datetime.datetime.now()
fileName = "/home/pi/TagAgent/MyProgramLog" + time.strftime("%Y-%m-%d_%H") +".txt"

d = open(fileName, "a")
d.write(time.strftime("%H:%M:%S"))

if checkIfProcessRunning('MyProgram'):
    d.write(" MyProgram still alive!\n")
    d.close()
else:
    d.write(" Not found MyProgram!\n")
    d.close()


หลังจากการรัน checkMyProgram.py ด้วยคำสั่ง python checkMyProgram.py แล้ว จะมีการสร้างไฟล์ที่ชื่อว่า /home/pi/MyProgramLogตามด้วยปีเดือนวันชั่วโมง.txt ขึ้นมา

เพื่อให้มาเปิดดูในภายหลังว่า โปรแกรม MyProgram ยังทำงานอยู่หรือไม่ หรือว่าตายไปตั้งแต่ช่วงไหน


ถ้าเราต้องการเช็คทุก 1 นาที ก็ให้ใช้ crontab เข้าช่วย

crontab -e

เพิ่มเข้าไปบรรทัดสุดท้าย

* * * * * python /home/pi/checkMyProgram.py


https://thispointer.com/python-check-if-a-process-is-running-by-name-and-find-its-process-id-pid/ 

https://www.programiz.com/python-programming/datetime/current-time

https://www.w3schools.com/python/python_datetime.asp

วันศุกร์ที่ 25 ธันวาคม พ.ศ. 2563

sqlite3 rpi4 Qt

ต้องลง sqlite3 ก่อน

sudo apt-get update
sudo apt-get install sqlite3

จากนั้นลง sqlitebrowser ตาม
sudo apt-get install sqlitebrowser

สร้าง database ดังนี้

$ sqlite3 test.db
sqlite> CREATE TABLE people(ids integer primary key, name text);
sqlite> .quit

 

ต่อมา จะเขียนโปรแกรมใน Qt ให้สามารถติดต่อกับ Database ได้ 

เมื่อเปิดโปรแกรม Qt ขึ้นมา ให้เปิด ไฟล์.pro และพิมพ์เพิ่มเข้าไปแบบนี้

 QT += sql

คลิกขวาที่โปรเจค แล้วกด Run Qmake


 คลิกขวาที่โปรเจค เพื่อเพิ่ม class


ตั้งชื่อ class ว่า dbmanager

เมื่อสร้าง class เสร็จแล้ว เราจะได้ dbmanager.h และ dbmanager.cpp มา

ในไฟล์ dbmanager.h ให้เขียน code ดังนี้

ส่วนไฟล์ dbmanager.cpp ให้เขียนดังนี้

ในไฟล์ main.cpp ให้เพิ่ม code ดังนี้
จากนั้นกด Run ก็จะเห็นว่ามีการสร้าง database ขึ้นมาแล้ว ในโฟลเดอร์ที่ระบุไว้

ถ้าหากเราต้องการฟังก์ชั่นอื่นๆที่สามารถจัดการกับ database ได้ ให้ทำดังนี้

1.เพิ่มใน dbmanager.h ในที่นี้ผมจะเพิ่มฟังก์ชั่นที่ชื่อว่า AddRecord โดยรับค่า QString เข้าไป

2.เพิ่มใน dbmanager.cpp

แล้วกด Run จะเห็นได้ว่า database ได้ถูกเพิ่มชื่อ Niran เข้าไปแล้ว โดยสามารถเปิดดูได้ใน sqlitebrowser ก็ได้

แก้ไข code ให้เช็คก่อนว่ามีชื่ออยู่แล้วหรือไม่

เมื่อกด Run จะเห็นได้ว่า มีการแจ้งว่า "Person exist"

และเมื่อเปลี่ยนชื่อใหม่เข้าไป ก็จะมีเพิ่มเข้าไปใน database.

จอบอ. 


ที่มา

https://scienceprog.com/powerful-open-source-sqlite-manager-for-raspberry-pi/ 

http://katecpp.github.io/sqlite-with-qt/



วันอังคารที่ 22 ธันวาคม พ.ศ. 2563

qt json

 วันนี้มีโอกาสใช้ json เป็นฐานข้อมูล

ก็เหมือนเดิม อาจารย์ google ช่วยได้

ต้องออกแบบหน้าตาของ json  ก่อน ว่าจะเก็บข้อมูลยังไง โดยผมกำหนดแบบนี้

ไฟล์ชื่อ  test_trans.json

{
    "HoseDelivery": [
        {
            "hose_num": 1,
            "id": 1
        },
        {
            "hose_num": 1,
            "id": 5
        }
    ]
}


เริ่มเขียน code

#include <QCoreApplication>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString val;
    QFile file;

//========================== read json file =====================
    file.setFileName("/home/pi/sourcecode/test_json/test_trans.json");
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    val = file.readAll();
    file.close();
    QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
    QJsonObject sett2 = d.object();
    qDebug() << sett2;

    QJsonArray value = sett2["hose_delivery"].toArray();  // get data in hose_delivery 

    qDebug() << value;

    QJsonObject item = value[1].toObject();                        // make QJsonValue to Object
    qDebug() << item;

    QJsonValue text1 = item.value(QString("money"));
    qDebug() << text1;
    qDebug() << QString::number(text1.toDouble());

//============================ write json file ============================
    file.setFileName("/home/pi/sourcecode/test_json/test_trans2.json");
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    val = file.readAll();

    QJsonDocument doc = QJsonDocument::fromJson(val.toUtf8());
    QJsonObject abc = doc.object();
    qDebug() << abc;

    QJsonArray valuez = abc["HoseDelivery"].toArray();  // get data in hose_delivery 

    qDebug() << valuez;


    QJsonObject hose_delivery;
    hose_delivery.insert("id",5);
    hose_delivery.insert("hose_num",1);
    valuez.append(hose_delivery);
    qDebug() << valuez;
    abc.insert("HoseDelivery",valuez);

    file.resize(0);
    file.write(QJsonDocument(abc).toJson(QJsonDocument::Indented));
    file.close();   // Close file

    return a.exec();
}



ที่มา

https://www.programmersought.com/article/2411597093/

วันอาทิตย์ที่ 20 ธันวาคม พ.ศ. 2563

Arduino VSCode

 วันนี้ลองใช้ Visual Studio Code (VSCode) ในการใช้งานกับ Arduino

ใช้งานครั้งแรกจะงงหน่อย จะสร้างโปรเจคยังไง เปิดไฟล์ยังไง เปิดไม่ถูก ต้องดูใน you tube ก่อน

เริ่มกันเลยดีกว่า

เมื่อเปิด vscode ขึ้นมาแล้ว ต้องลง extension arduino ก่อน

พอลงเสร็จ ก็จะสามารถใช้งาน arduino ได้

เริ่มต้นด้วยการคลิกไปที่ file, open folder, เลือก folder ที่เราต้องการเก็บ project ของเรา เราสามารถสร้างใหม่ได้

เมื่อเลือก folder เสร็จแล้ว ให้ทำการคลิก New file

แล้วก็ตั้งชื่อไฟล์ โดยให้นามสกุลเป็น .ino เพื่อให้ vscode รู้ว่าเรากำลังจะทำ Arduino

ให้เราเสียบสาย usb จากคอมพิวเตอร์ของเรา กับบอร์ด Arduino

จากนั้นก็เลือก Board type


เลือก Serial port

เริ่มเขียน code ได้

เมื่อเขียน code เสร็จแล้ว ให้กด Verify

แล้ว Verify ผ่าน ก็กด Upload


ถ้าเราต้องการ Debug ผ่าน Serial port ให้กดปุ่มนี้

แล้วก็เลือก Baud rate ให้ถูกต้องตามที่เราเขียนโปรแกรมเอาไว้

จอบอ.


ที่มา

https://www.youtube.com/watch?v=3vV_53Os9FU






วันอาทิตย์ที่ 22 พฤศจิกายน พ.ศ. 2563

ESP32 get public ip

พอดีว่า มีงานที่ต้องหา public ip เพื่อให้เครื่องข้างนอก สามารถ remote เข้ามาได้

มี code ดังนี้

https://github.com/kongimi/getPublicIP.git

 

ที่มา

https://www.esp8266.com/viewtopic.php?f=6&t=12782

วันศุกร์ที่ 16 ตุลาคม พ.ศ. 2563

Arduino Unique ID, Serial number

วันนี้ได้มีโอกาสทำ arduino และ ต้องการจะอ่าน serial number จาก arduino

เริ่มต้นจาก google ค้นหาคำว่า arduino serial number และได้พบว่า arduino มันไม่มี serial number แต่มันจะมีอะไรบางอย่างที่ใช้แทนได้ เขาเรียกว่า "UniqueID" และเขาก็ได้ทำ library มาให้เรา download เรียบร้อย

code ตัวอย่างการใช้งานครับ

#include <ArduinoUniqueID.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(19200,SERIAL_8N1);
  UniqueIDdump(Serial);
}

void loop() {
  // put your main code here, to run repeatedly:

}

 

download library

 

 

ที่มา

https://www.thethingsnetwork.org/forum/t/arduino-has-a-unique-id/21415

https://github.com/ricaun/ArduinoUniqueID

http://ww1.microchip.com/downloads/en/DeviceDoc/40001906A.pdf

วันจันทร์ที่ 28 กันยายน พ.ศ. 2563

rpi4b rotate 270 degree

สวัสดีครับ

วันนี้ได้ทำ LCD 7" touch screen ตัวนี้

 


และต้องทำให้หมุน 270 องศา มีวิธีการดังนี้

1.sudo nano /boot/config.txt

2.เพิ่ม display_rotate=3 บนบรรทัดแรกสุด

3.แก้ไขจาก dtoverlay=vc4-fkms-v3d ให้เป็น #dtoverlay=vc4-fkms-v3d

4.control+o, control+x

 

ยังไม่จบ เราต้องปรับ touch screen ให้หมุนตามหน้าจอ ดังนี้

1.sudo apt-get install xserver-xorg-input-libinput

2.sudo mkdir /etc/X11/xorg.conf.d

3.sudo cp /usr/share/X11/xorg.conf.d/40-libinput.conf /etc/X11/xorg.conf.d/

4. sudo nano /etc/X11/xorg.conf.d/40-libinput.conf

5.ให้มองหาคำว่า "touchscreen" แล้วเพิ่มบรรทัดนี้เข้าไป

Option "CalibrationMatrix" "0 -1 1 1 0 0 0 0 1" 

6.control+o, control+x

7.sudo reboot

เท่านี้เราก็สามารถหมุนหน้าจอให้เป็น 270 องศา และ touch screen ได้อย่างถูกต้องแล้ว 


ถ้าต้องการปรับหมุนหน้าจอเป็นแบบอื่น

https://www.waveshare.com/w/index.php?search=calibrationmatrix&title=Special%3ASearch&fulltext=Search

สำหรับ 90 องศา ให้ดูตามด้านล่าง

display_rotate=1 #1:90;2: 180; 3: 270
Option "CalibrationMatrix" "0 1 0 -1 0 1 0 0 1"



ที่มา

https://www.waveshare.com/wiki/7inch_HDMI_LCD_(B)


วันศุกร์ที่ 22 พฤษภาคม พ.ศ. 2563

USB QR Code Reader RaspberryPi4

เนื่องจากได้รับงานด่วนๆ ให้ทดลอง usb qr-code reader กับ raspberry pi4
จึงได้ซื้อของยี่ห้อ waveshare มา
สามารถซื้อได้จากที่นี่
https://www.waveshare.com/barcode-scanner-module.htm

คู่มือ ตามนี้
https://www.waveshare.com/w/upload/archive/3/3c/20180623102926%21Barcode_Scanner_Module_User_Manual_EN.pdf

qr-code reader รุ่นนี้ สามารถอ่าน bar-code ได้ด้วย

สามารถใช้งานได้ 2 แบบ คือ แบบ usb และแบบ uart

ในที่นี้ผมเลือกใช้แบบ usb เพราะว่าหน้างาน อาจจะได้ใช้ qr-code reader 2 ตัวพร้อมกัน
และคนที่ติดตั้งก็ไม่ใช่เรา ดังนั้นต้องยืดหยุ่นให้มากที่สุดเท่าที่จะทำได้

เมื่อได้ของมาแล้ว ก็ไม่รอช้า เสียบเข้าช่อง usb ของ raspberrypi4 เลย
ตัว raspberrypi จะเห็น qr-code reader อยู่ที่ /dev/hidraw0
เราสามารถตรวจสอบว่า raspberrypi มองเห็นอุปกรณ์ตัวนี้ไหม โดยพิมพ์ ls /dev/hi* แล้วกด enter
เราสามารถเขียนโปรแกรมให้อ่านข้อมูลที่ได้จากการสแกนจากที่นี่


ซึ่งผมและทีมงานก็ได้พยายามหาข้อมูลจากอาจารย์ goo เหมือนเดิม จนไปเจอที่นี่
https://www.raspberrypi.org/forums/viewtopic.php?f=45&t=55100

ซึ่งมี code ให้อยู่ จึงได้ copy มา แล้วก็ทดสอบเลย
ก็ติดปัญหาบ้าง เช่น
1. code ที่เขาแปะไว้ คือใช้กับ python2 เราก็ต้องเรียกใช้ให้ถูกวิธี
2. code ที่ได้มา มีการ map ค่าที่ได้ ต่างกับ Hardware ที่เรามี ก็ต้องมา map ใหม่ ยุ่งยากเล็กน้อย

สุดท้ายแล้ว ก็ต้องปรับ code จนออกมาเป็นเวอร์ชั่นที่ใช้ได้ ดังนี้

import sys

hid = { 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm', 17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y', 29: 'z', 30: '!', 31: '@', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ', 45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':' , 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'  }
hid2 = { 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M', 17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y', 29: 'Z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ', 45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';' , 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'  }


fp = open('/dev/hidraw0', 'rb')
ss = ""
shift = False
done = False
d = 0
first_char = 0
while not done:
    ## Get the character from the HID
    buffer = fp.read(8)
    for c in buffer:
        d = d+1
        if c > 0:
            if int((c)) == 57:
                print ("Start/Stop Package")
            else:
                ##  40 is carriage return which signifies
                ##  we are done looking for characters
                if int((c)) == 40:
                    if shift:
                        ss += '3'
                    done = True
                    break;
                ##  If we are shifted then we have to
                ##  use the hid2 characters.
                if shift:
                    ## If it is a '2' then it is the shift key
                    if int((c)) == 32 :
                        ss += '#'
                        shift = False
                    ## if not a 2 then lookup the mapping
                    else:
                        if d == first_char+16:
                            ss+= '3'
                            shift = False
                            ss += hid2[int(c)]
                        else:
                            ss += hid[ int((c)) ]
                            shift = False
                ##  If we are not shifted then use
                ##  the hid characters
                else:
                    ## If it is a '2' then it is the shift key
                    if int((c)) == 32 :
                        shift = True
                        first_char = d
                    ## if not a 2 then lookup the mapping
                    else:
                        ss += hid2[ int((c)) ]
print (ss)


เมื่อ save โปรแกรมแล้ว ให้เปลี่ยน permission ด้วย
sudo chmod 766 ชื่อโปรแกรม.py

ตอนเรียกใช้ ให้เรียกใช้แบบนี้
sudo python3 ชื่อโปรแกรม.py

ต่อมา
เราต้องการ QR-Code ตัวอย่าง ในการอ่านข้อมูล ก็ให้หาเวปที่สร้าง QR-Code ได้ ซึ่งมีอยู่มากมาย
ยกตัวอย่างเช่น https://www.the-qrcode-generator.com/ หรือ
https://th.qr-code-generator.com/

เมื่อเราสร้าง QR-Code ได้แล้ว ก็ลอง scan ได้เลย
ค่าที่อ่านได้ จะต้องเหมือนกันกับที่เราสร้างในเวป









น่าจะเป็นประโยชน์ต่อผู้สนใจนะครับ