Showing posts with label Raspberry PI. Show all posts
Showing posts with label Raspberry PI. Show all posts

9/18/2025

ส่งค่าอุณหภูมิจาก Pi ไป Home Assistant แบบ Docker

 ส่งค่าอุณหภูมิจาก Pi ไป Home Assistant แบบ Docker

ต่อจาก
https://intranet.scivalve.com/blog.php?u=281&b=2051

1. ตัว HA ลงแบบ Docker ก็ต้อง Mosquitto ด้วย Docker container
1.1. สร้างโฟลเดอร์เก็บ config/data/log ของ Mosquitto:

  1. mkdir -p /HA/mosquitto/config /HA/mosquitto/data /HA/mosquitto/log

1.2. สร้างไฟล์ config
  1. nano /HA/mosquitto/config/mosquitto.conf

1.3. ใส่ค่า
แบบใช้ได้หมด ไม่ต้องใส่ use password ไม่ปลอดภัย
  1. persistence true
  2. persistence_location /mosquitto/data/
  3. log_dest file /mosquitto/log/mosquitto.log
  4.  
  5. allow_anonymous true
  6. listener 1883

แบบตั้ง user password
  1. persistence true
  2. persistence_location /mosquitto/data/
  3. log_dest file /mosquitto/log/mosquitto.log
  4.  
  5. allow_anonymous false
  6. password_file /mosquitto/config/password.txt
  7. listener 1883


1.4. สร้าง user ด้วยคำสั่ง
docker run --rm -it \
  1.  -v /HA/mosquitto/config:/mosquitto/config \
  2.   eclipse-mosquitto mosquitto_passwd -c /mosquitto/config/password.txt hauserXXXXX

มันจะถาม password ให้คุณใส่ → เก็บไว้ใน /HA/mosquitto/config/password.txt

1.5. รัน container Mosquitto:
  1. docker run -d \
  2.   --name mosquitto \
  3.   -p 1883:1883 \
  4.   -p 9001:9001 \
  5.   -v /HA/mosquitto/config:/mosquitto/config \
  6.   -v /HA/mosquitto/data:/mosquitto/data \
  7.   -v /HA/mosquitto/log:/mosquitto/log \
  8.   eclipse-mosquitto


1.6. Restart Mosquitto
  1. docker restart mosquitto


1.7. ทดสอบ ที่เครื่อง HA Run
  1. mosquitto_sub -h localhost -p 1883 -u "hauser" -P "รหัสผ่าน" -t "#"


1.8. ที่เครื่องเรา ติดตั้ง
  1. apt install mosquitto-clients -y

แล้วลองส่งค่าไป
  1. mosquitto_pub -h 192.168.2.5 -p 1883 -u "xxx" -P "xxxx" -t "test/topic" -m "Hello MQTT"
  1. mosquitto_pub -h 192.168.2.5 -p 1883 -u "xxx" -P "xxxx" -t "hass/sensor/temperature" -m "27"

ที่ Terminal ของ HA จะต้องเห็นข้อความ Hello MQTT

1.9. ที่ เครื่อง HA เพิ่ม ที่ไฟล์ configuration.yaml เป็น Sensor และรอรับค่า MQTT
  1. mqtt:
  2.   sensor:
  3.     - name: "Server Temp."
  4.       state_topic: "hass/sensor/temperature"
  5.       value_template: "{{ value_json.temperature }}"
  6.       unit_of_measurement: "°C"
  7.  
  8.     - name: "Server Hum."
  9.       state_topic: "hass/sensor/temperature"
  10.       value_template: "{{ value_json.humidity }}"
  11.       unit_of_measurement: "%"


1.10. เข้า Setting --> Devices & Services Add integration MQTT เข้าไปด้วย
ใส่ IP User Password

1.11. ที่เครื่อง pi ทดลอง run python Code temp2mqtt.2.5.py
  1. #!/usr/bin/python3
  2. import sys
  3. import Adafruit_DHT
  4.  
  5. import time, json
  6. import RPi.GPIO as GPIO
  7. import paho.mqtt.client as mqtt
  8.  
  9. import requests
  10.  
  11. # Config
  12. MQTT_BROKER = "192.168.2.5"   # IP ของ Home Assistant
  13. MQTT_PORT = 1883
  14. MQTT_USER = "xx"
  15. MQTT_PASSWORD = "xx"
  16. MQTT_TOPIC = "hass/sensor/temperature"
  17.  
  18. SENSOR = Adafruit_DHT.AM2302  # หรือ DHT11 แล้วแต่ที่ใช้
  19. PIN = 4  # GPIO ที่ต่อ sensor
  20.  
  21. # Connect MQTT
  22. client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  23. client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
  24. client.connect(MQTT_BROKER, MQTT_PORT, 60)
  25.  
  26. # Try to grab a sensor reading.  Use the read_retry method which will retry up
  27. # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
  28. humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
  29.  
  30. # Un-comment the line below to convert the temperature to Fahrenheit.
  31. # temperature = temperature * 9/5.0 + 32
  32.  
  33. from datetime import datetime
  34. if humidity is not None and temperature is not None:
  35.    print('Temp={0:0.1f}*  Humidity={1:0.1f}%  Date={2}'.format(temperature, humidity, datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
  36.    payload = {
  37.         "temperature": round(temperature, 2),
  38.         "humidity": round(humidity, 2)
  39.    }
  40.    #print('{0}'.format(json.dumps(payload)))
  41.    client.publish(MQTT_TOPIC, json.dumps(payload))
  42.  


แก้ Code ให้ส่ง MQTT ไป 2 เครื่อง
  1. #!/usr/bin/python3
  2. import Adafruit_DHT
  3. import time, json
  4. from datetime import datetime
  5. import paho.mqtt.client as mqtt
  6.  
  7. # Config broker 1
  8. MQTT_BROKER1   = "192.168.0.187"
  9. MQTT_PORT1     = 1883
  10. MQTT_USER1     = "xxx"
  11. MQTT_PASSWORD1 = "xxx"
  12. BROKER1_TOPIC  = "hass/sensor/temperature"
  13.  
  14. # Config broker 2
  15. MQTT_BROKER2   = "192.168.2.5"
  16. MQTT_PORT2     = 1883
  17. MQTT_USER2     = "xxx"
  18. MQTT_PASSWORD2 = "xxx"
  19. BROKER2_TOPIC  = "hass/sensor/temperature"
  20.  
  21. SENSOR = Adafruit_DHT.AM2302
  22. PIN = 4
  23.  
  24. # อ่านค่าจาก DHT
  25. humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
  26.  
  27. if humidity is not None and temperature is not None:
  28.     payload = {
  29.         "temperature": round(temperature, 2),
  30.         "humidity": round(humidity, 2)
  31.     }
  32.  
  33.     print(f"Publish: {payload} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  34.  
  35.     # ส่งไป broker 1
  36.     client1 = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  37.     client1.username_pw_set(MQTT_USER1, MQTT_PASSWORD1)
  38.     client1.connect(MQTT_BROKER1, MQTT_PORT1, 60)
  39.     client1.publish(BROKER1_TOPIC, json.dumps(payload))
  40.     client1.disconnect()
  41.  
  42.     # ส่งไป broker 2
  43.     client2 = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  44.     client2.username_pw_set(MQTT_USER2, MQTT_PASSWORD2)
  45.     client2.connect(MQTT_BROKER2, MQTT_PORT2, 60)
  46.     client2.publish(BROKER2_TOPIC, json.dumps(payload))
  47.     client2.disconnect()

 

HA + Pi สั่งปิดเปิด Air Auto แทนเครื่อง MN-SERVER

 HA + Pi สั่งปิดเปิด Air Auto แทนเครื่อง MN-SERVER

คำสั่ง Restart service HA docker

  1. docker restart Docker-ID

ตั้งค่า Timezone ให้ Debian เพื่อให้เวลาตรง
  1. timedatectl set-timezone Asia/Bangkok
  2. timedatectl
  3. date


1. ติดตั้ง Home Assistant with Docker
https://intranet.scivalve.com/blog.php?u=281

2. HA และ PI สร้าง Private Key เพื่อให้ HA สามารถ SSH เข้าเครื่อง PI โดยไม่ต้องใช้รหัส
จะทำให้ HA สามารถเรียกคำสั่งโปรแกรมที่เครื่อง PI ได้
2.1. ใช้ Terminal ล็อคอินเข้าไปที่ เครื่อง Server ที่รัน Docker และ Home Assistant ของคุณ
2.2. รันคำสั่งนี้เพื่อสร้าง Key คู่ใหม่:
  1. ssh-keygen -t rsa -b 4096

2.3. ระบบจะถามคำถาม 2-3 ข้อ ให้ กด Enter ผ่านไปทั้งหมด เพื่อยอมรับค่าเริ่มต้น และ ไม่ต้องใส่รหัสผ่าน (passphrase) นะครับ
2.4. คำสั่งนี้จะสร้างไฟล์ id_rsa (กุญแจลับ) และ id_rsa.pub (กุญแจสาธารณะ) ขึ้นมาในโฟลเดอร์ .ssh ของ user ที่คุณกำลังล็อคอินอยู่บน Server (เช่น /root/.ssh/ หากคุณล็อคอินเป็น root)

[บนเครื่อง HA Server] ขั้นตอนที่ 2: คัดลอกเนื้อหา Public Key

2.5. รันคำสั่งนี้เพื่อแสดงเนื้อหาของ Public Key:
  1. cat ~/.ssh/id_rsa.pub

2.6. คัดลอก (Copy) ข้อความทั้งหมด ที่แสดงขึ้นมา มันจะขึ้นต้นด้วย ssh-rsa และลงท้ายด้วยชื่อ user@hostname ของคุณ

[บนเครื่อง Raspberry Pi] ขั้นตอนที่ 3: ติดตั้ง Public Key

2.7. ตอนนี้ ให้ใช้ Terminal ล็อคอินเข้าไปที่ เครื่อง Raspberry Pi ของคุณ
2.8. รันคำสั่งนี้เพื่อสร้างโฟลเดอร์และไฟล์ที่จำเป็น (หากยังไม่มี) และตั้งค่า permission ให้ถูกต้อง:
  1. mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys

2.9. เปิดไฟล์ authorized_keys ด้วยโปรแกรม nano:
  1. nano ~/.ssh/authorized_keys

2.10. วาง (Paste) Public Key ที่คุณคัดลอกมาจากขั้นตอนที่ 2 ลงในไฟล์นี้ จากนั้นกด Ctrl+X > กด Y > กด Enter เพื่อบันทึกและออกจากโปรแกรม

[บนเครื่อง HA Server] ขั้นตอนที่ 4: คัดลอก Private Key ให้ Docker
2.11. กลับมาที่ Terminal ของ เครื่อง HA Server
2.12. ตอนนี้ให้ทำขั้นตอนที่เราคุยกันล่าสุด คือคัดลอก Private Key (id_rsa) ที่เพิ่งสร้างในขั้นตอนที่ 1 ไปยังโฟลเดอร์คอนฟิกของ HA ที่แชร์กับ Docker

# แก้ /root/.ssh/id_rsa หาก Key ของคุณอยู่ที่อื่น
# แก้ /path/to/your/ha/config/ ให้เป็น Path จริง
เครื่องจริงอยู่ที่ /config/id_rsa
  1. cp /root/.ssh/id_rsa /path/to/your/ha/config/

2.13. ตั้งค่า permission ให้ไฟล์ที่คัดลอกไป:
  1. chmod 600 /path/to/your/ha/config/id_rsa

2.14. ทดสอบ SSH จากเครื่อง HA ไปเครื่อง PI จะต้องไม่ขึ้นถามรหัส Login

3. แก้ไข ไฟล์ configuration.yaml เพื่อให้มี Switch ปิดเปิด Air manual เพิ่ม
  1. ### Air ####
  2. shell_command:
  3.   # !!! สำคัญ: แก้ไข <IP_ของ_RPi> และ path ไปยังไฟล์ .py ของคุณให้ถูกต้อง !!!
  4.   #### TEST #####
  5.   #air1_on:  "sshpass -p 'XXX' ssh pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  6.   #air1_off: "sshpass -p 'XXX' ssh pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  7.   #air1_on:  "ssh -i /HA/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  8.   #air1_off: "ssh -i /HA/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  9.   #air1_on:  "ssh pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  10.   #air1_off: "ssh pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  11.   ##### Test Rocketchat #######
  12.   #air1_on:  "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  13.   #air1_off: "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Test.py 2302 4'"
  14.  
  15.   air1_on:  "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/On_air1.py'"
  16.   air1_off: "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Off_air1.py'"
  17.  
  18.   air2_on:  "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/On_air2.py'"
  19.   air2_off: "ssh -i /config/id_rsa -o 'StrictHostKeyChecking=no' pi@192.168.0.3 'python3 /home/pi/Off_air2.py'"
  20.  
  21.   # --- DEBUG COMMANDS ---
  22.   #debug_find_path: "pwd > pwd.txt && ls -la >> pwd.txt"
  23.  
  24. # New sensor for human-readable status
  25. sensor:
  26.   - platform: template
  27.     sensors:
  28.       air_status:
  29.         friendly_name: "สถานะแอร์"
  30.         value_template: >-
  31.           {% set state = states('input_select.active_air') %}
  32.           {% if state == 'air1' %}
  33.             Air 1 กำลังทำงาน
  34.           {% elif state == 'air2' %}
  35.             Air 2 กำลังทำงาน
  36.           {% elif state == 'both' %}
  37.             Air 1 และ Air 2 กำลังทำงาน
  38.           {% else %}
  39.             แอร์ทุกเครื่องปิดอยู่
  40.           {% endif %}
  41.  
  42. switch:
  43.   - platform: template
  44.     switches:
  45.       air1_switch:
  46.         friendly_name: "Air 1"
  47.         value_template: "{{ states('input_select.active_air') in ['air1', 'both'] }}"
  48.         turn_on:
  49.           - service: shell_command.air1_on
  50.           - service: input_select.select_option
  51.             target:
  52.               entity_id: input_select.active_air
  53.             data:
  54.               option: >-
  55.                 {% if is_state('input_select.active_air', 'air2') %}
  56.                   both
  57.                 {% else %}
  58.                   air1
  59.                 {% endif %}
  60.         turn_off:
  61.           - service: shell_command.air1_off
  62.           - service: input_select.select_option
  63.             target:
  64.               entity_id: input_select.active_air
  65.             data:
  66.               option: >-
  67.                 {% if is_state('input_select.active_air', 'both') %}
  68.                   air2
  69.                 {% else %}
  70.                   none
  71.                 {% endif %}
  72.  
  73.       air2_switch:
  74.         friendly_name: "Air 2"
  75.         value_template: "{{ states('input_select.active_air') in ['air2', 'both'] }}"
  76.         turn_on:
  77.           - service: shell_command.air2_on
  78.           - service: input_select.select_option
  79.             target:
  80.               entity_id: input_select.active_air
  81.             data:
  82.               option: >-
  83.                 {% if is_state('input_select.active_air', 'air1') %}
  84.                   both
  85.                 {% else %}
  86.                   air2
  87.                 {% endif %}
  88.         turn_off:
  89.           - service: shell_command.air2_off
  90.           - service: input_select.select_option
  91.             target:
  92.               entity_id: input_select.active_air
  93.             data:
  94.               option: >-
  95.                 {% if is_state('input_select.active_air', 'both') %}
  96.                   air1
  97.                 {% else %}
  98.                   none
  99.                 {% endif %}
  100.  
  101.       # New switch for controlling both
  102.       all_air_switch:
  103.         friendly_name: "Air1+Air2"
  104.         value_template: "{{ is_state('input_select.active_air', 'both') }}"
  105.         turn_on:
  106.           - service: shell_command.air1_on
  107.           - service: shell_command.air2_on
  108.           - service: input_select.select_option
  109.             target:
  110.               entity_id: input_select.active_air
  111.             data:
  112.               option: 'both'
  113.         turn_off:
  114.           - service: shell_command.air1_off
  115.           - service: shell_command.air2_off
  116.           - service: input_select.select_option
  117.             target:
  118.               entity_id: input_select.active_air
  119.             data:
  120.               option: 'none'
  121.  
  122. input_select:
  123.   active_air:
  124.     name: Air ที่ทำงานอยู่
  125.     options:
  126.       - none
  127.       - air1
  128.       - air2
  129.       - both # Added 'both' state
  130.     initial: none


4. ไฟล์ automation.yaml เพื่อให้สลับ Air อัตโนมัติ เพิ่ม
  1. #### Off ก่อนแล้วค่อย ON เพื่อไม่ให้ Switch เปิดทั้ง 2
  2. #### delay 15 วิ รอให้ คำสั่งแรกทำงานเสร็จก่อน ถ้าทำต่อเลย คำสั่งแรกยังทำไม่เสร็จ Status จะไม่ถูก
  3. - id: air1_0000
  4.   alias: "Air1 00:00 - 02:59"
  5.   trigger:
  6.     - platform: time
  7.       at: "00:00:00"
  8.   action:
  9.     - service: switch.turn_off
  10.       target:
  11.         entity_id: switch.all_air_switch
  12.     - delay: "00:00:15"   # รอ 15 วินาที      
  13.     - service: switch.turn_on
  14.       target:
  15.         entity_id: switch.air1_switch
  16.  
  17. - id: air2_0300
  18.   alias: "Air2 03:00 - 05:59"
  19.   trigger:
  20.     - platform: time
  21.       at: "03:00:00"
  22.   action:
  23.     - service: switch.turn_off
  24.       target:
  25.         entity_id: switch.all_air_switch
  26.     - delay: "00:00:15"   # รอ 15 วินาที      
  27.     - service: switch.turn_on
  28.       target:
  29.         entity_id: switch.air2_switch
  30.  
  31. - id: air1_0600
  32.   alias: "Air1 06:00 - 08:59"
  33.   trigger:
  34.     - platform: time
  35.       at: "06:00:00"
  36.   action:
  37.     - service: switch.turn_off
  38.       target:
  39.         entity_id: switch.all_air_switch
  40.     - delay: "00:00:15"   # รอ 15 วินาที      
  41.     - service: switch.turn_on
  42.       target:
  43.         entity_id: switch.air1_switch
  44.  
  45. - id: air2_0900
  46.   alias: "Air2 09:00 - 11:59"
  47.   trigger:
  48.     - platform: time
  49.       at: "09:00:00"
  50.   action:
  51.     - service: switch.turn_off
  52.       target:
  53.         entity_id: switch.all_air_switch
  54.     - delay: "00:00:15"   # รอ 15 วินาที      
  55.     - service: switch.turn_on
  56.       target:
  57.         entity_id: switch.air2_switch
  58.  
  59. - id: air1_1200
  60.   alias: "Air1 12:00 - 14:59"
  61.   trigger:
  62.     - platform: time
  63.       at: "12:00:00"
  64.   action:
  65.     - service: switch.turn_off
  66.       target:
  67.         entity_id: switch.all_air_switch
  68.     - delay: "00:00:15"   # รอ 15 วินาที      
  69.     - service: switch.turn_on
  70.       target:
  71.         entity_id: switch.air1_switch
  72.  
  73. - id: air2_1500
  74.   alias: "Air2 15:00 - 17:59"
  75.   trigger:
  76.     - platform: time
  77.       at: "15:00:00"
  78.   action:
  79.     - service: switch.turn_off
  80.       target:
  81.         entity_id: switch.all_air_switch
  82.     - delay: "00:00:15"   # รอ 15 วินาที    
  83.     - service: switch.turn_on
  84.       target:
  85.         entity_id: switch.air2_switch
  86.  
  87. - id: air1_1800
  88.   alias: "Air1 18:00 - 20:59"
  89.   trigger:
  90.     - platform: time
  91.       at: "18:00:00"
  92.   action:
  93.     - service: switch.turn_off
  94.       target:
  95.         entity_id: switch.all_air_switch
  96.     - delay: "00:00:15"   # รอ 15 วินาที      
  97.     - service: switch.turn_on
  98.       target:
  99.         entity_id: switch.air1_switch
  100.  
  101. - id: air2_2100
  102.   alias: "Air2 21:00 - 23:59"
  103.   trigger:
  104.     - platform: time
  105.       at: "21:00:00"
  106.   action:
  107.     - service: switch.turn_off
  108.       target:
  109.         entity_id: switch.all_air_switch
  110.     - delay: "00:00:15"   # รอ 15 วินาที      
  111.     - service: switch.turn_on
  112.       target:
  113.         entity_id: switch.air2_switch

5. ที่เครื่อง PI เพิ่มไฟล์ 4 ไฟล์ สำหรับ HA เรียกใช้
On_air1.py, On_air2.py, Off_air1.py, Off_air2.py
Code
On_air1.py
  1. #!/usr/bin/python3
  2. import time
  3. import RPi.GPIO as GPIO
  4.  
  5. GPIO.setmode(GPIO.BCM)
  6.  
  7. GPIO.setwarnings(False)
  8. GPIO.setup(20, GPIO.OUT)
  9. GPIO.output(20, GPIO.LOW)
  10. #GPIO.setup(21, GPIO.OUT)
  11. #GPIO.output(21, GPIO.LOW)
  12.  
  13. ##### Rocketchat #####
  14. import requests
  15. from datetime import datetime
  16. def send_to_rocketchat(message):
  17.    url = "http://xx.xx.xx.xx:3000/api/v1/chat.postMessage"
  18.  
  19.    headers = {
  20.       "Content-type": "application/json",
  21.       "X-Auth-Token": "XXX",
  22.       "X-User-Id": "XXX"
  23.    }
  24.  
  25.    payload = {
  26.        "channel": "#Test", #IT_Notification
  27.        "text": message
  28.    }
  29.    response = requests.post(url, json=payload, headers=headers)
  30.  
  31. message = "แจ้งเตือน เปิด AIR1 ปิด AIR2 " + datetime.today().strftime('%Y-%m-%d %H:%M:%S')
  32.  
  33. send_to_rocketchat(message)
  34.  

On_air2.py
  1. #!/usr/bin/python3
  2. import time
  3. import RPi.GPIO as GPIO
  4.  
  5. GPIO.setmode(GPIO.BCM)
  6.  
  7. GPIO.setwarnings(False)
  8. #GPIO.setup(20, GPIO.OUT)
  9. #GPIO.output(20, GPIO.LOW)
  10. GPIO.setup(21, GPIO.OUT)
  11. GPIO.output(21, GPIO.LOW)
  12.  
  13.  
  14. ##### Rocketchat #####
  15. import requests
  16. from datetime import datetime
  17. def send_to_rocketchat(message):
  18.    url = "http://192.168.2.76:3000/api/v1/chat.postMessage"
  19.  
  20.    headers = {
  21.       "Content-type": "application/json",
  22.       "X-Auth-Token": "XXX",
  23.       "X-User-Id": "XXX"
  24.    }
  25.  
  26.    payload = {
  27.        "channel": "#Test", #IT_Notification
  28.        "text": message
  29.    }
  30.    response = requests.post(url, json=payload, headers=headers)
  31.  
  32. message = "แจ้งเตือน เปิด AIR2 ปิด AIR1 " + datetime.today().strftime('%Y-%m-%d %H:%M:%S')
  33.  
  34. send_to_rocketchat(message)
  35.  

Off_air1.py

  1. import time
  2. import RPi.GPIO as GPIO
  3.  
  4. GPIO.setmode(GPIO.BCM)
  5.  
  6. GPIO.setwarnings(False)
  7. GPIO.setup(20, GPIO.OUT)
  8. GPIO.output(20, GPIO.HIGH)
  9. #GPIO.setup(21, GPIO.OUT)
  10. #GPIO.output(21, GPIO.HIGH)
  11. GPIO.cleanup()
  12.  

Off_air2.py
  1. #!/usr/bin/python3
  2. import time
  3. import RPi.GPIO as GPIO
  4.  
  5. GPIO.setmode(GPIO.BCM)
  6.  
  7. GPIO.setwarnings(False)
  8. #GPIO.setup(20, GPIO.OUT)
  9. #GPIO.output(20, GPIO.HIGH)
  10. GPIO.setup(21, GPIO.OUT)
  11. GPIO.output(21, GPIO.HIGH)
  12. GPIO.cleanup()

 

9/25/2023

Raspberrypi PI400 ติดตั้ง และ Auto RDP to windows

 Raspberrypi PI400 ติดตั้ง และ Auto RDP to windows

1. โหลดและติดตั้ง ใส่ sd
https://www.raspberrypi.com/software/operating-systems/
1.1. เปิด SSH
1.2. ตั้งรหัส wifi

  1. nano /etc/wpa_supplicant/wpa_supplicant.conf

เพิ่ม
network={
ssid="SCI_EMP"
psk="XXXXXX"
}



ใน Preferences --> Raspberry Pi Configuration หรือใช้คำสั่งผ่าน Terminal ก็ได้
sudo raspi-config
2. ตั้งค่า IP
3. ตั้งค่า Time zone
4. เปิด VNC ตั้งค่า Authentication เป็น VNC password ใส่รหัสสำหรับ Remote
5. เพิ่มตัวเปลี่ยนภาษาไทย
http://www.arduino-makerzone.com/article/59/raspberry-pi-tutorial-ep3-%E0%B8%95%E0%B8%B1%E0%B9%89%E0%B8%87%E0%B8%84%E0%B9%88%E0%B8%B2%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B2-%E0%B9%82%E0%B8%8B%E0%B8%99%E0%B9%80%E0%B8%A7%E0%B8%A5%E0%B8%B2-%E0%B8%84%E0%B8%B5%E0%B8%A2%E0%B9%8C%E0%B8%9A%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B8%94


6. ติดตั้ง Remmina

  1. apt-get install remmina


7. สร้าง config สำหรับ Remote ไปเครื่องที่ต้องการใน remmina ให้ Remote ได้
7.1. ทดลองเรียกใช้งานผ่าน Terminal
remmina /home/pd1/.local/share/remmina/group_rdp_win7_192-168-0-28.remmina
**** สำคัญ ให้ Run user ที่ไม่ใช่ root เพราะจะทำให้ รหัสในไฟล์เปลี่ยน ต้องกรอกรหัสใหม่*****

8. auto start remmina automatic to rdp.
8.2. หน่วงเวลาให้ เปิด remmina ตอน Start เครื่อง ช้าลง เพราะ Wifi ยังไม่ขึ้น
สร้างไฟล์
  1. nano .config/autostart/rdp.sh

เพิ่ม code
#!/bin/bash
env sleep 5
remmina /home/pd1/.local/share/remmina/group_rdp_win7_192-168-0-28.remmina


8.3. เรียกใช้งานในไฟล์ bash ตอนเปิดเครื่องผ่านโปรแกรม remmina โดย
แก้
  1. nano .config/autostart/remmina-applet.desktop

แก้ Exec ให้ไปใช้งานไฟลืข้อ 8.2.
Exec=bash .config/autostart/rdp.sh

ทดลอง Reboot เครื่อง ก็จะ Run และ เปิด RDP Auto

4/27/2022

Raspberry Pi Desktop install vmware tools

 Raspberry Pi Desktop install vmware tools
1. ติดตั้ง

  1. sudo apt-get update
  2. sudo apt-get install open-vm-tools


2. mount vmware tools ที่ VMware Actions --> Guest OS --> Install Vmware Tools


3. Copy ไฟล์ .tar.gz ไปไว้ที่ /tem
  1. cp VMwareTools-10.2.0-XXXXX.tar.gz /tmp/
  2. cd /tmp
  3. tar -zxvf VMwareTools-10.2.0-XXXXXX.tar.gz
  4. cd vmware-tools-distrib
  5. sudo ./vmware-install.pl

4. ขั้นตอน Install กด Enter ตอบตาม Default ที่โปรแกรมกำหนดมา
5. Reboot เครื่อง

12/25/2020

PI : Motion Trick GPIO

Motion Trick GPIO By Python

ถ้า Error
root@raspberrypi:/home/pi# python3 SCI_Notify.py
Traceback (most recent call last):
File "SCI_Notify.py", line 10, in <module>
import RPi.GPIO as GPIO
ModuleNotFoundError: No module named 'RPi'[/quote]

ต้องลง Program เพิ่ม

  1. sudo apt-get -y install python3-rpi.gpio

 

เพิ่มเติมสั่ง Motion ให้สั่ง GPIO ไม่ได้ต้อง
Add user motion เข้า GPIO ก่อน

  1. sudo adduser motion gpio

 

12/10/2020

PI : Python On Delay 10 Seconds

PI : Python On Delay 10 Seconds
การต่อ



เมื่อมีการทำงาน Python จะเปิด Delay และค้างไว้ 10 วิ และสั่ง Trick GPIO ขาที่ต่อ
Code Python
  1. import RPi.GPIO as GPIO
  2. import time
  3.  
  4. stop_time = time.time() + 10
  5.  
  6. GPIO.setmode(GPIO.BOARD)
  7. GPIO.setup(10,GPIO.OUT)
  8.  
  9. try:
  10.     while time.time() < stop_time:
  11.        GPIO.output(10,1)
  12.        time.sleep(0.0015)
  13.        GPIO.output(10,0)
  14.        time.sleep(0.01)
  15.  
  16. except KeyboardInterrupt:
  17.     pass
  18.  
  19. print"Stopping Auto-Feeder"
  20. GPIO.cleanup()

PI : PI Motion Monitor HC-SR501 PIR จับการเคลื่อนไหว และแจ้งเตือน

 PI : PI Motion Monitor HC-SR501 PIR จับการเคลื่อนไหว และแจ้งเตือน
การต่อ


เมื่อมีการเคลื่อนไหว ผ่าน หน้า Sensor ก็จะมีแจ้งเตือน ไฟก็จะติด
Code Python
  1. #!/usr/bin/python
  2.  
  3. import RPi.GPIO as GPIO
  4. import time
  5.  
  6. GPIO.setmode(GPIO.BOARD)            #Set GPIO to pin numbering
  7. pir = 8                             #Assign pin 8 to PIR
  8. led = 10                            #Assign pin 10 to LED
  9. GPIO.setup(pir, GPIO.IN)            #Setup GPIO pin PIR as input
  10. GPIO.setup(led, GPIO.OUT)           #Setup GPIO pin for LED as output
  11. print ("Sensor initializing . . .")
  12. time.sleep(2)                       #Give sensor time to startup
  13. print ("Active")
  14. print ("Press Ctrl+c to end program")
  15.  
  16. try:
  17.   while True:
  18.    if GPIO.input(pir) == True:      #If PIR pin goes high, motion is detected
  19.       print ("Motion Detected!")
  20.       GPIO.output(led, True)        #Turn on LED
  21.       time.sleep(4)                 #Keep LED on for 4 seconds
  22.    GPIO.output(led, False)          #Turn off LED
  23.    time.sleep(0.1)
  24.  
  25. except KeyboardInterrupt:           #Ctrl+c
  26.   pass                              #Do nothing, continue to finally
  27.  
  28. finally:
  29.   GPIO.output(led, False)           #Turn off LED in case left on
  30.   GPIO.cleanup()                    #reset all GPIO
  31.   print ("Program ended")
  32.  

10/27/2020

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/

9/29/2020

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)

6/11/2020

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