2024-07-21 -

This commit is contained in:
Adolfo Delorenzo 2024-07-21 19:55:14 -06:00
parent 66b2444317
commit 10b583f235
7 changed files with 1545 additions and 1301 deletions

0
gps.py Normal file → Executable file
View File

0
gps00.py Normal file → Executable file
View File

37
gps01.py Normal file → Executable file
View File

@ -7,12 +7,15 @@ import time, os
import csv import csv
from datetime import datetime from datetime import datetime
# GPIO configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# MQTT Broker settings # MQTT Broker settings
mqttBroker ="65.108.199.212" mqttBroker ="65.108.199.212"
myhost = os.uname()[1] myhost = os.uname()[1]
client = mqtt.Client(myhost) client = mqtt.Client(myhost)
# client.connect(mqttBroker, 1883) # client.connect(mqttBroker, 1883)
ser = serial.Serial('/dev/ttyS0',115200) ser = serial.Serial('/dev/ttyS0',115200)
ser.flushInput() ser.flushInput()
@ -52,6 +55,7 @@ def write_to_csv(lat, lon):
with open(csv_filename, mode='a', newline='') as file: with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file) writer = csv.writer(file)
writer.writerow([timestamp, lat, lon]) writer.writerow([timestamp, lat, lon])
def send_at(command,back,timeout): def send_at(command,back,timeout):
rec_buff = '' rec_buff = ''
@ -72,7 +76,8 @@ def send_at(command,back,timeout):
converted_gps = f"{lat}, {lon}" converted_gps = f"{lat}, {lon}"
print("Converted GPS data for Google Maps:", converted_gps) print("Converted GPS data for Google Maps:", converted_gps)
client.publish("iiot/"+ myhost +"/gps", converted_gps) client.publish("iiot/"+ myhost +"/gps", converted_gps)
write_to_csv(lat, lon) current_time = datetime.datetime.now()
write_to_csv(current_time, lat, lon)
return 1 return 1
else: else:
print('GPS no está listo') print('GPS no está listo')
@ -84,6 +89,7 @@ def get_gps_position():
print('Iniciando GPS') print('Iniciando GPS')
rec_buff = '' rec_buff = ''
send_at('AT+CGPS=1,1','OK',1) send_at('AT+CGPS=1,1','OK',1)
send_at("AT+CNTP=\"pool.ntp.org\",52")
time.sleep(2) time.sleep(2)
while rec_null: while rec_null:
answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1) answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1)
@ -101,26 +107,6 @@ def get_gps_position():
return False return False
time.sleep(1.5) time.sleep(1.5)
def power_on(power_key):
print('SIM7600X is starting:')
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(power_key,GPIO.OUT)
time.sleep(0.1)
GPIO.output(power_key,GPIO.HIGH)
time.sleep(2)
GPIO.output(power_key,GPIO.LOW)
time.sleep(20)
ser.flushInput()
print('SIM7600X is ready')
def power_down(power_key):
print('SIM7600X is loging off:')
GPIO.output(power_key,GPIO.HIGH)
time.sleep(3)
GPIO.output(power_key,GPIO.LOW)
time.sleep(18)
print('Good bye')
# Create CSV file with headers if it doesn't exist # Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename): if not os.path.exists(csv_filename):
@ -129,14 +115,13 @@ if not os.path.exists(csv_filename):
writer.writerow(csv_headers) writer.writerow(csv_headers)
try: try:
#power_on(power_key)
get_gps_position() get_gps_position()
#power_down(power_key)
except: except:
if ser != None: if ser != None:
ser.close() ser.close()
#power_down(power_key)
GPIO.cleanup() GPIO.cleanup()
if ser != None: if ser != None:
ser.close() ser.close()
GPIO.cleanup() GPIO.cleanup()

142
gps02.py Normal file
View File

@ -0,0 +1,142 @@
#!/usr/bin/python
# -*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import serial
import time, os
import csv
from datetime import datetime
# MQTT Broker settings
mqttBroker ="65.108.199.212"
myhost = os.uname()[1]
client = mqtt.Client(myhost)
# client.connect(mqttBroker, 1883)
ser = serial.Serial('/dev/ttyS0',115200)
ser.flushInput()
rec_buff = ''
time_count = 0
# CSV file settings
csv_filename = f"gps_data_{myhost}.csv"
csv_headers = ["Timestamp", "Latitude", "Longitude"]
def convert_to_decimal(coord_str):
coord = coord_str[:-2]
direction = coord_str[-1]
degrees = float(coord[:2] if direction in ['N', 'S'] else coord[:3])
minutes = float(coord[2:] if direction in ['N', 'S'] else coord[3:])
decimal = degrees + (minutes / 60)
if direction in ['S', 'W']:
decimal = -decimal
return decimal
def parse_gps_data(gps_string):
parts = gps_string.split(',')
if len(parts) != 4:
return "Invalid GPS data"
lat = convert_to_decimal(parts[0] + ',' + parts[1])
lon = convert_to_decimal(parts[2] + ',' + parts[3])
return f"{lat:.6f}", f"{lon:.6f}"
def write_to_csv(lat, lon):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(csv_filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, lat, lon])
def send_at(command,back,timeout):
rec_buff = ''
ser.write((command+'\r\n').encode())
time.sleep(timeout)
if ser.inWaiting():
time.sleep(0.01)
rec_buff = ser.read(ser.inWaiting())
if rec_buff != '':
if back not in rec_buff.decode():
print(command + ' ERROR')
print(command + ' back:\t' + rec_buff.decode())
return 0
else:
gps_data = rec_buff.decode()[13:-36]
print("Raw GPS data:", gps_data)
lat, lon = parse_gps_data(gps_data)
converted_gps = f"{lat}, {lon}"
print("Converted GPS data for Google Maps:", converted_gps)
client.publish("iiot/"+ myhost +"/gps", converted_gps)
write_to_csv(lat, lon)
return 1
else:
print('GPS no está listo')
return 0
def get_gps_position():
rec_null = True
answer = 0
print('Iniciando GPS')
rec_buff = ''
send_at('AT+CGPS=1,1','OK',1)
time.sleep(2)
while rec_null:
answer = send_at('AT+CGPSINFO','+CGPSINFO: ',1)
client.publish("iiot/"+ myhost +"/gps", rec_buff, 0)
if 1 == answer:
answer = 0
if ',,,,,,' in rec_buff:
print('GPS no está listo')
rec_null = False
time.sleep(1)
else:
print('error %d'%answer)
rec_buff = ''
send_at('AT+CGPS=0','OK',1)
return False
time.sleep(1.5)
def power_on(power_key):
print('SIM7600X is starting:')
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(power_key,GPIO.OUT)
time.sleep(0.1)
GPIO.output(power_key,GPIO.HIGH)
time.sleep(2)
GPIO.output(power_key,GPIO.LOW)
time.sleep(20)
ser.flushInput()
print('SIM7600X is ready')
def power_down(power_key):
print('SIM7600X is loging off:')
GPIO.output(power_key,GPIO.HIGH)
time.sleep(3)
GPIO.output(power_key,GPIO.LOW)
time.sleep(18)
print('Good bye')
# Create CSV file with headers if it doesn't exist
if not os.path.exists(csv_filename):
with open(csv_filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(csv_headers)
try:
#power_on(power_key)
get_gps_position()
#power_down(power_key)
except:
if ser != None:
ser.close()
#power_down(power_key)
GPIO.cleanup()
if ser != None:
ser.close()
GPIO.cleanup()

File diff suppressed because it is too large Load Diff

1373
gps_data_raspberrypi.csv.bkp Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,7 @@ import minimalmodbus
import time, os import time, os
import serial import serial
import RPi.GPIO as GPIO import RPi.GPIO as GPIO
import subprocess
import paho.mqtt.client as mqtt import paho.mqtt.client as mqtt
# MQTT Broker settings # MQTT Broker settings
@ -13,7 +14,7 @@ client.connect(mqttBroker, 1883)
# Modbus configuration # Modbus configuration
mb_address = 1 # Modbus address mb_address = 1 # Modbus address
sensy_boi = minimalmodbus.Instrument('/dev/ttyUSB0', mb_address) sensy_boi = minimalmodbus.Instrument('/dev/ttyUSB5', mb_address)
sensy_boi.serial.baudrate = 9600 sensy_boi.serial.baudrate = 9600
sensy_boi.serial.bytesize = 8 sensy_boi.serial.bytesize = 8
sensy_boi.serial.parity = minimalmodbus.serial.PARITY_NONE sensy_boi.serial.parity = minimalmodbus.serial.PARITY_NONE
@ -27,22 +28,27 @@ sensy_boi.close_port_after_each_call = True
# GPIO configuration # GPIO configuration
GPIO.setmode(GPIO.BCM) GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Define pin numbers # Define pin numbers
PIN_17 = 17 PIN_17 = 17
PIN_23 = 23 PIN_23 = 23
LuzPuerta = 18
LuzEncendido = 25
# Set GPIO # Set GPIO
GPIO.setup(PIN_17, GPIO.IN) GPIO.setup(PIN_17, GPIO.IN)
GPIO.setup(PIN_23, GPIO.IN) GPIO.setup(PIN_23, GPIO.IN)
GPIO.setup(LuzPuerta, GPIO.OUT)
GPIO.setup(LuzEncendido, GPIO.OUT)
try: try:
while True: while True:
status_17 = GPIO.input(PIN_17) status_17 = GPIO.input(PIN_17)
if GPIO.input(23) == GPIO.HIGH: if GPIO.input(23) == GPIO.HIGH:
print("Adquiriendo datos...") print("Adquiriendo datos...")
subprocess.run(['python3', '/home/pi/jdz/gps01.py'])
# Read data from multiple registers # Read data from multiple registers
data = sensy_boi.read_registers(0, 2, 3) data = sensy_boi.read_registers(0, 2, 3)
@ -64,11 +70,16 @@ try:
print("-------------------------------------") print("-------------------------------------")
print("") print("")
time.sleep(1.5) #time.sleep(5)
except KeyboardInterrupt: if GPIO.input(PIN_17) == GPIO.LOW:
print("Programa terminado por el usuario") GPIO.output(LuzPuerta, GPIO.HIGH) # Luz Roja encendida
else:
GPIO.output(LuzPuerta, GPIO.LOW)
GPIO.output(LuzEncendido, GPIO.HIGH)
time.sleep(5)
except Exception as e: except Exception as e:
print(f"Error: {str(e)}") print(f"Error: {str(e)}")
finally: finally: