File size: 4,128 Bytes
08dc47d
479fa28
 
67f1d47
 
60bd708
67f1d47
 
 
 
 
 
 
9b153ed
67f1d47
479fa28
08dc47d
 
 
479fa28
 
67f1d47
479fa28
 
 
67f1d47
 
479fa28
08dc47d
67f1d47
479fa28
 
08dc47d
 
 
 
 
67f1d47
08dc47d
479fa28
08dc47d
 
 
 
 
 
479fa28
67f1d47
 
60bd708
67f1d47
60bd708
67f1d47
 
 
 
91d808a
 
 
 
e606e82
91d808a
 
 
 
 
 
 
 
 
8fc4c93
91d808a
 
 
 
7d0ce22
91d808a
 
67f1d47
479fa28
7d0ce22
67f1d47
 
 
91d808a
67f1d47
91d808a
7d0ce22
479fa28
7d0ce22
67f1d47
ab4d419
479fa28
7d0ce22
 
479fa28
 
7d0ce22
479fa28
 
7d0ce22
 
 
 
13ec4f8
91d808a
7d0ce22
479fa28
 
7d0ce22
479fa28
 
 
08dc47d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import os
import requests
import gradio as gr
import gspread
from google.oauth2.service_account import Credentials
from datetime import datetime

# Autenticaci贸n con Google Sheets usando el archivo credentials.json
scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
creds = Credentials.from_service_account_file("credentials.json", scopes=scope)
client = gspread.authorize(creds)

# Abre el Google Sheet (reemplaza 'NOMBRE_DE_TU_SHEET' por el nombre de tu hoja)
spreadsheet = client.open("Sim Cards Invertaxi")
sheet = spreadsheet.sheet1  # Asume que trabajas en la primera hoja

# Obtener el token de la variable de entorno
api_token = os.getenv('API_TOKEN')

def get_sim_status(iccid):
    url = f"https://iot.truphone.com/api/v2.2/sims/{iccid}/status"
    headers = {"Authorization": f"Token {api_token}"}
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        print("Solicitud exitosa:", response.json())
        return response.json()
    else:
        print(f"Error al realizar la solicitud: {response.status_code}")
        return None

def send_sms(iccid, text):
    url = "https://iot.truphone.com/api/v2.0/sims/send_sms"
    headers = {
        "Authorization": f"Token {api_token}",
        "Content-Type": "application/json"
    }
    body = {"iccid": [iccid], "text": text}
    response = requests.post(url, json=body, headers=headers)

    if response.status_code == 200:
        print("Mensaje enviado exitosamente")
        return "ok"
    else:
        print(f"Error al enviar el mensaje: {response.status_code}")
        return "error"

def save_to_google_sheets(iccid, placa, imei, operario):
    """Guarda los datos en Google Sheets."""
    fecha_actual = datetime.now().strftime('%Y-%m-%d')
    try:
        sheet.append_row([iccid, placa, imei, operario, fecha_actual])
        print("Datos guardados exitosamente en Google Sheets.")
    except Exception as e:
        print(f"Error al guardar en Google Sheets: {e}")

def program_gps(iccid_list, placa, imei, operario, tipo_gps):
    """Programa los GPS con comandos espec铆ficos seg煤n el tipo de dispositivo."""
    messages = {
        'Coban': [
            'begin123456',
            'apn123456 iot.truphone.com',
            'fix090s***n123456',
            'dns123456 track.falconcol.com 5001',
            'gprs123456',
            'reset123456'
        ],
        'Concox': [
            'Apn,iot.truphone.com#',
            'TIMER,90,1200#',
            "SERVER,1,track.falconcol.com,5023,0#",
            'RESET#'
        ]
    }
    
    iccids = iccid_list.split(',')
    text = f"Programaci贸n iniciada por {operario} para GPS tipo {tipo_gps}.\n\n"
    gps_messages = messages[tipo_gps]

    for sim in iccids:
        sim = sim.strip()
        status_response = get_sim_status(sim)
        sim_card_service = status_response.get('status', {}).get('sim_card_service', "error") if status_response else "error"

        aswr_ok = sum([1 for message in gps_messages if send_sms(sim, message) == "ok"])

        if aswr_ok == len(gps_messages):
            status_text = f"{sim} (Placa: {placa}, IMEI: {imei}) - ok.\n"
            if sim_card_service == 'SUSPENDED':
                status_text += "Bloqueada por consumo, solicitar reactivaci贸n.\n"
            text += status_text
            save_to_google_sheets(sim, placa, imei, operario)
        else:
            text += f"{sim} (Placa: {placa}, IMEI: {imei}) - fail\n"
    
    return text

# Crea una interfaz de Gradio con los nuevos campos
iface = gr.Interface(
    fn=program_gps,
    inputs=[
        gr.Textbox(label="Introduce los ICCIDs separados por comas"),
        gr.Textbox(label="Placa del veh铆culo"),
        gr.Textbox(label="IMEI del dispositivo"),
        gr.Radio(choices=["Santiago", "Daniel"], label="Operario"),
        gr.Radio(choices=["Coban", "Concox"], label="Tipo de GPS")
    ],
    outputs="text",
    title="Programador de GPS",
    description="Introduce los ICCIDs, la placa, el IMEI y selecciona un operario para programar los GPS."
)

# Lanza la interfaz
iface.launch()