Commit a530e877 authored by Oleg Nikulin's avatar Oleg Nikulin

Логирование

parent 1dbe2f70
import serial import serial
import time import time
from crc import Calculator, Crc16 from crc import Calculator, Crc16
from general import *
def open_serial(port, baudrate): def open_serial(port, baudrate):
try: #пытаемся открыть serial порт try: #пытаемся открыть serial порт
...@@ -15,7 +16,7 @@ def open_serial(port, baudrate): ...@@ -15,7 +16,7 @@ def open_serial(port, baudrate):
return None return None
delaySec = 4 delaySec = 4
print(f'Delay {round(delaySec)} seconds before starting serial...') logger.info(f'Delay {round(delaySec)} seconds before starting serial...')
time.sleep(delaySec) time.sleep(delaySec)
serial_port.reset_input_buffer() serial_port.reset_input_buffer()
serial_port.reset_output_buffer() serial_port.reset_output_buffer()
......
...@@ -11,9 +11,9 @@ ...@@ -11,9 +11,9 @@
"controlGroups": "controlGroups":
[ [
{ {
"targetTemperature": 35, "targetTemperature": 50,
"overheatTemperature": 60, "overheatTemperature": 60,
"minDutyCycle": 0.15, "minDutyCycle": 0.125,
"maxDutyCycle": 1, "maxDutyCycle": 1,
"copyFromGroupIndex": 255 "copyFromGroupIndex": 255
}, },
...@@ -22,14 +22,14 @@ ...@@ -22,14 +22,14 @@
"overheatTemperature": 60, "overheatTemperature": 60,
"minDutyCycle": 0.15, "minDutyCycle": 0.15,
"maxDutyCycle": 1, "maxDutyCycle": 1,
"copyFromGroupIndex": 255 "copyFromGroupIndex": 0
}, },
{ {
"targetTemperature": 45, "targetTemperature": 45,
"overheatTemperature": 60, "overheatTemperature": 60,
"minDutyCycle": 0.15, "minDutyCycle": 0.15,
"maxDutyCycle": 1, "maxDutyCycle": 1,
"copyFromGroupIndex": 255 "copyFromGroupIndex": 0
} }
] ]
......
...@@ -7,7 +7,9 @@ import datetime ...@@ -7,7 +7,9 @@ import datetime
import threading import threading
from threading import Event from threading import Event
import json import json
import logging
import sys
import traceback
class pc_command_codes: class pc_command_codes:
initialize = 1 initialize = 1
...@@ -27,19 +29,39 @@ TIMEOUT_TIME = 3 #Считается что ардуина перестала о ...@@ -27,19 +29,39 @@ TIMEOUT_TIME = 3 #Считается что ардуина перестала о
config = None 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): def load_json(filename):
try: try:
jsonFile = open(filename, mode='r', encoding='utf-8') jsonFile = open(filename, mode='r', encoding='utf-8')
except: except:
print(f'Failed to open {filename}') logger.error(f'Failed to open {filename}')
return None return None
try: try:
config = json.load(jsonFile) config = json.load(jsonFile)
except: except:
print(f'Failed to read json from {filename}') logger.error(f'Failed to read json from {filename}')
return None return None
jsonFile.close() jsonFile.close()
......
...@@ -91,13 +91,13 @@ def initialize(serial_port): ...@@ -91,13 +91,13 @@ def initialize(serial_port):
response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec']) response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec'])
if response is None: if response is None:
print('Initialize no valid response') logger.error('Initialize no valid response')
else: else:
if response[0] == arduino_response_codes.initialize_ok: if response[0] == arduino_response_codes.initialize_ok:
initialized = True initialized = True
print('Initialize ok') logger.info('Initialize ok')
else: else:
print('Initialize bad response') logger.error('Initialize bad response')
def poll(serial_port): def poll(serial_port):
...@@ -118,11 +118,11 @@ def poll(serial_port): ...@@ -118,11 +118,11 @@ def poll(serial_port):
response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec']) response = serial_exchange(serial_port, transmit_bytes, response_length, config['arduinoTimeoutSec'])
if response is None: if response is None:
initialized = False initialized = False
print('Poll no valid response') logger.error('Poll no valid response')
else: else:
if response[0] == arduino_response_codes.poll_noinit: if response[0] == arduino_response_codes.poll_noinit:
initialized = False 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: elif response[0] == arduino_response_codes.poll_ok:
rpms = [0] * 6 rpms = [0] * 6
pwms = [0] * 3 pwms = [0] * 3
...@@ -140,16 +140,19 @@ def poll(serial_port): ...@@ -140,16 +140,19 @@ def poll(serial_port):
else: else:
print(f'RPM: {rpms} PWM: {pwms}') print(f'RPM: {rpms} PWM: {pwms}')
logger.debug(f'RPM: {rpms} PWM: {pwms}')
return True return True
else: else:
initialized = False initialized = False
print('Poll bad response') logger.error('Poll bad response')
return False return False
if __name__ == "__main__": if __name__ == "__main__":
logger.info('Start')
config = load_json( os.path.join(os.path.dirname(__file__), 'config.json') ) config = load_json( os.path.join(os.path.dirname(__file__), 'config.json') )
if config is None: if config is None:
exit() exit()
...@@ -174,28 +177,28 @@ if __name__ == "__main__": ...@@ -174,28 +177,28 @@ if __name__ == "__main__":
temperatures = [30, 45, 50] temperatures = [30, 45, 50]
if port is None: 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() exit()
if baudrate is None: 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() exit()
if not args.manual: if not args.manual:
drivesLen = len(config['drives']) drivesLen = len(config['drives'])
if drivesLen == 0: 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() exit()
if drivesLen > 3: 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: 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() exit()
serial_port = open_serial(port, baudrate) serial_port = open_serial(port, baudrate)
if serial_port is None: 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: try:
while True: while True:
...@@ -208,7 +211,7 @@ if __name__ == "__main__": ...@@ -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 output = str(subprocess.Popen(['netcat', '-d', 'localhost', '7634'], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0]) #получаем output от hddtemp
#b'|/dev/sda2|ST340014A|41|C|' #b'|/dev/sda2|ST340014A|41|C|'
if output == "b''": 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() #exit()
else: else:
driveCount = len(config['drives']) driveCount = len(config['drives'])
...@@ -219,7 +222,7 @@ if __name__ == "__main__": ...@@ -219,7 +222,7 @@ if __name__ == "__main__":
drive = config['drives'][i] drive = config['drives'][i]
drive_pos = output.find(drive) drive_pos = output.find(drive)
if drive_pos == -1: if drive_pos == -1:
print(f'Drive {drive} not found in hddtemp output') logger.error(f'Drive {drive} not found in hddtemp output')
continue continue
try: try:
...@@ -231,7 +234,7 @@ if __name__ == "__main__": ...@@ -231,7 +234,7 @@ if __name__ == "__main__":
temp = output[temp_pos_start:temp_pos_end] temp = output[temp_pos_start:temp_pos_end]
temperatures[i] = int(temp) temperatures[i] = int(temp)
except ValueError: 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 continue
if (poll(serial_port)): if (poll(serial_port)):
...@@ -242,10 +245,10 @@ if __name__ == "__main__": ...@@ -242,10 +245,10 @@ if __name__ == "__main__":
except (OSError, termios.error): except (OSError, termios.error):
if serial_port is not None: 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) serial_port = open_serial(port, baudrate)
if serial_port is not None: if serial_port is not None:
print('Success') logger.info('Success')
#обычнаый интервал используется при обычном обмене когда всё ок #обычнаый интервал используется при обычном обмене когда всё ок
if (regularPollInterval): if (regularPollInterval):
......
#include "crc.h" #include "crc.h"
#include "functions.h" #include "functions.h"
#define STANDALONE_MODE //#define STANDALONE_MODE
#define STANDALONE_SERIAL_DEBUG #define STANDALONE_SERIAL_DEBUG
#define FAN_COUNT 6 //Количество вентиляторов #define FAN_COUNT 6 //Количество вентиляторов
...@@ -534,9 +534,9 @@ void setup() { ...@@ -534,9 +534,9 @@ void setup() {
control_b.copy_from = 255; control_b.copy_from = 255;
control_c.copy_from = 255; control_c.copy_from = 255;
control_a.min_duty_cycle = 0; control_a.min_duty_cycle = 32;
control_b.min_duty_cycle = 0; control_b.min_duty_cycle = 32;
control_c.min_duty_cycle = 0; control_c.min_duty_cycle = 32;
control_a.max_duty_cycle = 255; control_a.max_duty_cycle = 255;
control_b.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