import socket
import threading
import requests
import json
###тут указывать именно ваши данные################
pak_url="https://pakvcmk.ru/api/"
pak_username="garant05"
pak_password="w5ww0x"
###################################################
token=""
checked_connection=False
def send_to_telegram(message):
try:
print(message)
#return ""
chat_id="-668116312"
botToken="5959401610:AAHoz3P7o50NmlBWtQwtCP6tHdCmJa1yyhc"
r = requests.post("https://api.telegram.org/bot"+botToken+"/sendMessage", data={"chat_id": chat_id,"text":message})
print("https://api.telegram.org/bot"+botToken+"/sendMessage")
print(r.text)
except:
tt=1
def get_token_for_pak():
global token
try:
headers={"Content-Type":'application/json'}
payload={"username": pak_username,"password":pak_password}
print(payload)
r = requests.post(pak_url+"login", json=payload, headers=headers)
response = json.loads(r.text)
print("\r\n============================\r\n")
print(response)
print("\r\n============================\r\n")
if(response["token"]!=""):
token=response["token"]
#print("token_from_pak="+token)
return token
else:
send_to_telegram("Ошибка при попытке авторизации в ПАК")
except Exception as ex:
tt=1
print("\r\n==============EXCEPTION==============\r\n")
print(ex)
send_to_telegram("Ошибка при попытке авторизации в ПАК")
def get_pak_objects():
global token
headers={"Content-Type":'application/json','Authorization':'Bearer '+token}
try:
r = requests.get(pak_url+"objects", headers=headers)
response = json.loads(r.text)
#print(response)
return response
except Exception as ex:
print(ex)
send_to_telegram("Ошибка при получении списка объектов в ПАК")
def create_alarm(object_id,object_num,founded_zone_id,description,zone_num):
global token
try:
headers={"Content-Type":'application/json','Authorization':'Bearer '+token}
if(founded_zone_id!=None):
payload={"object_id": object_id,"events": [{"zone_id":founded_zone_id,"type_id":0, "comment": description}]}
else:
payload={"object_id": object_id,"events": [{"type_id":0, "comment": description}]}
print(payload)
r = requests.post(pak_url+"alert", json=payload, headers=headers)
response = json.loads(r.text)
print(response)
if(response["alert_id"]!=""):
alert_id=response["alert_id"]
send_to_telegram("Тревога для объекта с пультовым номером "+str(object_num)+" и номером зоны "+str(zone_num)+" успешно отправлена в ПАК!")
return alert_id
else:
send_to_telegram("Ошибка при попытке отправить тревогу на объекте с пультовым номером "+str(object_id)+"и номером зоны "+str(zone_num)+" в ПАК!")
except Exception as ex:
tt=1
print(ex)
send_to_telegram("Ошибка при попытке отправить тревогу на объекте с пультовым номером "+str(object_id)+" в ПАК!")
def send_to_pak(object_id,type_alarm,description,zone_num):
global token
token = get_token_for_pak()
objects=get_pak_objects()
founded_object_id=""
print("objects=\r\n")
print(objects)
print("==================================\r\n\r\n")
for object in objects:
print("checking...")
print(object["object_num"])
print(object_id)
print("\r\n\r\n")
if(int(object["object_num"])==object_id):
print(object["object_num"]+"=>"+object["object_id"])
founded_object_id=object["object_id"]
zones=object["zones"]
for zone in zones:
if(int(zone["zone_num"])==int(zone_num)):
founded_zone_id=zone["zone_id"]
founded_zone_name=zone["name"]
founded_zone_description=zone["description"]
description=founded_zone_name+" ("+founded_zone_description+")"
if(founded_zone_id==None):
send_to_telegram("Ошибка при отправке тревоги в ПАК, зона с номером "+str(zone_num)+" не найдена!")
else:
create_alarm(object["object_id"],object_id,founded_zone_id,description,zone_num)
if(founded_object_id==""):
send_to_telegram("Объект с пультовым номером "+str(object_id)+" не найден, или не поставлен на охрану в ПАКе!")
def decode_andromeda(mess):
if(len(mess)>32):
type_mess=mess[0]+mess[1]+mess[2]+mess[3]
object_id=mess[7]+mess[8]+mess[9]+mess[10]
type_alarm=mess[11]+mess[12]+mess[13]+mess[14]
zone_num=mess[15]+mess[16]+mess[17]+mess[18]+mess[19]
print("type_mess="+type_mess+", object_id="+object_id+", type_alarm="+type_alarm+", zone_num="+zone_num)
description=""
#if(type_alarm=="R401"):
# description="Взятие на охрану"
#if(type_alarm=="E401"):
# description="Снятие с охраны"
if(type_alarm=="E120"):
description="Тревога КТС"
if(type_alarm=="E760"):
description="Тревога КТС"
if(type_alarm=="E130"):
description="Тревога датчик"
if(description!=""):
send_to_pak(int(object_id),type_alarm,description,zone_num)
else:
send_to_telegram("Объект с пультовым номером "+object_id+", код события "+type_alarm+", такого кода не знаю, в ПАК не отправляю")
def handle_client(conn, addr):
global checked_connection
while True:
msg_length = conn.recv(1024) # I got the error when I put server.recv
print(msg_length)
conn.send(b"\x06")
conn.close()
mess = msg_length.decode('utf-8')
if("1011 " not in mess):
send_to_telegram("Сообщение от Андромеды: "+mess)
decode_andromeda(mess)
else:
if(checked_connection==False):
checked_connection=True
send_to_telegram("Получил первое сообщение от Андромеды, все хорошо!")
print(mess)
#send_to_telegram("heart: "+mess)
break
#if msg_length:
# msg = conn.recv(int(msg_length)).decode('utf-8') # Here too
# print(msg)
def start():
server.listen()
while True:
conn, addr = server.accept()
print("accepted from ",addr)
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
send_to_telegram("Запуск скрипта приема данных от Андромеды")
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 26000))
#mess="5011 180004E1200001811:15:49-11/08"
#decode_andromeda(mess)
start()
а это все, что написано, которая раньше отправляла данные.