Слить регистратор телеметрии ECU и исправления сборки в main

This commit is contained in:
2026-11-30 11:10:30 +03:00
14 changed files with 1077 additions and 351 deletions
+53 -6
View File
@@ -10,7 +10,9 @@ No retries of writes: a timed-out snapshot may already exist on the device.
"""
from __future__ import annotations
import json
import csv
import re
from decimal import Decimal
import zlib
from pathlib import Path
@@ -37,12 +39,17 @@ def validate_map(data):
raise ValueError('Logger window exceeds GAS')
seen = {key: set() for key in ('key', 'gas', 'modbus', 'can')}
for channel in channels:
if not re.fullmatch(r'[a-z][a-z0-9_]*', channel['key']):
if (not re.fullmatch(r'[a-z][a-z0-9_]*', channel['key']) or
channel['key'] in ('time_ms', 'sequence', 'event')):
raise ValueError('Invalid channel key')
if not isinstance(channel['name'], str) or not channel['name'].strip():
raise ValueError('Missing channel name')
if channel['type'] not in ('u16', 'i16'):
raise ValueError('Unsupported channel type')
integer(channel.get('decimals', 0), 0, 6)
if 'invalid' in channel:
signed = channel['type'] == 'i16'
integer(channel['invalid'], -32768 if signed else 0, 32767 if signed else 65535)
if channel['can']['protocol'] != 'protocan_gas':
raise ValueError('CAN mapping must use ProtoCAN GAS')
if channel['modbus']['function'] != 3:
@@ -59,9 +66,10 @@ def validate_map(data):
raise ValueError('Duplicate ' + key)
seen[key].add(value)
source = channel['source']
if source['space'] not in ('pm35_modbus', 'pm67_cache'):
raise ValueError('Unknown PM35 source')
integer(source['address'], 0, 127 if source['space'] == 'pm35_modbus' else 1)
limits = {'pm35_modbus': 127, 'pm67_cache': 1, 'snapshot': 63}
if source['space'] not in limits:
raise ValueError('Unknown source space')
integer(source['address'], 0, limits[source['space']])
expected = ['magic', 'version', 'flags', 'channels', 'record_words', 'capacity',
'live_count', 'snapshot_count', 'generation_lo', 'generation_hi',
'schema_lo', 'schema_hi', 'sequence_lo', 'sequence_hi',
@@ -79,6 +87,36 @@ def load_map(path=None):
return validate_map(json.loads(path.read_text(encoding='utf-8')))
def profiles():
"""Bundled project maps, including their human-readable labels."""
directory = Path(__file__).with_name('gas_logger_maps')
for path in sorted(directory.glob('*.json')):
mapping = load_map(path)
yield mapping.get('title', 'ПМ35' if mapping['project'] == 'pm35' else mapping['project']), mapping
def _channel_value(raw, channel):
value = raw - 65536 if channel['type'] == 'i16' and raw >= 32768 else raw
if value == channel.get('invalid'):
return None
places = channel.get('decimals', 0)
return Decimal(value).scaleb(-places) if places else value
def write_csv(stream, records, mapping):
"""Write the existing SetGUI trend format, preserving missing values."""
channels = mapping['channels']
writer = csv.writer(stream)
writer.writerow(['time_ms', 'event', *[c['key'] for c in channels]])
epoch, previous = 0, None
for record in records:
stamp = record['time_ms']
if previous is not None and stamp < previous and previous - stamp > 2**31:
epoch += 2**32
previous = stamp
writer.writerow([epoch + stamp, record.get('event'), *[record[c['key']] for c in channels]])
def schema_id(mapping):
validate_map(mapping)
raw = json.dumps(mapping, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('ascii')
@@ -147,6 +185,16 @@ class GasLoggerClient:
self.status() # never write to an unrecognized device
self.write(self.base+18, 1)
def live(self):
"""Read one coherent live block for a contiguous project channel map."""
channels = self.mapping['channels']
addresses = [channel['modbus']['address'] for channel in channels]
if len(addresses) > self.block_words or addresses != list(range(addresses[0], addresses[0] + len(addresses))):
raise ValueError('Live view requires a contiguous channel block')
words = self._read(addresses[0], len(addresses))
return {channel['key']: _channel_value(word, channel)
for channel, word in zip(channels, words)}
def release(self, generation):
status = self.status()
if not status[2] & 2 or _u32(status, 8) != generation:
@@ -191,8 +239,7 @@ class GasLoggerClient:
if records and record['sequence'] != ((records[-1]['sequence']+1) & 0xffffffff):
raise ValueError('Snapshot record sequence is not contiguous')
for i,c in enumerate(self.mapping['channels']):
v=words[offset+HEADER_WORDS+i]
record[c['key']] = v-65536 if c['type']=='i16' and v>=32768 else v
record[c['key']] = _channel_value(words[offset+HEADER_WORDS+i], c)
records.append(record)
if cancelled():
raise InterruptedError('Snapshot download cancelled; snapshot retained')
@@ -0,0 +1,54 @@
{
"format": "set-gas-logger",
"version": 1,
"project": "ecu",
"title": "ECU Ignition",
"mcu_ports": ["stm32f1"],
"address_convention": "zero_based_16_bit_registers",
"capacity": 32,
"service": {
"base": 64536,
"data_offset": 256,
"registers": [
{"offset":0,"key":"magic","access":"r"},
{"offset":1,"key":"version","access":"r"},
{"offset":2,"key":"flags","access":"r"},
{"offset":3,"key":"channels","access":"r"},
{"offset":4,"key":"record_words","access":"r"},
{"offset":5,"key":"capacity","access":"r"},
{"offset":6,"key":"live_count","access":"r"},
{"offset":7,"key":"snapshot_count","access":"r"},
{"offset":8,"key":"generation_lo","access":"r"},
{"offset":9,"key":"generation_hi","access":"r"},
{"offset":10,"key":"schema_lo","access":"r"},
{"offset":11,"key":"schema_hi","access":"r"},
{"offset":12,"key":"sequence_lo","access":"r"},
{"offset":13,"key":"sequence_hi","access":"r"},
{"offset":14,"key":"missed_lo","access":"r"},
{"offset":15,"key":"missed_hi","access":"r"},
{"offset":16,"key":"source_errors_lo","access":"r"},
{"offset":17,"key":"source_errors_hi","access":"r"},
{"offset":18,"key":"command","access":"w"},
{"offset":19,"key":"release_generation_lo","access":"w"},
{"offset":20,"key":"release_generation_hi","access":"w"}
]
},
"channels": [
{"key":"rpm","name":"Обороты планировщика","unit":"об/мин","type":"u16","decimals":0,"invalid":65535,"gas":62536,"modbus":{"function":3,"address":62536},"can":{"protocol":"protocan_gas","address":62536},"source":{"space":"snapshot","address":0}},
{"key":"rpm_display","name":"Обороты отфильтрованные","unit":"об/мин","type":"u16","decimals":0,"invalid":65535,"gas":62537,"modbus":{"function":3,"address":62537},"can":{"protocol":"protocan_gas","address":62537},"source":{"space":"snapshot","address":1}},
{"key":"sync","name":"Синхронизация","unit":"","type":"u16","decimals":0,"invalid":65535,"gas":62538,"modbus":{"function":3,"address":62538},"can":{"protocol":"protocan_gas","address":62538},"source":{"space":"snapshot","address":2}},
{"key":"tooth","name":"Индекс зуба","unit":"","type":"u16","decimals":0,"invalid":65535,"gas":62539,"modbus":{"function":3,"address":62539},"can":{"protocol":"protocan_gas","address":62539},"source":{"space":"snapshot","address":3}},
{"key":"advance","name":"Угол опережения зажигания","unit":"°","type":"i16","decimals":2,"invalid":-32768,"gas":62540,"modbus":{"function":3,"address":62540},"can":{"protocol":"protocan_gas","address":62540},"source":{"space":"snapshot","address":4}},
{"key":"dwell","name":"Заряд катушки","unit":"мкс","type":"u16","decimals":0,"invalid":65535,"gas":62541,"modbus":{"function":3,"address":62541},"can":{"protocol":"protocan_gas","address":62541},"source":{"space":"snapshot","address":5}},
{"key":"injection_1","name":"Впрыск цилиндра 1","unit":"мкс","type":"u16","decimals":0,"invalid":65535,"gas":62542,"modbus":{"function":3,"address":62542},"can":{"protocol":"protocan_gas","address":62542},"source":{"space":"snapshot","address":6}},
{"key":"outputs","name":"Маска логических выходов","unit":"","type":"u16","decimals":0,"invalid":65535,"gas":62543,"modbus":{"function":3,"address":62543},"can":{"protocol":"protocan_gas","address":62543},"source":{"space":"snapshot","address":7}},
{"key":"tps","name":"Положение дросселя","unit":"%","type":"u16","decimals":2,"invalid":65535,"gas":62544,"modbus":{"function":3,"address":62544},"can":{"protocol":"protocan_gas","address":62544},"source":{"space":"snapshot","address":8}},
{"key":"map","name":"Абсолютное давление MAP","unit":"кПа","type":"u16","decimals":1,"invalid":65535,"gas":62545,"modbus":{"function":3,"address":62545},"can":{"protocol":"protocan_gas","address":62545},"source":{"space":"snapshot","address":9}},
{"key":"clt","name":"Температура ОЖ","unit":"°C","type":"i16","decimals":1,"invalid":-32768,"gas":62546,"modbus":{"function":3,"address":62546},"can":{"protocol":"protocan_gas","address":62546},"source":{"space":"snapshot","address":10}},
{"key":"iat","name":"Температура воздуха","unit":"°C","type":"i16","decimals":1,"invalid":-32768,"gas":62547,"modbus":{"function":3,"address":62547},"can":{"protocol":"protocan_gas","address":62547},"source":{"space":"snapshot","address":11}},
{"key":"batt","name":"Напряжение питания","unit":"мВ","type":"u16","decimals":0,"invalid":65535,"gas":62548,"modbus":{"function":3,"address":62548},"can":{"protocol":"protocan_gas","address":62548},"source":{"space":"snapshot","address":12}},
{"key":"lambda_measured","name":"Измеренная lambda","unit":"","type":"u16","decimals":3,"invalid":65535,"gas":62549,"modbus":{"function":3,"address":62549},"can":{"protocol":"protocan_gas","address":62549},"source":{"space":"snapshot","address":13}},
{"key":"lambda_target","name":"Целевая lambda","unit":"","type":"u16","decimals":3,"invalid":65535,"gas":62550,"modbus":{"function":3,"address":62550},"can":{"protocol":"protocan_gas","address":62550},"source":{"space":"snapshot","address":14}},
{"key":"fault","name":"Код последней ошибки","unit":"","type":"u16","decimals":0,"invalid":65535,"gas":62551,"modbus":{"function":3,"address":62551},"can":{"protocol":"protocan_gas","address":62551},"source":{"space":"snapshot","address":15}}
]
}