def connectme(self): """ Infinite loop to listen the data from the port """ while self.loopConnect: if self.connected: if time is None: break time.sleep(self._connectWait) continue if self._soc is None: self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self._soc.connect((self.host, self.port)) ready = True except: if not self.loopConnect: return False ready = False if ready: if not core.getAR(self._soc): core.killSock(self._soc) if not self.loopConnect: return False else: self._soc.sendall(Byt(self.name)) if not core.getAR(self._soc): core.killSock(self._soc) if not self.loopConnect: return False else: status = self._start() self._newconnection() if not self.loopConnect: return status time.sleep(self._connectWait) # process might have died in between if time is None: break
def split_flow(data, n=-1): """ Splits packets from flow if flow mode activated Args: * data (Byt): the data flow to split * n (int): how many packets should be splited, at maximum, set to -1 for all """ if not param_all.FRAMESFLOW: raise exc.NotInFramesFlow() # split CCSDS using the special split chars if not AX25ENCAPS: res = split_ccsds(Byt(data), int(n)) # no split found if len(res) < 2: return res # apply recovery of escaped chars to all splits found except last one return list(map(recover_ccsds, res[:-1])) + res[-1:] # split KISS using the special split chars elif param_all.KISSENCAPS: raise exc.NotImplemented("Frames-FLow with KISS") else: raise exc.NotImplemented("Unknown mode")
def merge_flow(datalist, trailingSplit=True): """ Merges the packets if the flow mode is activated Args: * datalist (list of Byt): the packets to merge together * trailingSplit (bool): whether to add a trailing split character """ if not FRAMESFLOW: raise exc.NotInFramesFlow() # merge CCSDS using the special split chars if not AX25ENCAPS: res = (CCSDSSPLITCHAR*2).join([ Byt(item).replace(CCSDSSPLITCHAR, CCSDSESCAPEDSPLIT)\ for item in datalist\ if len(item) > 0]) if trailingSplit: res += CCSDSSPLITCHAR * 2 return res # merge KISS using the special split chars elif KISSENCAPS: raise exc.NotImplemented("Frames-FLow with KISS") else: raise exc.NotImplemented("Unknown mode")
import sys TZON = True try: import pytz except ImportError: TZON = False try: unicode except: unicode = str __all__ = ['Message'] # acknowledgement character ACK = Byt('\x06') # basic encoding ENCODING = "utf-8" # escape character ESCAPE = Byt('\xee') # split character between key and value of a dictionary item # must a character that cannot be in a dict key DICTMAPPER = Byt(':') # end character of a communication MESSAGEEND = Byt('\xac\x96') DMESSAGEEND = MESSAGEEND * 2 ESCAPEDMESSAGEEND = MESSAGEEND + ESCAPE # maximum tag length
def base_type2bytes(v, keep_typ, json=False): """Returns a bytes representation of v Args: * v: the value to transform * keep_type (bool): whether to keep track of the type of v in the output Note: * Works with types in (int, float, bool, None, Byt) and string types in (Byt, unicode, str, bytes) * Any other type will undergo a repr() call """ if isinstance(v, Byt): if json: v = esc_quote(v) if keep_typ: return BYTCODE + DICTMAPPER + v return v elif isinstance(v, bool): data = _ONE if v else _ZERO if keep_typ: return BOOLCODE + DICTMAPPER + data return data elif isinstance(v, int): if keep_typ: return INTCODE + DICTMAPPER + Byt(repr(v)) return Byt(repr(v)) elif isinstance(v, float): if keep_typ: return FLOATCODE + DICTMAPPER + Byt(repr(v)) return Byt(repr(v)) elif v is None: if keep_typ: return NONECODE + DICTMAPPER return _EMPTY # catches python3 str and python2 unicode elif isinstance(v, unicode): data = Byt(v.encode(ENCODING)) if json: data = esc_quote(data) if keep_typ: return UNICODE + DICTMAPPER + data return data # only python2 str reach here elif isinstance(v, str): data = Byt(v) if json: data = esc_quote(data) if keep_typ: return STRCODE + DICTMAPPER + data return data # only python3 bytes here elif isinstance(v, bytes): data = Byt(v) if json: data = esc_quote(data) if keep_typ: return BYTESCODE + DICTMAPPER + data return data else: data = repr(v) # catches python3 str and python2 unicode if isinstance(data, unicode): code = UNICODE data = data.encode(ENCODING) # only python2 str reach here else: code = STRCODE data = Byt(data) if json: data = esc_quote(data) if keep_typ: return code + DICTMAPPER + data return data
def ustr(txt): """ Returns an ASCII cleaned version of the text """ return str(Byt('').join([ch for ch in Byt(txt)\ if 32 <= ord(ch) <= 127])).strip()
# along with this program. If not, see <http://www.gnu.org/licenses/>. # # For any information, bug report, idea, donation, hug, beer, please contact # [email protected] # ############################################################################### from byt import Byt __all__ = [ 'escape_special_codes', 'valid_callsign', 'recover_special_codes', 'strip_df_start' ] # Marks START and END of a Frame FEND = Byt('\xc0') # Escapes FEND and FESC bytes within a frame FESC = Byt('\xdb') # Sent as FESC TFEND TFEND = Byt('\xdc') # Sent as FESC TFESC TFESC = Byt('\xdd') # 0xC0 is sent as 0xDB 0xDC FESC_TFEND = FESC + TFEND # 0xDB is sent as 0xDB 0xDD FESC_TFESC = FESC + TFESC
def test_param_list(): p = Parameter('hop', 'blah', ftup(0, 65535), 'uint16', 2, None) bincore.TWINKLETWINKLELITTLEINDIA = True assert p.tohex([4, 260]) == Byt('\x04\x00\x04\x01') bincore.TWINKLETWINKLELITTLEINDIA = False assert p.tohex([4, 260]) == Byt('\x00\x04\x01\x04')
def pack(self, pid, TCdata=Byt(), TCid='', pktCat=None, retvalues=True, withPacketID=True, **kwargs): """ Creates a packet, returns the packet string and optionally the dictionnaries of primary/secondary and auxiliary headers Args: * pid (str): the process string-id related to the packet * TCdata (Byt): only for TC-mode, the data to include in the packet * TCid (int): only for TC-mode, the id of the telecommand * pktCat (int): only for TM-mode, the packet category * retvalues (bool): if ``True``, returns the encoded values * withPacketID (bool): set to ``False`` to deactivate the packet id determination Kwargs for TC-mode: * rack (bool) [default: REQACKRECEPTION]: ``True`` to recieve the acknowledgement of reception * fack (bool) [default: REQACKFORMAT]: ``True`` to recieve the acknowledgement of format * eack (bool) [default: REQACKEXECUTION]: ``True`` to recieve the acknowledgement of execution * emitter (int) [default: EMITTERID]: the id of the emitter * signit (bool) [default: USESIGGY]: sign the packet or not * wait (bool): ``True`` to make a blocking telecommand, until the acknowledgement is received, or ``timetout`` is elapsed * timeout (int): the time in second to wait for acknowledgements * at (datetime or timetuple): the time at which the TC shall be executed. Leave empty for immediate execution Kwargs for TM-mode: * auxiliary header and data keys-values """ hd = {} hd[param_ccsds.PID.name] = str(pid).lower() if not self.mode == 'telemetry': hd[param_ccsds.SIGNATURE.name] =\ Byt("\x00"*(param_ccsds.SIGNATURE.len//8)) hd[param_ccsds.TELECOMMANDID.name] = int(TCid) morevalues = ((param_ccsds.REQACKRECEPTIONTELECOMMAND.name, 'rack', param_all.REQACKRECEPTION), (param_ccsds.REQACKFORMATTELECOMMAND.name, 'fack', param_all.REQACKFORMAT), (param_ccsds.REQACKEXECUTIONTELECOMMAND.name, 'eack', param_all.REQACKEXECUTION), (param_ccsds.EMITTERID.name, 'emitter', param_all.EMITTERID)) # priority on short-names, then on long-names then default for (key, sht, defa) in morevalues: hd[key] = int(kwargs.pop(sht, hd.get(key, defa))) # process the "at" optional parameter at = kwargs.pop('at', None) if at is not None: if isinstance(at, (tuple, list)): at = fcts.PosixUTC(*at[:6]) elif isinstance(at, datetime.datetime): at = fcts.PosixUTC.fromdatetime(at) elif isinstance(at, PosixUTC): pass else: raise exc.WrongAt(at) # time in past: remove if fcts.PosixUTC.now().totimestamp() > at.totimestamp(): at = None else: hd[param_ccsds.PACKETCATEGORY.name] = int(pktCat) at = None # header prim retprim = self.pack_primHeader(values=hd, datalen=len(TCdata), retvalues=True, at=at) # header sec retsec = self.pack_secHeader(values=hd, retvalues=True) # make header return values hds = {} # if TC, add the time_delay parameter if not self.mode == 'telemetry': hds['time_delay'] = at hds.update(retprim[1]) hds.update(retsec[1]) maybeAux = Byt() hdx = {} retd = {} # header aux retaux = self.pack_auxHeader(values=kwargs, pldFlag=hds[param_ccsds.PAYLOADFLAG.name], pktCat=pktCat, retvalues=True) maybeAux = retaux[0] hdx.update(retaux[1]) # only if telemetry if self.mode == 'telemetry': # data retdata = self.pack_data(values=kwargs, header=hds, retvalues=True) data = retdata[0] retd.update(retdata[1]) retprim = self.increment_data_length(datalen=len(data), primaryHDpacket=retprim[0], primaryHDdict=retprim[1]) hds.update(retprim[1]) else: # append timestamp before data if at is not None: msstamp, daystamp = core.time2stamps(at) TS = param_ccsds.EXTRATS_TELECOMMAND.pack({ param_ccsds.MSECSINCEREF_TELEMETRY.name: msstamp, param_ccsds.DAYSINCEREF_TELEMETRY.name: daystamp })[0] TCdata = TS + TCdata retprim = self.increment_data_length( datalen=len(TS), primaryHDpacket=retprim[0], primaryHDdict=retprim[1]) hds.update(retprim[1]) data = TCdata theFullPacket = retprim[0] + retsec[0] + maybeAux + data theFullPacket, sig = self.add_siggy(fullPacket=theFullPacket, **kwargs) if retvalues: return theFullPacket, hds, hdx, retd else: return theFullPacket
def test_cm_call(): c = Cm(**echo) assert c.generate_data(hop='ab')[0] == Byt('\x61\x62') assert c.generate_data(hop='ab')[1] == {'hop': 'ab'} assert c(hop='ab') == c.generate_data(hop='ab')