The following is the Python script that I want to execute every time Raspberry Pi reboots. When I run this Python script directly from the terminal it works. Not only does IP gets stored in the file but also IP is sent to AWS when this script is executed from the terminal.
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import json
import socket
import time
ENDPOINT = "atfvhlb5vayj2-ats.iot.us-east-1.amazonaws.com"
PORT = 8883
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
# time.sleep(30)
ip_address = get_ip_address()
while(1):
if(ip_address != None):
break
file_path = "/home/pi/Documents/get_ip_py2/ip.txt"
with open(file_path,'w') as file:
file.write(ip_address)
myMQTTClient = AWSIoTMQTTClient(clientID="ip_thing")
myMQTTClient.configureEndpoint(ENDPOINT, PORT)
myMQTTClient.configureCredentials(
CAFilePath = "/home/pi/Downloads/AmazonRootCA1.crt",
KeyPath = "/home/pi/Downloads/ipthingprivate.pem",
CertificatePath = "/home/pi/Downloads/ipthingcertificate.pem")
myMQTTClient.connect()
myMQTTClient.publish(topic="elit/deviceRegister", payload=json.dumps(ip_address),QoS=1)
myMQTTClient.disconnect()
Here is a cronjob that I have created for this:
@reboot /usr/bin/python /home/pi/Documents/get_ip_py2/main.py
This cronjob doesn't execute. This cronjob doesn't even create the file(ip.txt) to store the IP.
I know the path of python and main.py are correct because the following cronjob is executing perfectly.
* * * * * /usr/bin/python /home/pi/Documents/get_ip_py2/main.py
Running the Python script with sudo commands also works:
sudo python main.py