def _get_picture(self, picure_type, *rest): photo_buffer = call(self.on_get_photo, [0xCC] * 10, self._resolution) def send_package(command_id, counter, package_id_0, package_id_1): package_id = (package_id_1 << 8) | package_id_0 self.log.info('SendPackage(Package ID={})'.format(package_id)) if package_id == 0xF0F0: self._on_ack = None self.log.info('Sending packages finished') return part = photo_buffer[package_id * 506:package_id * 506 + 506] package = [package_id_0, package_id_1, 0xFA, 0x01] + part + [0, 0] a = self._port.write(package) self.log.info('Written {}'.format(a)) self._on_ack = send_package self.log.info('Get Picture({})'.format(picure_type)) self._command(CommandCode.ACK, CommandCode.GetPicture) raw = ensure_byte_list(struct.pack('<L', len(photo_buffer)))[0:3] self._command(CommandCode.Data, 0x01, *raw)
def receive(decode=True): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('127.0.0.1', 1234)) sock.sendall('R') data = read_all(sock, 3) if data != 'ACK': raise EnvironmentError('Server not responed with ACK') count = ord(read_all(sock, 1)) frames = [] for i in xrange(count): size = ord(read_all(sock, 1)) frame_bytes = read_all(sock, size) frame_bytes = ensure_byte_list(frame_bytes) if decode: decoded = frame_decoder.decode(frame_bytes) frames.append(decoded) else: frames.append(frame_bytes) data = read_all(sock, 3) if data != 'ACK': raise EnvironmentError('Server not responed with ACK') sock.shutdown(socket.SHUT_RDWR) sock.close() return frames
def test_should_report_error_when_removing_non_existent_file(self): self._start() p = "/non_exist" self.system.comm.put_frame( telecommand.RemoveFile(correlation_id=0x11, path=p)) frame = self.system.comm.get_frame(20, filter_type=FileRemoveErrorFrame) self.assertIsInstance(frame, FileRemoveErrorFrame) self.assertEqual(frame.seq(), 0) self.assertEqual(frame.correlation_id, 0x11) self.assertEqual(frame.error_code, 0xFE) self.assertEqual(frame.response, ensure_byte_list(p)) self.assertEqual(frame.payload(), [0x11, 0xFE] + ensure_byte_list(p))
def test_parse_downlink_frame(self): bytes = '\x42\xD5\x76PONG' frame = DownlinkFrame.parse(bytes) self.assertIsNotNone(frame) self.assertEqual(frame.apid(), 0x02) self.assertEqual(frame.seq(), 0x1DB55) self.assertEqual(frame.payload(), ensure_byte_list('PONG'))
def decode(raw_frame_payload): frame_decoder = FallbackResponseDecorator(response_frames.FrameDecoder(response_frames.frame_factories)) frame_object = frame_decoder.decode(ensure_byte_list(raw_frame_payload)) if isinstance(frame_object, comm_beacon.BeaconFrame): return ParseBeacon.convert(ParseBeacon.parse(frame_object)) elif isinstance(frame_object, response_frames.file_system.FileListSuccessFrame): return ParseBeacon.parse_file_list(frame_object) else: return frame_object
def handle(self): while True: cmd = self._port.read(6) command_id = ord(cmd[1]) cmd_str = ensure_byte_list(cmd) self.log.debug('Got command %d (%s)', command_id, str(cmd_str)) handler = self._command_handlers[command_id] handler(*cmd_str[2:])
def test_auto_pingpong(self): def reset_handler(*args): return False self.system.comm.on_hardware_reset = reset_handler self.system.comm.receiver.on_reset = reset_handler self.power_on_obc() self.system.comm.put_frame(UplinkFrame(ord('P'), 'ABC')) msg = self.system.comm.get_frame(20, filter_type=PongFrame) self.assertIsInstance(msg, PongFrame) self.assertEqual(msg.payload(), ensure_byte_list("PONG"))
def _catch_beacon(self): while True: frame = ensure_byte_list(self._incoming_frames.recv()) decoded = self._frame_decoder.decode(frame[16:-2]) if isinstance(decoded, BeaconFrame): self.last_beacon.time = datetime.now() self.last_beacon.payload = decoded last_frames.insert(0, decoded) if len(last_frames) > 90: last_frames.remove(last_frames[-1])
def get_file(self, file_path, binary=False, as_lines=False): full_path = self.expand_path(file_path) mode = 'r' if binary: mode += 'b' with open(full_path, mode) as f: if as_lines: return f.readlines() data = f.read() if binary: data = ensure_byte_list(data) return data
def worker(): started.set() while True: (r, _, _) = zmq.select(receivers, [], [], timeout=2) if not r and signal.is_set(): break pass for socket in r: frame_raw = socket.recv() frame_raw = frame_raw[16:-2] frame_raw = ensure_byte_list(frame_raw) frame = Decoder.decode(frame_raw) callback(frame)
def test_should_remove_file(self): self._start() data = "content" p = "/test" self.system.obc.write_file(p, data) self.system.comm.put_frame( telecommand.RemoveFile(correlation_id=0x11, path=p)) frame = self.system.comm.get_frame(20, filter_type=FileRemoveSuccessFrame) self.assertEqual(frame.apid(), DownlinkApid.FileRemove) self.assertEqual(frame.seq(), 0) self.assertEqual(frame.response, ensure_byte_list(p))
def receive_file_parts(stations, correlation_id, requested_chunks): # type: (List[GroundStation], int, List[int]) -> List[Union[rf.FileSendSuccessFrame, rf.FileSendErrorFrame]] socks = map(lambda s: s.receiver.sock, stations) result = [] timeout_secs = 10 remaining_chunks = list(requested_chunks) while True: (r, _, _) = zmq.select(socks, [], [], timeout=timeout_secs) timeout_secs = 5 if not r: break for socket in r: frame_raw = socket.recv() frame_raw = frame_raw[16:-2] frame_raw = ensure_byte_list(frame_raw) frame = Decoder.decode(frame_raw) print '\tReceived {} (Remaining: {})'.format( repr(frame), remaining_chunks) if (isinstance(frame, rf.FileSendSuccessFrame) or isinstance(frame, rf.FileSendErrorFrame) ) and frame.correlation_id == correlation_id: result.append(frame) if frame.seq() in remaining_chunks: idx = remaining_chunks.index(frame.seq()) remaining_chunks = remaining_chunks[idx + 1:] if not remaining_chunks: break return result
def frames(self, sources, unique_only=True): def sorter(x): try: return (x.correlation_id, x.ReceivedAPID, x._seq) except: return (0, 0, 0) payloads = [] for source in sources: file_name = 'artifacts/{}_downlink.frames'.format(source) if source == 'all': file_name = 'artifacts/all.frames' frames_file = self.get_file(file_name, as_lines=True) for line in frames_file: (ts, direction, payload) = line.split(',') if direction != 'D': continue payloads.append(payload) if unique_only: payloads = list(set(payloads)) frames = [] for payload in payloads: binary_frame = base64.b64decode(payload) binary_frame = binary_frame[16:-2] binary_frame = ensure_byte_list(binary_frame) frame = self._frame_decoder.decode(binary_frame) frames.append(frame) result = list(frames) result.sort(key=sorter) return result
def parse_packet(self, frame_data): return decoder.decode(ensure_byte_list(frame_data[16:-2]))
def safe(l): return str(map(lambda x: ensure_byte_list(x), l))
def test_ensure_byte_list(self, input, output): result = ensure_byte_list(input) self.assertEqual(result, output)
def decode(self, payload): return BeaconFrame(ensure_byte_list(payload)[1:])
def _parse_packet(frame_data): return decoder.decode(ensure_byte_list(frame_data[17:-2]))
def payload(self): return ensure_byte_list( struct.pack('<BBBH' + 'B' * len(self._data), self._correlation_id, self._busSelect, self._address, self._delay, *self._data))
parser.add_argument('-u', '--upload', required=False, help="Store mapped telemetry items", action='store_true') parser.add_argument('--marker', required=False, help="Session import marker") parser.add_argument('--gs', required=True, help="GS name") args = parser.parse_args(sys.argv[1:]) raw = args.file.read() raw = ensure_byte_list(raw) entries = telemetry_file_mapper.read_telemetry_buffer(raw) print 'Found {} entries in telemetry file'.format(len(entries)) url = urlparse(args.influx) client = InfluxDBClient(host=url.hostname, port=url.port, database=url.path.strip('/')) entry_mapping = telemetry_file_mapper.map_telemetry(client, entries) for item in entry_mapping: print(item) if not args.upload: print('NOT uploading')
def parse_frame(raw_frame): return Decoder.decode(ensure_byte_list(raw_frame[16:-2]))
def get_apid(frame): frame_byte_list = ensure_byte_list(frame) return frame_byte_list[16]
def payload(self): seqs_bytes = ensure_byte_list(struct.pack('<' + 'L' * len(self._seqs), *self._seqs)) return [self._correlation_id, len(self._path)] + list(self._path) + [0x0] + seqs_bytes
def payload(self): return [ self._correlation_id, self._interval_minutes, self._repeat_count ] + ensure_byte_list(self._message)
url = urlparse(args.influx) db = InfluxDBClient(host=url.hostname, port=url.port, database=url.path.strip('/')) tz_offset = timedelta(seconds=time.timezone) for l in args.file.readlines(): (timestamp, direction, payload) = l.split(',') if direction != 'D': continue timestamp = datetime.strptime(timestamp, '%Y-%m-%d_%H:%M:%S:%f') payload = base64.b64decode(payload) frame_body = payload[16:-2] frame_body = ensure_byte_list(frame_body) frame_decoder = FallbackResponseDecorator(response_frames.FrameDecoder(response_frames.frame_factories)) frame = frame_decoder.decode(frame_body) if isinstance(frame, BeaconFrame): telemetry = ParseBeacon.parse(frame) points = generate_data_points(timestamp, telemetry, { 'ground_station': args.gs }) elif isinstance(frame, DeepSleepBeacon): telemetry = ParseDeepBeacon.parse(frame) points = generate_deep_sleep_data_points(timestamp, telemetry, { 'ground_station': args.gs }) elif isinstance(frame, LittleOryxDeepSleepBeacon): telemetry = ParseLttleOryxBeacon.parse(frame)
def decode_kiss(self, frame): frame = frame[16:] return ensure_byte_list(frame)
parser.add_argument('tasklist', nargs='?', help="Previous tasklist") parser.add_argument('-o', '--output', required=False, help="Output tasklist file") return parser.parse_args() args = parse_args() frame_decoder = FallbackResponseDecorator(response_frames.FrameDecoder(response_frames.frame_factories)) upload_done = [] with open(args.downlink_frames, 'r') as downlink_frames: for frame in downlink_frames: f = frame_decoder.decode(ensure_byte_list(b64decode(frame.split(',')[2])[16:-2])) if isinstance(f, response_frames.EntryProgramPartWriteSuccess): upload_done.append((f.offset, f.size, f.entries)) upload_done = sorted(list(set(upload_done))) print "Confirmed slots: ", for c in upload_done: chunk = c[0] * 1.0 / tc.WriteProgramPart.MAX_PART_SIZE if chunk.is_integer(): chunk = int(chunk) print chunk, print "\n\n" if args.tasklist is None: exit(0)