หน้าเว็บ

แสดงบทความที่มีป้ายกำกับ Raspberry PI แสดงบทความทั้งหมด
แสดงบทความที่มีป้ายกำกับ Raspberry PI แสดงบทความทั้งหมด

วันอังคารที่ 27 ตุลาคม พ.ศ. 2563

Pi : Pi moition camera notification Line Nofity API

 Pi : Pi moition camera notification Line Nofity API
ติดตั้ง motion
https://intranet.sci.com/blog.php?u=281&b=1667

เพิ่มเติม แก้ Motion ให้ไปเรียกใช้งาน ไฟล์ python ที่สร้างขึ้นเมื่อมีการสร้าง Video

  1. nana /etc/motion/motion.conf

แก้ตรง
on_movie_start python3 /home/pi/line.py


Code pyton ส่ง Line
http://intranet.sci.com/blog.php?u=281&b=1809

Code สำเร็จ
  1. import requests, json
  2. import urllib.parse
  3. import sys
  4.  
  5. import glob
  6. import os
  7. import time
  8.  
  9. LINE_ACCESS_TOKEN = "XXXXXXX"
  10.  
  11. URL_LINE = "https://notify-api.line.me/api/notify"
  12.  
  13. def line_text(message):
  14.     msg = urllib.parse.urlencode({"message":message})
  15.     LINE_HEADERS = {'Content-Type':'application/x-www-form-urlencoded',"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  16.     session = requests.Session()
  17.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, data=msg)
  18.     print(session_post.text)
  19.  
  20. def line_pic(message, path_file):
  21.     file_img = {'imageFile': open(path_file, 'rb')}
  22.     msg = ({'message': message})
  23.     LINE_HEADERS = {"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  24.     session = requests.Session()
  25.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, files=file_img, data=msg)
  26.     print(session_post.text)
  27.  
  28. list_of_files = glob.glob('/home/pi/Monitor/*.jpg')
  29. latest_file = max(list_of_files, key=os.path.getctime)
  30. #print(latest_file)
  31. text_send = "Motion Detect OD."
  32. line_pic(text_send, latest_file)
  33.  
  34. #//// Delete All File In Folder Monitor ////#
  35. parth = "/home/pi/Monitor/"
  36. for i in os.listdir ( parth ):
  37.     os.remove(parth+i)

Line : Python ส่งรูปเข้า Line API

 Line : Python ส่งรูปเข้า Line API
โปรแกรมที่ต้องใช้ ในเครื่อง rasberry pi
- python 3 ขึ้นไป
- ติดตั้ง

  1. pip install requests

- ติดตั้ง pip
  1. wget "https://bootstrap.pypa.io/get-pip.py"
  2. sudo python get-pip.py


1. เปิดใช้งาน Token ที่ https://notify-bot.line.me/
สามารถทำเป็น User หรือ ทำเป็น Group ก็ได้

*** สำคัญต้องเอา LINE Notify เข้าไปใน Group ด้วย ถึงจะส่งข้อความได้ ***

2. สร้าง Code python line.py
XXXX คือ Token ที่ได้จากข้อ 1.
Code
  1. import requests, json
  2. import urllib.parse
  3. import sys
  4.  
  5. LINE_ACCESS_TOKEN = "XXXX" #Use Token Or Group Token https://notify-bot.line.me/
  6.  
  7. URL_LINE = "https://notify-api.line.me/api/notify"
  8.  
  9. def line_text(message):
  10.     msg = urllib.parse.urlencode({"message":message})
  11.     LINE_HEADERS = {'Content-Type':'application/x-www-form-urlencoded',"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  12.     session = requests.Session()
  13.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, data=msg)
  14.     print(session_post.text)
  15.  
  16. def line_pic(message, path_file):
  17.     file_img = {'imageFile': open(path_file, 'rb')}
  18.     msg = ({'message': message})
  19.     LINE_HEADERS = {"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  20.     session = requests.Session()
  21.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, files=file_img, data=msg)
  22.     print(session_post.text)
  23.  
  24. if __name__ == "__main__":
  25.     if len(sys.argv) < 3:
  26.         # <Linux>
  27.         # python line.py "Test"
  28.         line_text(sys.argv[1])
  29.     else:
  30.         # <Linux>
  31.         # python line.py "Test" "/home/pi/test.jpg"
  32.         line_pic(sys.argv[1], sys.argv[2])


3. ทดลองส่งข้อความ
  1. python3 line_group.py "พบการเคลื่อนไหว"

จะมีข้อความแจ้ง
{"status":200,"message":"ok"}

และมีข้อความส่งไป Line

4. ส่งรูปใช้คำสั่ง
  1. python3 line.py "พบการเคลื่อนไหว" "/home/pi/3923-7.jpg"


ส่วนตัว Line Bot จะส่งได้เฉพาะรูปที่ผ่าน Link และต้องเป็น https เมื่อรูปถูกลบหรือเปลี่ยนชื่อ Line จะไม่สามารถแสดงผลรูป
ข้อจำกับ Line notify ส่งได้เดือนละ 1000 ครั้ง
https://notify-bot.line.me/doc/en/

ตัวอย่าง
https://maker.goisgo.net/raspberry-pi-w ... ne-notice/
https://medium.com/@dome.soda125/%E0%B8 ... 8ce98f0bd6
https://medium.com/dolab/blog-7-line-no ... 9724796428
https://engineering.linecorp.com/en/blo ... ad-images/

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

Pi : Pi moition camera notification Line Nofity API

 Pi : Pi moition camera notification Line Nofity API
ติดตั้ง motion
https://porpramarn.blogspot.com/2019/02/pi-pi-camera-motion.html

เพิ่มเติม แก้ Motion ให้ไปเรียกใช้งาน ไฟล์ python ที่สร้างขึ้นเมื่อมีการสร้าง Video

  1. nana /etc/motion/motion.conf
แก้ตรง
on_movie_start python3 /home/pi/line.py


Code python ส่ง Line
https://porpramarn.blogspot.com/2020/09/line-python-line-api-notify.html

Code สำเร็จ

  1. import requests, json
  2. import urllib.parse
  3. import sys
  4.  
  5. import glob
  6. import os
  7. import time
  8.  
  9. LINE_ACCESS_TOKEN = "XXXXXXX"
  10.  
  11. URL_LINE = "https://notify-api.line.me/api/notify"
  12.  
  13. def line_text(message):
  14.     msg = urllib.parse.urlencode({"message":message})
  15.     LINE_HEADERS = {'Content-Type':'application/x-www-form-urlencoded',"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  16.     session = requests.Session()
  17.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, data=msg)
  18.     print(session_post.text)
  19.  
  20. def line_pic(message, path_file):
  21.     file_img = {'imageFile': open(path_file, 'rb')}
  22.     msg = ({'message': message})
  23.     LINE_HEADERS = {"Authorization":"Bearer "+LINE_ACCESS_TOKEN}
  24.     session = requests.Session()
  25.     session_post = session.post(URL_LINE, headers=LINE_HEADERS, files=file_img, data=msg)
  26.     print(session_post.text)
  27.  
  28. list_of_files = glob.glob('/home/pi/Monitor/*.jpg')
  29. latest_file = max(list_of_files, key=os.path.getctime)
  30. #print(latest_file)
  31. text_send = "Motion Detect OD."
  32. line_pic(text_send, latest_file)
  33.  
  34. #//// Delete All File In Folder Monitor ////#
  35. parth = "/home/pi/Monitor/"
  36. for i in os.listdir ( parth ):
  37.     os.remove(parth+i)

วันพฤหัสบดีที่ 11 มิถุนายน พ.ศ. 2563

PI : Pi zero ตรวจวัดความร้อนและวัดการสั่น

PI : Pi zero ตรวจวัดความร้อนและวัดการสั่น
1. ติดตั้ง PI และ Set Headless
https://intranet.sci.com/blog.php?u=281&b=1770
boot เข้า Pi update upgrade set ntp

2. Fix ip wifi for pi zero
  1. nano /etc/dhcpcd.conf

Add
interface wlan0
static ip_address=192.168.0.164/24
static routers=192.168.0.2
static domain_name_servers=192.168.0.2 8.8.8.8

แล้ว Reboot เครื่อง


การต่อวัดอุณหภูมิ mlx90614
1. วัดอุณหภูมิ mlx90614 4 ขา ใช้ ไฟ 5V GNC SCL SDA

2. เปิดโหมด I2C
  1. raspi-config


http://domoticx.com/raspberry-pi-i2c-bus-gebruiken/
3. เปิดดูไฟล์ Boot config ว่า
  1. nano /boot/config.txt

ถูกเปิดแล้วหรือยัง
dtparam=i2c_arm=on
dtparam=spi=on

4. Download
https://github.com/mcauser/micropython-mlx90614
micropython-mlx90614-master(1).zip
(55.74 KB) Not downloaded yet

5. ติดตั้ง Uzip และแตกไฟล์
  1. apt-get install unzip

6. เข้าไปใน Folder ที่แตกได้ ติดตั้งโปรแกรม
  1. python setup.py install

7. เขียน Code
  1. nano Tmp_Sensor.py
  1. import smbus
  2.  
  3. class MLX90614():
  4.  
  5.     MLX90614_RAWIR1=0x04
  6.     MLX90614_RAWIR2=0x05
  7.     MLX90614_TA=0x06
  8.     MLX90614_TOBJ1=0x07
  9.     MLX90614_TOBJ2=0x08
  10.  
  11.     MLX90614_TOMAX=0x20
  12.     MLX90614_TOMIN=0x21
  13.     MLX90614_PWMCTRL=0x22
  14.     MLX90614_TARANGE=0x23
  15.     MLX90614_EMISS=0x24
  16.     MLX90614_CONFIG=0x25
  17.     MLX90614_ADDR=0x0E
  18.     MLX90614_ID1=0x3C
  19.     MLX90614_ID2=0x3D
  20.     MLX90614_ID3=0x3E
  21.     MLX90614_ID4=0x3F
  22.  
  23.     def __init__(self, address=0x5a, bus_num=1):
  24.         self.bus_num = bus_num
  25.         self.address = address
  26.         self.bus = smbus.SMBus(bus=bus_num)
  27.  
  28.     def read_reg(self, reg_addr):
  29.         return self.bus.read_word_data(self.address, reg_addr)
  30.  
  31.     def data_to_temp(self, data):
  32.         temp = (data*0.02) - 273.15
  33.         return temp
  34.  
  35.     #def get_amb_temp(self):
  36.     #    data = self.read_reg(self.MLX90614_TA)
  37.     #    return self.data_to_temp(data)
  38.  
  39.     def get_obj_temp(self):
  40.         data = self.read_reg(self.MLX90614_TOBJ1)
  41.         return self.data_to_temp(data)
  42.  
  43. if __name__ == "__main__":
  44.     sensor = MLX90614()
  45.     #print(sensor.get_amb_temp())
  46.     print(sensor.get_obj_temp())


http://domoticx.com/raspberry-pi-thermometer-ir-contactloos-mlx90614/

8. Test Run
  1. python Tmp_Sensor.py

9. จะได้ค่าอุณหภูมิ ของความร้อนที่ยิง
root@pi200:/home/pi# python Temp_Sensor.py
32.25
root@pi200:/home/pi# python Temp_Sensor.py
31.69
root@pi200:/home/pi#


การต่อตัววัดการสั่น 801S

1. การต่อ ตัววัดการสั่น 801S ตัว PI รับค่าได้เฉพาะ Digital ถ้าต้องการให้ได้รับค่า Analog ตัวใช้ตัวแปลงค่า
MCP3008
https://www.arduinoall.com/product/984/mcp3008-8-channel-10-bit-adc-with-spi-interface
การต่อเข้า PI
ไฟ 3.3V
GND
Aout
ต่อ PI และ MCP3008

2. เขียน Code
  1. nano Vibration_Sensor.py  

Code
  1. # Simple example of reading the MCP3008 analog input channels and printing
  2. # them all out.
  3. # Author: Tony DiCola
  4. # License: Public Domain
  5. import time
  6. import datetime
  7.  
  8. # Import SPI library (for hardware SPI) and MCP3008 library.
  9. import Adafruit_GPIO.SPI as SPI
  10. import Adafruit_MCP3008
  11.  
  12. # Software SPI configuration:
  13. ## GPIO ##
  14. CLK  = 11
  15. MISO = 9
  16. MOSI = 10
  17. CS   = 8
  18.  
  19. ## PIN ##
  20. #CLK  = 23
  21. #MISO = 21
  22. #MOSI = 19
  23. #CS   = 24
  24.  
  25. mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
  26. print(datetime.datetime.now())
  27. # Hardware SPI configuration:
  28. # SPI_PORT   = 0
  29. # SPI_DEVICE = 0
  30. # mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
  31.  
  32. print('Reading MCP3008 values, press Ctrl-C to quit...')
  33. # Print nice channel column headers.
  34. #print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8)))
  35. #print('{6:>4}|{7:>4}'.format(*range(8)))
  36. print('{7:>4}'.format(*range(8)))
  37. print('-' * 57)
  38. # Main program loop.
  39. while True:
  40.     # Read all the ADC channel values in a list.
  41.     values = [0]*8
  42.     for i in range(8):
  43.         # The read_adc function will get the value of the specified channel (0-7).
  44.         values[i] = mcp.read_adc(i)
  45.     # Print the ADC values.
  46.     print('{7:>4}'.format(*values))
  47.     #print('{6:>4}|{7:>4}'.format(*values))
  48.     #print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
  49.     # Pause for half a second.
  50.     time.sleep(1)


***สำคัญ SPI ใช้ GPIO ไม่ได้ใช่ PIN *** จะไม่ได้ค่า
https://learn.adafruit.com/raspberry-pi-analog-to-digital-converters/mcp3008
3. Test Run คำสั่ง จะได้ค่า ตัวเลข
python Vibration_Sensor.py
2020-05-21 18:37:18.288545
Reading MCP3008 values, press Ctrl-C to quit...
7
---------------------------------------------------------
0
1023
31
896
1023

////##########################////
Code สำเร็จที่ใช้ Run ทั้งวัดการสั่นและความร้อน
  1. # Simple example of reading the MCP3008 analog input channels and printing
  2. # them all out.
  3. # Author: Tony DiCola
  4. # License: Public Domain
  5. # Vibration 801S
  6. import time
  7. import datetime
  8. # Import SPI library (for hardware SPI) and MCP3008 library.
  9. import Adafruit_GPIO.SPI as SPI
  10. import Adafruit_MCP3008
  11.  
  12. # Tmp Sensor
  13. import smbus
  14.  
  15. # Vibration 801S
  16. # Software SPI configuration:
  17. ## GPIO ##
  18. CLK  = 11
  19. MISO = 9
  20. MOSI = 10
  21. CS   = 8
  22.  
  23. ## PIN ##
  24. #CLK  = 23
  25. #MISO = 21
  26. #MOSI = 19
  27. #CS   = 24
  28.  
  29. mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
  30. print(datetime.datetime.now())
  31. # Hardware SPI configuration:
  32. # SPI_PORT   = 0
  33. # SPI_DEVICE = 0
  34. # mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))
  35. #print('Reading MCP3008 values, press Ctrl-C to quit...')
  36. # Print nice channel column headers.
  37. #print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8)))
  38. #print('{6:>4}|{7:>4}'.format(*range(8)))
  39. #print('{7:>4}'.format(*range(8)))
  40. #print('-' * 57)
  41.  
  42. # Tmp Sensor Use
  43. class MLX90614():
  44.  
  45.     MLX90614_RAWIR1=0x04
  46.     MLX90614_RAWIR2=0x05
  47.     MLX90614_TA=0x06
  48.     MLX90614_TOBJ1=0x07
  49.     MLX90614_TOBJ2=0x08
  50.  
  51.     MLX90614_TOMAX=0x20
  52.     MLX90614_TOMIN=0x21
  53.     MLX90614_PWMCTRL=0x22
  54.     MLX90614_TARANGE=0x23
  55.     MLX90614_EMISS=0x24
  56.     MLX90614_CONFIG=0x25
  57.     MLX90614_ADDR=0x0E
  58.     MLX90614_ID1=0x3C
  59.     MLX90614_ID2=0x3D
  60.     MLX90614_ID3=0x3E
  61.     MLX90614_ID4=0x3F
  62.  
  63.     def __init__(self, address=0x5a, bus_num=1):
  64.         self.bus_num = bus_num
  65.         self.address = address
  66.         self.bus = smbus.SMBus(bus=bus_num)
  67.  
  68.     def read_reg(self, reg_addr):
  69.         return self.bus.read_word_data(self.address, reg_addr)
  70.  
  71.     def data_to_temp(self, data):
  72.         temp = (data*0.02) - 273.15
  73.         return temp
  74.  
  75.     #def get_amb_temp(self):
  76.     #    data = self.read_reg(self.MLX90614_TA)
  77.     #    return self.data_to_temp(data)
  78.  
  79.     def get_obj_temp(self):
  80.         data = self.read_reg(self.MLX90614_TOBJ1)
  81.         return self.data_to_temp(data)
  82.  
  83. #if __name__ == "__main__":
  84. #    sensor = MLX90614()
  85. #    #print(sensor.get_amb_temp())
  86. #    print(sensor.get_obj_temp())
  87.  
  88. # Main program loop.
  89. while True:
  90.     # Read all the ADC channel values in a list.
  91.     values = [0]*8
  92.     for i in range(8):
  93.         # The read_adc function will get the value of the specified channel (0-7).
  94.         values[i] = mcp.read_adc(i)
  95.  
  96.         sensor = MLX90614()
  97.         #print(sensor.get_amb_temp())
  98.         #print(sensor.get_obj_temp())
  99.  
  100.     # Print the ADC values.
  101.     print('{7:>4}'.format(*values))
  102.     print(sensor.get_obj_temp())
  103.     #print('{6:>4}|{7:>4}'.format(*values))
  104.     #print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
  105.     # Pause for half a second.
  106.     time.sleep(10)

นำข้อมูลเข้า Database
https://pynative.com/install-mysql-connector-python/

1. ติดตั้ง mysql-connector
  1. pip install mysql-connector-python

2. Code
  1. nano DB.py

  1. import mysql.connector
  2. from mysql.connector import Error
  3. from mysql.connector import errorcode
  4.  
  5. try:
  6.     connection = mysql.connector.connect(host='192.168.2.101',
  7.                                          database='sci_pi',
  8.                                          user='XXX',
  9.                                          password='XXX')
  10.     #INSERT INTO `Data` (`ID`, `Vibration`, `Tmp`, `TransDate`) VALUES (NULL, '50', '60', '2020-05-22');
  11.     mySql_insert_query = """INSERT INTO Data (ID, Vibration, Tmp, TransDate, FromPI)
  12.                           VALUES
  13.                           (NULL, 50, 60, '2020-05-22','192.168.0.164') """
  14.  
  15.     cursor = connection.cursor()
  16.     cursor.execute(mySql_insert_query)
  17.     connection.commit()
  18.     #print(cursor.rowcount, "Record inserted successfully into Laptop table")
  19.     cursor.close()
  20.  
  21. #except mysql.connector.Error as error:
  22. #    print("Failed to insert record into Laptop table {}".format(error))
  23.  
  24. finally:
  25.     if (connection.is_connected()):
  26.         connection.close()
  27.         #print("MySQL connection is closed")
  28.  


3. Test Run
  1. python DB.py


ดูว่าข้อมูลเข้า Database ที่สร้างไว้หรือไม่
ส่งเมล์ Zimbra แจ้งเตือนผู้เกี่ยวข้อง
เมื่อเครื่องสั่น มากหรือ มอเตอร์ร้อนมาก

1. ติดตั้ง
  1. apt-get install ssmtp


2. Code
  1. nano Mail.py

  1. import smtplib
  2.  
  3. server=smtplib.SMTP('192.168.2.102',25)
  4. server.starttls()
  5. server.login("suwit_j@sci.com","XXX")
  6.  
  7. message = """From: PI <suwit_j@sci.com>
  8. Subject: Wraning From PI Check Machine.
  9.  
  10. Wrannnig From PI Check machine.
  11. Please Chack.
  12. http://intranet.sci.com/sci/PR/rp_start.php
  13. """
  14.  
  15. server.sendmail("suwit_j@sci.com","suwit_j@sci.com", message)
  16.  
  17. server.quit()


3. ทดสอบ Run คำสั่ง
  1. python Mail.py

https://iotdesignpro.com/projects/sending-smtp-email-using-raspberry-pi

วันอาทิตย์ที่ 23 กุมภาพันธ์ พ.ศ. 2563

Home Assistant : HA Install On Pi Run Play MP3

Home Assistant : HA Install On Pi Run Play MP3
1. Download PI และ Restore ใส่ SD Card นำไป Boot
https://www.raspberrypi.org/downloads/raspbian/

2. ตั้งค่า wifi
https://raspberrypihq.com/how-to-connect-your-raspberry-pi-to-wifi/
ถ้ามี Error แสดง
Wi-Fi is currently blocked by rfkill

ใช้คำสั่ง
  1. sudo rfkill unblock 0
  2. ifconfig wlan0 up

https://www.raspberrypi.org/forums/viewtopic.php?t=206223

3. Set Wifi Connect
  1. iwlist wlan0 scan
  2. nano /etc/wpa_supplicant/wpa_supplicant.conf

เพิ่ม
network={
ssid="SCI_EMP"
psk="XXXXXX"
}
แล้ว reboot เครื่อง Run คำสั่ง
  1. ifconfig wlan0

จะได้ IP

4. Config rapberry pi
เลือก Time zone
  1. open ssh timezone

  1. raspi-config

- เปลี่ยนชื่อ Host ตามที่ต้องการ เช่น pi-moning
- เปิด ssh
และอื่น ๆ
Run set locale
  1. locale-gen en_US en_US.UTF-8 th_TH th_TH.UTF-8

ติดตั้ง ntp และ config ntp

5. ติดตั้ง
https://www.home-assistant.io/docs/installation/raspberry-pi/
Run Command
  1. sudo apt-get update
  2. sudo apt-get upgrade -y
  3. sudo apt-get install python3 python3-dev python3-venv python3-pip libffi-dev libssl-dev
  4. sudo useradd -rm homeassistant -G dialout,gpio,i2c
  5. cd /srv
  6. sudo mkdir homeassistant
  7. sudo chown homeassistant:homeassistant homeassistant
  8. sudo -u homeassistant -H -s
  9. cd /srv/homeassistant
  10. python3 -m venv .
  11. source bin/activate
  12. python3 -m pip install wheel
  13. pip3 install homeassistant


hass ใช้เวลาสักพัก ประมาณ 20-30 นาที
ถ้าขึ้น INFO (MainThread) [homeassistant.core] Timer:starting คือเสร็จแล้ว
6. เข้าหน้า Web ตั้งรหัสผ่าน user
http://ipaddress:8123

7. ทำ hass auto service
ทำต่อจากข้อ 8
https://intranet.sci.com/blog.php?u=281&b=1603
เพิ่มเติม
https://www.home-assistant.io/docs/autostart/systemd/
https://community.home-assistant.io/t/unit-home-assistant-homeassistant-service-not-found/28507

8. Confing configuration.yaml
all config file
  1. cd /home/homeassistant/.homeassistant

คำสั่ง restart service
  1. systemctl restart home-assistant@homeassistant

AIQ
สร้างไฟล aqi.sh
#!/bin/sh
#New Key 20200206 348 Day
result=$(curl -s --location --request GET "api.airvisual.com/v2/city?city=Samut%20Sakhon&state=Samut%20Sakhon&country=Thailand&key=XXXXXXXXXXXXXX")
echo $result | jq -r .data.current.pollution.aqius


สมัครฟรี 10000 ครั้ง/เดือน หมดอายุ 348 วัน XXXX คือคีย์ที่ได้จาก Web
https://www.airvisual.com/thailand/bangkok

9. ติดต้ง jq
  1. sudo apt install jq

10. Code sh ยัดค่าใส่ sensor
  1. nano configuration.yaml

เพิ่ม
#AIQ From aiq.sh
sensor:
- platform: command_line
name: AQI
scan_interval: 3600
command: "/home/homeassistant/.homeassistant/aqi.sh"


11. เล่นเพลง MP3
copy mp3 ไปไว้ตามที่ต้องการ
ติดตั้งโปรแกรม
  1. apt-get install omxplayer

ทดลองเล่นด้วยคำสั่ง
  1. omxplayer /home/pi/MP3/Auto_7.55.mp3

ถ้ามี Error
Error: Unable to open font

ให้ติดตั้ง fonts เพิ่ม
  1. apt-get install libpcre3 fonts-freefont-ttf

https://raspberrypi.stackexchange.com/questions/32755/install-omxplayer-on-the-commandline

จากข้อ 11. user อื่น ๆ เล่นได้แต่พอไป Test run จาก หน้า Web Home Assistant จะไม่ได้ ไม่เล่นเพลง
ต้อง Add user homeassistant เข้า Group ด้วย ไม่อย่างนั้น จะ Error เมื่อเรียกจาก homeassistant
  1. usermod -a -G audio homeassistant
  2. usermod -G video homeassistant

แล้ว reboot เครื่อง

ลอง Run ที่ User homeassistant
  1. su - homeassistant
  2. /usr/bin/omxplayer /home/pi/MP3/1.mp3


12. Fix IP Wifi
https://electrondust.com/2017/11/25/setting-raspberry-pi-wifi-static-ip-raspbian-stretch-lite/
  1. nono /etc/dhcpcd.conf

เพิ่มไว้ล่างสุด
interface wlan0
static ip_address=192.168.0.175
static routers=192.168.0.2
static domain_name_servers=8.8.8.8

แล้ว Reboot เครื่อง

13. configuration.yaml
  1. nano configuration.yaml

shell_command:
auto_normal: /usr/bin/omxplayer /home/homeassistant/.homeassistant/MP3/Auto_7.55.mp3
song_national: /usr/bin/omxplayer /home/homeassistant/.homeassistant/MP3/Song_National.mp3
no_act: /usr/bin/omxplayer /home/homeassistant/.homeassistant/MP3/No_Act.mp3
song_enough: /usr/bin/omxplayer /home/homeassistant/.homeassistant/MP3/Song_Enough.mp3
stop_mp3: bash /home/homeassistant/.homeassistant/stop_mp3.sh


14. scrip.yaml
  1. nano scrip.yaml

'1582256882671':
alias: 1. ^{ ^a ^d ^h ^` ^b ^i ^a ^v Manual
sequence:
- service: shell_command.no_act
- service: system_log.write
'1582256923595':
alias: 2. ^` ^~ ^g ^h ^h ^g ^~ ^` ^~ ^g Manual
sequence:
- service: shell_command.song_enough
'1582256950346':
alias: 3. ^` ^~ ^g ^j ^u Manual
sequence:
- service: shell_command.song_national
'1582259558847':
alias: Stop Sound
sequence:
- data: {}
service: shell_command.stop_mp3


15. automations.yaml
  1. nano automations.yaml

- id: '1582084332514'
alias: 1. ^` ^b ^i ^a ^v ^{ ^a ^u ^{ ^a ^w ^a ^y 7:55
description: ^` ^b ^i ^a ^v ^{ ^a ^u ^` ^{ ^t ^` ^~ ^g ^h ^h ^g ^~ ^` ^~ ^g + ^` ^~ ^g ^j ^u
trigger:
- at: '7:54:57'
platform: time
condition: []
action:
- service: shell_command.auto_normal
initial_state: true
- id: '1582106072377'
alias: 2. ^g ^t ^a ^h ^a 7:30, 7:50 ^a ^` ^{ ^t ^` ^~ ^g ^j ^u 8:00
description: ^{ ^a ^g ^t ^a ^h ^a ^a ^` ^{ ^t ^` ^~ ^g ^j ^u 8:00
trigger:
- at: '7:30:00'
platform: time
condition: []
action:
- data: {}
service: shell_command.no_act
- delay: 00:19:45
- service: shell_command.no_act
- delay: 00:09:45
- service: shell_command.song_national
initial_state: false


***** เพิ่มเติม IP Wifi มีปัญหา ****
พบปัญหา Wifi ที่ Config จาก Service dhcpcd มีปัญหา
เครื่องเปิดปกติทำงานปกติ แต่ Wifi ใช้ไม่ได้เข้าไม่ได้

เปลี่ยนวิธี Config ip wifi ใหม่ ใช้
https://raspberrypi.stackexchange.com/questions/37920/how-do-i-set-up-networking-wifi-static-ip-address

  1. nano /etc/network/interfaces

เพิ่ม
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.0.175
netmask 255.255.255.0
gateway 192.168.0.2
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf


ของ Lan ถ้าต้องการใช้ก็ Fix จากไฟล์นี้เหมือนกัน เช่น
auto eth0
iface eth0 inet static
address 10.1.1.30
netmask 255.255.255.0
gateway 10.1.1.1


แล้วปิด Service dhcpcd ไปให้ไปใช้ network/interfaces แทน
  1. sudo systemctl disable dhcpcd
  2. sudo systemctl enable networking


แล้ว Reboot เครื่อง ก็จะสามารถใช้ IP ที่ Fix ได้

วันอาทิตย์ที่ 2 กุมภาพันธ์ พ.ศ. 2563

Raspberry Pi Headless Setup With WiFi and SSH Enabled

Raspberry Pi Headless Setup With WiFi and SSH Enabled
https://www.gngrninja.com/code/2019/3/10/raspberry-pi-headless-setup-with-wifi-and-ssh-enabled

1. Download
https://www.raspberrypi.org/downloads/raspbian/
2. แตกไฟล์ Burn ใส่ SD ด้วยการ Restore ทับทั้งหมด
3. นำ SD ไปใส่เครื่องให้ Boot ก่อนสักพัก เพื่อให้ทำ Config และ Resize Partition (ถ้าไม่ทำมีการสร้างไฟล์เพิ่มใหม่ใน Boot จะหาย เมื่อนำไป Boot )
4. ปิดเครื่องเอา SD ไปต่อ Linux เปิดใน Disk Boot
5. สร้าง ไฟล์ wpa_supplicant.conf ในไปไว้ใน Boot
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
ap_scan=1
fast_reauth=1
country=JP

network={
ssid="Your network's SSID"
psk="Your network's password/psk"
id_str="0"
priority=100
}


6. สร้างไฟล์ ssh ด้วย text editor ไม่ต้องใส่นามสกุล ไว้ที่ Dive Boot
7. เปลี่ยนสิทธิ์ เป็น 777 ทั้ง 2 ไฟล์
8. นำไป Boot จะต่อ WIFI และ ได้ IP สามารถ SSH ไปได้

วันจันทร์ที่ 28 ตุลาคม พ.ศ. 2562

PI : Pi Camera Last version with python 3

Old version Use Python2
https://intranet.sci.com/blog.php?u=281&b=1667

PI : Pi Camera Last version with python 3
ที่แตกต่างจาก python2 คือคำสั่ง python จะไม่เหมือนกัน ต้องเขียน Code ใหม่
https://pypi.org/project/slackclient/
เช่น
print
เดิม print ตัวแปร
ใหม่ print (ตัวแปร, " ")

with open ใช้ไม่ได้ Error python io

from slackclient import SlackClient
ต้องเปลี่ยนเป็น
from slack import WebClient

code ส่งข้อความ
เดิม
  1. from slackclient import SlackClient
  2. sc = SlackClient("XXXXXXXXX")
  3. sc.api_call(
  4.    "chat.postMessage",
  5.     channel="CF6GEHBDF",
  6.     text="Hello from Python! camera :tada:"
  7. )

ใหม่
  1. from slack import WebClient
  2. client = WebClient("XXXXXXX")
  3. response = client.chat_postMessage(
  4.    channel='#wifi',
  5.    text="Test")

ใช้เป็น client.chat_postMessage และ client.file_upload เป็นต้น ตามนี้

https://pypi.org/project/slackclient/

วิธีลง ที่เพิ่มขึ้นมาคือ
1. ลง slackclient ด้วยคำสั่ง
  1. pip install slackclient

ไม่ได้จะ Error
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting slackclient
Using cached https://www.piwheels.org/simple/slackcl ... ne-any.whl
slackclient requires Python '>=3.6.0' but the running Python is 2.7.16


ต้อง ลง pip3 สำหรับ python3
1.1. ลง pip3
  1. apt-get install python3-pip

1.2. ลง slackclient
  1. pip3 install slackclient


2. ดู python version ต้องเป็นตัวเดียวกัน
root@raspberrypi:/home/pi/Monitor# python --version
Python 3.7.3
root@raspberrypi:/home/pi/Monitor# python3 --version
Python 3.7.3

ถ้าเป็นแบบนี้จะ run ไม่ได้ หา Module ไม่พบ
root@raspberrypi:/home/pi# python --version
Python 2.7.2
root@raspberrypi:/home/pi# python3 --version
Python 3.7.3


ติดตั้ง python 3.7.0 ตาม Link เพื่อให้เหมือนกัน
https://installvirtual.com/install-python-3-7-on-raspberry-pi/

ทำต่างขั้นสุดท้าย
2.1. แก้ให้โปรแกรม เป็น Default
  1. nano ~/.bashrc

เพิ่ม
alias python='python3'

2.2. run
  1. source ~/.bashrc


ทดลองสร้าง python แล้ว Run คำสั่ง จะสามารถส่ง Slack ได้
(ถ้าไม่ได้ทำข้อ 2 ลองใช้คำสั่ง )
python3 ตามด้วยไฟล์.py ก็ได้เช่นกัน

3. คำสั่งเพิ่มเติม
ดู slackclient version
  1. pip3 list

Update slackclient version
  1. pip3 install slackclient --upgrade


4. เพิ่มเติมใน Motion ไม่ทำงาน ไม่ run คำสั่ง python ที่ไฟล์ motion.conf ถึงจะทำงาน
เดิม ใช้
  1. on_movie_start python /home/pi/slack_post.py

ใหม่ต้องใส่ path ของโปรแกรมด้วย
  1. on_movie_start /usr/bin/python3 /home/pi/slack_post.py

นอกนั้น Set ตามของเดิม
https://intranet.sci.com/blog.php?u=281&b=1667

Code สำเหร็จ
Code สำเร็จ slack_post.py
  1. import glob
  2. import os
  3. import time
  4. import glob
  5.  
  6. from slack import WebClient
  7. client = WebClient("XXXXXXXXX")
  8.  
  9. time.sleep(2)   # Delays for 5 seconds. You can also use a float value.
  10.  
  11. list_of_files = glob.glob('/home/pi/Monitor/*.jpg') # * means all if need specific format then *.csv
  12. latest_file = max(list_of_files, key=os.path.getctime)
  13. #print (latest_file, " ")
  14.  
  15. head, tail = os.path.split(latest_file)
  16. pathName = head+'/'+tail
  17. #with open(latest_file) as file_content:
  18. response = client.files_upload(
  19.    channels="test",
  20.    file=pathName,
  21.    title="Find movement in room IF."
  22.    )
  23.  

วันพฤหัสบดีที่ 29 สิงหาคม พ.ศ. 2562

ปุ่มเปิด/ปิด Raspberry Pi

ปุ่มเปิด/ปิด Raspberry Pi
1.ต่อ Switch แบบกดติดปล่อยดับที่ขา 5 (GPIO3) กับขา 6 (GND) หรือจะต่อที่ GPIO อื่นก็ได้ แต่ต้องต้องต่อตัวต้านทานเพิ่มด้วย เพื่อป้องกันความเสียหายกับบอร์ด (GPIO3 มีตัวต้านทานภายในอยู่แล้ว) ที่มา : https://learn.sparkfun.com/tutorials/pull-up-resistors
2.กรณีต่อที่ GPIO3 ต้องเขียน Code เปิดใช้งานตัวต้านทานภายในด้วย
  1. GPIO.setmode(GPIO.BOARD)
  2. GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)

3.เขียน Code สำหรับควบคุมการเปิด/ปิด : pishutdown.py
  1. #!/usr/bin/python
  2. # shutdown/reboot(/power on) Raspberry Pi with pushbutton
  3.  
  4. import RPi.GPIO as GPIO
  5. from subprocess import call
  6. from datetime import datetime
  7. import time
  8.  
  9. # pushbutton connected to this GPIO pin, using pin 5 also has the benefit of
  10. # waking / powering up Raspberry Pi when button is pressed
  11. shutdownPin = 5
  12.  
  13. # if button pressed for at least this long then shut down. if less then reboot.
  14. shutdownMinSeconds = 3
  15.  
  16. # button debounce time in seconds
  17. debounceSeconds = 0.01
  18.  
  19. GPIO.setmode(GPIO.BOARD)
  20. GPIO.setup(shutdownPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
  21.  
  22. buttonPressedTime = None
  23.  
  24. def buttonStateChanged(pin):
  25.     global buttonPressedTime
  26.  
  27.     if not (GPIO.input(pin)):
  28.         # button is down
  29.         if buttonPressedTime is None:
  30.             buttonPressedTime = datetime.now()
  31.     else:
  32.         # button is up
  33.         if buttonPressedTime is not None:
  34.             elapsed = (datetime.now() - buttonPressedTime).total_seconds()
  35.             buttonPressedTime = None
  36.             if elapsed >= shutdownMinSeconds:
  37.                 # button pressed for more than specified time, shutdown
  38.                 call(['shutdown', '-h', 'now'], shell=False)
  39.             elif elapsed >= debounceSeconds:
  40.                 # button pressed for a shorter time, reboot
  41.                 call(['shutdown', '-r', 'now'], shell=False)
  42.  
  43. # subscribe to button presses
  44. GPIO.add_event_detect(shutdownPin, GPIO.BOTH, callback=buttonStateChanged)
  45.  
  46. while True:
  47.     # sleep to reduce unnecessary CPU usage
  48.     time.sleep(5)

* กดสวิตช์ค้างน้อยกว่า 3 วินาที จะเป็นการ reset, มากกว่า 3 วินาทีจะเป็นการ Shutdown, ถ้า Shutdown ไปแล้วจ่ายไฟค้างไว้ กดสวิตช์จะเป็นการเปิด

4.ถ้าอยากเก็บ Log ดูการทำงาน เพิ่ม Code ดังนี้
  1. import logging
  2.  
  3. logger = logging.getLogger(__name__)
  4. logger.setLevel(logging.INFO)
  5.  
  6. # create a file handler
  7. handler = logging.FileHandler('pishutdown.log')
  8. handler.setLevel(logging.INFO)
  9.  
  10. # create a logging format
  11. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  12. handler.setFormatter(formatter)
  13.  
  14. # add the handlers to the logger
  15. logger.addHandler(handler)
  16.  
  17. logger.info('Shutdown/Restart')

5.เรียก script ให้ทำงาน
  1. sudo python pishutdown.py

6.กำหนดให้ script ทำงานเป็น Service : /etc/systemd/system/pishutdown.service
  1. [Service]
  2. ExecStart=/usr/bin/python /path_to_pishutdown/pishutdown.py
  3. WorkingDirectory=/path_to_pishutdown/
  4. Restart=always
  5. StandardOutput=syslog
  6. StandardError=syslog
  7. SyslogIdentifier=pishutdown
  8. User=root
  9. Group=root
  10.  
  11. [Install]
  12. WantedBy=multi-user.target

7.Enable service:
  1. sudo systemctl enable pishutdown.service

8.Run service (will be automatically started on next reboot):
  1. sudo systemctl start pishutdown.service

ที่มา : https://gilyes.com/pi-shutdown-button/