Добавить профили, чтение телеметрии и CSV в клиент GAS
This commit is contained in:
@@ -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')
|
||||
|
||||
Reference in New Issue
Block a user