예제 #1
0
파일: recipe.py 프로젝트: pohmelie/muber
 def __init__(self, names, nums, index, reformer, i, line):
     Container.__init__(self)
     data = line.strip("\n").split("\t")
     self.__dict__ = (reformer or (lambda x: x))(dict(compress(zip(names, data), nums)))
     if index and data[index] and data[index].isdecimal():
         i = int(data[index])
     elif index:
         i = None
     self.__dict__["_id"] = i
예제 #2
0
def _header_digest(
    header: c.Container,
    header_type: c.Construct,
    hash_function: Callable = pyblake2.blake2s,
) -> bytes:
    stripped_header = header.copy()
    stripped_header.sigmask = 0
    stripped_header.signature = b"\0" * 64
    stripped_header.v1_key_indexes = [0, 0, 0]
    stripped_header.v1_signatures = [b"\0" * 64] * 3
    header_bytes = header_type.build(stripped_header)
    return hash_function(header_bytes).digest()
예제 #3
0
    def eos_remote_release_on(self, full=False):
        '''
        Remote control shutter press for EOS cameras

        This is the equivalent of pressing the shutter button: all the way in
        if `full` or half-way otherwise.
        '''
        ptp = Container(OperationCode='EOSRemoteReleaseOn',
                        SessionID=self.__session,
                        TransactionID=self.__transaction,
                        Parameter=[0x2 if full else 0x1])
        response = self.mesg(ptp)
        return response
예제 #4
0
    def eos_event_mode(self, mode):
        '''Set event mode on EOS cameras'''
        # Canon extension uses this to enrich the events returned by the camera
        # as well as allowing for polling at the convenience of the initiator.

        # TODO: Add automatic translation of event mode codes and names.
        code = mode
        ptp = Container(OperationCode='EOSSetEventMode',
                        SessionID=self.__session,
                        TransactionID=self.__transaction,
                        Parameter=[code])
        response = self.mesg(ptp)
        return response
    def send_message(self,
                     action,
                     msg_type,
                     crud_result,
                     tlvs=None,
                     callback=None):
        """Send message and set common parameters."""

        parser = self.proto.PT_TYPES[action][0]
        name = self.proto.PT_TYPES[action][1]

        if self.stream.closed():
            self.log.warning("Stream closed, unabled to send %s message to %s",
                             parser.name, self.device)
            return 0

        msg = Container()

        msg.version = self.proto.PT_VERSION
        msg.flags = Container(msg_type=msg_type)
        msg.tsrc = Container(crud_result=crud_result, action=action)
        msg.length = self.proto.HEADER.sizeof()
        msg.padding = 0
        msg.device = self.device.addr.to_raw()
        msg.seq = self.seq
        msg.xid = self.xid
        msg.tlvs = []

        addr = self.stream.socket.getpeername()

        self.log.debug("Sending %s message to %s seq %u", name, addr[0],
                       msg.seq)

        self.stream.write(parser.build(msg))

        if callback:
            self.xids[msg.xid] = (msg, callback)

        return msg.xid
예제 #6
0
def get_tx_bitrates(server, id=0, intf_name=None, sta_ip=None, sta_port=0):
    """ get the channels the interface intf_name supports, this function applies to access points

      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @param sta_ip: ip address of the station that this message should be relayed to, if sta_ip is different from None
      @type sta_ip: str
      @param sta_port: socket port number of the station
      @type sta_port: int
      @return: a dictionary, the index is the band
    """
    if intf_name is None:
        raise ValueError("intf_name must have a valid value!")
    # 1) create message
    msg_struct = Container(
        m_type=MSG_TYPE.MSG_GET_TX_BITRATES,
        m_id=id,
        p_version_length=len_of_string(VERSION),
        p_version=VERSION,
        m_size=0,
        intf_name_size=len_of_string(intf_name),
        intf_name=intf_name,
        sta_ip_size=len_of_string(sta_ip),
        sta_ip=sta_ip,
        sta_port=sta_port,
        num_bands=0,  # don´t know how many bands are in the AP
        iw_bands=[],  # field will be filled by the AP
    )
    error, msg = send_and_receive_msg(server, msg_struct,
                                      msg_tx_bitrates.build,
                                      msg_tx_bitrates.parse)
    value = dict()
    if not error or ('iw_bands' not in msg):
        for v in msg['iw_bands']:
            bitrates = []
            is_short = []
            for e in v['iw_bitrates']:
                bitrates.append(e['bitrate'])
                is_short.append(e['is_short'] == 1)
            value[v['band']] = {
                'intf_name': v['intf_name'],
                'bitrates': bitrates,
                'support_short':
                is_short,  # if this bitrate supports short preamble or not
            }
    """
      returns the value, note: {} equals an error has occured or no band found
    """
    return msg, value
예제 #7
0
    def send_add_lvap_request(self, lvap, block, set_mask):
        """Send a ADD_LVAP message."""

        flags = Container(ht_caps=lvap.ht_caps,
                          authenticated=lvap.authentication_state,
                          associated=lvap.association_state,
                          set_mask=set_mask)

        encap = EtherAddress("00:00:00:00:00:00")
        if lvap.encap:
            encap = lvap.encap

        bssid = EtherAddress()
        if lvap.bssid:
            bssid = lvap.bssid

        ssid = SSID()
        if lvap.ssid:
            ssid = lvap.ssid

        msg = Container(length=80,
                        flags=flags,
                        assoc_id=lvap.assoc_id,
                        iface_id=block.block_id,
                        ht_caps_info=Container(**lvap.ht_caps_info),
                        sta=lvap.addr.to_raw(),
                        encap=encap.to_raw(),
                        bssid=bssid.to_raw(),
                        ssid=ssid.to_raw(),
                        networks=[])

        for network in lvap.networks:
            msg.length = msg.length + 6 + WIFI_NWID_MAXSIZE + 1
            msg.networks.append(
                Container(bssid=network[0].to_raw(), ssid=network[1].to_raw()))

        return self.send_message(self.proto.PT_ADD_LVAP_REQUEST, msg,
                                 lvap.handle_add_lvap_response)
예제 #8
0
    def send_del_ran_mac_slice_request(self, cell, plmn_id, dscp):
        """Send an DEL_SLICE message. """

        msg = Container(plmn_id=plmn_id.to_raw(),
                        dscp=dscp.to_raw(),
                        padding=b'\x00\x00\x00',
                        length=REM_RAN_MAC_SLICE_REQUEST.sizeof())

        self.send_message(msg,
                          E_TYPE_SINGLE,
                          EP_ACT_RAN_MAC_SLICE,
                          REM_RAN_MAC_SLICE_REQUEST,
                          opcode=EP_OPERATION_REM,
                          cellid=cell.pci)
예제 #9
0
    async def handle_panel_raw_message(self, raw: bytes):
        """
        Handle message from panel, which must be sent to the client
        """

        out_message_container = Container(
            header=Container(
                message_type=IPMessageType.serial_passthrough_response,
                command=IPMessageCommand.passthrough,
                flags=Container(
                    keep_alive=True,
                    live_events=True,
                    neware=True,
                    upload_download=True,
                    encrypt=self.flags.encrypt,
                ),
                sb=3,
                wt=0,
            ),
            payload=raw,
        )

        await self._send_to_client(out_message_container)
예제 #10
0
파일: adapters.py 프로젝트: torretahacs/pai
    def _decode(self, obj, context, path):
        event_group = obj[0]
        event_1_high_nibble = obj[1] >> 6
        event_2_high_nibble = (obj[1] >> 4) & 0b11
        event_1 = obj[2] + (event_1_high_nibble << 8)
        event_2 = obj[3] + (event_2_high_nibble << 8)
        partition = obj[1] & 0x0F

        return Container({
            "major": event_group,
            "minor": event_1,
            "minor2": event_2,
            "partition": partition,
        })
예제 #11
0
    def run_once(self):
        """Send out rate request."""

        if self.tenant_id not in RUNTIME.tenants:
            self.log.info("Tenant %s not found", self.tenant_id)
            self.unload()
            return

        tenant = RUNTIME.tenants[self.tenant_id]

        if self.imsi not in tenant.ues:
            self.log.info("UE %u not found", self.imsi)
            self.unload()
            return

        ue = tenant.ues[self.imsi]

        if not ue.vbs or not ue.vbs.is_online():
            self.log.info("VBS %s not connected", ue.vbs.addr)
            self.unload()
            return

        self.vbs = ue.vbs

        for i in self.measurements:

            measurement = self.measurements[i]

            rrc_request = Container(type=E_TYPE_TRIG,
                                    version=PT_VERSION,
                                    enbid=self.vbs.enb_id,
                                    cellid=ue.cell.pci,
                                    modid=self.module_id,
                                    length=RRC_REQUEST.sizeof(),
                                    seq=self.vbs.seq,
                                    action=EP_ACT_RRC_MEASUREMENT,
                                    dir=EP_DIR_REQUEST,
                                    op=EP_OPERATION_ADD,
                                    meas_id=i,
                                    rnti=ue.rnti,
                                    earfcn=measurement["earfcn"],
                                    interval=measurement["interval"],
                                    max_cells=measurement["max_cells"],
                                    max_meas=measurement["max_meas"])

            self.log.info("Sending rrc request to %s @ %s (id=%u, meas_id=%u)",
                          ue.rnti, self.vbs.enb_id, self.module_id, i)

            msg = RRC_REQUEST.build(rrc_request)
            self.vbs.connection.stream.write(msg)
예제 #12
0
 def test_encoding(self):
     '''Puesta en hora'''
     from datetime import datetime
     frame = MaraFrame.build(
         Container(
             sof=0xFE,
             dest=1,
             source=0,
             sequence=32,
             command=0x12,
             peh=datetime.now(),
         ))
     parsed = MaraFrame.parse(frame)
     self.assertIn('peh', parsed)
예제 #13
0
    def loop(self):
        """Send out requests"""

        if self.addr not in self.context.lvaps:
            return

        lvap = self.context.lvaps[self.addr]

        msg = Container(length=TXP_BIN_COUNTERS_REQUEST.sizeof(),
                        iface_id=self.iface_id,
                        addr=lvap.addr.to_raw())

        lvap.wtp.connection.send_message(PT_TXP_BIN_COUNTERS_REQUEST, msg,
                                         self.handle_response)
예제 #14
0
async def test_wait_for_message(mocker):
    loop = asyncio.get_event_loop()
    msg = Container()

    mm = AsyncMessageManager()

    task1 = loop.create_task(mm.wait_for_message())
    s = mm.schedule_message_handling(msg)

    assert await task1 == msg
    assert task1.done()
    assert s.done()

    assert len(mm.handler_registry) == 0
예제 #15
0
파일: clases.py 프로젝트: sunzu/vot.ar
    def a_tag(self):
        """Devuelve la informacion del apertura para almacenar en tag rfid."""
        nombres, dnis, tipos = self.encodear_autoridades()
        container = Container(numero_mesa=int(self.mesa.numero),
                              hora=int(self.hora["horas"]),
                              minutos=int(self.hora["minutos"]),
                              cantidad_autoridades=len(self.autoridades),
                              len_nombres=len(nombres),
                              nombres=nombres,
                              tipos=tipos,
                              dnis=dnis)
        built = struct_apertura.build(container)

        return built
예제 #16
0
    def send_set_traffic_rule(self, traffic_rule):
        """Send an ADD_TRAFFIC_RULE message.
        Args:
            traffic_rule: a Traffic Rule object
        Returns:
            None
        """

        flags = Container(amsdu_aggregation=traffic_rule.amsdu_aggregation)

        add_tr = Container(version=PT_VERSION,
                           type=PT_SET_TRAFFIC_RULE,
                           length=25 + len(traffic_rule.ssid),
                           seq=self.wtp.seq,
                           flags=flags,
                           hwaddr=traffic_rule.block.hwaddr.to_raw(),
                           channel=traffic_rule.block.channel,
                           band=traffic_rule.block.band,
                           quantum=traffic_rule.quantum,
                           dscp=int(traffic_rule.dscp, 16),
                           ssid=traffic_rule.ssid.to_raw())

        self.send_message(add_tr, SET_TRAFFIC_RULE)
예제 #17
0
    def answer_to_gamecontroller(self, peer):
        """ Sends a life sign to the game controller """
        return_message = 0 if self.man_penalize else 2

        data = Container(header="RGrt",
                         version=GAME_CONTROLLER_RESPONSE_VERSION,
                         team=self.team,
                         player=self.player,
                         message=return_message)
        try:
            destination = peer[0], GAME_CONTROLLER_ANSWER_PORT
            self.socket.sendto(ReturnData.build(data), destination)
        except Exception as e:
            logger.log("Network Error: %s" % str(e))
예제 #18
0
 def open_session(self):
     self._session += 1
     self._transaction = 1
     ptp = Container(
         OperationCode='OpenSession',
         # Only the OpenSession operation is allowed to have a 0
         # SessionID, because no session is open yet.
         SessionID=0,
         TransactionID=0,
         Parameter=[self._session])
     response = self.mesg(ptp)
     if response.ResponseCode == 'OK':
         self.__session_open = True
     return response
예제 #19
0
    def loop(self):
        """Send out requests"""

        if self.sta not in self.context.lvaps:
            return

        lvap = self.context.lvaps[self.sta]

        msg = Container(length=WIFI_RC_STATS_REQUEST.sizeof(),
                        sta=lvap.addr.to_raw())

        lvap.wtp.connection.send_message(PT_WIFI_RC_STATS_REQUEST,
                                         msg,
                                         self.handle_response)
예제 #20
0
    def send_object(self, bytes_data):
        '''Send object to responder.

        The object should correspond to the latest SendObjectInfo interaction
        between Initiator and Responder.
        '''
        ptp = Container(OperationCode='SendObject',
                        SessionID=self._session,
                        TransactionID=self._transaction,
                        Parameter=[])
        response = self.send(ptp, bytes_data)
        if response.ResponseCode != 'OK':
            response = self.send(ptp, bytes_data)
        return response
예제 #21
0
    def get_resized_image_object(self, handle, width, height=0):
        '''Retrieve resized image object from responder.

        The object should correspond to a previous GetObjectInfo interaction
        between Initiator and Responder in the same session.

        If width is provided then the aspect ratio may change. The device may
        not support this.
        '''
        ptp = Container(OperationCode='GetResizedImageObject',
                        SessionID=self._session,
                        TransactionID=self._transaction,
                        Parameter=[handle, width, height])
        return self.recv(ptp)
예제 #22
0
    def _decode(self, obj, context, path):
        event_group = obj[0]
        event_1_high_nibble = obj[1] >> 6
        event_2_high_nibble = (obj[1] >> 4) & 0b11
        event_1 = obj[2] + (event_1_high_nibble << 8)
        event_2 = obj[3] + (event_2_high_nibble << 8)
        partition = obj[1] & 0x0f

        return Container({
            'major': event_group,
            'minor': event_1,
            'minor2': event_2,
            'partition': partition
        })
예제 #23
0
    def send_object_info(self, objectinfo):
        '''Send ObjectInfo to responder.

        The object should correspond to the latest SendObjectInfo interaction
        between Initiator and Responder.
        '''
        objectinfo = self._build_if_not_data(objectinfo, self._ObjectInfo)

        ptp = Container(OperationCode='SendObjectInfo',
                        SessionID=self._session,
                        TransactionID=self._transaction,
                        Parameter=[])

        return self.send(ptp, objectinfo)
예제 #24
0
    def send_caps_request(self):
        """Send a CAPS_REQUEST message.
        Args:
            vbs: an VBS object
        Returns:
            None
        """

        msg = Container(length=ENB_CAPS_REQUEST.sizeof(), dummy=0)

        self.send_message(msg,
                          E_TYPE_SINGLE,
                          EP_ACT_CAPS,
                          ENB_CAPS_REQUEST)
예제 #25
0
 def _Temperature(self):
     return ExprAdapter(
         self._PTPArray(self._Int32),
         encoder=lambda obj, ctx:
         [obj.P7, obj.P7MU, obj.DDR.obj.WiFi, obj.IMU, obj.IMUSunshine],
         decoder=lambda obj, ctx: Container(
             P7=obj[0],
             P7MU=obj[1],
             DDR=obj[2],
             WiFi=obj[3],
             IMU=obj[4],
             IMUSunshine=obj[5],
         ),
     )
예제 #26
0
 def as_bytes(self):
     if self.msg_type in [
             HandshakeType.SERVER_HELLO, HandshakeType.CLIENT_HELLO,
             HandshakeType.CERTIFICATE, HandshakeType.CERTIFICATE_REQUEST,
             HandshakeType.HELLO_REQUEST, HandshakeType.SERVER_HELLO_DONE,
             HandshakeType.FINISHED
     ]:
         _body_as_bytes = self.body.as_bytes()
     else:
         _body_as_bytes = b''
     return _constructs.Handshake.build(
         Container(msg_type=self.msg_type.value,
                   length=self.length,
                   body=_body_as_bytes))
    def loop(self):
        """Send out requests"""

        for wtp in self.context.lvapp_manager.devices.values():

            if not wtp.connection:
                continue

            msg = Container(length=WIFI_SLICE_STATS_REQUEST.sizeof(),
                            ssid=self.context.wifi_props.ssid.to_raw(),
                            slice_id=self.slice_id)

            wtp.connection.send_message(PT_WIFI_SLICE_STATS_REQUEST, msg,
                                        self.handle_response)
예제 #28
0
 def get_vendor_device_info(self, extension):
     '''Get VendorExtension maps when supporting more than one extension.
     '''
     code = self.__code(extension, self._VendorExtensionID)
     ptp = Container(
         OperationCode='GetVendorDeviceInfo',
         SessionID=self._session,
         TransactionID=self._transaction,
         Parameter=[code]
     )
     response = self.recv(ptp)
     return self._parse_if_data(
         response,
         self._DeviceInfo)
예제 #29
0
 def initiate_open_capture(self, storage_id=0, object_format=0):
     '''Initiate open capture in `storage_id` of type `object_format`.'''
     code = self.__code(object_format, self._ObjectFormatCode)
     ptp = Container(
         OperationCode='InitiateOpenCapture',
         SessionID=self._session,
         TransactionID=self._transaction,
         Parameter=[
             storage_id,
             code,
         ]
     )
     response = self.recv(ptp)
     return response
예제 #30
0
 def initiate_capture(self, storage_id=0, object_format=0):
     '''Initiate capture with current camera settings.'''
     code = self.__code(object_format, self._ObjectFormatCode)
     ptp = Container(
         OperationCode='InitiateCapture',
         SessionID=self._session,
         TransactionID=self._transaction,
         Parameter=[
             storage_id,
             code,
         ]
     )
     response = self.recv(ptp)
     return response
예제 #31
0
    def _encode(self, obj, context, path):
        passed_time: datetime = obj["date"]
        total_time = passed_time.timestamp(
        ) - MESH_UNIX_EPOCH_DIFF - passed_time.utcoffset().total_seconds()

        return Container(tai_seconds=int(total_time),
                         subsecond=seconds_to_subsecond(total_time),
                         uncertainty=int(
                             (obj["uncertainty"].total_seconds() * 100)),
                         tai_utc_delta=timedelta_to_mesh_tai_utc_delta(
                             obj["tai_utc_delta"]),
                         time_authority=bool(obj["time_authority"]),
                         time_zone_offset=timedelta_to_mesh_time_zone_offset(
                             passed_time.utcoffset()))
예제 #32
0
def get_snr_power(server,
                  id=0,
                  intf_name=None,
                  sta_ip=None,
                  sta_port=0,
                  m_type=None):
    """INTERVAL FUNCTION: DON'T CALL THIS METHOD.

      @param server: tuple (ip, port_num)
      @param id: message id
      @param intf_name: name of the wireless interface
      @type intf_name: str
      @param sta_ip: ip address of the station that this message should be relayed to, if sta_ip is different from None
      @type sta_ip: str
      @param sta_port: socket port number of the station
      @type sta_port: int

      @return: msg - received message
      @return: the value
      -1 equals an error has occured
    """

    if intf_name is None or \
       m_type not in [MSG_TYPE.MSG_GET_SNR, MSG_TYPE.MSG_GET_TXPOWER]:
        return None, -1

    # 1) create message
    msg_struct = Container(m_type=m_type,
                           m_id=id,
                           p_version_length=len_of_string(VERSION),
                           p_version=VERSION,
                           m_size=0,
                           intf_name_size=len_of_string(intf_name),
                           intf_name=intf_name,
                           sta_ip_size=len_of_string(sta_ip),
                           sta_ip=sta_ip,
                           sta_port=sta_port,
                           value=0)

    error, msg = send_and_receive_msg(server, msg_struct, msg_snr_power.build,
                                      msg_snr_power.parse)
    # print msg

    if not error:
        value = msg['value'] if 'value' in msg else -1
    else:
        value = -1

    return msg, value