Commit a530e877 authored by Oleg Nikulin's avatar Oleg Nikulin

Логирование

parent 1dbe2f70
import serial
import time
from crc import Calculator, Crc16
from general import *
def open_serial(port, baudrate):
try: #пытаемся открыть serial порт
......@@ -15,7 +16,7 @@ def open_serial(port, baudrate):
return None
delaySec = 4
print(f'Delay {round(delaySec)} seconds before starting serial...')
logger.info(f'Delay {round(delaySec)} seconds before starting serial...')
time.sleep(delaySec)
serial_port.reset_input_buffer()
serial_port.reset_output_buffer()
......
......@@ -11,9 +11,9 @@
"controlGroups":
[
{
"targetTemperature": 35,
"targetTemperature": 50,
"overheatTemperature": 60,
"minDutyCycle": 0.15,
"minDutyCycle": 0.125,
"maxDutyCycle": 1,
"copyFromGroupIndex": 255
},
......@@ -22,14 +22,14 @@
"overheatTemperature": 60,
"minDutyCycle": 0.15,
"maxDutyCycle": 1,
"copyFromGroupIndex": 255
"copyFromGroupIndex": 0
},
{
"targetTemperature": 45,
"overheatTemperature": 60,
"minDutyCycle": 0.15,
"maxDutyCycle": 1,
"copyFromGroupIndex": 255
"copyFromGroupIndex": 0
}
]
......
......@@ -7,7 +7,9 @@ import datetime
import threading
from threading import Event
import json
import logging
import sys
import traceback
class pc_command_codes:
initialize = 1
......@@ -27,19 +29,39 @@ TIMEOUT_TIME = 3 #Считается что ардуина перестала о
config = None
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logFormatter_file = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%d.%m.%Y %H:%M:%S')
logHandler_file = logging.FileHandler('hddtempserial.log')
logHandler_file.setLevel(logging.DEBUG)
logHandler_file.setFormatter(logFormatter_file)
logger.addHandler(logHandler_file)
logFormatter_console = logging.Formatter('%(levelname)s: %(message)s')
logHandler_console = logging.StreamHandler(sys.stdout)
logHandler_console.setLevel(logging.INFO)
logHandler_console.setFormatter(logFormatter_console)
logger.addHandler(logHandler_console)
def exceptionHandler(type, value, trback):
logger.exception(f'Type={type} Value="{value}"\n' + ''.join(traceback.format_tb(trback)))
sys.excepthook = exceptionHandler
def load_json(filename):
try:
jsonFile = open(filename, mode='r', encoding='utf-8')
except:
print(f'Failed to open {filename}')
logger.error(f'Failed to open {filename}')
return None
try:
config = json.load(jsonFile)
except:
print(f'Failed to read json from {filename}')
logger.error(f'Failed to read json from {filename}')
return None
jsonFile.close()
......
......@@ -91,13 +91,13 @@ def initialize(serial_port):
response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec'])
if response is None:
print('Initialize no valid response')
logger.error('Initialize no valid response')
else:
if response[0] == arduino_response_codes.initialize_ok:
initialized = True
print('Initialize ok')
logger.info('Initialize ok')
else:
print('Initialize bad response')
logger.error('Initialize bad response')
def poll(serial_port):
......@@ -118,11 +118,11 @@ def poll(serial_port):
response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec'])
if response is None:
initialized = False
print('Poll no valid response')
logger.error('Poll no valid response')
else:
if response[0] == arduino_response_codes.poll_noinit:
initialized = False
print('Arduino is not initialized. Probably it was reset')
logger.warn('Arduino is not initialized. Probably it was reset')
elif response[0] == arduino_response_codes.poll_ok:
rpms = [0] * 6
pwms = [0] * 3
......@@ -140,16 +140,19 @@ def poll(serial_port):
else:
print(f'RPM: {rpms} PWM: {pwms}')
logger.debug(f'RPM: {rpms} PWM: {pwms}')
return True
else:
initialized = False
print('Poll bad response')
logger.error('Poll bad response')
return False
if __name__ == "__main__":
logger.info('Start')
config = load_json( os.path.join(os.path.dirname(__file__), 'config.json') )
if config is None:
exit()
......@@ -174,28 +177,28 @@ if __name__ == "__main__":
temperatures = [30, 45, 50]
if port is None:
print('Serial device is not specified (neither in config nor in command line)')
logger.error('Serial device is not specified (neither in config nor in command line)')
exit()
if baudrate is None:
print('Baudrate is not specified (neither in config nor in command line)')
logger.error('Baudrate is not specified (neither in config nor in command line)')
exit()
if not args.manual:
drivesLen = len(config['drives'])
if drivesLen == 0:
print('No drives are specified in config. At least one drive must be specified')
logger.error('No drives are specified in config. At least one drive must be specified')
exit()
if drivesLen > 3:
print(f'{drivesLen} drives are specified in config. Note that only 3 drives are supported, so only the first 3 will be used.')
logger.warn(f'{drivesLen} drives are specified in config. Note that only 3 drives are supported, so only the first 3 will be used.')
if len(config['controlGroups']) != 3:
print('Incorrect number of control groups in config. There should be 3 control groups.')
logger.error('Incorrect number of control groups in config. There should be 3 control groups.')
exit()
serial_port = open_serial(port, baudrate)
if serial_port is None:
print(f'Failed to open {config["device"]} serial port. Trying again...')
logger.error(f'Failed to open {config["device"]} serial port. Trying again...')
try:
while True:
......@@ -208,7 +211,7 @@ if __name__ == "__main__":
output = str(subprocess.Popen(['netcat', '-d', 'localhost', '7634'], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]) #получаем output от hddtemp
#b'|/dev/sda2|ST340014A|41|C|'
if output == "b''":
print('Hddtemp output is empty, make sure it is running. If not, launch it: #systemctl start hddtemp.service')
logger.error('Hddtemp output is empty, make sure it is running. If not, launch it: #systemctl start hddtemp.service')
#exit()
else:
driveCount = len(config['drives'])
......@@ -219,7 +222,7 @@ if __name__ == "__main__":
drive = config['drives'][i]
drive_pos = output.find(drive)
if drive_pos == -1:
print(f'Drive {drive} not found in hddtemp output')
logger.error(f'Drive {drive} not found in hddtemp output')
continue
try:
......@@ -231,7 +234,7 @@ if __name__ == "__main__":
temp = output[temp_pos_start:temp_pos_end]
temperatures[i] = int(temp)
except ValueError:
print(f'Failed to parse a temperature value from hddtemp output for drive {drive}')
logger.error(f'Failed to parse a temperature value from hddtemp output for drive {drive}')
continue
if (poll(serial_port)):
......@@ -242,10 +245,10 @@ if __name__ == "__main__":
except (OSError, termios.error):
if serial_port is not None:
print('Serial port error. Trying to open serial port again...')
logger.error('Serial port error. Trying to open serial port again...')
serial_port = open_serial(port, baudrate)
if serial_port is not None:
print('Success')
logger.info('Success')
#обычнаый интервал используется при обычном обмене когда всё ок
if (regularPollInterval):
......
#include "crc.h"
#include "functions.h"
#define STANDALONE_MODE
//#define STANDALONE_MODE
#define STANDALONE_SERIAL_DEBUG
#define FAN_COUNT 6 //Количество вентиляторов
......@@ -534,9 +534,9 @@ void setup() {
control_b.copy_from = 255;
control_c.copy_from = 255;
control_a.min_duty_cycle = 0;
control_b.min_duty_cycle = 0;
control_c.min_duty_cycle = 0;
control_a.min_duty_cycle = 32;
control_b.min_duty_cycle = 32;
control_c.min_duty_cycle = 32;
control_a.max_duty_cycle = 255;
control_b.max_duty_cycle = 255;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment