Найти - Пользователи
Полная версия: rs485 - usb - win 10х64- python3
Начало » Python для новичков » rs485 - usb - win 10х64- python3
1 2
shiyri
Добрый день, подскажите пожалуйста!
Скрипт питон3 работает 4-5 минут, потом перестает принимать данные с USB(COM) порта, после презапуска скрипта все норм, но на эти 4-5 минут, в винде в энергосбережение отключил временное отключение порта USB. Запуск от имени админа ничего не дает, но при этом на win 7х64 все работает без сучка, хотелось бы на вин 10 переехать…..
py.user.next
shiyri
Скрипт питон3 работает 4-5 минут, потом перестает принимать данные с USB(COM) порта
Какой скрипт?
shiyri
 #! /usr/bin/python3
#coding: utf-8
import serial
import MySQLdb
import string
import time
import requests
import cv2
import os
import pysftp
from time import gmtime, strftime
s = serial.Serial('com5', 9600, bytesize=8, parity='N', stopbits=1, timeout=1)
def photo(door):
    if door == 2:
        stream_url = 'http://192.168.2.74/action/snapshot/'
    elif door == 1:
        stream_url = 'http://192.168.2.74/action/snapshot/'        
    absolute_script_dir = os.path.dirname(os.path.realpath(__file__))
    save_dir = absolute_script_dir + '/snapshots/'
    save_path = save_dir + '/snapshot.jpg'
    cap = cv2.VideoCapture(stream_url)
    ret, frame = cap.read()
    cv2.imwrite(save_path, frame)
    try:
        with sftp.Connection('http://museum.ru/telegram2.php', username='123', password='3123') as sftp:    
            remote = 'httpdocs/css/font/snapshot.jpg'
            local = 'D:\\www\\htdocs\\checkout\\snapshots\\snapshot.jpg'
            sftp.put(local,remote)
            sftp.close()
    except Exception:
            print("Ошибка ftp")    
while True:        
    last = ''
    for byte in s.read(s.inWaiting()): last += chr(byte)
    if (len(last) == 14):
        conn = MySQLdb.connect('localhost', 'user', '123', 'sotr')
        cursor = conn.cursor()
        # Do whatever you want with last
        print (last)
        id = str(last)[4:]
        #print(id)
        try:
            in_out = int(str(last)[:-11])            
        except Exception:
            print("Ошибка в пропуске")
        else:
            zapros = ("SELECT COUNT(*) FROM fio_table where (propusk=" + id +")")
            zapros_korr = ("SELECT COUNT(*) FROM `prohod` WHERE propusk = " + id +" AND status = '00FF00' ")        
            try:
                cursor.execute(zapros)            
            except Exception:
                print("Ошибка в пропуске")
            else:    
                row = cursor.fetchone()        
                row = row[0]
                print(in_out)
                if row < 1:
                    print("Доступ ЗАПРЕЩЕН")
                    conn.close()
                    if in_out == 931:
                        photo(1)                             
                        teleg =  "ОХРАННИК РАЗБЛОКИРОВАЛ ТУРНИКЕТ!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})                    
                        print("ОХРАННИК РАЗБЛОКИРОВАЛ ТУРНИКЕТ!!!")
                    elif in_out == 962:
                        photo(2)
                        time.sleep(1)                             
                        teleg =  "ОХРАННИК ВПУСТИЛ НЕИЗВЕСТНОГО!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})                    
                        print("ОХРАННИК ВПУСТИЛ НЕИЗВЕСТНОГО!!!")   
                    elif in_out == 972:
                        photo(1)
                        time.sleep(1)                             
                        teleg =  "ОХРАННИК ВЫПУСТИЛ НЕИЗВЕСТНОГО!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})                    
                        print("ОХРАННИК ВЫПУСТИЛ НЕИЗВЕСТНОГО!!!") 
                else:
                    print("Доступ РАЗРЕШЕН")
                    if in_out == 220:                    
                        conn.close()
                        time.sleep(1)
                        print("Подключение к базе")
                        conn = MySQLdb.connect(host='localhost', user='user', password='123', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())   
                        print("ОТправка запроса")
                        cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '00FF00', '" + datey + "', '" + datev + "')")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg = "Вошёл" + " "+ ss
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close()
                        print("Запрос в базу на вход")
                    if in_out == 200:
                        print("Входит")
                        cursor.execute(zapros_korr)
                        row = cursor.fetchone()
                        conn.close()
                        photo(2)
                        row = row[0]
                        #if row > 0:
                           # print("ИД уже на базе") тут нельзя войти 2 раза
                        #else:
                        print("Пропустить на вход")
                        sss = str("2200" + id)                    
                        ss = str.encode(sss)
                        type(ss) # ensure it is byte representation
                        print(ss) 
                        time.sleep(.5)
                        s.write(ss)                     
                        ss = " "
                    elif in_out == 120:                    
                        print("Запрос в базу на выход")
                        conn.close()
                        time.sleep(1)
                        conn = MySQLdb.connect(host='localhost', user='user', password='123', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())                    
                        cursor.execute("UPDATE prohod  as pr, (SELECT id FROM prohod WHERE propusk='"+ id +"' ORDER BY id DESC LIMIT 1) as src SET pr.status = 'DC143C', pr.time_vih='" + datev + "', pr.date_vih = '" + datey + "', pr.time_ar=TIMEDIFF('" + datey + "', pr.data) WHERE pr.id = src.id;")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg = "Вышел" + " "+ ss
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close() 
                    elif in_out == 100:
                        print("Выходит")
                        cursor.execute(zapros_korr)
                        row = cursor.fetchone()
                        conn.close()
                        photo(1)
                        row = row[0]
                        #if row < 1:
                        #    print("Еще не вошел") тут нельзя выйти 2 раза
                        #else:
                        print("Пропустить на выход")
                        sss = str("1100" + id)                    
                        ss = str.encode(sss)
                        type(ss) # ensure it is byte representation
                        print(ss) 
                        time.sleep(.5)
                        s.write(ss)                     
                        ss = " "
                    elif in_out == 900:
                        conn.close()
                        time.sleep(1)
                        conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())                    
                        cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '800080', '" + datey + "', '" + datev + "')")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        #iterate through rows
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg = "ВНИМАНИЕ "+ ss + " НЕ ТРЕЗВЫЙ!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close()
                        print("Бухой Ахтунг!!!")
                    elif in_out == 910:
                        conn.close()
                        time.sleep(1)
                        conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())                    
                        cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', '800080', '" + datey + "', '" + datev + "')")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        #iterate through rows
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg =  ss + " отказывается пройти тест!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close()
                        print("Отказался проходить тест!!!")
                    elif in_out == 130:
                        conn.close()
                        time.sleep(1)
                        conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())                    
                        cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', 'FFFF00', '" + datey + "', '" + datev + "')")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        #iterate through rows
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg =  ss + " ПРОПУСТИЛ ПОСТОРОННЕГО!!!"                       
                        response = requests.get(http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close()
                        print("Пропустил шпиона!!!")
                    elif in_out == 230:
                        conn.close()
                        time.sleep(1)
                        conn = MySQLdb.connect(host='localhost', user='user', password='TWkuDB7jE84TLiqx', database='sotr', charset='utf8')
                        cursor = conn.cursor()
                        datey = strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                        datev = strftime("%H:%M:%S", time.localtime())                    
                        cursor.execute("INSERT INTO prohod (propusk, status, data, time_vh) VALUES ('"+ id +"', 'FFFF00', '" + datey + "', '" + datev + "')")
                        cursor.execute("SELECT fio FROM fio_table where propusk='"+ id +"'")
                        rs = cursor.fetchall()
                        #iterate through rows
                        ss = ""
                        for o in range(len(rs)):
                            ss+=str(rs)
                        teleg = "" 
                        ss = ss[3:]
                        ss = ss[:-5]
                        print(ss)                        
                        teleg =  ss + " ВЫПУСТИЛ ПОСТОРОННЕГО!!!"
                        #requests.get("http://museum.ru/telegram2.php?text='+ teleg'")
                        response = requests.get('http://museum.ru/telegram2.php',params={'text': teleg})
                        conn.commit()
                        conn.close()
                        print("Выпустил дисидента!!!")   
doza_and
shiyri
потом перестает принимать данные с USB(COM) порта
А как вы об этом судите?
Может вам импортировать модуль logging и записать len после приема посылки, а может и прием каждого байта.
     
logging...... s.is_open
for byte in s.read(s.inWaiting()): last += chr(byte)
logging...... len(last)
if (len(last) == 14):
Ну и выкладывайте на форум хвост лога перед зависанием.

При переходе на десятку вы наверное и питон сменили?
py.user.next
shiyri
Скрипт питон3 работает 4-5 минут, потом перестает
Попробуй базу данных один раз открывать в начале работы скрипта и один раз закрывать в конце работы скрипта. Не факт, что в передаче данных дело.
shiyri
Да вы правы, mysql убрал и заработало без зависаний, то есть мне сейчас надо вывести ее в функцию? или в настройках базы данных что то поменять?
shiyri
Вынес запрос в отдельную функцию, не могу понять почему инициализация sftp не получается.
 #! /usr/bin/python3
#coding: utf-8
import serial
import MySQLdb
import string
import time
import requests
import cv2
import os
import pysftp as sftp
from time import gmtime, strftime
s = serial.Serial('com4', 9600, bytesize=8, parity='N', stopbits=1, timeout=1)
def photo(door):
    if door == 2:
        stream_url = 'http://192.168.2.74/action/snapshot/'
    elif door == 1:
        stream_url = 'http://192.168.2.74/action/snapshot/'   
        absolute_script_dir = os.path.dirname(os.path.realpath(__file__))
        save_dir = absolute_script_dir + '/snapshots/'
        save_path = save_dir + '/snapshot.jpg'
        cap = cv2.VideoCapture(stream_url)
        ret, frame = cap.read()
        cv2.imwrite(save_path, frame)
def ftp_photo():
    with sftp.Connection(host='server.ru',username='user',password='pass') as sftp:    
        remote = 'httpdocs/css/font/snapshot.jpg'
        local = './snapshots/snapshot.jpg'
        sftp.put(local,remote)
    sftp.close()
def telega(teleg):
    response = requests.get('museum.ru/css/font/telegram2.php',params={'text': teleg})
def sql(zapros):
    conn = MySQLdb.connect('localhost', 'user', 'TWkuDB7jE84TLiqx', 'sotr')
    cursor = conn.cursor()
    cursor.execute(zapros)
    global row
    row = cursor.fetchone()
    conn.commit()
    conn.close()
    return row      
while True:        
    last = ''
    for byte in s.read(s.inWaiting()): last += chr(byte)
    if (len(last) == 14):
        print (last)
        id = str(last)[4:]
        print(id)
        try:
            in_out = int(str(last)[:-11])            
        except Exception:
            print("Ошибка в пропуске")
        else:
            zapros = "SELECT COUNT(*) FROM fio_table where (propusk=" + id +")"            
            sql(zapros)            
            row = row[0]
            print(in_out)
            if row < 1:
                print("Доступ ЗАПРЕЩЕН")
                photo(2)
                ftp_photo()
                telega("Тест из офиса")
выходит такая ошибка
Traceback (most recent call last):
File “upload_snapshot.py”, line 60, in <module>
ftp_photo()
File “upload_snapshot.py”, line 25, in ftp_photo
with sftp.Connection(host='server.ru',username='user',password='pass') as sftp:
UnboundLocalError: local variable ‘sftp’ referenced before assignment
PEHDOM
ну дык оно вам пишет что нельзя так:
 with sftp.Connection(host='server.ru',username='user',password='pass') as sftp:
у вас и там и тут sftp, интерпретатор в растеряности….
напишите
 with sftp.Connection(host='server.ru',username='user',password='pass') as conn:
например.
shiyri
Помогите еще пожалста
отдельный кусок с сохраниением скрина с ип камеры работает, а в теле основного скрипта нет…. и ошибкон нет
 def photo(door):
    if door == 2:
        stream_url = 'http://192.168.2.74/action/snapshot/'
    elif door == 1:
        stream_url = 'http://192.168.2.74/action/snapshot/'        
        save_path0 = 'D:/www/htdocs/checkout/snapshots/snapshot.jpg'
        try:
            cap0 = cv2.VideoCapture(stream_url)
            ret, frame = cap0.read()
            cv2.imwrite(save_path0, frame)
        except Exception:
            print("Ошибка камеры")    
py.user.next
shiyri
то есть мне сейчас надо вывести ее в функцию? или в настройках базы данных что то поменять?
Думаю, тебе код кто-то грамотный должен разработать. Все эти ошибки из-за общего уровня кода происходят. То есть ты думаешь, что данные не передаются, а на самом деле виснет база данных. Код написан в целом так, что это хороший и большой омут для ошибок. Вместо того чтобы его менять в том виде, в котором он есть, его нужно изначально грамотно продумать и написать, тогда и ошибки не будет ни одной.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB