Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

9/23/2025

Home Assistant with Docker กล้อง ONVIF แจ้งเตือนเข้า Rocketchat

 *** หาต้องการให้แสดงรูป ต้องใช้ url
https://rocket.scivalve.com
- หากใช้ IP จะเห็น รูปได้เครื่องอยู่ในวง network เดียวกัน
- ใช้ chat.scivalve.com ใน app จะไม่เห็น เพราะ app ชี้ url ไปที่ rocket.scivalve.com
ให้ใช้ rocket.scivalve.com จะเห็นทั้งในหมด
ขึ้นตอน
1. Add integration ONVIF ถ้ากล้องอยู่วงเดียวกันกับ HA จะเจอเลย ถ้าไม่เจอ Add Manual Port 10080
2. Add กล้องสำหรับ view เข้า Dashboard ไว้ดู By entity แล้วเลือก Profile กล้องที่ต้องการ
*** หาวิธีส่งรูปตรง ๆ จาก HA แล้วไม่ได้ ติดปัญหา กล้องไม่มี function ที่ snap เป็น jpg จึงทำไม่ได้ ****
แก้ปัญหาโดย เขียน code python save ลง docker แล้วให้ HA เรียกใช้ python ส่งแจ้งเตือนเข้า Rocketchat
3. สร้างไฟล์ python ที่ Home Assistant
ไว้ที่ /HA/snapshot.py
Code

  1. #!/usr/bin/env python3
  2. import requests
  3.  
  4. url = "http://xxx.xx.xx.xx:8080/snapshot.cgi?user=xxx&pwd=xxx"
  5. res = requests.get(url, stream=True)
  6.  
  7. if res.status_code == 200:
  8.     #with open("/HA/www/snapshot.jpg", "wb") as f:
  9.     with open("/config/www/snapshot.jpg", "wb") as f:
  10.        for chunk in res.iter_content(1024):
  11.             f.write(chunk)
  12.  
  13.     url = "http://xxx.xx.xx.xx:3000/api/v1/rooms.upload/RoomId"
  14.     #url = "https://chat.scivalve.com/api/v1/rooms.upload/RoomId"
  15.     headers = {
  16.         "X-Auth-Token": "xxx",
  17.         "X-User-Id": "xxx"
  18.     }
  19.    
  20.     files = {
  21.         #"file": ("snapshot.jpg", open("/HA/www/snapshot.jpg", "rb"), "image/jpeg")
  22.         "file": ("snapshot.jpg", open("/config/www/snapshot.jpg", "rb"), "image/jpeg")
  23.     }
  24.  
  25.     data = {
  26.         "msg": "พบการเคลื่อนไหวจากกล้อง SERVER A"
  27.     }
  28.  
  29.     response = requests.post(url, headers=headers, files=files, data=data)
  30.     #print(response.text)
  31.     #print("Snapshot saved")
  32. else:
  33.     print("Error:", res.status_code)


***สำคัญไฟล์ ที่ save และส่ง ต้องใช้ใน /config/ เพื่อให้รูปได้จริง หากไว้ใน /HA/ จะ run คำสั่ง python ตรง ๆ ได้ แต่เมื่อ Home Assistant เรียกใช้จะส่งรูปไม่ได้ ***
RoomId หาได้จาก คำสั่ง
  1. curl -H "X-Auth-Token: xxx" \
  2.      -H "X-User-Id: xxx" \
  3.      http://xxx.xxx.xx.xx:3000/api/v1/rooms.info?roomName=ชื่อห้อง

เช่น
  1. curl -H "X-Auth-Token: xxx" \
  2.      -H "X-User-Id: xxx" \
  3.      http://xxx.xxx.xx.xx:3000/api/v1/rooms.info?roomName=Test

จะได้ _id คือ room id
{"room":{"_id":"xxx","fname":"Test"
{"room":{"_id":"xxx","fname":"IT_Notification",

4. configuration.yaml สำหรับเรียกใช้ python เพิ่ม
  1. shell_command:
  2.    send_snapshot: "python3 /config/snapshot.py"
  3.  


5. automation.yaml เพิ่ม
  1. - id: motion_alert_server_a
  2.   alias: "แจ้งเตือน SERVER A พร้อมส่งรูป"
  3.   trigger:
  4.     - platform: state
  5.       entity_id: binary_sensor.ip_camera_cell_motion_detection
  6.       to: "on"
  7.   action:
  8.     - service: shell_command.send_snapshot

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()

 

10/11/2021

Code Auto Remove Slack เปลี่ยน API ใหม่ Code เดิมลบไม่ได้

Python Auto Remove Slack Chet History.

 เปลี่ยน API

  1. response = sc.api_call('conversations.history', channel=channel, limit=1000, oldest=oldest_ts, latest=latest_ts)


Code สำเร็จ
  1.  
  2.  
  3. from slackclient import SlackClient
  4. #from time import sleep
  5. import time
  6. #import datetime
  7. from datetime import datetime, timedelta
  8.  
  9. legacy_token = 'XXXX'  # don't if you share your code
  10. ########## Chanel Camera ##############
  11. channel = 'XXXX'  # Camera Channel.
  12.  
  13. sc = SlackClient(legacy_token)
  14. response = sc.api_call('channels.info', channel=channel)
  15.  
  16. #oldest_ts = response['channel']['created']
  17. date_days_ago = datetime.now() - timedelta(days=90)
  18. oldest_ts = time.mktime(date_days_ago.timetuple())
  19. print(datetime.fromtimestamp(oldest_ts))
  20.  
  21. #date_days_ago = datetime.now() - timedelta(days=60) # Keep File On Slack 60 Day.
  22. date_days_ago = datetime.now() - timedelta(days=7) # Keep File On Slack 7 Day.
  23. latest_ts = time.mktime(date_days_ago.timetuple())
  24. print(datetime.fromtimestamp(latest_ts))
  25.  
  26. #response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  27. response = sc.api_call('conversations.history', channel=channel, limit=1000, oldest=oldest_ts, latest=latest_ts)
  28. allmsgs = [item['ts'] for item in response['messages']]
  29. print(len(allmsgs))
  30. for msg in allmsgs:
  31.     sc.api_call('chat.delete', channel=channel, ts=msg)
  32.     time.sleep(1)
  33.  
  34. ########### Chanel Server  ###################
  35. channel = 'XXXXX' # Server Channel.
  36.  
  37. sc = SlackClient(legacy_token)
  38. response = sc.api_call('channels.info', channel=channel)
  39.  
  40. #oldest_ts = response['channel']['created']
  41. date_days_ago = datetime.now() - timedelta(days=90)
  42. oldest_ts = time.mktime(date_days_ago.timetuple())
  43. print(datetime.fromtimestamp(oldest_ts))
  44.  
  45. date_days_ago = datetime.now() - timedelta(days=60)
  46. latest_ts = time.mktime(date_days_ago.timetuple())
  47. print(datetime.fromtimestamp(latest_ts))
  48. #response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  49. response = sc.api_call('conversations.history', channel=channel, limit=1000, oldest=oldest_ts, latest=latest_ts)
  50. allmsgs = [item['ts'] for item in response['messages']]
  51. print(len(allmsgs))
  52. for msg in allmsgs:
  53.     sc.api_call('chat.delete', channel=channel, ts=msg)
  54.     time.sleep(1)

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.  

11/28/2019

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Python : Script สำหรับลบข้อความใน Slack อัตโนมัติ

Run ที่เครื่องที่ออกเน็ต ได้ ในที่นี้ใช้เครื่อง Extranet
1. ติดตั้งโปรแกรม
  1. sudo apt-get install python-pip

2. ติดตั้ง Slack Client
  1. pip install slackclient
3. สร้าง code removeSlack.py
  1. from slackclient import SlackClient
  2. #from time import sleep
  3. import time
  4. #import datetime
  5. from datetime import datetime, timedelta
  6.  
  7. legacy_token = 'xxxxxx'  # don't if you share your code
  8. channel = 'Cxxxxx'  # the id of the channel to delete all msgs inside
  9.  
  10. sc = SlackClient(legacy_token)
  11. response = sc.api_call('channels.info', channel=channel)
  12.  
  13. #oldest_ts = response['channel']['created']
  14. date_days_ago = datetime.now() - timedelta(days=60)
  15. oldest_ts = time.mktime(date_days_ago.timetuple())
  16. print(datetime.fromtimestamp(oldest_ts))
  17.  
  18. date_days_ago = datetime.now() - timedelta(days=30)
  19. latest_ts = time.mktime(date_days_ago.timetuple())
  20. print(datetime.fromtimestamp(latest_ts))
  21.  
  22. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  23. allmsgs = [item['ts'] for item in response['messages']]
  24. print(len(allmsgs))
  25. for msg in allmsgs:
  26.     sc.api_call('chat.delete', channel=channel, ts=msg)
  27.     time.sleep(1)
  28. ########### Chanel Server  ###################
  29. channel = 'Cxxxxx'
  30.  
  31. sc = SlackClient(legacy_token)
  32. response = sc.api_call('channels.info', channel=channel)
  33.  
  34. #oldest_ts = response['channel']['created']
  35. date_days_ago = datetime.now() - timedelta(days=60)
  36. oldest_ts = time.mktime(date_days_ago.timetuple())
  37. print(datetime.fromtimestamp(oldest_ts))
  38.  
  39. date_days_ago = datetime.now() - timedelta(days=30)
  40. latest_ts = time.mktime(date_days_ago.timetuple())
  41. print(datetime.fromtimestamp(latest_ts))
  42.  
  43. response = sc.api_call('channels.history', channel=channel, count=1000, oldest=oldest_ts, latest=latest_ts)
  44. allmsgs = [item['ts'] for item in response['messages']]
  45. print(len(allmsgs))
  46. for msg in allmsgs:
  47.     sc.api_call('chat.delete', channel=channel, ts=msg)
  48.     time.sleep(1)
4. chmod ให้ Run ได้
5. สร้าง Cront ให้ run ตามที่ต้องการในที่นี้ run อาทิตย์ละครั้ง วันจันทร์
0 0 * * 1 python /home/pi/removeSlak.py >> /home/pi/removeSlack.log 2>&1

5/29/2019

Code Python ส่ง Slack ใหม่

Code Python ส่ง Slack ใหม่
Code เดิมส่งรูปสุดท้าย บางครั้งได้รูปว่าง
แก้ Code ใหม่เอารูปที่ 4 นับจากที่ Video มีการบันทึก
แล้วลบ jpg ทิ้ง
  1.  
  2. from slackclient import SlackClient
  3.  
  4. sc = SlackClient("xoxb-XXXXXXX")
  5.  
  6. import glob
  7. import os
  8.  
  9. #list jpg to array
  10. list_of_files = glob.glob('/home/pi/Pictures/*.jpg')
  11. if len(list_of_files) > 4:
  12.   file_select = list_of_files[4]
  13.   with open(file_select) as file_content:
  14.        sc.api_call(
  15.          "files.upload",
  16.          channels="CF6GEHBDF",
  17.          file=file_content,
  18.          title="IP Camera Room A 192.168.2.133."
  19.        )
  20. #delete jpg
  21. for i in glob.glob("/home/pi/Pictures/*.jpg"):
  22.   os.remove(i)

3/28/2018

Python : Python ส่งค่าเข้า MQTT

Python : Python ส่งค่าเข้า MQTT
  1.        # Start MQTT #
  2.         import paho.mqtt.client as mqtt
  3.  
  4.         mqttc = mqtt.Client("python_pub")
  5.         mqttc.connect("192.168.2.200", 1883)
  6.         mqttc.publish("hass/temperature_server_A", temperature)
  7.         mqttc.loop(2) #timeout = 2s
  8.  
  9.         # End MQTT #


Error ImportError: No module named paho.mqtt.client
  1. root@raspberrypi:/home/pi# python mqtt.py
  2. Traceback (most recent call last):
  3.   File "mqtt.py", line 21, in <module>
  4.     import paho.mqtt.client as mqtt
  5. ImportError: No module named paho.mqtt.client


  1. sudo apt-get install python-pip
  1. pip install paho-mqtt



คำสั่งพื้นฐาน

ดูสถานะ error สามารถใช้ start stop restart status
ไว้ Restart ถ้า Restart ผ่านหน้า Web แล้วไม่ทำงาน
  1. sudo systemctl status home-assistant@homeassistant


Python Auto Start Background On Pi

  1. chmod 755 /etc/rc.local

add before "exit 0"
  1. (sleep 10;sudo python /home/pi/mqttAir.py) &

11/06/2016

Python : python call file python , While, Time Delay

python : python call file python

Code : Call other file
  1. import os
  2. os.system('filename.py')

Example :
  1. os.system('/home/pi/checkair.py')


Code : Time Delay
  1. import time
  2. while True:
  3.     print "This prints once a minute."
  4.     time.sleep(60)  # Delay for 1 minute (60 seconds)


Example : All
  1. #!/usr/bin/python
  2. #### Check temperature Adafruit_DHT 22 23 #######
  3. import sys
  4. import os
  5. import Adafruit_DHT
  6. import time
  7.  
  8. humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  9.  
  10. #while(humidity is None and temperature is None):
  11. while(temperature is None):
  12.         humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  13.         time.sleep(10)  # Delay for 10 seconds before loop.
  14.  
  15. #### On Or Off Relay By Piface  #####
  16. import pifacedigitalio
  17. pf = pifacedigitalio.PiFaceDigital()
  18. import smtplib
  19.  
  20. print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
  21. if temperature > 27:
  22.         pf.relays[1].turn_on()
  23.         pf.relays[0].turn_on()
  24.  
  25.         from smtplib import SMTP
  26.  
  27.         recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  28.         def send_email (message, status):
  29.                 fromaddr = 'scivalve.suwit@gmail.com'
  30.                 server = SMTP('smtp.gmail.com:587')
  31.                 server.ehlo()
  32.                 server.starttls()
  33.                 server.ehlo()
  34.                 server.login('scivalve.suwit@gmail.com', 'PASSWORD')
  35.                 server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  36.                 server.quit()
  37.  
  38.         send_email("High temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "High temp alert! Turn ON relays.")
  39. else:
  40.         pf.relays[0].turn_off()
  41.         pf.relays[1].turn_off()
  42.  
  43. pf.deinit_board()
  44.  

http://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another

9/09/2016

Raspberry PI :: Raspberry PI Fix IP

Raspberry PI :: Raspberry PI Fix IP
1. Run Command
  1. nano /etc/network/interfaces

2. Example Fix IP
  1. auto eth0
  2. allow-hotplug eth0
  3. #iface eth0 inet manual
  4. iface eth0 inet static
  5. #your static IP
  6. address 192.168.0.3
  7. #your gateway IP
  8. gateway 192.168.0.2
  9. netmask 255.255.255.0
  10. #your network address "family"
  11. network 192.168.0.2
  12. broadcast 192.168.0.255

3. Restart Service
  1. /etc/init.d/networking restart

http://elinux.org/RPi_Setting_up_a_static_IP_in_Debian

Python :: python send email gmail One User recipient.

Python :: python send email gmail One User recipient.
1. Code
  1. import smtplib
  2.  
  3. fromaddr = 'fromuser@gmail.com'
  4. toaddrs  = 'touser@gmail.com'
  5. msg = 'There was a terrible error that occured and I wanted you to know!'
  6.  
  7.  
  8. # Credentials (if needed)
  9. username = 'username'
  10. password = 'password'
  11.  
  12. # The actual mail send
  13. server = smtplib.SMTP('smtp.gmail.com:587')
  14. server.starttls()
  15. server.login(username,password)
  16. server.sendmail(fromaddr, toaddrs, msg)
  17. server.quit()

Example :: https://www.nixtutor.com/linux/send-mai ... th-python/

Python :: python send email gmail multiple recipients.

Python :: python send email gmail multiple recipients.
1. Create file sendmail.py
2. Insert Code
  1. #!/usr/bin/python
  2. import smtplib
  3. from smtplib import SMTP
  4.  
  5. recipients = ['suwit.jph@gmail.com', 'suwit_jph@hotmail.co.th']
  6.  
  7. def send_email (message, status):
  8.     fromaddr = 'scivalve.suwit@gmail.com'
  9.     server = SMTP('smtp.gmail.com:587')
  10.     server.ehlo()
  11.     server.starttls()
  12.     server.ehlo()
  13.     server.login('scivalve.suwit@gmail.com', 'password')
  14.     server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  15.     server.quit()
  16.  
  17. send_email("Test","Test send mail")
  18.  
  19.  

3. Test Run Command.
  1. ./sendmail.py

Example : http://stackoverflow.com/questions/2050 ... -addresses

Python :: Python + Piface เช็คอุหภูมิปิดเปิดแอร์ Auto

Python :: Python + Piface เช็คอุณหภูมิปิดเปิดแอร์ Auto
1. ติดตั้ง OS
2. ติดตั้ง Python
  1. sudo apt-get install python{,3}-pifacedigitalio

3. ติดตั้ง library สำหรับ Run python เช็คอุณหภูมิ https://learn.adafruit.com/dht-humidity ... ll-updated
  1. cd Adafruit_Python_DHT
  1. sudo apt-get update
  1. sudo apt-get install build-essential python-dev python-openssl
  1. sudo python setup.py instal
l
4. สร้างไฟล์ checkair.py ด้วยคำสั่ง
  1. nano checkair.py

ใส่ code
  1.                                                                                               
  2. #!/usr/bin/python
  3. #### Check temperature Adafruit_DHT 22 23 #######
  4. import sys
  5.  
  6. import Adafruit_DHT
  7.  
  8. # Parse command line parameters.
  9. # Use This.
  10. #sensor_args = { '11': Adafruit_DHT.DHT11,
  11. #                                '22': Adafruit_DHT.DHT22,
  12. #                                '2302': Adafruit_DHT.AM2302 }
  13. #if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
  14. #        sensor = sensor_args[sys.argv[1]]
  15. #        pin = sys.argv[2]
  16. #else:
  17. #        print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#'
  18. #        print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4'
  19. #        sys.exit(1)
  20.  
  21. # Try to grab a sensor reading.  Use the read_retry method which will retry up
  22. # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
  23. #humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
  24. humidity, temperature = Adafruit_DHT.read_retry(22, 23)
  25.  
  26.  
  27. # Un-comment the line below to convert the temperature to Fahrenheit.
  28. # temperature = temperature * 9/5.0 + 32
  29.  
  30. # Note that sometimes you won't get a reading and
  31. # the results will be null (because Linux can't
  32. # guarantee the timing of calls to read the sensor).  
  33. # If this happens try again!
  34. if humidity is not None and temperature is not None:
  35.         print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
  36. else:
  37.         print 'Failed to get reading. Try again!'
  38.         sys.exit(1)
  39.  
  40. #### Opne and Close Relay By Piface  #####
  41.  
  42. import pifacedigitalio
  43. pf = pifacedigitalio.PiFaceDigital()
  44.  
  45. #pf.leds[1].turn_on()
  46. #pf.leds[2].turn_on()
  47. #pf.leds[3].turn_on()
  48. #pf.leds[4].turn_on()
  49. #pf.leds[5].turn_on()
  50. #pf.leds[6].turn_on()
  51. #pf.leds[7].turn_on()
  52. #### ON #####
  53. import smtplib
  54.  
  55. if temperature > 27:
  56.         pf.relays[1].turn_on()
  57.         pf.relays[0].turn_on()
  58.  
  59.         from smtplib import SMTP
  60.  
  61.         recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  62.  
  63.         def send_email (message, status):
  64.                 fromaddr = 'mail'
  65.                 server = SMTP('smtp.gmail.com:587')
  66.                 server.ehlo()
  67.                 server.starttls()
  68.                 server.ehlo()
  69.                 server.login('mail', 'password')
  70.                 server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  71.                 server.quit()
  72.  
  73.         send_email("High temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "High temp alert! Turn ON relays.")
  74. else:
  75.         pf.relays[0].turn_off()
  76.         pf.relays[1].turn_off()
  77.  
  78.         #from smtplib import SMTP
  79.  
  80.         #recipients = ['suwit.jph@gmail.com', '"komkid@gmail.com', 'nontiwaza@gmail.com']
  81.  
  82.         #def send_email (message, status):
  83.         #        fromaddr = 'mail'
  84.         #        server = SMTP('smtp.gmail.com:587')
  85.         #        server.ehlo()
  86.         #        server.starttls()
  87.         #        server.ehlo()
  88.         #        server.login('mail', 'password')
  89.         #        server.sendmail(fromaddr, recipients, 'Subject: %s\r\n%s' % (status, message))
  90.         #        server.quit()
  91.         #send_email("Temp alert! in Server Room A. " '{0:0.1f}*C'.format(temperature), "Temp alert! Turn OFF Relays.")
  92.  
  93. pf.deinit_board()
  94.  
  95.  

5. Run ไฟล์ py ด้วยคำสั่ง
  1. ./checkair.py 22 23

6. ตั้งให้ Run ตามเวลาใน crontab
  1. crontab -e

เพิ่มเวลาที่ต้องการให้ run เข้าไป
*/5 * * * * ./checkair.py 22 23

การต่อ วงจร ตามรูป

Python :: Python Check Speed Internet get Data for USE. PHP

Python :: Python Check Speed Internet get Data for USE.
1. Install follow This. http://porpramarn.blogspot.com/2016/09/python-python-check-speed-internet-on.html
2. Create File nettest.py
  1. nano nettest.py

3. Insert This Code.
  1. #!/usr/bin/python
  2. import os
  3. import sys
  4. import csv
  5. import datetime
  6. import time
  7. #import twitter
  8.  
  9. def test():
  10.  
  11.         #run speedtest-cli
  12.         print 'running test'
  13.         # /usr/bin/speedtest-cli
  14.         a = os.popen("python /usr/bin/speedtest-cli --simple").read()
  15.         # a = os.popen("python /home/pi/speedtest/speedtest-cli --simple").read()
  16.         print 'ran'
  17.         #split the 3 line result (ping,down,up)
  18.         lines = a.split('\n')
  19.         print a
  20.         ts = time.time()
  21.         date =datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
  22.         #if speedtest could not connect set the speeds to 0
  23.         if "Cannot" in a:
  24.                 p = 100
  25.                 d = 0
  26.                 u = 0
  27.         #extract the values for ping down and up values
  28.         else:
  29.                 p = lines[0][6:11]
  30.                 d = lines[1][10:14]
  31.                 u = lines[2][8:12]
  32.         print date,p, d, u
  33.         #save the data to file for local network plotting
  34.         # out_file = open('/var/www/assets/data.csv', 'a')
  35.         out_file = open('/home/pi/data.csv', 'a')
  36.  
  37.         writer = csv.writer(out_file)
  38.         writer.writerow((ts*1000,p,d,u))
  39.         out_file.close()
  40.         return
  41.  
  42. if __name__ == '__main__':
  43.         test()
  44.         print 'completed'
  45.  

4. Run python
  1. python nettest.py

Data
1454725814235.995,23.64,39.1,21.6

5. Use file data.csv Or Insert to database.

http://pastebin.com/WMEh802V

######################################################################
ติดตั้ง phpmyadmin เพิ่มต่อเพื่อดึงข้อมูลเข้า database เก็บไว้ใช้งานต่อไป
ติดตั้ง
  1. sudo apt-get install apache2
  1. sudo apt-get install mysql-server
  1. sudo apt-get install php5
  1. sudo apt-get install phpmyadmin


1. สร้าง ไฟล์ net-check.php ที่ var/www/
  1. nano /var/www/nano net-check.php

2. เพิ่มคนสำหรับ Check Speed Net ที่ Python และส่งเมล์เตือนเมื่อ Speed ได้ต่ำกว่ากำหนด Code
  1. <?php
  2. // Read Data From DHT22
  3. $strDateTime = date("Y-m-d H:i:s");
  4. //$strDhtData = exec("/usr/local/bin/Adafruit_DHT 22 23");
  5.  
  6. $command = escapeshellcmd('/home/pi/nettest.py');
  7. $output = shell_exec($command);
  8. //echo $output;
  9.  
  10. list($date, $time, $ping, $download, $upload) = explode(" ", $output);
  11.  
  12. echo $date.",".$time.",".$ping.",".$download.",".$upload;
  13.  
  14.         $fp = fopen('/var/www/data-net.txt', 'a+');
  15.         fwrite($fp, "Date = $, {$output}");
  16.         fclose($fp);
  17.  
  18.         if(floatval($download) < 50){
  19.                 $strToPost = "\nFrom Raspberry : Date = {$date} {$time} : Ping = {$ping} : Download = {$download} : Upload = {$upload} \n";
  20.                 //echo $strToPost;
  21. $ret = mail("komkid@gmail.com,suwit.jph@gmail.com,nontiwaza@gmail.com", "Internet Test Speed is low. Please Check Internet Connection.", $strToPost, "From: SCI Raspberry\n");
  22.                 //$ret = mail("suwit.jph@gmail.com","Internet Test Speed is low. Please Check Internet Connection.", $strToPost, "From: SCI Raspberry\n");
  23.                 if($ret)
  24.                         echo "OK {$output}";
  25.                 else
  26.                         echo "Failed!";
  27.         }
  28.  
  29. ?>
  30.  
  31.  


3. Chmod file pytho เพื่อให้ php สามารถ run ได้
  1. chmod +x nettest.py
ทดลอง Run ผ่าน Terminal แล้วดูผล
  1. /usr/bin/php /var/www/net-check.php

4. ตั้งเวลาให้ Run ทุก 1 ชั่วโมง โดยใช้คำสั่ง
  1. crontab -e

และเพิ่ม
  1. #Check Internet Every 1 Hours
  2. 0 * * * * /usr/bin/php /var/www/temp-alert.php

http://pastebin.com/WMEh802V